url.rs 18 KB

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