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