url.rs 13 KB

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