lib.rs 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610
  1. // Copyright 2013-2015 The rust-url developers.
  2. //
  3. // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
  4. // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
  5. // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
  6. // option. This file may not be copied, modified, or distributed
  7. // except according to those terms.
  8. /*!
  9. rust-url is an implementation of the [URL Standard](http://url.spec.whatwg.org/)
  10. for the [Rust](http://rust-lang.org/) programming language.
  11. It builds with [Cargo](http://crates.io/).
  12. To use it in your project, add this to your `Cargo.toml` file:
  13. ```Cargo
  14. [dependencies.url]
  15. git = "https://github.com/servo/rust-url"
  16. ```
  17. Supporting encodings other than UTF-8 in query strings is an optional feature
  18. that requires [rust-encoding](https://github.com/lifthrasiir/rust-encoding)
  19. and is off by default.
  20. You can enable it with
  21. [Cargo’s *features* mechanism](http://doc.crates.io/manifest.html#the-[features]-section):
  22. ```Cargo
  23. [dependencies.url]
  24. git = "https://github.com/servo/rust-url"
  25. features = ["query_encoding"]
  26. ```
  27. … or by passing `--cfg 'feature="query_encoding"'` to rustc.
  28. # URL parsing and data structures
  29. First, URL parsing may fail for various reasons and therefore returns a `Result`.
  30. ```
  31. use url::{Url, ParseError};
  32. assert!(Url::parse("http://[:::1]") == Err(ParseError::InvalidIpv6Address))
  33. ```
  34. Let’s parse a valid URL and look at its components.
  35. ```
  36. use url::{Url, Host};
  37. let issue_list_url = Url::parse(
  38. "https://github.com/rust-lang/rust/issues?labels=E-easy&state=open"
  39. ).unwrap();
  40. assert!(issue_list_url.scheme() == "https");
  41. assert!(issue_list_url.username() == "");
  42. assert!(issue_list_url.password() == None);
  43. assert!(issue_list_url.host_str() == Some("github.com"));
  44. assert!(issue_list_url.host() == Some(Host::Domain("github.com")));
  45. assert!(issue_list_url.port() == None);
  46. assert!(issue_list_url.path() == "/rust-lang/rust/issues");
  47. assert!(issue_list_url.path_segments().map(|c| c.collect::<Vec<_>>()) ==
  48. Some(vec!["rust-lang", "rust", "issues"]));
  49. assert!(issue_list_url.query() == Some("labels=E-easy&state=open"));
  50. assert!(issue_list_url.fragment() == None);
  51. assert!(!issue_list_url.cannot_be_a_base());
  52. ```
  53. Some URLs are said to be *cannot-be-a-base*:
  54. they don’t have a username, password, host, or port,
  55. and their "path" is an arbitrary string rather than slash-separated segments:
  56. ```
  57. use url::Url;
  58. let data_url = Url::parse("data:text/plain,Hello?World#").unwrap();
  59. assert!(data_url.cannot_be_a_base());
  60. assert!(data_url.scheme() == "data");
  61. assert!(data_url.path() == "text/plain,Hello");
  62. assert!(data_url.path_segments().is_none());
  63. assert!(data_url.query() == Some("World"));
  64. assert!(data_url.fragment() == Some(""));
  65. ```
  66. # Base URL
  67. Many contexts allow URL *references* that can be relative to a *base URL*:
  68. ```html
  69. <link rel="stylesheet" href="../main.css">
  70. ```
  71. Since parsed URL are absolute, giving a base is required for parsing relative URLs:
  72. ```
  73. use url::{Url, ParseError};
  74. assert!(Url::parse("../main.css") == Err(ParseError::RelativeUrlWithoutBase))
  75. ```
  76. Use the `join` method on an `Url` to use it as a base URL:
  77. ```
  78. use url::Url;
  79. let this_document = Url::parse("http://servo.github.io/rust-url/url/index.html").unwrap();
  80. let css_url = this_document.join("../main.css").unwrap();
  81. assert_eq!(css_url.as_str(), "http://servo.github.io/rust-url/main.css")
  82. */
  83. #[cfg(feature="rustc-serialize")] extern crate rustc_serialize;
  84. #[macro_use] extern crate matches;
  85. #[cfg(feature="serde")] extern crate serde;
  86. #[cfg(feature="heapsize")] #[macro_use] extern crate heapsize;
  87. pub extern crate idna;
  88. use encoding::EncodingOverride;
  89. #[cfg(feature = "heapsize")] use heapsize::HeapSizeOf;
  90. use host::HostInternal;
  91. use parser::{Parser, Context, SchemeType, to_u32};
  92. use percent_encoding::{PATH_SEGMENT_ENCODE_SET, USERINFO_ENCODE_SET,
  93. percent_encode, percent_decode, utf8_percent_encode};
  94. use std::cmp;
  95. use std::fmt::{self, Write};
  96. use std::hash;
  97. use std::io;
  98. use std::mem;
  99. use std::net::{ToSocketAddrs, IpAddr};
  100. use std::ops::{Range, RangeFrom, RangeTo};
  101. use std::path::{Path, PathBuf};
  102. use std::str;
  103. pub use origin::{Origin, OpaqueOrigin};
  104. pub use host::{Host, HostAndPort, SocketAddrs};
  105. pub use path_segments::PathSegmentsMut;
  106. pub use parser::ParseError;
  107. pub use slicing::Position;
  108. mod encoding;
  109. mod host;
  110. mod origin;
  111. mod path_segments;
  112. mod parser;
  113. mod slicing;
  114. pub mod form_urlencoded;
  115. pub mod percent_encoding;
  116. pub mod quirks;
  117. /// A parsed URL record.
  118. #[derive(Clone)]
  119. pub struct Url {
  120. /// Syntax in pseudo-BNF:
  121. ///
  122. /// url = scheme ":" [ hierarchical | non-hierarchical ] [ "?" query ]? [ "#" fragment ]?
  123. /// non-hierarchical = non-hierarchical-path
  124. /// non-hierarchical-path = /* Does not start with "/" */
  125. /// hierarchical = authority? hierarchical-path
  126. /// authority = "//" userinfo? host [ ":" port ]?
  127. /// userinfo = username [ ":" password ]? "@"
  128. /// hierarchical-path = [ "/" path-segment ]+
  129. serialization: String,
  130. // Components
  131. scheme_end: u32, // Before ':'
  132. username_end: u32, // Before ':' (if a password is given) or '@' (if not)
  133. host_start: u32,
  134. host_end: u32,
  135. host: HostInternal,
  136. port: Option<u16>,
  137. path_start: u32, // Before initial '/', if any
  138. query_start: Option<u32>, // Before '?', unlike Position::QueryStart
  139. fragment_start: Option<u32>, // Before '#', unlike Position::FragmentStart
  140. }
  141. #[cfg(feature = "heapsize")]
  142. impl HeapSizeOf for Url {
  143. fn heap_size_of_children(&self) -> usize {
  144. self.serialization.heap_size_of_children()
  145. }
  146. }
  147. /// Full configuration for the URL parser.
  148. #[derive(Copy, Clone)]
  149. pub struct ParseOptions<'a> {
  150. base_url: Option<&'a Url>,
  151. encoding_override: encoding::EncodingOverride,
  152. log_syntax_violation: Option<&'a Fn(&'static str)>,
  153. }
  154. impl<'a> ParseOptions<'a> {
  155. /// Change the base URL
  156. pub fn base_url(mut self, new: Option<&'a Url>) -> Self {
  157. self.base_url = new;
  158. self
  159. }
  160. /// Override the character encoding of query strings.
  161. /// This is a legacy concept only relevant for HTML.
  162. #[cfg(feature = "query_encoding")]
  163. pub fn encoding_override(mut self, new: Option<encoding::EncodingRef>) -> Self {
  164. self.encoding_override = EncodingOverride::from_opt_encoding(new).to_output_encoding();
  165. self
  166. }
  167. /// Call the provided function or closure on non-fatal parse errors.
  168. pub fn log_syntax_violation(mut self, new: Option<&'a Fn(&'static str)>) -> Self {
  169. self.log_syntax_violation = new;
  170. self
  171. }
  172. /// Parse an URL string with the configuration so far.
  173. pub fn parse(self, input: &str) -> Result<Url, ::ParseError> {
  174. Parser {
  175. serialization: String::with_capacity(input.len()),
  176. base_url: self.base_url,
  177. query_encoding_override: self.encoding_override,
  178. log_syntax_violation: self.log_syntax_violation,
  179. context: Context::UrlParser,
  180. }.parse_url(input)
  181. }
  182. }
  183. impl Url {
  184. /// Parse an absolute URL from a string.
  185. ///
  186. /// # Examples
  187. ///
  188. /// ```rust
  189. /// use url::Url;
  190. ///
  191. /// let url = Url::parse("https://example.net").unwrap();
  192. /// ```
  193. #[inline]
  194. pub fn parse(input: &str) -> Result<Url, ::ParseError> {
  195. Url::options().parse(input)
  196. }
  197. /// Parse a string as an URL, with this URL as the base URL.
  198. ///
  199. /// # Examples
  200. ///
  201. /// ```rust
  202. /// use url::Url;
  203. ///
  204. /// let url = Url::parse("https://example.net").unwrap();
  205. /// let url = url.join("foo").unwrap();
  206. /// assert_eq!(url.as_str(), "https://example.net/foo");
  207. /// ```
  208. ///
  209. /// Trailing slashes are not preserved:
  210. ///
  211. /// ```rust
  212. /// use url::Url;
  213. ///
  214. /// let url = Url::parse("https://example.net/foo/").unwrap();
  215. /// let url = url.join("bar").unwrap();
  216. /// assert_eq!(url.as_str(), "https://example.net/foo/bar");
  217. /// ```
  218. #[inline]
  219. pub fn join(&self, input: &str) -> Result<Url, ::ParseError> {
  220. Url::options().base_url(Some(self)).parse(input)
  221. }
  222. /// Return a default `ParseOptions` that can fully configure the URL parser.
  223. pub fn options<'a>() -> ParseOptions<'a> {
  224. ParseOptions {
  225. base_url: None,
  226. encoding_override: EncodingOverride::utf8(),
  227. log_syntax_violation: None,
  228. }
  229. }
  230. /// Return the serialization of this URL.
  231. ///
  232. /// This is fast since that serialization is already stored in the `Url` struct.
  233. ///
  234. /// # Examples
  235. ///
  236. /// ```rust
  237. /// use url::Url;
  238. ///
  239. /// let url_str = "https://example.net/";
  240. /// let url = Url::parse(url_str).unwrap();
  241. /// assert_eq!(url.as_str(), url_str);
  242. /// ```
  243. #[inline]
  244. pub fn as_str(&self) -> &str {
  245. &self.serialization
  246. }
  247. /// Return the serialization of this URL.
  248. ///
  249. /// This consumes the `Url` and takes ownership of the `String` stored in it.
  250. ///
  251. /// # Examples
  252. ///
  253. /// ```rust
  254. /// use url::Url;
  255. ///
  256. /// let url_str = "https://example.net/";
  257. /// let url = Url::parse(url_str).unwrap();
  258. /// assert_eq!(url.into_string(), url_str);
  259. /// ```
  260. #[inline]
  261. pub fn into_string(self) -> String {
  262. self.serialization
  263. }
  264. /// For internal testing, not part of the public API.
  265. ///
  266. /// Methods of the `Url` struct assume a number of invariants.
  267. /// This checks each of these invariants and panic if one is not met.
  268. /// This is for testing rust-url itself.
  269. #[doc(hidden)]
  270. pub fn assert_invariants(&self) {
  271. macro_rules! assert {
  272. ($x: expr) => {
  273. if !$x {
  274. panic!("!( {} ) for URL {:?}", stringify!($x), self.serialization)
  275. }
  276. }
  277. }
  278. macro_rules! assert_eq {
  279. ($a: expr, $b: expr) => {
  280. {
  281. let a = $a;
  282. let b = $b;
  283. if a != b {
  284. panic!("{:?} != {:?} ({} != {}) for URL {:?}",
  285. a, b, stringify!($a), stringify!($b), self.serialization)
  286. }
  287. }
  288. }
  289. }
  290. assert!(self.scheme_end >= 1);
  291. assert!(matches!(self.byte_at(0), b'a'...b'z' | b'A'...b'Z'));
  292. assert!(self.slice(1..self.scheme_end).chars()
  293. .all(|c| matches!(c, 'a'...'z' | 'A'...'Z' | '0'...'9' | '+' | '-' | '.')));
  294. assert_eq!(self.byte_at(self.scheme_end), b':');
  295. if self.slice(self.scheme_end + 1 ..).starts_with("//") {
  296. // URL with authority
  297. match self.byte_at(self.username_end) {
  298. b':' => {
  299. assert!(self.host_start >= self.username_end + 2);
  300. assert_eq!(self.byte_at(self.host_start - 1), b'@');
  301. }
  302. b'@' => assert!(self.host_start == self.username_end + 1),
  303. _ => assert_eq!(self.username_end, self.scheme_end + 3),
  304. }
  305. assert!(self.host_start >= self.username_end);
  306. assert!(self.host_end >= self.host_start);
  307. let host_str = self.slice(self.host_start..self.host_end);
  308. match self.host {
  309. HostInternal::None => assert_eq!(host_str, ""),
  310. HostInternal::Ipv4(address) => assert_eq!(host_str, address.to_string()),
  311. HostInternal::Ipv6(address) => {
  312. let h: Host<String> = Host::Ipv6(address);
  313. assert_eq!(host_str, h.to_string())
  314. }
  315. HostInternal::Domain => {
  316. if SchemeType::from(self.scheme()).is_special() {
  317. assert!(!host_str.is_empty())
  318. }
  319. }
  320. }
  321. if self.path_start == self.host_end {
  322. assert_eq!(self.port, None);
  323. } else {
  324. assert_eq!(self.byte_at(self.host_end), b':');
  325. let port_str = self.slice(self.host_end + 1..self.path_start);
  326. assert_eq!(self.port, Some(port_str.parse::<u16>().expect("Couldn't parse port?")));
  327. }
  328. assert_eq!(self.byte_at(self.path_start), b'/');
  329. } else {
  330. // Anarchist URL (no authority)
  331. assert_eq!(self.username_end, self.scheme_end + 1);
  332. assert_eq!(self.host_start, self.scheme_end + 1);
  333. assert_eq!(self.host_end, self.scheme_end + 1);
  334. assert_eq!(self.host, HostInternal::None);
  335. assert_eq!(self.port, None);
  336. assert_eq!(self.path_start, self.scheme_end + 1);
  337. }
  338. if let Some(start) = self.query_start {
  339. assert!(start > self.path_start);
  340. assert_eq!(self.byte_at(start), b'?');
  341. }
  342. if let Some(start) = self.fragment_start {
  343. assert!(start > self.path_start);
  344. assert_eq!(self.byte_at(start), b'#');
  345. }
  346. if let (Some(query_start), Some(fragment_start)) = (self.query_start, self.fragment_start) {
  347. assert!(fragment_start > query_start);
  348. }
  349. let other = Url::parse(self.as_str()).expect("Failed to parse myself?");
  350. assert_eq!(&self.serialization, &other.serialization);
  351. assert_eq!(self.scheme_end, other.scheme_end);
  352. assert_eq!(self.username_end, other.username_end);
  353. assert_eq!(self.host_start, other.host_start);
  354. assert_eq!(self.host_end, other.host_end);
  355. assert!(self.host == other.host ||
  356. // XXX No host round-trips to empty host.
  357. // See https://github.com/whatwg/url/issues/79
  358. (self.host_str(), other.host_str()) == (None, Some("")));
  359. assert_eq!(self.port, other.port);
  360. assert_eq!(self.path_start, other.path_start);
  361. assert_eq!(self.query_start, other.query_start);
  362. assert_eq!(self.fragment_start, other.fragment_start);
  363. }
  364. /// Return the origin of this URL (https://url.spec.whatwg.org/#origin)
  365. ///
  366. /// Note: this returns an opaque origin for `file:` URLs, which causes
  367. /// `url.origin() != url.origin()`.
  368. ///
  369. /// # Examples
  370. ///
  371. /// URL with `ftp` scheme:
  372. ///
  373. /// ```rust
  374. /// use url::{Host, Origin, Url};
  375. ///
  376. /// let url = Url::parse("ftp://example.com/foo").unwrap();
  377. /// assert_eq!(url.origin(),
  378. /// Origin::Tuple("ftp".into(),
  379. /// Host::Domain("example.com".into()),
  380. /// 21));
  381. /// ```
  382. ///
  383. /// URL with `blob` scheme:
  384. ///
  385. /// ```rust
  386. /// use url::{Host, Origin, Url};
  387. ///
  388. /// let url = Url::parse("blob:https://example.com/foo").unwrap();
  389. /// assert_eq!(url.origin(),
  390. /// Origin::Tuple("https".into(),
  391. /// Host::Domain("example.com".into()),
  392. /// 443));
  393. /// ```
  394. ///
  395. /// URL with `file` scheme:
  396. ///
  397. /// ```rust
  398. /// use url::{Host, Origin, Url};
  399. ///
  400. /// let url = Url::parse("file:///tmp/foo").unwrap();
  401. /// assert!(!url.origin().is_tuple());
  402. ///
  403. /// let other_url = Url::parse("file:///tmp/foo").unwrap();
  404. /// assert!(url.origin() != other_url.origin());
  405. /// ```
  406. ///
  407. /// URL with other scheme:
  408. ///
  409. /// ```rust
  410. /// use url::{Host, Origin, Url};
  411. ///
  412. /// let url = Url::parse("foo:bar").unwrap();
  413. /// assert!(!url.origin().is_tuple());
  414. /// ```
  415. #[inline]
  416. pub fn origin(&self) -> Origin {
  417. origin::url_origin(self)
  418. }
  419. /// Return the scheme of this URL, lower-cased, as an ASCII string without the ':' delimiter.
  420. ///
  421. /// # Examples
  422. ///
  423. /// ```
  424. /// use url::Url;
  425. ///
  426. /// let url = Url::parse("file:///tmp/foo").unwrap();
  427. /// assert_eq!(url.scheme(), "file");
  428. /// ```
  429. #[inline]
  430. pub fn scheme(&self) -> &str {
  431. self.slice(..self.scheme_end)
  432. }
  433. /// Return whether the URL has an 'authority',
  434. /// which can contain a username, password, host, and port number.
  435. ///
  436. /// URLs that do *not* are either path-only like `unix:/run/foo.socket`
  437. /// or cannot-be-a-base like `data:text/plain,Stuff`.
  438. ///
  439. /// # Examples
  440. ///
  441. /// ```
  442. /// use url::Url;
  443. ///
  444. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  445. /// assert!(url.has_authority());
  446. ///
  447. /// let url = Url::parse("unix:/run/foo.socket").unwrap();
  448. /// assert!(!url.has_authority());
  449. ///
  450. /// let url = Url::parse("data:text/plain,Stuff").unwrap();
  451. /// assert!(!url.has_authority());
  452. /// ```
  453. #[inline]
  454. pub fn has_authority(&self) -> bool {
  455. debug_assert!(self.byte_at(self.scheme_end) == b':');
  456. self.slice(self.scheme_end..).starts_with("://")
  457. }
  458. /// Return whether this URL is a cannot-be-a-base URL,
  459. /// meaning that parsing a relative URL string with this URL as the base will return an error.
  460. ///
  461. /// This is the case if the scheme and `:` delimiter are not followed by a `/` slash,
  462. /// as is typically the case of `data:` and `mailto:` URLs.
  463. ///
  464. /// # Examples
  465. ///
  466. /// ```
  467. /// use url::Url;
  468. ///
  469. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  470. /// assert!(!url.cannot_be_a_base());
  471. ///
  472. /// let url = Url::parse("unix:/run/foo.socket").unwrap();
  473. /// assert!(!url.cannot_be_a_base());
  474. ///
  475. /// let url = Url::parse("data:text/plain,Stuff").unwrap();
  476. /// assert!(url.cannot_be_a_base());
  477. /// ```
  478. #[inline]
  479. pub fn cannot_be_a_base(&self) -> bool {
  480. !self.slice(self.path_start..).starts_with('/')
  481. }
  482. /// Return the username for this URL (typically the empty string)
  483. /// as a percent-encoded ASCII string.
  484. ///
  485. /// # Examples
  486. ///
  487. /// ```
  488. /// use url::Url;
  489. ///
  490. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  491. /// assert_eq!(url.username(), "rms");
  492. ///
  493. /// let url = Url::parse("ftp://:secret123@example.com").unwrap();
  494. /// assert_eq!(url.username(), "");
  495. ///
  496. /// let url = Url::parse("https://example.com").unwrap();
  497. /// assert_eq!(url.username(), "");
  498. /// ```
  499. pub fn username(&self) -> &str {
  500. if self.has_authority() {
  501. self.slice(self.scheme_end + ("://".len() as u32)..self.username_end)
  502. } else {
  503. ""
  504. }
  505. }
  506. /// Return the password for this URL, if any, as a percent-encoded ASCII string.
  507. ///
  508. /// # Examples
  509. ///
  510. /// ```
  511. /// use url::Url;
  512. ///
  513. /// let url = Url::parse("ftp://rms:secret123@example.com").unwrap();
  514. /// assert_eq!(url.password(), Some("secret123"));
  515. ///
  516. /// let url = Url::parse("ftp://:secret123@example.com").unwrap();
  517. /// assert_eq!(url.password(), Some("secret123"));
  518. ///
  519. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  520. /// assert_eq!(url.password(), None);
  521. ///
  522. /// let url = Url::parse("https://example.com").unwrap();
  523. /// assert_eq!(url.password(), None);
  524. /// ```
  525. pub fn password(&self) -> Option<&str> {
  526. // This ':' is not the one marking a port number since a host can not be empty.
  527. // (Except for file: URLs, which do not have port numbers.)
  528. if self.has_authority() && self.byte_at(self.username_end) == b':' {
  529. debug_assert!(self.byte_at(self.host_start - 1) == b'@');
  530. Some(self.slice(self.username_end + 1..self.host_start - 1))
  531. } else {
  532. None
  533. }
  534. }
  535. /// Equivalent to `url.host().is_some()`.
  536. pub fn has_host(&self) -> bool {
  537. !matches!(self.host, HostInternal::None)
  538. }
  539. /// Return the string representation of the host (domain or IP address) for this URL, if any.
  540. ///
  541. /// Non-ASCII domains are punycode-encoded per IDNA.
  542. /// IPv6 addresses are given between `[` and `]` brackets.
  543. ///
  544. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  545. /// don’t have a host.
  546. ///
  547. /// See also the `host` method.
  548. pub fn host_str(&self) -> Option<&str> {
  549. if self.has_host() {
  550. Some(self.slice(self.host_start..self.host_end))
  551. } else {
  552. None
  553. }
  554. }
  555. /// Return the parsed representation of the host for this URL.
  556. /// Non-ASCII domain labels are punycode-encoded per IDNA.
  557. ///
  558. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  559. /// don’t have a host.
  560. ///
  561. /// See also the `host_str` method.
  562. pub fn host(&self) -> Option<Host<&str>> {
  563. match self.host {
  564. HostInternal::None => None,
  565. HostInternal::Domain => Some(Host::Domain(self.slice(self.host_start..self.host_end))),
  566. HostInternal::Ipv4(address) => Some(Host::Ipv4(address)),
  567. HostInternal::Ipv6(address) => Some(Host::Ipv6(address)),
  568. }
  569. }
  570. /// If this URL has a host and it is a domain name (not an IP address), return it.
  571. ///
  572. /// # Examples
  573. ///
  574. /// ```
  575. /// use url::Url;
  576. ///
  577. /// let url = Url::parse("https://127.0.0.1/").unwrap();
  578. /// assert_eq!(url.domain(), None);
  579. ///
  580. /// let url = Url::parse("https://example.com/").unwrap();
  581. /// assert_eq!(url.domain(), Some("example.com"));
  582. /// ```
  583. pub fn domain(&self) -> Option<&str> {
  584. match self.host {
  585. HostInternal::Domain => Some(self.slice(self.host_start..self.host_end)),
  586. _ => None,
  587. }
  588. }
  589. /// Return the port number for this URL, if any.
  590. ///
  591. /// # Examples
  592. ///
  593. /// ```
  594. /// use url::Url;
  595. ///
  596. /// let url = Url::parse("https://example.com").unwrap();
  597. /// assert_eq!(url.port(), None);
  598. ///
  599. /// let url = Url::parse("ssh://example.com:22").unwrap();
  600. /// assert_eq!(url.port(), Some(22));
  601. /// ```
  602. #[inline]
  603. pub fn port(&self) -> Option<u16> {
  604. self.port
  605. }
  606. /// Return the port number for this URL, or the default port number if it is known.
  607. ///
  608. /// This method only knows the default port number
  609. /// of the `http`, `https`, `ws`, `wss`, `ftp`, and `gopher` schemes.
  610. ///
  611. /// For URLs in these schemes, this method always returns `Some(_)`.
  612. /// For other schemes, it is the same as `Url::port()`.
  613. ///
  614. /// # Examples
  615. ///
  616. /// ```
  617. /// use url::Url;
  618. ///
  619. /// let url = Url::parse("foo://example.com").unwrap();
  620. /// assert_eq!(url.port_or_known_default(), None);
  621. ///
  622. /// let url = Url::parse("foo://example.com:1456").unwrap();
  623. /// assert_eq!(url.port_or_known_default(), Some(1456));
  624. ///
  625. /// let url = Url::parse("https://example.com").unwrap();
  626. /// assert_eq!(url.port_or_known_default(), Some(443));
  627. /// ```
  628. #[inline]
  629. pub fn port_or_known_default(&self) -> Option<u16> {
  630. self.port.or_else(|| parser::default_port(self.scheme()))
  631. }
  632. /// If the URL has a host, return something that implements `ToSocketAddrs`.
  633. ///
  634. /// If the URL has no port number and the scheme’s default port number is not known
  635. /// (see `Url::port_or_known_default`),
  636. /// the closure is called to obtain a port number.
  637. /// Typically, this closure can match on the result `Url::scheme`
  638. /// to have per-scheme default port numbers,
  639. /// and panic for schemes it’s not prepared to handle.
  640. /// For example:
  641. ///
  642. /// ```rust
  643. /// # use url::Url;
  644. /// # use std::net::TcpStream;
  645. /// # use std::io;
  646. ///
  647. /// fn connect(url: &Url) -> io::Result<TcpStream> {
  648. /// TcpStream::connect(try!(url.with_default_port(default_port)))
  649. /// }
  650. ///
  651. /// fn default_port(url: &Url) -> Result<u16, ()> {
  652. /// match url.scheme() {
  653. /// "git" => Ok(9418),
  654. /// "git+ssh" => Ok(22),
  655. /// "git+https" => Ok(443),
  656. /// "git+http" => Ok(80),
  657. /// _ => Err(()),
  658. /// }
  659. /// }
  660. /// ```
  661. pub fn with_default_port<F>(&self, f: F) -> io::Result<HostAndPort<&str>>
  662. where F: FnOnce(&Url) -> Result<u16, ()> {
  663. Ok(HostAndPort {
  664. host: try!(self.host()
  665. .ok_or(())
  666. .or_else(|()| io_error("URL has no host"))),
  667. port: try!(self.port_or_known_default()
  668. .ok_or(())
  669. .or_else(|()| f(self))
  670. .or_else(|()| io_error("URL has no port number")))
  671. })
  672. }
  673. /// Return the path for this URL, as a percent-encoded ASCII string.
  674. /// For cannot-be-a-base URLs, this is an arbitrary string that doesn’t start with '/'.
  675. /// For other URLs, this starts with a '/' slash
  676. /// and continues with slash-separated path segments.
  677. pub fn path(&self) -> &str {
  678. match (self.query_start, self.fragment_start) {
  679. (None, None) => self.slice(self.path_start..),
  680. (Some(next_component_start), _) |
  681. (None, Some(next_component_start)) => {
  682. self.slice(self.path_start..next_component_start)
  683. }
  684. }
  685. }
  686. /// Unless this URL is cannot-be-a-base,
  687. /// return an iterator of '/' slash-separated path segments,
  688. /// each as a percent-encoded ASCII string.
  689. ///
  690. /// Return `None` for cannot-be-a-base URLs.
  691. ///
  692. /// When `Some` is returned, the iterator always contains at least one string
  693. /// (which may be empty).
  694. pub fn path_segments(&self) -> Option<str::Split<char>> {
  695. let path = self.path();
  696. if path.starts_with('/') {
  697. Some(path[1..].split('/'))
  698. } else {
  699. None
  700. }
  701. }
  702. /// Return this URL’s query string, if any, as a percent-encoded ASCII string.
  703. pub fn query(&self) -> Option<&str> {
  704. match (self.query_start, self.fragment_start) {
  705. (None, _) => None,
  706. (Some(query_start), None) => {
  707. debug_assert!(self.byte_at(query_start) == b'?');
  708. Some(self.slice(query_start + 1..))
  709. }
  710. (Some(query_start), Some(fragment_start)) => {
  711. debug_assert!(self.byte_at(query_start) == b'?');
  712. Some(self.slice(query_start + 1..fragment_start))
  713. }
  714. }
  715. }
  716. /// Parse the URL’s query string, if any, as `application/x-www-form-urlencoded`
  717. /// and return an iterator of (key, value) pairs.
  718. #[inline]
  719. pub fn query_pairs(&self) -> form_urlencoded::Parse {
  720. form_urlencoded::parse(self.query().unwrap_or("").as_bytes())
  721. }
  722. /// Return this URL’s fragment identifier, if any.
  723. ///
  724. /// **Note:** the parser did *not* percent-encode this component,
  725. /// but the input may have been percent-encoded already.
  726. pub fn fragment(&self) -> Option<&str> {
  727. self.fragment_start.map(|start| {
  728. debug_assert!(self.byte_at(start) == b'#');
  729. self.slice(start + 1..)
  730. })
  731. }
  732. fn mutate<F: FnOnce(&mut Parser) -> R, R>(&mut self, f: F) -> R {
  733. let mut parser = Parser::for_setter(mem::replace(&mut self.serialization, String::new()));
  734. let result = f(&mut parser);
  735. self.serialization = parser.serialization;
  736. result
  737. }
  738. /// Change this URL’s fragment identifier.
  739. pub fn set_fragment(&mut self, fragment: Option<&str>) {
  740. // Remove any previous fragment
  741. if let Some(start) = self.fragment_start {
  742. debug_assert!(self.byte_at(start) == b'#');
  743. self.serialization.truncate(start as usize);
  744. }
  745. // Write the new one
  746. if let Some(input) = fragment {
  747. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  748. self.serialization.push('#');
  749. self.mutate(|parser| parser.parse_fragment(parser::Input::new(input)))
  750. } else {
  751. self.fragment_start = None
  752. }
  753. }
  754. fn take_fragment(&mut self) -> Option<String> {
  755. self.fragment_start.take().map(|start| {
  756. debug_assert!(self.byte_at(start) == b'#');
  757. let fragment = self.slice(start + 1..).to_owned();
  758. self.serialization.truncate(start as usize);
  759. fragment
  760. })
  761. }
  762. fn restore_already_parsed_fragment(&mut self, fragment: Option<String>) {
  763. if let Some(ref fragment) = fragment {
  764. assert!(self.fragment_start.is_none());
  765. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  766. self.serialization.push('#');
  767. self.serialization.push_str(fragment);
  768. }
  769. }
  770. /// Change this URL’s query string.
  771. pub fn set_query(&mut self, query: Option<&str>) {
  772. let fragment = self.take_fragment();
  773. // Remove any previous query
  774. if let Some(start) = self.query_start.take() {
  775. debug_assert!(self.byte_at(start) == b'?');
  776. self.serialization.truncate(start as usize);
  777. }
  778. // Write the new query, if any
  779. if let Some(input) = query {
  780. self.query_start = Some(to_u32(self.serialization.len()).unwrap());
  781. self.serialization.push('?');
  782. let scheme_end = self.scheme_end;
  783. self.mutate(|parser| parser.parse_query(scheme_end, parser::Input::new(input)));
  784. }
  785. self.restore_already_parsed_fragment(fragment);
  786. }
  787. /// Manipulate this URL’s query string, viewed as a sequence of name/value pairs
  788. /// in `application/x-www-form-urlencoded` syntax.
  789. ///
  790. /// The return value has a method-chaining API:
  791. ///
  792. /// ```rust
  793. /// # use url::Url;
  794. /// let mut url = Url::parse("https://example.net?lang=fr#nav").unwrap();
  795. /// assert_eq!(url.query(), Some("lang=fr"));
  796. ///
  797. /// url.query_pairs_mut().append_pair("foo", "bar");
  798. /// assert_eq!(url.query(), Some("lang=fr&foo=bar"));
  799. /// assert_eq!(url.as_str(), "https://example.net/?lang=fr&foo=bar#nav");
  800. ///
  801. /// url.query_pairs_mut()
  802. /// .clear()
  803. /// .append_pair("foo", "bar & baz")
  804. /// .append_pair("saisons", "\u{00C9}t\u{00E9}+hiver");
  805. /// assert_eq!(url.query(), Some("foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver"));
  806. /// assert_eq!(url.as_str(),
  807. /// "https://example.net/?foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver#nav");
  808. /// ```
  809. ///
  810. /// Note: `url.query_pairs_mut().clear();` is equivalent to `url.set_query(Some(""))`,
  811. /// not `url.set_query(None)`.
  812. ///
  813. /// The state of `Url` is unspecified if this return value is leaked without being dropped.
  814. pub fn query_pairs_mut(&mut self) -> form_urlencoded::Serializer<UrlQuery> {
  815. let fragment = self.take_fragment();
  816. let query_start;
  817. if let Some(start) = self.query_start {
  818. debug_assert!(self.byte_at(start) == b'?');
  819. query_start = start as usize;
  820. } else {
  821. query_start = self.serialization.len();
  822. self.query_start = Some(to_u32(query_start).unwrap());
  823. self.serialization.push('?');
  824. }
  825. let query = UrlQuery { url: self, fragment: fragment };
  826. form_urlencoded::Serializer::for_suffix(query, query_start + "?".len())
  827. }
  828. fn take_after_path(&mut self) -> String {
  829. match (self.query_start, self.fragment_start) {
  830. (Some(i), _) | (None, Some(i)) => {
  831. let after_path = self.slice(i..).to_owned();
  832. self.serialization.truncate(i as usize);
  833. after_path
  834. },
  835. (None, None) => String::new(),
  836. }
  837. }
  838. /// Change this URL’s path.
  839. pub fn set_path(&mut self, mut path: &str) {
  840. let after_path = self.take_after_path();
  841. let old_after_path_pos = to_u32(self.serialization.len()).unwrap();
  842. let cannot_be_a_base = self.cannot_be_a_base();
  843. let scheme_type = SchemeType::from(self.scheme());
  844. self.serialization.truncate(self.path_start as usize);
  845. self.mutate(|parser| {
  846. if cannot_be_a_base {
  847. if path.starts_with('/') {
  848. parser.serialization.push_str("%2F");
  849. path = &path[1..];
  850. }
  851. parser.parse_cannot_be_a_base_path(parser::Input::new(path));
  852. } else {
  853. let mut has_host = true; // FIXME
  854. parser.parse_path_start(scheme_type, &mut has_host, parser::Input::new(path));
  855. }
  856. });
  857. self.restore_after_path(old_after_path_pos, &after_path);
  858. }
  859. /// Return an object with methods to manipulate this URL’s path segments.
  860. ///
  861. /// Return `Err(())` if this URL is cannot-be-a-base.
  862. pub fn path_segments_mut(&mut self) -> Result<PathSegmentsMut, ()> {
  863. if self.cannot_be_a_base() {
  864. Err(())
  865. } else {
  866. Ok(path_segments::new(self))
  867. }
  868. }
  869. fn restore_after_path(&mut self, old_after_path_position: u32, after_path: &str) {
  870. let new_after_path_position = to_u32(self.serialization.len()).unwrap();
  871. let adjust = |index: &mut u32| {
  872. *index -= old_after_path_position;
  873. *index += new_after_path_position;
  874. };
  875. if let Some(ref mut index) = self.query_start { adjust(index) }
  876. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  877. self.serialization.push_str(after_path)
  878. }
  879. /// Change this URL’s port number.
  880. ///
  881. /// If this URL is cannot-be-a-base, does not have a host, or has the `file` scheme;
  882. /// do nothing and return `Err`.
  883. ///
  884. /// # Examples
  885. ///
  886. /// ```
  887. /// use url::Url;
  888. ///
  889. /// let mut url = Url::parse("ssh://example.net:2048/").unwrap();
  890. ///
  891. /// url.set_port(Some(4096)).unwrap();
  892. /// assert_eq!(url.as_str(), "ssh://example.net:4096/");
  893. ///
  894. /// url.set_port(None).unwrap();
  895. /// assert_eq!(url.as_str(), "ssh://example.net/");
  896. /// ```
  897. pub fn set_port(&mut self, mut port: Option<u16>) -> Result<(), ()> {
  898. if !self.has_host() || self.scheme() == "file" {
  899. return Err(())
  900. }
  901. if port.is_some() && port == parser::default_port(self.scheme()) {
  902. port = None
  903. }
  904. self.set_port_internal(port);
  905. Ok(())
  906. }
  907. fn set_port_internal(&mut self, port: Option<u16>) {
  908. match (self.port, port) {
  909. (None, None) => {}
  910. (Some(_), None) => {
  911. self.serialization.drain(self.host_end as usize .. self.path_start as usize);
  912. let offset = self.path_start - self.host_end;
  913. self.path_start = self.host_end;
  914. if let Some(ref mut index) = self.query_start { *index -= offset }
  915. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  916. }
  917. (Some(old), Some(new)) if old == new => {}
  918. (_, Some(new)) => {
  919. let path_and_after = self.slice(self.path_start..).to_owned();
  920. self.serialization.truncate(self.host_end as usize);
  921. write!(&mut self.serialization, ":{}", new).unwrap();
  922. let old_path_start = self.path_start;
  923. let new_path_start = to_u32(self.serialization.len()).unwrap();
  924. self.path_start = new_path_start;
  925. let adjust = |index: &mut u32| {
  926. *index -= old_path_start;
  927. *index += new_path_start;
  928. };
  929. if let Some(ref mut index) = self.query_start { adjust(index) }
  930. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  931. self.serialization.push_str(&path_and_after);
  932. }
  933. }
  934. self.port = port;
  935. }
  936. /// Change this URL’s host.
  937. ///
  938. /// If this URL is cannot-be-a-base or there is an error parsing the given `host`,
  939. /// do nothing and return `Err`.
  940. ///
  941. /// Removing the host (calling this with `None`)
  942. /// will also remove any username, password, and port number.
  943. pub fn set_host(&mut self, host: Option<&str>) -> Result<(), ParseError> {
  944. if self.cannot_be_a_base() {
  945. return Err(ParseError::SetHostOnCannotBeABaseUrl)
  946. }
  947. if let Some(host) = host {
  948. self.set_host_internal(try!(Host::parse(host)), None)
  949. } else if self.has_host() {
  950. debug_assert!(self.byte_at(self.scheme_end) == b':');
  951. debug_assert!(self.byte_at(self.path_start) == b'/');
  952. let new_path_start = self.scheme_end + 1;
  953. self.serialization.drain(self.path_start as usize..new_path_start as usize);
  954. let offset = self.path_start - new_path_start;
  955. self.path_start = new_path_start;
  956. self.username_end = new_path_start;
  957. self.host_start = new_path_start;
  958. self.host_end = new_path_start;
  959. self.port = None;
  960. if let Some(ref mut index) = self.query_start { *index -= offset }
  961. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  962. }
  963. Ok(())
  964. }
  965. /// opt_new_port: None means leave unchanged, Some(None) means remove any port number.
  966. fn set_host_internal(&mut self, host: Host<String>, opt_new_port: Option<Option<u16>>) {
  967. let old_suffix_pos = if opt_new_port.is_some() { self.path_start } else { self.host_end };
  968. let suffix = self.slice(old_suffix_pos..).to_owned();
  969. self.serialization.truncate(self.host_start as usize);
  970. if !self.has_authority() {
  971. debug_assert!(self.slice(self.scheme_end..self.host_start) == ":");
  972. debug_assert!(self.username_end == self.host_start);
  973. self.serialization.push('/');
  974. self.serialization.push('/');
  975. self.username_end += 2;
  976. self.host_start += 2;
  977. }
  978. write!(&mut self.serialization, "{}", host).unwrap();
  979. self.host_end = to_u32(self.serialization.len()).unwrap();
  980. self.host = host.into();
  981. if let Some(new_port) = opt_new_port {
  982. self.port = new_port;
  983. if let Some(port) = new_port {
  984. write!(&mut self.serialization, ":{}", port).unwrap();
  985. }
  986. }
  987. let new_suffix_pos = to_u32(self.serialization.len()).unwrap();
  988. self.serialization.push_str(&suffix);
  989. let adjust = |index: &mut u32| {
  990. *index -= old_suffix_pos;
  991. *index += new_suffix_pos;
  992. };
  993. adjust(&mut self.path_start);
  994. if let Some(ref mut index) = self.query_start { adjust(index) }
  995. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  996. }
  997. /// Change this URL’s host to the given IP address.
  998. ///
  999. /// If this URL is cannot-be-a-base, do nothing and return `Err`.
  1000. ///
  1001. /// Compared to `Url::set_host`, this skips the host parser.
  1002. pub fn set_ip_host(&mut self, address: IpAddr) -> Result<(), ()> {
  1003. if self.cannot_be_a_base() {
  1004. return Err(())
  1005. }
  1006. let address = match address {
  1007. IpAddr::V4(address) => Host::Ipv4(address),
  1008. IpAddr::V6(address) => Host::Ipv6(address),
  1009. };
  1010. self.set_host_internal(address, None);
  1011. Ok(())
  1012. }
  1013. /// Change this URL’s password.
  1014. ///
  1015. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  1016. pub fn set_password(&mut self, password: Option<&str>) -> Result<(), ()> {
  1017. if !self.has_host() {
  1018. return Err(())
  1019. }
  1020. if let Some(password) = password {
  1021. let host_and_after = self.slice(self.host_start..).to_owned();
  1022. self.serialization.truncate(self.username_end as usize);
  1023. self.serialization.push(':');
  1024. self.serialization.extend(utf8_percent_encode(password, USERINFO_ENCODE_SET));
  1025. self.serialization.push('@');
  1026. let old_host_start = self.host_start;
  1027. let new_host_start = to_u32(self.serialization.len()).unwrap();
  1028. let adjust = |index: &mut u32| {
  1029. *index -= old_host_start;
  1030. *index += new_host_start;
  1031. };
  1032. self.host_start = new_host_start;
  1033. adjust(&mut self.host_end);
  1034. adjust(&mut self.path_start);
  1035. if let Some(ref mut index) = self.query_start { adjust(index) }
  1036. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1037. self.serialization.push_str(&host_and_after);
  1038. } else if self.byte_at(self.username_end) == b':' { // If there is a password to remove
  1039. let has_username_or_password = self.byte_at(self.host_start - 1) == b'@';
  1040. debug_assert!(has_username_or_password);
  1041. let username_start = self.scheme_end + 3;
  1042. let empty_username = username_start == self.username_end;
  1043. let start = self.username_end; // Remove the ':'
  1044. let end = if empty_username {
  1045. self.host_start // Remove the '@' as well
  1046. } else {
  1047. self.host_start - 1 // Keep the '@' to separate the username from the host
  1048. };
  1049. self.serialization.drain(start as usize .. end as usize);
  1050. let offset = end - start;
  1051. self.host_start -= offset;
  1052. self.host_end -= offset;
  1053. self.path_start -= offset;
  1054. if let Some(ref mut index) = self.query_start { *index -= offset }
  1055. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  1056. }
  1057. Ok(())
  1058. }
  1059. /// Change this URL’s username.
  1060. ///
  1061. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  1062. pub fn set_username(&mut self, username: &str) -> Result<(), ()> {
  1063. if !self.has_host() {
  1064. return Err(())
  1065. }
  1066. let username_start = self.scheme_end + 3;
  1067. debug_assert!(self.slice(self.scheme_end..username_start) == "://");
  1068. if self.slice(username_start..self.username_end) == username {
  1069. return Ok(())
  1070. }
  1071. let after_username = self.slice(self.username_end..).to_owned();
  1072. self.serialization.truncate(username_start as usize);
  1073. self.serialization.extend(utf8_percent_encode(username, USERINFO_ENCODE_SET));
  1074. let mut removed_bytes = self.username_end;
  1075. self.username_end = to_u32(self.serialization.len()).unwrap();
  1076. let mut added_bytes = self.username_end;
  1077. let new_username_is_empty = self.username_end == username_start;
  1078. match (new_username_is_empty, after_username.chars().next()) {
  1079. (true, Some('@')) => {
  1080. removed_bytes += 1;
  1081. self.serialization.push_str(&after_username[1..]);
  1082. }
  1083. (false, Some('@')) | (_, Some(':')) | (true, _) => {
  1084. self.serialization.push_str(&after_username);
  1085. }
  1086. (false, _) => {
  1087. added_bytes += 1;
  1088. self.serialization.push('@');
  1089. self.serialization.push_str(&after_username);
  1090. }
  1091. }
  1092. let adjust = |index: &mut u32| {
  1093. *index -= removed_bytes;
  1094. *index += added_bytes;
  1095. };
  1096. adjust(&mut self.host_start);
  1097. adjust(&mut self.host_end);
  1098. adjust(&mut self.path_start);
  1099. if let Some(ref mut index) = self.query_start { adjust(index) }
  1100. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1101. Ok(())
  1102. }
  1103. /// Change this URL’s scheme.
  1104. ///
  1105. /// Do nothing and return `Err` if:
  1106. /// * The new scheme is not in `[a-zA-Z][a-zA-Z0-9+.-]+`
  1107. /// * This URL is cannot-be-a-base and the new scheme is one of
  1108. /// `http`, `https`, `ws`, `wss`, `ftp`, or `gopher`
  1109. pub fn set_scheme(&mut self, scheme: &str) -> Result<(), ()> {
  1110. let mut parser = Parser::for_setter(String::new());
  1111. let remaining = try!(parser.parse_scheme(parser::Input::new(scheme)));
  1112. if !remaining.is_empty() ||
  1113. (!self.has_host() && SchemeType::from(&parser.serialization).is_special()) {
  1114. return Err(())
  1115. }
  1116. let old_scheme_end = self.scheme_end;
  1117. let new_scheme_end = to_u32(parser.serialization.len()).unwrap();
  1118. let adjust = |index: &mut u32| {
  1119. *index -= old_scheme_end;
  1120. *index += new_scheme_end;
  1121. };
  1122. self.scheme_end = new_scheme_end;
  1123. adjust(&mut self.username_end);
  1124. adjust(&mut self.host_start);
  1125. adjust(&mut self.host_end);
  1126. adjust(&mut self.path_start);
  1127. if let Some(ref mut index) = self.query_start { adjust(index) }
  1128. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1129. parser.serialization.push_str(self.slice(old_scheme_end..));
  1130. self.serialization = parser.serialization;
  1131. Ok(())
  1132. }
  1133. /// Convert a file name as `std::path::Path` into an URL in the `file` scheme.
  1134. ///
  1135. /// This returns `Err` if the given path is not absolute or,
  1136. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`).
  1137. pub fn from_file_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  1138. let mut serialization = "file://".to_owned();
  1139. let path_start = serialization.len() as u32;
  1140. try!(path_to_file_url_segments(path.as_ref(), &mut serialization));
  1141. Ok(Url {
  1142. serialization: serialization,
  1143. scheme_end: "file".len() as u32,
  1144. username_end: path_start,
  1145. host_start: path_start,
  1146. host_end: path_start,
  1147. host: HostInternal::None,
  1148. port: None,
  1149. path_start: path_start,
  1150. query_start: None,
  1151. fragment_start: None,
  1152. })
  1153. }
  1154. /// Convert a directory name as `std::path::Path` into an URL in the `file` scheme.
  1155. ///
  1156. /// This returns `Err` if the given path is not absolute or,
  1157. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`).
  1158. ///
  1159. /// Compared to `from_file_path`, this ensure that URL’s the path has a trailing slash
  1160. /// so that the entire path is considered when using this URL as a base URL.
  1161. ///
  1162. /// For example:
  1163. ///
  1164. /// * `"index.html"` parsed with `Url::from_directory_path(Path::new("/var/www"))`
  1165. /// as the base URL is `file:///var/www/index.html`
  1166. /// * `"index.html"` parsed with `Url::from_file_path(Path::new("/var/www"))`
  1167. /// as the base URL is `file:///var/index.html`, which might not be what was intended.
  1168. ///
  1169. /// Note that `std::path` does not consider trailing slashes significant
  1170. /// and usually does not include them (e.g. in `Path::parent()`).
  1171. pub fn from_directory_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  1172. let mut url = try!(Url::from_file_path(path));
  1173. if !url.serialization.ends_with('/') {
  1174. url.serialization.push('/')
  1175. }
  1176. Ok(url)
  1177. }
  1178. /// Assuming the URL is in the `file` scheme or similar,
  1179. /// convert its path to an absolute `std::path::Path`.
  1180. ///
  1181. /// **Note:** This does not actually check the URL’s `scheme`,
  1182. /// and may give nonsensical results for other schemes.
  1183. /// It is the user’s responsibility to check the URL’s scheme before calling this.
  1184. ///
  1185. /// ```
  1186. /// # use url::Url;
  1187. /// # let url = Url::parse("file:///etc/passwd").unwrap();
  1188. /// let path = url.to_file_path();
  1189. /// ```
  1190. ///
  1191. /// Returns `Err` if the host is neither empty nor `"localhost"`,
  1192. /// or if `Path::new_opt()` returns `None`.
  1193. /// (That is, if the percent-decoded path contains a NUL byte or,
  1194. /// for a Windows path, is not UTF-8.)
  1195. #[inline]
  1196. pub fn to_file_path(&self) -> Result<PathBuf, ()> {
  1197. // FIXME: Figure out what to do w.r.t host.
  1198. if matches!(self.host(), None | Some(Host::Domain("localhost"))) {
  1199. if let Some(segments) = self.path_segments() {
  1200. return file_url_segments_to_pathbuf(segments)
  1201. }
  1202. }
  1203. Err(())
  1204. }
  1205. // Private helper methods:
  1206. #[inline]
  1207. fn slice<R>(&self, range: R) -> &str where R: RangeArg {
  1208. range.slice_of(&self.serialization)
  1209. }
  1210. #[inline]
  1211. fn byte_at(&self, i: u32) -> u8 {
  1212. self.serialization.as_bytes()[i as usize]
  1213. }
  1214. }
  1215. /// Return an error if `Url::host` or `Url::port_or_known_default` return `None`.
  1216. impl ToSocketAddrs for Url {
  1217. type Iter = SocketAddrs;
  1218. fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
  1219. try!(self.with_default_port(|_| Err(()))).to_socket_addrs()
  1220. }
  1221. }
  1222. /// Parse a string as an URL, without a base URL or encoding override.
  1223. impl str::FromStr for Url {
  1224. type Err = ParseError;
  1225. #[inline]
  1226. fn from_str(input: &str) -> Result<Url, ::ParseError> {
  1227. Url::parse(input)
  1228. }
  1229. }
  1230. /// Display the serialization of this URL.
  1231. impl fmt::Display for Url {
  1232. #[inline]
  1233. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  1234. fmt::Display::fmt(&self.serialization, formatter)
  1235. }
  1236. }
  1237. /// Debug the serialization of this URL.
  1238. impl fmt::Debug for Url {
  1239. #[inline]
  1240. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  1241. fmt::Debug::fmt(&self.serialization, formatter)
  1242. }
  1243. }
  1244. /// URLs compare like their serialization.
  1245. impl Eq for Url {}
  1246. /// URLs compare like their serialization.
  1247. impl PartialEq for Url {
  1248. #[inline]
  1249. fn eq(&self, other: &Self) -> bool {
  1250. self.serialization == other.serialization
  1251. }
  1252. }
  1253. /// URLs compare like their serialization.
  1254. impl Ord for Url {
  1255. #[inline]
  1256. fn cmp(&self, other: &Self) -> cmp::Ordering {
  1257. self.serialization.cmp(&other.serialization)
  1258. }
  1259. }
  1260. /// URLs compare like their serialization.
  1261. impl PartialOrd for Url {
  1262. #[inline]
  1263. fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
  1264. self.serialization.partial_cmp(&other.serialization)
  1265. }
  1266. }
  1267. /// URLs hash like their serialization.
  1268. impl hash::Hash for Url {
  1269. #[inline]
  1270. fn hash<H>(&self, state: &mut H) where H: hash::Hasher {
  1271. hash::Hash::hash(&self.serialization, state)
  1272. }
  1273. }
  1274. /// Return the serialization of this URL.
  1275. impl AsRef<str> for Url {
  1276. #[inline]
  1277. fn as_ref(&self) -> &str {
  1278. &self.serialization
  1279. }
  1280. }
  1281. trait RangeArg {
  1282. fn slice_of<'a>(&self, s: &'a str) -> &'a str;
  1283. }
  1284. impl RangeArg for Range<u32> {
  1285. #[inline]
  1286. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  1287. &s[self.start as usize .. self.end as usize]
  1288. }
  1289. }
  1290. impl RangeArg for RangeFrom<u32> {
  1291. #[inline]
  1292. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  1293. &s[self.start as usize ..]
  1294. }
  1295. }
  1296. impl RangeArg for RangeTo<u32> {
  1297. #[inline]
  1298. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  1299. &s[.. self.end as usize]
  1300. }
  1301. }
  1302. #[cfg(feature="rustc-serialize")]
  1303. impl rustc_serialize::Encodable for Url {
  1304. fn encode<S: rustc_serialize::Encoder>(&self, encoder: &mut S) -> Result<(), S::Error> {
  1305. encoder.emit_str(self.as_str())
  1306. }
  1307. }
  1308. #[cfg(feature="rustc-serialize")]
  1309. impl rustc_serialize::Decodable for Url {
  1310. fn decode<D: rustc_serialize::Decoder>(decoder: &mut D) -> Result<Url, D::Error> {
  1311. Url::parse(&*try!(decoder.read_str())).map_err(|error| {
  1312. decoder.error(&format!("URL parsing error: {}", error))
  1313. })
  1314. }
  1315. }
  1316. /// Serializes this URL into a `serde` stream.
  1317. ///
  1318. /// This implementation is only available if the `serde` Cargo feature is enabled.
  1319. #[cfg(feature="serde")]
  1320. impl serde::Serialize for Url {
  1321. fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::Serializer {
  1322. format!("{}", self).serialize(serializer)
  1323. }
  1324. }
  1325. /// Deserializes this URL from a `serde` stream.
  1326. ///
  1327. /// This implementation is only available if the `serde` Cargo feature is enabled.
  1328. #[cfg(feature="serde")]
  1329. impl serde::Deserialize for Url {
  1330. fn deserialize<D>(deserializer: &mut D) -> Result<Url, D::Error> where D: serde::Deserializer {
  1331. let string_representation: String = try!(serde::Deserialize::deserialize(deserializer));
  1332. Ok(Url::parse(&string_representation).unwrap())
  1333. }
  1334. }
  1335. #[cfg(unix)]
  1336. fn path_to_file_url_segments(path: &Path, serialization: &mut String) -> Result<(), ()> {
  1337. use std::os::unix::prelude::OsStrExt;
  1338. if !path.is_absolute() {
  1339. return Err(())
  1340. }
  1341. let mut empty = true;
  1342. // skip the root component
  1343. for component in path.components().skip(1) {
  1344. empty = false;
  1345. serialization.push('/');
  1346. serialization.extend(percent_encode(
  1347. component.as_os_str().as_bytes(), PATH_SEGMENT_ENCODE_SET));
  1348. }
  1349. if empty {
  1350. // An URL’s path must not be empty.
  1351. serialization.push('/');
  1352. }
  1353. Ok(())
  1354. }
  1355. #[cfg(windows)]
  1356. fn path_to_file_url_segments(path: &Path, serialization: &mut String) -> Result<(), ()> {
  1357. path_to_file_url_segments_windows(path, serialization)
  1358. }
  1359. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  1360. #[cfg_attr(not(windows), allow(dead_code))]
  1361. fn path_to_file_url_segments_windows(path: &Path, serialization: &mut String) -> Result<(), ()> {
  1362. use std::path::{Prefix, Component};
  1363. if !path.is_absolute() {
  1364. return Err(())
  1365. }
  1366. let mut components = path.components();
  1367. let disk = match components.next() {
  1368. Some(Component::Prefix(ref p)) => match p.kind() {
  1369. Prefix::Disk(byte) => byte,
  1370. Prefix::VerbatimDisk(byte) => byte,
  1371. _ => return Err(()),
  1372. },
  1373. // FIXME: do something with UNC and other prefixes?
  1374. _ => return Err(())
  1375. };
  1376. // Start with the prefix, e.g. "C:"
  1377. serialization.push('/');
  1378. serialization.push(disk as char);
  1379. serialization.push(':');
  1380. for component in components {
  1381. if component == Component::RootDir { continue }
  1382. // FIXME: somehow work with non-unicode?
  1383. let component = try!(component.as_os_str().to_str().ok_or(()));
  1384. serialization.push('/');
  1385. serialization.extend(percent_encode(component.as_bytes(), PATH_SEGMENT_ENCODE_SET));
  1386. }
  1387. Ok(())
  1388. }
  1389. #[cfg(unix)]
  1390. fn file_url_segments_to_pathbuf(segments: str::Split<char>) -> Result<PathBuf, ()> {
  1391. use std::ffi::OsStr;
  1392. use std::os::unix::prelude::OsStrExt;
  1393. use std::path::PathBuf;
  1394. let mut bytes = Vec::new();
  1395. for segment in segments {
  1396. bytes.push(b'/');
  1397. bytes.extend(percent_decode(segment.as_bytes()));
  1398. }
  1399. let os_str = OsStr::from_bytes(&bytes);
  1400. let path = PathBuf::from(os_str);
  1401. debug_assert!(path.is_absolute(),
  1402. "to_file_path() failed to produce an absolute Path");
  1403. Ok(path)
  1404. }
  1405. #[cfg(windows)]
  1406. fn file_url_segments_to_pathbuf(segments: str::Split<char>) -> Result<PathBuf, ()> {
  1407. file_url_segments_to_pathbuf_windows(segments)
  1408. }
  1409. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  1410. #[cfg_attr(not(windows), allow(dead_code))]
  1411. fn file_url_segments_to_pathbuf_windows(mut segments: str::Split<char>) -> Result<PathBuf, ()> {
  1412. let first = try!(segments.next().ok_or(()));
  1413. let mut string = match first.len() {
  1414. 2 => {
  1415. if !first.starts_with(parser::ascii_alpha) || first.as_bytes()[1] != b':' {
  1416. return Err(())
  1417. }
  1418. first.to_owned()
  1419. },
  1420. 4 => {
  1421. if !first.starts_with(parser::ascii_alpha) {
  1422. return Err(())
  1423. }
  1424. let bytes = first.as_bytes();
  1425. if bytes[1] != b'%' || bytes[2] != b'3' || (bytes[3] != b'a' && bytes[3] != b'A') {
  1426. return Err(())
  1427. }
  1428. first[0..1].to_owned() + ":"
  1429. },
  1430. _ => return Err(()),
  1431. };
  1432. for segment in segments {
  1433. string.push('\\');
  1434. // Currently non-unicode windows paths cannot be represented
  1435. match String::from_utf8(percent_decode(segment.as_bytes()).collect()) {
  1436. Ok(s) => string.push_str(&s),
  1437. Err(..) => return Err(()),
  1438. }
  1439. }
  1440. let path = PathBuf::from(string);
  1441. debug_assert!(path.is_absolute(),
  1442. "to_file_path() failed to produce an absolute Path");
  1443. Ok(path)
  1444. }
  1445. fn io_error<T>(reason: &str) -> io::Result<T> {
  1446. Err(io::Error::new(io::ErrorKind::InvalidData, reason))
  1447. }
  1448. /// Implementation detail of `Url::query_pairs_mut`. Typically not used directly.
  1449. pub struct UrlQuery<'a> {
  1450. url: &'a mut Url,
  1451. fragment: Option<String>,
  1452. }
  1453. impl<'a> Drop for UrlQuery<'a> {
  1454. fn drop(&mut self) {
  1455. self.url.restore_already_parsed_fragment(self.fragment.take())
  1456. }
  1457. }