url.rs 17 KB

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