quirks.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. // Copyright 2016 The rust-url developers.
  2. //
  3. // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
  4. // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
  5. // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
  6. // option. This file may not be copied, modified, or distributed
  7. // except according to those terms.
  8. //! Getters and setters for URL components implemented per <https://url.spec.whatwg.org/#api>
  9. //!
  10. //! Unless you need to be interoperable with web browsers,
  11. //! you probably want to use `Url` method instead.
  12. use crate::parser::{default_port, Context, Input, Parser, SchemeType};
  13. use crate::{Host, ParseError, Position, Url};
  14. use alloc::string::String;
  15. use alloc::string::ToString;
  16. /// Internal components / offsets of a URL.
  17. ///
  18. /// https://user@pass:example.com:1234/foo/bar?baz#quux
  19. /// | | | | ^^^^| | |
  20. /// | | | | | | | `----- fragment_start
  21. /// | | | | | | `--------- query_start
  22. /// | | | | | `----------------- path_start
  23. /// | | | | `--------------------- port
  24. /// | | | `----------------------- host_end
  25. /// | | `---------------------------------- host_start
  26. /// | `--------------------------------------- username_end
  27. /// `---------------------------------------------- scheme_end
  28. #[derive(Copy, Clone)]
  29. #[cfg(feature = "expose_internals")]
  30. pub struct InternalComponents {
  31. pub scheme_end: u32,
  32. pub username_end: u32,
  33. pub host_start: u32,
  34. pub host_end: u32,
  35. pub port: Option<u16>,
  36. pub path_start: u32,
  37. pub query_start: Option<u32>,
  38. pub fragment_start: Option<u32>,
  39. }
  40. /// Internal component / parsed offsets of the URL.
  41. ///
  42. /// This can be useful for implementing efficient serialization
  43. /// for the URL.
  44. #[cfg(feature = "expose_internals")]
  45. pub fn internal_components(url: &Url) -> InternalComponents {
  46. InternalComponents {
  47. scheme_end: url.scheme_end,
  48. username_end: url.username_end,
  49. host_start: url.host_start,
  50. host_end: url.host_end,
  51. port: url.port,
  52. path_start: url.path_start,
  53. query_start: url.query_start,
  54. fragment_start: url.fragment_start,
  55. }
  56. }
  57. /// <https://url.spec.whatwg.org/#dom-url-domaintoascii>
  58. pub fn domain_to_ascii(domain: &str) -> String {
  59. match Host::parse(domain) {
  60. Ok(Host::Domain(domain)) => domain,
  61. _ => String::new(),
  62. }
  63. }
  64. /// <https://url.spec.whatwg.org/#dom-url-domaintounicode>
  65. pub fn domain_to_unicode(domain: &str) -> String {
  66. match Host::parse(domain) {
  67. Ok(Host::Domain(ref domain)) => {
  68. let (unicode, _errors) = idna::domain_to_unicode(domain);
  69. unicode
  70. }
  71. _ => String::new(),
  72. }
  73. }
  74. /// Getter for <https://url.spec.whatwg.org/#dom-url-href>
  75. pub fn href(url: &Url) -> &str {
  76. url.as_str()
  77. }
  78. /// Setter for <https://url.spec.whatwg.org/#dom-url-href>
  79. pub fn set_href(url: &mut Url, value: &str) -> Result<(), ParseError> {
  80. *url = Url::parse(value)?;
  81. Ok(())
  82. }
  83. /// Getter for <https://url.spec.whatwg.org/#dom-url-origin>
  84. pub fn origin(url: &Url) -> String {
  85. url.origin().ascii_serialization()
  86. }
  87. /// Getter for <https://url.spec.whatwg.org/#dom-url-protocol>
  88. #[inline]
  89. pub fn protocol(url: &Url) -> &str {
  90. &url.as_str()[..url.scheme().len() + ":".len()]
  91. }
  92. /// Setter for <https://url.spec.whatwg.org/#dom-url-protocol>
  93. #[allow(clippy::result_unit_err)]
  94. pub fn set_protocol(url: &mut Url, mut new_protocol: &str) -> Result<(), ()> {
  95. // The scheme state in the spec ignores everything after the first `:`,
  96. // but `set_scheme` errors if there is more.
  97. if let Some(position) = new_protocol.find(':') {
  98. new_protocol = &new_protocol[..position];
  99. }
  100. url.set_scheme(new_protocol)
  101. }
  102. /// Getter for <https://url.spec.whatwg.org/#dom-url-username>
  103. #[inline]
  104. pub fn username(url: &Url) -> &str {
  105. url.username()
  106. }
  107. /// Setter for <https://url.spec.whatwg.org/#dom-url-username>
  108. #[allow(clippy::result_unit_err)]
  109. pub fn set_username(url: &mut Url, new_username: &str) -> Result<(), ()> {
  110. url.set_username(new_username)
  111. }
  112. /// Getter for <https://url.spec.whatwg.org/#dom-url-password>
  113. #[inline]
  114. pub fn password(url: &Url) -> &str {
  115. url.password().unwrap_or("")
  116. }
  117. /// Setter for <https://url.spec.whatwg.org/#dom-url-password>
  118. #[allow(clippy::result_unit_err)]
  119. pub fn set_password(url: &mut Url, new_password: &str) -> Result<(), ()> {
  120. url.set_password(if new_password.is_empty() {
  121. None
  122. } else {
  123. Some(new_password)
  124. })
  125. }
  126. /// Getter for <https://url.spec.whatwg.org/#dom-url-host>
  127. #[inline]
  128. pub fn host(url: &Url) -> &str {
  129. &url[Position::BeforeHost..Position::AfterPort]
  130. }
  131. /// Setter for <https://url.spec.whatwg.org/#dom-url-host>
  132. #[allow(clippy::result_unit_err)]
  133. pub fn set_host(url: &mut Url, new_host: &str) -> Result<(), ()> {
  134. // If context object’s url’s cannot-be-a-base-URL flag is set, then return.
  135. if url.cannot_be_a_base() {
  136. return Err(());
  137. }
  138. // Host parsing rules are strict,
  139. // We don't want to trim the input
  140. let input = Input::new_no_trim(new_host);
  141. let host;
  142. let opt_port;
  143. {
  144. let scheme = url.scheme();
  145. let scheme_type = SchemeType::from(scheme);
  146. if scheme_type == SchemeType::File && new_host.is_empty() {
  147. url.set_host_internal(Host::Domain("".into()), None);
  148. return Ok(());
  149. }
  150. if let Ok((h, remaining)) = Parser::parse_host(input, scheme_type) {
  151. host = h;
  152. opt_port = if let Some(remaining) = remaining.split_prefix(':') {
  153. if remaining.is_empty() {
  154. None
  155. } else {
  156. Parser::parse_port(remaining, || default_port(scheme), Context::Setter)
  157. .ok()
  158. .map(|(port, _remaining)| port)
  159. }
  160. } else {
  161. None
  162. };
  163. } else {
  164. return Err(());
  165. }
  166. }
  167. // Make sure we won't set an empty host to a url with a username or a port
  168. if host == Host::Domain("".to_string())
  169. && (!username(url).is_empty() || matches!(opt_port, Some(Some(_))) || url.port().is_some())
  170. {
  171. return Err(());
  172. }
  173. url.set_host_internal(host, opt_port);
  174. Ok(())
  175. }
  176. /// Getter for <https://url.spec.whatwg.org/#dom-url-hostname>
  177. #[inline]
  178. pub fn hostname(url: &Url) -> &str {
  179. url.host_str().unwrap_or("")
  180. }
  181. /// Setter for <https://url.spec.whatwg.org/#dom-url-hostname>
  182. #[allow(clippy::result_unit_err)]
  183. pub fn set_hostname(url: &mut Url, new_hostname: &str) -> Result<(), ()> {
  184. if url.cannot_be_a_base() {
  185. return Err(());
  186. }
  187. // Host parsing rules are strict we don't want to trim the input
  188. let input = Input::new_no_trim(new_hostname);
  189. let scheme_type = SchemeType::from(url.scheme());
  190. if scheme_type == SchemeType::File && new_hostname.is_empty() {
  191. url.set_host_internal(Host::Domain("".into()), None);
  192. return Ok(());
  193. }
  194. if let Ok((host, remaining)) = Parser::parse_host(input, scheme_type) {
  195. if remaining.starts_with(':') {
  196. return Err(());
  197. };
  198. if let Host::Domain(h) = &host {
  199. if h.is_empty() {
  200. // Empty host on special not file url
  201. if SchemeType::from(url.scheme()) == SchemeType::SpecialNotFile
  202. // Port with an empty host
  203. ||!port(url).is_empty()
  204. // Empty host that includes credentials
  205. || !url.username().is_empty()
  206. || !url.password().unwrap_or("").is_empty()
  207. {
  208. return Err(());
  209. }
  210. }
  211. }
  212. url.set_host_internal(host, None);
  213. Ok(())
  214. } else {
  215. Err(())
  216. }
  217. }
  218. /// Getter for <https://url.spec.whatwg.org/#dom-url-port>
  219. #[inline]
  220. pub fn port(url: &Url) -> &str {
  221. &url[Position::BeforePort..Position::AfterPort]
  222. }
  223. /// Setter for <https://url.spec.whatwg.org/#dom-url-port>
  224. #[allow(clippy::result_unit_err)]
  225. pub fn set_port(url: &mut Url, new_port: &str) -> Result<(), ()> {
  226. let result;
  227. {
  228. // has_host implies !cannot_be_a_base
  229. let scheme = url.scheme();
  230. if !url.has_host() || url.host() == Some(Host::Domain("")) || scheme == "file" {
  231. return Err(());
  232. }
  233. result = Parser::parse_port(
  234. Input::new_no_trim(new_port),
  235. || default_port(scheme),
  236. Context::Setter,
  237. )
  238. }
  239. if let Ok((new_port, _remaining)) = result {
  240. url.set_port_internal(new_port);
  241. Ok(())
  242. } else {
  243. Err(())
  244. }
  245. }
  246. /// Getter for <https://url.spec.whatwg.org/#dom-url-pathname>
  247. #[inline]
  248. pub fn pathname(url: &Url) -> &str {
  249. url.path()
  250. }
  251. /// Setter for <https://url.spec.whatwg.org/#dom-url-pathname>
  252. pub fn set_pathname(url: &mut Url, new_pathname: &str) {
  253. if url.cannot_be_a_base() {
  254. return;
  255. }
  256. if new_pathname.starts_with('/')
  257. || (SchemeType::from(url.scheme()).is_special()
  258. // \ is a segment delimiter for 'special' URLs"
  259. && new_pathname.starts_with('\\'))
  260. {
  261. url.set_path(new_pathname)
  262. } else if SchemeType::from(url.scheme()).is_special()
  263. || !new_pathname.is_empty()
  264. || !url.has_host()
  265. {
  266. let mut path_to_set = String::from("/");
  267. path_to_set.push_str(new_pathname);
  268. url.set_path(&path_to_set)
  269. } else {
  270. url.set_path(new_pathname)
  271. }
  272. }
  273. /// Getter for <https://url.spec.whatwg.org/#dom-url-search>
  274. pub fn search(url: &Url) -> &str {
  275. trim(&url[Position::AfterPath..Position::AfterQuery])
  276. }
  277. /// Setter for <https://url.spec.whatwg.org/#dom-url-search>
  278. pub fn set_search(url: &mut Url, new_search: &str) {
  279. url.set_query(match new_search {
  280. "" => None,
  281. _ if new_search.starts_with('?') => Some(&new_search[1..]),
  282. _ => Some(new_search),
  283. })
  284. }
  285. /// Getter for <https://url.spec.whatwg.org/#dom-url-hash>
  286. pub fn hash(url: &Url) -> &str {
  287. trim(&url[Position::AfterQuery..])
  288. }
  289. /// Setter for <https://url.spec.whatwg.org/#dom-url-hash>
  290. pub fn set_hash(url: &mut Url, new_hash: &str) {
  291. url.set_fragment(match new_hash {
  292. // If the given value is the empty string,
  293. // then set context object’s url’s fragment to null and return.
  294. "" => None,
  295. // Let input be the given value with a single leading U+0023 (#) removed, if any.
  296. _ if new_hash.starts_with('#') => Some(&new_hash[1..]),
  297. _ => Some(new_hash),
  298. })
  299. }
  300. fn trim(s: &str) -> &str {
  301. if s.len() == 1 {
  302. ""
  303. } else {
  304. s
  305. }
  306. }