url.rs 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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. #![crate_name = "url_"]
  9. #![crate_type = "dylib"]
  10. #![crate_type = "rlib"]
  11. //! <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>
  12. //! <style>.sidebar { margin-top: 53px }</style>
  13. //!
  14. //! rust-url is an implementation of the [URL Standard](http://url.spec.whatwg.org/)
  15. //! for the [Rust](http://rust-lang.org/) programming language.
  16. //!
  17. //! It builds with [Cargo](http://crates.io/).
  18. //! To use it in your project, add this to your `Cargo.toml` file:
  19. //!
  20. //! ```Cargo
  21. //! [dependencies.url]
  22. //! git = "https://github.com/servo/rust-url"
  23. //! ```
  24. //!
  25. //! This is a replacement of the [`url` crate](http://doc.rust-lang.org/url/index.html)
  26. //! currently distributed with Rust.
  27. //! rust-url’s crate is currently named `url_` with an underscore to avoid a naming conflict,
  28. //! but the intent is to rename it to just `url` when the old crate eventually
  29. //! [goes away](https://github.com/rust-lang/rust/issues/15874).
  30. //! Therefore, it is recommended that you use this crate as follows:
  31. //!
  32. //! ```ignore
  33. //! extern crate url = "url_";
  34. //!
  35. //! use url::{Url, ...};
  36. //! ```
  37. //!
  38. //! … so that, when the renaming is done, you will only need to change this one line.
  39. //!
  40. //! # URL parsing and data structures
  41. //!
  42. //! First, URL parsing may fail for various reasons and therefore returns a `Result`.
  43. //!
  44. //! ```
  45. //! # use url_::Url;
  46. //! assert!(Url::parse("http://[:::1]") == Err("Invalid IPv6 address"))
  47. //! ```
  48. //!
  49. //! Let’s parse a valid URL and look at its components.
  50. //!
  51. //! ```
  52. //! # use url_::{Url, RelativeSchemeData, NonRelativeSchemeData};
  53. //! let issue_list_url = Url::parse(
  54. //! "https://github.com/rust-lang/rust/issues?labels=E-easy&state=open"
  55. //! ).unwrap();
  56. //!
  57. //!
  58. //! assert!(issue_list_url.scheme == "https".to_string());
  59. //! assert!(issue_list_url.domain() == Some("github.com"));
  60. //! assert!(issue_list_url.port() == Some(""));
  61. //! assert!(issue_list_url.path() == Some(&["rust-lang".to_string(),
  62. //! "rust".to_string(),
  63. //! "issues".to_string()]));
  64. //! assert!(issue_list_url.query == Some("labels=E-easy&state=open".to_string()));
  65. //! assert!(issue_list_url.fragment == None);
  66. //! match issue_list_url.scheme_data {
  67. //! RelativeSchemeData(..) => {}, // Expected
  68. //! NonRelativeSchemeData(..) => fail!(),
  69. //! }
  70. //! ```
  71. //!
  72. //! The `scheme`, `query`, and `fragment` are directly fields of the `Url` struct:
  73. //! they apply to all URLs.
  74. //! Every other components has accessors because they only apply to URLs said to be
  75. //! “in a relative scheme”. `https` is a relative scheme, but `data` is not:
  76. //!
  77. //! ```
  78. //! # use url_::{Url, NonRelativeSchemeData};
  79. //! let data_url = Url::parse("data:text/plain,Hello#").unwrap();
  80. //!
  81. //! assert!(data_url.scheme == "data".to_string());
  82. //! assert!(data_url.scheme_data == NonRelativeSchemeData("text/plain,Hello".to_string()));
  83. //! assert!(data_url.non_relative_scheme_data() == Some("text/plain,Hello"));
  84. //! assert!(data_url.query == None);
  85. //! assert!(data_url.fragment == Some("".to_string()));
  86. //! ```
  87. //!
  88. //! # Base URL
  89. //!
  90. //! Many contexts allow URL *references* that can be relative to a *base URL*:
  91. //!
  92. //! ```html
  93. //! <link rel="stylesheet" href="../main.css">
  94. //! ```
  95. //!
  96. //! Since parsed URL are absolute, giving a base is required:
  97. //!
  98. //! ```
  99. //! # use url_::Url;
  100. //! assert!(Url::parse("../main.css") == Err("Relative URL without a base"))
  101. //! ```
  102. //!
  103. //! `UrlParser` is a method-chaining API to provide various optional parameters
  104. //! to URL parsing, including a base URL.
  105. //!
  106. //! ```
  107. //! # use url_::{Url, UrlParser};
  108. //! let this_document = Url::parse("http://servo.github.io/rust-url/url/index.html").unwrap();
  109. //! let css_url = UrlParser::new().base_url(&this_document).parse("../main.css").unwrap();
  110. //! assert!(css_url.serialize() == "http://servo.github.io/rust-url/main.css".to_string());
  111. //! ```
  112. #![feature(macro_rules, default_type_params)]
  113. extern crate encoding;
  114. #[cfg(test)]
  115. extern crate serialize;
  116. use std::cmp;
  117. use std::fmt::{Formatter, FormatError, Show};
  118. use std::hash;
  119. use std::path::Path;
  120. use std::ascii::OwnedStrAsciiExt;
  121. use encoding::EncodingRef;
  122. use encode_sets::{PASSWORD_ENCODE_SET, USERNAME_ENCODE_SET, DEFAULT_ENCODE_SET};
  123. mod encode_sets;
  124. mod parser;
  125. pub mod form_urlencoded;
  126. pub mod punycode;
  127. #[cfg(test)]
  128. mod tests;
  129. #[deriving(PartialEq, Eq, Clone)]
  130. pub struct Url {
  131. pub scheme: String,
  132. pub scheme_data: SchemeData,
  133. pub query: Option<String>, // See form_urlencoded::parse_str() to get name/value pairs.
  134. pub fragment: Option<String>,
  135. }
  136. #[deriving(PartialEq, Eq, Clone)]
  137. pub enum SchemeData {
  138. RelativeSchemeData(RelativeSchemeData),
  139. NonRelativeSchemeData(String), // data: URLs, mailto: URLs, etc.
  140. }
  141. #[deriving(PartialEq, Eq, Clone)]
  142. pub struct RelativeSchemeData {
  143. pub username: String,
  144. pub password: Option<String>,
  145. pub host: Host,
  146. pub port: String,
  147. pub path: Vec<String>,
  148. }
  149. #[deriving(PartialEq, Eq, Clone)]
  150. pub enum Host {
  151. Domain(String),
  152. Ipv6(Ipv6Address)
  153. }
  154. pub struct Ipv6Address {
  155. pub pieces: [u16, ..8]
  156. }
  157. impl Clone for Ipv6Address {
  158. fn clone(&self) -> Ipv6Address {
  159. Ipv6Address { pieces: self.pieces }
  160. }
  161. }
  162. impl Eq for Ipv6Address {}
  163. impl PartialEq for Ipv6Address {
  164. fn eq(&self, other: &Ipv6Address) -> bool {
  165. self.pieces == other.pieces
  166. }
  167. }
  168. impl<S: hash::Writer> hash::Hash<S> for Url {
  169. fn hash(&self, state: &mut S) {
  170. self.serialize().hash(state)
  171. }
  172. }
  173. pub struct UrlParser<'a> {
  174. base_url: Option<&'a Url>,
  175. query_encoding_override: Option<EncodingRef>,
  176. error_handler: ErrorHandler,
  177. scheme_type_mapper: fn(scheme: &str) -> SchemeType,
  178. }
  179. impl<'a> UrlParser<'a> {
  180. #[inline]
  181. pub fn new() -> UrlParser<'a> {
  182. UrlParser {
  183. base_url: None,
  184. query_encoding_override: None,
  185. error_handler: silent_handler,
  186. scheme_type_mapper: whatwg_scheme_type_mapper,
  187. }
  188. }
  189. #[inline]
  190. pub fn base_url<'b>(&'b mut self, value: &'a Url) -> &'b mut UrlParser<'a> {
  191. self.base_url = Some(value);
  192. self
  193. }
  194. #[inline]
  195. pub fn query_encoding_override<'b>(&'b mut self, value: EncodingRef) -> &'b mut UrlParser<'a> {
  196. self.query_encoding_override = Some(value);
  197. self
  198. }
  199. #[inline]
  200. pub fn error_handler<'b>(&'b mut self, value: ErrorHandler) -> &'b mut UrlParser<'a> {
  201. self.error_handler = value;
  202. self
  203. }
  204. #[inline]
  205. pub fn scheme_type_mapper<'b>(&'b mut self, value: fn(scheme: &str) -> SchemeType)
  206. -> &'b mut UrlParser<'a> {
  207. self.scheme_type_mapper = value;
  208. self
  209. }
  210. #[inline]
  211. pub fn parse(&self, input: &str) -> ParseResult<Url> {
  212. parser::parse_url(input, self)
  213. }
  214. #[inline]
  215. fn parse_error(&self, message: &'static str) -> ParseResult<()> {
  216. (self.error_handler)(message)
  217. }
  218. #[inline]
  219. fn get_scheme_type(&self, scheme: &str) -> SchemeType {
  220. (self.scheme_type_mapper)(scheme)
  221. }
  222. }
  223. #[deriving(PartialEq, Eq)]
  224. pub enum SchemeType {
  225. FileLikeRelativeScheme,
  226. RelativeScheme(&'static str), // str is the default port, in ASCII decimal.
  227. NonRelativeScheme,
  228. }
  229. /// http://url.spec.whatwg.org/#relative-scheme
  230. fn whatwg_scheme_type_mapper(scheme: &str) -> SchemeType {
  231. match scheme {
  232. "file" => FileLikeRelativeScheme,
  233. "ftp" => RelativeScheme("21"),
  234. "gopher" => RelativeScheme("70"),
  235. "http" => RelativeScheme("80"),
  236. "https" => RelativeScheme("443"),
  237. "ws" => RelativeScheme("80"),
  238. "wss" => RelativeScheme("443"),
  239. _ => NonRelativeScheme,
  240. }
  241. }
  242. pub type ParseResult<T> = Result<T, &'static str>;
  243. /// This is called on non-fatal parse errors.
  244. /// The handler can choose to continue or abort parsing by returning Ok() or Err(), respectively.
  245. /// FIXME: make this a by-ref closure when that’s supported.
  246. pub type ErrorHandler = fn(reason: &'static str) -> ParseResult<()>;
  247. fn silent_handler(_reason: &'static str) -> ParseResult<()> {
  248. Ok(())
  249. }
  250. impl Url {
  251. #[inline]
  252. pub fn parse(input: &str) -> ParseResult<Url> {
  253. UrlParser::new().parse(input)
  254. }
  255. // FIXME: Figure out what to do on Windows
  256. #[cfg(unix)]
  257. pub fn from_file_path(path: &Path) -> Result<Url, ()> {
  258. let path = try!(encode_file_path(path));
  259. Ok(Url::from_path_common(path))
  260. }
  261. // FIXME: Figure out what to do on Windows
  262. #[cfg(unix)]
  263. pub fn from_directory_path(path: &Path) -> Result<Url, ()> {
  264. let mut path = try!(encode_file_path(path));
  265. // Add an empty path component (i.e. a trailing slash in serialization)
  266. // so that the entire path is used as a base URL.
  267. path.push("".to_string());
  268. Ok(Url::from_path_common(path))
  269. }
  270. fn from_path_common(path: Vec<String>) -> Url {
  271. Url {
  272. scheme: "file".to_string(),
  273. scheme_data: RelativeSchemeData(RelativeSchemeData {
  274. username: "".to_string(),
  275. password: None,
  276. port: "".to_string(),
  277. host: Domain("".to_string()),
  278. path: path,
  279. }),
  280. query: None,
  281. fragment: None,
  282. }
  283. }
  284. #[inline]
  285. pub fn to_file_path(&self) -> Result<Path, ()> {
  286. match self.scheme_data {
  287. RelativeSchemeData(ref scheme_data) => scheme_data.to_file_path(),
  288. NonRelativeSchemeData(..) => Err(()),
  289. }
  290. }
  291. pub fn serialize(&self) -> String {
  292. self.to_string()
  293. }
  294. pub fn serialize_no_fragment(&self) -> String {
  295. UrlNoFragmentFormatter{ url: self }.to_string()
  296. }
  297. #[inline]
  298. pub fn non_relative_scheme_data<'a>(&'a self) -> Option<&'a str> {
  299. match self.scheme_data {
  300. RelativeSchemeData(..) => None,
  301. NonRelativeSchemeData(ref scheme_data) => Some(scheme_data.as_slice()),
  302. }
  303. }
  304. #[inline]
  305. pub fn relative_scheme_data<'a>(&'a self) -> Option<&'a RelativeSchemeData> {
  306. match self.scheme_data {
  307. RelativeSchemeData(ref scheme_data) => Some(scheme_data),
  308. NonRelativeSchemeData(..) => None,
  309. }
  310. }
  311. #[inline]
  312. pub fn host<'a>(&'a self) -> Option<&'a Host> {
  313. match self.scheme_data {
  314. RelativeSchemeData(ref scheme_data) => Some(&scheme_data.host),
  315. NonRelativeSchemeData(..) => None,
  316. }
  317. }
  318. #[inline]
  319. pub fn domain<'a>(&'a self) -> Option<&'a str> {
  320. match self.scheme_data {
  321. RelativeSchemeData(ref scheme_data) => scheme_data.domain(),
  322. NonRelativeSchemeData(..) => None,
  323. }
  324. }
  325. #[inline]
  326. pub fn port<'a>(&'a self) -> Option<&'a str> {
  327. match self.scheme_data {
  328. RelativeSchemeData(ref scheme_data) => Some(scheme_data.port.as_slice()),
  329. NonRelativeSchemeData(..) => None,
  330. }
  331. }
  332. #[inline]
  333. pub fn path<'a>(&'a self) -> Option<&'a [String]> {
  334. match self.scheme_data {
  335. RelativeSchemeData(ref scheme_data) => Some(scheme_data.path.as_slice()),
  336. NonRelativeSchemeData(..) => None,
  337. }
  338. }
  339. #[inline]
  340. pub fn serialize_host(&self) -> Option<String> {
  341. match self.scheme_data {
  342. RelativeSchemeData(ref scheme_data) => Some(scheme_data.host.serialize()),
  343. NonRelativeSchemeData(..) => None,
  344. }
  345. }
  346. #[inline]
  347. pub fn serialize_path(&self) -> Option<String> {
  348. match self.scheme_data {
  349. RelativeSchemeData(ref scheme_data) => Some(scheme_data.serialize_path()),
  350. NonRelativeSchemeData(..) => None,
  351. }
  352. }
  353. }
  354. impl Show for Url {
  355. fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> {
  356. try!(UrlNoFragmentFormatter{ url: self }.fmt(formatter));
  357. match self.fragment {
  358. None => (),
  359. Some(ref fragment) => {
  360. try!(formatter.write(b"#"));
  361. try!(formatter.write(fragment.as_bytes()));
  362. }
  363. }
  364. Ok(())
  365. }
  366. }
  367. struct UrlNoFragmentFormatter<'a> {
  368. url: &'a Url
  369. }
  370. impl<'a> Show for UrlNoFragmentFormatter<'a> {
  371. fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> {
  372. try!(formatter.write(self.url.scheme.as_bytes()));
  373. try!(formatter.write(b":"));
  374. try!(self.url.scheme_data.fmt(formatter));
  375. match self.url.query {
  376. None => (),
  377. Some(ref query) => {
  378. try!(formatter.write(b"?"));
  379. try!(formatter.write(query.as_bytes()));
  380. }
  381. }
  382. Ok(())
  383. }
  384. }
  385. impl Show for SchemeData {
  386. fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> {
  387. match *self {
  388. RelativeSchemeData(ref scheme_data) => scheme_data.fmt(formatter),
  389. NonRelativeSchemeData(ref scheme_data) => scheme_data.fmt(formatter),
  390. }
  391. }
  392. }
  393. impl RelativeSchemeData {
  394. // FIXME: Figure out what to do on Windows.
  395. #[cfg(unix)]
  396. pub fn to_file_path(&self) -> Result<Path, ()> {
  397. // FIXME: Figure out what to do w.r.t host.
  398. match self.domain() {
  399. Some("") => {
  400. if self.path.is_empty() {
  401. Ok(Path::new("/"))
  402. } else {
  403. let mut bytes = Vec::new();
  404. for path_part in self.path.iter() {
  405. bytes.push(b'/');
  406. percent_decode_to(path_part.as_bytes(), &mut bytes);
  407. }
  408. Ok(Path::new(bytes))
  409. }
  410. }
  411. _ => Err(())
  412. }
  413. }
  414. #[inline]
  415. pub fn domain<'a>(&'a self) -> Option<&'a str> {
  416. match self.host {
  417. Domain(ref domain) => Some(domain.as_slice()),
  418. _ => None,
  419. }
  420. }
  421. pub fn serialize_path(&self) -> String {
  422. PathFormatter { path: &self.path }.to_string()
  423. }
  424. }
  425. struct PathFormatter<'a> {
  426. path: &'a Vec<String>
  427. }
  428. impl<'a> Show for PathFormatter<'a> {
  429. fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> {
  430. if self.path.is_empty() {
  431. formatter.write(b"/")
  432. } else {
  433. for path_part in self.path.iter() {
  434. try!(formatter.write(b"/"));
  435. try!(formatter.write(path_part.as_bytes()));
  436. }
  437. Ok(())
  438. }
  439. }
  440. }
  441. impl Show for RelativeSchemeData {
  442. fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> {
  443. try!(formatter.write(b"//"));
  444. if !self.username.is_empty() || self.password.is_some() {
  445. try!(formatter.write(self.username.as_bytes()));
  446. match self.password {
  447. None => (),
  448. Some(ref password) => {
  449. try!(formatter.write(b":"));
  450. try!(formatter.write(password.as_bytes()));
  451. }
  452. }
  453. try!(formatter.write(b"@"));
  454. }
  455. try!(self.host.fmt(formatter));
  456. if !self.port.is_empty() {
  457. try!(formatter.write(b":"));
  458. try!(formatter.write(self.port.as_bytes()));
  459. }
  460. PathFormatter { path: &self.path }.fmt(formatter)
  461. }
  462. }
  463. #[allow(dead_code)]
  464. struct UrlUtilsWrapper<'a> {
  465. url: &'a mut Url,
  466. parser: &'a UrlParser<'a>,
  467. }
  468. /// These methods are not meant for use in Rust code,
  469. /// only to help implement the JavaScript URLUtils API: http://url.spec.whatwg.org/#urlutils
  470. trait UrlUtils {
  471. fn set_scheme(&mut self, input: &str) -> ParseResult<()>;
  472. fn set_username(&mut self, input: &str) -> ParseResult<()>;
  473. fn set_password(&mut self, input: &str) -> ParseResult<()>;
  474. fn set_host_and_port(&mut self, input: &str) -> ParseResult<()>;
  475. fn set_host(&mut self, input: &str) -> ParseResult<()>;
  476. fn set_port(&mut self, input: &str) -> ParseResult<()>;
  477. fn set_path(&mut self, input: &str) -> ParseResult<()>;
  478. fn set_query(&mut self, input: &str) -> ParseResult<()>;
  479. fn set_fragment(&mut self, input: &str) -> ParseResult<()>;
  480. }
  481. impl<'a> UrlUtils for UrlUtilsWrapper<'a> {
  482. /// `URLUtils.protocol` setter
  483. fn set_scheme(&mut self, input: &str) -> ParseResult<()> {
  484. match parser::parse_scheme(input.as_slice(), parser::SetterContext) {
  485. Some((scheme, _)) => {
  486. self.url.scheme = scheme;
  487. Ok(())
  488. },
  489. None => Err("Invalid scheme"),
  490. }
  491. }
  492. /// `URLUtils.username` setter
  493. fn set_username(&mut self, input: &str) -> ParseResult<()> {
  494. match self.url.scheme_data {
  495. RelativeSchemeData(RelativeSchemeData { ref mut username, .. }) => {
  496. username.truncate(0);
  497. utf8_percent_encode_to(input, USERNAME_ENCODE_SET, username);
  498. Ok(())
  499. },
  500. NonRelativeSchemeData(_) => Err("Can not set username on non-relative URL.")
  501. }
  502. }
  503. /// `URLUtils.password` setter
  504. fn set_password(&mut self, input: &str) -> ParseResult<()> {
  505. match self.url.scheme_data {
  506. RelativeSchemeData(RelativeSchemeData { ref mut password, .. }) => {
  507. let mut new_password = String::new();
  508. utf8_percent_encode_to(input, PASSWORD_ENCODE_SET, &mut new_password);
  509. *password = Some(new_password);
  510. Ok(())
  511. },
  512. NonRelativeSchemeData(_) => Err("Can not set password on non-relative URL.")
  513. }
  514. }
  515. /// `URLUtils.host` setter
  516. fn set_host_and_port(&mut self, input: &str) -> ParseResult<()> {
  517. match self.url.scheme_data {
  518. RelativeSchemeData(RelativeSchemeData { ref mut host, ref mut port, .. }) => {
  519. let scheme_type = self.parser.get_scheme_type(self.url.scheme.as_slice());
  520. let (new_host, new_port, _) = try!(parser::parse_host(
  521. input, scheme_type, self.parser));
  522. *host = new_host;
  523. *port = new_port;
  524. Ok(())
  525. },
  526. NonRelativeSchemeData(_) => Err("Can not set host/port on non-relative URL.")
  527. }
  528. }
  529. /// `URLUtils.hostname` setter
  530. fn set_host(&mut self, input: &str) -> ParseResult<()> {
  531. match self.url.scheme_data {
  532. RelativeSchemeData(RelativeSchemeData { ref mut host, .. }) => {
  533. let (new_host, _) = try!(parser::parse_hostname(input, self.parser));
  534. *host = new_host;
  535. Ok(())
  536. },
  537. NonRelativeSchemeData(_) => Err("Can not set host on non-relative URL.")
  538. }
  539. }
  540. /// `URLUtils.port` setter
  541. fn set_port(&mut self, input: &str) -> ParseResult<()> {
  542. match self.url.scheme_data {
  543. RelativeSchemeData(RelativeSchemeData { ref mut port, .. }) => {
  544. let scheme_type = self.parser.get_scheme_type(self.url.scheme.as_slice());
  545. if scheme_type == FileLikeRelativeScheme {
  546. return Err("Can not set port on file: URL.")
  547. }
  548. let (new_port, _) = try!(parser::parse_port(input, scheme_type, self.parser));
  549. *port = new_port;
  550. Ok(())
  551. },
  552. NonRelativeSchemeData(_) => Err("Can not set port on non-relative URL.")
  553. }
  554. }
  555. /// `URLUtils.pathname` setter
  556. fn set_path(&mut self, input: &str) -> ParseResult<()> {
  557. match self.url.scheme_data {
  558. RelativeSchemeData(RelativeSchemeData { ref mut path, .. }) => {
  559. let scheme_type = self.parser.get_scheme_type(self.url.scheme.as_slice());
  560. let (new_path, _) = try!(parser::parse_path_start(
  561. input, parser::SetterContext, scheme_type, self.parser));
  562. *path = new_path;
  563. Ok(())
  564. },
  565. NonRelativeSchemeData(_) => Err("Can not set path on non-relative URL.")
  566. }
  567. }
  568. /// `URLUtils.search` setter
  569. fn set_query(&mut self, input: &str) -> ParseResult<()> {
  570. // FIXME: This is in the spec, but seems superfluous.
  571. match self.url.scheme_data {
  572. RelativeSchemeData(_) => (),
  573. NonRelativeSchemeData(_) => return Err("Can not set query on non-relative URL.")
  574. }
  575. self.url.query = if input.is_empty() {
  576. None
  577. } else {
  578. let input = if input.starts_with("?") { input.slice_from(1) } else { input };
  579. let (new_query, _) = try!(parser::parse_query(
  580. input, parser::SetterContext, self.parser));
  581. Some(new_query)
  582. };
  583. Ok(())
  584. }
  585. /// `URLUtils.hash` setter
  586. fn set_fragment(&mut self, input: &str) -> ParseResult<()> {
  587. if self.url.scheme.as_slice() == "javascript" {
  588. return Err("Can not set fragment on a javascript: URL.")
  589. }
  590. self.url.fragment = if input.is_empty() {
  591. None
  592. } else {
  593. let input = if input.starts_with("#") { input.slice_from(1) } else { input };
  594. Some(try!(parser::parse_fragment(input, self.parser)))
  595. };
  596. Ok(())
  597. }
  598. }
  599. impl Host {
  600. pub fn parse(input: &str) -> ParseResult<Host> {
  601. if input.len() == 0 {
  602. Err("Empty host")
  603. } else if input.starts_with("[") {
  604. if input.ends_with("]") {
  605. Ipv6Address::parse(input.slice(1, input.len() - 1)).map(Ipv6)
  606. } else {
  607. Err("Invalid Ipv6 address")
  608. }
  609. } else {
  610. let decoded = percent_decode(input.as_bytes());
  611. let domain = String::from_utf8_lossy(decoded.as_slice());
  612. // TODO: Remove this check and use IDNA "domain to ASCII"
  613. if !domain.as_slice().is_ascii() {
  614. Err("Non-ASCII domains (IDNA) are not supported yet.")
  615. } else if domain.as_slice().find(&[
  616. '\0', '\t', '\n', '\r', ' ', '#', '%', '/', ':', '?', '@', '[', '\\', ']'
  617. ]).is_some() {
  618. Err("Invalid domain character.")
  619. } else {
  620. Ok(Domain(domain.into_string().into_ascii_lower()))
  621. }
  622. }
  623. }
  624. pub fn serialize(&self) -> String {
  625. self.to_string()
  626. }
  627. }
  628. impl Show for Host {
  629. fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> {
  630. match *self {
  631. Domain(ref domain) => domain.fmt(formatter),
  632. Ipv6(ref address) => {
  633. try!(formatter.write(b"["));
  634. try!(address.fmt(formatter));
  635. formatter.write(b"]")
  636. }
  637. }
  638. }
  639. }
  640. impl Ipv6Address {
  641. pub fn parse(input: &str) -> ParseResult<Ipv6Address> {
  642. let input = input.as_bytes();
  643. let len = input.len();
  644. let mut is_ip_v4 = false;
  645. let mut pieces = [0, 0, 0, 0, 0, 0, 0, 0];
  646. let mut piece_pointer = 0u;
  647. let mut compress_pointer = None;
  648. let mut i = 0u;
  649. if input[0] == b':' {
  650. if input[1] != b':' {
  651. return Err("Invalid IPv6 address")
  652. }
  653. i = 2;
  654. piece_pointer = 1;
  655. compress_pointer = Some(1u);
  656. }
  657. while i < len {
  658. if piece_pointer == 8 {
  659. return Err("Invalid IPv6 address")
  660. }
  661. if input[i] == b':' {
  662. if compress_pointer.is_some() {
  663. return Err("Invalid IPv6 address")
  664. }
  665. i += 1;
  666. piece_pointer += 1;
  667. compress_pointer = Some(piece_pointer);
  668. continue
  669. }
  670. let start = i;
  671. let end = cmp::min(len, start + 4);
  672. let mut value = 0u16;
  673. while i < end {
  674. match from_hex(input[i]) {
  675. Some(digit) => {
  676. value = value * 0x10 + digit as u16;
  677. i += 1;
  678. },
  679. None => break
  680. }
  681. }
  682. if i < len {
  683. match input[i] {
  684. b'.' => {
  685. if i == start {
  686. return Err("Invalid IPv6 address")
  687. }
  688. i = start;
  689. is_ip_v4 = true;
  690. },
  691. b':' => {
  692. i += 1;
  693. if i == len {
  694. return Err("Invalid IPv6 address")
  695. }
  696. },
  697. _ => return Err("Invalid IPv6 address")
  698. }
  699. }
  700. if is_ip_v4 {
  701. break
  702. }
  703. pieces[piece_pointer] = value;
  704. piece_pointer += 1;
  705. }
  706. if is_ip_v4 {
  707. if piece_pointer > 6 {
  708. return Err("Invalid IPv6 address")
  709. }
  710. let mut dots_seen = 0u;
  711. while i < len {
  712. let mut value = 0u16;
  713. while i < len {
  714. let digit = match input[i] {
  715. c @ b'0' .. b'9' => c - b'0',
  716. _ => break
  717. };
  718. value = value * 10 + digit as u16;
  719. if value == 0 || value > 255 {
  720. return Err("Invalid IPv6 address")
  721. }
  722. }
  723. if dots_seen < 3 && !(i < len && input[i] == b'.') {
  724. return Err("Invalid IPv6 address")
  725. }
  726. pieces[piece_pointer] = pieces[piece_pointer] * 0x100 + value;
  727. if dots_seen == 0 || dots_seen == 2 {
  728. piece_pointer += 1;
  729. }
  730. i += 1;
  731. if dots_seen == 3 && i < len {
  732. return Err("Invalid IPv6 address")
  733. }
  734. dots_seen += 1;
  735. }
  736. }
  737. match compress_pointer {
  738. Some(compress_pointer) => {
  739. let mut swaps = piece_pointer - compress_pointer;
  740. piece_pointer = 7;
  741. while swaps > 0 {
  742. pieces[piece_pointer] = pieces[compress_pointer + swaps - 1];
  743. pieces[compress_pointer + swaps - 1] = 0;
  744. swaps -= 1;
  745. piece_pointer -= 1;
  746. }
  747. }
  748. _ => if piece_pointer != 8 {
  749. return Err("Invalid IPv6 address")
  750. }
  751. }
  752. Ok(Ipv6Address { pieces: pieces })
  753. }
  754. pub fn serialize(&self) -> String {
  755. self.to_string()
  756. }
  757. }
  758. impl Show for Ipv6Address {
  759. fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> {
  760. let (compress_start, compress_end) = longest_zero_sequence(&self.pieces);
  761. let mut i = 0;
  762. while i < 8 {
  763. if i == compress_start {
  764. try!(formatter.write(b":"));
  765. if i == 0 {
  766. try!(formatter.write(b":"));
  767. }
  768. if compress_end < 8 {
  769. i = compress_end;
  770. } else {
  771. break;
  772. }
  773. }
  774. try!(write!(formatter, "{:X}", self.pieces[i as uint]));
  775. if i < 7 {
  776. try!(formatter.write(b":"));
  777. }
  778. i += 1;
  779. }
  780. Ok(())
  781. }
  782. }
  783. fn longest_zero_sequence(pieces: &[u16, ..8]) -> (int, int) {
  784. let mut longest = -1;
  785. let mut longest_length = -1;
  786. let mut start = -1;
  787. macro_rules! finish_sequence(
  788. ($end: expr) => {
  789. if start >= 0 {
  790. let length = $end - start;
  791. if length > longest_length {
  792. longest = start;
  793. longest_length = length;
  794. }
  795. }
  796. };
  797. );
  798. for i in range(0, 8) {
  799. if pieces[i as uint] == 0 {
  800. if start < 0 {
  801. start = i;
  802. }
  803. } else {
  804. finish_sequence!(i);
  805. start = -1;
  806. }
  807. }
  808. finish_sequence!(8);
  809. (longest, longest + longest_length)
  810. }
  811. #[inline]
  812. fn from_hex(byte: u8) -> Option<u8> {
  813. match byte {
  814. b'0' .. b'9' => Some(byte - b'0'), // 0..9
  815. b'A' .. b'F' => Some(byte + 10 - b'A'), // A..F
  816. b'a' .. b'f' => Some(byte + 10 - b'a'), // a..f
  817. _ => None
  818. }
  819. }
  820. pub struct EncodeSet {
  821. map: &'static [&'static str, ..256],
  822. }
  823. pub static SIMPLE_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::SIMPLE };
  824. pub static QUERY_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::QUERY };
  825. pub static DEFAULT_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::DEFAULT };
  826. pub static USERINFO_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::USERINFO };
  827. pub static PASSWORD_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::PASSWORD };
  828. pub static USERNAME_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::USERNAME };
  829. pub static FORM_URLENCODED_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::FORM_URLENCODED };
  830. #[inline]
  831. pub fn percent_encode_to(input: &[u8], encode_set: EncodeSet, output: &mut String) {
  832. for &byte in input.iter() {
  833. output.push_str(encode_set.map[byte as uint])
  834. }
  835. }
  836. /// Percent-encode the given bytes.
  837. ///
  838. /// The returned string. is within the ASCII range.
  839. #[inline]
  840. pub fn percent_encode(input: &[u8], encode_set: EncodeSet) -> String {
  841. let mut output = String::new();
  842. percent_encode_to(input, encode_set, &mut output);
  843. output
  844. }
  845. #[inline]
  846. pub fn utf8_percent_encode_to(input: &str, encode_set: EncodeSet, output: &mut String) {
  847. percent_encode_to(input.as_bytes(), encode_set, output)
  848. }
  849. #[inline]
  850. pub fn utf8_percent_encode(input: &str, encode_set: EncodeSet) -> String {
  851. let mut output = String::new();
  852. utf8_percent_encode_to(input, encode_set, &mut output);
  853. output
  854. }
  855. pub fn percent_decode_to(input: &[u8], output: &mut Vec<u8>) {
  856. let mut i = 0u;
  857. while i < input.len() {
  858. let c = input[i];
  859. if c == b'%' && i + 2 < input.len() {
  860. match (from_hex(input[i + 1]), from_hex(input[i + 2])) {
  861. (Some(h), Some(l)) => {
  862. output.push(h * 0x10 + l);
  863. i += 3;
  864. continue
  865. },
  866. _ => (),
  867. }
  868. }
  869. output.push(c);
  870. i += 1;
  871. }
  872. }
  873. #[inline]
  874. pub fn percent_decode(input: &[u8]) -> Vec<u8> {
  875. let mut output = Vec::new();
  876. percent_decode_to(input, &mut output);
  877. output
  878. }
  879. // FIXME: Figure out what to do on Windows
  880. #[cfg(unix)]
  881. fn encode_file_path(path: &Path) -> Result<Vec<String>, ()> {
  882. if !path.is_absolute() {
  883. return Err(())
  884. }
  885. Ok(path.components().map(|c| percent_encode(c, DEFAULT_ENCODE_SET)).collect())
  886. }