host.rs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. use std::ascii::OwnedAsciiExt;
  9. use std::cmp;
  10. use std::fmt::{mod, Formatter, Show};
  11. use parser::{ParseResult, ParseError};
  12. use percent_encoding::{from_hex, percent_decode};
  13. /// The host name of an URL.
  14. #[deriving(PartialEq, Eq, Clone)]
  15. pub enum Host {
  16. /// A (DNS) domain name or an IPv4 address.
  17. ///
  18. /// FIXME: IPv4 probably should be a separate variant.
  19. /// See https://www.w3.org/Bugs/Public/show_bug.cgi?id=26431
  20. Domain(String),
  21. /// An IPv6 address, represented inside `[...]` square brackets
  22. /// so that `:` colon characters in the address are not ambiguous
  23. /// with the port number delimiter.
  24. Ipv6(Ipv6Address),
  25. }
  26. /// A 128 bit IPv6 address
  27. #[deriving(Clone, Eq, PartialEq, Copy)]
  28. pub struct Ipv6Address {
  29. pub pieces: [u16, ..8]
  30. }
  31. impl Host {
  32. /// Parse a host: either an IPv6 address in [] square brackets, or a domain.
  33. ///
  34. /// Returns `Err` for an empty host, an invalid IPv6 address,
  35. /// or a or invalid non-ASCII domain.
  36. ///
  37. /// FIXME: Add IDNA support for non-ASCII domains.
  38. pub fn parse(input: &str) -> ParseResult<Host> {
  39. if input.len() == 0 {
  40. Err(ParseError::EmptyHost)
  41. } else if input.starts_with("[") {
  42. if input.ends_with("]") {
  43. Ipv6Address::parse(input.slice(1, input.len() - 1)).map(Host::Ipv6)
  44. } else {
  45. Err(ParseError::InvalidIpv6Address)
  46. }
  47. } else {
  48. let decoded = percent_decode(input.as_bytes());
  49. let domain = String::from_utf8_lossy(decoded.as_slice());
  50. // TODO: Remove this check and use IDNA "domain to ASCII"
  51. if !domain.as_slice().is_ascii() {
  52. Err(ParseError::NonAsciiDomainsNotSupportedYet)
  53. } else if domain.as_slice().find([
  54. '\0', '\t', '\n', '\r', ' ', '#', '%', '/', ':', '?', '@', '[', '\\', ']'
  55. ].as_slice()).is_some() {
  56. Err(ParseError::InvalidDomainCharacter)
  57. } else {
  58. Ok(Host::Domain(domain.into_string().into_ascii_lower()))
  59. }
  60. }
  61. }
  62. /// Serialize the host as a string.
  63. ///
  64. /// A domain a returned as-is, an IPv6 address between [] square brackets.
  65. pub fn serialize(&self) -> String {
  66. self.to_string()
  67. }
  68. }
  69. impl Show for Host {
  70. fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
  71. match *self {
  72. Host::Domain(ref domain) => domain.fmt(formatter),
  73. Host::Ipv6(ref address) => {
  74. try!(formatter.write(b"["));
  75. try!(address.fmt(formatter));
  76. formatter.write(b"]")
  77. }
  78. }
  79. }
  80. }
  81. impl Ipv6Address {
  82. /// Parse an IPv6 address, without the [] square brackets.
  83. pub fn parse(input: &str) -> ParseResult<Ipv6Address> {
  84. let input = input.as_bytes();
  85. let len = input.len();
  86. let mut is_ip_v4 = false;
  87. let mut pieces = [0, 0, 0, 0, 0, 0, 0, 0];
  88. let mut piece_pointer = 0u;
  89. let mut compress_pointer = None;
  90. let mut i = 0u;
  91. if input[0] == b':' {
  92. if input[1] != b':' {
  93. return Err(ParseError::InvalidIpv6Address)
  94. }
  95. i = 2;
  96. piece_pointer = 1;
  97. compress_pointer = Some(1u);
  98. }
  99. while i < len {
  100. if piece_pointer == 8 {
  101. return Err(ParseError::InvalidIpv6Address)
  102. }
  103. if input[i] == b':' {
  104. if compress_pointer.is_some() {
  105. return Err(ParseError::InvalidIpv6Address)
  106. }
  107. i += 1;
  108. piece_pointer += 1;
  109. compress_pointer = Some(piece_pointer);
  110. continue
  111. }
  112. let start = i;
  113. let end = cmp::min(len, start + 4);
  114. let mut value = 0u16;
  115. while i < end {
  116. match from_hex(input[i]) {
  117. Some(digit) => {
  118. value = value * 0x10 + digit as u16;
  119. i += 1;
  120. },
  121. None => break
  122. }
  123. }
  124. if i < len {
  125. match input[i] {
  126. b'.' => {
  127. if i == start {
  128. return Err(ParseError::InvalidIpv6Address)
  129. }
  130. i = start;
  131. is_ip_v4 = true;
  132. },
  133. b':' => {
  134. i += 1;
  135. if i == len {
  136. return Err(ParseError::InvalidIpv6Address)
  137. }
  138. },
  139. _ => return Err(ParseError::InvalidIpv6Address)
  140. }
  141. }
  142. if is_ip_v4 {
  143. break
  144. }
  145. pieces[piece_pointer] = value;
  146. piece_pointer += 1;
  147. }
  148. if is_ip_v4 {
  149. if piece_pointer > 6 {
  150. return Err(ParseError::InvalidIpv6Address)
  151. }
  152. let mut dots_seen = 0u;
  153. while i < len {
  154. // FIXME: https://github.com/whatwg/url/commit/1c22aa119c354e0020117e02571cec53f7c01064
  155. let mut value = 0u16;
  156. while i < len {
  157. let digit = match input[i] {
  158. c @ b'0' ... b'9' => c - b'0',
  159. _ => break
  160. };
  161. value = value * 10 + digit as u16;
  162. if value == 0 || value > 255 {
  163. return Err(ParseError::InvalidIpv6Address)
  164. }
  165. }
  166. if dots_seen < 3 && !(i < len && input[i] == b'.') {
  167. return Err(ParseError::InvalidIpv6Address)
  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 Err(ParseError::InvalidIpv6Address)
  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 Err(ParseError::InvalidIpv6Address)
  193. }
  194. }
  195. Ok(Ipv6Address { pieces: pieces })
  196. }
  197. /// Serialize the IPv6 address to a string.
  198. pub fn serialize(&self) -> String {
  199. self.to_string()
  200. }
  201. }
  202. impl Show for Ipv6Address {
  203. fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
  204. let (compress_start, compress_end) = longest_zero_sequence(&self.pieces);
  205. let mut i = 0;
  206. while i < 8 {
  207. if i == compress_start {
  208. try!(formatter.write(b":"));
  209. if i == 0 {
  210. try!(formatter.write(b":"));
  211. }
  212. if compress_end < 8 {
  213. i = compress_end;
  214. } else {
  215. break;
  216. }
  217. }
  218. try!(write!(formatter, "{:x}", self.pieces[i as uint]));
  219. if i < 7 {
  220. try!(formatter.write(b":"));
  221. }
  222. i += 1;
  223. }
  224. Ok(())
  225. }
  226. }
  227. fn longest_zero_sequence(pieces: &[u16, ..8]) -> (int, int) {
  228. let mut longest = -1;
  229. let mut longest_length = -1;
  230. let mut start = -1;
  231. macro_rules! finish_sequence(
  232. ($end: expr) => {
  233. if start >= 0 {
  234. let length = $end - start;
  235. if length > longest_length {
  236. longest = start;
  237. longest_length = length;
  238. }
  239. }
  240. };
  241. );
  242. for i in range(0, 8) {
  243. if pieces[i as uint] == 0 {
  244. if start < 0 {
  245. start = i;
  246. }
  247. } else {
  248. finish_sequence!(i);
  249. start = -1;
  250. }
  251. }
  252. finish_sequence!(8);
  253. (longest, longest + longest_length)
  254. }