• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
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 <stddef.h>
11 #include <stdint.h>
12 
13 #include <map>
14 #include <memory>
15 #include <optional>
16 #include <set>
17 #include <string>
18 #include <string_view>
19 #include <vector>
20 
21 #include "base/containers/circular_deque.h"
22 #include "base/containers/flat_map.h"
23 #include "base/functional/callback_forward.h"
24 #include "base/gtest_prod_util.h"
25 #include "base/memory/ref_counted.h"
26 #include "base/memory/weak_ptr.h"
27 #include "base/thread_annotations.h"
28 #include "base/threading/thread_checker.h"
29 #include "base/time/time.h"
30 #include "net/base/net_export.h"
31 #include "net/base/schemeful_site.h"
32 #include "net/cookies/canonical_cookie.h"
33 #include "net/cookies/cookie_access_delegate.h"
34 #include "net/cookies/cookie_constants.h"
35 #include "net/cookies/cookie_inclusion_status.h"
36 #include "net/cookies/cookie_monster_change_dispatcher.h"
37 #include "net/cookies/cookie_store.h"
38 #include "net/log/net_log_with_source.h"
39 #include "url/gurl.h"
40 
41 namespace net {
42 
43 class CookieChangeDispatcher;
44 
45 // The cookie monster is the system for storing and retrieving cookies. It has
46 // an in-memory list of all cookies, and synchronizes non-session cookies to an
47 // optional permanent storage that implements the PersistentCookieStore
48 // interface.
49 //
50 // Tasks may be deferred if all affected cookies are not yet loaded from the
51 // backing store. Otherwise, callbacks may be invoked immediately.
52 //
53 // A cookie task is either pending loading of the entire cookie store, or
54 // loading of cookies for a specific domain key (GetKey(), roughly eTLD+1). In
55 // the former case, the cookie callback will be queued in tasks_pending_ while
56 // PersistentCookieStore chain loads the cookie store on DB thread. In the
57 // latter case, the cookie callback will be queued in tasks_pending_for_key_
58 // while PermanentCookieStore loads cookies for the specified domain key on DB
59 // thread.
60 class NET_EXPORT CookieMonster : public CookieStore {
61  public:
62   class PersistentCookieStore;
63 
64   // Terminology:
65   //    * The 'top level domain' (TLD) of an internet domain name is
66   //      the terminal "." free substring (e.g. "com" for google.com
67   //      or world.std.com).
68   //    * The 'effective top level domain' (eTLD) is the longest
69   //      "." initiated terminal substring of an internet domain name
70   //      that is controlled by a general domain registrar.
71   //      (e.g. "co.uk" for news.bbc.co.uk).
72   //    * The 'effective top level domain plus one' (eTLD+1) is the
73   //      shortest "." delimited terminal substring of an internet
74   //      domain name that is not controlled by a general domain
75   //      registrar (e.g. "bbc.co.uk" for news.bbc.co.uk, or
76   //      "google.com" for news.google.com).  The general assumption
77   //      is that all hosts and domains under an eTLD+1 share some
78   //      administrative control.
79 
80   // CookieMap is the central data structure of the CookieMonster.  It
81   // is a map whose values are pointers to CanonicalCookie data
82   // structures (the data structures are owned by the CookieMonster
83   // and must be destroyed when removed from the map).  The key is based on the
84   // effective domain of the cookies.  If the domain of the cookie has an
85   // eTLD+1, that is the key for the map.  If the domain of the cookie does not
86   // have an eTLD+1, the key of the map is the host the cookie applies to (it is
87   // not legal to have domain cookies without an eTLD+1).  This rule
88   // excludes cookies for, e.g, ".com", ".co.uk", or ".internalnetwork".
89   // This behavior is the same as the behavior in Firefox v 3.6.10.
90   // CookieMap does not store cookies that were set with the Partitioned
91   // attribute, those are stored in PartitionedCookieMap.
92 
93   // NOTE(deanm):
94   // I benchmarked hash_multimap vs multimap.  We're going to be query-heavy
95   // so it would seem like hashing would help.  However they were very
96   // close, with multimap being a tiny bit faster.  I think this is because
97   // our map is at max around 1000 entries, and the additional complexity
98   // for the hashing might not overcome the O(log(1000)) for querying
99   // a multimap.  Also, multimap is standard, another reason to use it.
100   // TODO(rdsmith): This benchmark should be re-done now that we're allowing
101   // substantially more entries in the map.
102   using CookieMap =
103       std::multimap<std::string, std::unique_ptr<CanonicalCookie>>;
104   using CookieMapItPair = std::pair<CookieMap::iterator, CookieMap::iterator>;
105   using CookieItVector = std::vector<CookieMap::iterator>;
106   using CookieItList = std::list<CookieMap::iterator>;
107 
108   // PartitionedCookieMap only stores cookies that were set with the Partitioned
109   // attribute. The map is double-keyed on cookie's partition key and
110   // the cookie's effective domain of the cookie (the key of CookieMap).
111   // We store partitioned cookies in a separate map so that the queries for a
112   // request's unpartitioned and partitioned cookies will both be more
113   // efficient (since querying two smaller maps is more efficient that querying
114   // one larger map twice).
115   using PartitionedCookieMap =
116       std::map<CookiePartitionKey, std::unique_ptr<CookieMap>>;
117   using PartitionedCookieMapIterators =
118       std::pair<PartitionedCookieMap::iterator, CookieMap::iterator>;
119 
120   // Cookie garbage collection thresholds.  Based off of the Mozilla defaults.
121   // When the number of cookies gets to k{Domain,}MaxCookies
122   // purge down to k{Domain,}MaxCookies - k{Domain,}PurgeCookies.
123   // It might seem scary to have a high purge value, but really it's not.
124   // You just make sure that you increase the max to cover the increase
125   // in purge, and we would have been purging the same number of cookies.
126   // We're just going through the garbage collection process less often.
127   // Note that the DOMAIN values are per eTLD+1; see comment for the
128   // CookieMap typedef.  So, e.g., the maximum number of cookies allowed for
129   // google.com and all of its subdomains will be 150-180.
130   //
131   // Any cookies accessed more recently than kSafeFromGlobalPurgeDays will not
132   // be evicted by global garbage collection, even if we have more than
133   // kMaxCookies.  This does not affect domain garbage collection.
134   static const size_t kDomainMaxCookies;
135   static const size_t kDomainPurgeCookies;
136   static const size_t kMaxCookies;
137   static const size_t kPurgeCookies;
138 
139   // Max number of keys to store for domains that have been purged.
140   static const size_t kMaxDomainPurgedKeys;
141 
142   // Partitioned cookie garbage collection thresholds.
143   static const size_t kPerPartitionDomainMaxCookieBytes;
144   static const size_t kPerPartitionDomainMaxCookies;
145   // TODO(crbug.com/40188414): Add global limit to number of partitioned
146   // cookies.
147 
148   // Quota for cookies with {low, medium, high} priorities within a domain.
149   static const size_t kDomainCookiesQuotaLow;
150   static const size_t kDomainCookiesQuotaMedium;
151   static const size_t kDomainCookiesQuotaHigh;
152 
153   // The number of days since last access that cookies will not be subject
154   // to global garbage collection.
155   static const int kSafeFromGlobalPurgeDays;
156 
157   // The store passed in should not have had Init() called on it yet. This
158   // class will take care of initializing it. The backing store is NOT owned by
159   // this class, but it must remain valid for the duration of the cookie
160   // monster's existence. If |store| is NULL, then no backing store will be
161   // updated. |net_log| must outlive the CookieMonster and can be null.
162   CookieMonster(scoped_refptr<PersistentCookieStore> store, NetLog* net_log);
163 
164   // Only used during unit testing.
165   // |net_log| must outlive the CookieMonster.
166   CookieMonster(scoped_refptr<PersistentCookieStore> store,
167                 base::TimeDelta last_access_threshold,
168                 NetLog* net_log);
169 
170   CookieMonster(const CookieMonster&) = delete;
171   CookieMonster& operator=(const CookieMonster&) = delete;
172 
173   ~CookieMonster() override;
174 
175   // Writes all the cookies in |list| into the store, replacing all cookies
176   // currently present in store.
177   // This method does not flush the backend.
178   // TODO(rdsmith, mmenke): Do not use this function; it is deprecated
179   // and should be removed.
180   // See https://codereview.chromium.org/2882063002/#msg64.
181   void SetAllCookiesAsync(const CookieList& list, SetCookiesCallback callback);
182 
183   // CookieStore implementation.
184   void SetCanonicalCookieAsync(
185       std::unique_ptr<CanonicalCookie> cookie,
186       const GURL& source_url,
187       const CookieOptions& options,
188       SetCookiesCallback callback,
189       std::optional<CookieAccessResult> cookie_access_result =
190           std::nullopt) override;
191   void GetCookieListWithOptionsAsync(const GURL& url,
192                                      const CookieOptions& options,
193                                      const CookiePartitionKeyCollection& s,
194                                      GetCookieListCallback callback) override;
195   void GetAllCookiesAsync(GetAllCookiesCallback callback) override;
196   void GetAllCookiesWithAccessSemanticsAsync(
197       GetAllCookiesWithAccessSemanticsCallback callback) override;
198   void DeleteCanonicalCookieAsync(const CanonicalCookie& cookie,
199                                   DeleteCallback callback) override;
200   void DeleteAllCreatedInTimeRangeAsync(
201       const CookieDeletionInfo::TimeRange& creation_range,
202       DeleteCallback callback) override;
203   void DeleteAllMatchingInfoAsync(CookieDeletionInfo delete_info,
204                                   DeleteCallback callback) override;
205   void DeleteSessionCookiesAsync(DeleteCallback callback) override;
206   void DeleteMatchingCookiesAsync(DeletePredicate predicate,
207                                   DeleteCallback callback) override;
208   void FlushStore(base::OnceClosure callback) override;
209   void SetForceKeepSessionState() override;
210   CookieChangeDispatcher& GetChangeDispatcher() override;
211   void SetCookieableSchemes(const std::vector<std::string>& schemes,
212                             SetCookieableSchemesCallback callback) override;
213   std::optional<bool> SiteHasCookieInOtherPartition(
214       const net::SchemefulSite& site,
215       const std::optional<CookiePartitionKey>& partition_key) const override;
216 
217   // Enables writing session cookies into the cookie database. If this this
218   // method is called, it must be called before first use of the instance
219   // (i.e. as part of the instance initialization process).
220   void SetPersistSessionCookies(bool persist_session_cookies);
221 
222   // The default list of schemes the cookie monster can handle.
223   static const char* const kDefaultCookieableSchemes[];
224   static const int kDefaultCookieableSchemesCount;
225 
226   // Find a key based on the given domain, which will be used to find all
227   // cookies potentially relevant to it. This is used for lookup in cookies_ as
228   // well as for PersistentCookieStore::LoadCookiesForKey. See comment on keys
229   // before the CookieMap typedef.
230   static std::string GetKey(std::string_view domain);
231 
232   // Exposes the comparison function used when sorting cookies.
233   static bool CookieSorter(const CanonicalCookie* cc1,
234                            const CanonicalCookie* cc2);
235 
236   // Triggers immediate recording of stats that are typically reported
237   // periodically.
DoRecordPeriodicStatsForTesting()238   bool DoRecordPeriodicStatsForTesting() { return DoRecordPeriodicStats(); }
239 
240  private:
241   // For garbage collection constants.
242   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestHostGarbageCollection);
243   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest,
244                            GarbageCollectWithSecureCookiesOnly);
245   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGCTimes);
246 
247   // For validation of key values.
248   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestDomainTree);
249   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestImport);
250   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, GetKey);
251   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGetKey);
252 
253   // For FindCookiesForKey.
254   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, ShortLivedSessionCookies);
255 
256   // For CookieSource histogram enum.
257   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, CookieSourceHistogram);
258 
259   // For kSafeFromGlobalPurgeDays in CookieStore.
260   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, EvictSecureCookies);
261 
262   // For CookieDeleteEquivalent histogram enum.
263   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest,
264                            CookieDeleteEquivalentHistogramTest);
265 
266   // For CookieSentToSamePort enum.
267   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest,
268                            CookiePortReadDiffersFromSetHistogram);
269   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, IsCookieSentToSamePortThatSetIt);
270 
271   // For FilterCookiesWithOptions domain shadowing.
272   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest,
273                            FilterCookiesWithOptionsExcludeShadowingDomains);
274   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest,
275                            FilterCookiesWithOptionsWarnShadowingDomains);
276 
277   // For StoreLoadedCookies behavior with origin-bound cookies.
278   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest_StoreLoadedCookies,
279                            NoSchemeNoPort);
280   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest_StoreLoadedCookies,
281                            YesSchemeNoPort);
282   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest_StoreLoadedCookies,
283                            NoSchemeYesPort);
284   FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest_StoreLoadedCookies,
285                            YesSchemeYesPort);
286 
287   // Internal reasons for deletion, used to populate informative histograms
288   // and to provide a public cause for onCookieChange notifications.
289   //
290   // If you add or remove causes from this list, please be sure to also update
291   // the CookieChangeCause mapping inside ChangeCauseMapping. New items (if
292   // necessary) should be added at the end of the list, just before
293   // DELETE_COOKIE_LAST_ENTRY.
294   enum DeletionCause {
295     DELETE_COOKIE_EXPLICIT = 0,
296     DELETE_COOKIE_OVERWRITE = 1,
297     DELETE_COOKIE_EXPIRED = 2,
298     DELETE_COOKIE_EVICTED = 3,
299     DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE = 4,
300     DELETE_COOKIE_DONT_RECORD = 5,  // For final cleanup after flush to store.
301 
302     // Cookies evicted during domain-level garbage collection.
303     DELETE_COOKIE_EVICTED_DOMAIN = 6,
304 
305     // Cookies evicted during global garbage collection, which takes place after
306     // domain-level garbage collection fails to bring the cookie store under
307     // the overall quota.
308     DELETE_COOKIE_EVICTED_GLOBAL = 7,
309 
310     // #8 was DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE
311     // #9 was DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE
312 
313     // A common idiom is to remove a cookie by overwriting it with an
314     // already-expired expiration date. This captures that case.
315     DELETE_COOKIE_EXPIRED_OVERWRITE = 10,
316 
317     // Cookies are not allowed to contain control characters in the name or
318     // value. However, we used to allow them, so we are now evicting any such
319     // cookies as we load them. See http://crbug.com/238041.
320     DELETE_COOKIE_CONTROL_CHAR = 11,
321 
322     // When strict secure cookies is enabled, non-secure cookies are evicted
323     // right after expired cookies.
324     DELETE_COOKIE_NON_SECURE = 12,
325 
326     // Partitioned cookies evicted during per-partition domain-level garbage
327     // collection.
328     DELETE_COOKIE_EVICTED_PER_PARTITION_DOMAIN = 13,
329 
330     DELETE_COOKIE_LAST_ENTRY = 14,
331   };
332 
333   // Used to populate a histogram containing information about the
334   // sources of Secure and non-Secure cookies: that is, whether such
335   // cookies are set by origins with cryptographic or non-cryptographic
336   // schemes. Please do not reorder the list when adding new
337   // entries. New items MUST be added at the end of the list, and kMaxValue
338   // should be updated to the last value.
339   //
340   // CookieSource::k(Non)SecureCookie(Non)CryptographicScheme means
341   // that a cookie was set or overwritten from a URL with the given type
342   // of scheme. This enum should not be used when cookies are *cleared*,
343   // because its purpose is to understand if Chrome can deprecate the
344   // ability of HTTP urls to set/overwrite Secure cookies.
345   enum class CookieSource : uint8_t {
346     kSecureCookieCryptographicScheme = 0,
347     kSecureCookieNoncryptographicScheme,
348     kNonsecureCookieCryptographicScheme,
349     kNonsecureCookieNoncryptographicScheme,
350     kMaxValue = kNonsecureCookieNoncryptographicScheme
351   };
352 
353   // Enum for collecting metrics on how frequently a cookie is sent to the same
354   // port it was set by.
355   //
356   // kNoButDefault exists because we expect for cookies being sent between
357   // schemes to have a port mismatch and want to separate those out from other,
358   // more interesting, cases.
359   //
360   // Do not reorder or renumber. Used for metrics.
361   enum class CookieSentToSamePort {
362     kSourcePortUnspecified = 0,  // Cookie's source port is unspecified, we
363                                  // can't know if this is the same port or not.
364     kInvalid = 1,  // The source port was corrupted to be PORT_INVALID, we
365                    // can't know if this is the same port or not.
366     kNo = 2,       // Source port and destination port are different.
367     kNoButDefault =
368         3,     // Source and destination ports are different but they're
369                // the defaults for their scheme. This can mean that an http
370                // cookie was sent to a https origin or vice-versa.
371     kYes = 4,  // They're the same.
372     kMaxValue = kYes
373   };
374 
375   // Record statistics every kRecordStatisticsIntervalSeconds of uptime.
376   static const int kRecordStatisticsIntervalSeconds = 10 * 60;
377 
378   // Sets a canonical cookie, deletes equivalents and performs garbage
379   // collection.  |source_url| indicates what URL the cookie is being set
380   // from; secure cookies cannot be altered from insecure schemes, and some
381   // schemes may not be authorized.
382   //
383   // |options| indicates if this setting operation is allowed
384   // to affect http_only or same-site cookies.
385   //
386   // |cookie_access_result| is an optional input status, to allow for status
387   // chaining from callers. It helps callers provide the status of a
388   // canonical cookie that may have warnings associated with it.
389   void SetCanonicalCookie(
390       std::unique_ptr<CanonicalCookie> cookie,
391       const GURL& source_url,
392       const CookieOptions& options,
393       SetCookiesCallback callback,
394       std::optional<CookieAccessResult> cookie_access_result = std::nullopt);
395 
396   void GetAllCookies(GetAllCookiesCallback callback);
397 
398   void AttachAccessSemanticsListForCookieList(
399       GetAllCookiesWithAccessSemanticsCallback callback,
400       const CookieList& cookie_list);
401 
402   void GetCookieListWithOptions(
403       const GURL& url,
404       const CookieOptions& options,
405       const CookiePartitionKeyCollection& cookie_partition_key_collection,
406       GetCookieListCallback callback);
407 
408   void DeleteAllCreatedInTimeRange(
409       const CookieDeletionInfo::TimeRange& creation_range,
410       DeleteCallback callback);
411 
412   // Returns whether |cookie| matches |delete_info|.
413   bool MatchCookieDeletionInfo(const CookieDeletionInfo& delete_info,
414                                const net::CanonicalCookie& cookie);
415 
416   void DeleteCanonicalCookie(const CanonicalCookie& cookie,
417                              DeleteCallback callback);
418 
419   void DeleteMatchingCookies(DeletePredicate predicate,
420                              DeletionCause cause,
421                              DeleteCallback callback);
422 
423   // The first access to the cookie store initializes it. This method should be
424   // called before any access to the cookie store.
425   void MarkCookieStoreAsInitialized();
426 
427   // Fetches all cookies if the backing store exists and they're not already
428   // being fetched.
429   void FetchAllCookiesIfNecessary();
430 
431   // Fetches all cookies from the backing store.
432   void FetchAllCookies();
433 
434   // Whether all cookies should be fetched as soon as any is requested.
435   bool ShouldFetchAllCookiesWhenFetchingAnyCookie();
436 
437   // Stores cookies loaded from the backing store and invokes any deferred
438   // calls. |beginning_time| should be the moment PersistentCookieStore::Load
439   // was invoked and is used for reporting histogram_time_blocked_on_load_.
440   // See PersistentCookieStore::Load for details on the contents of cookies.
441   void OnLoaded(base::TimeTicks beginning_time,
442                 std::vector<std::unique_ptr<CanonicalCookie>> cookies);
443 
444   // Stores cookies loaded from the backing store and invokes the deferred
445   // task(s) pending loading of cookies associated with the domain key
446   // (GetKey, roughly eTLD+1). Called when all cookies for the domain key have
447   // been loaded from DB. See PersistentCookieStore::Load for details on the
448   // contents of cookies.
449   void OnKeyLoaded(const std::string& key,
450                    std::vector<std::unique_ptr<CanonicalCookie>> cookies);
451 
452   // Stores the loaded cookies.
453   void StoreLoadedCookies(
454       std::vector<std::unique_ptr<CanonicalCookie>> cookies);
455 
456   // Invokes deferred calls.
457   void InvokeQueue();
458 
459   // Checks that |cookies_| matches our invariants, and tries to repair any
460   // inconsistencies. (In other words, it does not have duplicate cookies).
461   void EnsureCookiesMapIsValid();
462 
463   // Checks for any duplicate cookies for CookieMap key |key| which lie between
464   // |begin| and |end|. If any are found, all but the most recent are deleted.
465   //
466   // If |cookie_partition_it| is not nullopt, then this function trims cookies
467   // from the CookieMap in |partitioned_cookies_| at |cookie_partition_it|
468   // instead of trimming cookies from |cookies_|.
469   void TrimDuplicateCookiesForKey(
470       const std::string& key,
471       CookieMap::iterator begin,
472       CookieMap::iterator end,
473       std::optional<PartitionedCookieMap::iterator> cookie_partition_it);
474 
475   void SetDefaultCookieableSchemes();
476 
477   std::vector<CanonicalCookie*> FindCookiesForRegistryControlledHost(
478       const GURL& url,
479       CookieMap* cookie_map = nullptr,
480       PartitionedCookieMap::iterator* partition_it = nullptr);
481 
482   std::vector<CanonicalCookie*> FindPartitionedCookiesForRegistryControlledHost(
483       const CookiePartitionKey& cookie_partition_key,
484       const GURL& url);
485 
486   void FilterCookiesWithOptions(const GURL& url,
487                                 const CookieOptions options,
488                                 std::vector<CanonicalCookie*>* cookie_ptrs,
489                                 CookieAccessResultList* included_cookies,
490                                 CookieAccessResultList* excluded_cookies);
491 
492   // Possibly delete an existing cookie equivalent to |cookie_being_set| (same
493   // path, domain, and name).
494   //
495   // |allowed_to_set_secure_cookie| indicates if the source may override
496   // existing secure cookies. If the source is not trustworthy, and there is an
497   // existing "equivalent" cookie that is Secure, that cookie will be preserved,
498   // under "Leave Secure Cookies Alone" (see
499   // https://tools.ietf.org/html/draft-ietf-httpbis-cookie-alone-01).
500   // ("equivalent" here is in quotes because the equivalency check for the
501   // purposes of preserving existing Secure cookies is slightly more inclusive.)
502   //
503   // If |skip_httponly| is true, httponly cookies will not be deleted even if
504   // they are equivalent.
505   // |key| is the key to find the cookie in cookies_; see the comment before the
506   // CookieMap typedef for details.
507   //
508   // If a cookie is deleted, and its value matches |cookie_being_set|'s value,
509   // then |creation_date_to_inherit| will be set to that cookie's creation date.
510   //
511   // The cookie will not be deleted if |*status| is not "include" when calling
512   // the function. The function will update |*status| with exclusion reasons if
513   // a secure cookie was skipped or an httponly cookie was skipped.
514   //
515   // If |cookie_partition_it| is nullopt, it will search |cookies_| for
516   // duplicates of |cookie_being_set|. Otherwise, |cookie_partition_it|'s value
517   // is the iterator of the CookieMap in |partitioned_cookies_| we should search
518   // for duplicates.
519   //
520   // NOTE: There should never be more than a single matching equivalent cookie.
521   void MaybeDeleteEquivalentCookieAndUpdateStatus(
522       const std::string& key,
523       const CanonicalCookie& cookie_being_set,
524       bool allowed_to_set_secure_cookie,
525       bool skip_httponly,
526       bool already_expired,
527       base::Time* creation_date_to_inherit,
528       CookieInclusionStatus* status,
529       std::optional<PartitionedCookieMap::iterator> cookie_partition_it);
530 
531   // Inserts `cc` into cookies_. Returns an iterator that points to the inserted
532   // cookie in `cookies_`. Guarantee: all iterators to `cookies_` remain valid.
533   // Dispatches the change to `change_dispatcher_` iff `dispatch_change` is
534   // true.
535   CookieMap::iterator InternalInsertCookie(
536       const std::string& key,
537       std::unique_ptr<CanonicalCookie> cc,
538       bool sync_to_store,
539       const CookieAccessResult& access_result,
540       bool dispatch_change = true);
541 
542   // Returns true if the cookie should be (or is already) synced to the store.
543   // Used for cookies during insertion and deletion into the in-memory store.
544   bool ShouldUpdatePersistentStore(CanonicalCookie* cc);
545 
546   // Inserts `cc` into partitioned_cookies_. Should only be used when
547   // cc->IsPartitioned() is true.
548   PartitionedCookieMapIterators InternalInsertPartitionedCookie(
549       std::string key,
550       std::unique_ptr<CanonicalCookie> cc,
551       bool sync_to_store,
552       const CookieAccessResult& access_result,
553       bool dispatch_change = true);
554 
555   // Sets all cookies from |list| after deleting any equivalent cookie.
556   // For data gathering purposes, this routine is treated as if it is
557   // restoring saved cookies; some statistics are not gathered in this case.
558   void SetAllCookies(CookieList list, SetCookiesCallback callback);
559 
560   void InternalUpdateCookieAccessTime(CanonicalCookie* cc,
561                                       const base::Time& current_time);
562 
563   // |deletion_cause| argument is used for collecting statistics and choosing
564   // the correct CookieChangeCause for OnCookieChange notifications. Guarantee:
565   // All iterators to cookies_, except for the deleted entry, remain valid.
566   void InternalDeleteCookie(CookieMap::iterator it,
567                             bool sync_to_store,
568                             DeletionCause deletion_cause);
569 
570   // Deletes a Partitioned cookie. Returns true if the deletion operation
571   // resulted in the CookieMap the cookie was stored in was deleted.
572   //
573   // If the CookieMap which contains the deleted cookie only has one entry, then
574   // this function will also delete the CookieMap from PartitionedCookieMap.
575   // This may invalidate the |cookie_partition_it| argument.
576   void InternalDeletePartitionedCookie(
577       PartitionedCookieMap::iterator partition_it,
578       CookieMap::iterator cookie_it,
579       bool sync_to_store,
580       DeletionCause deletion_cause);
581 
582   // If the number of cookies for CookieMap key |key|, or globally, are
583   // over the preset maximums above, garbage collect, first for the host and
584   // then globally.  See comments above garbage collection threshold
585   // constants for details. Also removes expired cookies.
586   //
587   // Returns the number of cookies deleted (useful for debugging).
588   size_t GarbageCollect(const base::Time& current, const std::string& key);
589 
590   // Run garbage collection for PartitionedCookieMap keys |cookie_partition_key|
591   // and |key|.
592   //
593   // Partitioned cookies are subject to different limits than unpartitioned
594   // cookies in order to prevent leaking entropy about user behavior across
595   // cookie partitions.
596   size_t GarbageCollectPartitionedCookies(
597       const base::Time& current,
598       const CookiePartitionKey& cookie_partition_key,
599       const std::string& key);
600 
601   // Helper for GarbageCollect(). Deletes up to |purge_goal| cookies with a
602   // priority less than or equal to |priority| from |cookies|, while ensuring
603   // that at least the |to_protect| most-recent cookies are retained.
604   // |protected_secure_cookies| specifies whether or not secure cookies should
605   // be protected from deletion.
606   //
607   // |cookies| must be sorted from least-recent to most-recent.
608   //
609   // Returns the number of cookies deleted.
610   size_t PurgeLeastRecentMatches(CookieItVector* cookies,
611                                  CookiePriority priority,
612                                  size_t to_protect,
613                                  size_t purge_goal,
614                                  bool protect_secure_cookies);
615   // Same as above except that for a given {priority, secureness} tuple domain
616   // cookies will be deleted before host cookies.
617   size_t PurgeLeastRecentMatchesForOBC(CookieItList* cookies,
618                                        CookiePriority priority,
619                                        size_t to_protect,
620                                        size_t purge_goal,
621                                        bool protect_secure_cookies);
622 
623   // Helper for GarbageCollect(); can be called directly as well.  Deletes all
624   // expired cookies in |itpair|.  If |cookie_its| is non-NULL, all the
625   // non-expired cookies from |itpair| are appended to |cookie_its|.
626   //
627   // Returns the number of cookies deleted.
628   size_t GarbageCollectExpired(const base::Time& current,
629                                const CookieMapItPair& itpair,
630                                CookieItVector* cookie_its);
631 
632   // Deletes all expired cookies in the double-keyed PartitionedCookie map in
633   // the CookieMap at |cookie_partition_it|. It deletes all cookies in that
634   // CookieMap in |itpair|. If |cookie_its| is non-NULL, all non-expired cookies
635   // from |itpair| are appended to |cookie_its|.
636   //
637   // Returns the number of cookies deleted.
638   size_t GarbageCollectExpiredPartitionedCookies(
639       const base::Time& current,
640       const PartitionedCookieMap::iterator& cookie_partition_it,
641       const CookieMapItPair& itpair,
642       CookieItVector* cookie_its);
643 
644   // Helper function to garbage collect all expired cookies in
645   // PartitionedCookieMap.
646   void GarbageCollectAllExpiredPartitionedCookies(const base::Time& current);
647 
648   // Helper for GarbageCollect(). Deletes all cookies in the range specified by
649   // [|it_begin|, |it_end|). Returns the number of cookies deleted.
650   size_t GarbageCollectDeleteRange(const base::Time& current,
651                                    DeletionCause cause,
652                                    CookieItVector::iterator cookie_its_begin,
653                                    CookieItVector::iterator cookie_its_end);
654 
655   // Helper for GarbageCollect(). Deletes cookies in |cookie_its| from least to
656   // most recently used, but only before |safe_date|. Also will stop deleting
657   // when the number of remaining cookies hits |purge_goal|.
658   //
659   // Sets |earliest_time| to be the earliest last access time of a cookie that
660   // was not deleted, or base::Time() if no such cookie exists.
661   size_t GarbageCollectLeastRecentlyAccessed(const base::Time& current,
662                                              const base::Time& safe_date,
663                                              size_t purge_goal,
664                                              CookieItVector cookie_its,
665                                              base::Time* earliest_time);
666 
667   bool HasCookieableScheme(const GURL& url);
668 
669   // Get the cookie's access semantics (LEGACY or NONLEGACY), by checking for a
670   // value from the cookie access delegate, if it is non-null. Otherwise returns
671   // UNKNOWN.
672   CookieAccessSemantics GetAccessSemanticsForCookie(
673       const CanonicalCookie& cookie) const;
674 
675   // Statistics support
676 
677   // This function should be called repeatedly, and will record
678   // statistics if a sufficient time period has passed.
679   void RecordPeriodicStats(const base::Time& current_time);
680 
681   // Records the aforementioned stats if we have already finished loading all
682   // cookies. Returns whether stats were recorded.
683   bool DoRecordPeriodicStats();
684 
685   // Records periodic stats related to First-Party Sets usage. Note that since
686   // First-Party Sets presents a potentially asynchronous interface, these stats
687   // may be collected asynchronously w.r.t. the rest of the stats collected by
688   // `RecordPeriodicStats`.
689   void RecordPeriodicFirstPartySetsStats(
690       base::flat_map<SchemefulSite, FirstPartySetEntry> sets) const;
691 
692   // Defers the callback until the full coookie database has been loaded. If
693   // it's already been loaded, runs the callback synchronously.
694   void DoCookieCallback(base::OnceClosure callback);
695 
696   // Defers the callback until the cookies relevant to given URL have been
697   // loaded. If they've already been loaded, runs the callback synchronously.
698   void DoCookieCallbackForURL(base::OnceClosure callback, const GURL& url);
699 
700   // Defers the callback until the cookies relevant to given host or domain
701   // have been loaded. If they've already been loaded, runs the callback
702   // synchronously.
703   void DoCookieCallbackForHostOrDomain(base::OnceClosure callback,
704                                        std::string_view host_or_domain);
705 
706   // Checks to see if a cookie is being sent to the same port it was set by. For
707   // metrics.
708   //
709   // This is in CookieMonster because only CookieMonster uses it. It's otherwise
710   // a standalone utility function.
711   static CookieSentToSamePort IsCookieSentToSamePortThatSetIt(
712       const GURL& destination,
713       int source_port,
714       CookieSourceScheme source_scheme);
715 
716   // Set of keys (eTLD+1's) for which non-expired cookies have
717   // been evicted for hitting the per-domain max. The size of this set is
718   // histogrammed periodically. The size is limited to |kMaxDomainPurgedKeys|.
719   std::set<std::string> domain_purged_keys_ GUARDED_BY_CONTEXT(thread_checker_);
720 
721   // The number of distinct keys (eTLD+1's) currently present in the |cookies_|
722   // multimap. This is histogrammed periodically.
723   size_t num_keys_ = 0u;
724 
725   CookieMap cookies_ GUARDED_BY_CONTEXT(thread_checker_);
726 
727   PartitionedCookieMap partitioned_cookies_ GUARDED_BY_CONTEXT(thread_checker_);
728 
729   // Number of distinct partitioned cookies globally. This is used to enforce a
730   // global maximum on the number of partitioned cookies.
731   size_t num_partitioned_cookies_ = 0u;
732   // Number of partitioned cookies whose partition key has a nonce.
733   size_t num_nonced_partitioned_cookies_ = 0u;
734 
735   // Number of bytes used by the partitioned cookie jar.
736   size_t num_partitioned_cookies_bytes_ = 0u;
737   // Number of bytes used by partitioned cookies whose partition key has a
738   // nonce.
739   size_t num_nonced_partitioned_cookie_bytes_ = 0u;
740   // Cookie jar sizes per partition.
741   std::map<CookiePartitionKey, size_t> bytes_per_cookie_partition_;
742 
743   CookieMonsterChangeDispatcher change_dispatcher_;
744 
745   // Indicates whether the cookie store has been initialized.
746   bool initialized_ = false;
747 
748   // Indicates whether the cookie store has started fetching all cookies.
749   bool started_fetching_all_cookies_ = false;
750   // Indicates whether the cookie store has finished fetching all cookies.
751   bool finished_fetching_all_cookies_ = false;
752 
753   // List of domain keys that have been loaded from the DB.
754   std::set<std::string> keys_loaded_;
755 
756   // Map of domain keys to their associated task queues. These tasks are blocked
757   // until all cookies for the associated domain key eTLD+1 are loaded from the
758   // backend store.
759   std::map<std::string, base::circular_deque<base::OnceClosure>>
760       tasks_pending_for_key_ GUARDED_BY_CONTEXT(thread_checker_);
761 
762   // Queues tasks that are blocked until all cookies are loaded from the backend
763   // store.
764   base::circular_deque<base::OnceClosure> tasks_pending_
765       GUARDED_BY_CONTEXT(thread_checker_);
766 
767   // Once a global cookie task has been seen, all per-key tasks must be put in
768   // |tasks_pending_| instead of |tasks_pending_for_key_| to ensure a reasonable
769   // view of the cookie store. This is more to ensure fancy cookie export/import
770   // code has a consistent view of the CookieStore, rather than out of concern
771   // for typical use.
772   bool seen_global_task_ = false;
773 
774   // If a global cookie operation is seen during the loading, record when it
775   // happens, to help measure how much extra blocking it introduced.
776   std::optional<base::TimeTicks> time_start_block_load_all_;
777 
778   NetLogWithSource net_log_;
779 
780   scoped_refptr<PersistentCookieStore> store_;
781 
782   // Minimum delay after updating a cookie's LastAccessDate before we will
783   // update it again.
784   const base::TimeDelta last_access_threshold_;
785 
786   // Approximate date of access time of least recently accessed cookie
787   // in |cookies_|.  Note that this is not guaranteed to be accurate, only a)
788   // to be before or equal to the actual time, and b) to be accurate
789   // immediately after a garbage collection that scans through all the cookies
790   // (When garbage collection does not scan through all cookies, it may not be
791   // updated). This value is used to determine whether global garbage collection
792   // might find cookies to purge. Note: The default Time() constructor will
793   // create a value that compares earlier than any other time value, which is
794   // wanted.  Thus this value is not initialized.
795   base::Time earliest_access_time_;
796 
797   std::vector<std::string> cookieable_schemes_;
798 
799   base::Time last_statistic_record_time_;
800 
801   bool persist_session_cookies_ = false;
802 
803   THREAD_CHECKER(thread_checker_);
804 
805   base::WeakPtrFactory<CookieMonster> weak_ptr_factory_{this};
806 };
807 
808 typedef base::RefCountedThreadSafe<CookieMonster::PersistentCookieStore>
809     RefcountedPersistentCookieStore;
810 
811 class NET_EXPORT CookieMonster::PersistentCookieStore
812     : public RefcountedPersistentCookieStore {
813  public:
814   typedef base::OnceCallback<void(
815       std::vector<std::unique_ptr<CanonicalCookie>>)>
816       LoadedCallback;
817 
818   PersistentCookieStore(const PersistentCookieStore&) = delete;
819   PersistentCookieStore& operator=(const PersistentCookieStore&) = delete;
820 
821   // Initializes the store and retrieves the existing cookies. This will be
822   // called only once at startup. The callback will return all the cookies
823   // that are not yet returned to CookieMonster by previous priority loads.
824   //
825   // |loaded_callback| may not be NULL.
826   // |net_log| is a NetLogWithSource that may be copied if the persistent
827   // store wishes to log NetLog events.
828   virtual void Load(LoadedCallback loaded_callback,
829                     const NetLogWithSource& net_log) = 0;
830 
831   // Does a priority load of all cookies for the domain key (eTLD+1). The
832   // callback will return all the cookies that are not yet returned by previous
833   // loads, which includes cookies for the requested domain key if they are not
834   // already returned, plus all cookies that are chain-loaded and not yet
835   // returned to CookieMonster.
836   //
837   // |loaded_callback| may not be NULL.
838   virtual void LoadCookiesForKey(const std::string& key,
839                                  LoadedCallback loaded_callback) = 0;
840 
841   virtual void AddCookie(const CanonicalCookie& cc) = 0;
842   virtual void UpdateCookieAccessTime(const CanonicalCookie& cc) = 0;
843   virtual void DeleteCookie(const CanonicalCookie& cc) = 0;
844 
845   // Instructs the store to not discard session only cookies on shutdown.
846   virtual void SetForceKeepSessionState() = 0;
847 
848   // Sets a callback that will be run before the store flushes.  If |callback|
849   // performs any async operations, the store will not wait for those to finish
850   // before flushing.
851   virtual void SetBeforeCommitCallback(base::RepeatingClosure callback) = 0;
852 
853   // Flushes the store and posts |callback| when complete. |callback| may be
854   // NULL.
855   virtual void Flush(base::OnceClosure callback) = 0;
856 
857  protected:
858   PersistentCookieStore() = default;
859   virtual ~PersistentCookieStore() = default;
860 
861  private:
862   friend class base::RefCountedThreadSafe<PersistentCookieStore>;
863 };
864 
865 }  // namespace net
866 
867 #endif  // NET_COOKIES_COOKIE_MONSTER_H_
868