URL.cpp 17 KB

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