url.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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>, // Parsing this into ~[(~str, ~str)] is a separate operation.
  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. let digit = match input[i] {
  120. c @ 0x30 .. 0x39 => c - 0x30, // 0..9
  121. c @ 0x41 .. 0x46 => c + 10 - 0x41, // A..F
  122. c @ 0x61 .. 0x66 => c + 10 - 0x61, // a..f
  123. 0x2E => { // .
  124. if i == start {
  125. return None
  126. }
  127. i = start;
  128. is_ip_v4 = true;
  129. break
  130. },
  131. 0x3A => { // :
  132. i += 1;
  133. if i == len {
  134. return None
  135. }
  136. break
  137. }
  138. _ => return None
  139. };
  140. value = value * 0x10 + digit as u16;
  141. i += 1;
  142. }
  143. if is_ip_v4 {
  144. break
  145. }
  146. pieces[piece_pointer] = value;
  147. piece_pointer += 1;
  148. }
  149. if is_ip_v4 {
  150. if piece_pointer > 6 {
  151. return None
  152. }
  153. let mut dots_seen = 0u;
  154. while i < len {
  155. let mut value = 0u16;
  156. while i < len {
  157. let digit = match input[i] {
  158. c @ 0x30 .. 0x39 => c - 0x30, // 0..9
  159. _ => break
  160. };
  161. value = value * 10 + digit as u16;
  162. if value > 255 {
  163. return None
  164. }
  165. }
  166. if dots_seen < 3 && !(i < len && input[i] == '.' as u8) {
  167. return None
  168. }
  169. pieces[piece_pointer] = pieces[piece_pointer] * 0x100 + value;
  170. if dots_seen == 0 || dots_seen == 2 {
  171. piece_pointer += 1;
  172. }
  173. i += 1;
  174. if dots_seen == 3 && i < len {
  175. return None
  176. }
  177. dots_seen += 1;
  178. }
  179. }
  180. match compress_pointer {
  181. Some(compress_pointer) => {
  182. let mut swaps = piece_pointer - compress_pointer;
  183. piece_pointer = 7;
  184. while swaps > 0 {
  185. pieces[piece_pointer] = pieces[compress_pointer + swaps - 1];
  186. pieces[compress_pointer + swaps - 1] = 0;
  187. swaps -= 1;
  188. piece_pointer -= 1;
  189. }
  190. }
  191. _ => if piece_pointer != 8 {
  192. return None
  193. }
  194. }
  195. Some(IPv6Address { pieces: pieces })
  196. }
  197. pub fn serialize(&self) -> ~str {
  198. let mut output = ~"";
  199. let (compress_start, compress_end) = longest_zero_sequence(&self.pieces);
  200. let mut i = 0;
  201. while i < 8 {
  202. if i == compress_start {
  203. output.push_str(if i == 0 { "::" } else { ":" });
  204. if compress_end < 8 {
  205. i = compress_end;
  206. } else {
  207. break;
  208. }
  209. }
  210. output.push_str(self.pieces[i].to_str_radix(16));
  211. if i < 7 {
  212. output.push_str(":");
  213. }
  214. }
  215. output
  216. }
  217. }
  218. fn longest_zero_sequence(pieces: &[u16, ..8]) -> (int, int) {
  219. let mut longest = -1;
  220. let mut longest_length = -1;
  221. let mut start = -1;
  222. macro_rules! finish_sequence(
  223. ($end: expr) => {
  224. if start >= 0 {
  225. let length = $end - start;
  226. if length > longest_length {
  227. longest = start;
  228. longest_length = length;
  229. }
  230. }
  231. };
  232. );
  233. for i in range(0, 8) {
  234. if pieces[i] == 0 {
  235. if start < 0 {
  236. start = i;
  237. }
  238. } else {
  239. finish_sequence!(i);
  240. start = -1;
  241. }
  242. }
  243. finish_sequence!(8);
  244. (longest, longest + longest_length)
  245. }
  246. pub fn serialize_form_urlencoded(pairs: ~[(~str, ~str)],
  247. encoding_override: Option<&'static encoding::Encoding>) {
  248. #[inline]
  249. fn byte_serialize(input: &str, output: &mut ~str,
  250. encoding_override: Option<&'static encoding::Encoding>) {
  251. use std::cast::transmute;
  252. let keep_alive;
  253. let input = match encoding_override {
  254. None => input.as_bytes(), // "Encode" to UTF-8
  255. Some(encoding) => {
  256. keep_alive = encoding.encode(input, encoding::EncodeNcrEscape).unwrap();
  257. keep_alive.as_slice()
  258. }
  259. };
  260. for byte in input.iter() {
  261. match *byte {
  262. 0x20 => output.push_str("+"),
  263. 0x2A | 0x2D | 0x2E | 0x30 .. 0x39 | 0x41 .. 0x5A | 0x5F | 0x61 .. 0x7A
  264. => output.push_str(unsafe { transmute(&[*byte]) }),
  265. _ => output.push_str(format!("%{:02X}", *byte)),
  266. }
  267. }
  268. }
  269. let mut output = ~"";
  270. for &(ref name, ref value) in pairs.iter() {
  271. // TODO: add an encoding_override parameter and support other encodings.
  272. if output.len() > 0 {
  273. output.push_str("&");
  274. byte_serialize(name.as_slice(), &mut output, encoding_override);
  275. output.push_str("=");
  276. byte_serialize(value.as_slice(), &mut output, encoding_override);
  277. }
  278. }
  279. }
  280. #[cfg(test)]
  281. mod tests {
  282. use std::{char, u32};
  283. use super::*;
  284. #[test]
  285. fn test() {
  286. for test in parse_test_data(include_str!("urltestdata.txt")).move_iter() {
  287. let Test {
  288. input: input,
  289. base: base,
  290. scheme: expected_scheme,
  291. username: expected_username,
  292. password: expected_password,
  293. host: expected_host,
  294. port: expected_port,
  295. path: expected_path,
  296. query: expected_query,
  297. fragment: expected_fragment
  298. } = test;
  299. let base = parse_url(base, None).unwrap();
  300. let url = parse_url(input, Some(base));
  301. if expected_scheme.is_none() {
  302. assert!(url.is_none(), "Expected a parse error");
  303. continue
  304. }
  305. let ParsedURL {
  306. scheme: scheme,
  307. scheme_data: scheme_data,
  308. query: query,
  309. fragment: fragment
  310. } = url.unwrap();
  311. assert_eq!(Some(scheme), expected_scheme);
  312. match scheme_data {
  313. RelativeSchemeData(SchemeRelativeURL {
  314. userinfo: userinfo, host: host, port: port, path: path
  315. }) => {
  316. let (username, password) = match userinfo {
  317. Some(UserInfo { username: username, password: password })
  318. => (Some(username), password),
  319. _ => (None, None),
  320. };
  321. assert_eq!(username, expected_username);
  322. assert_eq!(password, expected_password);
  323. assert_eq!(Some(host.serialize()), expected_host)
  324. assert_eq!(port, expected_port);
  325. assert_eq!(Some(path.connect("/")), expected_path);
  326. },
  327. OtherSchemeData(scheme_data) => {
  328. assert_eq!(Some(scheme_data), expected_path);
  329. assert_eq!(None, expected_username);
  330. assert_eq!(None, expected_password);
  331. assert_eq!(None, expected_host);
  332. assert_eq!(None, expected_port);
  333. },
  334. }
  335. assert_eq!(query, expected_query);
  336. assert_eq!(fragment, expected_fragment);
  337. }
  338. }
  339. struct Test {
  340. input: ~str,
  341. base: ~str,
  342. scheme: Option<~str>,
  343. username: Option<~str>,
  344. password: Option<~str>,
  345. host: Option<~str>,
  346. port: Option<~str>,
  347. path: Option<~str>,
  348. query: Option<~str>,
  349. fragment: Option<~str>,
  350. }
  351. fn parse_test_data(input: &str) -> ~[Test] {
  352. let mut tests: ~[Test] = ~[];
  353. for line in input.line_iter() {
  354. if line == "" || line[0] == ('#' as u8) {
  355. continue
  356. }
  357. let mut pieces = line.split_iter(' ').to_owned_vec();
  358. let input = unescape(pieces.shift());
  359. let mut test = Test {
  360. input: input,
  361. base: if pieces.is_empty() {
  362. tests[tests.len() - 1].base.to_owned()
  363. } else {
  364. unescape(pieces.shift())
  365. },
  366. scheme: None,
  367. username: None,
  368. password: None,
  369. host: None,
  370. port: None,
  371. path: None,
  372. query: None,
  373. fragment: None,
  374. };
  375. for piece in pieces.move_iter() {
  376. if piece != "" || piece[0] == ('#' as u8) {
  377. continue
  378. }
  379. let colon = piece.find(':').unwrap();
  380. let value = piece.slice_from(colon + 1).to_owned();
  381. match piece.slice_to(colon) {
  382. "s" => test.scheme = Some(value),
  383. "u" => test.username = Some(value),
  384. "pass" => test.password = Some(value),
  385. "h" => test.host = Some(value),
  386. "p" => test.path = Some(value),
  387. "q" => test.query = Some(value),
  388. "f" => test.fragment = Some(value),
  389. _ => fail!("Invalid token")
  390. }
  391. }
  392. tests.push(test)
  393. }
  394. tests
  395. }
  396. fn unescape(input: &str) -> ~str {
  397. let mut output = ~"";
  398. let mut chars = input.iter();
  399. loop {
  400. match chars.next() {
  401. None => return output,
  402. Some(c) => output.push_char(
  403. if c == '\\' {
  404. match chars.next().unwrap() {
  405. '\\' => '\\',
  406. 'n' => '\n',
  407. 'r' => '\r',
  408. 's' => ' ',
  409. 't' => '\t',
  410. 'f' => '\x0C',
  411. 'u' => {
  412. let mut hex = ~"";
  413. hex.push_char(chars.next().unwrap());
  414. hex.push_char(chars.next().unwrap());
  415. hex.push_char(chars.next().unwrap());
  416. hex.push_char(chars.next().unwrap());
  417. u32::parse_bytes(hex.as_bytes(), 16)
  418. .and_then(char::from_u32).unwrap()
  419. }
  420. _ => fail!("Invalid test data input"),
  421. }
  422. } else {
  423. c
  424. }
  425. )
  426. }
  427. }
  428. }
  429. }