lib.rs 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966
  1. // Copyright 2013-2015 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. rust-url is an implementation of the [URL Standard](http://url.spec.whatwg.org/)
  10. for the [Rust](http://rust-lang.org/) programming language.
  11. # URL parsing and data structures
  12. First, URL parsing may fail for various reasons and therefore returns a `Result`.
  13. ```
  14. use url::{Url, ParseError};
  15. assert!(Url::parse("http://[:::1]") == Err(ParseError::InvalidIpv6Address))
  16. ```
  17. Let’s parse a valid URL and look at its components.
  18. ```
  19. use url::{Url, Host, Position};
  20. # use url::ParseError;
  21. # fn run() -> Result<(), ParseError> {
  22. let issue_list_url = Url::parse(
  23. "https://github.com/rust-lang/rust/issues?labels=E-easy&state=open"
  24. )?;
  25. assert!(issue_list_url.scheme() == "https");
  26. assert!(issue_list_url.username() == "");
  27. assert!(issue_list_url.password() == None);
  28. assert!(issue_list_url.host_str() == Some("github.com"));
  29. assert!(issue_list_url.host() == Some(Host::Domain("github.com")));
  30. assert!(issue_list_url.port() == None);
  31. assert!(issue_list_url.path() == "/rust-lang/rust/issues");
  32. assert!(issue_list_url.path_segments().map(|c| c.collect::<Vec<_>>()) ==
  33. Some(vec!["rust-lang", "rust", "issues"]));
  34. assert!(issue_list_url.query() == Some("labels=E-easy&state=open"));
  35. assert!(&issue_list_url[Position::BeforePath..] == "/rust-lang/rust/issues?labels=E-easy&state=open");
  36. assert!(issue_list_url.fragment() == None);
  37. assert!(!issue_list_url.cannot_be_a_base());
  38. # Ok(())
  39. # }
  40. # run().unwrap();
  41. ```
  42. Some URLs are said to be *cannot-be-a-base*:
  43. they don’t have a username, password, host, or port,
  44. and their "path" is an arbitrary string rather than slash-separated segments:
  45. ```
  46. use url::Url;
  47. # use url::ParseError;
  48. # fn run() -> Result<(), ParseError> {
  49. let data_url = Url::parse("data:text/plain,Hello?World#")?;
  50. assert!(data_url.cannot_be_a_base());
  51. assert!(data_url.scheme() == "data");
  52. assert!(data_url.path() == "text/plain,Hello");
  53. assert!(data_url.path_segments().is_none());
  54. assert!(data_url.query() == Some("World"));
  55. assert!(data_url.fragment() == Some(""));
  56. # Ok(())
  57. # }
  58. # run().unwrap();
  59. ```
  60. ## Serde
  61. Enable the `serde` feature to include `Deserialize` and `Serialize` implementations for `url::Url`.
  62. # Base URL
  63. Many contexts allow URL *references* that can be relative to a *base URL*:
  64. ```html
  65. <link rel="stylesheet" href="../main.css">
  66. ```
  67. Since parsed URLs are absolute, giving a base is required for parsing relative URLs:
  68. ```
  69. use url::{Url, ParseError};
  70. assert!(Url::parse("../main.css") == Err(ParseError::RelativeUrlWithoutBase))
  71. ```
  72. Use the `join` method on an `Url` to use it as a base URL:
  73. ```
  74. use url::Url;
  75. # use url::ParseError;
  76. # fn run() -> Result<(), ParseError> {
  77. let this_document = Url::parse("http://servo.github.io/rust-url/url/index.html")?;
  78. let css_url = this_document.join("../main.css")?;
  79. assert_eq!(css_url.as_str(), "http://servo.github.io/rust-url/main.css");
  80. # Ok(())
  81. # }
  82. # run().unwrap();
  83. ```
  84. # Feature: `serde`
  85. If you enable the `serde` feature, [`Url`](struct.Url.html) will implement
  86. [`serde::Serialize`](https://docs.rs/serde/1/serde/trait.Serialize.html) and
  87. [`serde::Deserialize`](https://docs.rs/serde/1/serde/trait.Deserialize.html).
  88. See [serde documentation](https://serde.rs) for more information.
  89. ```toml
  90. url = { version = "2", features = ["serde"] }
  91. ```
  92. */
  93. #![doc(html_root_url = "https://docs.rs/url/2.3.1")]
  94. #![cfg_attr(
  95. feature = "debugger_visualizer",
  96. feature(debugger_visualizer),
  97. debugger_visualizer(natvis_file = "../../debug_metadata/url.natvis")
  98. )]
  99. pub use form_urlencoded;
  100. #[cfg(feature = "serde")]
  101. extern crate serde;
  102. use crate::host::HostInternal;
  103. use crate::parser::{to_u32, Context, Parser, SchemeType, PATH_SEGMENT, USERINFO};
  104. use percent_encoding::{percent_decode, percent_encode, utf8_percent_encode};
  105. use std::borrow::Borrow;
  106. use std::cmp;
  107. use std::fmt::{self, Write};
  108. use std::hash;
  109. use std::io;
  110. use std::mem;
  111. use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
  112. use std::ops::{Range, RangeFrom, RangeTo};
  113. use std::path::{Path, PathBuf};
  114. use std::str;
  115. use std::convert::TryFrom;
  116. pub use crate::host::Host;
  117. pub use crate::origin::{OpaqueOrigin, Origin};
  118. pub use crate::parser::{ParseError, SyntaxViolation};
  119. pub use crate::path_segments::PathSegmentsMut;
  120. pub use crate::slicing::Position;
  121. pub use form_urlencoded::EncodingOverride;
  122. mod host;
  123. mod origin;
  124. mod parser;
  125. mod path_segments;
  126. mod slicing;
  127. #[doc(hidden)]
  128. pub mod quirks;
  129. /// A parsed URL record.
  130. #[derive(Clone)]
  131. pub struct Url {
  132. /// Syntax in pseudo-BNF:
  133. ///
  134. /// url = scheme ":" [ hierarchical | non-hierarchical ] [ "?" query ]? [ "#" fragment ]?
  135. /// non-hierarchical = non-hierarchical-path
  136. /// non-hierarchical-path = /* Does not start with "/" */
  137. /// hierarchical = authority? hierarchical-path
  138. /// authority = "//" userinfo? host [ ":" port ]?
  139. /// userinfo = username [ ":" password ]? "@"
  140. /// hierarchical-path = [ "/" path-segment ]+
  141. serialization: String,
  142. // Components
  143. scheme_end: u32, // Before ':'
  144. username_end: u32, // Before ':' (if a password is given) or '@' (if not)
  145. host_start: u32,
  146. host_end: u32,
  147. host: HostInternal,
  148. port: Option<u16>,
  149. path_start: u32, // Before initial '/', if any
  150. query_start: Option<u32>, // Before '?', unlike Position::QueryStart
  151. fragment_start: Option<u32>, // Before '#', unlike Position::FragmentStart
  152. }
  153. /// Full configuration for the URL parser.
  154. #[derive(Copy, Clone)]
  155. pub struct ParseOptions<'a> {
  156. base_url: Option<&'a Url>,
  157. encoding_override: EncodingOverride<'a>,
  158. violation_fn: Option<&'a dyn Fn(SyntaxViolation)>,
  159. }
  160. impl<'a> ParseOptions<'a> {
  161. /// Change the base URL
  162. pub fn base_url(mut self, new: Option<&'a Url>) -> Self {
  163. self.base_url = new;
  164. self
  165. }
  166. /// Override the character encoding of query strings.
  167. /// This is a legacy concept only relevant for HTML.
  168. pub fn encoding_override(mut self, new: EncodingOverride<'a>) -> Self {
  169. self.encoding_override = new;
  170. self
  171. }
  172. /// Call the provided function or closure for a non-fatal `SyntaxViolation`
  173. /// when it occurs during parsing. Note that since the provided function is
  174. /// `Fn`, the caller might need to utilize _interior mutability_, such as with
  175. /// a `RefCell`, to collect the violations.
  176. ///
  177. /// ## Example
  178. /// ```
  179. /// use std::cell::RefCell;
  180. /// use url::{Url, SyntaxViolation};
  181. /// # use url::ParseError;
  182. /// # fn run() -> Result<(), url::ParseError> {
  183. /// let violations = RefCell::new(Vec::new());
  184. /// let url = Url::options()
  185. /// .syntax_violation_callback(Some(&|v| violations.borrow_mut().push(v)))
  186. /// .parse("https:////example.com")?;
  187. /// assert_eq!(url.as_str(), "https://example.com/");
  188. /// assert_eq!(violations.into_inner(),
  189. /// vec!(SyntaxViolation::ExpectedDoubleSlash));
  190. /// # Ok(())
  191. /// # }
  192. /// # run().unwrap();
  193. /// ```
  194. pub fn syntax_violation_callback(mut self, new: Option<&'a dyn Fn(SyntaxViolation)>) -> Self {
  195. self.violation_fn = new;
  196. self
  197. }
  198. /// Parse an URL string with the configuration so far.
  199. pub fn parse(self, input: &str) -> Result<Url, crate::ParseError> {
  200. Parser {
  201. serialization: String::with_capacity(input.len()),
  202. base_url: self.base_url,
  203. query_encoding_override: self.encoding_override,
  204. violation_fn: self.violation_fn,
  205. context: Context::UrlParser,
  206. }
  207. .parse_url(input)
  208. }
  209. }
  210. impl Url {
  211. /// Parse an absolute URL from a string.
  212. ///
  213. /// # Examples
  214. ///
  215. /// ```rust
  216. /// use url::Url;
  217. /// # use url::ParseError;
  218. ///
  219. /// # fn run() -> Result<(), ParseError> {
  220. /// let url = Url::parse("https://example.net")?;
  221. /// # Ok(())
  222. /// # }
  223. /// # run().unwrap();
  224. /// ```
  225. ///
  226. /// # Errors
  227. ///
  228. /// If the function can not parse an absolute URL from the given string,
  229. /// a [`ParseError`] variant will be returned.
  230. ///
  231. /// [`ParseError`]: enum.ParseError.html
  232. #[inline]
  233. pub fn parse(input: &str) -> Result<Url, crate::ParseError> {
  234. Url::options().parse(input)
  235. }
  236. /// Parse an absolute URL from a string and add params to its query string.
  237. ///
  238. /// Existing params are not removed.
  239. ///
  240. /// # Examples
  241. ///
  242. /// ```rust
  243. /// use url::Url;
  244. /// # use url::ParseError;
  245. ///
  246. /// # fn run() -> Result<(), ParseError> {
  247. /// let url = Url::parse_with_params("https://example.net?dont=clobberme",
  248. /// &[("lang", "rust"), ("browser", "servo")])?;
  249. /// assert_eq!("https://example.net/?dont=clobberme&lang=rust&browser=servo", url.as_str());
  250. /// # Ok(())
  251. /// # }
  252. /// # run().unwrap();
  253. /// ```
  254. ///
  255. /// # Errors
  256. ///
  257. /// If the function can not parse an absolute URL from the given string,
  258. /// a [`ParseError`] variant will be returned.
  259. ///
  260. /// [`ParseError`]: enum.ParseError.html
  261. #[inline]
  262. pub fn parse_with_params<I, K, V>(input: &str, iter: I) -> Result<Url, crate::ParseError>
  263. where
  264. I: IntoIterator,
  265. I::Item: Borrow<(K, V)>,
  266. K: AsRef<str>,
  267. V: AsRef<str>,
  268. {
  269. let mut url = Url::options().parse(input);
  270. if let Ok(ref mut url) = url {
  271. url.query_pairs_mut().extend_pairs(iter);
  272. }
  273. url
  274. }
  275. /// Parse a string as an URL, with this URL as the base URL.
  276. ///
  277. /// The inverse of this is [`make_relative`].
  278. ///
  279. /// Note: a trailing slash is significant.
  280. /// Without it, the last path component is considered to be a “file” name
  281. /// to be removed to get at the “directory” that is used as the base:
  282. ///
  283. /// # Examples
  284. ///
  285. /// ```rust
  286. /// use url::Url;
  287. /// # use url::ParseError;
  288. ///
  289. /// # fn run() -> Result<(), ParseError> {
  290. /// let base = Url::parse("https://example.net/a/b.html")?;
  291. /// let url = base.join("c.png")?;
  292. /// assert_eq!(url.as_str(), "https://example.net/a/c.png"); // Not /a/b.html/c.png
  293. ///
  294. /// let base = Url::parse("https://example.net/a/b/")?;
  295. /// let url = base.join("c.png")?;
  296. /// assert_eq!(url.as_str(), "https://example.net/a/b/c.png");
  297. /// # Ok(())
  298. /// # }
  299. /// # run().unwrap();
  300. /// ```
  301. ///
  302. /// # Errors
  303. ///
  304. /// If the function can not parse an URL from the given string
  305. /// with this URL as the base URL, a [`ParseError`] variant will be returned.
  306. ///
  307. /// [`ParseError`]: enum.ParseError.html
  308. /// [`make_relative`]: #method.make_relative
  309. #[inline]
  310. pub fn join(&self, input: &str) -> Result<Url, crate::ParseError> {
  311. Url::options().base_url(Some(self)).parse(input)
  312. }
  313. /// Creates a relative URL if possible, with this URL as the base URL.
  314. ///
  315. /// This is the inverse of [`join`].
  316. ///
  317. /// # Examples
  318. ///
  319. /// ```rust
  320. /// use url::Url;
  321. /// # use url::ParseError;
  322. ///
  323. /// # fn run() -> Result<(), ParseError> {
  324. /// let base = Url::parse("https://example.net/a/b.html")?;
  325. /// let url = Url::parse("https://example.net/a/c.png")?;
  326. /// let relative = base.make_relative(&url);
  327. /// assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("c.png"));
  328. ///
  329. /// let base = Url::parse("https://example.net/a/b/")?;
  330. /// let url = Url::parse("https://example.net/a/b/c.png")?;
  331. /// let relative = base.make_relative(&url);
  332. /// assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("c.png"));
  333. ///
  334. /// let base = Url::parse("https://example.net/a/b/")?;
  335. /// let url = Url::parse("https://example.net/a/d/c.png")?;
  336. /// let relative = base.make_relative(&url);
  337. /// assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("../d/c.png"));
  338. ///
  339. /// let base = Url::parse("https://example.net/a/b.html?c=d")?;
  340. /// let url = Url::parse("https://example.net/a/b.html?e=f")?;
  341. /// let relative = base.make_relative(&url);
  342. /// assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("?e=f"));
  343. /// # Ok(())
  344. /// # }
  345. /// # run().unwrap();
  346. /// ```
  347. ///
  348. /// # Errors
  349. ///
  350. /// If this URL can't be a base for the given URL, `None` is returned.
  351. /// This is for example the case if the scheme, host or port are not the same.
  352. ///
  353. /// [`join`]: #method.join
  354. pub fn make_relative(&self, url: &Url) -> Option<String> {
  355. if self.cannot_be_a_base() {
  356. return None;
  357. }
  358. // Scheme, host and port need to be the same
  359. if self.scheme() != url.scheme() || self.host() != url.host() || self.port() != url.port() {
  360. return None;
  361. }
  362. // We ignore username/password at this point
  363. // The path has to be transformed
  364. let mut relative = String::new();
  365. // Extract the filename of both URIs, these need to be handled separately
  366. fn extract_path_filename(s: &str) -> (&str, &str) {
  367. let last_slash_idx = s.rfind('/').unwrap_or(0);
  368. let (path, filename) = s.split_at(last_slash_idx);
  369. if filename.is_empty() {
  370. (path, "")
  371. } else {
  372. (path, &filename[1..])
  373. }
  374. }
  375. let (base_path, base_filename) = extract_path_filename(self.path());
  376. let (url_path, url_filename) = extract_path_filename(url.path());
  377. let mut base_path = base_path.split('/').peekable();
  378. let mut url_path = url_path.split('/').peekable();
  379. // Skip over the common prefix
  380. while base_path.peek().is_some() && base_path.peek() == url_path.peek() {
  381. base_path.next();
  382. url_path.next();
  383. }
  384. // Add `..` segments for the remainder of the base path
  385. for base_path_segment in base_path {
  386. // Skip empty last segments
  387. if base_path_segment.is_empty() {
  388. break;
  389. }
  390. if !relative.is_empty() {
  391. relative.push('/');
  392. }
  393. relative.push_str("..");
  394. }
  395. // Append the remainder of the other URI
  396. for url_path_segment in url_path {
  397. if !relative.is_empty() {
  398. relative.push('/');
  399. }
  400. relative.push_str(url_path_segment);
  401. }
  402. // Add the filename if they are not the same
  403. if !relative.is_empty() || base_filename != url_filename {
  404. // If the URIs filename is empty this means that it was a directory
  405. // so we'll have to append a '/'.
  406. //
  407. // Otherwise append it directly as the new filename.
  408. if url_filename.is_empty() {
  409. relative.push('/');
  410. } else {
  411. if !relative.is_empty() {
  412. relative.push('/');
  413. }
  414. relative.push_str(url_filename);
  415. }
  416. }
  417. // Query and fragment are only taken from the other URI
  418. if let Some(query) = url.query() {
  419. relative.push('?');
  420. relative.push_str(query);
  421. }
  422. if let Some(fragment) = url.fragment() {
  423. relative.push('#');
  424. relative.push_str(fragment);
  425. }
  426. Some(relative)
  427. }
  428. /// Return a default `ParseOptions` that can fully configure the URL parser.
  429. ///
  430. /// # Examples
  431. ///
  432. /// Get default `ParseOptions`, then change base url
  433. ///
  434. /// ```rust
  435. /// use url::Url;
  436. /// # use url::ParseError;
  437. /// # fn run() -> Result<(), ParseError> {
  438. /// let options = Url::options();
  439. /// let api = Url::parse("https://api.example.com")?;
  440. /// let base_url = options.base_url(Some(&api));
  441. /// let version_url = base_url.parse("version.json")?;
  442. /// assert_eq!(version_url.as_str(), "https://api.example.com/version.json");
  443. /// # Ok(())
  444. /// # }
  445. /// # run().unwrap();
  446. /// ```
  447. pub fn options<'a>() -> ParseOptions<'a> {
  448. ParseOptions {
  449. base_url: None,
  450. encoding_override: None,
  451. violation_fn: None,
  452. }
  453. }
  454. /// Return the serialization of this URL.
  455. ///
  456. /// This is fast since that serialization is already stored in the `Url` struct.
  457. ///
  458. /// # Examples
  459. ///
  460. /// ```rust
  461. /// use url::Url;
  462. /// # use url::ParseError;
  463. ///
  464. /// # fn run() -> Result<(), ParseError> {
  465. /// let url_str = "https://example.net/";
  466. /// let url = Url::parse(url_str)?;
  467. /// assert_eq!(url.as_str(), url_str);
  468. /// # Ok(())
  469. /// # }
  470. /// # run().unwrap();
  471. /// ```
  472. #[inline]
  473. pub fn as_str(&self) -> &str {
  474. &self.serialization
  475. }
  476. /// Return the serialization of this URL.
  477. ///
  478. /// This consumes the `Url` and takes ownership of the `String` stored in it.
  479. ///
  480. /// # Examples
  481. ///
  482. /// ```rust
  483. /// use url::Url;
  484. /// # use url::ParseError;
  485. ///
  486. /// # fn run() -> Result<(), ParseError> {
  487. /// let url_str = "https://example.net/";
  488. /// let url = Url::parse(url_str)?;
  489. /// assert_eq!(String::from(url), url_str);
  490. /// # Ok(())
  491. /// # }
  492. /// # run().unwrap();
  493. /// ```
  494. #[inline]
  495. #[deprecated(since = "2.3.0", note = "use Into<String>")]
  496. pub fn into_string(self) -> String {
  497. self.into()
  498. }
  499. /// For internal testing, not part of the public API.
  500. ///
  501. /// Methods of the `Url` struct assume a number of invariants.
  502. /// This checks each of these invariants and panic if one is not met.
  503. /// This is for testing rust-url itself.
  504. #[doc(hidden)]
  505. pub fn check_invariants(&self) -> Result<(), String> {
  506. macro_rules! assert {
  507. ($x: expr) => {
  508. if !$x {
  509. return Err(format!(
  510. "!( {} ) for URL {:?}",
  511. stringify!($x),
  512. self.serialization
  513. ));
  514. }
  515. };
  516. }
  517. macro_rules! assert_eq {
  518. ($a: expr, $b: expr) => {
  519. {
  520. let a = $a;
  521. let b = $b;
  522. if a != b {
  523. return Err(format!("{:?} != {:?} ({} != {}) for URL {:?}",
  524. a, b, stringify!($a), stringify!($b),
  525. self.serialization))
  526. }
  527. }
  528. }
  529. }
  530. assert!(self.scheme_end >= 1);
  531. assert!(matches!(self.byte_at(0), b'a'..=b'z' | b'A'..=b'Z'));
  532. assert!(self
  533. .slice(1..self.scheme_end)
  534. .chars()
  535. .all(|c| matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '+' | '-' | '.')));
  536. assert_eq!(self.byte_at(self.scheme_end), b':');
  537. if self.slice(self.scheme_end + 1..).starts_with("//") {
  538. // URL with authority
  539. if self.username_end != self.serialization.len() as u32 {
  540. match self.byte_at(self.username_end) {
  541. b':' => {
  542. assert!(self.host_start >= self.username_end + 2);
  543. assert_eq!(self.byte_at(self.host_start - 1), b'@');
  544. }
  545. b'@' => assert!(self.host_start == self.username_end + 1),
  546. _ => assert_eq!(self.username_end, self.scheme_end + 3),
  547. }
  548. }
  549. assert!(self.host_start >= self.username_end);
  550. assert!(self.host_end >= self.host_start);
  551. let host_str = self.slice(self.host_start..self.host_end);
  552. match self.host {
  553. HostInternal::None => assert_eq!(host_str, ""),
  554. HostInternal::Ipv4(address) => assert_eq!(host_str, address.to_string()),
  555. HostInternal::Ipv6(address) => {
  556. let h: Host<String> = Host::Ipv6(address);
  557. assert_eq!(host_str, h.to_string())
  558. }
  559. HostInternal::Domain => {
  560. if SchemeType::from(self.scheme()).is_special() {
  561. assert!(!host_str.is_empty())
  562. }
  563. }
  564. }
  565. if self.path_start == self.host_end {
  566. assert_eq!(self.port, None);
  567. } else {
  568. assert_eq!(self.byte_at(self.host_end), b':');
  569. let port_str = self.slice(self.host_end + 1..self.path_start);
  570. assert_eq!(
  571. self.port,
  572. Some(port_str.parse::<u16>().expect("Couldn't parse port?"))
  573. );
  574. }
  575. assert!(
  576. self.path_start as usize == self.serialization.len()
  577. || matches!(self.byte_at(self.path_start), b'/' | b'#' | b'?')
  578. );
  579. } else {
  580. // Anarchist URL (no authority)
  581. assert_eq!(self.username_end, self.scheme_end + 1);
  582. assert_eq!(self.host_start, self.scheme_end + 1);
  583. assert_eq!(self.host_end, self.scheme_end + 1);
  584. assert_eq!(self.host, HostInternal::None);
  585. assert_eq!(self.port, None);
  586. assert_eq!(self.path_start, self.scheme_end + 1);
  587. }
  588. if let Some(start) = self.query_start {
  589. assert!(start >= self.path_start);
  590. assert_eq!(self.byte_at(start), b'?');
  591. }
  592. if let Some(start) = self.fragment_start {
  593. assert!(start >= self.path_start);
  594. assert_eq!(self.byte_at(start), b'#');
  595. }
  596. if let (Some(query_start), Some(fragment_start)) = (self.query_start, self.fragment_start) {
  597. assert!(fragment_start > query_start);
  598. }
  599. let other = Url::parse(self.as_str()).expect("Failed to parse myself?");
  600. assert_eq!(&self.serialization, &other.serialization);
  601. assert_eq!(self.scheme_end, other.scheme_end);
  602. assert_eq!(self.username_end, other.username_end);
  603. assert_eq!(self.host_start, other.host_start);
  604. assert_eq!(self.host_end, other.host_end);
  605. assert!(
  606. self.host == other.host ||
  607. // XXX No host round-trips to empty host.
  608. // See https://github.com/whatwg/url/issues/79
  609. (self.host_str(), other.host_str()) == (None, Some(""))
  610. );
  611. assert_eq!(self.port, other.port);
  612. assert_eq!(self.path_start, other.path_start);
  613. assert_eq!(self.query_start, other.query_start);
  614. assert_eq!(self.fragment_start, other.fragment_start);
  615. Ok(())
  616. }
  617. /// Return the origin of this URL (<https://url.spec.whatwg.org/#origin>)
  618. ///
  619. /// Note: this returns an opaque origin for `file:` URLs, which causes
  620. /// `url.origin() != url.origin()`.
  621. ///
  622. /// # Examples
  623. ///
  624. /// URL with `ftp` scheme:
  625. ///
  626. /// ```rust
  627. /// use url::{Host, Origin, Url};
  628. /// # use url::ParseError;
  629. ///
  630. /// # fn run() -> Result<(), ParseError> {
  631. /// let url = Url::parse("ftp://example.com/foo")?;
  632. /// assert_eq!(url.origin(),
  633. /// Origin::Tuple("ftp".into(),
  634. /// Host::Domain("example.com".into()),
  635. /// 21));
  636. /// # Ok(())
  637. /// # }
  638. /// # run().unwrap();
  639. /// ```
  640. ///
  641. /// URL with `blob` scheme:
  642. ///
  643. /// ```rust
  644. /// use url::{Host, Origin, Url};
  645. /// # use url::ParseError;
  646. ///
  647. /// # fn run() -> Result<(), ParseError> {
  648. /// let url = Url::parse("blob:https://example.com/foo")?;
  649. /// assert_eq!(url.origin(),
  650. /// Origin::Tuple("https".into(),
  651. /// Host::Domain("example.com".into()),
  652. /// 443));
  653. /// # Ok(())
  654. /// # }
  655. /// # run().unwrap();
  656. /// ```
  657. ///
  658. /// URL with `file` scheme:
  659. ///
  660. /// ```rust
  661. /// use url::{Host, Origin, Url};
  662. /// # use url::ParseError;
  663. ///
  664. /// # fn run() -> Result<(), ParseError> {
  665. /// let url = Url::parse("file:///tmp/foo")?;
  666. /// assert!(!url.origin().is_tuple());
  667. ///
  668. /// let other_url = Url::parse("file:///tmp/foo")?;
  669. /// assert!(url.origin() != other_url.origin());
  670. /// # Ok(())
  671. /// # }
  672. /// # run().unwrap();
  673. /// ```
  674. ///
  675. /// URL with other scheme:
  676. ///
  677. /// ```rust
  678. /// use url::{Host, Origin, Url};
  679. /// # use url::ParseError;
  680. ///
  681. /// # fn run() -> Result<(), ParseError> {
  682. /// let url = Url::parse("foo:bar")?;
  683. /// assert!(!url.origin().is_tuple());
  684. /// # Ok(())
  685. /// # }
  686. /// # run().unwrap();
  687. /// ```
  688. #[inline]
  689. pub fn origin(&self) -> Origin {
  690. origin::url_origin(self)
  691. }
  692. /// Return the scheme of this URL, lower-cased, as an ASCII string without the ':' delimiter.
  693. ///
  694. /// # Examples
  695. ///
  696. /// ```
  697. /// use url::Url;
  698. /// # use url::ParseError;
  699. ///
  700. /// # fn run() -> Result<(), ParseError> {
  701. /// let url = Url::parse("file:///tmp/foo")?;
  702. /// assert_eq!(url.scheme(), "file");
  703. /// # Ok(())
  704. /// # }
  705. /// # run().unwrap();
  706. /// ```
  707. #[inline]
  708. pub fn scheme(&self) -> &str {
  709. self.slice(..self.scheme_end)
  710. }
  711. /// Return whether the URL has an 'authority',
  712. /// which can contain a username, password, host, and port number.
  713. ///
  714. /// URLs that do *not* are either path-only like `unix:/run/foo.socket`
  715. /// or cannot-be-a-base like `data:text/plain,Stuff`.
  716. ///
  717. /// See also the `authority` method.
  718. ///
  719. /// # Examples
  720. ///
  721. /// ```
  722. /// use url::Url;
  723. /// # use url::ParseError;
  724. ///
  725. /// # fn run() -> Result<(), ParseError> {
  726. /// let url = Url::parse("ftp://rms@example.com")?;
  727. /// assert!(url.has_authority());
  728. ///
  729. /// let url = Url::parse("unix:/run/foo.socket")?;
  730. /// assert!(!url.has_authority());
  731. ///
  732. /// let url = Url::parse("data:text/plain,Stuff")?;
  733. /// assert!(!url.has_authority());
  734. /// # Ok(())
  735. /// # }
  736. /// # run().unwrap();
  737. /// ```
  738. #[inline]
  739. pub fn has_authority(&self) -> bool {
  740. debug_assert!(self.byte_at(self.scheme_end) == b':');
  741. self.slice(self.scheme_end..).starts_with("://")
  742. }
  743. /// Return the authority of this URL as an ASCII string.
  744. ///
  745. /// Non-ASCII domains are punycode-encoded per IDNA if this is the host
  746. /// of a special URL, or percent encoded for non-special URLs.
  747. /// IPv6 addresses are given between `[` and `]` brackets.
  748. /// Ports are omitted if they match the well known port of a special URL.
  749. ///
  750. /// Username and password are percent-encoded.
  751. ///
  752. /// See also the `has_authority` method.
  753. ///
  754. /// # Examples
  755. ///
  756. /// ```
  757. /// use url::Url;
  758. /// # use url::ParseError;
  759. ///
  760. /// # fn run() -> Result<(), ParseError> {
  761. /// let url = Url::parse("unix:/run/foo.socket")?;
  762. /// assert_eq!(url.authority(), "");
  763. /// let url = Url::parse("file:///tmp/foo")?;
  764. /// assert_eq!(url.authority(), "");
  765. /// let url = Url::parse("https://user:password@example.com/tmp/foo")?;
  766. /// assert_eq!(url.authority(), "user:password@example.com");
  767. /// let url = Url::parse("irc://àlex.рф.example.com:6667/foo")?;
  768. /// assert_eq!(url.authority(), "%C3%A0lex.%D1%80%D1%84.example.com:6667");
  769. /// let url = Url::parse("http://àlex.рф.example.com:80/foo")?;
  770. /// assert_eq!(url.authority(), "xn--lex-8ka.xn--p1ai.example.com");
  771. /// # Ok(())
  772. /// # }
  773. /// # run().unwrap();
  774. /// ```
  775. pub fn authority(&self) -> &str {
  776. let scheme_separator_len = "://".len() as u32;
  777. if self.has_authority() && self.path_start > self.scheme_end + scheme_separator_len {
  778. self.slice(self.scheme_end + scheme_separator_len..self.path_start)
  779. } else {
  780. ""
  781. }
  782. }
  783. /// Return whether this URL is a cannot-be-a-base URL,
  784. /// meaning that parsing a relative URL string with this URL as the base will return an error.
  785. ///
  786. /// This is the case if the scheme and `:` delimiter are not followed by a `/` slash,
  787. /// as is typically the case of `data:` and `mailto:` URLs.
  788. ///
  789. /// # Examples
  790. ///
  791. /// ```
  792. /// use url::Url;
  793. /// # use url::ParseError;
  794. ///
  795. /// # fn run() -> Result<(), ParseError> {
  796. /// let url = Url::parse("ftp://rms@example.com")?;
  797. /// assert!(!url.cannot_be_a_base());
  798. ///
  799. /// let url = Url::parse("unix:/run/foo.socket")?;
  800. /// assert!(!url.cannot_be_a_base());
  801. ///
  802. /// let url = Url::parse("data:text/plain,Stuff")?;
  803. /// assert!(url.cannot_be_a_base());
  804. /// # Ok(())
  805. /// # }
  806. /// # run().unwrap();
  807. /// ```
  808. #[inline]
  809. pub fn cannot_be_a_base(&self) -> bool {
  810. !self.slice(self.scheme_end + 1..).starts_with('/')
  811. }
  812. /// Return the username for this URL (typically the empty string)
  813. /// as a percent-encoded ASCII string.
  814. ///
  815. /// # Examples
  816. ///
  817. /// ```
  818. /// use url::Url;
  819. /// # use url::ParseError;
  820. ///
  821. /// # fn run() -> Result<(), ParseError> {
  822. /// let url = Url::parse("ftp://rms@example.com")?;
  823. /// assert_eq!(url.username(), "rms");
  824. ///
  825. /// let url = Url::parse("ftp://:secret123@example.com")?;
  826. /// assert_eq!(url.username(), "");
  827. ///
  828. /// let url = Url::parse("https://example.com")?;
  829. /// assert_eq!(url.username(), "");
  830. /// # Ok(())
  831. /// # }
  832. /// # run().unwrap();
  833. /// ```
  834. pub fn username(&self) -> &str {
  835. let scheme_separator_len = "://".len() as u32;
  836. if self.has_authority() && self.username_end > self.scheme_end + scheme_separator_len {
  837. self.slice(self.scheme_end + scheme_separator_len..self.username_end)
  838. } else {
  839. ""
  840. }
  841. }
  842. /// Return the password for this URL, if any, as a percent-encoded ASCII string.
  843. ///
  844. /// # Examples
  845. ///
  846. /// ```
  847. /// use url::Url;
  848. /// # use url::ParseError;
  849. ///
  850. /// # fn run() -> Result<(), ParseError> {
  851. /// let url = Url::parse("ftp://rms:secret123@example.com")?;
  852. /// assert_eq!(url.password(), Some("secret123"));
  853. ///
  854. /// let url = Url::parse("ftp://:secret123@example.com")?;
  855. /// assert_eq!(url.password(), Some("secret123"));
  856. ///
  857. /// let url = Url::parse("ftp://rms@example.com")?;
  858. /// assert_eq!(url.password(), None);
  859. ///
  860. /// let url = Url::parse("https://example.com")?;
  861. /// assert_eq!(url.password(), None);
  862. /// # Ok(())
  863. /// # }
  864. /// # run().unwrap();
  865. /// ```
  866. pub fn password(&self) -> Option<&str> {
  867. // This ':' is not the one marking a port number since a host can not be empty.
  868. // (Except for file: URLs, which do not have port numbers.)
  869. if self.has_authority()
  870. && self.username_end != self.serialization.len() as u32
  871. && self.byte_at(self.username_end) == b':'
  872. {
  873. debug_assert!(self.byte_at(self.host_start - 1) == b'@');
  874. Some(self.slice(self.username_end + 1..self.host_start - 1))
  875. } else {
  876. None
  877. }
  878. }
  879. /// Equivalent to `url.host().is_some()`.
  880. ///
  881. /// # Examples
  882. ///
  883. /// ```
  884. /// use url::Url;
  885. /// # use url::ParseError;
  886. ///
  887. /// # fn run() -> Result<(), ParseError> {
  888. /// let url = Url::parse("ftp://rms@example.com")?;
  889. /// assert!(url.has_host());
  890. ///
  891. /// let url = Url::parse("unix:/run/foo.socket")?;
  892. /// assert!(!url.has_host());
  893. ///
  894. /// let url = Url::parse("data:text/plain,Stuff")?;
  895. /// assert!(!url.has_host());
  896. /// # Ok(())
  897. /// # }
  898. /// # run().unwrap();
  899. /// ```
  900. pub fn has_host(&self) -> bool {
  901. !matches!(self.host, HostInternal::None)
  902. }
  903. /// Return the string representation of the host (domain or IP address) for this URL, if any.
  904. ///
  905. /// Non-ASCII domains are punycode-encoded per IDNA if this is the host
  906. /// of a special URL, or percent encoded for non-special URLs.
  907. /// IPv6 addresses are given between `[` and `]` brackets.
  908. ///
  909. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  910. /// don’t have a host.
  911. ///
  912. /// See also the `host` method.
  913. ///
  914. /// # Examples
  915. ///
  916. /// ```
  917. /// use url::Url;
  918. /// # use url::ParseError;
  919. ///
  920. /// # fn run() -> Result<(), ParseError> {
  921. /// let url = Url::parse("https://127.0.0.1/index.html")?;
  922. /// assert_eq!(url.host_str(), Some("127.0.0.1"));
  923. ///
  924. /// let url = Url::parse("ftp://rms@example.com")?;
  925. /// assert_eq!(url.host_str(), Some("example.com"));
  926. ///
  927. /// let url = Url::parse("unix:/run/foo.socket")?;
  928. /// assert_eq!(url.host_str(), None);
  929. ///
  930. /// let url = Url::parse("data:text/plain,Stuff")?;
  931. /// assert_eq!(url.host_str(), None);
  932. /// # Ok(())
  933. /// # }
  934. /// # run().unwrap();
  935. /// ```
  936. pub fn host_str(&self) -> Option<&str> {
  937. if self.has_host() {
  938. Some(self.slice(self.host_start..self.host_end))
  939. } else {
  940. None
  941. }
  942. }
  943. /// Return the parsed representation of the host for this URL.
  944. /// Non-ASCII domain labels are punycode-encoded per IDNA if this is the host
  945. /// of a special URL, or percent encoded for non-special URLs.
  946. ///
  947. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  948. /// don’t have a host.
  949. ///
  950. /// See also the `host_str` method.
  951. ///
  952. /// # Examples
  953. ///
  954. /// ```
  955. /// use url::Url;
  956. /// # use url::ParseError;
  957. ///
  958. /// # fn run() -> Result<(), ParseError> {
  959. /// let url = Url::parse("https://127.0.0.1/index.html")?;
  960. /// assert!(url.host().is_some());
  961. ///
  962. /// let url = Url::parse("ftp://rms@example.com")?;
  963. /// assert!(url.host().is_some());
  964. ///
  965. /// let url = Url::parse("unix:/run/foo.socket")?;
  966. /// assert!(url.host().is_none());
  967. ///
  968. /// let url = Url::parse("data:text/plain,Stuff")?;
  969. /// assert!(url.host().is_none());
  970. /// # Ok(())
  971. /// # }
  972. /// # run().unwrap();
  973. /// ```
  974. pub fn host(&self) -> Option<Host<&str>> {
  975. match self.host {
  976. HostInternal::None => None,
  977. HostInternal::Domain => Some(Host::Domain(self.slice(self.host_start..self.host_end))),
  978. HostInternal::Ipv4(address) => Some(Host::Ipv4(address)),
  979. HostInternal::Ipv6(address) => Some(Host::Ipv6(address)),
  980. }
  981. }
  982. /// If this URL has a host and it is a domain name (not an IP address), return it.
  983. /// Non-ASCII domains are punycode-encoded per IDNA if this is the host
  984. /// of a special URL, or percent encoded for non-special URLs.
  985. ///
  986. /// # Examples
  987. ///
  988. /// ```
  989. /// use url::Url;
  990. /// # use url::ParseError;
  991. ///
  992. /// # fn run() -> Result<(), ParseError> {
  993. /// let url = Url::parse("https://127.0.0.1/")?;
  994. /// assert_eq!(url.domain(), None);
  995. ///
  996. /// let url = Url::parse("mailto:rms@example.net")?;
  997. /// assert_eq!(url.domain(), None);
  998. ///
  999. /// let url = Url::parse("https://example.com/")?;
  1000. /// assert_eq!(url.domain(), Some("example.com"));
  1001. /// # Ok(())
  1002. /// # }
  1003. /// # run().unwrap();
  1004. /// ```
  1005. pub fn domain(&self) -> Option<&str> {
  1006. match self.host {
  1007. HostInternal::Domain => Some(self.slice(self.host_start..self.host_end)),
  1008. _ => None,
  1009. }
  1010. }
  1011. /// Return the port number for this URL, if any.
  1012. ///
  1013. /// Note that default port numbers are never reflected by the serialization,
  1014. /// use the `port_or_known_default()` method if you want a default port number returned.
  1015. ///
  1016. /// # Examples
  1017. ///
  1018. /// ```
  1019. /// use url::Url;
  1020. /// # use url::ParseError;
  1021. ///
  1022. /// # fn run() -> Result<(), ParseError> {
  1023. /// let url = Url::parse("https://example.com")?;
  1024. /// assert_eq!(url.port(), None);
  1025. ///
  1026. /// let url = Url::parse("https://example.com:443/")?;
  1027. /// assert_eq!(url.port(), None);
  1028. ///
  1029. /// let url = Url::parse("ssh://example.com:22")?;
  1030. /// assert_eq!(url.port(), Some(22));
  1031. /// # Ok(())
  1032. /// # }
  1033. /// # run().unwrap();
  1034. /// ```
  1035. #[inline]
  1036. pub fn port(&self) -> Option<u16> {
  1037. self.port
  1038. }
  1039. /// Return the port number for this URL, or the default port number if it is known.
  1040. ///
  1041. /// This method only knows the default port number
  1042. /// of the `http`, `https`, `ws`, `wss` and `ftp` schemes.
  1043. ///
  1044. /// For URLs in these schemes, this method always returns `Some(_)`.
  1045. /// For other schemes, it is the same as `Url::port()`.
  1046. ///
  1047. /// # Examples
  1048. ///
  1049. /// ```
  1050. /// use url::Url;
  1051. /// # use url::ParseError;
  1052. ///
  1053. /// # fn run() -> Result<(), ParseError> {
  1054. /// let url = Url::parse("foo://example.com")?;
  1055. /// assert_eq!(url.port_or_known_default(), None);
  1056. ///
  1057. /// let url = Url::parse("foo://example.com:1456")?;
  1058. /// assert_eq!(url.port_or_known_default(), Some(1456));
  1059. ///
  1060. /// let url = Url::parse("https://example.com")?;
  1061. /// assert_eq!(url.port_or_known_default(), Some(443));
  1062. /// # Ok(())
  1063. /// # }
  1064. /// # run().unwrap();
  1065. /// ```
  1066. #[inline]
  1067. pub fn port_or_known_default(&self) -> Option<u16> {
  1068. self.port.or_else(|| parser::default_port(self.scheme()))
  1069. }
  1070. /// Resolve a URL’s host and port number to `SocketAddr`.
  1071. ///
  1072. /// If the URL has the default port number of a scheme that is unknown to this library,
  1073. /// `default_port_number` provides an opportunity to provide the actual port number.
  1074. /// In non-example code this should be implemented either simply as `|| None`,
  1075. /// or by matching on the URL’s `.scheme()`.
  1076. ///
  1077. /// If the host is a domain, it is resolved using the standard library’s DNS support.
  1078. ///
  1079. /// # Examples
  1080. ///
  1081. /// ```no_run
  1082. /// let url = url::Url::parse("https://example.net/").unwrap();
  1083. /// let addrs = url.socket_addrs(|| None).unwrap();
  1084. /// std::net::TcpStream::connect(&*addrs)
  1085. /// # ;
  1086. /// ```
  1087. ///
  1088. /// ```
  1089. /// /// With application-specific known default port numbers
  1090. /// fn socket_addrs(url: url::Url) -> std::io::Result<Vec<std::net::SocketAddr>> {
  1091. /// url.socket_addrs(|| match url.scheme() {
  1092. /// "socks5" | "socks5h" => Some(1080),
  1093. /// _ => None,
  1094. /// })
  1095. /// }
  1096. /// ```
  1097. pub fn socket_addrs(
  1098. &self,
  1099. default_port_number: impl Fn() -> Option<u16>,
  1100. ) -> io::Result<Vec<SocketAddr>> {
  1101. // Note: trying to avoid the Vec allocation by returning `impl AsRef<[SocketAddr]>`
  1102. // causes borrowck issues because the return value borrows `default_port_number`:
  1103. //
  1104. // https://github.com/rust-lang/rfcs/blob/master/text/1951-expand-impl-trait.md#scoping-for-type-and-lifetime-parameters
  1105. //
  1106. // > This RFC proposes that *all* type parameters are considered in scope
  1107. // > for `impl Trait` in return position
  1108. fn io_result<T>(opt: Option<T>, message: &str) -> io::Result<T> {
  1109. opt.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, message))
  1110. }
  1111. let host = io_result(self.host(), "No host name in the URL")?;
  1112. let port = io_result(
  1113. self.port_or_known_default().or_else(default_port_number),
  1114. "No port number in the URL",
  1115. )?;
  1116. Ok(match host {
  1117. Host::Domain(domain) => (domain, port).to_socket_addrs()?.collect(),
  1118. Host::Ipv4(ip) => vec![(ip, port).into()],
  1119. Host::Ipv6(ip) => vec![(ip, port).into()],
  1120. })
  1121. }
  1122. /// Return the path for this URL, as a percent-encoded ASCII string.
  1123. /// For cannot-be-a-base URLs, this is an arbitrary string that doesn’t start with '/'.
  1124. /// For other URLs, this starts with a '/' slash
  1125. /// and continues with slash-separated path segments.
  1126. ///
  1127. /// # Examples
  1128. ///
  1129. /// ```rust
  1130. /// use url::{Url, ParseError};
  1131. ///
  1132. /// # fn run() -> Result<(), ParseError> {
  1133. /// let url = Url::parse("https://example.com/api/versions?page=2")?;
  1134. /// assert_eq!(url.path(), "/api/versions");
  1135. ///
  1136. /// let url = Url::parse("https://example.com")?;
  1137. /// assert_eq!(url.path(), "/");
  1138. ///
  1139. /// let url = Url::parse("https://example.com/countries/việt nam")?;
  1140. /// assert_eq!(url.path(), "/countries/vi%E1%BB%87t%20nam");
  1141. /// # Ok(())
  1142. /// # }
  1143. /// # run().unwrap();
  1144. /// ```
  1145. pub fn path(&self) -> &str {
  1146. match (self.query_start, self.fragment_start) {
  1147. (None, None) => self.slice(self.path_start..),
  1148. (Some(next_component_start), _) | (None, Some(next_component_start)) => {
  1149. self.slice(self.path_start..next_component_start)
  1150. }
  1151. }
  1152. }
  1153. /// Unless this URL is cannot-be-a-base,
  1154. /// return an iterator of '/' slash-separated path segments,
  1155. /// each as a percent-encoded ASCII string.
  1156. ///
  1157. /// Return `None` for cannot-be-a-base URLs.
  1158. ///
  1159. /// When `Some` is returned, the iterator always contains at least one string
  1160. /// (which may be empty).
  1161. ///
  1162. /// # Examples
  1163. ///
  1164. /// ```
  1165. /// use url::Url;
  1166. /// # use std::error::Error;
  1167. ///
  1168. /// # fn run() -> Result<(), Box<dyn Error>> {
  1169. /// let url = Url::parse("https://example.com/foo/bar")?;
  1170. /// let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
  1171. /// assert_eq!(path_segments.next(), Some("foo"));
  1172. /// assert_eq!(path_segments.next(), Some("bar"));
  1173. /// assert_eq!(path_segments.next(), None);
  1174. ///
  1175. /// let url = Url::parse("https://example.com")?;
  1176. /// let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
  1177. /// assert_eq!(path_segments.next(), Some(""));
  1178. /// assert_eq!(path_segments.next(), None);
  1179. ///
  1180. /// let url = Url::parse("data:text/plain,HelloWorld")?;
  1181. /// assert!(url.path_segments().is_none());
  1182. ///
  1183. /// let url = Url::parse("https://example.com/countries/việt nam")?;
  1184. /// let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
  1185. /// assert_eq!(path_segments.next(), Some("countries"));
  1186. /// assert_eq!(path_segments.next(), Some("vi%E1%BB%87t%20nam"));
  1187. /// # Ok(())
  1188. /// # }
  1189. /// # run().unwrap();
  1190. /// ```
  1191. pub fn path_segments(&self) -> Option<str::Split<'_, char>> {
  1192. let path = self.path();
  1193. path.strip_prefix('/').map(|remainder| remainder.split('/'))
  1194. }
  1195. /// Return this URL’s query string, if any, as a percent-encoded ASCII string.
  1196. ///
  1197. /// # Examples
  1198. ///
  1199. /// ```rust
  1200. /// use url::Url;
  1201. /// # use url::ParseError;
  1202. ///
  1203. /// fn run() -> Result<(), ParseError> {
  1204. /// let url = Url::parse("https://example.com/products?page=2")?;
  1205. /// let query = url.query();
  1206. /// assert_eq!(query, Some("page=2"));
  1207. ///
  1208. /// let url = Url::parse("https://example.com/products")?;
  1209. /// let query = url.query();
  1210. /// assert!(query.is_none());
  1211. ///
  1212. /// let url = Url::parse("https://example.com/?country=español")?;
  1213. /// let query = url.query();
  1214. /// assert_eq!(query, Some("country=espa%C3%B1ol"));
  1215. /// # Ok(())
  1216. /// # }
  1217. /// # run().unwrap();
  1218. /// ```
  1219. pub fn query(&self) -> Option<&str> {
  1220. match (self.query_start, self.fragment_start) {
  1221. (None, _) => None,
  1222. (Some(query_start), None) => {
  1223. debug_assert!(self.byte_at(query_start) == b'?');
  1224. Some(self.slice(query_start + 1..))
  1225. }
  1226. (Some(query_start), Some(fragment_start)) => {
  1227. debug_assert!(self.byte_at(query_start) == b'?');
  1228. Some(self.slice(query_start + 1..fragment_start))
  1229. }
  1230. }
  1231. }
  1232. /// Parse the URL’s query string, if any, as `application/x-www-form-urlencoded`
  1233. /// and return an iterator of (key, value) pairs.
  1234. ///
  1235. /// # Examples
  1236. ///
  1237. /// ```rust
  1238. /// use std::borrow::Cow;
  1239. ///
  1240. /// use url::Url;
  1241. /// # use url::ParseError;
  1242. ///
  1243. /// # fn run() -> Result<(), ParseError> {
  1244. /// let url = Url::parse("https://example.com/products?page=2&sort=desc")?;
  1245. /// let mut pairs = url.query_pairs();
  1246. ///
  1247. /// assert_eq!(pairs.count(), 2);
  1248. ///
  1249. /// assert_eq!(pairs.next(), Some((Cow::Borrowed("page"), Cow::Borrowed("2"))));
  1250. /// assert_eq!(pairs.next(), Some((Cow::Borrowed("sort"), Cow::Borrowed("desc"))));
  1251. /// # Ok(())
  1252. /// # }
  1253. /// # run().unwrap();
  1254. /// ```
  1255. #[inline]
  1256. pub fn query_pairs(&self) -> form_urlencoded::Parse<'_> {
  1257. form_urlencoded::parse(self.query().unwrap_or("").as_bytes())
  1258. }
  1259. /// Return this URL’s fragment identifier, if any.
  1260. ///
  1261. /// A fragment is the part of the URL after the `#` symbol.
  1262. /// The fragment is optional and, if present, contains a fragment identifier
  1263. /// that identifies a secondary resource, such as a section heading
  1264. /// of a document.
  1265. ///
  1266. /// In HTML, the fragment identifier is usually the id attribute of a an element
  1267. /// that is scrolled to on load. Browsers typically will not send the fragment portion
  1268. /// of a URL to the server.
  1269. ///
  1270. /// **Note:** the parser did *not* percent-encode this component,
  1271. /// but the input may have been percent-encoded already.
  1272. ///
  1273. /// # Examples
  1274. ///
  1275. /// ```rust
  1276. /// use url::Url;
  1277. /// # use url::ParseError;
  1278. ///
  1279. /// # fn run() -> Result<(), ParseError> {
  1280. /// let url = Url::parse("https://example.com/data.csv#row=4")?;
  1281. ///
  1282. /// assert_eq!(url.fragment(), Some("row=4"));
  1283. ///
  1284. /// let url = Url::parse("https://example.com/data.csv#cell=4,1-6,2")?;
  1285. ///
  1286. /// assert_eq!(url.fragment(), Some("cell=4,1-6,2"));
  1287. /// # Ok(())
  1288. /// # }
  1289. /// # run().unwrap();
  1290. /// ```
  1291. pub fn fragment(&self) -> Option<&str> {
  1292. self.fragment_start.map(|start| {
  1293. debug_assert!(self.byte_at(start) == b'#');
  1294. self.slice(start + 1..)
  1295. })
  1296. }
  1297. fn mutate<F: FnOnce(&mut Parser<'_>) -> R, R>(&mut self, f: F) -> R {
  1298. let mut parser = Parser::for_setter(mem::take(&mut self.serialization));
  1299. let result = f(&mut parser);
  1300. self.serialization = parser.serialization;
  1301. result
  1302. }
  1303. /// Change this URL’s fragment identifier.
  1304. ///
  1305. /// # Examples
  1306. ///
  1307. /// ```rust
  1308. /// use url::Url;
  1309. /// # use url::ParseError;
  1310. ///
  1311. /// # fn run() -> Result<(), ParseError> {
  1312. /// let mut url = Url::parse("https://example.com/data.csv")?;
  1313. /// assert_eq!(url.as_str(), "https://example.com/data.csv");
  1314. /// url.set_fragment(Some("cell=4,1-6,2"));
  1315. /// assert_eq!(url.as_str(), "https://example.com/data.csv#cell=4,1-6,2");
  1316. /// assert_eq!(url.fragment(), Some("cell=4,1-6,2"));
  1317. ///
  1318. /// url.set_fragment(None);
  1319. /// assert_eq!(url.as_str(), "https://example.com/data.csv");
  1320. /// assert!(url.fragment().is_none());
  1321. /// # Ok(())
  1322. /// # }
  1323. /// # run().unwrap();
  1324. /// ```
  1325. pub fn set_fragment(&mut self, fragment: Option<&str>) {
  1326. // Remove any previous fragment
  1327. if let Some(start) = self.fragment_start {
  1328. debug_assert!(self.byte_at(start) == b'#');
  1329. self.serialization.truncate(start as usize);
  1330. }
  1331. // Write the new one
  1332. if let Some(input) = fragment {
  1333. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  1334. self.serialization.push('#');
  1335. self.mutate(|parser| parser.parse_fragment(parser::Input::no_trim(input)))
  1336. } else {
  1337. self.fragment_start = None
  1338. }
  1339. }
  1340. fn take_fragment(&mut self) -> Option<String> {
  1341. self.fragment_start.take().map(|start| {
  1342. debug_assert!(self.byte_at(start) == b'#');
  1343. let fragment = self.slice(start + 1..).to_owned();
  1344. self.serialization.truncate(start as usize);
  1345. fragment
  1346. })
  1347. }
  1348. fn restore_already_parsed_fragment(&mut self, fragment: Option<String>) {
  1349. if let Some(ref fragment) = fragment {
  1350. assert!(self.fragment_start.is_none());
  1351. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  1352. self.serialization.push('#');
  1353. self.serialization.push_str(fragment);
  1354. }
  1355. }
  1356. /// Change this URL’s query string.
  1357. ///
  1358. /// # Examples
  1359. ///
  1360. /// ```rust
  1361. /// use url::Url;
  1362. /// # use url::ParseError;
  1363. ///
  1364. /// # fn run() -> Result<(), ParseError> {
  1365. /// let mut url = Url::parse("https://example.com/products")?;
  1366. /// assert_eq!(url.as_str(), "https://example.com/products");
  1367. ///
  1368. /// url.set_query(Some("page=2"));
  1369. /// assert_eq!(url.as_str(), "https://example.com/products?page=2");
  1370. /// assert_eq!(url.query(), Some("page=2"));
  1371. /// # Ok(())
  1372. /// # }
  1373. /// # run().unwrap();
  1374. /// ```
  1375. pub fn set_query(&mut self, query: Option<&str>) {
  1376. let fragment = self.take_fragment();
  1377. // Remove any previous query
  1378. if let Some(start) = self.query_start.take() {
  1379. debug_assert!(self.byte_at(start) == b'?');
  1380. self.serialization.truncate(start as usize);
  1381. }
  1382. // Write the new query, if any
  1383. if let Some(input) = query {
  1384. self.query_start = Some(to_u32(self.serialization.len()).unwrap());
  1385. self.serialization.push('?');
  1386. let scheme_type = SchemeType::from(self.scheme());
  1387. let scheme_end = self.scheme_end;
  1388. self.mutate(|parser| {
  1389. let vfn = parser.violation_fn;
  1390. parser.parse_query(
  1391. scheme_type,
  1392. scheme_end,
  1393. parser::Input::trim_tab_and_newlines(input, vfn),
  1394. )
  1395. });
  1396. }
  1397. self.restore_already_parsed_fragment(fragment);
  1398. }
  1399. /// Manipulate this URL’s query string, viewed as a sequence of name/value pairs
  1400. /// in `application/x-www-form-urlencoded` syntax.
  1401. ///
  1402. /// The return value has a method-chaining API:
  1403. ///
  1404. /// ```rust
  1405. /// # use url::{Url, ParseError};
  1406. ///
  1407. /// # fn run() -> Result<(), ParseError> {
  1408. /// let mut url = Url::parse("https://example.net?lang=fr#nav")?;
  1409. /// assert_eq!(url.query(), Some("lang=fr"));
  1410. ///
  1411. /// url.query_pairs_mut().append_pair("foo", "bar");
  1412. /// assert_eq!(url.query(), Some("lang=fr&foo=bar"));
  1413. /// assert_eq!(url.as_str(), "https://example.net/?lang=fr&foo=bar#nav");
  1414. ///
  1415. /// url.query_pairs_mut()
  1416. /// .clear()
  1417. /// .append_pair("foo", "bar & baz")
  1418. /// .append_pair("saisons", "\u{00C9}t\u{00E9}+hiver");
  1419. /// assert_eq!(url.query(), Some("foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver"));
  1420. /// assert_eq!(url.as_str(),
  1421. /// "https://example.net/?foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver#nav");
  1422. /// # Ok(())
  1423. /// # }
  1424. /// # run().unwrap();
  1425. /// ```
  1426. ///
  1427. /// Note: `url.query_pairs_mut().clear();` is equivalent to `url.set_query(Some(""))`,
  1428. /// not `url.set_query(None)`.
  1429. ///
  1430. /// The state of `Url` is unspecified if this return value is leaked without being dropped.
  1431. pub fn query_pairs_mut(&mut self) -> form_urlencoded::Serializer<'_, UrlQuery<'_>> {
  1432. let fragment = self.take_fragment();
  1433. let query_start;
  1434. if let Some(start) = self.query_start {
  1435. debug_assert!(self.byte_at(start) == b'?');
  1436. query_start = start as usize;
  1437. } else {
  1438. query_start = self.serialization.len();
  1439. self.query_start = Some(to_u32(query_start).unwrap());
  1440. self.serialization.push('?');
  1441. }
  1442. let query = UrlQuery {
  1443. url: Some(self),
  1444. fragment,
  1445. };
  1446. form_urlencoded::Serializer::for_suffix(query, query_start + "?".len())
  1447. }
  1448. fn take_after_path(&mut self) -> String {
  1449. match (self.query_start, self.fragment_start) {
  1450. (Some(i), _) | (None, Some(i)) => {
  1451. let after_path = self.slice(i..).to_owned();
  1452. self.serialization.truncate(i as usize);
  1453. after_path
  1454. }
  1455. (None, None) => String::new(),
  1456. }
  1457. }
  1458. /// Change this URL’s path.
  1459. ///
  1460. /// # Examples
  1461. ///
  1462. /// ```rust
  1463. /// use url::Url;
  1464. /// # use url::ParseError;
  1465. ///
  1466. /// # fn run() -> Result<(), ParseError> {
  1467. /// let mut url = Url::parse("https://example.com")?;
  1468. /// url.set_path("api/comments");
  1469. /// assert_eq!(url.as_str(), "https://example.com/api/comments");
  1470. /// assert_eq!(url.path(), "/api/comments");
  1471. ///
  1472. /// let mut url = Url::parse("https://example.com/api")?;
  1473. /// url.set_path("data/report.csv");
  1474. /// assert_eq!(url.as_str(), "https://example.com/data/report.csv");
  1475. /// assert_eq!(url.path(), "/data/report.csv");
  1476. ///
  1477. /// // `set_path` percent-encodes the given string if it's not already percent-encoded.
  1478. /// let mut url = Url::parse("https://example.com")?;
  1479. /// url.set_path("api/some comments");
  1480. /// assert_eq!(url.as_str(), "https://example.com/api/some%20comments");
  1481. /// assert_eq!(url.path(), "/api/some%20comments");
  1482. ///
  1483. /// // `set_path` will not double percent-encode the string if it's already percent-encoded.
  1484. /// let mut url = Url::parse("https://example.com")?;
  1485. /// url.set_path("api/some%20comments");
  1486. /// assert_eq!(url.as_str(), "https://example.com/api/some%20comments");
  1487. /// assert_eq!(url.path(), "/api/some%20comments");
  1488. ///
  1489. /// # Ok(())
  1490. /// # }
  1491. /// # run().unwrap();
  1492. /// ```
  1493. pub fn set_path(&mut self, mut path: &str) {
  1494. let after_path = self.take_after_path();
  1495. let old_after_path_pos = to_u32(self.serialization.len()).unwrap();
  1496. let cannot_be_a_base = self.cannot_be_a_base();
  1497. let scheme_type = SchemeType::from(self.scheme());
  1498. self.serialization.truncate(self.path_start as usize);
  1499. self.mutate(|parser| {
  1500. if cannot_be_a_base {
  1501. if path.starts_with('/') {
  1502. parser.serialization.push_str("%2F");
  1503. path = &path[1..];
  1504. }
  1505. parser.parse_cannot_be_a_base_path(parser::Input::new(path));
  1506. } else {
  1507. let mut has_host = true; // FIXME
  1508. parser.parse_path_start(scheme_type, &mut has_host, parser::Input::new(path));
  1509. }
  1510. });
  1511. self.restore_after_path(old_after_path_pos, &after_path);
  1512. }
  1513. /// Return an object with methods to manipulate this URL’s path segments.
  1514. ///
  1515. /// Return `Err(())` if this URL is cannot-be-a-base.
  1516. #[allow(clippy::result_unit_err)]
  1517. pub fn path_segments_mut(&mut self) -> Result<PathSegmentsMut<'_>, ()> {
  1518. if self.cannot_be_a_base() {
  1519. Err(())
  1520. } else {
  1521. Ok(path_segments::new(self))
  1522. }
  1523. }
  1524. fn restore_after_path(&mut self, old_after_path_position: u32, after_path: &str) {
  1525. let new_after_path_position = to_u32(self.serialization.len()).unwrap();
  1526. let adjust = |index: &mut u32| {
  1527. *index -= old_after_path_position;
  1528. *index += new_after_path_position;
  1529. };
  1530. if let Some(ref mut index) = self.query_start {
  1531. adjust(index)
  1532. }
  1533. if let Some(ref mut index) = self.fragment_start {
  1534. adjust(index)
  1535. }
  1536. self.serialization.push_str(after_path)
  1537. }
  1538. /// Change this URL’s port number.
  1539. ///
  1540. /// Note that default port numbers are not reflected in the serialization.
  1541. ///
  1542. /// If this URL is cannot-be-a-base, does not have a host, or has the `file` scheme;
  1543. /// do nothing and return `Err`.
  1544. ///
  1545. /// # Examples
  1546. ///
  1547. /// ```
  1548. /// use url::Url;
  1549. /// # use std::error::Error;
  1550. ///
  1551. /// # fn run() -> Result<(), Box<dyn Error>> {
  1552. /// let mut url = Url::parse("ssh://example.net:2048/")?;
  1553. ///
  1554. /// url.set_port(Some(4096)).map_err(|_| "cannot be base")?;
  1555. /// assert_eq!(url.as_str(), "ssh://example.net:4096/");
  1556. ///
  1557. /// url.set_port(None).map_err(|_| "cannot be base")?;
  1558. /// assert_eq!(url.as_str(), "ssh://example.net/");
  1559. /// # Ok(())
  1560. /// # }
  1561. /// # run().unwrap();
  1562. /// ```
  1563. ///
  1564. /// Known default port numbers are not reflected:
  1565. ///
  1566. /// ```rust
  1567. /// use url::Url;
  1568. /// # use std::error::Error;
  1569. ///
  1570. /// # fn run() -> Result<(), Box<dyn Error>> {
  1571. /// let mut url = Url::parse("https://example.org/")?;
  1572. ///
  1573. /// url.set_port(Some(443)).map_err(|_| "cannot be base")?;
  1574. /// assert!(url.port().is_none());
  1575. /// # Ok(())
  1576. /// # }
  1577. /// # run().unwrap();
  1578. /// ```
  1579. ///
  1580. /// Cannot set port for cannot-be-a-base URLs:
  1581. ///
  1582. /// ```
  1583. /// use url::Url;
  1584. /// # use url::ParseError;
  1585. ///
  1586. /// # fn run() -> Result<(), ParseError> {
  1587. /// let mut url = Url::parse("mailto:rms@example.net")?;
  1588. ///
  1589. /// let result = url.set_port(Some(80));
  1590. /// assert!(result.is_err());
  1591. ///
  1592. /// let result = url.set_port(None);
  1593. /// assert!(result.is_err());
  1594. /// # Ok(())
  1595. /// # }
  1596. /// # run().unwrap();
  1597. /// ```
  1598. #[allow(clippy::result_unit_err)]
  1599. pub fn set_port(&mut self, mut port: Option<u16>) -> Result<(), ()> {
  1600. // has_host implies !cannot_be_a_base
  1601. if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
  1602. return Err(());
  1603. }
  1604. if port.is_some() && port == parser::default_port(self.scheme()) {
  1605. port = None
  1606. }
  1607. self.set_port_internal(port);
  1608. Ok(())
  1609. }
  1610. fn set_port_internal(&mut self, port: Option<u16>) {
  1611. match (self.port, port) {
  1612. (None, None) => {}
  1613. (Some(_), None) => {
  1614. self.serialization
  1615. .drain(self.host_end as usize..self.path_start as usize);
  1616. let offset = self.path_start - self.host_end;
  1617. self.path_start = self.host_end;
  1618. if let Some(ref mut index) = self.query_start {
  1619. *index -= offset
  1620. }
  1621. if let Some(ref mut index) = self.fragment_start {
  1622. *index -= offset
  1623. }
  1624. }
  1625. (Some(old), Some(new)) if old == new => {}
  1626. (_, Some(new)) => {
  1627. let path_and_after = self.slice(self.path_start..).to_owned();
  1628. self.serialization.truncate(self.host_end as usize);
  1629. write!(&mut self.serialization, ":{}", new).unwrap();
  1630. let old_path_start = self.path_start;
  1631. let new_path_start = to_u32(self.serialization.len()).unwrap();
  1632. self.path_start = new_path_start;
  1633. let adjust = |index: &mut u32| {
  1634. *index -= old_path_start;
  1635. *index += new_path_start;
  1636. };
  1637. if let Some(ref mut index) = self.query_start {
  1638. adjust(index)
  1639. }
  1640. if let Some(ref mut index) = self.fragment_start {
  1641. adjust(index)
  1642. }
  1643. self.serialization.push_str(&path_and_after);
  1644. }
  1645. }
  1646. self.port = port;
  1647. }
  1648. /// Change this URL’s host.
  1649. ///
  1650. /// Removing the host (calling this with `None`)
  1651. /// will also remove any username, password, and port number.
  1652. ///
  1653. /// # Examples
  1654. ///
  1655. /// Change host:
  1656. ///
  1657. /// ```
  1658. /// use url::Url;
  1659. /// # use url::ParseError;
  1660. ///
  1661. /// # fn run() -> Result<(), ParseError> {
  1662. /// let mut url = Url::parse("https://example.net")?;
  1663. /// let result = url.set_host(Some("rust-lang.org"));
  1664. /// assert!(result.is_ok());
  1665. /// assert_eq!(url.as_str(), "https://rust-lang.org/");
  1666. /// # Ok(())
  1667. /// # }
  1668. /// # run().unwrap();
  1669. /// ```
  1670. ///
  1671. /// Remove host:
  1672. ///
  1673. /// ```
  1674. /// use url::Url;
  1675. /// # use url::ParseError;
  1676. ///
  1677. /// # fn run() -> Result<(), ParseError> {
  1678. /// let mut url = Url::parse("foo://example.net")?;
  1679. /// let result = url.set_host(None);
  1680. /// assert!(result.is_ok());
  1681. /// assert_eq!(url.as_str(), "foo:/");
  1682. /// # Ok(())
  1683. /// # }
  1684. /// # run().unwrap();
  1685. /// ```
  1686. ///
  1687. /// Cannot remove host for 'special' schemes (e.g. `http`):
  1688. ///
  1689. /// ```
  1690. /// use url::Url;
  1691. /// # use url::ParseError;
  1692. ///
  1693. /// # fn run() -> Result<(), ParseError> {
  1694. /// let mut url = Url::parse("https://example.net")?;
  1695. /// let result = url.set_host(None);
  1696. /// assert!(result.is_err());
  1697. /// assert_eq!(url.as_str(), "https://example.net/");
  1698. /// # Ok(())
  1699. /// # }
  1700. /// # run().unwrap();
  1701. /// ```
  1702. ///
  1703. /// Cannot change or remove host for cannot-be-a-base URLs:
  1704. ///
  1705. /// ```
  1706. /// use url::Url;
  1707. /// # use url::ParseError;
  1708. ///
  1709. /// # fn run() -> Result<(), ParseError> {
  1710. /// let mut url = Url::parse("mailto:rms@example.net")?;
  1711. ///
  1712. /// let result = url.set_host(Some("rust-lang.org"));
  1713. /// assert!(result.is_err());
  1714. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  1715. ///
  1716. /// let result = url.set_host(None);
  1717. /// assert!(result.is_err());
  1718. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  1719. /// # Ok(())
  1720. /// # }
  1721. /// # run().unwrap();
  1722. /// ```
  1723. ///
  1724. /// # Errors
  1725. ///
  1726. /// If this URL is cannot-be-a-base or there is an error parsing the given `host`,
  1727. /// a [`ParseError`] variant will be returned.
  1728. ///
  1729. /// [`ParseError`]: enum.ParseError.html
  1730. pub fn set_host(&mut self, host: Option<&str>) -> Result<(), ParseError> {
  1731. if self.cannot_be_a_base() {
  1732. return Err(ParseError::SetHostOnCannotBeABaseUrl);
  1733. }
  1734. let scheme_type = SchemeType::from(self.scheme());
  1735. if let Some(host) = host {
  1736. if host.is_empty() && scheme_type.is_special() && !scheme_type.is_file() {
  1737. return Err(ParseError::EmptyHost);
  1738. }
  1739. let mut host_substr = host;
  1740. // Otherwise, if c is U+003A (:) and the [] flag is unset, then
  1741. if !host.starts_with('[') || !host.ends_with(']') {
  1742. match host.find(':') {
  1743. Some(0) => {
  1744. // If buffer is the empty string, validation error, return failure.
  1745. return Err(ParseError::InvalidDomainCharacter);
  1746. }
  1747. // Let host be the result of host parsing buffer
  1748. Some(colon_index) => {
  1749. host_substr = &host[..colon_index];
  1750. }
  1751. None => {}
  1752. }
  1753. }
  1754. if SchemeType::from(self.scheme()).is_special() {
  1755. self.set_host_internal(Host::parse(host_substr)?, None);
  1756. } else {
  1757. self.set_host_internal(Host::parse_opaque(host_substr)?, None);
  1758. }
  1759. } else if self.has_host() {
  1760. if scheme_type.is_special() && !scheme_type.is_file() {
  1761. return Err(ParseError::EmptyHost);
  1762. } else if self.serialization.len() == self.path_start as usize {
  1763. self.serialization.push('/');
  1764. }
  1765. debug_assert!(self.byte_at(self.scheme_end) == b':');
  1766. debug_assert!(self.byte_at(self.path_start) == b'/');
  1767. let new_path_start = if scheme_type.is_file() {
  1768. self.scheme_end + 3
  1769. } else {
  1770. self.scheme_end + 1
  1771. };
  1772. self.serialization
  1773. .drain(new_path_start as usize..self.path_start as usize);
  1774. let offset = self.path_start - new_path_start;
  1775. self.path_start = new_path_start;
  1776. self.username_end = new_path_start;
  1777. self.host_start = new_path_start;
  1778. self.host_end = new_path_start;
  1779. self.port = None;
  1780. if let Some(ref mut index) = self.query_start {
  1781. *index -= offset
  1782. }
  1783. if let Some(ref mut index) = self.fragment_start {
  1784. *index -= offset
  1785. }
  1786. }
  1787. Ok(())
  1788. }
  1789. /// opt_new_port: None means leave unchanged, Some(None) means remove any port number.
  1790. fn set_host_internal(&mut self, host: Host<String>, opt_new_port: Option<Option<u16>>) {
  1791. let old_suffix_pos = if opt_new_port.is_some() {
  1792. self.path_start
  1793. } else {
  1794. self.host_end
  1795. };
  1796. let suffix = self.slice(old_suffix_pos..).to_owned();
  1797. self.serialization.truncate(self.host_start as usize);
  1798. if !self.has_authority() {
  1799. debug_assert!(self.slice(self.scheme_end..self.host_start) == ":");
  1800. debug_assert!(self.username_end == self.host_start);
  1801. self.serialization.push('/');
  1802. self.serialization.push('/');
  1803. self.username_end += 2;
  1804. self.host_start += 2;
  1805. }
  1806. write!(&mut self.serialization, "{}", host).unwrap();
  1807. self.host_end = to_u32(self.serialization.len()).unwrap();
  1808. self.host = host.into();
  1809. if let Some(new_port) = opt_new_port {
  1810. self.port = new_port;
  1811. if let Some(port) = new_port {
  1812. write!(&mut self.serialization, ":{}", port).unwrap();
  1813. }
  1814. }
  1815. let new_suffix_pos = to_u32(self.serialization.len()).unwrap();
  1816. self.serialization.push_str(&suffix);
  1817. let adjust = |index: &mut u32| {
  1818. *index -= old_suffix_pos;
  1819. *index += new_suffix_pos;
  1820. };
  1821. adjust(&mut self.path_start);
  1822. if let Some(ref mut index) = self.query_start {
  1823. adjust(index)
  1824. }
  1825. if let Some(ref mut index) = self.fragment_start {
  1826. adjust(index)
  1827. }
  1828. }
  1829. /// Change this URL’s host to the given IP address.
  1830. ///
  1831. /// If this URL is cannot-be-a-base, do nothing and return `Err`.
  1832. ///
  1833. /// Compared to `Url::set_host`, this skips the host parser.
  1834. ///
  1835. /// # Examples
  1836. ///
  1837. /// ```rust
  1838. /// use url::{Url, ParseError};
  1839. ///
  1840. /// # fn run() -> Result<(), ParseError> {
  1841. /// let mut url = Url::parse("http://example.com")?;
  1842. /// url.set_ip_host("127.0.0.1".parse().unwrap());
  1843. /// assert_eq!(url.host_str(), Some("127.0.0.1"));
  1844. /// assert_eq!(url.as_str(), "http://127.0.0.1/");
  1845. /// # Ok(())
  1846. /// # }
  1847. /// # run().unwrap();
  1848. /// ```
  1849. ///
  1850. /// Cannot change URL's from mailto(cannot-be-base) to ip:
  1851. ///
  1852. /// ```rust
  1853. /// use url::{Url, ParseError};
  1854. ///
  1855. /// # fn run() -> Result<(), ParseError> {
  1856. /// let mut url = Url::parse("mailto:rms@example.com")?;
  1857. /// let result = url.set_ip_host("127.0.0.1".parse().unwrap());
  1858. ///
  1859. /// assert_eq!(url.as_str(), "mailto:rms@example.com");
  1860. /// assert!(result.is_err());
  1861. /// # Ok(())
  1862. /// # }
  1863. /// # run().unwrap();
  1864. /// ```
  1865. ///
  1866. #[allow(clippy::result_unit_err)]
  1867. pub fn set_ip_host(&mut self, address: IpAddr) -> Result<(), ()> {
  1868. if self.cannot_be_a_base() {
  1869. return Err(());
  1870. }
  1871. let address = match address {
  1872. IpAddr::V4(address) => Host::Ipv4(address),
  1873. IpAddr::V6(address) => Host::Ipv6(address),
  1874. };
  1875. self.set_host_internal(address, None);
  1876. Ok(())
  1877. }
  1878. /// Change this URL’s password.
  1879. ///
  1880. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  1881. ///
  1882. /// # Examples
  1883. ///
  1884. /// ```rust
  1885. /// use url::{Url, ParseError};
  1886. ///
  1887. /// # fn run() -> Result<(), ParseError> {
  1888. /// let mut url = Url::parse("mailto:rmz@example.com")?;
  1889. /// let result = url.set_password(Some("secret_password"));
  1890. /// assert!(result.is_err());
  1891. ///
  1892. /// let mut url = Url::parse("ftp://user1:secret1@example.com")?;
  1893. /// let result = url.set_password(Some("secret_password"));
  1894. /// assert_eq!(url.password(), Some("secret_password"));
  1895. ///
  1896. /// let mut url = Url::parse("ftp://user2:@example.com")?;
  1897. /// let result = url.set_password(Some("secret2"));
  1898. /// assert!(result.is_ok());
  1899. /// assert_eq!(url.password(), Some("secret2"));
  1900. /// # Ok(())
  1901. /// # }
  1902. /// # run().unwrap();
  1903. /// ```
  1904. #[allow(clippy::result_unit_err)]
  1905. pub fn set_password(&mut self, password: Option<&str>) -> Result<(), ()> {
  1906. // has_host implies !cannot_be_a_base
  1907. if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
  1908. return Err(());
  1909. }
  1910. if let Some(password) = password {
  1911. let host_and_after = self.slice(self.host_start..).to_owned();
  1912. self.serialization.truncate(self.username_end as usize);
  1913. self.serialization.push(':');
  1914. self.serialization
  1915. .extend(utf8_percent_encode(password, USERINFO));
  1916. self.serialization.push('@');
  1917. let old_host_start = self.host_start;
  1918. let new_host_start = to_u32(self.serialization.len()).unwrap();
  1919. let adjust = |index: &mut u32| {
  1920. *index -= old_host_start;
  1921. *index += new_host_start;
  1922. };
  1923. self.host_start = new_host_start;
  1924. adjust(&mut self.host_end);
  1925. adjust(&mut self.path_start);
  1926. if let Some(ref mut index) = self.query_start {
  1927. adjust(index)
  1928. }
  1929. if let Some(ref mut index) = self.fragment_start {
  1930. adjust(index)
  1931. }
  1932. self.serialization.push_str(&host_and_after);
  1933. } else if self.byte_at(self.username_end) == b':' {
  1934. // If there is a password to remove
  1935. let has_username_or_password = self.byte_at(self.host_start - 1) == b'@';
  1936. debug_assert!(has_username_or_password);
  1937. let username_start = self.scheme_end + 3;
  1938. let empty_username = username_start == self.username_end;
  1939. let start = self.username_end; // Remove the ':'
  1940. let end = if empty_username {
  1941. self.host_start // Remove the '@' as well
  1942. } else {
  1943. self.host_start - 1 // Keep the '@' to separate the username from the host
  1944. };
  1945. self.serialization.drain(start as usize..end as usize);
  1946. let offset = end - start;
  1947. self.host_start -= offset;
  1948. self.host_end -= offset;
  1949. self.path_start -= offset;
  1950. if let Some(ref mut index) = self.query_start {
  1951. *index -= offset
  1952. }
  1953. if let Some(ref mut index) = self.fragment_start {
  1954. *index -= offset
  1955. }
  1956. }
  1957. Ok(())
  1958. }
  1959. /// Change this URL’s username.
  1960. ///
  1961. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  1962. /// # Examples
  1963. ///
  1964. /// Cannot setup username from mailto(cannot-be-base)
  1965. ///
  1966. /// ```rust
  1967. /// use url::{Url, ParseError};
  1968. ///
  1969. /// # fn run() -> Result<(), ParseError> {
  1970. /// let mut url = Url::parse("mailto:rmz@example.com")?;
  1971. /// let result = url.set_username("user1");
  1972. /// assert_eq!(url.as_str(), "mailto:rmz@example.com");
  1973. /// assert!(result.is_err());
  1974. /// # Ok(())
  1975. /// # }
  1976. /// # run().unwrap();
  1977. /// ```
  1978. ///
  1979. /// Setup username to user1
  1980. ///
  1981. /// ```rust
  1982. /// use url::{Url, ParseError};
  1983. ///
  1984. /// # fn run() -> Result<(), ParseError> {
  1985. /// let mut url = Url::parse("ftp://:secre1@example.com/")?;
  1986. /// let result = url.set_username("user1");
  1987. /// assert!(result.is_ok());
  1988. /// assert_eq!(url.username(), "user1");
  1989. /// assert_eq!(url.as_str(), "ftp://user1:secre1@example.com/");
  1990. /// # Ok(())
  1991. /// # }
  1992. /// # run().unwrap();
  1993. /// ```
  1994. #[allow(clippy::result_unit_err)]
  1995. pub fn set_username(&mut self, username: &str) -> Result<(), ()> {
  1996. // has_host implies !cannot_be_a_base
  1997. if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
  1998. return Err(());
  1999. }
  2000. let username_start = self.scheme_end + 3;
  2001. debug_assert!(self.slice(self.scheme_end..username_start) == "://");
  2002. if self.slice(username_start..self.username_end) == username {
  2003. return Ok(());
  2004. }
  2005. let after_username = self.slice(self.username_end..).to_owned();
  2006. self.serialization.truncate(username_start as usize);
  2007. self.serialization
  2008. .extend(utf8_percent_encode(username, USERINFO));
  2009. let mut removed_bytes = self.username_end;
  2010. self.username_end = to_u32(self.serialization.len()).unwrap();
  2011. let mut added_bytes = self.username_end;
  2012. let new_username_is_empty = self.username_end == username_start;
  2013. match (new_username_is_empty, after_username.chars().next()) {
  2014. (true, Some('@')) => {
  2015. removed_bytes += 1;
  2016. self.serialization.push_str(&after_username[1..]);
  2017. }
  2018. (false, Some('@')) | (_, Some(':')) | (true, _) => {
  2019. self.serialization.push_str(&after_username);
  2020. }
  2021. (false, _) => {
  2022. added_bytes += 1;
  2023. self.serialization.push('@');
  2024. self.serialization.push_str(&after_username);
  2025. }
  2026. }
  2027. let adjust = |index: &mut u32| {
  2028. *index -= removed_bytes;
  2029. *index += added_bytes;
  2030. };
  2031. adjust(&mut self.host_start);
  2032. adjust(&mut self.host_end);
  2033. adjust(&mut self.path_start);
  2034. if let Some(ref mut index) = self.query_start {
  2035. adjust(index)
  2036. }
  2037. if let Some(ref mut index) = self.fragment_start {
  2038. adjust(index)
  2039. }
  2040. Ok(())
  2041. }
  2042. /// Change this URL’s scheme.
  2043. ///
  2044. /// Do nothing and return `Err` under the following circumstances:
  2045. ///
  2046. /// * If the new scheme is not in `[a-zA-Z][a-zA-Z0-9+.-]+`
  2047. /// * If this URL is cannot-be-a-base and the new scheme is one of
  2048. /// `http`, `https`, `ws`, `wss` or `ftp`
  2049. /// * If either the old or new scheme is `http`, `https`, `ws`,
  2050. /// `wss` or `ftp` and the other is not one of these
  2051. /// * If the new scheme is `file` and this URL includes credentials
  2052. /// or has a non-null port
  2053. /// * If this URL's scheme is `file` and its host is empty or null
  2054. ///
  2055. /// See also [the URL specification's section on legal scheme state
  2056. /// overrides](https://url.spec.whatwg.org/#scheme-state).
  2057. ///
  2058. /// # Examples
  2059. ///
  2060. /// Change the URL’s scheme from `https` to `http`:
  2061. ///
  2062. /// ```
  2063. /// use url::Url;
  2064. /// # use url::ParseError;
  2065. ///
  2066. /// # fn run() -> Result<(), ParseError> {
  2067. /// let mut url = Url::parse("https://example.net")?;
  2068. /// let result = url.set_scheme("http");
  2069. /// assert_eq!(url.as_str(), "http://example.net/");
  2070. /// assert!(result.is_ok());
  2071. /// # Ok(())
  2072. /// # }
  2073. /// # run().unwrap();
  2074. /// ```
  2075. /// Change the URL’s scheme from `foo` to `bar`:
  2076. ///
  2077. /// ```
  2078. /// use url::Url;
  2079. /// # use url::ParseError;
  2080. ///
  2081. /// # fn run() -> Result<(), ParseError> {
  2082. /// let mut url = Url::parse("foo://example.net")?;
  2083. /// let result = url.set_scheme("bar");
  2084. /// assert_eq!(url.as_str(), "bar://example.net");
  2085. /// assert!(result.is_ok());
  2086. /// # Ok(())
  2087. /// # }
  2088. /// # run().unwrap();
  2089. /// ```
  2090. ///
  2091. /// Cannot change URL’s scheme from `https` to `foõ`:
  2092. ///
  2093. /// ```
  2094. /// use url::Url;
  2095. /// # use url::ParseError;
  2096. ///
  2097. /// # fn run() -> Result<(), ParseError> {
  2098. /// let mut url = Url::parse("https://example.net")?;
  2099. /// let result = url.set_scheme("foõ");
  2100. /// assert_eq!(url.as_str(), "https://example.net/");
  2101. /// assert!(result.is_err());
  2102. /// # Ok(())
  2103. /// # }
  2104. /// # run().unwrap();
  2105. /// ```
  2106. ///
  2107. /// Cannot change URL’s scheme from `mailto` (cannot-be-a-base) to `https`:
  2108. ///
  2109. /// ```
  2110. /// use url::Url;
  2111. /// # use url::ParseError;
  2112. ///
  2113. /// # fn run() -> Result<(), ParseError> {
  2114. /// let mut url = Url::parse("mailto:rms@example.net")?;
  2115. /// let result = url.set_scheme("https");
  2116. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  2117. /// assert!(result.is_err());
  2118. /// # Ok(())
  2119. /// # }
  2120. /// # run().unwrap();
  2121. /// ```
  2122. /// Cannot change the URL’s scheme from `foo` to `https`:
  2123. ///
  2124. /// ```
  2125. /// use url::Url;
  2126. /// # use url::ParseError;
  2127. ///
  2128. /// # fn run() -> Result<(), ParseError> {
  2129. /// let mut url = Url::parse("foo://example.net")?;
  2130. /// let result = url.set_scheme("https");
  2131. /// assert_eq!(url.as_str(), "foo://example.net");
  2132. /// assert!(result.is_err());
  2133. /// # Ok(())
  2134. /// # }
  2135. /// # run().unwrap();
  2136. /// ```
  2137. /// Cannot change the URL’s scheme from `http` to `foo`:
  2138. ///
  2139. /// ```
  2140. /// use url::Url;
  2141. /// # use url::ParseError;
  2142. ///
  2143. /// # fn run() -> Result<(), ParseError> {
  2144. /// let mut url = Url::parse("http://example.net")?;
  2145. /// let result = url.set_scheme("foo");
  2146. /// assert_eq!(url.as_str(), "http://example.net/");
  2147. /// assert!(result.is_err());
  2148. /// # Ok(())
  2149. /// # }
  2150. /// # run().unwrap();
  2151. /// ```
  2152. #[allow(clippy::result_unit_err, clippy::suspicious_operation_groupings)]
  2153. pub fn set_scheme(&mut self, scheme: &str) -> Result<(), ()> {
  2154. let mut parser = Parser::for_setter(String::new());
  2155. let remaining = parser.parse_scheme(parser::Input::new(scheme))?;
  2156. let new_scheme_type = SchemeType::from(&parser.serialization);
  2157. let old_scheme_type = SchemeType::from(self.scheme());
  2158. // If url’s scheme is a special scheme and buffer is not a special scheme, then return.
  2159. if (new_scheme_type.is_special() && !old_scheme_type.is_special()) ||
  2160. // If url’s scheme is not a special scheme and buffer is a special scheme, then return.
  2161. (!new_scheme_type.is_special() && old_scheme_type.is_special()) ||
  2162. // If url includes credentials or has a non-null port, and buffer is "file", then return.
  2163. // If url’s scheme is "file" and its host is an empty host or null, then return.
  2164. (new_scheme_type.is_file() && self.has_authority())
  2165. {
  2166. return Err(());
  2167. }
  2168. if !remaining.is_empty() || (!self.has_host() && new_scheme_type.is_special()) {
  2169. return Err(());
  2170. }
  2171. let old_scheme_end = self.scheme_end;
  2172. let new_scheme_end = to_u32(parser.serialization.len()).unwrap();
  2173. let adjust = |index: &mut u32| {
  2174. *index -= old_scheme_end;
  2175. *index += new_scheme_end;
  2176. };
  2177. self.scheme_end = new_scheme_end;
  2178. adjust(&mut self.username_end);
  2179. adjust(&mut self.host_start);
  2180. adjust(&mut self.host_end);
  2181. adjust(&mut self.path_start);
  2182. if let Some(ref mut index) = self.query_start {
  2183. adjust(index)
  2184. }
  2185. if let Some(ref mut index) = self.fragment_start {
  2186. adjust(index)
  2187. }
  2188. parser.serialization.push_str(self.slice(old_scheme_end..));
  2189. self.serialization = parser.serialization;
  2190. // Update the port so it can be removed
  2191. // If it is the scheme's default
  2192. // we don't mind it silently failing
  2193. // if there was no port in the first place
  2194. let previous_port = self.port();
  2195. let _ = self.set_port(previous_port);
  2196. Ok(())
  2197. }
  2198. /// Convert a file name as `std::path::Path` into an URL in the `file` scheme.
  2199. ///
  2200. /// This returns `Err` if the given path is not absolute or,
  2201. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`) or a UNC prefix (`\\`).
  2202. ///
  2203. /// # Examples
  2204. ///
  2205. /// On Unix-like platforms:
  2206. ///
  2207. /// ```
  2208. /// # if cfg!(unix) {
  2209. /// use url::Url;
  2210. ///
  2211. /// # fn run() -> Result<(), ()> {
  2212. /// let url = Url::from_file_path("/tmp/foo.txt")?;
  2213. /// assert_eq!(url.as_str(), "file:///tmp/foo.txt");
  2214. ///
  2215. /// let url = Url::from_file_path("../foo.txt");
  2216. /// assert!(url.is_err());
  2217. ///
  2218. /// let url = Url::from_file_path("https://google.com/");
  2219. /// assert!(url.is_err());
  2220. /// # Ok(())
  2221. /// # }
  2222. /// # run().unwrap();
  2223. /// # }
  2224. /// ```
  2225. #[cfg(any(unix, windows, target_os = "redox", target_os = "wasi"))]
  2226. #[allow(clippy::result_unit_err)]
  2227. pub fn from_file_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  2228. let mut serialization = "file://".to_owned();
  2229. let host_start = serialization.len() as u32;
  2230. let (host_end, host) = path_to_file_url_segments(path.as_ref(), &mut serialization)?;
  2231. Ok(Url {
  2232. serialization,
  2233. scheme_end: "file".len() as u32,
  2234. username_end: host_start,
  2235. host_start,
  2236. host_end,
  2237. host,
  2238. port: None,
  2239. path_start: host_end,
  2240. query_start: None,
  2241. fragment_start: None,
  2242. })
  2243. }
  2244. /// Convert a directory name as `std::path::Path` into an URL in the `file` scheme.
  2245. ///
  2246. /// This returns `Err` if the given path is not absolute or,
  2247. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`) or a UNC prefix (`\\`).
  2248. ///
  2249. /// Compared to `from_file_path`, this ensure that URL’s the path has a trailing slash
  2250. /// so that the entire path is considered when using this URL as a base URL.
  2251. ///
  2252. /// For example:
  2253. ///
  2254. /// * `"index.html"` parsed with `Url::from_directory_path(Path::new("/var/www"))`
  2255. /// as the base URL is `file:///var/www/index.html`
  2256. /// * `"index.html"` parsed with `Url::from_file_path(Path::new("/var/www"))`
  2257. /// as the base URL is `file:///var/index.html`, which might not be what was intended.
  2258. ///
  2259. /// Note that `std::path` does not consider trailing slashes significant
  2260. /// and usually does not include them (e.g. in `Path::parent()`).
  2261. #[cfg(any(unix, windows, target_os = "redox", target_os = "wasi"))]
  2262. #[allow(clippy::result_unit_err)]
  2263. pub fn from_directory_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  2264. let mut url = Url::from_file_path(path)?;
  2265. if !url.serialization.ends_with('/') {
  2266. url.serialization.push('/')
  2267. }
  2268. Ok(url)
  2269. }
  2270. /// Serialize with Serde using the internal representation of the `Url` struct.
  2271. ///
  2272. /// The corresponding `deserialize_internal` method sacrifices some invariant-checking
  2273. /// for speed, compared to the `Deserialize` trait impl.
  2274. ///
  2275. /// This method is only available if the `serde` Cargo feature is enabled.
  2276. #[cfg(feature = "serde")]
  2277. #[deny(unused)]
  2278. pub fn serialize_internal<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  2279. where
  2280. S: serde::Serializer,
  2281. {
  2282. use serde::Serialize;
  2283. // Destructuring first lets us ensure that adding or removing fields forces this method
  2284. // to be updated
  2285. let Url {
  2286. ref serialization,
  2287. ref scheme_end,
  2288. ref username_end,
  2289. ref host_start,
  2290. ref host_end,
  2291. ref host,
  2292. ref port,
  2293. ref path_start,
  2294. ref query_start,
  2295. ref fragment_start,
  2296. } = *self;
  2297. (
  2298. serialization,
  2299. scheme_end,
  2300. username_end,
  2301. host_start,
  2302. host_end,
  2303. host,
  2304. port,
  2305. path_start,
  2306. query_start,
  2307. fragment_start,
  2308. )
  2309. .serialize(serializer)
  2310. }
  2311. /// Serialize with Serde using the internal representation of the `Url` struct.
  2312. ///
  2313. /// The corresponding `deserialize_internal` method sacrifices some invariant-checking
  2314. /// for speed, compared to the `Deserialize` trait impl.
  2315. ///
  2316. /// This method is only available if the `serde` Cargo feature is enabled.
  2317. #[cfg(feature = "serde")]
  2318. #[deny(unused)]
  2319. pub fn deserialize_internal<'de, D>(deserializer: D) -> Result<Self, D::Error>
  2320. where
  2321. D: serde::Deserializer<'de>,
  2322. {
  2323. use serde::de::{Deserialize, Error, Unexpected};
  2324. let (
  2325. serialization,
  2326. scheme_end,
  2327. username_end,
  2328. host_start,
  2329. host_end,
  2330. host,
  2331. port,
  2332. path_start,
  2333. query_start,
  2334. fragment_start,
  2335. ) = Deserialize::deserialize(deserializer)?;
  2336. let url = Url {
  2337. serialization,
  2338. scheme_end,
  2339. username_end,
  2340. host_start,
  2341. host_end,
  2342. host,
  2343. port,
  2344. path_start,
  2345. query_start,
  2346. fragment_start,
  2347. };
  2348. if cfg!(debug_assertions) {
  2349. url.check_invariants().map_err(|reason| {
  2350. let reason: &str = &reason;
  2351. Error::invalid_value(Unexpected::Other("value"), &reason)
  2352. })?
  2353. }
  2354. Ok(url)
  2355. }
  2356. /// Assuming the URL is in the `file` scheme or similar,
  2357. /// convert its path to an absolute `std::path::Path`.
  2358. ///
  2359. /// **Note:** This does not actually check the URL’s `scheme`,
  2360. /// and may give nonsensical results for other schemes.
  2361. /// It is the user’s responsibility to check the URL’s scheme before calling this.
  2362. ///
  2363. /// ```
  2364. /// # use url::Url;
  2365. /// # let url = Url::parse("file:///etc/passwd").unwrap();
  2366. /// let path = url.to_file_path();
  2367. /// ```
  2368. ///
  2369. /// Returns `Err` if the host is neither empty nor `"localhost"` (except on Windows, where
  2370. /// `file:` URLs may have a non-local host),
  2371. /// or if `Path::new_opt()` returns `None`.
  2372. /// (That is, if the percent-decoded path contains a NUL byte or,
  2373. /// for a Windows path, is not UTF-8.)
  2374. #[inline]
  2375. #[cfg(any(unix, windows, target_os = "redox", target_os = "wasi"))]
  2376. #[allow(clippy::result_unit_err)]
  2377. pub fn to_file_path(&self) -> Result<PathBuf, ()> {
  2378. if let Some(segments) = self.path_segments() {
  2379. let host = match self.host() {
  2380. None | Some(Host::Domain("localhost")) => None,
  2381. Some(_) if cfg!(windows) && self.scheme() == "file" => {
  2382. Some(&self.serialization[self.host_start as usize..self.host_end as usize])
  2383. }
  2384. _ => return Err(()),
  2385. };
  2386. return file_url_segments_to_pathbuf(host, segments);
  2387. }
  2388. Err(())
  2389. }
  2390. // Private helper methods:
  2391. #[inline]
  2392. fn slice<R>(&self, range: R) -> &str
  2393. where
  2394. R: RangeArg,
  2395. {
  2396. range.slice_of(&self.serialization)
  2397. }
  2398. #[inline]
  2399. fn byte_at(&self, i: u32) -> u8 {
  2400. self.serialization.as_bytes()[i as usize]
  2401. }
  2402. }
  2403. /// Parse a string as an URL, without a base URL or encoding override.
  2404. impl str::FromStr for Url {
  2405. type Err = ParseError;
  2406. #[inline]
  2407. fn from_str(input: &str) -> Result<Url, crate::ParseError> {
  2408. Url::parse(input)
  2409. }
  2410. }
  2411. impl<'a> TryFrom<&'a str> for Url {
  2412. type Error = ParseError;
  2413. fn try_from(s: &'a str) -> Result<Self, Self::Error> {
  2414. Url::parse(s)
  2415. }
  2416. }
  2417. /// Display the serialization of this URL.
  2418. impl fmt::Display for Url {
  2419. #[inline]
  2420. fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
  2421. fmt::Display::fmt(&self.serialization, formatter)
  2422. }
  2423. }
  2424. /// String conversion.
  2425. impl From<Url> for String {
  2426. fn from(value: Url) -> String {
  2427. value.serialization
  2428. }
  2429. }
  2430. /// Debug the serialization of this URL.
  2431. impl fmt::Debug for Url {
  2432. #[inline]
  2433. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  2434. formatter
  2435. .debug_struct("Url")
  2436. .field("scheme", &self.scheme())
  2437. .field("cannot_be_a_base", &self.cannot_be_a_base())
  2438. .field("username", &self.username())
  2439. .field("password", &self.password())
  2440. .field("host", &self.host())
  2441. .field("port", &self.port())
  2442. .field("path", &self.path())
  2443. .field("query", &self.query())
  2444. .field("fragment", &self.fragment())
  2445. .finish()
  2446. }
  2447. }
  2448. /// URLs compare like their serialization.
  2449. impl Eq for Url {}
  2450. /// URLs compare like their serialization.
  2451. impl PartialEq for Url {
  2452. #[inline]
  2453. fn eq(&self, other: &Self) -> bool {
  2454. self.serialization == other.serialization
  2455. }
  2456. }
  2457. /// URLs compare like their serialization.
  2458. impl Ord for Url {
  2459. #[inline]
  2460. fn cmp(&self, other: &Self) -> cmp::Ordering {
  2461. self.serialization.cmp(&other.serialization)
  2462. }
  2463. }
  2464. /// URLs compare like their serialization.
  2465. impl PartialOrd for Url {
  2466. #[inline]
  2467. fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
  2468. self.serialization.partial_cmp(&other.serialization)
  2469. }
  2470. }
  2471. /// URLs hash like their serialization.
  2472. impl hash::Hash for Url {
  2473. #[inline]
  2474. fn hash<H>(&self, state: &mut H)
  2475. where
  2476. H: hash::Hasher,
  2477. {
  2478. hash::Hash::hash(&self.serialization, state)
  2479. }
  2480. }
  2481. /// Return the serialization of this URL.
  2482. impl AsRef<str> for Url {
  2483. #[inline]
  2484. fn as_ref(&self) -> &str {
  2485. &self.serialization
  2486. }
  2487. }
  2488. trait RangeArg {
  2489. fn slice_of<'a>(&self, s: &'a str) -> &'a str;
  2490. }
  2491. impl RangeArg for Range<u32> {
  2492. #[inline]
  2493. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  2494. &s[self.start as usize..self.end as usize]
  2495. }
  2496. }
  2497. impl RangeArg for RangeFrom<u32> {
  2498. #[inline]
  2499. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  2500. &s[self.start as usize..]
  2501. }
  2502. }
  2503. impl RangeArg for RangeTo<u32> {
  2504. #[inline]
  2505. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  2506. &s[..self.end as usize]
  2507. }
  2508. }
  2509. /// Serializes this URL into a `serde` stream.
  2510. ///
  2511. /// This implementation is only available if the `serde` Cargo feature is enabled.
  2512. #[cfg(feature = "serde")]
  2513. impl serde::Serialize for Url {
  2514. fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  2515. where
  2516. S: serde::Serializer,
  2517. {
  2518. serializer.serialize_str(self.as_str())
  2519. }
  2520. }
  2521. /// Deserializes this URL from a `serde` stream.
  2522. ///
  2523. /// This implementation is only available if the `serde` Cargo feature is enabled.
  2524. #[cfg(feature = "serde")]
  2525. impl<'de> serde::Deserialize<'de> for Url {
  2526. fn deserialize<D>(deserializer: D) -> Result<Url, D::Error>
  2527. where
  2528. D: serde::Deserializer<'de>,
  2529. {
  2530. use serde::de::{Error, Unexpected, Visitor};
  2531. struct UrlVisitor;
  2532. impl<'de> Visitor<'de> for UrlVisitor {
  2533. type Value = Url;
  2534. fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  2535. formatter.write_str("a string representing an URL")
  2536. }
  2537. fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
  2538. where
  2539. E: Error,
  2540. {
  2541. Url::parse(s).map_err(|err| {
  2542. let err_s = format!("{}", err);
  2543. Error::invalid_value(Unexpected::Str(s), &err_s.as_str())
  2544. })
  2545. }
  2546. }
  2547. deserializer.deserialize_str(UrlVisitor)
  2548. }
  2549. }
  2550. #[cfg(any(unix, target_os = "redox", target_os = "wasi"))]
  2551. fn path_to_file_url_segments(
  2552. path: &Path,
  2553. serialization: &mut String,
  2554. ) -> Result<(u32, HostInternal), ()> {
  2555. #[cfg(any(unix, target_os = "redox"))]
  2556. use std::os::unix::prelude::OsStrExt;
  2557. #[cfg(target_os = "wasi")]
  2558. use std::os::wasi::prelude::OsStrExt;
  2559. if !path.is_absolute() {
  2560. return Err(());
  2561. }
  2562. let host_end = to_u32(serialization.len()).unwrap();
  2563. let mut empty = true;
  2564. // skip the root component
  2565. for component in path.components().skip(1) {
  2566. empty = false;
  2567. serialization.push('/');
  2568. serialization.extend(percent_encode(
  2569. component.as_os_str().as_bytes(),
  2570. PATH_SEGMENT,
  2571. ));
  2572. }
  2573. if empty {
  2574. // An URL’s path must not be empty.
  2575. serialization.push('/');
  2576. }
  2577. Ok((host_end, HostInternal::None))
  2578. }
  2579. #[cfg(windows)]
  2580. fn path_to_file_url_segments(
  2581. path: &Path,
  2582. serialization: &mut String,
  2583. ) -> Result<(u32, HostInternal), ()> {
  2584. path_to_file_url_segments_windows(path, serialization)
  2585. }
  2586. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  2587. #[cfg_attr(not(windows), allow(dead_code))]
  2588. fn path_to_file_url_segments_windows(
  2589. path: &Path,
  2590. serialization: &mut String,
  2591. ) -> Result<(u32, HostInternal), ()> {
  2592. use std::path::{Component, Prefix};
  2593. if !path.is_absolute() {
  2594. return Err(());
  2595. }
  2596. let mut components = path.components();
  2597. let host_start = serialization.len() + 1;
  2598. let host_end;
  2599. let host_internal;
  2600. match components.next() {
  2601. Some(Component::Prefix(ref p)) => match p.kind() {
  2602. Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => {
  2603. host_end = to_u32(serialization.len()).unwrap();
  2604. host_internal = HostInternal::None;
  2605. serialization.push('/');
  2606. serialization.push(letter as char);
  2607. serialization.push(':');
  2608. }
  2609. Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => {
  2610. let host = Host::parse(server.to_str().ok_or(())?).map_err(|_| ())?;
  2611. write!(serialization, "{}", host).unwrap();
  2612. host_end = to_u32(serialization.len()).unwrap();
  2613. host_internal = host.into();
  2614. serialization.push('/');
  2615. let share = share.to_str().ok_or(())?;
  2616. serialization.extend(percent_encode(share.as_bytes(), PATH_SEGMENT));
  2617. }
  2618. _ => return Err(()),
  2619. },
  2620. _ => return Err(()),
  2621. }
  2622. let mut path_only_has_prefix = true;
  2623. for component in components {
  2624. if component == Component::RootDir {
  2625. continue;
  2626. }
  2627. path_only_has_prefix = false;
  2628. // FIXME: somehow work with non-unicode?
  2629. let component = component.as_os_str().to_str().ok_or(())?;
  2630. serialization.push('/');
  2631. serialization.extend(percent_encode(component.as_bytes(), PATH_SEGMENT));
  2632. }
  2633. // A windows drive letter must end with a slash.
  2634. if serialization.len() > host_start
  2635. && parser::is_windows_drive_letter(&serialization[host_start..])
  2636. && path_only_has_prefix
  2637. {
  2638. serialization.push('/');
  2639. }
  2640. Ok((host_end, host_internal))
  2641. }
  2642. #[cfg(any(unix, target_os = "redox", target_os = "wasi"))]
  2643. fn file_url_segments_to_pathbuf(
  2644. host: Option<&str>,
  2645. segments: str::Split<'_, char>,
  2646. ) -> Result<PathBuf, ()> {
  2647. use std::ffi::OsStr;
  2648. #[cfg(any(unix, target_os = "redox"))]
  2649. use std::os::unix::prelude::OsStrExt;
  2650. #[cfg(target_os = "wasi")]
  2651. use std::os::wasi::prelude::OsStrExt;
  2652. if host.is_some() {
  2653. return Err(());
  2654. }
  2655. let mut bytes = if cfg!(target_os = "redox") {
  2656. b"file:".to_vec()
  2657. } else {
  2658. Vec::new()
  2659. };
  2660. for segment in segments {
  2661. bytes.push(b'/');
  2662. bytes.extend(percent_decode(segment.as_bytes()));
  2663. }
  2664. // A windows drive letter must end with a slash.
  2665. if bytes.len() > 2
  2666. && matches!(bytes[bytes.len() - 2], b'a'..=b'z' | b'A'..=b'Z')
  2667. && matches!(bytes[bytes.len() - 1], b':' | b'|')
  2668. {
  2669. bytes.push(b'/');
  2670. }
  2671. let os_str = OsStr::from_bytes(&bytes);
  2672. let path = PathBuf::from(os_str);
  2673. debug_assert!(
  2674. path.is_absolute(),
  2675. "to_file_path() failed to produce an absolute Path"
  2676. );
  2677. Ok(path)
  2678. }
  2679. #[cfg(windows)]
  2680. fn file_url_segments_to_pathbuf(
  2681. host: Option<&str>,
  2682. segments: str::Split<char>,
  2683. ) -> Result<PathBuf, ()> {
  2684. file_url_segments_to_pathbuf_windows(host, segments)
  2685. }
  2686. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  2687. #[cfg_attr(not(windows), allow(dead_code))]
  2688. fn file_url_segments_to_pathbuf_windows(
  2689. host: Option<&str>,
  2690. mut segments: str::Split<'_, char>,
  2691. ) -> Result<PathBuf, ()> {
  2692. let mut string = if let Some(host) = host {
  2693. r"\\".to_owned() + host
  2694. } else {
  2695. let first = segments.next().ok_or(())?;
  2696. match first.len() {
  2697. 2 => {
  2698. if !first.starts_with(parser::ascii_alpha) || first.as_bytes()[1] != b':' {
  2699. return Err(());
  2700. }
  2701. first.to_owned()
  2702. }
  2703. 4 => {
  2704. if !first.starts_with(parser::ascii_alpha) {
  2705. return Err(());
  2706. }
  2707. let bytes = first.as_bytes();
  2708. if bytes[1] != b'%' || bytes[2] != b'3' || (bytes[3] != b'a' && bytes[3] != b'A') {
  2709. return Err(());
  2710. }
  2711. first[0..1].to_owned() + ":"
  2712. }
  2713. _ => return Err(()),
  2714. }
  2715. };
  2716. for segment in segments {
  2717. string.push('\\');
  2718. // Currently non-unicode windows paths cannot be represented
  2719. match String::from_utf8(percent_decode(segment.as_bytes()).collect()) {
  2720. Ok(s) => string.push_str(&s),
  2721. Err(..) => return Err(()),
  2722. }
  2723. }
  2724. let path = PathBuf::from(string);
  2725. debug_assert!(
  2726. path.is_absolute(),
  2727. "to_file_path() failed to produce an absolute Path"
  2728. );
  2729. Ok(path)
  2730. }
  2731. /// Implementation detail of `Url::query_pairs_mut`. Typically not used directly.
  2732. #[derive(Debug)]
  2733. pub struct UrlQuery<'a> {
  2734. url: Option<&'a mut Url>,
  2735. fragment: Option<String>,
  2736. }
  2737. // `as_mut_string` string here exposes the internal serialization of an `Url`,
  2738. // which should not be exposed to users.
  2739. // We achieve that by not giving users direct access to `UrlQuery`:
  2740. // * Its fields are private
  2741. // (and so can not be constructed with struct literal syntax outside of this crate),
  2742. // * It has no constructor
  2743. // * It is only visible (on the type level) to users in the return type of
  2744. // `Url::query_pairs_mut` which is `Serializer<UrlQuery>`
  2745. // * `Serializer` keeps its target in a private field
  2746. // * Unlike in other `Target` impls, `UrlQuery::finished` does not return `Self`.
  2747. impl<'a> form_urlencoded::Target for UrlQuery<'a> {
  2748. fn as_mut_string(&mut self) -> &mut String {
  2749. &mut self.url.as_mut().unwrap().serialization
  2750. }
  2751. fn finish(mut self) -> &'a mut Url {
  2752. let url = self.url.take().unwrap();
  2753. url.restore_already_parsed_fragment(self.fragment.take());
  2754. url
  2755. }
  2756. type Finished = &'a mut Url;
  2757. }
  2758. impl<'a> Drop for UrlQuery<'a> {
  2759. fn drop(&mut self) {
  2760. if let Some(url) = self.url.take() {
  2761. url.restore_already_parsed_fragment(self.fragment.take())
  2762. }
  2763. }
  2764. }