lib.rs 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. // Copyright 2013-2014 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, SchemeData};
  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".to_string());
  43. assert!(issue_list_url.domain() == Some("github.com"));
  44. assert!(issue_list_url.port() == None);
  45. assert!(issue_list_url.path() == Some(["rust-lang".to_string(),
  46. "rust".to_string(),
  47. "issues".to_string()].as_slice()));
  48. assert!(issue_list_url.query == Some("labels=E-easy&state=open".to_string()));
  49. assert!(issue_list_url.fragment == None);
  50. match issue_list_url.scheme_data {
  51. SchemeData::Relative(..) => {}, // Expected
  52. SchemeData::NonRelative(..) => panic!(),
  53. }
  54. ```
  55. The `scheme`, `query`, and `fragment` are directly fields of the `Url` struct:
  56. they apply to all URLs.
  57. Every other components has accessors because they only apply to URLs said to be
  58. “in a relative scheme”. `https` is a relative scheme, but `data` is not:
  59. ```
  60. use url::{Url, SchemeData};
  61. let data_url = Url::parse("data:text/plain,Hello#").unwrap();
  62. assert!(data_url.scheme == "data".to_string());
  63. assert!(data_url.scheme_data == SchemeData::NonRelative("text/plain,Hello".to_string()));
  64. assert!(data_url.non_relative_scheme_data() == Some("text/plain,Hello"));
  65. assert!(data_url.query == None);
  66. assert!(data_url.fragment == Some("".to_string()));
  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:
  74. ```
  75. use url::{Url, ParseError};
  76. assert!(Url::parse("../main.css") == Err(ParseError::RelativeUrlWithoutBase))
  77. ```
  78. `UrlParser` is a method-chaining API to provide various optional parameters
  79. to URL parsing, including a base URL.
  80. ```
  81. use url::{Url, UrlParser};
  82. let this_document = Url::parse("http://servo.github.io/rust-url/url/index.html").unwrap();
  83. let css_url = UrlParser::new().base_url(&this_document).parse("../main.css").unwrap();
  84. assert!(css_url.serialize() == "http://servo.github.io/rust-url/main.css".to_string());
  85. ```
  86. */
  87. #![feature(macro_rules, default_type_params)]
  88. extern crate "rustc-serialize" as rustc_serialize;
  89. use std::fmt::{mod, Formatter, Show};
  90. use std::hash;
  91. use std::path;
  92. pub use host::{Host, Ipv6Address};
  93. pub use parser::{ErrorHandler, ParseResult, ParseError};
  94. #[deprecated = "Moved to the `percent_encoding` module"]
  95. pub use percent_encoding::{
  96. percent_decode, percent_decode_to, percent_encode, percent_encode_to,
  97. utf8_percent_encode, utf8_percent_encode_to, lossy_utf8_percent_decode,
  98. SIMPLE_ENCODE_SET, QUERY_ENCODE_SET, DEFAULT_ENCODE_SET, USERINFO_ENCODE_SET,
  99. PASSWORD_ENCODE_SET, USERNAME_ENCODE_SET, FORM_URLENCODED_ENCODE_SET, EncodeSet,
  100. };
  101. use format::{PathFormatter, UserInfoFormatter, UrlNoFragmentFormatter};
  102. use encoding::EncodingOverride;
  103. mod encoding;
  104. mod host;
  105. mod parser;
  106. mod urlutils;
  107. pub mod percent_encoding;
  108. pub mod form_urlencoded;
  109. pub mod punycode;
  110. pub mod format;
  111. #[cfg(test)]
  112. mod tests;
  113. /// The parsed representation of an absolute URL.
  114. #[deriving(PartialEq, Eq, Clone)]
  115. pub struct Url {
  116. /// The scheme (a.k.a. protocol) of the URL, in ASCII lower case.
  117. pub scheme: String,
  118. /// The components of the URL whose representation depends on where the scheme is *relative*.
  119. pub scheme_data: SchemeData,
  120. /// The query string of the URL.
  121. ///
  122. /// `None` if the `?` delimiter character was not part of the parsed input,
  123. /// otherwise a possibly empty, pecent-encoded string.
  124. ///
  125. /// Percent encoded strings are within the ASCII range.
  126. ///
  127. /// See also the `query_pairs`, `set_query_from_pairs`,
  128. /// and `lossy_percent_decode_query` methods.
  129. pub query: Option<String>,
  130. /// The fragment identifier of the URL.
  131. ///
  132. /// `None` if the `#` delimiter character was not part of the parsed input,
  133. /// otherwise a possibly empty, pecent-encoded string.
  134. ///
  135. /// Percent encoded strings are within the ASCII range.
  136. ///
  137. /// See also the `lossy_percent_decode_fragment` method.
  138. pub fragment: Option<String>,
  139. }
  140. /// The components of the URL whose representation depends on where the scheme is *relative*.
  141. #[deriving(PartialEq, Eq, Clone)]
  142. pub enum SchemeData {
  143. /// Components for URLs in a *relative* scheme such as HTTP.
  144. Relative(RelativeSchemeData),
  145. /// No further structure is assumed for *non-relative* schemes such as `data` and `mailto`.
  146. ///
  147. /// This is a single percent-encoded string, whose interpretation depends on the scheme.
  148. ///
  149. /// Percent encoded strings are within the ASCII range.
  150. NonRelative(String),
  151. }
  152. /// Components for URLs in a *relative* scheme such as HTTP.
  153. #[deriving(PartialEq, Eq, Clone)]
  154. pub struct RelativeSchemeData {
  155. /// The username of the URL, as a possibly empty, pecent-encoded string.
  156. ///
  157. /// Percent encoded strings are within the ASCII range.
  158. ///
  159. /// See also the `lossy_percent_decode_username` method.
  160. pub username: String,
  161. /// The password of the URL.
  162. ///
  163. /// `None` if the `:` delimiter character was not part of the parsed input,
  164. /// otherwise a possibly empty, pecent-encoded string.
  165. ///
  166. /// Percent encoded strings are within the ASCII range.
  167. ///
  168. /// See also the `lossy_percent_decode_password` method.
  169. pub password: Option<String>,
  170. /// The host of the URL, either a domain name or an IPv4 address
  171. pub host: Host,
  172. /// The port number of the URL.
  173. /// `None` for file-like schemes, or to indicate the default port number.
  174. pub port: Option<u16>,
  175. /// The default port number for the URL’s scheme.
  176. /// `None` for file-like schemes.
  177. pub default_port: Option<u16>,
  178. /// The path of the URL, as vector of pecent-encoded strings.
  179. ///
  180. /// Percent encoded strings are within the ASCII range.
  181. ///
  182. /// See also the `serialize_path` method and,
  183. /// for URLs in the `file` scheme, the `to_file_path` method.
  184. pub path: Vec<String>,
  185. }
  186. impl<S: hash::Writer> hash::Hash<S> for Url {
  187. fn hash(&self, state: &mut S) {
  188. self.serialize().hash(state)
  189. }
  190. }
  191. /// A set of optional parameters for URL parsing.
  192. pub struct UrlParser<'a> {
  193. base_url: Option<&'a Url>,
  194. query_encoding_override: EncodingOverride,
  195. error_handler: ErrorHandler,
  196. scheme_type_mapper: fn(scheme: &str) -> SchemeType,
  197. }
  198. /// A method-chaining API to provide a set of optional parameters for URL parsing.
  199. impl<'a> UrlParser<'a> {
  200. /// Return a new UrlParser with default parameters.
  201. #[inline]
  202. pub fn new() -> UrlParser<'a> {
  203. fn silent_handler(_reason: ParseError) -> ParseResult<()> { Ok(()) }
  204. UrlParser {
  205. base_url: None,
  206. query_encoding_override: EncodingOverride::utf8(),
  207. error_handler: silent_handler,
  208. scheme_type_mapper: whatwg_scheme_type_mapper,
  209. }
  210. }
  211. /// Set the base URL used for resolving relative URL references, and return the `UrlParser`.
  212. /// The default is no base URL, so that relative URLs references fail to parse.
  213. #[inline]
  214. pub fn base_url<'b>(&'b mut self, value: &'a Url) -> &'b mut UrlParser<'a> {
  215. self.base_url = Some(value);
  216. self
  217. }
  218. /// Set the character encoding the query string is encoded as before percent-encoding,
  219. /// and return the `UrlParser`.
  220. ///
  221. /// This legacy quirk is only relevant to HTML.
  222. ///
  223. /// This method is only available if the `query_encoding` Cargo feature is enabled.
  224. #[cfg(feature = "query_encoding")]
  225. #[inline]
  226. pub fn query_encoding_override<'b>(&'b mut self, value: encoding::EncodingRef)
  227. -> &'b mut UrlParser<'a> {
  228. self.query_encoding_override = EncodingOverride::from_encoding(value);
  229. self
  230. }
  231. /// Set an error handler for non-fatal parse errors, and return the `UrlParser`.
  232. ///
  233. /// Non-fatal parse errors are normally ignored by the parser,
  234. /// but indicate violations of authoring requirements.
  235. /// An error handler can be used, for example, to log these errors in the console
  236. /// of a browser’s developer tools.
  237. ///
  238. /// The error handler can choose to make the error fatal by returning `Err(..)`
  239. #[inline]
  240. pub fn error_handler<'b>(&'b mut self, value: ErrorHandler) -> &'b mut UrlParser<'a> {
  241. self.error_handler = value;
  242. self
  243. }
  244. /// Set a *scheme type mapper*, and return the `UrlParser`.
  245. ///
  246. /// The URL parser behaves differently based on the `SchemeType` of the URL.
  247. /// See the documentation for `SchemeType` for more details.
  248. /// A *scheme type mapper* returns a `SchemeType`
  249. /// based on the scheme as an ASCII lower case string,
  250. /// as found in the `scheme` field of an `Url` struct.
  251. ///
  252. /// The default scheme type mapper is as follows:
  253. ///
  254. /// ```ignore
  255. /// fn whatwg_scheme_type_mapper(scheme: &str) -> SchemeType {
  256. /// match scheme {
  257. /// "file" => SchemeType::FileLike,
  258. /// "ftp" => SchemeType::Relative(21),
  259. /// "gopher" => SchemeType::Relative(70),
  260. /// "http" => SchemeType::Relative(80),
  261. /// "https" => SchemeType::Relative(443),
  262. /// "ws" => SchemeType::Relative(80),
  263. /// "wss" => SchemeType::Relative(443),
  264. /// _ => NonRelative,
  265. /// }
  266. /// }
  267. /// ```
  268. ///
  269. /// Note that unknown schemes default to non-relative.
  270. /// Overriding the scheme type mapper can allow, for example,
  271. /// parsing URLs in the `git` or `irc` scheme as relative.
  272. #[inline]
  273. pub fn scheme_type_mapper<'b>(&'b mut self, value: fn(scheme: &str) -> SchemeType)
  274. -> &'b mut UrlParser<'a> {
  275. self.scheme_type_mapper = value;
  276. self
  277. }
  278. /// Parse `input` as an URL, with all the parameters previously set in the `UrlParser`.
  279. #[inline]
  280. pub fn parse(&self, input: &str) -> ParseResult<Url> {
  281. parser::parse_url(input, self)
  282. }
  283. /// Parse `input` as a “standalone” URL path,
  284. /// with an optional query string and fragment identifier.
  285. ///
  286. /// This is typically found in the start line of an HTTP header.
  287. ///
  288. /// Note that while the start line has no fragment identifier in the HTTP RFC,
  289. /// servers typically parse it and ignore it
  290. /// (rather than having it be part of the path or query string.)
  291. ///
  292. /// On success, return `(path, query_string, fragment_identifier)`
  293. #[inline]
  294. pub fn parse_path(&self, input: &str)
  295. -> ParseResult<(Vec<String>, Option<String>, Option<String>)> {
  296. parser::parse_standalone_path(input, self)
  297. }
  298. }
  299. /// Parse `input` as a “standalone” URL path,
  300. /// with an optional query string and fragment identifier.
  301. ///
  302. /// This is typically found in the start line of an HTTP header.
  303. ///
  304. /// Note that while the start line has no fragment identifier in the HTTP RFC,
  305. /// servers typically parse it and ignore it
  306. /// (rather than having it be part of the path or query string.)
  307. ///
  308. /// On success, return `(path, query_string, fragment_identifier)`
  309. ///
  310. /// ```rust
  311. /// let (path, query, fragment) = url::parse_path("/foo/bar/../baz?q=42").unwrap();
  312. /// assert_eq!(path, vec!["foo".to_string(), "baz".to_string()]);
  313. /// assert_eq!(query, Some("q=42".to_string()));
  314. /// assert_eq!(fragment, None);
  315. /// ```
  316. #[inline]
  317. pub fn parse_path(input: &str)
  318. -> ParseResult<(Vec<String>, Option<String>, Option<String>)> {
  319. UrlParser::new().parse_path(input)
  320. }
  321. /// Private convenience methods for use in parser.rs
  322. impl<'a> UrlParser<'a> {
  323. #[inline]
  324. fn parse_error(&self, error: ParseError) -> ParseResult<()> {
  325. (self.error_handler)(error)
  326. }
  327. #[inline]
  328. fn get_scheme_type(&self, scheme: &str) -> SchemeType {
  329. (self.scheme_type_mapper)(scheme)
  330. }
  331. }
  332. /// Determines the behavior of the URL parser for a given scheme.
  333. #[deriving(PartialEq, Eq, Copy)]
  334. pub enum SchemeType {
  335. /// Indicate that the scheme is *non-relative*.
  336. ///
  337. /// The *scheme data* of the URL
  338. /// (everything other than the scheme, query string, and fragment identifier)
  339. /// is parsed as a single percent-encoded string of which no structure is assumed.
  340. /// That string may need to be parsed further, per a scheme-specific format.
  341. NonRelative,
  342. /// Indicate that the scheme is *relative*, and what the default port number is.
  343. ///
  344. /// The *scheme data* is structured as
  345. /// *username*, *password*, *host*, *port number*, and *path*.
  346. /// Relative URL references are supported, if a base URL was given.
  347. /// The string value indicates the default port number as a string of ASCII digits,
  348. /// or the empty string to indicate no default port number.
  349. Relative(u16),
  350. /// Indicate a *relative* scheme similar to the *file* scheme.
  351. ///
  352. /// For example, you might want to have distinct `git+file` and `hg+file` URL schemes.
  353. ///
  354. /// This is like `Relative` except the host can be empty, there is no port number,
  355. /// and path parsing has (platform-independent) quirks to support Windows filenames.
  356. FileLike,
  357. }
  358. impl SchemeType {
  359. pub fn default_port(&self) -> Option<u16> {
  360. match self {
  361. &SchemeType::Relative(default_port) => Some(default_port),
  362. _ => None,
  363. }
  364. }
  365. }
  366. /// http://url.spec.whatwg.org/#relative-scheme
  367. pub fn whatwg_scheme_type_mapper(scheme: &str) -> SchemeType {
  368. match scheme {
  369. "file" => SchemeType::FileLike,
  370. "ftp" => SchemeType::Relative(21),
  371. "gopher" => SchemeType::Relative(70),
  372. "http" => SchemeType::Relative(80),
  373. "https" => SchemeType::Relative(443),
  374. "ws" => SchemeType::Relative(80),
  375. "wss" => SchemeType::Relative(443),
  376. _ => SchemeType::NonRelative,
  377. }
  378. }
  379. impl Url {
  380. /// Parse an URL with the default `UrlParser` parameters.
  381. ///
  382. /// In particular, relative URL references are parse errors since no base URL is provided.
  383. #[inline]
  384. pub fn parse(input: &str) -> ParseResult<Url> {
  385. UrlParser::new().parse(input)
  386. }
  387. /// Convert a file name as `std::path::Path` into an URL in the `file` scheme.
  388. ///
  389. /// This returns `Err` if the given path is not absolute
  390. /// or, with a Windows path, if the prefix is not a disk prefix (e.g. `C:`).
  391. pub fn from_file_path<T: ToUrlPath>(path: &T) -> Result<Url, ()> {
  392. let path = try!(path.to_url_path());
  393. Ok(Url::from_path_common(path))
  394. }
  395. /// Convert a directory name as `std::path::Path` into an URL in the `file` scheme.
  396. ///
  397. /// This returns `Err` if the given path is not absolute
  398. /// or, with a Windows path, if the prefix is not a disk prefix (e.g. `C:`).
  399. ///
  400. /// Compared to `from_file_path`, this adds an empty component to the path
  401. /// (or, in terms of URL syntax, adds a trailing slash)
  402. /// so that the entire path is considered when using this URL as a base URL.
  403. ///
  404. /// For example:
  405. ///
  406. /// * `"index.html"` parsed with `Url::from_directory_path(Path::new("/var/www"))`
  407. /// as the base URL is `file:///var/www/index.html`
  408. /// * `"index.html"` parsed with `Url::from_file_path(Path::new("/var/www/"))`
  409. /// as the base URL is `file:///var/index.html`, which might not be what was intended.
  410. ///
  411. /// (Note that `Path::new` removes any trailing slash.)
  412. pub fn from_directory_path<T: ToUrlPath>(path: &T) -> Result<Url, ()> {
  413. let mut path = try!(path.to_url_path());
  414. // Add an empty path component (i.e. a trailing slash in serialization)
  415. // so that the entire path is used as a base URL.
  416. path.push("".to_string());
  417. Ok(Url::from_path_common(path))
  418. }
  419. fn from_path_common(path: Vec<String>) -> Url {
  420. Url {
  421. scheme: "file".to_string(),
  422. scheme_data: SchemeData::Relative(RelativeSchemeData {
  423. username: "".to_string(),
  424. password: None,
  425. port: None,
  426. default_port: None,
  427. host: Host::Domain("".to_string()),
  428. path: path,
  429. }),
  430. query: None,
  431. fragment: None,
  432. }
  433. }
  434. /// Assuming the URL is in the `file` scheme or similar,
  435. /// convert its path to an absolute `std::path::Path`.
  436. ///
  437. /// **Note:** This does not actually check the URL’s `scheme`,
  438. /// and may give nonsensical results for other schemes.
  439. /// It is the user’s responsibility to check the URL’s scheme before calling this.
  440. ///
  441. /// The return type (when `Ok()`) is generic and can be either `std::path::posix::Path`
  442. /// or `std::path::windows::Path`.
  443. /// (Use `std::path::Path` to pick one of them depending on the local system.)
  444. /// If the compiler can not infer the desired type from context, you may have to specifiy it:
  445. ///
  446. /// ```ignore
  447. /// let path = url.to_file_path::<std::path::posix::Path>();
  448. /// ```
  449. ///
  450. /// Returns `Err` if the host is neither empty nor `"localhost"`,
  451. /// or if `Path::new_opt()` returns `None`.
  452. /// (That is, if the percent-decoded path contains a NUL byte or,
  453. /// for a Windows path, is not UTF-8.)
  454. #[inline]
  455. pub fn to_file_path<T: FromUrlPath>(&self) -> Result<T, ()> {
  456. match self.scheme_data {
  457. SchemeData::Relative(ref scheme_data) => scheme_data.to_file_path(),
  458. SchemeData::NonRelative(..) => Err(()),
  459. }
  460. }
  461. /// Return the serialization of this URL as a string.
  462. pub fn serialize(&self) -> String {
  463. self.to_string()
  464. }
  465. /// Return the serialization of this URL, without the fragment identifier, as a string
  466. pub fn serialize_no_fragment(&self) -> String {
  467. UrlNoFragmentFormatter{ url: self }.to_string()
  468. }
  469. /// If the URL is *non-relative*, return the string scheme data.
  470. #[inline]
  471. pub fn non_relative_scheme_data<'a>(&'a self) -> Option<&'a str> {
  472. match self.scheme_data {
  473. SchemeData::Relative(..) => None,
  474. SchemeData::NonRelative(ref scheme_data) => Some(scheme_data.as_slice()),
  475. }
  476. }
  477. /// If the URL is *non-relative*, return a mutable reference to the string scheme data.
  478. #[inline]
  479. pub fn non_relative_scheme_data_mut<'a>(&'a mut self) -> Option<&'a mut String> {
  480. match self.scheme_data {
  481. SchemeData::Relative(..) => None,
  482. SchemeData::NonRelative(ref mut scheme_data) => Some(scheme_data),
  483. }
  484. }
  485. /// If the URL is in a *relative scheme*, return the structured scheme data.
  486. #[inline]
  487. pub fn relative_scheme_data<'a>(&'a self) -> Option<&'a RelativeSchemeData> {
  488. match self.scheme_data {
  489. SchemeData::Relative(ref scheme_data) => Some(scheme_data),
  490. SchemeData::NonRelative(..) => None,
  491. }
  492. }
  493. /// If the URL is in a *relative scheme*,
  494. /// return a mutable reference to the structured scheme data.
  495. #[inline]
  496. pub fn relative_scheme_data_mut<'a>(&'a mut self) -> Option<&'a mut RelativeSchemeData> {
  497. match self.scheme_data {
  498. SchemeData::Relative(ref mut scheme_data) => Some(scheme_data),
  499. SchemeData::NonRelative(..) => None,
  500. }
  501. }
  502. /// If the URL is in a *relative scheme*, return its username.
  503. #[inline]
  504. pub fn username<'a>(&'a self) -> Option<&'a str> {
  505. self.relative_scheme_data().map(|scheme_data| scheme_data.username.as_slice())
  506. }
  507. /// If the URL is in a *relative scheme*, return a mutable reference to its username.
  508. #[inline]
  509. pub fn username_mut<'a>(&'a mut self) -> Option<&'a mut String> {
  510. self.relative_scheme_data_mut().map(|scheme_data| &mut scheme_data.username)
  511. }
  512. /// Percent-decode the URL’s username, if any.
  513. ///
  514. /// This is “lossy”: invalid UTF-8 percent-encoded byte sequences
  515. /// will be replaced � U+FFFD, the replacement character.
  516. #[inline]
  517. pub fn lossy_percent_decode_username(&self) -> Option<String> {
  518. self.relative_scheme_data().map(|scheme_data| scheme_data.lossy_percent_decode_username())
  519. }
  520. /// If the URL is in a *relative scheme*, return its password, if any.
  521. #[inline]
  522. pub fn password<'a>(&'a self) -> Option<&'a str> {
  523. self.relative_scheme_data().and_then(|scheme_data|
  524. scheme_data.password.as_ref().map(|password| password.as_slice()))
  525. }
  526. /// If the URL is in a *relative scheme*, return a mutable reference to its password, if any.
  527. #[inline]
  528. pub fn password_mut<'a>(&'a mut self) -> Option<&'a mut String> {
  529. self.relative_scheme_data_mut().and_then(|scheme_data| scheme_data.password.as_mut())
  530. }
  531. /// Percent-decode the URL’s password, if any.
  532. ///
  533. /// This is “lossy”: invalid UTF-8 percent-encoded byte sequences
  534. /// will be replaced � U+FFFD, the replacement character.
  535. #[inline]
  536. pub fn lossy_percent_decode_password(&self) -> Option<String> {
  537. self.relative_scheme_data().and_then(|scheme_data|
  538. scheme_data.lossy_percent_decode_password())
  539. }
  540. /// Serialize the URL's username and password, if any.
  541. ///
  542. /// Format: "<username>:<password>@"
  543. #[inline]
  544. pub fn serialize_userinfo<'a>(&'a mut self) -> Option<String> {
  545. self.relative_scheme_data().map(|scheme_data| scheme_data.serialize_userinfo())
  546. }
  547. /// If the URL is in a *relative scheme*, return its structured host.
  548. #[inline]
  549. pub fn host<'a>(&'a self) -> Option<&'a Host> {
  550. self.relative_scheme_data().map(|scheme_data| &scheme_data.host)
  551. }
  552. /// If the URL is in a *relative scheme*, return a mutable reference to its structured host.
  553. #[inline]
  554. pub fn host_mut<'a>(&'a mut self) -> Option<&'a mut Host> {
  555. self.relative_scheme_data_mut().map(|scheme_data| &mut scheme_data.host)
  556. }
  557. /// If the URL is in a *relative scheme* and its host is a domain,
  558. /// return the domain as a string.
  559. #[inline]
  560. pub fn domain<'a>(&'a self) -> Option<&'a str> {
  561. self.relative_scheme_data().and_then(|scheme_data| scheme_data.domain())
  562. }
  563. /// If the URL is in a *relative scheme* and its host is a domain,
  564. /// return a mutable reference to the domain string.
  565. #[inline]
  566. pub fn domain_mut<'a>(&'a mut self) -> Option<&'a mut String> {
  567. self.relative_scheme_data_mut().and_then(|scheme_data| scheme_data.domain_mut())
  568. }
  569. /// If the URL is in a *relative scheme*, serialize its host as a string.
  570. ///
  571. /// A domain a returned as-is, an IPv6 address between [] square brackets.
  572. #[inline]
  573. pub fn serialize_host(&self) -> Option<String> {
  574. self.relative_scheme_data().map(|scheme_data| scheme_data.host.serialize())
  575. }
  576. /// If the URL is in a *relative scheme* and has a port number, return it.
  577. #[inline]
  578. pub fn port<'a>(&'a self) -> Option<u16> {
  579. self.relative_scheme_data().and_then(|scheme_data| scheme_data.port)
  580. }
  581. /// If the URL is in a *relative scheme*, return a mutable reference to its port.
  582. #[inline]
  583. pub fn port_mut<'a>(&'a mut self) -> Option<&'a mut Option<u16>> {
  584. self.relative_scheme_data_mut().map(|scheme_data| &mut scheme_data.port)
  585. }
  586. /// If the URL is in a *relative scheme* that is not a file-like,
  587. /// return its port number, even if it is the default.
  588. #[inline]
  589. pub fn port_or_default(&self) -> Option<u16> {
  590. self.relative_scheme_data().and_then(|scheme_data| scheme_data.port_or_default())
  591. }
  592. /// If the URL is in a *relative scheme*, return its path components.
  593. #[inline]
  594. pub fn path<'a>(&'a self) -> Option<&'a [String]> {
  595. self.relative_scheme_data().map(|scheme_data| scheme_data.path.as_slice())
  596. }
  597. /// If the URL is in a *relative scheme*, return a mutable reference to its path components.
  598. #[inline]
  599. pub fn path_mut<'a>(&'a mut self) -> Option<&'a mut Vec<String>> {
  600. self.relative_scheme_data_mut().map(|scheme_data| &mut scheme_data.path)
  601. }
  602. /// If the URL is in a *relative scheme*, serialize its path as a string.
  603. ///
  604. /// The returned string starts with a "/" slash, and components are separated by slashes.
  605. /// A trailing slash represents an empty last component.
  606. #[inline]
  607. pub fn serialize_path(&self) -> Option<String> {
  608. self.relative_scheme_data().map(|scheme_data| scheme_data.serialize_path())
  609. }
  610. /// Parse the URL’s query string, if any, as `application/x-www-form-urlencoded`
  611. /// and return a vector of (key, value) pairs.
  612. #[inline]
  613. pub fn query_pairs(&self) -> Option<Vec<(String, String)>> {
  614. self.query.as_ref().map(|query| form_urlencoded::parse(query.as_bytes()))
  615. }
  616. /// Serialize an iterator of (key, value) pairs as `application/x-www-form-urlencoded`
  617. /// and set it as the URL’s query string.
  618. #[inline]
  619. pub fn set_query_from_pairs<'a, I: Iterator<(&'a str, &'a str)>>(&mut self, pairs: I) {
  620. self.query = Some(form_urlencoded::serialize(pairs));
  621. }
  622. /// Percent-decode the URL’s query string, if any.
  623. ///
  624. /// This is “lossy”: invalid UTF-8 percent-encoded byte sequences
  625. /// will be replaced � U+FFFD, the replacement character.
  626. #[inline]
  627. pub fn lossy_percent_decode_query(&self) -> Option<String> {
  628. self.query.as_ref().map(|value| lossy_utf8_percent_decode(value.as_bytes()))
  629. }
  630. /// Percent-decode the URL’s fragment identifier, if any.
  631. ///
  632. /// This is “lossy”: invalid UTF-8 percent-encoded byte sequences
  633. /// will be replaced � U+FFFD, the replacement character.
  634. #[inline]
  635. pub fn lossy_percent_decode_fragment(&self) -> Option<String> {
  636. self.fragment.as_ref().map(|value| lossy_utf8_percent_decode(value.as_bytes()))
  637. }
  638. }
  639. impl<E, S: rustc_serialize::Encoder<E>> rustc_serialize::Encodable<S, E> for Url {
  640. fn encode(&self, encoder: &mut S) -> Result<(), E> {
  641. encoder.emit_str(self.to_string().as_slice())
  642. }
  643. }
  644. impl<E, D: rustc_serialize::Decoder<E>> rustc_serialize::Decodable<D, E> for Url {
  645. fn decode(decoder: &mut D) -> Result<Url, E> {
  646. Url::parse(try!(decoder.read_str()).as_slice()).map_err(|error| {
  647. decoder.error(format!("URL parsing error: {}", error).as_slice())
  648. })
  649. }
  650. }
  651. impl Show for Url {
  652. fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
  653. try!(UrlNoFragmentFormatter{ url: self }.fmt(formatter));
  654. match self.fragment {
  655. None => (),
  656. Some(ref fragment) => {
  657. try!(formatter.write(b"#"));
  658. try!(formatter.write(fragment.as_bytes()));
  659. }
  660. }
  661. Ok(())
  662. }
  663. }
  664. impl Show for SchemeData {
  665. fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
  666. match *self {
  667. SchemeData::Relative(ref scheme_data) => scheme_data.fmt(formatter),
  668. SchemeData::NonRelative(ref scheme_data) => scheme_data.fmt(formatter),
  669. }
  670. }
  671. }
  672. impl RelativeSchemeData {
  673. /// Percent-decode the URL’s username.
  674. ///
  675. /// This is “lossy”: invalid UTF-8 percent-encoded byte sequences
  676. /// will be replaced � U+FFFD, the replacement character.
  677. #[inline]
  678. pub fn lossy_percent_decode_username(&self) -> String {
  679. lossy_utf8_percent_decode(self.username.as_bytes())
  680. }
  681. /// Percent-decode the URL’s password, if any.
  682. ///
  683. /// This is “lossy”: invalid UTF-8 percent-encoded byte sequences
  684. /// will be replaced � U+FFFD, the replacement character.
  685. #[inline]
  686. pub fn lossy_percent_decode_password(&self) -> Option<String> {
  687. self.password.as_ref().map(|value| lossy_utf8_percent_decode(value.as_bytes()))
  688. }
  689. /// Assuming the URL is in the `file` scheme or similar,
  690. /// convert its path to an absolute `std::path::Path`.
  691. ///
  692. /// **Note:** This does not actually check the URL’s `scheme`,
  693. /// and may give nonsensical results for other schemes.
  694. /// It is the user’s responsibility to check the URL’s scheme before calling this.
  695. ///
  696. /// The return type (when `Ok()`) is generic and can be either `std::path::posix::Path`
  697. /// or `std::path::windows::Path`.
  698. /// (Use `std::path::Path` to pick one of them depending on the local system.)
  699. /// If the compiler can not infer the desired type from context, you may have to specifiy it:
  700. ///
  701. /// ```ignore
  702. /// let path = url.to_file_path::<std::path::posix::Path>();
  703. /// ```
  704. ///
  705. /// Returns `Err` if the host is neither empty nor `"localhost"`,
  706. /// or if `Path::new_opt()` returns `None`.
  707. /// (That is, if the percent-decoded path contains a NUL byte or,
  708. /// for a Windows path, is not UTF-8.)
  709. #[inline]
  710. pub fn to_file_path<T: FromUrlPath>(&self) -> Result<T, ()> {
  711. // FIXME: Figure out what to do w.r.t host.
  712. match self.domain() {
  713. Some("") | Some("localhost") => FromUrlPath::from_url_path(self.path.as_slice()),
  714. _ => Err(())
  715. }
  716. }
  717. /// If the host is a domain, return the domain as a string.
  718. #[inline]
  719. pub fn domain<'a>(&'a self) -> Option<&'a str> {
  720. match self.host {
  721. Host::Domain(ref domain) => Some(domain.as_slice()),
  722. _ => None,
  723. }
  724. }
  725. /// If the host is a domain, return a mutable reference to the domain string.
  726. #[inline]
  727. pub fn domain_mut<'a>(&'a mut self) -> Option<&'a mut String> {
  728. match self.host {
  729. Host::Domain(ref mut domain) => Some(domain),
  730. _ => None,
  731. }
  732. }
  733. /// Return the port number of the URL, even if it is the default.
  734. /// Return `None` for file-like URLs.
  735. #[inline]
  736. pub fn port_or_default(&self) -> Option<u16> {
  737. self.port.or(self.default_port)
  738. }
  739. /// Serialize the path as a string.
  740. ///
  741. /// The returned string starts with a "/" slash, and components are separated by slashes.
  742. /// A trailing slash represents an empty last component.
  743. pub fn serialize_path(&self) -> String {
  744. PathFormatter {
  745. path: self.path.as_slice()
  746. }.to_string()
  747. }
  748. /// Serialize the userinfo as a string.
  749. ///
  750. /// Format: "<username>:<password>@".
  751. pub fn serialize_userinfo(&self) -> String {
  752. UserInfoFormatter {
  753. username: self.username.as_slice(),
  754. password: self.password.as_ref().map(|s| s.as_slice())
  755. }.to_string()
  756. }
  757. }
  758. impl Show for RelativeSchemeData {
  759. fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
  760. // Write the scheme-trailing double slashes.
  761. try!(formatter.write(b"//"));
  762. // Write the user info.
  763. try!(UserInfoFormatter {
  764. username: self.username.as_slice(),
  765. password: self.password.as_ref().map(|s| s.as_slice())
  766. }.fmt(formatter));
  767. // Write the host.
  768. try!(self.host.fmt(formatter));
  769. // Write the port.
  770. match self.port {
  771. Some(port) => {
  772. try!(write!(formatter, ":{}", port));
  773. },
  774. None => {}
  775. }
  776. // Write the path.
  777. PathFormatter {
  778. path: self.path.as_slice()
  779. }.fmt(formatter)
  780. }
  781. }
  782. pub trait ToUrlPath {
  783. fn to_url_path(&self) -> Result<Vec<String>, ()>;
  784. }
  785. impl ToUrlPath for path::posix::Path {
  786. fn to_url_path(&self) -> Result<Vec<String>, ()> {
  787. if !self.is_absolute() {
  788. return Err(())
  789. }
  790. Ok(self.components().map(|c| percent_encode(c, DEFAULT_ENCODE_SET)).collect())
  791. }
  792. }
  793. impl ToUrlPath for path::windows::Path {
  794. fn to_url_path(&self) -> Result<Vec<String>, ()> {
  795. if !self.is_absolute() {
  796. return Err(())
  797. }
  798. if path::windows::prefix(self) != Some(path::windows::PathPrefix::DiskPrefix) {
  799. // FIXME: do something with UNC and other prefixes?
  800. return Err(())
  801. }
  802. // Start with the prefix, e.g. "C:"
  803. let mut path = vec![self.as_str().unwrap().slice_to(2).to_string()];
  804. // self.components() does not include the prefix
  805. for component in self.components() {
  806. path.push(percent_encode(component, DEFAULT_ENCODE_SET));
  807. }
  808. Ok(path)
  809. }
  810. }
  811. pub trait FromUrlPath {
  812. fn from_url_path(path: &[String]) -> Result<Self, ()>;
  813. }
  814. impl FromUrlPath for path::posix::Path {
  815. fn from_url_path(path: &[String]) -> Result<path::posix::Path, ()> {
  816. if path.is_empty() {
  817. return Ok(path::posix::Path::new("/"))
  818. }
  819. let mut bytes = Vec::new();
  820. for path_part in path.iter() {
  821. bytes.push(b'/');
  822. percent_decode_to(path_part.as_bytes(), &mut bytes);
  823. }
  824. match path::posix::Path::new_opt(bytes) {
  825. None => Err(()), // Path contains a NUL byte
  826. Some(path) => {
  827. debug_assert!(path.is_absolute(),
  828. "to_file_path() failed to produce an absolute Path");
  829. Ok(path)
  830. }
  831. }
  832. }
  833. }
  834. impl FromUrlPath for path::windows::Path {
  835. fn from_url_path(path: &[String]) -> Result<path::windows::Path, ()> {
  836. if path.is_empty() {
  837. return Err(())
  838. }
  839. let prefix = path[0].as_slice();
  840. if prefix.len() != 2 || !parser::starts_with_ascii_alpha(prefix)
  841. || prefix.char_at(1) != ':' {
  842. return Err(())
  843. }
  844. let mut bytes = prefix.as_bytes().to_vec();
  845. for path_part in path.slice_from(1).iter() {
  846. bytes.push(b'\\');
  847. percent_decode_to(path_part.as_bytes(), &mut bytes);
  848. }
  849. match path::windows::Path::new_opt(bytes) {
  850. None => Err(()), // Path contains a NUL byte or invalid UTF-8
  851. Some(path) => {
  852. debug_assert!(path.is_absolute(),
  853. "to_file_path() failed to produce an absolute Path");
  854. debug_assert!(path::windows::prefix(&path) == Some(path::windows::PathPrefix::DiskPrefix),
  855. "to_file_path() failed to produce a Path with a disk prefix");
  856. Ok(path)
  857. }
  858. }
  859. }
  860. }