blob: d335ae41046f5c6f971bf4c56beea57d7fbc5c31 [file] [log] [blame]
[email protected]8e1583672012-02-11 04:39:411// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit586acc5fe2008-07-26 22:42:524
5// Portions of this code based on Mozilla:
6// (netwerk/cookie/src/nsCookieService.cpp)
7/* ***** BEGIN LICENSE BLOCK *****
8 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
9 *
10 * The contents of this file are subject to the Mozilla Public License Version
11 * 1.1 (the "License"); you may not use this file except in compliance with
12 * the License. You may obtain a copy of the License at
13 * http://www.mozilla.org/MPL/
14 *
15 * Software distributed under the License is distributed on an "AS IS" basis,
16 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
17 * for the specific language governing rights and limitations under the
18 * License.
19 *
20 * The Original Code is mozilla.org code.
21 *
22 * The Initial Developer of the Original Code is
23 * Netscape Communications Corporation.
24 * Portions created by the Initial Developer are Copyright (C) 2003
25 * the Initial Developer. All Rights Reserved.
26 *
27 * Contributor(s):
28 * Daniel Witte ([email protected])
29 * Michiel van Leeuwen ([email protected])
30 *
31 * Alternatively, the contents of this file may be used under the terms of
32 * either the GNU General Public License Version 2 or later (the "GPL"), or
33 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
34 * in which case the provisions of the GPL or the LGPL are applicable instead
35 * of those above. If you wish to allow use of your version of this file only
36 * under the terms of either the GPL or the LGPL, and not to allow others to
37 * use your version of this file under the terms of the MPL, indicate your
38 * decision by deleting the provisions above and replace them with the notice
39 * and other provisions required by the GPL or the LGPL. If you do not delete
40 * the provisions above, a recipient may use your version of this file under
41 * the terms of any one of the MPL, the GPL or the LGPL.
42 *
43 * ***** END LICENSE BLOCK ***** */
44
[email protected]63ee33bd2012-03-15 09:29:5845#include "net/cookies/cookie_monster.h"
initial.commit586acc5fe2008-07-26 22:42:5246
47#include <algorithm>
[email protected]8ad5d462013-05-02 08:45:2648#include <functional>
[email protected]09666482011-07-12 12:50:4049#include <set>
initial.commit586acc5fe2008-07-26 22:42:5250
51#include "base/basictypes.h"
[email protected]218aa6a12011-09-13 17:38:3852#include "base/bind.h"
[email protected]8562034e2011-10-17 17:35:0453#include "base/callback.h"
initial.commit586acc5fe2008-07-26 22:42:5254#include "base/logging.h"
[email protected]3b63f8f42011-03-28 01:54:1555#include "base/memory/scoped_ptr.h"
[email protected]5ee20982013-07-17 21:51:1856#include "base/message_loop/message_loop.h"
[email protected]7ccb7072013-06-10 20:56:2857#include "base/message_loop/message_loop_proxy.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"
[email protected]4b355212013-06-11 10:35:1960#include "base/strings/string_util.h"
61#include "base/strings/stringprintf.h"
[email protected]be28b5f42012-07-20 11:31:2562#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
[email protected]4b355212013-06-11 10:35:1963#include "net/cookies/canonical_cookie.h"
[email protected]63ee33bd2012-03-15 09:29:5864#include "net/cookies/cookie_util.h"
[email protected]ebfe3172012-07-12 12:21:4165#include "net/cookies/parsed_cookie.h"
initial.commit586acc5fe2008-07-26 22:42:5266
[email protected]e1acf6f2008-10-27 20:43:3367using base::Time;
68using base::TimeDelta;
[email protected]7a964a72010-09-07 19:33:2669using base::TimeTicks;
[email protected]e1acf6f2008-10-27 20:43:3370
[email protected]8562034e2011-10-17 17:35:0471// In steady state, most cookie requests can be satisfied by the in memory
72// cookie monster store. However, if a request comes in during the initial
73// cookie load, it must be delayed until that load completes. That is done by
[email protected]0184df32013-05-14 00:53:5574// queueing it on CookieMonster::tasks_pending_ and running it when notification
75// of cookie load completion is received via CookieMonster::OnLoaded. This
76// callback is passed to the persistent store from CookieMonster::InitStore(),
77// which is called on the first operation invoked on the CookieMonster.
[email protected]8562034e2011-10-17 17:35:0478//
79// On the browser critical paths (e.g. for loading initial web pages in a
80// session restore) it may take too long to wait for the full load. If a cookie
81// request is for a specific URL, DoCookieTaskForURL is called, which triggers a
82// priority load if the key is not loaded yet by calling PersistentCookieStore
[email protected]0184df32013-05-14 00:53:5583// :: LoadCookiesForKey. The request is queued in
84// CookieMonster::tasks_pending_for_key_ and executed upon receiving
85// notification of key load completion via CookieMonster::OnKeyLoaded(). If
86// multiple requests for the same eTLD+1 are received before key load
87// completion, only the first request calls
[email protected]8562034e2011-10-17 17:35:0488// PersistentCookieStore::LoadCookiesForKey, all subsequent requests are queued
[email protected]0184df32013-05-14 00:53:5589// in CookieMonster::tasks_pending_for_key_ and executed upon receiving
90// notification of key load completion triggered by the first request for the
91// same eTLD+1.
[email protected]8562034e2011-10-17 17:35:0492
[email protected]c4058fb2010-06-22 17:25:2693static const int kMinutesInTenYears = 10 * 365 * 24 * 60;
94
[email protected]8ac1a752008-07-31 19:40:3795namespace net {
96
[email protected]7a964a72010-09-07 19:33:2697// See comments at declaration of these variables in cookie_monster.h
98// for details.
mkwstbe84af312015-02-20 08:52:4599const size_t CookieMonster::kDomainMaxCookies = 180;
100const size_t CookieMonster::kDomainPurgeCookies = 30;
101const size_t CookieMonster::kMaxCookies = 3300;
102const size_t CookieMonster::kPurgeCookies = 300;
[email protected]8ad5d462013-05-02 08:45:26103
mkwstbe84af312015-02-20 08:52:45104const size_t CookieMonster::kDomainCookiesQuotaLow = 30;
[email protected]8ad5d462013-05-02 08:45:26105const size_t CookieMonster::kDomainCookiesQuotaMedium = 50;
mkwstbe84af312015-02-20 08:52:45106const size_t CookieMonster::kDomainCookiesQuotaHigh =
107 kDomainMaxCookies - kDomainPurgeCookies - kDomainCookiesQuotaLow -
108 kDomainCookiesQuotaMedium;
[email protected]8ad5d462013-05-02 08:45:26109
mkwstbe84af312015-02-20 08:52:45110const int CookieMonster::kSafeFromGlobalPurgeDays = 30;
[email protected]297a4ed02010-02-12 08:12:52111
[email protected]7a964a72010-09-07 19:33:26112namespace {
[email protected]e32306c52008-11-06 16:59:05113
[email protected]6210ce52013-09-20 03:33:14114bool ContainsControlCharacter(const std::string& s) {
115 for (std::string::const_iterator i = s.begin(); i != s.end(); ++i) {
116 if ((*i >= 0) && (*i <= 31))
117 return true;
118 }
119
120 return false;
121}
122
[email protected]5b9bc352012-07-18 13:13:34123typedef std::vector<CanonicalCookie*> CanonicalCookieVector;
[email protected]34a160d2011-05-12 22:12:49124
[email protected]77e0a462008-11-01 00:43:35125// Default minimum delay after updating a cookie's LastAccessDate before we
126// will update it again.
[email protected]297a4ed02010-02-12 08:12:52127const int kDefaultAccessUpdateThresholdSeconds = 60;
128
129// Comparator to sort cookies from highest creation date to lowest
130// creation date.
131struct OrderByCreationTimeDesc {
132 bool operator()(const CookieMonster::CookieMap::iterator& a,
133 const CookieMonster::CookieMap::iterator& b) const {
134 return a->second->CreationDate() > b->second->CreationDate();
135 }
136};
137
[email protected]4d3ce782010-10-29 18:31:28138// Constants for use in VLOG
139const int kVlogPerCookieMonster = 1;
140const int kVlogPeriodic = 3;
141const int kVlogGarbageCollection = 5;
142const int kVlogSetCookies = 7;
143const int kVlogGetCookies = 9;
144
[email protected]f48b9432011-01-11 07:25:40145// Mozilla sorts on the path length (longest first), and then it
146// sorts by creation time (oldest first).
147// The RFC says the sort order for the domain attribute is undefined.
[email protected]5b9bc352012-07-18 13:13:34148bool CookieSorter(CanonicalCookie* cc1, CanonicalCookie* cc2) {
[email protected]f48b9432011-01-11 07:25:40149 if (cc1->Path().length() == cc2->Path().length())
150 return cc1->CreationDate() < cc2->CreationDate();
151 return cc1->Path().length() > cc2->Path().length();
initial.commit586acc5fe2008-07-26 22:42:52152}
153
[email protected]8ad5d462013-05-02 08:45:26154bool LRACookieSorter(const CookieMonster::CookieMap::iterator& it1,
[email protected]f48b9432011-01-11 07:25:40155 const CookieMonster::CookieMap::iterator& it2) {
156 // Cookies accessed less recently should be deleted first.
157 if (it1->second->LastAccessDate() != it2->second->LastAccessDate())
158 return it1->second->LastAccessDate() < it2->second->LastAccessDate();
initial.commit586acc5fe2008-07-26 22:42:52159
[email protected]f48b9432011-01-11 07:25:40160 // In rare cases we might have two cookies with identical last access times.
161 // To preserve the stability of the sort, in these cases prefer to delete
162 // older cookies over newer ones. CreationDate() is guaranteed to be unique.
163 return it1->second->CreationDate() < it2->second->CreationDate();
[email protected]297a4ed02010-02-12 08:12:52164}
165
drogerd5d1278c2015-03-17 19:21:51166// Compare cookies using name, domain and path, so that "equivalent" cookies
167// (per RFC 2965) are equal to each other.
168bool PartialDiffCookieSorter(const net::CanonicalCookie& a,
169 const net::CanonicalCookie& b) {
170 return a.PartialCompare(b);
171}
172
173// This is a stricter ordering than PartialDiffCookieOrdering, where all fields
174// are used.
175bool FullDiffCookieSorter(const net::CanonicalCookie& a,
176 const net::CanonicalCookie& b) {
177 return a.FullCompare(b);
178}
179
[email protected]297a4ed02010-02-12 08:12:52180// Our strategy to find duplicates is:
181// (1) Build a map from (cookiename, cookiepath) to
182// {list of cookies with this signature, sorted by creation time}.
183// (2) For each list with more than 1 entry, keep the cookie having the
184// most recent creation time, and delete the others.
[email protected]f48b9432011-01-11 07:25:40185//
[email protected]1655ba342010-07-14 18:17:42186// Two cookies are considered equivalent if they have the same domain,
187// name, and path.
188struct CookieSignature {
189 public:
[email protected]dedec0b2013-02-28 04:50:10190 CookieSignature(const std::string& name,
191 const std::string& domain,
[email protected]1655ba342010-07-14 18:17:42192 const std::string& path)
mkwstbe84af312015-02-20 08:52:45193 : name(name), domain(domain), path(path) {}
[email protected]1655ba342010-07-14 18:17:42194
195 // To be a key for a map this class needs to be assignable, copyable,
196 // and have an operator<. The default assignment operator
197 // and copy constructor are exactly what we want.
198
199 bool operator<(const CookieSignature& cs) const {
200 // Name compare dominates, then domain, then path.
201 int diff = name.compare(cs.name);
202 if (diff != 0)
203 return diff < 0;
204
205 diff = domain.compare(cs.domain);
206 if (diff != 0)
207 return diff < 0;
208
209 return path.compare(cs.path) < 0;
210 }
211
212 std::string name;
213 std::string domain;
214 std::string path;
215};
[email protected]f48b9432011-01-11 07:25:40216
[email protected]8ad5d462013-05-02 08:45:26217// For a CookieItVector iterator range [|it_begin|, |it_end|),
218// sorts the first |num_sort| + 1 elements by LastAccessDate().
219// The + 1 element exists so for any interval of length <= |num_sort| starting
220// from |cookies_its_begin|, a LastAccessDate() bound can be found.
mkwstbe84af312015-02-20 08:52:45221void SortLeastRecentlyAccessed(CookieMonster::CookieItVector::iterator it_begin,
222 CookieMonster::CookieItVector::iterator it_end,
223 size_t num_sort) {
[email protected]8ad5d462013-05-02 08:45:26224 DCHECK_LT(static_cast<int>(num_sort), it_end - it_begin);
225 std::partial_sort(it_begin, it_begin + num_sort + 1, it_end, LRACookieSorter);
226}
[email protected]f48b9432011-01-11 07:25:40227
[email protected]8ad5d462013-05-02 08:45:26228// Predicate to support PartitionCookieByPriority().
229struct CookiePriorityEqualsTo
230 : std::unary_function<const CookieMonster::CookieMap::iterator, bool> {
[email protected]5edff3c52014-06-23 20:27:48231 explicit CookiePriorityEqualsTo(CookiePriority priority)
mkwstbe84af312015-02-20 08:52:45232 : priority_(priority) {}
[email protected]8ad5d462013-05-02 08:45:26233
234 bool operator()(const CookieMonster::CookieMap::iterator it) const {
235 return it->second->Priority() == priority_;
[email protected]f48b9432011-01-11 07:25:40236 }
[email protected]8ad5d462013-05-02 08:45:26237
238 const CookiePriority priority_;
239};
240
241// For a CookieItVector iterator range [|it_begin|, |it_end|),
242// moves all cookies with a given |priority| to the beginning of the list.
243// Returns: An iterator in [it_begin, it_end) to the first element with
244// priority != |priority|, or |it_end| if all have priority == |priority|.
245CookieMonster::CookieItVector::iterator PartitionCookieByPriority(
246 CookieMonster::CookieItVector::iterator it_begin,
247 CookieMonster::CookieItVector::iterator it_end,
248 CookiePriority priority) {
249 return std::partition(it_begin, it_end, CookiePriorityEqualsTo(priority));
250}
251
mkwstbe84af312015-02-20 08:52:45252bool LowerBoundAccessDateComparator(const CookieMonster::CookieMap::iterator it,
253 const Time& access_date) {
[email protected]8ad5d462013-05-02 08:45:26254 return it->second->LastAccessDate() < access_date;
255}
256
257// For a CookieItVector iterator range [|it_begin|, |it_end|)
258// from a CookieItVector sorted by LastAccessDate(), returns the
259// first iterator with access date >= |access_date|, or cookie_its_end if this
260// holds for all.
261CookieMonster::CookieItVector::iterator LowerBoundAccessDate(
262 const CookieMonster::CookieItVector::iterator its_begin,
263 const CookieMonster::CookieItVector::iterator its_end,
264 const Time& access_date) {
265 return std::lower_bound(its_begin, its_end, access_date,
266 LowerBoundAccessDateComparator);
[email protected]7a964a72010-09-07 19:33:26267}
268
[email protected]7c4b66b2014-01-04 12:28:13269// Mapping between DeletionCause and CookieMonsterDelegate::ChangeCause; the
270// mapping also provides a boolean that specifies whether or not an
271// OnCookieChanged notification ought to be generated.
[email protected]8bb846f2011-03-23 12:08:18272typedef struct ChangeCausePair_struct {
[email protected]7c4b66b2014-01-04 12:28:13273 CookieMonsterDelegate::ChangeCause cause;
[email protected]8bb846f2011-03-23 12:08:18274 bool notify;
275} ChangeCausePair;
276ChangeCausePair ChangeCauseMapping[] = {
mkwstbe84af312015-02-20 08:52:45277 // DELETE_COOKIE_EXPLICIT
278 {CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT, true},
279 // DELETE_COOKIE_OVERWRITE
280 {CookieMonsterDelegate::CHANGE_COOKIE_OVERWRITE, true},
281 // DELETE_COOKIE_EXPIRED
282 {CookieMonsterDelegate::CHANGE_COOKIE_EXPIRED, true},
283 // DELETE_COOKIE_EVICTED
284 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
285 // DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE
286 {CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT, false},
287 // DELETE_COOKIE_DONT_RECORD
288 {CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT, false},
289 // DELETE_COOKIE_EVICTED_DOMAIN
290 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
291 // DELETE_COOKIE_EVICTED_GLOBAL
292 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
293 // DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE
294 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
295 // DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE
296 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
297 // DELETE_COOKIE_EXPIRED_OVERWRITE
298 {CookieMonsterDelegate::CHANGE_COOKIE_EXPIRED_OVERWRITE, true},
299 // DELETE_COOKIE_CONTROL_CHAR
300 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED, true},
301 // DELETE_COOKIE_LAST_ENTRY
302 {CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT, false}};
[email protected]8bb846f2011-03-23 12:08:18303
[email protected]34a160d2011-05-12 22:12:49304std::string BuildCookieLine(const CanonicalCookieVector& cookies) {
305 std::string cookie_line;
306 for (CanonicalCookieVector::const_iterator it = cookies.begin();
307 it != cookies.end(); ++it) {
308 if (it != cookies.begin())
309 cookie_line += "; ";
310 // In Mozilla if you set a cookie like AAAA, it will have an empty token
311 // and a value of AAAA. When it sends the cookie back, it will send AAAA,
312 // so we need to avoid sending =AAAA for a blank token value.
313 if (!(*it)->Name().empty())
314 cookie_line += (*it)->Name() + "=";
315 cookie_line += (*it)->Value();
316 }
317 return cookie_line;
318}
319
ellyjones399e35a22014-10-27 11:09:56320void RunAsync(scoped_refptr<base::TaskRunner> proxy,
msarda0aad8f02014-10-30 09:22:39321 const CookieStore::CookieChangedCallback& callback,
322 const CanonicalCookie& cookie,
323 bool removed) {
324 proxy->PostTask(FROM_HERE, base::Bind(callback, cookie, removed));
ellyjones399e35a22014-10-27 11:09:56325}
326
[email protected]f48b9432011-01-11 07:25:40327} // namespace
328
[email protected]7c4b66b2014-01-04 12:28:13329CookieMonster::CookieMonster(PersistentCookieStore* store,
330 CookieMonsterDelegate* delegate)
[email protected]f48b9432011-01-11 07:25:40331 : initialized_(false),
davidben879199c2015-03-06 00:55:04332 loaded_(false),
[email protected]f48b9432011-01-11 07:25:40333 store_(store),
334 last_access_threshold_(
335 TimeDelta::FromSeconds(kDefaultAccessUpdateThresholdSeconds)),
336 delegate_(delegate),
[email protected]82388662011-03-10 21:04:06337 last_statistic_record_time_(Time::Now()),
[email protected]93c53a32011-12-05 10:40:35338 keep_expired_cookies_(false),
[email protected]8976e292013-11-02 13:38:57339 persist_session_cookies_(false) {
[email protected]f48b9432011-01-11 07:25:40340 InitializeHistograms();
341 SetDefaultCookieableSchemes();
[email protected]2d0f89a2010-12-06 12:02:23342}
343
[email protected]f48b9432011-01-11 07:25:40344CookieMonster::CookieMonster(PersistentCookieStore* store,
[email protected]7c4b66b2014-01-04 12:28:13345 CookieMonsterDelegate* delegate,
[email protected]f48b9432011-01-11 07:25:40346 int last_access_threshold_milliseconds)
347 : initialized_(false),
davidben879199c2015-03-06 00:55:04348 loaded_(false),
[email protected]f48b9432011-01-11 07:25:40349 store_(store),
350 last_access_threshold_(base::TimeDelta::FromMilliseconds(
351 last_access_threshold_milliseconds)),
352 delegate_(delegate),
[email protected]82388662011-03-10 21:04:06353 last_statistic_record_time_(base::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();
initial.commit586acc5fe2008-07-26 22:42:52358}
359
[email protected]218aa6a12011-09-13 17:38:38360// Task classes for queueing the coming request.
361
362class CookieMonster::CookieMonsterTask
363 : public base::RefCountedThreadSafe<CookieMonsterTask> {
364 public:
365 // Runs the task and invokes the client callback on the thread that
366 // originally constructed the task.
367 virtual void Run() = 0;
368
369 protected:
370 explicit CookieMonsterTask(CookieMonster* cookie_monster);
371 virtual ~CookieMonsterTask();
372
373 // Invokes the callback immediately, if the current thread is the one
374 // that originated the task, or queues the callback for execution on the
375 // appropriate thread. Maintains a reference to this CookieMonsterTask
376 // instance until the callback completes.
377 void InvokeCallback(base::Closure callback);
378
mkwstbe84af312015-02-20 08:52:45379 CookieMonster* cookie_monster() { return cookie_monster_; }
[email protected]218aa6a12011-09-13 17:38:38380
[email protected]a9813302012-04-28 09:29:28381 private:
[email protected]218aa6a12011-09-13 17:38:38382 friend class base::RefCountedThreadSafe<CookieMonsterTask>;
383
[email protected]218aa6a12011-09-13 17:38:38384 CookieMonster* cookie_monster_;
385 scoped_refptr<base::MessageLoopProxy> thread_;
386
387 DISALLOW_COPY_AND_ASSIGN(CookieMonsterTask);
388};
389
390CookieMonster::CookieMonsterTask::CookieMonsterTask(
391 CookieMonster* cookie_monster)
392 : cookie_monster_(cookie_monster),
[email protected]a9813302012-04-28 09:29:28393 thread_(base::MessageLoopProxy::current()) {
394}
[email protected]218aa6a12011-09-13 17:38:38395
mkwstbe84af312015-02-20 08:52:45396CookieMonster::CookieMonsterTask::~CookieMonsterTask() {
397}
[email protected]218aa6a12011-09-13 17:38:38398
399// Unfortunately, one cannot re-bind a Callback with parameters into a closure.
400// Therefore, the closure passed to InvokeCallback is a clumsy binding of
401// Callback::Run on a wrapped Callback instance. Since Callback is not
402// reference counted, we bind to an instance that is a member of the
403// CookieMonsterTask subclass. Then, we cannot simply post the callback to a
404// message loop because the underlying instance may be destroyed (along with the
405// CookieMonsterTask instance) in the interim. Therefore, we post a callback
406// bound to the CookieMonsterTask, which *is* reference counted (thus preventing
407// destruction of the original callback), and which invokes the closure (which
408// invokes the original callback with the returned data).
409void CookieMonster::CookieMonsterTask::InvokeCallback(base::Closure callback) {
410 if (thread_->BelongsToCurrentThread()) {
411 callback.Run();
412 } else {
mkwstbe84af312015-02-20 08:52:45413 thread_->PostTask(FROM_HERE, base::Bind(&CookieMonsterTask::InvokeCallback,
414 this, callback));
[email protected]218aa6a12011-09-13 17:38:38415 }
416}
417
418// Task class for SetCookieWithDetails call.
[email protected]5fa4f9a2013-10-03 10:13:16419class CookieMonster::SetCookieWithDetailsTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38420 public:
[email protected]dedec0b2013-02-28 04:50:10421 SetCookieWithDetailsTask(CookieMonster* cookie_monster,
422 const GURL& url,
423 const std::string& name,
424 const std::string& value,
425 const std::string& domain,
426 const std::string& path,
427 const base::Time& expiration_time,
428 bool secure,
429 bool http_only,
mkwstae819bb2015-02-23 05:10:31430 bool first_party_only,
[email protected]ab2d75c82013-04-19 18:39:04431 CookiePriority priority,
[email protected]5fa4f9a2013-10-03 10:13:16432 const SetCookiesCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38433 : CookieMonsterTask(cookie_monster),
434 url_(url),
435 name_(name),
436 value_(value),
437 domain_(domain),
438 path_(path),
439 expiration_time_(expiration_time),
440 secure_(secure),
441 http_only_(http_only),
mkwstae819bb2015-02-23 05:10:31442 first_party_only_(first_party_only),
[email protected]ab2d75c82013-04-19 18:39:04443 priority_(priority),
mkwstbe84af312015-02-20 08:52:45444 callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38445
[email protected]5fa4f9a2013-10-03 10:13:16446 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20447 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38448
[email protected]a9813302012-04-28 09:29:28449 protected:
dchengb03027d2014-10-21 12:00:20450 ~SetCookieWithDetailsTask() override {}
[email protected]a9813302012-04-28 09:29:28451
[email protected]218aa6a12011-09-13 17:38:38452 private:
453 GURL url_;
454 std::string name_;
455 std::string value_;
456 std::string domain_;
457 std::string path_;
458 base::Time expiration_time_;
459 bool secure_;
460 bool http_only_;
mkwstae819bb2015-02-23 05:10:31461 bool first_party_only_;
[email protected]ab2d75c82013-04-19 18:39:04462 CookiePriority priority_;
[email protected]5fa4f9a2013-10-03 10:13:16463 SetCookiesCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38464
465 DISALLOW_COPY_AND_ASSIGN(SetCookieWithDetailsTask);
466};
467
468void CookieMonster::SetCookieWithDetailsTask::Run() {
mkwstbe84af312015-02-20 08:52:45469 bool success = this->cookie_monster()->SetCookieWithDetails(
470 url_, name_, value_, domain_, path_, expiration_time_, secure_,
mkwstae819bb2015-02-23 05:10:31471 http_only_, first_party_only_, priority_);
[email protected]218aa6a12011-09-13 17:38:38472 if (!callback_.is_null()) {
[email protected]5fa4f9a2013-10-03 10:13:16473 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38474 base::Unretained(&callback_), success));
475 }
476}
477
478// Task class for GetAllCookies call.
[email protected]5fa4f9a2013-10-03 10:13:16479class CookieMonster::GetAllCookiesTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38480 public:
481 GetAllCookiesTask(CookieMonster* cookie_monster,
[email protected]5fa4f9a2013-10-03 10:13:16482 const GetCookieListCallback& callback)
mkwstbe84af312015-02-20 08:52:45483 : CookieMonsterTask(cookie_monster), callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38484
[email protected]5fa4f9a2013-10-03 10:13:16485 // CookieMonsterTask
dchengb03027d2014-10-21 12:00:20486 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38487
[email protected]a9813302012-04-28 09:29:28488 protected:
dchengb03027d2014-10-21 12:00:20489 ~GetAllCookiesTask() override {}
[email protected]a9813302012-04-28 09:29:28490
[email protected]218aa6a12011-09-13 17:38:38491 private:
[email protected]5fa4f9a2013-10-03 10:13:16492 GetCookieListCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38493
494 DISALLOW_COPY_AND_ASSIGN(GetAllCookiesTask);
495};
496
497void CookieMonster::GetAllCookiesTask::Run() {
498 if (!callback_.is_null()) {
499 CookieList cookies = this->cookie_monster()->GetAllCookies();
[email protected]5fa4f9a2013-10-03 10:13:16500 this->InvokeCallback(base::Bind(&GetCookieListCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38501 base::Unretained(&callback_), cookies));
mkwstbe84af312015-02-20 08:52:45502 }
[email protected]218aa6a12011-09-13 17:38:38503}
504
505// Task class for GetAllCookiesForURLWithOptions call.
506class CookieMonster::GetAllCookiesForURLWithOptionsTask
[email protected]5fa4f9a2013-10-03 10:13:16507 : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38508 public:
mkwstbe84af312015-02-20 08:52:45509 GetAllCookiesForURLWithOptionsTask(CookieMonster* cookie_monster,
510 const GURL& url,
511 const CookieOptions& options,
512 const GetCookieListCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38513 : CookieMonsterTask(cookie_monster),
514 url_(url),
515 options_(options),
mkwstbe84af312015-02-20 08:52:45516 callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38517
[email protected]5fa4f9a2013-10-03 10:13:16518 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20519 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38520
[email protected]a9813302012-04-28 09:29:28521 protected:
dchengb03027d2014-10-21 12:00:20522 ~GetAllCookiesForURLWithOptionsTask() override {}
[email protected]a9813302012-04-28 09:29:28523
[email protected]218aa6a12011-09-13 17:38:38524 private:
525 GURL url_;
526 CookieOptions options_;
[email protected]5fa4f9a2013-10-03 10:13:16527 GetCookieListCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38528
529 DISALLOW_COPY_AND_ASSIGN(GetAllCookiesForURLWithOptionsTask);
530};
531
532void CookieMonster::GetAllCookiesForURLWithOptionsTask::Run() {
533 if (!callback_.is_null()) {
mkwstbe84af312015-02-20 08:52:45534 CookieList cookies =
535 this->cookie_monster()->GetAllCookiesForURLWithOptions(url_, options_);
[email protected]5fa4f9a2013-10-03 10:13:16536 this->InvokeCallback(base::Bind(&GetCookieListCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38537 base::Unretained(&callback_), cookies));
538 }
539}
540
mkwstbe84af312015-02-20 08:52:45541template <typename Result>
542struct CallbackType {
[email protected]5fa4f9a2013-10-03 10:13:16543 typedef base::Callback<void(Result)> Type;
544};
545
mkwstbe84af312015-02-20 08:52:45546template <>
547struct CallbackType<void> {
[email protected]5fa4f9a2013-10-03 10:13:16548 typedef base::Closure Type;
549};
550
551// Base task class for Delete*Task.
552template <typename Result>
553class CookieMonster::DeleteTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38554 public:
[email protected]5fa4f9a2013-10-03 10:13:16555 DeleteTask(CookieMonster* cookie_monster,
556 const typename CallbackType<Result>::Type& callback)
mkwstbe84af312015-02-20 08:52:45557 : CookieMonsterTask(cookie_monster), callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38558
[email protected]5fa4f9a2013-10-03 10:13:16559 // CookieMonsterTask:
nickd3f30d022015-04-23 10:18:37560 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38561
dmichaeld6e570d2014-12-18 22:30:57562 protected:
563 ~DeleteTask() override;
564
[email protected]5fa4f9a2013-10-03 10:13:16565 private:
566 // Runs the delete task and returns a result.
567 virtual Result RunDeleteTask() = 0;
568 base::Closure RunDeleteTaskAndBindCallback();
569 void FlushDone(const base::Closure& callback);
570
571 typename CallbackType<Result>::Type callback_;
572
573 DISALLOW_COPY_AND_ASSIGN(DeleteTask);
574};
575
576template <typename Result>
dmichaeld6e570d2014-12-18 22:30:57577CookieMonster::DeleteTask<Result>::~DeleteTask() {
578}
579
580template <typename Result>
581base::Closure
582CookieMonster::DeleteTask<Result>::RunDeleteTaskAndBindCallback() {
[email protected]5fa4f9a2013-10-03 10:13:16583 Result result = RunDeleteTask();
584 if (callback_.is_null())
585 return base::Closure();
586 return base::Bind(callback_, result);
587}
588
589template <>
590base::Closure CookieMonster::DeleteTask<void>::RunDeleteTaskAndBindCallback() {
591 RunDeleteTask();
592 return callback_;
593}
594
595template <typename Result>
596void CookieMonster::DeleteTask<Result>::Run() {
mkwstbe84af312015-02-20 08:52:45597 this->cookie_monster()->FlushStore(base::Bind(
598 &DeleteTask<Result>::FlushDone, this, RunDeleteTaskAndBindCallback()));
[email protected]5fa4f9a2013-10-03 10:13:16599}
600
601template <typename Result>
602void CookieMonster::DeleteTask<Result>::FlushDone(
603 const base::Closure& callback) {
604 if (!callback.is_null()) {
605 this->InvokeCallback(callback);
606 }
607}
608
609// Task class for DeleteAll call.
610class CookieMonster::DeleteAllTask : public DeleteTask<int> {
611 public:
mkwstbe84af312015-02-20 08:52:45612 DeleteAllTask(CookieMonster* cookie_monster, const DeleteCallback& callback)
613 : DeleteTask<int>(cookie_monster, callback) {}
[email protected]5fa4f9a2013-10-03 10:13:16614
615 // DeleteTask:
dchengb03027d2014-10-21 12:00:20616 int RunDeleteTask() override;
[email protected]5fa4f9a2013-10-03 10:13:16617
[email protected]a9813302012-04-28 09:29:28618 protected:
dchengb03027d2014-10-21 12:00:20619 ~DeleteAllTask() override {}
[email protected]a9813302012-04-28 09:29:28620
[email protected]218aa6a12011-09-13 17:38:38621 private:
[email protected]218aa6a12011-09-13 17:38:38622 DISALLOW_COPY_AND_ASSIGN(DeleteAllTask);
623};
624
[email protected]5fa4f9a2013-10-03 10:13:16625int CookieMonster::DeleteAllTask::RunDeleteTask() {
626 return this->cookie_monster()->DeleteAll(true);
[email protected]218aa6a12011-09-13 17:38:38627}
628
629// Task class for DeleteAllCreatedBetween call.
[email protected]5fa4f9a2013-10-03 10:13:16630class CookieMonster::DeleteAllCreatedBetweenTask : public DeleteTask<int> {
[email protected]218aa6a12011-09-13 17:38:38631 public:
[email protected]dedec0b2013-02-28 04:50:10632 DeleteAllCreatedBetweenTask(CookieMonster* cookie_monster,
633 const Time& delete_begin,
634 const Time& delete_end,
[email protected]5fa4f9a2013-10-03 10:13:16635 const DeleteCallback& callback)
[email protected]151132f2013-11-18 21:37:00636 : DeleteTask<int>(cookie_monster, callback),
[email protected]218aa6a12011-09-13 17:38:38637 delete_begin_(delete_begin),
mkwstbe84af312015-02-20 08:52:45638 delete_end_(delete_end) {}
[email protected]218aa6a12011-09-13 17:38:38639
[email protected]5fa4f9a2013-10-03 10:13:16640 // DeleteTask:
dchengb03027d2014-10-21 12:00:20641 int RunDeleteTask() override;
[email protected]218aa6a12011-09-13 17:38:38642
[email protected]a9813302012-04-28 09:29:28643 protected:
dchengb03027d2014-10-21 12:00:20644 ~DeleteAllCreatedBetweenTask() override {}
[email protected]a9813302012-04-28 09:29:28645
[email protected]218aa6a12011-09-13 17:38:38646 private:
647 Time delete_begin_;
648 Time delete_end_;
[email protected]218aa6a12011-09-13 17:38:38649
650 DISALLOW_COPY_AND_ASSIGN(DeleteAllCreatedBetweenTask);
651};
652
[email protected]5fa4f9a2013-10-03 10:13:16653int CookieMonster::DeleteAllCreatedBetweenTask::RunDeleteTask() {
mkwstbe84af312015-02-20 08:52:45654 return this->cookie_monster()->DeleteAllCreatedBetween(delete_begin_,
655 delete_end_);
[email protected]218aa6a12011-09-13 17:38:38656}
657
658// Task class for DeleteAllForHost call.
[email protected]5fa4f9a2013-10-03 10:13:16659class CookieMonster::DeleteAllForHostTask : public DeleteTask<int> {
[email protected]218aa6a12011-09-13 17:38:38660 public:
661 DeleteAllForHostTask(CookieMonster* cookie_monster,
662 const GURL& url,
[email protected]5fa4f9a2013-10-03 10:13:16663 const DeleteCallback& callback)
mkwstbe84af312015-02-20 08:52:45664 : DeleteTask<int>(cookie_monster, callback), url_(url) {}
[email protected]218aa6a12011-09-13 17:38:38665
[email protected]5fa4f9a2013-10-03 10:13:16666 // DeleteTask:
dchengb03027d2014-10-21 12:00:20667 int RunDeleteTask() override;
[email protected]218aa6a12011-09-13 17:38:38668
[email protected]a9813302012-04-28 09:29:28669 protected:
dchengb03027d2014-10-21 12:00:20670 ~DeleteAllForHostTask() override {}
[email protected]a9813302012-04-28 09:29:28671
[email protected]218aa6a12011-09-13 17:38:38672 private:
673 GURL url_;
[email protected]218aa6a12011-09-13 17:38:38674
675 DISALLOW_COPY_AND_ASSIGN(DeleteAllForHostTask);
676};
677
[email protected]5fa4f9a2013-10-03 10:13:16678int CookieMonster::DeleteAllForHostTask::RunDeleteTask() {
679 return this->cookie_monster()->DeleteAllForHost(url_);
[email protected]218aa6a12011-09-13 17:38:38680}
681
[email protected]d8428d52013-08-07 06:58:25682// Task class for DeleteAllCreatedBetweenForHost call.
683class CookieMonster::DeleteAllCreatedBetweenForHostTask
[email protected]5fa4f9a2013-10-03 10:13:16684 : public DeleteTask<int> {
[email protected]d8428d52013-08-07 06:58:25685 public:
mkwstbe84af312015-02-20 08:52:45686 DeleteAllCreatedBetweenForHostTask(CookieMonster* cookie_monster,
687 Time delete_begin,
688 Time delete_end,
689 const GURL& url,
690 const DeleteCallback& callback)
[email protected]151132f2013-11-18 21:37:00691 : DeleteTask<int>(cookie_monster, callback),
[email protected]d8428d52013-08-07 06:58:25692 delete_begin_(delete_begin),
693 delete_end_(delete_end),
mkwstbe84af312015-02-20 08:52:45694 url_(url) {}
[email protected]d8428d52013-08-07 06:58:25695
[email protected]5fa4f9a2013-10-03 10:13:16696 // DeleteTask:
dchengb03027d2014-10-21 12:00:20697 int RunDeleteTask() override;
[email protected]d8428d52013-08-07 06:58:25698
699 protected:
dchengb03027d2014-10-21 12:00:20700 ~DeleteAllCreatedBetweenForHostTask() override {}
[email protected]d8428d52013-08-07 06:58:25701
702 private:
703 Time delete_begin_;
704 Time delete_end_;
705 GURL url_;
[email protected]d8428d52013-08-07 06:58:25706
707 DISALLOW_COPY_AND_ASSIGN(DeleteAllCreatedBetweenForHostTask);
708};
709
[email protected]5fa4f9a2013-10-03 10:13:16710int CookieMonster::DeleteAllCreatedBetweenForHostTask::RunDeleteTask() {
711 return this->cookie_monster()->DeleteAllCreatedBetweenForHost(
[email protected]d8428d52013-08-07 06:58:25712 delete_begin_, delete_end_, url_);
[email protected]d8428d52013-08-07 06:58:25713}
714
[email protected]218aa6a12011-09-13 17:38:38715// Task class for DeleteCanonicalCookie call.
[email protected]5fa4f9a2013-10-03 10:13:16716class CookieMonster::DeleteCanonicalCookieTask : public DeleteTask<bool> {
[email protected]218aa6a12011-09-13 17:38:38717 public:
[email protected]dedec0b2013-02-28 04:50:10718 DeleteCanonicalCookieTask(CookieMonster* cookie_monster,
719 const CanonicalCookie& cookie,
[email protected]5fa4f9a2013-10-03 10:13:16720 const DeleteCookieCallback& callback)
mkwstbe84af312015-02-20 08:52:45721 : DeleteTask<bool>(cookie_monster, callback), cookie_(cookie) {}
[email protected]218aa6a12011-09-13 17:38:38722
[email protected]5fa4f9a2013-10-03 10:13:16723 // DeleteTask:
dchengb03027d2014-10-21 12:00:20724 bool RunDeleteTask() override;
[email protected]218aa6a12011-09-13 17:38:38725
[email protected]a9813302012-04-28 09:29:28726 protected:
dchengb03027d2014-10-21 12:00:20727 ~DeleteCanonicalCookieTask() override {}
[email protected]a9813302012-04-28 09:29:28728
[email protected]218aa6a12011-09-13 17:38:38729 private:
[email protected]5b9bc352012-07-18 13:13:34730 CanonicalCookie cookie_;
[email protected]218aa6a12011-09-13 17:38:38731
732 DISALLOW_COPY_AND_ASSIGN(DeleteCanonicalCookieTask);
733};
734
[email protected]5fa4f9a2013-10-03 10:13:16735bool CookieMonster::DeleteCanonicalCookieTask::RunDeleteTask() {
736 return this->cookie_monster()->DeleteCanonicalCookie(cookie_);
[email protected]218aa6a12011-09-13 17:38:38737}
738
739// Task class for SetCookieWithOptions call.
[email protected]5fa4f9a2013-10-03 10:13:16740class CookieMonster::SetCookieWithOptionsTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38741 public:
742 SetCookieWithOptionsTask(CookieMonster* cookie_monster,
743 const GURL& url,
744 const std::string& cookie_line,
745 const CookieOptions& options,
[email protected]5fa4f9a2013-10-03 10:13:16746 const SetCookiesCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38747 : CookieMonsterTask(cookie_monster),
748 url_(url),
749 cookie_line_(cookie_line),
750 options_(options),
mkwstbe84af312015-02-20 08:52:45751 callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38752
[email protected]5fa4f9a2013-10-03 10:13:16753 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20754 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38755
[email protected]a9813302012-04-28 09:29:28756 protected:
dchengb03027d2014-10-21 12:00:20757 ~SetCookieWithOptionsTask() override {}
[email protected]a9813302012-04-28 09:29:28758
[email protected]218aa6a12011-09-13 17:38:38759 private:
760 GURL url_;
761 std::string cookie_line_;
762 CookieOptions options_;
[email protected]5fa4f9a2013-10-03 10:13:16763 SetCookiesCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38764
765 DISALLOW_COPY_AND_ASSIGN(SetCookieWithOptionsTask);
766};
767
768void CookieMonster::SetCookieWithOptionsTask::Run() {
mkwstbe84af312015-02-20 08:52:45769 bool result = this->cookie_monster()->SetCookieWithOptions(url_, cookie_line_,
770 options_);
[email protected]218aa6a12011-09-13 17:38:38771 if (!callback_.is_null()) {
[email protected]5fa4f9a2013-10-03 10:13:16772 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38773 base::Unretained(&callback_), result));
774 }
775}
776
drogerd5d1278c2015-03-17 19:21:51777// Task class for SetAllCookies call.
778class CookieMonster::SetAllCookiesTask : public CookieMonsterTask {
779 public:
780 SetAllCookiesTask(CookieMonster* cookie_monster,
781 const CookieList& list,
782 const SetCookiesCallback& callback)
783 : CookieMonsterTask(cookie_monster), list_(list), callback_(callback) {}
784
785 // CookieMonsterTask:
786 void Run() override;
787
788 protected:
789 ~SetAllCookiesTask() override {}
790
791 private:
792 CookieList list_;
793 SetCookiesCallback callback_;
794
795 DISALLOW_COPY_AND_ASSIGN(SetAllCookiesTask);
796};
797
798void CookieMonster::SetAllCookiesTask::Run() {
799 CookieList positive_diff;
800 CookieList negative_diff;
801 CookieList old_cookies = this->cookie_monster()->GetAllCookies();
802 this->cookie_monster()->ComputeCookieDiff(&old_cookies, &list_,
803 &positive_diff, &negative_diff);
804
805 for (CookieList::const_iterator it = negative_diff.begin();
806 it != negative_diff.end(); ++it) {
807 this->cookie_monster()->DeleteCanonicalCookie(*it);
808 }
809
810 bool result = true;
811 if (positive_diff.size() > 0)
812 result = this->cookie_monster()->SetCanonicalCookies(list_);
813
814 if (!callback_.is_null()) {
815 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run,
816 base::Unretained(&callback_), result));
817 }
818}
819
[email protected]218aa6a12011-09-13 17:38:38820// Task class for GetCookiesWithOptions call.
[email protected]5fa4f9a2013-10-03 10:13:16821class CookieMonster::GetCookiesWithOptionsTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38822 public:
823 GetCookiesWithOptionsTask(CookieMonster* cookie_monster,
[email protected]0298caf82011-12-20 23:15:46824 const GURL& url,
[email protected]218aa6a12011-09-13 17:38:38825 const CookieOptions& options,
[email protected]5fa4f9a2013-10-03 10:13:16826 const GetCookiesCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38827 : CookieMonsterTask(cookie_monster),
828 url_(url),
829 options_(options),
mkwstbe84af312015-02-20 08:52:45830 callback_(callback) {}
[email protected]218aa6a12011-09-13 17:38:38831
[email protected]5fa4f9a2013-10-03 10:13:16832 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20833 void Run() override;
[email protected]218aa6a12011-09-13 17:38:38834
[email protected]a9813302012-04-28 09:29:28835 protected:
dchengb03027d2014-10-21 12:00:20836 ~GetCookiesWithOptionsTask() override {}
[email protected]a9813302012-04-28 09:29:28837
[email protected]218aa6a12011-09-13 17:38:38838 private:
839 GURL url_;
840 CookieOptions options_;
[email protected]5fa4f9a2013-10-03 10:13:16841 GetCookiesCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38842
843 DISALLOW_COPY_AND_ASSIGN(GetCookiesWithOptionsTask);
844};
845
846void CookieMonster::GetCookiesWithOptionsTask::Run() {
pkastinga9269aa42015-04-10 01:42:26847 // TODO(mkwst): Remove ScopedTracker below once crbug.com/456373 is fixed.
pkasting58e029b2015-02-21 05:17:28848 tracked_objects::ScopedTracker tracking_profile(
849 FROM_HERE_WITH_EXPLICIT_FUNCTION(
850 "456373 CookieMonster::GetCookiesWithOptionsTask::Run"));
mkwstbe84af312015-02-20 08:52:45851 std::string cookie =
852 this->cookie_monster()->GetCookiesWithOptions(url_, options_);
[email protected]218aa6a12011-09-13 17:38:38853 if (!callback_.is_null()) {
[email protected]5fa4f9a2013-10-03 10:13:16854 this->InvokeCallback(base::Bind(&GetCookiesCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38855 base::Unretained(&callback_), cookie));
856 }
857}
858
[email protected]218aa6a12011-09-13 17:38:38859// Task class for DeleteCookie call.
[email protected]5fa4f9a2013-10-03 10:13:16860class CookieMonster::DeleteCookieTask : public DeleteTask<void> {
[email protected]218aa6a12011-09-13 17:38:38861 public:
862 DeleteCookieTask(CookieMonster* cookie_monster,
[email protected]0298caf82011-12-20 23:15:46863 const GURL& url,
[email protected]218aa6a12011-09-13 17:38:38864 const std::string& cookie_name,
865 const base::Closure& callback)
[email protected]151132f2013-11-18 21:37:00866 : DeleteTask<void>(cookie_monster, callback),
[email protected]218aa6a12011-09-13 17:38:38867 url_(url),
mkwstbe84af312015-02-20 08:52:45868 cookie_name_(cookie_name) {}
[email protected]218aa6a12011-09-13 17:38:38869
[email protected]5fa4f9a2013-10-03 10:13:16870 // DeleteTask:
dchengb03027d2014-10-21 12:00:20871 void RunDeleteTask() override;
[email protected]218aa6a12011-09-13 17:38:38872
[email protected]a9813302012-04-28 09:29:28873 protected:
dchengb03027d2014-10-21 12:00:20874 ~DeleteCookieTask() override {}
[email protected]a9813302012-04-28 09:29:28875
[email protected]218aa6a12011-09-13 17:38:38876 private:
877 GURL url_;
878 std::string cookie_name_;
[email protected]218aa6a12011-09-13 17:38:38879
880 DISALLOW_COPY_AND_ASSIGN(DeleteCookieTask);
881};
882
[email protected]5fa4f9a2013-10-03 10:13:16883void CookieMonster::DeleteCookieTask::RunDeleteTask() {
[email protected]218aa6a12011-09-13 17:38:38884 this->cookie_monster()->DeleteCookie(url_, cookie_name_);
[email protected]218aa6a12011-09-13 17:38:38885}
886
[email protected]264807b2012-04-25 14:49:37887// Task class for DeleteSessionCookies call.
[email protected]5fa4f9a2013-10-03 10:13:16888class CookieMonster::DeleteSessionCookiesTask : public DeleteTask<int> {
[email protected]264807b2012-04-25 14:49:37889 public:
[email protected]dedec0b2013-02-28 04:50:10890 DeleteSessionCookiesTask(CookieMonster* cookie_monster,
[email protected]5fa4f9a2013-10-03 10:13:16891 const DeleteCallback& callback)
mkwstbe84af312015-02-20 08:52:45892 : DeleteTask<int>(cookie_monster, callback) {}
[email protected]264807b2012-04-25 14:49:37893
[email protected]5fa4f9a2013-10-03 10:13:16894 // DeleteTask:
dchengb03027d2014-10-21 12:00:20895 int RunDeleteTask() override;
[email protected]264807b2012-04-25 14:49:37896
[email protected]a9813302012-04-28 09:29:28897 protected:
dchengb03027d2014-10-21 12:00:20898 ~DeleteSessionCookiesTask() override {}
[email protected]a9813302012-04-28 09:29:28899
[email protected]264807b2012-04-25 14:49:37900 private:
[email protected]264807b2012-04-25 14:49:37901 DISALLOW_COPY_AND_ASSIGN(DeleteSessionCookiesTask);
902};
903
[email protected]5fa4f9a2013-10-03 10:13:16904int CookieMonster::DeleteSessionCookiesTask::RunDeleteTask() {
905 return this->cookie_monster()->DeleteSessionCookies();
[email protected]264807b2012-04-25 14:49:37906}
907
[email protected]ee209482013-04-19 19:50:04908// Task class for HasCookiesForETLDP1Task call.
[email protected]5fa4f9a2013-10-03 10:13:16909class CookieMonster::HasCookiesForETLDP1Task : public CookieMonsterTask {
[email protected]ee209482013-04-19 19:50:04910 public:
mkwstbe84af312015-02-20 08:52:45911 HasCookiesForETLDP1Task(CookieMonster* cookie_monster,
912 const std::string& etldp1,
913 const HasCookiesForETLDP1Callback& callback)
[email protected]ee209482013-04-19 19:50:04914 : CookieMonsterTask(cookie_monster),
915 etldp1_(etldp1),
mkwstbe84af312015-02-20 08:52:45916 callback_(callback) {}
[email protected]ee209482013-04-19 19:50:04917
[email protected]5fa4f9a2013-10-03 10:13:16918 // CookieMonsterTask:
dchengb03027d2014-10-21 12:00:20919 void Run() override;
[email protected]ee209482013-04-19 19:50:04920
921 protected:
dchengb03027d2014-10-21 12:00:20922 ~HasCookiesForETLDP1Task() override {}
[email protected]ee209482013-04-19 19:50:04923
924 private:
925 std::string etldp1_;
[email protected]5fa4f9a2013-10-03 10:13:16926 HasCookiesForETLDP1Callback callback_;
[email protected]ee209482013-04-19 19:50:04927
928 DISALLOW_COPY_AND_ASSIGN(HasCookiesForETLDP1Task);
929};
930
931void CookieMonster::HasCookiesForETLDP1Task::Run() {
932 bool result = this->cookie_monster()->HasCookiesForETLDP1(etldp1_);
933 if (!callback_.is_null()) {
mkwstbe84af312015-02-20 08:52:45934 this->InvokeCallback(base::Bind(&HasCookiesForETLDP1Callback::Run,
935 base::Unretained(&callback_), result));
[email protected]ee209482013-04-19 19:50:04936 }
937}
938
[email protected]218aa6a12011-09-13 17:38:38939// Asynchronous CookieMonster API
940
941void CookieMonster::SetCookieWithDetailsAsync(
[email protected]dedec0b2013-02-28 04:50:10942 const GURL& url,
943 const std::string& name,
944 const std::string& value,
945 const std::string& domain,
946 const std::string& path,
[email protected]d8428d52013-08-07 06:58:25947 const Time& expiration_time,
[email protected]dedec0b2013-02-28 04:50:10948 bool secure,
949 bool http_only,
mkwstae819bb2015-02-23 05:10:31950 bool first_party_only,
[email protected]ab2d75c82013-04-19 18:39:04951 CookiePriority priority,
[email protected]218aa6a12011-09-13 17:38:38952 const SetCookiesCallback& callback) {
mkwstbe84af312015-02-20 08:52:45953 scoped_refptr<SetCookieWithDetailsTask> task = new SetCookieWithDetailsTask(
954 this, url, name, value, domain, path, expiration_time, secure, http_only,
mkwstae819bb2015-02-23 05:10:31955 first_party_only, priority, callback);
[email protected]8562034e2011-10-17 17:35:04956 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:38957}
958
959void CookieMonster::GetAllCookiesAsync(const GetCookieListCallback& callback) {
mkwstbe84af312015-02-20 08:52:45960 scoped_refptr<GetAllCookiesTask> task = new GetAllCookiesTask(this, callback);
[email protected]218aa6a12011-09-13 17:38:38961
962 DoCookieTask(task);
963}
964
[email protected]218aa6a12011-09-13 17:38:38965void CookieMonster::GetAllCookiesForURLWithOptionsAsync(
966 const GURL& url,
967 const CookieOptions& options,
968 const GetCookieListCallback& callback) {
969 scoped_refptr<GetAllCookiesForURLWithOptionsTask> task =
970 new GetAllCookiesForURLWithOptionsTask(this, url, options, callback);
971
[email protected]8562034e2011-10-17 17:35:04972 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:38973}
974
975void CookieMonster::GetAllCookiesForURLAsync(
mkwstbe84af312015-02-20 08:52:45976 const GURL& url,
977 const GetCookieListCallback& callback) {
[email protected]218aa6a12011-09-13 17:38:38978 CookieOptions options;
979 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:31980 options.set_include_first_party_only();
[email protected]218aa6a12011-09-13 17:38:38981 scoped_refptr<GetAllCookiesForURLWithOptionsTask> task =
982 new GetAllCookiesForURLWithOptionsTask(this, url, options, callback);
983
[email protected]8562034e2011-10-17 17:35:04984 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:38985}
986
[email protected]ee209482013-04-19 19:50:04987void CookieMonster::HasCookiesForETLDP1Async(
988 const std::string& etldp1,
989 const HasCookiesForETLDP1Callback& callback) {
990 scoped_refptr<HasCookiesForETLDP1Task> task =
991 new HasCookiesForETLDP1Task(this, etldp1, callback);
992
993 DoCookieTaskForURL(task, GURL("http://" + etldp1));
994}
995
[email protected]218aa6a12011-09-13 17:38:38996void CookieMonster::DeleteAllAsync(const DeleteCallback& callback) {
mkwstbe84af312015-02-20 08:52:45997 scoped_refptr<DeleteAllTask> task = new DeleteAllTask(this, callback);
[email protected]218aa6a12011-09-13 17:38:38998
999 DoCookieTask(task);
1000}
1001
1002void CookieMonster::DeleteAllCreatedBetweenAsync(
mkwstbe84af312015-02-20 08:52:451003 const Time& delete_begin,
1004 const Time& delete_end,
[email protected]218aa6a12011-09-13 17:38:381005 const DeleteCallback& callback) {
1006 scoped_refptr<DeleteAllCreatedBetweenTask> task =
mkwstbe84af312015-02-20 08:52:451007 new DeleteAllCreatedBetweenTask(this, delete_begin, delete_end, callback);
[email protected]218aa6a12011-09-13 17:38:381008
1009 DoCookieTask(task);
1010}
1011
[email protected]d8428d52013-08-07 06:58:251012void CookieMonster::DeleteAllCreatedBetweenForHostAsync(
1013 const Time delete_begin,
1014 const Time delete_end,
1015 const GURL& url,
1016 const DeleteCallback& callback) {
1017 scoped_refptr<DeleteAllCreatedBetweenForHostTask> task =
mkwstbe84af312015-02-20 08:52:451018 new DeleteAllCreatedBetweenForHostTask(this, delete_begin, delete_end,
1019 url, callback);
[email protected]d8428d52013-08-07 06:58:251020
1021 DoCookieTaskForURL(task, url);
1022}
1023
mkwstbe84af312015-02-20 08:52:451024void CookieMonster::DeleteAllForHostAsync(const GURL& url,
1025 const DeleteCallback& callback) {
[email protected]218aa6a12011-09-13 17:38:381026 scoped_refptr<DeleteAllForHostTask> task =
1027 new DeleteAllForHostTask(this, url, callback);
1028
[email protected]8562034e2011-10-17 17:35:041029 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381030}
1031
1032void CookieMonster::DeleteCanonicalCookieAsync(
1033 const CanonicalCookie& cookie,
1034 const DeleteCookieCallback& callback) {
1035 scoped_refptr<DeleteCanonicalCookieTask> task =
1036 new DeleteCanonicalCookieTask(this, cookie, callback);
1037
1038 DoCookieTask(task);
1039}
1040
drogerd5d1278c2015-03-17 19:21:511041void CookieMonster::SetAllCookiesAsync(const CookieList& list,
1042 const SetCookiesCallback& callback) {
1043 scoped_refptr<SetAllCookiesTask> task =
1044 new SetAllCookiesTask(this, list, callback);
1045 DoCookieTask(task);
1046}
1047
[email protected]218aa6a12011-09-13 17:38:381048void CookieMonster::SetCookieWithOptionsAsync(
1049 const GURL& url,
1050 const std::string& cookie_line,
1051 const CookieOptions& options,
1052 const SetCookiesCallback& callback) {
1053 scoped_refptr<SetCookieWithOptionsTask> task =
1054 new SetCookieWithOptionsTask(this, url, cookie_line, options, callback);
1055
[email protected]8562034e2011-10-17 17:35:041056 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381057}
1058
1059void CookieMonster::GetCookiesWithOptionsAsync(
1060 const GURL& url,
1061 const CookieOptions& options,
1062 const GetCookiesCallback& callback) {
1063 scoped_refptr<GetCookiesWithOptionsTask> task =
1064 new GetCookiesWithOptionsTask(this, url, options, callback);
1065
[email protected]8562034e2011-10-17 17:35:041066 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381067}
1068
[email protected]218aa6a12011-09-13 17:38:381069void CookieMonster::DeleteCookieAsync(const GURL& url,
1070 const std::string& cookie_name,
1071 const base::Closure& callback) {
1072 scoped_refptr<DeleteCookieTask> task =
1073 new DeleteCookieTask(this, url, cookie_name, callback);
1074
[email protected]8562034e2011-10-17 17:35:041075 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381076}
1077
[email protected]264807b2012-04-25 14:49:371078void CookieMonster::DeleteSessionCookiesAsync(
1079 const CookieStore::DeleteCallback& callback) {
1080 scoped_refptr<DeleteSessionCookiesTask> task =
1081 new DeleteSessionCookiesTask(this, callback);
1082
1083 DoCookieTask(task);
1084}
1085
[email protected]218aa6a12011-09-13 17:38:381086void CookieMonster::DoCookieTask(
1087 const scoped_refptr<CookieMonsterTask>& task_item) {
[email protected]218aa6a12011-09-13 17:38:381088 {
1089 base::AutoLock autolock(lock_);
[email protected]8562034e2011-10-17 17:35:041090 InitIfNecessary();
[email protected]218aa6a12011-09-13 17:38:381091 if (!loaded_) {
[email protected]0184df32013-05-14 00:53:551092 tasks_pending_.push(task_item);
[email protected]218aa6a12011-09-13 17:38:381093 return;
1094 }
1095 }
1096
1097 task_item->Run();
1098}
1099
[email protected]8562034e2011-10-17 17:35:041100void CookieMonster::DoCookieTaskForURL(
1101 const scoped_refptr<CookieMonsterTask>& task_item,
1102 const GURL& url) {
1103 {
1104 base::AutoLock autolock(lock_);
1105 InitIfNecessary();
1106 // If cookies for the requested domain key (eTLD+1) have been loaded from DB
1107 // then run the task, otherwise load from DB.
1108 if (!loaded_) {
1109 // Checks if the domain key has been loaded.
mkwstbe84af312015-02-20 08:52:451110 std::string key(
1111 cookie_util::GetEffectiveDomain(url.scheme(), url.host()));
[email protected]8562034e2011-10-17 17:35:041112 if (keys_loaded_.find(key) == keys_loaded_.end()) {
mkwstbe84af312015-02-20 08:52:451113 std::map<std::string,
1114 std::deque<scoped_refptr<CookieMonsterTask>>>::iterator it =
1115 tasks_pending_for_key_.find(key);
[email protected]0184df32013-05-14 00:53:551116 if (it == tasks_pending_for_key_.end()) {
mkwstbe84af312015-02-20 08:52:451117 store_->LoadCookiesForKey(
1118 key, base::Bind(&CookieMonster::OnKeyLoaded, this, key));
1119 it = tasks_pending_for_key_
1120 .insert(std::make_pair(
1121 key, std::deque<scoped_refptr<CookieMonsterTask>>()))
1122 .first;
[email protected]8562034e2011-10-17 17:35:041123 }
1124 it->second.push_back(task_item);
1125 return;
1126 }
1127 }
1128 }
1129 task_item->Run();
1130}
1131
[email protected]dedec0b2013-02-28 04:50:101132bool CookieMonster::SetCookieWithDetails(const GURL& url,
1133 const std::string& name,
1134 const std::string& value,
1135 const std::string& domain,
1136 const std::string& path,
1137 const base::Time& expiration_time,
1138 bool secure,
[email protected]ab2d75c82013-04-19 18:39:041139 bool http_only,
mkwstae819bb2015-02-23 05:10:311140 bool first_party_only,
[email protected]ab2d75c82013-04-19 18:39:041141 CookiePriority priority) {
[email protected]20305ec2011-01-21 04:55:521142 base::AutoLock autolock(lock_);
[email protected]69bb5872010-01-12 20:33:521143
[email protected]f48b9432011-01-11 07:25:401144 if (!HasCookieableScheme(url))
initial.commit586acc5fe2008-07-26 22:42:521145 return false;
1146
[email protected]f48b9432011-01-11 07:25:401147 Time creation_time = CurrentTime();
1148 last_time_seen_ = creation_time;
1149
1150 scoped_ptr<CanonicalCookie> cc;
[email protected]ab2d75c82013-04-19 18:39:041151 cc.reset(CanonicalCookie::Create(url, name, value, domain, path,
mkwstbe84af312015-02-20 08:52:451152 creation_time, expiration_time, secure,
mkwstae819bb2015-02-23 05:10:311153 http_only, first_party_only, priority));
[email protected]f48b9432011-01-11 07:25:401154
1155 if (!cc.get())
1156 return false;
1157
1158 CookieOptions options;
1159 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:311160 options.set_include_first_party_only();
[email protected]f48b9432011-01-11 07:25:401161 return SetCanonicalCookie(&cc, creation_time, options);
initial.commit586acc5fe2008-07-26 22:42:521162}
1163
bartfaba13acdf2014-09-05 15:07:281164bool CookieMonster::ImportCookies(const CookieList& list) {
[email protected]93460df2011-07-20 00:58:211165 base::AutoLock autolock(lock_);
1166 InitIfNecessary();
mkwstbe84af312015-02-20 08:52:451167 for (net::CookieList::const_iterator iter = list.begin(); iter != list.end();
1168 ++iter) {
[email protected]5b9bc352012-07-18 13:13:341169 scoped_ptr<CanonicalCookie> cookie(new CanonicalCookie(*iter));
[email protected]93460df2011-07-20 00:58:211170 net::CookieOptions options;
1171 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:311172 options.set_include_first_party_only();
[email protected]5b9bc352012-07-18 13:13:341173 if (!SetCanonicalCookie(&cookie, cookie->CreationDate(), options))
[email protected]93460df2011-07-20 00:58:211174 return false;
[email protected]93460df2011-07-20 00:58:211175 }
1176 return true;
1177}
1178
[email protected]f48b9432011-01-11 07:25:401179CookieList CookieMonster::GetAllCookies() {
[email protected]20305ec2011-01-21 04:55:521180 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401181
1182 // This function is being called to scrape the cookie list for management UI
1183 // or similar. We shouldn't show expired cookies in this list since it will
1184 // just be confusing to users, and this function is called rarely enough (and
1185 // is already slow enough) that it's OK to take the time to garbage collect
1186 // the expired cookies now.
1187 //
1188 // Note that this does not prune cookies to be below our limits (if we've
1189 // exceeded them) the way that calling GarbageCollect() would.
mkwstbe84af312015-02-20 08:52:451190 GarbageCollectExpired(
1191 Time::Now(), CookieMapItPair(cookies_.begin(), cookies_.end()), NULL);
[email protected]f48b9432011-01-11 07:25:401192
1193 // Copy the CanonicalCookie pointers from the map so that we can use the same
1194 // sorter as elsewhere, then copy the result out.
1195 std::vector<CanonicalCookie*> cookie_ptrs;
1196 cookie_ptrs.reserve(cookies_.size());
1197 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end(); ++it)
1198 cookie_ptrs.push_back(it->second);
1199 std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter);
1200
1201 CookieList cookie_list;
1202 cookie_list.reserve(cookie_ptrs.size());
1203 for (std::vector<CanonicalCookie*>::const_iterator it = cookie_ptrs.begin();
1204 it != cookie_ptrs.end(); ++it)
1205 cookie_list.push_back(**it);
1206
1207 return cookie_list;
[email protected]f325f1e12010-04-30 22:38:551208}
1209
[email protected]f48b9432011-01-11 07:25:401210CookieList CookieMonster::GetAllCookiesForURLWithOptions(
1211 const GURL& url,
1212 const CookieOptions& options) {
[email protected]20305ec2011-01-21 04:55:521213 base::AutoLock autolock(lock_);
initial.commit586acc5fe2008-07-26 22:42:521214
[email protected]f48b9432011-01-11 07:25:401215 std::vector<CanonicalCookie*> cookie_ptrs;
1216 FindCookiesForHostAndDomain(url, options, false, &cookie_ptrs);
1217 std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter);
initial.commit586acc5fe2008-07-26 22:42:521218
[email protected]f48b9432011-01-11 07:25:401219 CookieList cookies;
georgesakc15df6722014-12-02 23:52:121220 cookies.reserve(cookie_ptrs.size());
[email protected]f48b9432011-01-11 07:25:401221 for (std::vector<CanonicalCookie*>::const_iterator it = cookie_ptrs.begin();
1222 it != cookie_ptrs.end(); it++)
1223 cookies.push_back(**it);
initial.commit586acc5fe2008-07-26 22:42:521224
[email protected]f48b9432011-01-11 07:25:401225 return cookies;
initial.commit586acc5fe2008-07-26 22:42:521226}
1227
[email protected]f48b9432011-01-11 07:25:401228CookieList CookieMonster::GetAllCookiesForURL(const GURL& url) {
1229 CookieOptions options;
1230 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:311231 options.set_first_party_url(url);
[email protected]f48b9432011-01-11 07:25:401232
1233 return GetAllCookiesForURLWithOptions(url, options);
[email protected]f325f1e12010-04-30 22:38:551234}
1235
[email protected]f48b9432011-01-11 07:25:401236int CookieMonster::DeleteAll(bool sync_to_store) {
xiyuan8dbb89892015-04-13 17:04:301237 // TODO(xiyuan): Remove the log after http://crbug.com/449816.
1238 VLOG(kVlogSetCookies) << "CookieMonster::DeleteAll, sync_to_store="
1239 << sync_to_store;
1240
[email protected]20305ec2011-01-21 04:55:521241 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401242
1243 int num_deleted = 0;
1244 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1245 CookieMap::iterator curit = it;
1246 ++it;
1247 InternalDeleteCookie(curit, sync_to_store,
mkwstbe84af312015-02-20 08:52:451248 sync_to_store
1249 ? DELETE_COOKIE_EXPLICIT
1250 : DELETE_COOKIE_DONT_RECORD /* Destruction. */);
[email protected]f48b9432011-01-11 07:25:401251 ++num_deleted;
initial.commit586acc5fe2008-07-26 22:42:521252 }
1253
[email protected]f48b9432011-01-11 07:25:401254 return num_deleted;
initial.commit586acc5fe2008-07-26 22:42:521255}
1256
[email protected]f48b9432011-01-11 07:25:401257int CookieMonster::DeleteAllCreatedBetween(const Time& delete_begin,
[email protected]218aa6a12011-09-13 17:38:381258 const Time& delete_end) {
xiyuan8dbb89892015-04-13 17:04:301259 // TODO(xiyuan): Remove the log after http://crbug.com/449816.
1260 VLOG(kVlogSetCookies) << "CookieMonster::DeleteAllCreatedBetween";
1261
[email protected]20305ec2011-01-21 04:55:521262 base::AutoLock autolock(lock_);
[email protected]d0980332010-11-16 17:08:531263
[email protected]f48b9432011-01-11 07:25:401264 int num_deleted = 0;
1265 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1266 CookieMap::iterator curit = it;
1267 CanonicalCookie* cc = curit->second;
1268 ++it;
[email protected]d0980332010-11-16 17:08:531269
[email protected]f48b9432011-01-11 07:25:401270 if (cc->CreationDate() >= delete_begin &&
1271 (delete_end.is_null() || cc->CreationDate() < delete_end)) {
mkwstbe84af312015-02-20 08:52:451272 InternalDeleteCookie(curit, true, /*sync_to_store*/
[email protected]218aa6a12011-09-13 17:38:381273 DELETE_COOKIE_EXPLICIT);
[email protected]f48b9432011-01-11 07:25:401274 ++num_deleted;
initial.commit586acc5fe2008-07-26 22:42:521275 }
1276 }
1277
[email protected]f48b9432011-01-11 07:25:401278 return num_deleted;
1279}
1280
[email protected]d8428d52013-08-07 06:58:251281int CookieMonster::DeleteAllCreatedBetweenForHost(const Time delete_begin,
1282 const Time delete_end,
1283 const GURL& url) {
xiyuan8dbb89892015-04-13 17:04:301284 // TODO(xiyuan): Remove the log after http://crbug.com/449816.
1285 VLOG(kVlogSetCookies) << "CookieMonster::DeleteAllCreatedBetweenForHost";
1286
[email protected]20305ec2011-01-21 04:55:521287 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401288
1289 if (!HasCookieableScheme(url))
1290 return 0;
1291
[email protected]f48b9432011-01-11 07:25:401292 const std::string host(url.host());
1293
1294 // We store host cookies in the store by their canonical host name;
1295 // domain cookies are stored with a leading ".". So this is a pretty
1296 // simple lookup and per-cookie delete.
1297 int num_deleted = 0;
1298 for (CookieMapItPair its = cookies_.equal_range(GetKey(host));
1299 its.first != its.second;) {
1300 CookieMap::iterator curit = its.first;
1301 ++its.first;
1302
1303 const CanonicalCookie* const cc = curit->second;
1304
1305 // Delete only on a match as a host cookie.
[email protected]d8428d52013-08-07 06:58:251306 if (cc->IsHostCookie() && cc->IsDomainMatch(host) &&
1307 cc->CreationDate() >= delete_begin &&
1308 // The assumption that null |delete_end| is equivalent to
1309 // Time::Max() is confusing.
1310 (delete_end.is_null() || cc->CreationDate() < delete_end)) {
[email protected]f48b9432011-01-11 07:25:401311 num_deleted++;
1312
1313 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT);
1314 }
1315 }
1316 return num_deleted;
1317}
1318
[email protected]d8428d52013-08-07 06:58:251319int CookieMonster::DeleteAllForHost(const GURL& url) {
1320 return DeleteAllCreatedBetweenForHost(Time(), Time::Max(), url);
1321}
1322
[email protected]f48b9432011-01-11 07:25:401323bool CookieMonster::DeleteCanonicalCookie(const CanonicalCookie& cookie) {
xiyuan8dbb89892015-04-13 17:04:301324 // TODO(xiyuan): Remove the log after http://crbug.com/449816.
1325 VLOG(kVlogSetCookies) << "CookieMonster::DeleteCanonicalCookie";
1326
[email protected]20305ec2011-01-21 04:55:521327 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401328
1329 for (CookieMapItPair its = cookies_.equal_range(GetKey(cookie.Domain()));
1330 its.first != its.second; ++its.first) {
1331 // The creation date acts as our unique index...
1332 if (its.first->second->CreationDate() == cookie.CreationDate()) {
1333 InternalDeleteCookie(its.first, true, DELETE_COOKIE_EXPLICIT);
1334 return true;
1335 }
1336 }
initial.commit586acc5fe2008-07-26 22:42:521337 return false;
1338}
1339
[email protected]5edff3c52014-06-23 20:27:481340void CookieMonster::SetCookieableSchemes(const char* const schemes[],
[email protected]dedec0b2013-02-28 04:50:101341 size_t num_schemes) {
[email protected]20305ec2011-01-21 04:55:521342 base::AutoLock autolock(lock_);
[email protected]bb8905722010-05-21 17:29:041343
[email protected]cf12bd12010-06-17 14:41:301344 // Cookieable Schemes must be set before first use of function.
1345 DCHECK(!initialized_);
1346
[email protected]47accfd62009-05-14 18:46:211347 cookieable_schemes_.clear();
mkwstbe84af312015-02-20 08:52:451348 cookieable_schemes_.insert(cookieable_schemes_.end(), schemes,
1349 schemes + num_schemes);
[email protected]47accfd62009-05-14 18:46:211350}
1351
[email protected]ba4ad0e2011-03-15 08:12:471352void CookieMonster::SetKeepExpiredCookies() {
1353 keep_expired_cookies_ = true;
1354}
1355
[email protected]e67f0f42011-12-20 02:29:211356void CookieMonster::FlushStore(const base::Closure& callback) {
[email protected]20305ec2011-01-21 04:55:521357 base::AutoLock autolock(lock_);
[email protected]90499482013-06-01 00:39:501358 if (initialized_ && store_.get())
[email protected]e67f0f42011-12-20 02:29:211359 store_->Flush(callback);
1360 else if (!callback.is_null())
[email protected]2da659e2013-05-23 20:51:341361 base::MessageLoop::current()->PostTask(FROM_HERE, callback);
[email protected]f48b9432011-01-11 07:25:401362}
1363
1364bool CookieMonster::SetCookieWithOptions(const GURL& url,
1365 const std::string& cookie_line,
1366 const CookieOptions& options) {
[email protected]20305ec2011-01-21 04:55:521367 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401368
1369 if (!HasCookieableScheme(url)) {
1370 return false;
1371 }
1372
[email protected]f48b9432011-01-11 07:25:401373 return SetCookieWithCreationTimeAndOptions(url, cookie_line, Time(), options);
1374}
1375
1376std::string CookieMonster::GetCookiesWithOptions(const GURL& url,
1377 const CookieOptions& options) {
[email protected]20305ec2011-01-21 04:55:521378 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401379
[email protected]34a160d2011-05-12 22:12:491380 if (!HasCookieableScheme(url))
[email protected]f48b9432011-01-11 07:25:401381 return std::string();
[email protected]f48b9432011-01-11 07:25:401382
[email protected]f48b9432011-01-11 07:25:401383 std::vector<CanonicalCookie*> cookies;
1384 FindCookiesForHostAndDomain(url, options, true, &cookies);
1385 std::sort(cookies.begin(), cookies.end(), CookieSorter);
1386
[email protected]34a160d2011-05-12 22:12:491387 std::string cookie_line = BuildCookieLine(cookies);
[email protected]f48b9432011-01-11 07:25:401388
[email protected]f48b9432011-01-11 07:25:401389 VLOG(kVlogGetCookies) << "GetCookies() result: " << cookie_line;
1390
1391 return cookie_line;
1392}
1393
1394void CookieMonster::DeleteCookie(const GURL& url,
1395 const std::string& cookie_name) {
xiyuan8dbb89892015-04-13 17:04:301396 // TODO(xiyuan): Remove the log after http://crbug.com/449816.
1397 VLOG(kVlogSetCookies) << "CookieMonster::DeleteCookie";
1398
[email protected]20305ec2011-01-21 04:55:521399 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401400
1401 if (!HasCookieableScheme(url))
1402 return;
1403
1404 CookieOptions options;
1405 options.set_include_httponly();
mkwstae819bb2015-02-23 05:10:311406 options.set_include_first_party_only();
[email protected]f48b9432011-01-11 07:25:401407 // Get the cookies for this host and its domain(s).
1408 std::vector<CanonicalCookie*> cookies;
1409 FindCookiesForHostAndDomain(url, options, true, &cookies);
1410 std::set<CanonicalCookie*> matching_cookies;
1411
1412 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
1413 it != cookies.end(); ++it) {
1414 if ((*it)->Name() != cookie_name)
1415 continue;
1416 if (url.path().find((*it)->Path()))
1417 continue;
1418 matching_cookies.insert(*it);
1419 }
1420
1421 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1422 CookieMap::iterator curit = it;
1423 ++it;
1424 if (matching_cookies.find(curit->second) != matching_cookies.end()) {
1425 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT);
1426 }
1427 }
1428}
1429
[email protected]264807b2012-04-25 14:49:371430int CookieMonster::DeleteSessionCookies() {
xiyuan8dbb89892015-04-13 17:04:301431 // TODO(xiyuan): Remove the log after http://crbug.com/449816.
1432 VLOG(kVlogSetCookies) << "CookieMonster::DeleteSessionCookies";
1433
[email protected]264807b2012-04-25 14:49:371434 base::AutoLock autolock(lock_);
1435
1436 int num_deleted = 0;
1437 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1438 CookieMap::iterator curit = it;
1439 CanonicalCookie* cc = curit->second;
1440 ++it;
1441
1442 if (!cc->IsPersistent()) {
mkwstbe84af312015-02-20 08:52:451443 InternalDeleteCookie(curit, true, /*sync_to_store*/
[email protected]264807b2012-04-25 14:49:371444 DELETE_COOKIE_EXPIRED);
1445 ++num_deleted;
1446 }
1447 }
1448
1449 return num_deleted;
1450}
1451
[email protected]ee209482013-04-19 19:50:041452bool CookieMonster::HasCookiesForETLDP1(const std::string& etldp1) {
1453 base::AutoLock autolock(lock_);
1454
1455 const std::string key(GetKey(etldp1));
1456
1457 CookieMapItPair its = cookies_.equal_range(key);
1458 return its.first != its.second;
1459}
1460
[email protected]f48b9432011-01-11 07:25:401461CookieMonster* CookieMonster::GetCookieMonster() {
1462 return this;
1463}
1464
[email protected]8ad5d462013-05-02 08:45:261465// This function must be called before the CookieMonster is used.
[email protected]93c53a32011-12-05 10:40:351466void CookieMonster::SetPersistSessionCookies(bool persist_session_cookies) {
[email protected]93c53a32011-12-05 10:40:351467 DCHECK(!initialized_);
1468 persist_session_cookies_ = persist_session_cookies;
1469}
1470
[email protected]bf510ed2012-06-05 08:31:431471void CookieMonster::SetForceKeepSessionState() {
[email protected]90499482013-06-01 00:39:501472 if (store_.get()) {
[email protected]bf510ed2012-06-05 08:31:431473 store_->SetForceKeepSessionState();
[email protected]93c53a32011-12-05 10:40:351474 }
1475}
1476
[email protected]f48b9432011-01-11 07:25:401477CookieMonster::~CookieMonster() {
1478 DeleteAll(false);
1479}
1480
1481bool CookieMonster::SetCookieWithCreationTime(const GURL& url,
1482 const std::string& cookie_line,
1483 const base::Time& creation_time) {
[email protected]90499482013-06-01 00:39:501484 DCHECK(!store_.get()) << "This method is only to be used by unit-tests.";
[email protected]20305ec2011-01-21 04:55:521485 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401486
1487 if (!HasCookieableScheme(url)) {
1488 return false;
1489 }
1490
1491 InitIfNecessary();
1492 return SetCookieWithCreationTimeAndOptions(url, cookie_line, creation_time,
1493 CookieOptions());
1494}
1495
1496void CookieMonster::InitStore() {
[email protected]90499482013-06-01 00:39:501497 DCHECK(store_.get()) << "Store must exist to initialize";
[email protected]f48b9432011-01-11 07:25:401498
[email protected]218aa6a12011-09-13 17:38:381499 // We bind in the current time so that we can report the wall-clock time for
1500 // loading cookies.
1501 store_->Load(base::Bind(&CookieMonster::OnLoaded, this, TimeTicks::Now()));
1502}
[email protected]f48b9432011-01-11 07:25:401503
[email protected]218aa6a12011-09-13 17:38:381504void CookieMonster::OnLoaded(TimeTicks beginning_time,
1505 const std::vector<CanonicalCookie*>& cookies) {
pkastingeb49ae52015-04-14 03:40:501506 // TODO(pkasting): Remove ScopedTracker below once crbug.com/457528 is fixed.
1507 tracked_objects::ScopedTracker tracking_profile1(
1508 FROM_HERE_WITH_EXPLICIT_FUNCTION("457528 CookieMonster::OnLoaded 1"));
[email protected]218aa6a12011-09-13 17:38:381509 StoreLoadedCookies(cookies);
[email protected]c7593fb22011-11-14 23:54:271510 histogram_time_blocked_on_load_->AddTime(TimeTicks::Now() - beginning_time);
[email protected]218aa6a12011-09-13 17:38:381511
pkastingeb49ae52015-04-14 03:40:501512 // TODO(pkasting): Remove ScopedTracker below once crbug.com/457528 is fixed.
1513 tracked_objects::ScopedTracker tracking_profile2(
1514 FROM_HERE_WITH_EXPLICIT_FUNCTION("457528 CookieMonster::OnLoaded 2"));
[email protected]218aa6a12011-09-13 17:38:381515 // Invoke the task queue of cookie request.
1516 InvokeQueue();
1517}
1518
[email protected]8562034e2011-10-17 17:35:041519void CookieMonster::OnKeyLoaded(const std::string& key,
1520 const std::vector<CanonicalCookie*>& cookies) {
1521 // This function does its own separate locking.
1522 StoreLoadedCookies(cookies);
1523
mkwstbe84af312015-02-20 08:52:451524 std::deque<scoped_refptr<CookieMonsterTask>> tasks_pending_for_key;
[email protected]8562034e2011-10-17 17:35:041525
[email protected]bab72ec2013-10-30 20:50:021526 // We need to do this repeatedly until no more tasks were added to the queue
1527 // during the period where we release the lock.
1528 while (true) {
1529 {
1530 base::AutoLock autolock(lock_);
mkwstbe84af312015-02-20 08:52:451531 std::map<std::string,
1532 std::deque<scoped_refptr<CookieMonsterTask>>>::iterator it =
1533 tasks_pending_for_key_.find(key);
[email protected]bab72ec2013-10-30 20:50:021534 if (it == tasks_pending_for_key_.end()) {
1535 keys_loaded_.insert(key);
1536 return;
1537 }
1538 if (it->second.empty()) {
1539 keys_loaded_.insert(key);
1540 tasks_pending_for_key_.erase(it);
1541 return;
1542 }
1543 it->second.swap(tasks_pending_for_key);
1544 }
1545
1546 while (!tasks_pending_for_key.empty()) {
1547 scoped_refptr<CookieMonsterTask> task = tasks_pending_for_key.front();
1548 task->Run();
1549 tasks_pending_for_key.pop_front();
1550 }
[email protected]8562034e2011-10-17 17:35:041551 }
1552}
1553
[email protected]218aa6a12011-09-13 17:38:381554void CookieMonster::StoreLoadedCookies(
1555 const std::vector<CanonicalCookie*>& cookies) {
[email protected]f48b9432011-01-11 07:25:401556 // Initialize the store and sync in any saved persistent cookies. We don't
1557 // care if it's expired, insert it so it can be garbage collected, removed,
1558 // and sync'd.
[email protected]218aa6a12011-09-13 17:38:381559 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401560
[email protected]6210ce52013-09-20 03:33:141561 CookieItVector cookies_with_control_chars;
1562
[email protected]f48b9432011-01-11 07:25:401563 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
1564 it != cookies.end(); ++it) {
1565 int64 cookie_creation_time = (*it)->CreationDate().ToInternalValue();
1566
[email protected]8562034e2011-10-17 17:35:041567 if (creation_times_.insert(cookie_creation_time).second) {
[email protected]6210ce52013-09-20 03:33:141568 CookieMap::iterator inserted =
1569 InternalInsertCookie(GetKey((*it)->Domain()), *it, false);
[email protected]f48b9432011-01-11 07:25:401570 const Time cookie_access_time((*it)->LastAccessDate());
[email protected]8562034e2011-10-17 17:35:041571 if (earliest_access_time_.is_null() ||
1572 cookie_access_time < earliest_access_time_)
1573 earliest_access_time_ = cookie_access_time;
[email protected]6210ce52013-09-20 03:33:141574
1575 if (ContainsControlCharacter((*it)->Name()) ||
1576 ContainsControlCharacter((*it)->Value())) {
mkwstbe84af312015-02-20 08:52:451577 cookies_with_control_chars.push_back(inserted);
[email protected]6210ce52013-09-20 03:33:141578 }
[email protected]f48b9432011-01-11 07:25:401579 } else {
mkwstbe84af312015-02-20 08:52:451580 LOG(ERROR) << base::StringPrintf(
1581 "Found cookies with duplicate creation "
1582 "times in backing store: "
1583 "{name='%s', domain='%s', path='%s'}",
1584 (*it)->Name().c_str(), (*it)->Domain().c_str(),
1585 (*it)->Path().c_str());
[email protected]f48b9432011-01-11 07:25:401586 // We've been given ownership of the cookie and are throwing it
1587 // away; reclaim the space.
1588 delete (*it);
1589 }
1590 }
[email protected]f48b9432011-01-11 07:25:401591
[email protected]6210ce52013-09-20 03:33:141592 // Any cookies that contain control characters that we have loaded from the
1593 // persistent store should be deleted. See http://crbug.com/238041.
1594 for (CookieItVector::iterator it = cookies_with_control_chars.begin();
1595 it != cookies_with_control_chars.end();) {
1596 CookieItVector::iterator curit = it;
1597 ++it;
1598
1599 InternalDeleteCookie(*curit, true, DELETE_COOKIE_CONTROL_CHAR);
1600 }
1601
[email protected]f48b9432011-01-11 07:25:401602 // After importing cookies from the PersistentCookieStore, verify that
1603 // none of our other constraints are violated.
[email protected]f48b9432011-01-11 07:25:401604 // In particular, the backing store might have given us duplicate cookies.
[email protected]8562034e2011-10-17 17:35:041605
1606 // This method could be called multiple times due to priority loading, thus
1607 // cookies loaded in previous runs will be validated again, but this is OK
1608 // since they are expected to be much fewer than total DB.
[email protected]f48b9432011-01-11 07:25:401609 EnsureCookiesMapIsValid();
[email protected]218aa6a12011-09-13 17:38:381610}
[email protected]f48b9432011-01-11 07:25:401611
[email protected]218aa6a12011-09-13 17:38:381612void CookieMonster::InvokeQueue() {
1613 while (true) {
1614 scoped_refptr<CookieMonsterTask> request_task;
1615 {
1616 base::AutoLock autolock(lock_);
[email protected]0184df32013-05-14 00:53:551617 if (tasks_pending_.empty()) {
[email protected]218aa6a12011-09-13 17:38:381618 loaded_ = true;
[email protected]8562034e2011-10-17 17:35:041619 creation_times_.clear();
1620 keys_loaded_.clear();
[email protected]218aa6a12011-09-13 17:38:381621 break;
1622 }
[email protected]0184df32013-05-14 00:53:551623 request_task = tasks_pending_.front();
1624 tasks_pending_.pop();
[email protected]218aa6a12011-09-13 17:38:381625 }
1626 request_task->Run();
1627 }
[email protected]f48b9432011-01-11 07:25:401628}
1629
1630void CookieMonster::EnsureCookiesMapIsValid() {
1631 lock_.AssertAcquired();
1632
1633 int num_duplicates_trimmed = 0;
1634
1635 // Iterate through all the of the cookies, grouped by host.
1636 CookieMap::iterator prev_range_end = cookies_.begin();
1637 while (prev_range_end != cookies_.end()) {
1638 CookieMap::iterator cur_range_begin = prev_range_end;
1639 const std::string key = cur_range_begin->first; // Keep a copy.
1640 CookieMap::iterator cur_range_end = cookies_.upper_bound(key);
1641 prev_range_end = cur_range_end;
1642
1643 // Ensure no equivalent cookies for this host.
1644 num_duplicates_trimmed +=
1645 TrimDuplicateCookiesForKey(key, cur_range_begin, cur_range_end);
1646 }
1647
1648 // Record how many duplicates were found in the database.
1649 // See InitializeHistograms() for details.
mkwste0a9ca872015-03-30 20:24:381650 histogram_number_duplicate_db_cookies_->Add(num_duplicates_trimmed);
[email protected]f48b9432011-01-11 07:25:401651}
1652
mkwstbe84af312015-02-20 08:52:451653int CookieMonster::TrimDuplicateCookiesForKey(const std::string& key,
1654 CookieMap::iterator begin,
1655 CookieMap::iterator end) {
[email protected]f48b9432011-01-11 07:25:401656 lock_.AssertAcquired();
1657
1658 // Set of cookies ordered by creation time.
1659 typedef std::set<CookieMap::iterator, OrderByCreationTimeDesc> CookieSet;
1660
1661 // Helper map we populate to find the duplicates.
1662 typedef std::map<CookieSignature, CookieSet> EquivalenceMap;
1663 EquivalenceMap equivalent_cookies;
1664
1665 // The number of duplicate cookies that have been found.
1666 int num_duplicates = 0;
1667
1668 // Iterate through all of the cookies in our range, and insert them into
1669 // the equivalence map.
1670 for (CookieMap::iterator it = begin; it != end; ++it) {
1671 DCHECK_EQ(key, it->first);
1672 CanonicalCookie* cookie = it->second;
1673
mkwstbe84af312015-02-20 08:52:451674 CookieSignature signature(cookie->Name(), cookie->Domain(), cookie->Path());
[email protected]f48b9432011-01-11 07:25:401675 CookieSet& set = equivalent_cookies[signature];
1676
1677 // We found a duplicate!
1678 if (!set.empty())
1679 num_duplicates++;
1680
1681 // We save the iterator into |cookies_| rather than the actual cookie
1682 // pointer, since we may need to delete it later.
1683 bool insert_success = set.insert(it).second;
mkwstbe84af312015-02-20 08:52:451684 DCHECK(insert_success)
1685 << "Duplicate creation times found in duplicate cookie name scan.";
[email protected]f48b9432011-01-11 07:25:401686 }
1687
1688 // If there were no duplicates, we are done!
1689 if (num_duplicates == 0)
1690 return 0;
1691
1692 // Make sure we find everything below that we did above.
1693 int num_duplicates_found = 0;
1694
1695 // Otherwise, delete all the duplicate cookies, both from our in-memory store
1696 // and from the backing store.
1697 for (EquivalenceMap::iterator it = equivalent_cookies.begin();
mkwstbe84af312015-02-20 08:52:451698 it != equivalent_cookies.end(); ++it) {
[email protected]f48b9432011-01-11 07:25:401699 const CookieSignature& signature = it->first;
1700 CookieSet& dupes = it->second;
1701
1702 if (dupes.size() <= 1)
1703 continue; // This cookiename/path has no duplicates.
1704 num_duplicates_found += dupes.size() - 1;
1705
1706 // Since |dups| is sorted by creation time (descending), the first cookie
1707 // is the most recent one, so we will keep it. The rest are duplicates.
1708 dupes.erase(dupes.begin());
1709
1710 LOG(ERROR) << base::StringPrintf(
1711 "Found %d duplicate cookies for host='%s', "
1712 "with {name='%s', domain='%s', path='%s'}",
mkwstbe84af312015-02-20 08:52:451713 static_cast<int>(dupes.size()), key.c_str(), signature.name.c_str(),
1714 signature.domain.c_str(), signature.path.c_str());
[email protected]f48b9432011-01-11 07:25:401715
1716 // Remove all the cookies identified by |dupes|. It is valid to delete our
1717 // list of iterators one at a time, since |cookies_| is a multimap (they
1718 // don't invalidate existing iterators following deletion).
mkwstbe84af312015-02-20 08:52:451719 for (CookieSet::iterator dupes_it = dupes.begin(); dupes_it != dupes.end();
[email protected]f48b9432011-01-11 07:25:401720 ++dupes_it) {
[email protected]218aa6a12011-09-13 17:38:381721 InternalDeleteCookie(*dupes_it, true,
[email protected]f48b9432011-01-11 07:25:401722 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE);
1723 }
1724 }
1725 DCHECK_EQ(num_duplicates, num_duplicates_found);
1726
1727 return num_duplicates;
1728}
1729
[email protected]ba4ad0e2011-03-15 08:12:471730// Note: file must be the last scheme.
mkwstbe84af312015-02-20 08:52:451731const char* const CookieMonster::kDefaultCookieableSchemes[] = {"http",
1732 "https",
1733 "ws",
1734 "wss",
1735 "file"};
[email protected]ba4ad0e2011-03-15 08:12:471736const int CookieMonster::kDefaultCookieableSchemesCount =
[email protected]5fa4f9a2013-10-03 10:13:161737 arraysize(kDefaultCookieableSchemes);
[email protected]ba4ad0e2011-03-15 08:12:471738
[email protected]f48b9432011-01-11 07:25:401739void CookieMonster::SetDefaultCookieableSchemes() {
[email protected]7c4b66b2014-01-04 12:28:131740 // Always disable file scheme unless SetEnableFileScheme(true) is called.
1741 SetCookieableSchemes(kDefaultCookieableSchemes,
1742 kDefaultCookieableSchemesCount - 1);
[email protected]f48b9432011-01-11 07:25:401743}
1744
[email protected]f48b9432011-01-11 07:25:401745void CookieMonster::FindCookiesForHostAndDomain(
1746 const GURL& url,
1747 const CookieOptions& options,
1748 bool update_access_time,
1749 std::vector<CanonicalCookie*>* cookies) {
1750 lock_.AssertAcquired();
1751
1752 const Time current_time(CurrentTime());
1753
1754 // Probe to save statistics relatively frequently. We do it here rather
1755 // than in the set path as many websites won't set cookies, and we
1756 // want to collect statistics whenever the browser's being used.
1757 RecordPeriodicStats(current_time);
1758
[email protected]8e1583672012-02-11 04:39:411759 // Can just dispatch to FindCookiesForKey
1760 const std::string key(GetKey(url.host()));
mkwstbe84af312015-02-20 08:52:451761 FindCookiesForKey(key, url, options, current_time, update_access_time,
1762 cookies);
[email protected]f48b9432011-01-11 07:25:401763}
1764
[email protected]dedec0b2013-02-28 04:50:101765void CookieMonster::FindCookiesForKey(const std::string& key,
1766 const GURL& url,
1767 const CookieOptions& options,
1768 const Time& current,
1769 bool update_access_time,
1770 std::vector<CanonicalCookie*>* cookies) {
[email protected]f48b9432011-01-11 07:25:401771 lock_.AssertAcquired();
1772
[email protected]f48b9432011-01-11 07:25:401773 for (CookieMapItPair its = cookies_.equal_range(key);
mkwstbe84af312015-02-20 08:52:451774 its.first != its.second;) {
[email protected]f48b9432011-01-11 07:25:401775 CookieMap::iterator curit = its.first;
1776 CanonicalCookie* cc = curit->second;
1777 ++its.first;
1778
1779 // If the cookie is expired, delete it.
[email protected]ba4ad0e2011-03-15 08:12:471780 if (cc->IsExpired(current) && !keep_expired_cookies_) {
[email protected]f48b9432011-01-11 07:25:401781 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
1782 continue;
1783 }
1784
[email protected]65f4e7e2012-12-12 21:56:541785 // Filter out cookies that should not be included for a request to the
1786 // given |url|. HTTP only cookies are filtered depending on the passed
1787 // cookie |options|.
1788 if (!cc->IncludeForRequestURL(url, options))
[email protected]f48b9432011-01-11 07:25:401789 continue;
1790
[email protected]65f4e7e2012-12-12 21:56:541791 // Add this cookie to the set of matching cookies. Update the access
[email protected]f48b9432011-01-11 07:25:401792 // time if we've been requested to do so.
1793 if (update_access_time) {
1794 InternalUpdateCookieAccessTime(cc, current);
1795 }
1796 cookies->push_back(cc);
1797 }
1798}
1799
1800bool CookieMonster::DeleteAnyEquivalentCookie(const std::string& key,
1801 const CanonicalCookie& ecc,
[email protected]e7c590e52011-03-30 08:33:551802 bool skip_httponly,
1803 bool already_expired) {
[email protected]f48b9432011-01-11 07:25:401804 lock_.AssertAcquired();
1805
1806 bool found_equivalent_cookie = false;
1807 bool skipped_httponly = false;
1808 for (CookieMapItPair its = cookies_.equal_range(key);
mkwstbe84af312015-02-20 08:52:451809 its.first != its.second;) {
[email protected]f48b9432011-01-11 07:25:401810 CookieMap::iterator curit = its.first;
1811 CanonicalCookie* cc = curit->second;
1812 ++its.first;
1813
1814 if (ecc.IsEquivalent(*cc)) {
1815 // We should never have more than one equivalent cookie, since they should
1816 // overwrite each other.
mkwstbe84af312015-02-20 08:52:451817 CHECK(!found_equivalent_cookie)
1818 << "Duplicate equivalent cookies found, cookie store is corrupted.";
[email protected]f48b9432011-01-11 07:25:401819 if (skip_httponly && cc->IsHttpOnly()) {
1820 skipped_httponly = true;
1821 } else {
mkwstbe84af312015-02-20 08:52:451822 InternalDeleteCookie(curit, true, already_expired
1823 ? DELETE_COOKIE_EXPIRED_OVERWRITE
1824 : DELETE_COOKIE_OVERWRITE);
[email protected]f48b9432011-01-11 07:25:401825 }
1826 found_equivalent_cookie = true;
1827 }
1828 }
1829 return skipped_httponly;
1830}
1831
[email protected]6210ce52013-09-20 03:33:141832CookieMonster::CookieMap::iterator CookieMonster::InternalInsertCookie(
1833 const std::string& key,
1834 CanonicalCookie* cc,
1835 bool sync_to_store) {
pkastinga9269aa42015-04-10 01:42:261836 // TODO(mkwst): Remove ScopedTracker below once crbug.com/456373 is fixed.
pkasting58e029b2015-02-21 05:17:281837 tracked_objects::ScopedTracker tracking_profile(
1838 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1839 "456373 CookieMonster::InternalInsertCookie"));
[email protected]f48b9432011-01-11 07:25:401840 lock_.AssertAcquired();
1841
[email protected]90499482013-06-01 00:39:501842 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() &&
1843 sync_to_store)
[email protected]f48b9432011-01-11 07:25:401844 store_->AddCookie(*cc);
[email protected]6210ce52013-09-20 03:33:141845 CookieMap::iterator inserted =
1846 cookies_.insert(CookieMap::value_type(key, cc));
[email protected]8bb846f2011-03-23 12:08:181847 if (delegate_.get()) {
mkwstbe84af312015-02-20 08:52:451848 delegate_->OnCookieChanged(*cc, false,
1849 CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT);
[email protected]8bb846f2011-03-23 12:08:181850 }
mkwstc1aa4cc2015-04-03 19:57:451851
1852 // See InitializeHistograms() for details.
1853 int32_t sample = cc->IsFirstPartyOnly() ? 1 << COOKIE_TYPE_FIRSTPARTYONLY : 0;
1854 sample |= cc->IsHttpOnly() ? 1 << COOKIE_TYPE_HTTPONLY : 0;
1855 sample |= cc->IsSecure() ? 1 << COOKIE_TYPE_SECURE : 0;
1856 histogram_cookie_type_->Add(sample);
1857
msarda0aad8f02014-10-30 09:22:391858 RunCallbacks(*cc, false);
[email protected]6210ce52013-09-20 03:33:141859
1860 return inserted;
[email protected]f48b9432011-01-11 07:25:401861}
1862
[email protected]34602282010-02-03 22:14:151863bool CookieMonster::SetCookieWithCreationTimeAndOptions(
1864 const GURL& url,
1865 const std::string& cookie_line,
1866 const Time& creation_time_or_null,
1867 const CookieOptions& options) {
[email protected]b866a02d2010-07-28 16:41:041868 lock_.AssertAcquired();
initial.commit586acc5fe2008-07-26 22:42:521869
[email protected]4d3ce782010-10-29 18:31:281870 VLOG(kVlogSetCookies) << "SetCookie() line: " << cookie_line;
initial.commit586acc5fe2008-07-26 22:42:521871
[email protected]34602282010-02-03 22:14:151872 Time creation_time = creation_time_or_null;
1873 if (creation_time.is_null()) {
1874 creation_time = CurrentTime();
1875 last_time_seen_ = creation_time;
1876 }
1877
[email protected]abbd13b2012-11-15 17:54:201878 scoped_ptr<CanonicalCookie> cc(
1879 CanonicalCookie::Create(url, cookie_line, creation_time, options));
initial.commit586acc5fe2008-07-26 22:42:521880
1881 if (!cc.get()) {
[email protected]4d3ce782010-10-29 18:31:281882 VLOG(kVlogSetCookies) << "WARNING: Failed to allocate CanonicalCookie";
initial.commit586acc5fe2008-07-26 22:42:521883 return false;
1884 }
[email protected]fa77eb512010-07-22 16:12:511885 return SetCanonicalCookie(&cc, creation_time, options);
[email protected]f325f1e12010-04-30 22:38:551886}
initial.commit586acc5fe2008-07-26 22:42:521887
[email protected]f325f1e12010-04-30 22:38:551888bool CookieMonster::SetCanonicalCookie(scoped_ptr<CanonicalCookie>* cc,
[email protected]f325f1e12010-04-30 22:38:551889 const Time& creation_time,
1890 const CookieOptions& options) {
[email protected]7a964a72010-09-07 19:33:261891 const std::string key(GetKey((*cc)->Domain()));
[email protected]e7c590e52011-03-30 08:33:551892 bool already_expired = (*cc)->IsExpired(creation_time);
ellyjones399e35a22014-10-27 11:09:561893
[email protected]e7c590e52011-03-30 08:33:551894 if (DeleteAnyEquivalentCookie(key, **cc, options.exclude_httponly(),
1895 already_expired)) {
[email protected]4d3ce782010-10-29 18:31:281896 VLOG(kVlogSetCookies) << "SetCookie() not clobbering httponly cookie";
[email protected]3a96c742008-11-19 19:46:271897 return false;
1898 }
initial.commit586acc5fe2008-07-26 22:42:521899
mkwstbe84af312015-02-20 08:52:451900 VLOG(kVlogSetCookies) << "SetCookie() key: " << key
1901 << " cc: " << (*cc)->DebugString();
initial.commit586acc5fe2008-07-26 22:42:521902
1903 // Realize that we might be setting an expired cookie, and the only point
1904 // was to delete the cookie which we've already done.
[email protected]e7c590e52011-03-30 08:33:551905 if (!already_expired || keep_expired_cookies_) {
[email protected]374f58b2010-07-20 15:29:261906 // See InitializeHistograms() for details.
[email protected]10b691f2012-07-11 15:22:151907 if ((*cc)->IsPersistent()) {
[email protected]8475bee2011-03-17 18:40:241908 histogram_expiration_duration_minutes_->Add(
1909 ((*cc)->ExpiryDate() - creation_time).InMinutes());
1910 }
1911
ellyjones399e35a22014-10-27 11:09:561912 {
1913 CanonicalCookie cookie = *(cc->get());
1914 InternalInsertCookie(key, cc->release(), true);
ellyjones399e35a22014-10-27 11:09:561915 }
[email protected]348dd662013-03-13 20:25:071916 } else {
1917 VLOG(kVlogSetCookies) << "SetCookie() not storing already expired cookie.";
[email protected]c4058fb2010-06-22 17:25:261918 }
initial.commit586acc5fe2008-07-26 22:42:521919
1920 // We assume that hopefully setting a cookie will be less common than
1921 // querying a cookie. Since setting a cookie can put us over our limits,
1922 // make sure that we garbage collect... We can also make the assumption that
1923 // if a cookie was set, in the common case it will be used soon after,
1924 // and we will purge the expired cookies in GetCookies().
[email protected]7a964a72010-09-07 19:33:261925 GarbageCollect(creation_time, key);
initial.commit586acc5fe2008-07-26 22:42:521926
1927 return true;
1928}
1929
drogerd5d1278c2015-03-17 19:21:511930bool CookieMonster::SetCanonicalCookies(const CookieList& list) {
1931 base::AutoLock autolock(lock_);
1932
1933 net::CookieOptions options;
1934 options.set_include_httponly();
1935
1936 for (CookieList::const_iterator it = list.begin(); it != list.end(); ++it) {
1937 scoped_ptr<CanonicalCookie> canonical_cookie(new CanonicalCookie(*it));
1938 if (!SetCanonicalCookie(&canonical_cookie, it->CreationDate(), options))
1939 return false;
1940 }
1941
1942 return true;
1943}
1944
[email protected]7a964a72010-09-07 19:33:261945void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie* cc,
1946 const Time& current) {
[email protected]bb8905722010-05-21 17:29:041947 lock_.AssertAcquired();
1948
[email protected]77e0a462008-11-01 00:43:351949 // Based off the Mozilla code. When a cookie has been accessed recently,
1950 // don't bother updating its access time again. This reduces the number of
1951 // updates we do during pageload, which in turn reduces the chance our storage
1952 // backend will hit its batch thresholds and be forced to update.
[email protected]77e0a462008-11-01 00:43:351953 if ((current - cc->LastAccessDate()) < last_access_threshold_)
1954 return;
1955
[email protected]374f58b2010-07-20 15:29:261956 // See InitializeHistograms() for details.
1957 histogram_between_access_interval_minutes_->Add(
1958 (current - cc->LastAccessDate()).InMinutes());
[email protected]c4058fb2010-06-22 17:25:261959
[email protected]77e0a462008-11-01 00:43:351960 cc->SetLastAccessDate(current);
[email protected]90499482013-06-01 00:39:501961 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get())
[email protected]77e0a462008-11-01 00:43:351962 store_->UpdateCookieAccessTime(*cc);
1963}
1964
[email protected]6210ce52013-09-20 03:33:141965// InternalDeleteCookies must not invalidate iterators other than the one being
1966// deleted.
initial.commit586acc5fe2008-07-26 22:42:521967void CookieMonster::InternalDeleteCookie(CookieMap::iterator it,
[email protected]c4058fb2010-06-22 17:25:261968 bool sync_to_store,
1969 DeletionCause deletion_cause) {
[email protected]bb8905722010-05-21 17:29:041970 lock_.AssertAcquired();
1971
[email protected]8bb846f2011-03-23 12:08:181972 // Ideally, this would be asserted up where we define ChangeCauseMapping,
1973 // but DeletionCause's visibility (or lack thereof) forces us to make
1974 // this check here.
mostynb91e0da982015-01-20 19:17:271975 static_assert(arraysize(ChangeCauseMapping) == DELETE_COOKIE_LAST_ENTRY + 1,
1976 "ChangeCauseMapping size should match DeletionCause size");
[email protected]8bb846f2011-03-23 12:08:181977
[email protected]374f58b2010-07-20 15:29:261978 // See InitializeHistograms() for details.
[email protected]7a964a72010-09-07 19:33:261979 if (deletion_cause != DELETE_COOKIE_DONT_RECORD)
1980 histogram_cookie_deletion_cause_->Add(deletion_cause);
[email protected]c4058fb2010-06-22 17:25:261981
initial.commit586acc5fe2008-07-26 22:42:521982 CanonicalCookie* cc = it->second;
xiyuan8dbb89892015-04-13 17:04:301983 VLOG(kVlogSetCookies) << "InternalDeleteCookie()"
1984 << ", cause:" << deletion_cause
1985 << ", cc: " << cc->DebugString();
[email protected]7a964a72010-09-07 19:33:261986
[email protected]90499482013-06-01 00:39:501987 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() &&
1988 sync_to_store)
initial.commit586acc5fe2008-07-26 22:42:521989 store_->DeleteCookie(*cc);
[email protected]8bb846f2011-03-23 12:08:181990 if (delegate_.get()) {
1991 ChangeCausePair mapping = ChangeCauseMapping[deletion_cause];
1992
1993 if (mapping.notify)
1994 delegate_->OnCookieChanged(*cc, true, mapping.cause);
1995 }
msarda0aad8f02014-10-30 09:22:391996 RunCallbacks(*cc, true);
initial.commit586acc5fe2008-07-26 22:42:521997 cookies_.erase(it);
1998 delete cc;
1999}
2000
[email protected]8807b322010-10-01 17:10:142001// Domain expiry behavior is unchanged by key/expiry scheme (the
[email protected]8ad5d462013-05-02 08:45:262002// meaning of the key is different, but that's not visible to this routine).
mkwstbe84af312015-02-20 08:52:452003int CookieMonster::GarbageCollect(const Time& current, const std::string& key) {
[email protected]bb8905722010-05-21 17:29:042004 lock_.AssertAcquired();
2005
initial.commit586acc5fe2008-07-26 22:42:522006 int num_deleted = 0;
mkwstbe84af312015-02-20 08:52:452007 Time safe_date(Time::Now() - TimeDelta::FromDays(kSafeFromGlobalPurgeDays));
initial.commit586acc5fe2008-07-26 22:42:522008
[email protected]8ad5d462013-05-02 08:45:262009 // Collect garbage for this key, minding cookie priorities.
[email protected]7a964a72010-09-07 19:33:262010 if (cookies_.count(key) > kDomainMaxCookies) {
[email protected]4d3ce782010-10-29 18:31:282011 VLOG(kVlogGarbageCollection) << "GarbageCollect() key: " << key;
[email protected]7a964a72010-09-07 19:33:262012
[email protected]8ad5d462013-05-02 08:45:262013 CookieItVector cookie_its;
mkwstbe84af312015-02-20 08:52:452014 num_deleted +=
2015 GarbageCollectExpired(current, cookies_.equal_range(key), &cookie_its);
[email protected]8ad5d462013-05-02 08:45:262016 if (cookie_its.size() > kDomainMaxCookies) {
2017 VLOG(kVlogGarbageCollection) << "Deep Garbage Collect domain.";
2018 size_t purge_goal =
2019 cookie_its.size() - (kDomainMaxCookies - kDomainPurgeCookies);
2020 DCHECK(purge_goal > kDomainPurgeCookies);
2021
2022 // Boundary iterators into |cookie_its| for different priorities.
2023 CookieItVector::iterator it_bdd[4];
2024 // Intialize |it_bdd| while sorting |cookie_its| by priorities.
2025 // Schematic: [MLLHMHHLMM] => [LLL|MMMM|HHH], with 4 boundaries.
2026 it_bdd[0] = cookie_its.begin();
2027 it_bdd[3] = cookie_its.end();
mkwstbe84af312015-02-20 08:52:452028 it_bdd[1] =
2029 PartitionCookieByPriority(it_bdd[0], it_bdd[3], COOKIE_PRIORITY_LOW);
[email protected]8ad5d462013-05-02 08:45:262030 it_bdd[2] = PartitionCookieByPriority(it_bdd[1], it_bdd[3],
2031 COOKIE_PRIORITY_MEDIUM);
mkwstbe84af312015-02-20 08:52:452032 size_t quota[3] = {kDomainCookiesQuotaLow,
2033 kDomainCookiesQuotaMedium,
2034 kDomainCookiesQuotaHigh};
[email protected]8ad5d462013-05-02 08:45:262035
2036 // Purge domain cookies in 3 rounds.
2037 // Round 1: consider low-priority cookies only: evict least-recently
2038 // accessed, while protecting quota[0] of these from deletion.
2039 // Round 2: consider {low, medium}-priority cookies, evict least-recently
2040 // accessed, while protecting quota[0] + quota[1].
2041 // Round 3: consider all cookies, evict least-recently accessed.
2042 size_t accumulated_quota = 0;
2043 CookieItVector::iterator it_purge_begin = it_bdd[0];
2044 for (int i = 0; i < 3 && purge_goal > 0; ++i) {
2045 accumulated_quota += quota[i];
2046
[email protected]8ad5d462013-05-02 08:45:262047 size_t num_considered = it_bdd[i + 1] - it_purge_begin;
2048 if (num_considered <= accumulated_quota)
2049 continue;
2050
2051 // Number of cookies that will be purged in this round.
2052 size_t round_goal =
2053 std::min(purge_goal, num_considered - accumulated_quota);
2054 purge_goal -= round_goal;
2055
2056 SortLeastRecentlyAccessed(it_purge_begin, it_bdd[i + 1], round_goal);
2057 // Cookies accessed on or after |safe_date| would have been safe from
2058 // global purge, and we want to keep track of this.
2059 CookieItVector::iterator it_purge_end = it_purge_begin + round_goal;
2060 CookieItVector::iterator it_purge_middle =
2061 LowerBoundAccessDate(it_purge_begin, it_purge_end, safe_date);
2062 // Delete cookies accessed before |safe_date|.
2063 num_deleted += GarbageCollectDeleteRange(
mkwstbe84af312015-02-20 08:52:452064 current, DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE, it_purge_begin,
[email protected]8ad5d462013-05-02 08:45:262065 it_purge_middle);
2066 // Delete cookies accessed on or after |safe_date|.
2067 num_deleted += GarbageCollectDeleteRange(
mkwstbe84af312015-02-20 08:52:452068 current, DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE, it_purge_middle,
[email protected]8ad5d462013-05-02 08:45:262069 it_purge_end);
2070 it_purge_begin = it_purge_end;
2071 }
2072 DCHECK_EQ(0U, purge_goal);
[email protected]8807b322010-10-01 17:10:142073 }
initial.commit586acc5fe2008-07-26 22:42:522074 }
2075
[email protected]8ad5d462013-05-02 08:45:262076 // Collect garbage for everything. With firefox style we want to preserve
2077 // cookies accessed in kSafeFromGlobalPurgeDays, otherwise evict.
mkwstbe84af312015-02-20 08:52:452078 if (cookies_.size() > kMaxCookies && earliest_access_time_ < safe_date) {
[email protected]4d3ce782010-10-29 18:31:282079 VLOG(kVlogGarbageCollection) << "GarbageCollect() everything";
[email protected]8ad5d462013-05-02 08:45:262080 CookieItVector cookie_its;
[email protected]7a964a72010-09-07 19:33:262081 num_deleted += GarbageCollectExpired(
2082 current, CookieMapItPair(cookies_.begin(), cookies_.end()),
2083 &cookie_its);
[email protected]8ad5d462013-05-02 08:45:262084 if (cookie_its.size() > kMaxCookies) {
2085 VLOG(kVlogGarbageCollection) << "Deep Garbage Collect everything.";
2086 size_t purge_goal = cookie_its.size() - (kMaxCookies - kPurgeCookies);
2087 DCHECK(purge_goal > kPurgeCookies);
2088 // Sorts up to *and including* |cookie_its[purge_goal]|, so
2089 // |earliest_access_time| will be properly assigned even if
2090 // |global_purge_it| == |cookie_its.begin() + purge_goal|.
2091 SortLeastRecentlyAccessed(cookie_its.begin(), cookie_its.end(),
2092 purge_goal);
2093 // Find boundary to cookies older than safe_date.
mkwstbe84af312015-02-20 08:52:452094 CookieItVector::iterator global_purge_it = LowerBoundAccessDate(
2095 cookie_its.begin(), cookie_its.begin() + purge_goal, safe_date);
[email protected]8ad5d462013-05-02 08:45:262096 // Only delete the old cookies.
mkwstbe84af312015-02-20 08:52:452097 num_deleted +=
2098 GarbageCollectDeleteRange(current, DELETE_COOKIE_EVICTED_GLOBAL,
2099 cookie_its.begin(), global_purge_it);
[email protected]8ad5d462013-05-02 08:45:262100 // Set access day to the oldest cookie that wasn't deleted.
2101 earliest_access_time_ = (*global_purge_it)->second->LastAccessDate();
[email protected]8807b322010-10-01 17:10:142102 }
[email protected]c890ed192008-10-30 23:45:532103 }
2104
2105 return num_deleted;
2106}
2107
mkwstbe84af312015-02-20 08:52:452108int CookieMonster::GarbageCollectExpired(const Time& current,
2109 const CookieMapItPair& itpair,
2110 CookieItVector* cookie_its) {
xiyuan8dbb89892015-04-13 17:04:302111 // TODO(xiyuan): Remove the log after http://crbug.com/449816.
2112 VLOG(kVlogSetCookies) << "CookieMonster::GarbageCollectExpired";
2113
[email protected]ba4ad0e2011-03-15 08:12:472114 if (keep_expired_cookies_)
2115 return 0;
2116
[email protected]bb8905722010-05-21 17:29:042117 lock_.AssertAcquired();
2118
[email protected]c890ed192008-10-30 23:45:532119 int num_deleted = 0;
2120 for (CookieMap::iterator it = itpair.first, end = itpair.second; it != end;) {
2121 CookieMap::iterator curit = it;
2122 ++it;
2123
2124 if (curit->second->IsExpired(current)) {
[email protected]2f3f3592010-07-07 20:11:512125 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
[email protected]c890ed192008-10-30 23:45:532126 ++num_deleted;
2127 } else if (cookie_its) {
2128 cookie_its->push_back(curit);
2129 }
initial.commit586acc5fe2008-07-26 22:42:522130 }
2131
2132 return num_deleted;
2133}
2134
mkwstbe84af312015-02-20 08:52:452135int CookieMonster::GarbageCollectDeleteRange(const Time& current,
2136 DeletionCause cause,
2137 CookieItVector::iterator it_begin,
2138 CookieItVector::iterator it_end) {
xiyuan8dbb89892015-04-13 17:04:302139 // TODO(xiyuan): Remove the log after http://crbug.com/449816.
2140 VLOG(kVlogSetCookies) << "CookieMonster::GarbageCollectDeleteRange";
2141
[email protected]8ad5d462013-05-02 08:45:262142 for (CookieItVector::iterator it = it_begin; it != it_end; it++) {
2143 histogram_evicted_last_access_minutes_->Add(
2144 (current - (*it)->second->LastAccessDate()).InMinutes());
2145 InternalDeleteCookie((*it), true, cause);
[email protected]c10da4b02010-03-25 14:38:322146 }
[email protected]8ad5d462013-05-02 08:45:262147 return it_end - it_begin;
[email protected]c10da4b02010-03-25 14:38:322148}
2149
[email protected]ed32c212013-05-14 20:49:292150// A wrapper around registry_controlled_domains::GetDomainAndRegistry
[email protected]f48b9432011-01-11 07:25:402151// to make clear we're creating a key for our local map. Here and
2152// in FindCookiesForHostAndDomain() are the only two places where
2153// we need to conditionalize based on key type.
2154//
2155// Note that this key algorithm explicitly ignores the scheme. This is
2156// because when we're entering cookies into the map from the backing store,
2157// we in general won't have the scheme at that point.
2158// In practical terms, this means that file cookies will be stored
2159// in the map either by an empty string or by UNC name (and will be
2160// limited by kMaxCookiesPerHost), and extension cookies will be stored
2161// based on the single extension id, as the extension id won't have the
2162// form of a DNS host and hence GetKey() will return it unchanged.
2163//
2164// Arguably the right thing to do here is to make the key
2165// algorithm dependent on the scheme, and make sure that the scheme is
2166// available everywhere the key must be obtained (specfically at backing
2167// store load time). This would require either changing the backing store
2168// database schema to include the scheme (far more trouble than it's worth), or
2169// separating out file cookies into their own CookieMonster instance and
2170// thus restricting each scheme to a single cookie monster (which might
2171// be worth it, but is still too much trouble to solve what is currently a
2172// non-problem).
2173std::string CookieMonster::GetKey(const std::string& domain) const {
[email protected]f48b9432011-01-11 07:25:402174 std::string effective_domain(
[email protected]ed32c212013-05-14 20:49:292175 registry_controlled_domains::GetDomainAndRegistry(
[email protected]aabe1792014-01-30 21:37:462176 domain, registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES));
[email protected]f48b9432011-01-11 07:25:402177 if (effective_domain.empty())
2178 effective_domain = domain;
2179
2180 if (!effective_domain.empty() && effective_domain[0] == '.')
2181 return effective_domain.substr(1);
2182 return effective_domain;
2183}
2184
[email protected]97a3b6e2012-06-12 01:53:562185bool CookieMonster::IsCookieableScheme(const std::string& scheme) {
2186 base::AutoLock autolock(lock_);
2187
2188 return std::find(cookieable_schemes_.begin(), cookieable_schemes_.end(),
2189 scheme) != cookieable_schemes_.end();
2190}
2191
[email protected]f48b9432011-01-11 07:25:402192bool CookieMonster::HasCookieableScheme(const GURL& url) {
2193 lock_.AssertAcquired();
2194
2195 // Make sure the request is on a cookie-able url scheme.
2196 for (size_t i = 0; i < cookieable_schemes_.size(); ++i) {
2197 // We matched a scheme.
2198 if (url.SchemeIs(cookieable_schemes_[i].c_str())) {
2199 // We've matched a supported scheme.
initial.commit586acc5fe2008-07-26 22:42:522200 return true;
2201 }
2202 }
[email protected]f48b9432011-01-11 07:25:402203
2204 // The scheme didn't match any in our whitelist.
mkwstbe84af312015-02-20 08:52:452205 VLOG(kVlogPerCookieMonster)
2206 << "WARNING: Unsupported cookie scheme: " << url.scheme();
initial.commit586acc5fe2008-07-26 22:42:522207 return false;
2208}
2209
[email protected]c4058fb2010-06-22 17:25:262210// Test to see if stats should be recorded, and record them if so.
2211// The goal here is to get sampling for the average browser-hour of
2212// activity. We won't take samples when the web isn't being surfed,
2213// and when the web is being surfed, we'll take samples about every
2214// kRecordStatisticsIntervalSeconds.
2215// last_statistic_record_time_ is initialized to Now() rather than null
2216// in the constructor so that we won't take statistics right after
2217// startup, to avoid bias from browsers that are started but not used.
2218void CookieMonster::RecordPeriodicStats(const base::Time& current_time) {
2219 const base::TimeDelta kRecordStatisticsIntervalTime(
2220 base::TimeDelta::FromSeconds(kRecordStatisticsIntervalSeconds));
2221
[email protected]7a964a72010-09-07 19:33:262222 // If we've taken statistics recently, return.
2223 if (current_time - last_statistic_record_time_ <=
[email protected]c4058fb2010-06-22 17:25:262224 kRecordStatisticsIntervalTime) {
[email protected]7a964a72010-09-07 19:33:262225 return;
[email protected]c4058fb2010-06-22 17:25:262226 }
[email protected]7a964a72010-09-07 19:33:262227
2228 // See InitializeHistograms() for details.
2229 histogram_count_->Add(cookies_.size());
2230
2231 // More detailed statistics on cookie counts at different granularities.
2232 TimeTicks beginning_of_time(TimeTicks::Now());
2233
2234 for (CookieMap::const_iterator it_key = cookies_.begin();
mkwstbe84af312015-02-20 08:52:452235 it_key != cookies_.end();) {
[email protected]7a964a72010-09-07 19:33:262236 const std::string& key(it_key->first);
2237
2238 int key_count = 0;
2239 typedef std::map<std::string, unsigned int> DomainMap;
2240 DomainMap domain_map;
2241 CookieMapItPair its_cookies = cookies_.equal_range(key);
2242 while (its_cookies.first != its_cookies.second) {
2243 key_count++;
2244 const std::string& cookie_domain(its_cookies.first->second->Domain());
2245 domain_map[cookie_domain]++;
2246
2247 its_cookies.first++;
2248 }
2249 histogram_etldp1_count_->Add(key_count);
2250 histogram_domain_per_etldp1_count_->Add(domain_map.size());
2251 for (DomainMap::const_iterator domain_map_it = domain_map.begin();
2252 domain_map_it != domain_map.end(); domain_map_it++)
2253 histogram_domain_count_->Add(domain_map_it->second);
2254
2255 it_key = its_cookies.second;
2256 }
2257
mkwstbe84af312015-02-20 08:52:452258 VLOG(kVlogPeriodic) << "Time for recording cookie stats (us): "
2259 << (TimeTicks::Now() - beginning_of_time)
2260 .InMicroseconds();
[email protected]7a964a72010-09-07 19:33:262261
2262 last_statistic_record_time_ = current_time;
[email protected]c4058fb2010-06-22 17:25:262263}
2264
[email protected]f48b9432011-01-11 07:25:402265// Initialize all histogram counter variables used in this class.
2266//
2267// Normal histogram usage involves using the macros defined in
2268// histogram.h, which automatically takes care of declaring these
2269// variables (as statics), initializing them, and accumulating into
2270// them, all from a single entry point. Unfortunately, that solution
2271// doesn't work for the CookieMonster, as it's vulnerable to races between
2272// separate threads executing the same functions and hence initializing the
2273// same static variables. There isn't a race danger in the histogram
2274// accumulation calls; they are written to be resilient to simultaneous
2275// calls from multiple threads.
2276//
2277// The solution taken here is to have per-CookieMonster instance
2278// variables that are constructed during CookieMonster construction.
2279// Note that these variables refer to the same underlying histogram,
2280// so we still race (but safely) with other CookieMonster instances
2281// for accumulation.
2282//
2283// To do this we've expanded out the individual histogram macros calls,
2284// with declarations of the variables in the class decl, initialization here
2285// (done from the class constructor) and direct calls to the accumulation
2286// methods where needed. The specific histogram macro calls on which the
2287// initialization is based are included in comments below.
2288void CookieMonster::InitializeHistograms() {
2289 // From UMA_HISTOGRAM_CUSTOM_COUNTS
2290 histogram_expiration_duration_minutes_ = base::Histogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452291 "Cookie.ExpirationDurationMinutes", 1, kMinutesInTenYears, 50,
[email protected]f48b9432011-01-11 07:25:402292 base::Histogram::kUmaTargetedHistogramFlag);
2293 histogram_between_access_interval_minutes_ = base::Histogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452294 "Cookie.BetweenAccessIntervalMinutes", 1, kMinutesInTenYears, 50,
[email protected]f48b9432011-01-11 07:25:402295 base::Histogram::kUmaTargetedHistogramFlag);
2296 histogram_evicted_last_access_minutes_ = base::Histogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452297 "Cookie.EvictedLastAccessMinutes", 1, kMinutesInTenYears, 50,
[email protected]f48b9432011-01-11 07:25:402298 base::Histogram::kUmaTargetedHistogramFlag);
2299 histogram_count_ = base::Histogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452300 "Cookie.Count", 1, 4000, 50, base::Histogram::kUmaTargetedHistogramFlag);
2301 histogram_domain_count_ =
2302 base::Histogram::FactoryGet("Cookie.DomainCount", 1, 4000, 50,
2303 base::Histogram::kUmaTargetedHistogramFlag);
2304 histogram_etldp1_count_ =
2305 base::Histogram::FactoryGet("Cookie.Etldp1Count", 1, 4000, 50,
2306 base::Histogram::kUmaTargetedHistogramFlag);
2307 histogram_domain_per_etldp1_count_ =
2308 base::Histogram::FactoryGet("Cookie.DomainPerEtldp1Count", 1, 4000, 50,
2309 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]f48b9432011-01-11 07:25:402310
2311 // From UMA_HISTOGRAM_COUNTS_10000 & UMA_HISTOGRAM_CUSTOM_COUNTS
mkwstbe84af312015-02-20 08:52:452312 histogram_number_duplicate_db_cookies_ =
2313 base::Histogram::FactoryGet("Net.NumDuplicateCookiesInDb", 1, 10000, 50,
2314 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]f48b9432011-01-11 07:25:402315
2316 // From UMA_HISTOGRAM_ENUMERATION
2317 histogram_cookie_deletion_cause_ = base::LinearHistogram::FactoryGet(
mkwstbe84af312015-02-20 08:52:452318 "Cookie.DeletionCause", 1, DELETE_COOKIE_LAST_ENTRY - 1,
2319 DELETE_COOKIE_LAST_ENTRY, base::Histogram::kUmaTargetedHistogramFlag);
mkwstc1aa4cc2015-04-03 19:57:452320 histogram_cookie_type_ = base::LinearHistogram::FactoryGet(
mkwst87378d92015-04-10 21:22:112321 "Cookie.Type", 1, (1 << COOKIE_TYPE_LAST_ENTRY) - 1,
2322 1 << COOKIE_TYPE_LAST_ENTRY, base::Histogram::kUmaTargetedHistogramFlag);
[email protected]f48b9432011-01-11 07:25:402323
2324 // From UMA_HISTOGRAM_{CUSTOM_,}TIMES
[email protected]c7593fb22011-11-14 23:54:272325 histogram_time_blocked_on_load_ = base::Histogram::FactoryTimeGet(
mkwstbe84af312015-02-20 08:52:452326 "Cookie.TimeBlockedOnLoad", base::TimeDelta::FromMilliseconds(1),
2327 base::TimeDelta::FromMinutes(1), 50,
2328 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]f48b9432011-01-11 07:25:402329}
2330
[email protected]f48b9432011-01-11 07:25:402331// The system resolution is not high enough, so we can have multiple
2332// set cookies that result in the same system time. When this happens, we
2333// increment by one Time unit. Let's hope computers don't get too fast.
2334Time CookieMonster::CurrentTime() {
mkwstbe84af312015-02-20 08:52:452335 return std::max(Time::Now(), Time::FromInternalValue(
2336 last_time_seen_.ToInternalValue() + 1));
[email protected]f48b9432011-01-11 07:25:402337}
2338
drogerd5d1278c2015-03-17 19:21:512339void CookieMonster::ComputeCookieDiff(CookieList* old_cookies,
2340 CookieList* new_cookies,
2341 CookieList* cookies_to_add,
2342 CookieList* cookies_to_delete) {
2343 DCHECK(old_cookies);
2344 DCHECK(new_cookies);
2345 DCHECK(cookies_to_add);
2346 DCHECK(cookies_to_delete);
2347 DCHECK(cookies_to_add->empty());
2348 DCHECK(cookies_to_delete->empty());
2349
2350 // Sort both lists.
2351 // A set ordered by FullDiffCookieSorter is also ordered by
2352 // PartialDiffCookieSorter.
2353 std::sort(old_cookies->begin(), old_cookies->end(), FullDiffCookieSorter);
2354 std::sort(new_cookies->begin(), new_cookies->end(), FullDiffCookieSorter);
2355
2356 // Select any old cookie for deletion if no new cookie has the same name,
2357 // domain, and path.
2358 std::set_difference(
2359 old_cookies->begin(), old_cookies->end(), new_cookies->begin(),
2360 new_cookies->end(),
2361 std::inserter(*cookies_to_delete, cookies_to_delete->begin()),
2362 PartialDiffCookieSorter);
2363
2364 // Select any new cookie for addition (or update) if no old cookie is exactly
2365 // equivalent.
2366 std::set_difference(new_cookies->begin(), new_cookies->end(),
2367 old_cookies->begin(), old_cookies->end(),
2368 std::inserter(*cookies_to_add, cookies_to_add->begin()),
2369 FullDiffCookieSorter);
2370}
2371
ellyjones399e35a22014-10-27 11:09:562372scoped_ptr<CookieStore::CookieChangedSubscription>
mkwstbe84af312015-02-20 08:52:452373CookieMonster::AddCallbackForCookie(const GURL& gurl,
2374 const std::string& name,
2375 const CookieChangedCallback& callback) {
ellyjones399e35a22014-10-27 11:09:562376 base::AutoLock autolock(lock_);
2377 std::pair<GURL, std::string> key(gurl, name);
2378 if (hook_map_.count(key) == 0)
2379 hook_map_[key] = make_linked_ptr(new CookieChangedCallbackList());
msarda0aad8f02014-10-30 09:22:392380 return hook_map_[key]->Add(
2381 base::Bind(&RunAsync, base::MessageLoopProxy::current(), callback));
ellyjones399e35a22014-10-27 11:09:562382}
2383
mkwstb73bf8aa2015-03-31 07:33:452384#if defined(OS_ANDROID)
2385void CookieMonster::SetEnableFileScheme(bool accept) {
2386 // This assumes "file" is always at the end of the array. See the comment
2387 // above kDefaultCookieableSchemes.
2388 //
2389 // TODO(mkwst): We're keeping this method around to support the
2390 // 'CookieManager::setAcceptFileSchemeCookies' method on Android's WebView;
2391 // if/when we can deprecate and remove that method, we can remove this one
2392 // as well. Until then, we'll just ensure that the method has no effect on
2393 // non-android systems.
2394 int num_schemes = accept ? kDefaultCookieableSchemesCount
2395 : kDefaultCookieableSchemesCount - 1;
2396
2397 SetCookieableSchemes(kDefaultCookieableSchemes, num_schemes);
2398}
2399#endif
2400
msarda0aad8f02014-10-30 09:22:392401void CookieMonster::RunCallbacks(const CanonicalCookie& cookie, bool removed) {
ellyjones399e35a22014-10-27 11:09:562402 lock_.AssertAcquired();
2403 CookieOptions opts;
2404 opts.set_include_httponly();
mkwstae819bb2015-02-23 05:10:312405 opts.set_include_first_party_only();
ellyjones399e35a22014-10-27 11:09:562406 // Note that the callbacks in hook_map_ are wrapped with MakeAsync(), so they
2407 // are guaranteed to not take long - they just post a RunAsync task back to
2408 // the appropriate thread's message loop and return. It is important that this
2409 // method not run user-supplied callbacks directly, since the CookieMonster
2410 // lock is held and it is easy to accidentally introduce deadlocks.
2411 for (CookieChangedHookMap::iterator it = hook_map_.begin();
2412 it != hook_map_.end(); ++it) {
2413 std::pair<GURL, std::string> key = it->first;
2414 if (cookie.IncludeForRequestURL(key.first, opts) &&
2415 cookie.Name() == key.second) {
msarda0aad8f02014-10-30 09:22:392416 it->second->Notify(cookie, removed);
ellyjones399e35a22014-10-27 11:09:562417 }
2418 }
2419}
2420
[email protected]63725312012-07-19 08:24:162421} // namespace net