1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
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 "content/browser/net/sqlite_persistent_cookie_store.h"
6
7#include <list>
8#include <map>
9#include <set>
10#include <utility>
11
12#include "base/basictypes.h"
13#include "base/bind.h"
14#include "base/callback.h"
15#include "base/command_line.h"
16#include "base/files/file_path.h"
17#include "base/files/file_util.h"
18#include "base/location.h"
19#include "base/logging.h"
20#include "base/memory/ref_counted.h"
21#include "base/memory/scoped_ptr.h"
22#include "base/metrics/histogram.h"
23#include "base/sequenced_task_runner.h"
24#include "base/strings/string_util.h"
25#include "base/strings/stringprintf.h"
26#include "base/synchronization/lock.h"
27#include "base/threading/sequenced_worker_pool.h"
28#include "base/time/time.h"
29#include "content/public/browser/browser_thread.h"
30#include "content/public/browser/cookie_crypto_delegate.h"
31#include "content/public/browser/cookie_store_factory.h"
32#include "content/public/common/content_switches.h"
33#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
34#include "net/cookies/canonical_cookie.h"
35#include "net/cookies/cookie_constants.h"
36#include "net/cookies/cookie_util.h"
37#include "sql/error_delegate_util.h"
38#include "sql/meta_table.h"
39#include "sql/statement.h"
40#include "sql/transaction.h"
41#include "storage/browser/quota/special_storage_policy.h"
42#include "third_party/sqlite/sqlite3.h"
43#include "url/gurl.h"
44
45using base::Time;
46
47namespace content {
48
49// This class is designed to be shared between any client thread and the
50// background task runner. It batches operations and commits them on a timer.
51//
52// SQLitePersistentCookieStore::Load is called to load all cookies.  It
53// delegates to Backend::Load, which posts a Backend::LoadAndNotifyOnDBThread
54// task to the background runner.  This task calls Backend::ChainLoadCookies(),
55// which repeatedly posts itself to the BG runner to load each eTLD+1's cookies
56// in separate tasks.  When this is complete, Backend::CompleteLoadOnIOThread is
57// posted to the client runner, which notifies the caller of
58// SQLitePersistentCookieStore::Load that the load is complete.
59//
60// If a priority load request is invoked via SQLitePersistentCookieStore::
61// LoadCookiesForKey, it is delegated to Backend::LoadCookiesForKey, which posts
62// Backend::LoadKeyAndNotifyOnDBThread to the BG runner. That routine loads just
63// that single domain key (eTLD+1)'s cookies, and posts a Backend::
64// CompleteLoadForKeyOnIOThread to the client runner to notify the caller of
65// SQLitePersistentCookieStore::LoadCookiesForKey that that load is complete.
66//
67// Subsequent to loading, mutations may be queued by any thread using
68// AddCookie, UpdateCookieAccessTime, and DeleteCookie. These are flushed to
69// disk on the BG runner every 30 seconds, 512 operations, or call to Flush(),
70// whichever occurs first.
71class SQLitePersistentCookieStore::Backend
72    : public base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend> {
73 public:
74  Backend(
75      const base::FilePath& path,
76      const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
77      const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
78      bool restore_old_session_cookies,
79      storage::SpecialStoragePolicy* special_storage_policy,
80      CookieCryptoDelegate* crypto_delegate)
81      : path_(path),
82        num_pending_(0),
83        force_keep_session_state_(false),
84        initialized_(false),
85        corruption_detected_(false),
86        restore_old_session_cookies_(restore_old_session_cookies),
87        special_storage_policy_(special_storage_policy),
88        num_cookies_read_(0),
89        client_task_runner_(client_task_runner),
90        background_task_runner_(background_task_runner),
91        num_priority_waiting_(0),
92        total_priority_requests_(0),
93        crypto_(crypto_delegate) {}
94
95  // Creates or loads the SQLite database.
96  void Load(const LoadedCallback& loaded_callback);
97
98  // Loads cookies for the domain key (eTLD+1).
99  void LoadCookiesForKey(const std::string& domain,
100      const LoadedCallback& loaded_callback);
101
102  // Batch a cookie addition.
103  void AddCookie(const net::CanonicalCookie& cc);
104
105  // Batch a cookie access time update.
106  void UpdateCookieAccessTime(const net::CanonicalCookie& cc);
107
108  // Batch a cookie deletion.
109  void DeleteCookie(const net::CanonicalCookie& cc);
110
111  // Commit pending operations as soon as possible.
112  void Flush(const base::Closure& callback);
113
114  // Commit any pending operations and close the database.  This must be called
115  // before the object is destructed.
116  void Close();
117
118  void SetForceKeepSessionState();
119
120 private:
121  friend class base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend>;
122
123  // You should call Close() before destructing this object.
124  ~Backend() {
125    DCHECK(!db_.get()) << "Close should have already been called.";
126    DCHECK(num_pending_ == 0 && pending_.empty());
127  }
128
129  // Database upgrade statements.
130  bool EnsureDatabaseVersion();
131
132  class PendingOperation {
133   public:
134    typedef enum {
135      COOKIE_ADD,
136      COOKIE_UPDATEACCESS,
137      COOKIE_DELETE,
138    } OperationType;
139
140    PendingOperation(OperationType op, const net::CanonicalCookie& cc)
141        : op_(op), cc_(cc) { }
142
143    OperationType op() const { return op_; }
144    const net::CanonicalCookie& cc() const { return cc_; }
145
146   private:
147    OperationType op_;
148    net::CanonicalCookie cc_;
149  };
150
151 private:
152  // Creates or loads the SQLite database on background runner.
153  void LoadAndNotifyInBackground(const LoadedCallback& loaded_callback,
154                                 const base::Time& posted_at);
155
156  // Loads cookies for the domain key (eTLD+1) on background runner.
157  void LoadKeyAndNotifyInBackground(const std::string& domains,
158                                    const LoadedCallback& loaded_callback,
159                                    const base::Time& posted_at);
160
161  // Notifies the CookieMonster when loading completes for a specific domain key
162  // or for all domain keys. Triggers the callback and passes it all cookies
163  // that have been loaded from DB since last IO notification.
164  void Notify(const LoadedCallback& loaded_callback, bool load_success);
165
166  // Sends notification when the entire store is loaded, and reports metrics
167  // for the total time to load and aggregated results from any priority loads
168  // that occurred.
169  void CompleteLoadInForeground(const LoadedCallback& loaded_callback,
170                                bool load_success);
171
172  // Sends notification when a single priority load completes. Updates priority
173  // load metric data. The data is sent only after the final load completes.
174  void CompleteLoadForKeyInForeground(const LoadedCallback& loaded_callback,
175                                      bool load_success);
176
177  // Sends all metrics, including posting a ReportMetricsInBackground task.
178  // Called after all priority and regular loading is complete.
179  void ReportMetrics();
180
181  // Sends background-runner owned metrics (i.e., the combined duration of all
182  // BG-runner tasks).
183  void ReportMetricsInBackground();
184
185  // Initialize the data base.
186  bool InitializeDatabase();
187
188  // Loads cookies for the next domain key from the DB, then either reschedules
189  // itself or schedules the provided callback to run on the client runner (if
190  // all domains are loaded).
191  void ChainLoadCookies(const LoadedCallback& loaded_callback);
192
193  // Load all cookies for a set of domains/hosts
194  bool LoadCookiesForDomains(const std::set<std::string>& key);
195
196  // Batch a cookie operation (add or delete)
197  void BatchOperation(PendingOperation::OperationType op,
198                      const net::CanonicalCookie& cc);
199  // Commit our pending operations to the database.
200  void Commit();
201  // Close() executed on the background runner.
202  void InternalBackgroundClose();
203
204  void DeleteSessionCookiesOnStartup();
205
206  void DeleteSessionCookiesOnShutdown();
207
208  void DatabaseErrorCallback(int error, sql::Statement* stmt);
209  void KillDatabase();
210
211  void PostBackgroundTask(const tracked_objects::Location& origin,
212                          const base::Closure& task);
213  void PostClientTask(const tracked_objects::Location& origin,
214                      const base::Closure& task);
215
216  base::FilePath path_;
217  scoped_ptr<sql::Connection> db_;
218  sql::MetaTable meta_table_;
219
220  typedef std::list<PendingOperation*> PendingOperationsList;
221  PendingOperationsList pending_;
222  PendingOperationsList::size_type num_pending_;
223  // True if the persistent store should skip delete on exit rules.
224  bool force_keep_session_state_;
225  // Guard |cookies_|, |pending_|, |num_pending_|, |force_keep_session_state_|
226  base::Lock lock_;
227
228  // Temporary buffer for cookies loaded from DB. Accumulates cookies to reduce
229  // the number of messages sent to the client runner. Sent back in response to
230  // individual load requests for domain keys or when all loading completes.
231  std::vector<net::CanonicalCookie*> cookies_;
232
233  // Map of domain keys(eTLD+1) to domains/hosts that are to be loaded from DB.
234  std::map<std::string, std::set<std::string> > keys_to_load_;
235
236  // Map of (domain keys(eTLD+1), is secure cookie) to number of cookies in the
237  // database.
238  typedef std::pair<std::string, bool> CookieOrigin;
239  typedef std::map<CookieOrigin, int> CookiesPerOriginMap;
240  CookiesPerOriginMap cookies_per_origin_;
241
242  // Indicates if DB has been initialized.
243  bool initialized_;
244
245  // Indicates if the kill-database callback has been scheduled.
246  bool corruption_detected_;
247
248  // If false, we should filter out session cookies when reading the DB.
249  bool restore_old_session_cookies_;
250
251  // Policy defining what data is deleted on shutdown.
252  scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy_;
253
254  // The cumulative time spent loading the cookies on the background runner.
255  // Incremented and reported from the background runner.
256  base::TimeDelta cookie_load_duration_;
257
258  // The total number of cookies read. Incremented and reported on the
259  // background runner.
260  int num_cookies_read_;
261
262  scoped_refptr<base::SequencedTaskRunner> client_task_runner_;
263  scoped_refptr<base::SequencedTaskRunner> background_task_runner_;
264
265  // Guards the following metrics-related properties (only accessed when
266  // starting/completing priority loads or completing the total load).
267  base::Lock metrics_lock_;
268  int num_priority_waiting_;
269  // The total number of priority requests.
270  int total_priority_requests_;
271  // The time when |num_priority_waiting_| incremented to 1.
272  base::Time current_priority_wait_start_;
273  // The cumulative duration of time when |num_priority_waiting_| was greater
274  // than 1.
275  base::TimeDelta priority_wait_duration_;
276  // Class with functions that do cryptographic operations (for protecting
277  // cookies stored persistently).
278  //
279  // Not owned.
280  CookieCryptoDelegate* crypto_;
281
282  DISALLOW_COPY_AND_ASSIGN(Backend);
283};
284
285namespace {
286
287// Version number of the database.
288//
289// Version 7 adds encrypted values.  Old values will continue to be used but
290// all new values written will be encrypted on selected operating systems.  New
291// records read by old clients will simply get an empty cookie value while old
292// records read by new clients will continue to operate with the unencrypted
293// version.  New and old clients alike will always write/update records with
294// what they support.
295//
296// Version 6 adds cookie priorities. This allows developers to influence the
297// order in which cookies are evicted in order to meet domain cookie limits.
298//
299// Version 5 adds the columns has_expires and is_persistent, so that the
300// database can store session cookies as well as persistent cookies. Databases
301// of version 5 are incompatible with older versions of code. If a database of
302// version 5 is read by older code, session cookies will be treated as normal
303// cookies. Currently, these fields are written, but not read anymore.
304//
305// In version 4, we migrated the time epoch.  If you open the DB with an older
306// version on Mac or Linux, the times will look wonky, but the file will likely
307// be usable. On Windows version 3 and 4 are the same.
308//
309// Version 3 updated the database to include the last access time, so we can
310// expire them in decreasing order of use when we've reached the maximum
311// number of cookies.
312const int kCurrentVersionNumber = 7;
313const int kCompatibleVersionNumber = 5;
314
315// Possible values for the 'priority' column.
316enum DBCookiePriority {
317  kCookiePriorityLow = 0,
318  kCookiePriorityMedium = 1,
319  kCookiePriorityHigh = 2,
320};
321
322DBCookiePriority CookiePriorityToDBCookiePriority(net::CookiePriority value) {
323  switch (value) {
324    case net::COOKIE_PRIORITY_LOW:
325      return kCookiePriorityLow;
326    case net::COOKIE_PRIORITY_MEDIUM:
327      return kCookiePriorityMedium;
328    case net::COOKIE_PRIORITY_HIGH:
329      return kCookiePriorityHigh;
330  }
331
332  NOTREACHED();
333  return kCookiePriorityMedium;
334}
335
336net::CookiePriority DBCookiePriorityToCookiePriority(DBCookiePriority value) {
337  switch (value) {
338    case kCookiePriorityLow:
339      return net::COOKIE_PRIORITY_LOW;
340    case kCookiePriorityMedium:
341      return net::COOKIE_PRIORITY_MEDIUM;
342    case kCookiePriorityHigh:
343      return net::COOKIE_PRIORITY_HIGH;
344  }
345
346  NOTREACHED();
347  return net::COOKIE_PRIORITY_DEFAULT;
348}
349
350// Increments a specified TimeDelta by the duration between this object's
351// constructor and destructor. Not thread safe. Multiple instances may be
352// created with the same delta instance as long as their lifetimes are nested.
353// The shortest lived instances have no impact.
354class IncrementTimeDelta {
355 public:
356  explicit IncrementTimeDelta(base::TimeDelta* delta) :
357      delta_(delta),
358      original_value_(*delta),
359      start_(base::Time::Now()) {}
360
361  ~IncrementTimeDelta() {
362    *delta_ = original_value_ + base::Time::Now() - start_;
363  }
364
365 private:
366  base::TimeDelta* delta_;
367  base::TimeDelta original_value_;
368  base::Time start_;
369
370  DISALLOW_COPY_AND_ASSIGN(IncrementTimeDelta);
371};
372
373// Initializes the cookies table, returning true on success.
374bool InitTable(sql::Connection* db) {
375  if (!db->DoesTableExist("cookies")) {
376    std::string stmt(base::StringPrintf(
377        "CREATE TABLE cookies ("
378            "creation_utc INTEGER NOT NULL UNIQUE PRIMARY KEY,"
379            "host_key TEXT NOT NULL,"
380            "name TEXT NOT NULL,"
381            "value TEXT NOT NULL,"
382            "path TEXT NOT NULL,"
383            "expires_utc INTEGER NOT NULL,"
384            "secure INTEGER NOT NULL,"
385            "httponly INTEGER NOT NULL,"
386            "last_access_utc INTEGER NOT NULL, "
387            "has_expires INTEGER NOT NULL DEFAULT 1, "
388            "persistent INTEGER NOT NULL DEFAULT 1,"
389            "priority INTEGER NOT NULL DEFAULT %d,"
390            "encrypted_value BLOB DEFAULT '')",
391        CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT)));
392    if (!db->Execute(stmt.c_str()))
393      return false;
394  }
395
396  // Older code created an index on creation_utc, which is already
397  // primary key for the table.
398  if (!db->Execute("DROP INDEX IF EXISTS cookie_times"))
399    return false;
400
401  if (!db->Execute("CREATE INDEX IF NOT EXISTS domain ON cookies(host_key)"))
402    return false;
403
404  return true;
405}
406
407}  // namespace
408
409void SQLitePersistentCookieStore::Backend::Load(
410    const LoadedCallback& loaded_callback) {
411  // This function should be called only once per instance.
412  DCHECK(!db_.get());
413  PostBackgroundTask(FROM_HERE, base::Bind(
414      &Backend::LoadAndNotifyInBackground, this,
415      loaded_callback, base::Time::Now()));
416}
417
418void SQLitePersistentCookieStore::Backend::LoadCookiesForKey(
419    const std::string& key,
420    const LoadedCallback& loaded_callback) {
421  {
422    base::AutoLock locked(metrics_lock_);
423    if (num_priority_waiting_ == 0)
424      current_priority_wait_start_ = base::Time::Now();
425    num_priority_waiting_++;
426    total_priority_requests_++;
427  }
428
429  PostBackgroundTask(FROM_HERE, base::Bind(
430      &Backend::LoadKeyAndNotifyInBackground,
431      this, key, loaded_callback, base::Time::Now()));
432}
433
434void SQLitePersistentCookieStore::Backend::LoadAndNotifyInBackground(
435    const LoadedCallback& loaded_callback, const base::Time& posted_at) {
436  DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
437  IncrementTimeDelta increment(&cookie_load_duration_);
438
439  UMA_HISTOGRAM_CUSTOM_TIMES(
440      "Cookie.TimeLoadDBQueueWait",
441      base::Time::Now() - posted_at,
442      base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
443      50);
444
445  if (!InitializeDatabase()) {
446    PostClientTask(FROM_HERE, base::Bind(
447        &Backend::CompleteLoadInForeground, this, loaded_callback, false));
448  } else {
449    ChainLoadCookies(loaded_callback);
450  }
451}
452
453void SQLitePersistentCookieStore::Backend::LoadKeyAndNotifyInBackground(
454    const std::string& key,
455    const LoadedCallback& loaded_callback,
456    const base::Time& posted_at) {
457  DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
458  IncrementTimeDelta increment(&cookie_load_duration_);
459
460  UMA_HISTOGRAM_CUSTOM_TIMES(
461      "Cookie.TimeKeyLoadDBQueueWait",
462      base::Time::Now() - posted_at,
463      base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
464      50);
465
466  bool success = false;
467  if (InitializeDatabase()) {
468    std::map<std::string, std::set<std::string> >::iterator
469      it = keys_to_load_.find(key);
470    if (it != keys_to_load_.end()) {
471      success = LoadCookiesForDomains(it->second);
472      keys_to_load_.erase(it);
473    } else {
474      success = true;
475    }
476  }
477
478  PostClientTask(FROM_HERE, base::Bind(
479      &SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground,
480      this, loaded_callback, success));
481}
482
483void SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground(
484    const LoadedCallback& loaded_callback,
485    bool load_success) {
486  DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
487
488  Notify(loaded_callback, load_success);
489
490  {
491    base::AutoLock locked(metrics_lock_);
492    num_priority_waiting_--;
493    if (num_priority_waiting_ == 0) {
494      priority_wait_duration_ +=
495          base::Time::Now() - current_priority_wait_start_;
496    }
497  }
498
499}
500
501void SQLitePersistentCookieStore::Backend::ReportMetricsInBackground() {
502  UMA_HISTOGRAM_CUSTOM_TIMES(
503      "Cookie.TimeLoad",
504      cookie_load_duration_,
505      base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
506      50);
507}
508
509void SQLitePersistentCookieStore::Backend::ReportMetrics() {
510  PostBackgroundTask(FROM_HERE, base::Bind(
511      &SQLitePersistentCookieStore::Backend::ReportMetricsInBackground, this));
512
513  {
514    base::AutoLock locked(metrics_lock_);
515    UMA_HISTOGRAM_CUSTOM_TIMES(
516        "Cookie.PriorityBlockingTime",
517        priority_wait_duration_,
518        base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
519        50);
520
521    UMA_HISTOGRAM_COUNTS_100(
522        "Cookie.PriorityLoadCount",
523        total_priority_requests_);
524
525    UMA_HISTOGRAM_COUNTS_10000(
526        "Cookie.NumberOfLoadedCookies",
527        num_cookies_read_);
528  }
529}
530
531void SQLitePersistentCookieStore::Backend::CompleteLoadInForeground(
532    const LoadedCallback& loaded_callback, bool load_success) {
533  Notify(loaded_callback, load_success);
534
535  if (load_success)
536    ReportMetrics();
537}
538
539void SQLitePersistentCookieStore::Backend::Notify(
540    const LoadedCallback& loaded_callback,
541    bool load_success) {
542  DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
543
544  std::vector<net::CanonicalCookie*> cookies;
545  {
546    base::AutoLock locked(lock_);
547    cookies.swap(cookies_);
548  }
549
550  loaded_callback.Run(cookies);
551}
552
553bool SQLitePersistentCookieStore::Backend::InitializeDatabase() {
554  DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
555
556  if (initialized_ || corruption_detected_) {
557    // Return false if we were previously initialized but the DB has since been
558    // closed, or if corruption caused a database reset during initialization.
559    return db_ != NULL;
560  }
561
562  base::Time start = base::Time::Now();
563
564  const base::FilePath dir = path_.DirName();
565  if (!base::PathExists(dir) && !base::CreateDirectory(dir)) {
566    return false;
567  }
568
569  int64 db_size = 0;
570  if (base::GetFileSize(path_, &db_size))
571    UMA_HISTOGRAM_COUNTS("Cookie.DBSizeInKB", db_size / 1024 );
572
573  db_.reset(new sql::Connection);
574  db_->set_histogram_tag("Cookie");
575
576  // Unretained to avoid a ref loop with |db_|.
577  db_->set_error_callback(
578      base::Bind(&SQLitePersistentCookieStore::Backend::DatabaseErrorCallback,
579                 base::Unretained(this)));
580
581  if (!db_->Open(path_)) {
582    NOTREACHED() << "Unable to open cookie DB.";
583    if (corruption_detected_)
584      db_->Raze();
585    meta_table_.Reset();
586    db_.reset();
587    return false;
588  }
589
590  if (!EnsureDatabaseVersion() || !InitTable(db_.get())) {
591    NOTREACHED() << "Unable to open cookie DB.";
592    if (corruption_detected_)
593      db_->Raze();
594    meta_table_.Reset();
595    db_.reset();
596    return false;
597  }
598
599  UMA_HISTOGRAM_CUSTOM_TIMES(
600      "Cookie.TimeInitializeDB",
601      base::Time::Now() - start,
602      base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
603      50);
604
605  start = base::Time::Now();
606
607  // Retrieve all the domains
608  sql::Statement smt(db_->GetUniqueStatement(
609    "SELECT DISTINCT host_key FROM cookies"));
610
611  if (!smt.is_valid()) {
612    if (corruption_detected_)
613      db_->Raze();
614    meta_table_.Reset();
615    db_.reset();
616    return false;
617  }
618
619  std::vector<std::string> host_keys;
620  while (smt.Step())
621    host_keys.push_back(smt.ColumnString(0));
622
623  UMA_HISTOGRAM_CUSTOM_TIMES(
624      "Cookie.TimeLoadDomains",
625      base::Time::Now() - start,
626      base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
627      50);
628
629  base::Time start_parse = base::Time::Now();
630
631  // Build a map of domain keys (always eTLD+1) to domains.
632  for (size_t idx = 0; idx < host_keys.size(); ++idx) {
633    const std::string& domain = host_keys[idx];
634    std::string key =
635        net::registry_controlled_domains::GetDomainAndRegistry(
636            domain,
637            net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
638
639    keys_to_load_[key].insert(domain);
640  }
641
642  UMA_HISTOGRAM_CUSTOM_TIMES(
643      "Cookie.TimeParseDomains",
644      base::Time::Now() - start_parse,
645      base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
646      50);
647
648  UMA_HISTOGRAM_CUSTOM_TIMES(
649      "Cookie.TimeInitializeDomainMap",
650      base::Time::Now() - start,
651      base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
652      50);
653
654  initialized_ = true;
655  return true;
656}
657
658void SQLitePersistentCookieStore::Backend::ChainLoadCookies(
659    const LoadedCallback& loaded_callback) {
660  DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
661  IncrementTimeDelta increment(&cookie_load_duration_);
662
663  bool load_success = true;
664
665  if (!db_) {
666    // Close() has been called on this store.
667    load_success = false;
668  } else if (keys_to_load_.size() > 0) {
669    // Load cookies for the first domain key.
670    std::map<std::string, std::set<std::string> >::iterator
671      it = keys_to_load_.begin();
672    load_success = LoadCookiesForDomains(it->second);
673    keys_to_load_.erase(it);
674  }
675
676  // If load is successful and there are more domain keys to be loaded,
677  // then post a background task to continue chain-load;
678  // Otherwise notify on client runner.
679  if (load_success && keys_to_load_.size() > 0) {
680    PostBackgroundTask(FROM_HERE, base::Bind(
681        &Backend::ChainLoadCookies, this, loaded_callback));
682  } else {
683    PostClientTask(FROM_HERE, base::Bind(
684        &Backend::CompleteLoadInForeground, this,
685        loaded_callback, load_success));
686    if (load_success && !restore_old_session_cookies_)
687      DeleteSessionCookiesOnStartup();
688  }
689}
690
691bool SQLitePersistentCookieStore::Backend::LoadCookiesForDomains(
692  const std::set<std::string>& domains) {
693  DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
694
695  sql::Statement smt;
696  if (restore_old_session_cookies_) {
697    smt.Assign(db_->GetCachedStatement(
698        SQL_FROM_HERE,
699        "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
700        "expires_utc, secure, httponly, last_access_utc, has_expires, "
701        "persistent, priority FROM cookies WHERE host_key = ?"));
702  } else {
703    smt.Assign(db_->GetCachedStatement(
704        SQL_FROM_HERE,
705        "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
706        "expires_utc, secure, httponly, last_access_utc, has_expires, "
707        "persistent, priority FROM cookies WHERE host_key = ? "
708        "AND persistent = 1"));
709  }
710  if (!smt.is_valid()) {
711    smt.Clear();  // Disconnect smt_ref from db_.
712    meta_table_.Reset();
713    db_.reset();
714    return false;
715  }
716
717  std::vector<net::CanonicalCookie*> cookies;
718  std::set<std::string>::const_iterator it = domains.begin();
719  for (; it != domains.end(); ++it) {
720    smt.BindString(0, *it);
721    while (smt.Step()) {
722      std::string value;
723      std::string encrypted_value = smt.ColumnString(4);
724      if (!encrypted_value.empty() && crypto_) {
725        crypto_->DecryptString(encrypted_value, &value);
726      } else {
727        DCHECK(encrypted_value.empty());
728        value = smt.ColumnString(3);
729      }
730      scoped_ptr<net::CanonicalCookie> cc(new net::CanonicalCookie(
731          // The "source" URL is not used with persisted cookies.
732          GURL(),                                         // Source
733          smt.ColumnString(2),                            // name
734          value,                                          // value
735          smt.ColumnString(1),                            // domain
736          smt.ColumnString(5),                            // path
737          Time::FromInternalValue(smt.ColumnInt64(0)),    // creation_utc
738          Time::FromInternalValue(smt.ColumnInt64(6)),    // expires_utc
739          Time::FromInternalValue(smt.ColumnInt64(9)),    // last_access_utc
740          smt.ColumnInt(7) != 0,                          // secure
741          smt.ColumnInt(8) != 0,                          // httponly
742          DBCookiePriorityToCookiePriority(
743              static_cast<DBCookiePriority>(smt.ColumnInt(12)))));  // priority
744      DLOG_IF(WARNING,
745              cc->CreationDate() > Time::Now()) << L"CreationDate too recent";
746      cookies_per_origin_[CookieOrigin(cc->Domain(), cc->IsSecure())]++;
747      cookies.push_back(cc.release());
748      ++num_cookies_read_;
749    }
750    smt.Reset(true);
751  }
752  {
753    base::AutoLock locked(lock_);
754    cookies_.insert(cookies_.end(), cookies.begin(), cookies.end());
755  }
756  return true;
757}
758
759bool SQLitePersistentCookieStore::Backend::EnsureDatabaseVersion() {
760  // Version check.
761  if (!meta_table_.Init(
762      db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) {
763    return false;
764  }
765
766  if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) {
767    LOG(WARNING) << "Cookie database is too new.";
768    return false;
769  }
770
771  int cur_version = meta_table_.GetVersionNumber();
772  if (cur_version == 2) {
773    sql::Transaction transaction(db_.get());
774    if (!transaction.Begin())
775      return false;
776    if (!db_->Execute("ALTER TABLE cookies ADD COLUMN last_access_utc "
777                     "INTEGER DEFAULT 0") ||
778        !db_->Execute("UPDATE cookies SET last_access_utc = creation_utc")) {
779      LOG(WARNING) << "Unable to update cookie database to version 3.";
780      return false;
781    }
782    ++cur_version;
783    meta_table_.SetVersionNumber(cur_version);
784    meta_table_.SetCompatibleVersionNumber(
785        std::min(cur_version, kCompatibleVersionNumber));
786    transaction.Commit();
787  }
788
789  if (cur_version == 3) {
790    // The time epoch changed for Mac & Linux in this version to match Windows.
791    // This patch came after the main epoch change happened, so some
792    // developers have "good" times for cookies added by the more recent
793    // versions. So we have to be careful to only update times that are under
794    // the old system (which will appear to be from before 1970 in the new
795    // system). The magic number used below is 1970 in our time units.
796    sql::Transaction transaction(db_.get());
797    transaction.Begin();
798#if !defined(OS_WIN)
799    ignore_result(db_->Execute(
800        "UPDATE cookies "
801        "SET creation_utc = creation_utc + 11644473600000000 "
802        "WHERE rowid IN "
803        "(SELECT rowid FROM cookies WHERE "
804          "creation_utc > 0 AND creation_utc < 11644473600000000)"));
805    ignore_result(db_->Execute(
806        "UPDATE cookies "
807        "SET expires_utc = expires_utc + 11644473600000000 "
808        "WHERE rowid IN "
809        "(SELECT rowid FROM cookies WHERE "
810          "expires_utc > 0 AND expires_utc < 11644473600000000)"));
811    ignore_result(db_->Execute(
812        "UPDATE cookies "
813        "SET last_access_utc = last_access_utc + 11644473600000000 "
814        "WHERE rowid IN "
815        "(SELECT rowid FROM cookies WHERE "
816          "last_access_utc > 0 AND last_access_utc < 11644473600000000)"));
817#endif
818    ++cur_version;
819    meta_table_.SetVersionNumber(cur_version);
820    transaction.Commit();
821  }
822
823  if (cur_version == 4) {
824    const base::TimeTicks start_time = base::TimeTicks::Now();
825    sql::Transaction transaction(db_.get());
826    if (!transaction.Begin())
827      return false;
828    if (!db_->Execute("ALTER TABLE cookies "
829                      "ADD COLUMN has_expires INTEGER DEFAULT 1") ||
830        !db_->Execute("ALTER TABLE cookies "
831                      "ADD COLUMN persistent INTEGER DEFAULT 1")) {
832      LOG(WARNING) << "Unable to update cookie database to version 5.";
833      return false;
834    }
835    ++cur_version;
836    meta_table_.SetVersionNumber(cur_version);
837    meta_table_.SetCompatibleVersionNumber(
838        std::min(cur_version, kCompatibleVersionNumber));
839    transaction.Commit();
840    UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV5",
841                        base::TimeTicks::Now() - start_time);
842  }
843
844  if (cur_version == 5) {
845    const base::TimeTicks start_time = base::TimeTicks::Now();
846    sql::Transaction transaction(db_.get());
847    if (!transaction.Begin())
848      return false;
849    // Alter the table to add the priority column with a default value.
850    std::string stmt(base::StringPrintf(
851        "ALTER TABLE cookies ADD COLUMN priority INTEGER DEFAULT %d",
852        CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT)));
853    if (!db_->Execute(stmt.c_str())) {
854      LOG(WARNING) << "Unable to update cookie database to version 6.";
855      return false;
856    }
857    ++cur_version;
858    meta_table_.SetVersionNumber(cur_version);
859    meta_table_.SetCompatibleVersionNumber(
860        std::min(cur_version, kCompatibleVersionNumber));
861    transaction.Commit();
862    UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV6",
863                        base::TimeTicks::Now() - start_time);
864  }
865
866  if (cur_version == 6) {
867    const base::TimeTicks start_time = base::TimeTicks::Now();
868    sql::Transaction transaction(db_.get());
869    if (!transaction.Begin())
870      return false;
871    // Alter the table to add empty "encrypted value" column.
872    if (!db_->Execute("ALTER TABLE cookies "
873                      "ADD COLUMN encrypted_value BLOB DEFAULT ''")) {
874      LOG(WARNING) << "Unable to update cookie database to version 7.";
875      return false;
876    }
877    ++cur_version;
878    meta_table_.SetVersionNumber(cur_version);
879    meta_table_.SetCompatibleVersionNumber(
880        std::min(cur_version, kCompatibleVersionNumber));
881    transaction.Commit();
882    UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV7",
883                        base::TimeTicks::Now() - start_time);
884  }
885
886  // Put future migration cases here.
887
888  if (cur_version < kCurrentVersionNumber) {
889    UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTable", 1);
890
891    meta_table_.Reset();
892    db_.reset(new sql::Connection);
893    if (!base::DeleteFile(path_, false) ||
894        !db_->Open(path_) ||
895        !meta_table_.Init(
896            db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) {
897      UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTableRecoveryFailed", 1);
898      NOTREACHED() << "Unable to reset the cookie DB.";
899      meta_table_.Reset();
900      db_.reset();
901      return false;
902    }
903  }
904
905  return true;
906}
907
908void SQLitePersistentCookieStore::Backend::AddCookie(
909    const net::CanonicalCookie& cc) {
910  BatchOperation(PendingOperation::COOKIE_ADD, cc);
911}
912
913void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime(
914    const net::CanonicalCookie& cc) {
915  BatchOperation(PendingOperation::COOKIE_UPDATEACCESS, cc);
916}
917
918void SQLitePersistentCookieStore::Backend::DeleteCookie(
919    const net::CanonicalCookie& cc) {
920  BatchOperation(PendingOperation::COOKIE_DELETE, cc);
921}
922
923void SQLitePersistentCookieStore::Backend::BatchOperation(
924    PendingOperation::OperationType op,
925    const net::CanonicalCookie& cc) {
926  // Commit every 30 seconds.
927  static const int kCommitIntervalMs = 30 * 1000;
928  // Commit right away if we have more than 512 outstanding operations.
929  static const size_t kCommitAfterBatchSize = 512;
930  DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
931
932  // We do a full copy of the cookie here, and hopefully just here.
933  scoped_ptr<PendingOperation> po(new PendingOperation(op, cc));
934
935  PendingOperationsList::size_type num_pending;
936  {
937    base::AutoLock locked(lock_);
938    pending_.push_back(po.release());
939    num_pending = ++num_pending_;
940  }
941
942  if (num_pending == 1) {
943    // We've gotten our first entry for this batch, fire off the timer.
944    if (!background_task_runner_->PostDelayedTask(
945            FROM_HERE, base::Bind(&Backend::Commit, this),
946            base::TimeDelta::FromMilliseconds(kCommitIntervalMs))) {
947      NOTREACHED() << "background_task_runner_ is not running.";
948    }
949  } else if (num_pending == kCommitAfterBatchSize) {
950    // We've reached a big enough batch, fire off a commit now.
951    PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
952  }
953}
954
955void SQLitePersistentCookieStore::Backend::Commit() {
956  DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
957
958  PendingOperationsList ops;
959  {
960    base::AutoLock locked(lock_);
961    pending_.swap(ops);
962    num_pending_ = 0;
963  }
964
965  // Maybe an old timer fired or we are already Close()'ed.
966  if (!db_.get() || ops.empty())
967    return;
968
969  sql::Statement add_smt(db_->GetCachedStatement(SQL_FROM_HERE,
970      "INSERT INTO cookies (creation_utc, host_key, name, value, "
971      "encrypted_value, path, expires_utc, secure, httponly, last_access_utc, "
972      "has_expires, persistent, priority) "
973      "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"));
974  if (!add_smt.is_valid())
975    return;
976
977  sql::Statement update_access_smt(db_->GetCachedStatement(SQL_FROM_HERE,
978      "UPDATE cookies SET last_access_utc=? WHERE creation_utc=?"));
979  if (!update_access_smt.is_valid())
980    return;
981
982  sql::Statement del_smt(db_->GetCachedStatement(SQL_FROM_HERE,
983                         "DELETE FROM cookies WHERE creation_utc=?"));
984  if (!del_smt.is_valid())
985    return;
986
987  sql::Transaction transaction(db_.get());
988  if (!transaction.Begin())
989    return;
990
991  for (PendingOperationsList::iterator it = ops.begin();
992       it != ops.end(); ++it) {
993    // Free the cookies as we commit them to the database.
994    scoped_ptr<PendingOperation> po(*it);
995    switch (po->op()) {
996      case PendingOperation::COOKIE_ADD:
997        cookies_per_origin_[
998            CookieOrigin(po->cc().Domain(), po->cc().IsSecure())]++;
999        add_smt.Reset(true);
1000        add_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1001        add_smt.BindString(1, po->cc().Domain());
1002        add_smt.BindString(2, po->cc().Name());
1003        if (crypto_) {
1004          std::string encrypted_value;
1005          add_smt.BindCString(3, "");  // value
1006          crypto_->EncryptString(po->cc().Value(), &encrypted_value);
1007          // BindBlob() immediately makes an internal copy of the data.
1008          add_smt.BindBlob(4, encrypted_value.data(),
1009                           static_cast<int>(encrypted_value.length()));
1010        } else {
1011          add_smt.BindString(3, po->cc().Value());
1012          add_smt.BindBlob(4, "", 0);  // encrypted_value
1013        }
1014        add_smt.BindString(5, po->cc().Path());
1015        add_smt.BindInt64(6, po->cc().ExpiryDate().ToInternalValue());
1016        add_smt.BindInt(7, po->cc().IsSecure());
1017        add_smt.BindInt(8, po->cc().IsHttpOnly());
1018        add_smt.BindInt64(9, po->cc().LastAccessDate().ToInternalValue());
1019        add_smt.BindInt(10, po->cc().IsPersistent());
1020        add_smt.BindInt(11, po->cc().IsPersistent());
1021        add_smt.BindInt(
1022            12, CookiePriorityToDBCookiePriority(po->cc().Priority()));
1023        if (!add_smt.Run())
1024          NOTREACHED() << "Could not add a cookie to the DB.";
1025        break;
1026
1027      case PendingOperation::COOKIE_UPDATEACCESS:
1028        update_access_smt.Reset(true);
1029        update_access_smt.BindInt64(0,
1030            po->cc().LastAccessDate().ToInternalValue());
1031        update_access_smt.BindInt64(1,
1032            po->cc().CreationDate().ToInternalValue());
1033        if (!update_access_smt.Run())
1034          NOTREACHED() << "Could not update cookie last access time in the DB.";
1035        break;
1036
1037      case PendingOperation::COOKIE_DELETE:
1038        cookies_per_origin_[
1039            CookieOrigin(po->cc().Domain(), po->cc().IsSecure())]--;
1040        del_smt.Reset(true);
1041        del_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1042        if (!del_smt.Run())
1043          NOTREACHED() << "Could not delete a cookie from the DB.";
1044        break;
1045
1046      default:
1047        NOTREACHED();
1048        break;
1049    }
1050  }
1051  bool succeeded = transaction.Commit();
1052  UMA_HISTOGRAM_ENUMERATION("Cookie.BackingStoreUpdateResults",
1053                            succeeded ? 0 : 1, 2);
1054}
1055
1056void SQLitePersistentCookieStore::Backend::Flush(
1057    const base::Closure& callback) {
1058  DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
1059  PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
1060
1061  if (!callback.is_null()) {
1062    // We want the completion task to run immediately after Commit() returns.
1063    // Posting it from here means there is less chance of another task getting
1064    // onto the message queue first, than if we posted it from Commit() itself.
1065    PostBackgroundTask(FROM_HERE, callback);
1066  }
1067}
1068
1069// Fire off a close message to the background runner.  We could still have a
1070// pending commit timer or Load operations holding references on us, but if/when
1071// this fires we will already have been cleaned up and it will be ignored.
1072void SQLitePersistentCookieStore::Backend::Close() {
1073  if (background_task_runner_->RunsTasksOnCurrentThread()) {
1074    InternalBackgroundClose();
1075  } else {
1076    // Must close the backend on the background runner.
1077    PostBackgroundTask(FROM_HERE,
1078                       base::Bind(&Backend::InternalBackgroundClose, this));
1079  }
1080}
1081
1082void SQLitePersistentCookieStore::Backend::InternalBackgroundClose() {
1083  DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1084  // Commit any pending operations
1085  Commit();
1086
1087  if (!force_keep_session_state_ && special_storage_policy_.get() &&
1088      special_storage_policy_->HasSessionOnlyOrigins()) {
1089    DeleteSessionCookiesOnShutdown();
1090  }
1091
1092  meta_table_.Reset();
1093  db_.reset();
1094}
1095
1096void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnShutdown() {
1097  DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1098
1099  if (!db_)
1100    return;
1101
1102  if (!special_storage_policy_.get())
1103    return;
1104
1105  sql::Statement del_smt(db_->GetCachedStatement(
1106      SQL_FROM_HERE, "DELETE FROM cookies WHERE host_key=? AND secure=?"));
1107  if (!del_smt.is_valid()) {
1108    LOG(WARNING) << "Unable to delete cookies on shutdown.";
1109    return;
1110  }
1111
1112  sql::Transaction transaction(db_.get());
1113  if (!transaction.Begin()) {
1114    LOG(WARNING) << "Unable to delete cookies on shutdown.";
1115    return;
1116  }
1117
1118  for (CookiesPerOriginMap::iterator it = cookies_per_origin_.begin();
1119       it != cookies_per_origin_.end(); ++it) {
1120    if (it->second <= 0) {
1121      DCHECK_EQ(0, it->second);
1122      continue;
1123    }
1124    const GURL url(net::cookie_util::CookieOriginToURL(it->first.first,
1125                                                       it->first.second));
1126    if (!url.is_valid() || !special_storage_policy_->IsStorageSessionOnly(url))
1127      continue;
1128
1129    del_smt.Reset(true);
1130    del_smt.BindString(0, it->first.first);
1131    del_smt.BindInt(1, it->first.second);
1132    if (!del_smt.Run())
1133      NOTREACHED() << "Could not delete a cookie from the DB.";
1134  }
1135
1136  if (!transaction.Commit())
1137    LOG(WARNING) << "Unable to delete cookies on shutdown.";
1138}
1139
1140void SQLitePersistentCookieStore::Backend::DatabaseErrorCallback(
1141    int error,
1142    sql::Statement* stmt) {
1143  DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1144
1145  if (!sql::IsErrorCatastrophic(error))
1146    return;
1147
1148  // TODO(shess): Running KillDatabase() multiple times should be
1149  // safe.
1150  if (corruption_detected_)
1151    return;
1152
1153  corruption_detected_ = true;
1154
1155  // Don't just do the close/delete here, as we are being called by |db| and
1156  // that seems dangerous.
1157  // TODO(shess): Consider just calling RazeAndClose() immediately.
1158  // db_ may not be safe to reset at this point, but RazeAndClose()
1159  // would cause the stack to unwind safely with errors.
1160  PostBackgroundTask(FROM_HERE, base::Bind(&Backend::KillDatabase, this));
1161}
1162
1163void SQLitePersistentCookieStore::Backend::KillDatabase() {
1164  DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1165
1166  if (db_) {
1167    // This Backend will now be in-memory only. In a future run we will recreate
1168    // the database. Hopefully things go better then!
1169    bool success = db_->RazeAndClose();
1170    UMA_HISTOGRAM_BOOLEAN("Cookie.KillDatabaseResult", success);
1171    meta_table_.Reset();
1172    db_.reset();
1173  }
1174}
1175
1176void SQLitePersistentCookieStore::Backend::SetForceKeepSessionState() {
1177  base::AutoLock locked(lock_);
1178  force_keep_session_state_ = true;
1179}
1180
1181void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup() {
1182  DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1183  if (!db_->Execute("DELETE FROM cookies WHERE persistent == 0"))
1184    LOG(WARNING) << "Unable to delete session cookies.";
1185}
1186
1187void SQLitePersistentCookieStore::Backend::PostBackgroundTask(
1188    const tracked_objects::Location& origin, const base::Closure& task) {
1189  if (!background_task_runner_->PostTask(origin, task)) {
1190    LOG(WARNING) << "Failed to post task from " << origin.ToString()
1191                 << " to background_task_runner_.";
1192  }
1193}
1194
1195void SQLitePersistentCookieStore::Backend::PostClientTask(
1196    const tracked_objects::Location& origin, const base::Closure& task) {
1197  if (!client_task_runner_->PostTask(origin, task)) {
1198    LOG(WARNING) << "Failed to post task from " << origin.ToString()
1199                 << " to client_task_runner_.";
1200  }
1201}
1202
1203SQLitePersistentCookieStore::SQLitePersistentCookieStore(
1204    const base::FilePath& path,
1205    const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
1206    const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
1207    bool restore_old_session_cookies,
1208    storage::SpecialStoragePolicy* special_storage_policy,
1209    CookieCryptoDelegate* crypto_delegate)
1210    : backend_(new Backend(path,
1211                           client_task_runner,
1212                           background_task_runner,
1213                           restore_old_session_cookies,
1214                           special_storage_policy,
1215                           crypto_delegate)) {
1216}
1217
1218void SQLitePersistentCookieStore::Load(const LoadedCallback& loaded_callback) {
1219  backend_->Load(loaded_callback);
1220}
1221
1222void SQLitePersistentCookieStore::LoadCookiesForKey(
1223    const std::string& key,
1224    const LoadedCallback& loaded_callback) {
1225  backend_->LoadCookiesForKey(key, loaded_callback);
1226}
1227
1228void SQLitePersistentCookieStore::AddCookie(const net::CanonicalCookie& cc) {
1229  backend_->AddCookie(cc);
1230}
1231
1232void SQLitePersistentCookieStore::UpdateCookieAccessTime(
1233    const net::CanonicalCookie& cc) {
1234  backend_->UpdateCookieAccessTime(cc);
1235}
1236
1237void SQLitePersistentCookieStore::DeleteCookie(const net::CanonicalCookie& cc) {
1238  backend_->DeleteCookie(cc);
1239}
1240
1241void SQLitePersistentCookieStore::SetForceKeepSessionState() {
1242  backend_->SetForceKeepSessionState();
1243}
1244
1245void SQLitePersistentCookieStore::Flush(const base::Closure& callback) {
1246  backend_->Flush(callback);
1247}
1248
1249SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
1250  backend_->Close();
1251  // We release our reference to the Backend, though it will probably still have
1252  // a reference if the background runner has not run Close() yet.
1253}
1254
1255CookieStoreConfig::CookieStoreConfig()
1256  : session_cookie_mode(EPHEMERAL_SESSION_COOKIES),
1257    crypto_delegate(NULL) {
1258  // Default to an in-memory cookie store.
1259}
1260
1261CookieStoreConfig::CookieStoreConfig(
1262    const base::FilePath& path,
1263    SessionCookieMode session_cookie_mode,
1264    storage::SpecialStoragePolicy* storage_policy,
1265    net::CookieMonsterDelegate* cookie_delegate)
1266    : path(path),
1267      session_cookie_mode(session_cookie_mode),
1268      storage_policy(storage_policy),
1269      cookie_delegate(cookie_delegate),
1270      crypto_delegate(NULL) {
1271  CHECK(!path.empty() || session_cookie_mode == EPHEMERAL_SESSION_COOKIES);
1272}
1273
1274CookieStoreConfig::~CookieStoreConfig() {
1275}
1276
1277net::CookieStore* CreateCookieStore(const CookieStoreConfig& config) {
1278  net::CookieMonster* cookie_monster = NULL;
1279
1280  if (config.path.empty()) {
1281    // Empty path means in-memory store.
1282    cookie_monster = new net::CookieMonster(NULL, config.cookie_delegate.get());
1283  } else {
1284    scoped_refptr<base::SequencedTaskRunner> client_task_runner =
1285        config.client_task_runner;
1286    scoped_refptr<base::SequencedTaskRunner> background_task_runner =
1287        config.background_task_runner;
1288
1289    if (!client_task_runner.get()) {
1290      client_task_runner =
1291          BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
1292    }
1293
1294    if (!background_task_runner.get()) {
1295      background_task_runner =
1296          BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
1297              BrowserThread::GetBlockingPool()->GetSequenceToken());
1298    }
1299
1300    SQLitePersistentCookieStore* persistent_store =
1301        new SQLitePersistentCookieStore(
1302            config.path,
1303            client_task_runner,
1304            background_task_runner,
1305            (config.session_cookie_mode ==
1306             CookieStoreConfig::RESTORED_SESSION_COOKIES),
1307            config.storage_policy.get(),
1308            config.crypto_delegate);
1309
1310    cookie_monster =
1311        new net::CookieMonster(persistent_store, config.cookie_delegate.get());
1312    if ((config.session_cookie_mode ==
1313         CookieStoreConfig::PERSISTANT_SESSION_COOKIES) ||
1314        (config.session_cookie_mode ==
1315         CookieStoreConfig::RESTORED_SESSION_COOKIES)) {
1316      cookie_monster->SetPersistSessionCookies(true);
1317    }
1318  }
1319
1320  // In the case of Android WebView, the cookie store may be created
1321  // before the browser process fully initializes -- certainly before
1322  // the main loop ever runs. In this situation, the CommandLine singleton
1323  // will not have been set up. Android tests do not need file cookies
1324  // so always ignore them here.
1325  //
1326  // TODO(ajwong): Remove the InitializedForCurrentProcess() check
1327  // once http://crbug.com/331424 is resolved.
1328  if (base::CommandLine::InitializedForCurrentProcess() &&
1329      base::CommandLine::ForCurrentProcess()->HasSwitch(
1330          switches::kEnableFileCookies)) {
1331    cookie_monster->SetEnableFileScheme(true);
1332  }
1333
1334  return cookie_monster;
1335}
1336
1337}  // namespace content
1338