quirks.rs 8.6 KB

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