CookieJar.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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 <LibCore/Promise.h>
  14. #include <LibSQL/TupleDescriptor.h>
  15. #include <LibSQL/Value.h>
  16. #include <LibURL/URL.h>
  17. #include <LibWeb/Cookie/ParsedCookie.h>
  18. #include <LibWebView/CookieJar.h>
  19. #include <LibWebView/Database.h>
  20. #include <LibWebView/URL.h>
  21. namespace WebView {
  22. ErrorOr<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.update_cookie_last_access_time = TRY(database.prepare_statement(R"#(
  53. UPDATE Cookies SET last_access_time=?
  54. WHERE ((name = ?) AND (domain = ?) AND (path = ?));)#"sv));
  55. statements.insert_cookie = TRY(database.prepare_statement("INSERT INTO Cookies VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"sv));
  56. statements.expire_cookie = TRY(database.prepare_statement("DELETE FROM Cookies WHERE (expiry_time < ?);"sv));
  57. statements.select_cookie = TRY(database.prepare_statement("SELECT * FROM Cookies WHERE ((name = ?) AND (domain = ?) AND (path = ?));"sv));
  58. statements.select_all_cookies = TRY(database.prepare_statement("SELECT * FROM Cookies;"sv));
  59. return CookieJar { PersistedStorage { database, move(statements) } };
  60. }
  61. CookieJar CookieJar::create()
  62. {
  63. return CookieJar { TransientStorage {} };
  64. }
  65. CookieJar::CookieJar(PersistedStorage storage)
  66. : m_storage(move(storage))
  67. {
  68. auto& persisted_storage = m_storage.get<PersistedStorage>();
  69. persisted_storage.database.execute_statement(persisted_storage.statements.create_table, {}, {}, {});
  70. }
  71. CookieJar::CookieJar(TransientStorage storage)
  72. : m_storage(move(storage))
  73. {
  74. }
  75. String CookieJar::get_cookie(const URL::URL& url, Web::Cookie::Source source)
  76. {
  77. purge_expired_cookies();
  78. auto domain = canonicalize_domain(url);
  79. if (!domain.has_value())
  80. return {};
  81. auto cookie_list = get_matching_cookies(url, domain.value(), source);
  82. StringBuilder builder;
  83. for (auto const& cookie : cookie_list) {
  84. // If there is an unprocessed cookie in the cookie-list, output the characters %x3B and %x20 ("; ")
  85. if (!builder.is_empty())
  86. builder.append("; "sv);
  87. // Output the cookie's name, the %x3D ("=") character, and the cookie's value.
  88. builder.appendff("{}={}", cookie.name, cookie.value);
  89. }
  90. return MUST(builder.to_string());
  91. }
  92. void CookieJar::set_cookie(const URL::URL& url, Web::Cookie::ParsedCookie const& parsed_cookie, Web::Cookie::Source source)
  93. {
  94. auto domain = canonicalize_domain(url);
  95. if (!domain.has_value())
  96. return;
  97. store_cookie(parsed_cookie, url, domain.release_value(), source);
  98. }
  99. // This is based on https://www.rfc-editor.org/rfc/rfc6265#section-5.3 as store_cookie() below
  100. // however the whole ParsedCookie->Cookie conversion is skipped.
  101. void CookieJar::update_cookie(Web::Cookie::Cookie cookie)
  102. {
  103. select_cookie_from_database(
  104. move(cookie),
  105. // 11. If the cookie store contains a cookie with the same name, domain, and path as the newly created cookie:
  106. [this](auto& cookie, auto old_cookie) {
  107. // Update the creation-time of the newly created cookie to match the creation-time of the old-cookie.
  108. cookie.creation_time = old_cookie.creation_time;
  109. // Remove the old-cookie from the cookie store.
  110. // NOTE: Rather than deleting then re-inserting this cookie, we update it in-place.
  111. update_cookie_in_database(cookie);
  112. },
  113. // 12. Insert the newly created cookie into the cookie store.
  114. [this](auto cookie) {
  115. insert_cookie_into_database(cookie);
  116. });
  117. }
  118. void CookieJar::dump_cookies()
  119. {
  120. static constexpr auto key_color = "\033[34;1m"sv;
  121. static constexpr auto attribute_color = "\033[33m"sv;
  122. static constexpr auto no_color = "\033[0m"sv;
  123. StringBuilder builder;
  124. size_t total_cookies { 0 };
  125. select_all_cookies_from_database([&](auto cookie) {
  126. ++total_cookies;
  127. builder.appendff("{}{}{} - ", key_color, cookie.name, no_color);
  128. builder.appendff("{}{}{} - ", key_color, cookie.domain, no_color);
  129. builder.appendff("{}{}{}\n", key_color, cookie.path, no_color);
  130. builder.appendff("\t{}Value{} = {}\n", attribute_color, no_color, cookie.value);
  131. builder.appendff("\t{}CreationTime{} = {}\n", attribute_color, no_color, cookie.creation_time_to_string());
  132. builder.appendff("\t{}LastAccessTime{} = {}\n", attribute_color, no_color, cookie.last_access_time_to_string());
  133. builder.appendff("\t{}ExpiryTime{} = {}\n", attribute_color, no_color, cookie.expiry_time_to_string());
  134. builder.appendff("\t{}Secure{} = {:s}\n", attribute_color, no_color, cookie.secure);
  135. builder.appendff("\t{}HttpOnly{} = {:s}\n", attribute_color, no_color, cookie.http_only);
  136. builder.appendff("\t{}HostOnly{} = {:s}\n", attribute_color, no_color, cookie.host_only);
  137. builder.appendff("\t{}Persistent{} = {:s}\n", attribute_color, no_color, cookie.persistent);
  138. builder.appendff("\t{}SameSite{} = {:s}\n", attribute_color, no_color, Web::Cookie::same_site_to_string(cookie.same_site));
  139. });
  140. dbgln("{} cookies stored\n{}", total_cookies, builder.string_view());
  141. }
  142. Vector<Web::Cookie::Cookie> CookieJar::get_all_cookies()
  143. {
  144. Vector<Web::Cookie::Cookie> cookies;
  145. select_all_cookies_from_database([&](auto cookie) {
  146. cookies.append(move(cookie));
  147. });
  148. return cookies;
  149. }
  150. // https://w3c.github.io/webdriver/#dfn-associated-cookies
  151. Vector<Web::Cookie::Cookie> CookieJar::get_all_cookies(URL::URL const& url)
  152. {
  153. auto domain = canonicalize_domain(url);
  154. if (!domain.has_value())
  155. return {};
  156. return get_matching_cookies(url, domain.value(), Web::Cookie::Source::Http, MatchingCookiesSpecMode::WebDriver);
  157. }
  158. Optional<Web::Cookie::Cookie> CookieJar::get_named_cookie(URL::URL const& url, StringView name)
  159. {
  160. auto domain = canonicalize_domain(url);
  161. if (!domain.has_value())
  162. return {};
  163. auto cookie_list = get_matching_cookies(url, domain.value(), Web::Cookie::Source::Http, MatchingCookiesSpecMode::WebDriver);
  164. for (auto const& cookie : cookie_list) {
  165. if (cookie.name == name)
  166. return cookie;
  167. }
  168. return {};
  169. }
  170. Optional<String> CookieJar::canonicalize_domain(const URL::URL& url)
  171. {
  172. // https://tools.ietf.org/html/rfc6265#section-5.1.2
  173. if (!url.is_valid())
  174. return {};
  175. // FIXME: Implement RFC 5890 to "Convert each label that is not a Non-Reserved LDH (NR-LDH) label to an A-label".
  176. if (url.host().has<Empty>())
  177. return {};
  178. return MUST(MUST(url.serialized_host()).to_lowercase());
  179. }
  180. bool CookieJar::domain_matches(StringView string, StringView domain_string)
  181. {
  182. // https://tools.ietf.org/html/rfc6265#section-5.1.3
  183. // A string domain-matches a given domain string if at least one of the following conditions hold:
  184. // The domain string and the string are identical.
  185. if (string == domain_string)
  186. return true;
  187. // All of the following conditions hold:
  188. // - The domain string is a suffix of the string.
  189. // - The last character of the string that is not included in the domain string is a %x2E (".") character.
  190. // - The string is a host name (i.e., not an IP address).
  191. if (!string.ends_with(domain_string))
  192. return false;
  193. if (string[string.length() - domain_string.length() - 1] != '.')
  194. return false;
  195. if (AK::IPv4Address::from_string(string).has_value())
  196. return false;
  197. return true;
  198. }
  199. bool CookieJar::path_matches(StringView request_path, StringView cookie_path)
  200. {
  201. // https://tools.ietf.org/html/rfc6265#section-5.1.4
  202. // A request-path path-matches a given cookie-path if at least one of the following conditions holds:
  203. // The cookie-path and the request-path are identical.
  204. if (request_path == cookie_path)
  205. return true;
  206. if (request_path.starts_with(cookie_path)) {
  207. // The cookie-path is a prefix of the request-path, and the last character of the cookie-path is %x2F ("/").
  208. if (cookie_path.ends_with('/'))
  209. return true;
  210. // 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.
  211. if (request_path[cookie_path.length()] == '/')
  212. return true;
  213. }
  214. return false;
  215. }
  216. String CookieJar::default_path(const URL::URL& url)
  217. {
  218. // https://tools.ietf.org/html/rfc6265#section-5.1.4
  219. // 1. Let uri-path be the path portion of the request-uri if such a portion exists (and empty otherwise).
  220. auto uri_path = url.serialize_path();
  221. // 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.
  222. if (uri_path.is_empty() || (uri_path[0] != '/'))
  223. return "/"_string;
  224. StringView uri_path_view = uri_path;
  225. size_t last_separator = uri_path_view.find_last('/').value();
  226. // 3. If the uri-path contains no more than one %x2F ("/") character, output %x2F ("/") and skip the remaining step.
  227. if (last_separator == 0)
  228. return "/"_string;
  229. // 4. Output the characters of the uri-path from the first character up to, but not including, the right-most %x2F ("/").
  230. return MUST(String::from_utf8(uri_path.substring_view(0, last_separator)));
  231. }
  232. void CookieJar::store_cookie(Web::Cookie::ParsedCookie const& parsed_cookie, const URL::URL& url, String canonicalized_domain, Web::Cookie::Source source)
  233. {
  234. // https://tools.ietf.org/html/rfc6265#section-5.3
  235. // 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.
  236. Web::Cookie::Cookie cookie { parsed_cookie.name, parsed_cookie.value, parsed_cookie.same_site_attribute };
  237. cookie.creation_time = UnixDateTime::now();
  238. cookie.last_access_time = cookie.creation_time;
  239. if (parsed_cookie.expiry_time_from_max_age_attribute.has_value()) {
  240. // 3. If the cookie-attribute-list contains an attribute with an attribute-name of "Max-Age": Set the cookie's persistent-flag to true.
  241. // 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".
  242. cookie.persistent = true;
  243. cookie.expiry_time = parsed_cookie.expiry_time_from_max_age_attribute.value();
  244. } else if (parsed_cookie.expiry_time_from_expires_attribute.has_value()) {
  245. // If the cookie-attribute-list contains an attribute with an attribute-name of "Expires": Set the cookie's persistent-flag to true.
  246. // Set the cookie's expiry-time to attribute-value of the last attribute in the cookie-attribute-list with an attribute-name of "Expires".
  247. cookie.persistent = true;
  248. cookie.expiry_time = parsed_cookie.expiry_time_from_expires_attribute.value();
  249. } else {
  250. // Set the cookie's persistent-flag to false. Set the cookie's expiry-time to the latest representable date.
  251. cookie.persistent = false;
  252. cookie.expiry_time = UnixDateTime::latest();
  253. }
  254. // 4. If the cookie-attribute-list contains an attribute with an attribute-name of "Domain":
  255. if (parsed_cookie.domain.has_value()) {
  256. // Let the domain-attribute be the attribute-value of the last attribute in the cookie-attribute-list with an attribute-name of "Domain".
  257. cookie.domain = parsed_cookie.domain.value();
  258. }
  259. // 5. If the user agent is configured to reject "public suffixes" and the domain-attribute is a public suffix:
  260. if (is_public_suffix(cookie.domain)) {
  261. // If the domain-attribute is identical to the canonicalized request-host:
  262. if (cookie.domain == canonicalized_domain) {
  263. // Let the domain-attribute be the empty string.
  264. cookie.domain = String {};
  265. }
  266. // Otherwise:
  267. else {
  268. // Ignore the cookie entirely and abort these steps.
  269. return;
  270. }
  271. }
  272. // 6. If the domain-attribute is non-empty:
  273. if (!cookie.domain.is_empty()) {
  274. // If the canonicalized request-host does not domain-match the domain-attribute: Ignore the cookie entirely and abort these steps.
  275. if (!domain_matches(canonicalized_domain, cookie.domain))
  276. return;
  277. // Set the cookie's host-only-flag to false. Set the cookie's domain to the domain-attribute.
  278. cookie.host_only = false;
  279. } else {
  280. // Set the cookie's host-only-flag to true. Set the cookie's domain to the canonicalized request-host.
  281. cookie.host_only = true;
  282. cookie.domain = move(canonicalized_domain);
  283. }
  284. // 7. If the cookie-attribute-list contains an attribute with an attribute-name of "Path":
  285. if (parsed_cookie.path.has_value()) {
  286. // Set the cookie's path to attribute-value of the last attribute in the cookie-attribute-list with an attribute-name of "Path".
  287. cookie.path = parsed_cookie.path.value();
  288. } else {
  289. cookie.path = default_path(url);
  290. }
  291. // 8. If the cookie-attribute-list contains an attribute with an attribute-name of "Secure", set the cookie's secure-only-flag to true.
  292. cookie.secure = parsed_cookie.secure_attribute_present;
  293. // 9. If the cookie-attribute-list contains an attribute with an attribute-name of "HttpOnly", set the cookie's http-only-flag to false.
  294. cookie.http_only = parsed_cookie.http_only_attribute_present;
  295. // 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.
  296. if (source != Web::Cookie::Source::Http && cookie.http_only)
  297. return;
  298. // Synchronize persisting the cookie
  299. auto sync_promise = Core::Promise<Empty>::construct();
  300. select_cookie_from_database(
  301. move(cookie),
  302. // 11. If the cookie store contains a cookie with the same name, domain, and path as the newly created cookie:
  303. [this, source, sync_promise](auto& cookie, auto old_cookie) {
  304. ScopeGuard guard { [&]() { sync_promise->resolve({}); } };
  305. // If the newly created cookie was received from a "non-HTTP" API and the old-cookie's http-only-flag is set, abort these
  306. // steps and ignore the newly created cookie entirely.
  307. if (source != Web::Cookie::Source::Http && old_cookie.http_only)
  308. return;
  309. // Update the creation-time of the newly created cookie to match the creation-time of the old-cookie.
  310. cookie.creation_time = old_cookie.creation_time;
  311. // Remove the old-cookie from the cookie store.
  312. // NOTE: Rather than deleting then re-inserting this cookie, we update it in-place.
  313. update_cookie_in_database(cookie);
  314. },
  315. // 12. Insert the newly created cookie into the cookie store.
  316. [this, sync_promise](auto cookie) {
  317. insert_cookie_into_database(cookie);
  318. sync_promise->resolve({});
  319. });
  320. MUST(sync_promise->await());
  321. }
  322. Vector<Web::Cookie::Cookie> CookieJar::get_matching_cookies(const URL::URL& url, StringView canonicalized_domain, Web::Cookie::Source source, MatchingCookiesSpecMode mode)
  323. {
  324. // https://tools.ietf.org/html/rfc6265#section-5.4
  325. // 1. Let cookie-list be the set of cookies from the cookie store that meets all of the following requirements:
  326. Vector<Web::Cookie::Cookie> cookie_list;
  327. select_all_cookies_from_database([&](auto cookie) {
  328. // Either: The cookie's host-only-flag is true and the canonicalized request-host is identical to the cookie's domain.
  329. // Or: The cookie's host-only-flag is false and the canonicalized request-host domain-matches the cookie's domain.
  330. bool is_host_only_and_has_identical_domain = cookie.host_only && (canonicalized_domain == cookie.domain);
  331. bool is_not_host_only_and_domain_matches = !cookie.host_only && domain_matches(canonicalized_domain, cookie.domain);
  332. if (!is_host_only_and_has_identical_domain && !is_not_host_only_and_domain_matches)
  333. return;
  334. // The request-uri's path path-matches the cookie's path.
  335. if (!path_matches(url.serialize_path(), cookie.path))
  336. return;
  337. // If the cookie's secure-only-flag is true, then the request-uri's scheme must denote a "secure" protocol.
  338. if (cookie.secure && (url.scheme() != "https"))
  339. return;
  340. // 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.
  341. if (cookie.http_only && (source != Web::Cookie::Source::Http))
  342. return;
  343. // NOTE: The WebDriver spec expects only step 1 above to be executed to match cookies.
  344. if (mode == MatchingCookiesSpecMode::WebDriver) {
  345. cookie_list.append(move(cookie));
  346. return;
  347. }
  348. // 2. The user agent SHOULD sort the cookie-list in the following order:
  349. // - Cookies with longer paths are listed before cookies with shorter paths.
  350. // - Among cookies that have equal-length path fields, cookies with earlier creation-times are listed before cookies with later creation-times.
  351. auto cookie_path_length = cookie.path.bytes().size();
  352. auto cookie_creation_time = cookie.creation_time;
  353. cookie_list.insert_before_matching(move(cookie), [cookie_path_length, cookie_creation_time](auto const& entry) {
  354. if (cookie_path_length > entry.path.bytes().size()) {
  355. return true;
  356. } else if (cookie_path_length == entry.path.bytes().size()) {
  357. if (cookie_creation_time < entry.creation_time)
  358. return true;
  359. }
  360. return false;
  361. });
  362. });
  363. // NOTE: The WebDriver spec expects only step 1 above to be executed to match cookies.
  364. if (mode == MatchingCookiesSpecMode::WebDriver)
  365. return cookie_list;
  366. // 3. Update the last-access-time of each cookie in the cookie-list to the current date and time.
  367. auto now = UnixDateTime::now();
  368. for (auto& cookie : cookie_list) {
  369. cookie.last_access_time = now;
  370. update_cookie_last_access_time_in_database(cookie);
  371. }
  372. 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::insert_cookie_into_database(Web::Cookie::Cookie const& cookie)
  427. {
  428. m_storage.visit(
  429. [&](PersistedStorage& storage) {
  430. storage.database.execute_statement(
  431. storage.statements.insert_cookie, {}, [this]() { purge_expired_cookies(); }, {},
  432. cookie.name,
  433. cookie.value,
  434. to_underlying(cookie.same_site),
  435. cookie.creation_time,
  436. cookie.last_access_time,
  437. cookie.expiry_time,
  438. cookie.domain,
  439. cookie.path,
  440. cookie.secure,
  441. cookie.http_only,
  442. cookie.host_only,
  443. cookie.persistent);
  444. },
  445. [&](TransientStorage& storage) {
  446. CookieStorageKey key { cookie.name, cookie.domain, cookie.path };
  447. storage.set(key, cookie);
  448. });
  449. }
  450. void CookieJar::update_cookie_in_database(Web::Cookie::Cookie const& cookie)
  451. {
  452. m_storage.visit(
  453. [&](PersistedStorage& storage) {
  454. storage.database.execute_statement(
  455. storage.statements.update_cookie, {}, [this]() { purge_expired_cookies(); }, {},
  456. cookie.value,
  457. to_underlying(cookie.same_site),
  458. cookie.creation_time,
  459. cookie.last_access_time,
  460. cookie.expiry_time,
  461. cookie.secure,
  462. cookie.http_only,
  463. cookie.host_only,
  464. cookie.persistent,
  465. cookie.name,
  466. cookie.domain,
  467. cookie.path);
  468. },
  469. [&](TransientStorage& storage) {
  470. CookieStorageKey key { cookie.name, cookie.domain, cookie.path };
  471. storage.set(key, cookie);
  472. });
  473. }
  474. void CookieJar::update_cookie_last_access_time_in_database(Web::Cookie::Cookie const& cookie)
  475. {
  476. m_storage.visit(
  477. [&](PersistedStorage& storage) {
  478. storage.database.execute_statement(
  479. storage.statements.update_cookie_last_access_time,
  480. {}, {}, {},
  481. cookie.last_access_time,
  482. cookie.name,
  483. cookie.domain,
  484. cookie.path);
  485. },
  486. [&](TransientStorage& storage) {
  487. CookieStorageKey key { cookie.name, cookie.domain, cookie.path };
  488. storage.set(key, cookie);
  489. });
  490. }
  491. struct WrappedCookie : public RefCounted<WrappedCookie> {
  492. explicit WrappedCookie(Web::Cookie::Cookie cookie_)
  493. : RefCounted()
  494. , cookie(move(cookie_))
  495. {
  496. }
  497. Web::Cookie::Cookie cookie;
  498. bool had_any_results { false };
  499. };
  500. void CookieJar::select_cookie_from_database(Web::Cookie::Cookie cookie, OnCookieFound on_result, OnCookieNotFound on_complete_without_results)
  501. {
  502. m_storage.visit(
  503. [&](PersistedStorage& storage) {
  504. auto wrapped_cookie = make_ref_counted<WrappedCookie>(move(cookie));
  505. storage.database.execute_statement(
  506. storage.statements.select_cookie,
  507. [on_result = move(on_result), wrapped_cookie = wrapped_cookie](auto row) {
  508. if (auto selected_cookie = parse_cookie(row); selected_cookie.is_error())
  509. dbgln("Failed to parse cookie '{}': {}", selected_cookie.error(), row);
  510. else
  511. on_result(wrapped_cookie->cookie, selected_cookie.release_value());
  512. wrapped_cookie->had_any_results = true;
  513. },
  514. [on_complete_without_results = move(on_complete_without_results), wrapped_cookie = wrapped_cookie]() {
  515. if (!wrapped_cookie->had_any_results)
  516. on_complete_without_results(move(wrapped_cookie->cookie));
  517. },
  518. {},
  519. wrapped_cookie->cookie.name,
  520. wrapped_cookie->cookie.domain,
  521. wrapped_cookie->cookie.path);
  522. },
  523. [&](TransientStorage& storage) {
  524. CookieStorageKey key { cookie.name, cookie.domain, cookie.path };
  525. if (auto it = storage.find(key); it != storage.end())
  526. on_result(cookie, it->value);
  527. else
  528. on_complete_without_results(cookie);
  529. });
  530. }
  531. void CookieJar::select_all_cookies_from_database(OnSelectAllCookiesResult on_result)
  532. {
  533. // FIXME: Make surrounding APIs asynchronous.
  534. m_storage.visit(
  535. [&](PersistedStorage& storage) {
  536. storage.database.execute_statement(
  537. storage.statements.select_all_cookies,
  538. [on_result = move(on_result)](auto row) {
  539. if (auto cookie = parse_cookie(row); cookie.is_error())
  540. dbgln("Failed to parse cookie '{}': {}", cookie.error(), row);
  541. else
  542. on_result(cookie.release_value());
  543. },
  544. {},
  545. {});
  546. },
  547. [&](TransientStorage& storage) {
  548. for (auto const& cookie : storage)
  549. on_result(cookie.value);
  550. });
  551. }
  552. void CookieJar::purge_expired_cookies()
  553. {
  554. auto now = UnixDateTime::now();
  555. m_storage.visit(
  556. [&](PersistedStorage& storage) {
  557. storage.database.execute_statement(storage.statements.expire_cookie, {}, {}, {}, now);
  558. },
  559. [&](TransientStorage& storage) {
  560. Vector<CookieStorageKey> keys_to_evict;
  561. for (auto const& cookie : storage) {
  562. if (cookie.value.expiry_time < now)
  563. keys_to_evict.append(cookie.key);
  564. }
  565. for (auto const& key : keys_to_evict)
  566. storage.remove(key);
  567. });
  568. }
  569. }