url.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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 = match encoding_override {
  407. Some(encoding) => encoding,
  408. None => UTF_8 as &'static Encoding,
  409. };
  410. let mut pairs = ~[];
  411. for string in input.split_iter(|&c| c == '&'.to_ascii()) {
  412. if string.len() > 0 {
  413. let (name, value) = match string.position_elem(&'='.to_ascii()) {
  414. Some(position) => (string.slice_to(position), string.slice_from(position + 1)),
  415. None => if isindex { (&[], string) } else { (string, &[]) }
  416. };
  417. let name = name.to_str_ascii().replace("+", " ");
  418. let value = value.to_str_ascii().replace("+", " ");
  419. if use_charset && name.as_slice() == "_charset_" {
  420. match encoding_from_whatwg_label(value) {
  421. Some(encoding) => encoding_override = encoding,
  422. None => (),
  423. }
  424. }
  425. pairs.push((name, value));
  426. }
  427. isindex = false;
  428. }
  429. #[inline]
  430. fn decode(input: &~str, encoding_override: &'static Encoding) -> ~str {
  431. // No need to check as input comes from &[Ascii].to_str_ascii().replace("+", " ")
  432. let bytes = percent_decode(unsafe { input.as_slice().to_ascii_nocheck() });
  433. encoding_override.decode(bytes, encoding::DecodeReplace).unwrap()
  434. }
  435. for pair in pairs.mut_iter() {
  436. let new_pair = {
  437. let &(ref name, ref value) = pair;
  438. (decode(name, encoding_override), decode(value, encoding_override))
  439. };
  440. *pair = new_pair;
  441. }
  442. pairs
  443. }
  444. pub fn serialize_form_urlencoded(pairs: ~[(~str, ~str)],
  445. encoding_override: Option<&'static Encoding>)
  446. -> ~[Ascii] {
  447. #[inline]
  448. fn byte_serialize(input: &str, output: &mut ~[Ascii],
  449. encoding_override: Option<&'static Encoding>) {
  450. let keep_alive;
  451. let input = match encoding_override {
  452. None => input.as_bytes(), // "Encode" to UTF-8
  453. Some(encoding) => {
  454. keep_alive = encoding.encode(input, encoding::EncodeNcrEscape).unwrap();
  455. keep_alive.as_slice()
  456. }
  457. };
  458. for byte in input.iter() {
  459. match *byte {
  460. 0x20 => output.push('+'.to_ascii()),
  461. 0x2A | 0x2D | 0x2E | 0x30 .. 0x39 | 0x41 .. 0x5A | 0x5F | 0x61 .. 0x7A
  462. => output.push(unsafe { byte.to_ascii_nocheck() }),
  463. _ => percent_encode_byte(*byte, output),
  464. }
  465. }
  466. }
  467. let mut output = ~[];
  468. for &(ref name, ref value) in pairs.iter() {
  469. // TODO: add an encoding_override parameter and support other encodings.
  470. if output.len() > 0 {
  471. output.push('&'.to_ascii());
  472. byte_serialize(name.as_slice(), &mut output, encoding_override);
  473. output.push('='.to_ascii());
  474. byte_serialize(value.as_slice(), &mut output, encoding_override);
  475. }
  476. }
  477. output
  478. }
  479. #[cfg(test)]
  480. mod tests {
  481. use std::{char, u32};
  482. use super::*;
  483. #[test]
  484. fn test_url_parsing() {
  485. for test in parse_test_data(include_str!("urltestdata.txt")).move_iter() {
  486. let Test {
  487. input: input,
  488. base: base,
  489. scheme: expected_scheme,
  490. username: expected_username,
  491. password: expected_password,
  492. host: expected_host,
  493. port: expected_port,
  494. path: expected_path,
  495. query: expected_query,
  496. fragment: expected_fragment
  497. } = test;
  498. let base = URL::parse(base, None).unwrap();
  499. let url = URL::parse(input, Some(base));
  500. if expected_scheme.is_none() {
  501. assert!(url.is_none(), "Expected a parse error");
  502. continue
  503. }
  504. let URL {
  505. scheme: scheme,
  506. scheme_data: scheme_data,
  507. query: query,
  508. fragment: fragment
  509. } = url.unwrap();
  510. assert_eq!(Some(scheme.to_str_ascii()), expected_scheme);
  511. match scheme_data {
  512. RelativeSchemeData(SchemeRelativeURL {
  513. userinfo: userinfo, host: host, port: port, path: path
  514. }) => {
  515. let (username, password) = match userinfo {
  516. Some(UserInfo { username: username, password: password })
  517. => (Some(username.to_str_ascii()), password.map(|p| p.to_str_ascii())),
  518. _ => (None, None),
  519. };
  520. assert_eq!(username, expected_username);
  521. assert_eq!(password, expected_password);
  522. assert_eq!(Some(host.serialize().to_str_ascii()), expected_host)
  523. assert_eq!(Some(port.to_str_ascii()), expected_port);
  524. assert_eq!(Some(path.map(|p| p.to_str_ascii()).connect("/")), expected_path);
  525. },
  526. OtherSchemeData(scheme_data) => {
  527. assert_eq!(Some(scheme_data.to_str_ascii()), expected_path);
  528. assert_eq!(None, expected_username);
  529. assert_eq!(None, expected_password);
  530. assert_eq!(None, expected_host);
  531. assert_eq!(None, expected_port);
  532. },
  533. }
  534. assert_eq!(query.map(|p| p.to_str_ascii()), expected_query);
  535. assert_eq!(fragment.map(|p| p.to_str_ascii()), expected_fragment);
  536. }
  537. }
  538. struct Test {
  539. input: ~str,
  540. base: ~str,
  541. scheme: Option<~str>,
  542. username: Option<~str>,
  543. password: Option<~str>,
  544. host: Option<~str>,
  545. port: Option<~str>,
  546. path: Option<~str>,
  547. query: Option<~str>,
  548. fragment: Option<~str>,
  549. }
  550. fn parse_test_data(input: &str) -> ~[Test] {
  551. let mut tests: ~[Test] = ~[];
  552. for line in input.line_iter() {
  553. if line == "" || line[0] == ('#' as u8) {
  554. continue
  555. }
  556. let mut pieces = line.split_iter(' ').to_owned_vec();
  557. let input = unescape(pieces.shift());
  558. let mut test = Test {
  559. input: input,
  560. base: if pieces.is_empty() {
  561. tests[tests.len() - 1].base.to_owned()
  562. } else {
  563. unescape(pieces.shift())
  564. },
  565. scheme: None,
  566. username: None,
  567. password: None,
  568. host: None,
  569. port: None,
  570. path: None,
  571. query: None,
  572. fragment: None,
  573. };
  574. for piece in pieces.move_iter() {
  575. if piece != "" || piece[0] == ('#' as u8) {
  576. continue
  577. }
  578. let colon = piece.find(':').unwrap();
  579. let value = piece.slice_from(colon + 1).to_owned();
  580. match piece.slice_to(colon) {
  581. "s" => test.scheme = Some(value),
  582. "u" => test.username = Some(value),
  583. "pass" => test.password = Some(value),
  584. "h" => test.host = Some(value),
  585. "p" => test.path = Some(value),
  586. "q" => test.query = Some(value),
  587. "f" => test.fragment = Some(value),
  588. _ => fail!("Invalid token")
  589. }
  590. }
  591. tests.push(test)
  592. }
  593. tests
  594. }
  595. fn unescape(input: &str) -> ~str {
  596. let mut output = ~"";
  597. let mut chars = input.iter();
  598. loop {
  599. match chars.next() {
  600. None => return output,
  601. Some(c) => output.push_char(
  602. if c == '\\' {
  603. match chars.next().unwrap() {
  604. '\\' => '\\',
  605. 'n' => '\n',
  606. 'r' => '\r',
  607. 's' => ' ',
  608. 't' => '\t',
  609. 'f' => '\x0C',
  610. 'u' => {
  611. let mut hex = ~"";
  612. hex.push_char(chars.next().unwrap());
  613. hex.push_char(chars.next().unwrap());
  614. hex.push_char(chars.next().unwrap());
  615. hex.push_char(chars.next().unwrap());
  616. u32::parse_bytes(hex.as_bytes(), 16)
  617. .and_then(char::from_u32).unwrap()
  618. }
  619. _ => fail!("Invalid test data input"),
  620. }
  621. } else {
  622. c
  623. }
  624. )
  625. }
  626. }
  627. }
  628. }