CookieJar.cpp 27 KB

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