CookieJar.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. /*
  2. * Copyright (c) 2021-2024, Tim Flynn <trflynn89@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. * Copyright (c) 2022, Tobias Christiansen <tobyase@serenityos.org>
  5. * Copyright (c) 2023, Jelle Raaijmakers <jelle@gmta.nl>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/IPv4Address.h>
  10. #include <AK/StringBuilder.h>
  11. #include <AK/Time.h>
  12. #include <AK/Vector.h>
  13. #include <LibSQL/TupleDescriptor.h>
  14. #include <LibSQL/Value.h>
  15. #include <LibURL/URL.h>
  16. #include <LibWeb/Cookie/ParsedCookie.h>
  17. #include <LibWebView/CookieJar.h>
  18. #include <LibWebView/Database.h>
  19. #include <LibWebView/URL.h>
  20. namespace WebView {
  21. static constexpr auto DATABASE_SYNCHRONIZATION_TIMER = Duration::from_seconds(30);
  22. ErrorOr<NonnullOwnPtr<CookieJar>> CookieJar::create(Database& database)
  23. {
  24. Statements statements {};
  25. statements.create_table = TRY(database.prepare_statement(R"#(
  26. CREATE TABLE IF NOT EXISTS Cookies (
  27. name TEXT,
  28. value TEXT,
  29. same_site INTEGER,
  30. creation_time INTEGER,
  31. last_access_time INTEGER,
  32. expiry_time INTEGER,
  33. domain TEXT,
  34. path TEXT,
  35. secure BOOLEAN,
  36. http_only BOOLEAN,
  37. host_only BOOLEAN,
  38. persistent BOOLEAN
  39. );)#"sv));
  40. statements.update_cookie = TRY(database.prepare_statement(R"#(
  41. UPDATE Cookies SET
  42. value=?,
  43. same_site=?,
  44. creation_time=?,
  45. last_access_time=?,
  46. expiry_time=?,
  47. secure=?,
  48. http_only=?,
  49. host_only=?,
  50. persistent=?
  51. WHERE ((name = ?) AND (domain = ?) AND (path = ?));)#"sv));
  52. statements.insert_cookie = TRY(database.prepare_statement("INSERT INTO Cookies VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"sv));
  53. statements.expire_cookie = TRY(database.prepare_statement("DELETE FROM Cookies WHERE (expiry_time < ?);"sv));
  54. statements.select_all_cookies = TRY(database.prepare_statement("SELECT * FROM Cookies;"sv));
  55. return adopt_own(*new CookieJar { PersistedStorage { database, statements } });
  56. }
  57. NonnullOwnPtr<CookieJar> CookieJar::create()
  58. {
  59. return adopt_own(*new CookieJar { OptionalNone {} });
  60. }
  61. CookieJar::CookieJar(Optional<PersistedStorage> persisted_storage)
  62. : m_persisted_storage(move(persisted_storage))
  63. {
  64. if (!m_persisted_storage.has_value())
  65. return;
  66. m_persisted_storage->database.execute_statement(m_persisted_storage->statements.create_table, {}, {}, {});
  67. // FIXME: Make cookie retrieval lazy so we don't need to retrieve all cookies up front.
  68. auto cookies = m_persisted_storage->select_all_cookies();
  69. m_transient_storage.set_cookies(move(cookies));
  70. m_persisted_storage->synchronization_timer = Core::Timer::create_repeating(
  71. static_cast<int>(DATABASE_SYNCHRONIZATION_TIMER.to_milliseconds()),
  72. [this]() {
  73. auto now = m_transient_storage.purge_expired_cookies();
  74. m_persisted_storage->database.execute_statement(m_persisted_storage->statements.expire_cookie, {}, {}, {}, now);
  75. // FIXME: Implement "INSERT OR REPLACE"
  76. for (auto const& it : m_transient_storage.take_inserted_cookies())
  77. m_persisted_storage->insert_cookie(it.value);
  78. for (auto const& it : m_transient_storage.take_updated_cookies())
  79. m_persisted_storage->update_cookie(it.value);
  80. });
  81. m_persisted_storage->synchronization_timer->start();
  82. }
  83. CookieJar::~CookieJar()
  84. {
  85. if (!m_persisted_storage.has_value())
  86. return;
  87. m_persisted_storage->synchronization_timer->stop();
  88. m_persisted_storage->synchronization_timer->on_timeout();
  89. }
  90. String CookieJar::get_cookie(const URL::URL& url, Web::Cookie::Source source)
  91. {
  92. m_transient_storage.purge_expired_cookies();
  93. auto domain = canonicalize_domain(url);
  94. if (!domain.has_value())
  95. return {};
  96. auto cookie_list = get_matching_cookies(url, domain.value(), source);
  97. StringBuilder builder;
  98. for (auto const& cookie : cookie_list) {
  99. // If there is an unprocessed cookie in the cookie-list, output the characters %x3B and %x20 ("; ")
  100. if (!builder.is_empty())
  101. builder.append("; "sv);
  102. // Output the cookie's name, the %x3D ("=") character, and the cookie's value.
  103. builder.appendff("{}={}", cookie.name, cookie.value);
  104. }
  105. return MUST(builder.to_string());
  106. }
  107. void CookieJar::set_cookie(const URL::URL& url, Web::Cookie::ParsedCookie const& parsed_cookie, Web::Cookie::Source source)
  108. {
  109. auto domain = canonicalize_domain(url);
  110. if (!domain.has_value())
  111. return;
  112. store_cookie(parsed_cookie, url, domain.release_value(), source);
  113. }
  114. // This is based on https://www.rfc-editor.org/rfc/rfc6265#section-5.3 as store_cookie() below
  115. // however the whole ParsedCookie->Cookie conversion is skipped.
  116. void CookieJar::update_cookie(Web::Cookie::Cookie cookie)
  117. {
  118. CookieStorageKey key { cookie.name, cookie.domain, cookie.path };
  119. // 11. If the cookie store contains a cookie with the same name, domain, and path as the newly created cookie:
  120. if (auto old_cookie = m_transient_storage.get_cookie(key); old_cookie.has_value()) {
  121. // Update the creation-time of the newly created cookie to match the creation-time of the old-cookie.
  122. cookie.creation_time = old_cookie->creation_time;
  123. // Remove the old-cookie from the cookie store.
  124. // NOTE: Rather than deleting then re-inserting this cookie, we update it in-place.
  125. }
  126. // 12. Insert the newly created cookie into the cookie store.
  127. m_transient_storage.set_cookie(move(key), move(cookie));
  128. m_transient_storage.purge_expired_cookies();
  129. }
  130. void CookieJar::dump_cookies()
  131. {
  132. StringBuilder builder;
  133. m_transient_storage.for_each_cookie([&](auto const& cookie) {
  134. static constexpr auto key_color = "\033[34;1m"sv;
  135. static constexpr auto attribute_color = "\033[33m"sv;
  136. static constexpr auto no_color = "\033[0m"sv;
  137. builder.appendff("{}{}{} - ", key_color, cookie.name, no_color);
  138. builder.appendff("{}{}{} - ", key_color, cookie.domain, no_color);
  139. builder.appendff("{}{}{}\n", key_color, cookie.path, no_color);
  140. builder.appendff("\t{}Value{} = {}\n", attribute_color, no_color, cookie.value);
  141. builder.appendff("\t{}CreationTime{} = {}\n", attribute_color, no_color, cookie.creation_time_to_string());
  142. builder.appendff("\t{}LastAccessTime{} = {}\n", attribute_color, no_color, cookie.last_access_time_to_string());
  143. builder.appendff("\t{}ExpiryTime{} = {}\n", attribute_color, no_color, cookie.expiry_time_to_string());
  144. builder.appendff("\t{}Secure{} = {:s}\n", attribute_color, no_color, cookie.secure);
  145. builder.appendff("\t{}HttpOnly{} = {:s}\n", attribute_color, no_color, cookie.http_only);
  146. builder.appendff("\t{}HostOnly{} = {:s}\n", attribute_color, no_color, cookie.host_only);
  147. builder.appendff("\t{}Persistent{} = {:s}\n", attribute_color, no_color, cookie.persistent);
  148. builder.appendff("\t{}SameSite{} = {:s}\n", attribute_color, no_color, Web::Cookie::same_site_to_string(cookie.same_site));
  149. });
  150. dbgln("{} cookies stored\n{}", m_transient_storage.size(), builder.string_view());
  151. }
  152. Vector<Web::Cookie::Cookie> CookieJar::get_all_cookies()
  153. {
  154. Vector<Web::Cookie::Cookie> cookies;
  155. cookies.ensure_capacity(m_transient_storage.size());
  156. m_transient_storage.for_each_cookie([&](auto const& cookie) {
  157. cookies.unchecked_append(cookie);
  158. });
  159. return cookies;
  160. }
  161. // https://w3c.github.io/webdriver/#dfn-associated-cookies
  162. Vector<Web::Cookie::Cookie> CookieJar::get_all_cookies(URL::URL const& url)
  163. {
  164. auto domain = canonicalize_domain(url);
  165. if (!domain.has_value())
  166. return {};
  167. return get_matching_cookies(url, domain.value(), Web::Cookie::Source::Http, MatchingCookiesSpecMode::WebDriver);
  168. }
  169. Optional<Web::Cookie::Cookie> CookieJar::get_named_cookie(URL::URL const& url, StringView name)
  170. {
  171. auto domain = canonicalize_domain(url);
  172. if (!domain.has_value())
  173. return {};
  174. auto cookie_list = get_matching_cookies(url, domain.value(), Web::Cookie::Source::Http, MatchingCookiesSpecMode::WebDriver);
  175. for (auto const& cookie : cookie_list) {
  176. if (cookie.name == name)
  177. return cookie;
  178. }
  179. return {};
  180. }
  181. Optional<String> CookieJar::canonicalize_domain(const URL::URL& url)
  182. {
  183. // https://tools.ietf.org/html/rfc6265#section-5.1.2
  184. if (!url.is_valid())
  185. return {};
  186. // FIXME: Implement RFC 5890 to "Convert each label that is not a Non-Reserved LDH (NR-LDH) label to an A-label".
  187. if (url.host().has<Empty>())
  188. return {};
  189. return MUST(MUST(url.serialized_host()).to_lowercase());
  190. }
  191. bool CookieJar::domain_matches(StringView string, StringView domain_string)
  192. {
  193. // https://tools.ietf.org/html/rfc6265#section-5.1.3
  194. // A string domain-matches a given domain string if at least one of the following conditions hold:
  195. // The domain string and the string are identical.
  196. if (string == domain_string)
  197. return true;
  198. // All of the following conditions hold:
  199. // - The domain string is a suffix of the string.
  200. // - The last character of the string that is not included in the domain string is a %x2E (".") character.
  201. // - The string is a host name (i.e., not an IP address).
  202. if (!string.ends_with(domain_string))
  203. return false;
  204. if (string[string.length() - domain_string.length() - 1] != '.')
  205. return false;
  206. if (AK::IPv4Address::from_string(string).has_value())
  207. return false;
  208. return true;
  209. }
  210. bool CookieJar::path_matches(StringView request_path, StringView cookie_path)
  211. {
  212. // https://tools.ietf.org/html/rfc6265#section-5.1.4
  213. // A request-path path-matches a given cookie-path if at least one of the following conditions holds:
  214. // The cookie-path and the request-path are identical.
  215. if (request_path == cookie_path)
  216. return true;
  217. if (request_path.starts_with(cookie_path)) {
  218. // The cookie-path is a prefix of the request-path, and the last character of the cookie-path is %x2F ("/").
  219. if (cookie_path.ends_with('/'))
  220. return true;
  221. // The cookie-path is a prefix of the request-path, and the first character of the request-path that is not included in the cookie-path is a %x2F ("/") character.
  222. if (request_path[cookie_path.length()] == '/')
  223. return true;
  224. }
  225. return false;
  226. }
  227. String CookieJar::default_path(const URL::URL& url)
  228. {
  229. // https://tools.ietf.org/html/rfc6265#section-5.1.4
  230. // 1. Let uri-path be the path portion of the request-uri if such a portion exists (and empty otherwise).
  231. auto uri_path = url.serialize_path();
  232. // 2. If the uri-path is empty or if the first character of the uri-path is not a %x2F ("/") character, output %x2F ("/") and skip the remaining steps.
  233. if (uri_path.is_empty() || (uri_path[0] != '/'))
  234. return "/"_string;
  235. StringView uri_path_view = uri_path;
  236. size_t last_separator = uri_path_view.find_last('/').value();
  237. // 3. If the uri-path contains no more than one %x2F ("/") character, output %x2F ("/") and skip the remaining step.
  238. if (last_separator == 0)
  239. return "/"_string;
  240. // 4. Output the characters of the uri-path from the first character up to, but not including, the right-most %x2F ("/").
  241. return MUST(String::from_utf8(uri_path.substring_view(0, last_separator)));
  242. }
  243. void CookieJar::store_cookie(Web::Cookie::ParsedCookie const& parsed_cookie, const URL::URL& url, String canonicalized_domain, Web::Cookie::Source source)
  244. {
  245. // https://tools.ietf.org/html/rfc6265#section-5.3
  246. // 2. Create a new cookie with name cookie-name, value cookie-value. Set the creation-time and the last-access-time to the current date and time.
  247. Web::Cookie::Cookie cookie { parsed_cookie.name, parsed_cookie.value, parsed_cookie.same_site_attribute };
  248. cookie.creation_time = UnixDateTime::now();
  249. cookie.last_access_time = cookie.creation_time;
  250. if (parsed_cookie.expiry_time_from_max_age_attribute.has_value()) {
  251. // 3. If the cookie-attribute-list contains an attribute with an attribute-name of "Max-Age": Set the cookie's persistent-flag to true.
  252. // Set the cookie's expiry-time to attribute-value of the last attribute in the cookie-attribute-list with an attribute-name of "Max-Age".
  253. cookie.persistent = true;
  254. cookie.expiry_time = parsed_cookie.expiry_time_from_max_age_attribute.value();
  255. } else if (parsed_cookie.expiry_time_from_expires_attribute.has_value()) {
  256. // If the cookie-attribute-list contains an attribute with an attribute-name of "Expires": Set the cookie's persistent-flag to true.
  257. // Set the cookie's expiry-time to attribute-value of the last attribute in the cookie-attribute-list with an attribute-name of "Expires".
  258. cookie.persistent = true;
  259. cookie.expiry_time = parsed_cookie.expiry_time_from_expires_attribute.value();
  260. } else {
  261. // Set the cookie's persistent-flag to false. Set the cookie's expiry-time to the latest representable date.
  262. cookie.persistent = false;
  263. cookie.expiry_time = UnixDateTime::from_unix_time_parts(3000, 1, 1, 0, 0, 0, 0);
  264. }
  265. // 4. If the cookie-attribute-list contains an attribute with an attribute-name of "Domain":
  266. if (parsed_cookie.domain.has_value()) {
  267. // Let the domain-attribute be the attribute-value of the last attribute in the cookie-attribute-list with an attribute-name of "Domain".
  268. cookie.domain = parsed_cookie.domain.value();
  269. }
  270. // 5. If the user agent is configured to reject "public suffixes" and the domain-attribute is a public suffix:
  271. if (is_public_suffix(cookie.domain)) {
  272. // If the domain-attribute is identical to the canonicalized request-host:
  273. if (cookie.domain == canonicalized_domain) {
  274. // Let the domain-attribute be the empty string.
  275. cookie.domain = String {};
  276. }
  277. // Otherwise:
  278. else {
  279. // Ignore the cookie entirely and abort these steps.
  280. return;
  281. }
  282. }
  283. // 6. If the domain-attribute is non-empty:
  284. if (!cookie.domain.is_empty()) {
  285. // If the canonicalized request-host does not domain-match the domain-attribute: Ignore the cookie entirely and abort these steps.
  286. if (!domain_matches(canonicalized_domain, cookie.domain))
  287. return;
  288. // Set the cookie's host-only-flag to false. Set the cookie's domain to the domain-attribute.
  289. cookie.host_only = false;
  290. } else {
  291. // Set the cookie's host-only-flag to true. Set the cookie's domain to the canonicalized request-host.
  292. cookie.host_only = true;
  293. cookie.domain = move(canonicalized_domain);
  294. }
  295. // 7. If the cookie-attribute-list contains an attribute with an attribute-name of "Path":
  296. if (parsed_cookie.path.has_value()) {
  297. // Set the cookie's path to attribute-value of the last attribute in the cookie-attribute-list with an attribute-name of "Path".
  298. cookie.path = parsed_cookie.path.value();
  299. } else {
  300. cookie.path = default_path(url);
  301. }
  302. // 8. If the cookie-attribute-list contains an attribute with an attribute-name of "Secure", set the cookie's secure-only-flag to true.
  303. cookie.secure = parsed_cookie.secure_attribute_present;
  304. // 9. If the cookie-attribute-list contains an attribute with an attribute-name of "HttpOnly", set the cookie's http-only-flag to false.
  305. cookie.http_only = parsed_cookie.http_only_attribute_present;
  306. // 10. If the cookie was received from a "non-HTTP" API and the cookie's http-only-flag is set, abort these steps and ignore the cookie entirely.
  307. if (source != Web::Cookie::Source::Http && cookie.http_only)
  308. return;
  309. CookieStorageKey key { cookie.name, cookie.domain, cookie.path };
  310. // 11. If the cookie store contains a cookie with the same name, domain, and path as the newly created cookie:
  311. if (auto const& old_cookie = m_transient_storage.get_cookie(key); old_cookie.has_value()) {
  312. // If the newly created cookie was received from a "non-HTTP" API and the old-cookie's http-only-flag is set, abort these
  313. // steps and ignore the newly created cookie entirely.
  314. if (source != Web::Cookie::Source::Http && old_cookie->http_only)
  315. return;
  316. // Update the creation-time of the newly created cookie to match the creation-time of the old-cookie.
  317. cookie.creation_time = old_cookie->creation_time;
  318. // Remove the old-cookie from the cookie store.
  319. // NOTE: Rather than deleting then re-inserting this cookie, we update it in-place.
  320. }
  321. // 12. Insert the newly created cookie into the cookie store.
  322. m_transient_storage.set_cookie(move(key), move(cookie));
  323. m_transient_storage.purge_expired_cookies();
  324. }
  325. Vector<Web::Cookie::Cookie> CookieJar::get_matching_cookies(const URL::URL& url, StringView canonicalized_domain, Web::Cookie::Source source, MatchingCookiesSpecMode mode)
  326. {
  327. // https://tools.ietf.org/html/rfc6265#section-5.4
  328. auto now = UnixDateTime::now();
  329. // 1. Let cookie-list be the set of cookies from the cookie store that meets all of the following requirements:
  330. Vector<Web::Cookie::Cookie> cookie_list;
  331. m_transient_storage.for_each_cookie([&](auto& cookie) {
  332. // Either: The cookie's host-only-flag is true and the canonicalized request-host is identical to the cookie's domain.
  333. // Or: The cookie's host-only-flag is false and the canonicalized request-host domain-matches the cookie's domain.
  334. bool is_host_only_and_has_identical_domain = cookie.host_only && (canonicalized_domain == cookie.domain);
  335. bool is_not_host_only_and_domain_matches = !cookie.host_only && domain_matches(canonicalized_domain, cookie.domain);
  336. if (!is_host_only_and_has_identical_domain && !is_not_host_only_and_domain_matches)
  337. return;
  338. // The request-uri's path path-matches the cookie's path.
  339. if (!path_matches(url.serialize_path(), cookie.path))
  340. return;
  341. // If the cookie's secure-only-flag is true, then the request-uri's scheme must denote a "secure" protocol.
  342. if (cookie.secure && (url.scheme() != "https"))
  343. return;
  344. // If the cookie's http-only-flag is true, then exclude the cookie if the cookie-string is being generated for a "non-HTTP" API.
  345. if (cookie.http_only && (source != Web::Cookie::Source::Http))
  346. return;
  347. // NOTE: The WebDriver spec expects only step 1 above to be executed to match cookies.
  348. if (mode == MatchingCookiesSpecMode::WebDriver) {
  349. cookie_list.append(cookie);
  350. return;
  351. }
  352. // 3. Update the last-access-time of each cookie in the cookie-list to the current date and time.
  353. // NOTE: We do this first so that both our internal storage and cookie-list are updated.
  354. cookie.last_access_time = now;
  355. // 2. The user agent SHOULD sort the cookie-list in the following order:
  356. // - Cookies with longer paths are listed before cookies with shorter paths.
  357. // - Among cookies that have equal-length path fields, cookies with earlier creation-times are listed before cookies with later creation-times.
  358. auto cookie_path_length = cookie.path.bytes().size();
  359. auto cookie_creation_time = cookie.creation_time;
  360. cookie_list.insert_before_matching(cookie, [cookie_path_length, cookie_creation_time](auto const& entry) {
  361. if (cookie_path_length > entry.path.bytes().size()) {
  362. return true;
  363. }
  364. if (cookie_path_length == entry.path.bytes().size()) {
  365. if (cookie_creation_time < entry.creation_time)
  366. return true;
  367. }
  368. return false;
  369. });
  370. });
  371. if (mode != MatchingCookiesSpecMode::WebDriver)
  372. m_transient_storage.purge_expired_cookies();
  373. return cookie_list;
  374. }
  375. static ErrorOr<Web::Cookie::Cookie> parse_cookie(ReadonlySpan<SQL::Value> row)
  376. {
  377. if (row.size() != 12)
  378. return Error::from_string_view("Incorrect number of columns to parse cookie"sv);
  379. size_t index = 0;
  380. auto convert_text = [&](auto& field, StringView name) -> ErrorOr<void> {
  381. auto const& value = row[index++];
  382. if (value.type() != SQL::SQLType::Text)
  383. return Error::from_string_view(name);
  384. field = MUST(value.to_string());
  385. return {};
  386. };
  387. auto convert_bool = [&](auto& field, StringView name) -> ErrorOr<void> {
  388. auto const& value = row[index++];
  389. if (value.type() != SQL::SQLType::Boolean)
  390. return Error::from_string_view(name);
  391. field = value.to_bool().value();
  392. return {};
  393. };
  394. auto convert_time = [&](auto& field, StringView name) -> ErrorOr<void> {
  395. auto const& value = row[index++];
  396. if (value.type() != SQL::SQLType::Integer)
  397. return Error::from_string_view(name);
  398. field = value.to_unix_date_time().value();
  399. return {};
  400. };
  401. auto convert_same_site = [&](auto& field, StringView name) -> ErrorOr<void> {
  402. auto const& value = row[index++];
  403. if (value.type() != SQL::SQLType::Integer)
  404. return Error::from_string_view(name);
  405. auto same_site = value.to_int<UnderlyingType<Web::Cookie::SameSite>>().value();
  406. if (same_site > to_underlying(Web::Cookie::SameSite::Lax))
  407. return Error::from_string_view(name);
  408. field = static_cast<Web::Cookie::SameSite>(same_site);
  409. return {};
  410. };
  411. Web::Cookie::Cookie cookie;
  412. TRY(convert_text(cookie.name, "name"sv));
  413. TRY(convert_text(cookie.value, "value"sv));
  414. TRY(convert_same_site(cookie.same_site, "same_site"sv));
  415. TRY(convert_time(cookie.creation_time, "creation_time"sv));
  416. TRY(convert_time(cookie.last_access_time, "last_access_time"sv));
  417. TRY(convert_time(cookie.expiry_time, "expiry_time"sv));
  418. TRY(convert_text(cookie.domain, "domain"sv));
  419. TRY(convert_text(cookie.path, "path"sv));
  420. TRY(convert_bool(cookie.secure, "secure"sv));
  421. TRY(convert_bool(cookie.http_only, "http_only"sv));
  422. TRY(convert_bool(cookie.host_only, "host_only"sv));
  423. TRY(convert_bool(cookie.persistent, "persistent"sv));
  424. return cookie;
  425. }
  426. void CookieJar::TransientStorage::set_cookies(Cookies cookies)
  427. {
  428. m_cookies = move(cookies);
  429. purge_expired_cookies();
  430. }
  431. void CookieJar::TransientStorage::set_cookie(CookieStorageKey key, Web::Cookie::Cookie cookie)
  432. {
  433. auto result = m_cookies.set(key, cookie);
  434. switch (result) {
  435. case HashSetResult::InsertedNewEntry:
  436. m_inserted_cookies.set(move(key), move(cookie));
  437. break;
  438. case HashSetResult::ReplacedExistingEntry:
  439. if (m_inserted_cookies.contains(key))
  440. m_inserted_cookies.set(move(key), move(cookie));
  441. else
  442. m_updated_cookies.set(move(key), move(cookie));
  443. break;
  444. case HashSetResult::KeptExistingEntry:
  445. VERIFY_NOT_REACHED();
  446. break;
  447. }
  448. }
  449. Optional<Web::Cookie::Cookie> CookieJar::TransientStorage::get_cookie(CookieStorageKey const& key)
  450. {
  451. return m_cookies.get(key);
  452. }
  453. UnixDateTime CookieJar::TransientStorage::purge_expired_cookies()
  454. {
  455. auto now = UnixDateTime::now();
  456. auto is_expired = [&](auto const&, auto const& cookie) { return cookie.expiry_time < now; };
  457. m_cookies.remove_all_matching(is_expired);
  458. m_inserted_cookies.remove_all_matching(is_expired);
  459. m_updated_cookies.remove_all_matching(is_expired);
  460. return now;
  461. }
  462. void CookieJar::PersistedStorage::insert_cookie(Web::Cookie::Cookie const& cookie)
  463. {
  464. database.execute_statement(
  465. statements.insert_cookie,
  466. {}, {}, {},
  467. cookie.name,
  468. cookie.value,
  469. to_underlying(cookie.same_site),
  470. cookie.creation_time,
  471. cookie.last_access_time,
  472. cookie.expiry_time,
  473. cookie.domain,
  474. cookie.path,
  475. cookie.secure,
  476. cookie.http_only,
  477. cookie.host_only,
  478. cookie.persistent);
  479. }
  480. void CookieJar::PersistedStorage::update_cookie(Web::Cookie::Cookie const& cookie)
  481. {
  482. database.execute_statement(
  483. statements.update_cookie,
  484. {}, {}, {},
  485. cookie.value,
  486. to_underlying(cookie.same_site),
  487. cookie.creation_time,
  488. cookie.last_access_time,
  489. cookie.expiry_time,
  490. cookie.secure,
  491. cookie.http_only,
  492. cookie.host_only,
  493. cookie.persistent,
  494. cookie.name,
  495. cookie.domain,
  496. cookie.path);
  497. }
  498. CookieJar::TransientStorage::Cookies CookieJar::PersistedStorage::select_all_cookies()
  499. {
  500. HashMap<CookieStorageKey, Web::Cookie::Cookie> cookies;
  501. auto add_cookie = [&](auto cookie) {
  502. CookieStorageKey key { cookie.name, cookie.domain, cookie.path };
  503. cookies.set(move(key), move(cookie));
  504. };
  505. database.execute_statement(
  506. statements.select_all_cookies,
  507. [&](auto row) {
  508. if (auto cookie = parse_cookie(row); cookie.is_error())
  509. dbgln("Failed to parse cookie '{}': {}", cookie.error(), row);
  510. else
  511. add_cookie(cookie.release_value());
  512. },
  513. {},
  514. {});
  515. return cookies;
  516. }
  517. }