host.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. // Copyright 2013-2016 The rust-url developers.
  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 crate::net::{Ipv4Addr, Ipv6Addr};
  9. use alloc::borrow::Cow;
  10. use alloc::borrow::ToOwned;
  11. use alloc::string::String;
  12. use alloc::string::ToString;
  13. use alloc::vec::Vec;
  14. use core::cmp;
  15. use core::fmt::{self, Formatter};
  16. use percent_encoding::{percent_decode, utf8_percent_encode, CONTROLS};
  17. #[cfg(feature = "serde")]
  18. use serde::{Deserialize, Serialize};
  19. use crate::parser::{ParseError, ParseResult};
  20. #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
  21. #[derive(Copy, Clone, Debug, Eq, PartialEq)]
  22. pub(crate) enum HostInternal {
  23. None,
  24. Domain,
  25. Ipv4(Ipv4Addr),
  26. Ipv6(Ipv6Addr),
  27. }
  28. impl From<Host<String>> for HostInternal {
  29. fn from(host: Host<String>) -> HostInternal {
  30. match host {
  31. Host::Domain(ref s) if s.is_empty() => HostInternal::None,
  32. Host::Domain(_) => HostInternal::Domain,
  33. Host::Ipv4(address) => HostInternal::Ipv4(address),
  34. Host::Ipv6(address) => HostInternal::Ipv6(address),
  35. }
  36. }
  37. }
  38. /// The host name of an URL.
  39. #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
  40. #[derive(Clone, Debug, Eq, Ord, PartialOrd, Hash)]
  41. pub enum Host<S = String> {
  42. /// A DNS domain name, as '.' dot-separated labels.
  43. /// Non-ASCII labels are encoded in punycode per IDNA if this is the host of
  44. /// a special URL, or percent encoded for non-special URLs. Hosts for
  45. /// non-special URLs are also called opaque hosts.
  46. Domain(S),
  47. /// An IPv4 address.
  48. /// `Url::host_str` returns the serialization of this address,
  49. /// as four decimal integers separated by `.` dots.
  50. Ipv4(Ipv4Addr),
  51. /// An IPv6 address.
  52. /// `Url::host_str` returns the serialization of that address between `[` and `]` brackets,
  53. /// in the format per [RFC 5952 *A Recommendation
  54. /// for IPv6 Address Text Representation*](https://tools.ietf.org/html/rfc5952):
  55. /// lowercase hexadecimal with maximal `::` compression.
  56. Ipv6(Ipv6Addr),
  57. }
  58. impl<'a> Host<&'a str> {
  59. /// Return a copy of `self` that owns an allocated `String` but does not borrow an `&Url`.
  60. pub fn to_owned(&self) -> Host<String> {
  61. match *self {
  62. Host::Domain(domain) => Host::Domain(domain.to_owned()),
  63. Host::Ipv4(address) => Host::Ipv4(address),
  64. Host::Ipv6(address) => Host::Ipv6(address),
  65. }
  66. }
  67. }
  68. impl Host<String> {
  69. /// Parse a host: either an IPv6 address in [] square brackets, or a domain.
  70. ///
  71. /// <https://url.spec.whatwg.org/#host-parsing>
  72. pub fn parse(input: &str) -> Result<Self, ParseError> {
  73. if input.starts_with('[') {
  74. if !input.ends_with(']') {
  75. return Err(ParseError::InvalidIpv6Address);
  76. }
  77. return parse_ipv6addr(&input[1..input.len() - 1]).map(Host::Ipv6);
  78. }
  79. let domain: Cow<'_, [u8]> = percent_decode(input.as_bytes()).into();
  80. let domain = Self::domain_to_ascii(&domain)?;
  81. if domain.is_empty() {
  82. return Err(ParseError::EmptyHost);
  83. }
  84. if ends_in_a_number(&domain) {
  85. let address = parse_ipv4addr(&domain)?;
  86. Ok(Host::Ipv4(address))
  87. } else {
  88. Ok(Host::Domain(domain.to_string()))
  89. }
  90. }
  91. // <https://url.spec.whatwg.org/#concept-opaque-host-parser>
  92. pub fn parse_opaque(input: &str) -> Result<Self, ParseError> {
  93. if input.starts_with('[') {
  94. if !input.ends_with(']') {
  95. return Err(ParseError::InvalidIpv6Address);
  96. }
  97. return parse_ipv6addr(&input[1..input.len() - 1]).map(Host::Ipv6);
  98. }
  99. let is_invalid_host_char = |c| {
  100. matches!(
  101. c,
  102. '\0' | '\t'
  103. | '\n'
  104. | '\r'
  105. | ' '
  106. | '#'
  107. | '/'
  108. | ':'
  109. | '<'
  110. | '>'
  111. | '?'
  112. | '@'
  113. | '['
  114. | '\\'
  115. | ']'
  116. | '^'
  117. | '|'
  118. )
  119. };
  120. if input.find(is_invalid_host_char).is_some() {
  121. Err(ParseError::InvalidDomainCharacter)
  122. } else {
  123. Ok(Host::Domain(
  124. utf8_percent_encode(input, CONTROLS).to_string(),
  125. ))
  126. }
  127. }
  128. /// convert domain with idna
  129. fn domain_to_ascii(domain: &[u8]) -> Result<Cow<'_, str>, ParseError> {
  130. idna::domain_to_ascii_cow(domain, idna::AsciiDenyList::URL).map_err(Into::into)
  131. }
  132. }
  133. impl<S: AsRef<str>> fmt::Display for Host<S> {
  134. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  135. match *self {
  136. Host::Domain(ref domain) => domain.as_ref().fmt(f),
  137. Host::Ipv4(ref addr) => addr.fmt(f),
  138. Host::Ipv6(ref addr) => {
  139. f.write_str("[")?;
  140. write_ipv6(addr, f)?;
  141. f.write_str("]")
  142. }
  143. }
  144. }
  145. }
  146. impl<S, T> PartialEq<Host<T>> for Host<S>
  147. where
  148. S: PartialEq<T>,
  149. {
  150. fn eq(&self, other: &Host<T>) -> bool {
  151. match (self, other) {
  152. (Host::Domain(a), Host::Domain(b)) => a == b,
  153. (Host::Ipv4(a), Host::Ipv4(b)) => a == b,
  154. (Host::Ipv6(a), Host::Ipv6(b)) => a == b,
  155. (_, _) => false,
  156. }
  157. }
  158. }
  159. fn write_ipv6(addr: &Ipv6Addr, f: &mut Formatter<'_>) -> fmt::Result {
  160. let segments = addr.segments();
  161. let (compress_start, compress_end) = longest_zero_sequence(&segments);
  162. let mut i = 0;
  163. while i < 8 {
  164. if i == compress_start {
  165. f.write_str(":")?;
  166. if i == 0 {
  167. f.write_str(":")?;
  168. }
  169. if compress_end < 8 {
  170. i = compress_end;
  171. } else {
  172. break;
  173. }
  174. }
  175. write!(f, "{:x}", segments[i as usize])?;
  176. if i < 7 {
  177. f.write_str(":")?;
  178. }
  179. i += 1;
  180. }
  181. Ok(())
  182. }
  183. // https://url.spec.whatwg.org/#concept-ipv6-serializer step 2 and 3
  184. fn longest_zero_sequence(pieces: &[u16; 8]) -> (isize, isize) {
  185. let mut longest = -1;
  186. let mut longest_length = -1;
  187. let mut start = -1;
  188. macro_rules! finish_sequence(
  189. ($end: expr) => {
  190. if start >= 0 {
  191. let length = $end - start;
  192. if length > longest_length {
  193. longest = start;
  194. longest_length = length;
  195. }
  196. }
  197. };
  198. );
  199. for i in 0..8 {
  200. if pieces[i as usize] == 0 {
  201. if start < 0 {
  202. start = i;
  203. }
  204. } else {
  205. finish_sequence!(i);
  206. start = -1;
  207. }
  208. }
  209. finish_sequence!(8);
  210. // https://url.spec.whatwg.org/#concept-ipv6-serializer
  211. // step 3: ignore lone zeroes
  212. if longest_length < 2 {
  213. (-1, -2)
  214. } else {
  215. (longest, longest + longest_length)
  216. }
  217. }
  218. /// <https://url.spec.whatwg.org/#ends-in-a-number-checker>
  219. fn ends_in_a_number(input: &str) -> bool {
  220. let mut parts = input.rsplit('.');
  221. let last = parts.next().unwrap();
  222. let last = if last.is_empty() {
  223. if let Some(last) = parts.next() {
  224. last
  225. } else {
  226. return false;
  227. }
  228. } else {
  229. last
  230. };
  231. if !last.is_empty() && last.as_bytes().iter().all(|c| c.is_ascii_digit()) {
  232. return true;
  233. }
  234. parse_ipv4number(last).is_ok()
  235. }
  236. /// <https://url.spec.whatwg.org/#ipv4-number-parser>
  237. /// Ok(None) means the input is a valid number, but it overflows a `u32`.
  238. fn parse_ipv4number(mut input: &str) -> Result<Option<u32>, ()> {
  239. if input.is_empty() {
  240. return Err(());
  241. }
  242. let mut r = 10;
  243. if input.starts_with("0x") || input.starts_with("0X") {
  244. input = &input[2..];
  245. r = 16;
  246. } else if input.len() >= 2 && input.starts_with('0') {
  247. input = &input[1..];
  248. r = 8;
  249. }
  250. if input.is_empty() {
  251. return Ok(Some(0));
  252. }
  253. let valid_number = match r {
  254. 8 => input.as_bytes().iter().all(|c| (b'0'..=b'7').contains(c)),
  255. 10 => input.as_bytes().iter().all(|c| c.is_ascii_digit()),
  256. 16 => input.as_bytes().iter().all(|c| c.is_ascii_hexdigit()),
  257. _ => false,
  258. };
  259. if !valid_number {
  260. return Err(());
  261. }
  262. match u32::from_str_radix(input, r) {
  263. Ok(num) => Ok(Some(num)),
  264. Err(_) => Ok(None), // The only possible error kind here is an integer overflow.
  265. // The validity of the chars in the input is checked above.
  266. }
  267. }
  268. /// <https://url.spec.whatwg.org/#concept-ipv4-parser>
  269. fn parse_ipv4addr(input: &str) -> ParseResult<Ipv4Addr> {
  270. let mut parts: Vec<&str> = input.split('.').collect();
  271. if parts.last() == Some(&"") {
  272. parts.pop();
  273. }
  274. if parts.len() > 4 {
  275. return Err(ParseError::InvalidIpv4Address);
  276. }
  277. let mut numbers: Vec<u32> = Vec::new();
  278. for part in parts {
  279. match parse_ipv4number(part) {
  280. Ok(Some(n)) => numbers.push(n),
  281. Ok(None) => return Err(ParseError::InvalidIpv4Address), // u32 overflow
  282. Err(()) => return Err(ParseError::InvalidIpv4Address),
  283. };
  284. }
  285. let mut ipv4 = numbers.pop().expect("a non-empty list of numbers");
  286. // Equivalent to: ipv4 >= 256 ** (4 − numbers.len())
  287. if ipv4 > u32::MAX >> (8 * numbers.len() as u32) {
  288. return Err(ParseError::InvalidIpv4Address);
  289. }
  290. if numbers.iter().any(|x| *x > 255) {
  291. return Err(ParseError::InvalidIpv4Address);
  292. }
  293. for (counter, n) in numbers.iter().enumerate() {
  294. ipv4 += n << (8 * (3 - counter as u32))
  295. }
  296. Ok(Ipv4Addr::from(ipv4))
  297. }
  298. /// <https://url.spec.whatwg.org/#concept-ipv6-parser>
  299. fn parse_ipv6addr(input: &str) -> ParseResult<Ipv6Addr> {
  300. let input = input.as_bytes();
  301. let len = input.len();
  302. let mut is_ip_v4 = false;
  303. let mut pieces = [0, 0, 0, 0, 0, 0, 0, 0];
  304. let mut piece_pointer = 0;
  305. let mut compress_pointer = None;
  306. let mut i = 0;
  307. if len < 2 {
  308. return Err(ParseError::InvalidIpv6Address);
  309. }
  310. if input[0] == b':' {
  311. if input[1] != b':' {
  312. return Err(ParseError::InvalidIpv6Address);
  313. }
  314. i = 2;
  315. piece_pointer = 1;
  316. compress_pointer = Some(1);
  317. }
  318. while i < len {
  319. if piece_pointer == 8 {
  320. return Err(ParseError::InvalidIpv6Address);
  321. }
  322. if input[i] == b':' {
  323. if compress_pointer.is_some() {
  324. return Err(ParseError::InvalidIpv6Address);
  325. }
  326. i += 1;
  327. piece_pointer += 1;
  328. compress_pointer = Some(piece_pointer);
  329. continue;
  330. }
  331. let start = i;
  332. let end = cmp::min(len, start + 4);
  333. let mut value = 0u16;
  334. while i < end {
  335. match (input[i] as char).to_digit(16) {
  336. Some(digit) => {
  337. value = value * 0x10 + digit as u16;
  338. i += 1;
  339. }
  340. None => break,
  341. }
  342. }
  343. if i < len {
  344. match input[i] {
  345. b'.' => {
  346. if i == start {
  347. return Err(ParseError::InvalidIpv6Address);
  348. }
  349. i = start;
  350. if piece_pointer > 6 {
  351. return Err(ParseError::InvalidIpv6Address);
  352. }
  353. is_ip_v4 = true;
  354. }
  355. b':' => {
  356. i += 1;
  357. if i == len {
  358. return Err(ParseError::InvalidIpv6Address);
  359. }
  360. }
  361. _ => return Err(ParseError::InvalidIpv6Address),
  362. }
  363. }
  364. if is_ip_v4 {
  365. break;
  366. }
  367. pieces[piece_pointer] = value;
  368. piece_pointer += 1;
  369. }
  370. if is_ip_v4 {
  371. if piece_pointer > 6 {
  372. return Err(ParseError::InvalidIpv6Address);
  373. }
  374. let mut numbers_seen = 0;
  375. while i < len {
  376. if numbers_seen > 0 {
  377. if numbers_seen < 4 && (i < len && input[i] == b'.') {
  378. i += 1
  379. } else {
  380. return Err(ParseError::InvalidIpv6Address);
  381. }
  382. }
  383. let mut ipv4_piece = None;
  384. while i < len {
  385. let digit = match input[i] {
  386. c @ b'0'..=b'9' => c - b'0',
  387. _ => break,
  388. };
  389. match ipv4_piece {
  390. None => ipv4_piece = Some(digit as u16),
  391. Some(0) => return Err(ParseError::InvalidIpv6Address), // No leading zero
  392. Some(ref mut v) => {
  393. *v = *v * 10 + digit as u16;
  394. if *v > 255 {
  395. return Err(ParseError::InvalidIpv6Address);
  396. }
  397. }
  398. }
  399. i += 1;
  400. }
  401. pieces[piece_pointer] = if let Some(v) = ipv4_piece {
  402. pieces[piece_pointer] * 0x100 + v
  403. } else {
  404. return Err(ParseError::InvalidIpv6Address);
  405. };
  406. numbers_seen += 1;
  407. if numbers_seen == 2 || numbers_seen == 4 {
  408. piece_pointer += 1;
  409. }
  410. }
  411. if numbers_seen != 4 {
  412. return Err(ParseError::InvalidIpv6Address);
  413. }
  414. }
  415. if i < len {
  416. return Err(ParseError::InvalidIpv6Address);
  417. }
  418. match compress_pointer {
  419. Some(compress_pointer) => {
  420. let mut swaps = piece_pointer - compress_pointer;
  421. piece_pointer = 7;
  422. while swaps > 0 {
  423. pieces.swap(piece_pointer, compress_pointer + swaps - 1);
  424. swaps -= 1;
  425. piece_pointer -= 1;
  426. }
  427. }
  428. _ => {
  429. if piece_pointer != 8 {
  430. return Err(ParseError::InvalidIpv6Address);
  431. }
  432. }
  433. }
  434. Ok(Ipv6Addr::new(
  435. pieces[0], pieces[1], pieces[2], pieces[3], pieces[4], pieces[5], pieces[6], pieces[7],
  436. ))
  437. }