blob: d248f1007eef6fa1339b354abed549f5612712fb [file] [log] [blame]
[email protected]63ee33bd2012-03-15 09:29:581// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// Brought to you by the letter D and the number 2.
6
7#ifndef NET_COOKIES_COOKIE_MONSTER_H_
8#define NET_COOKIES_COOKIE_MONSTER_H_
[email protected]63ee33bd2012-03-15 09:29:589
10#include <deque>
11#include <map>
12#include <queue>
13#include <set>
14#include <string>
15#include <utility>
16#include <vector>
17
18#include "base/basictypes.h"
19#include "base/callback_forward.h"
20#include "base/gtest_prod_util.h"
21#include "base/memory/ref_counted.h"
22#include "base/memory/scoped_ptr.h"
23#include "base/synchronization/lock.h"
[email protected]9da992db2013-06-28 05:40:4724#include "base/time/time.h"
[email protected]565c3f42012-08-14 14:22:5825#include "net/base/net_export.h"
[email protected]8da4b1812012-07-25 13:54:3826#include "net/cookies/canonical_cookie.h"
[email protected]ab2d75c82013-04-19 18:39:0427#include "net/cookies/cookie_constants.h"
[email protected]63ee33bd2012-03-15 09:29:5828#include "net/cookies/cookie_store.h"
[email protected]63ee33bd2012-03-15 09:29:5829
30class GURL;
31
32namespace base {
33class Histogram;
[email protected]de415552013-01-23 04:12:1734class HistogramBase;
[email protected]63ee33bd2012-03-15 09:29:5835class TimeTicks;
36} // namespace base
37
38namespace net {
39
[email protected]ebfe3172012-07-12 12:21:4140class ParsedCookie;
[email protected]63ee33bd2012-03-15 09:29:5841
42// The cookie monster is the system for storing and retrieving cookies. It has
43// an in-memory list of all cookies, and synchronizes non-session cookies to an
44// optional permanent storage that implements the PersistentCookieStore
45// interface.
46//
47// This class IS thread-safe. Normally, it is only used on the I/O thread, but
48// is also accessed directly through Automation for UI testing.
49//
50// All cookie tasks are handled asynchronously. Tasks may be deferred if
51// all affected cookies are not yet loaded from the backing store. Otherwise,
52// the callback may be invoked immediately (prior to return of the asynchronous
53// function).
54//
55// A cookie task is either pending loading of the entire cookie store, or
56// loading of cookies for a specfic domain key(eTLD+1). In the former case, the
[email protected]0184df32013-05-14 00:53:5557// cookie task will be queued in tasks_pending_ while PersistentCookieStore
58// chain loads the cookie store on DB thread. In the latter case, the cookie
59// task will be queued in tasks_pending_for_key_ while PermanentCookieStore
60// loads cookies for the specified domain key(eTLD+1) on DB thread.
[email protected]63ee33bd2012-03-15 09:29:5861//
62// Callbacks are guaranteed to be invoked on the calling thread.
63//
64// TODO(deanm) Implement CookieMonster, the cookie database.
65// - Verify that our domain enforcement and non-dotted handling is correct
66class NET_EXPORT CookieMonster : public CookieStore {
67 public:
[email protected]63ee33bd2012-03-15 09:29:5868 class Delegate;
[email protected]63ee33bd2012-03-15 09:29:5869 class PersistentCookieStore;
70
71 // Terminology:
72 // * The 'top level domain' (TLD) of an internet domain name is
73 // the terminal "." free substring (e.g. "com" for google.com
74 // or world.std.com).
75 // * The 'effective top level domain' (eTLD) is the longest
76 // "." initiated terminal substring of an internet domain name
77 // that is controlled by a general domain registrar.
78 // (e.g. "co.uk" for news.bbc.co.uk).
79 // * The 'effective top level domain plus one' (eTLD+1) is the
80 // shortest "." delimited terminal substring of an internet
81 // domain name that is not controlled by a general domain
82 // registrar (e.g. "bbc.co.uk" for news.bbc.co.uk, or
83 // "google.com" for news.google.com). The general assumption
84 // is that all hosts and domains under an eTLD+1 share some
85 // administrative control.
86
87 // CookieMap is the central data structure of the CookieMonster. It
88 // is a map whose values are pointers to CanonicalCookie data
89 // structures (the data structures are owned by the CookieMonster
90 // and must be destroyed when removed from the map). The key is based on the
91 // effective domain of the cookies. If the domain of the cookie has an
92 // eTLD+1, that is the key for the map. If the domain of the cookie does not
93 // have an eTLD+1, the key of the map is the host the cookie applies to (it is
94 // not legal to have domain cookies without an eTLD+1). This rule
95 // excludes cookies for, e.g, ".com", ".co.uk", or ".internalnetwork".
96 // This behavior is the same as the behavior in Firefox v 3.6.10.
97
98 // NOTE(deanm):
99 // I benchmarked hash_multimap vs multimap. We're going to be query-heavy
100 // so it would seem like hashing would help. However they were very
101 // close, with multimap being a tiny bit faster. I think this is because
102 // our map is at max around 1000 entries, and the additional complexity
103 // for the hashing might not overcome the O(log(1000)) for querying
104 // a multimap. Also, multimap is standard, another reason to use it.
105 // TODO(rdsmith): This benchmark should be re-done now that we're allowing
106 // subtantially more entries in the map.
107 typedef std::multimap<std::string, CanonicalCookie*> CookieMap;
108 typedef std::pair<CookieMap::iterator, CookieMap::iterator> CookieMapItPair;
[email protected]8ad5d462013-05-02 08:45:26109 typedef std::vector<CookieMap::iterator> CookieItVector;
110
111 // Cookie garbage collection thresholds. Based off of the Mozilla defaults.
112 // When the number of cookies gets to k{Domain,}MaxCookies
113 // purge down to k{Domain,}MaxCookies - k{Domain,}PurgeCookies.
114 // It might seem scary to have a high purge value, but really it's not.
115 // You just make sure that you increase the max to cover the increase
116 // in purge, and we would have been purging the same number of cookies.
117 // We're just going through the garbage collection process less often.
118 // Note that the DOMAIN values are per eTLD+1; see comment for the
119 // CookieMap typedef. So, e.g., the maximum number of cookies allowed for
120 // google.com and all of its subdomains will be 150-180.
121 //
122 // Any cookies accessed more recently than kSafeFromGlobalPurgeDays will not
123 // be evicted by global garbage collection, even if we have more than
124 // kMaxCookies. This does not affect domain garbage collection.
125 static const size_t kDomainMaxCookies;
126 static const size_t kDomainPurgeCookies;
127 static const size_t kMaxCookies;
128 static const size_t kPurgeCookies;
129
130 // Quota for cookies with {low, medium, high} priorities within a domain.
131 static const size_t kDomainCookiesQuotaLow;
132 static const size_t kDomainCookiesQuotaMedium;
133 static const size_t kDomainCookiesQuotaHigh;
[email protected]63ee33bd2012-03-15 09:29:58134
135 // The store passed in should not have had Init() called on it yet. This
136 // class will take care of initializing it. The backing store is NOT owned by
137 // this class, but it must remain valid for the duration of the cookie
138 // monster's existence. If |store| is NULL, then no backing store will be
139 // updated. If |delegate| is non-NULL, it will be notified on
140 // creation/deletion of cookies.
141 CookieMonster(PersistentCookieStore* store, Delegate* delegate);
142
143 // Only used during unit testing.
144 CookieMonster(PersistentCookieStore* store,
145 Delegate* delegate,
146 int last_access_threshold_milliseconds);
147
[email protected]63ee33bd2012-03-15 09:29:58148 // Helper function that adds all cookies from |list| into this instance.
149 bool InitializeFrom(const CookieList& list);
150
151 typedef base::Callback<void(const CookieList& cookies)> GetCookieListCallback;
152 typedef base::Callback<void(bool success)> DeleteCookieCallback;
[email protected]ee209482013-04-19 19:50:04153 typedef base::Callback<void(bool cookies_exist)> HasCookiesForETLDP1Callback;
[email protected]63ee33bd2012-03-15 09:29:58154
155 // Sets a cookie given explicit user-provided cookie attributes. The cookie
156 // name, value, domain, etc. are each provided as separate strings. This
157 // function expects each attribute to be well-formed. It will check for
158 // disallowed characters (e.g. the ';' character is disallowed within the
159 // cookie value attribute) and will return false without setting the cookie
160 // if such characters are found.
161 void SetCookieWithDetailsAsync(const GURL& url,
162 const std::string& name,
163 const std::string& value,
164 const std::string& domain,
165 const std::string& path,
166 const base::Time& expiration_time,
[email protected]ab2d75c82013-04-19 18:39:04167 bool secure,
168 bool http_only,
169 CookiePriority priority,
[email protected]63ee33bd2012-03-15 09:29:58170 const SetCookiesCallback& callback);
171
172
173 // Returns all the cookies, for use in management UI, etc. This does not mark
174 // the cookies as having been accessed.
175 // The returned cookies are ordered by longest path, then by earliest
176 // creation date.
177 void GetAllCookiesAsync(const GetCookieListCallback& callback);
178
179 // Returns all the cookies, for use in management UI, etc. Filters results
180 // using given url scheme, host / domain and path and options. This does not
181 // mark the cookies as having been accessed.
182 // The returned cookies are ordered by longest path, then earliest
183 // creation date.
184 void GetAllCookiesForURLWithOptionsAsync(
185 const GURL& url,
186 const CookieOptions& options,
187 const GetCookieListCallback& callback);
188
189 // Invokes GetAllCookiesForURLWithOptions with options set to include HTTP
190 // only cookies.
191 void GetAllCookiesForURLAsync(const GURL& url,
192 const GetCookieListCallback& callback);
193
194 // Deletes all of the cookies.
195 void DeleteAllAsync(const DeleteCallback& callback);
196
197 // Deletes all cookies that match the host of the given URL
198 // regardless of path. This includes all http_only and secure cookies,
199 // but does not include any domain cookies that may apply to this host.
200 // Returns the number of cookies deleted.
201 void DeleteAllForHostAsync(const GURL& url,
202 const DeleteCallback& callback);
203
204 // Deletes one specific cookie.
205 void DeleteCanonicalCookieAsync(const CanonicalCookie& cookie,
206 const DeleteCookieCallback& callback);
207
[email protected]ee209482013-04-19 19:50:04208 // Checks whether for a given ETLD+1, there currently exist any cookies.
209 void HasCookiesForETLDP1Async(const std::string& etldp1,
210 const HasCookiesForETLDP1Callback& callback);
211
[email protected]97a3b6e2012-06-12 01:53:56212 // Resets the list of cookieable schemes to the supplied schemes.
[email protected]63ee33bd2012-03-15 09:29:58213 // If this this method is called, it must be called before first use of
214 // the instance (i.e. as part of the instance initialization process).
215 void SetCookieableSchemes(const char* schemes[], size_t num_schemes);
216
[email protected]97a3b6e2012-06-12 01:53:56217 // Resets the list of cookieable schemes to kDefaultCookieableSchemes with or
218 // without 'file' being included.
219 void SetEnableFileScheme(bool accept);
220
[email protected]63ee33bd2012-03-15 09:29:58221 // Instructs the cookie monster to not delete expired cookies. This is used
222 // in cases where the cookie monster is used as a data structure to keep
223 // arbitrary cookies.
224 void SetKeepExpiredCookies();
225
[email protected]bf510ed2012-06-05 08:31:43226 // Protects session cookies from deletion on shutdown.
227 void SetForceKeepSessionState();
[email protected]63ee33bd2012-03-15 09:29:58228
229 // There are some unknowns about how to correctly handle file:// cookies,
230 // and our implementation for this is not robust enough. This allows you
231 // to enable support, but it should only be used for testing. Bug 1157243.
232 // Must be called before creating a CookieMonster instance.
233 static void EnableFileScheme();
234
235 // Flush the backing store (if any) to disk and post the given callback when
236 // done.
237 // WARNING: THE CALLBACK WILL RUN ON A RANDOM THREAD. IT MUST BE THREAD SAFE.
238 // It may be posted to the current thread, or it may run on the thread that
239 // actually does the flushing. Your Task should generally post a notification
240 // to the thread you actually want to be notified on.
241 void FlushStore(const base::Closure& callback);
242
243 // CookieStore implementation.
244
245 // Sets the cookies specified by |cookie_list| returned from |url|
246 // with options |options| in effect.
247 virtual void SetCookieWithOptionsAsync(
248 const GURL& url,
249 const std::string& cookie_line,
250 const CookieOptions& options,
251 const SetCookiesCallback& callback) OVERRIDE;
252
253 // Gets all cookies that apply to |url| given |options|.
254 // The returned cookies are ordered by longest path, then earliest
255 // creation date.
256 virtual void GetCookiesWithOptionsAsync(
257 const GURL& url,
258 const CookieOptions& options,
259 const GetCookiesCallback& callback) OVERRIDE;
260
[email protected]63ee33bd2012-03-15 09:29:58261 // Deletes all cookies with that might apply to |url| that has |cookie_name|.
262 virtual void DeleteCookieAsync(
263 const GURL& url, const std::string& cookie_name,
264 const base::Closure& callback) OVERRIDE;
265
266 // Deletes all of the cookies that have a creation_date greater than or equal
267 // to |delete_begin| and less than |delete_end|
268 // Returns the number of cookies that have been deleted.
269 virtual void DeleteAllCreatedBetweenAsync(
270 const base::Time& delete_begin,
271 const base::Time& delete_end,
272 const DeleteCallback& callback) OVERRIDE;
273
[email protected]264807b2012-04-25 14:49:37274 virtual void DeleteSessionCookiesAsync(const DeleteCallback&) OVERRIDE;
275
[email protected]63ee33bd2012-03-15 09:29:58276 virtual CookieMonster* GetCookieMonster() OVERRIDE;
277
278 // Enables writing session cookies into the cookie database. If this this
279 // method is called, it must be called before first use of the instance
280 // (i.e. as part of the instance initialization process).
281 void SetPersistSessionCookies(bool persist_session_cookies);
282
[email protected]8ad5d462013-05-02 08:45:26283 // Enables the new garbage collection algorithm where domain cookie eviction
284 // uses cookie priorities to decide which cookies to purge and which to keep.
285 void SetPriorityAwareGarbageCollection(
286 bool priority_aware_garbage_collection);
287
[email protected]63ee33bd2012-03-15 09:29:58288 // Debugging method to perform various validation checks on the map.
289 // Currently just checking that there are no null CanonicalCookie pointers
290 // in the map.
291 // Argument |arg| is to allow retaining of arbitrary data if the CHECKs
292 // in the function trip. TODO(rdsmith):Remove hack.
293 void ValidateMap(int arg);
294
[email protected]97a3b6e2012-06-12 01:53:56295 // Determines if the scheme of the URL is a scheme that cookies will be
296 // stored for.
297 bool IsCookieableScheme(const std::string& scheme);
298
[email protected]63ee33bd2012-03-15 09:29:58299 // The default list of schemes the cookie monster can handle.
300 static const char* kDefaultCookieableSchemes[];
301 static const int kDefaultCookieableSchemesCount;
302
303 private:
304 // For queueing the cookie monster calls.
305 class CookieMonsterTask;
306 class DeleteAllCreatedBetweenTask;
307 class DeleteAllForHostTask;
308 class DeleteAllTask;
309 class DeleteCookieTask;
310 class DeleteCanonicalCookieTask;
311 class GetAllCookiesForURLWithOptionsTask;
312 class GetAllCookiesTask;
313 class GetCookiesWithOptionsTask;
[email protected]63ee33bd2012-03-15 09:29:58314 class SetCookieWithDetailsTask;
315 class SetCookieWithOptionsTask;
[email protected]264807b2012-04-25 14:49:37316 class DeleteSessionCookiesTask;
[email protected]ee209482013-04-19 19:50:04317 class HasCookiesForETLDP1Task;
[email protected]63ee33bd2012-03-15 09:29:58318
319 // Testing support.
320 // For SetCookieWithCreationTime.
321 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest,
322 TestCookieDeleteAllCreatedBetweenTimestamps);
323
324 // For gargage collection constants.
325 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestHostGarbageCollection);
326 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestTotalGarbageCollection);
327 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, GarbageCollectionTriggers);
328 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGCTimes);
329
330 // For validation of key values.
331 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestDomainTree);
332 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestImport);
333 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, GetKey);
334 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGetKey);
335
336 // For FindCookiesForKey.
337 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, ShortLivedSessionCookies);
338
339 // Internal reasons for deletion, used to populate informative histograms
340 // and to provide a public cause for onCookieChange notifications.
341 //
342 // If you add or remove causes from this list, please be sure to also update
343 // the Delegate::ChangeCause mapping inside ChangeCauseMapping. Moreover,
344 // these are used as array indexes, so avoid reordering to keep the
345 // histogram buckets consistent. New items (if necessary) should be added
346 // at the end of the list, just before DELETE_COOKIE_LAST_ENTRY.
347 enum DeletionCause {
348 DELETE_COOKIE_EXPLICIT = 0,
349 DELETE_COOKIE_OVERWRITE,
350 DELETE_COOKIE_EXPIRED,
351 DELETE_COOKIE_EVICTED,
352 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE,
353 DELETE_COOKIE_DONT_RECORD, // e.g. For final cleanup after flush to store.
354 DELETE_COOKIE_EVICTED_DOMAIN,
355 DELETE_COOKIE_EVICTED_GLOBAL,
356
357 // Cookies evicted during domain level garbage collection that
358 // were accessed longer ago than kSafeFromGlobalPurgeDays
359 DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE,
360
361 // Cookies evicted during domain level garbage collection that
362 // were accessed more recently than kSafeFromGlobalPurgeDays
363 // (and thus would have been preserved by global garbage collection).
364 DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE,
365
366 // A common idiom is to remove a cookie by overwriting it with an
367 // already-expired expiration date. This captures that case.
368 DELETE_COOKIE_EXPIRED_OVERWRITE,
369
370 DELETE_COOKIE_LAST_ENTRY
371 };
372
[email protected]63ee33bd2012-03-15 09:29:58373 // The number of days since last access that cookies will not be subject
374 // to global garbage collection.
375 static const int kSafeFromGlobalPurgeDays;
376
377 // Record statistics every kRecordStatisticsIntervalSeconds of uptime.
378 static const int kRecordStatisticsIntervalSeconds = 10 * 60;
379
380 virtual ~CookieMonster();
381
382 // The following are synchronous calls to which the asynchronous methods
383 // delegate either immediately (if the store is loaded) or through a deferred
384 // task (if the store is not yet loaded).
385 bool SetCookieWithDetails(const GURL& url,
386 const std::string& name,
387 const std::string& value,
388 const std::string& domain,
389 const std::string& path,
390 const base::Time& expiration_time,
[email protected]ab2d75c82013-04-19 18:39:04391 bool secure,
392 bool http_only,
393 CookiePriority priority);
[email protected]63ee33bd2012-03-15 09:29:58394
395 CookieList GetAllCookies();
396
397 CookieList GetAllCookiesForURLWithOptions(const GURL& url,
398 const CookieOptions& options);
399
400 CookieList GetAllCookiesForURL(const GURL& url);
401
402 int DeleteAll(bool sync_to_store);
403
404 int DeleteAllCreatedBetween(const base::Time& delete_begin,
405 const base::Time& delete_end);
406
407 int DeleteAllForHost(const GURL& url);
408
409 bool DeleteCanonicalCookie(const CanonicalCookie& cookie);
410
411 bool SetCookieWithOptions(const GURL& url,
412 const std::string& cookie_line,
413 const CookieOptions& options);
414
415 std::string GetCookiesWithOptions(const GURL& url,
416 const CookieOptions& options);
417
[email protected]63ee33bd2012-03-15 09:29:58418 void DeleteCookie(const GURL& url, const std::string& cookie_name);
419
420 bool SetCookieWithCreationTime(const GURL& url,
421 const std::string& cookie_line,
422 const base::Time& creation_time);
423
[email protected]264807b2012-04-25 14:49:37424 int DeleteSessionCookies();
425
[email protected]ee209482013-04-19 19:50:04426 bool HasCookiesForETLDP1(const std::string& etldp1);
427
[email protected]63ee33bd2012-03-15 09:29:58428 // Called by all non-static functions to ensure that the cookies store has
429 // been initialized. This is not done during creating so it doesn't block
430 // the window showing.
431 // Note: this method should always be called with lock_ held.
432 void InitIfNecessary() {
433 if (!initialized_) {
[email protected]90499482013-06-01 00:39:50434 if (store_.get()) {
[email protected]63ee33bd2012-03-15 09:29:58435 InitStore();
436 } else {
437 loaded_ = true;
438 }
439 initialized_ = true;
440 }
441 }
442
443 // Initializes the backing store and reads existing cookies from it.
444 // Should only be called by InitIfNecessary().
445 void InitStore();
446
447 // Stores cookies loaded from the backing store and invokes any deferred
448 // calls. |beginning_time| should be the moment PersistentCookieStore::Load
449 // was invoked and is used for reporting histogram_time_blocked_on_load_.
450 // See PersistentCookieStore::Load for details on the contents of cookies.
451 void OnLoaded(base::TimeTicks beginning_time,
452 const std::vector<CanonicalCookie*>& cookies);
453
454 // Stores cookies loaded from the backing store and invokes the deferred
455 // task(s) pending loading of cookies associated with the domain key
456 // (eTLD+1). Called when all cookies for the domain key(eTLD+1) have been
457 // loaded from DB. See PersistentCookieStore::Load for details on the contents
458 // of cookies.
459 void OnKeyLoaded(
460 const std::string& key,
461 const std::vector<CanonicalCookie*>& cookies);
462
463 // Stores the loaded cookies.
464 void StoreLoadedCookies(const std::vector<CanonicalCookie*>& cookies);
465
466 // Invokes deferred calls.
467 void InvokeQueue();
468
469 // Checks that |cookies_| matches our invariants, and tries to repair any
470 // inconsistencies. (In other words, it does not have duplicate cookies).
471 void EnsureCookiesMapIsValid();
472
473 // Checks for any duplicate cookies for CookieMap key |key| which lie between
474 // |begin| and |end|. If any are found, all but the most recent are deleted.
475 // Returns the number of duplicate cookies that were deleted.
476 int TrimDuplicateCookiesForKey(const std::string& key,
477 CookieMap::iterator begin,
478 CookieMap::iterator end);
479
480 void SetDefaultCookieableSchemes();
481
482 void FindCookiesForHostAndDomain(const GURL& url,
483 const CookieOptions& options,
484 bool update_access_time,
485 std::vector<CanonicalCookie*>* cookies);
486
487 void FindCookiesForKey(const std::string& key,
488 const GURL& url,
489 const CookieOptions& options,
490 const base::Time& current,
491 bool update_access_time,
492 std::vector<CanonicalCookie*>* cookies);
493
494 // Delete any cookies that are equivalent to |ecc| (same path, domain, etc).
495 // If |skip_httponly| is true, httponly cookies will not be deleted. The
496 // return value with be true if |skip_httponly| skipped an httponly cookie.
497 // |key| is the key to find the cookie in cookies_; see the comment before
498 // the CookieMap typedef for details.
499 // NOTE: There should never be more than a single matching equivalent cookie.
500 bool DeleteAnyEquivalentCookie(const std::string& key,
501 const CanonicalCookie& ecc,
502 bool skip_httponly,
503 bool already_expired);
504
505 // Takes ownership of *cc.
506 void InternalInsertCookie(const std::string& key,
507 CanonicalCookie* cc,
508 bool sync_to_store);
509
510 // Helper function that sets cookies with more control.
511 // Not exposed as we don't want callers to have the ability
512 // to specify (potentially duplicate) creation times.
513 bool SetCookieWithCreationTimeAndOptions(const GURL& url,
514 const std::string& cookie_line,
515 const base::Time& creation_time,
516 const CookieOptions& options);
517
518 // Helper function that sets a canonical cookie, deleting equivalents and
519 // performing garbage collection.
520 bool SetCanonicalCookie(scoped_ptr<CanonicalCookie>* cc,
521 const base::Time& creation_time,
522 const CookieOptions& options);
523
524 void InternalUpdateCookieAccessTime(CanonicalCookie* cc,
525 const base::Time& current_time);
526
527 // |deletion_cause| argument is used for collecting statistics and choosing
528 // the correct Delegate::ChangeCause for OnCookieChanged notifications.
529 void InternalDeleteCookie(CookieMap::iterator it, bool sync_to_store,
530 DeletionCause deletion_cause);
531
532 // If the number of cookies for CookieMap key |key|, or globally, are
533 // over the preset maximums above, garbage collect, first for the host and
534 // then globally. See comments above garbage collection threshold
535 // constants for details.
536 //
537 // Returns the number of cookies deleted (useful for debugging).
538 int GarbageCollect(const base::Time& current, const std::string& key);
539
540 // Helper for GarbageCollect(); can be called directly as well. Deletes
541 // all expired cookies in |itpair|. If |cookie_its| is non-NULL, it is
542 // populated with all the non-expired cookies from |itpair|.
543 //
544 // Returns the number of cookies deleted.
545 int GarbageCollectExpired(const base::Time& current,
546 const CookieMapItPair& itpair,
547 std::vector<CookieMap::iterator>* cookie_its);
548
[email protected]8ad5d462013-05-02 08:45:26549 // Helper for GarbageCollect(). Deletes all cookies in the range specified by
550 // [|it_begin|, |it_end|). Returns the number of cookies deleted.
551 int GarbageCollectDeleteRange(const base::Time& current,
552 DeletionCause cause,
553 CookieItVector::iterator cookie_its_begin,
554 CookieItVector::iterator cookie_its_end);
[email protected]63ee33bd2012-03-15 09:29:58555
556 // Find the key (for lookup in cookies_) based on the given domain.
557 // See comment on keys before the CookieMap typedef.
558 std::string GetKey(const std::string& domain) const;
559
560 bool HasCookieableScheme(const GURL& url);
561
562 // Statistics support
563
564 // This function should be called repeatedly, and will record
565 // statistics if a sufficient time period has passed.
566 void RecordPeriodicStats(const base::Time& current_time);
567
568 // Initialize the above variables; should only be called from
569 // the constructor.
570 void InitializeHistograms();
571
572 // The resolution of our time isn't enough, so we do something
573 // ugly and increment when we've seen the same time twice.
574 base::Time CurrentTime();
575
576 // Runs the task if, or defers the task until, the full cookie database is
577 // loaded.
578 void DoCookieTask(const scoped_refptr<CookieMonsterTask>& task_item);
579
580 // Runs the task if, or defers the task until, the cookies for the given URL
581 // are loaded.
582 void DoCookieTaskForURL(const scoped_refptr<CookieMonsterTask>& task_item,
583 const GURL& url);
584
585 // Histogram variables; see CookieMonster::InitializeHistograms() in
586 // cookie_monster.cc for details.
[email protected]de415552013-01-23 04:12:17587 base::HistogramBase* histogram_expiration_duration_minutes_;
588 base::HistogramBase* histogram_between_access_interval_minutes_;
589 base::HistogramBase* histogram_evicted_last_access_minutes_;
590 base::HistogramBase* histogram_count_;
591 base::HistogramBase* histogram_domain_count_;
592 base::HistogramBase* histogram_etldp1_count_;
593 base::HistogramBase* histogram_domain_per_etldp1_count_;
594 base::HistogramBase* histogram_number_duplicate_db_cookies_;
595 base::HistogramBase* histogram_cookie_deletion_cause_;
596 base::HistogramBase* histogram_time_get_;
597 base::HistogramBase* histogram_time_mac_;
598 base::HistogramBase* histogram_time_blocked_on_load_;
[email protected]63ee33bd2012-03-15 09:29:58599
600 CookieMap cookies_;
601
602 // Indicates whether the cookie store has been initialized. This happens
603 // lazily in InitStoreIfNecessary().
604 bool initialized_;
605
606 // Indicates whether loading from the backend store is completed and
607 // calls may be immediately processed.
608 bool loaded_;
609
610 // List of domain keys that have been loaded from the DB.
611 std::set<std::string> keys_loaded_;
612
613 // Map of domain keys to their associated task queues. These tasks are blocked
614 // until all cookies for the associated domain key eTLD+1 are loaded from the
615 // backend store.
616 std::map<std::string, std::deque<scoped_refptr<CookieMonsterTask> > >
[email protected]0184df32013-05-14 00:53:55617 tasks_pending_for_key_;
[email protected]63ee33bd2012-03-15 09:29:58618
619 // Queues tasks that are blocked until all cookies are loaded from the backend
620 // store.
[email protected]0184df32013-05-14 00:53:55621 std::queue<scoped_refptr<CookieMonsterTask> > tasks_pending_;
[email protected]63ee33bd2012-03-15 09:29:58622
623 scoped_refptr<PersistentCookieStore> store_;
624
625 base::Time last_time_seen_;
626
627 // Minimum delay after updating a cookie's LastAccessDate before we will
628 // update it again.
629 const base::TimeDelta last_access_threshold_;
630
631 // Approximate date of access time of least recently accessed cookie
632 // in |cookies_|. Note that this is not guaranteed to be accurate, only a)
633 // to be before or equal to the actual time, and b) to be accurate
634 // immediately after a garbage collection that scans through all the cookies.
635 // This value is used to determine whether global garbage collection might
636 // find cookies to purge.
637 // Note: The default Time() constructor will create a value that compares
638 // earlier than any other time value, which is wanted. Thus this
639 // value is not initialized.
640 base::Time earliest_access_time_;
641
642 // During loading, holds the set of all loaded cookie creation times. Used to
643 // avoid ever letting cookies with duplicate creation times into the store;
644 // that way we don't have to worry about what sections of code are safe
645 // to call while it's in that state.
646 std::set<int64> creation_times_;
647
648 std::vector<std::string> cookieable_schemes_;
649
650 scoped_refptr<Delegate> delegate_;
651
652 // Lock for thread-safety
653 base::Lock lock_;
654
655 base::Time last_statistic_record_time_;
656
657 bool keep_expired_cookies_;
658 bool persist_session_cookies_;
[email protected]8ad5d462013-05-02 08:45:26659 bool priority_aware_garbage_collection_;
[email protected]63ee33bd2012-03-15 09:29:58660
[email protected]97a3b6e2012-06-12 01:53:56661 // Static setting for whether or not file scheme cookies are allows when
662 // a new CookieMonster is created, or the accepted schemes on a CookieMonster
663 // instance are reset back to defaults.
664 static bool default_enable_file_scheme_;
[email protected]63ee33bd2012-03-15 09:29:58665
666 DISALLOW_COPY_AND_ASSIGN(CookieMonster);
667};
668
[email protected]1c5499c2013-04-08 19:55:45669class NET_EXPORT CookieMonster::Delegate
[email protected]63ee33bd2012-03-15 09:29:58670 : public base::RefCountedThreadSafe<CookieMonster::Delegate> {
671 public:
672 // The publicly relevant reasons a cookie might be changed.
673 enum ChangeCause {
674 // The cookie was changed directly by a consumer's action.
675 CHANGE_COOKIE_EXPLICIT,
676 // The cookie was automatically removed due to an insert operation that
677 // overwrote it.
678 CHANGE_COOKIE_OVERWRITE,
679 // The cookie was automatically removed as it expired.
680 CHANGE_COOKIE_EXPIRED,
681 // The cookie was automatically evicted during garbage collection.
682 CHANGE_COOKIE_EVICTED,
683 // The cookie was overwritten with an already-expired expiration date.
684 CHANGE_COOKIE_EXPIRED_OVERWRITE
685 };
686
687 // Will be called when a cookie is added or removed. The function is passed
688 // the respective |cookie| which was added to or removed from the cookies.
689 // If |removed| is true, the cookie was deleted, and |cause| will be set
[email protected]a2c92a1c2012-04-03 12:32:14690 // to the reason for its removal. If |removed| is false, the cookie was
[email protected]63ee33bd2012-03-15 09:29:58691 // added, and |cause| will be set to CHANGE_COOKIE_EXPLICIT.
692 //
693 // As a special case, note that updating a cookie's properties is implemented
694 // as a two step process: the cookie to be updated is first removed entirely,
695 // generating a notification with cause CHANGE_COOKIE_OVERWRITE. Afterwards,
696 // a new cookie is written with the updated values, generating a notification
697 // with cause CHANGE_COOKIE_EXPLICIT.
[email protected]5b9bc352012-07-18 13:13:34698 virtual void OnCookieChanged(const CanonicalCookie& cookie,
[email protected]63ee33bd2012-03-15 09:29:58699 bool removed,
700 ChangeCause cause) = 0;
701 protected:
702 friend class base::RefCountedThreadSafe<CookieMonster::Delegate>;
703 virtual ~Delegate() {}
704};
705
[email protected]63ee33bd2012-03-15 09:29:58706typedef base::RefCountedThreadSafe<CookieMonster::PersistentCookieStore>
707 RefcountedPersistentCookieStore;
708
[email protected]c1b6e102013-04-10 20:54:49709class NET_EXPORT CookieMonster::PersistentCookieStore
[email protected]63ee33bd2012-03-15 09:29:58710 : public RefcountedPersistentCookieStore {
711 public:
[email protected]5b9bc352012-07-18 13:13:34712 typedef base::Callback<void(const std::vector<CanonicalCookie*>&)>
713 LoadedCallback;
[email protected]63ee33bd2012-03-15 09:29:58714
715 // Initializes the store and retrieves the existing cookies. This will be
716 // called only once at startup. The callback will return all the cookies
717 // that are not yet returned to CookieMonster by previous priority loads.
718 virtual void Load(const LoadedCallback& loaded_callback) = 0;
719
720 // Does a priority load of all cookies for the domain key (eTLD+1). The
721 // callback will return all the cookies that are not yet returned by previous
722 // loads, which includes cookies for the requested domain key if they are not
723 // already returned, plus all cookies that are chain-loaded and not yet
724 // returned to CookieMonster.
725 virtual void LoadCookiesForKey(const std::string& key,
[email protected]dedec0b2013-02-28 04:50:10726 const LoadedCallback& loaded_callback) = 0;
[email protected]63ee33bd2012-03-15 09:29:58727
728 virtual void AddCookie(const CanonicalCookie& cc) = 0;
729 virtual void UpdateCookieAccessTime(const CanonicalCookie& cc) = 0;
730 virtual void DeleteCookie(const CanonicalCookie& cc) = 0;
731
[email protected]bf510ed2012-06-05 08:31:43732 // Instructs the store to not discard session only cookies on shutdown.
733 virtual void SetForceKeepSessionState() = 0;
[email protected]63ee33bd2012-03-15 09:29:58734
735 // Flushes the store and posts |callback| when complete.
736 virtual void Flush(const base::Closure& callback) = 0;
737
738 protected:
739 PersistentCookieStore() {}
[email protected]a9813302012-04-28 09:29:28740 virtual ~PersistentCookieStore() {}
[email protected]63ee33bd2012-03-15 09:29:58741
742 private:
[email protected]a9813302012-04-28 09:29:28743 friend class base::RefCountedThreadSafe<PersistentCookieStore>;
[email protected]63ee33bd2012-03-15 09:29:58744 DISALLOW_COPY_AND_ASSIGN(PersistentCookieStore);
745};
746
[email protected]63ee33bd2012-03-15 09:29:58747} // namespace net
748
749#endif // NET_COOKIES_COOKIE_MONSTER_H_