lib.rs 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923
  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. /// # Examples
  718. ///
  719. /// ```
  720. /// use url::Url;
  721. /// # use url::ParseError;
  722. ///
  723. /// # fn run() -> Result<(), ParseError> {
  724. /// let url = Url::parse("ftp://rms@example.com")?;
  725. /// assert!(url.has_authority());
  726. ///
  727. /// let url = Url::parse("unix:/run/foo.socket")?;
  728. /// assert!(!url.has_authority());
  729. ///
  730. /// let url = Url::parse("data:text/plain,Stuff")?;
  731. /// assert!(!url.has_authority());
  732. /// # Ok(())
  733. /// # }
  734. /// # run().unwrap();
  735. /// ```
  736. #[inline]
  737. pub fn has_authority(&self) -> bool {
  738. debug_assert!(self.byte_at(self.scheme_end) == b':');
  739. self.slice(self.scheme_end..).starts_with("://")
  740. }
  741. /// Return whether this URL is a cannot-be-a-base URL,
  742. /// meaning that parsing a relative URL string with this URL as the base will return an error.
  743. ///
  744. /// This is the case if the scheme and `:` delimiter are not followed by a `/` slash,
  745. /// as is typically the case of `data:` and `mailto:` URLs.
  746. ///
  747. /// # Examples
  748. ///
  749. /// ```
  750. /// use url::Url;
  751. /// # use url::ParseError;
  752. ///
  753. /// # fn run() -> Result<(), ParseError> {
  754. /// let url = Url::parse("ftp://rms@example.com")?;
  755. /// assert!(!url.cannot_be_a_base());
  756. ///
  757. /// let url = Url::parse("unix:/run/foo.socket")?;
  758. /// assert!(!url.cannot_be_a_base());
  759. ///
  760. /// let url = Url::parse("data:text/plain,Stuff")?;
  761. /// assert!(url.cannot_be_a_base());
  762. /// # Ok(())
  763. /// # }
  764. /// # run().unwrap();
  765. /// ```
  766. #[inline]
  767. pub fn cannot_be_a_base(&self) -> bool {
  768. !self.slice(self.scheme_end + 1..).starts_with('/')
  769. }
  770. /// Return the username for this URL (typically the empty string)
  771. /// as a percent-encoded ASCII string.
  772. ///
  773. /// # Examples
  774. ///
  775. /// ```
  776. /// use url::Url;
  777. /// # use url::ParseError;
  778. ///
  779. /// # fn run() -> Result<(), ParseError> {
  780. /// let url = Url::parse("ftp://rms@example.com")?;
  781. /// assert_eq!(url.username(), "rms");
  782. ///
  783. /// let url = Url::parse("ftp://:secret123@example.com")?;
  784. /// assert_eq!(url.username(), "");
  785. ///
  786. /// let url = Url::parse("https://example.com")?;
  787. /// assert_eq!(url.username(), "");
  788. /// # Ok(())
  789. /// # }
  790. /// # run().unwrap();
  791. /// ```
  792. pub fn username(&self) -> &str {
  793. let scheme_separator_len = "://".len() as u32;
  794. if self.has_authority() && self.username_end > self.scheme_end + scheme_separator_len {
  795. self.slice(self.scheme_end + scheme_separator_len..self.username_end)
  796. } else {
  797. ""
  798. }
  799. }
  800. /// Return the password for this URL, if any, as a percent-encoded ASCII string.
  801. ///
  802. /// # Examples
  803. ///
  804. /// ```
  805. /// use url::Url;
  806. /// # use url::ParseError;
  807. ///
  808. /// # fn run() -> Result<(), ParseError> {
  809. /// let url = Url::parse("ftp://rms:secret123@example.com")?;
  810. /// assert_eq!(url.password(), Some("secret123"));
  811. ///
  812. /// let url = Url::parse("ftp://:secret123@example.com")?;
  813. /// assert_eq!(url.password(), Some("secret123"));
  814. ///
  815. /// let url = Url::parse("ftp://rms@example.com")?;
  816. /// assert_eq!(url.password(), None);
  817. ///
  818. /// let url = Url::parse("https://example.com")?;
  819. /// assert_eq!(url.password(), None);
  820. /// # Ok(())
  821. /// # }
  822. /// # run().unwrap();
  823. /// ```
  824. pub fn password(&self) -> Option<&str> {
  825. // This ':' is not the one marking a port number since a host can not be empty.
  826. // (Except for file: URLs, which do not have port numbers.)
  827. if self.has_authority()
  828. && self.username_end != self.serialization.len() as u32
  829. && self.byte_at(self.username_end) == b':'
  830. {
  831. debug_assert!(self.byte_at(self.host_start - 1) == b'@');
  832. Some(self.slice(self.username_end + 1..self.host_start - 1))
  833. } else {
  834. None
  835. }
  836. }
  837. /// Equivalent to `url.host().is_some()`.
  838. ///
  839. /// # Examples
  840. ///
  841. /// ```
  842. /// use url::Url;
  843. /// # use url::ParseError;
  844. ///
  845. /// # fn run() -> Result<(), ParseError> {
  846. /// let url = Url::parse("ftp://rms@example.com")?;
  847. /// assert!(url.has_host());
  848. ///
  849. /// let url = Url::parse("unix:/run/foo.socket")?;
  850. /// assert!(!url.has_host());
  851. ///
  852. /// let url = Url::parse("data:text/plain,Stuff")?;
  853. /// assert!(!url.has_host());
  854. /// # Ok(())
  855. /// # }
  856. /// # run().unwrap();
  857. /// ```
  858. pub fn has_host(&self) -> bool {
  859. !matches!(self.host, HostInternal::None)
  860. }
  861. /// Return the string representation of the host (domain or IP address) for this URL, if any.
  862. ///
  863. /// Non-ASCII domains are punycode-encoded per IDNA if this is the host
  864. /// of a special URL, or percent encoded for non-special URLs.
  865. /// IPv6 addresses are given between `[` and `]` brackets.
  866. ///
  867. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  868. /// don’t have a host.
  869. ///
  870. /// See also the `host` method.
  871. ///
  872. /// # Examples
  873. ///
  874. /// ```
  875. /// use url::Url;
  876. /// # use url::ParseError;
  877. ///
  878. /// # fn run() -> Result<(), ParseError> {
  879. /// let url = Url::parse("https://127.0.0.1/index.html")?;
  880. /// assert_eq!(url.host_str(), Some("127.0.0.1"));
  881. ///
  882. /// let url = Url::parse("ftp://rms@example.com")?;
  883. /// assert_eq!(url.host_str(), Some("example.com"));
  884. ///
  885. /// let url = Url::parse("unix:/run/foo.socket")?;
  886. /// assert_eq!(url.host_str(), None);
  887. ///
  888. /// let url = Url::parse("data:text/plain,Stuff")?;
  889. /// assert_eq!(url.host_str(), None);
  890. /// # Ok(())
  891. /// # }
  892. /// # run().unwrap();
  893. /// ```
  894. pub fn host_str(&self) -> Option<&str> {
  895. if self.has_host() {
  896. Some(self.slice(self.host_start..self.host_end))
  897. } else {
  898. None
  899. }
  900. }
  901. /// Return the parsed representation of the host for this URL.
  902. /// Non-ASCII domain labels are punycode-encoded per IDNA if this is the host
  903. /// of a special URL, or percent encoded for non-special URLs.
  904. ///
  905. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  906. /// don’t have a host.
  907. ///
  908. /// See also the `host_str` method.
  909. ///
  910. /// # Examples
  911. ///
  912. /// ```
  913. /// use url::Url;
  914. /// # use url::ParseError;
  915. ///
  916. /// # fn run() -> Result<(), ParseError> {
  917. /// let url = Url::parse("https://127.0.0.1/index.html")?;
  918. /// assert!(url.host().is_some());
  919. ///
  920. /// let url = Url::parse("ftp://rms@example.com")?;
  921. /// assert!(url.host().is_some());
  922. ///
  923. /// let url = Url::parse("unix:/run/foo.socket")?;
  924. /// assert!(url.host().is_none());
  925. ///
  926. /// let url = Url::parse("data:text/plain,Stuff")?;
  927. /// assert!(url.host().is_none());
  928. /// # Ok(())
  929. /// # }
  930. /// # run().unwrap();
  931. /// ```
  932. pub fn host(&self) -> Option<Host<&str>> {
  933. match self.host {
  934. HostInternal::None => None,
  935. HostInternal::Domain => Some(Host::Domain(self.slice(self.host_start..self.host_end))),
  936. HostInternal::Ipv4(address) => Some(Host::Ipv4(address)),
  937. HostInternal::Ipv6(address) => Some(Host::Ipv6(address)),
  938. }
  939. }
  940. /// If this URL has a host and it is a domain name (not an IP address), return it.
  941. /// Non-ASCII domains are punycode-encoded per IDNA if this is the host
  942. /// of a special URL, or percent encoded for non-special URLs.
  943. ///
  944. /// # Examples
  945. ///
  946. /// ```
  947. /// use url::Url;
  948. /// # use url::ParseError;
  949. ///
  950. /// # fn run() -> Result<(), ParseError> {
  951. /// let url = Url::parse("https://127.0.0.1/")?;
  952. /// assert_eq!(url.domain(), None);
  953. ///
  954. /// let url = Url::parse("mailto:rms@example.net")?;
  955. /// assert_eq!(url.domain(), None);
  956. ///
  957. /// let url = Url::parse("https://example.com/")?;
  958. /// assert_eq!(url.domain(), Some("example.com"));
  959. /// # Ok(())
  960. /// # }
  961. /// # run().unwrap();
  962. /// ```
  963. pub fn domain(&self) -> Option<&str> {
  964. match self.host {
  965. HostInternal::Domain => Some(self.slice(self.host_start..self.host_end)),
  966. _ => None,
  967. }
  968. }
  969. /// Return the port number for this URL, if any.
  970. ///
  971. /// Note that default port numbers are never reflected by the serialization,
  972. /// use the `port_or_known_default()` method if you want a default port number returned.
  973. ///
  974. /// # Examples
  975. ///
  976. /// ```
  977. /// use url::Url;
  978. /// # use url::ParseError;
  979. ///
  980. /// # fn run() -> Result<(), ParseError> {
  981. /// let url = Url::parse("https://example.com")?;
  982. /// assert_eq!(url.port(), None);
  983. ///
  984. /// let url = Url::parse("https://example.com:443/")?;
  985. /// assert_eq!(url.port(), None);
  986. ///
  987. /// let url = Url::parse("ssh://example.com:22")?;
  988. /// assert_eq!(url.port(), Some(22));
  989. /// # Ok(())
  990. /// # }
  991. /// # run().unwrap();
  992. /// ```
  993. #[inline]
  994. pub fn port(&self) -> Option<u16> {
  995. self.port
  996. }
  997. /// Return the port number for this URL, or the default port number if it is known.
  998. ///
  999. /// This method only knows the default port number
  1000. /// of the `http`, `https`, `ws`, `wss` and `ftp` schemes.
  1001. ///
  1002. /// For URLs in these schemes, this method always returns `Some(_)`.
  1003. /// For other schemes, it is the same as `Url::port()`.
  1004. ///
  1005. /// # Examples
  1006. ///
  1007. /// ```
  1008. /// use url::Url;
  1009. /// # use url::ParseError;
  1010. ///
  1011. /// # fn run() -> Result<(), ParseError> {
  1012. /// let url = Url::parse("foo://example.com")?;
  1013. /// assert_eq!(url.port_or_known_default(), None);
  1014. ///
  1015. /// let url = Url::parse("foo://example.com:1456")?;
  1016. /// assert_eq!(url.port_or_known_default(), Some(1456));
  1017. ///
  1018. /// let url = Url::parse("https://example.com")?;
  1019. /// assert_eq!(url.port_or_known_default(), Some(443));
  1020. /// # Ok(())
  1021. /// # }
  1022. /// # run().unwrap();
  1023. /// ```
  1024. #[inline]
  1025. pub fn port_or_known_default(&self) -> Option<u16> {
  1026. self.port.or_else(|| parser::default_port(self.scheme()))
  1027. }
  1028. /// Resolve a URL’s host and port number to `SocketAddr`.
  1029. ///
  1030. /// If the URL has the default port number of a scheme that is unknown to this library,
  1031. /// `default_port_number` provides an opportunity to provide the actual port number.
  1032. /// In non-example code this should be implemented either simply as `|| None`,
  1033. /// or by matching on the URL’s `.scheme()`.
  1034. ///
  1035. /// If the host is a domain, it is resolved using the standard library’s DNS support.
  1036. ///
  1037. /// # Examples
  1038. ///
  1039. /// ```no_run
  1040. /// let url = url::Url::parse("https://example.net/").unwrap();
  1041. /// let addrs = url.socket_addrs(|| None).unwrap();
  1042. /// std::net::TcpStream::connect(&*addrs)
  1043. /// # ;
  1044. /// ```
  1045. ///
  1046. /// ```
  1047. /// /// With application-specific known default port numbers
  1048. /// fn socket_addrs(url: url::Url) -> std::io::Result<Vec<std::net::SocketAddr>> {
  1049. /// url.socket_addrs(|| match url.scheme() {
  1050. /// "socks5" | "socks5h" => Some(1080),
  1051. /// _ => None,
  1052. /// })
  1053. /// }
  1054. /// ```
  1055. pub fn socket_addrs(
  1056. &self,
  1057. default_port_number: impl Fn() -> Option<u16>,
  1058. ) -> io::Result<Vec<SocketAddr>> {
  1059. // Note: trying to avoid the Vec allocation by returning `impl AsRef<[SocketAddr]>`
  1060. // causes borrowck issues because the return value borrows `default_port_number`:
  1061. //
  1062. // https://github.com/rust-lang/rfcs/blob/master/text/1951-expand-impl-trait.md#scoping-for-type-and-lifetime-parameters
  1063. //
  1064. // > This RFC proposes that *all* type parameters are considered in scope
  1065. // > for `impl Trait` in return position
  1066. fn io_result<T>(opt: Option<T>, message: &str) -> io::Result<T> {
  1067. opt.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, message))
  1068. }
  1069. let host = io_result(self.host(), "No host name in the URL")?;
  1070. let port = io_result(
  1071. self.port_or_known_default().or_else(default_port_number),
  1072. "No port number in the URL",
  1073. )?;
  1074. Ok(match host {
  1075. Host::Domain(domain) => (domain, port).to_socket_addrs()?.collect(),
  1076. Host::Ipv4(ip) => vec![(ip, port).into()],
  1077. Host::Ipv6(ip) => vec![(ip, port).into()],
  1078. })
  1079. }
  1080. /// Return the path for this URL, as a percent-encoded ASCII string.
  1081. /// For cannot-be-a-base URLs, this is an arbitrary string that doesn’t start with '/'.
  1082. /// For other URLs, this starts with a '/' slash
  1083. /// and continues with slash-separated path segments.
  1084. ///
  1085. /// # Examples
  1086. ///
  1087. /// ```rust
  1088. /// use url::{Url, ParseError};
  1089. ///
  1090. /// # fn run() -> Result<(), ParseError> {
  1091. /// let url = Url::parse("https://example.com/api/versions?page=2")?;
  1092. /// assert_eq!(url.path(), "/api/versions");
  1093. ///
  1094. /// let url = Url::parse("https://example.com")?;
  1095. /// assert_eq!(url.path(), "/");
  1096. ///
  1097. /// let url = Url::parse("https://example.com/countries/việt nam")?;
  1098. /// assert_eq!(url.path(), "/countries/vi%E1%BB%87t%20nam");
  1099. /// # Ok(())
  1100. /// # }
  1101. /// # run().unwrap();
  1102. /// ```
  1103. pub fn path(&self) -> &str {
  1104. match (self.query_start, self.fragment_start) {
  1105. (None, None) => self.slice(self.path_start..),
  1106. (Some(next_component_start), _) | (None, Some(next_component_start)) => {
  1107. self.slice(self.path_start..next_component_start)
  1108. }
  1109. }
  1110. }
  1111. /// Unless this URL is cannot-be-a-base,
  1112. /// return an iterator of '/' slash-separated path segments,
  1113. /// each as a percent-encoded ASCII string.
  1114. ///
  1115. /// Return `None` for cannot-be-a-base URLs.
  1116. ///
  1117. /// When `Some` is returned, the iterator always contains at least one string
  1118. /// (which may be empty).
  1119. ///
  1120. /// # Examples
  1121. ///
  1122. /// ```
  1123. /// use url::Url;
  1124. /// # use std::error::Error;
  1125. ///
  1126. /// # fn run() -> Result<(), Box<dyn Error>> {
  1127. /// let url = Url::parse("https://example.com/foo/bar")?;
  1128. /// let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
  1129. /// assert_eq!(path_segments.next(), Some("foo"));
  1130. /// assert_eq!(path_segments.next(), Some("bar"));
  1131. /// assert_eq!(path_segments.next(), None);
  1132. ///
  1133. /// let url = Url::parse("https://example.com")?;
  1134. /// let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
  1135. /// assert_eq!(path_segments.next(), Some(""));
  1136. /// assert_eq!(path_segments.next(), None);
  1137. ///
  1138. /// let url = Url::parse("data:text/plain,HelloWorld")?;
  1139. /// assert!(url.path_segments().is_none());
  1140. ///
  1141. /// let url = Url::parse("https://example.com/countries/việt nam")?;
  1142. /// let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
  1143. /// assert_eq!(path_segments.next(), Some("countries"));
  1144. /// assert_eq!(path_segments.next(), Some("vi%E1%BB%87t%20nam"));
  1145. /// # Ok(())
  1146. /// # }
  1147. /// # run().unwrap();
  1148. /// ```
  1149. pub fn path_segments(&self) -> Option<str::Split<'_, char>> {
  1150. let path = self.path();
  1151. path.strip_prefix('/').map(|remainder| remainder.split('/'))
  1152. }
  1153. /// Return this URL’s query string, if any, as a percent-encoded ASCII string.
  1154. ///
  1155. /// # Examples
  1156. ///
  1157. /// ```rust
  1158. /// use url::Url;
  1159. /// # use url::ParseError;
  1160. ///
  1161. /// fn run() -> Result<(), ParseError> {
  1162. /// let url = Url::parse("https://example.com/products?page=2")?;
  1163. /// let query = url.query();
  1164. /// assert_eq!(query, Some("page=2"));
  1165. ///
  1166. /// let url = Url::parse("https://example.com/products")?;
  1167. /// let query = url.query();
  1168. /// assert!(query.is_none());
  1169. ///
  1170. /// let url = Url::parse("https://example.com/?country=español")?;
  1171. /// let query = url.query();
  1172. /// assert_eq!(query, Some("country=espa%C3%B1ol"));
  1173. /// # Ok(())
  1174. /// # }
  1175. /// # run().unwrap();
  1176. /// ```
  1177. pub fn query(&self) -> Option<&str> {
  1178. match (self.query_start, self.fragment_start) {
  1179. (None, _) => None,
  1180. (Some(query_start), None) => {
  1181. debug_assert!(self.byte_at(query_start) == b'?');
  1182. Some(self.slice(query_start + 1..))
  1183. }
  1184. (Some(query_start), Some(fragment_start)) => {
  1185. debug_assert!(self.byte_at(query_start) == b'?');
  1186. Some(self.slice(query_start + 1..fragment_start))
  1187. }
  1188. }
  1189. }
  1190. /// Parse the URL’s query string, if any, as `application/x-www-form-urlencoded`
  1191. /// and return an iterator of (key, value) pairs.
  1192. ///
  1193. /// # Examples
  1194. ///
  1195. /// ```rust
  1196. /// use std::borrow::Cow;
  1197. ///
  1198. /// use url::Url;
  1199. /// # use url::ParseError;
  1200. ///
  1201. /// # fn run() -> Result<(), ParseError> {
  1202. /// let url = Url::parse("https://example.com/products?page=2&sort=desc")?;
  1203. /// let mut pairs = url.query_pairs();
  1204. ///
  1205. /// assert_eq!(pairs.count(), 2);
  1206. ///
  1207. /// assert_eq!(pairs.next(), Some((Cow::Borrowed("page"), Cow::Borrowed("2"))));
  1208. /// assert_eq!(pairs.next(), Some((Cow::Borrowed("sort"), Cow::Borrowed("desc"))));
  1209. /// # Ok(())
  1210. /// # }
  1211. /// # run().unwrap();
  1212. /// ```
  1213. #[inline]
  1214. pub fn query_pairs(&self) -> form_urlencoded::Parse<'_> {
  1215. form_urlencoded::parse(self.query().unwrap_or("").as_bytes())
  1216. }
  1217. /// Return this URL’s fragment identifier, if any.
  1218. ///
  1219. /// A fragment is the part of the URL after the `#` symbol.
  1220. /// The fragment is optional and, if present, contains a fragment identifier
  1221. /// that identifies a secondary resource, such as a section heading
  1222. /// of a document.
  1223. ///
  1224. /// In HTML, the fragment identifier is usually the id attribute of a an element
  1225. /// that is scrolled to on load. Browsers typically will not send the fragment portion
  1226. /// of a URL to the server.
  1227. ///
  1228. /// **Note:** the parser did *not* percent-encode this component,
  1229. /// but the input may have been percent-encoded already.
  1230. ///
  1231. /// # Examples
  1232. ///
  1233. /// ```rust
  1234. /// use url::Url;
  1235. /// # use url::ParseError;
  1236. ///
  1237. /// # fn run() -> Result<(), ParseError> {
  1238. /// let url = Url::parse("https://example.com/data.csv#row=4")?;
  1239. ///
  1240. /// assert_eq!(url.fragment(), Some("row=4"));
  1241. ///
  1242. /// let url = Url::parse("https://example.com/data.csv#cell=4,1-6,2")?;
  1243. ///
  1244. /// assert_eq!(url.fragment(), Some("cell=4,1-6,2"));
  1245. /// # Ok(())
  1246. /// # }
  1247. /// # run().unwrap();
  1248. /// ```
  1249. pub fn fragment(&self) -> Option<&str> {
  1250. self.fragment_start.map(|start| {
  1251. debug_assert!(self.byte_at(start) == b'#');
  1252. self.slice(start + 1..)
  1253. })
  1254. }
  1255. fn mutate<F: FnOnce(&mut Parser<'_>) -> R, R>(&mut self, f: F) -> R {
  1256. let mut parser = Parser::for_setter(mem::take(&mut self.serialization));
  1257. let result = f(&mut parser);
  1258. self.serialization = parser.serialization;
  1259. result
  1260. }
  1261. /// Change this URL’s fragment identifier.
  1262. ///
  1263. /// # Examples
  1264. ///
  1265. /// ```rust
  1266. /// use url::Url;
  1267. /// # use url::ParseError;
  1268. ///
  1269. /// # fn run() -> Result<(), ParseError> {
  1270. /// let mut url = Url::parse("https://example.com/data.csv")?;
  1271. /// assert_eq!(url.as_str(), "https://example.com/data.csv");
  1272. /// url.set_fragment(Some("cell=4,1-6,2"));
  1273. /// assert_eq!(url.as_str(), "https://example.com/data.csv#cell=4,1-6,2");
  1274. /// assert_eq!(url.fragment(), Some("cell=4,1-6,2"));
  1275. ///
  1276. /// url.set_fragment(None);
  1277. /// assert_eq!(url.as_str(), "https://example.com/data.csv");
  1278. /// assert!(url.fragment().is_none());
  1279. /// # Ok(())
  1280. /// # }
  1281. /// # run().unwrap();
  1282. /// ```
  1283. pub fn set_fragment(&mut self, fragment: Option<&str>) {
  1284. // Remove any previous fragment
  1285. if let Some(start) = self.fragment_start {
  1286. debug_assert!(self.byte_at(start) == b'#');
  1287. self.serialization.truncate(start as usize);
  1288. }
  1289. // Write the new one
  1290. if let Some(input) = fragment {
  1291. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  1292. self.serialization.push('#');
  1293. self.mutate(|parser| parser.parse_fragment(parser::Input::no_trim(input)))
  1294. } else {
  1295. self.fragment_start = None
  1296. }
  1297. }
  1298. fn take_fragment(&mut self) -> Option<String> {
  1299. self.fragment_start.take().map(|start| {
  1300. debug_assert!(self.byte_at(start) == b'#');
  1301. let fragment = self.slice(start + 1..).to_owned();
  1302. self.serialization.truncate(start as usize);
  1303. fragment
  1304. })
  1305. }
  1306. fn restore_already_parsed_fragment(&mut self, fragment: Option<String>) {
  1307. if let Some(ref fragment) = fragment {
  1308. assert!(self.fragment_start.is_none());
  1309. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  1310. self.serialization.push('#');
  1311. self.serialization.push_str(fragment);
  1312. }
  1313. }
  1314. /// Change this URL’s query string.
  1315. ///
  1316. /// # Examples
  1317. ///
  1318. /// ```rust
  1319. /// use url::Url;
  1320. /// # use url::ParseError;
  1321. ///
  1322. /// # fn run() -> Result<(), ParseError> {
  1323. /// let mut url = Url::parse("https://example.com/products")?;
  1324. /// assert_eq!(url.as_str(), "https://example.com/products");
  1325. ///
  1326. /// url.set_query(Some("page=2"));
  1327. /// assert_eq!(url.as_str(), "https://example.com/products?page=2");
  1328. /// assert_eq!(url.query(), Some("page=2"));
  1329. /// # Ok(())
  1330. /// # }
  1331. /// # run().unwrap();
  1332. /// ```
  1333. pub fn set_query(&mut self, query: Option<&str>) {
  1334. let fragment = self.take_fragment();
  1335. // Remove any previous query
  1336. if let Some(start) = self.query_start.take() {
  1337. debug_assert!(self.byte_at(start) == b'?');
  1338. self.serialization.truncate(start as usize);
  1339. }
  1340. // Write the new query, if any
  1341. if let Some(input) = query {
  1342. self.query_start = Some(to_u32(self.serialization.len()).unwrap());
  1343. self.serialization.push('?');
  1344. let scheme_type = SchemeType::from(self.scheme());
  1345. let scheme_end = self.scheme_end;
  1346. self.mutate(|parser| {
  1347. let vfn = parser.violation_fn;
  1348. parser.parse_query(
  1349. scheme_type,
  1350. scheme_end,
  1351. parser::Input::trim_tab_and_newlines(input, vfn),
  1352. )
  1353. });
  1354. }
  1355. self.restore_already_parsed_fragment(fragment);
  1356. }
  1357. /// Manipulate this URL’s query string, viewed as a sequence of name/value pairs
  1358. /// in `application/x-www-form-urlencoded` syntax.
  1359. ///
  1360. /// The return value has a method-chaining API:
  1361. ///
  1362. /// ```rust
  1363. /// # use url::{Url, ParseError};
  1364. ///
  1365. /// # fn run() -> Result<(), ParseError> {
  1366. /// let mut url = Url::parse("https://example.net?lang=fr#nav")?;
  1367. /// assert_eq!(url.query(), Some("lang=fr"));
  1368. ///
  1369. /// url.query_pairs_mut().append_pair("foo", "bar");
  1370. /// assert_eq!(url.query(), Some("lang=fr&foo=bar"));
  1371. /// assert_eq!(url.as_str(), "https://example.net/?lang=fr&foo=bar#nav");
  1372. ///
  1373. /// url.query_pairs_mut()
  1374. /// .clear()
  1375. /// .append_pair("foo", "bar & baz")
  1376. /// .append_pair("saisons", "\u{00C9}t\u{00E9}+hiver");
  1377. /// assert_eq!(url.query(), Some("foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver"));
  1378. /// assert_eq!(url.as_str(),
  1379. /// "https://example.net/?foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver#nav");
  1380. /// # Ok(())
  1381. /// # }
  1382. /// # run().unwrap();
  1383. /// ```
  1384. ///
  1385. /// Note: `url.query_pairs_mut().clear();` is equivalent to `url.set_query(Some(""))`,
  1386. /// not `url.set_query(None)`.
  1387. ///
  1388. /// The state of `Url` is unspecified if this return value is leaked without being dropped.
  1389. pub fn query_pairs_mut(&mut self) -> form_urlencoded::Serializer<'_, UrlQuery<'_>> {
  1390. let fragment = self.take_fragment();
  1391. let query_start;
  1392. if let Some(start) = self.query_start {
  1393. debug_assert!(self.byte_at(start) == b'?');
  1394. query_start = start as usize;
  1395. } else {
  1396. query_start = self.serialization.len();
  1397. self.query_start = Some(to_u32(query_start).unwrap());
  1398. self.serialization.push('?');
  1399. }
  1400. let query = UrlQuery {
  1401. url: Some(self),
  1402. fragment,
  1403. };
  1404. form_urlencoded::Serializer::for_suffix(query, query_start + "?".len())
  1405. }
  1406. fn take_after_path(&mut self) -> String {
  1407. match (self.query_start, self.fragment_start) {
  1408. (Some(i), _) | (None, Some(i)) => {
  1409. let after_path = self.slice(i..).to_owned();
  1410. self.serialization.truncate(i as usize);
  1411. after_path
  1412. }
  1413. (None, None) => String::new(),
  1414. }
  1415. }
  1416. /// Change this URL’s path.
  1417. ///
  1418. /// # Examples
  1419. ///
  1420. /// ```rust
  1421. /// use url::Url;
  1422. /// # use url::ParseError;
  1423. ///
  1424. /// # fn run() -> Result<(), ParseError> {
  1425. /// let mut url = Url::parse("https://example.com")?;
  1426. /// url.set_path("api/comments");
  1427. /// assert_eq!(url.as_str(), "https://example.com/api/comments");
  1428. /// assert_eq!(url.path(), "/api/comments");
  1429. ///
  1430. /// let mut url = Url::parse("https://example.com/api")?;
  1431. /// url.set_path("data/report.csv");
  1432. /// assert_eq!(url.as_str(), "https://example.com/data/report.csv");
  1433. /// assert_eq!(url.path(), "/data/report.csv");
  1434. ///
  1435. /// // `set_path` percent-encodes the given string if it's not already percent-encoded.
  1436. /// let mut url = Url::parse("https://example.com")?;
  1437. /// url.set_path("api/some comments");
  1438. /// assert_eq!(url.as_str(), "https://example.com/api/some%20comments");
  1439. /// assert_eq!(url.path(), "/api/some%20comments");
  1440. ///
  1441. /// // `set_path` will not double percent-encode the string if it's already percent-encoded.
  1442. /// let mut url = Url::parse("https://example.com")?;
  1443. /// url.set_path("api/some%20comments");
  1444. /// assert_eq!(url.as_str(), "https://example.com/api/some%20comments");
  1445. /// assert_eq!(url.path(), "/api/some%20comments");
  1446. ///
  1447. /// # Ok(())
  1448. /// # }
  1449. /// # run().unwrap();
  1450. /// ```
  1451. pub fn set_path(&mut self, mut path: &str) {
  1452. let after_path = self.take_after_path();
  1453. let old_after_path_pos = to_u32(self.serialization.len()).unwrap();
  1454. let cannot_be_a_base = self.cannot_be_a_base();
  1455. let scheme_type = SchemeType::from(self.scheme());
  1456. self.serialization.truncate(self.path_start as usize);
  1457. self.mutate(|parser| {
  1458. if cannot_be_a_base {
  1459. if path.starts_with('/') {
  1460. parser.serialization.push_str("%2F");
  1461. path = &path[1..];
  1462. }
  1463. parser.parse_cannot_be_a_base_path(parser::Input::new(path));
  1464. } else {
  1465. let mut has_host = true; // FIXME
  1466. parser.parse_path_start(scheme_type, &mut has_host, parser::Input::new(path));
  1467. }
  1468. });
  1469. self.restore_after_path(old_after_path_pos, &after_path);
  1470. }
  1471. /// Return an object with methods to manipulate this URL’s path segments.
  1472. ///
  1473. /// Return `Err(())` if this URL is cannot-be-a-base.
  1474. #[allow(clippy::result_unit_err)]
  1475. pub fn path_segments_mut(&mut self) -> Result<PathSegmentsMut<'_>, ()> {
  1476. if self.cannot_be_a_base() {
  1477. Err(())
  1478. } else {
  1479. Ok(path_segments::new(self))
  1480. }
  1481. }
  1482. fn restore_after_path(&mut self, old_after_path_position: u32, after_path: &str) {
  1483. let new_after_path_position = to_u32(self.serialization.len()).unwrap();
  1484. let adjust = |index: &mut u32| {
  1485. *index -= old_after_path_position;
  1486. *index += new_after_path_position;
  1487. };
  1488. if let Some(ref mut index) = self.query_start {
  1489. adjust(index)
  1490. }
  1491. if let Some(ref mut index) = self.fragment_start {
  1492. adjust(index)
  1493. }
  1494. self.serialization.push_str(after_path)
  1495. }
  1496. /// Change this URL’s port number.
  1497. ///
  1498. /// Note that default port numbers are not reflected in the serialization.
  1499. ///
  1500. /// If this URL is cannot-be-a-base, does not have a host, or has the `file` scheme;
  1501. /// do nothing and return `Err`.
  1502. ///
  1503. /// # Examples
  1504. ///
  1505. /// ```
  1506. /// use url::Url;
  1507. /// # use std::error::Error;
  1508. ///
  1509. /// # fn run() -> Result<(), Box<dyn Error>> {
  1510. /// let mut url = Url::parse("ssh://example.net:2048/")?;
  1511. ///
  1512. /// url.set_port(Some(4096)).map_err(|_| "cannot be base")?;
  1513. /// assert_eq!(url.as_str(), "ssh://example.net:4096/");
  1514. ///
  1515. /// url.set_port(None).map_err(|_| "cannot be base")?;
  1516. /// assert_eq!(url.as_str(), "ssh://example.net/");
  1517. /// # Ok(())
  1518. /// # }
  1519. /// # run().unwrap();
  1520. /// ```
  1521. ///
  1522. /// Known default port numbers are not reflected:
  1523. ///
  1524. /// ```rust
  1525. /// use url::Url;
  1526. /// # use std::error::Error;
  1527. ///
  1528. /// # fn run() -> Result<(), Box<dyn Error>> {
  1529. /// let mut url = Url::parse("https://example.org/")?;
  1530. ///
  1531. /// url.set_port(Some(443)).map_err(|_| "cannot be base")?;
  1532. /// assert!(url.port().is_none());
  1533. /// # Ok(())
  1534. /// # }
  1535. /// # run().unwrap();
  1536. /// ```
  1537. ///
  1538. /// Cannot set port for cannot-be-a-base URLs:
  1539. ///
  1540. /// ```
  1541. /// use url::Url;
  1542. /// # use url::ParseError;
  1543. ///
  1544. /// # fn run() -> Result<(), ParseError> {
  1545. /// let mut url = Url::parse("mailto:rms@example.net")?;
  1546. ///
  1547. /// let result = url.set_port(Some(80));
  1548. /// assert!(result.is_err());
  1549. ///
  1550. /// let result = url.set_port(None);
  1551. /// assert!(result.is_err());
  1552. /// # Ok(())
  1553. /// # }
  1554. /// # run().unwrap();
  1555. /// ```
  1556. #[allow(clippy::result_unit_err)]
  1557. pub fn set_port(&mut self, mut port: Option<u16>) -> Result<(), ()> {
  1558. // has_host implies !cannot_be_a_base
  1559. if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
  1560. return Err(());
  1561. }
  1562. if port.is_some() && port == parser::default_port(self.scheme()) {
  1563. port = None
  1564. }
  1565. self.set_port_internal(port);
  1566. Ok(())
  1567. }
  1568. fn set_port_internal(&mut self, port: Option<u16>) {
  1569. match (self.port, port) {
  1570. (None, None) => {}
  1571. (Some(_), None) => {
  1572. self.serialization
  1573. .drain(self.host_end as usize..self.path_start as usize);
  1574. let offset = self.path_start - self.host_end;
  1575. self.path_start = self.host_end;
  1576. if let Some(ref mut index) = self.query_start {
  1577. *index -= offset
  1578. }
  1579. if let Some(ref mut index) = self.fragment_start {
  1580. *index -= offset
  1581. }
  1582. }
  1583. (Some(old), Some(new)) if old == new => {}
  1584. (_, Some(new)) => {
  1585. let path_and_after = self.slice(self.path_start..).to_owned();
  1586. self.serialization.truncate(self.host_end as usize);
  1587. write!(&mut self.serialization, ":{}", new).unwrap();
  1588. let old_path_start = self.path_start;
  1589. let new_path_start = to_u32(self.serialization.len()).unwrap();
  1590. self.path_start = new_path_start;
  1591. let adjust = |index: &mut u32| {
  1592. *index -= old_path_start;
  1593. *index += new_path_start;
  1594. };
  1595. if let Some(ref mut index) = self.query_start {
  1596. adjust(index)
  1597. }
  1598. if let Some(ref mut index) = self.fragment_start {
  1599. adjust(index)
  1600. }
  1601. self.serialization.push_str(&path_and_after);
  1602. }
  1603. }
  1604. self.port = port;
  1605. }
  1606. /// Change this URL’s host.
  1607. ///
  1608. /// Removing the host (calling this with `None`)
  1609. /// will also remove any username, password, and port number.
  1610. ///
  1611. /// # Examples
  1612. ///
  1613. /// Change host:
  1614. ///
  1615. /// ```
  1616. /// use url::Url;
  1617. /// # use url::ParseError;
  1618. ///
  1619. /// # fn run() -> Result<(), ParseError> {
  1620. /// let mut url = Url::parse("https://example.net")?;
  1621. /// let result = url.set_host(Some("rust-lang.org"));
  1622. /// assert!(result.is_ok());
  1623. /// assert_eq!(url.as_str(), "https://rust-lang.org/");
  1624. /// # Ok(())
  1625. /// # }
  1626. /// # run().unwrap();
  1627. /// ```
  1628. ///
  1629. /// Remove host:
  1630. ///
  1631. /// ```
  1632. /// use url::Url;
  1633. /// # use url::ParseError;
  1634. ///
  1635. /// # fn run() -> Result<(), ParseError> {
  1636. /// let mut url = Url::parse("foo://example.net")?;
  1637. /// let result = url.set_host(None);
  1638. /// assert!(result.is_ok());
  1639. /// assert_eq!(url.as_str(), "foo:/");
  1640. /// # Ok(())
  1641. /// # }
  1642. /// # run().unwrap();
  1643. /// ```
  1644. ///
  1645. /// Cannot remove host for 'special' schemes (e.g. `http`):
  1646. ///
  1647. /// ```
  1648. /// use url::Url;
  1649. /// # use url::ParseError;
  1650. ///
  1651. /// # fn run() -> Result<(), ParseError> {
  1652. /// let mut url = Url::parse("https://example.net")?;
  1653. /// let result = url.set_host(None);
  1654. /// assert!(result.is_err());
  1655. /// assert_eq!(url.as_str(), "https://example.net/");
  1656. /// # Ok(())
  1657. /// # }
  1658. /// # run().unwrap();
  1659. /// ```
  1660. ///
  1661. /// Cannot change or remove host for cannot-be-a-base URLs:
  1662. ///
  1663. /// ```
  1664. /// use url::Url;
  1665. /// # use url::ParseError;
  1666. ///
  1667. /// # fn run() -> Result<(), ParseError> {
  1668. /// let mut url = Url::parse("mailto:rms@example.net")?;
  1669. ///
  1670. /// let result = url.set_host(Some("rust-lang.org"));
  1671. /// assert!(result.is_err());
  1672. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  1673. ///
  1674. /// let result = url.set_host(None);
  1675. /// assert!(result.is_err());
  1676. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  1677. /// # Ok(())
  1678. /// # }
  1679. /// # run().unwrap();
  1680. /// ```
  1681. ///
  1682. /// # Errors
  1683. ///
  1684. /// If this URL is cannot-be-a-base or there is an error parsing the given `host`,
  1685. /// a [`ParseError`] variant will be returned.
  1686. ///
  1687. /// [`ParseError`]: enum.ParseError.html
  1688. pub fn set_host(&mut self, host: Option<&str>) -> Result<(), ParseError> {
  1689. if self.cannot_be_a_base() {
  1690. return Err(ParseError::SetHostOnCannotBeABaseUrl);
  1691. }
  1692. let scheme_type = SchemeType::from(self.scheme());
  1693. if let Some(host) = host {
  1694. if host.is_empty() && scheme_type.is_special() && !scheme_type.is_file() {
  1695. return Err(ParseError::EmptyHost);
  1696. }
  1697. let mut host_substr = host;
  1698. // Otherwise, if c is U+003A (:) and the [] flag is unset, then
  1699. if !host.starts_with('[') || !host.ends_with(']') {
  1700. match host.find(':') {
  1701. Some(0) => {
  1702. // If buffer is the empty string, validation error, return failure.
  1703. return Err(ParseError::InvalidDomainCharacter);
  1704. }
  1705. // Let host be the result of host parsing buffer
  1706. Some(colon_index) => {
  1707. host_substr = &host[..colon_index];
  1708. }
  1709. None => {}
  1710. }
  1711. }
  1712. if SchemeType::from(self.scheme()).is_special() {
  1713. self.set_host_internal(Host::parse(host_substr)?, None);
  1714. } else {
  1715. self.set_host_internal(Host::parse_opaque(host_substr)?, None);
  1716. }
  1717. } else if self.has_host() {
  1718. if scheme_type.is_special() && !scheme_type.is_file() {
  1719. return Err(ParseError::EmptyHost);
  1720. } else if self.serialization.len() == self.path_start as usize {
  1721. self.serialization.push('/');
  1722. }
  1723. debug_assert!(self.byte_at(self.scheme_end) == b':');
  1724. debug_assert!(self.byte_at(self.path_start) == b'/');
  1725. let new_path_start = if scheme_type.is_file() {
  1726. self.scheme_end + 3
  1727. } else {
  1728. self.scheme_end + 1
  1729. };
  1730. self.serialization
  1731. .drain(new_path_start as usize..self.path_start as usize);
  1732. let offset = self.path_start - new_path_start;
  1733. self.path_start = new_path_start;
  1734. self.username_end = new_path_start;
  1735. self.host_start = new_path_start;
  1736. self.host_end = new_path_start;
  1737. self.port = None;
  1738. if let Some(ref mut index) = self.query_start {
  1739. *index -= offset
  1740. }
  1741. if let Some(ref mut index) = self.fragment_start {
  1742. *index -= offset
  1743. }
  1744. }
  1745. Ok(())
  1746. }
  1747. /// opt_new_port: None means leave unchanged, Some(None) means remove any port number.
  1748. fn set_host_internal(&mut self, host: Host<String>, opt_new_port: Option<Option<u16>>) {
  1749. let old_suffix_pos = if opt_new_port.is_some() {
  1750. self.path_start
  1751. } else {
  1752. self.host_end
  1753. };
  1754. let suffix = self.slice(old_suffix_pos..).to_owned();
  1755. self.serialization.truncate(self.host_start as usize);
  1756. if !self.has_authority() {
  1757. debug_assert!(self.slice(self.scheme_end..self.host_start) == ":");
  1758. debug_assert!(self.username_end == self.host_start);
  1759. self.serialization.push('/');
  1760. self.serialization.push('/');
  1761. self.username_end += 2;
  1762. self.host_start += 2;
  1763. }
  1764. write!(&mut self.serialization, "{}", host).unwrap();
  1765. self.host_end = to_u32(self.serialization.len()).unwrap();
  1766. self.host = host.into();
  1767. if let Some(new_port) = opt_new_port {
  1768. self.port = new_port;
  1769. if let Some(port) = new_port {
  1770. write!(&mut self.serialization, ":{}", port).unwrap();
  1771. }
  1772. }
  1773. let new_suffix_pos = to_u32(self.serialization.len()).unwrap();
  1774. self.serialization.push_str(&suffix);
  1775. let adjust = |index: &mut u32| {
  1776. *index -= old_suffix_pos;
  1777. *index += new_suffix_pos;
  1778. };
  1779. adjust(&mut self.path_start);
  1780. if let Some(ref mut index) = self.query_start {
  1781. adjust(index)
  1782. }
  1783. if let Some(ref mut index) = self.fragment_start {
  1784. adjust(index)
  1785. }
  1786. }
  1787. /// Change this URL’s host to the given IP address.
  1788. ///
  1789. /// If this URL is cannot-be-a-base, do nothing and return `Err`.
  1790. ///
  1791. /// Compared to `Url::set_host`, this skips the host parser.
  1792. ///
  1793. /// # Examples
  1794. ///
  1795. /// ```rust
  1796. /// use url::{Url, ParseError};
  1797. ///
  1798. /// # fn run() -> Result<(), ParseError> {
  1799. /// let mut url = Url::parse("http://example.com")?;
  1800. /// url.set_ip_host("127.0.0.1".parse().unwrap());
  1801. /// assert_eq!(url.host_str(), Some("127.0.0.1"));
  1802. /// assert_eq!(url.as_str(), "http://127.0.0.1/");
  1803. /// # Ok(())
  1804. /// # }
  1805. /// # run().unwrap();
  1806. /// ```
  1807. ///
  1808. /// Cannot change URL's from mailto(cannot-be-base) to ip:
  1809. ///
  1810. /// ```rust
  1811. /// use url::{Url, ParseError};
  1812. ///
  1813. /// # fn run() -> Result<(), ParseError> {
  1814. /// let mut url = Url::parse("mailto:rms@example.com")?;
  1815. /// let result = url.set_ip_host("127.0.0.1".parse().unwrap());
  1816. ///
  1817. /// assert_eq!(url.as_str(), "mailto:rms@example.com");
  1818. /// assert!(result.is_err());
  1819. /// # Ok(())
  1820. /// # }
  1821. /// # run().unwrap();
  1822. /// ```
  1823. ///
  1824. #[allow(clippy::result_unit_err)]
  1825. pub fn set_ip_host(&mut self, address: IpAddr) -> Result<(), ()> {
  1826. if self.cannot_be_a_base() {
  1827. return Err(());
  1828. }
  1829. let address = match address {
  1830. IpAddr::V4(address) => Host::Ipv4(address),
  1831. IpAddr::V6(address) => Host::Ipv6(address),
  1832. };
  1833. self.set_host_internal(address, None);
  1834. Ok(())
  1835. }
  1836. /// Change this URL’s password.
  1837. ///
  1838. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  1839. ///
  1840. /// # Examples
  1841. ///
  1842. /// ```rust
  1843. /// use url::{Url, ParseError};
  1844. ///
  1845. /// # fn run() -> Result<(), ParseError> {
  1846. /// let mut url = Url::parse("mailto:rmz@example.com")?;
  1847. /// let result = url.set_password(Some("secret_password"));
  1848. /// assert!(result.is_err());
  1849. ///
  1850. /// let mut url = Url::parse("ftp://user1:secret1@example.com")?;
  1851. /// let result = url.set_password(Some("secret_password"));
  1852. /// assert_eq!(url.password(), Some("secret_password"));
  1853. ///
  1854. /// let mut url = Url::parse("ftp://user2:@example.com")?;
  1855. /// let result = url.set_password(Some("secret2"));
  1856. /// assert!(result.is_ok());
  1857. /// assert_eq!(url.password(), Some("secret2"));
  1858. /// # Ok(())
  1859. /// # }
  1860. /// # run().unwrap();
  1861. /// ```
  1862. #[allow(clippy::result_unit_err)]
  1863. pub fn set_password(&mut self, password: Option<&str>) -> Result<(), ()> {
  1864. // has_host implies !cannot_be_a_base
  1865. if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
  1866. return Err(());
  1867. }
  1868. if let Some(password) = password {
  1869. let host_and_after = self.slice(self.host_start..).to_owned();
  1870. self.serialization.truncate(self.username_end as usize);
  1871. self.serialization.push(':');
  1872. self.serialization
  1873. .extend(utf8_percent_encode(password, USERINFO));
  1874. self.serialization.push('@');
  1875. let old_host_start = self.host_start;
  1876. let new_host_start = to_u32(self.serialization.len()).unwrap();
  1877. let adjust = |index: &mut u32| {
  1878. *index -= old_host_start;
  1879. *index += new_host_start;
  1880. };
  1881. self.host_start = new_host_start;
  1882. adjust(&mut self.host_end);
  1883. adjust(&mut self.path_start);
  1884. if let Some(ref mut index) = self.query_start {
  1885. adjust(index)
  1886. }
  1887. if let Some(ref mut index) = self.fragment_start {
  1888. adjust(index)
  1889. }
  1890. self.serialization.push_str(&host_and_after);
  1891. } else if self.byte_at(self.username_end) == b':' {
  1892. // If there is a password to remove
  1893. let has_username_or_password = self.byte_at(self.host_start - 1) == b'@';
  1894. debug_assert!(has_username_or_password);
  1895. let username_start = self.scheme_end + 3;
  1896. let empty_username = username_start == self.username_end;
  1897. let start = self.username_end; // Remove the ':'
  1898. let end = if empty_username {
  1899. self.host_start // Remove the '@' as well
  1900. } else {
  1901. self.host_start - 1 // Keep the '@' to separate the username from the host
  1902. };
  1903. self.serialization.drain(start as usize..end as usize);
  1904. let offset = end - start;
  1905. self.host_start -= offset;
  1906. self.host_end -= offset;
  1907. self.path_start -= offset;
  1908. if let Some(ref mut index) = self.query_start {
  1909. *index -= offset
  1910. }
  1911. if let Some(ref mut index) = self.fragment_start {
  1912. *index -= offset
  1913. }
  1914. }
  1915. Ok(())
  1916. }
  1917. /// Change this URL’s username.
  1918. ///
  1919. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  1920. /// # Examples
  1921. ///
  1922. /// Cannot setup username from mailto(cannot-be-base)
  1923. ///
  1924. /// ```rust
  1925. /// use url::{Url, ParseError};
  1926. ///
  1927. /// # fn run() -> Result<(), ParseError> {
  1928. /// let mut url = Url::parse("mailto:rmz@example.com")?;
  1929. /// let result = url.set_username("user1");
  1930. /// assert_eq!(url.as_str(), "mailto:rmz@example.com");
  1931. /// assert!(result.is_err());
  1932. /// # Ok(())
  1933. /// # }
  1934. /// # run().unwrap();
  1935. /// ```
  1936. ///
  1937. /// Setup username to user1
  1938. ///
  1939. /// ```rust
  1940. /// use url::{Url, ParseError};
  1941. ///
  1942. /// # fn run() -> Result<(), ParseError> {
  1943. /// let mut url = Url::parse("ftp://:secre1@example.com/")?;
  1944. /// let result = url.set_username("user1");
  1945. /// assert!(result.is_ok());
  1946. /// assert_eq!(url.username(), "user1");
  1947. /// assert_eq!(url.as_str(), "ftp://user1:secre1@example.com/");
  1948. /// # Ok(())
  1949. /// # }
  1950. /// # run().unwrap();
  1951. /// ```
  1952. #[allow(clippy::result_unit_err)]
  1953. pub fn set_username(&mut self, username: &str) -> Result<(), ()> {
  1954. // has_host implies !cannot_be_a_base
  1955. if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
  1956. return Err(());
  1957. }
  1958. let username_start = self.scheme_end + 3;
  1959. debug_assert!(self.slice(self.scheme_end..username_start) == "://");
  1960. if self.slice(username_start..self.username_end) == username {
  1961. return Ok(());
  1962. }
  1963. let after_username = self.slice(self.username_end..).to_owned();
  1964. self.serialization.truncate(username_start as usize);
  1965. self.serialization
  1966. .extend(utf8_percent_encode(username, USERINFO));
  1967. let mut removed_bytes = self.username_end;
  1968. self.username_end = to_u32(self.serialization.len()).unwrap();
  1969. let mut added_bytes = self.username_end;
  1970. let new_username_is_empty = self.username_end == username_start;
  1971. match (new_username_is_empty, after_username.chars().next()) {
  1972. (true, Some('@')) => {
  1973. removed_bytes += 1;
  1974. self.serialization.push_str(&after_username[1..]);
  1975. }
  1976. (false, Some('@')) | (_, Some(':')) | (true, _) => {
  1977. self.serialization.push_str(&after_username);
  1978. }
  1979. (false, _) => {
  1980. added_bytes += 1;
  1981. self.serialization.push('@');
  1982. self.serialization.push_str(&after_username);
  1983. }
  1984. }
  1985. let adjust = |index: &mut u32| {
  1986. *index -= removed_bytes;
  1987. *index += added_bytes;
  1988. };
  1989. adjust(&mut self.host_start);
  1990. adjust(&mut self.host_end);
  1991. adjust(&mut self.path_start);
  1992. if let Some(ref mut index) = self.query_start {
  1993. adjust(index)
  1994. }
  1995. if let Some(ref mut index) = self.fragment_start {
  1996. adjust(index)
  1997. }
  1998. Ok(())
  1999. }
  2000. /// Change this URL’s scheme.
  2001. ///
  2002. /// Do nothing and return `Err` under the following circumstances:
  2003. ///
  2004. /// * If the new scheme is not in `[a-zA-Z][a-zA-Z0-9+.-]+`
  2005. /// * If this URL is cannot-be-a-base and the new scheme is one of
  2006. /// `http`, `https`, `ws`, `wss` or `ftp`
  2007. /// * If either the old or new scheme is `http`, `https`, `ws`,
  2008. /// `wss` or `ftp` and the other is not one of these
  2009. /// * If the new scheme is `file` and this URL includes credentials
  2010. /// or has a non-null port
  2011. /// * If this URL's scheme is `file` and its host is empty or null
  2012. ///
  2013. /// See also [the URL specification's section on legal scheme state
  2014. /// overrides](https://url.spec.whatwg.org/#scheme-state).
  2015. ///
  2016. /// # Examples
  2017. ///
  2018. /// Change the URL’s scheme from `https` to `http`:
  2019. ///
  2020. /// ```
  2021. /// use url::Url;
  2022. /// # use url::ParseError;
  2023. ///
  2024. /// # fn run() -> Result<(), ParseError> {
  2025. /// let mut url = Url::parse("https://example.net")?;
  2026. /// let result = url.set_scheme("http");
  2027. /// assert_eq!(url.as_str(), "http://example.net/");
  2028. /// assert!(result.is_ok());
  2029. /// # Ok(())
  2030. /// # }
  2031. /// # run().unwrap();
  2032. /// ```
  2033. /// Change the URL’s scheme from `foo` to `bar`:
  2034. ///
  2035. /// ```
  2036. /// use url::Url;
  2037. /// # use url::ParseError;
  2038. ///
  2039. /// # fn run() -> Result<(), ParseError> {
  2040. /// let mut url = Url::parse("foo://example.net")?;
  2041. /// let result = url.set_scheme("bar");
  2042. /// assert_eq!(url.as_str(), "bar://example.net");
  2043. /// assert!(result.is_ok());
  2044. /// # Ok(())
  2045. /// # }
  2046. /// # run().unwrap();
  2047. /// ```
  2048. ///
  2049. /// Cannot change URL’s scheme from `https` to `foõ`:
  2050. ///
  2051. /// ```
  2052. /// use url::Url;
  2053. /// # use url::ParseError;
  2054. ///
  2055. /// # fn run() -> Result<(), ParseError> {
  2056. /// let mut url = Url::parse("https://example.net")?;
  2057. /// let result = url.set_scheme("foõ");
  2058. /// assert_eq!(url.as_str(), "https://example.net/");
  2059. /// assert!(result.is_err());
  2060. /// # Ok(())
  2061. /// # }
  2062. /// # run().unwrap();
  2063. /// ```
  2064. ///
  2065. /// Cannot change URL’s scheme from `mailto` (cannot-be-a-base) to `https`:
  2066. ///
  2067. /// ```
  2068. /// use url::Url;
  2069. /// # use url::ParseError;
  2070. ///
  2071. /// # fn run() -> Result<(), ParseError> {
  2072. /// let mut url = Url::parse("mailto:rms@example.net")?;
  2073. /// let result = url.set_scheme("https");
  2074. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  2075. /// assert!(result.is_err());
  2076. /// # Ok(())
  2077. /// # }
  2078. /// # run().unwrap();
  2079. /// ```
  2080. /// Cannot change the URL’s scheme from `foo` to `https`:
  2081. ///
  2082. /// ```
  2083. /// use url::Url;
  2084. /// # use url::ParseError;
  2085. ///
  2086. /// # fn run() -> Result<(), ParseError> {
  2087. /// let mut url = Url::parse("foo://example.net")?;
  2088. /// let result = url.set_scheme("https");
  2089. /// assert_eq!(url.as_str(), "foo://example.net");
  2090. /// assert!(result.is_err());
  2091. /// # Ok(())
  2092. /// # }
  2093. /// # run().unwrap();
  2094. /// ```
  2095. /// Cannot change the URL’s scheme from `http` to `foo`:
  2096. ///
  2097. /// ```
  2098. /// use url::Url;
  2099. /// # use url::ParseError;
  2100. ///
  2101. /// # fn run() -> Result<(), ParseError> {
  2102. /// let mut url = Url::parse("http://example.net")?;
  2103. /// let result = url.set_scheme("foo");
  2104. /// assert_eq!(url.as_str(), "http://example.net/");
  2105. /// assert!(result.is_err());
  2106. /// # Ok(())
  2107. /// # }
  2108. /// # run().unwrap();
  2109. /// ```
  2110. #[allow(clippy::result_unit_err, clippy::suspicious_operation_groupings)]
  2111. pub fn set_scheme(&mut self, scheme: &str) -> Result<(), ()> {
  2112. let mut parser = Parser::for_setter(String::new());
  2113. let remaining = parser.parse_scheme(parser::Input::new(scheme))?;
  2114. let new_scheme_type = SchemeType::from(&parser.serialization);
  2115. let old_scheme_type = SchemeType::from(self.scheme());
  2116. // If url’s scheme is a special scheme and buffer is not a special scheme, then return.
  2117. if (new_scheme_type.is_special() && !old_scheme_type.is_special()) ||
  2118. // If url’s scheme is not a special scheme and buffer is a special scheme, then return.
  2119. (!new_scheme_type.is_special() && old_scheme_type.is_special()) ||
  2120. // If url includes credentials or has a non-null port, and buffer is "file", then return.
  2121. // If url’s scheme is "file" and its host is an empty host or null, then return.
  2122. (new_scheme_type.is_file() && self.has_authority())
  2123. {
  2124. return Err(());
  2125. }
  2126. if !remaining.is_empty() || (!self.has_host() && new_scheme_type.is_special()) {
  2127. return Err(());
  2128. }
  2129. let old_scheme_end = self.scheme_end;
  2130. let new_scheme_end = to_u32(parser.serialization.len()).unwrap();
  2131. let adjust = |index: &mut u32| {
  2132. *index -= old_scheme_end;
  2133. *index += new_scheme_end;
  2134. };
  2135. self.scheme_end = new_scheme_end;
  2136. adjust(&mut self.username_end);
  2137. adjust(&mut self.host_start);
  2138. adjust(&mut self.host_end);
  2139. adjust(&mut self.path_start);
  2140. if let Some(ref mut index) = self.query_start {
  2141. adjust(index)
  2142. }
  2143. if let Some(ref mut index) = self.fragment_start {
  2144. adjust(index)
  2145. }
  2146. parser.serialization.push_str(self.slice(old_scheme_end..));
  2147. self.serialization = parser.serialization;
  2148. // Update the port so it can be removed
  2149. // If it is the scheme's default
  2150. // we don't mind it silently failing
  2151. // if there was no port in the first place
  2152. let previous_port = self.port();
  2153. let _ = self.set_port(previous_port);
  2154. Ok(())
  2155. }
  2156. /// Convert a file name as `std::path::Path` into an URL in the `file` scheme.
  2157. ///
  2158. /// This returns `Err` if the given path is not absolute or,
  2159. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`) or a UNC prefix (`\\`).
  2160. ///
  2161. /// # Examples
  2162. ///
  2163. /// On Unix-like platforms:
  2164. ///
  2165. /// ```
  2166. /// # if cfg!(unix) {
  2167. /// use url::Url;
  2168. ///
  2169. /// # fn run() -> Result<(), ()> {
  2170. /// let url = Url::from_file_path("/tmp/foo.txt")?;
  2171. /// assert_eq!(url.as_str(), "file:///tmp/foo.txt");
  2172. ///
  2173. /// let url = Url::from_file_path("../foo.txt");
  2174. /// assert!(url.is_err());
  2175. ///
  2176. /// let url = Url::from_file_path("https://google.com/");
  2177. /// assert!(url.is_err());
  2178. /// # Ok(())
  2179. /// # }
  2180. /// # run().unwrap();
  2181. /// # }
  2182. /// ```
  2183. #[cfg(any(unix, windows, target_os = "redox", target_os = "wasi"))]
  2184. #[allow(clippy::result_unit_err)]
  2185. pub fn from_file_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  2186. let mut serialization = "file://".to_owned();
  2187. let host_start = serialization.len() as u32;
  2188. let (host_end, host) = path_to_file_url_segments(path.as_ref(), &mut serialization)?;
  2189. Ok(Url {
  2190. serialization,
  2191. scheme_end: "file".len() as u32,
  2192. username_end: host_start,
  2193. host_start,
  2194. host_end,
  2195. host,
  2196. port: None,
  2197. path_start: host_end,
  2198. query_start: None,
  2199. fragment_start: None,
  2200. })
  2201. }
  2202. /// Convert a directory name as `std::path::Path` into an URL in the `file` scheme.
  2203. ///
  2204. /// This returns `Err` if the given path is not absolute or,
  2205. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`) or a UNC prefix (`\\`).
  2206. ///
  2207. /// Compared to `from_file_path`, this ensure that URL’s the path has a trailing slash
  2208. /// so that the entire path is considered when using this URL as a base URL.
  2209. ///
  2210. /// For example:
  2211. ///
  2212. /// * `"index.html"` parsed with `Url::from_directory_path(Path::new("/var/www"))`
  2213. /// as the base URL is `file:///var/www/index.html`
  2214. /// * `"index.html"` parsed with `Url::from_file_path(Path::new("/var/www"))`
  2215. /// as the base URL is `file:///var/index.html`, which might not be what was intended.
  2216. ///
  2217. /// Note that `std::path` does not consider trailing slashes significant
  2218. /// and usually does not include them (e.g. in `Path::parent()`).
  2219. #[cfg(any(unix, windows, target_os = "redox", target_os = "wasi"))]
  2220. #[allow(clippy::result_unit_err)]
  2221. pub fn from_directory_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  2222. let mut url = Url::from_file_path(path)?;
  2223. if !url.serialization.ends_with('/') {
  2224. url.serialization.push('/')
  2225. }
  2226. Ok(url)
  2227. }
  2228. /// Serialize with Serde using the internal representation of the `Url` struct.
  2229. ///
  2230. /// The corresponding `deserialize_internal` method sacrifices some invariant-checking
  2231. /// for speed, compared to the `Deserialize` trait impl.
  2232. ///
  2233. /// This method is only available if the `serde` Cargo feature is enabled.
  2234. #[cfg(feature = "serde")]
  2235. #[deny(unused)]
  2236. pub fn serialize_internal<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  2237. where
  2238. S: serde::Serializer,
  2239. {
  2240. use serde::Serialize;
  2241. // Destructuring first lets us ensure that adding or removing fields forces this method
  2242. // to be updated
  2243. let Url {
  2244. ref serialization,
  2245. ref scheme_end,
  2246. ref username_end,
  2247. ref host_start,
  2248. ref host_end,
  2249. ref host,
  2250. ref port,
  2251. ref path_start,
  2252. ref query_start,
  2253. ref fragment_start,
  2254. } = *self;
  2255. (
  2256. serialization,
  2257. scheme_end,
  2258. username_end,
  2259. host_start,
  2260. host_end,
  2261. host,
  2262. port,
  2263. path_start,
  2264. query_start,
  2265. fragment_start,
  2266. )
  2267. .serialize(serializer)
  2268. }
  2269. /// Serialize with Serde using the internal representation of the `Url` struct.
  2270. ///
  2271. /// The corresponding `deserialize_internal` method sacrifices some invariant-checking
  2272. /// for speed, compared to the `Deserialize` trait impl.
  2273. ///
  2274. /// This method is only available if the `serde` Cargo feature is enabled.
  2275. #[cfg(feature = "serde")]
  2276. #[deny(unused)]
  2277. pub fn deserialize_internal<'de, D>(deserializer: D) -> Result<Self, D::Error>
  2278. where
  2279. D: serde::Deserializer<'de>,
  2280. {
  2281. use serde::de::{Deserialize, Error, Unexpected};
  2282. let (
  2283. serialization,
  2284. scheme_end,
  2285. username_end,
  2286. host_start,
  2287. host_end,
  2288. host,
  2289. port,
  2290. path_start,
  2291. query_start,
  2292. fragment_start,
  2293. ) = Deserialize::deserialize(deserializer)?;
  2294. let url = Url {
  2295. serialization,
  2296. scheme_end,
  2297. username_end,
  2298. host_start,
  2299. host_end,
  2300. host,
  2301. port,
  2302. path_start,
  2303. query_start,
  2304. fragment_start,
  2305. };
  2306. if cfg!(debug_assertions) {
  2307. url.check_invariants().map_err(|reason| {
  2308. let reason: &str = &reason;
  2309. Error::invalid_value(Unexpected::Other("value"), &reason)
  2310. })?
  2311. }
  2312. Ok(url)
  2313. }
  2314. /// Assuming the URL is in the `file` scheme or similar,
  2315. /// convert its path to an absolute `std::path::Path`.
  2316. ///
  2317. /// **Note:** This does not actually check the URL’s `scheme`,
  2318. /// and may give nonsensical results for other schemes.
  2319. /// It is the user’s responsibility to check the URL’s scheme before calling this.
  2320. ///
  2321. /// ```
  2322. /// # use url::Url;
  2323. /// # let url = Url::parse("file:///etc/passwd").unwrap();
  2324. /// let path = url.to_file_path();
  2325. /// ```
  2326. ///
  2327. /// Returns `Err` if the host is neither empty nor `"localhost"` (except on Windows, where
  2328. /// `file:` URLs may have a non-local host),
  2329. /// or if `Path::new_opt()` returns `None`.
  2330. /// (That is, if the percent-decoded path contains a NUL byte or,
  2331. /// for a Windows path, is not UTF-8.)
  2332. #[inline]
  2333. #[cfg(any(unix, windows, target_os = "redox", target_os = "wasi"))]
  2334. #[allow(clippy::result_unit_err)]
  2335. pub fn to_file_path(&self) -> Result<PathBuf, ()> {
  2336. if let Some(segments) = self.path_segments() {
  2337. let host = match self.host() {
  2338. None | Some(Host::Domain("localhost")) => None,
  2339. Some(_) if cfg!(windows) && self.scheme() == "file" => {
  2340. Some(&self.serialization[self.host_start as usize..self.host_end as usize])
  2341. }
  2342. _ => return Err(()),
  2343. };
  2344. return file_url_segments_to_pathbuf(host, segments);
  2345. }
  2346. Err(())
  2347. }
  2348. // Private helper methods:
  2349. #[inline]
  2350. fn slice<R>(&self, range: R) -> &str
  2351. where
  2352. R: RangeArg,
  2353. {
  2354. range.slice_of(&self.serialization)
  2355. }
  2356. #[inline]
  2357. fn byte_at(&self, i: u32) -> u8 {
  2358. self.serialization.as_bytes()[i as usize]
  2359. }
  2360. }
  2361. /// Parse a string as an URL, without a base URL or encoding override.
  2362. impl str::FromStr for Url {
  2363. type Err = ParseError;
  2364. #[inline]
  2365. fn from_str(input: &str) -> Result<Url, crate::ParseError> {
  2366. Url::parse(input)
  2367. }
  2368. }
  2369. impl<'a> TryFrom<&'a str> for Url {
  2370. type Error = ParseError;
  2371. fn try_from(s: &'a str) -> Result<Self, Self::Error> {
  2372. Url::parse(s)
  2373. }
  2374. }
  2375. /// Display the serialization of this URL.
  2376. impl fmt::Display for Url {
  2377. #[inline]
  2378. fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
  2379. fmt::Display::fmt(&self.serialization, formatter)
  2380. }
  2381. }
  2382. /// String conversion.
  2383. impl From<Url> for String {
  2384. fn from(value: Url) -> String {
  2385. value.serialization
  2386. }
  2387. }
  2388. /// Debug the serialization of this URL.
  2389. impl fmt::Debug for Url {
  2390. #[inline]
  2391. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  2392. formatter
  2393. .debug_struct("Url")
  2394. .field("scheme", &self.scheme())
  2395. .field("cannot_be_a_base", &self.cannot_be_a_base())
  2396. .field("username", &self.username())
  2397. .field("password", &self.password())
  2398. .field("host", &self.host())
  2399. .field("port", &self.port())
  2400. .field("path", &self.path())
  2401. .field("query", &self.query())
  2402. .field("fragment", &self.fragment())
  2403. .finish()
  2404. }
  2405. }
  2406. /// URLs compare like their serialization.
  2407. impl Eq for Url {}
  2408. /// URLs compare like their serialization.
  2409. impl PartialEq for Url {
  2410. #[inline]
  2411. fn eq(&self, other: &Self) -> bool {
  2412. self.serialization == other.serialization
  2413. }
  2414. }
  2415. /// URLs compare like their serialization.
  2416. impl Ord for Url {
  2417. #[inline]
  2418. fn cmp(&self, other: &Self) -> cmp::Ordering {
  2419. self.serialization.cmp(&other.serialization)
  2420. }
  2421. }
  2422. /// URLs compare like their serialization.
  2423. impl PartialOrd for Url {
  2424. #[inline]
  2425. fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
  2426. self.serialization.partial_cmp(&other.serialization)
  2427. }
  2428. }
  2429. /// URLs hash like their serialization.
  2430. impl hash::Hash for Url {
  2431. #[inline]
  2432. fn hash<H>(&self, state: &mut H)
  2433. where
  2434. H: hash::Hasher,
  2435. {
  2436. hash::Hash::hash(&self.serialization, state)
  2437. }
  2438. }
  2439. /// Return the serialization of this URL.
  2440. impl AsRef<str> for Url {
  2441. #[inline]
  2442. fn as_ref(&self) -> &str {
  2443. &self.serialization
  2444. }
  2445. }
  2446. trait RangeArg {
  2447. fn slice_of<'a>(&self, s: &'a str) -> &'a str;
  2448. }
  2449. impl RangeArg for Range<u32> {
  2450. #[inline]
  2451. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  2452. &s[self.start as usize..self.end as usize]
  2453. }
  2454. }
  2455. impl RangeArg for RangeFrom<u32> {
  2456. #[inline]
  2457. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  2458. &s[self.start as usize..]
  2459. }
  2460. }
  2461. impl RangeArg for RangeTo<u32> {
  2462. #[inline]
  2463. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  2464. &s[..self.end as usize]
  2465. }
  2466. }
  2467. /// Serializes this URL into a `serde` stream.
  2468. ///
  2469. /// This implementation is only available if the `serde` Cargo feature is enabled.
  2470. #[cfg(feature = "serde")]
  2471. impl serde::Serialize for Url {
  2472. fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  2473. where
  2474. S: serde::Serializer,
  2475. {
  2476. serializer.serialize_str(self.as_str())
  2477. }
  2478. }
  2479. /// Deserializes this URL from a `serde` stream.
  2480. ///
  2481. /// This implementation is only available if the `serde` Cargo feature is enabled.
  2482. #[cfg(feature = "serde")]
  2483. impl<'de> serde::Deserialize<'de> for Url {
  2484. fn deserialize<D>(deserializer: D) -> Result<Url, D::Error>
  2485. where
  2486. D: serde::Deserializer<'de>,
  2487. {
  2488. use serde::de::{Error, Unexpected, Visitor};
  2489. struct UrlVisitor;
  2490. impl<'de> Visitor<'de> for UrlVisitor {
  2491. type Value = Url;
  2492. fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  2493. formatter.write_str("a string representing an URL")
  2494. }
  2495. fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
  2496. where
  2497. E: Error,
  2498. {
  2499. Url::parse(s).map_err(|err| {
  2500. let err_s = format!("{}", err);
  2501. Error::invalid_value(Unexpected::Str(s), &err_s.as_str())
  2502. })
  2503. }
  2504. }
  2505. deserializer.deserialize_str(UrlVisitor)
  2506. }
  2507. }
  2508. #[cfg(any(unix, target_os = "redox", target_os = "wasi"))]
  2509. fn path_to_file_url_segments(
  2510. path: &Path,
  2511. serialization: &mut String,
  2512. ) -> Result<(u32, HostInternal), ()> {
  2513. #[cfg(any(unix, target_os = "redox"))]
  2514. use std::os::unix::prelude::OsStrExt;
  2515. #[cfg(target_os = "wasi")]
  2516. use std::os::wasi::prelude::OsStrExt;
  2517. if !path.is_absolute() {
  2518. return Err(());
  2519. }
  2520. let host_end = to_u32(serialization.len()).unwrap();
  2521. let mut empty = true;
  2522. // skip the root component
  2523. for component in path.components().skip(1) {
  2524. empty = false;
  2525. serialization.push('/');
  2526. serialization.extend(percent_encode(
  2527. component.as_os_str().as_bytes(),
  2528. PATH_SEGMENT,
  2529. ));
  2530. }
  2531. if empty {
  2532. // An URL’s path must not be empty.
  2533. serialization.push('/');
  2534. }
  2535. Ok((host_end, HostInternal::None))
  2536. }
  2537. #[cfg(windows)]
  2538. fn path_to_file_url_segments(
  2539. path: &Path,
  2540. serialization: &mut String,
  2541. ) -> Result<(u32, HostInternal), ()> {
  2542. path_to_file_url_segments_windows(path, serialization)
  2543. }
  2544. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  2545. #[cfg_attr(not(windows), allow(dead_code))]
  2546. fn path_to_file_url_segments_windows(
  2547. path: &Path,
  2548. serialization: &mut String,
  2549. ) -> Result<(u32, HostInternal), ()> {
  2550. use std::path::{Component, Prefix};
  2551. if !path.is_absolute() {
  2552. return Err(());
  2553. }
  2554. let mut components = path.components();
  2555. let host_start = serialization.len() + 1;
  2556. let host_end;
  2557. let host_internal;
  2558. match components.next() {
  2559. Some(Component::Prefix(ref p)) => match p.kind() {
  2560. Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => {
  2561. host_end = to_u32(serialization.len()).unwrap();
  2562. host_internal = HostInternal::None;
  2563. serialization.push('/');
  2564. serialization.push(letter as char);
  2565. serialization.push(':');
  2566. }
  2567. Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => {
  2568. let host = Host::parse(server.to_str().ok_or(())?).map_err(|_| ())?;
  2569. write!(serialization, "{}", host).unwrap();
  2570. host_end = to_u32(serialization.len()).unwrap();
  2571. host_internal = host.into();
  2572. serialization.push('/');
  2573. let share = share.to_str().ok_or(())?;
  2574. serialization.extend(percent_encode(share.as_bytes(), PATH_SEGMENT));
  2575. }
  2576. _ => return Err(()),
  2577. },
  2578. _ => return Err(()),
  2579. }
  2580. let mut path_only_has_prefix = true;
  2581. for component in components {
  2582. if component == Component::RootDir {
  2583. continue;
  2584. }
  2585. path_only_has_prefix = false;
  2586. // FIXME: somehow work with non-unicode?
  2587. let component = component.as_os_str().to_str().ok_or(())?;
  2588. serialization.push('/');
  2589. serialization.extend(percent_encode(component.as_bytes(), PATH_SEGMENT));
  2590. }
  2591. // A windows drive letter must end with a slash.
  2592. if serialization.len() > host_start
  2593. && parser::is_windows_drive_letter(&serialization[host_start..])
  2594. && path_only_has_prefix
  2595. {
  2596. serialization.push('/');
  2597. }
  2598. Ok((host_end, host_internal))
  2599. }
  2600. #[cfg(any(unix, target_os = "redox", target_os = "wasi"))]
  2601. fn file_url_segments_to_pathbuf(
  2602. host: Option<&str>,
  2603. segments: str::Split<'_, char>,
  2604. ) -> Result<PathBuf, ()> {
  2605. use std::ffi::OsStr;
  2606. #[cfg(any(unix, target_os = "redox"))]
  2607. use std::os::unix::prelude::OsStrExt;
  2608. #[cfg(target_os = "wasi")]
  2609. use std::os::wasi::prelude::OsStrExt;
  2610. if host.is_some() {
  2611. return Err(());
  2612. }
  2613. let mut bytes = if cfg!(target_os = "redox") {
  2614. b"file:".to_vec()
  2615. } else {
  2616. Vec::new()
  2617. };
  2618. for segment in segments {
  2619. bytes.push(b'/');
  2620. bytes.extend(percent_decode(segment.as_bytes()));
  2621. }
  2622. // A windows drive letter must end with a slash.
  2623. if bytes.len() > 2
  2624. && matches!(bytes[bytes.len() - 2], b'a'..=b'z' | b'A'..=b'Z')
  2625. && matches!(bytes[bytes.len() - 1], b':' | b'|')
  2626. {
  2627. bytes.push(b'/');
  2628. }
  2629. let os_str = OsStr::from_bytes(&bytes);
  2630. let path = PathBuf::from(os_str);
  2631. debug_assert!(
  2632. path.is_absolute(),
  2633. "to_file_path() failed to produce an absolute Path"
  2634. );
  2635. Ok(path)
  2636. }
  2637. #[cfg(windows)]
  2638. fn file_url_segments_to_pathbuf(
  2639. host: Option<&str>,
  2640. segments: str::Split<char>,
  2641. ) -> Result<PathBuf, ()> {
  2642. file_url_segments_to_pathbuf_windows(host, segments)
  2643. }
  2644. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  2645. #[cfg_attr(not(windows), allow(dead_code))]
  2646. fn file_url_segments_to_pathbuf_windows(
  2647. host: Option<&str>,
  2648. mut segments: str::Split<'_, char>,
  2649. ) -> Result<PathBuf, ()> {
  2650. let mut string = if let Some(host) = host {
  2651. r"\\".to_owned() + host
  2652. } else {
  2653. let first = segments.next().ok_or(())?;
  2654. match first.len() {
  2655. 2 => {
  2656. if !first.starts_with(parser::ascii_alpha) || first.as_bytes()[1] != b':' {
  2657. return Err(());
  2658. }
  2659. first.to_owned()
  2660. }
  2661. 4 => {
  2662. if !first.starts_with(parser::ascii_alpha) {
  2663. return Err(());
  2664. }
  2665. let bytes = first.as_bytes();
  2666. if bytes[1] != b'%' || bytes[2] != b'3' || (bytes[3] != b'a' && bytes[3] != b'A') {
  2667. return Err(());
  2668. }
  2669. first[0..1].to_owned() + ":"
  2670. }
  2671. _ => return Err(()),
  2672. }
  2673. };
  2674. for segment in segments {
  2675. string.push('\\');
  2676. // Currently non-unicode windows paths cannot be represented
  2677. match String::from_utf8(percent_decode(segment.as_bytes()).collect()) {
  2678. Ok(s) => string.push_str(&s),
  2679. Err(..) => return Err(()),
  2680. }
  2681. }
  2682. let path = PathBuf::from(string);
  2683. debug_assert!(
  2684. path.is_absolute(),
  2685. "to_file_path() failed to produce an absolute Path"
  2686. );
  2687. Ok(path)
  2688. }
  2689. /// Implementation detail of `Url::query_pairs_mut`. Typically not used directly.
  2690. #[derive(Debug)]
  2691. pub struct UrlQuery<'a> {
  2692. url: Option<&'a mut Url>,
  2693. fragment: Option<String>,
  2694. }
  2695. // `as_mut_string` string here exposes the internal serialization of an `Url`,
  2696. // which should not be exposed to users.
  2697. // We achieve that by not giving users direct access to `UrlQuery`:
  2698. // * Its fields are private
  2699. // (and so can not be constructed with struct literal syntax outside of this crate),
  2700. // * It has no constructor
  2701. // * It is only visible (on the type level) to users in the return type of
  2702. // `Url::query_pairs_mut` which is `Serializer<UrlQuery>`
  2703. // * `Serializer` keeps its target in a private field
  2704. // * Unlike in other `Target` impls, `UrlQuery::finished` does not return `Self`.
  2705. impl<'a> form_urlencoded::Target for UrlQuery<'a> {
  2706. fn as_mut_string(&mut self) -> &mut String {
  2707. &mut self.url.as_mut().unwrap().serialization
  2708. }
  2709. fn finish(mut self) -> &'a mut Url {
  2710. let url = self.url.take().unwrap();
  2711. url.restore_already_parsed_fragment(self.fragment.take());
  2712. url
  2713. }
  2714. type Finished = &'a mut Url;
  2715. }
  2716. impl<'a> Drop for UrlQuery<'a> {
  2717. fn drop(&mut self) {
  2718. if let Some(url) = self.url.take() {
  2719. url.restore_already_parsed_fragment(self.fragment.take())
  2720. }
  2721. }
  2722. }