CookieJar.cpp 26 KB

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