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