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