URL.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Max Wipfli <mail@maxwipfli.ch>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Base64.h>
  8. #include <AK/CharacterTypes.h>
  9. #include <AK/Debug.h>
  10. #include <AK/LexicalPath.h>
  11. #include <AK/StringBuilder.h>
  12. #include <AK/Utf8View.h>
  13. #include <LibURL/Parser.h>
  14. #include <LibURL/URL.h>
  15. namespace URL {
  16. // FIXME: It could make sense to force users of URL to use URL::Parser::basic_parse() explicitly instead of using a constructor.
  17. URL::URL(StringView string)
  18. : URL(Parser::basic_parse(string))
  19. {
  20. if constexpr (URL_PARSER_DEBUG) {
  21. if (m_data->valid)
  22. dbgln("URL constructor: Parsed URL to be '{}'.", serialize());
  23. else
  24. dbgln("URL constructor: Parsed URL to be invalid.");
  25. }
  26. }
  27. URL URL::complete_url(StringView relative_url) const
  28. {
  29. if (!is_valid())
  30. return {};
  31. return Parser::basic_parse(relative_url, *this);
  32. }
  33. ErrorOr<String> URL::username() const
  34. {
  35. return String::from_byte_string(percent_decode(m_data->username));
  36. }
  37. ErrorOr<String> URL::password() const
  38. {
  39. return String::from_byte_string(percent_decode(m_data->password));
  40. }
  41. ByteString URL::path_segment_at_index(size_t index) const
  42. {
  43. VERIFY(index < path_segment_count());
  44. return percent_decode(m_data->paths[index]);
  45. }
  46. ByteString URL::basename() const
  47. {
  48. if (!m_data->valid)
  49. return {};
  50. if (m_data->paths.is_empty())
  51. return {};
  52. auto& last_segment = m_data->paths.last();
  53. return percent_decode(last_segment);
  54. }
  55. void URL::set_scheme(String scheme)
  56. {
  57. m_data->scheme = move(scheme);
  58. m_data->valid = compute_validity();
  59. }
  60. // https://url.spec.whatwg.org/#set-the-username
  61. ErrorOr<void> URL::set_username(StringView username)
  62. {
  63. // To set the username given a url and username, set url’s username to the result of running UTF-8 percent-encode on username using the userinfo percent-encode set.
  64. m_data->username = TRY(String::from_byte_string(percent_encode(username, PercentEncodeSet::Userinfo)));
  65. m_data->valid = compute_validity();
  66. return {};
  67. }
  68. // https://url.spec.whatwg.org/#set-the-password
  69. ErrorOr<void> URL::set_password(StringView password)
  70. {
  71. // To set the password given a url and password, set url’s password to the result of running UTF-8 percent-encode on password using the userinfo percent-encode set.
  72. m_data->password = TRY(String::from_byte_string(percent_encode(password, PercentEncodeSet::Userinfo)));
  73. m_data->valid = compute_validity();
  74. return {};
  75. }
  76. void URL::set_host(Host host)
  77. {
  78. m_data->host = move(host);
  79. m_data->valid = compute_validity();
  80. }
  81. // https://url.spec.whatwg.org/#concept-host-serializer
  82. ErrorOr<String> URL::serialized_host() const
  83. {
  84. return Parser::serialize_host(m_data->host);
  85. }
  86. void URL::set_port(Optional<u16> port)
  87. {
  88. if (port == default_port_for_scheme(m_data->scheme)) {
  89. m_data->port = {};
  90. return;
  91. }
  92. m_data->port = move(port);
  93. m_data->valid = compute_validity();
  94. }
  95. void URL::set_paths(Vector<ByteString> const& paths)
  96. {
  97. m_data->paths.clear_with_capacity();
  98. m_data->paths.ensure_capacity(paths.size());
  99. for (auto const& segment : paths)
  100. m_data->paths.unchecked_append(String::from_byte_string(percent_encode(segment, PercentEncodeSet::Path)).release_value_but_fixme_should_propagate_errors());
  101. m_data->valid = compute_validity();
  102. }
  103. void URL::append_path(StringView path)
  104. {
  105. m_data->paths.append(String::from_byte_string(percent_encode(path, PercentEncodeSet::Path)).release_value_but_fixme_should_propagate_errors());
  106. }
  107. // https://url.spec.whatwg.org/#cannot-have-a-username-password-port
  108. bool URL::cannot_have_a_username_or_password_or_port() const
  109. {
  110. // A URL cannot have a username/password/port if its host is null or the empty string, or its scheme is "file".
  111. return m_data->host.has<Empty>() || m_data->host == String {} || m_data->scheme == "file"sv;
  112. }
  113. // FIXME: This is by no means complete.
  114. // NOTE: This relies on some assumptions about how the spec-defined URL parser works that may turn out to be wrong.
  115. bool URL::compute_validity() const
  116. {
  117. if (m_data->scheme.is_empty())
  118. return false;
  119. if (m_data->cannot_be_a_base_url) {
  120. if (m_data->paths.size() != 1)
  121. return false;
  122. if (m_data->paths[0].is_empty())
  123. return false;
  124. } else {
  125. if (m_data->scheme.is_one_of("about", "mailto"))
  126. return false;
  127. // NOTE: Maybe it is allowed to have a zero-segment path.
  128. if (m_data->paths.size() == 0)
  129. return false;
  130. }
  131. // NOTE: A file URL's host should be the empty string for localhost, not null.
  132. if (m_data->scheme == "file" && m_data->host.has<Empty>())
  133. return false;
  134. return true;
  135. }
  136. // https://url.spec.whatwg.org/#default-port
  137. Optional<u16> default_port_for_scheme(StringView scheme)
  138. {
  139. // Spec defined mappings with port:
  140. if (scheme == "ftp")
  141. return 21;
  142. if (scheme == "http")
  143. return 80;
  144. if (scheme == "https")
  145. return 443;
  146. if (scheme == "ws")
  147. return 80;
  148. if (scheme == "wss")
  149. return 443;
  150. // NOTE: not in spec, but we support these too
  151. if (scheme == "irc")
  152. return 6667;
  153. if (scheme == "ircs")
  154. return 6697;
  155. return {};
  156. }
  157. URL create_with_file_scheme(ByteString const& path, ByteString const& fragment, ByteString const& hostname)
  158. {
  159. LexicalPath lexical_path(path);
  160. if (!lexical_path.is_absolute())
  161. return {};
  162. URL url;
  163. url.set_scheme("file"_string);
  164. url.set_host(hostname == "localhost" ? String {} : String::from_byte_string(hostname).release_value_but_fixme_should_propagate_errors());
  165. url.set_paths(lexical_path.parts());
  166. if (path.ends_with('/'))
  167. url.append_slash();
  168. if (!fragment.is_empty())
  169. url.set_fragment(String::from_byte_string(fragment).release_value_but_fixme_should_propagate_errors());
  170. return url;
  171. }
  172. URL create_with_help_scheme(ByteString const& path, ByteString const& fragment, ByteString const& hostname)
  173. {
  174. LexicalPath lexical_path(path);
  175. URL url;
  176. url.set_scheme("help"_string);
  177. url.set_host(hostname == "localhost" ? String {} : String::from_byte_string(hostname).release_value_but_fixme_should_propagate_errors());
  178. url.set_paths(lexical_path.parts());
  179. if (path.ends_with('/'))
  180. url.append_slash();
  181. if (!fragment.is_empty())
  182. url.set_fragment(String::from_byte_string(fragment).release_value_but_fixme_should_propagate_errors());
  183. return url;
  184. }
  185. URL create_with_url_or_path(ByteString const& url_or_path)
  186. {
  187. URL url = url_or_path;
  188. if (url.is_valid())
  189. return url;
  190. ByteString path = LexicalPath::canonicalized_path(url_or_path);
  191. return create_with_file_scheme(path);
  192. }
  193. URL create_with_data(StringView mime_type, StringView payload, bool is_base64)
  194. {
  195. URL url;
  196. url.set_cannot_be_a_base_url(true);
  197. url.set_scheme("data"_string);
  198. StringBuilder builder;
  199. builder.append(mime_type);
  200. if (is_base64)
  201. builder.append(";base64"sv);
  202. builder.append(',');
  203. builder.append(payload);
  204. url.set_paths({ builder.to_byte_string() });
  205. return url;
  206. }
  207. // https://url.spec.whatwg.org/#special-scheme
  208. bool is_special_scheme(StringView scheme)
  209. {
  210. return scheme.is_one_of("ftp", "file", "http", "https", "ws", "wss");
  211. }
  212. // https://url.spec.whatwg.org/#url-path-serializer
  213. ByteString URL::serialize_path(ApplyPercentDecoding apply_percent_decoding) const
  214. {
  215. // 1. If url has an opaque path, then return url’s path.
  216. // FIXME: Reimplement this step once we modernize the URL implementation to meet the spec.
  217. if (cannot_be_a_base_url())
  218. return m_data->paths[0].to_byte_string();
  219. // 2. Let output be the empty string.
  220. StringBuilder output;
  221. // 3. For each segment of url’s path: append U+002F (/) followed by segment to output.
  222. for (auto const& segment : m_data->paths) {
  223. output.append('/');
  224. output.append(apply_percent_decoding == ApplyPercentDecoding::Yes ? percent_decode(segment) : segment.to_byte_string());
  225. }
  226. // 4. Return output.
  227. return output.to_byte_string();
  228. }
  229. // https://url.spec.whatwg.org/#concept-url-serializer
  230. ByteString URL::serialize(ExcludeFragment exclude_fragment) const
  231. {
  232. // 1. Let output be url’s scheme and U+003A (:) concatenated.
  233. StringBuilder output;
  234. output.append(m_data->scheme);
  235. output.append(':');
  236. // 2. If url’s host is non-null:
  237. if (!m_data->host.has<Empty>()) {
  238. // 1. Append "//" to output.
  239. output.append("//"sv);
  240. // 2. If url includes credentials, then:
  241. if (includes_credentials()) {
  242. // 1. Append url’s username to output.
  243. output.append(m_data->username);
  244. // 2. If url’s password is not the empty string, then append U+003A (:), followed by url’s password, to output.
  245. if (!m_data->password.is_empty()) {
  246. output.append(':');
  247. output.append(m_data->password);
  248. }
  249. // 3. Append U+0040 (@) to output.
  250. output.append('@');
  251. }
  252. // 3. Append url’s host, serialized, to output.
  253. output.append(serialized_host().release_value_but_fixme_should_propagate_errors());
  254. // 4. If url’s port is non-null, append U+003A (:) followed by url’s port, serialized, to output.
  255. if (m_data->port.has_value())
  256. output.appendff(":{}", *m_data->port);
  257. }
  258. // 3. If url’s host is null, url does not have an opaque path, url’s path’s size is greater than 1, and url’s path[0] is the empty string, then append U+002F (/) followed by U+002E (.) to output.
  259. // 4. Append the result of URL path serializing url to output.
  260. // FIXME: Implement this closer to spec steps.
  261. if (cannot_be_a_base_url()) {
  262. output.append(m_data->paths[0]);
  263. } else {
  264. if (m_data->host.has<Empty>() && m_data->paths.size() > 1 && m_data->paths[0].is_empty())
  265. output.append("/."sv);
  266. for (auto& segment : m_data->paths) {
  267. output.append('/');
  268. output.append(segment);
  269. }
  270. }
  271. // 5. If url’s query is non-null, append U+003F (?), followed by url’s query, to output.
  272. if (m_data->query.has_value()) {
  273. output.append('?');
  274. output.append(*m_data->query);
  275. }
  276. // 6. If exclude fragment is false and url’s fragment is non-null, then append U+0023 (#), followed by url’s fragment, to output.
  277. if (exclude_fragment == ExcludeFragment::No && m_data->fragment.has_value()) {
  278. output.append('#');
  279. output.append(*m_data->fragment);
  280. }
  281. // 7. Return output.
  282. return output.to_byte_string();
  283. }
  284. // https://url.spec.whatwg.org/#url-rendering
  285. // NOTE: This does e.g. not display credentials.
  286. // FIXME: Parts of the URL other than the host should have their sequences of percent-encoded bytes replaced with code points
  287. // resulting from percent-decoding those sequences converted to bytes, unless that renders those sequences invisible.
  288. ByteString URL::serialize_for_display() const
  289. {
  290. VERIFY(m_data->valid);
  291. StringBuilder builder;
  292. builder.append(m_data->scheme);
  293. builder.append(':');
  294. if (!m_data->host.has<Empty>()) {
  295. builder.append("//"sv);
  296. builder.append(serialized_host().release_value_but_fixme_should_propagate_errors());
  297. if (m_data->port.has_value())
  298. builder.appendff(":{}", *m_data->port);
  299. }
  300. if (cannot_be_a_base_url()) {
  301. builder.append(m_data->paths[0]);
  302. } else {
  303. if (m_data->host.has<Empty>() && m_data->paths.size() > 1 && m_data->paths[0].is_empty())
  304. builder.append("/."sv);
  305. for (auto& segment : m_data->paths) {
  306. builder.append('/');
  307. builder.append(segment);
  308. }
  309. }
  310. if (m_data->query.has_value()) {
  311. builder.append('?');
  312. builder.append(*m_data->query);
  313. }
  314. if (m_data->fragment.has_value()) {
  315. builder.append('#');
  316. builder.append(*m_data->fragment);
  317. }
  318. return builder.to_byte_string();
  319. }
  320. ErrorOr<String> URL::to_string() const
  321. {
  322. return String::from_byte_string(serialize());
  323. }
  324. // https://html.spec.whatwg.org/multipage/origin.html#ascii-serialisation-of-an-origin
  325. // https://url.spec.whatwg.org/#concept-url-origin
  326. ByteString URL::serialize_origin() const
  327. {
  328. VERIFY(m_data->valid);
  329. if (m_data->scheme == "blob"sv) {
  330. // TODO: 1. If URL’s blob URL entry is non-null, then return URL’s blob URL entry’s environment’s origin.
  331. // 2. Let url be the result of parsing URL’s path[0].
  332. VERIFY(!m_data->paths.is_empty());
  333. URL url = m_data->paths[0];
  334. // 3. Return a new opaque origin, if url is failure, and url’s origin otherwise.
  335. if (!url.is_valid())
  336. return "null";
  337. return url.serialize_origin();
  338. } else if (!m_data->scheme.is_one_of("ftp"sv, "http"sv, "https"sv, "ws"sv, "wss"sv)) { // file: "Unfortunate as it is, this is left as an exercise to the reader. When in doubt, return a new opaque origin."
  339. return "null";
  340. }
  341. StringBuilder builder;
  342. builder.append(m_data->scheme);
  343. builder.append("://"sv);
  344. builder.append(serialized_host().release_value_but_fixme_should_propagate_errors());
  345. if (m_data->port.has_value())
  346. builder.appendff(":{}", *m_data->port);
  347. return builder.to_byte_string();
  348. }
  349. bool URL::equals(URL const& other, ExcludeFragment exclude_fragments) const
  350. {
  351. if (this == &other)
  352. return true;
  353. if (!m_data->valid || !other.m_data->valid)
  354. return false;
  355. return serialize(exclude_fragments) == other.serialize(exclude_fragments);
  356. }
  357. void append_percent_encoded(StringBuilder& builder, u32 code_point)
  358. {
  359. if (code_point <= 0x7f)
  360. builder.appendff("%{:02X}", code_point);
  361. else if (code_point <= 0x07ff)
  362. builder.appendff("%{:02X}%{:02X}", ((code_point >> 6) & 0x1f) | 0xc0, (code_point & 0x3f) | 0x80);
  363. else if (code_point <= 0xffff)
  364. builder.appendff("%{:02X}%{:02X}%{:02X}", ((code_point >> 12) & 0x0f) | 0xe0, ((code_point >> 6) & 0x3f) | 0x80, (code_point & 0x3f) | 0x80);
  365. else if (code_point <= 0x10ffff)
  366. builder.appendff("%{:02X}%{:02X}%{:02X}%{:02X}", ((code_point >> 18) & 0x07) | 0xf0, ((code_point >> 12) & 0x3f) | 0x80, ((code_point >> 6) & 0x3f) | 0x80, (code_point & 0x3f) | 0x80);
  367. else
  368. VERIFY_NOT_REACHED();
  369. }
  370. // https://url.spec.whatwg.org/#c0-control-percent-encode-set
  371. bool code_point_is_in_percent_encode_set(u32 code_point, PercentEncodeSet set)
  372. {
  373. // NOTE: Once we've checked for presence in the C0Control set, we know that the code point is
  374. // a valid ASCII character in the range 0x20..0x7E, so we can safely cast it to char.
  375. switch (set) {
  376. case PercentEncodeSet::C0Control:
  377. return code_point < 0x20 || code_point > 0x7E;
  378. case PercentEncodeSet::Fragment:
  379. return code_point_is_in_percent_encode_set(code_point, PercentEncodeSet::C0Control) || " \"<>`"sv.contains(static_cast<char>(code_point));
  380. case PercentEncodeSet::Query:
  381. return code_point_is_in_percent_encode_set(code_point, PercentEncodeSet::C0Control) || " \"#<>"sv.contains(static_cast<char>(code_point));
  382. case PercentEncodeSet::SpecialQuery:
  383. return code_point_is_in_percent_encode_set(code_point, PercentEncodeSet::Query) || code_point == '\'';
  384. case PercentEncodeSet::Path:
  385. return code_point_is_in_percent_encode_set(code_point, PercentEncodeSet::Query) || "?`{}"sv.contains(static_cast<char>(code_point));
  386. case PercentEncodeSet::Userinfo:
  387. return code_point_is_in_percent_encode_set(code_point, PercentEncodeSet::Path) || "/:;=@[\\]^|"sv.contains(static_cast<char>(code_point));
  388. case PercentEncodeSet::Component:
  389. return code_point_is_in_percent_encode_set(code_point, PercentEncodeSet::Userinfo) || "$%&+,"sv.contains(static_cast<char>(code_point));
  390. case PercentEncodeSet::ApplicationXWWWFormUrlencoded:
  391. return code_point_is_in_percent_encode_set(code_point, PercentEncodeSet::Component) || "!'()~"sv.contains(static_cast<char>(code_point));
  392. case PercentEncodeSet::EncodeURI:
  393. // NOTE: This is the same percent encode set that JS encodeURI() uses.
  394. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI
  395. return code_point > 0x7E || (!is_ascii_alphanumeric(code_point) && !";,/?:@&=+$-_.!~*'()#"sv.contains(static_cast<char>(code_point)));
  396. default:
  397. VERIFY_NOT_REACHED();
  398. }
  399. }
  400. void append_percent_encoded_if_necessary(StringBuilder& builder, u32 code_point, PercentEncodeSet set)
  401. {
  402. if (code_point_is_in_percent_encode_set(code_point, set))
  403. append_percent_encoded(builder, code_point);
  404. else
  405. builder.append_code_point(code_point);
  406. }
  407. ByteString percent_encode(StringView input, PercentEncodeSet set, SpaceAsPlus space_as_plus)
  408. {
  409. StringBuilder builder;
  410. for (auto code_point : Utf8View(input)) {
  411. if (space_as_plus == SpaceAsPlus::Yes && code_point == ' ')
  412. builder.append('+');
  413. else
  414. append_percent_encoded_if_necessary(builder, code_point, set);
  415. }
  416. return builder.to_byte_string();
  417. }
  418. ByteString percent_decode(StringView input)
  419. {
  420. if (!input.contains('%'))
  421. return input;
  422. StringBuilder builder;
  423. Utf8View utf8_view(input);
  424. for (auto it = utf8_view.begin(); !it.done(); ++it) {
  425. if (*it != '%') {
  426. builder.append_code_point(*it);
  427. } else if (!is_ascii_hex_digit(it.peek(1).value_or(0)) || !is_ascii_hex_digit(it.peek(2).value_or(0))) {
  428. builder.append_code_point(*it);
  429. } else {
  430. ++it;
  431. u8 byte = parse_ascii_hex_digit(*it) << 4;
  432. ++it;
  433. byte += parse_ascii_hex_digit(*it);
  434. builder.append(byte);
  435. }
  436. }
  437. return builder.to_byte_string();
  438. }
  439. }