lib.rs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  1. // Copyright 2013-2015 Simon Sapin.
  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. <a href="https://github.com/servo/rust-url"><img style="position: absolute; top: 0; left: 0; border: 0;" src="../github.png" alt="Fork me on GitHub"></a>
  10. <style>.sidebar { margin-top: 53px }</style>
  11. rust-url is an implementation of the [URL Standard](http://url.spec.whatwg.org/)
  12. for the [Rust](http://rust-lang.org/) programming language.
  13. It builds with [Cargo](http://crates.io/).
  14. To use it in your project, add this to your `Cargo.toml` file:
  15. ```Cargo
  16. [dependencies.url]
  17. git = "https://github.com/servo/rust-url"
  18. ```
  19. Supporting encodings other than UTF-8 in query strings is an optional feature
  20. that requires [rust-encoding](https://github.com/lifthrasiir/rust-encoding)
  21. and is off by default.
  22. You can enable it with
  23. [Cargo’s *features* mechanism](http://doc.crates.io/manifest.html#the-[features]-section):
  24. ```Cargo
  25. [dependencies.url]
  26. git = "https://github.com/servo/rust-url"
  27. features = ["query_encoding"]
  28. ```
  29. … or by passing `--cfg 'feature="query_encoding"'` to rustc.
  30. # URL parsing and data structures
  31. First, URL parsing may fail for various reasons and therefore returns a `Result`.
  32. ```
  33. use url::{Url, ParseError};
  34. assert!(Url::parse("http://[:::1]") == Err(ParseError::InvalidIpv6Address))
  35. ```
  36. Let’s parse a valid URL and look at its components.
  37. ```
  38. use url::{Url, Host};
  39. let issue_list_url = Url::parse(
  40. "https://github.com/rust-lang/rust/issues?labels=E-easy&state=open"
  41. ).unwrap();
  42. assert!(issue_list_url.scheme() == "https");
  43. assert!(issue_list_url.username() == "");
  44. assert!(issue_list_url.password() == None);
  45. assert!(issue_list_url.host_str() == Some("github.com"));
  46. assert!(issue_list_url.host() == Some(Host::Domain("github.com")));
  47. assert!(issue_list_url.port() == None);
  48. assert!(issue_list_url.path() == "/rust-lang/rust/issues");
  49. assert!(issue_list_url.path_segments().map(|c| c.collect::<Vec<_>>()) ==
  50. Some(vec!["rust-lang", "rust", "issues"]));
  51. assert!(issue_list_url.query() == Some("labels=E-easy&state=open"));
  52. assert!(issue_list_url.fragment() == None);
  53. assert!(!issue_list_url.cannot_be_a_base());
  54. ```
  55. Some URLs are said to be *cannot-be-a-base*:
  56. they don’t have a username, password, host, or port,
  57. and their "path" is an arbitrary string rather than slash-separated segments:
  58. ```
  59. use url::Url;
  60. let data_url = Url::parse("data:text/plain,Hello?World#").unwrap();
  61. assert!(data_url.cannot_be_a_base());
  62. assert!(data_url.scheme() == "data");
  63. assert!(data_url.path() == "text/plain,Hello");
  64. assert!(data_url.path_segments().is_none());
  65. assert!(data_url.query() == Some("World"));
  66. assert!(data_url.fragment() == Some(""));
  67. ```
  68. # Base URL
  69. Many contexts allow URL *references* that can be relative to a *base URL*:
  70. ```html
  71. <link rel="stylesheet" href="../main.css">
  72. ```
  73. Since parsed URL are absolute, giving a base is required for parsing relative URLs:
  74. ```
  75. use url::{Url, ParseError};
  76. assert!(Url::parse("../main.css") == Err(ParseError::RelativeUrlWithoutBase))
  77. ```
  78. Use the `join` method on an `Url` to use it as a base URL:
  79. ```
  80. use url::Url;
  81. let this_document = Url::parse("http://servo.github.io/rust-url/url/index.html").unwrap();
  82. let css_url = this_document.join("../main.css").unwrap();
  83. assert_eq!(css_url.as_str(), "http://servo.github.io/rust-url/main.css")
  84. */
  85. #![cfg_attr(feature="heap_size", feature(plugin, custom_derive))]
  86. #![cfg_attr(feature="heap_size", plugin(heapsize_plugin))]
  87. #[cfg(feature="rustc-serialize")] extern crate rustc_serialize;
  88. #[macro_use] extern crate matches;
  89. #[cfg(feature="serde")] extern crate serde;
  90. #[cfg(feature="heap_size")] #[macro_use] extern crate heapsize;
  91. extern crate idna;
  92. use host::HostInternal;
  93. use parser::{Parser, Context};
  94. use percent_encoding::{PATH_SEGMENT_ENCODE_SET, USERINFO_ENCODE_SET,
  95. percent_encode, percent_decode, utf8_percent_encode};
  96. use std::cmp;
  97. use std::fmt::{self, Write};
  98. use std::hash;
  99. use std::io;
  100. use std::mem;
  101. use std::net::{ToSocketAddrs, IpAddr};
  102. use std::ops::{Range, RangeFrom, RangeTo};
  103. use std::path::{Path, PathBuf};
  104. use std::str;
  105. pub use encoding::EncodingOverride;
  106. pub use origin::{Origin, OpaqueOrigin};
  107. pub use host::{Host, HostAndPort, SocketAddrs};
  108. pub use parser::{ParseError, SchemeType, to_u32};
  109. pub use slicing::Position;
  110. pub use webidl::WebIdl;
  111. mod encoding;
  112. mod host;
  113. mod origin;
  114. mod parser;
  115. mod slicing;
  116. mod webidl;
  117. pub mod percent_encoding;
  118. pub mod form_urlencoded;
  119. /// A parsed URL record.
  120. #[derive(Clone)]
  121. #[cfg_attr(feature="heap_size", derive(HeapSizeOf))]
  122. pub struct Url {
  123. /// Syntax in pseudo-BNF:
  124. ///
  125. /// url = scheme ":" [ hierarchical | non-hierarchical ] [ "?" query ]? [ "#" fragment ]?
  126. /// non-hierarchical = non-hierarchical-path
  127. /// non-hierarchical-path = /* Does not start with "/" */
  128. /// hierarchical = authority? hierarchical-path
  129. /// authority = "//" userinfo? host [ ":" port ]?
  130. /// userinfo = username [ ":" password ]? "@"
  131. /// hierarchical-path = [ "/" path-segment ]+
  132. serialization: String,
  133. // Components
  134. scheme_end: u32, // Before ':'
  135. username_end: u32, // Before ':' (if a password is given) or '@' (if not)
  136. host_start: u32,
  137. host_end: u32,
  138. host: HostInternal,
  139. port: Option<u16>,
  140. path_start: u32, // Before initial '/', if any
  141. query_start: Option<u32>, // Before '?', unlike Position::QueryStart
  142. fragment_start: Option<u32>, // Before '#', unlike Position::FragmentStart
  143. }
  144. #[derive(Default)]
  145. pub struct ParseOptions<'a> {
  146. pub base_url: Option<&'a Url>,
  147. #[cfg(feature = "query_encoding")] pub encoding_override: Option<encoding::EncodingRef>,
  148. pub log_syntax_violation: Option<&'a Fn(&'static str)>,
  149. }
  150. impl Url {
  151. /// Parse an absolute URL from a string.
  152. #[inline]
  153. pub fn parse(input: &str) -> Result<Url, ::ParseError> {
  154. Url::parse_with(input, ParseOptions::default())
  155. }
  156. /// Parse a string as an URL, with this URL as the base URL.
  157. #[inline]
  158. pub fn join(&self, input: &str) -> Result<Url, ::ParseError> {
  159. Url::parse_with(input, ParseOptions { base_url: Some(self), ..Default::default() })
  160. }
  161. /// The URL parser with all of its parameters.
  162. ///
  163. /// `encoding_override` is a legacy concept only relevant for HTML.
  164. /// When it’s not needed,
  165. /// `s.parse::<Url>()`, `Url::from_str(s)` and `url.join(s)` can be used instead.
  166. pub fn parse_with(input: &str, options: ParseOptions) -> Result<Url, ::ParseError> {
  167. Parser {
  168. serialization: String::with_capacity(input.len()),
  169. base_url: options.base_url,
  170. query_encoding_override: EncodingOverride::from_parse_options(&options),
  171. log_syntax_violation: options.log_syntax_violation,
  172. context: Context::UrlParser,
  173. }.parse_url(input)
  174. }
  175. /// Return the serialization of this URL.
  176. ///
  177. /// This is fast since that serialization is already stored in the `Url` struct.
  178. #[inline]
  179. pub fn as_str(&self) -> &str {
  180. &self.serialization
  181. }
  182. /// Return the serialization of this URL.
  183. ///
  184. /// This consumes the `Url` and takes ownership of the `String` stored in it.
  185. #[inline]
  186. pub fn into_string(self) -> String {
  187. self.serialization
  188. }
  189. /// Return the scheme of this URL, lower-cased, as an ASCII string without the ':' delimiter.
  190. #[inline]
  191. pub fn scheme(&self) -> &str {
  192. self.slice(..self.scheme_end)
  193. }
  194. /// Return whether the URL has a host.
  195. #[inline]
  196. pub fn has_host(&self) -> bool {
  197. debug_assert!(self.byte_at(self.scheme_end) == b':');
  198. self.slice(self.scheme_end + 1 ..).starts_with("//")
  199. }
  200. /// Return whether this URL is a cannot-be-a-base URL,
  201. /// meaning that parsing a relative URL string with this URL as the base will return an error.
  202. ///
  203. /// This is the case if the scheme and `:` delimiter are not followed by a `/` slash,
  204. /// as is typically the case of `data:` and `mailto:` URLs.
  205. #[inline]
  206. pub fn cannot_be_a_base(&self) -> bool {
  207. self.byte_at(self.path_start) != b'/'
  208. }
  209. /// Return the username for this URL (typically the empty string)
  210. /// as a percent-encoded ASCII string.
  211. pub fn username(&self) -> &str {
  212. if self.has_host() {
  213. self.slice(self.scheme_end + 3..self.username_end)
  214. } else {
  215. ""
  216. }
  217. }
  218. /// Return the password for this URL, if any, as a percent-encoded ASCII string.
  219. pub fn password(&self) -> Option<&str> {
  220. // This ':' is not the one marking a port number since a host can not be empty.
  221. // (Except for file: URLs, which do not have port numbers.)
  222. if self.byte_at(self.username_end) == b':' {
  223. debug_assert!(self.has_host());
  224. debug_assert!(self.host_start < self.host_end);
  225. debug_assert!(self.byte_at(self.host_start - 1) == b'@');
  226. Some(self.slice(self.username_end + 1..self.host_start - 1))
  227. } else {
  228. None
  229. }
  230. }
  231. /// Return the string representation of the host (domain or IP address) for this URL, if any.
  232. ///
  233. /// Non-ASCII domains are punycode-encoded per IDNA.
  234. /// IPv6 addresses are given between `[` and `]` brackets.
  235. ///
  236. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  237. /// don’t have a host.
  238. ///
  239. /// See also the `host` method.
  240. pub fn host_str(&self) -> Option<&str> {
  241. if self.has_host() {
  242. Some(self.slice(self.host_start..self.host_end))
  243. } else {
  244. None
  245. }
  246. }
  247. /// Return the parsed representation of the host for this URL.
  248. /// Non-ASCII domain labels are punycode-encoded per IDNA.
  249. ///
  250. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  251. /// don’t have a host.
  252. ///
  253. /// See also the `host_str` method.
  254. pub fn host(&self) -> Option<Host<&str>> {
  255. match self.host {
  256. HostInternal::None => None,
  257. HostInternal::Domain => Some(Host::Domain(self.slice(self.host_start..self.host_end))),
  258. HostInternal::Ipv4(address) => Some(Host::Ipv4(address)),
  259. HostInternal::Ipv6(address) => Some(Host::Ipv6(address)),
  260. }
  261. }
  262. /// If this URL has a host and it is a domain name (not an IP address), return it.
  263. pub fn domain(&self) -> Option<&str> {
  264. match self.host {
  265. HostInternal::Domain => Some(self.slice(self.host_start..self.host_end)),
  266. _ => None,
  267. }
  268. }
  269. /// Return the port number for this URL, if any.
  270. #[inline]
  271. pub fn port(&self) -> Option<u16> {
  272. self.port
  273. }
  274. /// Return the port number for this URL, or the default port number if it is known.
  275. ///
  276. /// This method only knows the default port number
  277. /// of the `http`, `https`, `ws`, `wss`, `ftp`, and `gopher` schemes.
  278. ///
  279. /// For URLs in these schemes, this method always returns `Some(_)`.
  280. /// For other schemes, it is the same as `Url::port()`.
  281. #[inline]
  282. pub fn port_or_known_default(&self) -> Option<u16> {
  283. self.port.or_else(|| parser::default_port(self.scheme()))
  284. }
  285. /// If the URL has a host, return something that implements `ToSocketAddrs`.
  286. ///
  287. /// If the URL has no port number and the scheme’s default port number is not known
  288. /// (see `Url::port_or_known_default`),
  289. /// the closure is called to obtain a port number.
  290. /// Typically, this closure can match on the result `Url::scheme`
  291. /// to have per-scheme default port numbers,
  292. /// and panic for schemes it’s not prepared to handle.
  293. /// For example:
  294. ///
  295. /// ```rust
  296. /// # use url::Url;
  297. /// # use std::net::TcpStream;
  298. /// # use std::io;
  299. ///
  300. /// fn connect(url: &Url) -> io::Result<TcpStream> {
  301. /// TcpStream::connect(try!(url.with_default_port(default_port)))
  302. /// }
  303. ///
  304. /// fn default_port(url: &Url) -> Result<u16, ()> {
  305. /// match url.scheme() {
  306. /// "git" => Ok(9418),
  307. /// "git+ssh" => Ok(22),
  308. /// "git+https" => Ok(443),
  309. /// "git+http" => Ok(80),
  310. /// _ => Err(()),
  311. /// }
  312. /// }
  313. /// ```
  314. pub fn with_default_port<F>(&self, f: F) -> io::Result<HostAndPort<&str>>
  315. where F: FnOnce(&Url) -> Result<u16, ()> {
  316. Ok(HostAndPort {
  317. host: try!(self.host()
  318. .ok_or(())
  319. .or_else(|()| io_error("URL has no host"))),
  320. port: try!(self.port_or_known_default()
  321. .ok_or(())
  322. .or_else(|()| f(self))
  323. .or_else(|()| io_error("URL has no port number")))
  324. })
  325. }
  326. /// Return the path for this URL, as a percent-encoded ASCII string.
  327. /// For relative URLs, this starts with a '/' slash
  328. /// and continues with slash-separated path segments.
  329. /// For cannot-be-a-base URLs, this is an arbitrary string that doesn’t start with '/'.
  330. pub fn path(&self) -> &str {
  331. match (self.query_start, self.fragment_start) {
  332. (None, None) => self.slice(self.path_start..),
  333. (Some(next_component_start), _) |
  334. (None, Some(next_component_start)) => {
  335. self.slice(self.path_start..next_component_start)
  336. }
  337. }
  338. }
  339. /// If this URL is relative, return an iterator of '/' slash-separated path segments,
  340. /// each as a percent-encoded ASCII string.
  341. ///
  342. /// Return `None` for cannot-be-a-base URLs, or an iterator of at least one string.
  343. pub fn path_segments(&self) -> Option<str::Split<char>> {
  344. let path = self.path();
  345. if path.starts_with('/') {
  346. Some(path[1..].split('/'))
  347. } else {
  348. None
  349. }
  350. }
  351. /// Return this URL’s query string, if any, as a percent-encoded ASCII string.
  352. pub fn query(&self) -> Option<&str> {
  353. match (self.query_start, self.fragment_start) {
  354. (None, _) => None,
  355. (Some(query_start), None) => {
  356. debug_assert!(self.byte_at(query_start) == b'?');
  357. Some(self.slice(query_start + 1..))
  358. }
  359. (Some(query_start), Some(fragment_start)) => {
  360. debug_assert!(self.byte_at(query_start) == b'?');
  361. Some(self.slice(query_start + 1..fragment_start))
  362. }
  363. }
  364. }
  365. /// Return this URL’s fragment identifier, if any.
  366. ///
  367. /// **Note:** the parser did *not* percent-encode this component,
  368. /// but the input may have been percent-encoded already.
  369. pub fn fragment(&self) -> Option<&str> {
  370. self.fragment_start.map(|start| {
  371. debug_assert!(self.byte_at(start) == b'#');
  372. self.slice(start + 1..)
  373. })
  374. }
  375. fn mutate<F: FnOnce(&mut Parser) -> R, R>(&mut self, f: F) -> R {
  376. let mut parser = Parser::for_setter(mem::replace(&mut self.serialization, String::new()));
  377. let result = f(&mut parser);
  378. self.serialization = parser.serialization;
  379. result
  380. }
  381. /// Change this URL’s fragment identifier.
  382. pub fn set_fragment(&mut self, fragment: Option<&str>) {
  383. // Remove any previous fragment
  384. if let Some(start) = self.fragment_start {
  385. debug_assert!(self.byte_at(start) == b'#');
  386. self.serialization.truncate(start as usize);
  387. }
  388. // Write the new one
  389. if let Some(input) = fragment {
  390. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  391. self.serialization.push('#');
  392. self.mutate(|parser| parser.parse_fragment(input))
  393. } else {
  394. self.fragment_start = None
  395. }
  396. }
  397. /// Change this URL’s query string.
  398. pub fn set_query(&mut self, query: Option<&str>) {
  399. // Stash any fragment
  400. let fragment = self.fragment_start.map(|start| {
  401. let f = self.slice(start..).to_owned();
  402. self.serialization.truncate(start as usize);
  403. f
  404. });
  405. // Remove any previous query
  406. if let Some(start) = self.query_start {
  407. debug_assert!(self.byte_at(start) == b'?');
  408. self.serialization.truncate(start as usize);
  409. }
  410. // Write the new one
  411. if let Some(input) = query {
  412. self.query_start = Some(to_u32(self.serialization.len()).unwrap());
  413. self.serialization.push('?');
  414. let scheme_end = self.scheme_end;
  415. self.mutate(|parser| parser.parse_query(scheme_end, input));
  416. }
  417. // Restore the fragment, if any
  418. if let Some(ref fragment) = fragment {
  419. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  420. debug_assert!(fragment.starts_with('#'));
  421. self.serialization.push_str(fragment) // It’s already been through the parser
  422. }
  423. }
  424. /// Change this URL’s path.
  425. pub fn set_path(&mut self, path: &str) {
  426. let (old_after_path_pos, after_path) = match (self.query_start, self.fragment_start) {
  427. (Some(i), _) | (None, Some(i)) => (i, self.slice(i..).to_owned()),
  428. (None, None) => (to_u32(self.serialization.len()).unwrap(), String::new())
  429. };
  430. let cannot_be_a_base = self.cannot_be_a_base();
  431. let scheme_type = SchemeType::from(self.scheme());
  432. self.serialization.truncate(self.path_start as usize);
  433. self.mutate(|parser| {
  434. if cannot_be_a_base {
  435. if path.starts_with('/') {
  436. parser.serialization.push_str("%2F");
  437. parser.parse_cannot_be_a_base_path(&path[1..]);
  438. } else {
  439. parser.parse_cannot_be_a_base_path(path);
  440. }
  441. } else {
  442. let mut has_host = true; // FIXME
  443. parser.parse_path_start(scheme_type, &mut has_host, path);
  444. }
  445. });
  446. let new_after_path_pos = to_u32(self.serialization.len()).unwrap();
  447. let adjust = |index: &mut u32| {
  448. *index -= old_after_path_pos;
  449. *index += new_after_path_pos;
  450. };
  451. if let Some(ref mut index) = self.query_start { adjust(index) }
  452. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  453. self.serialization.push_str(&after_path)
  454. }
  455. /// Remove the last segment of this URL’s path.
  456. ///
  457. /// If this URL is cannot-be-a-base, do nothing and return `Err`.
  458. pub fn pop_path_segment(&mut self) -> Result<(), ()> {
  459. if self.cannot_be_a_base() {
  460. return Err(())
  461. }
  462. let last_slash;
  463. let path_len;
  464. {
  465. let path = self.path();
  466. last_slash = path.rfind('/').unwrap();
  467. path_len = path.len();
  468. };
  469. if last_slash > 0 {
  470. // Found a slash other than the initial one
  471. let last_slash = last_slash + self.path_start as usize;
  472. let path_end = path_len + self.path_start as usize;
  473. self.serialization.drain(last_slash..path_end);
  474. let offset = (path_end - last_slash) as u32;
  475. if let Some(ref mut index) = self.query_start { *index -= offset }
  476. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  477. }
  478. Ok(())
  479. }
  480. /// Add a segment at the end of this URL’s path.
  481. ///
  482. /// If this URL is cannot-be-a-base, do nothing and return `Err`.
  483. pub fn push_path_segment(&mut self, segment: &str) -> Result<(), ()> {
  484. if self.cannot_be_a_base() {
  485. return Err(())
  486. }
  487. let after_path = match (self.query_start, self.fragment_start) {
  488. (Some(i), _) | (None, Some(i)) => {
  489. let s = self.slice(i..).to_owned();
  490. self.serialization.truncate(i as usize);
  491. s
  492. },
  493. (None, None) => String::new()
  494. };
  495. let scheme_type = SchemeType::from(self.scheme());
  496. let path_start = self.path_start as usize;
  497. self.serialization.push('/');
  498. self.mutate(|parser| {
  499. parser.context = parser::Context::PathSegmentSetter;
  500. let mut has_host = true; // FIXME account for this?
  501. parser.parse_path(scheme_type, &mut has_host, path_start, segment)
  502. });
  503. let offset = to_u32(self.serialization.len()).unwrap() - self.path_start;
  504. if let Some(ref mut index) = self.query_start { *index += offset }
  505. if let Some(ref mut index) = self.fragment_start { *index += offset }
  506. self.serialization.push_str(&after_path);
  507. Ok(())
  508. }
  509. /// Change this URL’s port number.
  510. ///
  511. /// If this URL is cannot-be-a-base, does not have a host, or has the `file` scheme;
  512. /// do nothing and return `Err`.
  513. pub fn set_port(&mut self, mut port: Option<u16>) -> Result<(), ()> {
  514. if !self.has_host() || self.scheme() == "file" {
  515. return Err(())
  516. }
  517. if port.is_some() && port == parser::default_port(self.scheme()) {
  518. port = None
  519. }
  520. self.set_port_internal(port);
  521. Ok(())
  522. }
  523. fn set_port_internal(&mut self, port: Option<u16>) {
  524. match (self.port, port) {
  525. (None, None) => {}
  526. (Some(_), None) => {
  527. self.serialization.drain(self.host_end as usize .. self.path_start as usize);
  528. let offset = self.path_start - self.host_end;
  529. self.path_start = self.host_end;
  530. if let Some(ref mut index) = self.query_start { *index -= offset }
  531. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  532. }
  533. (Some(old), Some(new)) if old == new => {}
  534. (_, Some(new)) => {
  535. let path_and_after = self.slice(self.path_start..).to_owned();
  536. self.serialization.truncate(self.host_end as usize);
  537. write!(&mut self.serialization, ":{}", new).unwrap();
  538. let old_path_start = self.path_start;
  539. let new_path_start = to_u32(self.serialization.len()).unwrap();
  540. self.path_start = new_path_start;
  541. let adjust = |index: &mut u32| {
  542. *index -= old_path_start;
  543. *index += new_path_start;
  544. };
  545. if let Some(ref mut index) = self.query_start { adjust(index) }
  546. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  547. self.serialization.push_str(&path_and_after);
  548. }
  549. }
  550. }
  551. /// Change this URL’s host.
  552. ///
  553. /// If this URL is cannot-be-a-base or there is an error parsing the given `host`,
  554. /// do nothing and return `Err`.
  555. ///
  556. /// Removing the host (calling this with `None`)
  557. /// will also remove any username, password, and port number.
  558. pub fn set_host(&mut self, host: Option<&str>) -> Result<(), ()> {
  559. if self.cannot_be_a_base() {
  560. return Err(())
  561. }
  562. if let Some(host) = host {
  563. self.set_host_internal(try!(Host::parse(host).map_err(|_| ())), None)
  564. } else if self.has_host() {
  565. debug_assert!(self.byte_at(self.scheme_end) == b':');
  566. debug_assert!(self.byte_at(self.path_start) == b'/');
  567. let new_path_start = self.scheme_end + 1;
  568. self.serialization.drain(self.path_start as usize..new_path_start as usize);
  569. let offset = self.path_start - new_path_start;
  570. self.path_start = new_path_start;
  571. self.username_end = new_path_start;
  572. self.host_start = new_path_start;
  573. self.host_end = new_path_start;
  574. self.port = None;
  575. if let Some(ref mut index) = self.query_start { *index -= offset }
  576. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  577. }
  578. Ok(())
  579. }
  580. /// opt_new_port: None means leave unchanged, Some(None) means remove any port number.
  581. fn set_host_internal(&mut self, host: Host<String>, opt_new_port: Option<Option<u16>>) {
  582. let old_suffix_pos = if opt_new_port.is_some() { self.path_start } else { self.host_end };
  583. let suffix = self.slice(old_suffix_pos..).to_owned();
  584. self.serialization.truncate(self.host_start as usize);
  585. if !self.has_host() {
  586. debug_assert!(self.slice(self.scheme_end..self.host_start) == ":");
  587. debug_assert!(self.username_end == self.host_start);
  588. self.serialization.push('/');
  589. self.serialization.push('/');
  590. self.username_end += 2;
  591. self.host_start += 2;
  592. }
  593. write!(&mut self.serialization, "{}", host).unwrap();
  594. self.host_end = to_u32(self.serialization.len()).unwrap();
  595. self.host = host.into();
  596. if let Some(new_port) = opt_new_port {
  597. self.port = new_port;
  598. if let Some(port) = new_port {
  599. write!(&mut self.serialization, ":{}", port).unwrap();
  600. }
  601. }
  602. let new_suffix_pos = to_u32(self.serialization.len()).unwrap();
  603. self.serialization.push_str(&suffix);
  604. let adjust = |index: &mut u32| {
  605. *index -= old_suffix_pos;
  606. *index += new_suffix_pos;
  607. };
  608. adjust(&mut self.path_start);
  609. if let Some(ref mut index) = self.query_start { adjust(index) }
  610. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  611. }
  612. /// Change this URL’s host to the given IP address.
  613. ///
  614. /// If this URL is cannot-be-a-base, do nothing and return `Err`.
  615. ///
  616. /// Compared to `Url::set_host`, this skips the host parser.
  617. pub fn set_ip_host(&mut self, address: IpAddr) -> Result<(), ()> {
  618. if self.cannot_be_a_base() {
  619. return Err(())
  620. }
  621. let address = match address {
  622. IpAddr::V4(address) => Host::Ipv4(address),
  623. IpAddr::V6(address) => Host::Ipv6(address),
  624. };
  625. self.set_host_internal(address, None);
  626. Ok(())
  627. }
  628. /// Change this URL’s password.
  629. ///
  630. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  631. pub fn set_password(&mut self, password: Option<&str>) -> Result<(), ()> {
  632. if !self.has_host() {
  633. return Err(())
  634. }
  635. if let Some(password) = password {
  636. let host_and_after = self.slice(self.host_start..).to_owned();
  637. self.serialization.truncate(self.username_end as usize);
  638. self.serialization.push(':');
  639. self.serialization.extend(utf8_percent_encode(password, USERINFO_ENCODE_SET));
  640. self.serialization.push('@');
  641. let old_host_start = self.host_start;
  642. let new_host_start = to_u32(self.serialization.len()).unwrap();
  643. let adjust = |index: &mut u32| {
  644. *index -= old_host_start;
  645. *index += new_host_start;
  646. };
  647. self.host_start = new_host_start;
  648. adjust(&mut self.host_end);
  649. adjust(&mut self.path_start);
  650. if let Some(ref mut index) = self.query_start { adjust(index) }
  651. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  652. self.serialization.push_str(&host_and_after);
  653. } else if self.byte_at(self.username_end) == b':' { // If there is a password to remove
  654. let has_username_or_password = self.byte_at(self.host_start - 1) == b'@';
  655. debug_assert!(has_username_or_password);
  656. let username_start = self.scheme_end + 3;
  657. let empty_username = username_start == self.username_end;
  658. let start = self.username_end; // Remove the ':'
  659. let end = if empty_username {
  660. self.host_start // Remove the '@' as well
  661. } else {
  662. self.host_start - 1 // Keep the '@' to separate the username from the host
  663. };
  664. self.serialization.drain(start as usize .. end as usize);
  665. let offset = end - start;
  666. self.host_start -= offset;
  667. self.host_end -= offset;
  668. if let Some(ref mut index) = self.query_start { *index -= offset }
  669. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  670. }
  671. Ok(())
  672. }
  673. /// Change this URL’s username.
  674. ///
  675. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  676. pub fn set_username(&mut self, username: &str) -> Result<(), ()> {
  677. if !self.has_host() {
  678. return Err(())
  679. }
  680. let username_start = self.scheme_end + 3;
  681. if self.slice(username_start..self.username_end) == username {
  682. return Ok(())
  683. }
  684. let after_username = self.slice(self.username_end..).to_owned();
  685. self.serialization.truncate(username_start as usize);
  686. self.serialization.extend(utf8_percent_encode(username, USERINFO_ENCODE_SET));
  687. let old_username_end = self.username_end;
  688. let new_username_end = to_u32(self.serialization.len()).unwrap();
  689. let adjust = |index: &mut u32| {
  690. *index -= old_username_end;
  691. *index += new_username_end;
  692. };
  693. self.username_end = new_username_end;
  694. adjust(&mut self.host_start);
  695. adjust(&mut self.host_end);
  696. adjust(&mut self.path_start);
  697. if let Some(ref mut index) = self.query_start { adjust(index) }
  698. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  699. if !after_username.starts_with(|c| matches!(c, '@' | ':')) {
  700. self.serialization.push('@');
  701. }
  702. self.serialization.push_str(&after_username);
  703. Ok(())
  704. }
  705. /// Change this URL’s scheme.
  706. ///
  707. /// Do nothing and return `Err` if:
  708. /// * The new scheme is not in `[a-zA-Z][a-zA-Z0-9+.-]+`
  709. /// * This URL is cannot-be-a-base and the new scheme is one of
  710. /// `http`, `https`, `ws`, `wss`, `ftp`, or `gopher`
  711. pub fn set_scheme(&mut self, scheme: &str) -> Result<(), ()> {
  712. self.set_scheme_internal(scheme, false)
  713. }
  714. fn set_scheme_internal(&mut self, scheme: &str, allow_extra_input_after_colon: bool)
  715. -> Result<(), ()> {
  716. let mut parser = Parser::for_setter(String::new());
  717. let remaining = try!(parser.parse_scheme(scheme));
  718. if (!remaining.is_empty() && !allow_extra_input_after_colon) ||
  719. (!self.has_host() && SchemeType::from(&parser.serialization).is_special()) {
  720. return Err(())
  721. }
  722. let old_scheme_end = self.scheme_end;
  723. let new_scheme_end = to_u32(parser.serialization.len()).unwrap();
  724. let adjust = |index: &mut u32| {
  725. *index -= old_scheme_end;
  726. *index += new_scheme_end;
  727. };
  728. self.scheme_end = new_scheme_end;
  729. adjust(&mut self.username_end);
  730. adjust(&mut self.host_start);
  731. adjust(&mut self.host_end);
  732. adjust(&mut self.path_start);
  733. if let Some(ref mut index) = self.query_start { adjust(index) }
  734. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  735. parser.serialization.push_str(self.slice(old_scheme_end..));
  736. self.serialization = parser.serialization;
  737. Ok(())
  738. }
  739. /// Convert a file name as `std::path::Path` into an URL in the `file` scheme.
  740. ///
  741. /// This returns `Err` if the given path is not absolute or,
  742. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`).
  743. pub fn from_file_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  744. let mut serialization = "file://".to_owned();
  745. let path_start = serialization.len() as u32;
  746. try!(path_to_file_url_segments(path.as_ref(), &mut serialization));
  747. Ok(Url {
  748. serialization: serialization,
  749. scheme_end: "file".len() as u32,
  750. username_end: path_start,
  751. host_start: path_start,
  752. host_end: path_start,
  753. host: HostInternal::None,
  754. port: None,
  755. path_start: path_start,
  756. query_start: None,
  757. fragment_start: None,
  758. })
  759. }
  760. /// Convert a directory name as `std::path::Path` into an URL in the `file` scheme.
  761. ///
  762. /// This returns `Err` if the given path is not absolute or,
  763. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`).
  764. ///
  765. /// Compared to `from_file_path`, this ensure that URL’s the path has a trailing slash
  766. /// so that the entire path is considered when using this URL as a base URL.
  767. ///
  768. /// For example:
  769. ///
  770. /// * `"index.html"` parsed with `Url::from_directory_path(Path::new("/var/www"))`
  771. /// as the base URL is `file:///var/www/index.html`
  772. /// * `"index.html"` parsed with `Url::from_file_path(Path::new("/var/www"))`
  773. /// as the base URL is `file:///var/index.html`, which might not be what was intended.
  774. ///
  775. /// Note that `std::path` does not consider trailing slashes significant
  776. /// and usually does not include them (e.g. in `Path::parent()`).
  777. pub fn from_directory_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  778. let mut url = try!(Url::from_file_path(path));
  779. if !url.serialization.ends_with('/') {
  780. url.serialization.push('/')
  781. }
  782. Ok(url)
  783. }
  784. /// Assuming the URL is in the `file` scheme or similar,
  785. /// convert its path to an absolute `std::path::Path`.
  786. ///
  787. /// **Note:** This does not actually check the URL’s `scheme`,
  788. /// and may give nonsensical results for other schemes.
  789. /// It is the user’s responsibility to check the URL’s scheme before calling this.
  790. ///
  791. /// ```
  792. /// # use url::Url;
  793. /// # let url = Url::parse("file:///etc/passwd").unwrap();
  794. /// let path = url.to_file_path();
  795. /// ```
  796. ///
  797. /// Returns `Err` if the host is neither empty nor `"localhost"`,
  798. /// or if `Path::new_opt()` returns `None`.
  799. /// (That is, if the percent-decoded path contains a NUL byte or,
  800. /// for a Windows path, is not UTF-8.)
  801. #[inline]
  802. pub fn to_file_path(&self) -> Result<PathBuf, ()> {
  803. // FIXME: Figure out what to do w.r.t host.
  804. if matches!(self.host(), None | Some(Host::Domain("localhost"))) {
  805. if let Some(segments) = self.path_segments() {
  806. return file_url_segments_to_pathbuf(segments)
  807. }
  808. }
  809. Err(())
  810. }
  811. /// Parse the URL’s query string, if any, as `application/x-www-form-urlencoded`
  812. /// and return a vector of (key, value) pairs.
  813. #[inline]
  814. pub fn query_pairs(&self) -> Option<Vec<(String, String)>> {
  815. self.query().map(|query| form_urlencoded::parse(query.as_bytes()))
  816. }
  817. // Private helper methods:
  818. #[inline]
  819. fn slice<R>(&self, range: R) -> &str where R: RangeArg {
  820. range.slice_of(&self.serialization)
  821. }
  822. #[inline]
  823. fn byte_at(&self, i: u32) -> u8 {
  824. self.serialization.as_bytes()[i as usize]
  825. }
  826. }
  827. /// Return an error if `Url::host` or `Url::port_or_known_default` return `None`.
  828. impl ToSocketAddrs for Url {
  829. type Iter = SocketAddrs;
  830. fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
  831. try!(self.with_default_port(|_| Err(()))).to_socket_addrs()
  832. }
  833. }
  834. /// Parse a string as an URL, without a base URL or encoding override.
  835. impl str::FromStr for Url {
  836. type Err = ParseError;
  837. #[inline]
  838. fn from_str(input: &str) -> Result<Url, ::ParseError> {
  839. Url::parse(input)
  840. }
  841. }
  842. /// Display the serialization of this URL.
  843. impl fmt::Display for Url {
  844. #[inline]
  845. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  846. fmt::Display::fmt(&self.serialization, formatter)
  847. }
  848. }
  849. /// Debug the serialization of this URL.
  850. impl fmt::Debug for Url {
  851. #[inline]
  852. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  853. fmt::Debug::fmt(&self.serialization, formatter)
  854. }
  855. }
  856. /// URLs compare like their serialization.
  857. impl Eq for Url {}
  858. /// URLs compare like their serialization.
  859. impl PartialEq for Url {
  860. #[inline]
  861. fn eq(&self, other: &Self) -> bool {
  862. self.serialization == other.serialization
  863. }
  864. }
  865. /// URLs compare like their serialization.
  866. impl Ord for Url {
  867. #[inline]
  868. fn cmp(&self, other: &Self) -> cmp::Ordering {
  869. self.serialization.cmp(&other.serialization)
  870. }
  871. }
  872. /// URLs compare like their serialization.
  873. impl PartialOrd for Url {
  874. #[inline]
  875. fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
  876. self.serialization.partial_cmp(&other.serialization)
  877. }
  878. }
  879. /// URLs hash like their serialization.
  880. impl hash::Hash for Url {
  881. #[inline]
  882. fn hash<H>(&self, state: &mut H) where H: hash::Hasher {
  883. hash::Hash::hash(&self.serialization, state)
  884. }
  885. }
  886. /// Return the serialization of this URL.
  887. impl AsRef<str> for Url {
  888. #[inline]
  889. fn as_ref(&self) -> &str {
  890. &self.serialization
  891. }
  892. }
  893. trait RangeArg {
  894. fn slice_of<'a>(&self, s: &'a str) -> &'a str;
  895. }
  896. impl RangeArg for Range<u32> {
  897. #[inline]
  898. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  899. &s[self.start as usize .. self.end as usize]
  900. }
  901. }
  902. impl RangeArg for RangeFrom<u32> {
  903. #[inline]
  904. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  905. &s[self.start as usize ..]
  906. }
  907. }
  908. impl RangeArg for RangeTo<u32> {
  909. #[inline]
  910. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  911. &s[.. self.end as usize]
  912. }
  913. }
  914. #[cfg(feature="rustc-serialize")]
  915. impl rustc_serialize::Encodable for Url {
  916. fn encode<S: rustc_serialize::Encoder>(&self, encoder: &mut S) -> Result<(), S::Error> {
  917. encoder.emit_str(self.as_str())
  918. }
  919. }
  920. #[cfg(feature="rustc-serialize")]
  921. impl rustc_serialize::Decodable for Url {
  922. fn decode<D: rustc_serialize::Decoder>(decoder: &mut D) -> Result<Url, D::Error> {
  923. Url::parse(&*try!(decoder.read_str())).map_err(|error| {
  924. decoder.error(&format!("URL parsing error: {}", error))
  925. })
  926. }
  927. }
  928. /// Serializes this URL into a `serde` stream.
  929. ///
  930. /// This implementation is only available if the `serde` Cargo feature is enabled.
  931. #[cfg(feature="serde")]
  932. impl serde::Serialize for Url {
  933. fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::Serializer {
  934. format!("{}", self).serialize(serializer)
  935. }
  936. }
  937. /// Deserializes this URL from a `serde` stream.
  938. ///
  939. /// This implementation is only available if the `serde` Cargo feature is enabled.
  940. #[cfg(feature="serde")]
  941. impl serde::Deserialize for Url {
  942. fn deserialize<D>(deserializer: &mut D) -> Result<Url, D::Error> where D: serde::Deserializer {
  943. let string_representation: String = try!(serde::Deserialize::deserialize(deserializer));
  944. Ok(Url::parse(&string_representation).unwrap())
  945. }
  946. }
  947. #[cfg(unix)]
  948. fn path_to_file_url_segments(path: &Path, serialization: &mut String) -> Result<(), ()> {
  949. use std::os::unix::prelude::OsStrExt;
  950. if !path.is_absolute() {
  951. return Err(())
  952. }
  953. // skip the root component
  954. for component in path.components().skip(1) {
  955. serialization.push('/');
  956. serialization.extend(percent_encode(
  957. component.as_os_str().as_bytes(), PATH_SEGMENT_ENCODE_SET))
  958. }
  959. Ok(())
  960. }
  961. #[cfg(windows)]
  962. fn path_to_file_url_segments(path: &Path, serialization: &mut String) -> Result<(), ()> {
  963. path_to_file_url_segments_windows(path, serialization)
  964. }
  965. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  966. #[cfg_attr(not(windows), allow(dead_code))]
  967. fn path_to_file_url_segments_windows(path: &Path, serialization: &mut String) -> Result<(), ()> {
  968. use std::path::{Prefix, Component};
  969. if !path.is_absolute() {
  970. return Err(())
  971. }
  972. let mut components = path.components();
  973. let disk = match components.next() {
  974. Some(Component::Prefix(ref p)) => match p.kind() {
  975. Prefix::Disk(byte) => byte,
  976. Prefix::VerbatimDisk(byte) => byte,
  977. _ => return Err(()),
  978. },
  979. // FIXME: do something with UNC and other prefixes?
  980. _ => return Err(())
  981. };
  982. // Start with the prefix, e.g. "C:"
  983. serialization.push('/');
  984. serialization.push(disk as char);
  985. serialization.push(':');
  986. for component in components {
  987. if component == Component::RootDir { continue }
  988. // FIXME: somehow work with non-unicode?
  989. let component = try!(component.as_os_str().to_str().ok_or(()));
  990. serialization.push('/');
  991. serialization.extend(percent_encode(component.as_bytes(), PATH_SEGMENT_ENCODE_SET));
  992. }
  993. Ok(())
  994. }
  995. #[cfg(unix)]
  996. fn file_url_segments_to_pathbuf(segments: str::Split<char>) -> Result<PathBuf, ()> {
  997. use std::ffi::OsStr;
  998. use std::os::unix::prelude::OsStrExt;
  999. use std::path::PathBuf;
  1000. let mut bytes = Vec::new();
  1001. for segment in segments {
  1002. bytes.push(b'/');
  1003. bytes.extend(percent_decode(segment.as_bytes()));
  1004. }
  1005. let os_str = OsStr::from_bytes(&bytes);
  1006. let path = PathBuf::from(os_str);
  1007. debug_assert!(path.is_absolute(),
  1008. "to_file_path() failed to produce an absolute Path");
  1009. Ok(path)
  1010. }
  1011. #[cfg(windows)]
  1012. fn file_url_segments_to_pathbuf(segments: str::Split<char>) -> Result<PathBuf, ()> {
  1013. file_url_segments_to_pathbuf_windows(segments)
  1014. }
  1015. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  1016. #[cfg_attr(not(windows), allow(dead_code))]
  1017. fn file_url_segments_to_pathbuf_windows(mut segments: str::Split<char>) -> Result<PathBuf, ()> {
  1018. let first = try!(segments.next().ok_or(()));
  1019. if first.len() != 2 || !first.starts_with(parser::ascii_alpha)
  1020. || first.as_bytes()[1] != b':' {
  1021. return Err(())
  1022. }
  1023. let mut string = first.to_owned();
  1024. for segment in segments {
  1025. string.push('\\');
  1026. // Currently non-unicode windows paths cannot be represented
  1027. match String::from_utf8(percent_decode(segment.as_bytes()).collect()) {
  1028. Ok(s) => string.push_str(&s),
  1029. Err(..) => return Err(()),
  1030. }
  1031. }
  1032. let path = PathBuf::from(string);
  1033. debug_assert!(path.is_absolute(),
  1034. "to_file_path() failed to produce an absolute Path");
  1035. Ok(path)
  1036. }
  1037. fn io_error<T>(reason: &str) -> io::Result<T> {
  1038. Err(io::Error::new(io::ErrorKind::InvalidData, reason))
  1039. }