Home | History | Annotate | Download | only in net
      1 // Copyright (c) 2011 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 "chrome/browser/net/sqlite_persistent_cookie_store.h"
      6 
      7 #include <list>
      8 
      9 #include "app/sql/meta_table.h"
     10 #include "app/sql/statement.h"
     11 #include "app/sql/transaction.h"
     12 #include "base/basictypes.h"
     13 #include "base/file_path.h"
     14 #include "base/file_util.h"
     15 #ifdef ANDROID
     16 #include "base/lazy_instance.h"
     17 #endif
     18 #include "base/logging.h"
     19 #include "base/memory/ref_counted.h"
     20 #include "base/memory/scoped_ptr.h"
     21 #include "base/metrics/histogram.h"
     22 #include "base/string_util.h"
     23 #include "base/threading/thread.h"
     24 #include "base/threading/thread_restrictions.h"
     25 #include "chrome/browser/diagnostics/sqlite_diagnostics.h"
     26 #ifndef ANDROID
     27 #include "content/browser/browser_thread.h"
     28 #endif
     29 #include "googleurl/src/gurl.h"
     30 
     31 #ifdef ANDROID
     32 namespace {
     33 
     34 // This class is used by CookieMonster, which is threadsafe, so this class must
     35 // be threadsafe too.
     36 base::LazyInstance<base::Lock> db_thread_lock(base::LINKER_INITIALIZED);
     37 
     38 base::Thread* getDbThread() {
     39   base::AutoLock lock(*db_thread_lock.Pointer());
     40 
     41   // FIXME: We should probably be using LazyInstance here.
     42   static base::Thread* db_thread = NULL;
     43 
     44   if (db_thread && db_thread->IsRunning())
     45     return db_thread;
     46 
     47   if (!db_thread)
     48     db_thread = new base::Thread("db");
     49 
     50   if (!db_thread)
     51     return NULL;
     52 
     53   base::Thread::Options options;
     54   options.message_loop_type = MessageLoop::TYPE_DEFAULT;
     55   if (!db_thread->StartWithOptions(options)) {
     56     delete db_thread;
     57     db_thread = NULL;
     58   }
     59   return db_thread;
     60 }
     61 
     62 }  // namespace
     63 #endif
     64 
     65 using base::Time;
     66 
     67 // This class is designed to be shared between any calling threads and the
     68 // database thread.  It batches operations and commits them on a timer.
     69 class SQLitePersistentCookieStore::Backend
     70     : public base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend> {
     71  public:
     72   explicit Backend(const FilePath& path)
     73       : path_(path),
     74         db_(NULL),
     75         num_pending_(0),
     76         clear_local_state_on_exit_(false)
     77 #if defined(ANDROID)
     78         , cookie_count_(0)
     79 #endif
     80   {
     81   }
     82 
     83   // Creates or load the SQLite database.
     84   bool Load(std::vector<net::CookieMonster::CanonicalCookie*>* cookies);
     85 
     86   // Batch a cookie addition.
     87   void AddCookie(const net::CookieMonster::CanonicalCookie& cc);
     88 
     89   // Batch a cookie access time update.
     90   void UpdateCookieAccessTime(const net::CookieMonster::CanonicalCookie& cc);
     91 
     92   // Batch a cookie deletion.
     93   void DeleteCookie(const net::CookieMonster::CanonicalCookie& cc);
     94 
     95   // Commit pending operations as soon as possible.
     96   void Flush(Task* completion_task);
     97 
     98   // Commit any pending operations and close the database.  This must be called
     99   // before the object is destructed.
    100   void Close();
    101 
    102   void SetClearLocalStateOnExit(bool clear_local_state);
    103 
    104 #if defined(ANDROID)
    105   int get_cookie_count() const { return cookie_count_; }
    106   void set_cookie_count(int count) { cookie_count_ = count; }
    107 #endif
    108 
    109  private:
    110   friend class base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend>;
    111 
    112   // You should call Close() before destructing this object.
    113   ~Backend() {
    114     DCHECK(!db_.get()) << "Close should have already been called.";
    115     DCHECK(num_pending_ == 0 && pending_.empty());
    116   }
    117 
    118   // Database upgrade statements.
    119   bool EnsureDatabaseVersion();
    120 
    121   class PendingOperation {
    122    public:
    123     typedef enum {
    124       COOKIE_ADD,
    125       COOKIE_UPDATEACCESS,
    126       COOKIE_DELETE,
    127     } OperationType;
    128 
    129     PendingOperation(OperationType op,
    130                      const net::CookieMonster::CanonicalCookie& cc)
    131         : op_(op), cc_(cc) { }
    132 
    133     OperationType op() const { return op_; }
    134     const net::CookieMonster::CanonicalCookie& cc() const { return cc_; }
    135 
    136    private:
    137     OperationType op_;
    138     net::CookieMonster::CanonicalCookie cc_;
    139   };
    140 
    141  private:
    142   // Batch a cookie operation (add or delete)
    143   void BatchOperation(PendingOperation::OperationType op,
    144                       const net::CookieMonster::CanonicalCookie& cc);
    145   // Commit our pending operations to the database.
    146 #if defined(ANDROID)
    147   void Commit(Task* completion_task);
    148 #else
    149   void Commit();
    150 #endif
    151   // Close() executed on the background thread.
    152   void InternalBackgroundClose();
    153 
    154   FilePath path_;
    155   scoped_ptr<sql::Connection> db_;
    156   sql::MetaTable meta_table_;
    157 
    158   typedef std::list<PendingOperation*> PendingOperationsList;
    159   PendingOperationsList pending_;
    160   PendingOperationsList::size_type num_pending_;
    161   // True if the persistent store should be deleted upon destruction.
    162   bool clear_local_state_on_exit_;
    163   // Guard |pending_|, |num_pending_| and |clear_local_state_on_exit_|.
    164   base::Lock lock_;
    165 
    166 #if defined(ANDROID)
    167   // Number of cookies that have actually been saved. Updated during Commit().
    168   volatile int cookie_count_;
    169 #endif
    170 
    171   DISALLOW_COPY_AND_ASSIGN(Backend);
    172 };
    173 
    174 // Version number of the database. In version 4, we migrated the time epoch.
    175 // If you open the DB with an older version on Mac or Linux, the times will
    176 // look wonky, but the file will likely be usable. On Windows version 3 and 4
    177 // are the same.
    178 //
    179 // Version 3 updated the database to include the last access time, so we can
    180 // expire them in decreasing order of use when we've reached the maximum
    181 // number of cookies.
    182 static const int kCurrentVersionNumber = 4;
    183 static const int kCompatibleVersionNumber = 3;
    184 
    185 namespace {
    186 
    187 // Initializes the cookies table, returning true on success.
    188 bool InitTable(sql::Connection* db) {
    189   if (!db->DoesTableExist("cookies")) {
    190     if (!db->Execute("CREATE TABLE cookies ("
    191                      "creation_utc INTEGER NOT NULL UNIQUE PRIMARY KEY,"
    192                      "host_key TEXT NOT NULL,"
    193                      "name TEXT NOT NULL,"
    194                      "value TEXT NOT NULL,"
    195                      "path TEXT NOT NULL,"
    196 #if defined(ANDROID)
    197                      // On some mobile platforms, we persist session cookies
    198                      // because the OS can kill the browser during a session.
    199                      // If so, expires_utc is set to 0. When the field is read
    200                      // into a Time object, Time::is_null() will return true.
    201 #else
    202                      // We only store persistent, so we know it expires
    203 #endif
    204                      "expires_utc INTEGER NOT NULL,"
    205                      "secure INTEGER NOT NULL,"
    206                      "httponly INTEGER NOT NULL,"
    207                      "last_access_utc INTEGER NOT NULL)"))
    208       return false;
    209   }
    210 
    211   // Try to create the index every time. Older versions did not have this index,
    212   // so we want those people to get it. Ignore errors, since it may exist.
    213   db->Execute(
    214       "CREATE INDEX IF NOT EXISTS cookie_times ON cookies (creation_utc)");
    215   return true;
    216 }
    217 
    218 }  // namespace
    219 
    220 bool SQLitePersistentCookieStore::Backend::Load(
    221     std::vector<net::CookieMonster::CanonicalCookie*>* cookies) {
    222   // This function should be called only once per instance.
    223   DCHECK(!db_.get());
    224 
    225   // Ensure the parent directory for storing cookies is created before reading
    226   // from it.  We make an exception to allow IO on the UI thread here because
    227   // we are going to disk anyway in db_->Open.  (This code will be moved to the
    228   // DB thread as part of http://crbug.com/52909.)
    229   {
    230     base::ThreadRestrictions::ScopedAllowIO allow_io;
    231     const FilePath dir = path_.DirName();
    232     if (!file_util::PathExists(dir) && !file_util::CreateDirectory(dir))
    233       return false;
    234   }
    235 
    236   db_.reset(new sql::Connection);
    237   if (!db_->Open(path_)) {
    238     NOTREACHED() << "Unable to open cookie DB.";
    239     db_.reset();
    240     return false;
    241   }
    242 
    243 #ifndef ANDROID
    244   // GetErrorHandlerForCookieDb is defined in sqlite_diagnostics.h
    245   // which we do not currently include on Android
    246   db_->set_error_delegate(GetErrorHandlerForCookieDb());
    247 #endif
    248 
    249   if (!EnsureDatabaseVersion() || !InitTable(db_.get())) {
    250     NOTREACHED() << "Unable to open cookie DB.";
    251     db_.reset();
    252     return false;
    253   }
    254 
    255   db_->Preload();
    256 
    257   // Slurp all the cookies into the out-vector.
    258   sql::Statement smt(db_->GetUniqueStatement(
    259       "SELECT creation_utc, host_key, name, value, path, expires_utc, secure, "
    260       "httponly, last_access_utc FROM cookies"));
    261   if (!smt) {
    262     NOTREACHED() << "select statement prep failed";
    263     db_.reset();
    264     return false;
    265   }
    266 
    267   while (smt.Step()) {
    268 #if defined(ANDROID)
    269     base::Time expires = Time::FromInternalValue(smt.ColumnInt64(5));
    270 #endif
    271     scoped_ptr<net::CookieMonster::CanonicalCookie> cc(
    272         new net::CookieMonster::CanonicalCookie(
    273             // The "source" URL is not used with persisted cookies.
    274             GURL(),                                         // Source
    275             smt.ColumnString(2),                            // name
    276             smt.ColumnString(3),                            // value
    277             smt.ColumnString(1),                            // domain
    278             smt.ColumnString(4),                            // path
    279             Time::FromInternalValue(smt.ColumnInt64(0)),    // creation_utc
    280             Time::FromInternalValue(smt.ColumnInt64(5)),    // expires_utc
    281             Time::FromInternalValue(smt.ColumnInt64(8)),    // last_access_utc
    282             smt.ColumnInt(6) != 0,                          // secure
    283             smt.ColumnInt(7) != 0,                          // httponly
    284 #if defined(ANDROID)
    285             !expires.is_null()));                           // has_expires
    286 #else
    287             true));                                         // has_expires
    288 #endif
    289     DLOG_IF(WARNING,
    290             cc->CreationDate() > Time::Now()) << L"CreationDate too recent";
    291     cookies->push_back(cc.release());
    292   }
    293 
    294 #ifdef ANDROID
    295   set_cookie_count(cookies->size());
    296 #endif
    297 
    298   return true;
    299 }
    300 
    301 bool SQLitePersistentCookieStore::Backend::EnsureDatabaseVersion() {
    302   // Version check.
    303   if (!meta_table_.Init(
    304       db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) {
    305     return false;
    306   }
    307 
    308   if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) {
    309     LOG(WARNING) << "Cookie database is too new.";
    310     return false;
    311   }
    312 
    313   int cur_version = meta_table_.GetVersionNumber();
    314   if (cur_version == 2) {
    315     sql::Transaction transaction(db_.get());
    316     if (!transaction.Begin())
    317       return false;
    318     if (!db_->Execute("ALTER TABLE cookies ADD COLUMN last_access_utc "
    319                      "INTEGER DEFAULT 0") ||
    320         !db_->Execute("UPDATE cookies SET last_access_utc = creation_utc")) {
    321       LOG(WARNING) << "Unable to update cookie database to version 3.";
    322       return false;
    323     }
    324     ++cur_version;
    325     meta_table_.SetVersionNumber(cur_version);
    326     meta_table_.SetCompatibleVersionNumber(
    327         std::min(cur_version, kCompatibleVersionNumber));
    328     transaction.Commit();
    329   }
    330 
    331   if (cur_version == 3) {
    332     // The time epoch changed for Mac & Linux in this version to match Windows.
    333     // This patch came after the main epoch change happened, so some
    334     // developers have "good" times for cookies added by the more recent
    335     // versions. So we have to be careful to only update times that are under
    336     // the old system (which will appear to be from before 1970 in the new
    337     // system). The magic number used below is 1970 in our time units.
    338     sql::Transaction transaction(db_.get());
    339     transaction.Begin();
    340 #if !defined(OS_WIN)
    341     db_->Execute(
    342         "UPDATE cookies "
    343         "SET creation_utc = creation_utc + 11644473600000000 "
    344         "WHERE rowid IN "
    345         "(SELECT rowid FROM cookies WHERE "
    346           "creation_utc > 0 AND creation_utc < 11644473600000000)");
    347     db_->Execute(
    348         "UPDATE cookies "
    349         "SET expires_utc = expires_utc + 11644473600000000 "
    350         "WHERE rowid IN "
    351         "(SELECT rowid FROM cookies WHERE "
    352           "expires_utc > 0 AND expires_utc < 11644473600000000)");
    353     db_->Execute(
    354         "UPDATE cookies "
    355         "SET last_access_utc = last_access_utc + 11644473600000000 "
    356         "WHERE rowid IN "
    357         "(SELECT rowid FROM cookies WHERE "
    358           "last_access_utc > 0 AND last_access_utc < 11644473600000000)");
    359 #endif
    360     ++cur_version;
    361     meta_table_.SetVersionNumber(cur_version);
    362     transaction.Commit();
    363   }
    364 
    365   // Put future migration cases here.
    366 
    367   // When the version is too old, we just try to continue anyway, there should
    368   // not be a released product that makes a database too old for us to handle.
    369   LOG_IF(WARNING, cur_version < kCurrentVersionNumber) <<
    370       "Cookie database version " << cur_version << " is too old to handle.";
    371 
    372   return true;
    373 }
    374 
    375 void SQLitePersistentCookieStore::Backend::AddCookie(
    376     const net::CookieMonster::CanonicalCookie& cc) {
    377   BatchOperation(PendingOperation::COOKIE_ADD, cc);
    378 }
    379 
    380 void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime(
    381     const net::CookieMonster::CanonicalCookie& cc) {
    382   BatchOperation(PendingOperation::COOKIE_UPDATEACCESS, cc);
    383 }
    384 
    385 void SQLitePersistentCookieStore::Backend::DeleteCookie(
    386     const net::CookieMonster::CanonicalCookie& cc) {
    387   BatchOperation(PendingOperation::COOKIE_DELETE, cc);
    388 }
    389 
    390 void SQLitePersistentCookieStore::Backend::BatchOperation(
    391     PendingOperation::OperationType op,
    392     const net::CookieMonster::CanonicalCookie& cc) {
    393   // Commit every 30 seconds.
    394   static const int kCommitIntervalMs = 30 * 1000;
    395   // Commit right away if we have more than 512 outstanding operations.
    396   static const size_t kCommitAfterBatchSize = 512;
    397 #ifndef ANDROID
    398   DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::DB));
    399 #endif
    400 
    401   // We do a full copy of the cookie here, and hopefully just here.
    402   scoped_ptr<PendingOperation> po(new PendingOperation(op, cc));
    403 
    404   PendingOperationsList::size_type num_pending;
    405   {
    406     base::AutoLock locked(lock_);
    407     pending_.push_back(po.release());
    408     num_pending = ++num_pending_;
    409   }
    410 
    411 #ifdef ANDROID
    412   if (!getDbThread())
    413     return;
    414   MessageLoop* loop = getDbThread()->message_loop();
    415 #endif
    416 
    417   if (num_pending == 1) {
    418     // We've gotten our first entry for this batch, fire off the timer.
    419 #ifdef ANDROID
    420     loop->PostDelayedTask(FROM_HERE, NewRunnableMethod(
    421         this, &Backend::Commit, static_cast<Task*>(NULL)), kCommitIntervalMs);
    422 #else
    423     BrowserThread::PostDelayedTask(
    424         BrowserThread::DB, FROM_HERE,
    425         NewRunnableMethod(this, &Backend::Commit), kCommitIntervalMs);
    426 #endif
    427   } else if (num_pending == kCommitAfterBatchSize) {
    428     // We've reached a big enough batch, fire off a commit now.
    429 #ifdef ANDROID
    430     loop->PostTask(FROM_HERE, NewRunnableMethod(
    431         this, &Backend::Commit, static_cast<Task*>(NULL)));
    432 #else
    433     BrowserThread::PostTask(
    434         BrowserThread::DB, FROM_HERE,
    435         NewRunnableMethod(this, &Backend::Commit));
    436 #endif
    437   }
    438 }
    439 
    440 #if defined(ANDROID)
    441 void SQLitePersistentCookieStore::Backend::Commit(Task* completion_task) {
    442 #else
    443 void SQLitePersistentCookieStore::Backend::Commit() {
    444   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
    445 #endif
    446 
    447 #if defined(ANDROID)
    448   if (completion_task) {
    449     // We post this task to the current thread, so it won't run until we exit.
    450     MessageLoop::current()->PostTask(FROM_HERE, completion_task);
    451   }
    452 #endif
    453 
    454   PendingOperationsList ops;
    455   {
    456     base::AutoLock locked(lock_);
    457     pending_.swap(ops);
    458     num_pending_ = 0;
    459   }
    460 
    461   // Maybe an old timer fired or we are already Close()'ed.
    462   if (!db_.get() || ops.empty())
    463     return;
    464 
    465   sql::Statement add_smt(db_->GetCachedStatement(SQL_FROM_HERE,
    466       "INSERT INTO cookies (creation_utc, host_key, name, value, path, "
    467       "expires_utc, secure, httponly, last_access_utc) "
    468       "VALUES (?,?,?,?,?,?,?,?,?)"));
    469   if (!add_smt) {
    470     NOTREACHED();
    471     return;
    472   }
    473 
    474   sql::Statement update_access_smt(db_->GetCachedStatement(SQL_FROM_HERE,
    475       "UPDATE cookies SET last_access_utc=? WHERE creation_utc=?"));
    476   if (!update_access_smt) {
    477     NOTREACHED();
    478     return;
    479   }
    480 
    481   sql::Statement del_smt(db_->GetCachedStatement(SQL_FROM_HERE,
    482                          "DELETE FROM cookies WHERE creation_utc=?"));
    483   if (!del_smt) {
    484     NOTREACHED();
    485     return;
    486   }
    487 
    488   sql::Transaction transaction(db_.get());
    489   if (!transaction.Begin()) {
    490     NOTREACHED();
    491     return;
    492   }
    493 #if defined(ANDROID)
    494   int cookie_delta = 0;
    495 #endif
    496   for (PendingOperationsList::iterator it = ops.begin();
    497        it != ops.end(); ++it) {
    498     // Free the cookies as we commit them to the database.
    499     scoped_ptr<PendingOperation> po(*it);
    500     switch (po->op()) {
    501       case PendingOperation::COOKIE_ADD:
    502 #if defined(ANDROID)
    503         ++cookie_delta;
    504 #endif
    505         add_smt.Reset();
    506         add_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
    507         add_smt.BindString(1, po->cc().Domain());
    508         add_smt.BindString(2, po->cc().Name());
    509         add_smt.BindString(3, po->cc().Value());
    510         add_smt.BindString(4, po->cc().Path());
    511         add_smt.BindInt64(5, po->cc().ExpiryDate().ToInternalValue());
    512         add_smt.BindInt(6, po->cc().IsSecure());
    513         add_smt.BindInt(7, po->cc().IsHttpOnly());
    514         add_smt.BindInt64(8, po->cc().LastAccessDate().ToInternalValue());
    515         if (!add_smt.Run())
    516           NOTREACHED() << "Could not add a cookie to the DB.";
    517         break;
    518 
    519       case PendingOperation::COOKIE_UPDATEACCESS:
    520         update_access_smt.Reset();
    521         update_access_smt.BindInt64(0,
    522             po->cc().LastAccessDate().ToInternalValue());
    523         update_access_smt.BindInt64(1,
    524             po->cc().CreationDate().ToInternalValue());
    525         if (!update_access_smt.Run())
    526           NOTREACHED() << "Could not update cookie last access time in the DB.";
    527         break;
    528 
    529       case PendingOperation::COOKIE_DELETE:
    530 #if defined(ANDROID)
    531         --cookie_delta;
    532 #endif
    533         del_smt.Reset();
    534         del_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
    535         if (!del_smt.Run())
    536           NOTREACHED() << "Could not delete a cookie from the DB.";
    537         break;
    538 
    539       default:
    540         NOTREACHED();
    541         break;
    542     }
    543   }
    544   bool succeeded = transaction.Commit();
    545 #if defined(ANDROID)
    546   if (succeeded)
    547       cookie_count_ += cookie_delta;
    548 #endif
    549   UMA_HISTOGRAM_ENUMERATION("Cookie.BackingStoreUpdateResults",
    550                             succeeded ? 0 : 1, 2);
    551 }
    552 
    553 void SQLitePersistentCookieStore::Backend::Flush(Task* completion_task) {
    554 #if defined(ANDROID)
    555     if (!getDbThread()) {
    556       if (completion_task)
    557         MessageLoop::current()->PostTask(FROM_HERE, completion_task);
    558       return;
    559     }
    560 
    561     MessageLoop* loop = getDbThread()->message_loop();
    562     loop->PostTask(FROM_HERE, NewRunnableMethod(
    563         this, &Backend::Commit, completion_task));
    564 #else
    565   DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::DB));
    566   BrowserThread::PostTask(
    567       BrowserThread::DB, FROM_HERE, NewRunnableMethod(this, &Backend::Commit));
    568   if (completion_task) {
    569     // We want the completion task to run immediately after Commit() returns.
    570     // Posting it from here means there is less chance of another task getting
    571     // onto the message queue first, than if we posted it from Commit() itself.
    572     BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, completion_task);
    573   }
    574 #endif
    575 }
    576 
    577 // Fire off a close message to the background thread.  We could still have a
    578 // pending commit timer that will be holding a reference on us, but if/when
    579 // this fires we will already have been cleaned up and it will be ignored.
    580 void SQLitePersistentCookieStore::Backend::Close() {
    581 #ifndef ANDROID
    582   DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::DB));
    583 #endif
    584 
    585 #ifdef ANDROID
    586   if (!getDbThread())
    587     return;
    588 
    589   MessageLoop* loop = getDbThread()->message_loop();
    590   loop->PostTask(FROM_HERE,
    591       NewRunnableMethod(this, &Backend::InternalBackgroundClose));
    592 #else
    593   // Must close the backend on the background thread.
    594   BrowserThread::PostTask(
    595       BrowserThread::DB, FROM_HERE,
    596       NewRunnableMethod(this, &Backend::InternalBackgroundClose));
    597 #endif
    598 }
    599 
    600 void SQLitePersistentCookieStore::Backend::InternalBackgroundClose() {
    601 #ifndef ANDROID
    602   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
    603 #endif
    604   // Commit any pending operations
    605 #if defined(ANDROID)
    606   Commit(NULL);
    607 #else
    608   Commit();
    609 #endif
    610 
    611   db_.reset();
    612 
    613   if (clear_local_state_on_exit_)
    614     file_util::Delete(path_, false);
    615 }
    616 
    617 void SQLitePersistentCookieStore::Backend::SetClearLocalStateOnExit(
    618     bool clear_local_state) {
    619   base::AutoLock locked(lock_);
    620   clear_local_state_on_exit_ = clear_local_state;
    621 }
    622 SQLitePersistentCookieStore::SQLitePersistentCookieStore(const FilePath& path)
    623     : backend_(new Backend(path)) {
    624 }
    625 
    626 SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
    627   if (backend_.get()) {
    628     backend_->Close();
    629     // Release our reference, it will probably still have a reference if the
    630     // background thread has not run Close() yet.
    631     backend_ = NULL;
    632   }
    633 }
    634 
    635 bool SQLitePersistentCookieStore::Load(
    636     std::vector<net::CookieMonster::CanonicalCookie*>* cookies) {
    637   return backend_->Load(cookies);
    638 }
    639 
    640 void SQLitePersistentCookieStore::AddCookie(
    641     const net::CookieMonster::CanonicalCookie& cc) {
    642   if (backend_.get())
    643     backend_->AddCookie(cc);
    644 }
    645 
    646 void SQLitePersistentCookieStore::UpdateCookieAccessTime(
    647     const net::CookieMonster::CanonicalCookie& cc) {
    648   if (backend_.get())
    649     backend_->UpdateCookieAccessTime(cc);
    650 }
    651 
    652 void SQLitePersistentCookieStore::DeleteCookie(
    653     const net::CookieMonster::CanonicalCookie& cc) {
    654   if (backend_.get())
    655     backend_->DeleteCookie(cc);
    656 }
    657 
    658 void SQLitePersistentCookieStore::SetClearLocalStateOnExit(
    659     bool clear_local_state) {
    660   if (backend_.get())
    661     backend_->SetClearLocalStateOnExit(clear_local_state);
    662 }
    663 
    664 void SQLitePersistentCookieStore::Flush(Task* completion_task) {
    665   if (backend_.get())
    666     backend_->Flush(completion_task);
    667   else if (completion_task)
    668     MessageLoop::current()->PostTask(FROM_HERE, completion_task);
    669 }
    670 
    671 #if defined(ANDROID)
    672 int SQLitePersistentCookieStore::GetCookieCount() {
    673   int result = backend_ ? backend_->get_cookie_count() : 0;
    674   return result;
    675 }
    676 #endif
    677