Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(419)

Side by Side Diff: net/extras/sqlite/sqlite_persistent_cookie_store.cc

Issue 1016643004: Moves SQLitePersistentCookieStore to net/extras/sqlite. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@cookies
Patch Set: Remove NET_EXPORT. Created 5 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "content/browser/net/sqlite_persistent_cookie_store.h" 5 #include "net/extras/sqlite/sqlite_persistent_cookie_store.h"
6 6
7 #include <list> 7 #include <list>
8 #include <map> 8 #include <map>
9 #include <set> 9 #include <set>
10 #include <utility> 10 #include <utility>
11 11
12 #include "base/basictypes.h" 12 #include "base/basictypes.h"
13 #include "base/bind.h" 13 #include "base/bind.h"
14 #include "base/callback.h" 14 #include "base/callback.h"
15 #include "base/command_line.h" 15 #include "base/command_line.h"
16 #include "base/files/file_path.h" 16 #include "base/files/file_path.h"
17 #include "base/files/file_util.h" 17 #include "base/files/file_util.h"
18 #include "base/location.h" 18 #include "base/location.h"
19 #include "base/logging.h" 19 #include "base/logging.h"
20 #include "base/memory/ref_counted.h" 20 #include "base/memory/ref_counted.h"
21 #include "base/memory/scoped_ptr.h" 21 #include "base/memory/scoped_ptr.h"
22 #include "base/metrics/field_trial.h" 22 #include "base/metrics/field_trial.h"
23 #include "base/metrics/histogram.h" 23 #include "base/metrics/histogram.h"
24 #include "base/sequenced_task_runner.h" 24 #include "base/sequenced_task_runner.h"
25 #include "base/strings/string_util.h" 25 #include "base/strings/string_util.h"
26 #include "base/strings/stringprintf.h" 26 #include "base/strings/stringprintf.h"
27 #include "base/synchronization/lock.h" 27 #include "base/synchronization/lock.h"
28 #include "base/threading/sequenced_worker_pool.h" 28 #include "base/threading/sequenced_worker_pool.h"
29 #include "base/time/time.h" 29 #include "base/time/time.h"
30 #include "content/public/browser/browser_thread.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" 30 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
34 #include "net/cookies/canonical_cookie.h" 31 #include "net/cookies/canonical_cookie.h"
35 #include "net/cookies/cookie_constants.h" 32 #include "net/cookies/cookie_constants.h"
36 #include "net/cookies/cookie_util.h" 33 #include "net/cookies/cookie_util.h"
37 #include "net/extras/sqlite/cookie_crypto_delegate.h" 34 #include "net/extras/sqlite/cookie_crypto_delegate.h"
38 #include "sql/error_delegate_util.h" 35 #include "sql/error_delegate_util.h"
39 #include "sql/meta_table.h" 36 #include "sql/meta_table.h"
40 #include "sql/statement.h" 37 #include "sql/statement.h"
41 #include "sql/transaction.h" 38 #include "sql/transaction.h"
42 #include "storage/browser/quota/special_storage_policy.h"
43 #include "third_party/sqlite/sqlite3.h" 39 #include "third_party/sqlite/sqlite3.h"
44 #include "url/gurl.h" 40 #include "url/gurl.h"
45 41
46 using base::Time; 42 using base::Time;
47 43
48 namespace { 44 namespace {
49 45
50 // The persistent cookie store is loaded into memory on eTLD at a time. This 46 // The persistent cookie store is loaded into memory on eTLD at a time. This
51 // variable controls the delay between loading eTLDs, so as to not overload the 47 // variable controls the delay between loading eTLDs, so as to not overload the
52 // CPU or I/O with these low priority requests immediately after start up. 48 // CPU or I/O with these low priority requests immediately after start up.
53 const int kLoadDelayMilliseconds = 200; 49 const int kLoadDelayMilliseconds = 200;
54 50
55 } // namespace 51 } // namespace
56 52
57 namespace content { 53 namespace net {
58 54
59 // This class is designed to be shared between any client thread and the 55 // This class is designed to be shared between any client thread and the
60 // background task runner. It batches operations and commits them on a timer. 56 // background task runner. It batches operations and commits them on a timer.
61 // 57 //
62 // SQLitePersistentCookieStore::Load is called to load all cookies. It 58 // SQLitePersistentCookieStore::Load is called to load all cookies. It
63 // delegates to Backend::Load, which posts a Backend::LoadAndNotifyOnDBThread 59 // delegates to Backend::Load, which posts a Backend::LoadAndNotifyOnDBThread
64 // task to the background runner. This task calls Backend::ChainLoadCookies(), 60 // task to the background runner. This task calls Backend::ChainLoadCookies(),
65 // which repeatedly posts itself to the BG runner to load each eTLD+1's cookies 61 // which repeatedly posts itself to the BG runner to load each eTLD+1's cookies
66 // in separate tasks. When this is complete, Backend::CompleteLoadOnIOThread is 62 // in separate tasks. When this is complete, Backend::CompleteLoadOnIOThread is
67 // posted to the client runner, which notifies the caller of 63 // posted to the client runner, which notifies the caller of
(...skipping 11 matching lines...) Expand all
79 // disk on the BG runner every 30 seconds, 512 operations, or call to Flush(), 75 // disk on the BG runner every 30 seconds, 512 operations, or call to Flush(),
80 // whichever occurs first. 76 // whichever occurs first.
81 class SQLitePersistentCookieStore::Backend 77 class SQLitePersistentCookieStore::Backend
82 : public base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend> { 78 : public base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend> {
83 public: 79 public:
84 Backend( 80 Backend(
85 const base::FilePath& path, 81 const base::FilePath& path,
86 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner, 82 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
87 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner, 83 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
88 bool restore_old_session_cookies, 84 bool restore_old_session_cookies,
89 storage::SpecialStoragePolicy* special_storage_policy, 85 CookieCryptoDelegate* crypto_delegate)
90 net::CookieCryptoDelegate* crypto_delegate)
91 : path_(path), 86 : path_(path),
92 num_pending_(0), 87 num_pending_(0),
93 force_keep_session_state_(false),
94 initialized_(false), 88 initialized_(false),
95 corruption_detected_(false), 89 corruption_detected_(false),
96 restore_old_session_cookies_(restore_old_session_cookies), 90 restore_old_session_cookies_(restore_old_session_cookies),
97 special_storage_policy_(special_storage_policy),
98 num_cookies_read_(0), 91 num_cookies_read_(0),
99 client_task_runner_(client_task_runner), 92 client_task_runner_(client_task_runner),
100 background_task_runner_(background_task_runner), 93 background_task_runner_(background_task_runner),
101 num_priority_waiting_(0), 94 num_priority_waiting_(0),
102 total_priority_requests_(0), 95 total_priority_requests_(0),
103 crypto_(crypto_delegate) {} 96 crypto_(crypto_delegate) {}
104 97
105 // Creates or loads the SQLite database. 98 // Creates or loads the SQLite database.
106 void Load(const LoadedCallback& loaded_callback); 99 void Load(const LoadedCallback& loaded_callback);
107 100
108 // Loads cookies for the domain key (eTLD+1). 101 // Loads cookies for the domain key (eTLD+1).
109 void LoadCookiesForKey(const std::string& domain, 102 void LoadCookiesForKey(const std::string& domain,
110 const LoadedCallback& loaded_callback); 103 const LoadedCallback& loaded_callback);
111 104
112 // Steps through all results of |smt|, makes a cookie from each, and adds the 105 // Steps through all results of |smt|, makes a cookie from each, and adds the
113 // cookie to |cookies|. This method also updates |cookies_per_origin_| and 106 // cookie to |cookies|. This method also updates |num_cookies_read_|.
114 // |num_cookies_read_|. 107 void MakeCookiesFromSQLStatement(std::vector<CanonicalCookie*>* cookies,
115 void MakeCookiesFromSQLStatement(std::vector<net::CanonicalCookie*>* cookies,
116 sql::Statement* statement); 108 sql::Statement* statement);
117 109
118 // Batch a cookie addition. 110 // Batch a cookie addition.
119 void AddCookie(const net::CanonicalCookie& cc); 111 void AddCookie(const CanonicalCookie& cc);
120 112
121 // Batch a cookie access time update. 113 // Batch a cookie access time update.
122 void UpdateCookieAccessTime(const net::CanonicalCookie& cc); 114 void UpdateCookieAccessTime(const CanonicalCookie& cc);
123 115
124 // Batch a cookie deletion. 116 // Batch a cookie deletion.
125 void DeleteCookie(const net::CanonicalCookie& cc); 117 void DeleteCookie(const CanonicalCookie& cc);
126 118
127 // Commit pending operations as soon as possible. 119 // Commit pending operations as soon as possible.
128 void Flush(const base::Closure& callback); 120 void Flush(const base::Closure& callback);
129 121
130 // Commit any pending operations and close the database. This must be called 122 // Commit any pending operations and close the database. This must be called
131 // before the object is destructed. 123 // before the object is destructed.
132 void Close(); 124 void Close();
133 125
134 void SetForceKeepSessionState(); 126 // Post background delete of all cookies that match |cookies|.
127 void DeleteAllInList(const std::list<CookieOrigin> cookies);
Ryan Sleevi 2015/03/19 03:37:51 const-ref
rohitrao (ping after 24h) 2015/03/19 14:55:42 Done.
135 128
136 private: 129 private:
137 friend class base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend>; 130 friend class base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend>;
138 131
139 // You should call Close() before destructing this object. 132 // You should call Close() before destructing this object.
140 ~Backend() { 133 ~Backend() {
141 DCHECK(!db_.get()) << "Close should have already been called."; 134 DCHECK(!db_.get()) << "Close should have already been called.";
142 DCHECK(num_pending_ == 0 && pending_.empty()); 135 DCHECK_EQ(0u, num_pending_);
136 DCHECK(pending_.empty());
143 } 137 }
144 138
145 // Database upgrade statements. 139 // Database upgrade statements.
146 bool EnsureDatabaseVersion(); 140 bool EnsureDatabaseVersion();
147 141
148 class PendingOperation { 142 class PendingOperation {
149 public: 143 public:
150 typedef enum { 144 enum OperationType {
151 COOKIE_ADD, 145 COOKIE_ADD,
152 COOKIE_UPDATEACCESS, 146 COOKIE_UPDATEACCESS,
153 COOKIE_DELETE, 147 COOKIE_DELETE,
154 } OperationType; 148 };
155 149
156 PendingOperation(OperationType op, const net::CanonicalCookie& cc) 150 PendingOperation(OperationType op, const CanonicalCookie& cc)
157 : op_(op), cc_(cc) { } 151 : op_(op), cc_(cc) { }
158 152
159 OperationType op() const { return op_; } 153 OperationType op() const { return op_; }
160 const net::CanonicalCookie& cc() const { return cc_; } 154 const CanonicalCookie& cc() const { return cc_; }
161 155
162 private: 156 private:
163 OperationType op_; 157 OperationType op_;
164 net::CanonicalCookie cc_; 158 CanonicalCookie cc_;
165 }; 159 };
166 160
167 private: 161 private:
168 // Creates or loads the SQLite database on background runner. 162 // Creates or loads the SQLite database on background runner.
169 void LoadAndNotifyInBackground(const LoadedCallback& loaded_callback, 163 void LoadAndNotifyInBackground(const LoadedCallback& loaded_callback,
170 const base::Time& posted_at); 164 const base::Time& posted_at);
171 165
172 // Loads cookies for the domain key (eTLD+1) on background runner. 166 // Loads cookies for the domain key (eTLD+1) on background runner.
173 void LoadKeyAndNotifyInBackground(const std::string& domains, 167 void LoadKeyAndNotifyInBackground(const std::string& domains,
174 const LoadedCallback& loaded_callback, 168 const LoadedCallback& loaded_callback,
(...skipping 30 matching lines...) Expand all
205 // Loads cookies for the next domain key from the DB, then either reschedules 199 // Loads cookies for the next domain key from the DB, then either reschedules
206 // itself or schedules the provided callback to run on the client runner (if 200 // itself or schedules the provided callback to run on the client runner (if
207 // all domains are loaded). 201 // all domains are loaded).
208 void ChainLoadCookies(const LoadedCallback& loaded_callback); 202 void ChainLoadCookies(const LoadedCallback& loaded_callback);
209 203
210 // Load all cookies for a set of domains/hosts 204 // Load all cookies for a set of domains/hosts
211 bool LoadCookiesForDomains(const std::set<std::string>& key); 205 bool LoadCookiesForDomains(const std::set<std::string>& key);
212 206
213 // Batch a cookie operation (add or delete) 207 // Batch a cookie operation (add or delete)
214 void BatchOperation(PendingOperation::OperationType op, 208 void BatchOperation(PendingOperation::OperationType op,
215 const net::CanonicalCookie& cc); 209 const CanonicalCookie& cc);
216 // Commit our pending operations to the database. 210 // Commit our pending operations to the database.
217 void Commit(); 211 void Commit();
218 // Close() executed on the background runner. 212 // Close() executed on the background runner.
219 void InternalBackgroundClose(); 213 void InternalBackgroundClose();
220 214
221 void DeleteSessionCookiesOnStartup(); 215 void DeleteSessionCookiesOnStartup();
222 216
223 void DeleteSessionCookiesOnShutdown(); 217 void BackgroundDeleteAllInList(const std::list<CookieOrigin> cookies);
Ryan Sleevi 2015/03/19 03:37:51 const-ref
rohitrao (ping after 24h) 2015/03/19 14:55:42 Done. Just to double-check, will base::Bind() mak
224 218
225 void DatabaseErrorCallback(int error, sql::Statement* stmt); 219 void DatabaseErrorCallback(int error, sql::Statement* stmt);
226 void KillDatabase(); 220 void KillDatabase();
227 221
228 void PostBackgroundTask(const tracked_objects::Location& origin, 222 void PostBackgroundTask(const tracked_objects::Location& origin,
229 const base::Closure& task); 223 const base::Closure& task);
230 void PostClientTask(const tracked_objects::Location& origin, 224 void PostClientTask(const tracked_objects::Location& origin,
231 const base::Closure& task); 225 const base::Closure& task);
232 226
233 // Shared code between the different load strategies to be used after all 227 // Shared code between the different load strategies to be used after all
234 // cookies have been loaded. 228 // cookies have been loaded.
235 void FinishedLoadingCookies(const LoadedCallback& loaded_callback, 229 void FinishedLoadingCookies(const LoadedCallback& loaded_callback,
236 bool success); 230 bool success);
237 231
238 base::FilePath path_; 232 const base::FilePath path_;
239 scoped_ptr<sql::Connection> db_; 233 scoped_ptr<sql::Connection> db_;
240 sql::MetaTable meta_table_; 234 sql::MetaTable meta_table_;
241 235
242 typedef std::list<PendingOperation*> PendingOperationsList; 236 typedef std::list<PendingOperation*> PendingOperationsList;
243 PendingOperationsList pending_; 237 PendingOperationsList pending_;
244 PendingOperationsList::size_type num_pending_; 238 PendingOperationsList::size_type num_pending_;
245 // True if the persistent store should skip delete on exit rules. 239 // Guard |cookies_|, |pending_|, |num_pending_|.
246 bool force_keep_session_state_;
247 // Guard |cookies_|, |pending_|, |num_pending_|, |force_keep_session_state_|
248 base::Lock lock_; 240 base::Lock lock_;
249 241
250 // Temporary buffer for cookies loaded from DB. Accumulates cookies to reduce 242 // Temporary buffer for cookies loaded from DB. Accumulates cookies to reduce
251 // the number of messages sent to the client runner. Sent back in response to 243 // the number of messages sent to the client runner. Sent back in response to
252 // individual load requests for domain keys or when all loading completes. 244 // individual load requests for domain keys or when all loading completes.
253 std::vector<net::CanonicalCookie*> cookies_; 245 std::vector<CanonicalCookie*> cookies_;
254 246
255 // Map of domain keys(eTLD+1) to domains/hosts that are to be loaded from DB. 247 // Map of domain keys(eTLD+1) to domains/hosts that are to be loaded from DB.
256 std::map<std::string, std::set<std::string> > keys_to_load_; 248 std::map<std::string, std::set<std::string> > keys_to_load_;
257 249
258 // Map of (domain keys(eTLD+1), is secure cookie) to number of cookies in the
259 // database.
260 typedef std::pair<std::string, bool> CookieOrigin;
261 typedef std::map<CookieOrigin, int> CookiesPerOriginMap;
262 CookiesPerOriginMap cookies_per_origin_;
263
264 // Indicates if DB has been initialized. 250 // Indicates if DB has been initialized.
265 bool initialized_; 251 bool initialized_;
266 252
267 // Indicates if the kill-database callback has been scheduled. 253 // Indicates if the kill-database callback has been scheduled.
268 bool corruption_detected_; 254 bool corruption_detected_;
269 255
270 // If false, we should filter out session cookies when reading the DB. 256 // If false, we should filter out session cookies when reading the DB.
271 bool restore_old_session_cookies_; 257 bool restore_old_session_cookies_;
272 258
273 // Policy defining what data is deleted on shutdown.
274 scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy_;
275
276 // The cumulative time spent loading the cookies on the background runner. 259 // The cumulative time spent loading the cookies on the background runner.
277 // Incremented and reported from the background runner. 260 // Incremented and reported from the background runner.
278 base::TimeDelta cookie_load_duration_; 261 base::TimeDelta cookie_load_duration_;
279 262
280 // The total number of cookies read. Incremented and reported on the 263 // The total number of cookies read. Incremented and reported on the
281 // background runner. 264 // background runner.
282 int num_cookies_read_; 265 int num_cookies_read_;
283 266
284 scoped_refptr<base::SequencedTaskRunner> client_task_runner_; 267 scoped_refptr<base::SequencedTaskRunner> client_task_runner_;
285 scoped_refptr<base::SequencedTaskRunner> background_task_runner_; 268 scoped_refptr<base::SequencedTaskRunner> background_task_runner_;
286 269
287 // Guards the following metrics-related properties (only accessed when 270 // Guards the following metrics-related properties (only accessed when
288 // starting/completing priority loads or completing the total load). 271 // starting/completing priority loads or completing the total load).
289 base::Lock metrics_lock_; 272 base::Lock metrics_lock_;
290 int num_priority_waiting_; 273 int num_priority_waiting_;
291 // The total number of priority requests. 274 // The total number of priority requests.
292 int total_priority_requests_; 275 int total_priority_requests_;
293 // The time when |num_priority_waiting_| incremented to 1. 276 // The time when |num_priority_waiting_| incremented to 1.
294 base::Time current_priority_wait_start_; 277 base::Time current_priority_wait_start_;
295 // The cumulative duration of time when |num_priority_waiting_| was greater 278 // The cumulative duration of time when |num_priority_waiting_| was greater
296 // than 1. 279 // than 1.
297 base::TimeDelta priority_wait_duration_; 280 base::TimeDelta priority_wait_duration_;
298 // Class with functions that do cryptographic operations (for protecting 281 // Class with functions that do cryptographic operations (for protecting
299 // cookies stored persistently). 282 // cookies stored persistently).
300 // 283 //
301 // Not owned. 284 // Not owned.
302 net::CookieCryptoDelegate* crypto_; 285 CookieCryptoDelegate* crypto_;
303 286
304 DISALLOW_COPY_AND_ASSIGN(Backend); 287 DISALLOW_COPY_AND_ASSIGN(Backend);
305 }; 288 };
306 289
307 namespace { 290 namespace {
308 291
309 // Version number of the database. 292 // Version number of the database.
310 // 293 //
311 // Version 8 adds "first-party only" cookies. 294 // Version 8 adds "first-party only" cookies.
312 // 295 //
(...skipping 23 matching lines...) Expand all
336 const int kCurrentVersionNumber = 8; 319 const int kCurrentVersionNumber = 8;
337 const int kCompatibleVersionNumber = 5; 320 const int kCompatibleVersionNumber = 5;
338 321
339 // Possible values for the 'priority' column. 322 // Possible values for the 'priority' column.
340 enum DBCookiePriority { 323 enum DBCookiePriority {
341 kCookiePriorityLow = 0, 324 kCookiePriorityLow = 0,
342 kCookiePriorityMedium = 1, 325 kCookiePriorityMedium = 1,
343 kCookiePriorityHigh = 2, 326 kCookiePriorityHigh = 2,
344 }; 327 };
345 328
346 DBCookiePriority CookiePriorityToDBCookiePriority(net::CookiePriority value) { 329 DBCookiePriority CookiePriorityToDBCookiePriority(CookiePriority value) {
347 switch (value) { 330 switch (value) {
348 case net::COOKIE_PRIORITY_LOW: 331 case COOKIE_PRIORITY_LOW:
349 return kCookiePriorityLow; 332 return kCookiePriorityLow;
350 case net::COOKIE_PRIORITY_MEDIUM: 333 case COOKIE_PRIORITY_MEDIUM:
351 return kCookiePriorityMedium; 334 return kCookiePriorityMedium;
352 case net::COOKIE_PRIORITY_HIGH: 335 case COOKIE_PRIORITY_HIGH:
353 return kCookiePriorityHigh; 336 return kCookiePriorityHigh;
354 } 337 }
355 338
356 NOTREACHED(); 339 NOTREACHED();
357 return kCookiePriorityMedium; 340 return kCookiePriorityMedium;
358 } 341 }
359 342
360 net::CookiePriority DBCookiePriorityToCookiePriority(DBCookiePriority value) { 343 CookiePriority DBCookiePriorityToCookiePriority(DBCookiePriority value) {
361 switch (value) { 344 switch (value) {
362 case kCookiePriorityLow: 345 case kCookiePriorityLow:
363 return net::COOKIE_PRIORITY_LOW; 346 return COOKIE_PRIORITY_LOW;
364 case kCookiePriorityMedium: 347 case kCookiePriorityMedium:
365 return net::COOKIE_PRIORITY_MEDIUM; 348 return COOKIE_PRIORITY_MEDIUM;
366 case kCookiePriorityHigh: 349 case kCookiePriorityHigh:
367 return net::COOKIE_PRIORITY_HIGH; 350 return COOKIE_PRIORITY_HIGH;
368 } 351 }
369 352
370 NOTREACHED(); 353 NOTREACHED();
371 return net::COOKIE_PRIORITY_DEFAULT; 354 return COOKIE_PRIORITY_DEFAULT;
372 } 355 }
373 356
374 // Increments a specified TimeDelta by the duration between this object's 357 // Increments a specified TimeDelta by the duration between this object's
375 // constructor and destructor. Not thread safe. Multiple instances may be 358 // constructor and destructor. Not thread safe. Multiple instances may be
376 // created with the same delta instance as long as their lifetimes are nested. 359 // created with the same delta instance as long as their lifetimes are nested.
377 // The shortest lived instances have no impact. 360 // The shortest lived instances have no impact.
378 class IncrementTimeDelta { 361 class IncrementTimeDelta {
379 public: 362 public:
380 explicit IncrementTimeDelta(base::TimeDelta* delta) : 363 explicit IncrementTimeDelta(base::TimeDelta* delta) :
381 delta_(delta), 364 delta_(delta),
(...skipping 24 matching lines...) Expand all
406 "path TEXT NOT NULL," 389 "path TEXT NOT NULL,"
407 "expires_utc INTEGER NOT NULL," 390 "expires_utc INTEGER NOT NULL,"
408 "secure INTEGER NOT NULL," 391 "secure INTEGER NOT NULL,"
409 "httponly INTEGER NOT NULL," 392 "httponly INTEGER NOT NULL,"
410 "last_access_utc INTEGER NOT NULL, " 393 "last_access_utc INTEGER NOT NULL, "
411 "has_expires INTEGER NOT NULL DEFAULT 1, " 394 "has_expires INTEGER NOT NULL DEFAULT 1, "
412 "persistent INTEGER NOT NULL DEFAULT 1," 395 "persistent INTEGER NOT NULL DEFAULT 1,"
413 "priority INTEGER NOT NULL DEFAULT %d," 396 "priority INTEGER NOT NULL DEFAULT %d,"
414 "encrypted_value BLOB DEFAULT ''," 397 "encrypted_value BLOB DEFAULT '',"
415 "firstpartyonly INTEGER NOT NULL DEFAULT 0)", 398 "firstpartyonly INTEGER NOT NULL DEFAULT 0)",
416 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT))); 399 CookiePriorityToDBCookiePriority(COOKIE_PRIORITY_DEFAULT)));
417 if (!db->Execute(stmt.c_str())) 400 if (!db->Execute(stmt.c_str()))
418 return false; 401 return false;
419 } 402 }
420 403
421 // Older code created an index on creation_utc, which is already 404 // Older code created an index on creation_utc, which is already
422 // primary key for the table. 405 // primary key for the table.
423 if (!db->Execute("DROP INDEX IF EXISTS cookie_times")) 406 if (!db->Execute("DROP INDEX IF EXISTS cookie_times"))
424 return false; 407 return false;
425 408
426 if (!db->Execute("CREATE INDEX IF NOT EXISTS domain ON cookies(host_key)")) 409 if (!db->Execute("CREATE INDEX IF NOT EXISTS domain ON cookies(host_key)"))
(...skipping 139 matching lines...) Expand 10 before | Expand all | Expand 10 after
566 549
567 if (load_success) 550 if (load_success)
568 ReportMetrics(); 551 ReportMetrics();
569 } 552 }
570 553
571 void SQLitePersistentCookieStore::Backend::Notify( 554 void SQLitePersistentCookieStore::Backend::Notify(
572 const LoadedCallback& loaded_callback, 555 const LoadedCallback& loaded_callback,
573 bool load_success) { 556 bool load_success) {
574 DCHECK(client_task_runner_->RunsTasksOnCurrentThread()); 557 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
575 558
576 std::vector<net::CanonicalCookie*> cookies; 559 std::vector<CanonicalCookie*> cookies;
577 { 560 {
578 base::AutoLock locked(lock_); 561 base::AutoLock locked(lock_);
579 cookies.swap(cookies_); 562 cookies.swap(cookies_);
580 } 563 }
581 564
582 loaded_callback.Run(cookies); 565 loaded_callback.Run(cookies);
583 } 566 }
584 567
585 bool SQLitePersistentCookieStore::Backend::InitializeDatabase() { 568 bool SQLitePersistentCookieStore::Backend::InitializeDatabase() {
586 DCHECK(background_task_runner_->RunsTasksOnCurrentThread()); 569 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
(...skipping 70 matching lines...) Expand 10 before | Expand all | Expand 10 after
657 base::Time::Now() - start, 640 base::Time::Now() - start,
658 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1), 641 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
659 50); 642 50);
660 643
661 base::Time start_parse = base::Time::Now(); 644 base::Time start_parse = base::Time::Now();
662 645
663 // Build a map of domain keys (always eTLD+1) to domains. 646 // Build a map of domain keys (always eTLD+1) to domains.
664 for (size_t idx = 0; idx < host_keys.size(); ++idx) { 647 for (size_t idx = 0; idx < host_keys.size(); ++idx) {
665 const std::string& domain = host_keys[idx]; 648 const std::string& domain = host_keys[idx];
666 std::string key = 649 std::string key =
667 net::registry_controlled_domains::GetDomainAndRegistry( 650 registry_controlled_domains::GetDomainAndRegistry(
668 domain, 651 domain,
669 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); 652 registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
670 653
671 keys_to_load_[key].insert(domain); 654 keys_to_load_[key].insert(domain);
672 } 655 }
673 656
674 UMA_HISTOGRAM_CUSTOM_TIMES( 657 UMA_HISTOGRAM_CUSTOM_TIMES(
675 "Cookie.TimeParseDomains", 658 "Cookie.TimeParseDomains",
676 base::Time::Now() - start_parse, 659 base::Time::Now() - start_parse,
677 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1), 660 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
678 50); 661 50);
679 662
(...skipping 61 matching lines...) Expand 10 before | Expand all | Expand 10 after
741 "has_expires, persistent, priority FROM cookies WHERE host_key = ? " 724 "has_expires, persistent, priority FROM cookies WHERE host_key = ? "
742 "AND persistent = 1")); 725 "AND persistent = 1"));
743 } 726 }
744 if (!smt.is_valid()) { 727 if (!smt.is_valid()) {
745 smt.Clear(); // Disconnect smt_ref from db_. 728 smt.Clear(); // Disconnect smt_ref from db_.
746 meta_table_.Reset(); 729 meta_table_.Reset();
747 db_.reset(); 730 db_.reset();
748 return false; 731 return false;
749 } 732 }
750 733
751 std::vector<net::CanonicalCookie*> cookies; 734 std::vector<CanonicalCookie*> cookies;
752 std::set<std::string>::const_iterator it = domains.begin(); 735 std::set<std::string>::const_iterator it = domains.begin();
753 for (; it != domains.end(); ++it) { 736 for (; it != domains.end(); ++it) {
754 smt.BindString(0, *it); 737 smt.BindString(0, *it);
755 MakeCookiesFromSQLStatement(&cookies, &smt); 738 MakeCookiesFromSQLStatement(&cookies, &smt);
756 smt.Reset(true); 739 smt.Reset(true);
757 } 740 }
758 { 741 {
759 base::AutoLock locked(lock_); 742 base::AutoLock locked(lock_);
760 cookies_.insert(cookies_.end(), cookies.begin(), cookies.end()); 743 cookies_.insert(cookies_.end(), cookies.begin(), cookies.end());
761 } 744 }
762 return true; 745 return true;
763 } 746 }
764 747
765 void SQLitePersistentCookieStore::Backend::MakeCookiesFromSQLStatement( 748 void SQLitePersistentCookieStore::Backend::MakeCookiesFromSQLStatement(
766 std::vector<net::CanonicalCookie*>* cookies, 749 std::vector<CanonicalCookie*>* cookies,
767 sql::Statement* statement) { 750 sql::Statement* statement) {
768 sql::Statement& smt = *statement; 751 sql::Statement& smt = *statement;
769 while (smt.Step()) { 752 while (smt.Step()) {
770 std::string value; 753 std::string value;
771 std::string encrypted_value = smt.ColumnString(4); 754 std::string encrypted_value = smt.ColumnString(4);
772 if (!encrypted_value.empty() && crypto_) { 755 if (!encrypted_value.empty() && crypto_) {
773 crypto_->DecryptString(encrypted_value, &value); 756 crypto_->DecryptString(encrypted_value, &value);
774 } else { 757 } else {
775 DCHECK(encrypted_value.empty()); 758 DCHECK(encrypted_value.empty());
776 value = smt.ColumnString(3); 759 value = smt.ColumnString(3);
777 } 760 }
778 scoped_ptr<net::CanonicalCookie> cc(new net::CanonicalCookie( 761 scoped_ptr<CanonicalCookie> cc(new CanonicalCookie(
779 // The "source" URL is not used with persisted cookies. 762 // The "source" URL is not used with persisted cookies.
780 GURL(), // Source 763 GURL(), // Source
781 smt.ColumnString(2), // name 764 smt.ColumnString(2), // name
782 value, // value 765 value, // value
783 smt.ColumnString(1), // domain 766 smt.ColumnString(1), // domain
784 smt.ColumnString(5), // path 767 smt.ColumnString(5), // path
785 Time::FromInternalValue(smt.ColumnInt64(0)), // creation_utc 768 Time::FromInternalValue(smt.ColumnInt64(0)), // creation_utc
786 Time::FromInternalValue(smt.ColumnInt64(6)), // expires_utc 769 Time::FromInternalValue(smt.ColumnInt64(6)), // expires_utc
787 Time::FromInternalValue(smt.ColumnInt64(10)), // last_access_utc 770 Time::FromInternalValue(smt.ColumnInt64(10)), // last_access_utc
788 smt.ColumnInt(7) != 0, // secure 771 smt.ColumnInt(7) != 0, // secure
789 smt.ColumnInt(8) != 0, // httponly 772 smt.ColumnInt(8) != 0, // httponly
790 smt.ColumnInt(9) != 0, // firstpartyonly 773 smt.ColumnInt(9) != 0, // firstpartyonly
791 DBCookiePriorityToCookiePriority( 774 DBCookiePriorityToCookiePriority(
792 static_cast<DBCookiePriority>(smt.ColumnInt(13))))); // priority 775 static_cast<DBCookiePriority>(smt.ColumnInt(13))))); // priority
793 DLOG_IF(WARNING, cc->CreationDate() > Time::Now()) 776 DLOG_IF(WARNING, cc->CreationDate() > Time::Now())
794 << L"CreationDate too recent"; 777 << L"CreationDate too recent";
795 cookies_per_origin_[CookieOrigin(cc->Domain(), cc->IsSecure())]++;
796 cookies->push_back(cc.release()); 778 cookies->push_back(cc.release());
797 ++num_cookies_read_; 779 ++num_cookies_read_;
798 } 780 }
799 } 781 }
800 782
801 bool SQLitePersistentCookieStore::Backend::EnsureDatabaseVersion() { 783 bool SQLitePersistentCookieStore::Backend::EnsureDatabaseVersion() {
802 // Version check. 784 // Version check.
803 if (!meta_table_.Init( 785 if (!meta_table_.Init(
804 db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) { 786 db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) {
805 return false; 787 return false;
(...skipping 78 matching lines...) Expand 10 before | Expand all | Expand 10 after
884 } 866 }
885 867
886 if (cur_version == 5) { 868 if (cur_version == 5) {
887 const base::TimeTicks start_time = base::TimeTicks::Now(); 869 const base::TimeTicks start_time = base::TimeTicks::Now();
888 sql::Transaction transaction(db_.get()); 870 sql::Transaction transaction(db_.get());
889 if (!transaction.Begin()) 871 if (!transaction.Begin())
890 return false; 872 return false;
891 // Alter the table to add the priority column with a default value. 873 // Alter the table to add the priority column with a default value.
892 std::string stmt(base::StringPrintf( 874 std::string stmt(base::StringPrintf(
893 "ALTER TABLE cookies ADD COLUMN priority INTEGER DEFAULT %d", 875 "ALTER TABLE cookies ADD COLUMN priority INTEGER DEFAULT %d",
894 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT))); 876 CookiePriorityToDBCookiePriority(COOKIE_PRIORITY_DEFAULT)));
895 if (!db_->Execute(stmt.c_str())) { 877 if (!db_->Execute(stmt.c_str())) {
896 LOG(WARNING) << "Unable to update cookie database to version 6."; 878 LOG(WARNING) << "Unable to update cookie database to version 6.";
897 return false; 879 return false;
898 } 880 }
899 ++cur_version; 881 ++cur_version;
900 meta_table_.SetVersionNumber(cur_version); 882 meta_table_.SetVersionNumber(cur_version);
901 meta_table_.SetCompatibleVersionNumber( 883 meta_table_.SetCompatibleVersionNumber(
902 std::min(cur_version, kCompatibleVersionNumber)); 884 std::min(cur_version, kCompatibleVersionNumber));
903 transaction.Commit(); 885 transaction.Commit();
904 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV6", 886 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV6",
(...skipping 57 matching lines...) Expand 10 before | Expand all | Expand 10 after
962 meta_table_.Reset(); 944 meta_table_.Reset();
963 db_.reset(); 945 db_.reset();
964 return false; 946 return false;
965 } 947 }
966 } 948 }
967 949
968 return true; 950 return true;
969 } 951 }
970 952
971 void SQLitePersistentCookieStore::Backend::AddCookie( 953 void SQLitePersistentCookieStore::Backend::AddCookie(
972 const net::CanonicalCookie& cc) { 954 const CanonicalCookie& cc) {
973 BatchOperation(PendingOperation::COOKIE_ADD, cc); 955 BatchOperation(PendingOperation::COOKIE_ADD, cc);
974 } 956 }
975 957
976 void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime( 958 void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime(
977 const net::CanonicalCookie& cc) { 959 const CanonicalCookie& cc) {
978 BatchOperation(PendingOperation::COOKIE_UPDATEACCESS, cc); 960 BatchOperation(PendingOperation::COOKIE_UPDATEACCESS, cc);
979 } 961 }
980 962
981 void SQLitePersistentCookieStore::Backend::DeleteCookie( 963 void SQLitePersistentCookieStore::Backend::DeleteCookie(
982 const net::CanonicalCookie& cc) { 964 const CanonicalCookie& cc) {
983 BatchOperation(PendingOperation::COOKIE_DELETE, cc); 965 BatchOperation(PendingOperation::COOKIE_DELETE, cc);
984 } 966 }
985 967
986 void SQLitePersistentCookieStore::Backend::BatchOperation( 968 void SQLitePersistentCookieStore::Backend::BatchOperation(
987 PendingOperation::OperationType op, 969 PendingOperation::OperationType op,
988 const net::CanonicalCookie& cc) { 970 const CanonicalCookie& cc) {
989 // Commit every 30 seconds. 971 // Commit every 30 seconds.
990 static const int kCommitIntervalMs = 30 * 1000; 972 static const int kCommitIntervalMs = 30 * 1000;
991 // Commit right away if we have more than 512 outstanding operations. 973 // Commit right away if we have more than 512 outstanding operations.
992 static const size_t kCommitAfterBatchSize = 512; 974 static const size_t kCommitAfterBatchSize = 512;
993 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread()); 975 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
994 976
995 // We do a full copy of the cookie here, and hopefully just here. 977 // We do a full copy of the cookie here, and hopefully just here.
996 scoped_ptr<PendingOperation> po(new PendingOperation(op, cc)); 978 scoped_ptr<PendingOperation> po(new PendingOperation(op, cc));
997 979
998 PendingOperationsList::size_type num_pending; 980 PendingOperationsList::size_type num_pending;
(...skipping 52 matching lines...) Expand 10 before | Expand all | Expand 10 after
1051 sql::Transaction transaction(db_.get()); 1033 sql::Transaction transaction(db_.get());
1052 if (!transaction.Begin()) 1034 if (!transaction.Begin())
1053 return; 1035 return;
1054 1036
1055 for (PendingOperationsList::iterator it = ops.begin(); 1037 for (PendingOperationsList::iterator it = ops.begin();
1056 it != ops.end(); ++it) { 1038 it != ops.end(); ++it) {
1057 // Free the cookies as we commit them to the database. 1039 // Free the cookies as we commit them to the database.
1058 scoped_ptr<PendingOperation> po(*it); 1040 scoped_ptr<PendingOperation> po(*it);
1059 switch (po->op()) { 1041 switch (po->op()) {
1060 case PendingOperation::COOKIE_ADD: 1042 case PendingOperation::COOKIE_ADD:
1061 cookies_per_origin_[
1062 CookieOrigin(po->cc().Domain(), po->cc().IsSecure())]++;
1063 add_smt.Reset(true); 1043 add_smt.Reset(true);
1064 add_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue()); 1044 add_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1065 add_smt.BindString(1, po->cc().Domain()); 1045 add_smt.BindString(1, po->cc().Domain());
1066 add_smt.BindString(2, po->cc().Name()); 1046 add_smt.BindString(2, po->cc().Name());
1067 if (crypto_) { 1047 if (crypto_) {
1068 std::string encrypted_value; 1048 std::string encrypted_value;
1069 add_smt.BindCString(3, ""); // value 1049 add_smt.BindCString(3, ""); // value
1070 crypto_->EncryptString(po->cc().Value(), &encrypted_value); 1050 crypto_->EncryptString(po->cc().Value(), &encrypted_value);
1071 // BindBlob() immediately makes an internal copy of the data. 1051 // BindBlob() immediately makes an internal copy of the data.
1072 add_smt.BindBlob(4, encrypted_value.data(), 1052 add_smt.BindBlob(4, encrypted_value.data(),
(...skipping 20 matching lines...) Expand all
1093 update_access_smt.Reset(true); 1073 update_access_smt.Reset(true);
1094 update_access_smt.BindInt64(0, 1074 update_access_smt.BindInt64(0,
1095 po->cc().LastAccessDate().ToInternalValue()); 1075 po->cc().LastAccessDate().ToInternalValue());
1096 update_access_smt.BindInt64(1, 1076 update_access_smt.BindInt64(1,
1097 po->cc().CreationDate().ToInternalValue()); 1077 po->cc().CreationDate().ToInternalValue());
1098 if (!update_access_smt.Run()) 1078 if (!update_access_smt.Run())
1099 NOTREACHED() << "Could not update cookie last access time in the DB."; 1079 NOTREACHED() << "Could not update cookie last access time in the DB.";
1100 break; 1080 break;
1101 1081
1102 case PendingOperation::COOKIE_DELETE: 1082 case PendingOperation::COOKIE_DELETE:
1103 cookies_per_origin_[
1104 CookieOrigin(po->cc().Domain(), po->cc().IsSecure())]--;
1105 del_smt.Reset(true); 1083 del_smt.Reset(true);
1106 del_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue()); 1084 del_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1107 if (!del_smt.Run()) 1085 if (!del_smt.Run())
1108 NOTREACHED() << "Could not delete a cookie from the DB."; 1086 NOTREACHED() << "Could not delete a cookie from the DB.";
1109 break; 1087 break;
1110 1088
1111 default: 1089 default:
1112 NOTREACHED(); 1090 NOTREACHED();
1113 break; 1091 break;
1114 } 1092 }
(...skipping 27 matching lines...) Expand all
1142 PostBackgroundTask(FROM_HERE, 1120 PostBackgroundTask(FROM_HERE,
1143 base::Bind(&Backend::InternalBackgroundClose, this)); 1121 base::Bind(&Backend::InternalBackgroundClose, this));
1144 } 1122 }
1145 } 1123 }
1146 1124
1147 void SQLitePersistentCookieStore::Backend::InternalBackgroundClose() { 1125 void SQLitePersistentCookieStore::Backend::InternalBackgroundClose() {
1148 DCHECK(background_task_runner_->RunsTasksOnCurrentThread()); 1126 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1149 // Commit any pending operations 1127 // Commit any pending operations
1150 Commit(); 1128 Commit();
1151 1129
1152 if (!force_keep_session_state_ && special_storage_policy_.get() &&
1153 special_storage_policy_->HasSessionOnlyOrigins()) {
1154 DeleteSessionCookiesOnShutdown();
1155 }
1156
1157 meta_table_.Reset(); 1130 meta_table_.Reset();
1158 db_.reset(); 1131 db_.reset();
1159 } 1132 }
1160 1133
1161 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnShutdown() {
1162 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1163
1164 if (!db_)
1165 return;
1166
1167 if (!special_storage_policy_.get())
1168 return;
1169
1170 sql::Statement del_smt(db_->GetCachedStatement(
1171 SQL_FROM_HERE, "DELETE FROM cookies WHERE host_key=? AND secure=?"));
1172 if (!del_smt.is_valid()) {
1173 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1174 return;
1175 }
1176
1177 sql::Transaction transaction(db_.get());
1178 if (!transaction.Begin()) {
1179 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1180 return;
1181 }
1182
1183 for (CookiesPerOriginMap::iterator it = cookies_per_origin_.begin();
1184 it != cookies_per_origin_.end(); ++it) {
1185 if (it->second <= 0) {
1186 DCHECK_EQ(0, it->second);
1187 continue;
1188 }
1189 const GURL url(net::cookie_util::CookieOriginToURL(it->first.first,
1190 it->first.second));
1191 if (!url.is_valid() || !special_storage_policy_->IsStorageSessionOnly(url))
1192 continue;
1193
1194 del_smt.Reset(true);
1195 del_smt.BindString(0, it->first.first);
1196 del_smt.BindInt(1, it->first.second);
1197 if (!del_smt.Run())
1198 NOTREACHED() << "Could not delete a cookie from the DB.";
1199 }
1200
1201 if (!transaction.Commit())
1202 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1203 }
1204
1205 void SQLitePersistentCookieStore::Backend::DatabaseErrorCallback( 1134 void SQLitePersistentCookieStore::Backend::DatabaseErrorCallback(
1206 int error, 1135 int error,
1207 sql::Statement* stmt) { 1136 sql::Statement* stmt) {
1208 DCHECK(background_task_runner_->RunsTasksOnCurrentThread()); 1137 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1209 1138
1210 if (!sql::IsErrorCatastrophic(error)) 1139 if (!sql::IsErrorCatastrophic(error))
1211 return; 1140 return;
1212 1141
1213 // TODO(shess): Running KillDatabase() multiple times should be 1142 // TODO(shess): Running KillDatabase() multiple times should be
1214 // safe. 1143 // safe.
(...skipping 16 matching lines...) Expand all
1231 if (db_) { 1160 if (db_) {
1232 // This Backend will now be in-memory only. In a future run we will recreate 1161 // This Backend will now be in-memory only. In a future run we will recreate
1233 // the database. Hopefully things go better then! 1162 // the database. Hopefully things go better then!
1234 bool success = db_->RazeAndClose(); 1163 bool success = db_->RazeAndClose();
1235 UMA_HISTOGRAM_BOOLEAN("Cookie.KillDatabaseResult", success); 1164 UMA_HISTOGRAM_BOOLEAN("Cookie.KillDatabaseResult", success);
1236 meta_table_.Reset(); 1165 meta_table_.Reset();
1237 db_.reset(); 1166 db_.reset();
1238 } 1167 }
1239 } 1168 }
1240 1169
1241 void SQLitePersistentCookieStore::Backend::SetForceKeepSessionState() { 1170 void SQLitePersistentCookieStore::Backend::DeleteAllInList(
1242 base::AutoLock locked(lock_); 1171 const std::list<CookieOrigin> cookies) {
1243 force_keep_session_state_ = true; 1172 if (cookies.empty())
1173 return;
1174
1175 // Perform deletion on background task runner.
1176 background_task_runner_->PostTask(
1177 FROM_HERE,
1178 base::Bind(
1179 &Backend::BackgroundDeleteAllInList, this, cookies));
1244 } 1180 }
1245 1181
1246 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup() { 1182 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup() {
1247 DCHECK(background_task_runner_->RunsTasksOnCurrentThread()); 1183 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1248 if (!db_->Execute("DELETE FROM cookies WHERE persistent == 0")) 1184 if (!db_->Execute("DELETE FROM cookies WHERE persistent == 0"))
1249 LOG(WARNING) << "Unable to delete session cookies."; 1185 LOG(WARNING) << "Unable to delete session cookies.";
1250 } 1186 }
1251 1187
1188 void SQLitePersistentCookieStore::Backend::BackgroundDeleteAllInList(
1189 const std::list<CookieOrigin> cookies) {
1190 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1191
1192 if (!db_)
1193 return;
1194
1195 // Force a commit of any pending writes before issuing deletes.
1196 Commit();
1197
1198 sql::Statement del_smt(db_->GetCachedStatement(
1199 SQL_FROM_HERE, "DELETE FROM cookies WHERE host_key=? AND secure=?"));
1200 if (!del_smt.is_valid()) {
1201 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1202 return;
1203 }
1204
1205 sql::Transaction transaction(db_.get());
1206 if (!transaction.Begin()) {
1207 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1208 return;
1209 }
1210
1211 for (auto it = cookies.begin(); it != cookies.end(); ++it) {
1212 const GURL url(cookie_util::CookieOriginToURL(it->first, it->second));
1213 del_smt.Reset(true);
1214 del_smt.BindString(0, it->first);
1215 del_smt.BindInt(1, it->second);
1216 if (!del_smt.Run())
1217 NOTREACHED() << "Could not delete a cookie from the DB.";
1218 }
1219
1220 if (!transaction.Commit())
1221 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1222 }
1223
1252 void SQLitePersistentCookieStore::Backend::PostBackgroundTask( 1224 void SQLitePersistentCookieStore::Backend::PostBackgroundTask(
1253 const tracked_objects::Location& origin, const base::Closure& task) { 1225 const tracked_objects::Location& origin, const base::Closure& task) {
1254 if (!background_task_runner_->PostTask(origin, task)) { 1226 if (!background_task_runner_->PostTask(origin, task)) {
1255 LOG(WARNING) << "Failed to post task from " << origin.ToString() 1227 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1256 << " to background_task_runner_."; 1228 << " to background_task_runner_.";
1257 } 1229 }
1258 } 1230 }
1259 1231
1260 void SQLitePersistentCookieStore::Backend::PostClientTask( 1232 void SQLitePersistentCookieStore::Backend::PostClientTask(
1261 const tracked_objects::Location& origin, const base::Closure& task) { 1233 const tracked_objects::Location& origin, const base::Closure& task) {
(...skipping 10 matching lines...) Expand all
1272 loaded_callback, success)); 1244 loaded_callback, success));
1273 if (success && !restore_old_session_cookies_) 1245 if (success && !restore_old_session_cookies_)
1274 DeleteSessionCookiesOnStartup(); 1246 DeleteSessionCookiesOnStartup();
1275 } 1247 }
1276 1248
1277 SQLitePersistentCookieStore::SQLitePersistentCookieStore( 1249 SQLitePersistentCookieStore::SQLitePersistentCookieStore(
1278 const base::FilePath& path, 1250 const base::FilePath& path,
1279 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner, 1251 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
1280 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner, 1252 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
1281 bool restore_old_session_cookies, 1253 bool restore_old_session_cookies,
1282 storage::SpecialStoragePolicy* special_storage_policy, 1254 CookieCryptoDelegate* crypto_delegate)
1283 net::CookieCryptoDelegate* crypto_delegate)
1284 : backend_(new Backend(path, 1255 : backend_(new Backend(path,
1285 client_task_runner, 1256 client_task_runner,
1286 background_task_runner, 1257 background_task_runner,
1287 restore_old_session_cookies, 1258 restore_old_session_cookies,
1288 special_storage_policy,
1289 crypto_delegate)) { 1259 crypto_delegate)) {
1290 } 1260 }
1291 1261
1262 void SQLitePersistentCookieStore::DeleteAllInList(
1263 std::list<CookieOrigin> cookies) {
1264 backend_->DeleteAllInList(cookies);
1265 }
1266
1292 void SQLitePersistentCookieStore::Load(const LoadedCallback& loaded_callback) { 1267 void SQLitePersistentCookieStore::Load(const LoadedCallback& loaded_callback) {
1293 backend_->Load(loaded_callback); 1268 backend_->Load(loaded_callback);
1294 } 1269 }
1295 1270
1296 void SQLitePersistentCookieStore::LoadCookiesForKey( 1271 void SQLitePersistentCookieStore::LoadCookiesForKey(
1297 const std::string& key, 1272 const std::string& key,
1298 const LoadedCallback& loaded_callback) { 1273 const LoadedCallback& loaded_callback) {
1299 backend_->LoadCookiesForKey(key, loaded_callback); 1274 backend_->LoadCookiesForKey(key, loaded_callback);
1300 } 1275 }
1301 1276
1302 void SQLitePersistentCookieStore::AddCookie(const net::CanonicalCookie& cc) { 1277 void SQLitePersistentCookieStore::AddCookie(const CanonicalCookie& cc) {
1303 backend_->AddCookie(cc); 1278 backend_->AddCookie(cc);
1304 } 1279 }
1305 1280
1306 void SQLitePersistentCookieStore::UpdateCookieAccessTime( 1281 void SQLitePersistentCookieStore::UpdateCookieAccessTime(
1307 const net::CanonicalCookie& cc) { 1282 const CanonicalCookie& cc) {
1308 backend_->UpdateCookieAccessTime(cc); 1283 backend_->UpdateCookieAccessTime(cc);
1309 } 1284 }
1310 1285
1311 void SQLitePersistentCookieStore::DeleteCookie(const net::CanonicalCookie& cc) { 1286 void SQLitePersistentCookieStore::DeleteCookie(const CanonicalCookie& cc) {
1312 backend_->DeleteCookie(cc); 1287 backend_->DeleteCookie(cc);
1313 } 1288 }
1314 1289
1315 void SQLitePersistentCookieStore::SetForceKeepSessionState() { 1290 void SQLitePersistentCookieStore::SetForceKeepSessionState() {
1316 backend_->SetForceKeepSessionState(); 1291 // This store never discards session-only cookies, so this call has no effect.
1317 } 1292 }
1318 1293
1319 void SQLitePersistentCookieStore::Flush(const base::Closure& callback) { 1294 void SQLitePersistentCookieStore::Flush(const base::Closure& callback) {
1320 backend_->Flush(callback); 1295 backend_->Flush(callback);
1321 } 1296 }
1322 1297
1323 SQLitePersistentCookieStore::~SQLitePersistentCookieStore() { 1298 SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
1324 backend_->Close(); 1299 backend_->Close();
1325 // We release our reference to the Backend, though it will probably still have 1300 // We release our reference to the Backend, though it will probably still have
1326 // a reference if the background runner has not run Close() yet. 1301 // a reference if the background runner has not run Close() yet.
1327 } 1302 }
1328 1303
1329 CookieStoreConfig::CookieStoreConfig() 1304 } // namespace net
1330 : session_cookie_mode(EPHEMERAL_SESSION_COOKIES),
1331 crypto_delegate(NULL) {
1332 // Default to an in-memory cookie store.
1333 }
1334
1335 CookieStoreConfig::CookieStoreConfig(
1336 const base::FilePath& path,
1337 SessionCookieMode session_cookie_mode,
1338 storage::SpecialStoragePolicy* storage_policy,
1339 net::CookieMonsterDelegate* cookie_delegate)
1340 : path(path),
1341 session_cookie_mode(session_cookie_mode),
1342 storage_policy(storage_policy),
1343 cookie_delegate(cookie_delegate),
1344 crypto_delegate(NULL) {
1345 CHECK(!path.empty() || session_cookie_mode == EPHEMERAL_SESSION_COOKIES);
1346 }
1347
1348 CookieStoreConfig::~CookieStoreConfig() {
1349 }
1350
1351 net::CookieStore* CreateCookieStore(const CookieStoreConfig& config) {
1352 net::CookieMonster* cookie_monster = NULL;
1353
1354 if (config.path.empty()) {
1355 // Empty path means in-memory store.
1356 cookie_monster = new net::CookieMonster(NULL, config.cookie_delegate.get());
1357 } else {
1358 scoped_refptr<base::SequencedTaskRunner> client_task_runner =
1359 config.client_task_runner;
1360 scoped_refptr<base::SequencedTaskRunner> background_task_runner =
1361 config.background_task_runner;
1362
1363 if (!client_task_runner.get()) {
1364 client_task_runner =
1365 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
1366 }
1367
1368 if (!background_task_runner.get()) {
1369 background_task_runner =
1370 BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
1371 BrowserThread::GetBlockingPool()->GetSequenceToken());
1372 }
1373
1374 SQLitePersistentCookieStore* persistent_store =
1375 new SQLitePersistentCookieStore(
1376 config.path,
1377 client_task_runner,
1378 background_task_runner,
1379 (config.session_cookie_mode ==
1380 CookieStoreConfig::RESTORED_SESSION_COOKIES),
1381 config.storage_policy.get(),
1382 config.crypto_delegate);
1383
1384 cookie_monster =
1385 new net::CookieMonster(persistent_store, config.cookie_delegate.get());
1386 if ((config.session_cookie_mode ==
1387 CookieStoreConfig::PERSISTANT_SESSION_COOKIES) ||
1388 (config.session_cookie_mode ==
1389 CookieStoreConfig::RESTORED_SESSION_COOKIES)) {
1390 cookie_monster->SetPersistSessionCookies(true);
1391 }
1392 }
1393
1394 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1395 switches::kEnableFileCookies)) {
1396 cookie_monster->SetEnableFileScheme(true);
1397 }
1398
1399 return cookie_monster;
1400 }
1401
1402 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698