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