• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "net/extras/sqlite/sqlite_persistent_cookie_store.h"
6 
7 #include <iterator>
8 #include <map>
9 #include <memory>
10 #include <set>
11 #include <tuple>
12 #include <unordered_set>
13 
14 #include "base/feature_list.h"
15 #include "base/files/file_path.h"
16 #include "base/files/file_util.h"
17 #include "base/functional/bind.h"
18 #include "base/functional/callback.h"
19 #include "base/location.h"
20 #include "base/logging.h"
21 #include "base/memory/raw_ptr.h"
22 #include "base/memory/ref_counted.h"
23 #include "base/metrics/histogram_functions.h"
24 #include "base/metrics/histogram_macros.h"
25 #include "base/strings/string_util.h"
26 #include "base/strings/stringprintf.h"
27 #include "base/synchronization/lock.h"
28 #include "base/task/sequenced_task_runner.h"
29 #include "base/thread_annotations.h"
30 #include "base/time/time.h"
31 #include "base/types/optional_ref.h"
32 #include "base/values.h"
33 #include "build/build_config.h"
34 #include "net/cookies/canonical_cookie.h"
35 #include "net/cookies/cookie_constants.h"
36 #include "net/cookies/cookie_util.h"
37 #include "net/extras/sqlite/cookie_crypto_delegate.h"
38 #include "net/extras/sqlite/sqlite_persistent_store_backend_base.h"
39 #include "net/log/net_log.h"
40 #include "net/log/net_log_values.h"
41 #include "sql/error_delegate_util.h"
42 #include "sql/meta_table.h"
43 #include "sql/statement.h"
44 #include "sql/transaction.h"
45 #include "third_party/abseil-cpp/absl/types/optional.h"
46 #include "url/gurl.h"
47 #include "url/third_party/mozilla/url_parse.h"
48 
49 using base::Time;
50 
51 namespace {
52 
CookieKeyedLoadNetLogParams(const std::string & key,net::NetLogCaptureMode capture_mode)53 base::Value::Dict CookieKeyedLoadNetLogParams(
54     const std::string& key,
55     net::NetLogCaptureMode capture_mode) {
56   if (!net::NetLogCaptureIncludesSensitive(capture_mode))
57     return base::Value::Dict();
58   base::Value::Dict dict;
59   dict.Set("key", key);
60   return dict;
61 }
62 
63 // Used to populate a histogram for problems when loading cookies.
64 //
65 // Please do not reorder or remove entries. New entries must be added to the
66 // end of the list, just before COOKIE_LOAD_PROBLEM_LAST_ENTRY.
67 enum CookieLoadProblem {
68   COOKIE_LOAD_PROBLEM_DECRYPT_FAILED = 0,
69   // Deprecated 03/2021.
70   // COOKIE_LOAD_PROBLEM_DECRYPT_TIMEOUT = 1,
71   COOKIE_LOAD_PROBLEM_NON_CANONICAL = 2,
72   COOKIE_LOAD_PROBLEM_OPEN_DB = 3,
73   COOKIE_LOAD_PROBLEM_RECOVERY_FAILED = 4,
74   COOKIE_LOAD_DELETE_COOKIE_PARTITION_FAILED = 5,
75   COOKIE_LOAD_PROBLEM_LAST_ENTRY
76 };
77 
78 // Used to populate a histogram for problems when committing cookies.
79 //
80 // Please do not reorder or remove entries. New entries must be added to the
81 // end of the list, just before COOKIE_COMMIT_PROBLEM_LAST_ENTRY.
82 enum CookieCommitProblem {
83   COOKIE_COMMIT_PROBLEM_ENCRYPT_FAILED = 0,
84   COOKIE_COMMIT_PROBLEM_ADD = 1,
85   COOKIE_COMMIT_PROBLEM_UPDATE_ACCESS = 2,
86   COOKIE_COMMIT_PROBLEM_DELETE = 3,
87   COOKIE_COMMIT_PROBLEM_TRANSACTION_COMMIT = 4,
88   COOKIE_COMMIT_PROBLEM_LAST_ENTRY
89 };
90 
RecordCookieLoadProblem(CookieLoadProblem event)91 void RecordCookieLoadProblem(CookieLoadProblem event) {
92   UMA_HISTOGRAM_ENUMERATION("Cookie.LoadProblem", event,
93                             COOKIE_LOAD_PROBLEM_LAST_ENTRY);
94 }
95 
RecordCookieCommitProblem(CookieCommitProblem event)96 void RecordCookieCommitProblem(CookieCommitProblem event) {
97   UMA_HISTOGRAM_ENUMERATION("Cookie.CommitProblem", event,
98                             COOKIE_COMMIT_PROBLEM_LAST_ENTRY);
99 }
100 
101 }  // namespace
102 
103 namespace net {
104 
GetCookieStoreBackgroundSequencePriority()105 base::TaskPriority GetCookieStoreBackgroundSequencePriority() {
106   return base::TaskPriority::USER_BLOCKING;
107 }
108 
109 namespace {
110 
111 // Version number of the database.
112 //
113 // Version 21 - 2023/11/22 - https://crrev.com/c/5049032
114 // Version 20 - 2023/11/14 - https://crrev.com/c/5030577
115 // Version 19 - 2023/09/22 - https://crrev.com/c/4704672
116 // Version 18 - 2022/04/19 - https://crrev.com/c/3594203
117 // Version 17 - 2022/01/25 - https://crrev.com/c/3416230
118 // Version 16 - 2021/09/10 - https://crrev.com/c/3152897
119 // Version 15 - 2021/07/01 - https://crrev.com/c/3001822
120 //
121 // Versions older than two years should be removed and marked as unsupported.
122 // This was last done August 1, 2023. https://crrev.com/c/4701765
123 // Be sure to update SQLitePersistentCookieStoreTest.TestInvalidVersionRecovery
124 // to test the latest unsupported version number.
125 //
126 // Unsupported versions:
127 // Version 14 - 2021/02/23 - https://crrev.com/c/2036899
128 // Version 13 - 2020/10/28 - https://crrev.com/c/2505468
129 // Version 12 - 2019/11/20 - https://crrev.com/c/1898301
130 // Version 11 - 2019/04/17 - https://crrev.com/c/1570416
131 // Version 10 - 2018/02/13 - https://crrev.com/c/906675
132 // Version 9  - 2015/04/17 - https://codereview.chromium.org/1083623003
133 // Version 8  - 2015/02/23 - https://codereview.chromium.org/876973003
134 // Version 7  - 2013/12/16 - https://codereview.chromium.org/24734007
135 // Version 6  - 2013/04/23 - https://codereview.chromium.org/14208017
136 // Version 5  - 2011/12/05 - https://codereview.chromium.org/8533013
137 // Version 4  - 2009/09/01 - https://codereview.chromium.org/183021
138 //
139 // Version 21 removes the is_same_party column.
140 //
141 // Version 20 changes the UNIQUE constraint to include the source_scheme and
142 // source_port and begins to insert, update, and delete cookies based on their
143 // source_scheme and source_port.
144 //
145 // Version 19 caps expires_utc to no more than 400 days in the future for all
146 // stored cookies with has_expires. This is in compliance with section 7.2 of
147 // draft-ietf-httpbis-rfc6265bis-12.
148 //
149 // Version 18 adds one new field: "last_update_utc" (if not 0 this represents
150 // the last time the cookie was updated). This is distinct from creation_utc
151 // which is carried forward when cookies are updated.
152 //
153 // Version 17 fixes crbug.com/1290841: Bug in V16 migration.
154 //
155 // Version 16 changes the unique constraint's order of columns to have
156 // top_frame_site_key be after host_key. This allows us to use the internal
157 // index created by the UNIQUE keyword without to load cookies by domain
158 // without us needing to supply a top_frame_site_key. This is necessary because
159 // CookieMonster tracks pending cookie loading tasks by host key only.
160 // Version 16 also removes the DEFAULT value from several columns.
161 //
162 // Version 15 adds one new field: "top_frame_site_key" (if not empty then the
163 // string is the scheme and site of the topmost-level frame the cookie was
164 // created in). This field is deserialized into the cookie's partition key.
165 // top_frame_site_key is *NOT* the site-for-cookies when the cookie was created.
166 // In migrating, top_frame_site_key defaults to empty string. This change also
167 // changes the uniqueness constraint on cookies to include the
168 // top_frame_site_key as well.
169 //
170 // Version 14 just reads all encrypted cookies and re-writes them out again to
171 // make sure the new encryption key is in use. This active migration only
172 // happens on Windows, on other OS, this migration is a no-op.
173 //
174 // Version 13 adds two new fields: "source_port" (the port number of the source
175 // origin, and "is_same_party" (boolean indicating whether the cookie had a
176 // SameParty attribute). In migrating, source_port defaults to -1
177 // (url::PORT_UNSPECIFIED) for old entries for which the source port is unknown,
178 // and is_same_party defaults to false.
179 //
180 // Version 12 adds a column for "source_scheme" to store whether the
181 // cookie was set from a URL with a cryptographic scheme.
182 //
183 // Version 11 renames the "firstpartyonly" column to "samesite", and changes any
184 // stored values of kCookieSameSiteNoRestriction into
185 // kCookieSameSiteUnspecified to reflect the fact that those cookies were set
186 // without a SameSite attribute specified. Support for a value of
187 // kCookieSameSiteExtended for "samesite" was added, however, that value is now
188 // deprecated and is mapped to CookieSameSite::UNSPECIFIED when loading from the
189 // database.
190 //
191 // Version 10 removes the uniqueness constraint on the creation time (which
192 // was not propagated up the stack and caused problems in
193 // http://crbug.com/800414 and others).  It replaces that constraint by a
194 // constraint on (name, domain, path), which is spec-compliant (see
195 // https://tools.ietf.org/html/rfc6265#section-5.3 step 11).  Those fields
196 // can then be used in place of the creation time for updating access
197 // time and deleting cookies.
198 // Version 10 also marks all booleans in the store with an "is_" prefix
199 // to indicated their booleanness, as SQLite has no such concept.
200 //
201 // Version 9 adds a partial index to track non-persistent cookies.
202 // Non-persistent cookies sometimes need to be deleted on startup. There are
203 // frequently few or no non-persistent cookies, so the partial index allows the
204 // deletion to be sped up or skipped, without having to page in the DB.
205 //
206 // Version 8 adds "first-party only" cookies.
207 //
208 // Version 7 adds encrypted values.  Old values will continue to be used but
209 // all new values written will be encrypted on selected operating systems.  New
210 // records read by old clients will simply get an empty cookie value while old
211 // records read by new clients will continue to operate with the unencrypted
212 // version.  New and old clients alike will always write/update records with
213 // what they support.
214 //
215 // Version 6 adds cookie priorities. This allows developers to influence the
216 // order in which cookies are evicted in order to meet domain cookie limits.
217 //
218 // Version 5 adds the columns has_expires and is_persistent, so that the
219 // database can store session cookies as well as persistent cookies. Databases
220 // of version 5 are incompatible with older versions of code. If a database of
221 // version 5 is read by older code, session cookies will be treated as normal
222 // cookies. Currently, these fields are written, but not read anymore.
223 //
224 // In version 4, we migrated the time epoch.  If you open the DB with an older
225 // version on Mac or Linux, the times will look wonky, but the file will likely
226 // be usable. On Windows version 3 and 4 are the same.
227 //
228 // Version 3 updated the database to include the last access time, so we can
229 // expire them in decreasing order of use when we've reached the maximum
230 // number of cookies.
231 const int kCurrentVersionNumber = 21;
232 const int kCompatibleVersionNumber = 21;
233 
234 }  // namespace
235 
236 // This class is designed to be shared between any client thread and the
237 // background task runner. It batches operations and commits them on a timer.
238 //
239 // SQLitePersistentCookieStore::Load is called to load all cookies.  It
240 // delegates to Backend::Load, which posts a Backend::LoadAndNotifyOnDBThread
241 // task to the background runner.  This task calls Backend::ChainLoadCookies(),
242 // which repeatedly posts itself to the BG runner to load each eTLD+1's cookies
243 // in separate tasks.  When this is complete, Backend::CompleteLoadOnIOThread is
244 // posted to the client runner, which notifies the caller of
245 // SQLitePersistentCookieStore::Load that the load is complete.
246 //
247 // If a priority load request is invoked via SQLitePersistentCookieStore::
248 // LoadCookiesForKey, it is delegated to Backend::LoadCookiesForKey, which posts
249 // Backend::LoadKeyAndNotifyOnDBThread to the BG runner. That routine loads just
250 // that single domain key (eTLD+1)'s cookies, and posts a Backend::
251 // CompleteLoadForKeyOnIOThread to the client runner to notify the caller of
252 // SQLitePersistentCookieStore::LoadCookiesForKey that that load is complete.
253 //
254 // Subsequent to loading, mutations may be queued by any thread using
255 // AddCookie, UpdateCookieAccessTime, and DeleteCookie. These are flushed to
256 // disk on the BG runner every 30 seconds, 512 operations, or call to Flush(),
257 // whichever occurs first.
258 class SQLitePersistentCookieStore::Backend
259     : public SQLitePersistentStoreBackendBase {
260  public:
Backend(const base::FilePath & path,scoped_refptr<base::SequencedTaskRunner> client_task_runner,scoped_refptr<base::SequencedTaskRunner> background_task_runner,bool restore_old_session_cookies,CookieCryptoDelegate * crypto_delegate,bool enable_exclusive_access)261   Backend(const base::FilePath& path,
262           scoped_refptr<base::SequencedTaskRunner> client_task_runner,
263           scoped_refptr<base::SequencedTaskRunner> background_task_runner,
264           bool restore_old_session_cookies,
265           CookieCryptoDelegate* crypto_delegate,
266           bool enable_exclusive_access)
267       : SQLitePersistentStoreBackendBase(path,
268                                          /* histogram_tag = */ "Cookie",
269                                          kCurrentVersionNumber,
270                                          kCompatibleVersionNumber,
271                                          std::move(background_task_runner),
272                                          std::move(client_task_runner),
273                                          enable_exclusive_access),
274         restore_old_session_cookies_(restore_old_session_cookies),
275         crypto_(crypto_delegate) {}
276 
277   Backend(const Backend&) = delete;
278   Backend& operator=(const Backend&) = delete;
279 
280   // Creates or loads the SQLite database.
281   void Load(LoadedCallback loaded_callback);
282 
283   // Loads cookies for the domain key (eTLD+1). If no key is supplied then this
284   // behaves identically to `Load`.
285   void LoadCookiesForKey(base::optional_ref<const std::string> key,
286                          LoadedCallback loaded_callback);
287 
288   // Steps through all results of |statement|, makes a cookie from each, and
289   // adds the cookie to |cookies|. Returns true if everything loaded
290   // successfully.
291   bool MakeCookiesFromSQLStatement(
292       std::vector<std::unique_ptr<CanonicalCookie>>& cookies,
293       sql::Statement& statement,
294       std::unordered_set<std::string>& top_frame_site_keys_to_delete);
295 
296   // Batch a cookie addition.
297   void AddCookie(const CanonicalCookie& cc);
298 
299   // Batch a cookie access time update.
300   void UpdateCookieAccessTime(const CanonicalCookie& cc);
301 
302   // Batch a cookie deletion.
303   void DeleteCookie(const CanonicalCookie& cc);
304 
305   size_t GetQueueLengthForTesting();
306 
307   // Post background delete of all cookies that match |cookies|.
308   void DeleteAllInList(const std::list<CookieOrigin>& cookies);
309 
310  private:
311   // You should call Close() before destructing this object.
~Backend()312   ~Backend() override {
313     DCHECK_EQ(0u, num_pending_);
314     DCHECK(pending_.empty());
315   }
316 
317   // Database upgrade statements.
318   absl::optional<int> DoMigrateDatabaseSchema() override;
319 
320   class PendingOperation {
321    public:
322     enum OperationType {
323       COOKIE_ADD,
324       COOKIE_UPDATEACCESS,
325       COOKIE_DELETE,
326     };
327 
PendingOperation(OperationType op,const CanonicalCookie & cc)328     PendingOperation(OperationType op, const CanonicalCookie& cc)
329         : op_(op), cc_(cc) {}
330 
op() const331     OperationType op() const { return op_; }
cc() const332     const CanonicalCookie& cc() const { return cc_; }
333 
334    private:
335     OperationType op_;
336     CanonicalCookie cc_;
337   };
338 
339  private:
340   // Creates or loads the SQLite database on background runner. Supply domain
341   // key (eTLD+1) to only load for this domain.
342   void LoadAndNotifyInBackground(base::optional_ref<const std::string> key,
343                                  LoadedCallback loaded_callback);
344 
345   // Notifies the CookieMonster when loading completes for a specific domain key
346   // or for all domain keys. Triggers the callback and passes it all cookies
347   // that have been loaded from DB since last IO notification.
348   void NotifyLoadCompleteInForeground(LoadedCallback loaded_callback,
349                                       bool load_success);
350 
351   // Called from Load when crypto gets obtained.
352   void CryptoHasInitFromLoad(base::optional_ref<const std::string> key,
353                              LoadedCallback loaded_callback);
354 
355   // Initialize the Cookies table.
356   bool CreateDatabaseSchema() override;
357 
358   // Initialize the data base.
359   bool DoInitializeDatabase() override;
360 
361   // Loads cookies for the next domain key from the DB, then either reschedules
362   // itself or schedules the provided callback to run on the client runner (if
363   // all domains are loaded).
364   void ChainLoadCookies(LoadedCallback loaded_callback);
365 
366   // Load all cookies for a set of domains/hosts. The error recovery code
367   // assumes |key| includes all related domains within an eTLD + 1.
368   bool LoadCookiesForDomains(const std::set<std::string>& key);
369 
370   void DeleteTopFrameSiteKeys(
371       const std::unordered_set<std::string>& top_frame_site_keys);
372 
373   // Batch a cookie operation (add or delete)
374   void BatchOperation(PendingOperation::OperationType op,
375                       const CanonicalCookie& cc);
376   // Commit our pending operations to the database.
377   void DoCommit() override;
378 
379   void DeleteSessionCookiesOnStartup();
380 
381   void BackgroundDeleteAllInList(const std::list<CookieOrigin>& cookies);
382 
383   // Shared code between the different load strategies to be used after all
384   // cookies have been loaded.
385   void FinishedLoadingCookies(LoadedCallback loaded_callback, bool success);
386 
RecordOpenDBProblem()387   void RecordOpenDBProblem() override {
388     RecordCookieLoadProblem(COOKIE_LOAD_PROBLEM_OPEN_DB);
389   }
390 
RecordDBMigrationProblem()391   void RecordDBMigrationProblem() override {
392     RecordCookieLoadProblem(COOKIE_LOAD_PROBLEM_OPEN_DB);
393   }
394 
395   typedef std::list<std::unique_ptr<PendingOperation>> PendingOperationsForKey;
396   typedef std::map<CanonicalCookie::StrictlyUniqueCookieKey,
397                    PendingOperationsForKey>
398       PendingOperationsMap;
399   PendingOperationsMap pending_ GUARDED_BY(lock_);
400   PendingOperationsMap::size_type num_pending_ GUARDED_BY(lock_) = 0;
401   // Guard |cookies_|, |pending_|, |num_pending_|.
402   base::Lock lock_;
403 
404   // Temporary buffer for cookies loaded from DB. Accumulates cookies to reduce
405   // the number of messages sent to the client runner. Sent back in response to
406   // individual load requests for domain keys or when all loading completes.
407   std::vector<std::unique_ptr<CanonicalCookie>> cookies_ GUARDED_BY(lock_);
408 
409   // Map of domain keys(eTLD+1) to domains/hosts that are to be loaded from DB.
410   std::map<std::string, std::set<std::string>> keys_to_load_;
411 
412   // If false, we should filter out session cookies when reading the DB.
413   bool restore_old_session_cookies_;
414 
415   // Not owned.
416   raw_ptr<CookieCryptoDelegate, DanglingUntriaged> crypto_;
417 };
418 
419 namespace {
420 
421 // Possible values for the 'priority' column.
422 enum DBCookiePriority {
423   kCookiePriorityLow = 0,
424   kCookiePriorityMedium = 1,
425   kCookiePriorityHigh = 2,
426 };
427 
CookiePriorityToDBCookiePriority(CookiePriority value)428 DBCookiePriority CookiePriorityToDBCookiePriority(CookiePriority value) {
429   switch (value) {
430     case COOKIE_PRIORITY_LOW:
431       return kCookiePriorityLow;
432     case COOKIE_PRIORITY_MEDIUM:
433       return kCookiePriorityMedium;
434     case COOKIE_PRIORITY_HIGH:
435       return kCookiePriorityHigh;
436   }
437 
438   NOTREACHED();
439   return kCookiePriorityMedium;
440 }
441 
DBCookiePriorityToCookiePriority(DBCookiePriority value)442 CookiePriority DBCookiePriorityToCookiePriority(DBCookiePriority value) {
443   switch (value) {
444     case kCookiePriorityLow:
445       return COOKIE_PRIORITY_LOW;
446     case kCookiePriorityMedium:
447       return COOKIE_PRIORITY_MEDIUM;
448     case kCookiePriorityHigh:
449       return COOKIE_PRIORITY_HIGH;
450   }
451 
452   NOTREACHED();
453   return COOKIE_PRIORITY_DEFAULT;
454 }
455 
456 // Possible values for the 'samesite' column
457 enum DBCookieSameSite {
458   kCookieSameSiteUnspecified = -1,
459   kCookieSameSiteNoRestriction = 0,
460   kCookieSameSiteLax = 1,
461   kCookieSameSiteStrict = 2,
462   // Deprecated, mapped to kCookieSameSiteUnspecified.
463   kCookieSameSiteExtended = 3
464 };
465 
CookieSameSiteToDBCookieSameSite(CookieSameSite value)466 DBCookieSameSite CookieSameSiteToDBCookieSameSite(CookieSameSite value) {
467   switch (value) {
468     case CookieSameSite::NO_RESTRICTION:
469       return kCookieSameSiteNoRestriction;
470     case CookieSameSite::LAX_MODE:
471       return kCookieSameSiteLax;
472     case CookieSameSite::STRICT_MODE:
473       return kCookieSameSiteStrict;
474     case CookieSameSite::UNSPECIFIED:
475       return kCookieSameSiteUnspecified;
476   }
477 }
478 
DBCookieSameSiteToCookieSameSite(DBCookieSameSite value)479 CookieSameSite DBCookieSameSiteToCookieSameSite(DBCookieSameSite value) {
480   CookieSameSite samesite = CookieSameSite::UNSPECIFIED;
481   switch (value) {
482     case kCookieSameSiteNoRestriction:
483       samesite = CookieSameSite::NO_RESTRICTION;
484       break;
485     case kCookieSameSiteLax:
486       samesite = CookieSameSite::LAX_MODE;
487       break;
488     case kCookieSameSiteStrict:
489       samesite = CookieSameSite::STRICT_MODE;
490       break;
491     // SameSite=Extended is deprecated, so we map to UNSPECIFIED.
492     case kCookieSameSiteExtended:
493     case kCookieSameSiteUnspecified:
494       samesite = CookieSameSite::UNSPECIFIED;
495       break;
496   }
497   return samesite;
498 }
499 
DBToCookieSourceScheme(int value)500 CookieSourceScheme DBToCookieSourceScheme(int value) {
501   int enum_max_value = static_cast<int>(CookieSourceScheme::kMaxValue);
502 
503   if (value < 0 || value > enum_max_value) {
504     DLOG(WARNING) << "DB read of cookie's source scheme is invalid. Resetting "
505                      "value to unset.";
506     value = static_cast<int>(
507         CookieSourceScheme::kUnset);  // Reset value to a known, useful, state.
508   }
509 
510   return static_cast<CookieSourceScheme>(value);
511 }
512 
513 // Increments a specified TimeDelta by the duration between this object's
514 // constructor and destructor. Not thread safe. Multiple instances may be
515 // created with the same delta instance as long as their lifetimes are nested.
516 // The shortest lived instances have no impact.
517 class IncrementTimeDelta {
518  public:
IncrementTimeDelta(base::TimeDelta * delta)519   explicit IncrementTimeDelta(base::TimeDelta* delta)
520       : delta_(delta), original_value_(*delta), start_(base::Time::Now()) {}
521 
522   IncrementTimeDelta(const IncrementTimeDelta&) = delete;
523   IncrementTimeDelta& operator=(const IncrementTimeDelta&) = delete;
524 
~IncrementTimeDelta()525   ~IncrementTimeDelta() {
526     *delta_ = original_value_ + base::Time::Now() - start_;
527   }
528 
529  private:
530   raw_ptr<base::TimeDelta> delta_;
531   base::TimeDelta original_value_;
532   base::Time start_;
533 };
534 
535 // Initializes the cookies table, returning true on success.
536 // The table cannot exist when calling this function.
CreateV16Schema(sql::Database * db)537 bool CreateV16Schema(sql::Database* db) {
538   DCHECK(!db->DoesTableExist("cookies"));
539 
540   std::string stmt(base::StringPrintf(
541       "CREATE TABLE cookies("
542       "creation_utc INTEGER NOT NULL,"
543       "top_frame_site_key TEXT NOT NULL,"
544       "host_key TEXT NOT NULL,"
545       "name TEXT NOT NULL,"
546       "value TEXT NOT NULL,"
547       "encrypted_value BLOB DEFAULT '',"
548       "path TEXT NOT NULL,"
549       "expires_utc INTEGER NOT NULL,"
550       "is_secure INTEGER NOT NULL,"
551       "is_httponly INTEGER NOT NULL,"
552       "last_access_utc INTEGER NOT NULL,"
553       "has_expires INTEGER NOT NULL DEFAULT 1,"
554       "is_persistent INTEGER NOT NULL DEFAULT 1,"
555       "priority INTEGER NOT NULL DEFAULT %d,"
556       "samesite INTEGER NOT NULL DEFAULT %d,"
557       "source_scheme INTEGER NOT NULL DEFAULT %d,"
558       "source_port INTEGER NOT NULL DEFAULT %d,"
559       "is_same_party INTEGER NOT NULL DEFAULT 0,"
560       "UNIQUE (top_frame_site_key, host_key, name, path))",
561       CookiePriorityToDBCookiePriority(COOKIE_PRIORITY_DEFAULT),
562       CookieSameSiteToDBCookieSameSite(CookieSameSite::UNSPECIFIED),
563       static_cast<int>(CookieSourceScheme::kUnset),
564       SQLitePersistentCookieStore::kDefaultUnknownPort));
565   if (!db->Execute(stmt.c_str()))
566     return false;
567 
568   return true;
569 }
570 
571 // Initializes the cookies table, returning true on success.
572 // The table cannot exist when calling this function.
CreateV17Schema(sql::Database * db)573 bool CreateV17Schema(sql::Database* db) {
574   DCHECK(!db->DoesTableExist("cookies"));
575 
576   const char* kCreateTableQuery =
577       "CREATE TABLE cookies("
578       "creation_utc INTEGER NOT NULL,"
579       "host_key TEXT NOT NULL,"
580       "top_frame_site_key TEXT NOT NULL,"
581       "name TEXT NOT NULL,"
582       "value TEXT NOT NULL,"
583       "encrypted_value BLOB NOT NULL,"
584       "path TEXT NOT NULL,"
585       "expires_utc INTEGER NOT NULL,"
586       "is_secure INTEGER NOT NULL,"
587       "is_httponly INTEGER NOT NULL,"
588       "last_access_utc INTEGER NOT NULL,"
589       "has_expires INTEGER NOT NULL,"
590       "is_persistent INTEGER NOT NULL,"
591       "priority INTEGER NOT NULL,"
592       "samesite INTEGER NOT NULL,"
593       "source_scheme INTEGER NOT NULL,"
594       "source_port INTEGER NOT NULL,"
595       "is_same_party INTEGER NOT NULL);";
596 
597   const char* kCreateIndexQuery =
598       "CREATE UNIQUE INDEX cookies_unique_index "
599       "ON cookies(host_key, top_frame_site_key, name, path)";
600 
601   if (!db->Execute(kCreateTableQuery))
602     return false;
603   if (!db->Execute(kCreateIndexQuery))
604     return false;
605 
606   return true;
607 }
608 
609 // Initializes the cookies table, returning true on success.
610 // The table cannot exist when calling this function.
CreateV18Schema(sql::Database * db)611 bool CreateV18Schema(sql::Database* db) {
612   DCHECK(!db->DoesTableExist("cookies"));
613 
614   const char* kCreateTableQuery =
615       "CREATE TABLE cookies("
616       "creation_utc INTEGER NOT NULL,"
617       "host_key TEXT NOT NULL,"
618       "top_frame_site_key TEXT NOT NULL,"
619       "name TEXT NOT NULL,"
620       "value TEXT NOT NULL,"
621       "encrypted_value BLOB NOT NULL,"
622       "path TEXT NOT NULL,"
623       "expires_utc INTEGER NOT NULL,"
624       "is_secure INTEGER NOT NULL,"
625       "is_httponly INTEGER NOT NULL,"
626       "last_access_utc INTEGER NOT NULL,"
627       "has_expires INTEGER NOT NULL,"
628       "is_persistent INTEGER NOT NULL,"
629       "priority INTEGER NOT NULL,"
630       "samesite INTEGER NOT NULL,"
631       "source_scheme INTEGER NOT NULL,"
632       "source_port INTEGER NOT NULL,"
633       "is_same_party INTEGER NOT NULL,"
634       "last_update_utc INTEGER NOT NULL);";
635 
636   const char* kCreateIndexQuery =
637       "CREATE UNIQUE INDEX cookies_unique_index "
638       "ON cookies(host_key, top_frame_site_key, name, path)";
639 
640   if (!db->Execute(kCreateTableQuery))
641     return false;
642   if (!db->Execute(kCreateIndexQuery))
643     return false;
644 
645   return true;
646 }
647 
CreateV20Schema(sql::Database * db)648 bool CreateV20Schema(sql::Database* db) {
649   CHECK(!db->DoesTableExist("cookies"));
650 
651   const char* kCreateTableQuery =
652       "CREATE TABLE cookies("
653       "creation_utc INTEGER NOT NULL,"
654       "host_key TEXT NOT NULL,"
655       "top_frame_site_key TEXT NOT NULL,"
656       "name TEXT NOT NULL,"
657       "value TEXT NOT NULL,"
658       "encrypted_value BLOB NOT NULL,"
659       "path TEXT NOT NULL,"
660       "expires_utc INTEGER NOT NULL,"
661       "is_secure INTEGER NOT NULL,"
662       "is_httponly INTEGER NOT NULL,"
663       "last_access_utc INTEGER NOT NULL,"
664       "has_expires INTEGER NOT NULL,"
665       "is_persistent INTEGER NOT NULL,"
666       "priority INTEGER NOT NULL,"
667       "samesite INTEGER NOT NULL,"
668       "source_scheme INTEGER NOT NULL,"
669       "source_port INTEGER NOT NULL,"
670       "is_same_party INTEGER NOT NULL,"
671       "last_update_utc INTEGER NOT NULL);";
672 
673   const char* kCreateIndexQuery =
674       "CREATE UNIQUE INDEX cookies_unique_index "
675       "ON cookies(host_key, top_frame_site_key, name, path, source_scheme, "
676       "source_port)";
677 
678   if (!db->Execute(kCreateTableQuery)) {
679     return false;
680   }
681   if (!db->Execute(kCreateIndexQuery)) {
682     return false;
683   }
684 
685   return true;
686 }
687 
CreateV21Schema(sql::Database * db)688 bool CreateV21Schema(sql::Database* db) {
689   CHECK(!db->DoesTableExist("cookies"));
690 
691   const char* kCreateTableQuery =
692       "CREATE TABLE cookies("
693       "creation_utc INTEGER NOT NULL,"
694       "host_key TEXT NOT NULL,"
695       "top_frame_site_key TEXT NOT NULL,"
696       "name TEXT NOT NULL,"
697       "value TEXT NOT NULL,"
698       "encrypted_value BLOB NOT NULL,"
699       "path TEXT NOT NULL,"
700       "expires_utc INTEGER NOT NULL,"
701       "is_secure INTEGER NOT NULL,"
702       "is_httponly INTEGER NOT NULL,"
703       "last_access_utc INTEGER NOT NULL,"
704       "has_expires INTEGER NOT NULL,"
705       "is_persistent INTEGER NOT NULL,"
706       "priority INTEGER NOT NULL,"
707       "samesite INTEGER NOT NULL,"
708       "source_scheme INTEGER NOT NULL,"
709       "source_port INTEGER NOT NULL,"
710       "last_update_utc INTEGER NOT NULL);";
711 
712   const char* kCreateIndexQuery =
713       "CREATE UNIQUE INDEX cookies_unique_index "
714       "ON cookies(host_key, top_frame_site_key, name, path, source_scheme, "
715       "source_port)";
716 
717   if (!db->Execute(kCreateTableQuery)) {
718     return false;
719   }
720   if (!db->Execute(kCreateIndexQuery)) {
721     return false;
722   }
723 
724   return true;
725 }
726 
727 }  // namespace
728 
Load(LoadedCallback loaded_callback)729 void SQLitePersistentCookieStore::Backend::Load(
730     LoadedCallback loaded_callback) {
731   LoadCookiesForKey(absl::nullopt, std::move(loaded_callback));
732 }
733 
LoadCookiesForKey(base::optional_ref<const std::string> key,LoadedCallback loaded_callback)734 void SQLitePersistentCookieStore::Backend::LoadCookiesForKey(
735     base::optional_ref<const std::string> key,
736     LoadedCallback loaded_callback) {
737   if (crypto_) {
738     crypto_->Init(base::BindOnce(&Backend::CryptoHasInitFromLoad, this,
739                                  key.CopyAsOptional(),
740                                  std::move(loaded_callback)));
741   } else {
742     CryptoHasInitFromLoad(key, std::move(loaded_callback));
743   }
744 }
745 
CryptoHasInitFromLoad(base::optional_ref<const std::string> key,LoadedCallback loaded_callback)746 void SQLitePersistentCookieStore::Backend::CryptoHasInitFromLoad(
747     base::optional_ref<const std::string> key,
748     LoadedCallback loaded_callback) {
749   PostBackgroundTask(
750       FROM_HERE,
751       base::BindOnce(&Backend::LoadAndNotifyInBackground, this,
752                      key.CopyAsOptional(), std::move(loaded_callback)));
753 }
754 
LoadAndNotifyInBackground(base::optional_ref<const std::string> key,LoadedCallback loaded_callback)755 void SQLitePersistentCookieStore::Backend::LoadAndNotifyInBackground(
756     base::optional_ref<const std::string> key,
757     LoadedCallback loaded_callback) {
758   DCHECK(background_task_runner()->RunsTasksInCurrentSequence());
759   bool success = false;
760 
761   if (InitializeDatabase()) {
762     if (!key.has_value()) {
763       ChainLoadCookies(std::move(loaded_callback));
764       return;
765     }
766 
767     auto it = keys_to_load_.find(*key);
768     if (it != keys_to_load_.end()) {
769       success = LoadCookiesForDomains(it->second);
770       keys_to_load_.erase(it);
771     } else {
772       success = true;
773     }
774   }
775 
776   FinishedLoadingCookies(std::move(loaded_callback), success);
777 }
778 
NotifyLoadCompleteInForeground(LoadedCallback loaded_callback,bool load_success)779 void SQLitePersistentCookieStore::Backend::NotifyLoadCompleteInForeground(
780     LoadedCallback loaded_callback,
781     bool load_success) {
782   DCHECK(client_task_runner()->RunsTasksInCurrentSequence());
783 
784   std::vector<std::unique_ptr<CanonicalCookie>> cookies;
785   {
786     base::AutoLock locked(lock_);
787     cookies.swap(cookies_);
788   }
789 
790   std::move(loaded_callback).Run(std::move(cookies));
791 }
792 
CreateDatabaseSchema()793 bool SQLitePersistentCookieStore::Backend::CreateDatabaseSchema() {
794   DCHECK(db());
795 
796   if (db()->DoesTableExist("cookies"))
797     return true;
798 
799   return CreateV21Schema(db());
800 }
801 
DoInitializeDatabase()802 bool SQLitePersistentCookieStore::Backend::DoInitializeDatabase() {
803   DCHECK(db());
804 
805   // Retrieve all the domains
806   sql::Statement smt(
807       db()->GetUniqueStatement("SELECT DISTINCT host_key FROM cookies"));
808 
809   if (!smt.is_valid()) {
810     Reset();
811     return false;
812   }
813 
814   std::vector<std::string> host_keys;
815   while (smt.Step())
816     host_keys.push_back(smt.ColumnString(0));
817 
818   // Build a map of domain keys (always eTLD+1) to domains.
819   for (const auto& domain : host_keys) {
820     std::string key = CookieMonster::GetKey(domain);
821     keys_to_load_[key].insert(domain);
822   }
823 
824   if (!restore_old_session_cookies_)
825     DeleteSessionCookiesOnStartup();
826 
827   return true;
828 }
829 
ChainLoadCookies(LoadedCallback loaded_callback)830 void SQLitePersistentCookieStore::Backend::ChainLoadCookies(
831     LoadedCallback loaded_callback) {
832   DCHECK(background_task_runner()->RunsTasksInCurrentSequence());
833 
834   bool load_success = true;
835 
836   if (!db()) {
837     // Close() has been called on this store.
838     load_success = false;
839   } else if (keys_to_load_.size() > 0) {
840     // Load cookies for the first domain key.
841     auto it = keys_to_load_.begin();
842     load_success = LoadCookiesForDomains(it->second);
843     keys_to_load_.erase(it);
844   }
845 
846   // If load is successful and there are more domain keys to be loaded,
847   // then post a background task to continue chain-load;
848   // Otherwise notify on client runner.
849   if (load_success && keys_to_load_.size() > 0) {
850     bool success = background_task_runner()->PostTask(
851         FROM_HERE, base::BindOnce(&Backend::ChainLoadCookies, this,
852                                   std::move(loaded_callback)));
853     if (!success) {
854       LOG(WARNING) << "Failed to post task from " << FROM_HERE.ToString()
855                    << " to background_task_runner().";
856     }
857   } else {
858     FinishedLoadingCookies(std::move(loaded_callback), load_success);
859   }
860 }
861 
LoadCookiesForDomains(const std::set<std::string> & domains)862 bool SQLitePersistentCookieStore::Backend::LoadCookiesForDomains(
863     const std::set<std::string>& domains) {
864   DCHECK(background_task_runner()->RunsTasksInCurrentSequence());
865 
866   sql::Statement smt, delete_statement;
867   if (restore_old_session_cookies_) {
868     smt.Assign(db()->GetCachedStatement(
869         SQL_FROM_HERE,
870         "SELECT creation_utc, host_key, top_frame_site_key, name, value, path, "
871         "expires_utc, is_secure, is_httponly, last_access_utc, has_expires, "
872         "is_persistent, priority, encrypted_value, samesite, source_scheme, "
873         "source_port, last_update_utc FROM cookies WHERE host_key = ?"));
874   } else {
875     smt.Assign(db()->GetCachedStatement(
876         SQL_FROM_HERE,
877         "SELECT creation_utc, host_key, top_frame_site_key, name, value, path, "
878         "expires_utc, is_secure, is_httponly, last_access_utc, has_expires, "
879         "is_persistent, priority, encrypted_value, samesite, source_scheme, "
880         "source_port, last_update_utc FROM cookies WHERE "
881         "host_key = ? AND "
882         "is_persistent = 1"));
883   }
884   delete_statement.Assign(db()->GetCachedStatement(
885       SQL_FROM_HERE, "DELETE FROM cookies WHERE host_key = ?"));
886   if (!smt.is_valid() || !delete_statement.is_valid()) {
887     delete_statement.Clear();
888     smt.Clear();  // Disconnect smt_ref from db_.
889     Reset();
890     return false;
891   }
892 
893   std::vector<std::unique_ptr<CanonicalCookie>> cookies;
894   std::unordered_set<std::string> top_frame_site_keys_to_delete;
895   auto it = domains.begin();
896   bool ok = true;
897   for (; it != domains.end() && ok; ++it) {
898     smt.BindString(0, *it);
899     ok = MakeCookiesFromSQLStatement(cookies, smt,
900                                      top_frame_site_keys_to_delete);
901     smt.Reset(true);
902   }
903 
904   DeleteTopFrameSiteKeys(std::move(top_frame_site_keys_to_delete));
905 
906   if (ok) {
907     base::AutoLock locked(lock_);
908     std::move(cookies.begin(), cookies.end(), std::back_inserter(cookies_));
909   } else {
910     // There were some cookies that were in database but could not be loaded
911     // and handed over to CookieMonster. This is trouble since it means that
912     // if some website tries to send them again, CookieMonster won't know to
913     // issue a delete, and then the addition would violate the uniqueness
914     // constraints and not go through.
915     //
916     // For data consistency, we drop the entire eTLD group.
917     for (const std::string& domain : domains) {
918       delete_statement.BindString(0, domain);
919       if (!delete_statement.Run()) {
920         // TODO(morlovich): Is something more drastic called for here?
921         RecordCookieLoadProblem(COOKIE_LOAD_PROBLEM_RECOVERY_FAILED);
922       }
923       delete_statement.Reset(true);
924     }
925   }
926   return true;
927 }
928 
DeleteTopFrameSiteKeys(const std::unordered_set<std::string> & top_frame_site_keys)929 void SQLitePersistentCookieStore::Backend::DeleteTopFrameSiteKeys(
930     const std::unordered_set<std::string>& top_frame_site_keys) {
931   if (top_frame_site_keys.empty())
932     return;
933 
934   sql::Statement delete_statement;
935   delete_statement.Assign(db()->GetCachedStatement(
936       SQL_FROM_HERE, "DELETE FROM cookies WHERE top_frame_site_key = ?"));
937   if (!delete_statement.is_valid())
938     return;
939 
940   for (const std::string& key : top_frame_site_keys) {
941     delete_statement.BindString(0, key);
942     if (!delete_statement.Run())
943       RecordCookieLoadProblem(COOKIE_LOAD_DELETE_COOKIE_PARTITION_FAILED);
944     delete_statement.Reset(true);
945   }
946 }
947 
MakeCookiesFromSQLStatement(std::vector<std::unique_ptr<CanonicalCookie>> & cookies,sql::Statement & statement,std::unordered_set<std::string> & top_frame_site_keys_to_delete)948 bool SQLitePersistentCookieStore::Backend::MakeCookiesFromSQLStatement(
949     std::vector<std::unique_ptr<CanonicalCookie>>& cookies,
950     sql::Statement& statement,
951     std::unordered_set<std::string>& top_frame_site_keys_to_delete) {
952   DCHECK(background_task_runner()->RunsTasksInCurrentSequence());
953   bool ok = true;
954   while (statement.Step()) {
955     std::string value;
956     std::string encrypted_value = statement.ColumnString(13);
957     if (!encrypted_value.empty() && crypto_) {
958       bool decrypt_ok = crypto_->DecryptString(encrypted_value, &value);
959       if (!decrypt_ok) {
960         RecordCookieLoadProblem(COOKIE_LOAD_PROBLEM_DECRYPT_FAILED);
961         ok = false;
962         continue;
963       }
964     } else {
965       value = statement.ColumnString(4);
966     }
967 
968     absl::optional<CookiePartitionKey> cookie_partition_key;
969     std::string top_frame_site_key = statement.ColumnString(2);
970     // If we can't deserialize a top_frame_site_key, we delete any cookie with
971     // that key.
972     if (!CookiePartitionKey::Deserialize(top_frame_site_key,
973                                          cookie_partition_key)) {
974       top_frame_site_keys_to_delete.insert(std::move(top_frame_site_key));
975       continue;
976     }
977 
978     // Returns nullptr if the resulting cookie is not canonical.
979     std::unique_ptr<net::CanonicalCookie> cc = CanonicalCookie::FromStorage(
980         statement.ColumnString(3),  // name
981         value,                      // value
982         statement.ColumnString(1),  // domain
983         statement.ColumnString(5),  // path
984         statement.ColumnTime(0),    // creation_utc
985         statement.ColumnTime(6),    // expires_utc
986         statement.ColumnTime(9),    // last_access_utc
987         statement.ColumnTime(17),   // last_update_utc
988         statement.ColumnBool(7),    // secure
989         statement.ColumnBool(8),    // http_only
990         DBCookieSameSiteToCookieSameSite(static_cast<DBCookieSameSite>(
991             statement.ColumnInt(14))),  // samesite
992         DBCookiePriorityToCookiePriority(static_cast<DBCookiePriority>(
993             statement.ColumnInt(12))),                    // priority
994         std::move(cookie_partition_key),                  // top_frame_site_key
995         DBToCookieSourceScheme(statement.ColumnInt(15)),  // source_scheme
996         statement.ColumnInt(16));                         // source_port
997     if (cc) {
998       DLOG_IF(WARNING, cc->CreationDate() > Time::Now())
999           << "CreationDate too recent";
1000       if (!cc->LastUpdateDate().is_null()) {
1001         DLOG_IF(WARNING, cc->LastUpdateDate() > Time::Now())
1002             << "LastUpdateDate too recent";
1003         // In order to anticipate the potential effects of the expiry limit in
1004         // rfc6265bis, we need to check how long it's been since the cookie was
1005         // refreshed (if LastUpdateDate is populated). We use 100 buckets for
1006         // the highest reasonable granularity, set 1 day as the minimum and
1007         // don't track over a 400 max (since these cookies will expire anyway).
1008         UMA_HISTOGRAM_CUSTOM_COUNTS(
1009             "Cookie.DaysSinceRefreshForRetrieval",
1010             (base::Time::Now() - cc->LastUpdateDate()).InDays(), 1, 400, 100);
1011       }
1012       cookies.push_back(std::move(cc));
1013     } else {
1014       RecordCookieLoadProblem(COOKIE_LOAD_PROBLEM_NON_CANONICAL);
1015       ok = false;
1016     }
1017   }
1018 
1019   return ok;
1020 }
1021 
1022 absl::optional<int>
DoMigrateDatabaseSchema()1023 SQLitePersistentCookieStore::Backend::DoMigrateDatabaseSchema() {
1024   int cur_version = meta_table()->GetVersionNumber();
1025 
1026   if (cur_version == 15) {
1027     sql::Transaction transaction(db());
1028     if (!transaction.Begin())
1029       return absl::nullopt;
1030 
1031     if (!db()->Execute("DROP TABLE IF EXISTS cookies_old"))
1032       return absl::nullopt;
1033     if (!db()->Execute("ALTER TABLE cookies RENAME TO cookies_old"))
1034       return absl::nullopt;
1035 
1036     if (!CreateV16Schema(db())) {
1037       return absl::nullopt;
1038     }
1039     std::string insert_cookies_sql = base::StringPrintf(
1040         "INSERT OR REPLACE INTO cookies "
1041         "(creation_utc, host_key, top_frame_site_key, name, value, "
1042         "encrypted_value, path, expires_utc, is_secure, is_httponly, "
1043         "last_access_utc, has_expires, is_persistent, priority, samesite, "
1044         "source_scheme, source_port, is_same_party) "
1045         "SELECT creation_utc, host_key, top_frame_site_key, name, value,"
1046         "       encrypted_value, path, expires_utc, is_secure, is_httponly,"
1047         "       last_access_utc, has_expires, is_persistent, priority, "
1048         "samesite,"
1049         "       source_scheme, source_port, is_same_party "
1050         "FROM cookies_old ORDER BY creation_utc ASC");
1051     if (!db()->Execute(insert_cookies_sql.c_str()))
1052       return absl::nullopt;
1053     if (!db()->Execute("DROP TABLE cookies_old"))
1054       return absl::nullopt;
1055 
1056     ++cur_version;
1057     if (!meta_table()->SetVersionNumber(cur_version) ||
1058         !meta_table()->SetCompatibleVersionNumber(
1059             std::min(cur_version, kCompatibleVersionNumber)) ||
1060         !transaction.Commit()) {
1061       return absl::nullopt;
1062     }
1063   }
1064 
1065   if (cur_version == 16) {
1066     sql::Transaction transaction(db());
1067     if (!transaction.Begin())
1068       return absl::nullopt;
1069 
1070     if (!db()->Execute("DROP TABLE IF EXISTS cookies_old"))
1071       return absl::nullopt;
1072     if (!db()->Execute("ALTER TABLE cookies RENAME TO cookies_old"))
1073       return absl::nullopt;
1074     if (!db()->Execute("DROP INDEX IF EXISTS cookies_unique_index"))
1075       return absl::nullopt;
1076 
1077     if (!CreateV17Schema(db()))
1078       return absl::nullopt;
1079     static constexpr char insert_cookies_sql[] =
1080         "INSERT OR REPLACE INTO cookies "
1081         "(creation_utc, host_key, top_frame_site_key, name, value, "
1082         "encrypted_value, path, expires_utc, is_secure, is_httponly, "
1083         "last_access_utc, has_expires, is_persistent, priority, samesite, "
1084         "source_scheme, source_port, is_same_party) "
1085         "SELECT creation_utc, host_key, top_frame_site_key, name, value,"
1086         "       encrypted_value, path, expires_utc, is_secure, is_httponly,"
1087         "       last_access_utc, has_expires, is_persistent, priority, "
1088         "samesite,"
1089         "       source_scheme, source_port, is_same_party "
1090         "FROM cookies_old ORDER BY creation_utc ASC";
1091     if (!db()->Execute(insert_cookies_sql))
1092       return absl::nullopt;
1093     if (!db()->Execute("DROP TABLE cookies_old"))
1094       return absl::nullopt;
1095 
1096     ++cur_version;
1097     if (!meta_table()->SetVersionNumber(cur_version) ||
1098         !meta_table()->SetCompatibleVersionNumber(
1099             std::min(cur_version, kCompatibleVersionNumber)) ||
1100         !transaction.Commit()) {
1101       return absl::nullopt;
1102     }
1103   }
1104 
1105   if (cur_version == 17) {
1106     SCOPED_UMA_HISTOGRAM_TIMER("Cookie.TimeDatabaseMigrationToV18");
1107 
1108     sql::Transaction transaction(db());
1109     if (!transaction.Begin())
1110       return absl::nullopt;
1111 
1112     if (!db()->Execute("DROP TABLE IF EXISTS cookies_old"))
1113       return absl::nullopt;
1114     if (!db()->Execute("ALTER TABLE cookies RENAME TO cookies_old"))
1115       return absl::nullopt;
1116     if (!db()->Execute("DROP INDEX IF EXISTS cookies_unique_index"))
1117       return absl::nullopt;
1118 
1119     if (!CreateV18Schema(db()))
1120       return absl::nullopt;
1121     static constexpr char insert_cookies_sql[] =
1122         "INSERT OR REPLACE INTO cookies "
1123         "(creation_utc, host_key, top_frame_site_key, name, value, "
1124         "encrypted_value, path, expires_utc, is_secure, is_httponly, "
1125         "last_access_utc, has_expires, is_persistent, priority, samesite, "
1126         "source_scheme, source_port, is_same_party, last_update_utc) "
1127         "SELECT creation_utc, host_key, top_frame_site_key, name, value,"
1128         "       encrypted_value, path, expires_utc, is_secure, is_httponly,"
1129         "       last_access_utc, has_expires, is_persistent, priority, "
1130         "       samesite, source_scheme, source_port, is_same_party, 0 "
1131         "FROM cookies_old ORDER BY creation_utc ASC";
1132     if (!db()->Execute(insert_cookies_sql))
1133       return absl::nullopt;
1134     if (!db()->Execute("DROP TABLE cookies_old"))
1135       return absl::nullopt;
1136 
1137     ++cur_version;
1138     if (!meta_table()->SetVersionNumber(cur_version) ||
1139         !meta_table()->SetCompatibleVersionNumber(
1140             std::min(cur_version, kCompatibleVersionNumber)) ||
1141         !transaction.Commit()) {
1142       return absl::nullopt;
1143     }
1144   }
1145 
1146   if (cur_version == 18) {
1147     SCOPED_UMA_HISTOGRAM_TIMER("Cookie.TimeDatabaseMigrationToV19");
1148 
1149     sql::Statement update_statement(
1150         db()->GetCachedStatement(SQL_FROM_HERE,
1151                                  "UPDATE cookies SET expires_utc = ? WHERE "
1152                                  "has_expires = 1 AND expires_utc > ?"));
1153     if (!update_statement.is_valid()) {
1154       return absl::nullopt;
1155     }
1156 
1157     sql::Transaction transaction(db());
1158     if (!transaction.Begin()) {
1159       return absl::nullopt;
1160     }
1161 
1162     base::Time expires_cap = base::Time::Now() + base::Days(400);
1163     update_statement.BindTime(0, expires_cap);
1164     update_statement.BindTime(1, expires_cap);
1165     if (!update_statement.Run()) {
1166       return absl::nullopt;
1167     }
1168 
1169     ++cur_version;
1170     if (!meta_table()->SetVersionNumber(cur_version) ||
1171         !meta_table()->SetCompatibleVersionNumber(
1172             std::min(cur_version, kCompatibleVersionNumber)) ||
1173         !transaction.Commit()) {
1174       return absl::nullopt;
1175     }
1176   }
1177 
1178   if (cur_version == 19) {
1179     SCOPED_UMA_HISTOGRAM_TIMER("Cookie.TimeDatabaseMigrationToV20");
1180 
1181     sql::Transaction transaction(db());
1182     if (!transaction.Begin()) {
1183       return absl::nullopt;
1184     }
1185 
1186     if (!db()->Execute("DROP TABLE IF EXISTS cookies_old")) {
1187       return absl::nullopt;
1188     }
1189     if (!db()->Execute("ALTER TABLE cookies RENAME TO cookies_old")) {
1190       return absl::nullopt;
1191     }
1192     if (!db()->Execute("DROP INDEX IF EXISTS cookies_unique_index")) {
1193       return absl::nullopt;
1194     }
1195 
1196     if (!CreateV20Schema(db())) {
1197       return absl::nullopt;
1198     }
1199 
1200     static constexpr char insert_cookies_sql[] =
1201         "INSERT OR REPLACE INTO cookies "
1202         "(creation_utc, host_key, top_frame_site_key, name, value, "
1203         "encrypted_value, path, expires_utc, is_secure, is_httponly, "
1204         "last_access_utc, has_expires, is_persistent, priority, samesite, "
1205         "source_scheme, source_port, is_same_party, last_update_utc) "
1206         "SELECT creation_utc, host_key, top_frame_site_key, name, value,"
1207         "       encrypted_value, path, expires_utc, is_secure, is_httponly,"
1208         "       last_access_utc, has_expires, is_persistent, priority, "
1209         "       samesite, source_scheme, source_port, is_same_party, "
1210         "last_update_utc "
1211         "FROM cookies_old ORDER BY creation_utc ASC";
1212     if (!db()->Execute(insert_cookies_sql)) {
1213       return absl::nullopt;
1214     }
1215     if (!db()->Execute("DROP TABLE cookies_old")) {
1216       return absl::nullopt;
1217     }
1218 
1219     ++cur_version;
1220     if (!meta_table()->SetVersionNumber(cur_version) ||
1221         !meta_table()->SetCompatibleVersionNumber(
1222             std::min(cur_version, kCompatibleVersionNumber)) ||
1223         !transaction.Commit()) {
1224       return absl::nullopt;
1225     }
1226   }
1227 
1228   if (cur_version == 20) {
1229     SCOPED_UMA_HISTOGRAM_TIMER("Cookie.TimeDatabaseMigrationToV21");
1230 
1231     sql::Transaction transaction(db());
1232     if (!transaction.Begin()) {
1233       return absl::nullopt;
1234     }
1235 
1236     if (!db()->Execute("DROP TABLE IF EXISTS cookies_old")) {
1237       return absl::nullopt;
1238     }
1239     if (!db()->Execute("ALTER TABLE cookies RENAME TO cookies_old")) {
1240       return absl::nullopt;
1241     }
1242     if (!db()->Execute("DROP INDEX IF EXISTS cookies_unique_index")) {
1243       return absl::nullopt;
1244     }
1245 
1246     if (!CreateV21Schema(db())) {
1247       return absl::nullopt;
1248     }
1249 
1250     static constexpr char insert_cookies_sql[] =
1251         "INSERT OR REPLACE INTO cookies "
1252         "(creation_utc, host_key, top_frame_site_key, name, value, "
1253         "encrypted_value, path, expires_utc, is_secure, is_httponly, "
1254         "last_access_utc, has_expires, is_persistent, priority, samesite, "
1255         "source_scheme, source_port, last_update_utc) "
1256         "SELECT creation_utc, host_key, top_frame_site_key, name, value,"
1257         "       encrypted_value, path, expires_utc, is_secure, is_httponly,"
1258         "       last_access_utc, has_expires, is_persistent, priority, "
1259         "       samesite, source_scheme, source_port, last_update_utc "
1260         "FROM cookies_old ORDER BY creation_utc ASC";
1261     if (!db()->Execute(insert_cookies_sql)) {
1262       return absl::nullopt;
1263     }
1264     if (!db()->Execute("DROP TABLE cookies_old")) {
1265       return absl::nullopt;
1266     }
1267 
1268     ++cur_version;
1269     if (!meta_table()->SetVersionNumber(cur_version) ||
1270         !meta_table()->SetCompatibleVersionNumber(
1271             std::min(cur_version, kCompatibleVersionNumber)) ||
1272         !transaction.Commit()) {
1273       return absl::nullopt;
1274     }
1275   }
1276 
1277   // Put future migration cases here.
1278 
1279   return absl::make_optional(cur_version);
1280 }
1281 
AddCookie(const CanonicalCookie & cc)1282 void SQLitePersistentCookieStore::Backend::AddCookie(
1283     const CanonicalCookie& cc) {
1284   BatchOperation(PendingOperation::COOKIE_ADD, cc);
1285 }
1286 
UpdateCookieAccessTime(const CanonicalCookie & cc)1287 void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime(
1288     const CanonicalCookie& cc) {
1289   BatchOperation(PendingOperation::COOKIE_UPDATEACCESS, cc);
1290 }
1291 
DeleteCookie(const CanonicalCookie & cc)1292 void SQLitePersistentCookieStore::Backend::DeleteCookie(
1293     const CanonicalCookie& cc) {
1294   BatchOperation(PendingOperation::COOKIE_DELETE, cc);
1295 }
1296 
BatchOperation(PendingOperation::OperationType op,const CanonicalCookie & cc)1297 void SQLitePersistentCookieStore::Backend::BatchOperation(
1298     PendingOperation::OperationType op,
1299     const CanonicalCookie& cc) {
1300   // Commit every 30 seconds.
1301   static const int kCommitIntervalMs = 30 * 1000;
1302   // Commit right away if we have more than 512 outstanding operations.
1303   static const size_t kCommitAfterBatchSize = 512;
1304   DCHECK(!background_task_runner()->RunsTasksInCurrentSequence());
1305 
1306   // We do a full copy of the cookie here, and hopefully just here.
1307   auto po = std::make_unique<PendingOperation>(op, cc);
1308 
1309   PendingOperationsMap::size_type num_pending;
1310   {
1311     base::AutoLock locked(lock_);
1312     // When queueing the operation, see if it overwrites any already pending
1313     // ones for the same row.
1314     auto key = cc.StrictlyUniqueKey();
1315     auto iter_and_result =
1316         pending_.insert(std::make_pair(key, PendingOperationsForKey()));
1317     PendingOperationsForKey& ops_for_key = iter_and_result.first->second;
1318     if (!iter_and_result.second) {
1319       // Insert failed -> already have ops.
1320       if (po->op() == PendingOperation::COOKIE_DELETE) {
1321         // A delete op makes all the previous ones irrelevant.
1322         ops_for_key.clear();
1323       } else if (po->op() == PendingOperation::COOKIE_UPDATEACCESS) {
1324         if (!ops_for_key.empty() &&
1325             ops_for_key.back()->op() == PendingOperation::COOKIE_UPDATEACCESS) {
1326           // If access timestamp is updated twice in a row, can dump the earlier
1327           // one.
1328           ops_for_key.pop_back();
1329         }
1330         // At most delete + add before (and no access time updates after above
1331         // conditional).
1332         DCHECK_LE(ops_for_key.size(), 2u);
1333       } else {
1334         // Nothing special is done for adds, since if they're overwriting,
1335         // they'll be preceded by deletes anyway.
1336         DCHECK_LE(ops_for_key.size(), 1u);
1337       }
1338     }
1339     ops_for_key.push_back(std::move(po));
1340     // Note that num_pending_ counts number of calls to BatchOperation(), not
1341     // the current length of the queue; this is intentional to guarantee
1342     // progress, as the length of the queue may decrease in some cases.
1343     num_pending = ++num_pending_;
1344   }
1345 
1346   if (num_pending == 1) {
1347     // We've gotten our first entry for this batch, fire off the timer.
1348     if (!background_task_runner()->PostDelayedTask(
1349             FROM_HERE, base::BindOnce(&Backend::Commit, this),
1350             base::Milliseconds(kCommitIntervalMs))) {
1351       NOTREACHED() << "background_task_runner() is not running.";
1352     }
1353   } else if (num_pending == kCommitAfterBatchSize) {
1354     // We've reached a big enough batch, fire off a commit now.
1355     PostBackgroundTask(FROM_HERE, base::BindOnce(&Backend::Commit, this));
1356   }
1357 }
1358 
DoCommit()1359 void SQLitePersistentCookieStore::Backend::DoCommit() {
1360   DCHECK(background_task_runner()->RunsTasksInCurrentSequence());
1361 
1362   PendingOperationsMap ops;
1363   {
1364     base::AutoLock locked(lock_);
1365     pending_.swap(ops);
1366     num_pending_ = 0;
1367   }
1368 
1369   // Maybe an old timer fired or we are already Close()'ed.
1370   if (!db() || ops.empty())
1371     return;
1372 
1373   sql::Statement add_statement(db()->GetCachedStatement(
1374       SQL_FROM_HERE,
1375       "INSERT INTO cookies (creation_utc, host_key, top_frame_site_key, name, "
1376       "value, encrypted_value, path, expires_utc, is_secure, is_httponly, "
1377       "last_access_utc, has_expires, is_persistent, priority, samesite, "
1378       "source_scheme, source_port, last_update_utc) "
1379       "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));
1380   if (!add_statement.is_valid())
1381     return;
1382 
1383   sql::Statement update_access_statement(db()->GetCachedStatement(
1384       SQL_FROM_HERE,
1385       "UPDATE cookies SET last_access_utc=? WHERE "
1386       "name=? AND host_key=? AND top_frame_site_key=? AND path=? AND "
1387       "source_scheme=? AND source_port=?"));
1388   if (!update_access_statement.is_valid())
1389     return;
1390 
1391   sql::Statement delete_statement(db()->GetCachedStatement(
1392       SQL_FROM_HERE,
1393       "DELETE FROM cookies WHERE "
1394       "name=? AND host_key=? AND top_frame_site_key=? AND path=? AND "
1395       "source_scheme=? AND source_port=?"));
1396   if (!delete_statement.is_valid())
1397     return;
1398 
1399   sql::Transaction transaction(db());
1400   if (!transaction.Begin())
1401     return;
1402 
1403   for (auto& kv : ops) {
1404     for (std::unique_ptr<PendingOperation>& po_entry : kv.second) {
1405       // Free the cookies as we commit them to the database.
1406       std::unique_ptr<PendingOperation> po(std::move(po_entry));
1407       std::string top_frame_site_key;
1408       if (!CookiePartitionKey::Serialize(po->cc().PartitionKey(),
1409                                          top_frame_site_key)) {
1410         continue;
1411       }
1412       switch (po->op()) {
1413         case PendingOperation::COOKIE_ADD:
1414           add_statement.Reset(true);
1415           add_statement.BindTime(0, po->cc().CreationDate());
1416           add_statement.BindString(1, po->cc().Domain());
1417           add_statement.BindString(2, top_frame_site_key);
1418           add_statement.BindString(3, po->cc().Name());
1419           if (crypto_) {
1420             std::string encrypted_value;
1421             if (!crypto_->EncryptString(po->cc().Value(), &encrypted_value)) {
1422               DLOG(WARNING) << "Could not encrypt a cookie, skipping add.";
1423               RecordCookieCommitProblem(COOKIE_COMMIT_PROBLEM_ENCRYPT_FAILED);
1424               continue;
1425             }
1426             add_statement.BindCString(4, "");  // value
1427             // BindBlob() immediately makes an internal copy of the data.
1428             add_statement.BindBlob(5, encrypted_value);
1429           } else {
1430             add_statement.BindString(4, po->cc().Value());
1431             add_statement.BindBlob(5,
1432                                    base::span<uint8_t>());  // encrypted_value
1433           }
1434           add_statement.BindString(6, po->cc().Path());
1435           add_statement.BindTime(7, po->cc().ExpiryDate());
1436           add_statement.BindBool(8, po->cc().IsSecure());
1437           add_statement.BindBool(9, po->cc().IsHttpOnly());
1438           add_statement.BindTime(10, po->cc().LastAccessDate());
1439           add_statement.BindBool(11, po->cc().IsPersistent());
1440           add_statement.BindBool(12, po->cc().IsPersistent());
1441           add_statement.BindInt(
1442               13, CookiePriorityToDBCookiePriority(po->cc().Priority()));
1443           add_statement.BindInt(
1444               14, CookieSameSiteToDBCookieSameSite(po->cc().SameSite()));
1445           add_statement.BindInt(15, static_cast<int>(po->cc().SourceScheme()));
1446           add_statement.BindInt(16, po->cc().SourcePort());
1447           add_statement.BindTime(17, po->cc().LastUpdateDate());
1448           if (!add_statement.Run()) {
1449             DLOG(WARNING) << "Could not add a cookie to the DB.";
1450             RecordCookieCommitProblem(COOKIE_COMMIT_PROBLEM_ADD);
1451           }
1452           break;
1453 
1454         case PendingOperation::COOKIE_UPDATEACCESS:
1455           update_access_statement.Reset(true);
1456           update_access_statement.BindTime(0, po->cc().LastAccessDate());
1457           update_access_statement.BindString(1, po->cc().Name());
1458           update_access_statement.BindString(2, po->cc().Domain());
1459           update_access_statement.BindString(3, top_frame_site_key);
1460           update_access_statement.BindString(4, po->cc().Path());
1461           update_access_statement.BindInt(
1462               5, static_cast<int>(po->cc().SourceScheme()));
1463           update_access_statement.BindInt(6, po->cc().SourcePort());
1464           if (!update_access_statement.Run()) {
1465             DLOG(WARNING)
1466                 << "Could not update cookie last access time in the DB.";
1467             RecordCookieCommitProblem(COOKIE_COMMIT_PROBLEM_UPDATE_ACCESS);
1468           }
1469           break;
1470 
1471         case PendingOperation::COOKIE_DELETE:
1472           delete_statement.Reset(true);
1473           delete_statement.BindString(0, po->cc().Name());
1474           delete_statement.BindString(1, po->cc().Domain());
1475           delete_statement.BindString(2, top_frame_site_key);
1476           delete_statement.BindString(3, po->cc().Path());
1477           delete_statement.BindInt(4,
1478                                    static_cast<int>(po->cc().SourceScheme()));
1479           delete_statement.BindInt(5, po->cc().SourcePort());
1480           if (!delete_statement.Run()) {
1481             DLOG(WARNING) << "Could not delete a cookie from the DB.";
1482             RecordCookieCommitProblem(COOKIE_COMMIT_PROBLEM_DELETE);
1483           }
1484           break;
1485 
1486         default:
1487           NOTREACHED();
1488           break;
1489       }
1490     }
1491   }
1492   bool commit_ok = transaction.Commit();
1493   if (!commit_ok) {
1494     RecordCookieCommitProblem(COOKIE_COMMIT_PROBLEM_TRANSACTION_COMMIT);
1495   }
1496 }
1497 
GetQueueLengthForTesting()1498 size_t SQLitePersistentCookieStore::Backend::GetQueueLengthForTesting() {
1499   DCHECK(client_task_runner()->RunsTasksInCurrentSequence());
1500   size_t total = 0u;
1501   {
1502     base::AutoLock locked(lock_);
1503     for (const auto& key_val : pending_) {
1504       total += key_val.second.size();
1505     }
1506   }
1507   return total;
1508 }
1509 
DeleteAllInList(const std::list<CookieOrigin> & cookies)1510 void SQLitePersistentCookieStore::Backend::DeleteAllInList(
1511     const std::list<CookieOrigin>& cookies) {
1512   if (cookies.empty())
1513     return;
1514 
1515   if (background_task_runner()->RunsTasksInCurrentSequence()) {
1516     BackgroundDeleteAllInList(cookies);
1517   } else {
1518     // Perform deletion on background task runner.
1519     PostBackgroundTask(
1520         FROM_HERE,
1521         base::BindOnce(&Backend::BackgroundDeleteAllInList, this, cookies));
1522   }
1523 }
1524 
DeleteSessionCookiesOnStartup()1525 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup() {
1526   DCHECK(background_task_runner()->RunsTasksInCurrentSequence());
1527   if (!db()->Execute("DELETE FROM cookies WHERE is_persistent != 1"))
1528     LOG(WARNING) << "Unable to delete session cookies.";
1529 }
1530 
1531 // TODO(crbug.com/1225444) Investigate including top_frame_site_key in the WHERE
1532 // clause.
BackgroundDeleteAllInList(const std::list<CookieOrigin> & cookies)1533 void SQLitePersistentCookieStore::Backend::BackgroundDeleteAllInList(
1534     const std::list<CookieOrigin>& cookies) {
1535   DCHECK(background_task_runner()->RunsTasksInCurrentSequence());
1536 
1537   if (!db())
1538     return;
1539 
1540   // Force a commit of any pending writes before issuing deletes.
1541   // TODO(rohitrao): Remove the need for this Commit() by instead pruning the
1542   // list of pending operations. https://crbug.com/486742.
1543   Commit();
1544 
1545   sql::Statement delete_statement(db()->GetCachedStatement(
1546       SQL_FROM_HERE, "DELETE FROM cookies WHERE host_key=? AND is_secure=?"));
1547   if (!delete_statement.is_valid()) {
1548     LOG(WARNING) << "Unable to delete cookies on shutdown.";
1549     return;
1550   }
1551 
1552   sql::Transaction transaction(db());
1553   if (!transaction.Begin()) {
1554     LOG(WARNING) << "Unable to delete cookies on shutdown.";
1555     return;
1556   }
1557 
1558   for (const auto& cookie : cookies) {
1559     const GURL url(cookie_util::CookieOriginToURL(cookie.first, cookie.second));
1560     if (!url.is_valid())
1561       continue;
1562 
1563     delete_statement.Reset(true);
1564     delete_statement.BindString(0, cookie.first);
1565     delete_statement.BindInt(1, cookie.second);
1566     if (!delete_statement.Run()) {
1567       LOG(WARNING) << "Could not delete a cookie from the DB.";
1568     }
1569   }
1570 
1571   if (!transaction.Commit())
1572     LOG(WARNING) << "Unable to delete cookies on shutdown.";
1573 }
1574 
FinishedLoadingCookies(LoadedCallback loaded_callback,bool success)1575 void SQLitePersistentCookieStore::Backend::FinishedLoadingCookies(
1576     LoadedCallback loaded_callback,
1577     bool success) {
1578   PostClientTask(FROM_HERE,
1579                  base::BindOnce(&Backend::NotifyLoadCompleteInForeground, this,
1580                                 std::move(loaded_callback), success));
1581 }
1582 
SQLitePersistentCookieStore(const base::FilePath & path,const scoped_refptr<base::SequencedTaskRunner> & client_task_runner,const scoped_refptr<base::SequencedTaskRunner> & background_task_runner,bool restore_old_session_cookies,CookieCryptoDelegate * crypto_delegate,bool enable_exclusive_access)1583 SQLitePersistentCookieStore::SQLitePersistentCookieStore(
1584     const base::FilePath& path,
1585     const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
1586     const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
1587     bool restore_old_session_cookies,
1588     CookieCryptoDelegate* crypto_delegate,
1589     bool enable_exclusive_access)
1590     : backend_(base::MakeRefCounted<Backend>(path,
1591                                              client_task_runner,
1592                                              background_task_runner,
1593                                              restore_old_session_cookies,
1594                                              crypto_delegate,
1595                                              enable_exclusive_access)) {}
1596 
DeleteAllInList(const std::list<CookieOrigin> & cookies)1597 void SQLitePersistentCookieStore::DeleteAllInList(
1598     const std::list<CookieOrigin>& cookies) {
1599   backend_->DeleteAllInList(cookies);
1600 }
1601 
Load(LoadedCallback loaded_callback,const NetLogWithSource & net_log)1602 void SQLitePersistentCookieStore::Load(LoadedCallback loaded_callback,
1603                                        const NetLogWithSource& net_log) {
1604   DCHECK(!loaded_callback.is_null());
1605   net_log_ = net_log;
1606   net_log_.BeginEvent(NetLogEventType::COOKIE_PERSISTENT_STORE_LOAD);
1607   // Note that |backend_| keeps |this| alive by keeping a reference count.
1608   // If this class is ever converted over to a WeakPtr<> pattern (as TODO it
1609   // should be) this will need to be replaced by a more complex pattern that
1610   // guarantees |loaded_callback| being called even if the class has been
1611   // destroyed. |backend_| needs to outlive |this| to commit changes to disk.
1612   backend_->Load(base::BindOnce(&SQLitePersistentCookieStore::CompleteLoad,
1613                                 this, std::move(loaded_callback)));
1614 }
1615 
LoadCookiesForKey(const std::string & key,LoadedCallback loaded_callback)1616 void SQLitePersistentCookieStore::LoadCookiesForKey(
1617     const std::string& key,
1618     LoadedCallback loaded_callback) {
1619   DCHECK(!loaded_callback.is_null());
1620   net_log_.AddEvent(NetLogEventType::COOKIE_PERSISTENT_STORE_KEY_LOAD_STARTED,
1621                     [&](NetLogCaptureMode capture_mode) {
1622                       return CookieKeyedLoadNetLogParams(key, capture_mode);
1623                     });
1624   // Note that |backend_| keeps |this| alive by keeping a reference count.
1625   // If this class is ever converted over to a WeakPtr<> pattern (as TODO it
1626   // should be) this will need to be replaced by a more complex pattern that
1627   // guarantees |loaded_callback| being called even if the class has been
1628   // destroyed. |backend_| needs to outlive |this| to commit changes to disk.
1629   backend_->LoadCookiesForKey(
1630       key, base::BindOnce(&SQLitePersistentCookieStore::CompleteKeyedLoad, this,
1631                           key, std::move(loaded_callback)));
1632 }
1633 
AddCookie(const CanonicalCookie & cc)1634 void SQLitePersistentCookieStore::AddCookie(const CanonicalCookie& cc) {
1635   backend_->AddCookie(cc);
1636 }
1637 
UpdateCookieAccessTime(const CanonicalCookie & cc)1638 void SQLitePersistentCookieStore::UpdateCookieAccessTime(
1639     const CanonicalCookie& cc) {
1640   backend_->UpdateCookieAccessTime(cc);
1641 }
1642 
DeleteCookie(const CanonicalCookie & cc)1643 void SQLitePersistentCookieStore::DeleteCookie(const CanonicalCookie& cc) {
1644   backend_->DeleteCookie(cc);
1645 }
1646 
SetForceKeepSessionState()1647 void SQLitePersistentCookieStore::SetForceKeepSessionState() {
1648   // This store never discards session-only cookies, so this call has no effect.
1649 }
1650 
SetBeforeCommitCallback(base::RepeatingClosure callback)1651 void SQLitePersistentCookieStore::SetBeforeCommitCallback(
1652     base::RepeatingClosure callback) {
1653   backend_->SetBeforeCommitCallback(std::move(callback));
1654 }
1655 
Flush(base::OnceClosure callback)1656 void SQLitePersistentCookieStore::Flush(base::OnceClosure callback) {
1657   backend_->Flush(std::move(callback));
1658 }
1659 
GetQueueLengthForTesting()1660 size_t SQLitePersistentCookieStore::GetQueueLengthForTesting() {
1661   return backend_->GetQueueLengthForTesting();
1662 }
1663 
~SQLitePersistentCookieStore()1664 SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
1665   net_log_.AddEventWithStringParams(
1666       NetLogEventType::COOKIE_PERSISTENT_STORE_CLOSED, "type",
1667       "SQLitePersistentCookieStore");
1668   backend_->Close();
1669 }
1670 
CompleteLoad(LoadedCallback callback,std::vector<std::unique_ptr<CanonicalCookie>> cookie_list)1671 void SQLitePersistentCookieStore::CompleteLoad(
1672     LoadedCallback callback,
1673     std::vector<std::unique_ptr<CanonicalCookie>> cookie_list) {
1674   net_log_.EndEvent(NetLogEventType::COOKIE_PERSISTENT_STORE_LOAD);
1675   std::move(callback).Run(std::move(cookie_list));
1676 }
1677 
CompleteKeyedLoad(const std::string & key,LoadedCallback callback,std::vector<std::unique_ptr<CanonicalCookie>> cookie_list)1678 void SQLitePersistentCookieStore::CompleteKeyedLoad(
1679     const std::string& key,
1680     LoadedCallback callback,
1681     std::vector<std::unique_ptr<CanonicalCookie>> cookie_list) {
1682   net_log_.AddEventWithStringParams(
1683       NetLogEventType::COOKIE_PERSISTENT_STORE_KEY_LOAD_COMPLETED, "domain",
1684       key);
1685   std::move(callback).Run(std::move(cookie_list));
1686 }
1687 
1688 }  // namespace net
1689