url.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. // Copyright 2013 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. #[link(name = "url", vers = "0.1")];
  9. #[crate_type = "lib"];
  10. #[feature(globs, macro_rules)];
  11. extern mod encoding;
  12. #[cfg(test)]
  13. extern mod extra;
  14. use std::ascii::Ascii;
  15. use encoding::Encoding;
  16. use encoding::all::UTF_8;
  17. use encoding::label::encoding_from_whatwg_label;
  18. pub mod punycode;
  19. pub struct URL {
  20. scheme: ~[Ascii],
  21. scheme_data: SchemeData,
  22. query: Option<~[Ascii]>, // parse_form_urlencoded() parses this into ~[(~str, ~str)]
  23. fragment: Option<~[Ascii]>,
  24. }
  25. pub enum SchemeData {
  26. RelativeSchemeData(SchemeRelativeURL),
  27. OtherSchemeData(~[Ascii])
  28. }
  29. pub struct SchemeRelativeURL {
  30. userinfo: Option<UserInfo>,
  31. host: Host,
  32. port: ~[Ascii],
  33. path: ~[~[Ascii]],
  34. }
  35. pub struct UserInfo {
  36. username: ~[Ascii],
  37. password: Option<~[Ascii]>,
  38. }
  39. pub enum Host {
  40. Domain(~[~[Ascii]]),
  41. IPv6(IPv6Address)
  42. }
  43. pub struct IPv6Address {
  44. pieces: [u16, ..8]
  45. }
  46. pub type ParseResult<T> = Result<T, &'static str>;
  47. impl URL {
  48. pub fn parse(input: &str, base_url: Option<URL>) -> Option<URL> {
  49. let _ = input;
  50. let _ = base_url;
  51. // TODO
  52. None
  53. }
  54. pub fn serialize(&self) -> ~[Ascii] {
  55. let mut result = self.serialize_no_fragment();
  56. match self.fragment {
  57. None => (),
  58. Some(ref fragment) => {
  59. result.push('#'.to_ascii());
  60. result.push_all(fragment.as_slice());
  61. }
  62. }
  63. result
  64. }
  65. pub fn serialize_no_fragment(&self) -> ~[Ascii] {
  66. let mut result = self.scheme.to_owned();
  67. result.push(':'.to_ascii());
  68. match self.scheme_data {
  69. RelativeSchemeData(SchemeRelativeURL {
  70. userinfo: ref userinfo, host: ref host, port: ref port, path: ref path
  71. }) => {
  72. result.push_all("//".to_ascii());
  73. match userinfo {
  74. &None => (),
  75. &Some(UserInfo { username: ref username, password: ref password })
  76. => if username.len() > 0 || password.is_some() {
  77. result.push_all(username.as_slice());
  78. match password {
  79. &None => (),
  80. &Some(ref password) => {
  81. result.push(':'.to_ascii());
  82. result.push_all(password.as_slice());
  83. }
  84. }
  85. result.push('@'.to_ascii());
  86. }
  87. }
  88. result.push_all(host.serialize());
  89. if port.len() > 0 {
  90. result.push(':'.to_ascii());
  91. result.push_all(port.as_slice());
  92. }
  93. if path.len() > 0 {
  94. for path_part in path.iter() {
  95. result.push('/'.to_ascii());
  96. result.push_all(path_part.as_slice());
  97. }
  98. } else {
  99. result.push('/'.to_ascii());
  100. }
  101. },
  102. OtherSchemeData(ref data) => result.push_all(data.as_slice()),
  103. }
  104. match self.query {
  105. None => (),
  106. Some(ref query) => {
  107. result.push('?'.to_ascii());
  108. result.push_all(query.as_slice());
  109. }
  110. }
  111. result
  112. }
  113. }
  114. impl Host {
  115. pub fn parse(input: &str) -> ParseResult<Host> {
  116. if input.len() == 0 {
  117. Err("Empty host")
  118. } else if input[0] == '[' as u8 {
  119. if input[input.len()] == ']' as u8 {
  120. match IPv6Address::parse(input.slice(1, input.len() - 1)) {
  121. Some(address) => Ok(IPv6(address)),
  122. None => Err("Invalid IPv6 address"),
  123. }
  124. } else {
  125. Err("Invalid IPv6 address")
  126. }
  127. } else {
  128. let mut percent_encoded = ~[];
  129. utf8_percent_encode(input, SimpleEncodeSet, &mut percent_encoded);
  130. let bytes = percent_decode(percent_encoded);
  131. let decoded = UTF_8.decode(bytes, encoding::DecodeReplace).unwrap();
  132. let mut labels = ~[];
  133. for label in decoded.split_iter(&['.', '\u3002', '\uFF0E', '\uFF61']) {
  134. // TODO: Remove this check and use IDNA "domain to ASCII"
  135. // TODO: switch to .map(domain_label_to_ascii).collect() then.
  136. if label.is_ascii() {
  137. labels.push(unsafe { label.to_ascii_nocheck() }.to_owned())
  138. } else {
  139. return Err("Non-ASCII domains (IDNA) are not supported yet.")
  140. }
  141. }
  142. Ok(Domain(labels))
  143. }
  144. }
  145. pub fn serialize(&self) -> ~[Ascii] {
  146. match *self {
  147. Domain(ref labels) => labels.connect_vec(&'.'.to_ascii()),
  148. IPv6(ref address) => {
  149. let mut result = ~['['.to_ascii()];
  150. result.push_all(address.serialize());
  151. result.push(']'.to_ascii());
  152. result
  153. }
  154. }
  155. }
  156. }
  157. macro_rules! matches(
  158. ($value: expr, ($pattern: pat)|+) => {
  159. match $value {
  160. $($pattern)|+ => true,
  161. _ => false,
  162. }
  163. };
  164. )
  165. impl IPv6Address {
  166. pub fn parse(input: &str) -> Option<IPv6Address> {
  167. let len = input.len();
  168. let mut is_ip_v4 = false;
  169. let mut pieces = [0, 0, 0, 0, 0, 0, 0, 0];
  170. let mut piece_pointer = 0u;
  171. let mut compress_pointer = None;
  172. let mut i = 0u;
  173. if input[0] == ':' as u8 {
  174. if input[1] != ':' as u8 {
  175. return None
  176. }
  177. i = 2;
  178. piece_pointer = 1;
  179. compress_pointer = Some(1u);
  180. }
  181. while i < len {
  182. if piece_pointer == 8 {
  183. return None
  184. }
  185. if input[i] == ':' as u8 {
  186. if compress_pointer.is_some() {
  187. return None
  188. }
  189. piece_pointer += 1;
  190. compress_pointer = Some(piece_pointer);
  191. continue
  192. }
  193. let start = i;
  194. let end = len.min(&(start + 4));
  195. let mut value = 0u16;
  196. while i < end {
  197. match from_hex(input[i]) {
  198. Some(digit) => {
  199. value = value * 0x10 + digit as u16;
  200. i += 1;
  201. },
  202. None => {
  203. if input[i] == 0x2E { // .
  204. if i == start {
  205. return None
  206. }
  207. i = start;
  208. is_ip_v4 = true;
  209. break
  210. }
  211. if input[i] == 0x3A { // :
  212. i += 1;
  213. if i == len {
  214. return None
  215. }
  216. break
  217. }
  218. return None
  219. }
  220. }
  221. }
  222. if is_ip_v4 {
  223. break
  224. }
  225. pieces[piece_pointer] = value;
  226. piece_pointer += 1;
  227. }
  228. if is_ip_v4 {
  229. if piece_pointer > 6 {
  230. return None
  231. }
  232. let mut dots_seen = 0u;
  233. while i < len {
  234. let mut value = 0u16;
  235. while i < len {
  236. let digit = match input[i] {
  237. c @ 0x30 .. 0x39 => c - 0x30, // 0..9
  238. _ => break
  239. };
  240. value = value * 10 + digit as u16;
  241. if value > 255 {
  242. return None
  243. }
  244. }
  245. if dots_seen < 3 && !(i < len && input[i] == '.' as u8) {
  246. return None
  247. }
  248. pieces[piece_pointer] = pieces[piece_pointer] * 0x100 + value;
  249. if dots_seen == 0 || dots_seen == 2 {
  250. piece_pointer += 1;
  251. }
  252. i += 1;
  253. if dots_seen == 3 && i < len {
  254. return None
  255. }
  256. dots_seen += 1;
  257. }
  258. }
  259. match compress_pointer {
  260. Some(compress_pointer) => {
  261. let mut swaps = piece_pointer - compress_pointer;
  262. piece_pointer = 7;
  263. while swaps > 0 {
  264. pieces[piece_pointer] = pieces[compress_pointer + swaps - 1];
  265. pieces[compress_pointer + swaps - 1] = 0;
  266. swaps -= 1;
  267. piece_pointer -= 1;
  268. }
  269. }
  270. _ => if piece_pointer != 8 {
  271. return None
  272. }
  273. }
  274. Some(IPv6Address { pieces: pieces })
  275. }
  276. pub fn serialize(&self) -> ~[Ascii] {
  277. let mut output = ~[];
  278. let (compress_start, compress_end) = longest_zero_sequence(&self.pieces);
  279. let mut i = 0;
  280. while i < 8 {
  281. if i == compress_start {
  282. output.push(':'.to_ascii());
  283. if i == 0 {
  284. output.push(':'.to_ascii());
  285. }
  286. if compress_end < 8 {
  287. i = compress_end;
  288. } else {
  289. break;
  290. }
  291. }
  292. let hex = self.pieces[i].to_str_radix(16);
  293. // No need to check that hex digits are ASCII
  294. output.push_all(unsafe { hex.to_ascii_nocheck() });
  295. if i < 7 {
  296. output.push(':'.to_ascii());
  297. }
  298. }
  299. output
  300. }
  301. }
  302. fn longest_zero_sequence(pieces: &[u16, ..8]) -> (int, int) {
  303. let mut longest = -1;
  304. let mut longest_length = -1;
  305. let mut start = -1;
  306. macro_rules! finish_sequence(
  307. ($end: expr) => {
  308. if start >= 0 {
  309. let length = $end - start;
  310. if length > longest_length {
  311. longest = start;
  312. longest_length = length;
  313. }
  314. }
  315. };
  316. );
  317. for i in range(0, 8) {
  318. if pieces[i] == 0 {
  319. if start < 0 {
  320. start = i;
  321. }
  322. } else {
  323. finish_sequence!(i);
  324. start = -1;
  325. }
  326. }
  327. finish_sequence!(8);
  328. (longest, longest + longest_length)
  329. }
  330. #[inline]
  331. fn from_hex(byte: u8) -> Option<u8> {
  332. match byte {
  333. 0x30 .. 0x39 => Some(byte - 0x30), // 0..9
  334. 0x41 .. 0x46 => Some(byte + 10 - 0x41), // A..F
  335. 0x61 .. 0x66 => Some(byte + 10 - 0x61), // a..f
  336. _ => None
  337. }
  338. }
  339. #[inline]
  340. fn to_hex_upper(value: u8) -> Ascii {
  341. let digit = match value {
  342. 0 .. 9 => value + 0x30,
  343. 10 .. 15 => value - 10 + 0x41,
  344. _ => fail!()
  345. };
  346. unsafe { digit.to_ascii_nocheck() }
  347. }
  348. enum EncodeSet {
  349. SimpleEncodeSet,
  350. DefaultEncodeSet,
  351. PasswordEncodeSet,
  352. UsernameEncodeSet
  353. }
  354. #[inline]
  355. fn utf8_percent_encode(input: &str, encode_set: EncodeSet, output: &mut ~[Ascii]) {
  356. use Default = self::DefaultEncodeSet;
  357. use Password = self::PasswordEncodeSet;
  358. use Username = self::UsernameEncodeSet;
  359. for &byte in input.as_bytes().iter() {
  360. if byte < 0x20 || byte > 0x7E || match byte as char {
  361. ' ' | '"' | '#' | '<' | '>' | '?' | '`'
  362. => match encode_set { Default | Password | Username => true, _ => false },
  363. '/' | '@' | '\\'
  364. => match encode_set { Password | Username => true, _ => false },
  365. ':'
  366. => match encode_set { Username => true, _ => false },
  367. _ => false,
  368. } {
  369. percent_encode_byte(byte, output)
  370. } else {
  371. output.push(unsafe { byte.to_ascii_nocheck() }) // Already checked
  372. }
  373. }
  374. }
  375. #[inline]
  376. fn percent_encode_byte(byte: u8, output: &mut ~[Ascii]) {
  377. output.push_all(['%'.to_ascii(), to_hex_upper(byte >> 4), to_hex_upper(byte & 0x0F)])
  378. }
  379. #[inline]
  380. fn percent_decode(input: &[Ascii]) -> ~[u8] {
  381. let mut output = ~[];
  382. let mut i = 0u;
  383. while i < input.len() {
  384. let c = input[i];
  385. if c == '%'.to_ascii() && i + 2 < input.len() {
  386. match (from_hex(input[i + 1].to_byte()),
  387. from_hex(input[i + 2].to_byte())) {
  388. (Some(h), Some(l)) => {
  389. output.push(h * 0x10 + l);
  390. i += 3;
  391. continue
  392. },
  393. _ => (),
  394. }
  395. }
  396. output.push(c.to_byte());
  397. i += 1;
  398. }
  399. output
  400. }
  401. pub fn parse_form_urlencoded(input: &[Ascii],
  402. encoding_override: Option<&'static Encoding>,
  403. use_charset: bool,
  404. mut isindex: bool)
  405. -> ~[(~str, ~str)] {
  406. let mut encoding_override = encoding_override.unwrap_or(UTF_8 as &'static Encoding);
  407. let mut pairs = ~[];
  408. for string in input.split_iter(|&c| c == '&'.to_ascii()) {
  409. if string.len() > 0 {
  410. let (name, value) = match string.position_elem(&'='.to_ascii()) {
  411. Some(position) => (string.slice_to(position), string.slice_from(position + 1)),
  412. None => if isindex { (&[], string) } else { (string, &[]) }
  413. };
  414. let name = name.to_str_ascii().replace("+", " ");
  415. let value = value.to_str_ascii().replace("+", " ");
  416. if use_charset && name.as_slice() == "_charset_" {
  417. match encoding_from_whatwg_label(value) {
  418. Some(encoding) => encoding_override = encoding,
  419. None => (),
  420. }
  421. }
  422. pairs.push((name, value));
  423. }
  424. isindex = false;
  425. }
  426. #[inline]
  427. fn decode(input: &~str, encoding_override: &'static Encoding) -> ~str {
  428. // No need to check as input comes from &[Ascii].to_str_ascii().replace("+", " ")
  429. let bytes = percent_decode(unsafe { input.as_slice().to_ascii_nocheck() });
  430. encoding_override.decode(bytes, encoding::DecodeReplace).unwrap()
  431. }
  432. for pair in pairs.mut_iter() {
  433. let new_pair = {
  434. let &(ref name, ref value) = pair;
  435. (decode(name, encoding_override), decode(value, encoding_override))
  436. };
  437. *pair = new_pair;
  438. }
  439. pairs
  440. }
  441. pub fn serialize_form_urlencoded(pairs: ~[(~str, ~str)],
  442. encoding_override: Option<&'static Encoding>)
  443. -> ~[Ascii] {
  444. #[inline]
  445. fn byte_serialize(input: &str, output: &mut ~[Ascii],
  446. encoding_override: Option<&'static Encoding>) {
  447. let keep_alive;
  448. let input = match encoding_override {
  449. None => input.as_bytes(), // "Encode" to UTF-8
  450. Some(encoding) => {
  451. keep_alive = encoding.encode(input, encoding::EncodeNcrEscape).unwrap();
  452. keep_alive.as_slice()
  453. }
  454. };
  455. for byte in input.iter() {
  456. match *byte {
  457. 0x20 => output.push('+'.to_ascii()),
  458. 0x2A | 0x2D | 0x2E | 0x30 .. 0x39 | 0x41 .. 0x5A | 0x5F | 0x61 .. 0x7A
  459. => output.push(unsafe { byte.to_ascii_nocheck() }),
  460. _ => percent_encode_byte(*byte, output),
  461. }
  462. }
  463. }
  464. let mut output = ~[];
  465. for &(ref name, ref value) in pairs.iter() {
  466. if output.len() > 0 {
  467. output.push('&'.to_ascii());
  468. byte_serialize(name.as_slice(), &mut output, encoding_override);
  469. output.push('='.to_ascii());
  470. byte_serialize(value.as_slice(), &mut output, encoding_override);
  471. }
  472. }
  473. output
  474. }
  475. #[cfg(test)]
  476. mod tests {
  477. use std::{char, u32};
  478. use super::*;
  479. #[test]
  480. fn test_url_parsing() {
  481. for test in parse_test_data(include_str!("urltestdata.txt")).move_iter() {
  482. let Test {
  483. input: input,
  484. base: base,
  485. scheme: expected_scheme,
  486. username: expected_username,
  487. password: expected_password,
  488. host: expected_host,
  489. port: expected_port,
  490. path: expected_path,
  491. query: expected_query,
  492. fragment: expected_fragment
  493. } = test;
  494. let base = URL::parse(base, None).unwrap();
  495. let url = URL::parse(input, Some(base));
  496. if expected_scheme.is_none() {
  497. assert!(url.is_none(), "Expected a parse error");
  498. continue
  499. }
  500. let URL {
  501. scheme: scheme,
  502. scheme_data: scheme_data,
  503. query: query,
  504. fragment: fragment
  505. } = url.unwrap();
  506. assert_eq!(Some(scheme.to_str_ascii()), expected_scheme);
  507. match scheme_data {
  508. RelativeSchemeData(SchemeRelativeURL {
  509. userinfo: userinfo, host: host, port: port, path: path
  510. }) => {
  511. let (username, password) = match userinfo {
  512. Some(UserInfo { username: username, password: password })
  513. => (Some(username.to_str_ascii()), password.map(|p| p.to_str_ascii())),
  514. _ => (None, None),
  515. };
  516. assert_eq!(username, expected_username);
  517. assert_eq!(password, expected_password);
  518. assert_eq!(Some(host.serialize().to_str_ascii()), expected_host)
  519. assert_eq!(Some(port.to_str_ascii()), expected_port);
  520. assert_eq!(Some(path.map(|p| p.to_str_ascii()).connect("/")), expected_path);
  521. },
  522. OtherSchemeData(scheme_data) => {
  523. assert_eq!(Some(scheme_data.to_str_ascii()), expected_path);
  524. assert_eq!(None, expected_username);
  525. assert_eq!(None, expected_password);
  526. assert_eq!(None, expected_host);
  527. assert_eq!(None, expected_port);
  528. },
  529. }
  530. assert_eq!(query.map(|p| p.to_str_ascii()), expected_query);
  531. assert_eq!(fragment.map(|p| p.to_str_ascii()), expected_fragment);
  532. }
  533. }
  534. struct Test {
  535. input: ~str,
  536. base: ~str,
  537. scheme: Option<~str>,
  538. username: Option<~str>,
  539. password: Option<~str>,
  540. host: Option<~str>,
  541. port: Option<~str>,
  542. path: Option<~str>,
  543. query: Option<~str>,
  544. fragment: Option<~str>,
  545. }
  546. fn parse_test_data(input: &str) -> ~[Test] {
  547. let mut tests: ~[Test] = ~[];
  548. for line in input.line_iter() {
  549. if line == "" || line[0] == ('#' as u8) {
  550. continue
  551. }
  552. let mut pieces = line.split_iter(' ').to_owned_vec();
  553. let input = unescape(pieces.shift());
  554. let mut test = Test {
  555. input: input,
  556. base: if pieces.is_empty() {
  557. tests[tests.len() - 1].base.to_owned()
  558. } else {
  559. unescape(pieces.shift())
  560. },
  561. scheme: None,
  562. username: None,
  563. password: None,
  564. host: None,
  565. port: None,
  566. path: None,
  567. query: None,
  568. fragment: None,
  569. };
  570. for piece in pieces.move_iter() {
  571. if piece != "" || piece[0] == ('#' as u8) {
  572. continue
  573. }
  574. let colon = piece.find(':').unwrap();
  575. let value = piece.slice_from(colon + 1).to_owned();
  576. match piece.slice_to(colon) {
  577. "s" => test.scheme = Some(value),
  578. "u" => test.username = Some(value),
  579. "pass" => test.password = Some(value),
  580. "h" => test.host = Some(value),
  581. "p" => test.path = Some(value),
  582. "q" => test.query = Some(value),
  583. "f" => test.fragment = Some(value),
  584. _ => fail!("Invalid token")
  585. }
  586. }
  587. tests.push(test)
  588. }
  589. tests
  590. }
  591. fn unescape(input: &str) -> ~str {
  592. let mut output = ~"";
  593. let mut chars = input.iter();
  594. loop {
  595. match chars.next() {
  596. None => return output,
  597. Some(c) => output.push_char(
  598. if c == '\\' {
  599. match chars.next().unwrap() {
  600. '\\' => '\\',
  601. 'n' => '\n',
  602. 'r' => '\r',
  603. 's' => ' ',
  604. 't' => '\t',
  605. 'f' => '\x0C',
  606. 'u' => {
  607. let mut hex = ~"";
  608. hex.push_char(chars.next().unwrap());
  609. hex.push_char(chars.next().unwrap());
  610. hex.push_char(chars.next().unwrap());
  611. hex.push_char(chars.next().unwrap());
  612. u32::parse_bytes(hex.as_bytes(), 16)
  613. .and_then(char::from_u32).unwrap()
  614. }
  615. _ => fail!("Invalid test data input"),
  616. }
  617. } else {
  618. c
  619. }
  620. )
  621. }
  622. }
  623. }
  624. }