parser.rs 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836
  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 alloc::borrow::Cow;
  9. use alloc::string::String;
  10. use core::fmt::{self, Formatter, Write};
  11. use core::str;
  12. use crate::host::{Host, HostInternal};
  13. use crate::Url;
  14. use form_urlencoded::EncodingOverride;
  15. use percent_encoding::{percent_encode, utf8_percent_encode, AsciiSet, CONTROLS};
  16. /// https://url.spec.whatwg.org/#fragment-percent-encode-set
  17. const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
  18. /// https://url.spec.whatwg.org/#path-percent-encode-set
  19. const PATH: &AsciiSet = &FRAGMENT.add(b'#').add(b'?').add(b'{').add(b'}');
  20. /// https://url.spec.whatwg.org/#userinfo-percent-encode-set
  21. pub(crate) const USERINFO: &AsciiSet = &PATH
  22. .add(b'/')
  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. pub(crate) const PATH_SEGMENT: &AsciiSet = &PATH.add(b'/').add(b'%');
  33. // The backslash (\) character is treated as a path separator in special URLs
  34. // so it needs to be additionally escaped in that case.
  35. pub(crate) const SPECIAL_PATH_SEGMENT: &AsciiSet = &PATH_SEGMENT.add(b'\\');
  36. // https://url.spec.whatwg.org/#query-state
  37. const QUERY: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'#').add(b'<').add(b'>');
  38. const SPECIAL_QUERY: &AsciiSet = &QUERY.add(b'\'');
  39. pub type ParseResult<T> = Result<T, ParseError>;
  40. macro_rules! simple_enum_error {
  41. ($($name: ident => $description: expr,)+) => {
  42. /// Errors that can occur during parsing.
  43. ///
  44. /// This may be extended in the future so exhaustive matching is
  45. /// discouraged with an unused variant.
  46. #[derive(PartialEq, Eq, Clone, Copy, Debug)]
  47. #[non_exhaustive]
  48. pub enum ParseError {
  49. $(
  50. $name,
  51. )+
  52. }
  53. impl fmt::Display for ParseError {
  54. fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
  55. match *self {
  56. $(
  57. ParseError::$name => fmt.write_str($description),
  58. )+
  59. }
  60. }
  61. }
  62. }
  63. }
  64. macro_rules! ascii_tab_or_new_line_pattern {
  65. () => {
  66. '\t' | '\n' | '\r'
  67. };
  68. }
  69. #[cfg(feature = "std")]
  70. impl std::error::Error for ParseError {}
  71. #[cfg(not(feature = "std"))]
  72. impl core::error::Error for ParseError {}
  73. simple_enum_error! {
  74. EmptyHost => "empty host",
  75. IdnaError => "invalid international domain name",
  76. InvalidPort => "invalid port number",
  77. InvalidIpv4Address => "invalid IPv4 address",
  78. InvalidIpv6Address => "invalid IPv6 address",
  79. InvalidDomainCharacter => "invalid domain character",
  80. RelativeUrlWithoutBase => "relative URL without a base",
  81. RelativeUrlWithCannotBeABaseBase => "relative URL with a cannot-be-a-base base",
  82. SetHostOnCannotBeABaseUrl => "a cannot-be-a-base URL doesn’t have a host to set",
  83. Overflow => "URLs more than 4 GB are not supported",
  84. }
  85. impl From<::idna::Errors> for ParseError {
  86. fn from(_: ::idna::Errors) -> ParseError {
  87. ParseError::IdnaError
  88. }
  89. }
  90. macro_rules! syntax_violation_enum {
  91. ($($name: ident => $description: literal,)+) => {
  92. /// Non-fatal syntax violations that can occur during parsing.
  93. ///
  94. /// This may be extended in the future so exhaustive matching is
  95. /// forbidden.
  96. #[derive(PartialEq, Eq, Clone, Copy, Debug)]
  97. #[non_exhaustive]
  98. pub enum SyntaxViolation {
  99. $(
  100. /// ```text
  101. #[doc = $description]
  102. /// ```
  103. $name,
  104. )+
  105. }
  106. impl SyntaxViolation {
  107. pub fn description(&self) -> &'static str {
  108. match *self {
  109. $(
  110. SyntaxViolation::$name => $description,
  111. )+
  112. }
  113. }
  114. }
  115. }
  116. }
  117. syntax_violation_enum! {
  118. Backslash => "backslash",
  119. C0SpaceIgnored =>
  120. "leading or trailing control or space character are ignored in URLs",
  121. EmbeddedCredentials =>
  122. "embedding authentication information (username or password) \
  123. in an URL is not recommended",
  124. ExpectedDoubleSlash => "expected //",
  125. ExpectedFileDoubleSlash => "expected // after file:",
  126. FileWithHostAndWindowsDrive => "file: with host and Windows drive letter",
  127. NonUrlCodePoint => "non-URL code point",
  128. NullInFragment => "NULL characters are ignored in URL fragment identifiers",
  129. PercentDecode => "expected 2 hex digits after %",
  130. TabOrNewlineIgnored => "tabs or newlines are ignored in URLs",
  131. UnencodedAtSign => "unencoded @ sign in username or password",
  132. }
  133. impl fmt::Display for SyntaxViolation {
  134. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  135. fmt::Display::fmt(self.description(), f)
  136. }
  137. }
  138. #[derive(Copy, Clone, PartialEq, Eq)]
  139. pub enum SchemeType {
  140. File,
  141. SpecialNotFile,
  142. NotSpecial,
  143. }
  144. impl SchemeType {
  145. pub fn is_special(&self) -> bool {
  146. !matches!(*self, SchemeType::NotSpecial)
  147. }
  148. pub fn is_file(&self) -> bool {
  149. matches!(*self, SchemeType::File)
  150. }
  151. }
  152. impl<T: AsRef<str>> From<T> for SchemeType {
  153. fn from(s: T) -> Self {
  154. match s.as_ref() {
  155. "http" | "https" | "ws" | "wss" | "ftp" => SchemeType::SpecialNotFile,
  156. "file" => SchemeType::File,
  157. _ => SchemeType::NotSpecial,
  158. }
  159. }
  160. }
  161. pub fn default_port(scheme: &str) -> Option<u16> {
  162. match scheme {
  163. "http" | "ws" => Some(80),
  164. "https" | "wss" => Some(443),
  165. "ftp" => Some(21),
  166. _ => None,
  167. }
  168. }
  169. #[derive(Clone, Debug)]
  170. pub struct Input<'i> {
  171. chars: str::Chars<'i>,
  172. }
  173. impl<'i> Input<'i> {
  174. pub fn new_no_trim(input: &'i str) -> Self {
  175. Input {
  176. chars: input.chars(),
  177. }
  178. }
  179. pub fn new_trim_tab_and_newlines(
  180. original_input: &'i str,
  181. vfn: Option<&dyn Fn(SyntaxViolation)>,
  182. ) -> Self {
  183. let input = original_input.trim_matches(ascii_tab_or_new_line);
  184. if let Some(vfn) = vfn {
  185. if input.len() < original_input.len() {
  186. vfn(SyntaxViolation::C0SpaceIgnored)
  187. }
  188. if input.chars().any(ascii_tab_or_new_line) {
  189. vfn(SyntaxViolation::TabOrNewlineIgnored)
  190. }
  191. }
  192. Input {
  193. chars: input.chars(),
  194. }
  195. }
  196. pub fn new_trim_c0_control_and_space(
  197. original_input: &'i str,
  198. vfn: Option<&dyn Fn(SyntaxViolation)>,
  199. ) -> Self {
  200. let input = original_input.trim_matches(c0_control_or_space);
  201. if let Some(vfn) = vfn {
  202. if input.len() < original_input.len() {
  203. vfn(SyntaxViolation::C0SpaceIgnored)
  204. }
  205. if input.chars().any(ascii_tab_or_new_line) {
  206. vfn(SyntaxViolation::TabOrNewlineIgnored)
  207. }
  208. }
  209. Input {
  210. chars: input.chars(),
  211. }
  212. }
  213. #[inline]
  214. pub fn is_empty(&self) -> bool {
  215. self.clone().next().is_none()
  216. }
  217. #[inline]
  218. fn starts_with<P: Pattern>(&self, p: P) -> bool {
  219. p.split_prefix(&mut self.clone())
  220. }
  221. #[inline]
  222. pub fn split_prefix<P: Pattern>(&self, p: P) -> Option<Self> {
  223. let mut remaining = self.clone();
  224. if p.split_prefix(&mut remaining) {
  225. Some(remaining)
  226. } else {
  227. None
  228. }
  229. }
  230. #[inline]
  231. fn split_first(&self) -> (Option<char>, Self) {
  232. let mut remaining = self.clone();
  233. (remaining.next(), remaining)
  234. }
  235. #[inline]
  236. fn count_matching<F: Fn(char) -> bool>(&self, f: F) -> (u32, Self) {
  237. let mut count = 0;
  238. let mut remaining = self.clone();
  239. loop {
  240. let mut input = remaining.clone();
  241. if matches!(input.next(), Some(c) if f(c)) {
  242. remaining = input;
  243. count += 1;
  244. } else {
  245. return (count, remaining);
  246. }
  247. }
  248. }
  249. #[inline]
  250. fn next_utf8(&mut self) -> Option<(char, &'i str)> {
  251. loop {
  252. let utf8 = self.chars.as_str();
  253. match self.chars.next() {
  254. Some(c) => {
  255. if !ascii_tab_or_new_line(c) {
  256. return Some((c, &utf8[..c.len_utf8()]));
  257. }
  258. }
  259. None => return None,
  260. }
  261. }
  262. }
  263. }
  264. pub trait Pattern {
  265. fn split_prefix(self, input: &mut Input) -> bool;
  266. }
  267. impl Pattern for char {
  268. fn split_prefix(self, input: &mut Input) -> bool {
  269. input.next() == Some(self)
  270. }
  271. }
  272. impl Pattern for &str {
  273. fn split_prefix(self, input: &mut Input) -> bool {
  274. for c in self.chars() {
  275. if input.next() != Some(c) {
  276. return false;
  277. }
  278. }
  279. true
  280. }
  281. }
  282. impl<F: FnMut(char) -> bool> Pattern for F {
  283. fn split_prefix(self, input: &mut Input) -> bool {
  284. input.next().map_or(false, self)
  285. }
  286. }
  287. impl Iterator for Input<'_> {
  288. type Item = char;
  289. fn next(&mut self) -> Option<char> {
  290. self.chars.by_ref().find(|&c| !ascii_tab_or_new_line(c))
  291. }
  292. fn size_hint(&self) -> (usize, Option<usize>) {
  293. (0, Some(self.chars.as_str().len()))
  294. }
  295. }
  296. pub struct Parser<'a> {
  297. pub serialization: String,
  298. pub base_url: Option<&'a Url>,
  299. pub query_encoding_override: EncodingOverride<'a>,
  300. pub violation_fn: Option<&'a dyn Fn(SyntaxViolation)>,
  301. pub context: Context,
  302. }
  303. #[derive(PartialEq, Eq, Copy, Clone)]
  304. pub enum Context {
  305. UrlParser,
  306. Setter,
  307. PathSegmentSetter,
  308. }
  309. impl<'a> Parser<'a> {
  310. fn log_violation(&self, v: SyntaxViolation) {
  311. if let Some(f) = self.violation_fn {
  312. f(v)
  313. }
  314. }
  315. fn log_violation_if(&self, v: SyntaxViolation, test: impl FnOnce() -> bool) {
  316. if let Some(f) = self.violation_fn {
  317. if test() {
  318. f(v)
  319. }
  320. }
  321. }
  322. pub fn for_setter(serialization: String) -> Parser<'a> {
  323. Parser {
  324. serialization,
  325. base_url: None,
  326. query_encoding_override: None,
  327. violation_fn: None,
  328. context: Context::Setter,
  329. }
  330. }
  331. /// https://url.spec.whatwg.org/#concept-basic-url-parser
  332. pub fn parse_url(mut self, input: &str) -> ParseResult<Url> {
  333. let input = Input::new_trim_c0_control_and_space(input, self.violation_fn);
  334. if let Ok(remaining) = self.parse_scheme(input.clone()) {
  335. return self.parse_with_scheme(remaining);
  336. }
  337. // No-scheme state
  338. if let Some(base_url) = self.base_url {
  339. if input.starts_with('#') {
  340. self.fragment_only(base_url, input)
  341. } else if base_url.cannot_be_a_base() {
  342. Err(ParseError::RelativeUrlWithCannotBeABaseBase)
  343. } else {
  344. let scheme_type = SchemeType::from(base_url.scheme());
  345. if scheme_type.is_file() {
  346. self.parse_file(input, scheme_type, Some(base_url))
  347. } else {
  348. self.parse_relative(input, scheme_type, base_url)
  349. }
  350. }
  351. } else {
  352. Err(ParseError::RelativeUrlWithoutBase)
  353. }
  354. }
  355. pub fn parse_scheme<'i>(&mut self, mut input: Input<'i>) -> Result<Input<'i>, ()> {
  356. // starts_with will also fail for empty strings so we can skip that comparison for perf
  357. if !input.starts_with(ascii_alpha) {
  358. return Err(());
  359. }
  360. debug_assert!(self.serialization.is_empty());
  361. while let Some(c) = input.next() {
  362. match c {
  363. 'a'..='z' | '0'..='9' | '+' | '-' | '.' => self.serialization.push(c),
  364. 'A'..='Z' => self.serialization.push(c.to_ascii_lowercase()),
  365. ':' => return Ok(input),
  366. _ => {
  367. self.serialization.clear();
  368. return Err(());
  369. }
  370. }
  371. }
  372. // EOF before ':'
  373. if self.context == Context::Setter {
  374. Ok(input)
  375. } else {
  376. self.serialization.clear();
  377. Err(())
  378. }
  379. }
  380. fn parse_with_scheme(mut self, input: Input<'_>) -> ParseResult<Url> {
  381. use crate::SyntaxViolation::{ExpectedDoubleSlash, ExpectedFileDoubleSlash};
  382. let scheme_end = to_u32(self.serialization.len())?;
  383. let scheme_type = SchemeType::from(&self.serialization);
  384. self.serialization.push(':');
  385. match scheme_type {
  386. SchemeType::File => {
  387. self.log_violation_if(ExpectedFileDoubleSlash, || !input.starts_with("//"));
  388. let base_file_url = self.base_url.and_then(|base| {
  389. if base.scheme() == "file" {
  390. Some(base)
  391. } else {
  392. None
  393. }
  394. });
  395. self.serialization.clear();
  396. self.parse_file(input, scheme_type, base_file_url)
  397. }
  398. SchemeType::SpecialNotFile => {
  399. // special relative or authority state
  400. let (slashes_count, remaining) = input.count_matching(|c| matches!(c, '/' | '\\'));
  401. if let Some(base_url) = self.base_url {
  402. if slashes_count < 2
  403. && base_url.scheme() == &self.serialization[..scheme_end as usize]
  404. {
  405. // "Cannot-be-a-base" URLs only happen with "not special" schemes.
  406. debug_assert!(!base_url.cannot_be_a_base());
  407. self.serialization.clear();
  408. return self.parse_relative(input, scheme_type, base_url);
  409. }
  410. }
  411. // special authority slashes state
  412. self.log_violation_if(ExpectedDoubleSlash, || {
  413. input
  414. .clone()
  415. .take_while(|&c| matches!(c, '/' | '\\'))
  416. .collect::<String>()
  417. != "//"
  418. });
  419. self.after_double_slash(remaining, scheme_type, scheme_end)
  420. }
  421. SchemeType::NotSpecial => self.parse_non_special(input, scheme_type, scheme_end),
  422. }
  423. }
  424. /// Scheme other than file, http, https, ws, ws, ftp.
  425. fn parse_non_special(
  426. mut self,
  427. input: Input<'_>,
  428. scheme_type: SchemeType,
  429. scheme_end: u32,
  430. ) -> ParseResult<Url> {
  431. // path or authority state (
  432. if let Some(input) = input.split_prefix("//") {
  433. return self.after_double_slash(input, scheme_type, scheme_end);
  434. }
  435. // Anarchist URL (no authority)
  436. let path_start = to_u32(self.serialization.len())?;
  437. let username_end = path_start;
  438. let host_start = path_start;
  439. let host_end = path_start;
  440. let host = HostInternal::None;
  441. let port = None;
  442. let remaining = if let Some(input) = input.split_prefix('/') {
  443. self.serialization.push('/');
  444. self.parse_path(scheme_type, &mut false, path_start as usize, input)
  445. } else {
  446. self.parse_cannot_be_a_base_path(input)
  447. };
  448. self.with_query_and_fragment(
  449. scheme_type,
  450. scheme_end,
  451. username_end,
  452. host_start,
  453. host_end,
  454. host,
  455. port,
  456. path_start,
  457. remaining,
  458. )
  459. }
  460. fn parse_file(
  461. mut self,
  462. input: Input<'_>,
  463. scheme_type: SchemeType,
  464. base_file_url: Option<&Url>,
  465. ) -> ParseResult<Url> {
  466. use crate::SyntaxViolation::Backslash;
  467. // file state
  468. debug_assert!(self.serialization.is_empty());
  469. let (first_char, input_after_first_char) = input.split_first();
  470. if matches!(first_char, Some('/') | Some('\\')) {
  471. self.log_violation_if(SyntaxViolation::Backslash, || first_char == Some('\\'));
  472. // file slash state
  473. let (next_char, input_after_next_char) = input_after_first_char.split_first();
  474. if matches!(next_char, Some('/') | Some('\\')) {
  475. self.log_violation_if(Backslash, || next_char == Some('\\'));
  476. // file host state
  477. self.serialization.push_str("file://");
  478. let scheme_end = "file".len() as u32;
  479. let host_start = "file://".len() as u32;
  480. let (path_start, mut host, remaining) =
  481. self.parse_file_host(input_after_next_char)?;
  482. let mut host_end = to_u32(self.serialization.len())?;
  483. let mut has_host = !matches!(host, HostInternal::None);
  484. let remaining = if path_start {
  485. self.parse_path_start(SchemeType::File, &mut has_host, remaining)
  486. } else {
  487. let path_start = self.serialization.len();
  488. self.serialization.push('/');
  489. self.parse_path(SchemeType::File, &mut has_host, path_start, remaining)
  490. };
  491. // For file URLs that have a host and whose path starts
  492. // with the windows drive letter we just remove the host.
  493. if !has_host {
  494. self.serialization
  495. .drain(host_start as usize..host_end as usize);
  496. host_end = host_start;
  497. host = HostInternal::None;
  498. }
  499. let (query_start, fragment_start) =
  500. self.parse_query_and_fragment(scheme_type, scheme_end, remaining)?;
  501. return Ok(Url {
  502. serialization: self.serialization,
  503. scheme_end,
  504. username_end: host_start,
  505. host_start,
  506. host_end,
  507. host,
  508. port: None,
  509. path_start: host_end,
  510. query_start,
  511. fragment_start,
  512. });
  513. } else {
  514. self.serialization.push_str("file://");
  515. let scheme_end = "file".len() as u32;
  516. let host_start = "file://".len();
  517. let mut host_end = host_start;
  518. let mut host = HostInternal::None;
  519. if !starts_with_windows_drive_letter_segment(&input_after_first_char) {
  520. if let Some(base_url) = base_file_url {
  521. let first_segment = base_url.path_segments().unwrap().next().unwrap();
  522. if is_normalized_windows_drive_letter(first_segment) {
  523. self.serialization.push('/');
  524. self.serialization.push_str(first_segment);
  525. } else if let Some(host_str) = base_url.host_str() {
  526. self.serialization.push_str(host_str);
  527. host_end = self.serialization.len();
  528. host = base_url.host;
  529. }
  530. }
  531. }
  532. // If c is the EOF code point, U+002F (/), U+005C (\), U+003F (?), or U+0023 (#), then decrease pointer by one
  533. let parse_path_input = if let Some(c) = first_char {
  534. if c == '/' || c == '\\' || c == '?' || c == '#' {
  535. input
  536. } else {
  537. input_after_first_char
  538. }
  539. } else {
  540. input_after_first_char
  541. };
  542. let remaining =
  543. self.parse_path(SchemeType::File, &mut false, host_end, parse_path_input);
  544. let host_start = host_start as u32;
  545. let (query_start, fragment_start) =
  546. self.parse_query_and_fragment(scheme_type, scheme_end, remaining)?;
  547. let host_end = host_end as u32;
  548. return Ok(Url {
  549. serialization: self.serialization,
  550. scheme_end,
  551. username_end: host_start,
  552. host_start,
  553. host_end,
  554. host,
  555. port: None,
  556. path_start: host_end,
  557. query_start,
  558. fragment_start,
  559. });
  560. }
  561. }
  562. if let Some(base_url) = base_file_url {
  563. match first_char {
  564. None => {
  565. // Copy everything except the fragment
  566. let before_fragment = match base_url.fragment_start {
  567. Some(i) => &base_url.serialization[..i as usize],
  568. None => &*base_url.serialization,
  569. };
  570. self.serialization.push_str(before_fragment);
  571. Ok(Url {
  572. serialization: self.serialization,
  573. fragment_start: None,
  574. ..*base_url
  575. })
  576. }
  577. Some('?') => {
  578. // Copy everything up to the query string
  579. let before_query = match (base_url.query_start, base_url.fragment_start) {
  580. (None, None) => &*base_url.serialization,
  581. (Some(i), _) | (None, Some(i)) => base_url.slice(..i),
  582. };
  583. self.serialization.push_str(before_query);
  584. let (query_start, fragment_start) =
  585. self.parse_query_and_fragment(scheme_type, base_url.scheme_end, input)?;
  586. Ok(Url {
  587. serialization: self.serialization,
  588. query_start,
  589. fragment_start,
  590. ..*base_url
  591. })
  592. }
  593. Some('#') => self.fragment_only(base_url, input),
  594. _ => {
  595. if !starts_with_windows_drive_letter_segment(&input) {
  596. let before_query = match (base_url.query_start, base_url.fragment_start) {
  597. (None, None) => &*base_url.serialization,
  598. (Some(i), _) | (None, Some(i)) => base_url.slice(..i),
  599. };
  600. self.serialization.push_str(before_query);
  601. self.shorten_path(SchemeType::File, base_url.path_start as usize);
  602. let remaining = self.parse_path(
  603. SchemeType::File,
  604. &mut true,
  605. base_url.path_start as usize,
  606. input,
  607. );
  608. self.with_query_and_fragment(
  609. SchemeType::File,
  610. base_url.scheme_end,
  611. base_url.username_end,
  612. base_url.host_start,
  613. base_url.host_end,
  614. base_url.host,
  615. base_url.port,
  616. base_url.path_start,
  617. remaining,
  618. )
  619. } else {
  620. self.serialization.push_str("file:///");
  621. let scheme_end = "file".len() as u32;
  622. let path_start = "file://".len();
  623. let remaining =
  624. self.parse_path(SchemeType::File, &mut false, path_start, input);
  625. let (query_start, fragment_start) =
  626. self.parse_query_and_fragment(SchemeType::File, scheme_end, remaining)?;
  627. let path_start = path_start as u32;
  628. Ok(Url {
  629. serialization: self.serialization,
  630. scheme_end,
  631. username_end: path_start,
  632. host_start: path_start,
  633. host_end: path_start,
  634. host: HostInternal::None,
  635. port: None,
  636. path_start,
  637. query_start,
  638. fragment_start,
  639. })
  640. }
  641. }
  642. }
  643. } else {
  644. self.serialization.push_str("file:///");
  645. let scheme_end = "file".len() as u32;
  646. let path_start = "file://".len();
  647. let remaining = self.parse_path(SchemeType::File, &mut false, path_start, input);
  648. let (query_start, fragment_start) =
  649. self.parse_query_and_fragment(SchemeType::File, scheme_end, remaining)?;
  650. let path_start = path_start as u32;
  651. Ok(Url {
  652. serialization: self.serialization,
  653. scheme_end,
  654. username_end: path_start,
  655. host_start: path_start,
  656. host_end: path_start,
  657. host: HostInternal::None,
  658. port: None,
  659. path_start,
  660. query_start,
  661. fragment_start,
  662. })
  663. }
  664. }
  665. fn parse_relative(
  666. mut self,
  667. input: Input<'_>,
  668. scheme_type: SchemeType,
  669. base_url: &Url,
  670. ) -> ParseResult<Url> {
  671. // relative state
  672. debug_assert!(self.serialization.is_empty());
  673. let (first_char, input_after_first_char) = input.split_first();
  674. match first_char {
  675. None => {
  676. // Copy everything except the fragment
  677. let before_fragment = match base_url.fragment_start {
  678. Some(i) => &base_url.serialization[..i as usize],
  679. None => &*base_url.serialization,
  680. };
  681. self.serialization.push_str(before_fragment);
  682. Ok(Url {
  683. serialization: self.serialization,
  684. fragment_start: None,
  685. ..*base_url
  686. })
  687. }
  688. Some('?') => {
  689. // Copy everything up to the query string
  690. let before_query = match (base_url.query_start, base_url.fragment_start) {
  691. (None, None) => &*base_url.serialization,
  692. (Some(i), _) | (None, Some(i)) => base_url.slice(..i),
  693. };
  694. self.serialization.push_str(before_query);
  695. let (query_start, fragment_start) =
  696. self.parse_query_and_fragment(scheme_type, base_url.scheme_end, input)?;
  697. Ok(Url {
  698. serialization: self.serialization,
  699. query_start,
  700. fragment_start,
  701. ..*base_url
  702. })
  703. }
  704. Some('#') => self.fragment_only(base_url, input),
  705. Some('/') | Some('\\') => {
  706. let (slashes_count, remaining) = input.count_matching(|c| matches!(c, '/' | '\\'));
  707. if slashes_count >= 2 {
  708. self.log_violation_if(SyntaxViolation::ExpectedDoubleSlash, || {
  709. input
  710. .clone()
  711. .take_while(|&c| matches!(c, '/' | '\\'))
  712. .collect::<String>()
  713. != "//"
  714. });
  715. let scheme_end = base_url.scheme_end;
  716. debug_assert!(base_url.byte_at(scheme_end) == b':');
  717. self.serialization
  718. .push_str(base_url.slice(..scheme_end + 1));
  719. if let Some(after_prefix) = input.split_prefix("//") {
  720. return self.after_double_slash(after_prefix, scheme_type, scheme_end);
  721. }
  722. return self.after_double_slash(remaining, scheme_type, scheme_end);
  723. }
  724. let path_start = base_url.path_start;
  725. self.serialization.push_str(base_url.slice(..path_start));
  726. self.serialization.push('/');
  727. let remaining = self.parse_path(
  728. scheme_type,
  729. &mut true,
  730. path_start as usize,
  731. input_after_first_char,
  732. );
  733. self.with_query_and_fragment(
  734. scheme_type,
  735. base_url.scheme_end,
  736. base_url.username_end,
  737. base_url.host_start,
  738. base_url.host_end,
  739. base_url.host,
  740. base_url.port,
  741. base_url.path_start,
  742. remaining,
  743. )
  744. }
  745. _ => {
  746. let before_query = match (base_url.query_start, base_url.fragment_start) {
  747. (None, None) => &*base_url.serialization,
  748. (Some(i), _) | (None, Some(i)) => base_url.slice(..i),
  749. };
  750. self.serialization.push_str(before_query);
  751. // FIXME spec says just "remove last entry", not the "pop" algorithm
  752. self.pop_path(scheme_type, base_url.path_start as usize);
  753. // A special url always has a path.
  754. // A path always starts with '/'
  755. if self.serialization.len() == base_url.path_start as usize
  756. && (SchemeType::from(base_url.scheme()).is_special() || !input.is_empty())
  757. {
  758. self.serialization.push('/');
  759. }
  760. let remaining = match input.split_first() {
  761. (Some('/'), remaining) => self.parse_path(
  762. scheme_type,
  763. &mut true,
  764. base_url.path_start as usize,
  765. remaining,
  766. ),
  767. _ => {
  768. self.parse_path(scheme_type, &mut true, base_url.path_start as usize, input)
  769. }
  770. };
  771. self.with_query_and_fragment(
  772. scheme_type,
  773. base_url.scheme_end,
  774. base_url.username_end,
  775. base_url.host_start,
  776. base_url.host_end,
  777. base_url.host,
  778. base_url.port,
  779. base_url.path_start,
  780. remaining,
  781. )
  782. }
  783. }
  784. }
  785. fn after_double_slash(
  786. mut self,
  787. input: Input<'_>,
  788. scheme_type: SchemeType,
  789. scheme_end: u32,
  790. ) -> ParseResult<Url> {
  791. self.serialization.push('/');
  792. self.serialization.push('/');
  793. // authority state
  794. let before_authority = self.serialization.len();
  795. let (username_end, remaining) = self.parse_userinfo(input, scheme_type)?;
  796. let has_authority = before_authority != self.serialization.len();
  797. // host state
  798. let host_start = to_u32(self.serialization.len())?;
  799. let (host_end, host, port, remaining) =
  800. self.parse_host_and_port(remaining, scheme_end, scheme_type)?;
  801. if host == HostInternal::None && has_authority {
  802. return Err(ParseError::EmptyHost);
  803. }
  804. // path state
  805. let path_start = to_u32(self.serialization.len())?;
  806. let remaining = self.parse_path_start(scheme_type, &mut true, remaining);
  807. self.with_query_and_fragment(
  808. scheme_type,
  809. scheme_end,
  810. username_end,
  811. host_start,
  812. host_end,
  813. host,
  814. port,
  815. path_start,
  816. remaining,
  817. )
  818. }
  819. /// Return (username_end, remaining)
  820. fn parse_userinfo<'i>(
  821. &mut self,
  822. mut input: Input<'i>,
  823. scheme_type: SchemeType,
  824. ) -> ParseResult<(u32, Input<'i>)> {
  825. let mut last_at = None;
  826. let mut remaining = input.clone();
  827. let mut char_count = 0;
  828. while let Some(c) = remaining.next() {
  829. match c {
  830. '@' => {
  831. if last_at.is_some() {
  832. self.log_violation(SyntaxViolation::UnencodedAtSign)
  833. } else {
  834. self.log_violation(SyntaxViolation::EmbeddedCredentials)
  835. }
  836. last_at = Some((char_count, remaining.clone()))
  837. }
  838. '/' | '?' | '#' => break,
  839. '\\' if scheme_type.is_special() => break,
  840. _ => (),
  841. }
  842. char_count += 1;
  843. }
  844. let (mut userinfo_char_count, remaining) = match last_at {
  845. None => return Ok((to_u32(self.serialization.len())?, input)),
  846. Some((0, remaining)) => {
  847. // Otherwise, if one of the following is true
  848. // c is the EOF code point, U+002F (/), U+003F (?), or U+0023 (#)
  849. // url is special and c is U+005C (\)
  850. // If @ flag is set and buffer is the empty string, validation error, return failure.
  851. if let (Some(c), _) = remaining.split_first() {
  852. if c == '/' || c == '?' || c == '#' || (scheme_type.is_special() && c == '\\') {
  853. return Err(ParseError::EmptyHost);
  854. }
  855. }
  856. return Ok((to_u32(self.serialization.len())?, remaining));
  857. }
  858. Some(x) => x,
  859. };
  860. let mut username_end = None;
  861. let mut has_password = false;
  862. let mut has_username = false;
  863. while userinfo_char_count > 0 {
  864. let (c, utf8_c) = input.next_utf8().unwrap();
  865. userinfo_char_count -= 1;
  866. if c == ':' && username_end.is_none() {
  867. // Start parsing password
  868. username_end = Some(to_u32(self.serialization.len())?);
  869. // We don't add a colon if the password is empty
  870. if userinfo_char_count > 0 {
  871. self.serialization.push(':');
  872. has_password = true;
  873. }
  874. } else {
  875. if !has_password {
  876. has_username = true;
  877. }
  878. self.check_url_code_point(c, &input);
  879. self.serialization
  880. .extend(utf8_percent_encode(utf8_c, USERINFO));
  881. }
  882. }
  883. let username_end = match username_end {
  884. Some(i) => i,
  885. None => to_u32(self.serialization.len())?,
  886. };
  887. if has_username || has_password {
  888. self.serialization.push('@');
  889. }
  890. Ok((username_end, remaining))
  891. }
  892. fn parse_host_and_port<'i>(
  893. &mut self,
  894. input: Input<'i>,
  895. scheme_end: u32,
  896. scheme_type: SchemeType,
  897. ) -> ParseResult<(u32, HostInternal, Option<u16>, Input<'i>)> {
  898. let (host, remaining) = Parser::parse_host(input, scheme_type)?;
  899. write!(&mut self.serialization, "{}", host).unwrap();
  900. let host_end = to_u32(self.serialization.len())?;
  901. if let Host::Domain(h) = &host {
  902. if h.is_empty() {
  903. // Port with an empty host
  904. if remaining.starts_with(":") {
  905. return Err(ParseError::EmptyHost);
  906. }
  907. if scheme_type.is_special() {
  908. return Err(ParseError::EmptyHost);
  909. }
  910. }
  911. };
  912. let (port, remaining) = if let Some(remaining) = remaining.split_prefix(':') {
  913. let scheme = || default_port(&self.serialization[..scheme_end as usize]);
  914. let (port, remaining) = Parser::parse_port(remaining, scheme, self.context)?;
  915. if let Some(port) = port {
  916. self.serialization.push(':');
  917. let mut buffer = [0u8; 5];
  918. let port_str = fast_u16_to_str(&mut buffer, port);
  919. self.serialization.push_str(port_str);
  920. }
  921. (port, remaining)
  922. } else {
  923. (None, remaining)
  924. };
  925. Ok((host_end, host.into(), port, remaining))
  926. }
  927. pub fn parse_host(
  928. mut input: Input<'_>,
  929. scheme_type: SchemeType,
  930. ) -> ParseResult<(Host<Cow<'_, str>>, Input<'_>)> {
  931. if scheme_type.is_file() {
  932. return Parser::get_file_host(input);
  933. }
  934. // Undo the Input abstraction here to avoid allocating in the common case
  935. // where the host part of the input does not contain any tab or newline
  936. let input_str = input.chars.as_str();
  937. let mut inside_square_brackets = false;
  938. let mut has_ignored_chars = false;
  939. let mut non_ignored_chars = 0;
  940. let mut bytes = 0;
  941. for c in input_str.chars() {
  942. match c {
  943. ':' if !inside_square_brackets => break,
  944. '\\' if scheme_type.is_special() => break,
  945. '/' | '?' | '#' => break,
  946. ascii_tab_or_new_line_pattern!() => {
  947. has_ignored_chars = true;
  948. }
  949. '[' => {
  950. inside_square_brackets = true;
  951. non_ignored_chars += 1
  952. }
  953. ']' => {
  954. inside_square_brackets = false;
  955. non_ignored_chars += 1
  956. }
  957. _ => non_ignored_chars += 1,
  958. }
  959. bytes += c.len_utf8();
  960. }
  961. let host_str;
  962. {
  963. let host_input = input.by_ref().take(non_ignored_chars);
  964. if has_ignored_chars {
  965. host_str = Cow::Owned(host_input.collect());
  966. } else {
  967. for _ in host_input {}
  968. host_str = Cow::Borrowed(&input_str[..bytes]);
  969. }
  970. }
  971. if scheme_type == SchemeType::SpecialNotFile && host_str.is_empty() {
  972. return Err(ParseError::EmptyHost);
  973. }
  974. if !scheme_type.is_special() {
  975. let host = Host::parse_opaque_cow(host_str)?;
  976. return Ok((host, input));
  977. }
  978. let host = Host::parse_cow(host_str)?;
  979. Ok((host, input))
  980. }
  981. fn get_file_host(input: Input<'_>) -> ParseResult<(Host<Cow<'_, str>>, Input<'_>)> {
  982. let (_, host_str, remaining) = Parser::file_host(input)?;
  983. let host = match Host::parse(&host_str)? {
  984. Host::Domain(ref d) if d == "localhost" => Host::Domain(Cow::Borrowed("")),
  985. Host::Domain(s) => Host::Domain(Cow::Owned(s)),
  986. Host::Ipv4(ip) => Host::Ipv4(ip),
  987. Host::Ipv6(ip) => Host::Ipv6(ip),
  988. };
  989. Ok((host, remaining))
  990. }
  991. fn parse_file_host<'i>(
  992. &mut self,
  993. input: Input<'i>,
  994. ) -> ParseResult<(bool, HostInternal, Input<'i>)> {
  995. let has_host;
  996. let (_, host_str, remaining) = Parser::file_host(input)?;
  997. let host = if host_str.is_empty() {
  998. has_host = false;
  999. HostInternal::None
  1000. } else {
  1001. match Host::parse_cow(host_str)? {
  1002. Host::Domain(ref d) if d == "localhost" => {
  1003. has_host = false;
  1004. HostInternal::None
  1005. }
  1006. host => {
  1007. write!(&mut self.serialization, "{}", host).unwrap();
  1008. has_host = true;
  1009. host.into()
  1010. }
  1011. }
  1012. };
  1013. Ok((has_host, host, remaining))
  1014. }
  1015. pub fn file_host(input: Input<'_>) -> ParseResult<(bool, Cow<'_, str>, Input<'_>)> {
  1016. // Undo the Input abstraction here to avoid allocating in the common case
  1017. // where the host part of the input does not contain any tab or newline
  1018. let input_str = input.chars.as_str();
  1019. let mut has_ignored_chars = false;
  1020. let mut non_ignored_chars = 0;
  1021. let mut bytes = 0;
  1022. for c in input_str.chars() {
  1023. match c {
  1024. '/' | '\\' | '?' | '#' => break,
  1025. ascii_tab_or_new_line_pattern!() => has_ignored_chars = true,
  1026. _ => non_ignored_chars += 1,
  1027. }
  1028. bytes += c.len_utf8();
  1029. }
  1030. let host_str;
  1031. let mut remaining = input.clone();
  1032. {
  1033. let host_input = remaining.by_ref().take(non_ignored_chars);
  1034. if has_ignored_chars {
  1035. host_str = Cow::Owned(host_input.collect());
  1036. } else {
  1037. for _ in host_input {}
  1038. host_str = Cow::Borrowed(&input_str[..bytes]);
  1039. }
  1040. }
  1041. if is_windows_drive_letter(&host_str) {
  1042. return Ok((false, "".into(), input));
  1043. }
  1044. Ok((true, host_str, remaining))
  1045. }
  1046. pub fn parse_port<P>(
  1047. mut input: Input<'_>,
  1048. default_port: P,
  1049. context: Context,
  1050. ) -> ParseResult<(Option<u16>, Input<'_>)>
  1051. where
  1052. P: Fn() -> Option<u16>,
  1053. {
  1054. let mut port: u32 = 0;
  1055. let mut has_any_digit = false;
  1056. while let (Some(c), remaining) = input.split_first() {
  1057. if let Some(digit) = c.to_digit(10) {
  1058. port = port * 10 + digit;
  1059. if port > u16::MAX as u32 {
  1060. return Err(ParseError::InvalidPort);
  1061. }
  1062. has_any_digit = true;
  1063. } else if context == Context::UrlParser && !matches!(c, '/' | '\\' | '?' | '#') {
  1064. return Err(ParseError::InvalidPort);
  1065. } else {
  1066. break;
  1067. }
  1068. input = remaining;
  1069. }
  1070. if !has_any_digit && context == Context::Setter && !input.is_empty() {
  1071. return Err(ParseError::InvalidPort);
  1072. }
  1073. let mut opt_port = Some(port as u16);
  1074. if !has_any_digit || opt_port == default_port() {
  1075. opt_port = None;
  1076. }
  1077. Ok((opt_port, input))
  1078. }
  1079. pub fn parse_path_start<'i>(
  1080. &mut self,
  1081. scheme_type: SchemeType,
  1082. has_host: &mut bool,
  1083. input: Input<'i>,
  1084. ) -> Input<'i> {
  1085. let path_start = self.serialization.len();
  1086. let (maybe_c, remaining) = input.split_first();
  1087. // If url is special, then:
  1088. if scheme_type.is_special() {
  1089. if maybe_c == Some('\\') {
  1090. // If c is U+005C (\), validation error.
  1091. self.log_violation(SyntaxViolation::Backslash);
  1092. }
  1093. // A special URL always has a non-empty path.
  1094. if !self.serialization.ends_with('/') {
  1095. self.serialization.push('/');
  1096. // We have already made sure the forward slash is present.
  1097. if maybe_c == Some('/') || maybe_c == Some('\\') {
  1098. return self.parse_path(scheme_type, has_host, path_start, remaining);
  1099. }
  1100. }
  1101. return self.parse_path(scheme_type, has_host, path_start, input);
  1102. } else if maybe_c == Some('?') || maybe_c == Some('#') {
  1103. // Otherwise, if state override is not given and c is U+003F (?),
  1104. // set url’s query to the empty string and state to query state.
  1105. // Otherwise, if state override is not given and c is U+0023 (#),
  1106. // set url’s fragment to the empty string and state to fragment state.
  1107. // The query and path states will be handled by the caller.
  1108. return input;
  1109. }
  1110. if maybe_c.is_some() && maybe_c != Some('/') {
  1111. self.serialization.push('/');
  1112. }
  1113. // Otherwise, if c is not the EOF code point:
  1114. self.parse_path(scheme_type, has_host, path_start, input)
  1115. }
  1116. pub fn parse_path<'i>(
  1117. &mut self,
  1118. scheme_type: SchemeType,
  1119. has_host: &mut bool,
  1120. path_start: usize,
  1121. mut input: Input<'i>,
  1122. ) -> Input<'i> {
  1123. // it's much faster to call utf8_percent_encode in bulk
  1124. fn push_pending(
  1125. serialization: &mut String,
  1126. start_str: &str,
  1127. remaining_len: usize,
  1128. context: Context,
  1129. scheme_type: SchemeType,
  1130. ) {
  1131. let text = &start_str[..start_str.len() - remaining_len];
  1132. if text.is_empty() {
  1133. return;
  1134. }
  1135. if context == Context::PathSegmentSetter {
  1136. if scheme_type.is_special() {
  1137. serialization.extend(utf8_percent_encode(text, SPECIAL_PATH_SEGMENT));
  1138. } else {
  1139. serialization.extend(utf8_percent_encode(text, PATH_SEGMENT));
  1140. }
  1141. } else {
  1142. serialization.extend(utf8_percent_encode(text, PATH));
  1143. }
  1144. }
  1145. // Relative path state
  1146. loop {
  1147. let mut segment_start = self.serialization.len();
  1148. let mut ends_with_slash = false;
  1149. let mut start_str = input.chars.as_str();
  1150. loop {
  1151. let input_before_c = input.clone();
  1152. // bypass input.next() and manually handle ascii_tab_or_new_line
  1153. // in order to encode string slices in bulk
  1154. let c = if let Some(c) = input.chars.next() {
  1155. c
  1156. } else {
  1157. push_pending(
  1158. &mut self.serialization,
  1159. start_str,
  1160. 0,
  1161. self.context,
  1162. scheme_type,
  1163. );
  1164. break;
  1165. };
  1166. match c {
  1167. ascii_tab_or_new_line_pattern!() => {
  1168. push_pending(
  1169. &mut self.serialization,
  1170. start_str,
  1171. input_before_c.chars.as_str().len(),
  1172. self.context,
  1173. scheme_type,
  1174. );
  1175. start_str = input.chars.as_str();
  1176. }
  1177. '/' if self.context != Context::PathSegmentSetter => {
  1178. push_pending(
  1179. &mut self.serialization,
  1180. start_str,
  1181. input_before_c.chars.as_str().len(),
  1182. self.context,
  1183. scheme_type,
  1184. );
  1185. self.serialization.push(c);
  1186. ends_with_slash = true;
  1187. break;
  1188. }
  1189. '\\' if self.context != Context::PathSegmentSetter
  1190. && scheme_type.is_special() =>
  1191. {
  1192. push_pending(
  1193. &mut self.serialization,
  1194. start_str,
  1195. input_before_c.chars.as_str().len(),
  1196. self.context,
  1197. scheme_type,
  1198. );
  1199. self.log_violation(SyntaxViolation::Backslash);
  1200. self.serialization.push('/');
  1201. ends_with_slash = true;
  1202. break;
  1203. }
  1204. '?' | '#' if self.context == Context::UrlParser => {
  1205. push_pending(
  1206. &mut self.serialization,
  1207. start_str,
  1208. input_before_c.chars.as_str().len(),
  1209. self.context,
  1210. scheme_type,
  1211. );
  1212. input = input_before_c;
  1213. break;
  1214. }
  1215. _ => {
  1216. self.check_url_code_point(c, &input);
  1217. if scheme_type.is_file()
  1218. && self.serialization.len() > path_start
  1219. && is_normalized_windows_drive_letter(
  1220. &self.serialization[path_start + 1..],
  1221. )
  1222. {
  1223. push_pending(
  1224. &mut self.serialization,
  1225. start_str,
  1226. input_before_c.chars.as_str().len(),
  1227. self.context,
  1228. scheme_type,
  1229. );
  1230. start_str = input_before_c.chars.as_str();
  1231. self.serialization.push('/');
  1232. segment_start += 1;
  1233. }
  1234. }
  1235. }
  1236. }
  1237. let segment_before_slash = if ends_with_slash {
  1238. &self.serialization[segment_start..self.serialization.len() - 1]
  1239. } else {
  1240. &self.serialization[segment_start..self.serialization.len()]
  1241. };
  1242. match segment_before_slash {
  1243. // If buffer is a double-dot path segment, shorten url’s path,
  1244. ".." | "%2e%2e" | "%2e%2E" | "%2E%2e" | "%2E%2E" | "%2e." | "%2E." | ".%2e"
  1245. | ".%2E" => {
  1246. debug_assert!(self.serialization.as_bytes()[segment_start - 1] == b'/');
  1247. self.serialization.truncate(segment_start);
  1248. if self.serialization.ends_with('/')
  1249. && Parser::last_slash_can_be_removed(&self.serialization, path_start)
  1250. {
  1251. self.serialization.pop();
  1252. }
  1253. self.shorten_path(scheme_type, path_start);
  1254. // and then if neither c is U+002F (/), nor url is special and c is U+005C (\), append the empty string to url’s path.
  1255. if ends_with_slash && !self.serialization.ends_with('/') {
  1256. self.serialization.push('/');
  1257. }
  1258. }
  1259. // Otherwise, if buffer is a single-dot path segment and if neither c is U+002F (/),
  1260. // nor url is special and c is U+005C (\), append the empty string to url’s path.
  1261. "." | "%2e" | "%2E" => {
  1262. self.serialization.truncate(segment_start);
  1263. if !self.serialization.ends_with('/') {
  1264. self.serialization.push('/');
  1265. }
  1266. }
  1267. _ => {
  1268. // If url’s scheme is "file", url’s path is empty, and buffer is a Windows drive letter, then
  1269. if scheme_type.is_file()
  1270. && segment_start == path_start + 1
  1271. && is_windows_drive_letter(segment_before_slash)
  1272. {
  1273. // Replace the second code point in buffer with U+003A (:).
  1274. if let Some(c) = segment_before_slash.chars().next() {
  1275. self.serialization.truncate(segment_start);
  1276. self.serialization.push(c);
  1277. self.serialization.push(':');
  1278. if ends_with_slash {
  1279. self.serialization.push('/');
  1280. }
  1281. }
  1282. // If url’s host is neither the empty string nor null,
  1283. // validation error, set url’s host to the empty string.
  1284. if *has_host {
  1285. self.log_violation(SyntaxViolation::FileWithHostAndWindowsDrive);
  1286. *has_host = false; // FIXME account for this in callers
  1287. }
  1288. }
  1289. }
  1290. }
  1291. if !ends_with_slash {
  1292. break;
  1293. }
  1294. }
  1295. if scheme_type.is_file() {
  1296. // while url’s path’s size is greater than 1
  1297. // and url’s path[0] is the empty string,
  1298. // validation error, remove the first item from url’s path.
  1299. //FIXME: log violation
  1300. let path = self.serialization.split_off(path_start);
  1301. self.serialization.push('/');
  1302. self.serialization.push_str(path.trim_start_matches('/'));
  1303. }
  1304. input
  1305. }
  1306. fn last_slash_can_be_removed(serialization: &str, path_start: usize) -> bool {
  1307. let url_before_segment = &serialization[..serialization.len() - 1];
  1308. if let Some(segment_before_start) = url_before_segment.rfind('/') {
  1309. // Do not remove the root slash
  1310. segment_before_start >= path_start
  1311. // Or a windows drive letter slash
  1312. && !path_starts_with_windows_drive_letter(&serialization[segment_before_start..])
  1313. } else {
  1314. false
  1315. }
  1316. }
  1317. /// https://url.spec.whatwg.org/#shorten-a-urls-path
  1318. fn shorten_path(&mut self, scheme_type: SchemeType, path_start: usize) {
  1319. // If path is empty, then return.
  1320. if self.serialization.len() == path_start {
  1321. return;
  1322. }
  1323. // If url’s scheme is "file", path’s size is 1, and path[0] is a normalized Windows drive letter, then return.
  1324. if scheme_type.is_file()
  1325. && is_normalized_windows_drive_letter(&self.serialization[path_start..])
  1326. {
  1327. return;
  1328. }
  1329. // Remove path’s last item.
  1330. self.pop_path(scheme_type, path_start);
  1331. }
  1332. /// https://url.spec.whatwg.org/#pop-a-urls-path
  1333. fn pop_path(&mut self, scheme_type: SchemeType, path_start: usize) {
  1334. if self.serialization.len() > path_start {
  1335. let slash_position = self.serialization[path_start..].rfind('/').unwrap();
  1336. // + 1 since rfind returns the position before the slash.
  1337. let segment_start = path_start + slash_position + 1;
  1338. // Don’t pop a Windows drive letter
  1339. if !(scheme_type.is_file()
  1340. && is_normalized_windows_drive_letter(&self.serialization[segment_start..]))
  1341. {
  1342. self.serialization.truncate(segment_start);
  1343. }
  1344. }
  1345. }
  1346. pub fn parse_cannot_be_a_base_path<'i>(&mut self, mut input: Input<'i>) -> Input<'i> {
  1347. loop {
  1348. let input_before_c = input.clone();
  1349. match input.next_utf8() {
  1350. Some(('?', _)) | Some(('#', _)) if self.context == Context::UrlParser => {
  1351. return input_before_c
  1352. }
  1353. Some((c, utf8_c)) => {
  1354. self.check_url_code_point(c, &input);
  1355. self.serialization
  1356. .extend(utf8_percent_encode(utf8_c, CONTROLS));
  1357. }
  1358. None => return input,
  1359. }
  1360. }
  1361. }
  1362. #[allow(clippy::too_many_arguments)]
  1363. fn with_query_and_fragment(
  1364. mut self,
  1365. scheme_type: SchemeType,
  1366. scheme_end: u32,
  1367. username_end: u32,
  1368. host_start: u32,
  1369. host_end: u32,
  1370. host: HostInternal,
  1371. port: Option<u16>,
  1372. mut path_start: u32,
  1373. remaining: Input<'_>,
  1374. ) -> ParseResult<Url> {
  1375. // Special case for anarchist URL's with a leading empty path segment
  1376. // This prevents web+demo:/.//not-a-host/ or web+demo:/path/..//not-a-host/,
  1377. // when parsed and then serialized, from ending up as web+demo://not-a-host/
  1378. // (they end up as web+demo:/.//not-a-host/).
  1379. //
  1380. // If url’s host is null, url does not have an opaque path,
  1381. // url’s path’s size is greater than 1, and url’s path[0] is the empty string,
  1382. // then append U+002F (/) followed by U+002E (.) to output.
  1383. let scheme_end_as_usize = scheme_end as usize;
  1384. let path_start_as_usize = path_start as usize;
  1385. if path_start_as_usize == scheme_end_as_usize + 1 {
  1386. // Anarchist URL
  1387. if self.serialization[path_start_as_usize..].starts_with("//") {
  1388. // Case 1: The base URL did not have an empty path segment, but the resulting one does
  1389. // Insert the "/." prefix
  1390. self.serialization.insert_str(path_start_as_usize, "/.");
  1391. path_start += 2;
  1392. }
  1393. assert!(!self.serialization[scheme_end_as_usize..].starts_with("://"));
  1394. } else if path_start_as_usize == scheme_end_as_usize + 3
  1395. && &self.serialization[scheme_end_as_usize..path_start_as_usize] == ":/."
  1396. {
  1397. // Anarchist URL with leading empty path segment
  1398. // The base URL has a "/." between the host and the path
  1399. assert_eq!(self.serialization.as_bytes()[path_start_as_usize], b'/');
  1400. if self
  1401. .serialization
  1402. .as_bytes()
  1403. .get(path_start_as_usize + 1)
  1404. .copied()
  1405. != Some(b'/')
  1406. {
  1407. // Case 2: The base URL had an empty path segment, but the resulting one does not
  1408. // Remove the "/." prefix
  1409. self.serialization
  1410. .replace_range(scheme_end_as_usize..path_start_as_usize, ":");
  1411. path_start -= 2;
  1412. }
  1413. assert!(!self.serialization[scheme_end_as_usize..].starts_with("://"));
  1414. }
  1415. let (query_start, fragment_start) =
  1416. self.parse_query_and_fragment(scheme_type, scheme_end, remaining)?;
  1417. Ok(Url {
  1418. serialization: self.serialization,
  1419. scheme_end,
  1420. username_end,
  1421. host_start,
  1422. host_end,
  1423. host,
  1424. port,
  1425. path_start,
  1426. query_start,
  1427. fragment_start,
  1428. })
  1429. }
  1430. /// Return (query_start, fragment_start)
  1431. fn parse_query_and_fragment(
  1432. &mut self,
  1433. scheme_type: SchemeType,
  1434. scheme_end: u32,
  1435. mut input: Input<'_>,
  1436. ) -> ParseResult<(Option<u32>, Option<u32>)> {
  1437. let mut query_start = None;
  1438. match input.next() {
  1439. Some('#') => {}
  1440. Some('?') => {
  1441. query_start = Some(to_u32(self.serialization.len())?);
  1442. self.serialization.push('?');
  1443. let remaining = self.parse_query(scheme_type, scheme_end, input);
  1444. if let Some(remaining) = remaining {
  1445. input = remaining
  1446. } else {
  1447. return Ok((query_start, None));
  1448. }
  1449. }
  1450. None => return Ok((None, None)),
  1451. _ => panic!("Programming error. parse_query_and_fragment() called without ? or #"),
  1452. }
  1453. let fragment_start = to_u32(self.serialization.len())?;
  1454. self.serialization.push('#');
  1455. self.parse_fragment(input);
  1456. Ok((query_start, Some(fragment_start)))
  1457. }
  1458. pub fn parse_query<'i>(
  1459. &mut self,
  1460. scheme_type: SchemeType,
  1461. scheme_end: u32,
  1462. input: Input<'i>,
  1463. ) -> Option<Input<'i>> {
  1464. struct QueryPartIter<'i, 'p> {
  1465. is_url_parser: bool,
  1466. input: Input<'i>,
  1467. violation_fn: Option<&'p dyn Fn(SyntaxViolation)>,
  1468. }
  1469. impl<'i> Iterator for QueryPartIter<'i, '_> {
  1470. type Item = (&'i str, bool);
  1471. fn next(&mut self) -> Option<Self::Item> {
  1472. let start = self.input.chars.as_str();
  1473. // bypass self.input.next() in order to get string slices
  1474. // which are faster to operate on
  1475. while let Some(c) = self.input.chars.next() {
  1476. match c {
  1477. ascii_tab_or_new_line_pattern!() => {
  1478. return Some((
  1479. &start[..start.len() - self.input.chars.as_str().len() - 1],
  1480. false,
  1481. ));
  1482. }
  1483. '#' if self.is_url_parser => {
  1484. return Some((
  1485. &start[..start.len() - self.input.chars.as_str().len() - 1],
  1486. true,
  1487. ));
  1488. }
  1489. c => {
  1490. if let Some(vfn) = &self.violation_fn {
  1491. check_url_code_point(vfn, c, &self.input);
  1492. }
  1493. }
  1494. }
  1495. }
  1496. if start.is_empty() {
  1497. None
  1498. } else {
  1499. Some((start, false))
  1500. }
  1501. }
  1502. }
  1503. let mut part_iter = QueryPartIter {
  1504. is_url_parser: self.context == Context::UrlParser,
  1505. input,
  1506. violation_fn: self.violation_fn,
  1507. };
  1508. let set = if scheme_type.is_special() {
  1509. SPECIAL_QUERY
  1510. } else {
  1511. QUERY
  1512. };
  1513. let query_encoding_override = self.query_encoding_override.filter(|_| {
  1514. matches!(
  1515. &self.serialization[..scheme_end as usize],
  1516. "http" | "https" | "file" | "ftp"
  1517. )
  1518. });
  1519. while let Some((part, is_finished)) = part_iter.next() {
  1520. match query_encoding_override {
  1521. // slightly faster to be repetitive and not convert text to Cow
  1522. Some(o) => self.serialization.extend(percent_encode(&o(part), set)),
  1523. None => self
  1524. .serialization
  1525. .extend(percent_encode(part.as_bytes(), set)),
  1526. }
  1527. if is_finished {
  1528. return Some(part_iter.input);
  1529. }
  1530. }
  1531. None
  1532. }
  1533. fn fragment_only(mut self, base_url: &Url, mut input: Input<'_>) -> ParseResult<Url> {
  1534. let before_fragment = match base_url.fragment_start {
  1535. Some(i) => base_url.slice(..i),
  1536. None => &*base_url.serialization,
  1537. };
  1538. debug_assert!(self.serialization.is_empty());
  1539. self.serialization
  1540. .reserve(before_fragment.len() + input.chars.as_str().len());
  1541. self.serialization.push_str(before_fragment);
  1542. self.serialization.push('#');
  1543. let next = input.next();
  1544. debug_assert!(next == Some('#'));
  1545. self.parse_fragment(input);
  1546. Ok(Url {
  1547. serialization: self.serialization,
  1548. fragment_start: Some(to_u32(before_fragment.len())?),
  1549. ..*base_url
  1550. })
  1551. }
  1552. pub fn parse_fragment(&mut self, input: Input<'_>) {
  1553. struct FragmentPartIter<'i, 'p> {
  1554. input: Input<'i>,
  1555. violation_fn: Option<&'p dyn Fn(SyntaxViolation)>,
  1556. }
  1557. impl<'i> Iterator for FragmentPartIter<'i, '_> {
  1558. type Item = &'i str;
  1559. fn next(&mut self) -> Option<Self::Item> {
  1560. let start = self.input.chars.as_str();
  1561. // bypass self.input.next() in order to get string slices
  1562. // which are faster to operate on
  1563. while let Some(c) = self.input.chars.next() {
  1564. match c {
  1565. ascii_tab_or_new_line_pattern!() => {
  1566. return Some(
  1567. &start[..start.len() - self.input.chars.as_str().len() - 1],
  1568. );
  1569. }
  1570. '\0' => {
  1571. if let Some(vfn) = &self.violation_fn {
  1572. vfn(SyntaxViolation::NullInFragment);
  1573. }
  1574. }
  1575. c => {
  1576. if let Some(vfn) = &self.violation_fn {
  1577. check_url_code_point(vfn, c, &self.input);
  1578. }
  1579. }
  1580. }
  1581. }
  1582. if start.is_empty() {
  1583. None
  1584. } else {
  1585. Some(start)
  1586. }
  1587. }
  1588. }
  1589. let part_iter = FragmentPartIter {
  1590. input,
  1591. violation_fn: self.violation_fn,
  1592. };
  1593. for part in part_iter {
  1594. self.serialization
  1595. .extend(utf8_percent_encode(part, FRAGMENT));
  1596. }
  1597. }
  1598. #[inline]
  1599. fn check_url_code_point(&self, c: char, input: &Input<'_>) {
  1600. if let Some(vfn) = self.violation_fn {
  1601. check_url_code_point(vfn, c, input)
  1602. }
  1603. }
  1604. }
  1605. fn check_url_code_point(vfn: &dyn Fn(SyntaxViolation), c: char, input: &Input<'_>) {
  1606. if c == '%' {
  1607. let mut input = input.clone();
  1608. if !matches!((input.next(), input.next()), (Some(a), Some(b))
  1609. if a.is_ascii_hexdigit() && b.is_ascii_hexdigit())
  1610. {
  1611. vfn(SyntaxViolation::PercentDecode)
  1612. }
  1613. } else if !is_url_code_point(c) {
  1614. vfn(SyntaxViolation::NonUrlCodePoint)
  1615. }
  1616. }
  1617. // Non URL code points:
  1618. // U+0000 to U+0020 (space)
  1619. // " # % < > [ \ ] ^ ` { | }
  1620. // U+007F to U+009F
  1621. // surrogates
  1622. // U+FDD0 to U+FDEF
  1623. // Last two of each plane: U+__FFFE to U+__FFFF for __ in 00 to 10 hex
  1624. #[inline]
  1625. fn is_url_code_point(c: char) -> bool {
  1626. matches!(c,
  1627. 'a'..='z' |
  1628. 'A'..='Z' |
  1629. '0'..='9' |
  1630. '!' | '$' | '&' | '\'' | '(' | ')' | '*' | '+' | ',' | '-' |
  1631. '.' | '/' | ':' | ';' | '=' | '?' | '@' | '_' | '~' |
  1632. '\u{A0}'..='\u{D7FF}' | '\u{E000}'..='\u{FDCF}' | '\u{FDF0}'..='\u{FFFD}' |
  1633. '\u{10000}'..='\u{1FFFD}' | '\u{20000}'..='\u{2FFFD}' |
  1634. '\u{30000}'..='\u{3FFFD}' | '\u{40000}'..='\u{4FFFD}' |
  1635. '\u{50000}'..='\u{5FFFD}' | '\u{60000}'..='\u{6FFFD}' |
  1636. '\u{70000}'..='\u{7FFFD}' | '\u{80000}'..='\u{8FFFD}' |
  1637. '\u{90000}'..='\u{9FFFD}' | '\u{A0000}'..='\u{AFFFD}' |
  1638. '\u{B0000}'..='\u{BFFFD}' | '\u{C0000}'..='\u{CFFFD}' |
  1639. '\u{D0000}'..='\u{DFFFD}' | '\u{E1000}'..='\u{EFFFD}' |
  1640. '\u{F0000}'..='\u{FFFFD}' | '\u{100000}'..='\u{10FFFD}')
  1641. }
  1642. /// https://url.spec.whatwg.org/#c0-controls-and-space
  1643. #[inline]
  1644. fn c0_control_or_space(ch: char) -> bool {
  1645. ch <= ' ' // U+0000 to U+0020
  1646. }
  1647. /// https://infra.spec.whatwg.org/#ascii-tab-or-newline
  1648. #[inline]
  1649. fn ascii_tab_or_new_line(ch: char) -> bool {
  1650. matches!(ch, ascii_tab_or_new_line_pattern!())
  1651. }
  1652. /// https://url.spec.whatwg.org/#ascii-alpha
  1653. #[inline]
  1654. pub fn ascii_alpha(ch: char) -> bool {
  1655. ch.is_ascii_alphabetic()
  1656. }
  1657. #[inline]
  1658. pub fn to_u32(i: usize) -> ParseResult<u32> {
  1659. if i <= u32::MAX as usize {
  1660. Ok(i as u32)
  1661. } else {
  1662. Err(ParseError::Overflow)
  1663. }
  1664. }
  1665. fn is_normalized_windows_drive_letter(segment: &str) -> bool {
  1666. is_windows_drive_letter(segment) && segment.as_bytes()[1] == b':'
  1667. }
  1668. /// Whether the scheme is file:, the path has a single segment, and that segment
  1669. /// is a Windows drive letter
  1670. #[inline]
  1671. pub fn is_windows_drive_letter(segment: &str) -> bool {
  1672. segment.len() == 2 && starts_with_windows_drive_letter(segment)
  1673. }
  1674. /// Whether path starts with a root slash
  1675. /// and a windows drive letter eg: "/c:" or "/a:/"
  1676. fn path_starts_with_windows_drive_letter(s: &str) -> bool {
  1677. if let Some(c) = s.as_bytes().first() {
  1678. matches!(c, b'/' | b'\\' | b'?' | b'#') && starts_with_windows_drive_letter(&s[1..])
  1679. } else {
  1680. false
  1681. }
  1682. }
  1683. fn starts_with_windows_drive_letter(s: &str) -> bool {
  1684. s.len() >= 2
  1685. && ascii_alpha(s.as_bytes()[0] as char)
  1686. && matches!(s.as_bytes()[1], b':' | b'|')
  1687. && (s.len() == 2 || matches!(s.as_bytes()[2], b'/' | b'\\' | b'?' | b'#'))
  1688. }
  1689. /// https://url.spec.whatwg.org/#start-with-a-windows-drive-letter
  1690. fn starts_with_windows_drive_letter_segment(input: &Input<'_>) -> bool {
  1691. let mut input = input.clone();
  1692. match (input.next(), input.next(), input.next()) {
  1693. // its first two code points are a Windows drive letter
  1694. // its third code point is U+002F (/), U+005C (\), U+003F (?), or U+0023 (#).
  1695. (Some(a), Some(b), Some(c))
  1696. if ascii_alpha(a) && matches!(b, ':' | '|') && matches!(c, '/' | '\\' | '?' | '#') =>
  1697. {
  1698. true
  1699. }
  1700. // its first two code points are a Windows drive letter
  1701. // its length is 2
  1702. (Some(a), Some(b), None) if ascii_alpha(a) && matches!(b, ':' | '|') => true,
  1703. _ => false,
  1704. }
  1705. }
  1706. #[inline]
  1707. fn fast_u16_to_str(
  1708. // max 5 digits for u16 (65535)
  1709. buffer: &mut [u8; 5],
  1710. mut value: u16,
  1711. ) -> &str {
  1712. let mut index = buffer.len();
  1713. loop {
  1714. index -= 1;
  1715. buffer[index] = b'0' + (value % 10) as u8;
  1716. value /= 10;
  1717. if value == 0 {
  1718. break;
  1719. }
  1720. }
  1721. // SAFETY: we know the values in the buffer from the
  1722. // current index on will be a number
  1723. unsafe { core::str::from_utf8_unchecked(&buffer[index..]) }
  1724. }