blob: 037d1b791d56d4f9bfcbbd413661341cf3d0c666 [file] [log] [blame]
[email protected]8e1583672012-02-11 04:39:411// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit586acc5fe2008-07-26 22:42:524
5// Portions of this code based on Mozilla:
6// (netwerk/cookie/src/nsCookieService.cpp)
7/* ***** BEGIN LICENSE BLOCK *****
8 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
9 *
10 * The contents of this file are subject to the Mozilla Public License Version
11 * 1.1 (the "License"); you may not use this file except in compliance with
12 * the License. You may obtain a copy of the License at
13 * http://www.mozilla.org/MPL/
14 *
15 * Software distributed under the License is distributed on an "AS IS" basis,
16 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
17 * for the specific language governing rights and limitations under the
18 * License.
19 *
20 * The Original Code is mozilla.org code.
21 *
22 * The Initial Developer of the Original Code is
23 * Netscape Communications Corporation.
24 * Portions created by the Initial Developer are Copyright (C) 2003
25 * the Initial Developer. All Rights Reserved.
26 *
27 * Contributor(s):
28 * Daniel Witte ([email protected])
29 * Michiel van Leeuwen ([email protected])
30 *
31 * Alternatively, the contents of this file may be used under the terms of
32 * either the GNU General Public License Version 2 or later (the "GPL"), or
33 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
34 * in which case the provisions of the GPL or the LGPL are applicable instead
35 * of those above. If you wish to allow use of your version of this file only
36 * under the terms of either the GPL or the LGPL, and not to allow others to
37 * use your version of this file under the terms of the MPL, indicate your
38 * decision by deleting the provisions above and replace them with the notice
39 * and other provisions required by the GPL or the LGPL. If you do not delete
40 * the provisions above, a recipient may use your version of this file under
41 * the terms of any one of the MPL, the GPL or the LGPL.
42 *
43 * ***** END LICENSE BLOCK ***** */
44
[email protected]63ee33bd2012-03-15 09:29:5845#include "net/cookies/cookie_monster.h"
initial.commit586acc5fe2008-07-26 22:42:5246
47#include <algorithm>
[email protected]8ad5d462013-05-02 08:45:2648#include <functional>
[email protected]09666482011-07-12 12:50:4049#include <set>
initial.commit586acc5fe2008-07-26 22:42:5250
51#include "base/basictypes.h"
[email protected]218aa6a12011-09-13 17:38:3852#include "base/bind.h"
[email protected]8562034e2011-10-17 17:35:0453#include "base/callback.h"
skyostil4891b25b2015-06-11 11:43:4554#include "base/location.h"
initial.commit586acc5fe2008-07-26 22:42:5255#include "base/logging.h"
[email protected]3b63f8f42011-03-28 01:54:1556#include "base/memory/scoped_ptr.h"
erikchen1dd72a72015-05-06 20:45:0557#include "base/metrics/field_trial.h"
[email protected]835d7c82010-10-14 04:38:3858#include "base/metrics/histogram.h"
pkastingb60049a2015-02-07 03:25:2559#include "base/profiler/scoped_tracker.h"
anujk.sharmaafc45172015-05-15 00:50:3460#include "base/single_thread_task_runner.h"
[email protected]4b355212013-06-11 10:35:1961#include "base/strings/string_util.h"
62#include "base/strings/stringprintf.h"
anujk.sharmaafc45172015-05-15 00:50:3463#include "base/thread_task_runner_handle.h"
[email protected]be28b5f42012-07-20 11:31:2564#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
[email protected]4b355212013-06-11 10:35:1965#include "net/cookies/canonical_cookie.h"
[email protected]63ee33bd2012-03-15 09:29:5866#include "net/cookies/cookie_util.h"
[email protected]ebfe3172012-07-12 12:21:4167#include "net/cookies/parsed_cookie.h"
mkwst8241a122015-10-20 07:15:1068#include "url/origin.h"
initial.commit586acc5fe2008-07-26 22:42:5269
[email protected]e1acf6f2008-10-27 20:43:3370using base::Time;
71using base::TimeDelta;
[email protected]7a964a72010-09-07 19:33:2672using base::TimeTicks;
[email protected]e1acf6f2008-10-27 20:43:3373
[email protected]8562034e2011-10-17 17:35:0474// In steady state, most cookie requests can be satisfied by the in memory
erikchen1dd72a72015-05-06 20:45:0575// cookie monster store. If the cookie request cannot be satisfied by the in
76// memory store, the relevant cookies must be fetched from the persistent
77// store. The task is queued in CookieMonster::tasks_pending_ if it requires
78// all cookies to be loaded from the backend, or tasks_pending_for_key_ if it
79// only requires all cookies associated with an eTLD+1.
[email protected]8562034e2011-10-17 17:35:0480//
81// On the browser critical paths (e.g. for loading initial web pages in a
82// session restore) it may take too long to wait for the full load. If a cookie
83// request is for a specific URL, DoCookieTaskForURL is called, which triggers a
84// priority load if the key is not loaded yet by calling PersistentCookieStore
[email protected]0184df32013-05-14 00:53:5585// :: LoadCookiesForKey. The request is queued in
86// CookieMonster::tasks_pending_for_key_ and executed upon receiving
87// notification of key load completion via CookieMonster::OnKeyLoaded(). If
88// multiple requests for the same eTLD+1 are received before key load
89// completion, only the first request calls
[email protected]8562034e2011-10-17 17:35:0490// PersistentCookieStore::LoadCookiesForKey, all subsequent requests are queued
[email protected]0184df32013-05-14 00:53:5591// in CookieMonster::tasks_pending_for_key_ and executed upon receiving
92// notification of key load completion triggered by the first request for the
93// same eTLD+1.
[email protected]8562034e2011-10-17 17:35:0494
[email protected]c4058fb2010-06-22 17:25:2695static const int kMinutesInTenYears = 10 * 365 * 24 * 60;
96
erikchen1dd72a72015-05-06 20:45:0597namespace {
98
99const char kFetchWhenNecessaryName[] = "FetchWhenNecessary";
100const char kAlwaysFetchName[] = "AlwaysFetch";
101const char kCookieMonsterFetchStrategyName[] = "CookieMonsterFetchStrategy";
102
103} // namespace
104
[email protected]8ac1a752008-07-31 19:40:37105namespace net {
106
[email protected]7a964a72010-09-07 19:33:26107// See comments at declaration of these variables in cookie_monster.h
108// for details.
mkwstbe84af312015-02-20 08:52:45109const size_t CookieMonster::kDomainMaxCookies = 180;
110const size_t CookieMonster::kDomainPurgeCookies = 30;
111const size_t CookieMonster::kMaxCookies = 3300;
112const size_t CookieMonster::kPurgeCookies = 300;
[email protected]8ad5d462013-05-02 08:45:26113
mkwstbe84af312015-02-20 08:52:45114const size_t CookieMonster::kDomainCookiesQuotaLow = 30;
[email protected]8ad5d462013-05-02 08:45:26115const size_t CookieMonster::kDomainCookiesQuotaMedium = 50;
mkwstbe84af312015-02-20 08:52:45116const size_t CookieMonster::kDomainCookiesQuotaHigh =
117 kDomainMaxCookies - kDomainPurgeCookies - kDomainCookiesQuotaLow -
118 kDomainCookiesQuotaMedium;
[email protected]8ad5d462013-05-02 08:45:26119
mkwstbe84af312015-02-20 08:52:45120const int CookieMonster::kSafeFromGlobalPurgeDays = 30;
[email protected]297a4ed02010-02-12 08:12:52121
[email protected]7a964a72010-09-07 19:33:26122namespace {
[email protected]e32306c52008-11-06 16:59:05123
[email protected]6210ce52013-09-20 03:33:14124bool ContainsControlCharacter(const std::string& s) {
125 for (std::string::const_iterator i = s.begin(); i != s.end(); ++i) {
126 if ((*i >= 0) && (*i <= 31))
127 return true;
128 }
129
130 return false;
131}
132
[email protected]5b9bc352012-07-18 13:13:34133typedef std::vector<CanonicalCookie*> CanonicalCookieVector;
[email protected]34a160d2011-05-12 22:12:49134
[email protected]77e0a462008-11-01 00:43:35135// Default minimum delay after updating a cookie's LastAccessDate before we
136// will update it again.
[email protected]297a4ed02010-02-12 08:12:52137const int kDefaultAccessUpdateThresholdSeconds = 60;
138
139// Comparator to sort cookies from highest creation date to lowest
140// creation date.
141struct OrderByCreationTimeDesc {
142 bool operator()(const CookieMonster::CookieMap::iterator& a,
143 const CookieMonster::CookieMap::iterator& b) const {
144 return a->second->CreationDate() > b->second->CreationDate();
145 }
146};
147
[email protected]4d3ce782010-10-29 18:31:28148// Constants for use in VLOG
149const int kVlogPerCookieMonster = 1;
[email protected]4d3ce782010-10-29 18:31:28150const int kVlogGarbageCollection = 5;
151const int kVlogSetCookies = 7;
152const int kVlogGetCookies = 9;
153
[email protected]f48b9432011-01-11 07:25:40154// Mozilla sorts on the path length (longest first), and then it
155// sorts by creation time (oldest first).
156// The RFC says the sort order for the domain attribute is undefined.
[email protected]5b9bc352012-07-18 13:13:34157bool CookieSorter(CanonicalCookie* cc1, CanonicalCookie* cc2) {
[email protected]f48b9432011-01-11 07:25:40158 if (cc1->Path().length() == cc2->Path().length())
159 return cc1->CreationDate() < cc2->CreationDate();
160 return cc1->Path().length() > cc2->Path().length();
initial.commit586acc5fe2008-07-26 22:42:52161}
162
[email protected]8ad5d462013-05-02 08:45:26163bool LRACookieSorter(const CookieMonster::CookieMap::iterator& it1,
[email protected]f48b9432011-01-11 07:25:40164 const CookieMonster::CookieMap::iterator& it2) {
165 // Cookies accessed less recently should be deleted first.
166 if (it1->second->LastAccessDate() != it2->second->LastAccessDate())
167 return it1->second->LastAccessDate() < it2->second->LastAccessDate();
initial.commit586acc5fe2008-07-26 22:42:52168
[email protected]f48b9432011-01-11 07:25:40169 // In rare cases we might have two cookies with identical last access times.
170 // To preserve the stability of the sort, in these cases prefer to delete
171 // older cookies over newer ones. CreationDate() is guaranteed to be unique.
172 return it1->second->CreationDate() < it2->second->CreationDate();
[email protected]297a4ed02010-02-12 08:12:52173}
174
drogerd5d1278c2015-03-17 19:21:51175// Compare cookies using name, domain and path, so that "equivalent" cookies
176// (per RFC 2965) are equal to each other.
ttuttle859dc7a2015-04-23 19:42:29177bool PartialDiffCookieSorter(const CanonicalCookie& a,
178 const CanonicalCookie& b) {
drogerd5d1278c2015-03-17 19:21:51179 return a.PartialCompare(b);
180}
181
182// This is a stricter ordering than PartialDiffCookieOrdering, where all fields
183// are used.
ttuttle859dc7a2015-04-23 19:42:29184bool FullDiffCookieSorter(const CanonicalCookie& a, const CanonicalCookie& b) {
drogerd5d1278c2015-03-17 19:21:51185 return a.FullCompare(b);
186}
187
[email protected]297a4ed02010-02-12 08:12:52188// Our strategy to find duplicates is:
189// (1) Build a map from (cookiename, cookiepath) to
190// {list of cookies with this signature, sorted by creation time}.
191// (2) For each list with more than 1 entry, keep the cookie having the
192// most recent creation time, and delete the others.
[email protected]f48b9432011-01-11 07:25:40193//
[email protected]1655ba342010-07-14 18:17:42194// Two cookies are considered equivalent if they have the same domain,
195// name, and path.
196struct CookieSignature {
197 public:
[email protected]dedec0b2013-02-28 04:50:10198 CookieSignature(const std::string& name,
199 const std::string& domain,
[email protected]1655ba342010-07-14 18:17:42200 const std::string& path)
mkwstbe84af312015-02-20 08:52:45201 : name(name), domain(domain), path(path) {}
[email protected]1655ba342010-07-14 18:17:42202
203 // To be a key for a map this class needs to be assignable, copyable,
204 // and have an operator<. The default assignment operator
205 // and copy constructor are exactly what we want.
206
207 bool operator<(const CookieSignature& cs) const {
208 // Name compare dominates, then domain, then path.
209 int diff = name.compare(cs.name);
210 if (diff != 0)
211 return diff < 0;
212
213 diff = domain.compare(cs.domain);
214 if (diff != 0)
215 return diff < 0;
216
217 return path.compare(cs.path) < 0;
218 }
219
220 std::string name;
221 std::string domain;
222 std::string path;
223};
[email protected]f48b9432011-01-11 07:25:40224
[email protected]8ad5d462013-05-02 08:45:26225// For a CookieItVector iterator range [|it_begin|, |it_end|),
226// sorts the first |num_sort| + 1 elements by LastAccessDate().
227// The + 1 element exists so for any interval of length <= |num_sort| starting
228// from |cookies_its_begin|, a LastAccessDate() bound can be found.
mkwstbe84af312015-02-20 08:52:45229void SortLeastRecentlyAccessed(CookieMonster::CookieItVector::iterator it_begin,
230 CookieMonster::CookieItVector::iterator it_end,
231 size_t num_sort) {
[email protected]8ad5d462013-05-02 08:45:26232 DCHECK_LT(static_cast<int>(num_sort), it_end - it_begin);
233 std::partial_sort(it_begin, it_begin + num_sort + 1, it_end, LRACookieSorter);
234}
[email protected]f48b9432011-01-11 07:25:40235
[email protected]8ad5d462013-05-02 08:45:26236// Predicate to support PartitionCookieByPriority().
237struct CookiePriorityEqualsTo
238 : std::unary_function<const CookieMonster::CookieMap::iterator, bool> {
[email protected]5edff3c52014-06-23 20:27:48239 explicit CookiePriorityEqualsTo(CookiePriority priority)
mkwstbe84af312015-02-20 08:52:45240 : priority_(priority) {}
[email protected]8ad5d462013-05-02 08:45:26241
242 bool operator()(const CookieMonster::CookieMap::iterator it) const {
243 return it->second->Priority() == priority_;
[email protected]f48b9432011-01-11 07:25:40244 }
[email protected]8ad5d462013-05-02 08:45:26245
246 const CookiePriority priority_;
247};
248
249// For a CookieItVector iterator range [|it_begin|, |it_end|),
250// moves all cookies with a given |priority| to the beginning of the list.
251// Returns: An iterator in [it_begin, it_end) to the first element with
252// priority != |priority|, or |it_end| if all have priority == |priority|.
253CookieMonster::CookieItVector::iterator PartitionCookieByPriority(
254 CookieMonster::CookieItVector::iterator it_begin,
255 CookieMonster::CookieItVector::iterator it_end,
256 CookiePriority priority) {
257 return std::partition(it_begin, it_end, CookiePriorityEqualsTo(priority));
258}
259
mkwstbe84af312015-02-20 08:52:45260bool LowerBoundAccessDateComparator(const CookieMonster::CookieMap::iterator it,
261 const Time& access_date) {
[email protected]8ad5d462013-05-02 08:45:26262 return it->second->LastAccessDate() < access_date;
263}
264
265// For a CookieItVector iterator range [|it_begin|, |it_end|)
266// from a CookieItVector sorted by LastAccessDate(), returns the
267// first iterator with access date >= |access_date|, or cookie_its_end if this
268// holds for all.
269CookieMonster::CookieItVector::iterator LowerBoundAccessDate(
270 const CookieMonster::CookieItVector::iterator its_begin,
271 const CookieMonster::CookieItVector::iterator its_end,
272 const Time& access_date) {
273 return std::lower_bound(its_begin, its_end, access_date,
274 LowerBoundAccessDateComparator);
[email protected]7a964a72010-09-07 19:33:26275}
276
[email protected]7c4b66b2014-01-04 12:28:13277// Mapping between DeletionCause and CookieMonsterDelegate::ChangeCause; the
278// mapping also provides a boolean that specifies whether or not an
279// OnCookieChanged notification ought to be generated.
[email protected]8bb846f2011-03-23 12:08:18280typedef struct ChangeCausePair_struct {
[email protected]7c4b66b2014-01-04 12:28:13281 CookieMonsterDelegate::ChangeCause cause;
[email protected]8bb846f2011-03-23 12:08:18282 bool notify;
283} ChangeCausePair;
284ChangeCausePair ChangeCauseMapping[] = {
mkwstbe84af312015-02-20 08:52:45285 // DELETE_COOKIE_EXPLICIT
286 {CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT, true},
287 // DELETE_COOKIE_OVERWRITE
288 {CookieMonsterDelegate::CHANGE_COOKIE_OVERWRITE, true},
289 // DELETE_COOKIE_EXPIRED
290 {CookieMonsterDelegate::CHANGE_COOKIE_EXPIRED, true},
291 // DELETE_COOKIE_EVICTED
292 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
293 // DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE
294 {CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT, false},
295 // DELETE_COOKIE_DONT_RECORD
296 {CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT, false},
297 // DELETE_COOKIE_EVICTED_DOMAIN
298 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
299 // DELETE_COOKIE_EVICTED_GLOBAL
300 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
301 // DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE
302 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
303 // DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE
304 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
305 // DELETE_COOKIE_EXPIRED_OVERWRITE
306 {CookieMonsterDelegate::CHANGE_COOKIE_EXPIRED_OVERWRITE, true},
307 // DELETE_COOKIE_CONTROL_CHAR
308 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
309 // DELETE_COOKIE_LAST_ENTRY
310 {CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT, false}};
[email protected]8bb846f2011-03-23 12:08:18311
[email protected]34a160d2011-05-12 22:12:49312std::string BuildCookieLine(const CanonicalCookieVector& cookies) {
313 std::string cookie_line;
314 for (CanonicalCookieVector::const_iterator it = cookies.begin();
315 it != cookies.end(); ++it) {
316 if (it != cookies.begin())
317 cookie_line += "; ";
318 // In Mozilla if you set a cookie like AAAA, it will have an empty token
319 // and a value of AAAA. When it sends the cookie back, it will send AAAA,
320 // so we need to avoid sending =AAAA for a blank token value.
321 if (!(*it)->Name().empty())
322 cookie_line += (*it)->Name() + "=";
323 cookie_line += (*it)->Value();
324 }
325 return cookie_line;
326}
327
ellyjones399e35a22014-10-27 11:09:56328void RunAsync(scoped_refptr<base::TaskRunner> proxy,
msarda0aad8f02014-10-30 09:22:39329 const CookieStore::CookieChangedCallback& callback,
330 const CanonicalCookie& cookie,
331 bool removed) {
332 proxy->PostTask(FROM_HERE, base::Bind(callback, cookie, removed));
ellyjones399e35a22014-10-27 11:09:56333}
334
estarkcd39c11f2015-10-19 19:46:36335bool CheckCookiePrefix(CanonicalCookie* cc, const CookieOptions& options) {
336 const char kSecurePrefix[] = "$Secure-";
337 if (cc->Name().find(kSecurePrefix) == 0)
338 return cc->IsSecure() && cc->Source().SchemeIsCryptographic();
339 return true;
340}
341
[email protected]f48b9432011-01-11 07:25:40342} // namespace
343
[email protected]7c4b66b2014-01-04 12:28:13344CookieMonster::CookieMonster(PersistentCookieStore* store,
345 CookieMonsterDelegate* delegate)
[email protected]f48b9432011-01-11 07:25:40346 : initialized_(false),
erikchen1dd72a72015-05-06 20:45:05347 started_fetching_all_cookies_(false),
348 finished_fetching_all_cookies_(false),
349 fetch_strategy_(kUnknownFetch),
[email protected]f48b9432011-01-11 07:25:40350 store_(store),
351 last_access_threshold_(
352 TimeDelta::FromSeconds(kDefaultAccessUpdateThresholdSeconds)),
353 delegate_(delegate),
[email protected]82388662011-03-10 21:04:06354 last_statistic_record_time_(Time::Now()),
[email protected]93c53a32011-12-05 10:40:35355 keep_expired_cookies_(false),
[email protected]8976e292013-11-02 13:38:57356 persist_session_cookies_(false) {
[email protected]f48b9432011-01-11 07:25:40357 InitializeHistograms();
358 SetDefaultCookieableSchemes();
[email protected]2d0f89a2010-12-06 12:02:23359}
360
[email protected]f48b9432011-01-11 07:25:40361CookieMonster::CookieMonster(PersistentCookieStore* store,
[email protected]7c4b66b2014-01-04 12:28:13362 CookieMonsterDelegate* delegate,
[email protected]f48b9432011-01-11 07:25:40363 int last_access_threshold_milliseconds)
364 : initialized_(false),
erikchen1dd72a72015-05-06 20:45:05365 started_fetching_all_cookies_(false),
366 finished_fetching_all_cookies_(false),
367 fetch_strategy_(kUnknownFetch),
[email protected]f48b9432011-01-11 07:25:40368 store_(store),
369 last_access_threshold_(base::TimeDelta::FromMilliseconds(
370 last_access_threshold_milliseconds)),
371 delegate_(delegate),
[email protected]82388662011-03-10 21:04:06372 last_statistic_record_time_(base::Time::Now()),
[email protected]93c53a32011-12-05 10:40:35373 keep_expired_cookies_(false),
[email protected]8976e292013-11-02 13:38:57374 persist_session_cookies_(false) {
[email protected]f48b9432011-01-11 07:25:40375 InitializeHistograms();
376 SetDefaultCookieableSchemes();
initial.commit586acc5fe2008-07-26 22:42:52377}
378
[email protected]218aa6a12011-09-13 17:38:38379// Task classes for queueing the coming request.
380
381class CookieMonster::CookieMonsterTask
382 : public base::RefCountedThreadSafe<CookieMonsterTask> {
383 public:
384 // Runs the task and invokes the client callback on the thread that
385 // originally constructed the task.
386 virtual void Run() = 0;
387
388 protected:
389 explicit CookieMonsterTask(CookieMonster* cookie_monster);
390 virtual ~CookieMonsterTask();
391
392 // Invokes the callback immediately, if the current thread is the one
393 // that originated the task, or queues the callback for execution on the
394 // appropriate thread. Maintains a reference to this CookieMonsterTask
395 // instance until the callback completes.
396 void InvokeCallback(base::Closure callback);
397
mkwstbe84af312015-02-20 08:52:45398 CookieMonster* cookie_monster() { return cookie_monster_; }
[email protected]218aa6a12011-09-13 17:38:38399
[email protected]a9813302012-04-28 09:29:28400 private:
[email protected]218aa6a12011-09-13 17:38:38401 friend class base::RefCountedThreadSafe<CookieMonsterTask>;
402
[email protected]218aa6a12011-09-13 17:38:38403 CookieMonster* cookie_monster_;
anujk.sharmaafc45172015-05-15 00:50:34404 scoped_refptr<base::SingleThreadTaskRunner> thread_;
[email protected]218aa6a12011-09-13 17:38:38405
406 DISALLOW_COPY_AND_ASSIGN(CookieMonsterTask);
407};
408
409CookieMonster::CookieMonsterTask::CookieMonsterTask(
410 CookieMonster* cookie_monster)
411 : cookie_monster_(cookie_monster),
anujk.sharmaafc45172015-05-15 00:50:34412 thread_(base::ThreadTaskRunnerHandle::Get()) {
[email protected]a9813302012-04-28 09:29:28413}
[email protected]218aa6a12011-09-13 17:38:38414
mkwstbe84af312015-02-20 08:52:45415CookieMonster::CookieMonsterTask::~CookieMonsterTask() {
416}
[email protected]218aa6a12011-09-13 17:38:38417
418// Unfortunately, one cannot re-bind a Callback with parameters into a closure.
419// Therefore, the closure passed to InvokeCallback is a clumsy binding of
420// Callback::Run on a wrapped Callback instance. Since Callback is not
421// reference counted, we bind to an instance that is a member of the
422// CookieMonsterTask subclass. Then, we cannot simply post the callback to a
423// message loop because the underlying instance may be destroyed (along with the
424// CookieMonsterTask instance) in the interim. Therefore, we post a callback
425// bound to the CookieMonsterTask, which *is* reference counted (thus preventing
426// destruction of the original callback), and which invokes the closure (which
427// invokes the original callback with the returned data).
428void CookieMonster::CookieMonsterTask::InvokeCallback(base::Closure callback) {
429 if (thread_->BelongsToCurrentThread()) {
430 callback.Run();
431 } else {
mkwstbe84af312015-02-20 08:52:45432 thread_->PostTask(FROM_HERE, base::Bind(&CookieMonsterTask::InvokeCallback,
433 this, callback));
[email protected]218aa6a12011-09-13 17:38:38434 }
435}
436
437// Task class for SetCookieWithDetails call.
[email protected]5fa4f9a2013-10-03 10:13:16438class CookieMonster::SetCookieWithDetailsTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38439 public:
[email protected]dedec0b2013-02-28 04:50:10440 SetCookieWithDetailsTask(CookieMonster* cookie_monster,
441 const GURL& url,
442 const std::string& name,
443 const std::string& value,
444 const std::string& domain,
445 const std::string& path,
446 const base::Time& expiration_time,
447 bool secure,
448 bool http_only,
mkwstae819bb2015-02-23 05:10:31449 bool first_party_only,
estarkcd39c11f2015-10-19 19:46:36450 bool enforce_prefixes,
[email protected]ab2d75c82013-04-19 18:39:04451 CookiePriority priority,
[email protected]5fa4f9a2013-10-03 10:13:16452 const SetCookiesCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38453 : CookieMonsterTask(cookie_monster),
454 url_(url),
455 name_(name),
456 value_(value),
457 domain_(domain),
458 path_(path),
459 expiration_time_(expiration_time),
460 secure_(secure),
461 http_only_(http_only),
mkwstae819bb2015-02-23 05:10:31462 first_party_only_(first_party_only),
estarkcd39c11f2015-10-19 19:46:36463 enforce_prefixes_(enforce_prefixes),
[email protected]ab2d75c82013-04-19 18:39:04464 priority_(priority),
mkwstbe84af312015-02-20 08:52:45465 callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38466
[email protected]5fa4f9a2013-10-03 10:13:16467 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20468 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38469
[email protected]a9813302012-04-28 09:29:28470 protected:
dchengb03027d2014-10-21 12:00:20471 ~SetCookieWithDetailsTask() override {}
[email protected]a9813302012-04-28 09:29:28472
[email protected]218aa6a12011-09-13 17:38:38473 private:
474 GURL url_;
475 std::string name_;
476 std::string value_;
477 std::string domain_;
478 std::string path_;
479 base::Time expiration_time_;
480 bool secure_;
481 bool http_only_;
mkwstae819bb2015-02-23 05:10:31482 bool first_party_only_;
estarkcd39c11f2015-10-19 19:46:36483 bool enforce_prefixes_;
[email protected]ab2d75c82013-04-19 18:39:04484 CookiePriority priority_;
[email protected]5fa4f9a2013-10-03 10:13:16485 SetCookiesCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38486
487 DISALLOW_COPY_AND_ASSIGN(SetCookieWithDetailsTask);
488};
489
490void CookieMonster::SetCookieWithDetailsTask::Run() {
mkwstbe84af312015-02-20 08:52:45491 bool success = this->cookie_monster()->SetCookieWithDetails(
492 url_, name_, value_, domain_, path_, expiration_time_, secure_,
estarkcd39c11f2015-10-19 19:46:36493 http_only_, first_party_only_, enforce_prefixes_, priority_);
[email protected]218aa6a12011-09-13 17:38:38494 if (!callback_.is_null()) {
[email protected]5fa4f9a2013-10-03 10:13:16495 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38496 base::Unretained(&callback_), success));
497 }
498}
499
500// Task class for GetAllCookies call.
[email protected]5fa4f9a2013-10-03 10:13:16501class CookieMonster::GetAllCookiesTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38502 public:
503 GetAllCookiesTask(CookieMonster* cookie_monster,
[email protected]5fa4f9a2013-10-03 10:13:16504 const GetCookieListCallback& callback)
mkwstbe84af312015-02-20 08:52:45505 : CookieMonsterTask(cookie_monster), callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38506
[email protected]5fa4f9a2013-10-03 10:13:16507 // CookieMonsterTask
dchengb03027d2014-10-21 12:00:20508 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38509
[email protected]a9813302012-04-28 09:29:28510 protected:
dchengb03027d2014-10-21 12:00:20511 ~GetAllCookiesTask() override {}
[email protected]a9813302012-04-28 09:29:28512
[email protected]218aa6a12011-09-13 17:38:38513 private:
[email protected]5fa4f9a2013-10-03 10:13:16514 GetCookieListCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38515
516 DISALLOW_COPY_AND_ASSIGN(GetAllCookiesTask);
517};
518
519void CookieMonster::GetAllCookiesTask::Run() {
520 if (!callback_.is_null()) {
521 CookieList cookies = this->cookie_monster()->GetAllCookies();
[email protected]5fa4f9a2013-10-03 10:13:16522 this->InvokeCallback(base::Bind(&GetCookieListCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38523 base::Unretained(&callback_), cookies));
mkwstbe84af312015-02-20 08:52:45524 }
[email protected]218aa6a12011-09-13 17:38:38525}
526
527// Task class for GetAllCookiesForURLWithOptions call.
528class CookieMonster::GetAllCookiesForURLWithOptionsTask
[email protected]5fa4f9a2013-10-03 10:13:16529 : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38530 public:
mkwstbe84af312015-02-20 08:52:45531 GetAllCookiesForURLWithOptionsTask(CookieMonster* cookie_monster,
532 const GURL& url,
533 const CookieOptions& options,
534 const GetCookieListCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38535 : CookieMonsterTask(cookie_monster),
536 url_(url),
537 options_(options),
mkwstbe84af312015-02-20 08:52:45538 callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38539
[email protected]5fa4f9a2013-10-03 10:13:16540 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20541 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38542
[email protected]a9813302012-04-28 09:29:28543 protected:
dchengb03027d2014-10-21 12:00:20544 ~GetAllCookiesForURLWithOptionsTask() override {}
[email protected]a9813302012-04-28 09:29:28545
[email protected]218aa6a12011-09-13 17:38:38546 private:
547 GURL url_;
548 CookieOptions options_;
[email protected]5fa4f9a2013-10-03 10:13:16549 GetCookieListCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38550
551 DISALLOW_COPY_AND_ASSIGN(GetAllCookiesForURLWithOptionsTask);
552};
553
554void CookieMonster::GetAllCookiesForURLWithOptionsTask::Run() {
555 if (!callback_.is_null()) {
mkwstbe84af312015-02-20 08:52:45556 CookieList cookies =
557 this->cookie_monster()->GetAllCookiesForURLWithOptions(url_, options_);
[email protected]5fa4f9a2013-10-03 10:13:16558 this->InvokeCallback(base::Bind(&GetCookieListCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38559 base::Unretained(&callback_), cookies));
560 }
561}
562
mkwstbe84af312015-02-20 08:52:45563template <typename Result>
564struct CallbackType {
[email protected]5fa4f9a2013-10-03 10:13:16565 typedef base::Callback<void(Result)> Type;
566};
567
mkwstbe84af312015-02-20 08:52:45568template <>
569struct CallbackType<void> {
[email protected]5fa4f9a2013-10-03 10:13:16570 typedef base::Closure Type;
571};
572
573// Base task class for Delete*Task.
574template <typename Result>
575class CookieMonster::DeleteTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38576 public:
[email protected]5fa4f9a2013-10-03 10:13:16577 DeleteTask(CookieMonster* cookie_monster,
578 const typename CallbackType<Result>::Type& callback)
mkwstbe84af312015-02-20 08:52:45579 : CookieMonsterTask(cookie_monster), callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38580
[email protected]5fa4f9a2013-10-03 10:13:16581 // CookieMonsterTask:
nickd3f30d022015-04-23 10:18:37582 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38583
dmichaeld6e570d2014-12-18 22:30:57584 protected:
585 ~DeleteTask() override;
586
[email protected]5fa4f9a2013-10-03 10:13:16587 private:
588 // Runs the delete task and returns a result.
589 virtual Result RunDeleteTask() = 0;
590 base::Closure RunDeleteTaskAndBindCallback();
591 void FlushDone(const base::Closure& callback);
592
593 typename CallbackType<Result>::Type callback_;
594
595 DISALLOW_COPY_AND_ASSIGN(DeleteTask);
596};
597
598template <typename Result>
dmichaeld6e570d2014-12-18 22:30:57599CookieMonster::DeleteTask<Result>::~DeleteTask() {
600}
601
602template <typename Result>
603base::Closure
604CookieMonster::DeleteTask<Result>::RunDeleteTaskAndBindCallback() {
[email protected]5fa4f9a2013-10-03 10:13:16605 Result result = RunDeleteTask();
606 if (callback_.is_null())
607 return base::Closure();
608 return base::Bind(callback_, result);
609}
610
611template <>
612base::Closure CookieMonster::DeleteTask<void>::RunDeleteTaskAndBindCallback() {
613 RunDeleteTask();
614 return callback_;
615}
616
617template <typename Result>
618void CookieMonster::DeleteTask<Result>::Run() {
mkwstbe84af312015-02-20 08:52:45619 this->cookie_monster()->FlushStore(base::Bind(
620 &DeleteTask<Result>::FlushDone, this, RunDeleteTaskAndBindCallback()));
[email protected]5fa4f9a2013-10-03 10:13:16621}
622
623template <typename Result>
624void CookieMonster::DeleteTask<Result>::FlushDone(
625 const base::Closure& callback) {
626 if (!callback.is_null()) {
627 this->InvokeCallback(callback);
628 }
629}
630
631// Task class for DeleteAll call.
632class CookieMonster::DeleteAllTask : public DeleteTask<int> {
633 public:
mkwstbe84af312015-02-20 08:52:45634 DeleteAllTask(CookieMonster* cookie_monster, const DeleteCallback& callback)
635 : DeleteTask<int>(cookie_monster, callback) {}
[email protected]5fa4f9a2013-10-03 10:13:16636
637 // DeleteTask:
dchengb03027d2014-10-21 12:00:20638 int RunDeleteTask() override;
[email protected]5fa4f9a2013-10-03 10:13:16639
[email protected]a9813302012-04-28 09:29:28640 protected:
dchengb03027d2014-10-21 12:00:20641 ~DeleteAllTask() override {}
[email protected]a9813302012-04-28 09:29:28642
[email protected]218aa6a12011-09-13 17:38:38643 private:
[email protected]218aa6a12011-09-13 17:38:38644 DISALLOW_COPY_AND_ASSIGN(DeleteAllTask);
645};
646
[email protected]5fa4f9a2013-10-03 10:13:16647int CookieMonster::DeleteAllTask::RunDeleteTask() {
648 return this->cookie_monster()->DeleteAll(true);
[email protected]218aa6a12011-09-13 17:38:38649}
650
651// Task class for DeleteAllCreatedBetween call.
[email protected]5fa4f9a2013-10-03 10:13:16652class CookieMonster::DeleteAllCreatedBetweenTask : public DeleteTask<int> {
[email protected]218aa6a12011-09-13 17:38:38653 public:
[email protected]dedec0b2013-02-28 04:50:10654 DeleteAllCreatedBetweenTask(CookieMonster* cookie_monster,
655 const Time& delete_begin,
656 const Time& delete_end,
[email protected]5fa4f9a2013-10-03 10:13:16657 const DeleteCallback& callback)
[email protected]151132f2013-11-18 21:37:00658 : DeleteTask<int>(cookie_monster, callback),
[email protected]218aa6a12011-09-13 17:38:38659 delete_begin_(delete_begin),
mkwstbe84af312015-02-20 08:52:45660 delete_end_(delete_end) {}
[email protected]218aa6a12011-09-13 17:38:38661
[email protected]5fa4f9a2013-10-03 10:13:16662 // DeleteTask:
dchengb03027d2014-10-21 12:00:20663 int RunDeleteTask() override;
[email protected]218aa6a12011-09-13 17:38:38664
[email protected]a9813302012-04-28 09:29:28665 protected:
dchengb03027d2014-10-21 12:00:20666 ~DeleteAllCreatedBetweenTask() override {}
[email protected]a9813302012-04-28 09:29:28667
[email protected]218aa6a12011-09-13 17:38:38668 private:
669 Time delete_begin_;
670 Time delete_end_;
[email protected]218aa6a12011-09-13 17:38:38671
672 DISALLOW_COPY_AND_ASSIGN(DeleteAllCreatedBetweenTask);
673};
674
[email protected]5fa4f9a2013-10-03 10:13:16675int CookieMonster::DeleteAllCreatedBetweenTask::RunDeleteTask() {
mkwstbe84af312015-02-20 08:52:45676 return this->cookie_monster()->DeleteAllCreatedBetween(delete_begin_,
677 delete_end_);
[email protected]218aa6a12011-09-13 17:38:38678}
679
680// Task class for DeleteAllForHost call.
[email protected]5fa4f9a2013-10-03 10:13:16681class CookieMonster::DeleteAllForHostTask : public DeleteTask<int> {
[email protected]218aa6a12011-09-13 17:38:38682 public:
683 DeleteAllForHostTask(CookieMonster* cookie_monster,
684 const GURL& url,
[email protected]5fa4f9a2013-10-03 10:13:16685 const DeleteCallback& callback)
mkwstbe84af312015-02-20 08:52:45686 : DeleteTask<int>(cookie_monster, callback), url_(url) {}
[email protected]218aa6a12011-09-13 17:38:38687
[email protected]5fa4f9a2013-10-03 10:13:16688 // DeleteTask:
dchengb03027d2014-10-21 12:00:20689 int RunDeleteTask() override;
[email protected]218aa6a12011-09-13 17:38:38690
[email protected]a9813302012-04-28 09:29:28691 protected:
dchengb03027d2014-10-21 12:00:20692 ~DeleteAllForHostTask() override {}
[email protected]a9813302012-04-28 09:29:28693
[email protected]218aa6a12011-09-13 17:38:38694 private:
695 GURL url_;
[email protected]218aa6a12011-09-13 17:38:38696
697 DISALLOW_COPY_AND_ASSIGN(DeleteAllForHostTask);
698};
699
[email protected]5fa4f9a2013-10-03 10:13:16700int CookieMonster::DeleteAllForHostTask::RunDeleteTask() {
701 return this->cookie_monster()->DeleteAllForHost(url_);
[email protected]218aa6a12011-09-13 17:38:38702}
703
[email protected]d8428d52013-08-07 06:58:25704// Task class for DeleteAllCreatedBetweenForHost call.
705class CookieMonster::DeleteAllCreatedBetweenForHostTask
[email protected]5fa4f9a2013-10-03 10:13:16706 : public DeleteTask<int> {
[email protected]d8428d52013-08-07 06:58:25707 public:
mkwstbe84af312015-02-20 08:52:45708 DeleteAllCreatedBetweenForHostTask(CookieMonster* cookie_monster,
709 Time delete_begin,
710 Time delete_end,
711 const GURL& url,
712 const DeleteCallback& callback)
[email protected]151132f2013-11-18 21:37:00713 : DeleteTask<int>(cookie_monster, callback),
[email protected]d8428d52013-08-07 06:58:25714 delete_begin_(delete_begin),
715 delete_end_(delete_end),
mkwstbe84af312015-02-20 08:52:45716 url_(url) {}
[email protected]d8428d52013-08-07 06:58:25717
[email protected]5fa4f9a2013-10-03 10:13:16718 // DeleteTask:
dchengb03027d2014-10-21 12:00:20719 int RunDeleteTask() override;
[email protected]d8428d52013-08-07 06:58:25720
721 protected:
dchengb03027d2014-10-21 12:00:20722 ~DeleteAllCreatedBetweenForHostTask() override {}
[email protected]d8428d52013-08-07 06:58:25723
724 private:
725 Time delete_begin_;
726 Time delete_end_;
727 GURL url_;
[email protected]d8428d52013-08-07 06:58:25728
729 DISALLOW_COPY_AND_ASSIGN(DeleteAllCreatedBetweenForHostTask);
730};
731
[email protected]5fa4f9a2013-10-03 10:13:16732int CookieMonster::DeleteAllCreatedBetweenForHostTask::RunDeleteTask() {
733 return this->cookie_monster()->DeleteAllCreatedBetweenForHost(
[email protected]d8428d52013-08-07 06:58:25734 delete_begin_, delete_end_, url_);
[email protected]d8428d52013-08-07 06:58:25735}
736
[email protected]218aa6a12011-09-13 17:38:38737// Task class for DeleteCanonicalCookie call.
[email protected]5fa4f9a2013-10-03 10:13:16738class CookieMonster::DeleteCanonicalCookieTask : public DeleteTask<bool> {
[email protected]218aa6a12011-09-13 17:38:38739 public:
[email protected]dedec0b2013-02-28 04:50:10740 DeleteCanonicalCookieTask(CookieMonster* cookie_monster,
741 const CanonicalCookie& cookie,
[email protected]5fa4f9a2013-10-03 10:13:16742 const DeleteCookieCallback& callback)
mkwstbe84af312015-02-20 08:52:45743 : DeleteTask<bool>(cookie_monster, callback), cookie_(cookie) {}
[email protected]218aa6a12011-09-13 17:38:38744
[email protected]5fa4f9a2013-10-03 10:13:16745 // DeleteTask:
dchengb03027d2014-10-21 12:00:20746 bool RunDeleteTask() override;
[email protected]218aa6a12011-09-13 17:38:38747
[email protected]a9813302012-04-28 09:29:28748 protected:
dchengb03027d2014-10-21 12:00:20749 ~DeleteCanonicalCookieTask() override {}
[email protected]a9813302012-04-28 09:29:28750
[email protected]218aa6a12011-09-13 17:38:38751 private:
[email protected]5b9bc352012-07-18 13:13:34752 CanonicalCookie cookie_;
[email protected]218aa6a12011-09-13 17:38:38753
754 DISALLOW_COPY_AND_ASSIGN(DeleteCanonicalCookieTask);
755};
756
[email protected]5fa4f9a2013-10-03 10:13:16757bool CookieMonster::DeleteCanonicalCookieTask::RunDeleteTask() {
758 return this->cookie_monster()->DeleteCanonicalCookie(cookie_);
[email protected]218aa6a12011-09-13 17:38:38759}
760
761// Task class for SetCookieWithOptions call.
[email protected]5fa4f9a2013-10-03 10:13:16762class CookieMonster::SetCookieWithOptionsTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38763 public:
764 SetCookieWithOptionsTask(CookieMonster* cookie_monster,
765 const GURL& url,
766 const std::string& cookie_line,
767 const CookieOptions& options,
[email protected]5fa4f9a2013-10-03 10:13:16768 const SetCookiesCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38769 : CookieMonsterTask(cookie_monster),
770 url_(url),
771 cookie_line_(cookie_line),
772 options_(options),
mkwstbe84af312015-02-20 08:52:45773 callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38774
[email protected]5fa4f9a2013-10-03 10:13:16775 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20776 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38777
[email protected]a9813302012-04-28 09:29:28778 protected:
dchengb03027d2014-10-21 12:00:20779 ~SetCookieWithOptionsTask() override {}
[email protected]a9813302012-04-28 09:29:28780
[email protected]218aa6a12011-09-13 17:38:38781 private:
782 GURL url_;
783 std::string cookie_line_;
784 CookieOptions options_;
[email protected]5fa4f9a2013-10-03 10:13:16785 SetCookiesCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38786
787 DISALLOW_COPY_AND_ASSIGN(SetCookieWithOptionsTask);
788};
789
790void CookieMonster::SetCookieWithOptionsTask::Run() {
mkwstbe84af312015-02-20 08:52:45791 bool result = this->cookie_monster()->SetCookieWithOptions(url_, cookie_line_,
792 options_);
[email protected]218aa6a12011-09-13 17:38:38793 if (!callback_.is_null()) {
[email protected]5fa4f9a2013-10-03 10:13:16794 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38795 base::Unretained(&callback_), result));
796 }
797}
798
drogerd5d1278c2015-03-17 19:21:51799// Task class for SetAllCookies call.
800class CookieMonster::SetAllCookiesTask : public CookieMonsterTask {
801 public:
802 SetAllCookiesTask(CookieMonster* cookie_monster,
803 const CookieList& list,
804 const SetCookiesCallback& callback)
805 : CookieMonsterTask(cookie_monster), list_(list), callback_(callback) {}
806
807 // CookieMonsterTask:
808 void Run() override;
809
810 protected:
811 ~SetAllCookiesTask() override {}
812
813 private:
814 CookieList list_;
815 SetCookiesCallback callback_;
816
817 DISALLOW_COPY_AND_ASSIGN(SetAllCookiesTask);
818};
819
820void CookieMonster::SetAllCookiesTask::Run() {
821 CookieList positive_diff;
822 CookieList negative_diff;
823 CookieList old_cookies = this->cookie_monster()->GetAllCookies();
824 this->cookie_monster()->ComputeCookieDiff(&old_cookies, &list_,
825 &positive_diff, &negative_diff);
826
827 for (CookieList::const_iterator it = negative_diff.begin();
828 it != negative_diff.end(); ++it) {
829 this->cookie_monster()->DeleteCanonicalCookie(*it);
830 }
831
832 bool result = true;
833 if (positive_diff.size() > 0)
834 result = this->cookie_monster()->SetCanonicalCookies(list_);
835
836 if (!callback_.is_null()) {
837 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run,
838 base::Unretained(&callback_), result));
839 }
840}
841
[email protected]218aa6a12011-09-13 17:38:38842// Task class for GetCookiesWithOptions call.
[email protected]5fa4f9a2013-10-03 10:13:16843class CookieMonster::GetCookiesWithOptionsTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38844 public:
845 GetCookiesWithOptionsTask(CookieMonster* cookie_monster,
[email protected]0298caf82011-12-20 23:15:46846 const GURL& url,
[email protected]218aa6a12011-09-13 17:38:38847 const CookieOptions& options,
[email protected]5fa4f9a2013-10-03 10:13:16848 const GetCookiesCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38849 : CookieMonsterTask(cookie_monster),
850 url_(url),
851 options_(options),
mkwstbe84af312015-02-20 08:52:45852 callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38853
[email protected]5fa4f9a2013-10-03 10:13:16854 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20855 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38856
[email protected]a9813302012-04-28 09:29:28857 protected:
dchengb03027d2014-10-21 12:00:20858 ~GetCookiesWithOptionsTask() override {}
[email protected]a9813302012-04-28 09:29:28859
[email protected]218aa6a12011-09-13 17:38:38860 private:
861 GURL url_;
862 CookieOptions options_;
[email protected]5fa4f9a2013-10-03 10:13:16863 GetCookiesCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38864
865 DISALLOW_COPY_AND_ASSIGN(GetCookiesWithOptionsTask);
866};
867
868void CookieMonster::GetCookiesWithOptionsTask::Run() {
pkastinga9269aa42015-04-10 01:42:26869 // TODO(mkwst): Remove ScopedTracker below once crbug.com/456373 is fixed.
pkasting58e029b2015-02-21 05:17:28870 tracked_objects::ScopedTracker tracking_profile(
871 FROM_HERE_WITH_EXPLICIT_FUNCTION(
872 "456373 CookieMonster::GetCookiesWithOptionsTask::Run"));
mkwstbe84af312015-02-20 08:52:45873 std::string cookie =
874 this->cookie_monster()->GetCookiesWithOptions(url_, options_);
[email protected]218aa6a12011-09-13 17:38:38875 if (!callback_.is_null()) {
[email protected]5fa4f9a2013-10-03 10:13:16876 this->InvokeCallback(base::Bind(&GetCookiesCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38877 base::Unretained(&callback_), cookie));
878 }
879}
880
[email protected]218aa6a12011-09-13 17:38:38881// Task class for DeleteCookie call.
[email protected]5fa4f9a2013-10-03 10:13:16882class CookieMonster::DeleteCookieTask : public DeleteTask<void> {
[email protected]218aa6a12011-09-13 17:38:38883 public:
884 DeleteCookieTask(CookieMonster* cookie_monster,
[email protected]0298caf82011-12-20 23:15:46885 const GURL& url,
[email protected]218aa6a12011-09-13 17:38:38886 const std::string& cookie_name,
887 const base::Closure& callback)
[email protected]151132f2013-11-18 21:37:00888 : DeleteTask<void>(cookie_monster, callback),
[email protected]218aa6a12011-09-13 17:38:38889 url_(url),
mkwstbe84af312015-02-20 08:52:45890 cookie_name_(cookie_name) {}
[email protected]218aa6a12011-09-13 17:38:38891
[email protected]5fa4f9a2013-10-03 10:13:16892 // DeleteTask:
dchengb03027d2014-10-21 12:00:20893 void RunDeleteTask() override;
[email protected]218aa6a12011-09-13 17:38:38894
[email protected]a9813302012-04-28 09:29:28895 protected:
dchengb03027d2014-10-21 12:00:20896 ~DeleteCookieTask() override {}
[email protected]a9813302012-04-28 09:29:28897
[email protected]218aa6a12011-09-13 17:38:38898 private:
899 GURL url_;
900 std::string cookie_name_;
[email protected]218aa6a12011-09-13 17:38:38901
902 DISALLOW_COPY_AND_ASSIGN(DeleteCookieTask);
903};
904
[email protected]5fa4f9a2013-10-03 10:13:16905void CookieMonster::DeleteCookieTask::RunDeleteTask() {
[email protected]218aa6a12011-09-13 17:38:38906 this->cookie_monster()->DeleteCookie(url_, cookie_name_);
[email protected]218aa6a12011-09-13 17:38:38907}
908
[email protected]264807b2012-04-25 14:49:37909// Task class for DeleteSessionCookies call.
[email protected]5fa4f9a2013-10-03 10:13:16910class CookieMonster::DeleteSessionCookiesTask : public DeleteTask<int> {
[email protected]264807b2012-04-25 14:49:37911 public:
[email protected]dedec0b2013-02-28 04:50:10912 DeleteSessionCookiesTask(CookieMonster* cookie_monster,
[email protected]5fa4f9a2013-10-03 10:13:16913 const DeleteCallback& callback)
mkwstbe84af312015-02-20 08:52:45914 : DeleteTask<int>(cookie_monster, callback) {}
[email protected]264807b2012-04-25 14:49:37915
[email protected]5fa4f9a2013-10-03 10:13:16916 // DeleteTask:
dchengb03027d2014-10-21 12:00:20917 int RunDeleteTask() override;
[email protected]264807b2012-04-25 14:49:37918
[email protected]a9813302012-04-28 09:29:28919 protected:
dchengb03027d2014-10-21 12:00:20920 ~DeleteSessionCookiesTask() override {}
[email protected]a9813302012-04-28 09:29:28921
[email protected]264807b2012-04-25 14:49:37922 private:
[email protected]264807b2012-04-25 14:49:37923 DISALLOW_COPY_AND_ASSIGN(DeleteSessionCookiesTask);
924};
925
[email protected]5fa4f9a2013-10-03 10:13:16926int CookieMonster::DeleteSessionCookiesTask::RunDeleteTask() {
927 return this->cookie_monster()->DeleteSessionCookies();
[email protected]264807b2012-04-25 14:49:37928}
929
[email protected]218aa6a12011-09-13 17:38:38930// Asynchronous CookieMonster API
931
932void CookieMonster::SetCookieWithDetailsAsync(
[email protected]dedec0b2013-02-28 04:50:10933 const GURL& url,
934 const std::string& name,
935 const std::string& value,
936 const std::string& domain,
937 const std::string& path,
[email protected]d8428d52013-08-07 06:58:25938 const Time& expiration_time,
[email protected]dedec0b2013-02-28 04:50:10939 bool secure,
940 bool http_only,
mkwstae819bb2015-02-23 05:10:31941 bool first_party_only,
estarkcd39c11f2015-10-19 19:46:36942 bool enforce_prefixes,
[email protected]ab2d75c82013-04-19 18:39:04943 CookiePriority priority,
[email protected]218aa6a12011-09-13 17:38:38944 const SetCookiesCallback& callback) {
mkwstbe84af312015-02-20 08:52:45945 scoped_refptr<SetCookieWithDetailsTask> task = new SetCookieWithDetailsTask(
946 this, url, name, value, domain, path, expiration_time, secure, http_only,
estarkcd39c11f2015-10-19 19:46:36947 first_party_only, enforce_prefixes, priority, callback);
[email protected]8562034e2011-10-17 17:35:04948 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:38949}
950
951void CookieMonster::GetAllCookiesAsync(const GetCookieListCallback& callback) {
mkwstbe84af312015-02-20 08:52:45952 scoped_refptr<GetAllCookiesTask> task = new GetAllCookiesTask(this, callback);
[email protected]218aa6a12011-09-13 17:38:38953
954 DoCookieTask(task);
955}
956
[email protected]218aa6a12011-09-13 17:38:38957void CookieMonster::GetAllCookiesForURLWithOptionsAsync(
958 const GURL& url,
959 const CookieOptions& options,
960 const GetCookieListCallback& callback) {
961 scoped_refptr<GetAllCookiesForURLWithOptionsTask> task =
962 new GetAllCookiesForURLWithOptionsTask(this, url, options, callback);
963
[email protected]8562034e2011-10-17 17:35:04964 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:38965}
966
967void CookieMonster::GetAllCookiesForURLAsync(
mkwstbe84af312015-02-20 08:52:45968 const GURL& url,
969 const GetCookieListCallback& callback) {
[email protected]218aa6a12011-09-13 17:38:38970 CookieOptions options;
971 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:31972 options.set_include_first_party_only();
[email protected]218aa6a12011-09-13 17:38:38973 scoped_refptr<GetAllCookiesForURLWithOptionsTask> task =
974 new GetAllCookiesForURLWithOptionsTask(this, url, options, callback);
975
[email protected]8562034e2011-10-17 17:35:04976 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:38977}
978
979void CookieMonster::DeleteAllAsync(const DeleteCallback& callback) {
mkwstbe84af312015-02-20 08:52:45980 scoped_refptr<DeleteAllTask> task = new DeleteAllTask(this, callback);
[email protected]218aa6a12011-09-13 17:38:38981
982 DoCookieTask(task);
983}
984
985void CookieMonster::DeleteAllCreatedBetweenAsync(
mkwstbe84af312015-02-20 08:52:45986 const Time& delete_begin,
987 const Time& delete_end,
[email protected]218aa6a12011-09-13 17:38:38988 const DeleteCallback& callback) {
989 scoped_refptr<DeleteAllCreatedBetweenTask> task =
mkwstbe84af312015-02-20 08:52:45990 new DeleteAllCreatedBetweenTask(this, delete_begin, delete_end, callback);
[email protected]218aa6a12011-09-13 17:38:38991
992 DoCookieTask(task);
993}
994
[email protected]d8428d52013-08-07 06:58:25995void CookieMonster::DeleteAllCreatedBetweenForHostAsync(
996 const Time delete_begin,
997 const Time delete_end,
998 const GURL& url,
999 const DeleteCallback& callback) {
1000 scoped_refptr<DeleteAllCreatedBetweenForHostTask> task =
mkwstbe84af312015-02-20 08:52:451001 new DeleteAllCreatedBetweenForHostTask(this, delete_begin, delete_end,
1002 url, callback);
[email protected]d8428d52013-08-07 06:58:251003
1004 DoCookieTaskForURL(task, url);
1005}
1006
mkwstbe84af312015-02-20 08:52:451007void CookieMonster::DeleteAllForHostAsync(const GURL& url,
1008 const DeleteCallback& callback) {
[email protected]218aa6a12011-09-13 17:38:381009 scoped_refptr<DeleteAllForHostTask> task =
1010 new DeleteAllForHostTask(this, url, callback);
1011
[email protected]8562034e2011-10-17 17:35:041012 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381013}
1014
1015void CookieMonster::DeleteCanonicalCookieAsync(
1016 const CanonicalCookie& cookie,
1017 const DeleteCookieCallback& callback) {
1018 scoped_refptr<DeleteCanonicalCookieTask> task =
1019 new DeleteCanonicalCookieTask(this, cookie, callback);
1020
1021 DoCookieTask(task);
1022}
1023
drogerd5d1278c2015-03-17 19:21:511024void CookieMonster::SetAllCookiesAsync(const CookieList& list,
1025 const SetCookiesCallback& callback) {
1026 scoped_refptr<SetAllCookiesTask> task =
1027 new SetAllCookiesTask(this, list, callback);
1028 DoCookieTask(task);
1029}
1030
[email protected]218aa6a12011-09-13 17:38:381031void CookieMonster::SetCookieWithOptionsAsync(
1032 const GURL& url,
1033 const std::string& cookie_line,
1034 const CookieOptions& options,
1035 const SetCookiesCallback& callback) {
1036 scoped_refptr<SetCookieWithOptionsTask> task =
1037 new SetCookieWithOptionsTask(this, url, cookie_line, options, callback);
1038
[email protected]8562034e2011-10-17 17:35:041039 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381040}
1041
1042void CookieMonster::GetCookiesWithOptionsAsync(
1043 const GURL& url,
1044 const CookieOptions& options,
1045 const GetCookiesCallback& callback) {
1046 scoped_refptr<GetCookiesWithOptionsTask> task =
1047 new GetCookiesWithOptionsTask(this, url, options, callback);
1048
[email protected]8562034e2011-10-17 17:35:041049 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381050}
1051
[email protected]218aa6a12011-09-13 17:38:381052void CookieMonster::DeleteCookieAsync(const GURL& url,
1053 const std::string& cookie_name,
1054 const base::Closure& callback) {
1055 scoped_refptr<DeleteCookieTask> task =
1056 new DeleteCookieTask(this, url, cookie_name, callback);
1057
[email protected]8562034e2011-10-17 17:35:041058 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381059}
1060
[email protected]264807b2012-04-25 14:49:371061void CookieMonster::DeleteSessionCookiesAsync(
1062 const CookieStore::DeleteCallback& callback) {
1063 scoped_refptr<DeleteSessionCookiesTask> task =
1064 new DeleteSessionCookiesTask(this, callback);
1065
1066 DoCookieTask(task);
1067}
1068
[email protected]218aa6a12011-09-13 17:38:381069void CookieMonster::DoCookieTask(
1070 const scoped_refptr<CookieMonsterTask>& task_item) {
[email protected]218aa6a12011-09-13 17:38:381071 {
1072 base::AutoLock autolock(lock_);
erikchen1dd72a72015-05-06 20:45:051073 MarkCookieStoreAsInitialized();
1074 FetchAllCookiesIfNecessary();
1075 if (!finished_fetching_all_cookies_ && store_.get()) {
[email protected]0184df32013-05-14 00:53:551076 tasks_pending_.push(task_item);
[email protected]218aa6a12011-09-13 17:38:381077 return;
1078 }
1079 }
1080
1081 task_item->Run();
1082}
1083
[email protected]8562034e2011-10-17 17:35:041084void CookieMonster::DoCookieTaskForURL(
1085 const scoped_refptr<CookieMonsterTask>& task_item,
1086 const GURL& url) {
1087 {
1088 base::AutoLock autolock(lock_);
erikchen1dd72a72015-05-06 20:45:051089 MarkCookieStoreAsInitialized();
1090 if (ShouldFetchAllCookiesWhenFetchingAnyCookie())
1091 FetchAllCookiesIfNecessary();
[email protected]8562034e2011-10-17 17:35:041092 // If cookies for the requested domain key (eTLD+1) have been loaded from DB
1093 // then run the task, otherwise load from DB.
erikchen1dd72a72015-05-06 20:45:051094 if (!finished_fetching_all_cookies_ && store_.get()) {
[email protected]8562034e2011-10-17 17:35:041095 // Checks if the domain key has been loaded.
mkwstbe84af312015-02-20 08:52:451096 std::string key(
1097 cookie_util::GetEffectiveDomain(url.scheme(), url.host()));
[email protected]8562034e2011-10-17 17:35:041098 if (keys_loaded_.find(key) == keys_loaded_.end()) {
mkwstbe84af312015-02-20 08:52:451099 std::map<std::string,
1100 std::deque<scoped_refptr<CookieMonsterTask>>>::iterator it =
1101 tasks_pending_for_key_.find(key);
[email protected]0184df32013-05-14 00:53:551102 if (it == tasks_pending_for_key_.end()) {
mkwstbe84af312015-02-20 08:52:451103 store_->LoadCookiesForKey(
1104 key, base::Bind(&CookieMonster::OnKeyLoaded, this, key));
1105 it = tasks_pending_for_key_
1106 .insert(std::make_pair(
1107 key, std::deque<scoped_refptr<CookieMonsterTask>>()))
1108 .first;
[email protected]8562034e2011-10-17 17:35:041109 }
1110 it->second.push_back(task_item);
1111 return;
1112 }
1113 }
1114 }
1115 task_item->Run();
1116}
1117
[email protected]dedec0b2013-02-28 04:50:101118bool CookieMonster::SetCookieWithDetails(const GURL& url,
1119 const std::string& name,
1120 const std::string& value,
1121 const std::string& domain,
1122 const std::string& path,
1123 const base::Time& expiration_time,
1124 bool secure,
[email protected]ab2d75c82013-04-19 18:39:041125 bool http_only,
mkwstae819bb2015-02-23 05:10:311126 bool first_party_only,
estarkcd39c11f2015-10-19 19:46:361127 bool enforce_prefixes,
[email protected]ab2d75c82013-04-19 18:39:041128 CookiePriority priority) {
[email protected]20305ec2011-01-21 04:55:521129 base::AutoLock autolock(lock_);
[email protected]69bb5872010-01-12 20:33:521130
[email protected]f48b9432011-01-11 07:25:401131 if (!HasCookieableScheme(url))
initial.commit586acc5fe2008-07-26 22:42:521132 return false;
1133
[email protected]f48b9432011-01-11 07:25:401134 Time creation_time = CurrentTime();
1135 last_time_seen_ = creation_time;
1136
1137 scoped_ptr<CanonicalCookie> cc;
[email protected]ab2d75c82013-04-19 18:39:041138 cc.reset(CanonicalCookie::Create(url, name, value, domain, path,
mkwstbe84af312015-02-20 08:52:451139 creation_time, expiration_time, secure,
mkwstae819bb2015-02-23 05:10:311140 http_only, first_party_only, priority));
[email protected]f48b9432011-01-11 07:25:401141
1142 if (!cc.get())
1143 return false;
1144
1145 CookieOptions options;
1146 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:311147 options.set_include_first_party_only();
estarkcd39c11f2015-10-19 19:46:361148 if (enforce_prefixes)
1149 options.set_enforce_prefixes();
[email protected]f48b9432011-01-11 07:25:401150 return SetCanonicalCookie(&cc, creation_time, options);
initial.commit586acc5fe2008-07-26 22:42:521151}
1152
bartfaba13acdf2014-09-05 15:07:281153bool CookieMonster::ImportCookies(const CookieList& list) {
[email protected]93460df2011-07-20 00:58:211154 base::AutoLock autolock(lock_);
erikchen1dd72a72015-05-06 20:45:051155 MarkCookieStoreAsInitialized();
1156 if (ShouldFetchAllCookiesWhenFetchingAnyCookie())
1157 FetchAllCookiesIfNecessary();
ttuttle859dc7a2015-04-23 19:42:291158 for (CookieList::const_iterator iter = list.begin(); iter != list.end();
mkwstbe84af312015-02-20 08:52:451159 ++iter) {
[email protected]5b9bc352012-07-18 13:13:341160 scoped_ptr<CanonicalCookie> cookie(new CanonicalCookie(*iter));
ttuttle859dc7a2015-04-23 19:42:291161 CookieOptions options;
[email protected]93460df2011-07-20 00:58:211162 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:311163 options.set_include_first_party_only();
[email protected]5b9bc352012-07-18 13:13:341164 if (!SetCanonicalCookie(&cookie, cookie->CreationDate(), options))
[email protected]93460df2011-07-20 00:58:211165 return false;
[email protected]93460df2011-07-20 00:58:211166 }
1167 return true;
1168}
1169
[email protected]f48b9432011-01-11 07:25:401170CookieList CookieMonster::GetAllCookies() {
[email protected]20305ec2011-01-21 04:55:521171 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401172
1173 // This function is being called to scrape the cookie list for management UI
1174 // or similar. We shouldn't show expired cookies in this list since it will
1175 // just be confusing to users, and this function is called rarely enough (and
1176 // is already slow enough) that it's OK to take the time to garbage collect
1177 // the expired cookies now.
1178 //
1179 // Note that this does not prune cookies to be below our limits (if we've
1180 // exceeded them) the way that calling GarbageCollect() would.
mkwstbe84af312015-02-20 08:52:451181 GarbageCollectExpired(
1182 Time::Now(), CookieMapItPair(cookies_.begin(), cookies_.end()), NULL);
[email protected]f48b9432011-01-11 07:25:401183
1184 // Copy the CanonicalCookie pointers from the map so that we can use the same
1185 // sorter as elsewhere, then copy the result out.
1186 std::vector<CanonicalCookie*> cookie_ptrs;
1187 cookie_ptrs.reserve(cookies_.size());
1188 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end(); ++it)
1189 cookie_ptrs.push_back(it->second);
1190 std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter);
1191
1192 CookieList cookie_list;
1193 cookie_list.reserve(cookie_ptrs.size());
1194 for (std::vector<CanonicalCookie*>::const_iterator it = cookie_ptrs.begin();
1195 it != cookie_ptrs.end(); ++it)
1196 cookie_list.push_back(**it);
1197
1198 return cookie_list;
[email protected]f325f1e12010-04-30 22:38:551199}
1200
[email protected]f48b9432011-01-11 07:25:401201CookieList CookieMonster::GetAllCookiesForURLWithOptions(
1202 const GURL& url,
1203 const CookieOptions& options) {
[email protected]20305ec2011-01-21 04:55:521204 base::AutoLock autolock(lock_);
initial.commit586acc5fe2008-07-26 22:42:521205
[email protected]f48b9432011-01-11 07:25:401206 std::vector<CanonicalCookie*> cookie_ptrs;
1207 FindCookiesForHostAndDomain(url, options, false, &cookie_ptrs);
1208 std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter);
initial.commit586acc5fe2008-07-26 22:42:521209
[email protected]f48b9432011-01-11 07:25:401210 CookieList cookies;
georgesakc15df6722014-12-02 23:52:121211 cookies.reserve(cookie_ptrs.size());
[email protected]f48b9432011-01-11 07:25:401212 for (std::vector<CanonicalCookie*>::const_iterator it = cookie_ptrs.begin();
1213 it != cookie_ptrs.end(); it++)
1214 cookies.push_back(**it);
initial.commit586acc5fe2008-07-26 22:42:521215
[email protected]f48b9432011-01-11 07:25:401216 return cookies;
initial.commit586acc5fe2008-07-26 22:42:521217}
1218
[email protected]f48b9432011-01-11 07:25:401219CookieList CookieMonster::GetAllCookiesForURL(const GURL& url) {
1220 CookieOptions options;
1221 options.set_include_httponly();
mkwst8241a122015-10-20 07:15:101222 options.set_first_party(url::Origin(url));
[email protected]f48b9432011-01-11 07:25:401223
1224 return GetAllCookiesForURLWithOptions(url, options);
[email protected]f325f1e12010-04-30 22:38:551225}
1226
[email protected]f48b9432011-01-11 07:25:401227int CookieMonster::DeleteAll(bool sync_to_store) {
[email protected]20305ec2011-01-21 04:55:521228 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401229
1230 int num_deleted = 0;
1231 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1232 CookieMap::iterator curit = it;
1233 ++it;
1234 InternalDeleteCookie(curit, sync_to_store,
mkwstbe84af312015-02-20 08:52:451235 sync_to_store
1236 ? DELETE_COOKIE_EXPLICIT
1237 : DELETE_COOKIE_DONT_RECORD /* Destruction. */);
[email protected]f48b9432011-01-11 07:25:401238 ++num_deleted;
initial.commit586acc5fe2008-07-26 22:42:521239 }
1240
[email protected]f48b9432011-01-11 07:25:401241 return num_deleted;
initial.commit586acc5fe2008-07-26 22:42:521242}
1243
[email protected]f48b9432011-01-11 07:25:401244int CookieMonster::DeleteAllCreatedBetween(const Time& delete_begin,
[email protected]218aa6a12011-09-13 17:38:381245 const Time& delete_end) {
[email protected]20305ec2011-01-21 04:55:521246 base::AutoLock autolock(lock_);
[email protected]d0980332010-11-16 17:08:531247
[email protected]f48b9432011-01-11 07:25:401248 int num_deleted = 0;
1249 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1250 CookieMap::iterator curit = it;
1251 CanonicalCookie* cc = curit->second;
1252 ++it;
[email protected]d0980332010-11-16 17:08:531253
[email protected]f48b9432011-01-11 07:25:401254 if (cc->CreationDate() >= delete_begin &&
1255 (delete_end.is_null() || cc->CreationDate() < delete_end)) {
mkwstbe84af312015-02-20 08:52:451256 InternalDeleteCookie(curit, true, /*sync_to_store*/
[email protected]218aa6a12011-09-13 17:38:381257 DELETE_COOKIE_EXPLICIT);
[email protected]f48b9432011-01-11 07:25:401258 ++num_deleted;
initial.commit586acc5fe2008-07-26 22:42:521259 }
1260 }
1261
[email protected]f48b9432011-01-11 07:25:401262 return num_deleted;
1263}
1264
[email protected]d8428d52013-08-07 06:58:251265int CookieMonster::DeleteAllCreatedBetweenForHost(const Time delete_begin,
1266 const Time delete_end,
1267 const GURL& url) {
[email protected]20305ec2011-01-21 04:55:521268 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401269
1270 if (!HasCookieableScheme(url))
1271 return 0;
1272
[email protected]f48b9432011-01-11 07:25:401273 const std::string host(url.host());
1274
1275 // We store host cookies in the store by their canonical host name;
1276 // domain cookies are stored with a leading ".". So this is a pretty
1277 // simple lookup and per-cookie delete.
1278 int num_deleted = 0;
1279 for (CookieMapItPair its = cookies_.equal_range(GetKey(host));
1280 its.first != its.second;) {
1281 CookieMap::iterator curit = its.first;
1282 ++its.first;
1283
1284 const CanonicalCookie* const cc = curit->second;
1285
1286 // Delete only on a match as a host cookie.
[email protected]d8428d52013-08-07 06:58:251287 if (cc->IsHostCookie() && cc->IsDomainMatch(host) &&
1288 cc->CreationDate() >= delete_begin &&
1289 // The assumption that null |delete_end| is equivalent to
1290 // Time::Max() is confusing.
1291 (delete_end.is_null() || cc->CreationDate() < delete_end)) {
[email protected]f48b9432011-01-11 07:25:401292 num_deleted++;
1293
1294 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT);
1295 }
1296 }
1297 return num_deleted;
1298}
1299
[email protected]d8428d52013-08-07 06:58:251300int CookieMonster::DeleteAllForHost(const GURL& url) {
1301 return DeleteAllCreatedBetweenForHost(Time(), Time::Max(), url);
1302}
1303
[email protected]f48b9432011-01-11 07:25:401304bool CookieMonster::DeleteCanonicalCookie(const CanonicalCookie& cookie) {
[email protected]20305ec2011-01-21 04:55:521305 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401306
1307 for (CookieMapItPair its = cookies_.equal_range(GetKey(cookie.Domain()));
1308 its.first != its.second; ++its.first) {
1309 // The creation date acts as our unique index...
1310 if (its.first->second->CreationDate() == cookie.CreationDate()) {
1311 InternalDeleteCookie(its.first, true, DELETE_COOKIE_EXPLICIT);
1312 return true;
1313 }
1314 }
initial.commit586acc5fe2008-07-26 22:42:521315 return false;
1316}
1317
[email protected]5edff3c52014-06-23 20:27:481318void CookieMonster::SetCookieableSchemes(const char* const schemes[],
[email protected]dedec0b2013-02-28 04:50:101319 size_t num_schemes) {
[email protected]20305ec2011-01-21 04:55:521320 base::AutoLock autolock(lock_);
[email protected]bb8905722010-05-21 17:29:041321
paulmillere7b3668e2015-07-23 16:37:331322 // Calls to this method will have no effect if made after a WebView or
1323 // CookieManager instance has been created.
1324 if (initialized_) {
1325 return;
1326 }
[email protected]cf12bd12010-06-17 14:41:301327
[email protected]47accfd62009-05-14 18:46:211328 cookieable_schemes_.clear();
mkwstbe84af312015-02-20 08:52:451329 cookieable_schemes_.insert(cookieable_schemes_.end(), schemes,
1330 schemes + num_schemes);
[email protected]47accfd62009-05-14 18:46:211331}
1332
[email protected]ba4ad0e2011-03-15 08:12:471333void CookieMonster::SetKeepExpiredCookies() {
1334 keep_expired_cookies_ = true;
1335}
1336
[email protected]e67f0f42011-12-20 02:29:211337void CookieMonster::FlushStore(const base::Closure& callback) {
[email protected]20305ec2011-01-21 04:55:521338 base::AutoLock autolock(lock_);
[email protected]90499482013-06-01 00:39:501339 if (initialized_ && store_.get())
[email protected]e67f0f42011-12-20 02:29:211340 store_->Flush(callback);
1341 else if (!callback.is_null())
skyostil4891b25b2015-06-11 11:43:451342 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback);
[email protected]f48b9432011-01-11 07:25:401343}
1344
1345bool CookieMonster::SetCookieWithOptions(const GURL& url,
1346 const std::string& cookie_line,
1347 const CookieOptions& options) {
[email protected]20305ec2011-01-21 04:55:521348 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401349
1350 if (!HasCookieableScheme(url)) {
1351 return false;
1352 }
1353
[email protected]f48b9432011-01-11 07:25:401354 return SetCookieWithCreationTimeAndOptions(url, cookie_line, Time(), options);
1355}
1356
1357std::string CookieMonster::GetCookiesWithOptions(const GURL& url,
1358 const CookieOptions& options) {
[email protected]20305ec2011-01-21 04:55:521359 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401360
[email protected]34a160d2011-05-12 22:12:491361 if (!HasCookieableScheme(url))
[email protected]f48b9432011-01-11 07:25:401362 return std::string();
[email protected]f48b9432011-01-11 07:25:401363
[email protected]f48b9432011-01-11 07:25:401364 std::vector<CanonicalCookie*> cookies;
1365 FindCookiesForHostAndDomain(url, options, true, &cookies);
1366 std::sort(cookies.begin(), cookies.end(), CookieSorter);
1367
[email protected]34a160d2011-05-12 22:12:491368 std::string cookie_line = BuildCookieLine(cookies);
[email protected]f48b9432011-01-11 07:25:401369
[email protected]f48b9432011-01-11 07:25:401370 VLOG(kVlogGetCookies) << "GetCookies() result: " << cookie_line;
1371
1372 return cookie_line;
1373}
1374
1375void CookieMonster::DeleteCookie(const GURL& url,
1376 const std::string& cookie_name) {
[email protected]20305ec2011-01-21 04:55:521377 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401378
1379 if (!HasCookieableScheme(url))
1380 return;
1381
1382 CookieOptions options;
1383 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:311384 options.set_include_first_party_only();
[email protected]f48b9432011-01-11 07:25:401385 // Get the cookies for this host and its domain(s).
1386 std::vector<CanonicalCookie*> cookies;
1387 FindCookiesForHostAndDomain(url, options, true, &cookies);
1388 std::set<CanonicalCookie*> matching_cookies;
1389
1390 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
1391 it != cookies.end(); ++it) {
1392 if ((*it)->Name() != cookie_name)
1393 continue;
1394 if (url.path().find((*it)->Path()))
1395 continue;
1396 matching_cookies.insert(*it);
1397 }
1398
1399 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1400 CookieMap::iterator curit = it;
1401 ++it;
1402 if (matching_cookies.find(curit->second) != matching_cookies.end()) {
1403 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT);
1404 }
1405 }
1406}
1407
[email protected]264807b2012-04-25 14:49:371408int CookieMonster::DeleteSessionCookies() {
1409 base::AutoLock autolock(lock_);
1410
1411 int num_deleted = 0;
1412 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1413 CookieMap::iterator curit = it;
1414 CanonicalCookie* cc = curit->second;
1415 ++it;
1416
1417 if (!cc->IsPersistent()) {
mkwstbe84af312015-02-20 08:52:451418 InternalDeleteCookie(curit, true, /*sync_to_store*/
[email protected]264807b2012-04-25 14:49:371419 DELETE_COOKIE_EXPIRED);
1420 ++num_deleted;
1421 }
1422 }
1423
1424 return num_deleted;
1425}
1426
[email protected]f48b9432011-01-11 07:25:401427CookieMonster* CookieMonster::GetCookieMonster() {
1428 return this;
1429}
1430
[email protected]8ad5d462013-05-02 08:45:261431// This function must be called before the CookieMonster is used.
[email protected]93c53a32011-12-05 10:40:351432void CookieMonster::SetPersistSessionCookies(bool persist_session_cookies) {
[email protected]93c53a32011-12-05 10:40:351433 DCHECK(!initialized_);
1434 persist_session_cookies_ = persist_session_cookies;
1435}
1436
[email protected]bf510ed2012-06-05 08:31:431437void CookieMonster::SetForceKeepSessionState() {
[email protected]90499482013-06-01 00:39:501438 if (store_.get()) {
[email protected]bf510ed2012-06-05 08:31:431439 store_->SetForceKeepSessionState();
[email protected]93c53a32011-12-05 10:40:351440 }
1441}
1442
[email protected]f48b9432011-01-11 07:25:401443CookieMonster::~CookieMonster() {
1444 DeleteAll(false);
1445}
1446
1447bool CookieMonster::SetCookieWithCreationTime(const GURL& url,
1448 const std::string& cookie_line,
1449 const base::Time& creation_time) {
[email protected]90499482013-06-01 00:39:501450 DCHECK(!store_.get()) << "This method is only to be used by unit-tests.";
[email protected]20305ec2011-01-21 04:55:521451 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401452
1453 if (!HasCookieableScheme(url)) {
1454 return false;
1455 }
1456
erikchen1dd72a72015-05-06 20:45:051457 MarkCookieStoreAsInitialized();
1458 if (ShouldFetchAllCookiesWhenFetchingAnyCookie())
1459 FetchAllCookiesIfNecessary();
1460
[email protected]f48b9432011-01-11 07:25:401461 return SetCookieWithCreationTimeAndOptions(url, cookie_line, creation_time,
1462 CookieOptions());
1463}
1464
erikchen1dd72a72015-05-06 20:45:051465void CookieMonster::MarkCookieStoreAsInitialized() {
1466 initialized_ = true;
1467}
1468
1469void CookieMonster::FetchAllCookiesIfNecessary() {
1470 if (store_.get() && !started_fetching_all_cookies_) {
1471 started_fetching_all_cookies_ = true;
1472 FetchAllCookies();
1473 }
1474}
1475
1476bool CookieMonster::ShouldFetchAllCookiesWhenFetchingAnyCookie() {
1477 if (fetch_strategy_ == kUnknownFetch) {
1478 const std::string group_name =
1479 base::FieldTrialList::FindFullName(kCookieMonsterFetchStrategyName);
1480 if (group_name == kFetchWhenNecessaryName) {
1481 fetch_strategy_ = kFetchWhenNecessary;
1482 } else if (group_name == kAlwaysFetchName) {
1483 fetch_strategy_ = kAlwaysFetch;
1484 } else {
1485 // The logic in the conditional is redundant, but it makes trials of
1486 // the Finch experiment more explicit.
1487 fetch_strategy_ = kAlwaysFetch;
1488 }
1489 }
1490
1491 return fetch_strategy_ == kAlwaysFetch;
1492}
1493
1494void CookieMonster::FetchAllCookies() {
[email protected]90499482013-06-01 00:39:501495 DCHECK(store_.get()) << "Store must exist to initialize";
erikchen1dd72a72015-05-06 20:45:051496 DCHECK(!finished_fetching_all_cookies_)
1497 << "All cookies have already been fetched.";
[email protected]f48b9432011-01-11 07:25:401498
[email protected]218aa6a12011-09-13 17:38:381499 // We bind in the current time so that we can report the wall-clock time for
1500 // loading cookies.
1501 store_->Load(base::Bind(&CookieMonster::OnLoaded, this, TimeTicks::Now()));
1502}
[email protected]f48b9432011-01-11 07:25:401503
[email protected]218aa6a12011-09-13 17:38:381504void CookieMonster::OnLoaded(TimeTicks beginning_time,
1505 const std::vector<CanonicalCookie*>& cookies) {
1506 StoreLoadedCookies(cookies);
[email protected]c7593fb22011-11-14 23:54:271507 histogram_time_blocked_on_load_->AddTime(TimeTicks::Now() - beginning_time);
[email protected]218aa6a12011-09-13 17:38:381508
1509 // Invoke the task queue of cookie request.
1510 InvokeQueue();
1511}
1512
[email protected]8562034e2011-10-17 17:35:041513void CookieMonster::OnKeyLoaded(const std::string& key,
1514 const std::vector<CanonicalCookie*>& cookies) {
1515 // This function does its own separate locking.
1516 StoreLoadedCookies(cookies);
1517
mkwstbe84af312015-02-20 08:52:451518 std::deque<scoped_refptr<CookieMonsterTask>> tasks_pending_for_key;
[email protected]8562034e2011-10-17 17:35:041519
[email protected]bab72ec2013-10-30 20:50:021520 // We need to do this repeatedly until no more tasks were added to the queue
1521 // during the period where we release the lock.
1522 while (true) {
1523 {
1524 base::AutoLock autolock(lock_);
mkwstbe84af312015-02-20 08:52:451525 std::map<std::string,
1526 std::deque<scoped_refptr<CookieMonsterTask>>>::iterator it =
1527 tasks_pending_for_key_.find(key);
[email protected]bab72ec2013-10-30 20:50:021528 if (it == tasks_pending_for_key_.end()) {
1529 keys_loaded_.insert(key);
1530 return;
1531 }
1532 if (it->second.empty()) {
1533 keys_loaded_.insert(key);
1534 tasks_pending_for_key_.erase(it);
1535 return;
1536 }
1537 it->second.swap(tasks_pending_for_key);
1538 }
1539
1540 while (!tasks_pending_for_key.empty()) {
1541 scoped_refptr<CookieMonsterTask> task = tasks_pending_for_key.front();
1542 task->Run();
1543 tasks_pending_for_key.pop_front();
1544 }
[email protected]8562034e2011-10-17 17:35:041545 }
1546}
1547
[email protected]218aa6a12011-09-13 17:38:381548void CookieMonster::StoreLoadedCookies(
1549 const std::vector<CanonicalCookie*>& cookies) {
pkastingec2cdb52015-05-02 01:19:341550 // TODO(erikwright): Remove ScopedTracker below once crbug.com/457528 is
1551 // fixed.
1552 tracked_objects::ScopedTracker tracking_profile(
1553 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1554 "457528 CookieMonster::StoreLoadedCookies"));
1555
[email protected]f48b9432011-01-11 07:25:401556 // Initialize the store and sync in any saved persistent cookies. We don't
1557 // care if it's expired, insert it so it can be garbage collected, removed,
1558 // and sync'd.
[email protected]218aa6a12011-09-13 17:38:381559 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401560
[email protected]6210ce52013-09-20 03:33:141561 CookieItVector cookies_with_control_chars;
1562
[email protected]f48b9432011-01-11 07:25:401563 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
1564 it != cookies.end(); ++it) {
1565 int64 cookie_creation_time = (*it)->CreationDate().ToInternalValue();
1566
[email protected]8562034e2011-10-17 17:35:041567 if (creation_times_.insert(cookie_creation_time).second) {
[email protected]6210ce52013-09-20 03:33:141568 CookieMap::iterator inserted =
1569 InternalInsertCookie(GetKey((*it)->Domain()), *it, false);
[email protected]f48b9432011-01-11 07:25:401570 const Time cookie_access_time((*it)->LastAccessDate());
[email protected]8562034e2011-10-17 17:35:041571 if (earliest_access_time_.is_null() ||
1572 cookie_access_time < earliest_access_time_)
1573 earliest_access_time_ = cookie_access_time;
[email protected]6210ce52013-09-20 03:33:141574
1575 if (ContainsControlCharacter((*it)->Name()) ||
1576 ContainsControlCharacter((*it)->Value())) {
mkwstbe84af312015-02-20 08:52:451577 cookies_with_control_chars.push_back(inserted);
[email protected]6210ce52013-09-20 03:33:141578 }
[email protected]f48b9432011-01-11 07:25:401579 } else {
mkwstbe84af312015-02-20 08:52:451580 LOG(ERROR) << base::StringPrintf(
1581 "Found cookies with duplicate creation "
1582 "times in backing store: "
1583 "{name='%s', domain='%s', path='%s'}",
1584 (*it)->Name().c_str(), (*it)->Domain().c_str(),
1585 (*it)->Path().c_str());
[email protected]f48b9432011-01-11 07:25:401586 // We've been given ownership of the cookie and are throwing it
1587 // away; reclaim the space.
1588 delete (*it);
1589 }
1590 }
[email protected]f48b9432011-01-11 07:25:401591
[email protected]6210ce52013-09-20 03:33:141592 // Any cookies that contain control characters that we have loaded from the
1593 // persistent store should be deleted. See http://crbug.com/238041.
1594 for (CookieItVector::iterator it = cookies_with_control_chars.begin();
1595 it != cookies_with_control_chars.end();) {
1596 CookieItVector::iterator curit = it;
1597 ++it;
1598
1599 InternalDeleteCookie(*curit, true, DELETE_COOKIE_CONTROL_CHAR);
1600 }
1601
[email protected]f48b9432011-01-11 07:25:401602 // After importing cookies from the PersistentCookieStore, verify that
1603 // none of our other constraints are violated.
[email protected]f48b9432011-01-11 07:25:401604 // In particular, the backing store might have given us duplicate cookies.
[email protected]8562034e2011-10-17 17:35:041605
1606 // This method could be called multiple times due to priority loading, thus
1607 // cookies loaded in previous runs will be validated again, but this is OK
1608 // since they are expected to be much fewer than total DB.
[email protected]f48b9432011-01-11 07:25:401609 EnsureCookiesMapIsValid();
[email protected]218aa6a12011-09-13 17:38:381610}
[email protected]f48b9432011-01-11 07:25:401611
[email protected]218aa6a12011-09-13 17:38:381612void CookieMonster::InvokeQueue() {
1613 while (true) {
1614 scoped_refptr<CookieMonsterTask> request_task;
1615 {
1616 base::AutoLock autolock(lock_);
[email protected]0184df32013-05-14 00:53:551617 if (tasks_pending_.empty()) {
erikchen1dd72a72015-05-06 20:45:051618 finished_fetching_all_cookies_ = true;
[email protected]8562034e2011-10-17 17:35:041619 creation_times_.clear();
1620 keys_loaded_.clear();
[email protected]218aa6a12011-09-13 17:38:381621 break;
1622 }
[email protected]0184df32013-05-14 00:53:551623 request_task = tasks_pending_.front();
1624 tasks_pending_.pop();
[email protected]218aa6a12011-09-13 17:38:381625 }
1626 request_task->Run();
1627 }
[email protected]f48b9432011-01-11 07:25:401628}
1629
1630void CookieMonster::EnsureCookiesMapIsValid() {
1631 lock_.AssertAcquired();
1632
[email protected]f48b9432011-01-11 07:25:401633 // Iterate through all the of the cookies, grouped by host.
1634 CookieMap::iterator prev_range_end = cookies_.begin();
1635 while (prev_range_end != cookies_.end()) {
1636 CookieMap::iterator cur_range_begin = prev_range_end;
1637 const std::string key = cur_range_begin->first; // Keep a copy.
1638 CookieMap::iterator cur_range_end = cookies_.upper_bound(key);
1639 prev_range_end = cur_range_end;
1640
1641 // Ensure no equivalent cookies for this host.
ellyjonescabf57422015-08-21 18:44:511642 TrimDuplicateCookiesForKey(key, cur_range_begin, cur_range_end);
[email protected]f48b9432011-01-11 07:25:401643 }
[email protected]f48b9432011-01-11 07:25:401644}
1645
ellyjonescabf57422015-08-21 18:44:511646void CookieMonster::TrimDuplicateCookiesForKey(const std::string& key,
1647 CookieMap::iterator begin,
1648 CookieMap::iterator end) {
[email protected]f48b9432011-01-11 07:25:401649 lock_.AssertAcquired();
1650
1651 // Set of cookies ordered by creation time.
1652 typedef std::set<CookieMap::iterator, OrderByCreationTimeDesc> CookieSet;
1653
1654 // Helper map we populate to find the duplicates.
1655 typedef std::map<CookieSignature, CookieSet> EquivalenceMap;
1656 EquivalenceMap equivalent_cookies;
1657
1658 // The number of duplicate cookies that have been found.
1659 int num_duplicates = 0;
1660
1661 // Iterate through all of the cookies in our range, and insert them into
1662 // the equivalence map.
1663 for (CookieMap::iterator it = begin; it != end; ++it) {
1664 DCHECK_EQ(key, it->first);
1665 CanonicalCookie* cookie = it->second;
1666
mkwstbe84af312015-02-20 08:52:451667 CookieSignature signature(cookie->Name(), cookie->Domain(), cookie->Path());
[email protected]f48b9432011-01-11 07:25:401668 CookieSet& set = equivalent_cookies[signature];
1669
1670 // We found a duplicate!
1671 if (!set.empty())
1672 num_duplicates++;
1673
1674 // We save the iterator into |cookies_| rather than the actual cookie
1675 // pointer, since we may need to delete it later.
1676 bool insert_success = set.insert(it).second;
mkwstbe84af312015-02-20 08:52:451677 DCHECK(insert_success)
1678 << "Duplicate creation times found in duplicate cookie name scan.";
[email protected]f48b9432011-01-11 07:25:401679 }
1680
1681 // If there were no duplicates, we are done!
1682 if (num_duplicates == 0)
ellyjonescabf57422015-08-21 18:44:511683 return;
[email protected]f48b9432011-01-11 07:25:401684
1685 // Make sure we find everything below that we did above.
1686 int num_duplicates_found = 0;
1687
1688 // Otherwise, delete all the duplicate cookies, both from our in-memory store
1689 // and from the backing store.
1690 for (EquivalenceMap::iterator it = equivalent_cookies.begin();
mkwstbe84af312015-02-20 08:52:451691 it != equivalent_cookies.end(); ++it) {
[email protected]f48b9432011-01-11 07:25:401692 const CookieSignature& signature = it->first;
1693 CookieSet& dupes = it->second;
1694
1695 if (dupes.size() <= 1)
1696 continue; // This cookiename/path has no duplicates.
1697 num_duplicates_found += dupes.size() - 1;
1698
1699 // Since |dups| is sorted by creation time (descending), the first cookie
1700 // is the most recent one, so we will keep it. The rest are duplicates.
1701 dupes.erase(dupes.begin());
1702
1703 LOG(ERROR) << base::StringPrintf(
1704 "Found %d duplicate cookies for host='%s', "
1705 "with {name='%s', domain='%s', path='%s'}",
mkwstbe84af312015-02-20 08:52:451706 static_cast<int>(dupes.size()), key.c_str(), signature.name.c_str(),
1707 signature.domain.c_str(), signature.path.c_str());
[email protected]f48b9432011-01-11 07:25:401708
1709 // Remove all the cookies identified by |dupes|. It is valid to delete our
1710 // list of iterators one at a time, since |cookies_| is a multimap (they
1711 // don't invalidate existing iterators following deletion).
mkwstbe84af312015-02-20 08:52:451712 for (CookieSet::iterator dupes_it = dupes.begin(); dupes_it != dupes.end();
[email protected]f48b9432011-01-11 07:25:401713 ++dupes_it) {
[email protected]218aa6a12011-09-13 17:38:381714 InternalDeleteCookie(*dupes_it, true,
[email protected]f48b9432011-01-11 07:25:401715 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE);
1716 }
1717 }
1718 DCHECK_EQ(num_duplicates, num_duplicates_found);
[email protected]f48b9432011-01-11 07:25:401719}
1720
[email protected]ba4ad0e2011-03-15 08:12:471721// Note: file must be the last scheme.
mkwstbe84af312015-02-20 08:52:451722const char* const CookieMonster::kDefaultCookieableSchemes[] = {"http",
1723 "https",
1724 "ws",
1725 "wss",
1726 "file"};
[email protected]ba4ad0e2011-03-15 08:12:471727const int CookieMonster::kDefaultCookieableSchemesCount =
[email protected]5fa4f9a2013-10-03 10:13:161728 arraysize(kDefaultCookieableSchemes);
[email protected]ba4ad0e2011-03-15 08:12:471729
[email protected]f48b9432011-01-11 07:25:401730void CookieMonster::SetDefaultCookieableSchemes() {
[email protected]7c4b66b2014-01-04 12:28:131731 // Always disable file scheme unless SetEnableFileScheme(true) is called.
1732 SetCookieableSchemes(kDefaultCookieableSchemes,
1733 kDefaultCookieableSchemesCount - 1);
[email protected]f48b9432011-01-11 07:25:401734}
1735
[email protected]f48b9432011-01-11 07:25:401736void CookieMonster::FindCookiesForHostAndDomain(
1737 const GURL& url,
1738 const CookieOptions& options,
1739 bool update_access_time,
1740 std::vector<CanonicalCookie*>* cookies) {
1741 lock_.AssertAcquired();
1742
1743 const Time current_time(CurrentTime());
1744
1745 // Probe to save statistics relatively frequently. We do it here rather
1746 // than in the set path as many websites won't set cookies, and we
1747 // want to collect statistics whenever the browser's being used.
1748 RecordPeriodicStats(current_time);
1749
[email protected]8e1583672012-02-11 04:39:411750 // Can just dispatch to FindCookiesForKey
1751 const std::string key(GetKey(url.host()));
mkwstbe84af312015-02-20 08:52:451752 FindCookiesForKey(key, url, options, current_time, update_access_time,
1753 cookies);
[email protected]f48b9432011-01-11 07:25:401754}
1755
[email protected]dedec0b2013-02-28 04:50:101756void CookieMonster::FindCookiesForKey(const std::string& key,
1757 const GURL& url,
1758 const CookieOptions& options,
1759 const Time& current,
1760 bool update_access_time,
1761 std::vector<CanonicalCookie*>* cookies) {
[email protected]f48b9432011-01-11 07:25:401762 lock_.AssertAcquired();
1763
[email protected]f48b9432011-01-11 07:25:401764 for (CookieMapItPair its = cookies_.equal_range(key);
mkwstbe84af312015-02-20 08:52:451765 its.first != its.second;) {
[email protected]f48b9432011-01-11 07:25:401766 CookieMap::iterator curit = its.first;
1767 CanonicalCookie* cc = curit->second;
1768 ++its.first;
1769
1770 // If the cookie is expired, delete it.
[email protected]ba4ad0e2011-03-15 08:12:471771 if (cc->IsExpired(current) && !keep_expired_cookies_) {
[email protected]f48b9432011-01-11 07:25:401772 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
1773 continue;
1774 }
1775
[email protected]65f4e7e2012-12-12 21:56:541776 // Filter out cookies that should not be included for a request to the
1777 // given |url|. HTTP only cookies are filtered depending on the passed
1778 // cookie |options|.
1779 if (!cc->IncludeForRequestURL(url, options))
[email protected]f48b9432011-01-11 07:25:401780 continue;
1781
[email protected]65f4e7e2012-12-12 21:56:541782 // Add this cookie to the set of matching cookies. Update the access
[email protected]f48b9432011-01-11 07:25:401783 // time if we've been requested to do so.
1784 if (update_access_time) {
1785 InternalUpdateCookieAccessTime(cc, current);
1786 }
1787 cookies->push_back(cc);
1788 }
1789}
1790
1791bool CookieMonster::DeleteAnyEquivalentCookie(const std::string& key,
1792 const CanonicalCookie& ecc,
[email protected]e7c590e52011-03-30 08:33:551793 bool skip_httponly,
1794 bool already_expired) {
[email protected]f48b9432011-01-11 07:25:401795 lock_.AssertAcquired();
1796
1797 bool found_equivalent_cookie = false;
1798 bool skipped_httponly = false;
1799 for (CookieMapItPair its = cookies_.equal_range(key);
mkwstbe84af312015-02-20 08:52:451800 its.first != its.second;) {
[email protected]f48b9432011-01-11 07:25:401801 CookieMap::iterator curit = its.first;
1802 CanonicalCookie* cc = curit->second;
1803 ++its.first;
1804
1805 if (ecc.IsEquivalent(*cc)) {
1806 // We should never have more than one equivalent cookie, since they should
1807 // overwrite each other.
mkwstbe84af312015-02-20 08:52:451808 CHECK(!found_equivalent_cookie)
1809 << "Duplicate equivalent cookies found, cookie store is corrupted.";
[email protected]f48b9432011-01-11 07:25:401810 if (skip_httponly && cc->IsHttpOnly()) {
1811 skipped_httponly = true;
1812 } else {
mkwstbe84af312015-02-20 08:52:451813 InternalDeleteCookie(curit, true, already_expired
1814 ? DELETE_COOKIE_EXPIRED_OVERWRITE
1815 : DELETE_COOKIE_OVERWRITE);
[email protected]f48b9432011-01-11 07:25:401816 }
1817 found_equivalent_cookie = true;
1818 }
1819 }
1820 return skipped_httponly;
1821}
1822
[email protected]6210ce52013-09-20 03:33:141823CookieMonster::CookieMap::iterator CookieMonster::InternalInsertCookie(
1824 const std::string& key,
1825 CanonicalCookie* cc,
1826 bool sync_to_store) {
pkastinga9269aa42015-04-10 01:42:261827 // TODO(mkwst): Remove ScopedTracker below once crbug.com/456373 is fixed.
pkasting58e029b2015-02-21 05:17:281828 tracked_objects::ScopedTracker tracking_profile(
1829 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1830 "456373 CookieMonster::InternalInsertCookie"));
[email protected]f48b9432011-01-11 07:25:401831 lock_.AssertAcquired();
1832
[email protected]90499482013-06-01 00:39:501833 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() &&
1834 sync_to_store)
[email protected]f48b9432011-01-11 07:25:401835 store_->AddCookie(*cc);
[email protected]6210ce52013-09-20 03:33:141836 CookieMap::iterator inserted =
1837 cookies_.insert(CookieMap::value_type(key, cc));
[email protected]8bb846f2011-03-23 12:08:181838 if (delegate_.get()) {
mkwstbe84af312015-02-20 08:52:451839 delegate_->OnCookieChanged(*cc, false,
1840 CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT);
[email protected]8bb846f2011-03-23 12:08:181841 }
mkwstc1aa4cc2015-04-03 19:57:451842
1843 // See InitializeHistograms() for details.
estark7feb65c2b2015-08-21 23:38:201844 int32_t cookie_type_sample =
1845 cc->IsFirstPartyOnly() ? 1 << COOKIE_TYPE_FIRSTPARTYONLY : 0;
1846 cookie_type_sample |= cc->IsHttpOnly() ? 1 << COOKIE_TYPE_HTTPONLY : 0;
1847 cookie_type_sample |= cc->IsSecure() ? 1 << COOKIE_TYPE_SECURE : 0;
1848 histogram_cookie_type_->Add(cookie_type_sample);
1849
1850 // Histogram the type of scheme used on URLs that set cookies. This
1851 // intentionally includes cookies that are set or overwritten by
1852 // http:// URLs, but not cookies that are cleared by http:// URLs, to
1853 // understand if the former behavior can be deprecated for Secure
1854 // cookies.
1855 if (!cc->Source().is_empty()) {
1856 CookieSource cookie_source_sample;
1857 if (cc->Source().SchemeIsCryptographic()) {
1858 cookie_source_sample =
1859 cc->IsSecure() ? COOKIE_SOURCE_SECURE_COOKIE_CRYPTOGRAPHIC_SCHEME
1860 : COOKIE_SOURCE_NONSECURE_COOKIE_CRYPTOGRAPHIC_SCHEME;
1861 } else {
1862 cookie_source_sample =
1863 cc->IsSecure()
1864 ? COOKIE_SOURCE_SECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME
1865 : COOKIE_SOURCE_NONSECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME;
1866 }
1867 histogram_cookie_source_scheme_->Add(cookie_source_sample);
1868 }
mkwstc1aa4cc2015-04-03 19:57:451869
msarda0aad8f02014-10-30 09:22:391870 RunCallbacks(*cc, false);
[email protected]6210ce52013-09-20 03:33:141871
1872 return inserted;
[email protected]f48b9432011-01-11 07:25:401873}
1874
[email protected]34602282010-02-03 22:14:151875bool CookieMonster::SetCookieWithCreationTimeAndOptions(
1876 const GURL& url,
1877 const std::string& cookie_line,
1878 const Time& creation_time_or_null,
1879 const CookieOptions& options) {
[email protected]b866a02d2010-07-28 16:41:041880 lock_.AssertAcquired();
initial.commit586acc5fe2008-07-26 22:42:521881
[email protected]4d3ce782010-10-29 18:31:281882 VLOG(kVlogSetCookies) << "SetCookie() line: " << cookie_line;
initial.commit586acc5fe2008-07-26 22:42:521883
[email protected]34602282010-02-03 22:14:151884 Time creation_time = creation_time_or_null;
1885 if (creation_time.is_null()) {
1886 creation_time = CurrentTime();
1887 last_time_seen_ = creation_time;
1888 }
1889
[email protected]abbd13b2012-11-15 17:54:201890 scoped_ptr<CanonicalCookie> cc(
1891 CanonicalCookie::Create(url, cookie_line, creation_time, options));
initial.commit586acc5fe2008-07-26 22:42:521892
1893 if (!cc.get()) {
[email protected]4d3ce782010-10-29 18:31:281894 VLOG(kVlogSetCookies) << "WARNING: Failed to allocate CanonicalCookie";
initial.commit586acc5fe2008-07-26 22:42:521895 return false;
1896 }
[email protected]fa77eb512010-07-22 16:12:511897 return SetCanonicalCookie(&cc, creation_time, options);
[email protected]f325f1e12010-04-30 22:38:551898}
initial.commit586acc5fe2008-07-26 22:42:521899
[email protected]f325f1e12010-04-30 22:38:551900bool CookieMonster::SetCanonicalCookie(scoped_ptr<CanonicalCookie>* cc,
[email protected]f325f1e12010-04-30 22:38:551901 const Time& creation_time,
1902 const CookieOptions& options) {
[email protected]7a964a72010-09-07 19:33:261903 const std::string key(GetKey((*cc)->Domain()));
[email protected]e7c590e52011-03-30 08:33:551904 bool already_expired = (*cc)->IsExpired(creation_time);
ellyjones399e35a22014-10-27 11:09:561905
estarkcd39c11f2015-10-19 19:46:361906 if (options.enforce_prefixes() && !CheckCookiePrefix(cc->get(), options)) {
1907 VLOG(kVlogSetCookies) << "SetCookie() not storing cookie '" << (*cc)->Name()
1908 << "' that violates prefix rules.";
1909 return false;
1910 }
1911
[email protected]e7c590e52011-03-30 08:33:551912 if (DeleteAnyEquivalentCookie(key, **cc, options.exclude_httponly(),
1913 already_expired)) {
[email protected]4d3ce782010-10-29 18:31:281914 VLOG(kVlogSetCookies) << "SetCookie() not clobbering httponly cookie";
[email protected]3a96c742008-11-19 19:46:271915 return false;
1916 }
initial.commit586acc5fe2008-07-26 22:42:521917
mkwstbe84af312015-02-20 08:52:451918 VLOG(kVlogSetCookies) << "SetCookie() key: " << key
1919 << " cc: " << (*cc)->DebugString();
initial.commit586acc5fe2008-07-26 22:42:521920
1921 // Realize that we might be setting an expired cookie, and the only point
1922 // was to delete the cookie which we've already done.
[email protected]e7c590e52011-03-30 08:33:551923 if (!already_expired || keep_expired_cookies_) {
[email protected]374f58b2010-07-20 15:29:261924 // See InitializeHistograms() for details.
[email protected]10b691f2012-07-11 15:22:151925 if ((*cc)->IsPersistent()) {
[email protected]8475bee2011-03-17 18:40:241926 histogram_expiration_duration_minutes_->Add(
1927 ((*cc)->ExpiryDate() - creation_time).InMinutes());
1928 }
1929
ellyjones399e35a22014-10-27 11:09:561930 {
1931 CanonicalCookie cookie = *(cc->get());
1932 InternalInsertCookie(key, cc->release(), true);
ellyjones399e35a22014-10-27 11:09:561933 }
[email protected]348dd662013-03-13 20:25:071934 } else {
1935 VLOG(kVlogSetCookies) << "SetCookie() not storing already expired cookie.";
[email protected]c4058fb2010-06-22 17:25:261936 }
initial.commit586acc5fe2008-07-26 22:42:521937
1938 // We assume that hopefully setting a cookie will be less common than
1939 // querying a cookie. Since setting a cookie can put us over our limits,
1940 // make sure that we garbage collect... We can also make the assumption that
1941 // if a cookie was set, in the common case it will be used soon after,
1942 // and we will purge the expired cookies in GetCookies().
[email protected]7a964a72010-09-07 19:33:261943 GarbageCollect(creation_time, key);
initial.commit586acc5fe2008-07-26 22:42:521944
1945 return true;
1946}
1947
drogerd5d1278c2015-03-17 19:21:511948bool CookieMonster::SetCanonicalCookies(const CookieList& list) {
1949 base::AutoLock autolock(lock_);
1950
ttuttle859dc7a2015-04-23 19:42:291951 CookieOptions options;
drogerd5d1278c2015-03-17 19:21:511952 options.set_include_httponly();
1953
1954 for (CookieList::const_iterator it = list.begin(); it != list.end(); ++it) {
1955 scoped_ptr<CanonicalCookie> canonical_cookie(new CanonicalCookie(*it));
1956 if (!SetCanonicalCookie(&canonical_cookie, it->CreationDate(), options))
1957 return false;
1958 }
1959
1960 return true;
1961}
1962
[email protected]7a964a72010-09-07 19:33:261963void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie* cc,
1964 const Time& current) {
[email protected]bb8905722010-05-21 17:29:041965 lock_.AssertAcquired();
1966
[email protected]77e0a462008-11-01 00:43:351967 // Based off the Mozilla code. When a cookie has been accessed recently,
1968 // don't bother updating its access time again. This reduces the number of
1969 // updates we do during pageload, which in turn reduces the chance our storage
1970 // backend will hit its batch thresholds and be forced to update.
[email protected]77e0a462008-11-01 00:43:351971 if ((current - cc->LastAccessDate()) < last_access_threshold_)
1972 return;
1973
1974 cc->SetLastAccessDate(current);
[email protected]90499482013-06-01 00:39:501975 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get())
[email protected]77e0a462008-11-01 00:43:351976 store_->UpdateCookieAccessTime(*cc);
1977}
1978
[email protected]6210ce52013-09-20 03:33:141979// InternalDeleteCookies must not invalidate iterators other than the one being
1980// deleted.
initial.commit586acc5fe2008-07-26 22:42:521981void CookieMonster::InternalDeleteCookie(CookieMap::iterator it,
[email protected]c4058fb2010-06-22 17:25:261982 bool sync_to_store,
1983 DeletionCause deletion_cause) {
[email protected]bb8905722010-05-21 17:29:041984 lock_.AssertAcquired();
1985
[email protected]8bb846f2011-03-23 12:08:181986 // Ideally, this would be asserted up where we define ChangeCauseMapping,
1987 // but DeletionCause's visibility (or lack thereof) forces us to make
1988 // this check here.
mostynb91e0da982015-01-20 19:17:271989 static_assert(arraysize(ChangeCauseMapping) == DELETE_COOKIE_LAST_ENTRY + 1,
1990 "ChangeCauseMapping size should match DeletionCause size");
[email protected]8bb846f2011-03-23 12:08:181991
[email protected]374f58b2010-07-20 15:29:261992 // See InitializeHistograms() for details.
[email protected]7a964a72010-09-07 19:33:261993 if (deletion_cause != DELETE_COOKIE_DONT_RECORD)
1994 histogram_cookie_deletion_cause_->Add(deletion_cause);
[email protected]c4058fb2010-06-22 17:25:261995
initial.commit586acc5fe2008-07-26 22:42:521996 CanonicalCookie* cc = it->second;
xiyuan8dbb89892015-04-13 17:04:301997 VLOG(kVlogSetCookies) << "InternalDeleteCookie()"
1998 << ", cause:" << deletion_cause
1999 << ", cc: " << cc->DebugString();
[email protected]7a964a72010-09-07 19:33:262000
[email protected]90499482013-06-01 00:39:502001 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() &&
2002 sync_to_store)
initial.commit586acc5fe2008-07-26 22:42:522003 store_->DeleteCookie(*cc);
[email protected]8bb846f2011-03-23 12:08:182004 if (delegate_.get()) {
2005 ChangeCausePair mapping = ChangeCauseMapping[deletion_cause];
2006
2007 if (mapping.notify)
2008 delegate_->OnCookieChanged(*cc, true, mapping.cause);
2009 }
msarda0aad8f02014-10-30 09:22:392010 RunCallbacks(*cc, true);
initial.commit586acc5fe2008-07-26 22:42:522011 cookies_.erase(it);
2012 delete cc;
2013}
2014
[email protected]8807b322010-10-01 17:10:142015// Domain expiry behavior is unchanged by key/expiry scheme (the
[email protected]8ad5d462013-05-02 08:45:262016// meaning of the key is different, but that's not visible to this routine).
mkwstbe84af312015-02-20 08:52:452017int CookieMonster::GarbageCollect(const Time& current, const std::string& key) {
[email protected]bb8905722010-05-21 17:29:042018 lock_.AssertAcquired();
2019
initial.commit586acc5fe2008-07-26 22:42:522020 int num_deleted = 0;
mkwstbe84af312015-02-20 08:52:452021 Time safe_date(Time::Now() - TimeDelta::FromDays(kSafeFromGlobalPurgeDays));
initial.commit586acc5fe2008-07-26 22:42:522022
[email protected]8ad5d462013-05-02 08:45:262023 // Collect garbage for this key, minding cookie priorities.
[email protected]7a964a72010-09-07 19:33:262024 if (cookies_.count(key) > kDomainMaxCookies) {
[email protected]4d3ce782010-10-29 18:31:282025 VLOG(kVlogGarbageCollection) << "GarbageCollect() key: " << key;
[email protected]7a964a72010-09-07 19:33:262026
[email protected]8ad5d462013-05-02 08:45:262027 CookieItVector cookie_its;
mkwstbe84af312015-02-20 08:52:452028 num_deleted +=
2029 GarbageCollectExpired(current, cookies_.equal_range(key), &cookie_its);
[email protected]8ad5d462013-05-02 08:45:262030 if (cookie_its.size() > kDomainMaxCookies) {
2031 VLOG(kVlogGarbageCollection) << "Deep Garbage Collect domain.";
2032 size_t purge_goal =
2033 cookie_its.size() - (kDomainMaxCookies - kDomainPurgeCookies);
2034 DCHECK(purge_goal > kDomainPurgeCookies);
2035
2036 // Boundary iterators into |cookie_its| for different priorities.
2037 CookieItVector::iterator it_bdd[4];
2038 // Intialize |it_bdd| while sorting |cookie_its| by priorities.
2039 // Schematic: [MLLHMHHLMM] => [LLL|MMMM|HHH], with 4 boundaries.
2040 it_bdd[0] = cookie_its.begin();
2041 it_bdd[3] = cookie_its.end();
mkwstbe84af312015-02-20 08:52:452042 it_bdd[1] =
2043 PartitionCookieByPriority(it_bdd[0], it_bdd[3], COOKIE_PRIORITY_LOW);
[email protected]8ad5d462013-05-02 08:45:262044 it_bdd[2] = PartitionCookieByPriority(it_bdd[1], it_bdd[3],
2045 COOKIE_PRIORITY_MEDIUM);
mkwstbe84af312015-02-20 08:52:452046 size_t quota[3] = {kDomainCookiesQuotaLow,
2047 kDomainCookiesQuotaMedium,
2048 kDomainCookiesQuotaHigh};
[email protected]8ad5d462013-05-02 08:45:262049
2050 // Purge domain cookies in 3 rounds.
2051 // Round 1: consider low-priority cookies only: evict least-recently
2052 // accessed, while protecting quota[0] of these from deletion.
2053 // Round 2: consider {low, medium}-priority cookies, evict least-recently
2054 // accessed, while protecting quota[0] + quota[1].
2055 // Round 3: consider all cookies, evict least-recently accessed.
2056 size_t accumulated_quota = 0;
2057 CookieItVector::iterator it_purge_begin = it_bdd[0];
2058 for (int i = 0; i < 3 && purge_goal > 0; ++i) {
2059 accumulated_quota += quota[i];
2060
[email protected]8ad5d462013-05-02 08:45:262061 size_t num_considered = it_bdd[i + 1] - it_purge_begin;
2062 if (num_considered <= accumulated_quota)
2063 continue;
2064
2065 // Number of cookies that will be purged in this round.
2066 size_t round_goal =
2067 std::min(purge_goal, num_considered - accumulated_quota);
2068 purge_goal -= round_goal;
2069
2070 SortLeastRecentlyAccessed(it_purge_begin, it_bdd[i + 1], round_goal);
2071 // Cookies accessed on or after |safe_date| would have been safe from
2072 // global purge, and we want to keep track of this.
2073 CookieItVector::iterator it_purge_end = it_purge_begin + round_goal;
2074 CookieItVector::iterator it_purge_middle =
2075 LowerBoundAccessDate(it_purge_begin, it_purge_end, safe_date);
2076 // Delete cookies accessed before |safe_date|.
2077 num_deleted += GarbageCollectDeleteRange(
mkwstbe84af312015-02-20 08:52:452078 current, DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE, it_purge_begin,
[email protected]8ad5d462013-05-02 08:45:262079 it_purge_middle);
2080 // Delete cookies accessed on or after |safe_date|.
2081 num_deleted += GarbageCollectDeleteRange(
mkwstbe84af312015-02-20 08:52:452082 current, DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE, it_purge_middle,
[email protected]8ad5d462013-05-02 08:45:262083 it_purge_end);
2084 it_purge_begin = it_purge_end;
2085 }
2086 DCHECK_EQ(0U, purge_goal);
[email protected]8807b322010-10-01 17:10:142087 }
initial.commit586acc5fe2008-07-26 22:42:522088 }
2089
[email protected]8ad5d462013-05-02 08:45:262090 // Collect garbage for everything. With firefox style we want to preserve
2091 // cookies accessed in kSafeFromGlobalPurgeDays, otherwise evict.
mkwstbe84af312015-02-20 08:52:452092 if (cookies_.size() > kMaxCookies && earliest_access_time_ < safe_date) {
[email protected]4d3ce782010-10-29 18:31:282093 VLOG(kVlogGarbageCollection) << "GarbageCollect() everything";
[email protected]8ad5d462013-05-02 08:45:262094 CookieItVector cookie_its;
[email protected]7a964a72010-09-07 19:33:262095 num_deleted += GarbageCollectExpired(
2096 current, CookieMapItPair(cookies_.begin(), cookies_.end()),
2097 &cookie_its);
[email protected]8ad5d462013-05-02 08:45:262098 if (cookie_its.size() > kMaxCookies) {
2099 VLOG(kVlogGarbageCollection) << "Deep Garbage Collect everything.";
2100 size_t purge_goal = cookie_its.size() - (kMaxCookies - kPurgeCookies);
2101 DCHECK(purge_goal > kPurgeCookies);
2102 // Sorts up to *and including* |cookie_its[purge_goal]|, so
2103 // |earliest_access_time| will be properly assigned even if
2104 // |global_purge_it| == |cookie_its.begin() + purge_goal|.
2105 SortLeastRecentlyAccessed(cookie_its.begin(), cookie_its.end(),
2106 purge_goal);
2107 // Find boundary to cookies older than safe_date.
mkwstbe84af312015-02-20 08:52:452108 CookieItVector::iterator global_purge_it = LowerBoundAccessDate(
2109 cookie_its.begin(), cookie_its.begin() + purge_goal, safe_date);
[email protected]8ad5d462013-05-02 08:45:262110 // Only delete the old cookies.
mkwstbe84af312015-02-20 08:52:452111 num_deleted +=
2112 GarbageCollectDeleteRange(current, DELETE_COOKIE_EVICTED_GLOBAL,
2113 cookie_its.begin(), global_purge_it);
[email protected]8ad5d462013-05-02 08:45:262114 // Set access day to the oldest cookie that wasn't deleted.
2115 earliest_access_time_ = (*global_purge_it)->second->LastAccessDate();
[email protected]8807b322010-10-01 17:10:142116 }
[email protected]c890ed192008-10-30 23:45:532117 }
2118
2119 return num_deleted;
2120}
2121
mkwstbe84af312015-02-20 08:52:452122int CookieMonster::GarbageCollectExpired(const Time& current,
2123 const CookieMapItPair& itpair,
2124 CookieItVector* cookie_its) {
[email protected]ba4ad0e2011-03-15 08:12:472125 if (keep_expired_cookies_)
2126 return 0;
2127
[email protected]bb8905722010-05-21 17:29:042128 lock_.AssertAcquired();
2129
[email protected]c890ed192008-10-30 23:45:532130 int num_deleted = 0;
2131 for (CookieMap::iterator it = itpair.first, end = itpair.second; it != end;) {
2132 CookieMap::iterator curit = it;
2133 ++it;
2134
2135 if (curit->second->IsExpired(current)) {
[email protected]2f3f3592010-07-07 20:11:512136 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
[email protected]c890ed192008-10-30 23:45:532137 ++num_deleted;
2138 } else if (cookie_its) {
2139 cookie_its->push_back(curit);
2140 }
initial.commit586acc5fe2008-07-26 22:42:522141 }
2142
2143 return num_deleted;
2144}
2145
mkwstbe84af312015-02-20 08:52:452146int CookieMonster::GarbageCollectDeleteRange(const Time& current,
2147 DeletionCause cause,
2148 CookieItVector::iterator it_begin,
2149 CookieItVector::iterator it_end) {
[email protected]8ad5d462013-05-02 08:45:262150 for (CookieItVector::iterator it = it_begin; it != it_end; it++) {
2151 histogram_evicted_last_access_minutes_->Add(
2152 (current - (*it)->second->LastAccessDate()).InMinutes());
2153 InternalDeleteCookie((*it), true, cause);
[email protected]c10da4b02010-03-25 14:38:322154 }
[email protected]8ad5d462013-05-02 08:45:262155 return it_end - it_begin;
[email protected]c10da4b02010-03-25 14:38:322156}
2157
[email protected]ed32c212013-05-14 20:49:292158// A wrapper around registry_controlled_domains::GetDomainAndRegistry
[email protected]f48b9432011-01-11 07:25:402159// to make clear we're creating a key for our local map. Here and
2160// in FindCookiesForHostAndDomain() are the only two places where
2161// we need to conditionalize based on key type.
2162//
2163// Note that this key algorithm explicitly ignores the scheme. This is
2164// because when we're entering cookies into the map from the backing store,
2165// we in general won't have the scheme at that point.
2166// In practical terms, this means that file cookies will be stored
2167// in the map either by an empty string or by UNC name (and will be
2168// limited by kMaxCookiesPerHost), and extension cookies will be stored
2169// based on the single extension id, as the extension id won't have the
2170// form of a DNS host and hence GetKey() will return it unchanged.
2171//
2172// Arguably the right thing to do here is to make the key
2173// algorithm dependent on the scheme, and make sure that the scheme is
2174// available everywhere the key must be obtained (specfically at backing
2175// store load time). This would require either changing the backing store
2176// database schema to include the scheme (far more trouble than it's worth), or
2177// separating out file cookies into their own CookieMonster instance and
2178// thus restricting each scheme to a single cookie monster (which might
2179// be worth it, but is still too much trouble to solve what is currently a
2180// non-problem).
2181std::string CookieMonster::GetKey(const std::string& domain) const {
[email protected]f48b9432011-01-11 07:25:402182 std::string effective_domain(
[email protected]ed32c212013-05-14 20:49:292183 registry_controlled_domains::GetDomainAndRegistry(
[email protected]aabe1792014-01-30 21:37:462184 domain, registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES));
[email protected]f48b9432011-01-11 07:25:402185 if (effective_domain.empty())
2186 effective_domain = domain;
2187
2188 if (!effective_domain.empty() && effective_domain[0] == '.')
2189 return effective_domain.substr(1);
2190 return effective_domain;
2191}
2192
[email protected]97a3b6e2012-06-12 01:53:562193bool CookieMonster::IsCookieableScheme(const std::string& scheme) {
2194 base::AutoLock autolock(lock_);
2195
2196 return std::find(cookieable_schemes_.begin(), cookieable_schemes_.end(),
2197 scheme) != cookieable_schemes_.end();
2198}
2199
[email protected]f48b9432011-01-11 07:25:402200bool CookieMonster::HasCookieableScheme(const GURL& url) {
2201 lock_.AssertAcquired();
2202
2203 // Make sure the request is on a cookie-able url scheme.
2204 for (size_t i = 0; i < cookieable_schemes_.size(); ++i) {
2205 // We matched a scheme.
2206 if (url.SchemeIs(cookieable_schemes_[i].c_str())) {
2207 // We've matched a supported scheme.
initial.commit586acc5fe2008-07-26 22:42:522208 return true;
2209 }
2210 }
[email protected]f48b9432011-01-11 07:25:402211
2212 // The scheme didn't match any in our whitelist.
mkwstbe84af312015-02-20 08:52:452213 VLOG(kVlogPerCookieMonster)
2214 << "WARNING: Unsupported cookie scheme: " << url.scheme();
initial.commit586acc5fe2008-07-26 22:42:522215 return false;
2216}
2217
[email protected]c4058fb2010-06-22 17:25:262218// Test to see if stats should be recorded, and record them if so.
2219// The goal here is to get sampling for the average browser-hour of
2220// activity. We won't take samples when the web isn't being surfed,
2221// and when the web is being surfed, we'll take samples about every
2222// kRecordStatisticsIntervalSeconds.
2223// last_statistic_record_time_ is initialized to Now() rather than null
2224// in the constructor so that we won't take statistics right after
2225// startup, to avoid bias from browsers that are started but not used.
2226void CookieMonster::RecordPeriodicStats(const base::Time& current_time) {
2227 const base::TimeDelta kRecordStatisticsIntervalTime(
2228 base::TimeDelta::FromSeconds(kRecordStatisticsIntervalSeconds));
2229
[email protected]7a964a72010-09-07 19:33:262230 // If we've taken statistics recently, return.
2231 if (current_time - last_statistic_record_time_ <=
[email protected]c4058fb2010-06-22 17:25:262232 kRecordStatisticsIntervalTime) {
[email protected]7a964a72010-09-07 19:33:262233 return;
[email protected]c4058fb2010-06-22 17:25:262234 }
[email protected]7a964a72010-09-07 19:33:262235
2236 // See InitializeHistograms() for details.
2237 histogram_count_->Add(cookies_.size());
2238
2239 // More detailed statistics on cookie counts at different granularities.
[email protected]7a964a72010-09-07 19:33:262240 last_statistic_record_time_ = current_time;
[email protected]c4058fb2010-06-22 17:25:262241}
2242
[email protected]f48b9432011-01-11 07:25:402243// Initialize all histogram counter variables used in this class.
2244//
2245// Normal histogram usage involves using the macros defined in
2246// histogram.h, which automatically takes care of declaring these
2247// variables (as statics), initializing them, and accumulating into
2248// them, all from a single entry point. Unfortunately, that solution
2249// doesn't work for the CookieMonster, as it's vulnerable to races between
2250// separate threads executing the same functions and hence initializing the
2251// same static variables. There isn't a race danger in the histogram
2252// accumulation calls; they are written to be resilient to simultaneous
2253// calls from multiple threads.
2254//
2255// The solution taken here is to have per-CookieMonster instance
2256// variables that are constructed during CookieMonster construction.
2257// Note that these variables refer to the same underlying histogram,
2258// so we still race (but safely) with other CookieMonster instances
2259// for accumulation.
2260//
2261// To do this we've expanded out the individual histogram macros calls,
2262// with declarations of the variables in the class decl, initialization here
2263// (done from the class constructor) and direct calls to the accumulation
2264// methods where needed. The specific histogram macro calls on which the
2265// initialization is based are included in comments below.
2266void CookieMonster::InitializeHistograms() {
2267 // From UMA_HISTOGRAM_CUSTOM_COUNTS
2268 histogram_expiration_duration_minutes_ = base::Histogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452269 "Cookie.ExpirationDurationMinutes", 1, kMinutesInTenYears, 50,
[email protected]f48b9432011-01-11 07:25:402270 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]f48b9432011-01-11 07:25:402271 histogram_evicted_last_access_minutes_ = base::Histogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452272 "Cookie.EvictedLastAccessMinutes", 1, kMinutesInTenYears, 50,
[email protected]f48b9432011-01-11 07:25:402273 base::Histogram::kUmaTargetedHistogramFlag);
2274 histogram_count_ = base::Histogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452275 "Cookie.Count", 1, 4000, 50, base::Histogram::kUmaTargetedHistogramFlag);
[email protected]f48b9432011-01-11 07:25:402276
2277 // From UMA_HISTOGRAM_ENUMERATION
2278 histogram_cookie_deletion_cause_ = base::LinearHistogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452279 "Cookie.DeletionCause", 1, DELETE_COOKIE_LAST_ENTRY - 1,
2280 DELETE_COOKIE_LAST_ENTRY, base::Histogram::kUmaTargetedHistogramFlag);
mkwstc1aa4cc2015-04-03 19:57:452281 histogram_cookie_type_ = base::LinearHistogram::FactoryGet(
mkwst87378d92015-04-10 21:22:112282 "Cookie.Type", 1, (1 << COOKIE_TYPE_LAST_ENTRY) - 1,
2283 1 << COOKIE_TYPE_LAST_ENTRY, base::Histogram::kUmaTargetedHistogramFlag);
estark7feb65c2b2015-08-21 23:38:202284 histogram_cookie_source_scheme_ = base::LinearHistogram::FactoryGet(
2285 "Cookie.CookieSourceScheme", 1, COOKIE_SOURCE_LAST_ENTRY - 1,
2286 COOKIE_SOURCE_LAST_ENTRY, base::Histogram::kUmaTargetedHistogramFlag);
[email protected]f48b9432011-01-11 07:25:402287
2288 // From UMA_HISTOGRAM_{CUSTOM_,}TIMES
[email protected]c7593fb22011-11-14 23:54:272289 histogram_time_blocked_on_load_ = base::Histogram::FactoryTimeGet(
mkwstbe84af312015-02-20 08:52:452290 "Cookie.TimeBlockedOnLoad", base::TimeDelta::FromMilliseconds(1),
2291 base::TimeDelta::FromMinutes(1), 50,
2292 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]f48b9432011-01-11 07:25:402293}
2294
[email protected]f48b9432011-01-11 07:25:402295// The system resolution is not high enough, so we can have multiple
2296// set cookies that result in the same system time. When this happens, we
2297// increment by one Time unit. Let's hope computers don't get too fast.
2298Time CookieMonster::CurrentTime() {
mkwstbe84af312015-02-20 08:52:452299 return std::max(Time::Now(), Time::FromInternalValue(
2300 last_time_seen_.ToInternalValue() + 1));
[email protected]f48b9432011-01-11 07:25:402301}
2302
drogerd5d1278c2015-03-17 19:21:512303void CookieMonster::ComputeCookieDiff(CookieList* old_cookies,
2304 CookieList* new_cookies,
2305 CookieList* cookies_to_add,
2306 CookieList* cookies_to_delete) {
2307 DCHECK(old_cookies);
2308 DCHECK(new_cookies);
2309 DCHECK(cookies_to_add);
2310 DCHECK(cookies_to_delete);
2311 DCHECK(cookies_to_add->empty());
2312 DCHECK(cookies_to_delete->empty());
2313
2314 // Sort both lists.
2315 // A set ordered by FullDiffCookieSorter is also ordered by
2316 // PartialDiffCookieSorter.
2317 std::sort(old_cookies->begin(), old_cookies->end(), FullDiffCookieSorter);
2318 std::sort(new_cookies->begin(), new_cookies->end(), FullDiffCookieSorter);
2319
2320 // Select any old cookie for deletion if no new cookie has the same name,
2321 // domain, and path.
2322 std::set_difference(
2323 old_cookies->begin(), old_cookies->end(), new_cookies->begin(),
2324 new_cookies->end(),
2325 std::inserter(*cookies_to_delete, cookies_to_delete->begin()),
2326 PartialDiffCookieSorter);
2327
2328 // Select any new cookie for addition (or update) if no old cookie is exactly
2329 // equivalent.
2330 std::set_difference(new_cookies->begin(), new_cookies->end(),
2331 old_cookies->begin(), old_cookies->end(),
2332 std::inserter(*cookies_to_add, cookies_to_add->begin()),
2333 FullDiffCookieSorter);
2334}
2335
ellyjones399e35a22014-10-27 11:09:562336scoped_ptr<CookieStore::CookieChangedSubscription>
mkwstbe84af312015-02-20 08:52:452337CookieMonster::AddCallbackForCookie(const GURL& gurl,
2338 const std::string& name,
2339 const CookieChangedCallback& callback) {
ellyjones399e35a22014-10-27 11:09:562340 base::AutoLock autolock(lock_);
2341 std::pair<GURL, std::string> key(gurl, name);
2342 if (hook_map_.count(key) == 0)
2343 hook_map_[key] = make_linked_ptr(new CookieChangedCallbackList());
msarda0aad8f02014-10-30 09:22:392344 return hook_map_[key]->Add(
anujk.sharmaafc45172015-05-15 00:50:342345 base::Bind(&RunAsync, base::ThreadTaskRunnerHandle::Get(), callback));
ellyjones399e35a22014-10-27 11:09:562346}
2347
mkwstb73bf8aa2015-03-31 07:33:452348#if defined(OS_ANDROID)
2349void CookieMonster::SetEnableFileScheme(bool accept) {
2350 // This assumes "file" is always at the end of the array. See the comment
2351 // above kDefaultCookieableSchemes.
2352 //
2353 // TODO(mkwst): We're keeping this method around to support the
2354 // 'CookieManager::setAcceptFileSchemeCookies' method on Android's WebView;
2355 // if/when we can deprecate and remove that method, we can remove this one
2356 // as well. Until then, we'll just ensure that the method has no effect on
2357 // non-android systems.
2358 int num_schemes = accept ? kDefaultCookieableSchemesCount
2359 : kDefaultCookieableSchemesCount - 1;
2360
2361 SetCookieableSchemes(kDefaultCookieableSchemes, num_schemes);
2362}
2363#endif
2364
msarda0aad8f02014-10-30 09:22:392365void CookieMonster::RunCallbacks(const CanonicalCookie& cookie, bool removed) {
ellyjones399e35a22014-10-27 11:09:562366 lock_.AssertAcquired();
2367 CookieOptions opts;
2368 opts.set_include_httponly();
mkwstae819bb2015-02-23 05:10:312369 opts.set_include_first_party_only();
ellyjones399e35a22014-10-27 11:09:562370 // Note that the callbacks in hook_map_ are wrapped with MakeAsync(), so they
2371 // are guaranteed to not take long - they just post a RunAsync task back to
2372 // the appropriate thread's message loop and return. It is important that this
2373 // method not run user-supplied callbacks directly, since the CookieMonster
2374 // lock is held and it is easy to accidentally introduce deadlocks.
2375 for (CookieChangedHookMap::iterator it = hook_map_.begin();
2376 it != hook_map_.end(); ++it) {
2377 std::pair<GURL, std::string> key = it->first;
2378 if (cookie.IncludeForRequestURL(key.first, opts) &&
2379 cookie.Name() == key.second) {
msarda0aad8f02014-10-30 09:22:392380 it->second->Notify(cookie, removed);
ellyjones399e35a22014-10-27 11:09:562381 }
2382 }
2383}
2384
[email protected]63725312012-07-19 08:24:162385} // namespace net