URLSearchParams.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. * Copyright (c) 2023, Shannon Booth <shannon@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/QuickSort.h>
  8. #include <AK/StringBuilder.h>
  9. #include <AK/Utf8View.h>
  10. #include <LibTextCodec/Decoder.h>
  11. #include <LibURL/Parser.h>
  12. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  13. #include <LibWeb/Bindings/Intrinsics.h>
  14. #include <LibWeb/Bindings/URLSearchParamsPrototype.h>
  15. #include <LibWeb/DOMURL/DOMURL.h>
  16. #include <LibWeb/DOMURL/URLSearchParams.h>
  17. namespace Web::DOMURL {
  18. JS_DEFINE_ALLOCATOR(URLSearchParams);
  19. URLSearchParams::URLSearchParams(JS::Realm& realm, Vector<QueryParam> list)
  20. : PlatformObject(realm)
  21. , m_list(move(list))
  22. {
  23. }
  24. URLSearchParams::~URLSearchParams() = default;
  25. void URLSearchParams::initialize(JS::Realm& realm)
  26. {
  27. Base::initialize(realm);
  28. WEB_SET_PROTOTYPE_FOR_INTERFACE(URLSearchParams);
  29. }
  30. void URLSearchParams::visit_edges(Cell::Visitor& visitor)
  31. {
  32. Base::visit_edges(visitor);
  33. visitor.visit(m_url);
  34. }
  35. // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  36. // The application/x-www-form-urlencoded serializer takes a list of name-value tuples tuples, with an optional encoding encoding (default UTF-8), and then runs these steps. They return an ASCII string.
  37. ErrorOr<String> url_encode(Vector<QueryParam> const& tuples, StringView encoding)
  38. {
  39. // 1. Set encoding to the result of getting an output encoding from encoding.
  40. encoding = TextCodec::get_output_encoding(encoding);
  41. // 2. Let output be the empty string.
  42. StringBuilder output;
  43. // 3. For each tuple of tuples:
  44. for (auto const& tuple : tuples) {
  45. // 1. Assert: tuple’s name and tuple’s value are scalar value strings.
  46. // 2. Let name be the result of running percent-encode after encoding with encoding, tuple’s name, the application/x-www-form-urlencoded percent-encode set, and true.
  47. // FIXME: URL::Parser does not currently implement encoding.
  48. auto name = TRY(URL::Parser::percent_encode_after_encoding(tuple.name, URL::PercentEncodeSet::ApplicationXWWWFormUrlencoded, true));
  49. // 3. Let value be the result of running percent-encode after encoding with encoding, tuple’s value, the application/x-www-form-urlencoded percent-encode set, and true.
  50. // FIXME: URL::Parser does not currently implement encoding.
  51. auto value = TRY(URL::Parser::percent_encode_after_encoding(tuple.value, URL::PercentEncodeSet::ApplicationXWWWFormUrlencoded, true));
  52. // 4. If output is not the empty string, then append U+0026 (&) to output.
  53. if (!output.is_empty())
  54. TRY(output.try_append('&'));
  55. // 5. Append name, followed by U+003D (=), followed by value, to output.
  56. TRY(output.try_append(name));
  57. TRY(output.try_append('='));
  58. TRY(output.try_append(value));
  59. }
  60. // 4. Return output.
  61. return output.to_string();
  62. }
  63. // https://url.spec.whatwg.org/#concept-urlencoded-parser
  64. // The application/x-www-form-urlencoded parser takes a byte sequence input, and then runs these steps:
  65. ErrorOr<Vector<QueryParam>> url_decode(StringView input)
  66. {
  67. // 1. Let sequences be the result of splitting input on 0x26 (&).
  68. auto sequences = input.split_view('&');
  69. // 2. Let output be an initially empty list of name-value tuples where both name and value hold a string.
  70. Vector<QueryParam> output;
  71. // 3. For each byte sequence bytes in sequences:
  72. for (auto bytes : sequences) {
  73. // 1. If bytes is the empty byte sequence, then continue.
  74. if (bytes.is_empty())
  75. continue;
  76. StringView name;
  77. StringView value;
  78. // 2. If bytes contains a 0x3D (=), then let name be the bytes from the start of bytes up to but excluding its first 0x3D (=), and let value be the bytes, if any, after the first 0x3D (=) up to the end of bytes. If 0x3D (=) is the first byte, then name will be the empty byte sequence. If it is the last, then value will be the empty byte sequence.
  79. if (auto index = bytes.find('='); index.has_value()) {
  80. name = bytes.substring_view(0, *index);
  81. value = bytes.substring_view(*index + 1);
  82. }
  83. // 3. Otherwise, let name have the value of bytes and let value be the empty byte sequence.
  84. else {
  85. name = bytes;
  86. value = ""sv;
  87. }
  88. // 4. Replace any 0x2B (+) in name and value with 0x20 (SP).
  89. auto space_decoded_name = name.replace("+"sv, " "sv, ReplaceMode::All);
  90. // 5. Let nameString and valueString be the result of running UTF-8 decode without BOM on the percent-decoding of name and value, respectively.
  91. auto name_string = TRY(String::from_byte_string(URL::percent_decode(space_decoded_name)));
  92. auto value_string = TRY(String::from_byte_string(URL::percent_decode(value)));
  93. TRY(output.try_empend(move(name_string), move(value_string)));
  94. }
  95. return output;
  96. }
  97. WebIDL::ExceptionOr<JS::NonnullGCPtr<URLSearchParams>> URLSearchParams::create(JS::Realm& realm, Vector<QueryParam> list)
  98. {
  99. return realm.heap().allocate<URLSearchParams>(realm, realm, move(list));
  100. }
  101. // https://url.spec.whatwg.org/#urlsearchparams-initialize
  102. WebIDL::ExceptionOr<JS::NonnullGCPtr<URLSearchParams>> URLSearchParams::create(JS::Realm& realm, StringView init)
  103. {
  104. // NOTE: We skip the other steps since we know it is a string at this point.
  105. // b. Set query’s list to the result of parsing init.
  106. return URLSearchParams::create(realm, MUST(url_decode(init)));
  107. }
  108. // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  109. // https://url.spec.whatwg.org/#urlsearchparams-initialize
  110. WebIDL::ExceptionOr<JS::NonnullGCPtr<URLSearchParams>> URLSearchParams::construct_impl(JS::Realm& realm, Variant<Vector<Vector<String>>, OrderedHashMap<String, String>, String> const& init)
  111. {
  112. auto& vm = realm.vm();
  113. // 1. If init is a string and starts with U+003F (?), then remove the first code point from init.
  114. // NOTE: We do this when we know that it's a string on step 3 of initialization.
  115. // 2. Initialize this with init.
  116. // URLSearchParams init from this point forward
  117. // 1. If init is a sequence, then for each pair in init:
  118. if (init.has<Vector<Vector<String>>>()) {
  119. auto const& init_sequence = init.get<Vector<Vector<String>>>();
  120. Vector<QueryParam> list;
  121. list.ensure_capacity(init_sequence.size());
  122. for (auto const& pair : init_sequence) {
  123. // a. If pair does not contain exactly two items, then throw a TypeError.
  124. if (pair.size() != 2)
  125. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, TRY_OR_THROW_OOM(vm, String::formatted("Expected only 2 items in pair, got {}", pair.size())) };
  126. // b. Append a new name-value pair whose name is pair’s first item, and value is pair’s second item, to query’s list.
  127. list.append(QueryParam { .name = pair[0], .value = pair[1] });
  128. }
  129. return URLSearchParams::create(realm, move(list));
  130. }
  131. // 2. Otherwise, if init is a record, then for each name → value of init, append a new name-value pair whose name is name and value is value, to query’s list.
  132. if (init.has<OrderedHashMap<String, String>>()) {
  133. auto const& init_record = init.get<OrderedHashMap<String, String>>();
  134. Vector<QueryParam> list;
  135. list.ensure_capacity(init_record.size());
  136. for (auto const& pair : init_record)
  137. list.append(QueryParam { .name = pair.key, .value = pair.value });
  138. return URLSearchParams::create(realm, move(list));
  139. }
  140. // 3. Otherwise:
  141. // a. Assert: init is a string.
  142. // NOTE: `get` performs `VERIFY(has<T>())`
  143. auto const& init_string = init.get<String>();
  144. // See NOTE at the start of this function.
  145. auto init_string_view = init_string.bytes_as_string_view();
  146. auto stripped_init = init_string_view.substring_view(init_string_view.starts_with('?'));
  147. // b. Set query’s list to the result of parsing init.
  148. return URLSearchParams::create(realm, stripped_init);
  149. }
  150. // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  151. size_t URLSearchParams::size() const
  152. {
  153. // The size getter steps are to return this’s list’s size.
  154. return m_list.size();
  155. }
  156. WebIDL::ExceptionOr<void> URLSearchParams::append(String const& name, String const& value)
  157. {
  158. auto& vm = realm().vm();
  159. // 1. Append a new name-value pair whose name is name and value is value, to list.
  160. TRY_OR_THROW_OOM(vm, m_list.try_empend(name, value));
  161. // 2. Update this.
  162. TRY(update());
  163. return {};
  164. }
  165. WebIDL::ExceptionOr<void> URLSearchParams::update()
  166. {
  167. // 1. If query’s URL object is null, then return.
  168. if (!m_url)
  169. return {};
  170. // 2. Let serializedQuery be the serialization of query’s list.
  171. auto serialized_query = TRY(to_string());
  172. // 3. If serializedQuery is the empty string, then set serializedQuery to null.
  173. if (serialized_query.is_empty())
  174. serialized_query = {};
  175. // 4. Set query’s URL object’s URL’s query to serializedQuery.
  176. m_url->set_query({}, move(serialized_query));
  177. return {};
  178. }
  179. WebIDL::ExceptionOr<void> URLSearchParams::delete_(String const& name)
  180. {
  181. // 1. Remove all name-value pairs whose name is name from list.
  182. m_list.remove_all_matching([&name](auto& entry) {
  183. return entry.name == name;
  184. });
  185. // 2. Update this.
  186. TRY(update());
  187. return {};
  188. }
  189. Optional<String> URLSearchParams::get(String const& name)
  190. {
  191. // return the value of the first name-value pair whose name is name in this’s list, if there is such a pair, and null otherwise.
  192. auto result = m_list.find_if([&name](auto& entry) {
  193. return entry.name == name;
  194. });
  195. if (result.is_end())
  196. return {};
  197. return result->value;
  198. }
  199. // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  200. WebIDL::ExceptionOr<Vector<String>> URLSearchParams::get_all(String const& name)
  201. {
  202. auto& vm = realm().vm();
  203. // return the values of all name-value pairs whose name is name, in this’s list, in list order, and the empty sequence otherwise.
  204. Vector<String> values;
  205. for (auto& entry : m_list) {
  206. if (entry.name == name)
  207. TRY_OR_THROW_OOM(vm, values.try_append(entry.value));
  208. }
  209. return values;
  210. }
  211. bool URLSearchParams::has(String const& name)
  212. {
  213. // return true if there is a name-value pair whose name is name in this’s list, and false otherwise.
  214. return !m_list.find_if([&name](auto& entry) {
  215. return entry.name == name;
  216. })
  217. .is_end();
  218. }
  219. WebIDL::ExceptionOr<void> URLSearchParams::set(String const& name, String const& value)
  220. {
  221. auto& vm = realm().vm();
  222. // 1. If this’s list contains any name-value pairs whose name is name, then set the value of the first such name-value pair to value and remove the others.
  223. auto existing = m_list.find_if([&name](auto& entry) {
  224. return entry.name == name;
  225. });
  226. if (!existing.is_end()) {
  227. existing->value = value;
  228. m_list.remove_all_matching([&name, &existing](auto& entry) {
  229. return &entry != &*existing && entry.name == name;
  230. });
  231. }
  232. // 2. Otherwise, append a new name-value pair whose name is name and value is value, to this’s list.
  233. else {
  234. TRY_OR_THROW_OOM(vm, m_list.try_empend(name, value));
  235. }
  236. // 3. Update this.
  237. TRY(update());
  238. return {};
  239. }
  240. WebIDL::ExceptionOr<void> URLSearchParams::sort()
  241. {
  242. // 1. Sort all name-value pairs, if any, by their names. Sorting must be done by comparison of code units. The relative order between name-value pairs with equal names must be preserved.
  243. quick_sort(m_list.begin(), m_list.end(), [](auto& a, auto& b) {
  244. Utf8View a_code_points { a.name };
  245. Utf8View b_code_points { b.name };
  246. if (a_code_points.starts_with(b_code_points))
  247. return false;
  248. if (b_code_points.starts_with(a_code_points))
  249. return true;
  250. for (auto k = a_code_points.begin(), l = b_code_points.begin();
  251. k != a_code_points.end() && l != b_code_points.end();
  252. ++k, ++l) {
  253. if (*k != *l) {
  254. return *k < *l;
  255. }
  256. }
  257. VERIFY_NOT_REACHED();
  258. });
  259. // 2. Update this.
  260. TRY(update());
  261. return {};
  262. }
  263. WebIDL::ExceptionOr<String> URLSearchParams::to_string() const
  264. {
  265. auto& vm = realm().vm();
  266. // return the serialization of this’s list.
  267. return TRY_OR_THROW_OOM(vm, url_encode(m_list));
  268. }
  269. JS::ThrowCompletionOr<void> URLSearchParams::for_each(ForEachCallback callback)
  270. {
  271. for (auto i = 0u; i < m_list.size(); ++i) {
  272. auto& query_param = m_list[i]; // We are explicitly iterating over the indices here as the callback might delete items from the list
  273. TRY(callback(query_param.name, query_param.value));
  274. }
  275. return {};
  276. }
  277. }