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

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: Better timestamp fix. Created 5 years, 7 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/files/file_path.h" 15 #include "base/files/file_path.h"
16 #include "base/files/file_util.h" 16 #include "base/files/file_util.h"
17 #include "base/location.h" 17 #include "base/location.h"
18 #include "base/logging.h" 18 #include "base/logging.h"
19 #include "base/memory/ref_counted.h" 19 #include "base/memory/ref_counted.h"
20 #include "base/memory/scoped_ptr.h" 20 #include "base/memory/scoped_ptr.h"
21 #include "base/metrics/field_trial.h" 21 #include "base/metrics/field_trial.h"
22 #include "base/metrics/histogram.h" 22 #include "base/metrics/histogram.h"
23 #include "base/profiler/scoped_tracker.h" 23 #include "base/profiler/scoped_tracker.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 "net/base/registry_controlled_domains/registry_controlled_domain.h" 30 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
33 #include "net/cookies/canonical_cookie.h" 31 #include "net/cookies/canonical_cookie.h"
34 #include "net/cookies/cookie_constants.h" 32 #include "net/cookies/cookie_constants.h"
35 #include "net/cookies/cookie_util.h" 33 #include "net/cookies/cookie_util.h"
36 #include "net/extras/sqlite/cookie_crypto_delegate.h" 34 #include "net/extras/sqlite/cookie_crypto_delegate.h"
37 #include "sql/error_delegate_util.h" 35 #include "sql/error_delegate_util.h"
38 #include "sql/meta_table.h" 36 #include "sql/meta_table.h"
39 #include "sql/statement.h" 37 #include "sql/statement.h"
40 #include "sql/transaction.h" 38 #include "sql/transaction.h"
41 #include "storage/browser/quota/special_storage_policy.h"
42 #include "third_party/sqlite/sqlite3.h"
43 #include "url/gurl.h" 39 #include "url/gurl.h"
44 40
45 using base::Time; 41 using base::Time;
46 42
47 namespace { 43 namespace {
48 44
49 // The persistent cookie store is loaded into memory on eTLD at a time. This 45 // The persistent cookie store is loaded into memory on eTLD at a time. This
50 // variable controls the delay between loading eTLDs, so as to not overload the 46 // variable controls the delay between loading eTLDs, so as to not overload the
51 // CPU or I/O with these low priority requests immediately after start up. 47 // CPU or I/O with these low priority requests immediately after start up.
52 const int kLoadDelayMilliseconds = 0; 48 const int kLoadDelayMilliseconds = 0;
53 49
54 } // namespace 50 } // namespace
55 51
56 namespace content { 52 namespace net {
57 53
58 // This class is designed to be shared between any client thread and the 54 // This class is designed to be shared between any client thread and the
59 // background task runner. It batches operations and commits them on a timer. 55 // background task runner. It batches operations and commits them on a timer.
60 // 56 //
61 // SQLitePersistentCookieStore::Load is called to load all cookies. It 57 // SQLitePersistentCookieStore::Load is called to load all cookies. It
62 // delegates to Backend::Load, which posts a Backend::LoadAndNotifyOnDBThread 58 // delegates to Backend::Load, which posts a Backend::LoadAndNotifyOnDBThread
63 // task to the background runner. This task calls Backend::ChainLoadCookies(), 59 // task to the background runner. This task calls Backend::ChainLoadCookies(),
64 // which repeatedly posts itself to the BG runner to load each eTLD+1's cookies 60 // which repeatedly posts itself to the BG runner to load each eTLD+1's cookies
65 // in separate tasks. When this is complete, Backend::CompleteLoadOnIOThread is 61 // in separate tasks. When this is complete, Backend::CompleteLoadOnIOThread is
66 // posted to the client runner, which notifies the caller of 62 // posted to the client runner, which notifies the caller of
(...skipping 11 matching lines...) Expand all
78 // disk on the BG runner every 30 seconds, 512 operations, or call to Flush(), 74 // disk on the BG runner every 30 seconds, 512 operations, or call to Flush(),
79 // whichever occurs first. 75 // whichever occurs first.
80 class SQLitePersistentCookieStore::Backend 76 class SQLitePersistentCookieStore::Backend
81 : public base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend> { 77 : public base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend> {
82 public: 78 public:
83 Backend( 79 Backend(
84 const base::FilePath& path, 80 const base::FilePath& path,
85 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner, 81 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
86 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner, 82 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
87 bool restore_old_session_cookies, 83 bool restore_old_session_cookies,
88 storage::SpecialStoragePolicy* special_storage_policy, 84 CookieCryptoDelegate* crypto_delegate)
89 net::CookieCryptoDelegate* crypto_delegate)
90 : path_(path), 85 : path_(path),
91 num_pending_(0), 86 num_pending_(0),
92 force_keep_session_state_(false),
93 initialized_(false), 87 initialized_(false),
94 corruption_detected_(false), 88 corruption_detected_(false),
95 restore_old_session_cookies_(restore_old_session_cookies), 89 restore_old_session_cookies_(restore_old_session_cookies),
96 special_storage_policy_(special_storage_policy),
97 num_cookies_read_(0), 90 num_cookies_read_(0),
98 client_task_runner_(client_task_runner), 91 client_task_runner_(client_task_runner),
99 background_task_runner_(background_task_runner), 92 background_task_runner_(background_task_runner),
100 num_priority_waiting_(0), 93 num_priority_waiting_(0),
101 total_priority_requests_(0), 94 total_priority_requests_(0),
102 crypto_(crypto_delegate) {} 95 crypto_(crypto_delegate) {}
103 96
104 // Creates or loads the SQLite database. 97 // Creates or loads the SQLite database.
105 void Load(const LoadedCallback& loaded_callback); 98 void Load(const LoadedCallback& loaded_callback);
106 99
107 // Loads cookies for the domain key (eTLD+1). 100 // Loads cookies for the domain key (eTLD+1).
108 void LoadCookiesForKey(const std::string& domain, 101 void LoadCookiesForKey(const std::string& domain,
109 const LoadedCallback& loaded_callback); 102 const LoadedCallback& loaded_callback);
110 103
111 // Steps through all results of |smt|, makes a cookie from each, and adds the 104 // Steps through all results of |smt|, makes a cookie from each, and adds the
112 // cookie to |cookies|. This method also updates |cookies_per_origin_| and 105 // cookie to |cookies|. This method also updates |num_cookies_read_|.
113 // |num_cookies_read_|. 106 void MakeCookiesFromSQLStatement(std::vector<CanonicalCookie*>* cookies,
114 void MakeCookiesFromSQLStatement(std::vector<net::CanonicalCookie*>* cookies,
115 sql::Statement* statement); 107 sql::Statement* statement);
116 108
117 // Batch a cookie addition. 109 // Batch a cookie addition.
118 void AddCookie(const net::CanonicalCookie& cc); 110 void AddCookie(const CanonicalCookie& cc);
119 111
120 // Batch a cookie access time update. 112 // Batch a cookie access time update.
121 void UpdateCookieAccessTime(const net::CanonicalCookie& cc); 113 void UpdateCookieAccessTime(const CanonicalCookie& cc);
122 114
123 // Batch a cookie deletion. 115 // Batch a cookie deletion.
124 void DeleteCookie(const net::CanonicalCookie& cc); 116 void DeleteCookie(const CanonicalCookie& cc);
125 117
126 // Commit pending operations as soon as possible. 118 // Commit pending operations as soon as possible.
127 void Flush(const base::Closure& callback); 119 void Flush(const base::Closure& callback);
128 120
129 // Commit any pending operations and close the database. This must be called 121 // Commit any pending operations and close the database. This must be called
130 // before the object is destructed. 122 // before the object is destructed.
131 void Close(); 123 void Close();
132 124
133 void SetForceKeepSessionState(); 125 // Post background delete of all cookies that match |cookies|.
126 void DeleteAllInList(const std::list<CookieOrigin>& cookies);
134 127
135 private: 128 private:
136 friend class base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend>; 129 friend class base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend>;
137 130
138 // You should call Close() before destructing this object. 131 // You should call Close() before destructing this object.
139 ~Backend() { 132 ~Backend() {
140 DCHECK(!db_.get()) << "Close should have already been called."; 133 DCHECK(!db_.get()) << "Close should have already been called.";
141 DCHECK(num_pending_ == 0 && pending_.empty()); 134 DCHECK_EQ(0u, num_pending_);
135 DCHECK(pending_.empty());
142 136
143 for (net::CanonicalCookie* cookie : cookies_) { 137 for (CanonicalCookie* cookie : cookies_) {
144 delete cookie; 138 delete cookie;
145 } 139 }
146 } 140 }
147 141
148 // Database upgrade statements. 142 // Database upgrade statements.
149 bool EnsureDatabaseVersion(); 143 bool EnsureDatabaseVersion();
150 144
151 class PendingOperation { 145 class PendingOperation {
152 public: 146 public:
153 typedef enum { 147 enum OperationType {
154 COOKIE_ADD, 148 COOKIE_ADD,
155 COOKIE_UPDATEACCESS, 149 COOKIE_UPDATEACCESS,
156 COOKIE_DELETE, 150 COOKIE_DELETE,
157 } OperationType; 151 };
158 152
159 PendingOperation(OperationType op, const net::CanonicalCookie& cc) 153 PendingOperation(OperationType op, const CanonicalCookie& cc)
160 : op_(op), cc_(cc) { } 154 : op_(op), cc_(cc) { }
161 155
162 OperationType op() const { return op_; } 156 OperationType op() const { return op_; }
163 const net::CanonicalCookie& cc() const { return cc_; } 157 const CanonicalCookie& cc() const { return cc_; }
164 158
165 private: 159 private:
166 OperationType op_; 160 OperationType op_;
167 net::CanonicalCookie cc_; 161 CanonicalCookie cc_;
168 }; 162 };
169 163
170 private: 164 private:
171 // Creates or loads the SQLite database on background runner. 165 // Creates or loads the SQLite database on background runner.
172 void LoadAndNotifyInBackground(const LoadedCallback& loaded_callback, 166 void LoadAndNotifyInBackground(const LoadedCallback& loaded_callback,
173 const base::Time& posted_at); 167 const base::Time& posted_at);
174 168
175 // Loads cookies for the domain key (eTLD+1) on background runner. 169 // Loads cookies for the domain key (eTLD+1) on background runner.
176 void LoadKeyAndNotifyInBackground(const std::string& domains, 170 void LoadKeyAndNotifyInBackground(const std::string& domains,
177 const LoadedCallback& loaded_callback, 171 const LoadedCallback& loaded_callback,
(...skipping 30 matching lines...) Expand all
208 // Loads cookies for the next domain key from the DB, then either reschedules 202 // Loads cookies for the next domain key from the DB, then either reschedules
209 // itself or schedules the provided callback to run on the client runner (if 203 // itself or schedules the provided callback to run on the client runner (if
210 // all domains are loaded). 204 // all domains are loaded).
211 void ChainLoadCookies(const LoadedCallback& loaded_callback); 205 void ChainLoadCookies(const LoadedCallback& loaded_callback);
212 206
213 // Load all cookies for a set of domains/hosts 207 // Load all cookies for a set of domains/hosts
214 bool LoadCookiesForDomains(const std::set<std::string>& key); 208 bool LoadCookiesForDomains(const std::set<std::string>& key);
215 209
216 // Batch a cookie operation (add or delete) 210 // Batch a cookie operation (add or delete)
217 void BatchOperation(PendingOperation::OperationType op, 211 void BatchOperation(PendingOperation::OperationType op,
218 const net::CanonicalCookie& cc); 212 const CanonicalCookie& cc);
219 // Commit our pending operations to the database. 213 // Commit our pending operations to the database.
220 void Commit(); 214 void Commit();
221 // Close() executed on the background runner. 215 // Close() executed on the background runner.
222 void InternalBackgroundClose(); 216 void InternalBackgroundClose();
223 217
224 void DeleteSessionCookiesOnStartup(); 218 void DeleteSessionCookiesOnStartup();
225 219
226 void DeleteSessionCookiesOnShutdown(); 220 void BackgroundDeleteAllInList(const std::list<CookieOrigin>& cookies);
227 221
228 void DatabaseErrorCallback(int error, sql::Statement* stmt); 222 void DatabaseErrorCallback(int error, sql::Statement* stmt);
229 void KillDatabase(); 223 void KillDatabase();
230 224
231 void PostBackgroundTask(const tracked_objects::Location& origin, 225 void PostBackgroundTask(const tracked_objects::Location& origin,
232 const base::Closure& task); 226 const base::Closure& task);
233 void PostClientTask(const tracked_objects::Location& origin, 227 void PostClientTask(const tracked_objects::Location& origin,
234 const base::Closure& task); 228 const base::Closure& task);
235 229
236 // Shared code between the different load strategies to be used after all 230 // Shared code between the different load strategies to be used after all
237 // cookies have been loaded. 231 // cookies have been loaded.
238 void FinishedLoadingCookies(const LoadedCallback& loaded_callback, 232 void FinishedLoadingCookies(const LoadedCallback& loaded_callback,
239 bool success); 233 bool success);
240 234
241 base::FilePath path_; 235 const base::FilePath path_;
242 scoped_ptr<sql::Connection> db_; 236 scoped_ptr<sql::Connection> db_;
243 sql::MetaTable meta_table_; 237 sql::MetaTable meta_table_;
244 238
245 typedef std::list<PendingOperation*> PendingOperationsList; 239 typedef std::list<PendingOperation*> PendingOperationsList;
246 PendingOperationsList pending_; 240 PendingOperationsList pending_;
247 PendingOperationsList::size_type num_pending_; 241 PendingOperationsList::size_type num_pending_;
248 // True if the persistent store should skip delete on exit rules. 242 // Guard |cookies_|, |pending_|, |num_pending_|.
249 bool force_keep_session_state_;
250 // Guard |cookies_|, |pending_|, |num_pending_|, |force_keep_session_state_|
251 base::Lock lock_; 243 base::Lock lock_;
252 244
253 // Temporary buffer for cookies loaded from DB. Accumulates cookies to reduce 245 // Temporary buffer for cookies loaded from DB. Accumulates cookies to reduce
254 // the number of messages sent to the client runner. Sent back in response to 246 // the number of messages sent to the client runner. Sent back in response to
255 // individual load requests for domain keys or when all loading completes. 247 // individual load requests for domain keys or when all loading completes.
256 // Ownership of the cookies in this vector is transferred to the client in 248 // Ownership of the cookies in this vector is transferred to the client in
257 // response to individual load requests or when all loading completes. 249 // response to individual load requests or when all loading completes.
258 std::vector<net::CanonicalCookie*> cookies_; 250 std::vector<CanonicalCookie*> cookies_;
259 251
260 // Map of domain keys(eTLD+1) to domains/hosts that are to be loaded from DB. 252 // Map of domain keys(eTLD+1) to domains/hosts that are to be loaded from DB.
261 std::map<std::string, std::set<std::string> > keys_to_load_; 253 std::map<std::string, std::set<std::string> > keys_to_load_;
262 254
263 // Map of (domain keys(eTLD+1), is secure cookie) to number of cookies in the
264 // database.
265 typedef std::pair<std::string, bool> CookieOrigin;
266 typedef std::map<CookieOrigin, int> CookiesPerOriginMap;
267 CookiesPerOriginMap cookies_per_origin_;
268
269 // Indicates if DB has been initialized. 255 // Indicates if DB has been initialized.
270 bool initialized_; 256 bool initialized_;
271 257
272 // Indicates if the kill-database callback has been scheduled. 258 // Indicates if the kill-database callback has been scheduled.
273 bool corruption_detected_; 259 bool corruption_detected_;
274 260
275 // If false, we should filter out session cookies when reading the DB. 261 // If false, we should filter out session cookies when reading the DB.
276 bool restore_old_session_cookies_; 262 bool restore_old_session_cookies_;
277 263
278 // Policy defining what data is deleted on shutdown.
279 scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy_;
280
281 // The cumulative time spent loading the cookies on the background runner. 264 // The cumulative time spent loading the cookies on the background runner.
282 // Incremented and reported from the background runner. 265 // Incremented and reported from the background runner.
283 base::TimeDelta cookie_load_duration_; 266 base::TimeDelta cookie_load_duration_;
284 267
285 // The total number of cookies read. Incremented and reported on the 268 // The total number of cookies read. Incremented and reported on the
286 // background runner. 269 // background runner.
287 int num_cookies_read_; 270 int num_cookies_read_;
288 271
289 scoped_refptr<base::SequencedTaskRunner> client_task_runner_; 272 scoped_refptr<base::SequencedTaskRunner> client_task_runner_;
290 scoped_refptr<base::SequencedTaskRunner> background_task_runner_; 273 scoped_refptr<base::SequencedTaskRunner> background_task_runner_;
291 274
292 // Guards the following metrics-related properties (only accessed when 275 // Guards the following metrics-related properties (only accessed when
293 // starting/completing priority loads or completing the total load). 276 // starting/completing priority loads or completing the total load).
294 base::Lock metrics_lock_; 277 base::Lock metrics_lock_;
295 int num_priority_waiting_; 278 int num_priority_waiting_;
296 // The total number of priority requests. 279 // The total number of priority requests.
297 int total_priority_requests_; 280 int total_priority_requests_;
298 // The time when |num_priority_waiting_| incremented to 1. 281 // The time when |num_priority_waiting_| incremented to 1.
299 base::Time current_priority_wait_start_; 282 base::Time current_priority_wait_start_;
300 // The cumulative duration of time when |num_priority_waiting_| was greater 283 // The cumulative duration of time when |num_priority_waiting_| was greater
301 // than 1. 284 // than 1.
302 base::TimeDelta priority_wait_duration_; 285 base::TimeDelta priority_wait_duration_;
303 // Class with functions that do cryptographic operations (for protecting 286 // Class with functions that do cryptographic operations (for protecting
304 // cookies stored persistently). 287 // cookies stored persistently).
305 // 288 //
306 // Not owned. 289 // Not owned.
307 net::CookieCryptoDelegate* crypto_; 290 CookieCryptoDelegate* crypto_;
308 291
309 DISALLOW_COPY_AND_ASSIGN(Backend); 292 DISALLOW_COPY_AND_ASSIGN(Backend);
310 }; 293 };
311 294
312 namespace { 295 namespace {
313 296
314 // Version number of the database. 297 // Version number of the database.
315 // 298 //
316 // Version 9 adds a partial index to track non-persistent cookies. 299 // Version 9 adds a partial index to track non-persistent cookies.
317 // Non-persistent cookies sometimes need to be deleted on startup. There are 300 // Non-persistent cookies sometimes need to be deleted on startup. There are
(...skipping 28 matching lines...) Expand all
346 const int kCurrentVersionNumber = 9; 329 const int kCurrentVersionNumber = 9;
347 const int kCompatibleVersionNumber = 5; 330 const int kCompatibleVersionNumber = 5;
348 331
349 // Possible values for the 'priority' column. 332 // Possible values for the 'priority' column.
350 enum DBCookiePriority { 333 enum DBCookiePriority {
351 kCookiePriorityLow = 0, 334 kCookiePriorityLow = 0,
352 kCookiePriorityMedium = 1, 335 kCookiePriorityMedium = 1,
353 kCookiePriorityHigh = 2, 336 kCookiePriorityHigh = 2,
354 }; 337 };
355 338
356 DBCookiePriority CookiePriorityToDBCookiePriority(net::CookiePriority value) { 339 DBCookiePriority CookiePriorityToDBCookiePriority(CookiePriority value) {
357 switch (value) { 340 switch (value) {
358 case net::COOKIE_PRIORITY_LOW: 341 case COOKIE_PRIORITY_LOW:
359 return kCookiePriorityLow; 342 return kCookiePriorityLow;
360 case net::COOKIE_PRIORITY_MEDIUM: 343 case COOKIE_PRIORITY_MEDIUM:
361 return kCookiePriorityMedium; 344 return kCookiePriorityMedium;
362 case net::COOKIE_PRIORITY_HIGH: 345 case COOKIE_PRIORITY_HIGH:
363 return kCookiePriorityHigh; 346 return kCookiePriorityHigh;
364 } 347 }
365 348
366 NOTREACHED(); 349 NOTREACHED();
367 return kCookiePriorityMedium; 350 return kCookiePriorityMedium;
368 } 351 }
369 352
370 net::CookiePriority DBCookiePriorityToCookiePriority(DBCookiePriority value) { 353 CookiePriority DBCookiePriorityToCookiePriority(DBCookiePriority value) {
371 switch (value) { 354 switch (value) {
372 case kCookiePriorityLow: 355 case kCookiePriorityLow:
373 return net::COOKIE_PRIORITY_LOW; 356 return COOKIE_PRIORITY_LOW;
374 case kCookiePriorityMedium: 357 case kCookiePriorityMedium:
375 return net::COOKIE_PRIORITY_MEDIUM; 358 return COOKIE_PRIORITY_MEDIUM;
376 case kCookiePriorityHigh: 359 case kCookiePriorityHigh:
377 return net::COOKIE_PRIORITY_HIGH; 360 return COOKIE_PRIORITY_HIGH;
378 } 361 }
379 362
380 NOTREACHED(); 363 NOTREACHED();
381 return net::COOKIE_PRIORITY_DEFAULT; 364 return COOKIE_PRIORITY_DEFAULT;
382 } 365 }
383 366
384 // Increments a specified TimeDelta by the duration between this object's 367 // Increments a specified TimeDelta by the duration between this object's
385 // constructor and destructor. Not thread safe. Multiple instances may be 368 // constructor and destructor. Not thread safe. Multiple instances may be
386 // created with the same delta instance as long as their lifetimes are nested. 369 // created with the same delta instance as long as their lifetimes are nested.
387 // The shortest lived instances have no impact. 370 // The shortest lived instances have no impact.
388 class IncrementTimeDelta { 371 class IncrementTimeDelta {
389 public: 372 public:
390 explicit IncrementTimeDelta(base::TimeDelta* delta) : 373 explicit IncrementTimeDelta(base::TimeDelta* delta) :
391 delta_(delta), 374 delta_(delta),
(...skipping 26 matching lines...) Expand all
418 "path TEXT NOT NULL," 401 "path TEXT NOT NULL,"
419 "expires_utc INTEGER NOT NULL," 402 "expires_utc INTEGER NOT NULL,"
420 "secure INTEGER NOT NULL," 403 "secure INTEGER NOT NULL,"
421 "httponly INTEGER NOT NULL," 404 "httponly INTEGER NOT NULL,"
422 "last_access_utc INTEGER NOT NULL, " 405 "last_access_utc INTEGER NOT NULL, "
423 "has_expires INTEGER NOT NULL DEFAULT 1, " 406 "has_expires INTEGER NOT NULL DEFAULT 1, "
424 "persistent INTEGER NOT NULL DEFAULT 1," 407 "persistent INTEGER NOT NULL DEFAULT 1,"
425 "priority INTEGER NOT NULL DEFAULT %d," 408 "priority INTEGER NOT NULL DEFAULT %d,"
426 "encrypted_value BLOB DEFAULT ''," 409 "encrypted_value BLOB DEFAULT '',"
427 "firstpartyonly INTEGER NOT NULL DEFAULT 0)", 410 "firstpartyonly INTEGER NOT NULL DEFAULT 0)",
428 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT))); 411 CookiePriorityToDBCookiePriority(COOKIE_PRIORITY_DEFAULT)));
429 if (!db->Execute(stmt.c_str())) 412 if (!db->Execute(stmt.c_str()))
430 return false; 413 return false;
431 414
432 if (!db->Execute("CREATE INDEX domain ON cookies(host_key)")) 415 if (!db->Execute("CREATE INDEX domain ON cookies(host_key)"))
433 return false; 416 return false;
434 417
435 #if defined(OS_IOS) 418 #if defined(OS_IOS)
436 // iOS 8.1 and older doesn't support partial indices. iOS 8.2 supports 419 // iOS 8.1 and older doesn't support partial indices. iOS 8.2 supports
437 // partial indices. 420 // partial indices.
438 if (!db->Execute("CREATE INDEX is_transient ON cookies(persistent)")) { 421 if (!db->Execute("CREATE INDEX is_transient ON cookies(persistent)")) {
(...skipping 145 matching lines...) Expand 10 before | Expand all | Expand 10 after
584 567
585 if (load_success) 568 if (load_success)
586 ReportMetrics(); 569 ReportMetrics();
587 } 570 }
588 571
589 void SQLitePersistentCookieStore::Backend::Notify( 572 void SQLitePersistentCookieStore::Backend::Notify(
590 const LoadedCallback& loaded_callback, 573 const LoadedCallback& loaded_callback,
591 bool load_success) { 574 bool load_success) {
592 DCHECK(client_task_runner_->RunsTasksOnCurrentThread()); 575 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
593 576
594 std::vector<net::CanonicalCookie*> cookies; 577 std::vector<CanonicalCookie*> cookies;
595 { 578 {
596 base::AutoLock locked(lock_); 579 base::AutoLock locked(lock_);
597 cookies.swap(cookies_); 580 cookies.swap(cookies_);
598 } 581 }
599 582
600 loaded_callback.Run(cookies); 583 loaded_callback.Run(cookies);
601 } 584 }
602 585
603 bool SQLitePersistentCookieStore::Backend::InitializeDatabase() { 586 bool SQLitePersistentCookieStore::Backend::InitializeDatabase() {
604 DCHECK(background_task_runner_->RunsTasksOnCurrentThread()); 587 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
(...skipping 70 matching lines...) Expand 10 before | Expand all | Expand 10 after
675 base::Time::Now() - start, 658 base::Time::Now() - start,
676 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1), 659 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
677 50); 660 50);
678 661
679 base::Time start_parse = base::Time::Now(); 662 base::Time start_parse = base::Time::Now();
680 663
681 // Build a map of domain keys (always eTLD+1) to domains. 664 // Build a map of domain keys (always eTLD+1) to domains.
682 for (size_t idx = 0; idx < host_keys.size(); ++idx) { 665 for (size_t idx = 0; idx < host_keys.size(); ++idx) {
683 const std::string& domain = host_keys[idx]; 666 const std::string& domain = host_keys[idx];
684 std::string key = 667 std::string key =
685 net::registry_controlled_domains::GetDomainAndRegistry( 668 registry_controlled_domains::GetDomainAndRegistry(
686 domain, 669 domain,
687 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); 670 registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
688 671
689 keys_to_load_[key].insert(domain); 672 keys_to_load_[key].insert(domain);
690 } 673 }
691 674
692 UMA_HISTOGRAM_CUSTOM_TIMES( 675 UMA_HISTOGRAM_CUSTOM_TIMES(
693 "Cookie.TimeParseDomains", 676 "Cookie.TimeParseDomains",
694 base::Time::Now() - start_parse, 677 base::Time::Now() - start_parse,
695 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1), 678 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
696 50); 679 50);
697 680
(...skipping 64 matching lines...) Expand 10 before | Expand all | Expand 10 after
762 "has_expires, persistent, priority FROM cookies WHERE host_key = ? " 745 "has_expires, persistent, priority FROM cookies WHERE host_key = ? "
763 "AND persistent = 1")); 746 "AND persistent = 1"));
764 } 747 }
765 if (!smt.is_valid()) { 748 if (!smt.is_valid()) {
766 smt.Clear(); // Disconnect smt_ref from db_. 749 smt.Clear(); // Disconnect smt_ref from db_.
767 meta_table_.Reset(); 750 meta_table_.Reset();
768 db_.reset(); 751 db_.reset();
769 return false; 752 return false;
770 } 753 }
771 754
772 std::vector<net::CanonicalCookie*> cookies; 755 std::vector<CanonicalCookie*> cookies;
773 std::set<std::string>::const_iterator it = domains.begin(); 756 std::set<std::string>::const_iterator it = domains.begin();
774 for (; it != domains.end(); ++it) { 757 for (; it != domains.end(); ++it) {
775 smt.BindString(0, *it); 758 smt.BindString(0, *it);
776 MakeCookiesFromSQLStatement(&cookies, &smt); 759 MakeCookiesFromSQLStatement(&cookies, &smt);
777 smt.Reset(true); 760 smt.Reset(true);
778 } 761 }
779 { 762 {
780 base::AutoLock locked(lock_); 763 base::AutoLock locked(lock_);
781 cookies_.insert(cookies_.end(), cookies.begin(), cookies.end()); 764 cookies_.insert(cookies_.end(), cookies.begin(), cookies.end());
782 } 765 }
783 return true; 766 return true;
784 } 767 }
785 768
786 void SQLitePersistentCookieStore::Backend::MakeCookiesFromSQLStatement( 769 void SQLitePersistentCookieStore::Backend::MakeCookiesFromSQLStatement(
787 std::vector<net::CanonicalCookie*>* cookies, 770 std::vector<CanonicalCookie*>* cookies,
788 sql::Statement* statement) { 771 sql::Statement* statement) {
789 sql::Statement& smt = *statement; 772 sql::Statement& smt = *statement;
790 while (smt.Step()) { 773 while (smt.Step()) {
791 std::string value; 774 std::string value;
792 std::string encrypted_value = smt.ColumnString(4); 775 std::string encrypted_value = smt.ColumnString(4);
793 if (!encrypted_value.empty() && crypto_) { 776 if (!encrypted_value.empty() && crypto_) {
794 crypto_->DecryptString(encrypted_value, &value); 777 crypto_->DecryptString(encrypted_value, &value);
795 } else { 778 } else {
796 DCHECK(encrypted_value.empty()); 779 DCHECK(encrypted_value.empty());
797 value = smt.ColumnString(3); 780 value = smt.ColumnString(3);
798 } 781 }
799 scoped_ptr<net::CanonicalCookie> cc(new net::CanonicalCookie( 782 scoped_ptr<CanonicalCookie> cc(new CanonicalCookie(
800 // The "source" URL is not used with persisted cookies. 783 // The "source" URL is not used with persisted cookies.
801 GURL(), // Source 784 GURL(), // Source
802 smt.ColumnString(2), // name 785 smt.ColumnString(2), // name
803 value, // value 786 value, // value
804 smt.ColumnString(1), // domain 787 smt.ColumnString(1), // domain
805 smt.ColumnString(5), // path 788 smt.ColumnString(5), // path
806 Time::FromInternalValue(smt.ColumnInt64(0)), // creation_utc 789 Time::FromInternalValue(smt.ColumnInt64(0)), // creation_utc
807 Time::FromInternalValue(smt.ColumnInt64(6)), // expires_utc 790 Time::FromInternalValue(smt.ColumnInt64(6)), // expires_utc
808 Time::FromInternalValue(smt.ColumnInt64(10)), // last_access_utc 791 Time::FromInternalValue(smt.ColumnInt64(10)), // last_access_utc
809 smt.ColumnInt(7) != 0, // secure 792 smt.ColumnInt(7) != 0, // secure
810 smt.ColumnInt(8) != 0, // httponly 793 smt.ColumnInt(8) != 0, // httponly
811 smt.ColumnInt(9) != 0, // firstpartyonly 794 smt.ColumnInt(9) != 0, // firstpartyonly
812 DBCookiePriorityToCookiePriority( 795 DBCookiePriorityToCookiePriority(
813 static_cast<DBCookiePriority>(smt.ColumnInt(13))))); // priority 796 static_cast<DBCookiePriority>(smt.ColumnInt(13))))); // priority
814 DLOG_IF(WARNING, cc->CreationDate() > Time::Now()) 797 DLOG_IF(WARNING, cc->CreationDate() > Time::Now())
815 << L"CreationDate too recent"; 798 << L"CreationDate too recent";
816 cookies_per_origin_[CookieOrigin(cc->Domain(), cc->IsSecure())]++;
817 cookies->push_back(cc.release()); 799 cookies->push_back(cc.release());
818 ++num_cookies_read_; 800 ++num_cookies_read_;
819 } 801 }
820 } 802 }
821 803
822 bool SQLitePersistentCookieStore::Backend::EnsureDatabaseVersion() { 804 bool SQLitePersistentCookieStore::Backend::EnsureDatabaseVersion() {
823 // Version check. 805 // Version check.
824 if (!meta_table_.Init( 806 if (!meta_table_.Init(
825 db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) { 807 db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) {
826 return false; 808 return false;
(...skipping 78 matching lines...) Expand 10 before | Expand all | Expand 10 after
905 } 887 }
906 888
907 if (cur_version == 5) { 889 if (cur_version == 5) {
908 const base::TimeTicks start_time = base::TimeTicks::Now(); 890 const base::TimeTicks start_time = base::TimeTicks::Now();
909 sql::Transaction transaction(db_.get()); 891 sql::Transaction transaction(db_.get());
910 if (!transaction.Begin()) 892 if (!transaction.Begin())
911 return false; 893 return false;
912 // Alter the table to add the priority column with a default value. 894 // Alter the table to add the priority column with a default value.
913 std::string stmt(base::StringPrintf( 895 std::string stmt(base::StringPrintf(
914 "ALTER TABLE cookies ADD COLUMN priority INTEGER DEFAULT %d", 896 "ALTER TABLE cookies ADD COLUMN priority INTEGER DEFAULT %d",
915 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT))); 897 CookiePriorityToDBCookiePriority(COOKIE_PRIORITY_DEFAULT)));
916 if (!db_->Execute(stmt.c_str())) { 898 if (!db_->Execute(stmt.c_str())) {
917 LOG(WARNING) << "Unable to update cookie database to version 6."; 899 LOG(WARNING) << "Unable to update cookie database to version 6.";
918 return false; 900 return false;
919 } 901 }
920 ++cur_version; 902 ++cur_version;
921 meta_table_.SetVersionNumber(cur_version); 903 meta_table_.SetVersionNumber(cur_version);
922 meta_table_.SetCompatibleVersionNumber( 904 meta_table_.SetCompatibleVersionNumber(
923 std::min(cur_version, kCompatibleVersionNumber)); 905 std::min(cur_version, kCompatibleVersionNumber));
924 transaction.Commit(); 906 transaction.Commit();
925 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV6", 907 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV6",
(...skipping 98 matching lines...) Expand 10 before | Expand all | Expand 10 after
1024 meta_table_.Reset(); 1006 meta_table_.Reset();
1025 db_.reset(); 1007 db_.reset();
1026 return false; 1008 return false;
1027 } 1009 }
1028 } 1010 }
1029 1011
1030 return true; 1012 return true;
1031 } 1013 }
1032 1014
1033 void SQLitePersistentCookieStore::Backend::AddCookie( 1015 void SQLitePersistentCookieStore::Backend::AddCookie(
1034 const net::CanonicalCookie& cc) { 1016 const CanonicalCookie& cc) {
1035 BatchOperation(PendingOperation::COOKIE_ADD, cc); 1017 BatchOperation(PendingOperation::COOKIE_ADD, cc);
1036 } 1018 }
1037 1019
1038 void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime( 1020 void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime(
1039 const net::CanonicalCookie& cc) { 1021 const CanonicalCookie& cc) {
1040 BatchOperation(PendingOperation::COOKIE_UPDATEACCESS, cc); 1022 BatchOperation(PendingOperation::COOKIE_UPDATEACCESS, cc);
1041 } 1023 }
1042 1024
1043 void SQLitePersistentCookieStore::Backend::DeleteCookie( 1025 void SQLitePersistentCookieStore::Backend::DeleteCookie(
1044 const net::CanonicalCookie& cc) { 1026 const CanonicalCookie& cc) {
1045 BatchOperation(PendingOperation::COOKIE_DELETE, cc); 1027 BatchOperation(PendingOperation::COOKIE_DELETE, cc);
1046 } 1028 }
1047 1029
1048 void SQLitePersistentCookieStore::Backend::BatchOperation( 1030 void SQLitePersistentCookieStore::Backend::BatchOperation(
1049 PendingOperation::OperationType op, 1031 PendingOperation::OperationType op,
1050 const net::CanonicalCookie& cc) { 1032 const CanonicalCookie& cc) {
1051 // Commit every 30 seconds. 1033 // Commit every 30 seconds.
1052 static const int kCommitIntervalMs = 30 * 1000; 1034 static const int kCommitIntervalMs = 30 * 1000;
1053 // Commit right away if we have more than 512 outstanding operations. 1035 // Commit right away if we have more than 512 outstanding operations.
1054 static const size_t kCommitAfterBatchSize = 512; 1036 static const size_t kCommitAfterBatchSize = 512;
1055 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread()); 1037 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
1056 1038
1057 // We do a full copy of the cookie here, and hopefully just here. 1039 // We do a full copy of the cookie here, and hopefully just here.
1058 scoped_ptr<PendingOperation> po(new PendingOperation(op, cc)); 1040 scoped_ptr<PendingOperation> po(new PendingOperation(op, cc));
1059 1041
1060 PendingOperationsList::size_type num_pending; 1042 PendingOperationsList::size_type num_pending;
(...skipping 52 matching lines...) Expand 10 before | Expand all | Expand 10 after
1113 sql::Transaction transaction(db_.get()); 1095 sql::Transaction transaction(db_.get());
1114 if (!transaction.Begin()) 1096 if (!transaction.Begin())
1115 return; 1097 return;
1116 1098
1117 for (PendingOperationsList::iterator it = ops.begin(); 1099 for (PendingOperationsList::iterator it = ops.begin();
1118 it != ops.end(); ++it) { 1100 it != ops.end(); ++it) {
1119 // Free the cookies as we commit them to the database. 1101 // Free the cookies as we commit them to the database.
1120 scoped_ptr<PendingOperation> po(*it); 1102 scoped_ptr<PendingOperation> po(*it);
1121 switch (po->op()) { 1103 switch (po->op()) {
1122 case PendingOperation::COOKIE_ADD: 1104 case PendingOperation::COOKIE_ADD:
1123 cookies_per_origin_[
1124 CookieOrigin(po->cc().Domain(), po->cc().IsSecure())]++;
1125 add_smt.Reset(true); 1105 add_smt.Reset(true);
1126 add_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue()); 1106 add_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1127 add_smt.BindString(1, po->cc().Domain()); 1107 add_smt.BindString(1, po->cc().Domain());
1128 add_smt.BindString(2, po->cc().Name()); 1108 add_smt.BindString(2, po->cc().Name());
1129 if (crypto_) { 1109 if (crypto_) {
1130 std::string encrypted_value; 1110 std::string encrypted_value;
1131 add_smt.BindCString(3, ""); // value 1111 add_smt.BindCString(3, ""); // value
1132 crypto_->EncryptString(po->cc().Value(), &encrypted_value); 1112 crypto_->EncryptString(po->cc().Value(), &encrypted_value);
1133 // BindBlob() immediately makes an internal copy of the data. 1113 // BindBlob() immediately makes an internal copy of the data.
1134 add_smt.BindBlob(4, encrypted_value.data(), 1114 add_smt.BindBlob(4, encrypted_value.data(),
(...skipping 20 matching lines...) Expand all
1155 update_access_smt.Reset(true); 1135 update_access_smt.Reset(true);
1156 update_access_smt.BindInt64(0, 1136 update_access_smt.BindInt64(0,
1157 po->cc().LastAccessDate().ToInternalValue()); 1137 po->cc().LastAccessDate().ToInternalValue());
1158 update_access_smt.BindInt64(1, 1138 update_access_smt.BindInt64(1,
1159 po->cc().CreationDate().ToInternalValue()); 1139 po->cc().CreationDate().ToInternalValue());
1160 if (!update_access_smt.Run()) 1140 if (!update_access_smt.Run())
1161 NOTREACHED() << "Could not update cookie last access time in the DB."; 1141 NOTREACHED() << "Could not update cookie last access time in the DB.";
1162 break; 1142 break;
1163 1143
1164 case PendingOperation::COOKIE_DELETE: 1144 case PendingOperation::COOKIE_DELETE:
1165 cookies_per_origin_[
1166 CookieOrigin(po->cc().Domain(), po->cc().IsSecure())]--;
1167 del_smt.Reset(true); 1145 del_smt.Reset(true);
1168 del_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue()); 1146 del_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1169 if (!del_smt.Run()) 1147 if (!del_smt.Run())
1170 NOTREACHED() << "Could not delete a cookie from the DB."; 1148 NOTREACHED() << "Could not delete a cookie from the DB.";
1171 break; 1149 break;
1172 1150
1173 default: 1151 default:
1174 NOTREACHED(); 1152 NOTREACHED();
1175 break; 1153 break;
1176 } 1154 }
(...skipping 27 matching lines...) Expand all
1204 PostBackgroundTask(FROM_HERE, 1182 PostBackgroundTask(FROM_HERE,
1205 base::Bind(&Backend::InternalBackgroundClose, this)); 1183 base::Bind(&Backend::InternalBackgroundClose, this));
1206 } 1184 }
1207 } 1185 }
1208 1186
1209 void SQLitePersistentCookieStore::Backend::InternalBackgroundClose() { 1187 void SQLitePersistentCookieStore::Backend::InternalBackgroundClose() {
1210 DCHECK(background_task_runner_->RunsTasksOnCurrentThread()); 1188 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1211 // Commit any pending operations 1189 // Commit any pending operations
1212 Commit(); 1190 Commit();
1213 1191
1214 if (!force_keep_session_state_ && special_storage_policy_.get() &&
1215 special_storage_policy_->HasSessionOnlyOrigins()) {
1216 DeleteSessionCookiesOnShutdown();
1217 }
1218
1219 meta_table_.Reset(); 1192 meta_table_.Reset();
1220 db_.reset(); 1193 db_.reset();
1221 } 1194 }
1222 1195
1223 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnShutdown() {
1224 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1225
1226 if (!db_)
1227 return;
1228
1229 if (!special_storage_policy_.get())
1230 return;
1231
1232 sql::Statement del_smt(db_->GetCachedStatement(
1233 SQL_FROM_HERE, "DELETE FROM cookies WHERE host_key=? AND secure=?"));
1234 if (!del_smt.is_valid()) {
1235 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1236 return;
1237 }
1238
1239 sql::Transaction transaction(db_.get());
1240 if (!transaction.Begin()) {
1241 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1242 return;
1243 }
1244
1245 for (CookiesPerOriginMap::iterator it = cookies_per_origin_.begin();
1246 it != cookies_per_origin_.end(); ++it) {
1247 if (it->second <= 0) {
1248 DCHECK_EQ(0, it->second);
1249 continue;
1250 }
1251 const GURL url(net::cookie_util::CookieOriginToURL(it->first.first,
1252 it->first.second));
1253 if (!url.is_valid() || !special_storage_policy_->IsStorageSessionOnly(url))
1254 continue;
1255
1256 del_smt.Reset(true);
1257 del_smt.BindString(0, it->first.first);
1258 del_smt.BindInt(1, it->first.second);
1259 if (!del_smt.Run())
1260 NOTREACHED() << "Could not delete a cookie from the DB.";
1261 }
1262
1263 if (!transaction.Commit())
1264 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1265 }
1266
1267 void SQLitePersistentCookieStore::Backend::DatabaseErrorCallback( 1196 void SQLitePersistentCookieStore::Backend::DatabaseErrorCallback(
1268 int error, 1197 int error,
1269 sql::Statement* stmt) { 1198 sql::Statement* stmt) {
1270 DCHECK(background_task_runner_->RunsTasksOnCurrentThread()); 1199 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1271 1200
1272 if (!sql::IsErrorCatastrophic(error)) 1201 if (!sql::IsErrorCatastrophic(error))
1273 return; 1202 return;
1274 1203
1275 // TODO(shess): Running KillDatabase() multiple times should be 1204 // TODO(shess): Running KillDatabase() multiple times should be
1276 // safe. 1205 // safe.
(...skipping 16 matching lines...) Expand all
1293 if (db_) { 1222 if (db_) {
1294 // This Backend will now be in-memory only. In a future run we will recreate 1223 // This Backend will now be in-memory only. In a future run we will recreate
1295 // the database. Hopefully things go better then! 1224 // the database. Hopefully things go better then!
1296 bool success = db_->RazeAndClose(); 1225 bool success = db_->RazeAndClose();
1297 UMA_HISTOGRAM_BOOLEAN("Cookie.KillDatabaseResult", success); 1226 UMA_HISTOGRAM_BOOLEAN("Cookie.KillDatabaseResult", success);
1298 meta_table_.Reset(); 1227 meta_table_.Reset();
1299 db_.reset(); 1228 db_.reset();
1300 } 1229 }
1301 } 1230 }
1302 1231
1303 void SQLitePersistentCookieStore::Backend::SetForceKeepSessionState() { 1232 void SQLitePersistentCookieStore::Backend::DeleteAllInList(
1304 base::AutoLock locked(lock_); 1233 const std::list<CookieOrigin>& cookies) {
1305 force_keep_session_state_ = true; 1234 if (cookies.empty())
1235 return;
1236
1237 // Perform deletion on background task runner.
1238 background_task_runner_->PostTask(
1239 FROM_HERE,
1240 base::Bind(
1241 &Backend::BackgroundDeleteAllInList, this, cookies));
1306 } 1242 }
1307 1243
1308 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup() { 1244 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup() {
1309 DCHECK(background_task_runner_->RunsTasksOnCurrentThread()); 1245 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1310 if (!db_->Execute("DELETE FROM cookies WHERE persistent != 1")) 1246 if (!db_->Execute("DELETE FROM cookies WHERE persistent != 1"))
1311 LOG(WARNING) << "Unable to delete session cookies."; 1247 LOG(WARNING) << "Unable to delete session cookies.";
1312 } 1248 }
1313 1249
1250 void SQLitePersistentCookieStore::Backend::BackgroundDeleteAllInList(
1251 const std::list<CookieOrigin>& cookies) {
1252 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1253
1254 if (!db_)
1255 return;
1256
1257 // Force a commit of any pending writes before issuing deletes.
1258 // TODO(rohitrao): Remove the need for this Commit() by instead pruning the
1259 // list of pending operations.
Ryan Sleevi 2015/05/06 00:44:18 Bug to track this follow-up work so I can incessan
rohitrao (ping after 24h) 2015/05/11 19:25:30 Drat, you've found my secret plan to never fix it.
1260 Commit();
1261
1262 sql::Statement del_smt(db_->GetCachedStatement(
1263 SQL_FROM_HERE, "DELETE FROM cookies WHERE host_key=? AND secure=?"));
1264 if (!del_smt.is_valid()) {
1265 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1266 return;
1267 }
1268
1269 sql::Transaction transaction(db_.get());
1270 if (!transaction.Begin()) {
1271 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1272 return;
1273 }
1274
1275 for (auto it = cookies.begin(); it != cookies.end(); ++it) {
Ryan Sleevi 2015/05/06 00:44:18 for (const auto& cookie : cookies) { }
rohitrao (ping after 24h) 2015/05/11 19:25:30 Done.
1276 const GURL url(cookie_util::CookieOriginToURL(it->first, it->second));
1277 if (!url.is_valid())
1278 continue;
1279
1280 del_smt.Reset(true);
1281 del_smt.BindString(0, it->first);
1282 del_smt.BindInt(1, it->second);
1283 if (!del_smt.Run())
1284 NOTREACHED() << "Could not delete a cookie from the DB.";
1285 }
1286
1287 if (!transaction.Commit())
1288 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1289 }
1290
1314 void SQLitePersistentCookieStore::Backend::PostBackgroundTask( 1291 void SQLitePersistentCookieStore::Backend::PostBackgroundTask(
1315 const tracked_objects::Location& origin, const base::Closure& task) { 1292 const tracked_objects::Location& origin, const base::Closure& task) {
1316 if (!background_task_runner_->PostTask(origin, task)) { 1293 if (!background_task_runner_->PostTask(origin, task)) {
1317 LOG(WARNING) << "Failed to post task from " << origin.ToString() 1294 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1318 << " to background_task_runner_."; 1295 << " to background_task_runner_.";
1319 } 1296 }
1320 } 1297 }
1321 1298
1322 void SQLitePersistentCookieStore::Backend::PostClientTask( 1299 void SQLitePersistentCookieStore::Backend::PostClientTask(
1323 const tracked_objects::Location& origin, const base::Closure& task) { 1300 const tracked_objects::Location& origin, const base::Closure& task) {
1324 if (!client_task_runner_->PostTask(origin, task)) { 1301 if (!client_task_runner_->PostTask(origin, task)) {
1325 LOG(WARNING) << "Failed to post task from " << origin.ToString() 1302 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1326 << " to client_task_runner_."; 1303 << " to client_task_runner_.";
1327 } 1304 }
1328 } 1305 }
1329 1306
1330 void SQLitePersistentCookieStore::Backend::FinishedLoadingCookies( 1307 void SQLitePersistentCookieStore::Backend::FinishedLoadingCookies(
1331 const LoadedCallback& loaded_callback, 1308 const LoadedCallback& loaded_callback,
1332 bool success) { 1309 bool success) {
1333 PostClientTask(FROM_HERE, base::Bind(&Backend::CompleteLoadInForeground, this, 1310 PostClientTask(FROM_HERE, base::Bind(&Backend::CompleteLoadInForeground, this,
1334 loaded_callback, success)); 1311 loaded_callback, success));
1335 } 1312 }
1336 1313
1337 SQLitePersistentCookieStore::SQLitePersistentCookieStore( 1314 SQLitePersistentCookieStore::SQLitePersistentCookieStore(
1338 const base::FilePath& path, 1315 const base::FilePath& path,
1339 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner, 1316 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
1340 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner, 1317 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
1341 bool restore_old_session_cookies, 1318 bool restore_old_session_cookies,
1342 storage::SpecialStoragePolicy* special_storage_policy, 1319 CookieCryptoDelegate* crypto_delegate)
1343 net::CookieCryptoDelegate* crypto_delegate)
1344 : backend_(new Backend(path, 1320 : backend_(new Backend(path,
1345 client_task_runner, 1321 client_task_runner,
1346 background_task_runner, 1322 background_task_runner,
1347 restore_old_session_cookies, 1323 restore_old_session_cookies,
1348 special_storage_policy,
1349 crypto_delegate)) { 1324 crypto_delegate)) {
1350 } 1325 }
1351 1326
1327 void SQLitePersistentCookieStore::DeleteAllInList(
1328 const std::list<CookieOrigin>& cookies) {
1329 backend_->DeleteAllInList(cookies);
1330 }
1331
1352 void SQLitePersistentCookieStore::Load(const LoadedCallback& loaded_callback) { 1332 void SQLitePersistentCookieStore::Load(const LoadedCallback& loaded_callback) {
1353 backend_->Load(loaded_callback); 1333 backend_->Load(loaded_callback);
1354 } 1334 }
1355 1335
1356 void SQLitePersistentCookieStore::LoadCookiesForKey( 1336 void SQLitePersistentCookieStore::LoadCookiesForKey(
1357 const std::string& key, 1337 const std::string& key,
1358 const LoadedCallback& loaded_callback) { 1338 const LoadedCallback& loaded_callback) {
1359 backend_->LoadCookiesForKey(key, loaded_callback); 1339 backend_->LoadCookiesForKey(key, loaded_callback);
1360 } 1340 }
1361 1341
1362 void SQLitePersistentCookieStore::AddCookie(const net::CanonicalCookie& cc) { 1342 void SQLitePersistentCookieStore::AddCookie(const CanonicalCookie& cc) {
1363 backend_->AddCookie(cc); 1343 backend_->AddCookie(cc);
1364 } 1344 }
1365 1345
1366 void SQLitePersistentCookieStore::UpdateCookieAccessTime( 1346 void SQLitePersistentCookieStore::UpdateCookieAccessTime(
1367 const net::CanonicalCookie& cc) { 1347 const CanonicalCookie& cc) {
1368 backend_->UpdateCookieAccessTime(cc); 1348 backend_->UpdateCookieAccessTime(cc);
1369 } 1349 }
1370 1350
1371 void SQLitePersistentCookieStore::DeleteCookie(const net::CanonicalCookie& cc) { 1351 void SQLitePersistentCookieStore::DeleteCookie(const CanonicalCookie& cc) {
1372 backend_->DeleteCookie(cc); 1352 backend_->DeleteCookie(cc);
1373 } 1353 }
1374 1354
1375 void SQLitePersistentCookieStore::SetForceKeepSessionState() { 1355 void SQLitePersistentCookieStore::SetForceKeepSessionState() {
1376 backend_->SetForceKeepSessionState(); 1356 // This store never discards session-only cookies, so this call has no effect.
1377 } 1357 }
1378 1358
1379 void SQLitePersistentCookieStore::Flush(const base::Closure& callback) { 1359 void SQLitePersistentCookieStore::Flush(const base::Closure& callback) {
1380 backend_->Flush(callback); 1360 backend_->Flush(callback);
1381 } 1361 }
1382 1362
1383 SQLitePersistentCookieStore::~SQLitePersistentCookieStore() { 1363 SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
1384 backend_->Close(); 1364 backend_->Close();
1385 // We release our reference to the Backend, though it will probably still have 1365 // We release our reference to the Backend, though it will probably still have
1386 // a reference if the background runner has not run Close() yet. 1366 // a reference if the background runner has not run Close() yet.
1387 } 1367 }
1388 1368
1389 CookieStoreConfig::CookieStoreConfig() 1369 } // namespace net
1390 : session_cookie_mode(EPHEMERAL_SESSION_COOKIES),
1391 crypto_delegate(NULL) {
1392 // Default to an in-memory cookie store.
1393 }
1394
1395 CookieStoreConfig::CookieStoreConfig(
1396 const base::FilePath& path,
1397 SessionCookieMode session_cookie_mode,
1398 storage::SpecialStoragePolicy* storage_policy,
1399 net::CookieMonsterDelegate* cookie_delegate)
1400 : path(path),
1401 session_cookie_mode(session_cookie_mode),
1402 storage_policy(storage_policy),
1403 cookie_delegate(cookie_delegate),
1404 crypto_delegate(NULL) {
1405 CHECK(!path.empty() || session_cookie_mode == EPHEMERAL_SESSION_COOKIES);
1406 }
1407
1408 CookieStoreConfig::~CookieStoreConfig() {
1409 }
1410
1411 net::CookieStore* CreateCookieStore(const CookieStoreConfig& config) {
1412 // TODO(bcwhite): Remove ScopedTracker below once crbug.com/483686 is fixed.
1413 tracked_objects::ScopedTracker tracking_profile(
1414 FROM_HERE_WITH_EXPLICIT_FUNCTION("483686 content::CreateCookieStore"));
1415
1416 net::CookieMonster* cookie_monster = NULL;
1417
1418 if (config.path.empty()) {
1419 // Empty path means in-memory store.
1420 cookie_monster = new net::CookieMonster(NULL, config.cookie_delegate.get());
1421 } else {
1422 scoped_refptr<base::SequencedTaskRunner> client_task_runner =
1423 config.client_task_runner;
1424 scoped_refptr<base::SequencedTaskRunner> background_task_runner =
1425 config.background_task_runner;
1426
1427 if (!client_task_runner.get()) {
1428 client_task_runner =
1429 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
1430 }
1431
1432 if (!background_task_runner.get()) {
1433 background_task_runner =
1434 BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
1435 BrowserThread::GetBlockingPool()->GetSequenceToken());
1436 }
1437
1438 SQLitePersistentCookieStore* persistent_store =
1439 new SQLitePersistentCookieStore(
1440 config.path,
1441 client_task_runner,
1442 background_task_runner,
1443 (config.session_cookie_mode ==
1444 CookieStoreConfig::RESTORED_SESSION_COOKIES),
1445 config.storage_policy.get(),
1446 config.crypto_delegate);
1447
1448 cookie_monster =
1449 new net::CookieMonster(persistent_store, config.cookie_delegate.get());
1450 if ((config.session_cookie_mode ==
1451 CookieStoreConfig::PERSISTANT_SESSION_COOKIES) ||
1452 (config.session_cookie_mode ==
1453 CookieStoreConfig::RESTORED_SESSION_COOKIES)) {
1454 cookie_monster->SetPersistSessionCookies(true);
1455 }
1456 }
1457
1458 return cookie_monster;
1459 }
1460
1461 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698