lib.rs 41 KB

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