blob: a83ec119850ebda36a5aca22a6e61998cbf32390 [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]85620342011-10-17 17:35:0453#include "base/callback.h"
initial.commit586acc5fe2008-07-26 22:42:5254#include "base/logging.h"
[email protected]3b63f8f42011-03-28 01:54:1555#include "base/memory/scoped_ptr.h"
[email protected]5ee20982013-07-17 21:51:1856#include "base/message_loop/message_loop.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"
initial.commit586acc5fe2008-07-26 22:42:5268
[email protected]e1acf6f2008-10-27 20:43:3369using base::Time;
70using base::TimeDelta;
[email protected]7a964a72010-09-07 19:33:2671using base::TimeTicks;
[email protected]e1acf6f2008-10-27 20:43:3372
[email protected]85620342011-10-17 17:35:0473// In steady state, most cookie requests can be satisfied by the in memory
erikchen1dd72a72015-05-06 20:45:0574// cookie monster store. If the cookie request cannot be satisfied by the in
75// memory store, the relevant cookies must be fetched from the persistent
76// store. The task is queued in CookieMonster::tasks_pending_ if it requires
77// all cookies to be loaded from the backend, or tasks_pending_for_key_ if it
78// only requires all cookies associated with an eTLD+1.
[email protected]85620342011-10-17 17:35:0479//
80// On the browser critical paths (e.g. for loading initial web pages in a
81// session restore) it may take too long to wait for the full load. If a cookie
82// request is for a specific URL, DoCookieTaskForURL is called, which triggers a
83// priority load if the key is not loaded yet by calling PersistentCookieStore
[email protected]0184df32013-05-14 00:53:5584// :: LoadCookiesForKey. The request is queued in
85// CookieMonster::tasks_pending_for_key_ and executed upon receiving
86// notification of key load completion via CookieMonster::OnKeyLoaded(). If
87// multiple requests for the same eTLD+1 are received before key load
88// completion, only the first request calls
[email protected]85620342011-10-17 17:35:0489// PersistentCookieStore::LoadCookiesForKey, all subsequent requests are queued
[email protected]0184df32013-05-14 00:53:5590// in CookieMonster::tasks_pending_for_key_ and executed upon receiving
91// notification of key load completion triggered by the first request for the
92// same eTLD+1.
[email protected]85620342011-10-17 17:35:0493
[email protected]c4058fb2010-06-22 17:25:2694static const int kMinutesInTenYears = 10 * 365 * 24 * 60;
95
erikchen1dd72a72015-05-06 20:45:0596namespace {
97
98const char kFetchWhenNecessaryName[] = "FetchWhenNecessary";
99const char kAlwaysFetchName[] = "AlwaysFetch";
100const char kCookieMonsterFetchStrategyName[] = "CookieMonsterFetchStrategy";
101
102} // namespace
103
[email protected]8ac1a752008-07-31 19:40:37104namespace net {
105
[email protected]7a964a72010-09-07 19:33:26106// See comments at declaration of these variables in cookie_monster.h
107// for details.
mkwstbe84af312015-02-20 08:52:45108const size_t CookieMonster::kDomainMaxCookies = 180;
109const size_t CookieMonster::kDomainPurgeCookies = 30;
110const size_t CookieMonster::kMaxCookies = 3300;
111const size_t CookieMonster::kPurgeCookies = 300;
[email protected]8ad5d462013-05-02 08:45:26112
mkwstbe84af312015-02-20 08:52:45113const size_t CookieMonster::kDomainCookiesQuotaLow = 30;
[email protected]8ad5d462013-05-02 08:45:26114const size_t CookieMonster::kDomainCookiesQuotaMedium = 50;
mkwstbe84af312015-02-20 08:52:45115const size_t CookieMonster::kDomainCookiesQuotaHigh =
116 kDomainMaxCookies - kDomainPurgeCookies - kDomainCookiesQuotaLow -
117 kDomainCookiesQuotaMedium;
[email protected]8ad5d462013-05-02 08:45:26118
mkwstbe84af312015-02-20 08:52:45119const int CookieMonster::kSafeFromGlobalPurgeDays = 30;
[email protected]297a4ed02010-02-12 08:12:52120
[email protected]7a964a72010-09-07 19:33:26121namespace {
[email protected]e32306c52008-11-06 16:59:05122
[email protected]6210ce52013-09-20 03:33:14123bool ContainsControlCharacter(const std::string& s) {
124 for (std::string::const_iterator i = s.begin(); i != s.end(); ++i) {
125 if ((*i >= 0) && (*i <= 31))
126 return true;
127 }
128
129 return false;
130}
131
[email protected]5b9bc352012-07-18 13:13:34132typedef std::vector<CanonicalCookie*> CanonicalCookieVector;
[email protected]34a160d2011-05-12 22:12:49133
[email protected]77e0a462008-11-01 00:43:35134// Default minimum delay after updating a cookie's LastAccessDate before we
135// will update it again.
[email protected]297a4ed02010-02-12 08:12:52136const int kDefaultAccessUpdateThresholdSeconds = 60;
137
138// Comparator to sort cookies from highest creation date to lowest
139// creation date.
140struct OrderByCreationTimeDesc {
141 bool operator()(const CookieMonster::CookieMap::iterator& a,
142 const CookieMonster::CookieMap::iterator& b) const {
143 return a->second->CreationDate() > b->second->CreationDate();
144 }
145};
146
[email protected]4d3ce782010-10-29 18:31:28147// Constants for use in VLOG
148const int kVlogPerCookieMonster = 1;
149const int kVlogPeriodic = 3;
150const 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
[email protected]f48b9432011-01-11 07:25:40335} // namespace
336
[email protected]7c4b66b2014-01-04 12:28:13337CookieMonster::CookieMonster(PersistentCookieStore* store,
338 CookieMonsterDelegate* delegate)
[email protected]f48b9432011-01-11 07:25:40339 : initialized_(false),
erikchen1dd72a72015-05-06 20:45:05340 started_fetching_all_cookies_(false),
341 finished_fetching_all_cookies_(false),
342 fetch_strategy_(kUnknownFetch),
[email protected]f48b9432011-01-11 07:25:40343 store_(store),
344 last_access_threshold_(
345 TimeDelta::FromSeconds(kDefaultAccessUpdateThresholdSeconds)),
346 delegate_(delegate),
[email protected]82388662011-03-10 21:04:06347 last_statistic_record_time_(Time::Now()),
[email protected]93c53a32011-12-05 10:40:35348 keep_expired_cookies_(false),
[email protected]8976e292013-11-02 13:38:57349 persist_session_cookies_(false) {
[email protected]f48b9432011-01-11 07:25:40350 InitializeHistograms();
351 SetDefaultCookieableSchemes();
[email protected]2d0f89a2010-12-06 12:02:23352}
353
[email protected]f48b9432011-01-11 07:25:40354CookieMonster::CookieMonster(PersistentCookieStore* store,
[email protected]7c4b66b2014-01-04 12:28:13355 CookieMonsterDelegate* delegate,
[email protected]f48b9432011-01-11 07:25:40356 int last_access_threshold_milliseconds)
357 : initialized_(false),
erikchen1dd72a72015-05-06 20:45:05358 started_fetching_all_cookies_(false),
359 finished_fetching_all_cookies_(false),
360 fetch_strategy_(kUnknownFetch),
[email protected]f48b9432011-01-11 07:25:40361 store_(store),
362 last_access_threshold_(base::TimeDelta::FromMilliseconds(
363 last_access_threshold_milliseconds)),
364 delegate_(delegate),
[email protected]82388662011-03-10 21:04:06365 last_statistic_record_time_(base::Time::Now()),
[email protected]93c53a32011-12-05 10:40:35366 keep_expired_cookies_(false),
[email protected]8976e292013-11-02 13:38:57367 persist_session_cookies_(false) {
[email protected]f48b9432011-01-11 07:25:40368 InitializeHistograms();
369 SetDefaultCookieableSchemes();
initial.commit586acc5fe2008-07-26 22:42:52370}
371
[email protected]218aa6a12011-09-13 17:38:38372// Task classes for queueing the coming request.
373
374class CookieMonster::CookieMonsterTask
375 : public base::RefCountedThreadSafe<CookieMonsterTask> {
376 public:
377 // Runs the task and invokes the client callback on the thread that
378 // originally constructed the task.
379 virtual void Run() = 0;
380
381 protected:
382 explicit CookieMonsterTask(CookieMonster* cookie_monster);
383 virtual ~CookieMonsterTask();
384
385 // Invokes the callback immediately, if the current thread is the one
386 // that originated the task, or queues the callback for execution on the
387 // appropriate thread. Maintains a reference to this CookieMonsterTask
388 // instance until the callback completes.
389 void InvokeCallback(base::Closure callback);
390
mkwstbe84af312015-02-20 08:52:45391 CookieMonster* cookie_monster() { return cookie_monster_; }
[email protected]218aa6a12011-09-13 17:38:38392
[email protected]a9813302012-04-28 09:29:28393 private:
[email protected]218aa6a12011-09-13 17:38:38394 friend class base::RefCountedThreadSafe<CookieMonsterTask>;
395
[email protected]218aa6a12011-09-13 17:38:38396 CookieMonster* cookie_monster_;
anujk.sharmaafc45172015-05-15 00:50:34397 scoped_refptr<base::SingleThreadTaskRunner> thread_;
[email protected]218aa6a12011-09-13 17:38:38398
399 DISALLOW_COPY_AND_ASSIGN(CookieMonsterTask);
400};
401
402CookieMonster::CookieMonsterTask::CookieMonsterTask(
403 CookieMonster* cookie_monster)
404 : cookie_monster_(cookie_monster),
anujk.sharmaafc45172015-05-15 00:50:34405 thread_(base::ThreadTaskRunnerHandle::Get()) {
[email protected]a9813302012-04-28 09:29:28406}
[email protected]218aa6a12011-09-13 17:38:38407
mkwstbe84af312015-02-20 08:52:45408CookieMonster::CookieMonsterTask::~CookieMonsterTask() {
409}
[email protected]218aa6a12011-09-13 17:38:38410
411// Unfortunately, one cannot re-bind a Callback with parameters into a closure.
412// Therefore, the closure passed to InvokeCallback is a clumsy binding of
413// Callback::Run on a wrapped Callback instance. Since Callback is not
414// reference counted, we bind to an instance that is a member of the
415// CookieMonsterTask subclass. Then, we cannot simply post the callback to a
416// message loop because the underlying instance may be destroyed (along with the
417// CookieMonsterTask instance) in the interim. Therefore, we post a callback
418// bound to the CookieMonsterTask, which *is* reference counted (thus preventing
419// destruction of the original callback), and which invokes the closure (which
420// invokes the original callback with the returned data).
421void CookieMonster::CookieMonsterTask::InvokeCallback(base::Closure callback) {
422 if (thread_->BelongsToCurrentThread()) {
423 callback.Run();
424 } else {
mkwstbe84af312015-02-20 08:52:45425 thread_->PostTask(FROM_HERE, base::Bind(&CookieMonsterTask::InvokeCallback,
426 this, callback));
[email protected]218aa6a12011-09-13 17:38:38427 }
428}
429
430// Task class for SetCookieWithDetails call.
[email protected]5fa4f9a2013-10-03 10:13:16431class CookieMonster::SetCookieWithDetailsTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38432 public:
[email protected]dedec0b2013-02-28 04:50:10433 SetCookieWithDetailsTask(CookieMonster* cookie_monster,
434 const GURL& url,
435 const std::string& name,
436 const std::string& value,
437 const std::string& domain,
438 const std::string& path,
439 const base::Time& expiration_time,
440 bool secure,
441 bool http_only,
mkwstae819bb2015-02-23 05:10:31442 bool first_party_only,
[email protected]ab2d75c82013-04-19 18:39:04443 CookiePriority priority,
[email protected]5fa4f9a2013-10-03 10:13:16444 const SetCookiesCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38445 : CookieMonsterTask(cookie_monster),
446 url_(url),
447 name_(name),
448 value_(value),
449 domain_(domain),
450 path_(path),
451 expiration_time_(expiration_time),
452 secure_(secure),
453 http_only_(http_only),
mkwstae819bb2015-02-23 05:10:31454 first_party_only_(first_party_only),
[email protected]ab2d75c82013-04-19 18:39:04455 priority_(priority),
mkwstbe84af312015-02-20 08:52:45456 callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38457
[email protected]5fa4f9a2013-10-03 10:13:16458 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20459 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38460
[email protected]a9813302012-04-28 09:29:28461 protected:
dchengb03027d2014-10-21 12:00:20462 ~SetCookieWithDetailsTask() override {}
[email protected]a9813302012-04-28 09:29:28463
[email protected]218aa6a12011-09-13 17:38:38464 private:
465 GURL url_;
466 std::string name_;
467 std::string value_;
468 std::string domain_;
469 std::string path_;
470 base::Time expiration_time_;
471 bool secure_;
472 bool http_only_;
mkwstae819bb2015-02-23 05:10:31473 bool first_party_only_;
[email protected]ab2d75c82013-04-19 18:39:04474 CookiePriority priority_;
[email protected]5fa4f9a2013-10-03 10:13:16475 SetCookiesCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38476
477 DISALLOW_COPY_AND_ASSIGN(SetCookieWithDetailsTask);
478};
479
480void CookieMonster::SetCookieWithDetailsTask::Run() {
mkwstbe84af312015-02-20 08:52:45481 bool success = this->cookie_monster()->SetCookieWithDetails(
482 url_, name_, value_, domain_, path_, expiration_time_, secure_,
mkwstae819bb2015-02-23 05:10:31483 http_only_, first_party_only_, priority_);
[email protected]218aa6a12011-09-13 17:38:38484 if (!callback_.is_null()) {
[email protected]5fa4f9a2013-10-03 10:13:16485 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38486 base::Unretained(&callback_), success));
487 }
488}
489
490// Task class for GetAllCookies call.
[email protected]5fa4f9a2013-10-03 10:13:16491class CookieMonster::GetAllCookiesTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38492 public:
493 GetAllCookiesTask(CookieMonster* cookie_monster,
[email protected]5fa4f9a2013-10-03 10:13:16494 const GetCookieListCallback& callback)
mkwstbe84af312015-02-20 08:52:45495 : CookieMonsterTask(cookie_monster), callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38496
[email protected]5fa4f9a2013-10-03 10:13:16497 // CookieMonsterTask
dchengb03027d2014-10-21 12:00:20498 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38499
[email protected]a9813302012-04-28 09:29:28500 protected:
dchengb03027d2014-10-21 12:00:20501 ~GetAllCookiesTask() override {}
[email protected]a9813302012-04-28 09:29:28502
[email protected]218aa6a12011-09-13 17:38:38503 private:
[email protected]5fa4f9a2013-10-03 10:13:16504 GetCookieListCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38505
506 DISALLOW_COPY_AND_ASSIGN(GetAllCookiesTask);
507};
508
509void CookieMonster::GetAllCookiesTask::Run() {
510 if (!callback_.is_null()) {
511 CookieList cookies = this->cookie_monster()->GetAllCookies();
[email protected]5fa4f9a2013-10-03 10:13:16512 this->InvokeCallback(base::Bind(&GetCookieListCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38513 base::Unretained(&callback_), cookies));
mkwstbe84af312015-02-20 08:52:45514 }
[email protected]218aa6a12011-09-13 17:38:38515}
516
517// Task class for GetAllCookiesForURLWithOptions call.
518class CookieMonster::GetAllCookiesForURLWithOptionsTask
[email protected]5fa4f9a2013-10-03 10:13:16519 : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38520 public:
mkwstbe84af312015-02-20 08:52:45521 GetAllCookiesForURLWithOptionsTask(CookieMonster* cookie_monster,
522 const GURL& url,
523 const CookieOptions& options,
524 const GetCookieListCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38525 : CookieMonsterTask(cookie_monster),
526 url_(url),
527 options_(options),
mkwstbe84af312015-02-20 08:52:45528 callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38529
[email protected]5fa4f9a2013-10-03 10:13:16530 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20531 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38532
[email protected]a9813302012-04-28 09:29:28533 protected:
dchengb03027d2014-10-21 12:00:20534 ~GetAllCookiesForURLWithOptionsTask() override {}
[email protected]a9813302012-04-28 09:29:28535
[email protected]218aa6a12011-09-13 17:38:38536 private:
537 GURL url_;
538 CookieOptions options_;
[email protected]5fa4f9a2013-10-03 10:13:16539 GetCookieListCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38540
541 DISALLOW_COPY_AND_ASSIGN(GetAllCookiesForURLWithOptionsTask);
542};
543
544void CookieMonster::GetAllCookiesForURLWithOptionsTask::Run() {
545 if (!callback_.is_null()) {
mkwstbe84af312015-02-20 08:52:45546 CookieList cookies =
547 this->cookie_monster()->GetAllCookiesForURLWithOptions(url_, options_);
[email protected]5fa4f9a2013-10-03 10:13:16548 this->InvokeCallback(base::Bind(&GetCookieListCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38549 base::Unretained(&callback_), cookies));
550 }
551}
552
mkwstbe84af312015-02-20 08:52:45553template <typename Result>
554struct CallbackType {
[email protected]5fa4f9a2013-10-03 10:13:16555 typedef base::Callback<void(Result)> Type;
556};
557
mkwstbe84af312015-02-20 08:52:45558template <>
559struct CallbackType<void> {
[email protected]5fa4f9a2013-10-03 10:13:16560 typedef base::Closure Type;
561};
562
563// Base task class for Delete*Task.
564template <typename Result>
565class CookieMonster::DeleteTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38566 public:
[email protected]5fa4f9a2013-10-03 10:13:16567 DeleteTask(CookieMonster* cookie_monster,
568 const typename CallbackType<Result>::Type& callback)
mkwstbe84af312015-02-20 08:52:45569 : CookieMonsterTask(cookie_monster), callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38570
[email protected]5fa4f9a2013-10-03 10:13:16571 // CookieMonsterTask:
nickd3f30d022015-04-23 10:18:37572 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38573
dmichaeld6e570d2014-12-18 22:30:57574 protected:
575 ~DeleteTask() override;
576
[email protected]5fa4f9a2013-10-03 10:13:16577 private:
578 // Runs the delete task and returns a result.
579 virtual Result RunDeleteTask() = 0;
580 base::Closure RunDeleteTaskAndBindCallback();
581 void FlushDone(const base::Closure& callback);
582
583 typename CallbackType<Result>::Type callback_;
584
585 DISALLOW_COPY_AND_ASSIGN(DeleteTask);
586};
587
588template <typename Result>
dmichaeld6e570d2014-12-18 22:30:57589CookieMonster::DeleteTask<Result>::~DeleteTask() {
590}
591
592template <typename Result>
593base::Closure
594CookieMonster::DeleteTask<Result>::RunDeleteTaskAndBindCallback() {
[email protected]5fa4f9a2013-10-03 10:13:16595 Result result = RunDeleteTask();
596 if (callback_.is_null())
597 return base::Closure();
598 return base::Bind(callback_, result);
599}
600
601template <>
602base::Closure CookieMonster::DeleteTask<void>::RunDeleteTaskAndBindCallback() {
603 RunDeleteTask();
604 return callback_;
605}
606
607template <typename Result>
608void CookieMonster::DeleteTask<Result>::Run() {
mkwstbe84af312015-02-20 08:52:45609 this->cookie_monster()->FlushStore(base::Bind(
610 &DeleteTask<Result>::FlushDone, this, RunDeleteTaskAndBindCallback()));
[email protected]5fa4f9a2013-10-03 10:13:16611}
612
613template <typename Result>
614void CookieMonster::DeleteTask<Result>::FlushDone(
615 const base::Closure& callback) {
616 if (!callback.is_null()) {
617 this->InvokeCallback(callback);
618 }
619}
620
621// Task class for DeleteAll call.
622class CookieMonster::DeleteAllTask : public DeleteTask<int> {
623 public:
mkwstbe84af312015-02-20 08:52:45624 DeleteAllTask(CookieMonster* cookie_monster, const DeleteCallback& callback)
625 : DeleteTask<int>(cookie_monster, callback) {}
[email protected]5fa4f9a2013-10-03 10:13:16626
627 // DeleteTask:
dchengb03027d2014-10-21 12:00:20628 int RunDeleteTask() override;
[email protected]5fa4f9a2013-10-03 10:13:16629
[email protected]a9813302012-04-28 09:29:28630 protected:
dchengb03027d2014-10-21 12:00:20631 ~DeleteAllTask() override {}
[email protected]a9813302012-04-28 09:29:28632
[email protected]218aa6a12011-09-13 17:38:38633 private:
[email protected]218aa6a12011-09-13 17:38:38634 DISALLOW_COPY_AND_ASSIGN(DeleteAllTask);
635};
636
[email protected]5fa4f9a2013-10-03 10:13:16637int CookieMonster::DeleteAllTask::RunDeleteTask() {
638 return this->cookie_monster()->DeleteAll(true);
[email protected]218aa6a12011-09-13 17:38:38639}
640
641// Task class for DeleteAllCreatedBetween call.
[email protected]5fa4f9a2013-10-03 10:13:16642class CookieMonster::DeleteAllCreatedBetweenTask : public DeleteTask<int> {
[email protected]218aa6a12011-09-13 17:38:38643 public:
[email protected]dedec0b2013-02-28 04:50:10644 DeleteAllCreatedBetweenTask(CookieMonster* cookie_monster,
645 const Time& delete_begin,
646 const Time& delete_end,
[email protected]5fa4f9a2013-10-03 10:13:16647 const DeleteCallback& callback)
[email protected]151132f2013-11-18 21:37:00648 : DeleteTask<int>(cookie_monster, callback),
[email protected]218aa6a12011-09-13 17:38:38649 delete_begin_(delete_begin),
mkwstbe84af312015-02-20 08:52:45650 delete_end_(delete_end) {}
[email protected]218aa6a12011-09-13 17:38:38651
[email protected]5fa4f9a2013-10-03 10:13:16652 // DeleteTask:
dchengb03027d2014-10-21 12:00:20653 int RunDeleteTask() override;
[email protected]218aa6a12011-09-13 17:38:38654
[email protected]a9813302012-04-28 09:29:28655 protected:
dchengb03027d2014-10-21 12:00:20656 ~DeleteAllCreatedBetweenTask() override {}
[email protected]a9813302012-04-28 09:29:28657
[email protected]218aa6a12011-09-13 17:38:38658 private:
659 Time delete_begin_;
660 Time delete_end_;
[email protected]218aa6a12011-09-13 17:38:38661
662 DISALLOW_COPY_AND_ASSIGN(DeleteAllCreatedBetweenTask);
663};
664
[email protected]5fa4f9a2013-10-03 10:13:16665int CookieMonster::DeleteAllCreatedBetweenTask::RunDeleteTask() {
mkwstbe84af312015-02-20 08:52:45666 return this->cookie_monster()->DeleteAllCreatedBetween(delete_begin_,
667 delete_end_);
[email protected]218aa6a12011-09-13 17:38:38668}
669
670// Task class for DeleteAllForHost call.
[email protected]5fa4f9a2013-10-03 10:13:16671class CookieMonster::DeleteAllForHostTask : public DeleteTask<int> {
[email protected]218aa6a12011-09-13 17:38:38672 public:
673 DeleteAllForHostTask(CookieMonster* cookie_monster,
674 const GURL& url,
[email protected]5fa4f9a2013-10-03 10:13:16675 const DeleteCallback& callback)
mkwstbe84af312015-02-20 08:52:45676 : DeleteTask<int>(cookie_monster, callback), url_(url) {}
[email protected]218aa6a12011-09-13 17:38:38677
[email protected]5fa4f9a2013-10-03 10:13:16678 // DeleteTask:
dchengb03027d2014-10-21 12:00:20679 int RunDeleteTask() override;
[email protected]218aa6a12011-09-13 17:38:38680
[email protected]a9813302012-04-28 09:29:28681 protected:
dchengb03027d2014-10-21 12:00:20682 ~DeleteAllForHostTask() override {}
[email protected]a9813302012-04-28 09:29:28683
[email protected]218aa6a12011-09-13 17:38:38684 private:
685 GURL url_;
[email protected]218aa6a12011-09-13 17:38:38686
687 DISALLOW_COPY_AND_ASSIGN(DeleteAllForHostTask);
688};
689
[email protected]5fa4f9a2013-10-03 10:13:16690int CookieMonster::DeleteAllForHostTask::RunDeleteTask() {
691 return this->cookie_monster()->DeleteAllForHost(url_);
[email protected]218aa6a12011-09-13 17:38:38692}
693
[email protected]d8428d52013-08-07 06:58:25694// Task class for DeleteAllCreatedBetweenForHost call.
695class CookieMonster::DeleteAllCreatedBetweenForHostTask
[email protected]5fa4f9a2013-10-03 10:13:16696 : public DeleteTask<int> {
[email protected]d8428d52013-08-07 06:58:25697 public:
mkwstbe84af312015-02-20 08:52:45698 DeleteAllCreatedBetweenForHostTask(CookieMonster* cookie_monster,
699 Time delete_begin,
700 Time delete_end,
701 const GURL& url,
702 const DeleteCallback& callback)
[email protected]151132f2013-11-18 21:37:00703 : DeleteTask<int>(cookie_monster, callback),
[email protected]d8428d52013-08-07 06:58:25704 delete_begin_(delete_begin),
705 delete_end_(delete_end),
mkwstbe84af312015-02-20 08:52:45706 url_(url) {}
[email protected]d8428d52013-08-07 06:58:25707
[email protected]5fa4f9a2013-10-03 10:13:16708 // DeleteTask:
dchengb03027d2014-10-21 12:00:20709 int RunDeleteTask() override;
[email protected]d8428d52013-08-07 06:58:25710
711 protected:
dchengb03027d2014-10-21 12:00:20712 ~DeleteAllCreatedBetweenForHostTask() override {}
[email protected]d8428d52013-08-07 06:58:25713
714 private:
715 Time delete_begin_;
716 Time delete_end_;
717 GURL url_;
[email protected]d8428d52013-08-07 06:58:25718
719 DISALLOW_COPY_AND_ASSIGN(DeleteAllCreatedBetweenForHostTask);
720};
721
[email protected]5fa4f9a2013-10-03 10:13:16722int CookieMonster::DeleteAllCreatedBetweenForHostTask::RunDeleteTask() {
723 return this->cookie_monster()->DeleteAllCreatedBetweenForHost(
[email protected]d8428d52013-08-07 06:58:25724 delete_begin_, delete_end_, url_);
[email protected]d8428d52013-08-07 06:58:25725}
726
[email protected]218aa6a12011-09-13 17:38:38727// Task class for DeleteCanonicalCookie call.
[email protected]5fa4f9a2013-10-03 10:13:16728class CookieMonster::DeleteCanonicalCookieTask : public DeleteTask<bool> {
[email protected]218aa6a12011-09-13 17:38:38729 public:
[email protected]dedec0b2013-02-28 04:50:10730 DeleteCanonicalCookieTask(CookieMonster* cookie_monster,
731 const CanonicalCookie& cookie,
[email protected]5fa4f9a2013-10-03 10:13:16732 const DeleteCookieCallback& callback)
mkwstbe84af312015-02-20 08:52:45733 : DeleteTask<bool>(cookie_monster, callback), cookie_(cookie) {}
[email protected]218aa6a12011-09-13 17:38:38734
[email protected]5fa4f9a2013-10-03 10:13:16735 // DeleteTask:
dchengb03027d2014-10-21 12:00:20736 bool RunDeleteTask() override;
[email protected]218aa6a12011-09-13 17:38:38737
[email protected]a9813302012-04-28 09:29:28738 protected:
dchengb03027d2014-10-21 12:00:20739 ~DeleteCanonicalCookieTask() override {}
[email protected]a9813302012-04-28 09:29:28740
[email protected]218aa6a12011-09-13 17:38:38741 private:
[email protected]5b9bc352012-07-18 13:13:34742 CanonicalCookie cookie_;
[email protected]218aa6a12011-09-13 17:38:38743
744 DISALLOW_COPY_AND_ASSIGN(DeleteCanonicalCookieTask);
745};
746
[email protected]5fa4f9a2013-10-03 10:13:16747bool CookieMonster::DeleteCanonicalCookieTask::RunDeleteTask() {
748 return this->cookie_monster()->DeleteCanonicalCookie(cookie_);
[email protected]218aa6a12011-09-13 17:38:38749}
750
751// Task class for SetCookieWithOptions call.
[email protected]5fa4f9a2013-10-03 10:13:16752class CookieMonster::SetCookieWithOptionsTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38753 public:
754 SetCookieWithOptionsTask(CookieMonster* cookie_monster,
755 const GURL& url,
756 const std::string& cookie_line,
757 const CookieOptions& options,
[email protected]5fa4f9a2013-10-03 10:13:16758 const SetCookiesCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38759 : CookieMonsterTask(cookie_monster),
760 url_(url),
761 cookie_line_(cookie_line),
762 options_(options),
mkwstbe84af312015-02-20 08:52:45763 callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38764
[email protected]5fa4f9a2013-10-03 10:13:16765 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20766 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38767
[email protected]a9813302012-04-28 09:29:28768 protected:
dchengb03027d2014-10-21 12:00:20769 ~SetCookieWithOptionsTask() override {}
[email protected]a9813302012-04-28 09:29:28770
[email protected]218aa6a12011-09-13 17:38:38771 private:
772 GURL url_;
773 std::string cookie_line_;
774 CookieOptions options_;
[email protected]5fa4f9a2013-10-03 10:13:16775 SetCookiesCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38776
777 DISALLOW_COPY_AND_ASSIGN(SetCookieWithOptionsTask);
778};
779
780void CookieMonster::SetCookieWithOptionsTask::Run() {
mkwstbe84af312015-02-20 08:52:45781 bool result = this->cookie_monster()->SetCookieWithOptions(url_, cookie_line_,
782 options_);
[email protected]218aa6a12011-09-13 17:38:38783 if (!callback_.is_null()) {
[email protected]5fa4f9a2013-10-03 10:13:16784 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38785 base::Unretained(&callback_), result));
786 }
787}
788
drogerd5d1278c2015-03-17 19:21:51789// Task class for SetAllCookies call.
790class CookieMonster::SetAllCookiesTask : public CookieMonsterTask {
791 public:
792 SetAllCookiesTask(CookieMonster* cookie_monster,
793 const CookieList& list,
794 const SetCookiesCallback& callback)
795 : CookieMonsterTask(cookie_monster), list_(list), callback_(callback) {}
796
797 // CookieMonsterTask:
798 void Run() override;
799
800 protected:
801 ~SetAllCookiesTask() override {}
802
803 private:
804 CookieList list_;
805 SetCookiesCallback callback_;
806
807 DISALLOW_COPY_AND_ASSIGN(SetAllCookiesTask);
808};
809
810void CookieMonster::SetAllCookiesTask::Run() {
811 CookieList positive_diff;
812 CookieList negative_diff;
813 CookieList old_cookies = this->cookie_monster()->GetAllCookies();
814 this->cookie_monster()->ComputeCookieDiff(&old_cookies, &list_,
815 &positive_diff, &negative_diff);
816
817 for (CookieList::const_iterator it = negative_diff.begin();
818 it != negative_diff.end(); ++it) {
819 this->cookie_monster()->DeleteCanonicalCookie(*it);
820 }
821
822 bool result = true;
823 if (positive_diff.size() > 0)
824 result = this->cookie_monster()->SetCanonicalCookies(list_);
825
826 if (!callback_.is_null()) {
827 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run,
828 base::Unretained(&callback_), result));
829 }
830}
831
[email protected]218aa6a12011-09-13 17:38:38832// Task class for GetCookiesWithOptions call.
[email protected]5fa4f9a2013-10-03 10:13:16833class CookieMonster::GetCookiesWithOptionsTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38834 public:
835 GetCookiesWithOptionsTask(CookieMonster* cookie_monster,
[email protected]0298caf82011-12-20 23:15:46836 const GURL& url,
[email protected]218aa6a12011-09-13 17:38:38837 const CookieOptions& options,
[email protected]5fa4f9a2013-10-03 10:13:16838 const GetCookiesCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38839 : CookieMonsterTask(cookie_monster),
840 url_(url),
841 options_(options),
mkwstbe84af312015-02-20 08:52:45842 callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38843
[email protected]5fa4f9a2013-10-03 10:13:16844 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20845 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38846
[email protected]a9813302012-04-28 09:29:28847 protected:
dchengb03027d2014-10-21 12:00:20848 ~GetCookiesWithOptionsTask() override {}
[email protected]a9813302012-04-28 09:29:28849
[email protected]218aa6a12011-09-13 17:38:38850 private:
851 GURL url_;
852 CookieOptions options_;
[email protected]5fa4f9a2013-10-03 10:13:16853 GetCookiesCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38854
855 DISALLOW_COPY_AND_ASSIGN(GetCookiesWithOptionsTask);
856};
857
858void CookieMonster::GetCookiesWithOptionsTask::Run() {
pkastinga9269aa42015-04-10 01:42:26859 // TODO(mkwst): Remove ScopedTracker below once crbug.com/456373 is fixed.
pkasting58e029b2015-02-21 05:17:28860 tracked_objects::ScopedTracker tracking_profile(
861 FROM_HERE_WITH_EXPLICIT_FUNCTION(
862 "456373 CookieMonster::GetCookiesWithOptionsTask::Run"));
mkwstbe84af312015-02-20 08:52:45863 std::string cookie =
864 this->cookie_monster()->GetCookiesWithOptions(url_, options_);
[email protected]218aa6a12011-09-13 17:38:38865 if (!callback_.is_null()) {
[email protected]5fa4f9a2013-10-03 10:13:16866 this->InvokeCallback(base::Bind(&GetCookiesCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38867 base::Unretained(&callback_), cookie));
868 }
869}
870
[email protected]218aa6a12011-09-13 17:38:38871// Task class for DeleteCookie call.
[email protected]5fa4f9a2013-10-03 10:13:16872class CookieMonster::DeleteCookieTask : public DeleteTask<void> {
[email protected]218aa6a12011-09-13 17:38:38873 public:
874 DeleteCookieTask(CookieMonster* cookie_monster,
[email protected]0298caf82011-12-20 23:15:46875 const GURL& url,
[email protected]218aa6a12011-09-13 17:38:38876 const std::string& cookie_name,
877 const base::Closure& callback)
[email protected]151132f2013-11-18 21:37:00878 : DeleteTask<void>(cookie_monster, callback),
[email protected]218aa6a12011-09-13 17:38:38879 url_(url),
mkwstbe84af312015-02-20 08:52:45880 cookie_name_(cookie_name) {}
[email protected]218aa6a12011-09-13 17:38:38881
[email protected]5fa4f9a2013-10-03 10:13:16882 // DeleteTask:
dchengb03027d2014-10-21 12:00:20883 void RunDeleteTask() override;
[email protected]218aa6a12011-09-13 17:38:38884
[email protected]a9813302012-04-28 09:29:28885 protected:
dchengb03027d2014-10-21 12:00:20886 ~DeleteCookieTask() override {}
[email protected]a9813302012-04-28 09:29:28887
[email protected]218aa6a12011-09-13 17:38:38888 private:
889 GURL url_;
890 std::string cookie_name_;
[email protected]218aa6a12011-09-13 17:38:38891
892 DISALLOW_COPY_AND_ASSIGN(DeleteCookieTask);
893};
894
[email protected]5fa4f9a2013-10-03 10:13:16895void CookieMonster::DeleteCookieTask::RunDeleteTask() {
[email protected]218aa6a12011-09-13 17:38:38896 this->cookie_monster()->DeleteCookie(url_, cookie_name_);
[email protected]218aa6a12011-09-13 17:38:38897}
898
[email protected]264807b2012-04-25 14:49:37899// Task class for DeleteSessionCookies call.
[email protected]5fa4f9a2013-10-03 10:13:16900class CookieMonster::DeleteSessionCookiesTask : public DeleteTask<int> {
[email protected]264807b2012-04-25 14:49:37901 public:
[email protected]dedec0b2013-02-28 04:50:10902 DeleteSessionCookiesTask(CookieMonster* cookie_monster,
[email protected]5fa4f9a2013-10-03 10:13:16903 const DeleteCallback& callback)
mkwstbe84af312015-02-20 08:52:45904 : DeleteTask<int>(cookie_monster, callback) {}
[email protected]264807b2012-04-25 14:49:37905
[email protected]5fa4f9a2013-10-03 10:13:16906 // DeleteTask:
dchengb03027d2014-10-21 12:00:20907 int RunDeleteTask() override;
[email protected]264807b2012-04-25 14:49:37908
[email protected]a9813302012-04-28 09:29:28909 protected:
dchengb03027d2014-10-21 12:00:20910 ~DeleteSessionCookiesTask() override {}
[email protected]a9813302012-04-28 09:29:28911
[email protected]264807b2012-04-25 14:49:37912 private:
[email protected]264807b2012-04-25 14:49:37913 DISALLOW_COPY_AND_ASSIGN(DeleteSessionCookiesTask);
914};
915
[email protected]5fa4f9a2013-10-03 10:13:16916int CookieMonster::DeleteSessionCookiesTask::RunDeleteTask() {
917 return this->cookie_monster()->DeleteSessionCookies();
[email protected]264807b2012-04-25 14:49:37918}
919
[email protected]ee209482013-04-19 19:50:04920// Task class for HasCookiesForETLDP1Task call.
[email protected]5fa4f9a2013-10-03 10:13:16921class CookieMonster::HasCookiesForETLDP1Task : public CookieMonsterTask {
[email protected]ee209482013-04-19 19:50:04922 public:
mkwstbe84af312015-02-20 08:52:45923 HasCookiesForETLDP1Task(CookieMonster* cookie_monster,
924 const std::string& etldp1,
925 const HasCookiesForETLDP1Callback& callback)
[email protected]ee209482013-04-19 19:50:04926 : CookieMonsterTask(cookie_monster),
927 etldp1_(etldp1),
mkwstbe84af312015-02-20 08:52:45928 callback_(callback) {}
[email protected]ee209482013-04-19 19:50:04929
[email protected]5fa4f9a2013-10-03 10:13:16930 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20931 void Run() override;
[email protected]ee209482013-04-19 19:50:04932
933 protected:
dchengb03027d2014-10-21 12:00:20934 ~HasCookiesForETLDP1Task() override {}
[email protected]ee209482013-04-19 19:50:04935
936 private:
937 std::string etldp1_;
[email protected]5fa4f9a2013-10-03 10:13:16938 HasCookiesForETLDP1Callback callback_;
[email protected]ee209482013-04-19 19:50:04939
940 DISALLOW_COPY_AND_ASSIGN(HasCookiesForETLDP1Task);
941};
942
943void CookieMonster::HasCookiesForETLDP1Task::Run() {
944 bool result = this->cookie_monster()->HasCookiesForETLDP1(etldp1_);
945 if (!callback_.is_null()) {
mkwstbe84af312015-02-20 08:52:45946 this->InvokeCallback(base::Bind(&HasCookiesForETLDP1Callback::Run,
947 base::Unretained(&callback_), result));
[email protected]ee209482013-04-19 19:50:04948 }
949}
950
[email protected]218aa6a12011-09-13 17:38:38951// Asynchronous CookieMonster API
952
953void CookieMonster::SetCookieWithDetailsAsync(
[email protected]dedec0b2013-02-28 04:50:10954 const GURL& url,
955 const std::string& name,
956 const std::string& value,
957 const std::string& domain,
958 const std::string& path,
[email protected]d8428d52013-08-07 06:58:25959 const Time& expiration_time,
[email protected]dedec0b2013-02-28 04:50:10960 bool secure,
961 bool http_only,
mkwstae819bb2015-02-23 05:10:31962 bool first_party_only,
[email protected]ab2d75c82013-04-19 18:39:04963 CookiePriority priority,
[email protected]218aa6a12011-09-13 17:38:38964 const SetCookiesCallback& callback) {
mkwstbe84af312015-02-20 08:52:45965 scoped_refptr<SetCookieWithDetailsTask> task = new SetCookieWithDetailsTask(
966 this, url, name, value, domain, path, expiration_time, secure, http_only,
mkwstae819bb2015-02-23 05:10:31967 first_party_only, priority, callback);
[email protected]85620342011-10-17 17:35:04968 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:38969}
970
971void CookieMonster::GetAllCookiesAsync(const GetCookieListCallback& callback) {
mkwstbe84af312015-02-20 08:52:45972 scoped_refptr<GetAllCookiesTask> task = new GetAllCookiesTask(this, callback);
[email protected]218aa6a12011-09-13 17:38:38973
974 DoCookieTask(task);
975}
976
[email protected]218aa6a12011-09-13 17:38:38977void CookieMonster::GetAllCookiesForURLWithOptionsAsync(
978 const GURL& url,
979 const CookieOptions& options,
980 const GetCookieListCallback& callback) {
981 scoped_refptr<GetAllCookiesForURLWithOptionsTask> task =
982 new GetAllCookiesForURLWithOptionsTask(this, url, options, callback);
983
[email protected]85620342011-10-17 17:35:04984 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:38985}
986
987void CookieMonster::GetAllCookiesForURLAsync(
mkwstbe84af312015-02-20 08:52:45988 const GURL& url,
989 const GetCookieListCallback& callback) {
[email protected]218aa6a12011-09-13 17:38:38990 CookieOptions options;
991 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:31992 options.set_include_first_party_only();
[email protected]218aa6a12011-09-13 17:38:38993 scoped_refptr<GetAllCookiesForURLWithOptionsTask> task =
994 new GetAllCookiesForURLWithOptionsTask(this, url, options, callback);
995
[email protected]85620342011-10-17 17:35:04996 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:38997}
998
[email protected]ee209482013-04-19 19:50:04999void CookieMonster::HasCookiesForETLDP1Async(
1000 const std::string& etldp1,
1001 const HasCookiesForETLDP1Callback& callback) {
1002 scoped_refptr<HasCookiesForETLDP1Task> task =
1003 new HasCookiesForETLDP1Task(this, etldp1, callback);
1004
1005 DoCookieTaskForURL(task, GURL("http://" + etldp1));
1006}
1007
[email protected]218aa6a12011-09-13 17:38:381008void CookieMonster::DeleteAllAsync(const DeleteCallback& callback) {
mkwstbe84af312015-02-20 08:52:451009 scoped_refptr<DeleteAllTask> task = new DeleteAllTask(this, callback);
[email protected]218aa6a12011-09-13 17:38:381010
1011 DoCookieTask(task);
1012}
1013
1014void CookieMonster::DeleteAllCreatedBetweenAsync(
mkwstbe84af312015-02-20 08:52:451015 const Time& delete_begin,
1016 const Time& delete_end,
[email protected]218aa6a12011-09-13 17:38:381017 const DeleteCallback& callback) {
1018 scoped_refptr<DeleteAllCreatedBetweenTask> task =
mkwstbe84af312015-02-20 08:52:451019 new DeleteAllCreatedBetweenTask(this, delete_begin, delete_end, callback);
[email protected]218aa6a12011-09-13 17:38:381020
1021 DoCookieTask(task);
1022}
1023
[email protected]d8428d52013-08-07 06:58:251024void CookieMonster::DeleteAllCreatedBetweenForHostAsync(
1025 const Time delete_begin,
1026 const Time delete_end,
1027 const GURL& url,
1028 const DeleteCallback& callback) {
1029 scoped_refptr<DeleteAllCreatedBetweenForHostTask> task =
mkwstbe84af312015-02-20 08:52:451030 new DeleteAllCreatedBetweenForHostTask(this, delete_begin, delete_end,
1031 url, callback);
[email protected]d8428d52013-08-07 06:58:251032
1033 DoCookieTaskForURL(task, url);
1034}
1035
mkwstbe84af312015-02-20 08:52:451036void CookieMonster::DeleteAllForHostAsync(const GURL& url,
1037 const DeleteCallback& callback) {
[email protected]218aa6a12011-09-13 17:38:381038 scoped_refptr<DeleteAllForHostTask> task =
1039 new DeleteAllForHostTask(this, url, callback);
1040
[email protected]85620342011-10-17 17:35:041041 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381042}
1043
1044void CookieMonster::DeleteCanonicalCookieAsync(
1045 const CanonicalCookie& cookie,
1046 const DeleteCookieCallback& callback) {
1047 scoped_refptr<DeleteCanonicalCookieTask> task =
1048 new DeleteCanonicalCookieTask(this, cookie, callback);
1049
1050 DoCookieTask(task);
1051}
1052
drogerd5d1278c2015-03-17 19:21:511053void CookieMonster::SetAllCookiesAsync(const CookieList& list,
1054 const SetCookiesCallback& callback) {
1055 scoped_refptr<SetAllCookiesTask> task =
1056 new SetAllCookiesTask(this, list, callback);
1057 DoCookieTask(task);
1058}
1059
[email protected]218aa6a12011-09-13 17:38:381060void CookieMonster::SetCookieWithOptionsAsync(
1061 const GURL& url,
1062 const std::string& cookie_line,
1063 const CookieOptions& options,
1064 const SetCookiesCallback& callback) {
1065 scoped_refptr<SetCookieWithOptionsTask> task =
1066 new SetCookieWithOptionsTask(this, url, cookie_line, options, callback);
1067
[email protected]85620342011-10-17 17:35:041068 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381069}
1070
1071void CookieMonster::GetCookiesWithOptionsAsync(
1072 const GURL& url,
1073 const CookieOptions& options,
1074 const GetCookiesCallback& callback) {
1075 scoped_refptr<GetCookiesWithOptionsTask> task =
1076 new GetCookiesWithOptionsTask(this, url, options, callback);
1077
[email protected]85620342011-10-17 17:35:041078 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381079}
1080
[email protected]218aa6a12011-09-13 17:38:381081void CookieMonster::DeleteCookieAsync(const GURL& url,
1082 const std::string& cookie_name,
1083 const base::Closure& callback) {
1084 scoped_refptr<DeleteCookieTask> task =
1085 new DeleteCookieTask(this, url, cookie_name, callback);
1086
[email protected]85620342011-10-17 17:35:041087 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381088}
1089
[email protected]264807b2012-04-25 14:49:371090void CookieMonster::DeleteSessionCookiesAsync(
1091 const CookieStore::DeleteCallback& callback) {
1092 scoped_refptr<DeleteSessionCookiesTask> task =
1093 new DeleteSessionCookiesTask(this, callback);
1094
1095 DoCookieTask(task);
1096}
1097
[email protected]218aa6a12011-09-13 17:38:381098void CookieMonster::DoCookieTask(
1099 const scoped_refptr<CookieMonsterTask>& task_item) {
[email protected]218aa6a12011-09-13 17:38:381100 {
1101 base::AutoLock autolock(lock_);
erikchen1dd72a72015-05-06 20:45:051102 MarkCookieStoreAsInitialized();
1103 FetchAllCookiesIfNecessary();
1104 if (!finished_fetching_all_cookies_ && store_.get()) {
[email protected]0184df32013-05-14 00:53:551105 tasks_pending_.push(task_item);
[email protected]218aa6a12011-09-13 17:38:381106 return;
1107 }
1108 }
1109
1110 task_item->Run();
1111}
1112
[email protected]85620342011-10-17 17:35:041113void CookieMonster::DoCookieTaskForURL(
1114 const scoped_refptr<CookieMonsterTask>& task_item,
1115 const GURL& url) {
1116 {
1117 base::AutoLock autolock(lock_);
erikchen1dd72a72015-05-06 20:45:051118 MarkCookieStoreAsInitialized();
1119 if (ShouldFetchAllCookiesWhenFetchingAnyCookie())
1120 FetchAllCookiesIfNecessary();
[email protected]85620342011-10-17 17:35:041121 // If cookies for the requested domain key (eTLD+1) have been loaded from DB
1122 // then run the task, otherwise load from DB.
erikchen1dd72a72015-05-06 20:45:051123 if (!finished_fetching_all_cookies_ && store_.get()) {
[email protected]85620342011-10-17 17:35:041124 // Checks if the domain key has been loaded.
mkwstbe84af312015-02-20 08:52:451125 std::string key(
1126 cookie_util::GetEffectiveDomain(url.scheme(), url.host()));
[email protected]85620342011-10-17 17:35:041127 if (keys_loaded_.find(key) == keys_loaded_.end()) {
mkwstbe84af312015-02-20 08:52:451128 std::map<std::string,
1129 std::deque<scoped_refptr<CookieMonsterTask>>>::iterator it =
1130 tasks_pending_for_key_.find(key);
[email protected]0184df32013-05-14 00:53:551131 if (it == tasks_pending_for_key_.end()) {
mkwstbe84af312015-02-20 08:52:451132 store_->LoadCookiesForKey(
1133 key, base::Bind(&CookieMonster::OnKeyLoaded, this, key));
1134 it = tasks_pending_for_key_
1135 .insert(std::make_pair(
1136 key, std::deque<scoped_refptr<CookieMonsterTask>>()))
1137 .first;
[email protected]85620342011-10-17 17:35:041138 }
1139 it->second.push_back(task_item);
1140 return;
1141 }
1142 }
1143 }
1144 task_item->Run();
1145}
1146
[email protected]dedec0b2013-02-28 04:50:101147bool CookieMonster::SetCookieWithDetails(const GURL& url,
1148 const std::string& name,
1149 const std::string& value,
1150 const std::string& domain,
1151 const std::string& path,
1152 const base::Time& expiration_time,
1153 bool secure,
[email protected]ab2d75c82013-04-19 18:39:041154 bool http_only,
mkwstae819bb2015-02-23 05:10:311155 bool first_party_only,
[email protected]ab2d75c82013-04-19 18:39:041156 CookiePriority priority) {
[email protected]20305ec2011-01-21 04:55:521157 base::AutoLock autolock(lock_);
[email protected]69bb5872010-01-12 20:33:521158
[email protected]f48b9432011-01-11 07:25:401159 if (!HasCookieableScheme(url))
initial.commit586acc5fe2008-07-26 22:42:521160 return false;
1161
[email protected]f48b9432011-01-11 07:25:401162 Time creation_time = CurrentTime();
1163 last_time_seen_ = creation_time;
1164
1165 scoped_ptr<CanonicalCookie> cc;
[email protected]ab2d75c82013-04-19 18:39:041166 cc.reset(CanonicalCookie::Create(url, name, value, domain, path,
mkwstbe84af312015-02-20 08:52:451167 creation_time, expiration_time, secure,
mkwstae819bb2015-02-23 05:10:311168 http_only, first_party_only, priority));
[email protected]f48b9432011-01-11 07:25:401169
1170 if (!cc.get())
1171 return false;
1172
1173 CookieOptions options;
1174 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:311175 options.set_include_first_party_only();
[email protected]f48b9432011-01-11 07:25:401176 return SetCanonicalCookie(&cc, creation_time, options);
initial.commit586acc5fe2008-07-26 22:42:521177}
1178
bartfaba13acdf2014-09-05 15:07:281179bool CookieMonster::ImportCookies(const CookieList& list) {
[email protected]93460df2011-07-20 00:58:211180 base::AutoLock autolock(lock_);
erikchen1dd72a72015-05-06 20:45:051181 MarkCookieStoreAsInitialized();
1182 if (ShouldFetchAllCookiesWhenFetchingAnyCookie())
1183 FetchAllCookiesIfNecessary();
ttuttle859dc7a2015-04-23 19:42:291184 for (CookieList::const_iterator iter = list.begin(); iter != list.end();
mkwstbe84af312015-02-20 08:52:451185 ++iter) {
[email protected]5b9bc352012-07-18 13:13:341186 scoped_ptr<CanonicalCookie> cookie(new CanonicalCookie(*iter));
ttuttle859dc7a2015-04-23 19:42:291187 CookieOptions options;
[email protected]93460df2011-07-20 00:58:211188 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:311189 options.set_include_first_party_only();
[email protected]5b9bc352012-07-18 13:13:341190 if (!SetCanonicalCookie(&cookie, cookie->CreationDate(), options))
[email protected]93460df2011-07-20 00:58:211191 return false;
[email protected]93460df2011-07-20 00:58:211192 }
1193 return true;
1194}
1195
[email protected]f48b9432011-01-11 07:25:401196CookieList CookieMonster::GetAllCookies() {
[email protected]20305ec2011-01-21 04:55:521197 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401198
1199 // This function is being called to scrape the cookie list for management UI
1200 // or similar. We shouldn't show expired cookies in this list since it will
1201 // just be confusing to users, and this function is called rarely enough (and
1202 // is already slow enough) that it's OK to take the time to garbage collect
1203 // the expired cookies now.
1204 //
1205 // Note that this does not prune cookies to be below our limits (if we've
1206 // exceeded them) the way that calling GarbageCollect() would.
mkwstbe84af312015-02-20 08:52:451207 GarbageCollectExpired(
1208 Time::Now(), CookieMapItPair(cookies_.begin(), cookies_.end()), NULL);
[email protected]f48b9432011-01-11 07:25:401209
1210 // Copy the CanonicalCookie pointers from the map so that we can use the same
1211 // sorter as elsewhere, then copy the result out.
1212 std::vector<CanonicalCookie*> cookie_ptrs;
1213 cookie_ptrs.reserve(cookies_.size());
1214 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end(); ++it)
1215 cookie_ptrs.push_back(it->second);
1216 std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter);
1217
1218 CookieList cookie_list;
1219 cookie_list.reserve(cookie_ptrs.size());
1220 for (std::vector<CanonicalCookie*>::const_iterator it = cookie_ptrs.begin();
1221 it != cookie_ptrs.end(); ++it)
1222 cookie_list.push_back(**it);
1223
1224 return cookie_list;
[email protected]f325f1e12010-04-30 22:38:551225}
1226
[email protected]f48b9432011-01-11 07:25:401227CookieList CookieMonster::GetAllCookiesForURLWithOptions(
1228 const GURL& url,
1229 const CookieOptions& options) {
[email protected]20305ec2011-01-21 04:55:521230 base::AutoLock autolock(lock_);
initial.commit586acc5fe2008-07-26 22:42:521231
[email protected]f48b9432011-01-11 07:25:401232 std::vector<CanonicalCookie*> cookie_ptrs;
1233 FindCookiesForHostAndDomain(url, options, false, &cookie_ptrs);
1234 std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter);
initial.commit586acc5fe2008-07-26 22:42:521235
[email protected]f48b9432011-01-11 07:25:401236 CookieList cookies;
georgesakc15df6722014-12-02 23:52:121237 cookies.reserve(cookie_ptrs.size());
[email protected]f48b9432011-01-11 07:25:401238 for (std::vector<CanonicalCookie*>::const_iterator it = cookie_ptrs.begin();
1239 it != cookie_ptrs.end(); it++)
1240 cookies.push_back(**it);
initial.commit586acc5fe2008-07-26 22:42:521241
[email protected]f48b9432011-01-11 07:25:401242 return cookies;
initial.commit586acc5fe2008-07-26 22:42:521243}
1244
[email protected]f48b9432011-01-11 07:25:401245CookieList CookieMonster::GetAllCookiesForURL(const GURL& url) {
1246 CookieOptions options;
1247 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:311248 options.set_first_party_url(url);
[email protected]f48b9432011-01-11 07:25:401249
1250 return GetAllCookiesForURLWithOptions(url, options);
[email protected]f325f1e12010-04-30 22:38:551251}
1252
[email protected]f48b9432011-01-11 07:25:401253int CookieMonster::DeleteAll(bool sync_to_store) {
[email protected]20305ec2011-01-21 04:55:521254 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401255
1256 int num_deleted = 0;
1257 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1258 CookieMap::iterator curit = it;
1259 ++it;
1260 InternalDeleteCookie(curit, sync_to_store,
mkwstbe84af312015-02-20 08:52:451261 sync_to_store
1262 ? DELETE_COOKIE_EXPLICIT
1263 : DELETE_COOKIE_DONT_RECORD /* Destruction. */);
[email protected]f48b9432011-01-11 07:25:401264 ++num_deleted;
initial.commit586acc5fe2008-07-26 22:42:521265 }
1266
[email protected]f48b9432011-01-11 07:25:401267 return num_deleted;
initial.commit586acc5fe2008-07-26 22:42:521268}
1269
[email protected]f48b9432011-01-11 07:25:401270int CookieMonster::DeleteAllCreatedBetween(const Time& delete_begin,
[email protected]218aa6a12011-09-13 17:38:381271 const Time& delete_end) {
[email protected]20305ec2011-01-21 04:55:521272 base::AutoLock autolock(lock_);
[email protected]d0980332010-11-16 17:08:531273
[email protected]f48b9432011-01-11 07:25:401274 int num_deleted = 0;
1275 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1276 CookieMap::iterator curit = it;
1277 CanonicalCookie* cc = curit->second;
1278 ++it;
[email protected]d0980332010-11-16 17:08:531279
[email protected]f48b9432011-01-11 07:25:401280 if (cc->CreationDate() >= delete_begin &&
1281 (delete_end.is_null() || cc->CreationDate() < delete_end)) {
mkwstbe84af312015-02-20 08:52:451282 InternalDeleteCookie(curit, true, /*sync_to_store*/
[email protected]218aa6a12011-09-13 17:38:381283 DELETE_COOKIE_EXPLICIT);
[email protected]f48b9432011-01-11 07:25:401284 ++num_deleted;
initial.commit586acc5fe2008-07-26 22:42:521285 }
1286 }
1287
[email protected]f48b9432011-01-11 07:25:401288 return num_deleted;
1289}
1290
[email protected]d8428d52013-08-07 06:58:251291int CookieMonster::DeleteAllCreatedBetweenForHost(const Time delete_begin,
1292 const Time delete_end,
1293 const GURL& url) {
[email protected]20305ec2011-01-21 04:55:521294 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401295
1296 if (!HasCookieableScheme(url))
1297 return 0;
1298
[email protected]f48b9432011-01-11 07:25:401299 const std::string host(url.host());
1300
1301 // We store host cookies in the store by their canonical host name;
1302 // domain cookies are stored with a leading ".". So this is a pretty
1303 // simple lookup and per-cookie delete.
1304 int num_deleted = 0;
1305 for (CookieMapItPair its = cookies_.equal_range(GetKey(host));
1306 its.first != its.second;) {
1307 CookieMap::iterator curit = its.first;
1308 ++its.first;
1309
1310 const CanonicalCookie* const cc = curit->second;
1311
1312 // Delete only on a match as a host cookie.
[email protected]d8428d52013-08-07 06:58:251313 if (cc->IsHostCookie() && cc->IsDomainMatch(host) &&
1314 cc->CreationDate() >= delete_begin &&
1315 // The assumption that null |delete_end| is equivalent to
1316 // Time::Max() is confusing.
1317 (delete_end.is_null() || cc->CreationDate() < delete_end)) {
[email protected]f48b9432011-01-11 07:25:401318 num_deleted++;
1319
1320 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT);
1321 }
1322 }
1323 return num_deleted;
1324}
1325
[email protected]d8428d52013-08-07 06:58:251326int CookieMonster::DeleteAllForHost(const GURL& url) {
1327 return DeleteAllCreatedBetweenForHost(Time(), Time::Max(), url);
1328}
1329
[email protected]f48b9432011-01-11 07:25:401330bool CookieMonster::DeleteCanonicalCookie(const CanonicalCookie& cookie) {
[email protected]20305ec2011-01-21 04:55:521331 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401332
1333 for (CookieMapItPair its = cookies_.equal_range(GetKey(cookie.Domain()));
1334 its.first != its.second; ++its.first) {
1335 // The creation date acts as our unique index...
1336 if (its.first->second->CreationDate() == cookie.CreationDate()) {
1337 InternalDeleteCookie(its.first, true, DELETE_COOKIE_EXPLICIT);
1338 return true;
1339 }
1340 }
initial.commit586acc5fe2008-07-26 22:42:521341 return false;
1342}
1343
[email protected]5edff3c52014-06-23 20:27:481344void CookieMonster::SetCookieableSchemes(const char* const schemes[],
[email protected]dedec0b2013-02-28 04:50:101345 size_t num_schemes) {
[email protected]20305ec2011-01-21 04:55:521346 base::AutoLock autolock(lock_);
[email protected]bb8905722010-05-21 17:29:041347
[email protected]cf12bd12010-06-17 14:41:301348 // Cookieable Schemes must be set before first use of function.
1349 DCHECK(!initialized_);
1350
[email protected]47accfd62009-05-14 18:46:211351 cookieable_schemes_.clear();
mkwstbe84af312015-02-20 08:52:451352 cookieable_schemes_.insert(cookieable_schemes_.end(), schemes,
1353 schemes + num_schemes);
[email protected]47accfd62009-05-14 18:46:211354}
1355
[email protected]ba4ad0e2011-03-15 08:12:471356void CookieMonster::SetKeepExpiredCookies() {
1357 keep_expired_cookies_ = true;
1358}
1359
[email protected]e67f0f42011-12-20 02:29:211360void CookieMonster::FlushStore(const base::Closure& callback) {
[email protected]20305ec2011-01-21 04:55:521361 base::AutoLock autolock(lock_);
[email protected]90499482013-06-01 00:39:501362 if (initialized_ && store_.get())
[email protected]e67f0f42011-12-20 02:29:211363 store_->Flush(callback);
1364 else if (!callback.is_null())
[email protected]2da659e2013-05-23 20:51:341365 base::MessageLoop::current()->PostTask(FROM_HERE, callback);
[email protected]f48b9432011-01-11 07:25:401366}
1367
1368bool CookieMonster::SetCookieWithOptions(const GURL& url,
1369 const std::string& cookie_line,
1370 const CookieOptions& options) {
[email protected]20305ec2011-01-21 04:55:521371 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401372
1373 if (!HasCookieableScheme(url)) {
1374 return false;
1375 }
1376
[email protected]f48b9432011-01-11 07:25:401377 return SetCookieWithCreationTimeAndOptions(url, cookie_line, Time(), options);
1378}
1379
1380std::string CookieMonster::GetCookiesWithOptions(const GURL& url,
1381 const CookieOptions& options) {
[email protected]20305ec2011-01-21 04:55:521382 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401383
[email protected]34a160d2011-05-12 22:12:491384 if (!HasCookieableScheme(url))
[email protected]f48b9432011-01-11 07:25:401385 return std::string();
[email protected]f48b9432011-01-11 07:25:401386
[email protected]f48b9432011-01-11 07:25:401387 std::vector<CanonicalCookie*> cookies;
1388 FindCookiesForHostAndDomain(url, options, true, &cookies);
1389 std::sort(cookies.begin(), cookies.end(), CookieSorter);
1390
[email protected]34a160d2011-05-12 22:12:491391 std::string cookie_line = BuildCookieLine(cookies);
[email protected]f48b9432011-01-11 07:25:401392
[email protected]f48b9432011-01-11 07:25:401393 VLOG(kVlogGetCookies) << "GetCookies() result: " << cookie_line;
1394
1395 return cookie_line;
1396}
1397
1398void CookieMonster::DeleteCookie(const GURL& url,
1399 const std::string& cookie_name) {
[email protected]20305ec2011-01-21 04:55:521400 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401401
1402 if (!HasCookieableScheme(url))
1403 return;
1404
1405 CookieOptions options;
1406 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:311407 options.set_include_first_party_only();
[email protected]f48b9432011-01-11 07:25:401408 // Get the cookies for this host and its domain(s).
1409 std::vector<CanonicalCookie*> cookies;
1410 FindCookiesForHostAndDomain(url, options, true, &cookies);
1411 std::set<CanonicalCookie*> matching_cookies;
1412
1413 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
1414 it != cookies.end(); ++it) {
1415 if ((*it)->Name() != cookie_name)
1416 continue;
1417 if (url.path().find((*it)->Path()))
1418 continue;
1419 matching_cookies.insert(*it);
1420 }
1421
1422 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1423 CookieMap::iterator curit = it;
1424 ++it;
1425 if (matching_cookies.find(curit->second) != matching_cookies.end()) {
1426 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT);
1427 }
1428 }
1429}
1430
[email protected]264807b2012-04-25 14:49:371431int CookieMonster::DeleteSessionCookies() {
1432 base::AutoLock autolock(lock_);
1433
1434 int num_deleted = 0;
1435 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1436 CookieMap::iterator curit = it;
1437 CanonicalCookie* cc = curit->second;
1438 ++it;
1439
1440 if (!cc->IsPersistent()) {
mkwstbe84af312015-02-20 08:52:451441 InternalDeleteCookie(curit, true, /*sync_to_store*/
[email protected]264807b2012-04-25 14:49:371442 DELETE_COOKIE_EXPIRED);
1443 ++num_deleted;
1444 }
1445 }
1446
1447 return num_deleted;
1448}
1449
[email protected]ee209482013-04-19 19:50:041450bool CookieMonster::HasCookiesForETLDP1(const std::string& etldp1) {
1451 base::AutoLock autolock(lock_);
1452
1453 const std::string key(GetKey(etldp1));
1454
1455 CookieMapItPair its = cookies_.equal_range(key);
1456 return its.first != its.second;
1457}
1458
[email protected]f48b9432011-01-11 07:25:401459CookieMonster* CookieMonster::GetCookieMonster() {
1460 return this;
1461}
1462
[email protected]8ad5d462013-05-02 08:45:261463// This function must be called before the CookieMonster is used.
[email protected]93c53a32011-12-05 10:40:351464void CookieMonster::SetPersistSessionCookies(bool persist_session_cookies) {
[email protected]93c53a32011-12-05 10:40:351465 DCHECK(!initialized_);
1466 persist_session_cookies_ = persist_session_cookies;
1467}
1468
[email protected]bf510ed2012-06-05 08:31:431469void CookieMonster::SetForceKeepSessionState() {
[email protected]90499482013-06-01 00:39:501470 if (store_.get()) {
[email protected]bf510ed2012-06-05 08:31:431471 store_->SetForceKeepSessionState();
[email protected]93c53a32011-12-05 10:40:351472 }
1473}
1474
[email protected]f48b9432011-01-11 07:25:401475CookieMonster::~CookieMonster() {
1476 DeleteAll(false);
1477}
1478
1479bool CookieMonster::SetCookieWithCreationTime(const GURL& url,
1480 const std::string& cookie_line,
1481 const base::Time& creation_time) {
[email protected]90499482013-06-01 00:39:501482 DCHECK(!store_.get()) << "This method is only to be used by unit-tests.";
[email protected]20305ec2011-01-21 04:55:521483 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401484
1485 if (!HasCookieableScheme(url)) {
1486 return false;
1487 }
1488
erikchen1dd72a72015-05-06 20:45:051489 MarkCookieStoreAsInitialized();
1490 if (ShouldFetchAllCookiesWhenFetchingAnyCookie())
1491 FetchAllCookiesIfNecessary();
1492
[email protected]f48b9432011-01-11 07:25:401493 return SetCookieWithCreationTimeAndOptions(url, cookie_line, creation_time,
1494 CookieOptions());
1495}
1496
erikchen1dd72a72015-05-06 20:45:051497void CookieMonster::MarkCookieStoreAsInitialized() {
1498 initialized_ = true;
1499}
1500
1501void CookieMonster::FetchAllCookiesIfNecessary() {
1502 if (store_.get() && !started_fetching_all_cookies_) {
1503 started_fetching_all_cookies_ = true;
1504 FetchAllCookies();
1505 }
1506}
1507
1508bool CookieMonster::ShouldFetchAllCookiesWhenFetchingAnyCookie() {
1509 if (fetch_strategy_ == kUnknownFetch) {
1510 const std::string group_name =
1511 base::FieldTrialList::FindFullName(kCookieMonsterFetchStrategyName);
1512 if (group_name == kFetchWhenNecessaryName) {
1513 fetch_strategy_ = kFetchWhenNecessary;
1514 } else if (group_name == kAlwaysFetchName) {
1515 fetch_strategy_ = kAlwaysFetch;
1516 } else {
1517 // The logic in the conditional is redundant, but it makes trials of
1518 // the Finch experiment more explicit.
1519 fetch_strategy_ = kAlwaysFetch;
1520 }
1521 }
1522
1523 return fetch_strategy_ == kAlwaysFetch;
1524}
1525
1526void CookieMonster::FetchAllCookies() {
[email protected]90499482013-06-01 00:39:501527 DCHECK(store_.get()) << "Store must exist to initialize";
erikchen1dd72a72015-05-06 20:45:051528 DCHECK(!finished_fetching_all_cookies_)
1529 << "All cookies have already been fetched.";
[email protected]f48b9432011-01-11 07:25:401530
[email protected]218aa6a12011-09-13 17:38:381531 // We bind in the current time so that we can report the wall-clock time for
1532 // loading cookies.
1533 store_->Load(base::Bind(&CookieMonster::OnLoaded, this, TimeTicks::Now()));
1534}
[email protected]f48b9432011-01-11 07:25:401535
[email protected]218aa6a12011-09-13 17:38:381536void CookieMonster::OnLoaded(TimeTicks beginning_time,
1537 const std::vector<CanonicalCookie*>& cookies) {
1538 StoreLoadedCookies(cookies);
[email protected]c7593fb22011-11-14 23:54:271539 histogram_time_blocked_on_load_->AddTime(TimeTicks::Now() - beginning_time);
[email protected]218aa6a12011-09-13 17:38:381540
1541 // Invoke the task queue of cookie request.
1542 InvokeQueue();
1543}
1544
[email protected]85620342011-10-17 17:35:041545void CookieMonster::OnKeyLoaded(const std::string& key,
1546 const std::vector<CanonicalCookie*>& cookies) {
1547 // This function does its own separate locking.
1548 StoreLoadedCookies(cookies);
1549
mkwstbe84af312015-02-20 08:52:451550 std::deque<scoped_refptr<CookieMonsterTask>> tasks_pending_for_key;
[email protected]85620342011-10-17 17:35:041551
[email protected]bab72ec2013-10-30 20:50:021552 // We need to do this repeatedly until no more tasks were added to the queue
1553 // during the period where we release the lock.
1554 while (true) {
1555 {
1556 base::AutoLock autolock(lock_);
mkwstbe84af312015-02-20 08:52:451557 std::map<std::string,
1558 std::deque<scoped_refptr<CookieMonsterTask>>>::iterator it =
1559 tasks_pending_for_key_.find(key);
[email protected]bab72ec2013-10-30 20:50:021560 if (it == tasks_pending_for_key_.end()) {
1561 keys_loaded_.insert(key);
1562 return;
1563 }
1564 if (it->second.empty()) {
1565 keys_loaded_.insert(key);
1566 tasks_pending_for_key_.erase(it);
1567 return;
1568 }
1569 it->second.swap(tasks_pending_for_key);
1570 }
1571
1572 while (!tasks_pending_for_key.empty()) {
1573 scoped_refptr<CookieMonsterTask> task = tasks_pending_for_key.front();
1574 task->Run();
1575 tasks_pending_for_key.pop_front();
1576 }
[email protected]85620342011-10-17 17:35:041577 }
1578}
1579
[email protected]218aa6a12011-09-13 17:38:381580void CookieMonster::StoreLoadedCookies(
1581 const std::vector<CanonicalCookie*>& cookies) {
pkastingec2cdb52015-05-02 01:19:341582 // TODO(erikwright): Remove ScopedTracker below once crbug.com/457528 is
1583 // fixed.
1584 tracked_objects::ScopedTracker tracking_profile(
1585 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1586 "457528 CookieMonster::StoreLoadedCookies"));
1587
[email protected]f48b9432011-01-11 07:25:401588 // Initialize the store and sync in any saved persistent cookies. We don't
1589 // care if it's expired, insert it so it can be garbage collected, removed,
1590 // and sync'd.
[email protected]218aa6a12011-09-13 17:38:381591 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401592
[email protected]6210ce52013-09-20 03:33:141593 CookieItVector cookies_with_control_chars;
1594
[email protected]f48b9432011-01-11 07:25:401595 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
1596 it != cookies.end(); ++it) {
1597 int64 cookie_creation_time = (*it)->CreationDate().ToInternalValue();
1598
[email protected]85620342011-10-17 17:35:041599 if (creation_times_.insert(cookie_creation_time).second) {
[email protected]6210ce52013-09-20 03:33:141600 CookieMap::iterator inserted =
1601 InternalInsertCookie(GetKey((*it)->Domain()), *it, false);
[email protected]f48b9432011-01-11 07:25:401602 const Time cookie_access_time((*it)->LastAccessDate());
[email protected]85620342011-10-17 17:35:041603 if (earliest_access_time_.is_null() ||
1604 cookie_access_time < earliest_access_time_)
1605 earliest_access_time_ = cookie_access_time;
[email protected]6210ce52013-09-20 03:33:141606
1607 if (ContainsControlCharacter((*it)->Name()) ||
1608 ContainsControlCharacter((*it)->Value())) {
mkwstbe84af312015-02-20 08:52:451609 cookies_with_control_chars.push_back(inserted);
[email protected]6210ce52013-09-20 03:33:141610 }
[email protected]f48b9432011-01-11 07:25:401611 } else {
mkwstbe84af312015-02-20 08:52:451612 LOG(ERROR) << base::StringPrintf(
1613 "Found cookies with duplicate creation "
1614 "times in backing store: "
1615 "{name='%s', domain='%s', path='%s'}",
1616 (*it)->Name().c_str(), (*it)->Domain().c_str(),
1617 (*it)->Path().c_str());
[email protected]f48b9432011-01-11 07:25:401618 // We've been given ownership of the cookie and are throwing it
1619 // away; reclaim the space.
1620 delete (*it);
1621 }
1622 }
[email protected]f48b9432011-01-11 07:25:401623
[email protected]6210ce52013-09-20 03:33:141624 // Any cookies that contain control characters that we have loaded from the
1625 // persistent store should be deleted. See http://crbug.com/238041.
1626 for (CookieItVector::iterator it = cookies_with_control_chars.begin();
1627 it != cookies_with_control_chars.end();) {
1628 CookieItVector::iterator curit = it;
1629 ++it;
1630
1631 InternalDeleteCookie(*curit, true, DELETE_COOKIE_CONTROL_CHAR);
1632 }
1633
[email protected]f48b9432011-01-11 07:25:401634 // After importing cookies from the PersistentCookieStore, verify that
1635 // none of our other constraints are violated.
[email protected]f48b9432011-01-11 07:25:401636 // In particular, the backing store might have given us duplicate cookies.
[email protected]85620342011-10-17 17:35:041637
1638 // This method could be called multiple times due to priority loading, thus
1639 // cookies loaded in previous runs will be validated again, but this is OK
1640 // since they are expected to be much fewer than total DB.
[email protected]f48b9432011-01-11 07:25:401641 EnsureCookiesMapIsValid();
[email protected]218aa6a12011-09-13 17:38:381642}
[email protected]f48b9432011-01-11 07:25:401643
[email protected]218aa6a12011-09-13 17:38:381644void CookieMonster::InvokeQueue() {
1645 while (true) {
1646 scoped_refptr<CookieMonsterTask> request_task;
1647 {
1648 base::AutoLock autolock(lock_);
[email protected]0184df32013-05-14 00:53:551649 if (tasks_pending_.empty()) {
erikchen1dd72a72015-05-06 20:45:051650 finished_fetching_all_cookies_ = true;
[email protected]85620342011-10-17 17:35:041651 creation_times_.clear();
1652 keys_loaded_.clear();
[email protected]218aa6a12011-09-13 17:38:381653 break;
1654 }
[email protected]0184df32013-05-14 00:53:551655 request_task = tasks_pending_.front();
1656 tasks_pending_.pop();
[email protected]218aa6a12011-09-13 17:38:381657 }
1658 request_task->Run();
1659 }
[email protected]f48b9432011-01-11 07:25:401660}
1661
1662void CookieMonster::EnsureCookiesMapIsValid() {
1663 lock_.AssertAcquired();
1664
1665 int num_duplicates_trimmed = 0;
1666
1667 // Iterate through all the of the cookies, grouped by host.
1668 CookieMap::iterator prev_range_end = cookies_.begin();
1669 while (prev_range_end != cookies_.end()) {
1670 CookieMap::iterator cur_range_begin = prev_range_end;
1671 const std::string key = cur_range_begin->first; // Keep a copy.
1672 CookieMap::iterator cur_range_end = cookies_.upper_bound(key);
1673 prev_range_end = cur_range_end;
1674
1675 // Ensure no equivalent cookies for this host.
1676 num_duplicates_trimmed +=
1677 TrimDuplicateCookiesForKey(key, cur_range_begin, cur_range_end);
1678 }
1679
1680 // Record how many duplicates were found in the database.
1681 // See InitializeHistograms() for details.
mkwste0a9ca872015-03-30 20:24:381682 histogram_number_duplicate_db_cookies_->Add(num_duplicates_trimmed);
[email protected]f48b9432011-01-11 07:25:401683}
1684
mkwstbe84af312015-02-20 08:52:451685int CookieMonster::TrimDuplicateCookiesForKey(const std::string& key,
1686 CookieMap::iterator begin,
1687 CookieMap::iterator end) {
[email protected]f48b9432011-01-11 07:25:401688 lock_.AssertAcquired();
1689
1690 // Set of cookies ordered by creation time.
1691 typedef std::set<CookieMap::iterator, OrderByCreationTimeDesc> CookieSet;
1692
1693 // Helper map we populate to find the duplicates.
1694 typedef std::map<CookieSignature, CookieSet> EquivalenceMap;
1695 EquivalenceMap equivalent_cookies;
1696
1697 // The number of duplicate cookies that have been found.
1698 int num_duplicates = 0;
1699
1700 // Iterate through all of the cookies in our range, and insert them into
1701 // the equivalence map.
1702 for (CookieMap::iterator it = begin; it != end; ++it) {
1703 DCHECK_EQ(key, it->first);
1704 CanonicalCookie* cookie = it->second;
1705
mkwstbe84af312015-02-20 08:52:451706 CookieSignature signature(cookie->Name(), cookie->Domain(), cookie->Path());
[email protected]f48b9432011-01-11 07:25:401707 CookieSet& set = equivalent_cookies[signature];
1708
1709 // We found a duplicate!
1710 if (!set.empty())
1711 num_duplicates++;
1712
1713 // We save the iterator into |cookies_| rather than the actual cookie
1714 // pointer, since we may need to delete it later.
1715 bool insert_success = set.insert(it).second;
mkwstbe84af312015-02-20 08:52:451716 DCHECK(insert_success)
1717 << "Duplicate creation times found in duplicate cookie name scan.";
[email protected]f48b9432011-01-11 07:25:401718 }
1719
1720 // If there were no duplicates, we are done!
1721 if (num_duplicates == 0)
1722 return 0;
1723
1724 // Make sure we find everything below that we did above.
1725 int num_duplicates_found = 0;
1726
1727 // Otherwise, delete all the duplicate cookies, both from our in-memory store
1728 // and from the backing store.
1729 for (EquivalenceMap::iterator it = equivalent_cookies.begin();
mkwstbe84af312015-02-20 08:52:451730 it != equivalent_cookies.end(); ++it) {
[email protected]f48b9432011-01-11 07:25:401731 const CookieSignature& signature = it->first;
1732 CookieSet& dupes = it->second;
1733
1734 if (dupes.size() <= 1)
1735 continue; // This cookiename/path has no duplicates.
1736 num_duplicates_found += dupes.size() - 1;
1737
1738 // Since |dups| is sorted by creation time (descending), the first cookie
1739 // is the most recent one, so we will keep it. The rest are duplicates.
1740 dupes.erase(dupes.begin());
1741
1742 LOG(ERROR) << base::StringPrintf(
1743 "Found %d duplicate cookies for host='%s', "
1744 "with {name='%s', domain='%s', path='%s'}",
mkwstbe84af312015-02-20 08:52:451745 static_cast<int>(dupes.size()), key.c_str(), signature.name.c_str(),
1746 signature.domain.c_str(), signature.path.c_str());
[email protected]f48b9432011-01-11 07:25:401747
1748 // Remove all the cookies identified by |dupes|. It is valid to delete our
1749 // list of iterators one at a time, since |cookies_| is a multimap (they
1750 // don't invalidate existing iterators following deletion).
mkwstbe84af312015-02-20 08:52:451751 for (CookieSet::iterator dupes_it = dupes.begin(); dupes_it != dupes.end();
[email protected]f48b9432011-01-11 07:25:401752 ++dupes_it) {
[email protected]218aa6a12011-09-13 17:38:381753 InternalDeleteCookie(*dupes_it, true,
[email protected]f48b9432011-01-11 07:25:401754 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE);
1755 }
1756 }
1757 DCHECK_EQ(num_duplicates, num_duplicates_found);
1758
1759 return num_duplicates;
1760}
1761
[email protected]ba4ad0e2011-03-15 08:12:471762// Note: file must be the last scheme.
mkwstbe84af312015-02-20 08:52:451763const char* const CookieMonster::kDefaultCookieableSchemes[] = {"http",
1764 "https",
1765 "ws",
1766 "wss",
1767 "file"};
[email protected]ba4ad0e2011-03-15 08:12:471768const int CookieMonster::kDefaultCookieableSchemesCount =
[email protected]5fa4f9a2013-10-03 10:13:161769 arraysize(kDefaultCookieableSchemes);
[email protected]ba4ad0e2011-03-15 08:12:471770
[email protected]f48b9432011-01-11 07:25:401771void CookieMonster::SetDefaultCookieableSchemes() {
[email protected]7c4b66b2014-01-04 12:28:131772 // Always disable file scheme unless SetEnableFileScheme(true) is called.
1773 SetCookieableSchemes(kDefaultCookieableSchemes,
1774 kDefaultCookieableSchemesCount - 1);
[email protected]f48b9432011-01-11 07:25:401775}
1776
[email protected]f48b9432011-01-11 07:25:401777void CookieMonster::FindCookiesForHostAndDomain(
1778 const GURL& url,
1779 const CookieOptions& options,
1780 bool update_access_time,
1781 std::vector<CanonicalCookie*>* cookies) {
1782 lock_.AssertAcquired();
1783
1784 const Time current_time(CurrentTime());
1785
1786 // Probe to save statistics relatively frequently. We do it here rather
1787 // than in the set path as many websites won't set cookies, and we
1788 // want to collect statistics whenever the browser's being used.
1789 RecordPeriodicStats(current_time);
1790
[email protected]8e1583672012-02-11 04:39:411791 // Can just dispatch to FindCookiesForKey
1792 const std::string key(GetKey(url.host()));
mkwstbe84af312015-02-20 08:52:451793 FindCookiesForKey(key, url, options, current_time, update_access_time,
1794 cookies);
[email protected]f48b9432011-01-11 07:25:401795}
1796
[email protected]dedec0b2013-02-28 04:50:101797void CookieMonster::FindCookiesForKey(const std::string& key,
1798 const GURL& url,
1799 const CookieOptions& options,
1800 const Time& current,
1801 bool update_access_time,
1802 std::vector<CanonicalCookie*>* cookies) {
[email protected]f48b9432011-01-11 07:25:401803 lock_.AssertAcquired();
1804
[email protected]f48b9432011-01-11 07:25:401805 for (CookieMapItPair its = cookies_.equal_range(key);
mkwstbe84af312015-02-20 08:52:451806 its.first != its.second;) {
[email protected]f48b9432011-01-11 07:25:401807 CookieMap::iterator curit = its.first;
1808 CanonicalCookie* cc = curit->second;
1809 ++its.first;
1810
1811 // If the cookie is expired, delete it.
[email protected]ba4ad0e2011-03-15 08:12:471812 if (cc->IsExpired(current) && !keep_expired_cookies_) {
[email protected]f48b9432011-01-11 07:25:401813 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
1814 continue;
1815 }
1816
[email protected]65f4e7e2012-12-12 21:56:541817 // Filter out cookies that should not be included for a request to the
1818 // given |url|. HTTP only cookies are filtered depending on the passed
1819 // cookie |options|.
1820 if (!cc->IncludeForRequestURL(url, options))
[email protected]f48b9432011-01-11 07:25:401821 continue;
1822
[email protected]65f4e7e2012-12-12 21:56:541823 // Add this cookie to the set of matching cookies. Update the access
[email protected]f48b9432011-01-11 07:25:401824 // time if we've been requested to do so.
1825 if (update_access_time) {
1826 InternalUpdateCookieAccessTime(cc, current);
1827 }
1828 cookies->push_back(cc);
1829 }
1830}
1831
1832bool CookieMonster::DeleteAnyEquivalentCookie(const std::string& key,
1833 const CanonicalCookie& ecc,
[email protected]e7c590e52011-03-30 08:33:551834 bool skip_httponly,
1835 bool already_expired) {
[email protected]f48b9432011-01-11 07:25:401836 lock_.AssertAcquired();
1837
1838 bool found_equivalent_cookie = false;
1839 bool skipped_httponly = false;
1840 for (CookieMapItPair its = cookies_.equal_range(key);
mkwstbe84af312015-02-20 08:52:451841 its.first != its.second;) {
[email protected]f48b9432011-01-11 07:25:401842 CookieMap::iterator curit = its.first;
1843 CanonicalCookie* cc = curit->second;
1844 ++its.first;
1845
1846 if (ecc.IsEquivalent(*cc)) {
1847 // We should never have more than one equivalent cookie, since they should
1848 // overwrite each other.
mkwstbe84af312015-02-20 08:52:451849 CHECK(!found_equivalent_cookie)
1850 << "Duplicate equivalent cookies found, cookie store is corrupted.";
[email protected]f48b9432011-01-11 07:25:401851 if (skip_httponly && cc->IsHttpOnly()) {
1852 skipped_httponly = true;
1853 } else {
mkwstbe84af312015-02-20 08:52:451854 InternalDeleteCookie(curit, true, already_expired
1855 ? DELETE_COOKIE_EXPIRED_OVERWRITE
1856 : DELETE_COOKIE_OVERWRITE);
[email protected]f48b9432011-01-11 07:25:401857 }
1858 found_equivalent_cookie = true;
1859 }
1860 }
1861 return skipped_httponly;
1862}
1863
[email protected]6210ce52013-09-20 03:33:141864CookieMonster::CookieMap::iterator CookieMonster::InternalInsertCookie(
1865 const std::string& key,
1866 CanonicalCookie* cc,
1867 bool sync_to_store) {
pkastinga9269aa42015-04-10 01:42:261868 // TODO(mkwst): Remove ScopedTracker below once crbug.com/456373 is fixed.
pkasting58e029b2015-02-21 05:17:281869 tracked_objects::ScopedTracker tracking_profile(
1870 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1871 "456373 CookieMonster::InternalInsertCookie"));
[email protected]f48b9432011-01-11 07:25:401872 lock_.AssertAcquired();
1873
[email protected]90499482013-06-01 00:39:501874 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() &&
1875 sync_to_store)
[email protected]f48b9432011-01-11 07:25:401876 store_->AddCookie(*cc);
[email protected]6210ce52013-09-20 03:33:141877 CookieMap::iterator inserted =
1878 cookies_.insert(CookieMap::value_type(key, cc));
[email protected]8bb846f2011-03-23 12:08:181879 if (delegate_.get()) {
mkwstbe84af312015-02-20 08:52:451880 delegate_->OnCookieChanged(*cc, false,
1881 CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT);
[email protected]8bb846f2011-03-23 12:08:181882 }
mkwstc1aa4cc2015-04-03 19:57:451883
1884 // See InitializeHistograms() for details.
1885 int32_t sample = cc->IsFirstPartyOnly() ? 1 << COOKIE_TYPE_FIRSTPARTYONLY : 0;
1886 sample |= cc->IsHttpOnly() ? 1 << COOKIE_TYPE_HTTPONLY : 0;
1887 sample |= cc->IsSecure() ? 1 << COOKIE_TYPE_SECURE : 0;
1888 histogram_cookie_type_->Add(sample);
1889
msarda0aad8f02014-10-30 09:22:391890 RunCallbacks(*cc, false);
[email protected]6210ce52013-09-20 03:33:141891
1892 return inserted;
[email protected]f48b9432011-01-11 07:25:401893}
1894
[email protected]34602282010-02-03 22:14:151895bool CookieMonster::SetCookieWithCreationTimeAndOptions(
1896 const GURL& url,
1897 const std::string& cookie_line,
1898 const Time& creation_time_or_null,
1899 const CookieOptions& options) {
[email protected]b866a02d2010-07-28 16:41:041900 lock_.AssertAcquired();
initial.commit586acc5fe2008-07-26 22:42:521901
[email protected]4d3ce782010-10-29 18:31:281902 VLOG(kVlogSetCookies) << "SetCookie() line: " << cookie_line;
initial.commit586acc5fe2008-07-26 22:42:521903
[email protected]34602282010-02-03 22:14:151904 Time creation_time = creation_time_or_null;
1905 if (creation_time.is_null()) {
1906 creation_time = CurrentTime();
1907 last_time_seen_ = creation_time;
1908 }
1909
[email protected]abbd13b2012-11-15 17:54:201910 scoped_ptr<CanonicalCookie> cc(
1911 CanonicalCookie::Create(url, cookie_line, creation_time, options));
initial.commit586acc5fe2008-07-26 22:42:521912
1913 if (!cc.get()) {
[email protected]4d3ce782010-10-29 18:31:281914 VLOG(kVlogSetCookies) << "WARNING: Failed to allocate CanonicalCookie";
initial.commit586acc5fe2008-07-26 22:42:521915 return false;
1916 }
[email protected]fa77eb512010-07-22 16:12:511917 return SetCanonicalCookie(&cc, creation_time, options);
[email protected]f325f1e12010-04-30 22:38:551918}
initial.commit586acc5fe2008-07-26 22:42:521919
[email protected]f325f1e12010-04-30 22:38:551920bool CookieMonster::SetCanonicalCookie(scoped_ptr<CanonicalCookie>* cc,
[email protected]f325f1e12010-04-30 22:38:551921 const Time& creation_time,
1922 const CookieOptions& options) {
[email protected]7a964a72010-09-07 19:33:261923 const std::string key(GetKey((*cc)->Domain()));
[email protected]e7c590e52011-03-30 08:33:551924 bool already_expired = (*cc)->IsExpired(creation_time);
ellyjones399e35a22014-10-27 11:09:561925
[email protected]e7c590e52011-03-30 08:33:551926 if (DeleteAnyEquivalentCookie(key, **cc, options.exclude_httponly(),
1927 already_expired)) {
[email protected]4d3ce782010-10-29 18:31:281928 VLOG(kVlogSetCookies) << "SetCookie() not clobbering httponly cookie";
[email protected]3a96c742008-11-19 19:46:271929 return false;
1930 }
initial.commit586acc5fe2008-07-26 22:42:521931
mkwstbe84af312015-02-20 08:52:451932 VLOG(kVlogSetCookies) << "SetCookie() key: " << key
1933 << " cc: " << (*cc)->DebugString();
initial.commit586acc5fe2008-07-26 22:42:521934
1935 // Realize that we might be setting an expired cookie, and the only point
1936 // was to delete the cookie which we've already done.
[email protected]e7c590e52011-03-30 08:33:551937 if (!already_expired || keep_expired_cookies_) {
[email protected]374f58b2010-07-20 15:29:261938 // See InitializeHistograms() for details.
[email protected]10b691f2012-07-11 15:22:151939 if ((*cc)->IsPersistent()) {
[email protected]8475bee2011-03-17 18:40:241940 histogram_expiration_duration_minutes_->Add(
1941 ((*cc)->ExpiryDate() - creation_time).InMinutes());
1942 }
1943
ellyjones399e35a22014-10-27 11:09:561944 {
1945 CanonicalCookie cookie = *(cc->get());
1946 InternalInsertCookie(key, cc->release(), true);
ellyjones399e35a22014-10-27 11:09:561947 }
[email protected]348dd662013-03-13 20:25:071948 } else {
1949 VLOG(kVlogSetCookies) << "SetCookie() not storing already expired cookie.";
[email protected]c4058fb2010-06-22 17:25:261950 }
initial.commit586acc5fe2008-07-26 22:42:521951
1952 // We assume that hopefully setting a cookie will be less common than
1953 // querying a cookie. Since setting a cookie can put us over our limits,
1954 // make sure that we garbage collect... We can also make the assumption that
1955 // if a cookie was set, in the common case it will be used soon after,
1956 // and we will purge the expired cookies in GetCookies().
[email protected]7a964a72010-09-07 19:33:261957 GarbageCollect(creation_time, key);
initial.commit586acc5fe2008-07-26 22:42:521958
1959 return true;
1960}
1961
drogerd5d1278c2015-03-17 19:21:511962bool CookieMonster::SetCanonicalCookies(const CookieList& list) {
1963 base::AutoLock autolock(lock_);
1964
ttuttle859dc7a2015-04-23 19:42:291965 CookieOptions options;
drogerd5d1278c2015-03-17 19:21:511966 options.set_include_httponly();
1967
1968 for (CookieList::const_iterator it = list.begin(); it != list.end(); ++it) {
1969 scoped_ptr<CanonicalCookie> canonical_cookie(new CanonicalCookie(*it));
1970 if (!SetCanonicalCookie(&canonical_cookie, it->CreationDate(), options))
1971 return false;
1972 }
1973
1974 return true;
1975}
1976
[email protected]7a964a72010-09-07 19:33:261977void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie* cc,
1978 const Time& current) {
[email protected]bb8905722010-05-21 17:29:041979 lock_.AssertAcquired();
1980
[email protected]77e0a462008-11-01 00:43:351981 // Based off the Mozilla code. When a cookie has been accessed recently,
1982 // don't bother updating its access time again. This reduces the number of
1983 // updates we do during pageload, which in turn reduces the chance our storage
1984 // backend will hit its batch thresholds and be forced to update.
[email protected]77e0a462008-11-01 00:43:351985 if ((current - cc->LastAccessDate()) < last_access_threshold_)
1986 return;
1987
[email protected]374f58b2010-07-20 15:29:261988 // See InitializeHistograms() for details.
1989 histogram_between_access_interval_minutes_->Add(
1990 (current - cc->LastAccessDate()).InMinutes());
[email protected]c4058fb2010-06-22 17:25:261991
[email protected]77e0a462008-11-01 00:43:351992 cc->SetLastAccessDate(current);
[email protected]90499482013-06-01 00:39:501993 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get())
[email protected]77e0a462008-11-01 00:43:351994 store_->UpdateCookieAccessTime(*cc);
1995}
1996
[email protected]6210ce52013-09-20 03:33:141997// InternalDeleteCookies must not invalidate iterators other than the one being
1998// deleted.
initial.commit586acc5fe2008-07-26 22:42:521999void CookieMonster::InternalDeleteCookie(CookieMap::iterator it,
[email protected]c4058fb2010-06-22 17:25:262000 bool sync_to_store,
2001 DeletionCause deletion_cause) {
[email protected]bb8905722010-05-21 17:29:042002 lock_.AssertAcquired();
2003
[email protected]8bb846f2011-03-23 12:08:182004 // Ideally, this would be asserted up where we define ChangeCauseMapping,
2005 // but DeletionCause's visibility (or lack thereof) forces us to make
2006 // this check here.
mostynb91e0da982015-01-20 19:17:272007 static_assert(arraysize(ChangeCauseMapping) == DELETE_COOKIE_LAST_ENTRY + 1,
2008 "ChangeCauseMapping size should match DeletionCause size");
[email protected]8bb846f2011-03-23 12:08:182009
[email protected]374f58b2010-07-20 15:29:262010 // See InitializeHistograms() for details.
[email protected]7a964a72010-09-07 19:33:262011 if (deletion_cause != DELETE_COOKIE_DONT_RECORD)
2012 histogram_cookie_deletion_cause_->Add(deletion_cause);
[email protected]c4058fb2010-06-22 17:25:262013
initial.commit586acc5fe2008-07-26 22:42:522014 CanonicalCookie* cc = it->second;
xiyuan8dbb89892015-04-13 17:04:302015 VLOG(kVlogSetCookies) << "InternalDeleteCookie()"
2016 << ", cause:" << deletion_cause
2017 << ", cc: " << cc->DebugString();
[email protected]7a964a72010-09-07 19:33:262018
[email protected]90499482013-06-01 00:39:502019 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() &&
2020 sync_to_store)
initial.commit586acc5fe2008-07-26 22:42:522021 store_->DeleteCookie(*cc);
[email protected]8bb846f2011-03-23 12:08:182022 if (delegate_.get()) {
2023 ChangeCausePair mapping = ChangeCauseMapping[deletion_cause];
2024
2025 if (mapping.notify)
2026 delegate_->OnCookieChanged(*cc, true, mapping.cause);
2027 }
msarda0aad8f02014-10-30 09:22:392028 RunCallbacks(*cc, true);
initial.commit586acc5fe2008-07-26 22:42:522029 cookies_.erase(it);
2030 delete cc;
2031}
2032
[email protected]8807b322010-10-01 17:10:142033// Domain expiry behavior is unchanged by key/expiry scheme (the
[email protected]8ad5d462013-05-02 08:45:262034// meaning of the key is different, but that's not visible to this routine).
mkwstbe84af312015-02-20 08:52:452035int CookieMonster::GarbageCollect(const Time& current, const std::string& key) {
[email protected]bb8905722010-05-21 17:29:042036 lock_.AssertAcquired();
2037
initial.commit586acc5fe2008-07-26 22:42:522038 int num_deleted = 0;
mkwstbe84af312015-02-20 08:52:452039 Time safe_date(Time::Now() - TimeDelta::FromDays(kSafeFromGlobalPurgeDays));
initial.commit586acc5fe2008-07-26 22:42:522040
[email protected]8ad5d462013-05-02 08:45:262041 // Collect garbage for this key, minding cookie priorities.
[email protected]7a964a72010-09-07 19:33:262042 if (cookies_.count(key) > kDomainMaxCookies) {
[email protected]4d3ce782010-10-29 18:31:282043 VLOG(kVlogGarbageCollection) << "GarbageCollect() key: " << key;
[email protected]7a964a72010-09-07 19:33:262044
[email protected]8ad5d462013-05-02 08:45:262045 CookieItVector cookie_its;
mkwstbe84af312015-02-20 08:52:452046 num_deleted +=
2047 GarbageCollectExpired(current, cookies_.equal_range(key), &cookie_its);
[email protected]8ad5d462013-05-02 08:45:262048 if (cookie_its.size() > kDomainMaxCookies) {
2049 VLOG(kVlogGarbageCollection) << "Deep Garbage Collect domain.";
2050 size_t purge_goal =
2051 cookie_its.size() - (kDomainMaxCookies - kDomainPurgeCookies);
2052 DCHECK(purge_goal > kDomainPurgeCookies);
2053
2054 // Boundary iterators into |cookie_its| for different priorities.
2055 CookieItVector::iterator it_bdd[4];
2056 // Intialize |it_bdd| while sorting |cookie_its| by priorities.
2057 // Schematic: [MLLHMHHLMM] => [LLL|MMMM|HHH], with 4 boundaries.
2058 it_bdd[0] = cookie_its.begin();
2059 it_bdd[3] = cookie_its.end();
mkwstbe84af312015-02-20 08:52:452060 it_bdd[1] =
2061 PartitionCookieByPriority(it_bdd[0], it_bdd[3], COOKIE_PRIORITY_LOW);
[email protected]8ad5d462013-05-02 08:45:262062 it_bdd[2] = PartitionCookieByPriority(it_bdd[1], it_bdd[3],
2063 COOKIE_PRIORITY_MEDIUM);
mkwstbe84af312015-02-20 08:52:452064 size_t quota[3] = {kDomainCookiesQuotaLow,
2065 kDomainCookiesQuotaMedium,
2066 kDomainCookiesQuotaHigh};
[email protected]8ad5d462013-05-02 08:45:262067
2068 // Purge domain cookies in 3 rounds.
2069 // Round 1: consider low-priority cookies only: evict least-recently
2070 // accessed, while protecting quota[0] of these from deletion.
2071 // Round 2: consider {low, medium}-priority cookies, evict least-recently
2072 // accessed, while protecting quota[0] + quota[1].
2073 // Round 3: consider all cookies, evict least-recently accessed.
2074 size_t accumulated_quota = 0;
2075 CookieItVector::iterator it_purge_begin = it_bdd[0];
2076 for (int i = 0; i < 3 && purge_goal > 0; ++i) {
2077 accumulated_quota += quota[i];
2078
[email protected]8ad5d462013-05-02 08:45:262079 size_t num_considered = it_bdd[i + 1] - it_purge_begin;
2080 if (num_considered <= accumulated_quota)
2081 continue;
2082
2083 // Number of cookies that will be purged in this round.
2084 size_t round_goal =
2085 std::min(purge_goal, num_considered - accumulated_quota);
2086 purge_goal -= round_goal;
2087
2088 SortLeastRecentlyAccessed(it_purge_begin, it_bdd[i + 1], round_goal);
2089 // Cookies accessed on or after |safe_date| would have been safe from
2090 // global purge, and we want to keep track of this.
2091 CookieItVector::iterator it_purge_end = it_purge_begin + round_goal;
2092 CookieItVector::iterator it_purge_middle =
2093 LowerBoundAccessDate(it_purge_begin, it_purge_end, safe_date);
2094 // Delete cookies accessed before |safe_date|.
2095 num_deleted += GarbageCollectDeleteRange(
mkwstbe84af312015-02-20 08:52:452096 current, DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE, it_purge_begin,
[email protected]8ad5d462013-05-02 08:45:262097 it_purge_middle);
2098 // Delete cookies accessed on or after |safe_date|.
2099 num_deleted += GarbageCollectDeleteRange(
mkwstbe84af312015-02-20 08:52:452100 current, DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE, it_purge_middle,
[email protected]8ad5d462013-05-02 08:45:262101 it_purge_end);
2102 it_purge_begin = it_purge_end;
2103 }
2104 DCHECK_EQ(0U, purge_goal);
[email protected]8807b322010-10-01 17:10:142105 }
initial.commit586acc5fe2008-07-26 22:42:522106 }
2107
[email protected]8ad5d462013-05-02 08:45:262108 // Collect garbage for everything. With firefox style we want to preserve
2109 // cookies accessed in kSafeFromGlobalPurgeDays, otherwise evict.
mkwstbe84af312015-02-20 08:52:452110 if (cookies_.size() > kMaxCookies && earliest_access_time_ < safe_date) {
[email protected]4d3ce782010-10-29 18:31:282111 VLOG(kVlogGarbageCollection) << "GarbageCollect() everything";
[email protected]8ad5d462013-05-02 08:45:262112 CookieItVector cookie_its;
[email protected]7a964a72010-09-07 19:33:262113 num_deleted += GarbageCollectExpired(
2114 current, CookieMapItPair(cookies_.begin(), cookies_.end()),
2115 &cookie_its);
[email protected]8ad5d462013-05-02 08:45:262116 if (cookie_its.size() > kMaxCookies) {
2117 VLOG(kVlogGarbageCollection) << "Deep Garbage Collect everything.";
2118 size_t purge_goal = cookie_its.size() - (kMaxCookies - kPurgeCookies);
2119 DCHECK(purge_goal > kPurgeCookies);
2120 // Sorts up to *and including* |cookie_its[purge_goal]|, so
2121 // |earliest_access_time| will be properly assigned even if
2122 // |global_purge_it| == |cookie_its.begin() + purge_goal|.
2123 SortLeastRecentlyAccessed(cookie_its.begin(), cookie_its.end(),
2124 purge_goal);
2125 // Find boundary to cookies older than safe_date.
mkwstbe84af312015-02-20 08:52:452126 CookieItVector::iterator global_purge_it = LowerBoundAccessDate(
2127 cookie_its.begin(), cookie_its.begin() + purge_goal, safe_date);
[email protected]8ad5d462013-05-02 08:45:262128 // Only delete the old cookies.
mkwstbe84af312015-02-20 08:52:452129 num_deleted +=
2130 GarbageCollectDeleteRange(current, DELETE_COOKIE_EVICTED_GLOBAL,
2131 cookie_its.begin(), global_purge_it);
[email protected]8ad5d462013-05-02 08:45:262132 // Set access day to the oldest cookie that wasn't deleted.
2133 earliest_access_time_ = (*global_purge_it)->second->LastAccessDate();
[email protected]8807b322010-10-01 17:10:142134 }
[email protected]c890ed192008-10-30 23:45:532135 }
2136
2137 return num_deleted;
2138}
2139
mkwstbe84af312015-02-20 08:52:452140int CookieMonster::GarbageCollectExpired(const Time& current,
2141 const CookieMapItPair& itpair,
2142 CookieItVector* cookie_its) {
[email protected]ba4ad0e2011-03-15 08:12:472143 if (keep_expired_cookies_)
2144 return 0;
2145
[email protected]bb8905722010-05-21 17:29:042146 lock_.AssertAcquired();
2147
[email protected]c890ed192008-10-30 23:45:532148 int num_deleted = 0;
2149 for (CookieMap::iterator it = itpair.first, end = itpair.second; it != end;) {
2150 CookieMap::iterator curit = it;
2151 ++it;
2152
2153 if (curit->second->IsExpired(current)) {
[email protected]2f3f3592010-07-07 20:11:512154 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
[email protected]c890ed192008-10-30 23:45:532155 ++num_deleted;
2156 } else if (cookie_its) {
2157 cookie_its->push_back(curit);
2158 }
initial.commit586acc5fe2008-07-26 22:42:522159 }
2160
2161 return num_deleted;
2162}
2163
mkwstbe84af312015-02-20 08:52:452164int CookieMonster::GarbageCollectDeleteRange(const Time& current,
2165 DeletionCause cause,
2166 CookieItVector::iterator it_begin,
2167 CookieItVector::iterator it_end) {
[email protected]8ad5d462013-05-02 08:45:262168 for (CookieItVector::iterator it = it_begin; it != it_end; it++) {
2169 histogram_evicted_last_access_minutes_->Add(
2170 (current - (*it)->second->LastAccessDate()).InMinutes());
2171 InternalDeleteCookie((*it), true, cause);
[email protected]c10da4b02010-03-25 14:38:322172 }
[email protected]8ad5d462013-05-02 08:45:262173 return it_end - it_begin;
[email protected]c10da4b02010-03-25 14:38:322174}
2175
[email protected]ed32c212013-05-14 20:49:292176// A wrapper around registry_controlled_domains::GetDomainAndRegistry
[email protected]f48b9432011-01-11 07:25:402177// to make clear we're creating a key for our local map. Here and
2178// in FindCookiesForHostAndDomain() are the only two places where
2179// we need to conditionalize based on key type.
2180//
2181// Note that this key algorithm explicitly ignores the scheme. This is
2182// because when we're entering cookies into the map from the backing store,
2183// we in general won't have the scheme at that point.
2184// In practical terms, this means that file cookies will be stored
2185// in the map either by an empty string or by UNC name (and will be
2186// limited by kMaxCookiesPerHost), and extension cookies will be stored
2187// based on the single extension id, as the extension id won't have the
2188// form of a DNS host and hence GetKey() will return it unchanged.
2189//
2190// Arguably the right thing to do here is to make the key
2191// algorithm dependent on the scheme, and make sure that the scheme is
2192// available everywhere the key must be obtained (specfically at backing
2193// store load time). This would require either changing the backing store
2194// database schema to include the scheme (far more trouble than it's worth), or
2195// separating out file cookies into their own CookieMonster instance and
2196// thus restricting each scheme to a single cookie monster (which might
2197// be worth it, but is still too much trouble to solve what is currently a
2198// non-problem).
2199std::string CookieMonster::GetKey(const std::string& domain) const {
[email protected]f48b9432011-01-11 07:25:402200 std::string effective_domain(
[email protected]ed32c212013-05-14 20:49:292201 registry_controlled_domains::GetDomainAndRegistry(
[email protected]aabe1792014-01-30 21:37:462202 domain, registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES));
[email protected]f48b9432011-01-11 07:25:402203 if (effective_domain.empty())
2204 effective_domain = domain;
2205
2206 if (!effective_domain.empty() && effective_domain[0] == '.')
2207 return effective_domain.substr(1);
2208 return effective_domain;
2209}
2210
[email protected]97a3b6e2012-06-12 01:53:562211bool CookieMonster::IsCookieableScheme(const std::string& scheme) {
2212 base::AutoLock autolock(lock_);
2213
2214 return std::find(cookieable_schemes_.begin(), cookieable_schemes_.end(),
2215 scheme) != cookieable_schemes_.end();
2216}
2217
[email protected]f48b9432011-01-11 07:25:402218bool CookieMonster::HasCookieableScheme(const GURL& url) {
2219 lock_.AssertAcquired();
2220
2221 // Make sure the request is on a cookie-able url scheme.
2222 for (size_t i = 0; i < cookieable_schemes_.size(); ++i) {
2223 // We matched a scheme.
2224 if (url.SchemeIs(cookieable_schemes_[i].c_str())) {
2225 // We've matched a supported scheme.
initial.commit586acc5fe2008-07-26 22:42:522226 return true;
2227 }
2228 }
[email protected]f48b9432011-01-11 07:25:402229
2230 // The scheme didn't match any in our whitelist.
mkwstbe84af312015-02-20 08:52:452231 VLOG(kVlogPerCookieMonster)
2232 << "WARNING: Unsupported cookie scheme: " << url.scheme();
initial.commit586acc5fe2008-07-26 22:42:522233 return false;
2234}
2235
[email protected]c4058fb2010-06-22 17:25:262236// Test to see if stats should be recorded, and record them if so.
2237// The goal here is to get sampling for the average browser-hour of
2238// activity. We won't take samples when the web isn't being surfed,
2239// and when the web is being surfed, we'll take samples about every
2240// kRecordStatisticsIntervalSeconds.
2241// last_statistic_record_time_ is initialized to Now() rather than null
2242// in the constructor so that we won't take statistics right after
2243// startup, to avoid bias from browsers that are started but not used.
2244void CookieMonster::RecordPeriodicStats(const base::Time& current_time) {
2245 const base::TimeDelta kRecordStatisticsIntervalTime(
2246 base::TimeDelta::FromSeconds(kRecordStatisticsIntervalSeconds));
2247
[email protected]7a964a72010-09-07 19:33:262248 // If we've taken statistics recently, return.
2249 if (current_time - last_statistic_record_time_ <=
[email protected]c4058fb2010-06-22 17:25:262250 kRecordStatisticsIntervalTime) {
[email protected]7a964a72010-09-07 19:33:262251 return;
[email protected]c4058fb2010-06-22 17:25:262252 }
[email protected]7a964a72010-09-07 19:33:262253
2254 // See InitializeHistograms() for details.
2255 histogram_count_->Add(cookies_.size());
2256
2257 // More detailed statistics on cookie counts at different granularities.
2258 TimeTicks beginning_of_time(TimeTicks::Now());
2259
2260 for (CookieMap::const_iterator it_key = cookies_.begin();
mkwstbe84af312015-02-20 08:52:452261 it_key != cookies_.end();) {
[email protected]7a964a72010-09-07 19:33:262262 const std::string& key(it_key->first);
2263
2264 int key_count = 0;
2265 typedef std::map<std::string, unsigned int> DomainMap;
2266 DomainMap domain_map;
2267 CookieMapItPair its_cookies = cookies_.equal_range(key);
2268 while (its_cookies.first != its_cookies.second) {
2269 key_count++;
2270 const std::string& cookie_domain(its_cookies.first->second->Domain());
2271 domain_map[cookie_domain]++;
2272
2273 its_cookies.first++;
2274 }
2275 histogram_etldp1_count_->Add(key_count);
2276 histogram_domain_per_etldp1_count_->Add(domain_map.size());
2277 for (DomainMap::const_iterator domain_map_it = domain_map.begin();
2278 domain_map_it != domain_map.end(); domain_map_it++)
2279 histogram_domain_count_->Add(domain_map_it->second);
2280
2281 it_key = its_cookies.second;
2282 }
2283
mkwstbe84af312015-02-20 08:52:452284 VLOG(kVlogPeriodic) << "Time for recording cookie stats (us): "
2285 << (TimeTicks::Now() - beginning_of_time)
2286 .InMicroseconds();
[email protected]7a964a72010-09-07 19:33:262287
2288 last_statistic_record_time_ = current_time;
[email protected]c4058fb2010-06-22 17:25:262289}
2290
[email protected]f48b9432011-01-11 07:25:402291// Initialize all histogram counter variables used in this class.
2292//
2293// Normal histogram usage involves using the macros defined in
2294// histogram.h, which automatically takes care of declaring these
2295// variables (as statics), initializing them, and accumulating into
2296// them, all from a single entry point. Unfortunately, that solution
2297// doesn't work for the CookieMonster, as it's vulnerable to races between
2298// separate threads executing the same functions and hence initializing the
2299// same static variables. There isn't a race danger in the histogram
2300// accumulation calls; they are written to be resilient to simultaneous
2301// calls from multiple threads.
2302//
2303// The solution taken here is to have per-CookieMonster instance
2304// variables that are constructed during CookieMonster construction.
2305// Note that these variables refer to the same underlying histogram,
2306// so we still race (but safely) with other CookieMonster instances
2307// for accumulation.
2308//
2309// To do this we've expanded out the individual histogram macros calls,
2310// with declarations of the variables in the class decl, initialization here
2311// (done from the class constructor) and direct calls to the accumulation
2312// methods where needed. The specific histogram macro calls on which the
2313// initialization is based are included in comments below.
2314void CookieMonster::InitializeHistograms() {
2315 // From UMA_HISTOGRAM_CUSTOM_COUNTS
2316 histogram_expiration_duration_minutes_ = base::Histogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452317 "Cookie.ExpirationDurationMinutes", 1, kMinutesInTenYears, 50,
[email protected]f48b9432011-01-11 07:25:402318 base::Histogram::kUmaTargetedHistogramFlag);
2319 histogram_between_access_interval_minutes_ = base::Histogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452320 "Cookie.BetweenAccessIntervalMinutes", 1, kMinutesInTenYears, 50,
[email protected]f48b9432011-01-11 07:25:402321 base::Histogram::kUmaTargetedHistogramFlag);
2322 histogram_evicted_last_access_minutes_ = base::Histogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452323 "Cookie.EvictedLastAccessMinutes", 1, kMinutesInTenYears, 50,
[email protected]f48b9432011-01-11 07:25:402324 base::Histogram::kUmaTargetedHistogramFlag);
2325 histogram_count_ = base::Histogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452326 "Cookie.Count", 1, 4000, 50, base::Histogram::kUmaTargetedHistogramFlag);
2327 histogram_domain_count_ =
2328 base::Histogram::FactoryGet("Cookie.DomainCount", 1, 4000, 50,
2329 base::Histogram::kUmaTargetedHistogramFlag);
2330 histogram_etldp1_count_ =
2331 base::Histogram::FactoryGet("Cookie.Etldp1Count", 1, 4000, 50,
2332 base::Histogram::kUmaTargetedHistogramFlag);
2333 histogram_domain_per_etldp1_count_ =
2334 base::Histogram::FactoryGet("Cookie.DomainPerEtldp1Count", 1, 4000, 50,
2335 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]f48b9432011-01-11 07:25:402336
2337 // From UMA_HISTOGRAM_COUNTS_10000 & UMA_HISTOGRAM_CUSTOM_COUNTS
mkwstbe84af312015-02-20 08:52:452338 histogram_number_duplicate_db_cookies_ =
2339 base::Histogram::FactoryGet("Net.NumDuplicateCookiesInDb", 1, 10000, 50,
2340 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]f48b9432011-01-11 07:25:402341
2342 // From UMA_HISTOGRAM_ENUMERATION
2343 histogram_cookie_deletion_cause_ = base::LinearHistogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452344 "Cookie.DeletionCause", 1, DELETE_COOKIE_LAST_ENTRY - 1,
2345 DELETE_COOKIE_LAST_ENTRY, base::Histogram::kUmaTargetedHistogramFlag);
mkwstc1aa4cc2015-04-03 19:57:452346 histogram_cookie_type_ = base::LinearHistogram::FactoryGet(
mkwst87378d92015-04-10 21:22:112347 "Cookie.Type", 1, (1 << COOKIE_TYPE_LAST_ENTRY) - 1,
2348 1 << COOKIE_TYPE_LAST_ENTRY, base::Histogram::kUmaTargetedHistogramFlag);
[email protected]f48b9432011-01-11 07:25:402349
2350 // From UMA_HISTOGRAM_{CUSTOM_,}TIMES
[email protected]c7593fb22011-11-14 23:54:272351 histogram_time_blocked_on_load_ = base::Histogram::FactoryTimeGet(
mkwstbe84af312015-02-20 08:52:452352 "Cookie.TimeBlockedOnLoad", base::TimeDelta::FromMilliseconds(1),
2353 base::TimeDelta::FromMinutes(1), 50,
2354 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]f48b9432011-01-11 07:25:402355}
2356
[email protected]f48b9432011-01-11 07:25:402357// The system resolution is not high enough, so we can have multiple
2358// set cookies that result in the same system time. When this happens, we
2359// increment by one Time unit. Let's hope computers don't get too fast.
2360Time CookieMonster::CurrentTime() {
mkwstbe84af312015-02-20 08:52:452361 return std::max(Time::Now(), Time::FromInternalValue(
2362 last_time_seen_.ToInternalValue() + 1));
[email protected]f48b9432011-01-11 07:25:402363}
2364
drogerd5d1278c2015-03-17 19:21:512365void CookieMonster::ComputeCookieDiff(CookieList* old_cookies,
2366 CookieList* new_cookies,
2367 CookieList* cookies_to_add,
2368 CookieList* cookies_to_delete) {
2369 DCHECK(old_cookies);
2370 DCHECK(new_cookies);
2371 DCHECK(cookies_to_add);
2372 DCHECK(cookies_to_delete);
2373 DCHECK(cookies_to_add->empty());
2374 DCHECK(cookies_to_delete->empty());
2375
2376 // Sort both lists.
2377 // A set ordered by FullDiffCookieSorter is also ordered by
2378 // PartialDiffCookieSorter.
2379 std::sort(old_cookies->begin(), old_cookies->end(), FullDiffCookieSorter);
2380 std::sort(new_cookies->begin(), new_cookies->end(), FullDiffCookieSorter);
2381
2382 // Select any old cookie for deletion if no new cookie has the same name,
2383 // domain, and path.
2384 std::set_difference(
2385 old_cookies->begin(), old_cookies->end(), new_cookies->begin(),
2386 new_cookies->end(),
2387 std::inserter(*cookies_to_delete, cookies_to_delete->begin()),
2388 PartialDiffCookieSorter);
2389
2390 // Select any new cookie for addition (or update) if no old cookie is exactly
2391 // equivalent.
2392 std::set_difference(new_cookies->begin(), new_cookies->end(),
2393 old_cookies->begin(), old_cookies->end(),
2394 std::inserter(*cookies_to_add, cookies_to_add->begin()),
2395 FullDiffCookieSorter);
2396}
2397
ellyjones399e35a22014-10-27 11:09:562398scoped_ptr<CookieStore::CookieChangedSubscription>
mkwstbe84af312015-02-20 08:52:452399CookieMonster::AddCallbackForCookie(const GURL& gurl,
2400 const std::string& name,
2401 const CookieChangedCallback& callback) {
ellyjones399e35a22014-10-27 11:09:562402 base::AutoLock autolock(lock_);
2403 std::pair<GURL, std::string> key(gurl, name);
2404 if (hook_map_.count(key) == 0)
2405 hook_map_[key] = make_linked_ptr(new CookieChangedCallbackList());
msarda0aad8f02014-10-30 09:22:392406 return hook_map_[key]->Add(
anujk.sharmaafc45172015-05-15 00:50:342407 base::Bind(&RunAsync, base::ThreadTaskRunnerHandle::Get(), callback));
ellyjones399e35a22014-10-27 11:09:562408}
2409
mkwstb73bf8aa2015-03-31 07:33:452410#if defined(OS_ANDROID)
2411void CookieMonster::SetEnableFileScheme(bool accept) {
2412 // This assumes "file" is always at the end of the array. See the comment
2413 // above kDefaultCookieableSchemes.
2414 //
2415 // TODO(mkwst): We're keeping this method around to support the
2416 // 'CookieManager::setAcceptFileSchemeCookies' method on Android's WebView;
2417 // if/when we can deprecate and remove that method, we can remove this one
2418 // as well. Until then, we'll just ensure that the method has no effect on
2419 // non-android systems.
2420 int num_schemes = accept ? kDefaultCookieableSchemesCount
2421 : kDefaultCookieableSchemesCount - 1;
2422
2423 SetCookieableSchemes(kDefaultCookieableSchemes, num_schemes);
2424}
2425#endif
2426
msarda0aad8f02014-10-30 09:22:392427void CookieMonster::RunCallbacks(const CanonicalCookie& cookie, bool removed) {
ellyjones399e35a22014-10-27 11:09:562428 lock_.AssertAcquired();
2429 CookieOptions opts;
2430 opts.set_include_httponly();
mkwstae819bb2015-02-23 05:10:312431 opts.set_include_first_party_only();
ellyjones399e35a22014-10-27 11:09:562432 // Note that the callbacks in hook_map_ are wrapped with MakeAsync(), so they
2433 // are guaranteed to not take long - they just post a RunAsync task back to
2434 // the appropriate thread's message loop and return. It is important that this
2435 // method not run user-supplied callbacks directly, since the CookieMonster
2436 // lock is held and it is easy to accidentally introduce deadlocks.
2437 for (CookieChangedHookMap::iterator it = hook_map_.begin();
2438 it != hook_map_.end(); ++it) {
2439 std::pair<GURL, std::string> key = it->first;
2440 if (cookie.IncludeForRequestURL(key.first, opts) &&
2441 cookie.Name() == key.second) {
msarda0aad8f02014-10-30 09:22:392442 it->second->Notify(cookie, removed);
ellyjones399e35a22014-10-27 11:09:562443 }
2444 }
2445}
2446
[email protected]63725312012-07-19 08:24:162447} // namespace net