url.rs 21 KB

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