Debian Codegraph @

src/url_parser/parser.rs

raw symbols SCIP
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
9 use std::error::Error;
10 use std::fmt::{self, Formatter, Write};
11
12 use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
13 use std::ops::{Range, RangeFrom, RangeTo};
14
15 /// https://url.spec.whatwg.org/#fragment-percent-encode-set
16 const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
17
18 /// https://url.spec.whatwg.org/#path-percent-encode-set
19 const PATH: &AsciiSet = &FRAGMENT.add(b'#').add(b'?').add(b'{').add(b'}');
20
21 /// https://url.spec.whatwg.org/#userinfo-percent-encode-set
22 pub(crate) const USERINFO: &AsciiSet = &PATH
23 .add(b'/')
24 .add(b':')
25 .add(b';')
26 .add(b'=')
27 .add(b'@')
28 .add(b'[')
29 .add(b'\\')
30 .add(b']')
31 .add(b'^')
32 .add(b'|');
33
34 #[derive(Clone)]
35 pub(super) struct Hostname {
36 serialization: String,
37
38 // Components
39 pub(super) scheme_end: usize, // Before ':'
40 pub(super) host_start: usize,
41 pub(super) host_end: usize,
42 }
43
44 impl Hostname {
45 pub fn parse(input: &str) -> Result<Hostname, ParseError> {
46 Parser {
47 serialization: String::with_capacity(input.len()),
48 }
49 .parse_url(input)
50 }
51
52 /// Equivalent to `url.host().is_some()`.
53 ///
54 /// # Examples
55 ///
56 /// ```
57 /// use url::Url;
58 /// # use url::ParseError;
59 ///
60 /// # fn run() -> Result<(), ParseError> {
61 /// let url = Url::parse("ftp://[email protected]")?;
62 /// assert!(url.has_host());
63 ///
64 /// let url = Url::parse("unix:/run/foo.socket")?;
65 /// assert!(!url.has_host());
66 ///
67 /// let url = Url::parse("data:text/plain,Stuff")?;
68 /// assert!(!url.has_host());
69 /// # Ok(())
70 /// # }
71 /// # run().unwrap();
72 /// ```
73 fn has_host(&self) -> bool {
74 self.host_end > self.host_start
75 }
76
77 /// Return the string representation of the host (domain or IP address) for this URL, if any.
78 ///
79 /// Non-ASCII domains are punycode-encoded per IDNA.
80 /// IPv6 addresses are given between `[` and `]` brackets.
81 ///
82 /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
83 /// don’t have a host.
84 ///
85 /// See also the `host` method.
86 ///
87 /// # Examples
88 ///
89 /// ```
90 /// use url::Url;
91 /// # use url::ParseError;
92 ///
93 /// # fn run() -> Result<(), ParseError> {
94 /// let url = Url::parse("https://127.0.0.1/index.html")?;
95 /// assert_eq!(url.host_str(), Some("127.0.0.1"));
96 ///
97 /// let url = Url::parse("ftp://[email protected]")?;
98 /// assert_eq!(url.host_str(), Some("example.com"));
99 ///
100 /// let url = Url::parse("unix:/run/foo.socket")?;
101 /// assert_eq!(url.host_str(), None);
102 ///
103 /// let url = Url::parse("data:text/plain,Stuff")?;
104 /// assert_eq!(url.host_str(), None);
105 /// # Ok(())
106 /// # }
107 /// # run().unwrap();
108 /// ```
109 pub fn host_str(&self) -> Option<&str> {
110 if self.has_host() {
111 Some(self.slice(self.host_start..self.host_end))
112 } else {
113 None
114 }
115 }
116
117 pub fn url_str(&self) -> &str {
118 &self.serialization
119 }
120
121 // Private helper methods:
122
123 fn slice<R>(&self, range: R) -> &str
124 where
125 R: RangeArg,
126 {
127 range.slice_of(&self.serialization)
128 }
129 }
130
131 trait RangeArg {
132 fn slice_of<'a>(&self, s: &'a str) -> &'a str;
133 }
134
135 impl RangeArg for Range<usize> {
136 fn slice_of<'a>(&self, s: &'a str) -> &'a str {
137 &s[self.start..self.end]
138 }
139 }
140
141 impl RangeArg for RangeFrom<usize> {
142 fn slice_of<'a>(&self, s: &'a str) -> &'a str {
143 &s[self.start..]
144 }
145 }
146
147 impl RangeArg for RangeTo<usize> {
148 fn slice_of<'a>(&self, s: &'a str) -> &'a str {
149 &s[..self.end]
150 }
151 }
152
153 pub type ParseResult<T> = Result<T, ParseError>;
154
155 macro_rules! simple_enum_error {
156 ($($name: ident => $description: expr,)+) => {
157 /// Errors that can occur during parsing.
158 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
159 pub enum ParseError {
160 $(
161 $name,
162 )+
163 }
164
165 impl Error for ParseError {}
166
167 impl fmt::Display for ParseError {
168 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
169 match *self {
170 $(
171 ParseError::$name => $description,
172 )+
173 }.fmt(fmt)
174 }
175 }
176 }
177 }
178
179 simple_enum_error! {
180 // EmptyHost => "empty host",
181 IdnaError => "invalid international domain name",
182 // InvalidPort => "invalid port number",
183 // InvalidIpv4Address => "invalid IPv4 address",
184 // InvalidIpv6Address => "invalid IPv6 address",
185 // InvalidDomainCharacter => "invalid domain character",
186 // HostParseError => "internal host parse error",
187 RelativeUrlWithoutBase => "relative URL without a base",
188 // RelativeUrlWithCannotBeABaseBase => "relative URL with a cannot-be-a-base base",
189 // SetHostOnCannotBeABaseUrl => "a cannot-be-a-base URL doesn’t have a host to set",
190 // Overflow => "URLs more than 4 GB are not supported",
191 FileUrlNotSupported => "file URLs are not supported",
192 ExpectedMoreChars => "Expected more characters",
193 }
194
195 impl From<idna::Errors> for ParseError {
196 fn from(_: idna::Errors) -> ParseError {
197 ParseError::IdnaError
198 }
199 }
200
201 #[derive(Copy, Clone)]
202 pub enum SchemeType {
203 File,
204 SpecialNotFile,
205 NotSpecial,
206 }
207
208 impl SchemeType {
209 pub fn is_special(self) -> bool {
210 !matches!(self, SchemeType::NotSpecial)
211 }
212
213 pub fn from(s: &str) -> Self {
214 match s {
215 "http" | "https" | "ws" | "wss" | "ftp" | "gopher" => SchemeType::SpecialNotFile,
216 "file" => SchemeType::File,
217 _ => SchemeType::NotSpecial,
218 }
219 }
220 }
221
222 #[derive(Clone)]
223 pub struct Input<'i> {
224 chars: std::str::Chars<'i>,
225 }
226
227 impl<'i> Input<'i> {
228 pub fn new(input: &'i str) -> Self {
229 let input = input.trim_matches(c0_control_or_space);
230 Input {
231 chars: input.chars(),
232 }
233 }
234
235 pub fn is_empty(&self) -> bool {
236 self.clone().next().is_none()
237 }
238
239 fn starts_with<P: Pattern>(&self, p: P) -> bool {
240 p.split_prefix(&mut self.clone())
241 }
242
243 pub fn split_prefix<P: Pattern>(&self, p: P) -> Option<Self> {
244 let mut remaining = self.clone();
245 if p.split_prefix(&mut remaining) {
246 Some(remaining)
247 } else {
248 None
249 }
250 }
251
252 fn count_matching<F: Fn(char) -> bool>(&self, f: F) -> (u32, Self) {
253 let mut count = 0;
254 let mut remaining = self.clone();
255 loop {
256 let mut input = remaining.clone();
257 if matches!(input.next(), Some(c) if f(c)) {
258 remaining = input;
259 count += 1;
260 } else {
261 return (count, remaining);
262 }
263 }
264 }
265
266 fn next_utf8(&mut self) -> Option<(char, &'i str)> {
267 loop {
268 let utf8 = self.chars.as_str();
269 match self.chars.next() {
270 Some(c) => {
271 if !matches!(c, '\t' | '\n' | '\r') {
272 return Some((c, &utf8[..c.len_utf8()]));
273 }
274 }
275 None => return None,
276 }
277 }
278 }
279 }
280
281 pub trait Pattern {
282 fn split_prefix(self, input: &mut Input) -> bool;
283 }
284
285 impl Pattern for char {
286 fn split_prefix(self, input: &mut Input) -> bool {
287 input.next() == Some(self)
288 }
289 }
290
291 impl<'a> Pattern for &'a str {
292 fn split_prefix(self, input: &mut Input) -> bool {
293 for c in self.chars() {
294 if input.next() != Some(c) {
295 return false;
296 }
297 }
298 true
299 }
300 }
301
302 impl<F: FnMut(char) -> bool> Pattern for F {
303 fn split_prefix(self, input: &mut Input) -> bool {
304 input.next().map_or(false, self)
305 }
306 }
307
308 impl<'i> Iterator for Input<'i> {
309 type Item = char;
310 fn next(&mut self) -> Option<char> {
311 self.chars.next() //by_ref().find(|&c| !matches!(c, '\t' | '\n' | '\r'))
312 }
313 }
314
315 pub struct Parser {
316 pub serialization: String,
317 }
318
319 impl Parser {
320 /// https://url.spec.whatwg.org/#concept-basic-url-parser
321 pub fn parse_url(mut self, input: &str) -> ParseResult<Hostname> {
322 // println!("Parse {}", input);
323 let input = Input::new(input);
324 if let Ok(remaining) = self.parse_scheme(input.clone()) {
325 return self.parse_with_scheme(remaining);
326 }
327
328 // No-scheme state
329 Err(ParseError::RelativeUrlWithoutBase)
330 }
331
332 pub fn parse_scheme<'i>(&mut self, mut input: Input<'i>) -> Result<Input<'i>, ()> {
333 if input.is_empty() || !input.starts_with(|c: char| c.is_ascii_alphabetic()) {
334 return Err(());
335 }
336 debug_assert!(self.serialization.is_empty());
337 while let Some(c) = input.next() {
338 match c {
339 'a'..='z' => self.serialization.push(c),
340 'A'..='Z' => self.serialization.push(c.to_ascii_lowercase()),
341 '0'..='9' | '+' | '-' | '.' => self.serialization.push(c),
342 ':' => return Ok(input),
343 _ => {
344 self.serialization.clear();
345 return Err(());
346 }
347 }
348 }
349
350 Err(())
351 }
352
353 fn parse_with_scheme(mut self, input: Input) -> ParseResult<Hostname> {
354 let scheme_end = self.serialization.len();
355 let scheme_type = SchemeType::from(&self.serialization);
356 self.serialization.push(':');
357 match scheme_type {
358 SchemeType::File => {
359 // println!("Parse file - not supported");
360 Err(ParseError::FileUrlNotSupported)
361 }
362 SchemeType::SpecialNotFile => {
363 // println!("Parse special, not file");
364 // special relative or authority state
365 let (_, remaining) = input.count_matching(|c| matches!(c, '/' | '\\'));
366 // special authority slashes state
367 // println!("Parse after double slash {}", remaining.chars.as_str());
368 self.after_double_slash(remaining, scheme_type, scheme_end)
369 }
370 SchemeType::NotSpecial => {
371 // println!("Parse non special {}", &self.serialization);
372 self.parse_non_special(input, scheme_type, scheme_end)
373 }
374 }
375 }
376
377 /// Scheme other than file, http, https, ws, ws, ftp, gopher.
378 fn parse_non_special(
379 mut self,
380 input: Input,
381 scheme_type: SchemeType,
382 scheme_end: usize,
383 ) -> ParseResult<Hostname> {
384 // path or authority state (
385 if let Some(input) = input.split_prefix("//") {
386 return self.after_double_slash(input, scheme_type, scheme_end);
387 }
388 // Anarchist URL (no authority)
389 let path_start = self.serialization.len();
390 let host_start = path_start;
391 let host_end = path_start;
392 self.serialization.push_str(input.chars.as_str());
393 let ser_remaining = self.serialization.as_mut_str().get_mut(host_end..);
394 ser_remaining.map(|s| {
395 s.make_ascii_lowercase();
396 &*s
397 });
398
399 Ok(Hostname {
400 serialization: self.serialization,
401 scheme_end,
402 host_start,
403 host_end,
404 })
405 }
406
407 fn after_double_slash(
408 mut self,
409 input: Input,
410 scheme_type: SchemeType,
411 scheme_end: usize,
412 ) -> ParseResult<Hostname> {
413 self.serialization.push_str("//");
414 // authority state
415 let (_username_end, remaining) = self.parse_userinfo(input, scheme_type)?;
416 // host state
417 let host_start = self.serialization.len();
418 let (host_end, remaining) = self.parse_host(remaining, scheme_type)?;
419 self.serialization.push_str(remaining.chars.as_str());
420 Ok(Hostname {
421 serialization: self.serialization,
422 scheme_end,
423 host_start,
424 host_end,
425 })
426 }
427
428 /// Return (username_end, remaining)
429 fn parse_userinfo<'i>(
430 &mut self,
431 mut input: Input<'i>,
432 scheme_type: SchemeType,
433 ) -> ParseResult<(usize, Input<'i>)> {
434 let mut last_at = None;
435 let mut remaining = input.clone();
436 let mut char_count = 0;
437 while let Some(c) = remaining.next() {
438 match c {
439 '@' => last_at = Some((char_count, remaining.clone())),
440 '/' | '?' | '#' => break,
441 '\\' if scheme_type.is_special() => break,
442 _ => (),
443 }
444 char_count += 1;
445 }
446 let (mut userinfo_char_count, remaining) = match last_at {
447 None => return Ok((self.serialization.len(), input)),
448 Some((0, remaining)) => return Ok((self.serialization.len(), remaining)),
449 Some(x) => x,
450 };
451
452 let mut username_end = None;
453 let mut has_password = false;
454 let mut has_username = false;
455 while userinfo_char_count > 0 {
456 let (c, utf8_c) = input.next_utf8().ok_or(ParseError::ExpectedMoreChars)?;
457 userinfo_char_count -= 1;
458 if c == ':' && username_end.is_none() {
459 // Start parsing password
460 username_end = Some(self.serialization.len());
461 // We don't add a colon if the password is empty
462 if userinfo_char_count > 0 {
463 self.serialization.push(':');
464 has_password = true;
465 }
466 } else {
467 if !has_password {
468 has_username = true;
469 }
470 self.serialization
471 .extend(utf8_percent_encode(utf8_c, USERINFO));
472 }
473 }
474 let username_end = match username_end {
475 Some(i) => i,
476 None => self.serialization.len(),
477 };
478 if has_username || has_password {
479 self.serialization.push('@');
480 }
481 Ok((username_end, remaining))
482 }
483
484 pub fn parse_host<'i>(
485 &mut self,
486 mut input: Input<'i>,
487 scheme_type: SchemeType,
488 ) -> ParseResult<(usize, Input<'i>)> {
489 // Undo the Input abstraction here to avoid allocating in the common case
490 // where the host part of the input does not contain any tab or newline
491 let input_str = input.chars.as_str();
492 let mut remaining = input.clone();
493 let mut inside_square_brackets = false;
494 let mut has_ignored_chars = false;
495 let mut non_ignored_chars = 0;
496 let mut bytes = 0;
497 for c in input_str.chars() {
498 match c {
499 ':' if !inside_square_brackets => break,
500 '\\' if scheme_type.is_special() => break,
501 '/' | '?' | '#' => break,
502 '\t' | '\n' | '\r' => {
503 has_ignored_chars = true;
504 }
505 '[' => {
506 inside_square_brackets = true;
507 non_ignored_chars += 1
508 }
509 ']' => {
510 inside_square_brackets = false;
511 non_ignored_chars += 1
512 }
513 _ => non_ignored_chars += 1,
514 }
515 remaining.next();
516 bytes += c.len_utf8();
517 }
518 let replaced: String;
519 let host_str;
520 {
521 let host_input = input.by_ref().take(non_ignored_chars);
522 if has_ignored_chars {
523 replaced = host_input.collect();
524 host_str = &*replaced
525 } else {
526 for _ in host_input {}
527 host_str = &input_str[..bytes]
528 }
529 }
530
531 if host_str.is_ascii() {
532 write!(&mut self.serialization, "{}", host_str).unwrap();
533 } else {
534 let encoded = idna::domain_to_ascii(host_str)?;
535 write!(&mut self.serialization, "{}", encoded).unwrap();
536 }
537
538 let host_end = self.serialization.len();
539 Ok((host_end, remaining))
540 }
541 }
542
543 /// https://url.spec.whatwg.org/#c0-controls-and-space
544 #[inline]
545 fn c0_control_or_space(ch: char) -> bool {
546 ch <= ' ' // U+0000 to U+0020
547 }