url.rs 21 KB

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