url.rs 15 KB

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