quirks.rs 10 KB

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