blob: 46001bd4e4e1667e470863b6a04db3ee50b96380 [file] [log] [blame]
[email protected]63ee33bd2012-03-15 09:29:581// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// Brought to you by the letter D and the number 2.
6
7#ifndef NET_COOKIES_COOKIE_MONSTER_H_
8#define NET_COOKIES_COOKIE_MONSTER_H_
[email protected]63ee33bd2012-03-15 09:29:589
Avi Drissman13fc8932015-12-20 04:40:4610#include <stddef.h>
11#include <stdint.h>
12
[email protected]63ee33bd2012-03-15 09:29:5813#include <map>
danakja9850e12016-04-18 22:28:0814#include <memory>
[email protected]63ee33bd2012-03-15 09:29:5815#include <set>
16#include <string>
17#include <utility>
18#include <vector>
19
[email protected]63ee33bd2012-03-15 09:29:5820#include "base/callback_forward.h"
Brett Wilsonc6a0c822017-09-12 00:04:2921#include "base/containers/circular_deque.h"
[email protected]63ee33bd2012-03-15 09:29:5822#include "base/gtest_prod_util.h"
Avi Drissman13fc8932015-12-20 04:40:4623#include "base/macros.h"
[email protected]63ee33bd2012-03-15 09:29:5824#include "base/memory/ref_counted.h"
mmenkebe0910d2016-03-01 19:09:0925#include "base/memory/weak_ptr.h"
Lily Chenb851acc2019-08-07 15:54:4426#include "base/optional.h"
Maks Orlovich323efaf2018-03-06 02:56:3927#include "base/strings/string_piece.h"
mmenkebe0910d2016-03-01 19:09:0928#include "base/threading/thread_checker.h"
[email protected]9da992db2013-06-28 05:40:4729#include "base/time/time.h"
[email protected]565c3f42012-08-14 14:22:5830#include "net/base/net_export.h"
[email protected]8da4b1812012-07-25 13:54:3831#include "net/cookies/canonical_cookie.h"
Lily Chenab36a112019-09-19 20:17:2832#include "net/cookies/cookie_access_delegate.h"
[email protected]ab2d75c82013-04-19 18:39:0433#include "net/cookies/cookie_constants.h"
Victor Costan14f47c12018-03-01 08:02:2434#include "net/cookies/cookie_monster_change_dispatcher.h"
[email protected]63ee33bd2012-03-15 09:29:5835#include "net/cookies/cookie_store.h"
Helen Licd0fab862018-08-13 16:07:5336#include "net/log/net_log_with_source.h"
ellyjones399e35a22014-10-27 11:09:5637#include "url/gurl.h"
[email protected]63ee33bd2012-03-15 09:29:5838
39namespace base {
[email protected]de415552013-01-23 04:12:1740class HistogramBase;
[email protected]63ee33bd2012-03-15 09:29:5841} // namespace base
42
43namespace net {
44
Victor Costan14f47c12018-03-01 08:02:2445class CookieChangeDispatcher;
[email protected]63ee33bd2012-03-15 09:29:5846
47// The cookie monster is the system for storing and retrieving cookies. It has
48// an in-memory list of all cookies, and synchronizes non-session cookies to an
49// optional permanent storage that implements the PersistentCookieStore
50// interface.
51//
mmenke96f3bab2016-01-22 17:34:0252// Tasks may be deferred if all affected cookies are not yet loaded from the
53// backing store. Otherwise, callbacks may be invoked immediately.
[email protected]63ee33bd2012-03-15 09:29:5854//
55// A cookie task is either pending loading of the entire cookie store, or
Maks Orlovich323efaf2018-03-06 02:56:3956// loading of cookies for a specific domain key (GetKey(), roughly eTLD+1). In
57// the former case, the cookie callback will be queued in tasks_pending_ while
58// PersistentCookieStore chain loads the cookie store on DB thread. In the
59// latter case, the cookie callback will be queued in tasks_pending_for_key_
60// while PermanentCookieStore loads cookies for the specified domain key on DB
61// thread.
[email protected]63ee33bd2012-03-15 09:29:5862class NET_EXPORT CookieMonster : public CookieStore {
63 public:
[email protected]63ee33bd2012-03-15 09:29:5864 class PersistentCookieStore;
65
66 // Terminology:
67 // * The 'top level domain' (TLD) of an internet domain name is
68 // the terminal "." free substring (e.g. "com" for google.com
69 // or world.std.com).
70 // * The 'effective top level domain' (eTLD) is the longest
71 // "." initiated terminal substring of an internet domain name
72 // that is controlled by a general domain registrar.
73 // (e.g. "co.uk" for news.bbc.co.uk).
74 // * The 'effective top level domain plus one' (eTLD+1) is the
75 // shortest "." delimited terminal substring of an internet
76 // domain name that is not controlled by a general domain
77 // registrar (e.g. "bbc.co.uk" for news.bbc.co.uk, or
78 // "google.com" for news.google.com). The general assumption
79 // is that all hosts and domains under an eTLD+1 share some
80 // administrative control.
81
82 // CookieMap is the central data structure of the CookieMonster. It
83 // is a map whose values are pointers to CanonicalCookie data
84 // structures (the data structures are owned by the CookieMonster
85 // and must be destroyed when removed from the map). The key is based on the
86 // effective domain of the cookies. If the domain of the cookie has an
87 // eTLD+1, that is the key for the map. If the domain of the cookie does not
88 // have an eTLD+1, the key of the map is the host the cookie applies to (it is
89 // not legal to have domain cookies without an eTLD+1). This rule
90 // excludes cookies for, e.g, ".com", ".co.uk", or ".internalnetwork".
91 // This behavior is the same as the behavior in Firefox v 3.6.10.
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
avie7cd11a2016-10-11 02:00:35101 // 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>;
[email protected]8ad5d462013-05-02 08:45:26106
107 // Cookie garbage collection thresholds. Based off of the Mozilla defaults.
108 // When the number of cookies gets to k{Domain,}MaxCookies
109 // purge down to k{Domain,}MaxCookies - k{Domain,}PurgeCookies.
110 // It might seem scary to have a high purge value, but really it's not.
111 // You just make sure that you increase the max to cover the increase
112 // in purge, and we would have been purging the same number of cookies.
113 // We're just going through the garbage collection process less often.
114 // Note that the DOMAIN values are per eTLD+1; see comment for the
115 // CookieMap typedef. So, e.g., the maximum number of cookies allowed for
116 // google.com and all of its subdomains will be 150-180.
117 //
118 // Any cookies accessed more recently than kSafeFromGlobalPurgeDays will not
119 // be evicted by global garbage collection, even if we have more than
120 // kMaxCookies. This does not affect domain garbage collection.
121 static const size_t kDomainMaxCookies;
122 static const size_t kDomainPurgeCookies;
123 static const size_t kMaxCookies;
124 static const size_t kPurgeCookies;
125
126 // Quota for cookies with {low, medium, high} priorities within a domain.
mkwst87734352016-03-03 17:36:23127 static const size_t kDomainCookiesQuotaLow;
128 static const size_t kDomainCookiesQuotaMedium;
129 static const size_t kDomainCookiesQuotaHigh;
[email protected]63ee33bd2012-03-15 09:29:58130
Matt Menke477ab632019-06-27 23:12:17131 // The number of days since last access that cookies will not be subject
132 // to global garbage collection.
133 static const int kSafeFromGlobalPurgeDays;
134
[email protected]63ee33bd2012-03-15 09:29:58135 // The store passed in should not have had Init() called on it yet. This
136 // class will take care of initializing it. The backing store is NOT owned by
137 // this class, but it must remain valid for the duration of the cookie
138 // monster's existence. If |store| is NULL, then no backing store will be
Nick Harper57142b1c2019-03-14 21:03:59139 // updated. |net_log| must outlive the CookieMonster and can be null.
Pritam8354cf702018-03-10 08:55:41140 CookieMonster(scoped_refptr<PersistentCookieStore> store,
Helen Lifb313a92018-08-14 15:46:44141 NetLog* net_log);
nharper2b0ad9a2017-05-22 18:33:45142
[email protected]63ee33bd2012-03-15 09:29:58143 // Only used during unit testing.
Helen Lifb313a92018-08-14 15:46:44144 // |net_log| must outlive the CookieMonster.
Pritam8354cf702018-03-10 08:55:41145 CookieMonster(scoped_refptr<PersistentCookieStore> store,
Helen Lifb313a92018-08-14 15:46:44146 base::TimeDelta last_access_threshold,
147 NetLog* net_log);
[email protected]63ee33bd2012-03-15 09:29:58148
mmenke606c59c2016-03-07 18:20:55149 ~CookieMonster() override;
150
rdsmith0e84cea2017-07-13 03:09:53151 // Writes all the cookies in |list| into the store, replacing all cookies
152 // currently present in store.
rdsmith2709eee2017-06-20 22:43:27153 // This method does not flush the backend.
154 // TODO(rdsmith, mmenke): Do not use this function; it is deprecated
155 // and should be removed.
156 // See https://codereview.chromium.org/2882063002/#msg64.
rdsmith7ac81712017-06-22 17:09:54157 void SetAllCookiesAsync(const CookieList& list, SetCookiesCallback callback);
drogerd5d1278c2015-03-17 19:21:51158
[email protected]63ee33bd2012-03-15 09:29:58159 // CookieStore implementation.
rdsmitha6ce4442017-06-21 17:11:05160 void SetCanonicalCookieAsync(std::unique_ptr<CanonicalCookie> cookie,
Lily Chen96f29a132020-04-15 17:59:36161 const GURL& source_url,
Maks Orlovichfdbc8be2019-03-18 18:34:52162 const CookieOptions& options,
rdsmith7ac81712017-06-22 17:09:54163 SetCookiesCallback callback) override;
rdsmith7ac81712017-06-22 17:09:54164 void GetCookieListWithOptionsAsync(const GURL& url,
165 const CookieOptions& options,
166 GetCookieListCallback callback) override;
Lily Chenf068a762019-08-21 21:10:50167 void GetAllCookiesAsync(GetAllCookiesCallback callback) override;
Lily Chene2e9ae012019-10-09 20:02:54168 void GetAllCookiesWithAccessSemanticsAsync(
169 GetAllCookiesWithAccessSemanticsCallback callback) override;
mmenke24379d52016-02-05 23:50:17170 void DeleteCanonicalCookieAsync(const CanonicalCookie& cookie,
rdsmith7ac81712017-06-22 17:09:54171 DeleteCallback callback) override;
Chris Mumfordd8ed9f82018-05-01 15:43:13172 void DeleteAllCreatedInTimeRangeAsync(
173 const CookieDeletionInfo::TimeRange& creation_range,
174 DeleteCallback callback) override;
Chris Mumford800caa62018-04-20 19:34:44175 void DeleteAllMatchingInfoAsync(CookieDeletionInfo delete_info,
176 DeleteCallback callback) override;
rdsmith7ac81712017-06-22 17:09:54177 void DeleteSessionCookiesAsync(DeleteCallback) override;
178 void FlushStore(base::OnceClosure callback) override;
mmenkeded79da2016-02-06 08:28:51179 void SetForceKeepSessionState() override;
Victor Costan14f47c12018-03-01 08:02:24180 CookieChangeDispatcher& GetChangeDispatcher() override;
Nate Fischerc6fb6cf2019-03-27 00:39:49181 void SetCookieableSchemes(const std::vector<std::string>& schemes,
182 SetCookieableSchemesCallback callback) override;
mmenke74bcbd52016-01-21 17:17:56183
[email protected]63ee33bd2012-03-15 09:29:58184 // Enables writing session cookies into the cookie database. If this this
185 // method is called, it must be called before first use of the instance
186 // (i.e. as part of the instance initialization process).
187 void SetPersistSessionCookies(bool persist_session_cookies);
188
[email protected]97a3b6e2012-06-12 01:53:56189 // Determines if the scheme of the URL is a scheme that cookies will be
190 // stored for.
191 bool IsCookieableScheme(const std::string& scheme);
192
[email protected]63ee33bd2012-03-15 09:29:58193 // The default list of schemes the cookie monster can handle.
[email protected]5edff3c52014-06-23 20:27:48194 static const char* const kDefaultCookieableSchemes[];
[email protected]63ee33bd2012-03-15 09:29:58195 static const int kDefaultCookieableSchemesCount;
196
Maks Orlovich5cf437b02018-03-27 04:40:42197 void DumpMemoryStats(base::trace_event::ProcessMemoryDump* pmd,
198 const std::string& parent_absolute_name) const override;
199
Maks Orlovich323efaf2018-03-06 02:56:39200 // Find a key based on the given domain, which will be used to find all
201 // cookies potentially relevant to it. This is used for lookup in cookies_ as
202 // well as for PersistentCookieStore::LoadCookiesForKey. See comment on keys
203 // before the CookieMap typedef.
204 static std::string GetKey(base::StringPiece domain);
205
[email protected]63ee33bd2012-03-15 09:29:58206 private:
avie7cd11a2016-10-11 02:00:35207 // For garbage collection constants.
[email protected]63ee33bd2012-03-15 09:29:58208 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestHostGarbageCollection);
mmenkef4721d992017-06-07 17:13:59209 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest,
210 GarbageCollectWithSecureCookiesOnly);
[email protected]63ee33bd2012-03-15 09:29:58211 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGCTimes);
212
213 // For validation of key values.
214 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestDomainTree);
215 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestImport);
216 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, GetKey);
217 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGetKey);
218
219 // For FindCookiesForKey.
220 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, ShortLivedSessionCookies);
221
estark7feb65c2b2015-08-21 23:38:20222 // For CookieSource histogram enum.
223 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, CookieSourceHistogram);
224
jww31e32632015-12-16 23:38:34225 // For kSafeFromGlobalPurgeDays in CookieStore.
jwwa26e439d2017-01-27 18:17:27226 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, EvictSecureCookies);
jww82d99c12015-11-25 18:39:53227
jww31e32632015-12-16 23:38:34228 // For CookieDeleteEquivalent histogram enum.
229 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest,
230 CookieDeleteEquivalentHistogramTest);
jww31e32632015-12-16 23:38:34231
[email protected]63ee33bd2012-03-15 09:29:58232 // Internal reasons for deletion, used to populate informative histograms
233 // and to provide a public cause for onCookieChange notifications.
234 //
235 // If you add or remove causes from this list, please be sure to also update
Victor Costan14f47c12018-03-01 08:02:24236 // the CookieChangeCause mapping inside ChangeCauseMapping. New items (if
237 // necessary) should be added at the end of the list, just before
Nick Harper7a6683a2018-01-30 20:42:52238 // DELETE_COOKIE_LAST_ENTRY.
[email protected]63ee33bd2012-03-15 09:29:58239 enum DeletionCause {
240 DELETE_COOKIE_EXPLICIT = 0,
mkwstaa07ee82016-03-11 15:32:14241 DELETE_COOKIE_OVERWRITE = 1,
242 DELETE_COOKIE_EXPIRED = 2,
243 DELETE_COOKIE_EVICTED = 3,
244 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE = 4,
245 DELETE_COOKIE_DONT_RECORD = 5, // For final cleanup after flush to store.
[email protected]63ee33bd2012-03-15 09:29:58246
mkwstaa07ee82016-03-11 15:32:14247 // Cookies evicted during domain-level garbage collection.
248 DELETE_COOKIE_EVICTED_DOMAIN = 6,
[email protected]63ee33bd2012-03-15 09:29:58249
mkwstaa07ee82016-03-11 15:32:14250 // Cookies evicted during global garbage collection (which takes place after
251 // domain-level garbage collection fails to bring the cookie store under
252 // the overall quota.
253 DELETE_COOKIE_EVICTED_GLOBAL = 7,
254
255 // #8 was DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE
256 // #9 was DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE
[email protected]63ee33bd2012-03-15 09:29:58257
258 // A common idiom is to remove a cookie by overwriting it with an
259 // already-expired expiration date. This captures that case.
mkwstaa07ee82016-03-11 15:32:14260 DELETE_COOKIE_EXPIRED_OVERWRITE = 10,
[email protected]63ee33bd2012-03-15 09:29:58261
[email protected]6210ce52013-09-20 03:33:14262 // Cookies are not allowed to contain control characters in the name or
263 // value. However, we used to allow them, so we are now evicting any such
264 // cookies as we load them. See http://crbug.com/238041.
mkwstaa07ee82016-03-11 15:32:14265 DELETE_COOKIE_CONTROL_CHAR = 11,
[email protected]6210ce52013-09-20 03:33:14266
jww82d99c12015-11-25 18:39:53267 // When strict secure cookies is enabled, non-secure cookies are evicted
268 // right after expired cookies.
mkwstaa07ee82016-03-11 15:32:14269 DELETE_COOKIE_NON_SECURE = 12,
jww82d99c12015-11-25 18:39:53270
Nick Harper7a6683a2018-01-30 20:42:52271 DELETE_COOKIE_LAST_ENTRY = 13
[email protected]63ee33bd2012-03-15 09:29:58272 };
273
mkwstc1aa4cc2015-04-03 19:57:45274 // This enum is used to generate a histogramed bitmask measureing the types
275 // of stored cookies. Please do not reorder the list when adding new entries.
276 // New items MUST be added at the end of the list, just before
277 // COOKIE_TYPE_LAST_ENTRY;
278 enum CookieType {
mkwst46549412016-02-01 10:05:37279 COOKIE_TYPE_SAME_SITE = 0,
mkwstc1aa4cc2015-04-03 19:57:45280 COOKIE_TYPE_HTTPONLY,
281 COOKIE_TYPE_SECURE,
282 COOKIE_TYPE_LAST_ENTRY
283 };
284
estark7feb65c2b2015-08-21 23:38:20285 // Used to populate a histogram containing information about the
286 // sources of Secure and non-Secure cookies: that is, whether such
287 // cookies are set by origins with cryptographic or non-cryptographic
288 // schemes. Please do not reorder the list when adding new
289 // entries. New items MUST be added at the end of the list, just
290 // before COOKIE_SOURCE_LAST_ENTRY.
291 //
292 // COOKIE_SOURCE_(NON)SECURE_COOKIE_(NON)CRYPTOGRAPHIC_SCHEME means
293 // that a cookie was set or overwritten from a URL with the given type
294 // of scheme. This enum should not be used when cookies are *cleared*,
295 // because its purpose is to understand if Chrome can deprecate the
296 // ability of HTTP urls to set/overwrite Secure cookies.
297 enum CookieSource {
298 COOKIE_SOURCE_SECURE_COOKIE_CRYPTOGRAPHIC_SCHEME = 0,
299 COOKIE_SOURCE_SECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME,
300 COOKIE_SOURCE_NONSECURE_COOKIE_CRYPTOGRAPHIC_SCHEME,
301 COOKIE_SOURCE_NONSECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME,
302 COOKIE_SOURCE_LAST_ENTRY
303 };
304
[email protected]63ee33bd2012-03-15 09:29:58305 // Record statistics every kRecordStatisticsIntervalSeconds of uptime.
306 static const int kRecordStatisticsIntervalSeconds = 10 * 60;
307
rdsmitha6ce4442017-06-21 17:11:05308 // Sets a canonical cookie, deletes equivalents and performs garbage
Lily Chen96f29a132020-04-15 17:59:36309 // collection. |source_url| indicates what URL the cookie is being set
Maks Orlovichfdbc8be2019-03-18 18:34:52310 // from; secure cookies cannot be altered from insecure schemes, and some
311 // schemes may not be authorized.
312 //
313 // |options| indicates if this setting operation is allowed
314 // to affect http_only or same-site cookies.
rdsmithe5c701d2017-07-12 21:50:00315 void SetCanonicalCookie(std::unique_ptr<CanonicalCookie> cookie,
Lily Chen96f29a132020-04-15 17:59:36316 const GURL& source_url,
Maks Orlovichfdbc8be2019-03-18 18:34:52317 const CookieOptions& options,
rdsmithe5c701d2017-07-12 21:50:00318 SetCookiesCallback callback);
rdsmitha6ce4442017-06-21 17:11:05319
Lily Chenf068a762019-08-21 21:10:50320 void GetAllCookies(GetAllCookiesCallback callback);
[email protected]63ee33bd2012-03-15 09:29:58321
Lily Chene2e9ae012019-10-09 20:02:54322 void AttachAccessSemanticsListForCookieList(
323 GetAllCookiesWithAccessSemanticsCallback callback,
324 const CookieList& cookie_list);
325
rdsmithe5c701d2017-07-12 21:50:00326 void GetCookieListWithOptions(const GURL& url,
327 const CookieOptions& options,
328 GetCookieListCallback callback);
[email protected]63ee33bd2012-03-15 09:29:58329
Chris Mumfordd8ed9f82018-05-01 15:43:13330 void DeleteAllCreatedInTimeRange(
331 const CookieDeletionInfo::TimeRange& creation_range,
332 DeleteCallback callback);
[email protected]63ee33bd2012-03-15 09:29:58333
Chris Mumfordd8ed9f82018-05-01 15:43:13334 void DeleteAllMatchingInfo(net::CookieDeletionInfo delete_info,
Chris Mumford800caa62018-04-20 19:34:44335 DeleteCallback callback);
[email protected]63ee33bd2012-03-15 09:29:58336
rdsmithe5c701d2017-07-12 21:50:00337 void DeleteCanonicalCookie(const CanonicalCookie& cookie,
338 DeleteCallback callback);
mmenke24379d52016-02-05 23:50:17339
rdsmithe5c701d2017-07-12 21:50:00340 void DeleteSessionCookies(DeleteCallback callback);
[email protected]264807b2012-04-25 14:49:37341
erikchen1dd72a72015-05-06 20:45:05342 // The first access to the cookie store initializes it. This method should be
343 // called before any access to the cookie store.
344 void MarkCookieStoreAsInitialized();
[email protected]63ee33bd2012-03-15 09:29:58345
erikchen1dd72a72015-05-06 20:45:05346 // Fetches all cookies if the backing store exists and they're not already
347 // being fetched.
erikchen1dd72a72015-05-06 20:45:05348 void FetchAllCookiesIfNecessary();
349
350 // Fetches all cookies from the backing store.
erikchen1dd72a72015-05-06 20:45:05351 void FetchAllCookies();
352
353 // Whether all cookies should be fetched as soon as any is requested.
354 bool ShouldFetchAllCookiesWhenFetchingAnyCookie();
[email protected]63ee33bd2012-03-15 09:29:58355
356 // Stores cookies loaded from the backing store and invokes any deferred
357 // calls. |beginning_time| should be the moment PersistentCookieStore::Load
358 // was invoked and is used for reporting histogram_time_blocked_on_load_.
359 // See PersistentCookieStore::Load for details on the contents of cookies.
360 void OnLoaded(base::TimeTicks beginning_time,
avie7cd11a2016-10-11 02:00:35361 std::vector<std::unique_ptr<CanonicalCookie>> cookies);
[email protected]63ee33bd2012-03-15 09:29:58362
363 // Stores cookies loaded from the backing store and invokes the deferred
364 // task(s) pending loading of cookies associated with the domain key
Maks Orlovich323efaf2018-03-06 02:56:39365 // (GetKey, roughly eTLD+1). Called when all cookies for the domain key have
366 // been loaded from DB. See PersistentCookieStore::Load for details on the
367 // contents of cookies.
mkwstbe84af312015-02-20 08:52:45368 void OnKeyLoaded(const std::string& key,
avie7cd11a2016-10-11 02:00:35369 std::vector<std::unique_ptr<CanonicalCookie>> cookies);
[email protected]63ee33bd2012-03-15 09:29:58370
371 // Stores the loaded cookies.
avie7cd11a2016-10-11 02:00:35372 void StoreLoadedCookies(
373 std::vector<std::unique_ptr<CanonicalCookie>> cookies);
[email protected]63ee33bd2012-03-15 09:29:58374
375 // Invokes deferred calls.
376 void InvokeQueue();
377
378 // Checks that |cookies_| matches our invariants, and tries to repair any
379 // inconsistencies. (In other words, it does not have duplicate cookies).
380 void EnsureCookiesMapIsValid();
381
382 // Checks for any duplicate cookies for CookieMap key |key| which lie between
383 // |begin| and |end|. If any are found, all but the most recent are deleted.
ellyjonescabf57422015-08-21 18:44:51384 void TrimDuplicateCookiesForKey(const std::string& key,
385 CookieMap::iterator begin,
386 CookieMap::iterator end);
[email protected]63ee33bd2012-03-15 09:29:58387
388 void SetDefaultCookieableSchemes();
389
Aaron Tagliaboschibd34cc0c2019-01-31 01:19:52390 void FindCookiesForRegistryControlledHost(
391 const GURL& url,
392 std::vector<CanonicalCookie*>* cookies);
[email protected]63ee33bd2012-03-15 09:29:58393
Lily Chenf068a762019-08-21 21:10:50394 void FilterCookiesWithOptions(const GURL url,
395 const CookieOptions options,
396 std::vector<CanonicalCookie*>* cookie_ptrs,
397 CookieStatusList* included_cookies,
398 CookieStatusList* excluded_cookies);
399
Lily Chen4c5f8632019-10-30 18:11:51400 // Possibly delete an existing cookie equivalent to |cookie_being_set| (same
401 // path, domain, and name).
Mike Westc4a777b2017-10-06 14:04:20402 //
Lily Chen4c5f8632019-10-30 18:11:51403 // |source_secure| indicates if the source may override existing secure
404 // cookies. If the source is not secure, and there is an existing "equivalent"
405 // cookie that is Secure, that cookie will be preserved, under "Leave Secure
406 // Cookies Alone" (see
407 // https://tools.ietf.org/html/draft-ietf-httpbis-cookie-alone-01).
408 // ("equivalent" here is in quotes because the equivalency check for the
409 // purposes of preserving existing Secure cookies is slightly more inclusive.)
410 //
411 // If |skip_httponly| is true, httponly cookies will not be deleted even if
412 // they are equivalent.
413 // |key| is the key to find the cookie in cookies_; see the comment before the
jwwa26e439d2017-01-27 18:17:27414 // CookieMap typedef for details.
Mike Westc4a777b2017-10-06 14:04:20415 //
Lily Chen4c5f8632019-10-30 18:11:51416 // If a cookie is deleted, and its value matches |cookie_being_set|'s value,
417 // then |creation_date_to_inherit| will be set to that cookie's creation date.
Mike Westc4a777b2017-10-06 14:04:20418 //
Lily Chenf53dfbcd2019-08-30 01:42:10419 // The cookie will not be deleted if |*status| is not "include" when calling
420 // the function. The function will update |*status| with exclusion reasons if
421 // a secure cookie was skipped or an httponly cookie was skipped.
422 //
[email protected]63ee33bd2012-03-15 09:29:58423 // NOTE: There should never be more than a single matching equivalent cookie.
Lily Chenf53dfbcd2019-08-30 01:42:10424 void MaybeDeleteEquivalentCookieAndUpdateStatus(
Aaron Tagliaboschi29764f52019-02-21 17:19:59425 const std::string& key,
Lily Chen4c5f8632019-10-30 18:11:51426 const CanonicalCookie& cookie_being_set,
Aaron Tagliaboschi29764f52019-02-21 17:19:59427 bool source_secure,
428 bool skip_httponly,
429 bool already_expired,
Lily Chenf53dfbcd2019-08-30 01:42:10430 base::Time* creation_date_to_inherit,
431 CanonicalCookie::CookieInclusionStatus* status);
[email protected]63ee33bd2012-03-15 09:29:58432
Lily Chenb0ca3f72019-12-05 18:06:29433 // This is only used if the RecentCreationTimeGrantsLegacyCookieSemantics
434 // feature is enabled. It finds an equivalent cookie (based on name, domain,
435 // path) with the same value, if there is any, and returns its creation time,
436 // or the creation time of the |cookie| itself, if there is none.
437 base::Time EffectiveCreationTimeForMaybePreexistingCookie(
438 const std::string& key,
439 const CanonicalCookie& cookie) const;
440
avie7cd11a2016-10-11 02:00:35441 // Inserts |cc| into cookies_. Returns an iterator that points to the inserted
[email protected]6210ce52013-09-20 03:33:14442 // cookie in cookies_. Guarantee: all iterators to cookies_ remain valid.
443 CookieMap::iterator InternalInsertCookie(const std::string& key,
avie7cd11a2016-10-11 02:00:35444 std::unique_ptr<CanonicalCookie> cc,
[email protected]6210ce52013-09-20 03:33:14445 bool sync_to_store);
[email protected]63ee33bd2012-03-15 09:29:58446
rdsmith2709eee2017-06-20 22:43:27447 // Sets all cookies from |list| after deleting any equivalent cookie.
448 // For data gathering purposes, this routine is treated as if it is
449 // restoring saved cookies; some statistics are not gathered in this case.
rdsmithe5c701d2017-07-12 21:50:00450 void SetAllCookies(CookieList list, SetCookiesCallback callback);
drogerd5d1278c2015-03-17 19:21:51451
[email protected]63ee33bd2012-03-15 09:29:58452 void InternalUpdateCookieAccessTime(CanonicalCookie* cc,
453 const base::Time& current_time);
454
455 // |deletion_cause| argument is used for collecting statistics and choosing
Victor Costan14f47c12018-03-01 08:02:24456 // the correct CookieChangeCause for OnCookieChange notifications. Guarantee:
457 // All iterators to cookies_, except for the deleted entry, remain valid.
mkwstbe84af312015-02-20 08:52:45458 void InternalDeleteCookie(CookieMap::iterator it,
459 bool sync_to_store,
[email protected]63ee33bd2012-03-15 09:29:58460 DeletionCause deletion_cause);
461
462 // If the number of cookies for CookieMap key |key|, or globally, are
463 // over the preset maximums above, garbage collect, first for the host and
464 // then globally. See comments above garbage collection threshold
465 // constants for details.
466 //
467 // Returns the number of cookies deleted (useful for debugging).
jwwa26e439d2017-01-27 18:17:27468 size_t GarbageCollect(const base::Time& current, const std::string& key);
[email protected]63ee33bd2012-03-15 09:29:58469
mkwste079ac412016-03-11 09:04:06470 // Helper for GarbageCollect(). Deletes up to |purge_goal| cookies with a
471 // priority less than or equal to |priority| from |cookies|, while ensuring
472 // that at least the |to_protect| most-recent cookies are retained.
jwwc00ac712016-05-05 22:21:44473 // |protected_secure_cookies| specifies whether or not secure cookies should
474 // be protected from deletion.
mkwste079ac412016-03-11 09:04:06475 //
476 // |cookies| must be sorted from least-recent to most-recent.
477 //
mkwste079ac412016-03-11 09:04:06478 // Returns the number of cookies deleted.
479 size_t PurgeLeastRecentMatches(CookieItVector* cookies,
480 CookiePriority priority,
481 size_t to_protect,
jwwc00ac712016-05-05 22:21:44482 size_t purge_goal,
483 bool protect_secure_cookies);
mkwste079ac412016-03-11 09:04:06484
jww82d99c12015-11-25 18:39:53485 // Helper for GarbageCollect(); can be called directly as well. Deletes all
486 // expired cookies in |itpair|. If |cookie_its| is non-NULL, all the
487 // non-expired cookies from |itpair| are appended to |cookie_its|.
[email protected]63ee33bd2012-03-15 09:29:58488 //
489 // Returns the number of cookies deleted.
jww82d99c12015-11-25 18:39:53490 size_t GarbageCollectExpired(const base::Time& current,
491 const CookieMapItPair& itpair,
492 CookieItVector* cookie_its);
493
[email protected]8ad5d462013-05-02 08:45:26494 // Helper for GarbageCollect(). Deletes all cookies in the range specified by
495 // [|it_begin|, |it_end|). Returns the number of cookies deleted.
jww82d99c12015-11-25 18:39:53496 size_t GarbageCollectDeleteRange(const base::Time& current,
497 DeletionCause cause,
498 CookieItVector::iterator cookie_its_begin,
499 CookieItVector::iterator cookie_its_end);
500
501 // Helper for GarbageCollect(). Deletes cookies in |cookie_its| from least to
502 // most recently used, but only before |safe_date|. Also will stop deleting
503 // when the number of remaining cookies hits |purge_goal|.
mmenkef4721d992017-06-07 17:13:59504 //
505 // Sets |earliest_time| to be the earliest last access time of a cookie that
506 // was not deleted, or base::Time() if no such cookie exists.
jww82d99c12015-11-25 18:39:53507 size_t GarbageCollectLeastRecentlyAccessed(const base::Time& current,
508 const base::Time& safe_date,
509 size_t purge_goal,
mmenkef4721d992017-06-07 17:13:59510 CookieItVector cookie_its,
511 base::Time* earliest_time);
[email protected]63ee33bd2012-03-15 09:29:58512
[email protected]63ee33bd2012-03-15 09:29:58513 bool HasCookieableScheme(const GURL& url);
514
Lily Chene7295b12019-12-04 00:23:30515 // Get the cookie's access semantics (LEGACY or NONLEGACY), considering any
Lily Chenb0ca3f72019-12-05 18:06:29516 // features granting legacy semantics for special conditions (if any are
517 // active and meet the conditions for granting legacy access, pass true for
518 // |legacy_semantics_granted|). If none are active, this then checks for a
519 // value from the cookie access delegate, if it is non-null. Otherwise returns
520 // UNKNOWN.
Lily Chen70f997f2019-10-07 22:01:37521 CookieAccessSemantics GetAccessSemanticsForCookie(
Lily Chenb0ca3f72019-12-05 18:06:29522 const CanonicalCookie& cookie,
523 bool legacy_semantics_granted) const;
524
525 // This is called for getting a cookie.
526 CookieAccessSemantics GetAccessSemanticsForCookieGet(
Lily Chen70f997f2019-10-07 22:01:37527 const CanonicalCookie& cookie) const;
528
Lily Chene7295b12019-12-04 00:23:30529 // This is called for setting a cookie with the options specified by
Lily Chenb0ca3f72019-12-05 18:06:29530 // |options|. For setting a cookie, a same-site access is lax or better (since
Lily Chene7295b12019-12-04 00:23:30531 // CookieOptions for setting a cookie will never be strict).
Lily Chenb0ca3f72019-12-05 18:06:29532 // |effective_creation_time| is the time that should be used for deciding
533 // whether the RecentCreationTimeGrantsLegacyCookieSemantics feature should
534 // grant legacy semantics. This may differ from the CreationDate() field of
535 // the cookie, if there was a preexisting equivalent cookie (in which case it
536 // is the creation time of that equivalent cookie).
Lily Chene7295b12019-12-04 00:23:30537 CookieAccessSemantics GetAccessSemanticsForCookieSet(
538 const CanonicalCookie& cookie,
Lily Chenb0ca3f72019-12-05 18:06:29539 const CookieOptions& options,
540 base::Time effective_creation_time) const;
Lily Chene7295b12019-12-04 00:23:30541
542 // Looks up the last time a cookie matching the (name, domain, path) of
543 // |cookie| was accessed in a same-site context permitting HttpOnly
544 // cookie access. If there was none, this returns a null base::Time.
545 // Returns null value if RecentHttpSameSiteAccessGrantsLegacyCookieSemantics
546 // is not enabled.
547 base::TimeTicks LastAccessFromHttpSameSiteContext(
548 const CanonicalCookie& cookie) const;
549
550 // Updates |last_http_same_site_accesses_| with the current time if the
551 // |options| are appropriate (same-site and permits HttpOnly access).
552 // |is_set| is true if the access is setting the cookie, false otherwise (e.g.
553 // if getting the cookie). Does nothing if
554 // RecentHttpSameSiteAccessGrantsLegacyCookieSemantics is not enabled.
555 void MaybeRecordCookieAccessWithOptions(const CanonicalCookie& cookie,
556 const CookieOptions& options,
557 bool is_set);
558
[email protected]63ee33bd2012-03-15 09:29:58559 // Statistics support
560
561 // This function should be called repeatedly, and will record
562 // statistics if a sufficient time period has passed.
563 void RecordPeriodicStats(const base::Time& current_time);
564
565 // Initialize the above variables; should only be called from
566 // the constructor.
567 void InitializeHistograms();
568
Maks Orlovich323efaf2018-03-06 02:56:39569 // Defers the callback until the full coookie database has been loaded. If
570 // it's already been loaded, runs the callback synchronously.
rdsmithe5c701d2017-07-12 21:50:00571 void DoCookieCallback(base::OnceClosure callback);
[email protected]63ee33bd2012-03-15 09:29:58572
Maks Orlovich323efaf2018-03-06 02:56:39573 // Defers the callback until the cookies relevant to given URL have been
574 // loaded. If they've already been loaded, runs the callback synchronously.
rdsmithe5c701d2017-07-12 21:50:00575 void DoCookieCallbackForURL(base::OnceClosure callback, const GURL& url);
[email protected]63ee33bd2012-03-15 09:29:58576
Maks Orlovich323efaf2018-03-06 02:56:39577 // Defers the callback until the cookies relevant to given host or domain
578 // have been loaded. If they've already been loaded, runs the callback
579 // synchronously.
580 void DoCookieCallbackForHostOrDomain(base::OnceClosure callback,
581 base::StringPiece host_or_domain);
582
[email protected]63ee33bd2012-03-15 09:29:58583 // Histogram variables; see CookieMonster::InitializeHistograms() in
584 // cookie_monster.cc for details.
[email protected]de415552013-01-23 04:12:17585 base::HistogramBase* histogram_expiration_duration_minutes_;
[email protected]de415552013-01-23 04:12:17586 base::HistogramBase* histogram_count_;
mkwstc1aa4cc2015-04-03 19:57:45587 base::HistogramBase* histogram_cookie_type_;
estark7feb65c2b2015-08-21 23:38:20588 base::HistogramBase* histogram_cookie_source_scheme_;
[email protected]de415552013-01-23 04:12:17589 base::HistogramBase* histogram_time_blocked_on_load_;
[email protected]63ee33bd2012-03-15 09:29:58590
591 CookieMap cookies_;
592
Victor Costan14f47c12018-03-01 08:02:24593 CookieMonsterChangeDispatcher change_dispatcher_;
594
erikchen1dd72a72015-05-06 20:45:05595 // Indicates whether the cookie store has been initialized.
[email protected]63ee33bd2012-03-15 09:29:58596 bool initialized_;
597
erikchen1dd72a72015-05-06 20:45:05598 // Indicates whether the cookie store has started fetching all cookies.
599 bool started_fetching_all_cookies_;
600 // Indicates whether the cookie store has finished fetching all cookies.
601 bool finished_fetching_all_cookies_;
[email protected]63ee33bd2012-03-15 09:29:58602
603 // List of domain keys that have been loaded from the DB.
604 std::set<std::string> keys_loaded_;
605
606 // Map of domain keys to their associated task queues. These tasks are blocked
607 // until all cookies for the associated domain key eTLD+1 are loaded from the
608 // backend store.
Brett Wilsonc6a0c822017-09-12 00:04:29609 std::map<std::string, base::circular_deque<base::OnceClosure>>
610 tasks_pending_for_key_;
[email protected]63ee33bd2012-03-15 09:29:58611
612 // Queues tasks that are blocked until all cookies are loaded from the backend
613 // store.
Brett Wilsonc6a0c822017-09-12 00:04:29614 base::circular_deque<base::OnceClosure> tasks_pending_;
mmenkef49fca0e2016-03-08 12:46:24615
616 // Once a global cookie task has been seen, all per-key tasks must be put in
617 // |tasks_pending_| instead of |tasks_pending_for_key_| to ensure a reasonable
rdsmithe5c701d2017-07-12 21:50:00618 // view of the cookie store. This is more to ensure fancy cookie export/import
mmenkef49fca0e2016-03-08 12:46:24619 // code has a consistent view of the CookieStore, rather than out of concern
620 // for typical use.
621 bool seen_global_task_;
[email protected]63ee33bd2012-03-15 09:29:58622
Helen Licd0fab862018-08-13 16:07:53623 NetLogWithSource net_log_;
624
[email protected]63ee33bd2012-03-15 09:29:58625 scoped_refptr<PersistentCookieStore> store_;
626
[email protected]63ee33bd2012-03-15 09:29:58627 // Minimum delay after updating a cookie's LastAccessDate before we will
628 // update it again.
629 const base::TimeDelta last_access_threshold_;
630
631 // Approximate date of access time of least recently accessed cookie
632 // in |cookies_|. Note that this is not guaranteed to be accurate, only a)
633 // to be before or equal to the actual time, and b) to be accurate
mmenkef4721d992017-06-07 17:13:59634 // immediately after a garbage collection that scans through all the cookies
635 // (When garbage collection does not scan through all cookies, it may not be
636 // updated). This value is used to determine whether global garbage collection
637 // might find cookies to purge. Note: The default Time() constructor will
638 // create a value that compares earlier than any other time value, which is
639 // wanted. Thus this value is not initialized.
[email protected]63ee33bd2012-03-15 09:29:58640 base::Time earliest_access_time_;
641
Lily Chene7295b12019-12-04 00:23:30642 // Records the last access to a cookie (either getting or setting) from a
643 // context that is both same-site and permits HttpOnly access.
644 // The access is considered same-site if it is at least laxly same-site for
645 // set, or strictly same-site for get.
646 // This information is used to determine if the feature
647 // kRecentSameSiteAccessGrantsLegacyCookieSemantics should grant legacy
648 // access semantics to a cookie for subsequent accesses.
649 // This map is not used if that feature is not enabled.
650 std::map<CanonicalCookie::UniqueCookieKey, base::TimeTicks>
651 last_http_same_site_accesses_;
652
[email protected]63ee33bd2012-03-15 09:29:58653 std::vector<std::string> cookieable_schemes_;
654
[email protected]63ee33bd2012-03-15 09:29:58655 base::Time last_statistic_record_time_;
656
[email protected]63ee33bd2012-03-15 09:29:58657 bool persist_session_cookies_;
658
mmenkebe0910d2016-03-01 19:09:09659 base::ThreadChecker thread_checker_;
660
Jeremy Romand54000b22019-07-08 18:40:16661 base::WeakPtrFactory<CookieMonster> weak_ptr_factory_{this};
mmenkebe0910d2016-03-01 19:09:09662
[email protected]63ee33bd2012-03-15 09:29:58663 DISALLOW_COPY_AND_ASSIGN(CookieMonster);
664};
665
[email protected]63ee33bd2012-03-15 09:29:58666typedef base::RefCountedThreadSafe<CookieMonster::PersistentCookieStore>
667 RefcountedPersistentCookieStore;
668
[email protected]c1b6e102013-04-10 20:54:49669class NET_EXPORT CookieMonster::PersistentCookieStore
[email protected]63ee33bd2012-03-15 09:29:58670 : public RefcountedPersistentCookieStore {
671 public:
Maks Orlovich108cb4c2019-03-26 20:24:57672 typedef base::OnceCallback<void(
673 std::vector<std::unique_ptr<CanonicalCookie>>)>
[email protected]5b9bc352012-07-18 13:13:34674 LoadedCallback;
[email protected]63ee33bd2012-03-15 09:29:58675
676 // Initializes the store and retrieves the existing cookies. This will be
677 // called only once at startup. The callback will return all the cookies
678 // that are not yet returned to CookieMonster by previous priority loads.
mmenkebe0910d2016-03-01 19:09:09679 //
680 // |loaded_callback| may not be NULL.
Helen Li92a29f102018-08-15 23:02:26681 // |net_log| is a NetLogWithSource that may be copied if the persistent
682 // store wishes to log NetLog events.
Maks Orlovich108cb4c2019-03-26 20:24:57683 virtual void Load(LoadedCallback loaded_callback,
Helen Li92a29f102018-08-15 23:02:26684 const NetLogWithSource& net_log) = 0;
[email protected]63ee33bd2012-03-15 09:29:58685
686 // Does a priority load of all cookies for the domain key (eTLD+1). The
687 // callback will return all the cookies that are not yet returned by previous
688 // loads, which includes cookies for the requested domain key if they are not
689 // already returned, plus all cookies that are chain-loaded and not yet
690 // returned to CookieMonster.
mmenkebe0910d2016-03-01 19:09:09691 //
692 // |loaded_callback| may not be NULL.
[email protected]63ee33bd2012-03-15 09:29:58693 virtual void LoadCookiesForKey(const std::string& key,
Maks Orlovich108cb4c2019-03-26 20:24:57694 LoadedCallback loaded_callback) = 0;
[email protected]63ee33bd2012-03-15 09:29:58695
696 virtual void AddCookie(const CanonicalCookie& cc) = 0;
697 virtual void UpdateCookieAccessTime(const CanonicalCookie& cc) = 0;
698 virtual void DeleteCookie(const CanonicalCookie& cc) = 0;
699
[email protected]bf510ed2012-06-05 08:31:43700 // Instructs the store to not discard session only cookies on shutdown.
701 virtual void SetForceKeepSessionState() = 0;
[email protected]63ee33bd2012-03-15 09:29:58702
Nick Harper14e23332017-07-28 00:27:23703 // Sets a callback that will be run before the store flushes. If |callback|
704 // performs any async operations, the store will not wait for those to finish
705 // before flushing.
Lily Chen9934f7e2019-03-13 19:16:55706 virtual void SetBeforeCommitCallback(base::RepeatingClosure callback) = 0;
Nick Harper14e23332017-07-28 00:27:23707
mmenkebe0910d2016-03-01 19:09:09708 // Flushes the store and posts |callback| when complete. |callback| may be
709 // NULL.
rdsmith7ac81712017-06-22 17:09:54710 virtual void Flush(base::OnceClosure callback) = 0;
[email protected]63ee33bd2012-03-15 09:29:58711
712 protected:
713 PersistentCookieStore() {}
[email protected]a9813302012-04-28 09:29:28714 virtual ~PersistentCookieStore() {}
[email protected]63ee33bd2012-03-15 09:29:58715
716 private:
[email protected]a9813302012-04-28 09:29:28717 friend class base::RefCountedThreadSafe<PersistentCookieStore>;
[email protected]63ee33bd2012-03-15 09:29:58718 DISALLOW_COPY_AND_ASSIGN(PersistentCookieStore);
719};
720
[email protected]63ee33bd2012-03-15 09:29:58721} // namespace net
722
723#endif // NET_COOKIES_COOKIE_MONSTER_H_