DOMURL.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. * Copyright (c) 2021, the SerenityOS developers.
  4. * Copyright (c) 2023, networkException <networkexception@serenityos.org>
  5. * Copyright (c) 2024, Shannon Booth <shannon@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/IPv4Address.h>
  10. #include <AK/IPv6Address.h>
  11. #include <LibURL/Parser.h>
  12. #include <LibWeb/Bindings/DOMURLPrototype.h>
  13. #include <LibWeb/Bindings/Intrinsics.h>
  14. #include <LibWeb/DOMURL/DOMURL.h>
  15. #include <LibWeb/FileAPI/Blob.h>
  16. #include <LibWeb/FileAPI/BlobURLStore.h>
  17. namespace Web::DOMURL {
  18. JS_DEFINE_ALLOCATOR(DOMURL);
  19. JS::NonnullGCPtr<DOMURL> DOMURL::create(JS::Realm& realm, URL::URL url, JS::NonnullGCPtr<URLSearchParams> query)
  20. {
  21. return realm.heap().allocate<DOMURL>(realm, realm, move(url), move(query));
  22. }
  23. // https://url.spec.whatwg.org/#api-url-parser
  24. static Optional<URL::URL> parse_api_url(String const& url, Optional<String> const& base)
  25. {
  26. // FIXME: We somewhat awkwardly have two failure states encapsulated in the return type (and convert between them in the steps),
  27. // ideally we'd get rid of URL's valid flag
  28. // 1. Let parsedBase be null.
  29. Optional<URL::URL> parsed_base;
  30. // 2. If base is non-null:
  31. if (base.has_value()) {
  32. // 1. Set parsedBase to the result of running the basic URL parser on base.
  33. auto parsed_base_url = URL::Parser::basic_parse(*base);
  34. // 2. If parsedBase is failure, then return failure.
  35. if (!parsed_base_url.is_valid())
  36. return {};
  37. parsed_base = parsed_base_url;
  38. }
  39. // 3. Return the result of running the basic URL parser on url with parsedBase.
  40. auto parsed = URL::Parser::basic_parse(url, parsed_base);
  41. return parsed.is_valid() ? parsed : Optional<URL::URL> {};
  42. }
  43. // https://url.spec.whatwg.org/#url-initialize
  44. JS::NonnullGCPtr<DOMURL> DOMURL::initialize_a_url(JS::Realm& realm, URL::URL const& url_record)
  45. {
  46. // 1. Let query be urlRecord’s query, if that is non-null; otherwise the empty string.
  47. auto query = url_record.query().value_or(String {});
  48. // 2. Set url’s URL to urlRecord.
  49. // 3. Set url’s query object to a new URLSearchParams object.
  50. auto query_object = URLSearchParams::create(realm, query);
  51. // 4. Initialize url’s query object with query.
  52. auto result_url = DOMURL::create(realm, url_record, move(query_object));
  53. // 5. Set url’s query object’s URL object to url.
  54. result_url->m_query->m_url = result_url;
  55. return result_url;
  56. }
  57. // https://url.spec.whatwg.org/#dom-url-parse
  58. JS::GCPtr<DOMURL> DOMURL::parse_for_bindings(JS::VM& vm, String const& url, Optional<String> const& base)
  59. {
  60. auto& realm = *vm.current_realm();
  61. // 1. Let parsedURL be the result of running the API URL parser on url with base, if given.
  62. auto parsed_url = parse_api_url(url, base);
  63. // 2. If parsedURL is failure, then return null.
  64. if (!parsed_url.has_value())
  65. return nullptr;
  66. // 3. Let url be a new URL object.
  67. // 4. Initialize url with parsedURL.
  68. // 5. Return url.
  69. return initialize_a_url(realm, parsed_url.value());
  70. }
  71. // https://url.spec.whatwg.org/#dom-url-url
  72. WebIDL::ExceptionOr<JS::NonnullGCPtr<DOMURL>> DOMURL::construct_impl(JS::Realm& realm, String const& url, Optional<String> const& base)
  73. {
  74. // 1. Let parsedURL be the result of running the API URL parser on url with base, if given.
  75. auto parsed_url = parse_api_url(url, base);
  76. // 2. If parsedURL is failure, then throw a TypeError.
  77. if (!parsed_url.has_value())
  78. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid URL"sv };
  79. // 3. Initialize this with parsedURL.
  80. return initialize_a_url(realm, parsed_url.value());
  81. }
  82. DOMURL::DOMURL(JS::Realm& realm, URL::URL url, JS::NonnullGCPtr<URLSearchParams> query)
  83. : PlatformObject(realm)
  84. , m_url(move(url))
  85. , m_query(move(query))
  86. {
  87. }
  88. DOMURL::~DOMURL() = default;
  89. void DOMURL::initialize(JS::Realm& realm)
  90. {
  91. Base::initialize(realm);
  92. WEB_SET_PROTOTYPE_FOR_INTERFACE_WITH_CUSTOM_NAME(DOMURL, URL);
  93. }
  94. void DOMURL::visit_edges(Cell::Visitor& visitor)
  95. {
  96. Base::visit_edges(visitor);
  97. visitor.visit(m_query);
  98. }
  99. // https://w3c.github.io/FileAPI/#dfn-createObjectURL
  100. WebIDL::ExceptionOr<String> DOMURL::create_object_url(JS::VM& vm, JS::NonnullGCPtr<FileAPI::Blob> object)
  101. {
  102. // The createObjectURL(obj) static method must return the result of adding an entry to the blob URL store for obj.
  103. return TRY_OR_THROW_OOM(vm, FileAPI::add_entry_to_blob_url_store(object));
  104. }
  105. // https://w3c.github.io/FileAPI/#dfn-revokeObjectURL
  106. WebIDL::ExceptionOr<void> DOMURL::revoke_object_url(JS::VM& vm, StringView url)
  107. {
  108. // 1. Let url record be the result of parsing url.
  109. auto url_record = parse(url);
  110. // 2. If url record’s scheme is not "blob", return.
  111. if (url_record.scheme() != "blob"sv)
  112. return {};
  113. // 3. Let origin be the origin of url record.
  114. auto origin = url_record.origin();
  115. // 4. Let settings be the current settings object.
  116. auto& settings = HTML::current_settings_object();
  117. // 5. If origin is not same origin with settings’s origin, return.
  118. if (!origin.is_same_origin(settings.origin()))
  119. return {};
  120. // 6. Remove an entry from the Blob URL Store for url.
  121. TRY_OR_THROW_OOM(vm, FileAPI::remove_entry_from_blob_url_store(url));
  122. return {};
  123. }
  124. // https://url.spec.whatwg.org/#dom-url-canparse
  125. bool DOMURL::can_parse(JS::VM&, String const& url, Optional<String> const& base)
  126. {
  127. // 1. Let parsedURL be the result of running the API URL parser on url with base, if given.
  128. auto parsed_url = parse_api_url(url, base);
  129. // 2. If parsedURL is failure, then return false.
  130. if (!parsed_url.has_value())
  131. return false;
  132. // 3. Return true.
  133. return true;
  134. }
  135. // https://url.spec.whatwg.org/#dom-url-href
  136. WebIDL::ExceptionOr<String> DOMURL::href() const
  137. {
  138. auto& vm = realm().vm();
  139. // The href getter steps and the toJSON() method steps are to return the serialization of this’s URL.
  140. return TRY_OR_THROW_OOM(vm, String::from_byte_string(m_url.serialize()));
  141. }
  142. // https://url.spec.whatwg.org/#dom-url-tojson
  143. WebIDL::ExceptionOr<String> DOMURL::to_json() const
  144. {
  145. auto& vm = realm().vm();
  146. // The href getter steps and the toJSON() method steps are to return the serialization of this’s URL.
  147. return TRY_OR_THROW_OOM(vm, String::from_byte_string(m_url.serialize()));
  148. }
  149. // https://url.spec.whatwg.org/#ref-for-dom-url-href②
  150. WebIDL::ExceptionOr<void> DOMURL::set_href(String const& href)
  151. {
  152. // 1. Let parsedURL be the result of running the basic URL parser on the given value.
  153. URL::URL parsed_url = href;
  154. // 2. If parsedURL is failure, then throw a TypeError.
  155. if (!parsed_url.is_valid())
  156. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid URL"sv };
  157. // 3. Set this’s URL to parsedURL.
  158. m_url = move(parsed_url);
  159. // 4. Empty this’s query object’s list.
  160. m_query->m_list.clear();
  161. // 5. Let query be this’s URL’s query.
  162. auto query = m_url.query();
  163. // 6. If query is non-null, then set this’s query object’s list to the result of parsing query.
  164. if (query.has_value())
  165. m_query->m_list = url_decode(*query);
  166. return {};
  167. }
  168. // https://url.spec.whatwg.org/#dom-url-origin
  169. WebIDL::ExceptionOr<String> DOMURL::origin() const
  170. {
  171. auto& vm = realm().vm();
  172. // The origin getter steps are to return the serialization of this’s URL’s origin. [HTML]
  173. return TRY_OR_THROW_OOM(vm, String::from_byte_string(m_url.origin().serialize()));
  174. }
  175. // https://url.spec.whatwg.org/#dom-url-protocol
  176. WebIDL::ExceptionOr<String> DOMURL::protocol() const
  177. {
  178. auto& vm = realm().vm();
  179. // The protocol getter steps are to return this’s URL’s scheme, followed by U+003A (:).
  180. return TRY_OR_THROW_OOM(vm, String::formatted("{}:", m_url.scheme()));
  181. }
  182. // https://url.spec.whatwg.org/#ref-for-dom-url-protocol%E2%91%A0
  183. WebIDL::ExceptionOr<void> DOMURL::set_protocol(String const& protocol)
  184. {
  185. auto& vm = realm().vm();
  186. // The protocol setter steps are to basic URL parse the given value, followed by U+003A (:), with this’s URL as
  187. // url and scheme start state as state override.
  188. (void)URL::Parser::basic_parse(TRY_OR_THROW_OOM(vm, String::formatted("{}:", protocol)), {}, &m_url, URL::Parser::State::SchemeStart);
  189. return {};
  190. }
  191. // https://url.spec.whatwg.org/#dom-url-username
  192. String const& DOMURL::username() const
  193. {
  194. // The username getter steps are to return this’s URL’s username.
  195. return m_url.username();
  196. }
  197. // https://url.spec.whatwg.org/#ref-for-dom-url-username%E2%91%A0
  198. void DOMURL::set_username(String const& username)
  199. {
  200. // 1. If this’s URL cannot have a username/password/port, then return.
  201. if (m_url.cannot_have_a_username_or_password_or_port())
  202. return;
  203. // 2. Set the username given this’s URL and the given value.
  204. m_url.set_username(username);
  205. }
  206. // https://url.spec.whatwg.org/#dom-url-password
  207. String const& DOMURL::password() const
  208. {
  209. // The password getter steps are to return this’s URL’s password.
  210. return m_url.password();
  211. }
  212. // https://url.spec.whatwg.org/#ref-for-dom-url-password%E2%91%A0
  213. void DOMURL::set_password(String const& password)
  214. {
  215. // 1. If this’s URL cannot have a username/password/port, then return.
  216. if (m_url.cannot_have_a_username_or_password_or_port())
  217. return;
  218. // 2. Set the password given this’s URL and the given value.
  219. m_url.set_password(password);
  220. }
  221. // https://url.spec.whatwg.org/#dom-url-host
  222. WebIDL::ExceptionOr<String> DOMURL::host() const
  223. {
  224. auto& vm = realm().vm();
  225. // 1. Let url be this’s URL.
  226. auto& url = m_url;
  227. // 2. If url’s host is null, then return the empty string.
  228. if (url.host().has<Empty>())
  229. return String {};
  230. // 3. If url’s port is null, return url’s host, serialized.
  231. if (!url.port().has_value())
  232. return TRY_OR_THROW_OOM(vm, url.serialized_host());
  233. // 4. Return url’s host, serialized, followed by U+003A (:) and url’s port, serialized.
  234. return TRY_OR_THROW_OOM(vm, String::formatted("{}:{}", TRY_OR_THROW_OOM(vm, url.serialized_host()), *url.port()));
  235. }
  236. // https://url.spec.whatwg.org/#dom-url-hostref-for-dom-url-host%E2%91%A0
  237. void DOMURL::set_host(String const& host)
  238. {
  239. // 1. If this’s URL’s cannot-be-a-base-URL is true, then return.
  240. if (m_url.cannot_be_a_base_url())
  241. return;
  242. // 2. Basic URL parse the given value with this’s URL as url and host state as state override.
  243. (void)URL::Parser::basic_parse(host, {}, &m_url, URL::Parser::State::Host);
  244. }
  245. // https://url.spec.whatwg.org/#dom-url-hostname
  246. WebIDL::ExceptionOr<String> DOMURL::hostname() const
  247. {
  248. auto& vm = realm().vm();
  249. // 1. If this’s URL’s host is null, then return the empty string.
  250. if (m_url.host().has<Empty>())
  251. return String {};
  252. // 2. Return this’s URL’s host, serialized.
  253. return TRY_OR_THROW_OOM(vm, m_url.serialized_host());
  254. }
  255. // https://url.spec.whatwg.org/#ref-for-dom-url-hostname①
  256. void DOMURL::set_hostname(String const& hostname)
  257. {
  258. // 1. If this’s URL’s cannot-be-a-base-URL is true, then return.
  259. if (m_url.cannot_be_a_base_url())
  260. return;
  261. // 2. Basic URL parse the given value with this’s URL as url and hostname state as state override.
  262. (void)URL::Parser::basic_parse(hostname, {}, &m_url, URL::Parser::State::Hostname);
  263. }
  264. // https://url.spec.whatwg.org/#dom-url-port
  265. WebIDL::ExceptionOr<String> DOMURL::port() const
  266. {
  267. auto& vm = realm().vm();
  268. // 1. If this’s URL’s port is null, then return the empty string.
  269. if (!m_url.port().has_value())
  270. return String {};
  271. // 2. Return this’s URL’s port, serialized.
  272. return TRY_OR_THROW_OOM(vm, String::formatted("{}", *m_url.port()));
  273. }
  274. // https://url.spec.whatwg.org/#ref-for-dom-url-port%E2%91%A0
  275. void DOMURL::set_port(String const& port)
  276. {
  277. // 1. If this’s URL cannot have a username/password/port, then return.
  278. if (m_url.cannot_have_a_username_or_password_or_port())
  279. return;
  280. // 2. If the given value is the empty string, then set this’s URL’s port to null.
  281. if (port.is_empty()) {
  282. m_url.set_port({});
  283. }
  284. // 3. Otherwise, basic URL parse the given value with this’s URL as url and port state as state override.
  285. else {
  286. (void)URL::Parser::basic_parse(port, {}, &m_url, URL::Parser::State::Port);
  287. }
  288. }
  289. // https://url.spec.whatwg.org/#dom-url-pathname
  290. String DOMURL::pathname() const
  291. {
  292. // The pathname getter steps are to return the result of URL path serializing this’s URL.
  293. return m_url.serialize_path();
  294. }
  295. // https://url.spec.whatwg.org/#ref-for-dom-url-pathname%E2%91%A0
  296. void DOMURL::set_pathname(String const& pathname)
  297. {
  298. // FIXME: These steps no longer match the speci.
  299. // 1. If this’s URL’s cannot-be-a-base-URL is true, then return.
  300. if (m_url.cannot_be_a_base_url())
  301. return;
  302. // 2. Empty this’s URL’s path.
  303. m_url.set_paths({});
  304. // 3. Basic URL parse the given value with this’s URL as url and path start state as state override.
  305. (void)URL::Parser::basic_parse(pathname, {}, &m_url, URL::Parser::State::PathStart);
  306. }
  307. // https://url.spec.whatwg.org/#dom-url-search
  308. WebIDL::ExceptionOr<String> DOMURL::search() const
  309. {
  310. auto& vm = realm().vm();
  311. // 1. If this’s URL’s query is either null or the empty string, then return the empty string.
  312. if (!m_url.query().has_value() || m_url.query()->is_empty())
  313. return String {};
  314. // 2. Return U+003F (?), followed by this’s URL’s query.
  315. return TRY_OR_THROW_OOM(vm, String::formatted("?{}", *m_url.query()));
  316. }
  317. // https://url.spec.whatwg.org/#ref-for-dom-url-search%E2%91%A0
  318. void DOMURL::set_search(String const& search)
  319. {
  320. // 1. Let url be this’s URL.
  321. auto& url = m_url;
  322. // 2. If the given value is the empty string:
  323. if (search.is_empty()) {
  324. // 1. Set url’s query to null.
  325. url.set_query({});
  326. // 2. Empty this’s query object’s list.
  327. m_query->m_list.clear();
  328. // 3. Potentially strip trailing spaces from an opaque path with this.
  329. strip_trailing_spaces_from_an_opaque_path(*this);
  330. // 4. Return.
  331. return;
  332. }
  333. // 3. Let input be the given value with a single leading U+003F (?) removed, if any.
  334. auto search_as_string_view = search.bytes_as_string_view();
  335. auto input = search_as_string_view.substring_view(search_as_string_view.starts_with('?'));
  336. // 4. Set url’s query to the empty string.
  337. url.set_query(String {});
  338. // 5. Basic URL parse input with url as url and query state as state override.
  339. (void)URL::Parser::basic_parse(input, {}, &url, URL::Parser::State::Query);
  340. // 6. Set this’s query object’s list to the result of parsing input.
  341. m_query->m_list = url_decode(input);
  342. }
  343. // https://url.spec.whatwg.org/#dom-url-searchparams
  344. JS::NonnullGCPtr<URLSearchParams const> DOMURL::search_params() const
  345. {
  346. // The searchParams getter steps are to return this’s query object.
  347. return m_query;
  348. }
  349. // https://url.spec.whatwg.org/#dom-url-hash
  350. WebIDL::ExceptionOr<String> DOMURL::hash() const
  351. {
  352. auto& vm = realm().vm();
  353. // 1. If this’s URL’s fragment is either null or the empty string, then return the empty string.
  354. if (!m_url.fragment().has_value() || m_url.fragment()->is_empty())
  355. return String {};
  356. // 2. Return U+0023 (#), followed by this’s URL’s fragment.
  357. return TRY_OR_THROW_OOM(vm, String::formatted("#{}", m_url.fragment()));
  358. }
  359. // https://url.spec.whatwg.org/#ref-for-dom-url-hash%E2%91%A0
  360. void DOMURL::set_hash(String const& hash)
  361. {
  362. // 1. If the given value is the empty string:
  363. if (hash.is_empty()) {
  364. // 1. Set this’s URL’s fragment to null.
  365. m_url.set_fragment({});
  366. // 2. Potentially strip trailing spaces from an opaque path with this.
  367. strip_trailing_spaces_from_an_opaque_path(*this);
  368. // 3. Return.
  369. return;
  370. }
  371. // 2. Let input be the given value with a single leading U+0023 (#) removed, if any.
  372. auto hash_as_string_view = hash.bytes_as_string_view();
  373. auto input = hash_as_string_view.substring_view(hash_as_string_view.starts_with('#'));
  374. // 3. Set this’s URL’s fragment to the empty string.
  375. m_url.set_fragment(String {});
  376. // 4. Basic URL parse input with this’s URL as url and fragment state as state override.
  377. (void)URL::Parser::basic_parse(input, {}, &m_url, URL::Parser::State::Fragment);
  378. }
  379. // https://url.spec.whatwg.org/#concept-domain
  380. bool host_is_domain(URL::Host const& host)
  381. {
  382. // A domain is a non-empty ASCII string that identifies a realm within a network.
  383. return host.has<String>() && host.get<String>() != String {};
  384. }
  385. // https://url.spec.whatwg.org/#potentially-strip-trailing-spaces-from-an-opaque-path
  386. void strip_trailing_spaces_from_an_opaque_path(DOMURL& url)
  387. {
  388. // 1. If url’s URL does not have an opaque path, then return.
  389. // FIXME: Reimplement this step once we modernize the URL implementation to meet the spec.
  390. if (!url.cannot_be_a_base_url())
  391. return;
  392. // 2. If url’s URL’s fragment is non-null, then return.
  393. if (url.fragment().has_value())
  394. return;
  395. // 3. If url’s URL’s query is non-null, then return.
  396. if (url.query().has_value())
  397. return;
  398. // 4. Remove all trailing U+0020 SPACE code points from url’s URL’s path.
  399. // NOTE: At index 0 since the first step tells us that the URL only has one path segment.
  400. auto opaque_path = url.path_segment_at_index(0);
  401. auto trimmed_path = opaque_path.trim(" "sv, TrimMode::Right);
  402. url.set_paths({ trimmed_path });
  403. }
  404. // https://url.spec.whatwg.org/#concept-url-parser
  405. URL::URL parse(StringView input, Optional<URL::URL> const& base_url, Optional<StringView> encoding)
  406. {
  407. // FIXME: We should probably have an extended version of URL::URL for LibWeb instead of standalone functions like this.
  408. // 1. Let url be the result of running the basic URL parser on input with base and encoding.
  409. auto url = URL::Parser::basic_parse(input, base_url, {}, {}, encoding);
  410. // 2. If url is failure, return failure.
  411. if (!url.is_valid())
  412. return {};
  413. // 3. If url’s scheme is not "blob", return url.
  414. if (url.scheme() != "blob")
  415. return url;
  416. // 4. Set url’s blob URL entry to the result of resolving the blob URL url, if that did not return failure, and null otherwise.
  417. auto blob_url_entry = FileAPI::resolve_a_blob_url(url);
  418. if (blob_url_entry.has_value()) {
  419. url.set_blob_url_entry(URL::BlobURLEntry {
  420. .type = blob_url_entry->object->type(),
  421. .byte_buffer = MUST(ByteBuffer::copy(blob_url_entry->object->raw_bytes())),
  422. .environment_origin = blob_url_entry->environment->origin(),
  423. });
  424. }
  425. // 5. Return url
  426. return url;
  427. }
  428. }