url.rs 21 KB

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