blob: 0f8ba79d515d61fb15958769013eedc3dbaa4623 [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"
skyostil4891b25b2015-06-11 11:43:4554#include "base/location.h"
initial.commit586acc5fe2008-07-26 22:42:5255#include "base/logging.h"
[email protected]3b63f8f42011-03-28 01:54:1556#include "base/memory/scoped_ptr.h"
erikchen1dd72a72015-05-06 20:45:0557#include "base/metrics/field_trial.h"
[email protected]835d7c82010-10-14 04:38:3858#include "base/metrics/histogram.h"
pkastingb60049a2015-02-07 03:25:2559#include "base/profiler/scoped_tracker.h"
anujk.sharmaafc45172015-05-15 00:50:3460#include "base/single_thread_task_runner.h"
[email protected]4b355212013-06-11 10:35:1961#include "base/strings/string_util.h"
62#include "base/strings/stringprintf.h"
anujk.sharmaafc45172015-05-15 00:50:3463#include "base/thread_task_runner_handle.h"
[email protected]be28b5f42012-07-20 11:31:2564#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
[email protected]4b355212013-06-11 10:35:1965#include "net/cookies/canonical_cookie.h"
[email protected]63ee33bd2012-03-15 09:29:5866#include "net/cookies/cookie_util.h"
[email protected]ebfe3172012-07-12 12:21:4167#include "net/cookies/parsed_cookie.h"
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;
[email protected]4d3ce782010-10-29 18:31:28149const int kVlogGarbageCollection = 5;
150const int kVlogSetCookies = 7;
151const int kVlogGetCookies = 9;
152
[email protected]f48b9432011-01-11 07:25:40153// Mozilla sorts on the path length (longest first), and then it
154// sorts by creation time (oldest first).
155// The RFC says the sort order for the domain attribute is undefined.
[email protected]5b9bc352012-07-18 13:13:34156bool CookieSorter(CanonicalCookie* cc1, CanonicalCookie* cc2) {
[email protected]f48b9432011-01-11 07:25:40157 if (cc1->Path().length() == cc2->Path().length())
158 return cc1->CreationDate() < cc2->CreationDate();
159 return cc1->Path().length() > cc2->Path().length();
initial.commit586acc5fe2008-07-26 22:42:52160}
161
[email protected]8ad5d462013-05-02 08:45:26162bool LRACookieSorter(const CookieMonster::CookieMap::iterator& it1,
[email protected]f48b9432011-01-11 07:25:40163 const CookieMonster::CookieMap::iterator& it2) {
164 // Cookies accessed less recently should be deleted first.
165 if (it1->second->LastAccessDate() != it2->second->LastAccessDate())
166 return it1->second->LastAccessDate() < it2->second->LastAccessDate();
initial.commit586acc5fe2008-07-26 22:42:52167
[email protected]f48b9432011-01-11 07:25:40168 // In rare cases we might have two cookies with identical last access times.
169 // To preserve the stability of the sort, in these cases prefer to delete
170 // older cookies over newer ones. CreationDate() is guaranteed to be unique.
171 return it1->second->CreationDate() < it2->second->CreationDate();
[email protected]297a4ed02010-02-12 08:12:52172}
173
drogerd5d1278c2015-03-17 19:21:51174// Compare cookies using name, domain and path, so that "equivalent" cookies
175// (per RFC 2965) are equal to each other.
ttuttle859dc7a2015-04-23 19:42:29176bool PartialDiffCookieSorter(const CanonicalCookie& a,
177 const CanonicalCookie& b) {
drogerd5d1278c2015-03-17 19:21:51178 return a.PartialCompare(b);
179}
180
181// This is a stricter ordering than PartialDiffCookieOrdering, where all fields
182// are used.
ttuttle859dc7a2015-04-23 19:42:29183bool FullDiffCookieSorter(const CanonicalCookie& a, const CanonicalCookie& b) {
drogerd5d1278c2015-03-17 19:21:51184 return a.FullCompare(b);
185}
186
[email protected]297a4ed02010-02-12 08:12:52187// Our strategy to find duplicates is:
188// (1) Build a map from (cookiename, cookiepath) to
189// {list of cookies with this signature, sorted by creation time}.
190// (2) For each list with more than 1 entry, keep the cookie having the
191// most recent creation time, and delete the others.
[email protected]f48b9432011-01-11 07:25:40192//
[email protected]1655ba342010-07-14 18:17:42193// Two cookies are considered equivalent if they have the same domain,
194// name, and path.
195struct CookieSignature {
196 public:
[email protected]dedec0b2013-02-28 04:50:10197 CookieSignature(const std::string& name,
198 const std::string& domain,
[email protected]1655ba342010-07-14 18:17:42199 const std::string& path)
mkwstbe84af312015-02-20 08:52:45200 : name(name), domain(domain), path(path) {}
[email protected]1655ba342010-07-14 18:17:42201
202 // To be a key for a map this class needs to be assignable, copyable,
203 // and have an operator<. The default assignment operator
204 // and copy constructor are exactly what we want.
205
206 bool operator<(const CookieSignature& cs) const {
207 // Name compare dominates, then domain, then path.
208 int diff = name.compare(cs.name);
209 if (diff != 0)
210 return diff < 0;
211
212 diff = domain.compare(cs.domain);
213 if (diff != 0)
214 return diff < 0;
215
216 return path.compare(cs.path) < 0;
217 }
218
219 std::string name;
220 std::string domain;
221 std::string path;
222};
[email protected]f48b9432011-01-11 07:25:40223
[email protected]8ad5d462013-05-02 08:45:26224// For a CookieItVector iterator range [|it_begin|, |it_end|),
225// sorts the first |num_sort| + 1 elements by LastAccessDate().
226// The + 1 element exists so for any interval of length <= |num_sort| starting
227// from |cookies_its_begin|, a LastAccessDate() bound can be found.
mkwstbe84af312015-02-20 08:52:45228void SortLeastRecentlyAccessed(CookieMonster::CookieItVector::iterator it_begin,
229 CookieMonster::CookieItVector::iterator it_end,
230 size_t num_sort) {
[email protected]8ad5d462013-05-02 08:45:26231 DCHECK_LT(static_cast<int>(num_sort), it_end - it_begin);
232 std::partial_sort(it_begin, it_begin + num_sort + 1, it_end, LRACookieSorter);
233}
[email protected]f48b9432011-01-11 07:25:40234
[email protected]8ad5d462013-05-02 08:45:26235// Predicate to support PartitionCookieByPriority().
236struct CookiePriorityEqualsTo
237 : std::unary_function<const CookieMonster::CookieMap::iterator, bool> {
[email protected]5edff3c52014-06-23 20:27:48238 explicit CookiePriorityEqualsTo(CookiePriority priority)
mkwstbe84af312015-02-20 08:52:45239 : priority_(priority) {}
[email protected]8ad5d462013-05-02 08:45:26240
241 bool operator()(const CookieMonster::CookieMap::iterator it) const {
242 return it->second->Priority() == priority_;
[email protected]f48b9432011-01-11 07:25:40243 }
[email protected]8ad5d462013-05-02 08:45:26244
245 const CookiePriority priority_;
246};
247
248// For a CookieItVector iterator range [|it_begin|, |it_end|),
249// moves all cookies with a given |priority| to the beginning of the list.
250// Returns: An iterator in [it_begin, it_end) to the first element with
251// priority != |priority|, or |it_end| if all have priority == |priority|.
252CookieMonster::CookieItVector::iterator PartitionCookieByPriority(
253 CookieMonster::CookieItVector::iterator it_begin,
254 CookieMonster::CookieItVector::iterator it_end,
255 CookiePriority priority) {
256 return std::partition(it_begin, it_end, CookiePriorityEqualsTo(priority));
257}
258
mkwstbe84af312015-02-20 08:52:45259bool LowerBoundAccessDateComparator(const CookieMonster::CookieMap::iterator it,
260 const Time& access_date) {
[email protected]8ad5d462013-05-02 08:45:26261 return it->second->LastAccessDate() < access_date;
262}
263
264// For a CookieItVector iterator range [|it_begin|, |it_end|)
265// from a CookieItVector sorted by LastAccessDate(), returns the
266// first iterator with access date >= |access_date|, or cookie_its_end if this
267// holds for all.
268CookieMonster::CookieItVector::iterator LowerBoundAccessDate(
269 const CookieMonster::CookieItVector::iterator its_begin,
270 const CookieMonster::CookieItVector::iterator its_end,
271 const Time& access_date) {
272 return std::lower_bound(its_begin, its_end, access_date,
273 LowerBoundAccessDateComparator);
[email protected]7a964a72010-09-07 19:33:26274}
275
[email protected]7c4b66b2014-01-04 12:28:13276// Mapping between DeletionCause and CookieMonsterDelegate::ChangeCause; the
277// mapping also provides a boolean that specifies whether or not an
278// OnCookieChanged notification ought to be generated.
[email protected]8bb846f2011-03-23 12:08:18279typedef struct ChangeCausePair_struct {
[email protected]7c4b66b2014-01-04 12:28:13280 CookieMonsterDelegate::ChangeCause cause;
[email protected]8bb846f2011-03-23 12:08:18281 bool notify;
282} ChangeCausePair;
283ChangeCausePair ChangeCauseMapping[] = {
mkwstbe84af312015-02-20 08:52:45284 // DELETE_COOKIE_EXPLICIT
285 {CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT, true},
286 // DELETE_COOKIE_OVERWRITE
287 {CookieMonsterDelegate::CHANGE_COOKIE_OVERWRITE, true},
288 // DELETE_COOKIE_EXPIRED
289 {CookieMonsterDelegate::CHANGE_COOKIE_EXPIRED, true},
290 // DELETE_COOKIE_EVICTED
291 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
292 // DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE
293 {CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT, false},
294 // DELETE_COOKIE_DONT_RECORD
295 {CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT, false},
296 // DELETE_COOKIE_EVICTED_DOMAIN
297 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
298 // DELETE_COOKIE_EVICTED_GLOBAL
299 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
300 // DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE
301 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
302 // DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE
303 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
304 // DELETE_COOKIE_EXPIRED_OVERWRITE
305 {CookieMonsterDelegate::CHANGE_COOKIE_EXPIRED_OVERWRITE, true},
306 // DELETE_COOKIE_CONTROL_CHAR
307 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
308 // DELETE_COOKIE_LAST_ENTRY
309 {CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT, false}};
[email protected]8bb846f2011-03-23 12:08:18310
[email protected]34a160d2011-05-12 22:12:49311std::string BuildCookieLine(const CanonicalCookieVector& cookies) {
312 std::string cookie_line;
313 for (CanonicalCookieVector::const_iterator it = cookies.begin();
314 it != cookies.end(); ++it) {
315 if (it != cookies.begin())
316 cookie_line += "; ";
317 // In Mozilla if you set a cookie like AAAA, it will have an empty token
318 // and a value of AAAA. When it sends the cookie back, it will send AAAA,
319 // so we need to avoid sending =AAAA for a blank token value.
320 if (!(*it)->Name().empty())
321 cookie_line += (*it)->Name() + "=";
322 cookie_line += (*it)->Value();
323 }
324 return cookie_line;
325}
326
ellyjones399e35a22014-10-27 11:09:56327void RunAsync(scoped_refptr<base::TaskRunner> proxy,
msarda0aad8f02014-10-30 09:22:39328 const CookieStore::CookieChangedCallback& callback,
329 const CanonicalCookie& cookie,
330 bool removed) {
331 proxy->PostTask(FROM_HERE, base::Bind(callback, cookie, removed));
ellyjones399e35a22014-10-27 11:09:56332}
333
estarkcd39c11f2015-10-19 19:46:36334bool CheckCookiePrefix(CanonicalCookie* cc, const CookieOptions& options) {
335 const char kSecurePrefix[] = "$Secure-";
336 if (cc->Name().find(kSecurePrefix) == 0)
337 return cc->IsSecure() && cc->Source().SchemeIsCryptographic();
338 return true;
339}
340
[email protected]f48b9432011-01-11 07:25:40341} // namespace
342
[email protected]7c4b66b2014-01-04 12:28:13343CookieMonster::CookieMonster(PersistentCookieStore* store,
344 CookieMonsterDelegate* delegate)
[email protected]f48b9432011-01-11 07:25:40345 : initialized_(false),
erikchen1dd72a72015-05-06 20:45:05346 started_fetching_all_cookies_(false),
347 finished_fetching_all_cookies_(false),
348 fetch_strategy_(kUnknownFetch),
[email protected]f48b9432011-01-11 07:25:40349 store_(store),
350 last_access_threshold_(
351 TimeDelta::FromSeconds(kDefaultAccessUpdateThresholdSeconds)),
352 delegate_(delegate),
[email protected]82388662011-03-10 21:04:06353 last_statistic_record_time_(Time::Now()),
[email protected]93c53a32011-12-05 10:40:35354 keep_expired_cookies_(false),
[email protected]8976e292013-11-02 13:38:57355 persist_session_cookies_(false) {
[email protected]f48b9432011-01-11 07:25:40356 InitializeHistograms();
357 SetDefaultCookieableSchemes();
[email protected]2d0f89a2010-12-06 12:02:23358}
359
[email protected]f48b9432011-01-11 07:25:40360CookieMonster::CookieMonster(PersistentCookieStore* store,
[email protected]7c4b66b2014-01-04 12:28:13361 CookieMonsterDelegate* delegate,
[email protected]f48b9432011-01-11 07:25:40362 int last_access_threshold_milliseconds)
363 : initialized_(false),
erikchen1dd72a72015-05-06 20:45:05364 started_fetching_all_cookies_(false),
365 finished_fetching_all_cookies_(false),
366 fetch_strategy_(kUnknownFetch),
[email protected]f48b9432011-01-11 07:25:40367 store_(store),
368 last_access_threshold_(base::TimeDelta::FromMilliseconds(
369 last_access_threshold_milliseconds)),
370 delegate_(delegate),
[email protected]82388662011-03-10 21:04:06371 last_statistic_record_time_(base::Time::Now()),
[email protected]93c53a32011-12-05 10:40:35372 keep_expired_cookies_(false),
[email protected]8976e292013-11-02 13:38:57373 persist_session_cookies_(false) {
[email protected]f48b9432011-01-11 07:25:40374 InitializeHistograms();
375 SetDefaultCookieableSchemes();
initial.commit586acc5fe2008-07-26 22:42:52376}
377
[email protected]218aa6a12011-09-13 17:38:38378// Task classes for queueing the coming request.
379
380class CookieMonster::CookieMonsterTask
381 : public base::RefCountedThreadSafe<CookieMonsterTask> {
382 public:
383 // Runs the task and invokes the client callback on the thread that
384 // originally constructed the task.
385 virtual void Run() = 0;
386
387 protected:
388 explicit CookieMonsterTask(CookieMonster* cookie_monster);
389 virtual ~CookieMonsterTask();
390
391 // Invokes the callback immediately, if the current thread is the one
392 // that originated the task, or queues the callback for execution on the
393 // appropriate thread. Maintains a reference to this CookieMonsterTask
394 // instance until the callback completes.
395 void InvokeCallback(base::Closure callback);
396
mkwstbe84af312015-02-20 08:52:45397 CookieMonster* cookie_monster() { return cookie_monster_; }
[email protected]218aa6a12011-09-13 17:38:38398
[email protected]a9813302012-04-28 09:29:28399 private:
[email protected]218aa6a12011-09-13 17:38:38400 friend class base::RefCountedThreadSafe<CookieMonsterTask>;
401
[email protected]218aa6a12011-09-13 17:38:38402 CookieMonster* cookie_monster_;
anujk.sharmaafc45172015-05-15 00:50:34403 scoped_refptr<base::SingleThreadTaskRunner> thread_;
[email protected]218aa6a12011-09-13 17:38:38404
405 DISALLOW_COPY_AND_ASSIGN(CookieMonsterTask);
406};
407
408CookieMonster::CookieMonsterTask::CookieMonsterTask(
409 CookieMonster* cookie_monster)
410 : cookie_monster_(cookie_monster),
anujk.sharmaafc45172015-05-15 00:50:34411 thread_(base::ThreadTaskRunnerHandle::Get()) {
[email protected]a9813302012-04-28 09:29:28412}
[email protected]218aa6a12011-09-13 17:38:38413
mkwstbe84af312015-02-20 08:52:45414CookieMonster::CookieMonsterTask::~CookieMonsterTask() {
415}
[email protected]218aa6a12011-09-13 17:38:38416
417// Unfortunately, one cannot re-bind a Callback with parameters into a closure.
418// Therefore, the closure passed to InvokeCallback is a clumsy binding of
419// Callback::Run on a wrapped Callback instance. Since Callback is not
420// reference counted, we bind to an instance that is a member of the
421// CookieMonsterTask subclass. Then, we cannot simply post the callback to a
422// message loop because the underlying instance may be destroyed (along with the
423// CookieMonsterTask instance) in the interim. Therefore, we post a callback
424// bound to the CookieMonsterTask, which *is* reference counted (thus preventing
425// destruction of the original callback), and which invokes the closure (which
426// invokes the original callback with the returned data).
427void CookieMonster::CookieMonsterTask::InvokeCallback(base::Closure callback) {
428 if (thread_->BelongsToCurrentThread()) {
429 callback.Run();
430 } else {
mkwstbe84af312015-02-20 08:52:45431 thread_->PostTask(FROM_HERE, base::Bind(&CookieMonsterTask::InvokeCallback,
432 this, callback));
[email protected]218aa6a12011-09-13 17:38:38433 }
434}
435
436// Task class for SetCookieWithDetails call.
[email protected]5fa4f9a2013-10-03 10:13:16437class CookieMonster::SetCookieWithDetailsTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38438 public:
[email protected]dedec0b2013-02-28 04:50:10439 SetCookieWithDetailsTask(CookieMonster* cookie_monster,
440 const GURL& url,
441 const std::string& name,
442 const std::string& value,
443 const std::string& domain,
444 const std::string& path,
445 const base::Time& expiration_time,
446 bool secure,
447 bool http_only,
mkwstae819bb2015-02-23 05:10:31448 bool first_party_only,
estarkcd39c11f2015-10-19 19:46:36449 bool enforce_prefixes,
[email protected]ab2d75c82013-04-19 18:39:04450 CookiePriority priority,
[email protected]5fa4f9a2013-10-03 10:13:16451 const SetCookiesCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38452 : CookieMonsterTask(cookie_monster),
453 url_(url),
454 name_(name),
455 value_(value),
456 domain_(domain),
457 path_(path),
458 expiration_time_(expiration_time),
459 secure_(secure),
460 http_only_(http_only),
mkwstae819bb2015-02-23 05:10:31461 first_party_only_(first_party_only),
estarkcd39c11f2015-10-19 19:46:36462 enforce_prefixes_(enforce_prefixes),
[email protected]ab2d75c82013-04-19 18:39:04463 priority_(priority),
mkwstbe84af312015-02-20 08:52:45464 callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38465
[email protected]5fa4f9a2013-10-03 10:13:16466 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20467 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38468
[email protected]a9813302012-04-28 09:29:28469 protected:
dchengb03027d2014-10-21 12:00:20470 ~SetCookieWithDetailsTask() override {}
[email protected]a9813302012-04-28 09:29:28471
[email protected]218aa6a12011-09-13 17:38:38472 private:
473 GURL url_;
474 std::string name_;
475 std::string value_;
476 std::string domain_;
477 std::string path_;
478 base::Time expiration_time_;
479 bool secure_;
480 bool http_only_;
mkwstae819bb2015-02-23 05:10:31481 bool first_party_only_;
estarkcd39c11f2015-10-19 19:46:36482 bool enforce_prefixes_;
[email protected]ab2d75c82013-04-19 18:39:04483 CookiePriority priority_;
[email protected]5fa4f9a2013-10-03 10:13:16484 SetCookiesCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38485
486 DISALLOW_COPY_AND_ASSIGN(SetCookieWithDetailsTask);
487};
488
489void CookieMonster::SetCookieWithDetailsTask::Run() {
mkwstbe84af312015-02-20 08:52:45490 bool success = this->cookie_monster()->SetCookieWithDetails(
491 url_, name_, value_, domain_, path_, expiration_time_, secure_,
estarkcd39c11f2015-10-19 19:46:36492 http_only_, first_party_only_, enforce_prefixes_, priority_);
[email protected]218aa6a12011-09-13 17:38:38493 if (!callback_.is_null()) {
[email protected]5fa4f9a2013-10-03 10:13:16494 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38495 base::Unretained(&callback_), success));
496 }
497}
498
499// Task class for GetAllCookies call.
[email protected]5fa4f9a2013-10-03 10:13:16500class CookieMonster::GetAllCookiesTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38501 public:
502 GetAllCookiesTask(CookieMonster* cookie_monster,
[email protected]5fa4f9a2013-10-03 10:13:16503 const GetCookieListCallback& callback)
mkwstbe84af312015-02-20 08:52:45504 : CookieMonsterTask(cookie_monster), callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38505
[email protected]5fa4f9a2013-10-03 10:13:16506 // CookieMonsterTask
dchengb03027d2014-10-21 12:00:20507 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38508
[email protected]a9813302012-04-28 09:29:28509 protected:
dchengb03027d2014-10-21 12:00:20510 ~GetAllCookiesTask() override {}
[email protected]a9813302012-04-28 09:29:28511
[email protected]218aa6a12011-09-13 17:38:38512 private:
[email protected]5fa4f9a2013-10-03 10:13:16513 GetCookieListCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38514
515 DISALLOW_COPY_AND_ASSIGN(GetAllCookiesTask);
516};
517
518void CookieMonster::GetAllCookiesTask::Run() {
519 if (!callback_.is_null()) {
520 CookieList cookies = this->cookie_monster()->GetAllCookies();
[email protected]5fa4f9a2013-10-03 10:13:16521 this->InvokeCallback(base::Bind(&GetCookieListCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38522 base::Unretained(&callback_), cookies));
mkwstbe84af312015-02-20 08:52:45523 }
[email protected]218aa6a12011-09-13 17:38:38524}
525
526// Task class for GetAllCookiesForURLWithOptions call.
527class CookieMonster::GetAllCookiesForURLWithOptionsTask
[email protected]5fa4f9a2013-10-03 10:13:16528 : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38529 public:
mkwstbe84af312015-02-20 08:52:45530 GetAllCookiesForURLWithOptionsTask(CookieMonster* cookie_monster,
531 const GURL& url,
532 const CookieOptions& options,
533 const GetCookieListCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38534 : CookieMonsterTask(cookie_monster),
535 url_(url),
536 options_(options),
mkwstbe84af312015-02-20 08:52:45537 callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38538
[email protected]5fa4f9a2013-10-03 10:13:16539 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20540 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38541
[email protected]a9813302012-04-28 09:29:28542 protected:
dchengb03027d2014-10-21 12:00:20543 ~GetAllCookiesForURLWithOptionsTask() override {}
[email protected]a9813302012-04-28 09:29:28544
[email protected]218aa6a12011-09-13 17:38:38545 private:
546 GURL url_;
547 CookieOptions options_;
[email protected]5fa4f9a2013-10-03 10:13:16548 GetCookieListCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38549
550 DISALLOW_COPY_AND_ASSIGN(GetAllCookiesForURLWithOptionsTask);
551};
552
553void CookieMonster::GetAllCookiesForURLWithOptionsTask::Run() {
554 if (!callback_.is_null()) {
mkwstbe84af312015-02-20 08:52:45555 CookieList cookies =
556 this->cookie_monster()->GetAllCookiesForURLWithOptions(url_, options_);
[email protected]5fa4f9a2013-10-03 10:13:16557 this->InvokeCallback(base::Bind(&GetCookieListCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38558 base::Unretained(&callback_), cookies));
559 }
560}
561
mkwstbe84af312015-02-20 08:52:45562template <typename Result>
563struct CallbackType {
[email protected]5fa4f9a2013-10-03 10:13:16564 typedef base::Callback<void(Result)> Type;
565};
566
mkwstbe84af312015-02-20 08:52:45567template <>
568struct CallbackType<void> {
[email protected]5fa4f9a2013-10-03 10:13:16569 typedef base::Closure Type;
570};
571
572// Base task class for Delete*Task.
573template <typename Result>
574class CookieMonster::DeleteTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38575 public:
[email protected]5fa4f9a2013-10-03 10:13:16576 DeleteTask(CookieMonster* cookie_monster,
577 const typename CallbackType<Result>::Type& callback)
mkwstbe84af312015-02-20 08:52:45578 : CookieMonsterTask(cookie_monster), callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38579
[email protected]5fa4f9a2013-10-03 10:13:16580 // CookieMonsterTask:
nickd3f30d022015-04-23 10:18:37581 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38582
dmichaeld6e570d2014-12-18 22:30:57583 protected:
584 ~DeleteTask() override;
585
[email protected]5fa4f9a2013-10-03 10:13:16586 private:
587 // Runs the delete task and returns a result.
588 virtual Result RunDeleteTask() = 0;
589 base::Closure RunDeleteTaskAndBindCallback();
590 void FlushDone(const base::Closure& callback);
591
592 typename CallbackType<Result>::Type callback_;
593
594 DISALLOW_COPY_AND_ASSIGN(DeleteTask);
595};
596
597template <typename Result>
dmichaeld6e570d2014-12-18 22:30:57598CookieMonster::DeleteTask<Result>::~DeleteTask() {
599}
600
601template <typename Result>
602base::Closure
603CookieMonster::DeleteTask<Result>::RunDeleteTaskAndBindCallback() {
[email protected]5fa4f9a2013-10-03 10:13:16604 Result result = RunDeleteTask();
605 if (callback_.is_null())
606 return base::Closure();
607 return base::Bind(callback_, result);
608}
609
610template <>
611base::Closure CookieMonster::DeleteTask<void>::RunDeleteTaskAndBindCallback() {
612 RunDeleteTask();
613 return callback_;
614}
615
616template <typename Result>
617void CookieMonster::DeleteTask<Result>::Run() {
mkwstbe84af312015-02-20 08:52:45618 this->cookie_monster()->FlushStore(base::Bind(
619 &DeleteTask<Result>::FlushDone, this, RunDeleteTaskAndBindCallback()));
[email protected]5fa4f9a2013-10-03 10:13:16620}
621
622template <typename Result>
623void CookieMonster::DeleteTask<Result>::FlushDone(
624 const base::Closure& callback) {
625 if (!callback.is_null()) {
626 this->InvokeCallback(callback);
627 }
628}
629
630// Task class for DeleteAll call.
631class CookieMonster::DeleteAllTask : public DeleteTask<int> {
632 public:
mkwstbe84af312015-02-20 08:52:45633 DeleteAllTask(CookieMonster* cookie_monster, const DeleteCallback& callback)
634 : DeleteTask<int>(cookie_monster, callback) {}
[email protected]5fa4f9a2013-10-03 10:13:16635
636 // DeleteTask:
dchengb03027d2014-10-21 12:00:20637 int RunDeleteTask() override;
[email protected]5fa4f9a2013-10-03 10:13:16638
[email protected]a9813302012-04-28 09:29:28639 protected:
dchengb03027d2014-10-21 12:00:20640 ~DeleteAllTask() override {}
[email protected]a9813302012-04-28 09:29:28641
[email protected]218aa6a12011-09-13 17:38:38642 private:
[email protected]218aa6a12011-09-13 17:38:38643 DISALLOW_COPY_AND_ASSIGN(DeleteAllTask);
644};
645
[email protected]5fa4f9a2013-10-03 10:13:16646int CookieMonster::DeleteAllTask::RunDeleteTask() {
647 return this->cookie_monster()->DeleteAll(true);
[email protected]218aa6a12011-09-13 17:38:38648}
649
650// Task class for DeleteAllCreatedBetween call.
[email protected]5fa4f9a2013-10-03 10:13:16651class CookieMonster::DeleteAllCreatedBetweenTask : public DeleteTask<int> {
[email protected]218aa6a12011-09-13 17:38:38652 public:
[email protected]dedec0b2013-02-28 04:50:10653 DeleteAllCreatedBetweenTask(CookieMonster* cookie_monster,
654 const Time& delete_begin,
655 const Time& delete_end,
[email protected]5fa4f9a2013-10-03 10:13:16656 const DeleteCallback& callback)
[email protected]151132f2013-11-18 21:37:00657 : DeleteTask<int>(cookie_monster, callback),
[email protected]218aa6a12011-09-13 17:38:38658 delete_begin_(delete_begin),
mkwstbe84af312015-02-20 08:52:45659 delete_end_(delete_end) {}
[email protected]218aa6a12011-09-13 17:38:38660
[email protected]5fa4f9a2013-10-03 10:13:16661 // DeleteTask:
dchengb03027d2014-10-21 12:00:20662 int RunDeleteTask() override;
[email protected]218aa6a12011-09-13 17:38:38663
[email protected]a9813302012-04-28 09:29:28664 protected:
dchengb03027d2014-10-21 12:00:20665 ~DeleteAllCreatedBetweenTask() override {}
[email protected]a9813302012-04-28 09:29:28666
[email protected]218aa6a12011-09-13 17:38:38667 private:
668 Time delete_begin_;
669 Time delete_end_;
[email protected]218aa6a12011-09-13 17:38:38670
671 DISALLOW_COPY_AND_ASSIGN(DeleteAllCreatedBetweenTask);
672};
673
[email protected]5fa4f9a2013-10-03 10:13:16674int CookieMonster::DeleteAllCreatedBetweenTask::RunDeleteTask() {
mkwstbe84af312015-02-20 08:52:45675 return this->cookie_monster()->DeleteAllCreatedBetween(delete_begin_,
676 delete_end_);
[email protected]218aa6a12011-09-13 17:38:38677}
678
679// Task class for DeleteAllForHost call.
[email protected]5fa4f9a2013-10-03 10:13:16680class CookieMonster::DeleteAllForHostTask : public DeleteTask<int> {
[email protected]218aa6a12011-09-13 17:38:38681 public:
682 DeleteAllForHostTask(CookieMonster* cookie_monster,
683 const GURL& url,
[email protected]5fa4f9a2013-10-03 10:13:16684 const DeleteCallback& callback)
mkwstbe84af312015-02-20 08:52:45685 : DeleteTask<int>(cookie_monster, callback), url_(url) {}
[email protected]218aa6a12011-09-13 17:38:38686
[email protected]5fa4f9a2013-10-03 10:13:16687 // DeleteTask:
dchengb03027d2014-10-21 12:00:20688 int RunDeleteTask() override;
[email protected]218aa6a12011-09-13 17:38:38689
[email protected]a9813302012-04-28 09:29:28690 protected:
dchengb03027d2014-10-21 12:00:20691 ~DeleteAllForHostTask() override {}
[email protected]a9813302012-04-28 09:29:28692
[email protected]218aa6a12011-09-13 17:38:38693 private:
694 GURL url_;
[email protected]218aa6a12011-09-13 17:38:38695
696 DISALLOW_COPY_AND_ASSIGN(DeleteAllForHostTask);
697};
698
[email protected]5fa4f9a2013-10-03 10:13:16699int CookieMonster::DeleteAllForHostTask::RunDeleteTask() {
700 return this->cookie_monster()->DeleteAllForHost(url_);
[email protected]218aa6a12011-09-13 17:38:38701}
702
[email protected]d8428d52013-08-07 06:58:25703// Task class for DeleteAllCreatedBetweenForHost call.
704class CookieMonster::DeleteAllCreatedBetweenForHostTask
[email protected]5fa4f9a2013-10-03 10:13:16705 : public DeleteTask<int> {
[email protected]d8428d52013-08-07 06:58:25706 public:
mkwstbe84af312015-02-20 08:52:45707 DeleteAllCreatedBetweenForHostTask(CookieMonster* cookie_monster,
708 Time delete_begin,
709 Time delete_end,
710 const GURL& url,
711 const DeleteCallback& callback)
[email protected]151132f2013-11-18 21:37:00712 : DeleteTask<int>(cookie_monster, callback),
[email protected]d8428d52013-08-07 06:58:25713 delete_begin_(delete_begin),
714 delete_end_(delete_end),
mkwstbe84af312015-02-20 08:52:45715 url_(url) {}
[email protected]d8428d52013-08-07 06:58:25716
[email protected]5fa4f9a2013-10-03 10:13:16717 // DeleteTask:
dchengb03027d2014-10-21 12:00:20718 int RunDeleteTask() override;
[email protected]d8428d52013-08-07 06:58:25719
720 protected:
dchengb03027d2014-10-21 12:00:20721 ~DeleteAllCreatedBetweenForHostTask() override {}
[email protected]d8428d52013-08-07 06:58:25722
723 private:
724 Time delete_begin_;
725 Time delete_end_;
726 GURL url_;
[email protected]d8428d52013-08-07 06:58:25727
728 DISALLOW_COPY_AND_ASSIGN(DeleteAllCreatedBetweenForHostTask);
729};
730
[email protected]5fa4f9a2013-10-03 10:13:16731int CookieMonster::DeleteAllCreatedBetweenForHostTask::RunDeleteTask() {
732 return this->cookie_monster()->DeleteAllCreatedBetweenForHost(
[email protected]d8428d52013-08-07 06:58:25733 delete_begin_, delete_end_, url_);
[email protected]d8428d52013-08-07 06:58:25734}
735
[email protected]218aa6a12011-09-13 17:38:38736// Task class for DeleteCanonicalCookie call.
[email protected]5fa4f9a2013-10-03 10:13:16737class CookieMonster::DeleteCanonicalCookieTask : public DeleteTask<bool> {
[email protected]218aa6a12011-09-13 17:38:38738 public:
[email protected]dedec0b2013-02-28 04:50:10739 DeleteCanonicalCookieTask(CookieMonster* cookie_monster,
740 const CanonicalCookie& cookie,
[email protected]5fa4f9a2013-10-03 10:13:16741 const DeleteCookieCallback& callback)
mkwstbe84af312015-02-20 08:52:45742 : DeleteTask<bool>(cookie_monster, callback), cookie_(cookie) {}
[email protected]218aa6a12011-09-13 17:38:38743
[email protected]5fa4f9a2013-10-03 10:13:16744 // DeleteTask:
dchengb03027d2014-10-21 12:00:20745 bool RunDeleteTask() override;
[email protected]218aa6a12011-09-13 17:38:38746
[email protected]a9813302012-04-28 09:29:28747 protected:
dchengb03027d2014-10-21 12:00:20748 ~DeleteCanonicalCookieTask() override {}
[email protected]a9813302012-04-28 09:29:28749
[email protected]218aa6a12011-09-13 17:38:38750 private:
[email protected]5b9bc352012-07-18 13:13:34751 CanonicalCookie cookie_;
[email protected]218aa6a12011-09-13 17:38:38752
753 DISALLOW_COPY_AND_ASSIGN(DeleteCanonicalCookieTask);
754};
755
[email protected]5fa4f9a2013-10-03 10:13:16756bool CookieMonster::DeleteCanonicalCookieTask::RunDeleteTask() {
757 return this->cookie_monster()->DeleteCanonicalCookie(cookie_);
[email protected]218aa6a12011-09-13 17:38:38758}
759
760// Task class for SetCookieWithOptions call.
[email protected]5fa4f9a2013-10-03 10:13:16761class CookieMonster::SetCookieWithOptionsTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38762 public:
763 SetCookieWithOptionsTask(CookieMonster* cookie_monster,
764 const GURL& url,
765 const std::string& cookie_line,
766 const CookieOptions& options,
[email protected]5fa4f9a2013-10-03 10:13:16767 const SetCookiesCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38768 : CookieMonsterTask(cookie_monster),
769 url_(url),
770 cookie_line_(cookie_line),
771 options_(options),
mkwstbe84af312015-02-20 08:52:45772 callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38773
[email protected]5fa4f9a2013-10-03 10:13:16774 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20775 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38776
[email protected]a9813302012-04-28 09:29:28777 protected:
dchengb03027d2014-10-21 12:00:20778 ~SetCookieWithOptionsTask() override {}
[email protected]a9813302012-04-28 09:29:28779
[email protected]218aa6a12011-09-13 17:38:38780 private:
781 GURL url_;
782 std::string cookie_line_;
783 CookieOptions options_;
[email protected]5fa4f9a2013-10-03 10:13:16784 SetCookiesCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38785
786 DISALLOW_COPY_AND_ASSIGN(SetCookieWithOptionsTask);
787};
788
789void CookieMonster::SetCookieWithOptionsTask::Run() {
mkwstbe84af312015-02-20 08:52:45790 bool result = this->cookie_monster()->SetCookieWithOptions(url_, cookie_line_,
791 options_);
[email protected]218aa6a12011-09-13 17:38:38792 if (!callback_.is_null()) {
[email protected]5fa4f9a2013-10-03 10:13:16793 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38794 base::Unretained(&callback_), result));
795 }
796}
797
drogerd5d1278c2015-03-17 19:21:51798// Task class for SetAllCookies call.
799class CookieMonster::SetAllCookiesTask : public CookieMonsterTask {
800 public:
801 SetAllCookiesTask(CookieMonster* cookie_monster,
802 const CookieList& list,
803 const SetCookiesCallback& callback)
804 : CookieMonsterTask(cookie_monster), list_(list), callback_(callback) {}
805
806 // CookieMonsterTask:
807 void Run() override;
808
809 protected:
810 ~SetAllCookiesTask() override {}
811
812 private:
813 CookieList list_;
814 SetCookiesCallback callback_;
815
816 DISALLOW_COPY_AND_ASSIGN(SetAllCookiesTask);
817};
818
819void CookieMonster::SetAllCookiesTask::Run() {
820 CookieList positive_diff;
821 CookieList negative_diff;
822 CookieList old_cookies = this->cookie_monster()->GetAllCookies();
823 this->cookie_monster()->ComputeCookieDiff(&old_cookies, &list_,
824 &positive_diff, &negative_diff);
825
826 for (CookieList::const_iterator it = negative_diff.begin();
827 it != negative_diff.end(); ++it) {
828 this->cookie_monster()->DeleteCanonicalCookie(*it);
829 }
830
831 bool result = true;
832 if (positive_diff.size() > 0)
833 result = this->cookie_monster()->SetCanonicalCookies(list_);
834
835 if (!callback_.is_null()) {
836 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run,
837 base::Unretained(&callback_), result));
838 }
839}
840
[email protected]218aa6a12011-09-13 17:38:38841// Task class for GetCookiesWithOptions call.
[email protected]5fa4f9a2013-10-03 10:13:16842class CookieMonster::GetCookiesWithOptionsTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38843 public:
844 GetCookiesWithOptionsTask(CookieMonster* cookie_monster,
[email protected]0298caf82011-12-20 23:15:46845 const GURL& url,
[email protected]218aa6a12011-09-13 17:38:38846 const CookieOptions& options,
[email protected]5fa4f9a2013-10-03 10:13:16847 const GetCookiesCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38848 : CookieMonsterTask(cookie_monster),
849 url_(url),
850 options_(options),
mkwstbe84af312015-02-20 08:52:45851 callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38852
[email protected]5fa4f9a2013-10-03 10:13:16853 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20854 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38855
[email protected]a9813302012-04-28 09:29:28856 protected:
dchengb03027d2014-10-21 12:00:20857 ~GetCookiesWithOptionsTask() override {}
[email protected]a9813302012-04-28 09:29:28858
[email protected]218aa6a12011-09-13 17:38:38859 private:
860 GURL url_;
861 CookieOptions options_;
[email protected]5fa4f9a2013-10-03 10:13:16862 GetCookiesCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38863
864 DISALLOW_COPY_AND_ASSIGN(GetCookiesWithOptionsTask);
865};
866
867void CookieMonster::GetCookiesWithOptionsTask::Run() {
pkastinga9269aa42015-04-10 01:42:26868 // TODO(mkwst): Remove ScopedTracker below once crbug.com/456373 is fixed.
pkasting58e029b2015-02-21 05:17:28869 tracked_objects::ScopedTracker tracking_profile(
870 FROM_HERE_WITH_EXPLICIT_FUNCTION(
871 "456373 CookieMonster::GetCookiesWithOptionsTask::Run"));
mkwstbe84af312015-02-20 08:52:45872 std::string cookie =
873 this->cookie_monster()->GetCookiesWithOptions(url_, options_);
[email protected]218aa6a12011-09-13 17:38:38874 if (!callback_.is_null()) {
[email protected]5fa4f9a2013-10-03 10:13:16875 this->InvokeCallback(base::Bind(&GetCookiesCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38876 base::Unretained(&callback_), cookie));
877 }
878}
879
[email protected]218aa6a12011-09-13 17:38:38880// Task class for DeleteCookie call.
[email protected]5fa4f9a2013-10-03 10:13:16881class CookieMonster::DeleteCookieTask : public DeleteTask<void> {
[email protected]218aa6a12011-09-13 17:38:38882 public:
883 DeleteCookieTask(CookieMonster* cookie_monster,
[email protected]0298caf82011-12-20 23:15:46884 const GURL& url,
[email protected]218aa6a12011-09-13 17:38:38885 const std::string& cookie_name,
886 const base::Closure& callback)
[email protected]151132f2013-11-18 21:37:00887 : DeleteTask<void>(cookie_monster, callback),
[email protected]218aa6a12011-09-13 17:38:38888 url_(url),
mkwstbe84af312015-02-20 08:52:45889 cookie_name_(cookie_name) {}
[email protected]218aa6a12011-09-13 17:38:38890
[email protected]5fa4f9a2013-10-03 10:13:16891 // DeleteTask:
dchengb03027d2014-10-21 12:00:20892 void RunDeleteTask() override;
[email protected]218aa6a12011-09-13 17:38:38893
[email protected]a9813302012-04-28 09:29:28894 protected:
dchengb03027d2014-10-21 12:00:20895 ~DeleteCookieTask() override {}
[email protected]a9813302012-04-28 09:29:28896
[email protected]218aa6a12011-09-13 17:38:38897 private:
898 GURL url_;
899 std::string cookie_name_;
[email protected]218aa6a12011-09-13 17:38:38900
901 DISALLOW_COPY_AND_ASSIGN(DeleteCookieTask);
902};
903
[email protected]5fa4f9a2013-10-03 10:13:16904void CookieMonster::DeleteCookieTask::RunDeleteTask() {
[email protected]218aa6a12011-09-13 17:38:38905 this->cookie_monster()->DeleteCookie(url_, cookie_name_);
[email protected]218aa6a12011-09-13 17:38:38906}
907
[email protected]264807b2012-04-25 14:49:37908// Task class for DeleteSessionCookies call.
[email protected]5fa4f9a2013-10-03 10:13:16909class CookieMonster::DeleteSessionCookiesTask : public DeleteTask<int> {
[email protected]264807b2012-04-25 14:49:37910 public:
[email protected]dedec0b2013-02-28 04:50:10911 DeleteSessionCookiesTask(CookieMonster* cookie_monster,
[email protected]5fa4f9a2013-10-03 10:13:16912 const DeleteCallback& callback)
mkwstbe84af312015-02-20 08:52:45913 : DeleteTask<int>(cookie_monster, callback) {}
[email protected]264807b2012-04-25 14:49:37914
[email protected]5fa4f9a2013-10-03 10:13:16915 // DeleteTask:
dchengb03027d2014-10-21 12:00:20916 int RunDeleteTask() override;
[email protected]264807b2012-04-25 14:49:37917
[email protected]a9813302012-04-28 09:29:28918 protected:
dchengb03027d2014-10-21 12:00:20919 ~DeleteSessionCookiesTask() override {}
[email protected]a9813302012-04-28 09:29:28920
[email protected]264807b2012-04-25 14:49:37921 private:
[email protected]264807b2012-04-25 14:49:37922 DISALLOW_COPY_AND_ASSIGN(DeleteSessionCookiesTask);
923};
924
[email protected]5fa4f9a2013-10-03 10:13:16925int CookieMonster::DeleteSessionCookiesTask::RunDeleteTask() {
926 return this->cookie_monster()->DeleteSessionCookies();
[email protected]264807b2012-04-25 14:49:37927}
928
[email protected]218aa6a12011-09-13 17:38:38929// Asynchronous CookieMonster API
930
931void CookieMonster::SetCookieWithDetailsAsync(
[email protected]dedec0b2013-02-28 04:50:10932 const GURL& url,
933 const std::string& name,
934 const std::string& value,
935 const std::string& domain,
936 const std::string& path,
[email protected]d8428d52013-08-07 06:58:25937 const Time& expiration_time,
[email protected]dedec0b2013-02-28 04:50:10938 bool secure,
939 bool http_only,
mkwstae819bb2015-02-23 05:10:31940 bool first_party_only,
estarkcd39c11f2015-10-19 19:46:36941 bool enforce_prefixes,
[email protected]ab2d75c82013-04-19 18:39:04942 CookiePriority priority,
[email protected]218aa6a12011-09-13 17:38:38943 const SetCookiesCallback& callback) {
mkwstbe84af312015-02-20 08:52:45944 scoped_refptr<SetCookieWithDetailsTask> task = new SetCookieWithDetailsTask(
945 this, url, name, value, domain, path, expiration_time, secure, http_only,
estarkcd39c11f2015-10-19 19:46:36946 first_party_only, enforce_prefixes, priority, callback);
[email protected]85620342011-10-17 17:35:04947 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:38948}
949
950void CookieMonster::GetAllCookiesAsync(const GetCookieListCallback& callback) {
mkwstbe84af312015-02-20 08:52:45951 scoped_refptr<GetAllCookiesTask> task = new GetAllCookiesTask(this, callback);
[email protected]218aa6a12011-09-13 17:38:38952
953 DoCookieTask(task);
954}
955
[email protected]218aa6a12011-09-13 17:38:38956void CookieMonster::GetAllCookiesForURLWithOptionsAsync(
957 const GURL& url,
958 const CookieOptions& options,
959 const GetCookieListCallback& callback) {
960 scoped_refptr<GetAllCookiesForURLWithOptionsTask> task =
961 new GetAllCookiesForURLWithOptionsTask(this, url, options, callback);
962
[email protected]85620342011-10-17 17:35:04963 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:38964}
965
966void CookieMonster::GetAllCookiesForURLAsync(
mkwstbe84af312015-02-20 08:52:45967 const GURL& url,
968 const GetCookieListCallback& callback) {
[email protected]218aa6a12011-09-13 17:38:38969 CookieOptions options;
970 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:31971 options.set_include_first_party_only();
[email protected]218aa6a12011-09-13 17:38:38972 scoped_refptr<GetAllCookiesForURLWithOptionsTask> task =
973 new GetAllCookiesForURLWithOptionsTask(this, url, options, callback);
974
[email protected]85620342011-10-17 17:35:04975 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:38976}
977
978void CookieMonster::DeleteAllAsync(const DeleteCallback& callback) {
mkwstbe84af312015-02-20 08:52:45979 scoped_refptr<DeleteAllTask> task = new DeleteAllTask(this, callback);
[email protected]218aa6a12011-09-13 17:38:38980
981 DoCookieTask(task);
982}
983
984void CookieMonster::DeleteAllCreatedBetweenAsync(
mkwstbe84af312015-02-20 08:52:45985 const Time& delete_begin,
986 const Time& delete_end,
[email protected]218aa6a12011-09-13 17:38:38987 const DeleteCallback& callback) {
988 scoped_refptr<DeleteAllCreatedBetweenTask> task =
mkwstbe84af312015-02-20 08:52:45989 new DeleteAllCreatedBetweenTask(this, delete_begin, delete_end, callback);
[email protected]218aa6a12011-09-13 17:38:38990
991 DoCookieTask(task);
992}
993
[email protected]d8428d52013-08-07 06:58:25994void CookieMonster::DeleteAllCreatedBetweenForHostAsync(
995 const Time delete_begin,
996 const Time delete_end,
997 const GURL& url,
998 const DeleteCallback& callback) {
999 scoped_refptr<DeleteAllCreatedBetweenForHostTask> task =
mkwstbe84af312015-02-20 08:52:451000 new DeleteAllCreatedBetweenForHostTask(this, delete_begin, delete_end,
1001 url, callback);
[email protected]d8428d52013-08-07 06:58:251002
1003 DoCookieTaskForURL(task, url);
1004}
1005
mkwstbe84af312015-02-20 08:52:451006void CookieMonster::DeleteAllForHostAsync(const GURL& url,
1007 const DeleteCallback& callback) {
[email protected]218aa6a12011-09-13 17:38:381008 scoped_refptr<DeleteAllForHostTask> task =
1009 new DeleteAllForHostTask(this, url, callback);
1010
[email protected]85620342011-10-17 17:35:041011 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381012}
1013
1014void CookieMonster::DeleteCanonicalCookieAsync(
1015 const CanonicalCookie& cookie,
1016 const DeleteCookieCallback& callback) {
1017 scoped_refptr<DeleteCanonicalCookieTask> task =
1018 new DeleteCanonicalCookieTask(this, cookie, callback);
1019
1020 DoCookieTask(task);
1021}
1022
drogerd5d1278c2015-03-17 19:21:511023void CookieMonster::SetAllCookiesAsync(const CookieList& list,
1024 const SetCookiesCallback& callback) {
1025 scoped_refptr<SetAllCookiesTask> task =
1026 new SetAllCookiesTask(this, list, callback);
1027 DoCookieTask(task);
1028}
1029
[email protected]218aa6a12011-09-13 17:38:381030void CookieMonster::SetCookieWithOptionsAsync(
1031 const GURL& url,
1032 const std::string& cookie_line,
1033 const CookieOptions& options,
1034 const SetCookiesCallback& callback) {
1035 scoped_refptr<SetCookieWithOptionsTask> task =
1036 new SetCookieWithOptionsTask(this, url, cookie_line, options, callback);
1037
[email protected]85620342011-10-17 17:35:041038 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381039}
1040
1041void CookieMonster::GetCookiesWithOptionsAsync(
1042 const GURL& url,
1043 const CookieOptions& options,
1044 const GetCookiesCallback& callback) {
1045 scoped_refptr<GetCookiesWithOptionsTask> task =
1046 new GetCookiesWithOptionsTask(this, url, options, callback);
1047
[email protected]85620342011-10-17 17:35:041048 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381049}
1050
[email protected]218aa6a12011-09-13 17:38:381051void CookieMonster::DeleteCookieAsync(const GURL& url,
1052 const std::string& cookie_name,
1053 const base::Closure& callback) {
1054 scoped_refptr<DeleteCookieTask> task =
1055 new DeleteCookieTask(this, url, cookie_name, callback);
1056
[email protected]85620342011-10-17 17:35:041057 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381058}
1059
[email protected]264807b2012-04-25 14:49:371060void CookieMonster::DeleteSessionCookiesAsync(
1061 const CookieStore::DeleteCallback& callback) {
1062 scoped_refptr<DeleteSessionCookiesTask> task =
1063 new DeleteSessionCookiesTask(this, callback);
1064
1065 DoCookieTask(task);
1066}
1067
[email protected]218aa6a12011-09-13 17:38:381068void CookieMonster::DoCookieTask(
1069 const scoped_refptr<CookieMonsterTask>& task_item) {
[email protected]218aa6a12011-09-13 17:38:381070 {
1071 base::AutoLock autolock(lock_);
erikchen1dd72a72015-05-06 20:45:051072 MarkCookieStoreAsInitialized();
1073 FetchAllCookiesIfNecessary();
1074 if (!finished_fetching_all_cookies_ && store_.get()) {
[email protected]0184df32013-05-14 00:53:551075 tasks_pending_.push(task_item);
[email protected]218aa6a12011-09-13 17:38:381076 return;
1077 }
1078 }
1079
1080 task_item->Run();
1081}
1082
[email protected]85620342011-10-17 17:35:041083void CookieMonster::DoCookieTaskForURL(
1084 const scoped_refptr<CookieMonsterTask>& task_item,
1085 const GURL& url) {
1086 {
1087 base::AutoLock autolock(lock_);
erikchen1dd72a72015-05-06 20:45:051088 MarkCookieStoreAsInitialized();
1089 if (ShouldFetchAllCookiesWhenFetchingAnyCookie())
1090 FetchAllCookiesIfNecessary();
[email protected]85620342011-10-17 17:35:041091 // If cookies for the requested domain key (eTLD+1) have been loaded from DB
1092 // then run the task, otherwise load from DB.
erikchen1dd72a72015-05-06 20:45:051093 if (!finished_fetching_all_cookies_ && store_.get()) {
[email protected]85620342011-10-17 17:35:041094 // Checks if the domain key has been loaded.
mkwstbe84af312015-02-20 08:52:451095 std::string key(
1096 cookie_util::GetEffectiveDomain(url.scheme(), url.host()));
[email protected]85620342011-10-17 17:35:041097 if (keys_loaded_.find(key) == keys_loaded_.end()) {
mkwstbe84af312015-02-20 08:52:451098 std::map<std::string,
1099 std::deque<scoped_refptr<CookieMonsterTask>>>::iterator it =
1100 tasks_pending_for_key_.find(key);
[email protected]0184df32013-05-14 00:53:551101 if (it == tasks_pending_for_key_.end()) {
mkwstbe84af312015-02-20 08:52:451102 store_->LoadCookiesForKey(
1103 key, base::Bind(&CookieMonster::OnKeyLoaded, this, key));
1104 it = tasks_pending_for_key_
1105 .insert(std::make_pair(
1106 key, std::deque<scoped_refptr<CookieMonsterTask>>()))
1107 .first;
[email protected]85620342011-10-17 17:35:041108 }
1109 it->second.push_back(task_item);
1110 return;
1111 }
1112 }
1113 }
1114 task_item->Run();
1115}
1116
[email protected]dedec0b2013-02-28 04:50:101117bool CookieMonster::SetCookieWithDetails(const GURL& url,
1118 const std::string& name,
1119 const std::string& value,
1120 const std::string& domain,
1121 const std::string& path,
1122 const base::Time& expiration_time,
1123 bool secure,
[email protected]ab2d75c82013-04-19 18:39:041124 bool http_only,
mkwstae819bb2015-02-23 05:10:311125 bool first_party_only,
estarkcd39c11f2015-10-19 19:46:361126 bool enforce_prefixes,
[email protected]ab2d75c82013-04-19 18:39:041127 CookiePriority priority) {
[email protected]20305ec2011-01-21 04:55:521128 base::AutoLock autolock(lock_);
[email protected]69bb5872010-01-12 20:33:521129
[email protected]f48b9432011-01-11 07:25:401130 if (!HasCookieableScheme(url))
initial.commit586acc5fe2008-07-26 22:42:521131 return false;
1132
[email protected]f48b9432011-01-11 07:25:401133 Time creation_time = CurrentTime();
1134 last_time_seen_ = creation_time;
1135
1136 scoped_ptr<CanonicalCookie> cc;
[email protected]ab2d75c82013-04-19 18:39:041137 cc.reset(CanonicalCookie::Create(url, name, value, domain, path,
mkwstbe84af312015-02-20 08:52:451138 creation_time, expiration_time, secure,
mkwstae819bb2015-02-23 05:10:311139 http_only, first_party_only, priority));
[email protected]f48b9432011-01-11 07:25:401140
1141 if (!cc.get())
1142 return false;
1143
1144 CookieOptions options;
1145 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:311146 options.set_include_first_party_only();
estarkcd39c11f2015-10-19 19:46:361147 if (enforce_prefixes)
1148 options.set_enforce_prefixes();
[email protected]f48b9432011-01-11 07:25:401149 return SetCanonicalCookie(&cc, creation_time, options);
initial.commit586acc5fe2008-07-26 22:42:521150}
1151
bartfaba13acdf2014-09-05 15:07:281152bool CookieMonster::ImportCookies(const CookieList& list) {
[email protected]93460df2011-07-20 00:58:211153 base::AutoLock autolock(lock_);
erikchen1dd72a72015-05-06 20:45:051154 MarkCookieStoreAsInitialized();
1155 if (ShouldFetchAllCookiesWhenFetchingAnyCookie())
1156 FetchAllCookiesIfNecessary();
ttuttle859dc7a2015-04-23 19:42:291157 for (CookieList::const_iterator iter = list.begin(); iter != list.end();
mkwstbe84af312015-02-20 08:52:451158 ++iter) {
[email protected]5b9bc352012-07-18 13:13:341159 scoped_ptr<CanonicalCookie> cookie(new CanonicalCookie(*iter));
ttuttle859dc7a2015-04-23 19:42:291160 CookieOptions options;
[email protected]93460df2011-07-20 00:58:211161 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:311162 options.set_include_first_party_only();
[email protected]5b9bc352012-07-18 13:13:341163 if (!SetCanonicalCookie(&cookie, cookie->CreationDate(), options))
[email protected]93460df2011-07-20 00:58:211164 return false;
[email protected]93460df2011-07-20 00:58:211165 }
1166 return true;
1167}
1168
[email protected]f48b9432011-01-11 07:25:401169CookieList CookieMonster::GetAllCookies() {
[email protected]20305ec2011-01-21 04:55:521170 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401171
1172 // This function is being called to scrape the cookie list for management UI
1173 // or similar. We shouldn't show expired cookies in this list since it will
1174 // just be confusing to users, and this function is called rarely enough (and
1175 // is already slow enough) that it's OK to take the time to garbage collect
1176 // the expired cookies now.
1177 //
1178 // Note that this does not prune cookies to be below our limits (if we've
1179 // exceeded them) the way that calling GarbageCollect() would.
mkwstbe84af312015-02-20 08:52:451180 GarbageCollectExpired(
1181 Time::Now(), CookieMapItPair(cookies_.begin(), cookies_.end()), NULL);
[email protected]f48b9432011-01-11 07:25:401182
1183 // Copy the CanonicalCookie pointers from the map so that we can use the same
1184 // sorter as elsewhere, then copy the result out.
1185 std::vector<CanonicalCookie*> cookie_ptrs;
1186 cookie_ptrs.reserve(cookies_.size());
1187 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end(); ++it)
1188 cookie_ptrs.push_back(it->second);
1189 std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter);
1190
1191 CookieList cookie_list;
1192 cookie_list.reserve(cookie_ptrs.size());
1193 for (std::vector<CanonicalCookie*>::const_iterator it = cookie_ptrs.begin();
1194 it != cookie_ptrs.end(); ++it)
1195 cookie_list.push_back(**it);
1196
1197 return cookie_list;
[email protected]f325f1e12010-04-30 22:38:551198}
1199
[email protected]f48b9432011-01-11 07:25:401200CookieList CookieMonster::GetAllCookiesForURLWithOptions(
1201 const GURL& url,
1202 const CookieOptions& options) {
[email protected]20305ec2011-01-21 04:55:521203 base::AutoLock autolock(lock_);
initial.commit586acc5fe2008-07-26 22:42:521204
[email protected]f48b9432011-01-11 07:25:401205 std::vector<CanonicalCookie*> cookie_ptrs;
1206 FindCookiesForHostAndDomain(url, options, false, &cookie_ptrs);
1207 std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter);
initial.commit586acc5fe2008-07-26 22:42:521208
[email protected]f48b9432011-01-11 07:25:401209 CookieList cookies;
georgesakc15df6722014-12-02 23:52:121210 cookies.reserve(cookie_ptrs.size());
[email protected]f48b9432011-01-11 07:25:401211 for (std::vector<CanonicalCookie*>::const_iterator it = cookie_ptrs.begin();
1212 it != cookie_ptrs.end(); it++)
1213 cookies.push_back(**it);
initial.commit586acc5fe2008-07-26 22:42:521214
[email protected]f48b9432011-01-11 07:25:401215 return cookies;
initial.commit586acc5fe2008-07-26 22:42:521216}
1217
[email protected]f48b9432011-01-11 07:25:401218CookieList CookieMonster::GetAllCookiesForURL(const GURL& url) {
1219 CookieOptions options;
1220 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:311221 options.set_first_party_url(url);
[email protected]f48b9432011-01-11 07:25:401222
1223 return GetAllCookiesForURLWithOptions(url, options);
[email protected]f325f1e12010-04-30 22:38:551224}
1225
[email protected]f48b9432011-01-11 07:25:401226int CookieMonster::DeleteAll(bool sync_to_store) {
[email protected]20305ec2011-01-21 04:55:521227 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401228
1229 int num_deleted = 0;
1230 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1231 CookieMap::iterator curit = it;
1232 ++it;
1233 InternalDeleteCookie(curit, sync_to_store,
mkwstbe84af312015-02-20 08:52:451234 sync_to_store
1235 ? DELETE_COOKIE_EXPLICIT
1236 : DELETE_COOKIE_DONT_RECORD /* Destruction. */);
[email protected]f48b9432011-01-11 07:25:401237 ++num_deleted;
initial.commit586acc5fe2008-07-26 22:42:521238 }
1239
[email protected]f48b9432011-01-11 07:25:401240 return num_deleted;
initial.commit586acc5fe2008-07-26 22:42:521241}
1242
[email protected]f48b9432011-01-11 07:25:401243int CookieMonster::DeleteAllCreatedBetween(const Time& delete_begin,
[email protected]218aa6a12011-09-13 17:38:381244 const Time& delete_end) {
[email protected]20305ec2011-01-21 04:55:521245 base::AutoLock autolock(lock_);
[email protected]d0980332010-11-16 17:08:531246
[email protected]f48b9432011-01-11 07:25:401247 int num_deleted = 0;
1248 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1249 CookieMap::iterator curit = it;
1250 CanonicalCookie* cc = curit->second;
1251 ++it;
[email protected]d0980332010-11-16 17:08:531252
[email protected]f48b9432011-01-11 07:25:401253 if (cc->CreationDate() >= delete_begin &&
1254 (delete_end.is_null() || cc->CreationDate() < delete_end)) {
mkwstbe84af312015-02-20 08:52:451255 InternalDeleteCookie(curit, true, /*sync_to_store*/
[email protected]218aa6a12011-09-13 17:38:381256 DELETE_COOKIE_EXPLICIT);
[email protected]f48b9432011-01-11 07:25:401257 ++num_deleted;
initial.commit586acc5fe2008-07-26 22:42:521258 }
1259 }
1260
[email protected]f48b9432011-01-11 07:25:401261 return num_deleted;
1262}
1263
[email protected]d8428d52013-08-07 06:58:251264int CookieMonster::DeleteAllCreatedBetweenForHost(const Time delete_begin,
1265 const Time delete_end,
1266 const GURL& url) {
[email protected]20305ec2011-01-21 04:55:521267 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401268
1269 if (!HasCookieableScheme(url))
1270 return 0;
1271
[email protected]f48b9432011-01-11 07:25:401272 const std::string host(url.host());
1273
1274 // We store host cookies in the store by their canonical host name;
1275 // domain cookies are stored with a leading ".". So this is a pretty
1276 // simple lookup and per-cookie delete.
1277 int num_deleted = 0;
1278 for (CookieMapItPair its = cookies_.equal_range(GetKey(host));
1279 its.first != its.second;) {
1280 CookieMap::iterator curit = its.first;
1281 ++its.first;
1282
1283 const CanonicalCookie* const cc = curit->second;
1284
1285 // Delete only on a match as a host cookie.
[email protected]d8428d52013-08-07 06:58:251286 if (cc->IsHostCookie() && cc->IsDomainMatch(host) &&
1287 cc->CreationDate() >= delete_begin &&
1288 // The assumption that null |delete_end| is equivalent to
1289 // Time::Max() is confusing.
1290 (delete_end.is_null() || cc->CreationDate() < delete_end)) {
[email protected]f48b9432011-01-11 07:25:401291 num_deleted++;
1292
1293 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT);
1294 }
1295 }
1296 return num_deleted;
1297}
1298
[email protected]d8428d52013-08-07 06:58:251299int CookieMonster::DeleteAllForHost(const GURL& url) {
1300 return DeleteAllCreatedBetweenForHost(Time(), Time::Max(), url);
1301}
1302
[email protected]f48b9432011-01-11 07:25:401303bool CookieMonster::DeleteCanonicalCookie(const CanonicalCookie& cookie) {
[email protected]20305ec2011-01-21 04:55:521304 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401305
1306 for (CookieMapItPair its = cookies_.equal_range(GetKey(cookie.Domain()));
1307 its.first != its.second; ++its.first) {
1308 // The creation date acts as our unique index...
1309 if (its.first->second->CreationDate() == cookie.CreationDate()) {
1310 InternalDeleteCookie(its.first, true, DELETE_COOKIE_EXPLICIT);
1311 return true;
1312 }
1313 }
initial.commit586acc5fe2008-07-26 22:42:521314 return false;
1315}
1316
[email protected]5edff3c52014-06-23 20:27:481317void CookieMonster::SetCookieableSchemes(const char* const schemes[],
[email protected]dedec0b2013-02-28 04:50:101318 size_t num_schemes) {
[email protected]20305ec2011-01-21 04:55:521319 base::AutoLock autolock(lock_);
[email protected]bb8905722010-05-21 17:29:041320
paulmillere7b3668e2015-07-23 16:37:331321 // Calls to this method will have no effect if made after a WebView or
1322 // CookieManager instance has been created.
1323 if (initialized_) {
1324 return;
1325 }
[email protected]cf12bd12010-06-17 14:41:301326
[email protected]47accfd62009-05-14 18:46:211327 cookieable_schemes_.clear();
mkwstbe84af312015-02-20 08:52:451328 cookieable_schemes_.insert(cookieable_schemes_.end(), schemes,
1329 schemes + num_schemes);
[email protected]47accfd62009-05-14 18:46:211330}
1331
[email protected]ba4ad0e2011-03-15 08:12:471332void CookieMonster::SetKeepExpiredCookies() {
1333 keep_expired_cookies_ = true;
1334}
1335
[email protected]e67f0f42011-12-20 02:29:211336void CookieMonster::FlushStore(const base::Closure& callback) {
[email protected]20305ec2011-01-21 04:55:521337 base::AutoLock autolock(lock_);
[email protected]90499482013-06-01 00:39:501338 if (initialized_ && store_.get())
[email protected]e67f0f42011-12-20 02:29:211339 store_->Flush(callback);
1340 else if (!callback.is_null())
skyostil4891b25b2015-06-11 11:43:451341 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback);
[email protected]f48b9432011-01-11 07:25:401342}
1343
1344bool CookieMonster::SetCookieWithOptions(const GURL& url,
1345 const std::string& cookie_line,
1346 const CookieOptions& options) {
[email protected]20305ec2011-01-21 04:55:521347 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401348
1349 if (!HasCookieableScheme(url)) {
1350 return false;
1351 }
1352
[email protected]f48b9432011-01-11 07:25:401353 return SetCookieWithCreationTimeAndOptions(url, cookie_line, Time(), options);
1354}
1355
1356std::string CookieMonster::GetCookiesWithOptions(const GURL& url,
1357 const CookieOptions& options) {
[email protected]20305ec2011-01-21 04:55:521358 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401359
[email protected]34a160d2011-05-12 22:12:491360 if (!HasCookieableScheme(url))
[email protected]f48b9432011-01-11 07:25:401361 return std::string();
[email protected]f48b9432011-01-11 07:25:401362
[email protected]f48b9432011-01-11 07:25:401363 std::vector<CanonicalCookie*> cookies;
1364 FindCookiesForHostAndDomain(url, options, true, &cookies);
1365 std::sort(cookies.begin(), cookies.end(), CookieSorter);
1366
[email protected]34a160d2011-05-12 22:12:491367 std::string cookie_line = BuildCookieLine(cookies);
[email protected]f48b9432011-01-11 07:25:401368
[email protected]f48b9432011-01-11 07:25:401369 VLOG(kVlogGetCookies) << "GetCookies() result: " << cookie_line;
1370
1371 return cookie_line;
1372}
1373
1374void CookieMonster::DeleteCookie(const GURL& url,
1375 const std::string& cookie_name) {
[email protected]20305ec2011-01-21 04:55:521376 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401377
1378 if (!HasCookieableScheme(url))
1379 return;
1380
1381 CookieOptions options;
1382 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:311383 options.set_include_first_party_only();
[email protected]f48b9432011-01-11 07:25:401384 // Get the cookies for this host and its domain(s).
1385 std::vector<CanonicalCookie*> cookies;
1386 FindCookiesForHostAndDomain(url, options, true, &cookies);
1387 std::set<CanonicalCookie*> matching_cookies;
1388
1389 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
1390 it != cookies.end(); ++it) {
1391 if ((*it)->Name() != cookie_name)
1392 continue;
1393 if (url.path().find((*it)->Path()))
1394 continue;
1395 matching_cookies.insert(*it);
1396 }
1397
1398 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1399 CookieMap::iterator curit = it;
1400 ++it;
1401 if (matching_cookies.find(curit->second) != matching_cookies.end()) {
1402 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT);
1403 }
1404 }
1405}
1406
[email protected]264807b2012-04-25 14:49:371407int CookieMonster::DeleteSessionCookies() {
1408 base::AutoLock autolock(lock_);
1409
1410 int num_deleted = 0;
1411 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1412 CookieMap::iterator curit = it;
1413 CanonicalCookie* cc = curit->second;
1414 ++it;
1415
1416 if (!cc->IsPersistent()) {
mkwstbe84af312015-02-20 08:52:451417 InternalDeleteCookie(curit, true, /*sync_to_store*/
[email protected]264807b2012-04-25 14:49:371418 DELETE_COOKIE_EXPIRED);
1419 ++num_deleted;
1420 }
1421 }
1422
1423 return num_deleted;
1424}
1425
[email protected]f48b9432011-01-11 07:25:401426CookieMonster* CookieMonster::GetCookieMonster() {
1427 return this;
1428}
1429
[email protected]8ad5d462013-05-02 08:45:261430// This function must be called before the CookieMonster is used.
[email protected]93c53a32011-12-05 10:40:351431void CookieMonster::SetPersistSessionCookies(bool persist_session_cookies) {
[email protected]93c53a32011-12-05 10:40:351432 DCHECK(!initialized_);
1433 persist_session_cookies_ = persist_session_cookies;
1434}
1435
[email protected]bf510ed2012-06-05 08:31:431436void CookieMonster::SetForceKeepSessionState() {
[email protected]90499482013-06-01 00:39:501437 if (store_.get()) {
[email protected]bf510ed2012-06-05 08:31:431438 store_->SetForceKeepSessionState();
[email protected]93c53a32011-12-05 10:40:351439 }
1440}
1441
[email protected]f48b9432011-01-11 07:25:401442CookieMonster::~CookieMonster() {
1443 DeleteAll(false);
1444}
1445
1446bool CookieMonster::SetCookieWithCreationTime(const GURL& url,
1447 const std::string& cookie_line,
1448 const base::Time& creation_time) {
[email protected]90499482013-06-01 00:39:501449 DCHECK(!store_.get()) << "This method is only to be used by unit-tests.";
[email protected]20305ec2011-01-21 04:55:521450 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401451
1452 if (!HasCookieableScheme(url)) {
1453 return false;
1454 }
1455
erikchen1dd72a72015-05-06 20:45:051456 MarkCookieStoreAsInitialized();
1457 if (ShouldFetchAllCookiesWhenFetchingAnyCookie())
1458 FetchAllCookiesIfNecessary();
1459
[email protected]f48b9432011-01-11 07:25:401460 return SetCookieWithCreationTimeAndOptions(url, cookie_line, creation_time,
1461 CookieOptions());
1462}
1463
erikchen1dd72a72015-05-06 20:45:051464void CookieMonster::MarkCookieStoreAsInitialized() {
1465 initialized_ = true;
1466}
1467
1468void CookieMonster::FetchAllCookiesIfNecessary() {
1469 if (store_.get() && !started_fetching_all_cookies_) {
1470 started_fetching_all_cookies_ = true;
1471 FetchAllCookies();
1472 }
1473}
1474
1475bool CookieMonster::ShouldFetchAllCookiesWhenFetchingAnyCookie() {
1476 if (fetch_strategy_ == kUnknownFetch) {
1477 const std::string group_name =
1478 base::FieldTrialList::FindFullName(kCookieMonsterFetchStrategyName);
1479 if (group_name == kFetchWhenNecessaryName) {
1480 fetch_strategy_ = kFetchWhenNecessary;
1481 } else if (group_name == kAlwaysFetchName) {
1482 fetch_strategy_ = kAlwaysFetch;
1483 } else {
1484 // The logic in the conditional is redundant, but it makes trials of
1485 // the Finch experiment more explicit.
1486 fetch_strategy_ = kAlwaysFetch;
1487 }
1488 }
1489
1490 return fetch_strategy_ == kAlwaysFetch;
1491}
1492
1493void CookieMonster::FetchAllCookies() {
[email protected]90499482013-06-01 00:39:501494 DCHECK(store_.get()) << "Store must exist to initialize";
erikchen1dd72a72015-05-06 20:45:051495 DCHECK(!finished_fetching_all_cookies_)
1496 << "All cookies have already been fetched.";
[email protected]f48b9432011-01-11 07:25:401497
[email protected]218aa6a12011-09-13 17:38:381498 // We bind in the current time so that we can report the wall-clock time for
1499 // loading cookies.
1500 store_->Load(base::Bind(&CookieMonster::OnLoaded, this, TimeTicks::Now()));
1501}
[email protected]f48b9432011-01-11 07:25:401502
[email protected]218aa6a12011-09-13 17:38:381503void CookieMonster::OnLoaded(TimeTicks beginning_time,
1504 const std::vector<CanonicalCookie*>& cookies) {
1505 StoreLoadedCookies(cookies);
[email protected]c7593fb22011-11-14 23:54:271506 histogram_time_blocked_on_load_->AddTime(TimeTicks::Now() - beginning_time);
[email protected]218aa6a12011-09-13 17:38:381507
1508 // Invoke the task queue of cookie request.
1509 InvokeQueue();
1510}
1511
[email protected]85620342011-10-17 17:35:041512void CookieMonster::OnKeyLoaded(const std::string& key,
1513 const std::vector<CanonicalCookie*>& cookies) {
1514 // This function does its own separate locking.
1515 StoreLoadedCookies(cookies);
1516
mkwstbe84af312015-02-20 08:52:451517 std::deque<scoped_refptr<CookieMonsterTask>> tasks_pending_for_key;
[email protected]85620342011-10-17 17:35:041518
[email protected]bab72ec2013-10-30 20:50:021519 // We need to do this repeatedly until no more tasks were added to the queue
1520 // during the period where we release the lock.
1521 while (true) {
1522 {
1523 base::AutoLock autolock(lock_);
mkwstbe84af312015-02-20 08:52:451524 std::map<std::string,
1525 std::deque<scoped_refptr<CookieMonsterTask>>>::iterator it =
1526 tasks_pending_for_key_.find(key);
[email protected]bab72ec2013-10-30 20:50:021527 if (it == tasks_pending_for_key_.end()) {
1528 keys_loaded_.insert(key);
1529 return;
1530 }
1531 if (it->second.empty()) {
1532 keys_loaded_.insert(key);
1533 tasks_pending_for_key_.erase(it);
1534 return;
1535 }
1536 it->second.swap(tasks_pending_for_key);
1537 }
1538
1539 while (!tasks_pending_for_key.empty()) {
1540 scoped_refptr<CookieMonsterTask> task = tasks_pending_for_key.front();
1541 task->Run();
1542 tasks_pending_for_key.pop_front();
1543 }
[email protected]85620342011-10-17 17:35:041544 }
1545}
1546
[email protected]218aa6a12011-09-13 17:38:381547void CookieMonster::StoreLoadedCookies(
1548 const std::vector<CanonicalCookie*>& cookies) {
pkastingec2cdb52015-05-02 01:19:341549 // TODO(erikwright): Remove ScopedTracker below once crbug.com/457528 is
1550 // fixed.
1551 tracked_objects::ScopedTracker tracking_profile(
1552 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1553 "457528 CookieMonster::StoreLoadedCookies"));
1554
[email protected]f48b9432011-01-11 07:25:401555 // Initialize the store and sync in any saved persistent cookies. We don't
1556 // care if it's expired, insert it so it can be garbage collected, removed,
1557 // and sync'd.
[email protected]218aa6a12011-09-13 17:38:381558 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401559
[email protected]6210ce52013-09-20 03:33:141560 CookieItVector cookies_with_control_chars;
1561
[email protected]f48b9432011-01-11 07:25:401562 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
1563 it != cookies.end(); ++it) {
1564 int64 cookie_creation_time = (*it)->CreationDate().ToInternalValue();
1565
[email protected]85620342011-10-17 17:35:041566 if (creation_times_.insert(cookie_creation_time).second) {
[email protected]6210ce52013-09-20 03:33:141567 CookieMap::iterator inserted =
1568 InternalInsertCookie(GetKey((*it)->Domain()), *it, false);
[email protected]f48b9432011-01-11 07:25:401569 const Time cookie_access_time((*it)->LastAccessDate());
[email protected]85620342011-10-17 17:35:041570 if (earliest_access_time_.is_null() ||
1571 cookie_access_time < earliest_access_time_)
1572 earliest_access_time_ = cookie_access_time;
[email protected]6210ce52013-09-20 03:33:141573
1574 if (ContainsControlCharacter((*it)->Name()) ||
1575 ContainsControlCharacter((*it)->Value())) {
mkwstbe84af312015-02-20 08:52:451576 cookies_with_control_chars.push_back(inserted);
[email protected]6210ce52013-09-20 03:33:141577 }
[email protected]f48b9432011-01-11 07:25:401578 } else {
mkwstbe84af312015-02-20 08:52:451579 LOG(ERROR) << base::StringPrintf(
1580 "Found cookies with duplicate creation "
1581 "times in backing store: "
1582 "{name='%s', domain='%s', path='%s'}",
1583 (*it)->Name().c_str(), (*it)->Domain().c_str(),
1584 (*it)->Path().c_str());
[email protected]f48b9432011-01-11 07:25:401585 // We've been given ownership of the cookie and are throwing it
1586 // away; reclaim the space.
1587 delete (*it);
1588 }
1589 }
[email protected]f48b9432011-01-11 07:25:401590
[email protected]6210ce52013-09-20 03:33:141591 // Any cookies that contain control characters that we have loaded from the
1592 // persistent store should be deleted. See http://crbug.com/238041.
1593 for (CookieItVector::iterator it = cookies_with_control_chars.begin();
1594 it != cookies_with_control_chars.end();) {
1595 CookieItVector::iterator curit = it;
1596 ++it;
1597
1598 InternalDeleteCookie(*curit, true, DELETE_COOKIE_CONTROL_CHAR);
1599 }
1600
[email protected]f48b9432011-01-11 07:25:401601 // After importing cookies from the PersistentCookieStore, verify that
1602 // none of our other constraints are violated.
[email protected]f48b9432011-01-11 07:25:401603 // In particular, the backing store might have given us duplicate cookies.
[email protected]85620342011-10-17 17:35:041604
1605 // This method could be called multiple times due to priority loading, thus
1606 // cookies loaded in previous runs will be validated again, but this is OK
1607 // since they are expected to be much fewer than total DB.
[email protected]f48b9432011-01-11 07:25:401608 EnsureCookiesMapIsValid();
[email protected]218aa6a12011-09-13 17:38:381609}
[email protected]f48b9432011-01-11 07:25:401610
[email protected]218aa6a12011-09-13 17:38:381611void CookieMonster::InvokeQueue() {
1612 while (true) {
1613 scoped_refptr<CookieMonsterTask> request_task;
1614 {
1615 base::AutoLock autolock(lock_);
[email protected]0184df32013-05-14 00:53:551616 if (tasks_pending_.empty()) {
erikchen1dd72a72015-05-06 20:45:051617 finished_fetching_all_cookies_ = true;
[email protected]85620342011-10-17 17:35:041618 creation_times_.clear();
1619 keys_loaded_.clear();
[email protected]218aa6a12011-09-13 17:38:381620 break;
1621 }
[email protected]0184df32013-05-14 00:53:551622 request_task = tasks_pending_.front();
1623 tasks_pending_.pop();
[email protected]218aa6a12011-09-13 17:38:381624 }
1625 request_task->Run();
1626 }
[email protected]f48b9432011-01-11 07:25:401627}
1628
1629void CookieMonster::EnsureCookiesMapIsValid() {
1630 lock_.AssertAcquired();
1631
[email protected]f48b9432011-01-11 07:25:401632 // Iterate through all the of the cookies, grouped by host.
1633 CookieMap::iterator prev_range_end = cookies_.begin();
1634 while (prev_range_end != cookies_.end()) {
1635 CookieMap::iterator cur_range_begin = prev_range_end;
1636 const std::string key = cur_range_begin->first; // Keep a copy.
1637 CookieMap::iterator cur_range_end = cookies_.upper_bound(key);
1638 prev_range_end = cur_range_end;
1639
1640 // Ensure no equivalent cookies for this host.
ellyjonescabf57422015-08-21 18:44:511641 TrimDuplicateCookiesForKey(key, cur_range_begin, cur_range_end);
[email protected]f48b9432011-01-11 07:25:401642 }
[email protected]f48b9432011-01-11 07:25:401643}
1644
ellyjonescabf57422015-08-21 18:44:511645void CookieMonster::TrimDuplicateCookiesForKey(const std::string& key,
1646 CookieMap::iterator begin,
1647 CookieMap::iterator end) {
[email protected]f48b9432011-01-11 07:25:401648 lock_.AssertAcquired();
1649
1650 // Set of cookies ordered by creation time.
1651 typedef std::set<CookieMap::iterator, OrderByCreationTimeDesc> CookieSet;
1652
1653 // Helper map we populate to find the duplicates.
1654 typedef std::map<CookieSignature, CookieSet> EquivalenceMap;
1655 EquivalenceMap equivalent_cookies;
1656
1657 // The number of duplicate cookies that have been found.
1658 int num_duplicates = 0;
1659
1660 // Iterate through all of the cookies in our range, and insert them into
1661 // the equivalence map.
1662 for (CookieMap::iterator it = begin; it != end; ++it) {
1663 DCHECK_EQ(key, it->first);
1664 CanonicalCookie* cookie = it->second;
1665
mkwstbe84af312015-02-20 08:52:451666 CookieSignature signature(cookie->Name(), cookie->Domain(), cookie->Path());
[email protected]f48b9432011-01-11 07:25:401667 CookieSet& set = equivalent_cookies[signature];
1668
1669 // We found a duplicate!
1670 if (!set.empty())
1671 num_duplicates++;
1672
1673 // We save the iterator into |cookies_| rather than the actual cookie
1674 // pointer, since we may need to delete it later.
1675 bool insert_success = set.insert(it).second;
mkwstbe84af312015-02-20 08:52:451676 DCHECK(insert_success)
1677 << "Duplicate creation times found in duplicate cookie name scan.";
[email protected]f48b9432011-01-11 07:25:401678 }
1679
1680 // If there were no duplicates, we are done!
1681 if (num_duplicates == 0)
ellyjonescabf57422015-08-21 18:44:511682 return;
[email protected]f48b9432011-01-11 07:25:401683
1684 // Make sure we find everything below that we did above.
1685 int num_duplicates_found = 0;
1686
1687 // Otherwise, delete all the duplicate cookies, both from our in-memory store
1688 // and from the backing store.
1689 for (EquivalenceMap::iterator it = equivalent_cookies.begin();
mkwstbe84af312015-02-20 08:52:451690 it != equivalent_cookies.end(); ++it) {
[email protected]f48b9432011-01-11 07:25:401691 const CookieSignature& signature = it->first;
1692 CookieSet& dupes = it->second;
1693
1694 if (dupes.size() <= 1)
1695 continue; // This cookiename/path has no duplicates.
1696 num_duplicates_found += dupes.size() - 1;
1697
1698 // Since |dups| is sorted by creation time (descending), the first cookie
1699 // is the most recent one, so we will keep it. The rest are duplicates.
1700 dupes.erase(dupes.begin());
1701
1702 LOG(ERROR) << base::StringPrintf(
1703 "Found %d duplicate cookies for host='%s', "
1704 "with {name='%s', domain='%s', path='%s'}",
mkwstbe84af312015-02-20 08:52:451705 static_cast<int>(dupes.size()), key.c_str(), signature.name.c_str(),
1706 signature.domain.c_str(), signature.path.c_str());
[email protected]f48b9432011-01-11 07:25:401707
1708 // Remove all the cookies identified by |dupes|. It is valid to delete our
1709 // list of iterators one at a time, since |cookies_| is a multimap (they
1710 // don't invalidate existing iterators following deletion).
mkwstbe84af312015-02-20 08:52:451711 for (CookieSet::iterator dupes_it = dupes.begin(); dupes_it != dupes.end();
[email protected]f48b9432011-01-11 07:25:401712 ++dupes_it) {
[email protected]218aa6a12011-09-13 17:38:381713 InternalDeleteCookie(*dupes_it, true,
[email protected]f48b9432011-01-11 07:25:401714 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE);
1715 }
1716 }
1717 DCHECK_EQ(num_duplicates, num_duplicates_found);
[email protected]f48b9432011-01-11 07:25:401718}
1719
[email protected]ba4ad0e2011-03-15 08:12:471720// Note: file must be the last scheme.
mkwstbe84af312015-02-20 08:52:451721const char* const CookieMonster::kDefaultCookieableSchemes[] = {"http",
1722 "https",
1723 "ws",
1724 "wss",
1725 "file"};
[email protected]ba4ad0e2011-03-15 08:12:471726const int CookieMonster::kDefaultCookieableSchemesCount =
[email protected]5fa4f9a2013-10-03 10:13:161727 arraysize(kDefaultCookieableSchemes);
[email protected]ba4ad0e2011-03-15 08:12:471728
[email protected]f48b9432011-01-11 07:25:401729void CookieMonster::SetDefaultCookieableSchemes() {
[email protected]7c4b66b2014-01-04 12:28:131730 // Always disable file scheme unless SetEnableFileScheme(true) is called.
1731 SetCookieableSchemes(kDefaultCookieableSchemes,
1732 kDefaultCookieableSchemesCount - 1);
[email protected]f48b9432011-01-11 07:25:401733}
1734
[email protected]f48b9432011-01-11 07:25:401735void CookieMonster::FindCookiesForHostAndDomain(
1736 const GURL& url,
1737 const CookieOptions& options,
1738 bool update_access_time,
1739 std::vector<CanonicalCookie*>* cookies) {
1740 lock_.AssertAcquired();
1741
1742 const Time current_time(CurrentTime());
1743
1744 // Probe to save statistics relatively frequently. We do it here rather
1745 // than in the set path as many websites won't set cookies, and we
1746 // want to collect statistics whenever the browser's being used.
1747 RecordPeriodicStats(current_time);
1748
[email protected]8e1583672012-02-11 04:39:411749 // Can just dispatch to FindCookiesForKey
1750 const std::string key(GetKey(url.host()));
mkwstbe84af312015-02-20 08:52:451751 FindCookiesForKey(key, url, options, current_time, update_access_time,
1752 cookies);
[email protected]f48b9432011-01-11 07:25:401753}
1754
[email protected]dedec0b2013-02-28 04:50:101755void CookieMonster::FindCookiesForKey(const std::string& key,
1756 const GURL& url,
1757 const CookieOptions& options,
1758 const Time& current,
1759 bool update_access_time,
1760 std::vector<CanonicalCookie*>* cookies) {
[email protected]f48b9432011-01-11 07:25:401761 lock_.AssertAcquired();
1762
[email protected]f48b9432011-01-11 07:25:401763 for (CookieMapItPair its = cookies_.equal_range(key);
mkwstbe84af312015-02-20 08:52:451764 its.first != its.second;) {
[email protected]f48b9432011-01-11 07:25:401765 CookieMap::iterator curit = its.first;
1766 CanonicalCookie* cc = curit->second;
1767 ++its.first;
1768
1769 // If the cookie is expired, delete it.
[email protected]ba4ad0e2011-03-15 08:12:471770 if (cc->IsExpired(current) && !keep_expired_cookies_) {
[email protected]f48b9432011-01-11 07:25:401771 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
1772 continue;
1773 }
1774
[email protected]65f4e7e2012-12-12 21:56:541775 // Filter out cookies that should not be included for a request to the
1776 // given |url|. HTTP only cookies are filtered depending on the passed
1777 // cookie |options|.
1778 if (!cc->IncludeForRequestURL(url, options))
[email protected]f48b9432011-01-11 07:25:401779 continue;
1780
[email protected]65f4e7e2012-12-12 21:56:541781 // Add this cookie to the set of matching cookies. Update the access
[email protected]f48b9432011-01-11 07:25:401782 // time if we've been requested to do so.
1783 if (update_access_time) {
1784 InternalUpdateCookieAccessTime(cc, current);
1785 }
1786 cookies->push_back(cc);
1787 }
1788}
1789
1790bool CookieMonster::DeleteAnyEquivalentCookie(const std::string& key,
1791 const CanonicalCookie& ecc,
[email protected]e7c590e52011-03-30 08:33:551792 bool skip_httponly,
1793 bool already_expired) {
[email protected]f48b9432011-01-11 07:25:401794 lock_.AssertAcquired();
1795
1796 bool found_equivalent_cookie = false;
1797 bool skipped_httponly = false;
1798 for (CookieMapItPair its = cookies_.equal_range(key);
mkwstbe84af312015-02-20 08:52:451799 its.first != its.second;) {
[email protected]f48b9432011-01-11 07:25:401800 CookieMap::iterator curit = its.first;
1801 CanonicalCookie* cc = curit->second;
1802 ++its.first;
1803
1804 if (ecc.IsEquivalent(*cc)) {
1805 // We should never have more than one equivalent cookie, since they should
1806 // overwrite each other.
mkwstbe84af312015-02-20 08:52:451807 CHECK(!found_equivalent_cookie)
1808 << "Duplicate equivalent cookies found, cookie store is corrupted.";
[email protected]f48b9432011-01-11 07:25:401809 if (skip_httponly && cc->IsHttpOnly()) {
1810 skipped_httponly = true;
1811 } else {
mkwstbe84af312015-02-20 08:52:451812 InternalDeleteCookie(curit, true, already_expired
1813 ? DELETE_COOKIE_EXPIRED_OVERWRITE
1814 : DELETE_COOKIE_OVERWRITE);
[email protected]f48b9432011-01-11 07:25:401815 }
1816 found_equivalent_cookie = true;
1817 }
1818 }
1819 return skipped_httponly;
1820}
1821
[email protected]6210ce52013-09-20 03:33:141822CookieMonster::CookieMap::iterator CookieMonster::InternalInsertCookie(
1823 const std::string& key,
1824 CanonicalCookie* cc,
1825 bool sync_to_store) {
pkastinga9269aa42015-04-10 01:42:261826 // TODO(mkwst): Remove ScopedTracker below once crbug.com/456373 is fixed.
pkasting58e029b2015-02-21 05:17:281827 tracked_objects::ScopedTracker tracking_profile(
1828 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1829 "456373 CookieMonster::InternalInsertCookie"));
[email protected]f48b9432011-01-11 07:25:401830 lock_.AssertAcquired();
1831
[email protected]90499482013-06-01 00:39:501832 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() &&
1833 sync_to_store)
[email protected]f48b9432011-01-11 07:25:401834 store_->AddCookie(*cc);
[email protected]6210ce52013-09-20 03:33:141835 CookieMap::iterator inserted =
1836 cookies_.insert(CookieMap::value_type(key, cc));
[email protected]8bb846f2011-03-23 12:08:181837 if (delegate_.get()) {
mkwstbe84af312015-02-20 08:52:451838 delegate_->OnCookieChanged(*cc, false,
1839 CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT);
[email protected]8bb846f2011-03-23 12:08:181840 }
mkwstc1aa4cc2015-04-03 19:57:451841
1842 // See InitializeHistograms() for details.
estark7feb65c2b2015-08-21 23:38:201843 int32_t cookie_type_sample =
1844 cc->IsFirstPartyOnly() ? 1 << COOKIE_TYPE_FIRSTPARTYONLY : 0;
1845 cookie_type_sample |= cc->IsHttpOnly() ? 1 << COOKIE_TYPE_HTTPONLY : 0;
1846 cookie_type_sample |= cc->IsSecure() ? 1 << COOKIE_TYPE_SECURE : 0;
1847 histogram_cookie_type_->Add(cookie_type_sample);
1848
1849 // Histogram the type of scheme used on URLs that set cookies. This
1850 // intentionally includes cookies that are set or overwritten by
1851 // http:// URLs, but not cookies that are cleared by http:// URLs, to
1852 // understand if the former behavior can be deprecated for Secure
1853 // cookies.
1854 if (!cc->Source().is_empty()) {
1855 CookieSource cookie_source_sample;
1856 if (cc->Source().SchemeIsCryptographic()) {
1857 cookie_source_sample =
1858 cc->IsSecure() ? COOKIE_SOURCE_SECURE_COOKIE_CRYPTOGRAPHIC_SCHEME
1859 : COOKIE_SOURCE_NONSECURE_COOKIE_CRYPTOGRAPHIC_SCHEME;
1860 } else {
1861 cookie_source_sample =
1862 cc->IsSecure()
1863 ? COOKIE_SOURCE_SECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME
1864 : COOKIE_SOURCE_NONSECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME;
1865 }
1866 histogram_cookie_source_scheme_->Add(cookie_source_sample);
1867 }
mkwstc1aa4cc2015-04-03 19:57:451868
msarda0aad8f02014-10-30 09:22:391869 RunCallbacks(*cc, false);
[email protected]6210ce52013-09-20 03:33:141870
1871 return inserted;
[email protected]f48b9432011-01-11 07:25:401872}
1873
[email protected]34602282010-02-03 22:14:151874bool CookieMonster::SetCookieWithCreationTimeAndOptions(
1875 const GURL& url,
1876 const std::string& cookie_line,
1877 const Time& creation_time_or_null,
1878 const CookieOptions& options) {
[email protected]b866a02d2010-07-28 16:41:041879 lock_.AssertAcquired();
initial.commit586acc5fe2008-07-26 22:42:521880
[email protected]4d3ce782010-10-29 18:31:281881 VLOG(kVlogSetCookies) << "SetCookie() line: " << cookie_line;
initial.commit586acc5fe2008-07-26 22:42:521882
[email protected]34602282010-02-03 22:14:151883 Time creation_time = creation_time_or_null;
1884 if (creation_time.is_null()) {
1885 creation_time = CurrentTime();
1886 last_time_seen_ = creation_time;
1887 }
1888
[email protected]abbd13b2012-11-15 17:54:201889 scoped_ptr<CanonicalCookie> cc(
1890 CanonicalCookie::Create(url, cookie_line, creation_time, options));
initial.commit586acc5fe2008-07-26 22:42:521891
1892 if (!cc.get()) {
[email protected]4d3ce782010-10-29 18:31:281893 VLOG(kVlogSetCookies) << "WARNING: Failed to allocate CanonicalCookie";
initial.commit586acc5fe2008-07-26 22:42:521894 return false;
1895 }
[email protected]fa77eb512010-07-22 16:12:511896 return SetCanonicalCookie(&cc, creation_time, options);
[email protected]f325f1e12010-04-30 22:38:551897}
initial.commit586acc5fe2008-07-26 22:42:521898
[email protected]f325f1e12010-04-30 22:38:551899bool CookieMonster::SetCanonicalCookie(scoped_ptr<CanonicalCookie>* cc,
[email protected]f325f1e12010-04-30 22:38:551900 const Time& creation_time,
1901 const CookieOptions& options) {
[email protected]7a964a72010-09-07 19:33:261902 const std::string key(GetKey((*cc)->Domain()));
[email protected]e7c590e52011-03-30 08:33:551903 bool already_expired = (*cc)->IsExpired(creation_time);
ellyjones399e35a22014-10-27 11:09:561904
estarkcd39c11f2015-10-19 19:46:361905 if (options.enforce_prefixes() && !CheckCookiePrefix(cc->get(), options)) {
1906 VLOG(kVlogSetCookies) << "SetCookie() not storing cookie '" << (*cc)->Name()
1907 << "' that violates prefix rules.";
1908 return false;
1909 }
1910
[email protected]e7c590e52011-03-30 08:33:551911 if (DeleteAnyEquivalentCookie(key, **cc, options.exclude_httponly(),
1912 already_expired)) {
[email protected]4d3ce782010-10-29 18:31:281913 VLOG(kVlogSetCookies) << "SetCookie() not clobbering httponly cookie";
[email protected]3a96c742008-11-19 19:46:271914 return false;
1915 }
initial.commit586acc5fe2008-07-26 22:42:521916
mkwstbe84af312015-02-20 08:52:451917 VLOG(kVlogSetCookies) << "SetCookie() key: " << key
1918 << " cc: " << (*cc)->DebugString();
initial.commit586acc5fe2008-07-26 22:42:521919
1920 // Realize that we might be setting an expired cookie, and the only point
1921 // was to delete the cookie which we've already done.
[email protected]e7c590e52011-03-30 08:33:551922 if (!already_expired || keep_expired_cookies_) {
[email protected]374f58b2010-07-20 15:29:261923 // See InitializeHistograms() for details.
[email protected]10b691f2012-07-11 15:22:151924 if ((*cc)->IsPersistent()) {
[email protected]8475bee2011-03-17 18:40:241925 histogram_expiration_duration_minutes_->Add(
1926 ((*cc)->ExpiryDate() - creation_time).InMinutes());
1927 }
1928
ellyjones399e35a22014-10-27 11:09:561929 {
1930 CanonicalCookie cookie = *(cc->get());
1931 InternalInsertCookie(key, cc->release(), true);
ellyjones399e35a22014-10-27 11:09:561932 }
[email protected]348dd662013-03-13 20:25:071933 } else {
1934 VLOG(kVlogSetCookies) << "SetCookie() not storing already expired cookie.";
[email protected]c4058fb2010-06-22 17:25:261935 }
initial.commit586acc5fe2008-07-26 22:42:521936
1937 // We assume that hopefully setting a cookie will be less common than
1938 // querying a cookie. Since setting a cookie can put us over our limits,
1939 // make sure that we garbage collect... We can also make the assumption that
1940 // if a cookie was set, in the common case it will be used soon after,
1941 // and we will purge the expired cookies in GetCookies().
[email protected]7a964a72010-09-07 19:33:261942 GarbageCollect(creation_time, key);
initial.commit586acc5fe2008-07-26 22:42:521943
1944 return true;
1945}
1946
drogerd5d1278c2015-03-17 19:21:511947bool CookieMonster::SetCanonicalCookies(const CookieList& list) {
1948 base::AutoLock autolock(lock_);
1949
ttuttle859dc7a2015-04-23 19:42:291950 CookieOptions options;
drogerd5d1278c2015-03-17 19:21:511951 options.set_include_httponly();
1952
1953 for (CookieList::const_iterator it = list.begin(); it != list.end(); ++it) {
1954 scoped_ptr<CanonicalCookie> canonical_cookie(new CanonicalCookie(*it));
1955 if (!SetCanonicalCookie(&canonical_cookie, it->CreationDate(), options))
1956 return false;
1957 }
1958
1959 return true;
1960}
1961
[email protected]7a964a72010-09-07 19:33:261962void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie* cc,
1963 const Time& current) {
[email protected]bb8905722010-05-21 17:29:041964 lock_.AssertAcquired();
1965
[email protected]77e0a462008-11-01 00:43:351966 // Based off the Mozilla code. When a cookie has been accessed recently,
1967 // don't bother updating its access time again. This reduces the number of
1968 // updates we do during pageload, which in turn reduces the chance our storage
1969 // backend will hit its batch thresholds and be forced to update.
[email protected]77e0a462008-11-01 00:43:351970 if ((current - cc->LastAccessDate()) < last_access_threshold_)
1971 return;
1972
1973 cc->SetLastAccessDate(current);
[email protected]90499482013-06-01 00:39:501974 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get())
[email protected]77e0a462008-11-01 00:43:351975 store_->UpdateCookieAccessTime(*cc);
1976}
1977
[email protected]6210ce52013-09-20 03:33:141978// InternalDeleteCookies must not invalidate iterators other than the one being
1979// deleted.
initial.commit586acc5fe2008-07-26 22:42:521980void CookieMonster::InternalDeleteCookie(CookieMap::iterator it,
[email protected]c4058fb2010-06-22 17:25:261981 bool sync_to_store,
1982 DeletionCause deletion_cause) {
[email protected]bb8905722010-05-21 17:29:041983 lock_.AssertAcquired();
1984
[email protected]8bb846f2011-03-23 12:08:181985 // Ideally, this would be asserted up where we define ChangeCauseMapping,
1986 // but DeletionCause's visibility (or lack thereof) forces us to make
1987 // this check here.
mostynb91e0da982015-01-20 19:17:271988 static_assert(arraysize(ChangeCauseMapping) == DELETE_COOKIE_LAST_ENTRY + 1,
1989 "ChangeCauseMapping size should match DeletionCause size");
[email protected]8bb846f2011-03-23 12:08:181990
[email protected]374f58b2010-07-20 15:29:261991 // See InitializeHistograms() for details.
[email protected]7a964a72010-09-07 19:33:261992 if (deletion_cause != DELETE_COOKIE_DONT_RECORD)
1993 histogram_cookie_deletion_cause_->Add(deletion_cause);
[email protected]c4058fb2010-06-22 17:25:261994
initial.commit586acc5fe2008-07-26 22:42:521995 CanonicalCookie* cc = it->second;
xiyuan8dbb89892015-04-13 17:04:301996 VLOG(kVlogSetCookies) << "InternalDeleteCookie()"
1997 << ", cause:" << deletion_cause
1998 << ", cc: " << cc->DebugString();
[email protected]7a964a72010-09-07 19:33:261999
[email protected]90499482013-06-01 00:39:502000 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() &&
2001 sync_to_store)
initial.commit586acc5fe2008-07-26 22:42:522002 store_->DeleteCookie(*cc);
[email protected]8bb846f2011-03-23 12:08:182003 if (delegate_.get()) {
2004 ChangeCausePair mapping = ChangeCauseMapping[deletion_cause];
2005
2006 if (mapping.notify)
2007 delegate_->OnCookieChanged(*cc, true, mapping.cause);
2008 }
msarda0aad8f02014-10-30 09:22:392009 RunCallbacks(*cc, true);
initial.commit586acc5fe2008-07-26 22:42:522010 cookies_.erase(it);
2011 delete cc;
2012}
2013
[email protected]8807b322010-10-01 17:10:142014// Domain expiry behavior is unchanged by key/expiry scheme (the
[email protected]8ad5d462013-05-02 08:45:262015// meaning of the key is different, but that's not visible to this routine).
mkwstbe84af312015-02-20 08:52:452016int CookieMonster::GarbageCollect(const Time& current, const std::string& key) {
[email protected]bb8905722010-05-21 17:29:042017 lock_.AssertAcquired();
2018
initial.commit586acc5fe2008-07-26 22:42:522019 int num_deleted = 0;
mkwstbe84af312015-02-20 08:52:452020 Time safe_date(Time::Now() - TimeDelta::FromDays(kSafeFromGlobalPurgeDays));
initial.commit586acc5fe2008-07-26 22:42:522021
[email protected]8ad5d462013-05-02 08:45:262022 // Collect garbage for this key, minding cookie priorities.
[email protected]7a964a72010-09-07 19:33:262023 if (cookies_.count(key) > kDomainMaxCookies) {
[email protected]4d3ce782010-10-29 18:31:282024 VLOG(kVlogGarbageCollection) << "GarbageCollect() key: " << key;
[email protected]7a964a72010-09-07 19:33:262025
[email protected]8ad5d462013-05-02 08:45:262026 CookieItVector cookie_its;
mkwstbe84af312015-02-20 08:52:452027 num_deleted +=
2028 GarbageCollectExpired(current, cookies_.equal_range(key), &cookie_its);
[email protected]8ad5d462013-05-02 08:45:262029 if (cookie_its.size() > kDomainMaxCookies) {
2030 VLOG(kVlogGarbageCollection) << "Deep Garbage Collect domain.";
2031 size_t purge_goal =
2032 cookie_its.size() - (kDomainMaxCookies - kDomainPurgeCookies);
2033 DCHECK(purge_goal > kDomainPurgeCookies);
2034
2035 // Boundary iterators into |cookie_its| for different priorities.
2036 CookieItVector::iterator it_bdd[4];
2037 // Intialize |it_bdd| while sorting |cookie_its| by priorities.
2038 // Schematic: [MLLHMHHLMM] => [LLL|MMMM|HHH], with 4 boundaries.
2039 it_bdd[0] = cookie_its.begin();
2040 it_bdd[3] = cookie_its.end();
mkwstbe84af312015-02-20 08:52:452041 it_bdd[1] =
2042 PartitionCookieByPriority(it_bdd[0], it_bdd[3], COOKIE_PRIORITY_LOW);
[email protected]8ad5d462013-05-02 08:45:262043 it_bdd[2] = PartitionCookieByPriority(it_bdd[1], it_bdd[3],
2044 COOKIE_PRIORITY_MEDIUM);
mkwstbe84af312015-02-20 08:52:452045 size_t quota[3] = {kDomainCookiesQuotaLow,
2046 kDomainCookiesQuotaMedium,
2047 kDomainCookiesQuotaHigh};
[email protected]8ad5d462013-05-02 08:45:262048
2049 // Purge domain cookies in 3 rounds.
2050 // Round 1: consider low-priority cookies only: evict least-recently
2051 // accessed, while protecting quota[0] of these from deletion.
2052 // Round 2: consider {low, medium}-priority cookies, evict least-recently
2053 // accessed, while protecting quota[0] + quota[1].
2054 // Round 3: consider all cookies, evict least-recently accessed.
2055 size_t accumulated_quota = 0;
2056 CookieItVector::iterator it_purge_begin = it_bdd[0];
2057 for (int i = 0; i < 3 && purge_goal > 0; ++i) {
2058 accumulated_quota += quota[i];
2059
[email protected]8ad5d462013-05-02 08:45:262060 size_t num_considered = it_bdd[i + 1] - it_purge_begin;
2061 if (num_considered <= accumulated_quota)
2062 continue;
2063
2064 // Number of cookies that will be purged in this round.
2065 size_t round_goal =
2066 std::min(purge_goal, num_considered - accumulated_quota);
2067 purge_goal -= round_goal;
2068
2069 SortLeastRecentlyAccessed(it_purge_begin, it_bdd[i + 1], round_goal);
2070 // Cookies accessed on or after |safe_date| would have been safe from
2071 // global purge, and we want to keep track of this.
2072 CookieItVector::iterator it_purge_end = it_purge_begin + round_goal;
2073 CookieItVector::iterator it_purge_middle =
2074 LowerBoundAccessDate(it_purge_begin, it_purge_end, safe_date);
2075 // Delete cookies accessed before |safe_date|.
2076 num_deleted += GarbageCollectDeleteRange(
mkwstbe84af312015-02-20 08:52:452077 current, DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE, it_purge_begin,
[email protected]8ad5d462013-05-02 08:45:262078 it_purge_middle);
2079 // Delete cookies accessed on or after |safe_date|.
2080 num_deleted += GarbageCollectDeleteRange(
mkwstbe84af312015-02-20 08:52:452081 current, DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE, it_purge_middle,
[email protected]8ad5d462013-05-02 08:45:262082 it_purge_end);
2083 it_purge_begin = it_purge_end;
2084 }
2085 DCHECK_EQ(0U, purge_goal);
[email protected]8807b322010-10-01 17:10:142086 }
initial.commit586acc5fe2008-07-26 22:42:522087 }
2088
[email protected]8ad5d462013-05-02 08:45:262089 // Collect garbage for everything. With firefox style we want to preserve
2090 // cookies accessed in kSafeFromGlobalPurgeDays, otherwise evict.
mkwstbe84af312015-02-20 08:52:452091 if (cookies_.size() > kMaxCookies && earliest_access_time_ < safe_date) {
[email protected]4d3ce782010-10-29 18:31:282092 VLOG(kVlogGarbageCollection) << "GarbageCollect() everything";
[email protected]8ad5d462013-05-02 08:45:262093 CookieItVector cookie_its;
[email protected]7a964a72010-09-07 19:33:262094 num_deleted += GarbageCollectExpired(
2095 current, CookieMapItPair(cookies_.begin(), cookies_.end()),
2096 &cookie_its);
[email protected]8ad5d462013-05-02 08:45:262097 if (cookie_its.size() > kMaxCookies) {
2098 VLOG(kVlogGarbageCollection) << "Deep Garbage Collect everything.";
2099 size_t purge_goal = cookie_its.size() - (kMaxCookies - kPurgeCookies);
2100 DCHECK(purge_goal > kPurgeCookies);
2101 // Sorts up to *and including* |cookie_its[purge_goal]|, so
2102 // |earliest_access_time| will be properly assigned even if
2103 // |global_purge_it| == |cookie_its.begin() + purge_goal|.
2104 SortLeastRecentlyAccessed(cookie_its.begin(), cookie_its.end(),
2105 purge_goal);
2106 // Find boundary to cookies older than safe_date.
mkwstbe84af312015-02-20 08:52:452107 CookieItVector::iterator global_purge_it = LowerBoundAccessDate(
2108 cookie_its.begin(), cookie_its.begin() + purge_goal, safe_date);
[email protected]8ad5d462013-05-02 08:45:262109 // Only delete the old cookies.
mkwstbe84af312015-02-20 08:52:452110 num_deleted +=
2111 GarbageCollectDeleteRange(current, DELETE_COOKIE_EVICTED_GLOBAL,
2112 cookie_its.begin(), global_purge_it);
[email protected]8ad5d462013-05-02 08:45:262113 // Set access day to the oldest cookie that wasn't deleted.
2114 earliest_access_time_ = (*global_purge_it)->second->LastAccessDate();
[email protected]8807b322010-10-01 17:10:142115 }
[email protected]c890ed192008-10-30 23:45:532116 }
2117
2118 return num_deleted;
2119}
2120
mkwstbe84af312015-02-20 08:52:452121int CookieMonster::GarbageCollectExpired(const Time& current,
2122 const CookieMapItPair& itpair,
2123 CookieItVector* cookie_its) {
[email protected]ba4ad0e2011-03-15 08:12:472124 if (keep_expired_cookies_)
2125 return 0;
2126
[email protected]bb8905722010-05-21 17:29:042127 lock_.AssertAcquired();
2128
[email protected]c890ed192008-10-30 23:45:532129 int num_deleted = 0;
2130 for (CookieMap::iterator it = itpair.first, end = itpair.second; it != end;) {
2131 CookieMap::iterator curit = it;
2132 ++it;
2133
2134 if (curit->second->IsExpired(current)) {
[email protected]2f3f3592010-07-07 20:11:512135 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
[email protected]c890ed192008-10-30 23:45:532136 ++num_deleted;
2137 } else if (cookie_its) {
2138 cookie_its->push_back(curit);
2139 }
initial.commit586acc5fe2008-07-26 22:42:522140 }
2141
2142 return num_deleted;
2143}
2144
mkwstbe84af312015-02-20 08:52:452145int CookieMonster::GarbageCollectDeleteRange(const Time& current,
2146 DeletionCause cause,
2147 CookieItVector::iterator it_begin,
2148 CookieItVector::iterator it_end) {
[email protected]8ad5d462013-05-02 08:45:262149 for (CookieItVector::iterator it = it_begin; it != it_end; it++) {
2150 histogram_evicted_last_access_minutes_->Add(
2151 (current - (*it)->second->LastAccessDate()).InMinutes());
2152 InternalDeleteCookie((*it), true, cause);
[email protected]c10da4b02010-03-25 14:38:322153 }
[email protected]8ad5d462013-05-02 08:45:262154 return it_end - it_begin;
[email protected]c10da4b02010-03-25 14:38:322155}
2156
[email protected]ed32c212013-05-14 20:49:292157// A wrapper around registry_controlled_domains::GetDomainAndRegistry
[email protected]f48b9432011-01-11 07:25:402158// to make clear we're creating a key for our local map. Here and
2159// in FindCookiesForHostAndDomain() are the only two places where
2160// we need to conditionalize based on key type.
2161//
2162// Note that this key algorithm explicitly ignores the scheme. This is
2163// because when we're entering cookies into the map from the backing store,
2164// we in general won't have the scheme at that point.
2165// In practical terms, this means that file cookies will be stored
2166// in the map either by an empty string or by UNC name (and will be
2167// limited by kMaxCookiesPerHost), and extension cookies will be stored
2168// based on the single extension id, as the extension id won't have the
2169// form of a DNS host and hence GetKey() will return it unchanged.
2170//
2171// Arguably the right thing to do here is to make the key
2172// algorithm dependent on the scheme, and make sure that the scheme is
2173// available everywhere the key must be obtained (specfically at backing
2174// store load time). This would require either changing the backing store
2175// database schema to include the scheme (far more trouble than it's worth), or
2176// separating out file cookies into their own CookieMonster instance and
2177// thus restricting each scheme to a single cookie monster (which might
2178// be worth it, but is still too much trouble to solve what is currently a
2179// non-problem).
2180std::string CookieMonster::GetKey(const std::string& domain) const {
[email protected]f48b9432011-01-11 07:25:402181 std::string effective_domain(
[email protected]ed32c212013-05-14 20:49:292182 registry_controlled_domains::GetDomainAndRegistry(
[email protected]aabe1792014-01-30 21:37:462183 domain, registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES));
[email protected]f48b9432011-01-11 07:25:402184 if (effective_domain.empty())
2185 effective_domain = domain;
2186
2187 if (!effective_domain.empty() && effective_domain[0] == '.')
2188 return effective_domain.substr(1);
2189 return effective_domain;
2190}
2191
[email protected]97a3b6e2012-06-12 01:53:562192bool CookieMonster::IsCookieableScheme(const std::string& scheme) {
2193 base::AutoLock autolock(lock_);
2194
2195 return std::find(cookieable_schemes_.begin(), cookieable_schemes_.end(),
2196 scheme) != cookieable_schemes_.end();
2197}
2198
[email protected]f48b9432011-01-11 07:25:402199bool CookieMonster::HasCookieableScheme(const GURL& url) {
2200 lock_.AssertAcquired();
2201
2202 // Make sure the request is on a cookie-able url scheme.
2203 for (size_t i = 0; i < cookieable_schemes_.size(); ++i) {
2204 // We matched a scheme.
2205 if (url.SchemeIs(cookieable_schemes_[i].c_str())) {
2206 // We've matched a supported scheme.
initial.commit586acc5fe2008-07-26 22:42:522207 return true;
2208 }
2209 }
[email protected]f48b9432011-01-11 07:25:402210
2211 // The scheme didn't match any in our whitelist.
mkwstbe84af312015-02-20 08:52:452212 VLOG(kVlogPerCookieMonster)
2213 << "WARNING: Unsupported cookie scheme: " << url.scheme();
initial.commit586acc5fe2008-07-26 22:42:522214 return false;
2215}
2216
[email protected]c4058fb2010-06-22 17:25:262217// Test to see if stats should be recorded, and record them if so.
2218// The goal here is to get sampling for the average browser-hour of
2219// activity. We won't take samples when the web isn't being surfed,
2220// and when the web is being surfed, we'll take samples about every
2221// kRecordStatisticsIntervalSeconds.
2222// last_statistic_record_time_ is initialized to Now() rather than null
2223// in the constructor so that we won't take statistics right after
2224// startup, to avoid bias from browsers that are started but not used.
2225void CookieMonster::RecordPeriodicStats(const base::Time& current_time) {
2226 const base::TimeDelta kRecordStatisticsIntervalTime(
2227 base::TimeDelta::FromSeconds(kRecordStatisticsIntervalSeconds));
2228
[email protected]7a964a72010-09-07 19:33:262229 // If we've taken statistics recently, return.
2230 if (current_time - last_statistic_record_time_ <=
[email protected]c4058fb2010-06-22 17:25:262231 kRecordStatisticsIntervalTime) {
[email protected]7a964a72010-09-07 19:33:262232 return;
[email protected]c4058fb2010-06-22 17:25:262233 }
[email protected]7a964a72010-09-07 19:33:262234
2235 // See InitializeHistograms() for details.
2236 histogram_count_->Add(cookies_.size());
2237
2238 // More detailed statistics on cookie counts at different granularities.
[email protected]7a964a72010-09-07 19:33:262239 last_statistic_record_time_ = current_time;
[email protected]c4058fb2010-06-22 17:25:262240}
2241
[email protected]f48b9432011-01-11 07:25:402242// Initialize all histogram counter variables used in this class.
2243//
2244// Normal histogram usage involves using the macros defined in
2245// histogram.h, which automatically takes care of declaring these
2246// variables (as statics), initializing them, and accumulating into
2247// them, all from a single entry point. Unfortunately, that solution
2248// doesn't work for the CookieMonster, as it's vulnerable to races between
2249// separate threads executing the same functions and hence initializing the
2250// same static variables. There isn't a race danger in the histogram
2251// accumulation calls; they are written to be resilient to simultaneous
2252// calls from multiple threads.
2253//
2254// The solution taken here is to have per-CookieMonster instance
2255// variables that are constructed during CookieMonster construction.
2256// Note that these variables refer to the same underlying histogram,
2257// so we still race (but safely) with other CookieMonster instances
2258// for accumulation.
2259//
2260// To do this we've expanded out the individual histogram macros calls,
2261// with declarations of the variables in the class decl, initialization here
2262// (done from the class constructor) and direct calls to the accumulation
2263// methods where needed. The specific histogram macro calls on which the
2264// initialization is based are included in comments below.
2265void CookieMonster::InitializeHistograms() {
2266 // From UMA_HISTOGRAM_CUSTOM_COUNTS
2267 histogram_expiration_duration_minutes_ = base::Histogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452268 "Cookie.ExpirationDurationMinutes", 1, kMinutesInTenYears, 50,
[email protected]f48b9432011-01-11 07:25:402269 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]f48b9432011-01-11 07:25:402270 histogram_evicted_last_access_minutes_ = base::Histogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452271 "Cookie.EvictedLastAccessMinutes", 1, kMinutesInTenYears, 50,
[email protected]f48b9432011-01-11 07:25:402272 base::Histogram::kUmaTargetedHistogramFlag);
2273 histogram_count_ = base::Histogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452274 "Cookie.Count", 1, 4000, 50, base::Histogram::kUmaTargetedHistogramFlag);
[email protected]f48b9432011-01-11 07:25:402275
2276 // From UMA_HISTOGRAM_ENUMERATION
2277 histogram_cookie_deletion_cause_ = base::LinearHistogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452278 "Cookie.DeletionCause", 1, DELETE_COOKIE_LAST_ENTRY - 1,
2279 DELETE_COOKIE_LAST_ENTRY, base::Histogram::kUmaTargetedHistogramFlag);
mkwstc1aa4cc2015-04-03 19:57:452280 histogram_cookie_type_ = base::LinearHistogram::FactoryGet(
mkwst87378d92015-04-10 21:22:112281 "Cookie.Type", 1, (1 << COOKIE_TYPE_LAST_ENTRY) - 1,
2282 1 << COOKIE_TYPE_LAST_ENTRY, base::Histogram::kUmaTargetedHistogramFlag);
estark7feb65c2b2015-08-21 23:38:202283 histogram_cookie_source_scheme_ = base::LinearHistogram::FactoryGet(
2284 "Cookie.CookieSourceScheme", 1, COOKIE_SOURCE_LAST_ENTRY - 1,
2285 COOKIE_SOURCE_LAST_ENTRY, base::Histogram::kUmaTargetedHistogramFlag);
[email protected]f48b9432011-01-11 07:25:402286
2287 // From UMA_HISTOGRAM_{CUSTOM_,}TIMES
[email protected]c7593fb22011-11-14 23:54:272288 histogram_time_blocked_on_load_ = base::Histogram::FactoryTimeGet(
mkwstbe84af312015-02-20 08:52:452289 "Cookie.TimeBlockedOnLoad", base::TimeDelta::FromMilliseconds(1),
2290 base::TimeDelta::FromMinutes(1), 50,
2291 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]f48b9432011-01-11 07:25:402292}
2293
[email protected]f48b9432011-01-11 07:25:402294// The system resolution is not high enough, so we can have multiple
2295// set cookies that result in the same system time. When this happens, we
2296// increment by one Time unit. Let's hope computers don't get too fast.
2297Time CookieMonster::CurrentTime() {
mkwstbe84af312015-02-20 08:52:452298 return std::max(Time::Now(), Time::FromInternalValue(
2299 last_time_seen_.ToInternalValue() + 1));
[email protected]f48b9432011-01-11 07:25:402300}
2301
drogerd5d1278c2015-03-17 19:21:512302void CookieMonster::ComputeCookieDiff(CookieList* old_cookies,
2303 CookieList* new_cookies,
2304 CookieList* cookies_to_add,
2305 CookieList* cookies_to_delete) {
2306 DCHECK(old_cookies);
2307 DCHECK(new_cookies);
2308 DCHECK(cookies_to_add);
2309 DCHECK(cookies_to_delete);
2310 DCHECK(cookies_to_add->empty());
2311 DCHECK(cookies_to_delete->empty());
2312
2313 // Sort both lists.
2314 // A set ordered by FullDiffCookieSorter is also ordered by
2315 // PartialDiffCookieSorter.
2316 std::sort(old_cookies->begin(), old_cookies->end(), FullDiffCookieSorter);
2317 std::sort(new_cookies->begin(), new_cookies->end(), FullDiffCookieSorter);
2318
2319 // Select any old cookie for deletion if no new cookie has the same name,
2320 // domain, and path.
2321 std::set_difference(
2322 old_cookies->begin(), old_cookies->end(), new_cookies->begin(),
2323 new_cookies->end(),
2324 std::inserter(*cookies_to_delete, cookies_to_delete->begin()),
2325 PartialDiffCookieSorter);
2326
2327 // Select any new cookie for addition (or update) if no old cookie is exactly
2328 // equivalent.
2329 std::set_difference(new_cookies->begin(), new_cookies->end(),
2330 old_cookies->begin(), old_cookies->end(),
2331 std::inserter(*cookies_to_add, cookies_to_add->begin()),
2332 FullDiffCookieSorter);
2333}
2334
ellyjones399e35a22014-10-27 11:09:562335scoped_ptr<CookieStore::CookieChangedSubscription>
mkwstbe84af312015-02-20 08:52:452336CookieMonster::AddCallbackForCookie(const GURL& gurl,
2337 const std::string& name,
2338 const CookieChangedCallback& callback) {
ellyjones399e35a22014-10-27 11:09:562339 base::AutoLock autolock(lock_);
2340 std::pair<GURL, std::string> key(gurl, name);
2341 if (hook_map_.count(key) == 0)
2342 hook_map_[key] = make_linked_ptr(new CookieChangedCallbackList());
msarda0aad8f02014-10-30 09:22:392343 return hook_map_[key]->Add(
anujk.sharmaafc45172015-05-15 00:50:342344 base::Bind(&RunAsync, base::ThreadTaskRunnerHandle::Get(), callback));
ellyjones399e35a22014-10-27 11:09:562345}
2346
mkwstb73bf8aa2015-03-31 07:33:452347#if defined(OS_ANDROID)
2348void CookieMonster::SetEnableFileScheme(bool accept) {
2349 // This assumes "file" is always at the end of the array. See the comment
2350 // above kDefaultCookieableSchemes.
2351 //
2352 // TODO(mkwst): We're keeping this method around to support the
2353 // 'CookieManager::setAcceptFileSchemeCookies' method on Android's WebView;
2354 // if/when we can deprecate and remove that method, we can remove this one
2355 // as well. Until then, we'll just ensure that the method has no effect on
2356 // non-android systems.
2357 int num_schemes = accept ? kDefaultCookieableSchemesCount
2358 : kDefaultCookieableSchemesCount - 1;
2359
2360 SetCookieableSchemes(kDefaultCookieableSchemes, num_schemes);
2361}
2362#endif
2363
msarda0aad8f02014-10-30 09:22:392364void CookieMonster::RunCallbacks(const CanonicalCookie& cookie, bool removed) {
ellyjones399e35a22014-10-27 11:09:562365 lock_.AssertAcquired();
2366 CookieOptions opts;
2367 opts.set_include_httponly();
mkwstae819bb2015-02-23 05:10:312368 opts.set_include_first_party_only();
ellyjones399e35a22014-10-27 11:09:562369 // Note that the callbacks in hook_map_ are wrapped with MakeAsync(), so they
2370 // are guaranteed to not take long - they just post a RunAsync task back to
2371 // the appropriate thread's message loop and return. It is important that this
2372 // method not run user-supplied callbacks directly, since the CookieMonster
2373 // lock is held and it is easy to accidentally introduce deadlocks.
2374 for (CookieChangedHookMap::iterator it = hook_map_.begin();
2375 it != hook_map_.end(); ++it) {
2376 std::pair<GURL, std::string> key = it->first;
2377 if (cookie.IncludeForRequestURL(key.first, opts) &&
2378 cookie.Name() == key.second) {
msarda0aad8f02014-10-30 09:22:392379 it->second->Notify(cookie, removed);
ellyjones399e35a22014-10-27 11:09:562380 }
2381 }
2382}
2383
[email protected]63725312012-07-19 08:24:162384} // namespace net