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