url.rs 16 KB

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