url.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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(macro_rules)];
  11. extern mod encoding;
  12. #[cfg(test)]
  13. extern mod extra;
  14. use std::ascii::Ascii;
  15. use encoding::EncodingRef;
  16. use encoding::Encoding;
  17. use encoding::all::UTF_8;
  18. use encoding::label::encoding_from_whatwg_label;
  19. pub mod punycode;
  20. #[cfg(test)]
  21. mod tests;
  22. pub struct URL {
  23. scheme: ~[Ascii],
  24. scheme_data: SchemeData,
  25. query: Option<~[Ascii]>, // parse_form_urlencoded() parses this into ~[(~str, ~str)]
  26. fragment: Option<~[Ascii]>,
  27. }
  28. pub enum SchemeData {
  29. RelativeSchemeData(SchemeRelativeURL),
  30. OtherSchemeData(~[Ascii])
  31. }
  32. pub struct SchemeRelativeURL {
  33. userinfo: Option<UserInfo>,
  34. host: Host,
  35. port: ~[Ascii],
  36. path: ~[~[Ascii]],
  37. }
  38. pub struct UserInfo {
  39. username: ~[Ascii],
  40. password: Option<~[Ascii]>,
  41. }
  42. pub enum Host {
  43. Domain(~[~[Ascii]]),
  44. IPv6(IPv6Address)
  45. }
  46. pub struct IPv6Address {
  47. pieces: [u16, ..8]
  48. }
  49. pub type ParseResult<T> = Result<T, &'static str>;
  50. impl URL {
  51. pub fn parse(input: &str, base_url: Option<URL>) -> Option<URL> {
  52. let _ = input;
  53. let _ = base_url;
  54. // TODO
  55. None
  56. }
  57. pub fn serialize(&self) -> ~[Ascii] {
  58. let mut result = self.serialize_no_fragment();
  59. match self.fragment {
  60. None => (),
  61. Some(ref fragment) => {
  62. result.push('#'.to_ascii());
  63. result.push_all(fragment.as_slice());
  64. }
  65. }
  66. result
  67. }
  68. pub fn serialize_no_fragment(&self) -> ~[Ascii] {
  69. let mut result = self.scheme.to_owned();
  70. result.push(':'.to_ascii());
  71. match self.scheme_data {
  72. RelativeSchemeData(SchemeRelativeURL {
  73. userinfo: ref userinfo, host: ref host, port: ref port, path: ref path
  74. }) => {
  75. result.push_all("//".to_ascii());
  76. match userinfo {
  77. &None => (),
  78. &Some(UserInfo { username: ref username, password: ref password })
  79. => if username.len() > 0 || password.is_some() {
  80. result.push_all(username.as_slice());
  81. match password {
  82. &None => (),
  83. &Some(ref password) => {
  84. result.push(':'.to_ascii());
  85. result.push_all(password.as_slice());
  86. }
  87. }
  88. result.push('@'.to_ascii());
  89. }
  90. }
  91. result.push_all(host.serialize());
  92. if port.len() > 0 {
  93. result.push(':'.to_ascii());
  94. result.push_all(port.as_slice());
  95. }
  96. if path.len() > 0 {
  97. for path_part in path.iter() {
  98. result.push('/'.to_ascii());
  99. result.push_all(path_part.as_slice());
  100. }
  101. } else {
  102. result.push('/'.to_ascii());
  103. }
  104. },
  105. OtherSchemeData(ref data) => result.push_all(data.as_slice()),
  106. }
  107. match self.query {
  108. None => (),
  109. Some(ref query) => {
  110. result.push('?'.to_ascii());
  111. result.push_all(query.as_slice());
  112. }
  113. }
  114. result
  115. }
  116. }
  117. impl Host {
  118. pub fn parse(input: &str) -> ParseResult<Host> {
  119. if input.len() == 0 {
  120. Err("Empty host")
  121. } else if input[0] == '[' as u8 {
  122. if input[input.len()] == ']' as u8 {
  123. match IPv6Address::parse(input.slice(1, input.len() - 1)) {
  124. Some(address) => Ok(IPv6(address)),
  125. None => Err("Invalid IPv6 address"),
  126. }
  127. } else {
  128. Err("Invalid IPv6 address")
  129. }
  130. } else {
  131. let mut percent_encoded = ~[];
  132. utf8_percent_encode(input, SimpleEncodeSet, &mut percent_encoded);
  133. let bytes = percent_decode(percent_encoded);
  134. let decoded = UTF_8.decode(bytes, encoding::DecodeReplace).unwrap();
  135. let mut labels = ~[];
  136. for label in decoded.split_iter(&['.', '\u3002', '\uFF0E', '\uFF61']) {
  137. // TODO: Remove this check and use IDNA "domain to ASCII"
  138. // TODO: switch to .map(domain_label_to_ascii).collect() then.
  139. if label.is_ascii() {
  140. labels.push(unsafe { label.to_ascii_nocheck() }.to_owned())
  141. } else {
  142. return Err("Non-ASCII domains (IDNA) are not supported yet.")
  143. }
  144. }
  145. Ok(Domain(labels))
  146. }
  147. }
  148. pub fn serialize(&self) -> ~[Ascii] {
  149. match *self {
  150. Domain(ref labels) => labels.connect_vec(&'.'.to_ascii()),
  151. IPv6(ref address) => {
  152. let mut result = ~['['.to_ascii()];
  153. result.push_all(address.serialize());
  154. result.push(']'.to_ascii());
  155. result
  156. }
  157. }
  158. }
  159. }
  160. macro_rules! matches(
  161. ($value: expr, ($pattern: pat)|+) => {
  162. match $value {
  163. $($pattern)|+ => true,
  164. _ => false,
  165. }
  166. };
  167. )
  168. impl IPv6Address {
  169. pub fn parse(input: &str) -> Option<IPv6Address> {
  170. let len = input.len();
  171. let mut is_ip_v4 = false;
  172. let mut pieces = [0, 0, 0, 0, 0, 0, 0, 0];
  173. let mut piece_pointer = 0u;
  174. let mut compress_pointer = None;
  175. let mut i = 0u;
  176. if input[0] == ':' as u8 {
  177. if input[1] != ':' as u8 {
  178. return None
  179. }
  180. i = 2;
  181. piece_pointer = 1;
  182. compress_pointer = Some(1u);
  183. }
  184. while i < len {
  185. if piece_pointer == 8 {
  186. return None
  187. }
  188. if input[i] == ':' as u8 {
  189. if compress_pointer.is_some() {
  190. return None
  191. }
  192. piece_pointer += 1;
  193. compress_pointer = Some(piece_pointer);
  194. continue
  195. }
  196. let start = i;
  197. let end = len.min(&(start + 4));
  198. let mut value = 0u16;
  199. while i < end {
  200. match from_hex(input[i]) {
  201. Some(digit) => {
  202. value = value * 0x10 + digit as u16;
  203. i += 1;
  204. },
  205. None => {
  206. if input[i] == 0x2E { // .
  207. if i == start {
  208. return None
  209. }
  210. i = start;
  211. is_ip_v4 = true;
  212. break
  213. }
  214. if input[i] == 0x3A { // :
  215. i += 1;
  216. if i == len {
  217. return None
  218. }
  219. break
  220. }
  221. return None
  222. }
  223. }
  224. }
  225. if is_ip_v4 {
  226. break
  227. }
  228. pieces[piece_pointer] = value;
  229. piece_pointer += 1;
  230. }
  231. if is_ip_v4 {
  232. if piece_pointer > 6 {
  233. return None
  234. }
  235. let mut dots_seen = 0u;
  236. while i < len {
  237. let mut value = 0u16;
  238. while i < len {
  239. let digit = match input[i] {
  240. c @ 0x30 .. 0x39 => c - 0x30, // 0..9
  241. _ => break
  242. };
  243. value = value * 10 + digit as u16;
  244. if value > 255 {
  245. return None
  246. }
  247. }
  248. if dots_seen < 3 && !(i < len && input[i] == '.' as u8) {
  249. return None
  250. }
  251. pieces[piece_pointer] = pieces[piece_pointer] * 0x100 + value;
  252. if dots_seen == 0 || dots_seen == 2 {
  253. piece_pointer += 1;
  254. }
  255. i += 1;
  256. if dots_seen == 3 && i < len {
  257. return None
  258. }
  259. dots_seen += 1;
  260. }
  261. }
  262. match compress_pointer {
  263. Some(compress_pointer) => {
  264. let mut swaps = piece_pointer - compress_pointer;
  265. piece_pointer = 7;
  266. while swaps > 0 {
  267. pieces[piece_pointer] = pieces[compress_pointer + swaps - 1];
  268. pieces[compress_pointer + swaps - 1] = 0;
  269. swaps -= 1;
  270. piece_pointer -= 1;
  271. }
  272. }
  273. _ => if piece_pointer != 8 {
  274. return None
  275. }
  276. }
  277. Some(IPv6Address { pieces: pieces })
  278. }
  279. pub fn serialize(&self) -> ~[Ascii] {
  280. let mut output = ~[];
  281. let (compress_start, compress_end) = longest_zero_sequence(&self.pieces);
  282. let mut i = 0;
  283. while i < 8 {
  284. if i == compress_start {
  285. output.push(':'.to_ascii());
  286. if i == 0 {
  287. output.push(':'.to_ascii());
  288. }
  289. if compress_end < 8 {
  290. i = compress_end;
  291. } else {
  292. break;
  293. }
  294. }
  295. let hex = self.pieces[i].to_str_radix(16);
  296. // No need to check that hex digits are ASCII
  297. output.push_all(unsafe { hex.to_ascii_nocheck() });
  298. if i < 7 {
  299. output.push(':'.to_ascii());
  300. }
  301. }
  302. output
  303. }
  304. }
  305. fn longest_zero_sequence(pieces: &[u16, ..8]) -> (int, int) {
  306. let mut longest = -1;
  307. let mut longest_length = -1;
  308. let mut start = -1;
  309. macro_rules! finish_sequence(
  310. ($end: expr) => {
  311. if start >= 0 {
  312. let length = $end - start;
  313. if length > longest_length {
  314. longest = start;
  315. longest_length = length;
  316. }
  317. }
  318. };
  319. );
  320. for i in range(0, 8) {
  321. if pieces[i] == 0 {
  322. if start < 0 {
  323. start = i;
  324. }
  325. } else {
  326. finish_sequence!(i);
  327. start = -1;
  328. }
  329. }
  330. finish_sequence!(8);
  331. (longest, longest + longest_length)
  332. }
  333. #[inline]
  334. fn from_hex(byte: u8) -> Option<u8> {
  335. match byte {
  336. 0x30 .. 0x39 => Some(byte - 0x30), // 0..9
  337. 0x41 .. 0x46 => Some(byte + 10 - 0x41), // A..F
  338. 0x61 .. 0x66 => Some(byte + 10 - 0x61), // a..f
  339. _ => None
  340. }
  341. }
  342. #[inline]
  343. fn to_hex_upper(value: u8) -> Ascii {
  344. let digit = match value {
  345. 0 .. 9 => value + 0x30,
  346. 10 .. 15 => value - 10 + 0x41,
  347. _ => fail!()
  348. };
  349. unsafe { digit.to_ascii_nocheck() }
  350. }
  351. enum EncodeSet {
  352. SimpleEncodeSet,
  353. DefaultEncodeSet,
  354. PasswordEncodeSet,
  355. UsernameEncodeSet
  356. }
  357. #[inline]
  358. fn utf8_percent_encode(input: &str, encode_set: EncodeSet, output: &mut ~[Ascii]) {
  359. use Default = self::DefaultEncodeSet;
  360. use Password = self::PasswordEncodeSet;
  361. use Username = self::UsernameEncodeSet;
  362. for &byte in input.as_bytes().iter() {
  363. if byte < 0x20 || byte > 0x7E || match byte as char {
  364. ' ' | '"' | '#' | '<' | '>' | '?' | '`'
  365. => match encode_set { Default | Password | Username => true, _ => false },
  366. '/' | '@' | '\\'
  367. => match encode_set { Password | Username => true, _ => false },
  368. ':'
  369. => match encode_set { Username => true, _ => false },
  370. _ => false,
  371. } {
  372. percent_encode_byte(byte, output)
  373. } else {
  374. output.push(unsafe { byte.to_ascii_nocheck() }) // Already checked
  375. }
  376. }
  377. }
  378. #[inline]
  379. fn percent_encode_byte(byte: u8, output: &mut ~[Ascii]) {
  380. output.push_all(['%'.to_ascii(), to_hex_upper(byte >> 4), to_hex_upper(byte & 0x0F)])
  381. }
  382. #[inline]
  383. fn percent_decode(input: &[Ascii]) -> ~[u8] {
  384. let mut output = ~[];
  385. let mut i = 0u;
  386. while i < input.len() {
  387. let c = input[i];
  388. if c == '%'.to_ascii() && i + 2 < input.len() {
  389. match (from_hex(input[i + 1].to_byte()),
  390. from_hex(input[i + 2].to_byte())) {
  391. (Some(h), Some(l)) => {
  392. output.push(h * 0x10 + l);
  393. i += 3;
  394. continue
  395. },
  396. _ => (),
  397. }
  398. }
  399. output.push(c.to_byte());
  400. i += 1;
  401. }
  402. output
  403. }
  404. pub fn parse_form_urlencoded(input: &[Ascii],
  405. encoding_override: Option<EncodingRef>,
  406. use_charset: bool,
  407. mut isindex: bool)
  408. -> ~[(~str, ~str)] {
  409. let mut encoding_override = encoding_override.unwrap_or(UTF_8 as EncodingRef);
  410. let mut pairs = ~[];
  411. for string in input.split_iter(|&c| c == '&'.to_ascii()) {
  412. if string.len() > 0 {
  413. let (name, value) = match string.position_elem(&'='.to_ascii()) {
  414. Some(position) => (string.slice_to(position), string.slice_from(position + 1)),
  415. None => if isindex { (&[], string) } else { (string, &[]) }
  416. };
  417. let name = name.to_str_ascii().replace("+", " ");
  418. let value = value.to_str_ascii().replace("+", " ");
  419. if use_charset && name.as_slice() == "_charset_" {
  420. match encoding_from_whatwg_label(value) {
  421. Some(encoding) => encoding_override = encoding,
  422. None => (),
  423. }
  424. }
  425. pairs.push((name, value));
  426. }
  427. isindex = false;
  428. }
  429. #[inline]
  430. fn decode(input: &~str, encoding_override: EncodingRef) -> ~str {
  431. // No need to check as input comes from &[Ascii].to_str_ascii().replace("+", " ")
  432. let bytes = percent_decode(unsafe { input.as_slice().to_ascii_nocheck() });
  433. encoding_override.decode(bytes, encoding::DecodeReplace).unwrap()
  434. }
  435. for pair in pairs.mut_iter() {
  436. let new_pair = {
  437. let &(ref name, ref value) = pair;
  438. (decode(name, encoding_override), decode(value, encoding_override))
  439. };
  440. *pair = new_pair;
  441. }
  442. pairs
  443. }
  444. pub fn serialize_form_urlencoded(pairs: ~[(~str, ~str)],
  445. encoding_override: Option<EncodingRef>)
  446. -> ~[Ascii] {
  447. #[inline]
  448. fn byte_serialize(input: &str, output: &mut ~[Ascii],
  449. encoding_override: Option<EncodingRef>) {
  450. let keep_alive;
  451. let input = match encoding_override {
  452. None => input.as_bytes(), // "Encode" to UTF-8
  453. Some(encoding) => {
  454. keep_alive = encoding.encode(input, encoding::EncodeNcrEscape).unwrap();
  455. keep_alive.as_slice()
  456. }
  457. };
  458. for byte in input.iter() {
  459. match *byte {
  460. 0x20 => output.push('+'.to_ascii()),
  461. 0x2A | 0x2D | 0x2E | 0x30 .. 0x39 | 0x41 .. 0x5A | 0x5F | 0x61 .. 0x7A
  462. => output.push(unsafe { byte.to_ascii_nocheck() }),
  463. _ => percent_encode_byte(*byte, output),
  464. }
  465. }
  466. }
  467. let mut output = ~[];
  468. for &(ref name, ref value) in pairs.iter() {
  469. if output.len() > 0 {
  470. output.push('&'.to_ascii());
  471. byte_serialize(name.as_slice(), &mut output, encoding_override);
  472. output.push('='.to_ascii());
  473. byte_serialize(value.as_slice(), &mut output, encoding_override);
  474. }
  475. }
  476. output
  477. }