blob: b9f78ce18415df9f816172834f62ca20bd49bbdf [file] [log] [blame]
[email protected]8e1583672012-02-11 04:39:411// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit586acc5fe2008-07-26 22:42:524
5// Portions of this code based on Mozilla:
6// (netwerk/cookie/src/nsCookieService.cpp)
7/* ***** BEGIN LICENSE BLOCK *****
8 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
9 *
10 * The contents of this file are subject to the Mozilla Public License Version
11 * 1.1 (the "License"); you may not use this file except in compliance with
12 * the License. You may obtain a copy of the License at
13 * http://www.mozilla.org/MPL/
14 *
15 * Software distributed under the License is distributed on an "AS IS" basis,
16 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
17 * for the specific language governing rights and limitations under the
18 * License.
19 *
20 * The Original Code is mozilla.org code.
21 *
22 * The Initial Developer of the Original Code is
23 * Netscape Communications Corporation.
24 * Portions created by the Initial Developer are Copyright (C) 2003
25 * the Initial Developer. All Rights Reserved.
26 *
27 * Contributor(s):
28 * Daniel Witte ([email protected])
29 * Michiel van Leeuwen ([email protected])
30 *
31 * Alternatively, the contents of this file may be used under the terms of
32 * either the GNU General Public License Version 2 or later (the "GPL"), or
33 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
34 * in which case the provisions of the GPL or the LGPL are applicable instead
35 * of those above. If you wish to allow use of your version of this file only
36 * under the terms of either the GPL or the LGPL, and not to allow others to
37 * use your version of this file under the terms of the MPL, indicate your
38 * decision by deleting the provisions above and replace them with the notice
39 * and other provisions required by the GPL or the LGPL. If you do not delete
40 * the provisions above, a recipient may use your version of this file under
41 * the terms of any one of the MPL, the GPL or the LGPL.
42 *
43 * ***** END LICENSE BLOCK ***** */
44
[email protected]63ee33bd2012-03-15 09:29:5845#include "net/cookies/cookie_monster.h"
initial.commit586acc5fe2008-07-26 22:42:5246
47#include <algorithm>
[email protected]8ad5d462013-05-02 08:45:2648#include <functional>
[email protected]09666482011-07-12 12:50:4049#include <set>
initial.commit586acc5fe2008-07-26 22:42:5250
51#include "base/basictypes.h"
[email protected]218aa6a12011-09-13 17:38:3852#include "base/bind.h"
[email protected]85620342011-10-17 17:35:0453#include "base/callback.h"
initial.commit586acc5fe2008-07-26 22:42:5254#include "base/logging.h"
[email protected]3b63f8f42011-03-28 01:54:1555#include "base/memory/scoped_ptr.h"
[email protected]5ee20982013-07-17 21:51:1856#include "base/message_loop/message_loop.h"
[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"
[email protected]4b355212013-06-11 10:35:1959#include "base/strings/string_util.h"
60#include "base/strings/stringprintf.h"
[email protected]be28b5f42012-07-20 11:31:2561#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
[email protected]4b355212013-06-11 10:35:1962#include "net/cookies/canonical_cookie.h"
[email protected]63ee33bd2012-03-15 09:29:5863#include "net/cookies/cookie_util.h"
[email protected]ebfe3172012-07-12 12:21:4164#include "net/cookies/parsed_cookie.h"
[email protected]f89276a72013-07-12 06:41:5465#include "url/gurl.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]85620342011-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]85620342011-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]85620342011-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]85620342011-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.
[email protected]8807b322010-10-01 17:10:1499const 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
104const size_t CookieMonster::kDomainCookiesQuotaLow = 30;
105const size_t CookieMonster::kDomainCookiesQuotaMedium = 50;
106const size_t CookieMonster::kDomainCookiesQuotaHigh =
[email protected]5fa4f9a2013-10-03 10:13:16107 kDomainMaxCookies - kDomainPurgeCookies
108 - kDomainCookiesQuotaLow - kDomainCookiesQuotaMedium;
[email protected]8ad5d462013-05-02 08:45:26109
[email protected]8807b322010-10-01 17:10:14110const 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
166// Our strategy to find duplicates is:
167// (1) Build a map from (cookiename, cookiepath) to
168// {list of cookies with this signature, sorted by creation time}.
169// (2) For each list with more than 1 entry, keep the cookie having the
170// most recent creation time, and delete the others.
[email protected]f48b9432011-01-11 07:25:40171//
[email protected]1655ba342010-07-14 18:17:42172// Two cookies are considered equivalent if they have the same domain,
173// name, and path.
174struct CookieSignature {
175 public:
[email protected]dedec0b2013-02-28 04:50:10176 CookieSignature(const std::string& name,
177 const std::string& domain,
[email protected]1655ba342010-07-14 18:17:42178 const std::string& path)
[email protected]dedec0b2013-02-28 04:50:10179 : name(name), domain(domain), path(path) {
180 }
[email protected]1655ba342010-07-14 18:17:42181
182 // To be a key for a map this class needs to be assignable, copyable,
183 // and have an operator<. The default assignment operator
184 // and copy constructor are exactly what we want.
185
186 bool operator<(const CookieSignature& cs) const {
187 // Name compare dominates, then domain, then path.
188 int diff = name.compare(cs.name);
189 if (diff != 0)
190 return diff < 0;
191
192 diff = domain.compare(cs.domain);
193 if (diff != 0)
194 return diff < 0;
195
196 return path.compare(cs.path) < 0;
197 }
198
199 std::string name;
200 std::string domain;
201 std::string path;
202};
[email protected]f48b9432011-01-11 07:25:40203
[email protected]8ad5d462013-05-02 08:45:26204// For a CookieItVector iterator range [|it_begin|, |it_end|),
205// sorts the first |num_sort| + 1 elements by LastAccessDate().
206// The + 1 element exists so for any interval of length <= |num_sort| starting
207// from |cookies_its_begin|, a LastAccessDate() bound can be found.
208void SortLeastRecentlyAccessed(
209 CookieMonster::CookieItVector::iterator it_begin,
210 CookieMonster::CookieItVector::iterator it_end,
211 size_t num_sort) {
212 DCHECK_LT(static_cast<int>(num_sort), it_end - it_begin);
213 std::partial_sort(it_begin, it_begin + num_sort + 1, it_end, LRACookieSorter);
214}
[email protected]f48b9432011-01-11 07:25:40215
[email protected]8ad5d462013-05-02 08:45:26216// Predicate to support PartitionCookieByPriority().
217struct CookiePriorityEqualsTo
218 : std::unary_function<const CookieMonster::CookieMap::iterator, bool> {
219 CookiePriorityEqualsTo(CookiePriority priority)
220 : priority_(priority) {}
221
222 bool operator()(const CookieMonster::CookieMap::iterator it) const {
223 return it->second->Priority() == priority_;
[email protected]f48b9432011-01-11 07:25:40224 }
[email protected]8ad5d462013-05-02 08:45:26225
226 const CookiePriority priority_;
227};
228
229// For a CookieItVector iterator range [|it_begin|, |it_end|),
230// moves all cookies with a given |priority| to the beginning of the list.
231// Returns: An iterator in [it_begin, it_end) to the first element with
232// priority != |priority|, or |it_end| if all have priority == |priority|.
233CookieMonster::CookieItVector::iterator PartitionCookieByPriority(
234 CookieMonster::CookieItVector::iterator it_begin,
235 CookieMonster::CookieItVector::iterator it_end,
236 CookiePriority priority) {
237 return std::partition(it_begin, it_end, CookiePriorityEqualsTo(priority));
238}
239
240bool LowerBoundAccessDateComparator(
241 const CookieMonster::CookieMap::iterator it, const Time& access_date) {
242 return it->second->LastAccessDate() < access_date;
243}
244
245// For a CookieItVector iterator range [|it_begin|, |it_end|)
246// from a CookieItVector sorted by LastAccessDate(), returns the
247// first iterator with access date >= |access_date|, or cookie_its_end if this
248// holds for all.
249CookieMonster::CookieItVector::iterator LowerBoundAccessDate(
250 const CookieMonster::CookieItVector::iterator its_begin,
251 const CookieMonster::CookieItVector::iterator its_end,
252 const Time& access_date) {
253 return std::lower_bound(its_begin, its_end, access_date,
254 LowerBoundAccessDateComparator);
[email protected]7a964a72010-09-07 19:33:26255}
256
[email protected]33ad6ce92013-08-27 14:39:08257// Mapping between DeletionCause and Delegate::ChangeCause; the mapping also
258// provides a boolean that specifies whether or not an OnCookieChanged
259// notification ought to be generated.
[email protected]8bb846f2011-03-23 12:08:18260typedef struct ChangeCausePair_struct {
[email protected]33ad6ce92013-08-27 14:39:08261 CookieMonster::Delegate::ChangeCause cause;
[email protected]8bb846f2011-03-23 12:08:18262 bool notify;
263} ChangeCausePair;
264ChangeCausePair ChangeCauseMapping[] = {
265 // DELETE_COOKIE_EXPLICIT
[email protected]33ad6ce92013-08-27 14:39:08266 { CookieMonster::Delegate::CHANGE_COOKIE_EXPLICIT, true },
[email protected]8bb846f2011-03-23 12:08:18267 // DELETE_COOKIE_OVERWRITE
[email protected]33ad6ce92013-08-27 14:39:08268 { CookieMonster::Delegate::CHANGE_COOKIE_OVERWRITE, true },
[email protected]8bb846f2011-03-23 12:08:18269 // DELETE_COOKIE_EXPIRED
[email protected]33ad6ce92013-08-27 14:39:08270 { CookieMonster::Delegate::CHANGE_COOKIE_EXPIRED, true },
[email protected]8bb846f2011-03-23 12:08:18271 // DELETE_COOKIE_EVICTED
[email protected]33ad6ce92013-08-27 14:39:08272 { CookieMonster::Delegate::CHANGE_COOKIE_EVICTED, true },
[email protected]8bb846f2011-03-23 12:08:18273 // DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE
[email protected]33ad6ce92013-08-27 14:39:08274 { CookieMonster::Delegate::CHANGE_COOKIE_EXPLICIT, false },
[email protected]8bb846f2011-03-23 12:08:18275 // DELETE_COOKIE_DONT_RECORD
[email protected]33ad6ce92013-08-27 14:39:08276 { CookieMonster::Delegate::CHANGE_COOKIE_EXPLICIT, false },
[email protected]8bb846f2011-03-23 12:08:18277 // DELETE_COOKIE_EVICTED_DOMAIN
[email protected]33ad6ce92013-08-27 14:39:08278 { CookieMonster::Delegate::CHANGE_COOKIE_EVICTED, true },
[email protected]8bb846f2011-03-23 12:08:18279 // DELETE_COOKIE_EVICTED_GLOBAL
[email protected]33ad6ce92013-08-27 14:39:08280 { CookieMonster::Delegate::CHANGE_COOKIE_EVICTED, true },
[email protected]8bb846f2011-03-23 12:08:18281 // DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE
[email protected]33ad6ce92013-08-27 14:39:08282 { CookieMonster::Delegate::CHANGE_COOKIE_EVICTED, true },
[email protected]8bb846f2011-03-23 12:08:18283 // DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE
[email protected]33ad6ce92013-08-27 14:39:08284 { CookieMonster::Delegate::CHANGE_COOKIE_EVICTED, true },
[email protected]e7c590e52011-03-30 08:33:55285 // DELETE_COOKIE_EXPIRED_OVERWRITE
[email protected]33ad6ce92013-08-27 14:39:08286 { CookieMonster::Delegate::CHANGE_COOKIE_EXPIRED_OVERWRITE, true },
[email protected]6210ce52013-09-20 03:33:14287 // DELETE_COOKIE_CONTROL_CHAR
288 { CookieMonster::Delegate::CHANGE_COOKIE_EVICTED, true},
[email protected]8bb846f2011-03-23 12:08:18289 // DELETE_COOKIE_LAST_ENTRY
[email protected]33ad6ce92013-08-27 14:39:08290 { CookieMonster::Delegate::CHANGE_COOKIE_EXPLICIT, false }
[email protected]8bb846f2011-03-23 12:08:18291};
292
[email protected]34a160d2011-05-12 22:12:49293std::string BuildCookieLine(const CanonicalCookieVector& cookies) {
294 std::string cookie_line;
295 for (CanonicalCookieVector::const_iterator it = cookies.begin();
296 it != cookies.end(); ++it) {
297 if (it != cookies.begin())
298 cookie_line += "; ";
299 // In Mozilla if you set a cookie like AAAA, it will have an empty token
300 // and a value of AAAA. When it sends the cookie back, it will send AAAA,
301 // so we need to avoid sending =AAAA for a blank token value.
302 if (!(*it)->Name().empty())
303 cookie_line += (*it)->Name() + "=";
304 cookie_line += (*it)->Value();
305 }
306 return cookie_line;
307}
308
[email protected]f48b9432011-01-11 07:25:40309} // namespace
310
[email protected]33ad6ce92013-08-27 14:39:08311// static
312bool CookieMonster::default_enable_file_scheme_ = false;
313
314CookieMonster::CookieMonster(PersistentCookieStore* store, Delegate* delegate)
[email protected]f48b9432011-01-11 07:25:40315 : initialized_(false),
[email protected]218aa6a12011-09-13 17:38:38316 loaded_(false),
[email protected]f48b9432011-01-11 07:25:40317 store_(store),
318 last_access_threshold_(
319 TimeDelta::FromSeconds(kDefaultAccessUpdateThresholdSeconds)),
320 delegate_(delegate),
[email protected]82388662011-03-10 21:04:06321 last_statistic_record_time_(Time::Now()),
[email protected]93c53a32011-12-05 10:40:35322 keep_expired_cookies_(false),
[email protected]8976e292013-11-02 13:38:57323 persist_session_cookies_(false) {
[email protected]f48b9432011-01-11 07:25:40324 InitializeHistograms();
325 SetDefaultCookieableSchemes();
[email protected]2d0f89a2010-12-06 12:02:23326}
327
[email protected]f48b9432011-01-11 07:25:40328CookieMonster::CookieMonster(PersistentCookieStore* store,
[email protected]33ad6ce92013-08-27 14:39:08329 Delegate* delegate,
[email protected]f48b9432011-01-11 07:25:40330 int last_access_threshold_milliseconds)
331 : initialized_(false),
[email protected]218aa6a12011-09-13 17:38:38332 loaded_(false),
[email protected]f48b9432011-01-11 07:25:40333 store_(store),
334 last_access_threshold_(base::TimeDelta::FromMilliseconds(
335 last_access_threshold_milliseconds)),
336 delegate_(delegate),
[email protected]82388662011-03-10 21:04:06337 last_statistic_record_time_(base::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();
initial.commit586acc5fe2008-07-26 22:42:52342}
343
initial.commit586acc5fe2008-07-26 22:42:52344
[email protected]218aa6a12011-09-13 17:38:38345// Task classes for queueing the coming request.
346
347class CookieMonster::CookieMonsterTask
348 : public base::RefCountedThreadSafe<CookieMonsterTask> {
349 public:
350 // Runs the task and invokes the client callback on the thread that
351 // originally constructed the task.
352 virtual void Run() = 0;
353
354 protected:
355 explicit CookieMonsterTask(CookieMonster* cookie_monster);
356 virtual ~CookieMonsterTask();
357
358 // Invokes the callback immediately, if the current thread is the one
359 // that originated the task, or queues the callback for execution on the
360 // appropriate thread. Maintains a reference to this CookieMonsterTask
361 // instance until the callback completes.
362 void InvokeCallback(base::Closure callback);
363
364 CookieMonster* cookie_monster() {
365 return cookie_monster_;
366 }
367
[email protected]a9813302012-04-28 09:29:28368 private:
[email protected]218aa6a12011-09-13 17:38:38369 friend class base::RefCountedThreadSafe<CookieMonsterTask>;
370
[email protected]218aa6a12011-09-13 17:38:38371 CookieMonster* cookie_monster_;
372 scoped_refptr<base::MessageLoopProxy> thread_;
373
374 DISALLOW_COPY_AND_ASSIGN(CookieMonsterTask);
375};
376
377CookieMonster::CookieMonsterTask::CookieMonsterTask(
378 CookieMonster* cookie_monster)
379 : cookie_monster_(cookie_monster),
[email protected]a9813302012-04-28 09:29:28380 thread_(base::MessageLoopProxy::current()) {
381}
[email protected]218aa6a12011-09-13 17:38:38382
[email protected]a9813302012-04-28 09:29:28383CookieMonster::CookieMonsterTask::~CookieMonsterTask() {}
[email protected]218aa6a12011-09-13 17:38:38384
385// Unfortunately, one cannot re-bind a Callback with parameters into a closure.
386// Therefore, the closure passed to InvokeCallback is a clumsy binding of
387// Callback::Run on a wrapped Callback instance. Since Callback is not
388// reference counted, we bind to an instance that is a member of the
389// CookieMonsterTask subclass. Then, we cannot simply post the callback to a
390// message loop because the underlying instance may be destroyed (along with the
391// CookieMonsterTask instance) in the interim. Therefore, we post a callback
392// bound to the CookieMonsterTask, which *is* reference counted (thus preventing
393// destruction of the original callback), and which invokes the closure (which
394// invokes the original callback with the returned data).
395void CookieMonster::CookieMonsterTask::InvokeCallback(base::Closure callback) {
396 if (thread_->BelongsToCurrentThread()) {
397 callback.Run();
398 } else {
399 thread_->PostTask(FROM_HERE, base::Bind(
[email protected]5fa4f9a2013-10-03 10:13:16400 &CookieMonsterTask::InvokeCallback, this, callback));
[email protected]218aa6a12011-09-13 17:38:38401 }
402}
403
404// Task class for SetCookieWithDetails call.
[email protected]5fa4f9a2013-10-03 10:13:16405class CookieMonster::SetCookieWithDetailsTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38406 public:
[email protected]dedec0b2013-02-28 04:50:10407 SetCookieWithDetailsTask(CookieMonster* cookie_monster,
408 const GURL& url,
409 const std::string& name,
410 const std::string& value,
411 const std::string& domain,
412 const std::string& path,
413 const base::Time& expiration_time,
414 bool secure,
415 bool http_only,
[email protected]ab2d75c82013-04-19 18:39:04416 CookiePriority priority,
[email protected]5fa4f9a2013-10-03 10:13:16417 const SetCookiesCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38418 : CookieMonsterTask(cookie_monster),
419 url_(url),
420 name_(name),
421 value_(value),
422 domain_(domain),
423 path_(path),
424 expiration_time_(expiration_time),
425 secure_(secure),
426 http_only_(http_only),
[email protected]ab2d75c82013-04-19 18:39:04427 priority_(priority),
[email protected]a9813302012-04-28 09:29:28428 callback_(callback) {
429 }
[email protected]218aa6a12011-09-13 17:38:38430
[email protected]5fa4f9a2013-10-03 10:13:16431 // CookieMonsterTask:
[email protected]218aa6a12011-09-13 17:38:38432 virtual void Run() OVERRIDE;
433
[email protected]a9813302012-04-28 09:29:28434 protected:
435 virtual ~SetCookieWithDetailsTask() {}
436
[email protected]218aa6a12011-09-13 17:38:38437 private:
438 GURL url_;
439 std::string name_;
440 std::string value_;
441 std::string domain_;
442 std::string path_;
443 base::Time expiration_time_;
444 bool secure_;
445 bool http_only_;
[email protected]ab2d75c82013-04-19 18:39:04446 CookiePriority priority_;
[email protected]5fa4f9a2013-10-03 10:13:16447 SetCookiesCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38448
449 DISALLOW_COPY_AND_ASSIGN(SetCookieWithDetailsTask);
450};
451
452void CookieMonster::SetCookieWithDetailsTask::Run() {
453 bool success = this->cookie_monster()->
454 SetCookieWithDetails(url_, name_, value_, domain_, path_,
[email protected]ab2d75c82013-04-19 18:39:04455 expiration_time_, secure_, http_only_, priority_);
[email protected]218aa6a12011-09-13 17:38:38456 if (!callback_.is_null()) {
[email protected]5fa4f9a2013-10-03 10:13:16457 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38458 base::Unretained(&callback_), success));
459 }
460}
461
462// Task class for GetAllCookies call.
[email protected]5fa4f9a2013-10-03 10:13:16463class CookieMonster::GetAllCookiesTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38464 public:
465 GetAllCookiesTask(CookieMonster* cookie_monster,
[email protected]5fa4f9a2013-10-03 10:13:16466 const GetCookieListCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38467 : CookieMonsterTask(cookie_monster),
[email protected]a9813302012-04-28 09:29:28468 callback_(callback) {
469 }
[email protected]218aa6a12011-09-13 17:38:38470
[email protected]5fa4f9a2013-10-03 10:13:16471 // CookieMonsterTask
[email protected]218aa6a12011-09-13 17:38:38472 virtual void Run() OVERRIDE;
473
[email protected]a9813302012-04-28 09:29:28474 protected:
475 virtual ~GetAllCookiesTask() {}
476
[email protected]218aa6a12011-09-13 17:38:38477 private:
[email protected]5fa4f9a2013-10-03 10:13:16478 GetCookieListCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38479
480 DISALLOW_COPY_AND_ASSIGN(GetAllCookiesTask);
481};
482
483void CookieMonster::GetAllCookiesTask::Run() {
484 if (!callback_.is_null()) {
485 CookieList cookies = this->cookie_monster()->GetAllCookies();
[email protected]5fa4f9a2013-10-03 10:13:16486 this->InvokeCallback(base::Bind(&GetCookieListCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38487 base::Unretained(&callback_), cookies));
488 }
489}
490
491// Task class for GetAllCookiesForURLWithOptions call.
492class CookieMonster::GetAllCookiesForURLWithOptionsTask
[email protected]5fa4f9a2013-10-03 10:13:16493 : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38494 public:
495 GetAllCookiesForURLWithOptionsTask(
496 CookieMonster* cookie_monster,
497 const GURL& url,
498 const CookieOptions& options,
[email protected]5fa4f9a2013-10-03 10:13:16499 const GetCookieListCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38500 : CookieMonsterTask(cookie_monster),
501 url_(url),
502 options_(options),
[email protected]a9813302012-04-28 09:29:28503 callback_(callback) {
504 }
[email protected]218aa6a12011-09-13 17:38:38505
[email protected]5fa4f9a2013-10-03 10:13:16506 // CookieMonsterTask:
[email protected]218aa6a12011-09-13 17:38:38507 virtual void Run() OVERRIDE;
508
[email protected]a9813302012-04-28 09:29:28509 protected:
510 virtual ~GetAllCookiesForURLWithOptionsTask() {}
511
[email protected]218aa6a12011-09-13 17:38:38512 private:
513 GURL url_;
514 CookieOptions options_;
[email protected]5fa4f9a2013-10-03 10:13:16515 GetCookieListCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38516
517 DISALLOW_COPY_AND_ASSIGN(GetAllCookiesForURLWithOptionsTask);
518};
519
520void CookieMonster::GetAllCookiesForURLWithOptionsTask::Run() {
521 if (!callback_.is_null()) {
522 CookieList cookies = this->cookie_monster()->
523 GetAllCookiesForURLWithOptions(url_, options_);
[email protected]5fa4f9a2013-10-03 10:13:16524 this->InvokeCallback(base::Bind(&GetCookieListCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38525 base::Unretained(&callback_), cookies));
526 }
527}
528
[email protected]5fa4f9a2013-10-03 10:13:16529template <typename Result> struct CallbackType {
530 typedef base::Callback<void(Result)> Type;
531};
532
533template <> struct CallbackType<void> {
534 typedef base::Closure Type;
535};
536
537// Base task class for Delete*Task.
538template <typename Result>
539class CookieMonster::DeleteTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38540 public:
[email protected]5fa4f9a2013-10-03 10:13:16541 DeleteTask(CookieMonster* cookie_monster,
542 const typename CallbackType<Result>::Type& callback)
[email protected]218aa6a12011-09-13 17:38:38543 : CookieMonsterTask(cookie_monster),
[email protected]a9813302012-04-28 09:29:28544 callback_(callback) {
545 }
[email protected]218aa6a12011-09-13 17:38:38546
[email protected]5fa4f9a2013-10-03 10:13:16547 // CookieMonsterTask:
[email protected]218aa6a12011-09-13 17:38:38548 virtual void Run() OVERRIDE;
549
[email protected]5fa4f9a2013-10-03 10:13:16550 private:
551 // Runs the delete task and returns a result.
552 virtual Result RunDeleteTask() = 0;
553 base::Closure RunDeleteTaskAndBindCallback();
554 void FlushDone(const base::Closure& callback);
555
556 typename CallbackType<Result>::Type callback_;
557
558 DISALLOW_COPY_AND_ASSIGN(DeleteTask);
559};
560
561template <typename Result>
562base::Closure CookieMonster::DeleteTask<Result>::
563RunDeleteTaskAndBindCallback() {
564 Result result = RunDeleteTask();
565 if (callback_.is_null())
566 return base::Closure();
567 return base::Bind(callback_, result);
568}
569
570template <>
571base::Closure CookieMonster::DeleteTask<void>::RunDeleteTaskAndBindCallback() {
572 RunDeleteTask();
573 return callback_;
574}
575
576template <typename Result>
577void CookieMonster::DeleteTask<Result>::Run() {
578 this->cookie_monster()->FlushStore(
579 base::Bind(&DeleteTask<Result>::FlushDone, this,
580 RunDeleteTaskAndBindCallback()));
581}
582
583template <typename Result>
584void CookieMonster::DeleteTask<Result>::FlushDone(
585 const base::Closure& callback) {
586 if (!callback.is_null()) {
587 this->InvokeCallback(callback);
588 }
589}
590
591// Task class for DeleteAll call.
592class CookieMonster::DeleteAllTask : public DeleteTask<int> {
593 public:
594 DeleteAllTask(CookieMonster* cookie_monster,
595 const DeleteCallback& callback)
[email protected]151132f2013-11-18 21:37:00596 : DeleteTask<int>(cookie_monster, callback) {
[email protected]5fa4f9a2013-10-03 10:13:16597 }
598
599 // DeleteTask:
600 virtual int RunDeleteTask() OVERRIDE;
601
[email protected]a9813302012-04-28 09:29:28602 protected:
603 virtual ~DeleteAllTask() {}
604
[email protected]218aa6a12011-09-13 17:38:38605 private:
[email protected]218aa6a12011-09-13 17:38:38606 DISALLOW_COPY_AND_ASSIGN(DeleteAllTask);
607};
608
[email protected]5fa4f9a2013-10-03 10:13:16609int CookieMonster::DeleteAllTask::RunDeleteTask() {
610 return this->cookie_monster()->DeleteAll(true);
[email protected]218aa6a12011-09-13 17:38:38611}
612
613// Task class for DeleteAllCreatedBetween call.
[email protected]5fa4f9a2013-10-03 10:13:16614class CookieMonster::DeleteAllCreatedBetweenTask : public DeleteTask<int> {
[email protected]218aa6a12011-09-13 17:38:38615 public:
[email protected]dedec0b2013-02-28 04:50:10616 DeleteAllCreatedBetweenTask(CookieMonster* cookie_monster,
617 const Time& delete_begin,
618 const Time& delete_end,
[email protected]5fa4f9a2013-10-03 10:13:16619 const DeleteCallback& callback)
[email protected]151132f2013-11-18 21:37:00620 : DeleteTask<int>(cookie_monster, callback),
[email protected]218aa6a12011-09-13 17:38:38621 delete_begin_(delete_begin),
[email protected]5fa4f9a2013-10-03 10:13:16622 delete_end_(delete_end) {
[email protected]a9813302012-04-28 09:29:28623 }
[email protected]218aa6a12011-09-13 17:38:38624
[email protected]5fa4f9a2013-10-03 10:13:16625 // DeleteTask:
626 virtual int RunDeleteTask() OVERRIDE;
[email protected]218aa6a12011-09-13 17:38:38627
[email protected]a9813302012-04-28 09:29:28628 protected:
629 virtual ~DeleteAllCreatedBetweenTask() {}
630
[email protected]218aa6a12011-09-13 17:38:38631 private:
632 Time delete_begin_;
633 Time delete_end_;
[email protected]218aa6a12011-09-13 17:38:38634
635 DISALLOW_COPY_AND_ASSIGN(DeleteAllCreatedBetweenTask);
636};
637
[email protected]5fa4f9a2013-10-03 10:13:16638int CookieMonster::DeleteAllCreatedBetweenTask::RunDeleteTask() {
639 return this->cookie_monster()->
[email protected]218aa6a12011-09-13 17:38:38640 DeleteAllCreatedBetween(delete_begin_, delete_end_);
[email protected]218aa6a12011-09-13 17:38:38641}
642
643// Task class for DeleteAllForHost call.
[email protected]5fa4f9a2013-10-03 10:13:16644class CookieMonster::DeleteAllForHostTask : public DeleteTask<int> {
[email protected]218aa6a12011-09-13 17:38:38645 public:
646 DeleteAllForHostTask(CookieMonster* cookie_monster,
647 const GURL& url,
[email protected]5fa4f9a2013-10-03 10:13:16648 const DeleteCallback& callback)
[email protected]151132f2013-11-18 21:37:00649 : DeleteTask<int>(cookie_monster, callback),
[email protected]5fa4f9a2013-10-03 10:13:16650 url_(url) {
[email protected]a9813302012-04-28 09:29:28651 }
[email protected]218aa6a12011-09-13 17:38:38652
[email protected]5fa4f9a2013-10-03 10:13:16653 // DeleteTask:
654 virtual int RunDeleteTask() OVERRIDE;
[email protected]218aa6a12011-09-13 17:38:38655
[email protected]a9813302012-04-28 09:29:28656 protected:
657 virtual ~DeleteAllForHostTask() {}
658
[email protected]218aa6a12011-09-13 17:38:38659 private:
660 GURL url_;
[email protected]218aa6a12011-09-13 17:38:38661
662 DISALLOW_COPY_AND_ASSIGN(DeleteAllForHostTask);
663};
664
[email protected]5fa4f9a2013-10-03 10:13:16665int CookieMonster::DeleteAllForHostTask::RunDeleteTask() {
666 return this->cookie_monster()->DeleteAllForHost(url_);
[email protected]218aa6a12011-09-13 17:38:38667}
668
[email protected]d8428d52013-08-07 06:58:25669// Task class for DeleteAllCreatedBetweenForHost call.
670class CookieMonster::DeleteAllCreatedBetweenForHostTask
[email protected]5fa4f9a2013-10-03 10:13:16671 : public DeleteTask<int> {
[email protected]d8428d52013-08-07 06:58:25672 public:
673 DeleteAllCreatedBetweenForHostTask(
674 CookieMonster* cookie_monster,
675 Time delete_begin,
676 Time delete_end,
677 const GURL& url,
[email protected]5fa4f9a2013-10-03 10:13:16678 const DeleteCallback& callback)
[email protected]151132f2013-11-18 21:37:00679 : DeleteTask<int>(cookie_monster, callback),
[email protected]d8428d52013-08-07 06:58:25680 delete_begin_(delete_begin),
681 delete_end_(delete_end),
[email protected]5fa4f9a2013-10-03 10:13:16682 url_(url) {
[email protected]d8428d52013-08-07 06:58:25683 }
684
[email protected]5fa4f9a2013-10-03 10:13:16685 // DeleteTask:
686 virtual int RunDeleteTask() OVERRIDE;
[email protected]d8428d52013-08-07 06:58:25687
688 protected:
689 virtual ~DeleteAllCreatedBetweenForHostTask() {}
690
691 private:
692 Time delete_begin_;
693 Time delete_end_;
694 GURL url_;
[email protected]d8428d52013-08-07 06:58:25695
696 DISALLOW_COPY_AND_ASSIGN(DeleteAllCreatedBetweenForHostTask);
697};
698
[email protected]5fa4f9a2013-10-03 10:13:16699int CookieMonster::DeleteAllCreatedBetweenForHostTask::RunDeleteTask() {
700 return this->cookie_monster()->DeleteAllCreatedBetweenForHost(
[email protected]d8428d52013-08-07 06:58:25701 delete_begin_, delete_end_, url_);
[email protected]d8428d52013-08-07 06:58:25702}
703
[email protected]218aa6a12011-09-13 17:38:38704// Task class for DeleteCanonicalCookie call.
[email protected]5fa4f9a2013-10-03 10:13:16705class CookieMonster::DeleteCanonicalCookieTask : public DeleteTask<bool> {
[email protected]218aa6a12011-09-13 17:38:38706 public:
[email protected]dedec0b2013-02-28 04:50:10707 DeleteCanonicalCookieTask(CookieMonster* cookie_monster,
708 const CanonicalCookie& cookie,
[email protected]5fa4f9a2013-10-03 10:13:16709 const DeleteCookieCallback& callback)
[email protected]151132f2013-11-18 21:37:00710 : DeleteTask<bool>(cookie_monster, callback),
[email protected]5fa4f9a2013-10-03 10:13:16711 cookie_(cookie) {
[email protected]a9813302012-04-28 09:29:28712 }
[email protected]218aa6a12011-09-13 17:38:38713
[email protected]5fa4f9a2013-10-03 10:13:16714 // DeleteTask:
715 virtual bool RunDeleteTask() OVERRIDE;
[email protected]218aa6a12011-09-13 17:38:38716
[email protected]a9813302012-04-28 09:29:28717 protected:
718 virtual ~DeleteCanonicalCookieTask() {}
719
[email protected]218aa6a12011-09-13 17:38:38720 private:
[email protected]5b9bc352012-07-18 13:13:34721 CanonicalCookie cookie_;
[email protected]218aa6a12011-09-13 17:38:38722
723 DISALLOW_COPY_AND_ASSIGN(DeleteCanonicalCookieTask);
724};
725
[email protected]5fa4f9a2013-10-03 10:13:16726bool CookieMonster::DeleteCanonicalCookieTask::RunDeleteTask() {
727 return this->cookie_monster()->DeleteCanonicalCookie(cookie_);
[email protected]218aa6a12011-09-13 17:38:38728}
729
730// Task class for SetCookieWithOptions call.
[email protected]5fa4f9a2013-10-03 10:13:16731class CookieMonster::SetCookieWithOptionsTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38732 public:
733 SetCookieWithOptionsTask(CookieMonster* cookie_monster,
734 const GURL& url,
735 const std::string& cookie_line,
736 const CookieOptions& options,
[email protected]5fa4f9a2013-10-03 10:13:16737 const SetCookiesCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38738 : CookieMonsterTask(cookie_monster),
739 url_(url),
740 cookie_line_(cookie_line),
741 options_(options),
[email protected]a9813302012-04-28 09:29:28742 callback_(callback) {
743 }
[email protected]218aa6a12011-09-13 17:38:38744
[email protected]5fa4f9a2013-10-03 10:13:16745 // CookieMonsterTask:
[email protected]218aa6a12011-09-13 17:38:38746 virtual void Run() OVERRIDE;
747
[email protected]a9813302012-04-28 09:29:28748 protected:
749 virtual ~SetCookieWithOptionsTask() {}
750
[email protected]218aa6a12011-09-13 17:38:38751 private:
752 GURL url_;
753 std::string cookie_line_;
754 CookieOptions options_;
[email protected]5fa4f9a2013-10-03 10:13:16755 SetCookiesCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38756
757 DISALLOW_COPY_AND_ASSIGN(SetCookieWithOptionsTask);
758};
759
760void CookieMonster::SetCookieWithOptionsTask::Run() {
761 bool result = this->cookie_monster()->
762 SetCookieWithOptions(url_, cookie_line_, options_);
763 if (!callback_.is_null()) {
[email protected]5fa4f9a2013-10-03 10:13:16764 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38765 base::Unretained(&callback_), result));
766 }
767}
768
769// Task class for GetCookiesWithOptions call.
[email protected]5fa4f9a2013-10-03 10:13:16770class CookieMonster::GetCookiesWithOptionsTask : public CookieMonsterTask {
[email protected]218aa6a12011-09-13 17:38:38771 public:
772 GetCookiesWithOptionsTask(CookieMonster* cookie_monster,
[email protected]0298caf82011-12-20 23:15:46773 const GURL& url,
[email protected]218aa6a12011-09-13 17:38:38774 const CookieOptions& options,
[email protected]5fa4f9a2013-10-03 10:13:16775 const GetCookiesCallback& callback)
[email protected]218aa6a12011-09-13 17:38:38776 : CookieMonsterTask(cookie_monster),
777 url_(url),
778 options_(options),
[email protected]a9813302012-04-28 09:29:28779 callback_(callback) {
780 }
[email protected]218aa6a12011-09-13 17:38:38781
[email protected]5fa4f9a2013-10-03 10:13:16782 // CookieMonsterTask:
[email protected]218aa6a12011-09-13 17:38:38783 virtual void Run() OVERRIDE;
784
[email protected]a9813302012-04-28 09:29:28785 protected:
786 virtual ~GetCookiesWithOptionsTask() {}
787
[email protected]218aa6a12011-09-13 17:38:38788 private:
789 GURL url_;
790 CookieOptions options_;
[email protected]5fa4f9a2013-10-03 10:13:16791 GetCookiesCallback callback_;
[email protected]218aa6a12011-09-13 17:38:38792
793 DISALLOW_COPY_AND_ASSIGN(GetCookiesWithOptionsTask);
794};
795
796void CookieMonster::GetCookiesWithOptionsTask::Run() {
797 std::string cookie = this->cookie_monster()->
798 GetCookiesWithOptions(url_, options_);
799 if (!callback_.is_null()) {
[email protected]5fa4f9a2013-10-03 10:13:16800 this->InvokeCallback(base::Bind(&GetCookiesCallback::Run,
[email protected]218aa6a12011-09-13 17:38:38801 base::Unretained(&callback_), cookie));
802 }
803}
804
[email protected]218aa6a12011-09-13 17:38:38805// Task class for DeleteCookie call.
[email protected]5fa4f9a2013-10-03 10:13:16806class CookieMonster::DeleteCookieTask : public DeleteTask<void> {
[email protected]218aa6a12011-09-13 17:38:38807 public:
808 DeleteCookieTask(CookieMonster* cookie_monster,
[email protected]0298caf82011-12-20 23:15:46809 const GURL& url,
[email protected]218aa6a12011-09-13 17:38:38810 const std::string& cookie_name,
811 const base::Closure& callback)
[email protected]151132f2013-11-18 21:37:00812 : DeleteTask<void>(cookie_monster, callback),
[email protected]218aa6a12011-09-13 17:38:38813 url_(url),
[email protected]5fa4f9a2013-10-03 10:13:16814 cookie_name_(cookie_name) {
815 }
[email protected]218aa6a12011-09-13 17:38:38816
[email protected]5fa4f9a2013-10-03 10:13:16817 // DeleteTask:
818 virtual void RunDeleteTask() OVERRIDE;
[email protected]218aa6a12011-09-13 17:38:38819
[email protected]a9813302012-04-28 09:29:28820 protected:
821 virtual ~DeleteCookieTask() {}
822
[email protected]218aa6a12011-09-13 17:38:38823 private:
824 GURL url_;
825 std::string cookie_name_;
[email protected]218aa6a12011-09-13 17:38:38826
827 DISALLOW_COPY_AND_ASSIGN(DeleteCookieTask);
828};
829
[email protected]5fa4f9a2013-10-03 10:13:16830void CookieMonster::DeleteCookieTask::RunDeleteTask() {
[email protected]218aa6a12011-09-13 17:38:38831 this->cookie_monster()->DeleteCookie(url_, cookie_name_);
[email protected]218aa6a12011-09-13 17:38:38832}
833
[email protected]264807b2012-04-25 14:49:37834// Task class for DeleteSessionCookies call.
[email protected]5fa4f9a2013-10-03 10:13:16835class CookieMonster::DeleteSessionCookiesTask : public DeleteTask<int> {
[email protected]264807b2012-04-25 14:49:37836 public:
[email protected]dedec0b2013-02-28 04:50:10837 DeleteSessionCookiesTask(CookieMonster* cookie_monster,
[email protected]5fa4f9a2013-10-03 10:13:16838 const DeleteCallback& callback)
[email protected]151132f2013-11-18 21:37:00839 : DeleteTask<int>(cookie_monster, callback) {
[email protected]a9813302012-04-28 09:29:28840 }
[email protected]264807b2012-04-25 14:49:37841
[email protected]5fa4f9a2013-10-03 10:13:16842 // DeleteTask:
843 virtual int RunDeleteTask() OVERRIDE;
[email protected]264807b2012-04-25 14:49:37844
[email protected]a9813302012-04-28 09:29:28845 protected:
846 virtual ~DeleteSessionCookiesTask() {}
847
[email protected]264807b2012-04-25 14:49:37848 private:
[email protected]264807b2012-04-25 14:49:37849
850 DISALLOW_COPY_AND_ASSIGN(DeleteSessionCookiesTask);
851};
852
[email protected]5fa4f9a2013-10-03 10:13:16853int CookieMonster::DeleteSessionCookiesTask::RunDeleteTask() {
854 return this->cookie_monster()->DeleteSessionCookies();
[email protected]264807b2012-04-25 14:49:37855}
856
[email protected]ee209482013-04-19 19:50:04857// Task class for HasCookiesForETLDP1Task call.
[email protected]5fa4f9a2013-10-03 10:13:16858class CookieMonster::HasCookiesForETLDP1Task : public CookieMonsterTask {
[email protected]ee209482013-04-19 19:50:04859 public:
860 HasCookiesForETLDP1Task(
861 CookieMonster* cookie_monster,
862 const std::string& etldp1,
[email protected]5fa4f9a2013-10-03 10:13:16863 const HasCookiesForETLDP1Callback& callback)
[email protected]ee209482013-04-19 19:50:04864 : CookieMonsterTask(cookie_monster),
865 etldp1_(etldp1),
866 callback_(callback) {
867 }
868
[email protected]5fa4f9a2013-10-03 10:13:16869 // CookieMonsterTask:
[email protected]ee209482013-04-19 19:50:04870 virtual void Run() OVERRIDE;
871
872 protected:
873 virtual ~HasCookiesForETLDP1Task() {}
874
875 private:
876 std::string etldp1_;
[email protected]5fa4f9a2013-10-03 10:13:16877 HasCookiesForETLDP1Callback callback_;
[email protected]ee209482013-04-19 19:50:04878
879 DISALLOW_COPY_AND_ASSIGN(HasCookiesForETLDP1Task);
880};
881
882void CookieMonster::HasCookiesForETLDP1Task::Run() {
883 bool result = this->cookie_monster()->HasCookiesForETLDP1(etldp1_);
884 if (!callback_.is_null()) {
885 this->InvokeCallback(
[email protected]5fa4f9a2013-10-03 10:13:16886 base::Bind(&HasCookiesForETLDP1Callback::Run,
[email protected]ee209482013-04-19 19:50:04887 base::Unretained(&callback_), result));
888 }
889}
890
[email protected]218aa6a12011-09-13 17:38:38891// Asynchronous CookieMonster API
892
893void CookieMonster::SetCookieWithDetailsAsync(
[email protected]dedec0b2013-02-28 04:50:10894 const GURL& url,
895 const std::string& name,
896 const std::string& value,
897 const std::string& domain,
898 const std::string& path,
[email protected]d8428d52013-08-07 06:58:25899 const Time& expiration_time,
[email protected]dedec0b2013-02-28 04:50:10900 bool secure,
901 bool http_only,
[email protected]ab2d75c82013-04-19 18:39:04902 CookiePriority priority,
[email protected]218aa6a12011-09-13 17:38:38903 const SetCookiesCallback& callback) {
904 scoped_refptr<SetCookieWithDetailsTask> task =
905 new SetCookieWithDetailsTask(this, url, name, value, domain, path,
[email protected]ab2d75c82013-04-19 18:39:04906 expiration_time, secure, http_only, priority,
[email protected]218aa6a12011-09-13 17:38:38907 callback);
908
[email protected]85620342011-10-17 17:35:04909 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:38910}
911
912void CookieMonster::GetAllCookiesAsync(const GetCookieListCallback& callback) {
913 scoped_refptr<GetAllCookiesTask> task =
914 new GetAllCookiesTask(this, callback);
915
916 DoCookieTask(task);
917}
918
919
920void CookieMonster::GetAllCookiesForURLWithOptionsAsync(
921 const GURL& url,
922 const CookieOptions& options,
923 const GetCookieListCallback& callback) {
924 scoped_refptr<GetAllCookiesForURLWithOptionsTask> task =
925 new GetAllCookiesForURLWithOptionsTask(this, url, options, callback);
926
[email protected]85620342011-10-17 17:35:04927 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:38928}
929
930void CookieMonster::GetAllCookiesForURLAsync(
931 const GURL& url, const GetCookieListCallback& callback) {
932 CookieOptions options;
933 options.set_include_httponly();
934 scoped_refptr<GetAllCookiesForURLWithOptionsTask> task =
935 new GetAllCookiesForURLWithOptionsTask(this, url, options, callback);
936
[email protected]85620342011-10-17 17:35:04937 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:38938}
939
[email protected]ee209482013-04-19 19:50:04940void CookieMonster::HasCookiesForETLDP1Async(
941 const std::string& etldp1,
942 const HasCookiesForETLDP1Callback& callback) {
943 scoped_refptr<HasCookiesForETLDP1Task> task =
944 new HasCookiesForETLDP1Task(this, etldp1, callback);
945
946 DoCookieTaskForURL(task, GURL("http://" + etldp1));
947}
948
[email protected]218aa6a12011-09-13 17:38:38949void CookieMonster::DeleteAllAsync(const DeleteCallback& callback) {
950 scoped_refptr<DeleteAllTask> task =
951 new DeleteAllTask(this, callback);
952
953 DoCookieTask(task);
954}
955
956void CookieMonster::DeleteAllCreatedBetweenAsync(
957 const Time& delete_begin, const Time& delete_end,
958 const DeleteCallback& callback) {
959 scoped_refptr<DeleteAllCreatedBetweenTask> task =
960 new DeleteAllCreatedBetweenTask(this, delete_begin, delete_end,
961 callback);
962
963 DoCookieTask(task);
964}
965
[email protected]d8428d52013-08-07 06:58:25966void CookieMonster::DeleteAllCreatedBetweenForHostAsync(
967 const Time delete_begin,
968 const Time delete_end,
969 const GURL& url,
970 const DeleteCallback& callback) {
971 scoped_refptr<DeleteAllCreatedBetweenForHostTask> task =
972 new DeleteAllCreatedBetweenForHostTask(
973 this, delete_begin, delete_end, url, callback);
974
975 DoCookieTaskForURL(task, url);
976}
977
[email protected]218aa6a12011-09-13 17:38:38978void CookieMonster::DeleteAllForHostAsync(
979 const GURL& url, const DeleteCallback& callback) {
980 scoped_refptr<DeleteAllForHostTask> task =
981 new DeleteAllForHostTask(this, url, callback);
982
[email protected]85620342011-10-17 17:35:04983 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:38984}
985
986void CookieMonster::DeleteCanonicalCookieAsync(
987 const CanonicalCookie& cookie,
988 const DeleteCookieCallback& callback) {
989 scoped_refptr<DeleteCanonicalCookieTask> task =
990 new DeleteCanonicalCookieTask(this, cookie, callback);
991
992 DoCookieTask(task);
993}
994
995void CookieMonster::SetCookieWithOptionsAsync(
996 const GURL& url,
997 const std::string& cookie_line,
998 const CookieOptions& options,
999 const SetCookiesCallback& callback) {
1000 scoped_refptr<SetCookieWithOptionsTask> task =
1001 new SetCookieWithOptionsTask(this, url, cookie_line, options, callback);
1002
[email protected]85620342011-10-17 17:35:041003 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381004}
1005
1006void CookieMonster::GetCookiesWithOptionsAsync(
1007 const GURL& url,
1008 const CookieOptions& options,
1009 const GetCookiesCallback& callback) {
1010 scoped_refptr<GetCookiesWithOptionsTask> task =
1011 new GetCookiesWithOptionsTask(this, url, options, callback);
1012
[email protected]85620342011-10-17 17:35:041013 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381014}
1015
[email protected]218aa6a12011-09-13 17:38:381016void CookieMonster::DeleteCookieAsync(const GURL& url,
1017 const std::string& cookie_name,
1018 const base::Closure& callback) {
1019 scoped_refptr<DeleteCookieTask> task =
1020 new DeleteCookieTask(this, url, cookie_name, callback);
1021
[email protected]85620342011-10-17 17:35:041022 DoCookieTaskForURL(task, url);
[email protected]218aa6a12011-09-13 17:38:381023}
1024
[email protected]264807b2012-04-25 14:49:371025void CookieMonster::DeleteSessionCookiesAsync(
1026 const CookieStore::DeleteCallback& callback) {
1027 scoped_refptr<DeleteSessionCookiesTask> task =
1028 new DeleteSessionCookiesTask(this, callback);
1029
1030 DoCookieTask(task);
1031}
1032
[email protected]218aa6a12011-09-13 17:38:381033void CookieMonster::DoCookieTask(
1034 const scoped_refptr<CookieMonsterTask>& task_item) {
[email protected]218aa6a12011-09-13 17:38:381035 {
1036 base::AutoLock autolock(lock_);
[email protected]85620342011-10-17 17:35:041037 InitIfNecessary();
[email protected]218aa6a12011-09-13 17:38:381038 if (!loaded_) {
[email protected]0184df32013-05-14 00:53:551039 tasks_pending_.push(task_item);
[email protected]218aa6a12011-09-13 17:38:381040 return;
1041 }
1042 }
1043
1044 task_item->Run();
1045}
1046
[email protected]85620342011-10-17 17:35:041047void CookieMonster::DoCookieTaskForURL(
1048 const scoped_refptr<CookieMonsterTask>& task_item,
1049 const GURL& url) {
1050 {
1051 base::AutoLock autolock(lock_);
1052 InitIfNecessary();
1053 // If cookies for the requested domain key (eTLD+1) have been loaded from DB
1054 // then run the task, otherwise load from DB.
1055 if (!loaded_) {
1056 // Checks if the domain key has been loaded.
[email protected]2fb376a2011-11-17 09:22:031057 std::string key(cookie_util::GetEffectiveDomain(url.scheme(),
1058 url.host()));
[email protected]85620342011-10-17 17:35:041059 if (keys_loaded_.find(key) == keys_loaded_.end()) {
1060 std::map<std::string, std::deque<scoped_refptr<CookieMonsterTask> > >
[email protected]0184df32013-05-14 00:53:551061 ::iterator it = tasks_pending_for_key_.find(key);
1062 if (it == tasks_pending_for_key_.end()) {
[email protected]85620342011-10-17 17:35:041063 store_->LoadCookiesForKey(key,
1064 base::Bind(&CookieMonster::OnKeyLoaded, this, key));
[email protected]0184df32013-05-14 00:53:551065 it = tasks_pending_for_key_.insert(std::make_pair(key,
[email protected]85620342011-10-17 17:35:041066 std::deque<scoped_refptr<CookieMonsterTask> >())).first;
1067 }
1068 it->second.push_back(task_item);
1069 return;
1070 }
1071 }
1072 }
1073 task_item->Run();
1074}
1075
[email protected]dedec0b2013-02-28 04:50:101076bool CookieMonster::SetCookieWithDetails(const GURL& url,
1077 const std::string& name,
1078 const std::string& value,
1079 const std::string& domain,
1080 const std::string& path,
1081 const base::Time& expiration_time,
1082 bool secure,
[email protected]ab2d75c82013-04-19 18:39:041083 bool http_only,
1084 CookiePriority priority) {
[email protected]20305ec2011-01-21 04:55:521085 base::AutoLock autolock(lock_);
[email protected]69bb5872010-01-12 20:33:521086
[email protected]f48b9432011-01-11 07:25:401087 if (!HasCookieableScheme(url))
initial.commit586acc5fe2008-07-26 22:42:521088 return false;
1089
[email protected]f48b9432011-01-11 07:25:401090 Time creation_time = CurrentTime();
1091 last_time_seen_ = creation_time;
1092
1093 scoped_ptr<CanonicalCookie> cc;
[email protected]ab2d75c82013-04-19 18:39:041094 cc.reset(CanonicalCookie::Create(url, name, value, domain, path,
1095 creation_time, expiration_time,
1096 secure, http_only, priority));
[email protected]f48b9432011-01-11 07:25:401097
1098 if (!cc.get())
1099 return false;
1100
1101 CookieOptions options;
1102 options.set_include_httponly();
1103 return SetCanonicalCookie(&cc, creation_time, options);
initial.commit586acc5fe2008-07-26 22:42:521104}
1105
[email protected]30fa68c52011-08-12 20:15:361106bool CookieMonster::InitializeFrom(const CookieList& list) {
[email protected]93460df2011-07-20 00:58:211107 base::AutoLock autolock(lock_);
1108 InitIfNecessary();
1109 for (net::CookieList::const_iterator iter = list.begin();
1110 iter != list.end(); ++iter) {
[email protected]5b9bc352012-07-18 13:13:341111 scoped_ptr<CanonicalCookie> cookie(new CanonicalCookie(*iter));
[email protected]93460df2011-07-20 00:58:211112 net::CookieOptions options;
1113 options.set_include_httponly();
[email protected]5b9bc352012-07-18 13:13:341114 if (!SetCanonicalCookie(&cookie, cookie->CreationDate(), options))
[email protected]93460df2011-07-20 00:58:211115 return false;
[email protected]93460df2011-07-20 00:58:211116 }
1117 return true;
1118}
1119
[email protected]f48b9432011-01-11 07:25:401120CookieList CookieMonster::GetAllCookies() {
[email protected]20305ec2011-01-21 04:55:521121 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401122
1123 // This function is being called to scrape the cookie list for management UI
1124 // or similar. We shouldn't show expired cookies in this list since it will
1125 // just be confusing to users, and this function is called rarely enough (and
1126 // is already slow enough) that it's OK to take the time to garbage collect
1127 // the expired cookies now.
1128 //
1129 // Note that this does not prune cookies to be below our limits (if we've
1130 // exceeded them) the way that calling GarbageCollect() would.
1131 GarbageCollectExpired(Time::Now(),
1132 CookieMapItPair(cookies_.begin(), cookies_.end()),
1133 NULL);
1134
1135 // Copy the CanonicalCookie pointers from the map so that we can use the same
1136 // sorter as elsewhere, then copy the result out.
1137 std::vector<CanonicalCookie*> cookie_ptrs;
1138 cookie_ptrs.reserve(cookies_.size());
1139 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end(); ++it)
1140 cookie_ptrs.push_back(it->second);
1141 std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter);
1142
1143 CookieList cookie_list;
1144 cookie_list.reserve(cookie_ptrs.size());
1145 for (std::vector<CanonicalCookie*>::const_iterator it = cookie_ptrs.begin();
1146 it != cookie_ptrs.end(); ++it)
1147 cookie_list.push_back(**it);
1148
1149 return cookie_list;
[email protected]f325f1e12010-04-30 22:38:551150}
1151
[email protected]f48b9432011-01-11 07:25:401152CookieList CookieMonster::GetAllCookiesForURLWithOptions(
1153 const GURL& url,
1154 const CookieOptions& options) {
[email protected]20305ec2011-01-21 04:55:521155 base::AutoLock autolock(lock_);
initial.commit586acc5fe2008-07-26 22:42:521156
[email protected]f48b9432011-01-11 07:25:401157 std::vector<CanonicalCookie*> cookie_ptrs;
1158 FindCookiesForHostAndDomain(url, options, false, &cookie_ptrs);
1159 std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter);
initial.commit586acc5fe2008-07-26 22:42:521160
[email protected]f48b9432011-01-11 07:25:401161 CookieList cookies;
1162 for (std::vector<CanonicalCookie*>::const_iterator it = cookie_ptrs.begin();
1163 it != cookie_ptrs.end(); it++)
1164 cookies.push_back(**it);
initial.commit586acc5fe2008-07-26 22:42:521165
[email protected]f48b9432011-01-11 07:25:401166 return cookies;
initial.commit586acc5fe2008-07-26 22:42:521167}
1168
[email protected]f48b9432011-01-11 07:25:401169CookieList CookieMonster::GetAllCookiesForURL(const GURL& url) {
1170 CookieOptions options;
1171 options.set_include_httponly();
1172
1173 return GetAllCookiesForURLWithOptions(url, options);
[email protected]f325f1e12010-04-30 22:38:551174}
1175
[email protected]f48b9432011-01-11 07:25:401176int CookieMonster::DeleteAll(bool sync_to_store) {
[email protected]20305ec2011-01-21 04:55:521177 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401178
1179 int num_deleted = 0;
1180 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1181 CookieMap::iterator curit = it;
1182 ++it;
1183 InternalDeleteCookie(curit, sync_to_store,
1184 sync_to_store ? DELETE_COOKIE_EXPLICIT :
1185 DELETE_COOKIE_DONT_RECORD /* Destruction. */);
1186 ++num_deleted;
initial.commit586acc5fe2008-07-26 22:42:521187 }
1188
[email protected]f48b9432011-01-11 07:25:401189 return num_deleted;
initial.commit586acc5fe2008-07-26 22:42:521190}
1191
[email protected]f48b9432011-01-11 07:25:401192int CookieMonster::DeleteAllCreatedBetween(const Time& delete_begin,
[email protected]218aa6a12011-09-13 17:38:381193 const Time& delete_end) {
[email protected]20305ec2011-01-21 04:55:521194 base::AutoLock autolock(lock_);
[email protected]d0980332010-11-16 17:08:531195
[email protected]f48b9432011-01-11 07:25:401196 int num_deleted = 0;
1197 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1198 CookieMap::iterator curit = it;
1199 CanonicalCookie* cc = curit->second;
1200 ++it;
[email protected]d0980332010-11-16 17:08:531201
[email protected]f48b9432011-01-11 07:25:401202 if (cc->CreationDate() >= delete_begin &&
1203 (delete_end.is_null() || cc->CreationDate() < delete_end)) {
[email protected]218aa6a12011-09-13 17:38:381204 InternalDeleteCookie(curit,
1205 true, /*sync_to_store*/
1206 DELETE_COOKIE_EXPLICIT);
[email protected]f48b9432011-01-11 07:25:401207 ++num_deleted;
initial.commit586acc5fe2008-07-26 22:42:521208 }
1209 }
1210
[email protected]f48b9432011-01-11 07:25:401211 return num_deleted;
1212}
1213
[email protected]d8428d52013-08-07 06:58:251214int CookieMonster::DeleteAllCreatedBetweenForHost(const Time delete_begin,
1215 const Time delete_end,
1216 const GURL& url) {
[email protected]20305ec2011-01-21 04:55:521217 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401218
1219 if (!HasCookieableScheme(url))
1220 return 0;
1221
[email protected]f48b9432011-01-11 07:25:401222 const std::string host(url.host());
1223
1224 // We store host cookies in the store by their canonical host name;
1225 // domain cookies are stored with a leading ".". So this is a pretty
1226 // simple lookup and per-cookie delete.
1227 int num_deleted = 0;
1228 for (CookieMapItPair its = cookies_.equal_range(GetKey(host));
1229 its.first != its.second;) {
1230 CookieMap::iterator curit = its.first;
1231 ++its.first;
1232
1233 const CanonicalCookie* const cc = curit->second;
1234
1235 // Delete only on a match as a host cookie.
[email protected]d8428d52013-08-07 06:58:251236 if (cc->IsHostCookie() && cc->IsDomainMatch(host) &&
1237 cc->CreationDate() >= delete_begin &&
1238 // The assumption that null |delete_end| is equivalent to
1239 // Time::Max() is confusing.
1240 (delete_end.is_null() || cc->CreationDate() < delete_end)) {
[email protected]f48b9432011-01-11 07:25:401241 num_deleted++;
1242
1243 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT);
1244 }
1245 }
1246 return num_deleted;
1247}
1248
[email protected]d8428d52013-08-07 06:58:251249int CookieMonster::DeleteAllForHost(const GURL& url) {
1250 return DeleteAllCreatedBetweenForHost(Time(), Time::Max(), url);
1251}
1252
1253
[email protected]f48b9432011-01-11 07:25:401254bool CookieMonster::DeleteCanonicalCookie(const CanonicalCookie& cookie) {
[email protected]20305ec2011-01-21 04:55:521255 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401256
1257 for (CookieMapItPair its = cookies_.equal_range(GetKey(cookie.Domain()));
1258 its.first != its.second; ++its.first) {
1259 // The creation date acts as our unique index...
1260 if (its.first->second->CreationDate() == cookie.CreationDate()) {
1261 InternalDeleteCookie(its.first, true, DELETE_COOKIE_EXPLICIT);
1262 return true;
1263 }
1264 }
initial.commit586acc5fe2008-07-26 22:42:521265 return false;
1266}
1267
[email protected]dedec0b2013-02-28 04:50:101268void CookieMonster::SetCookieableSchemes(const char* schemes[],
1269 size_t num_schemes) {
[email protected]20305ec2011-01-21 04:55:521270 base::AutoLock autolock(lock_);
[email protected]bb8905722010-05-21 17:29:041271
[email protected]cf12bd12010-06-17 14:41:301272 // Cookieable Schemes must be set before first use of function.
1273 DCHECK(!initialized_);
1274
[email protected]47accfd62009-05-14 18:46:211275 cookieable_schemes_.clear();
1276 cookieable_schemes_.insert(cookieable_schemes_.end(),
1277 schemes, schemes + num_schemes);
1278}
1279
[email protected]97a3b6e2012-06-12 01:53:561280void CookieMonster::SetEnableFileScheme(bool accept) {
1281 // This assumes "file" is always at the end of the array. See the comment
1282 // above kDefaultCookieableSchemes.
1283 int num_schemes = accept ? kDefaultCookieableSchemesCount :
1284 kDefaultCookieableSchemesCount - 1;
1285 SetCookieableSchemes(kDefaultCookieableSchemes, num_schemes);
1286}
1287
[email protected]ba4ad0e2011-03-15 08:12:471288void CookieMonster::SetKeepExpiredCookies() {
1289 keep_expired_cookies_ = true;
1290}
1291
[email protected]33ad6ce92013-08-27 14:39:081292// static
1293void CookieMonster::EnableFileScheme() {
1294 default_enable_file_scheme_ = true;
1295}
1296
[email protected]e67f0f42011-12-20 02:29:211297void CookieMonster::FlushStore(const base::Closure& callback) {
[email protected]20305ec2011-01-21 04:55:521298 base::AutoLock autolock(lock_);
[email protected]90499482013-06-01 00:39:501299 if (initialized_ && store_.get())
[email protected]e67f0f42011-12-20 02:29:211300 store_->Flush(callback);
1301 else if (!callback.is_null())
[email protected]2da659e2013-05-23 20:51:341302 base::MessageLoop::current()->PostTask(FROM_HERE, callback);
[email protected]f48b9432011-01-11 07:25:401303}
1304
1305bool CookieMonster::SetCookieWithOptions(const GURL& url,
1306 const std::string& cookie_line,
1307 const CookieOptions& options) {
[email protected]20305ec2011-01-21 04:55:521308 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401309
1310 if (!HasCookieableScheme(url)) {
1311 return false;
1312 }
1313
[email protected]f48b9432011-01-11 07:25:401314 return SetCookieWithCreationTimeAndOptions(url, cookie_line, Time(), options);
1315}
1316
1317std::string CookieMonster::GetCookiesWithOptions(const GURL& url,
1318 const CookieOptions& options) {
[email protected]20305ec2011-01-21 04:55:521319 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401320
[email protected]34a160d2011-05-12 22:12:491321 if (!HasCookieableScheme(url))
[email protected]f48b9432011-01-11 07:25:401322 return std::string();
[email protected]f48b9432011-01-11 07:25:401323
1324 TimeTicks start_time(TimeTicks::Now());
1325
[email protected]f48b9432011-01-11 07:25:401326 std::vector<CanonicalCookie*> cookies;
1327 FindCookiesForHostAndDomain(url, options, true, &cookies);
1328 std::sort(cookies.begin(), cookies.end(), CookieSorter);
1329
[email protected]34a160d2011-05-12 22:12:491330 std::string cookie_line = BuildCookieLine(cookies);
[email protected]f48b9432011-01-11 07:25:401331
1332 histogram_time_get_->AddTime(TimeTicks::Now() - start_time);
1333
1334 VLOG(kVlogGetCookies) << "GetCookies() result: " << cookie_line;
1335
1336 return cookie_line;
1337}
1338
1339void CookieMonster::DeleteCookie(const GURL& url,
1340 const std::string& cookie_name) {
[email protected]20305ec2011-01-21 04:55:521341 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401342
1343 if (!HasCookieableScheme(url))
1344 return;
1345
1346 CookieOptions options;
1347 options.set_include_httponly();
1348 // Get the cookies for this host and its domain(s).
1349 std::vector<CanonicalCookie*> cookies;
1350 FindCookiesForHostAndDomain(url, options, true, &cookies);
1351 std::set<CanonicalCookie*> matching_cookies;
1352
1353 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
1354 it != cookies.end(); ++it) {
1355 if ((*it)->Name() != cookie_name)
1356 continue;
1357 if (url.path().find((*it)->Path()))
1358 continue;
1359 matching_cookies.insert(*it);
1360 }
1361
1362 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1363 CookieMap::iterator curit = it;
1364 ++it;
1365 if (matching_cookies.find(curit->second) != matching_cookies.end()) {
1366 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT);
1367 }
1368 }
1369}
1370
[email protected]264807b2012-04-25 14:49:371371int CookieMonster::DeleteSessionCookies() {
1372 base::AutoLock autolock(lock_);
1373
1374 int num_deleted = 0;
1375 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1376 CookieMap::iterator curit = it;
1377 CanonicalCookie* cc = curit->second;
1378 ++it;
1379
1380 if (!cc->IsPersistent()) {
1381 InternalDeleteCookie(curit,
1382 true, /*sync_to_store*/
1383 DELETE_COOKIE_EXPIRED);
1384 ++num_deleted;
1385 }
1386 }
1387
1388 return num_deleted;
1389}
1390
[email protected]ee209482013-04-19 19:50:041391bool CookieMonster::HasCookiesForETLDP1(const std::string& etldp1) {
1392 base::AutoLock autolock(lock_);
1393
1394 const std::string key(GetKey(etldp1));
1395
1396 CookieMapItPair its = cookies_.equal_range(key);
1397 return its.first != its.second;
1398}
1399
[email protected]f48b9432011-01-11 07:25:401400CookieMonster* CookieMonster::GetCookieMonster() {
1401 return this;
1402}
1403
[email protected]8ad5d462013-05-02 08:45:261404// This function must be called before the CookieMonster is used.
[email protected]93c53a32011-12-05 10:40:351405void CookieMonster::SetPersistSessionCookies(bool persist_session_cookies) {
[email protected]93c53a32011-12-05 10:40:351406 DCHECK(!initialized_);
1407 persist_session_cookies_ = persist_session_cookies;
1408}
1409
[email protected]bf510ed2012-06-05 08:31:431410void CookieMonster::SetForceKeepSessionState() {
[email protected]90499482013-06-01 00:39:501411 if (store_.get()) {
[email protected]bf510ed2012-06-05 08:31:431412 store_->SetForceKeepSessionState();
[email protected]93c53a32011-12-05 10:40:351413 }
1414}
1415
[email protected]f48b9432011-01-11 07:25:401416CookieMonster::~CookieMonster() {
1417 DeleteAll(false);
1418}
1419
1420bool CookieMonster::SetCookieWithCreationTime(const GURL& url,
1421 const std::string& cookie_line,
1422 const base::Time& creation_time) {
[email protected]90499482013-06-01 00:39:501423 DCHECK(!store_.get()) << "This method is only to be used by unit-tests.";
[email protected]20305ec2011-01-21 04:55:521424 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401425
1426 if (!HasCookieableScheme(url)) {
1427 return false;
1428 }
1429
1430 InitIfNecessary();
1431 return SetCookieWithCreationTimeAndOptions(url, cookie_line, creation_time,
1432 CookieOptions());
1433}
1434
1435void CookieMonster::InitStore() {
[email protected]90499482013-06-01 00:39:501436 DCHECK(store_.get()) << "Store must exist to initialize";
[email protected]f48b9432011-01-11 07:25:401437
[email protected]218aa6a12011-09-13 17:38:381438 // We bind in the current time so that we can report the wall-clock time for
1439 // loading cookies.
1440 store_->Load(base::Bind(&CookieMonster::OnLoaded, this, TimeTicks::Now()));
1441}
[email protected]f48b9432011-01-11 07:25:401442
[email protected]218aa6a12011-09-13 17:38:381443void CookieMonster::OnLoaded(TimeTicks beginning_time,
1444 const std::vector<CanonicalCookie*>& cookies) {
1445 StoreLoadedCookies(cookies);
[email protected]c7593fb22011-11-14 23:54:271446 histogram_time_blocked_on_load_->AddTime(TimeTicks::Now() - beginning_time);
[email protected]218aa6a12011-09-13 17:38:381447
1448 // Invoke the task queue of cookie request.
1449 InvokeQueue();
1450}
1451
[email protected]85620342011-10-17 17:35:041452void CookieMonster::OnKeyLoaded(const std::string& key,
1453 const std::vector<CanonicalCookie*>& cookies) {
1454 // This function does its own separate locking.
1455 StoreLoadedCookies(cookies);
1456
[email protected]0184df32013-05-14 00:53:551457 std::deque<scoped_refptr<CookieMonsterTask> > tasks_pending_for_key;
[email protected]85620342011-10-17 17:35:041458
[email protected]bab72ec2013-10-30 20:50:021459 // We need to do this repeatedly until no more tasks were added to the queue
1460 // during the period where we release the lock.
1461 while (true) {
1462 {
1463 base::AutoLock autolock(lock_);
1464 std::map<std::string, std::deque<scoped_refptr<CookieMonsterTask> > >
1465 ::iterator it = tasks_pending_for_key_.find(key);
1466 if (it == tasks_pending_for_key_.end()) {
1467 keys_loaded_.insert(key);
1468 return;
1469 }
1470 if (it->second.empty()) {
1471 keys_loaded_.insert(key);
1472 tasks_pending_for_key_.erase(it);
1473 return;
1474 }
1475 it->second.swap(tasks_pending_for_key);
1476 }
1477
1478 while (!tasks_pending_for_key.empty()) {
1479 scoped_refptr<CookieMonsterTask> task = tasks_pending_for_key.front();
1480 task->Run();
1481 tasks_pending_for_key.pop_front();
1482 }
[email protected]85620342011-10-17 17:35:041483 }
1484}
1485
[email protected]218aa6a12011-09-13 17:38:381486void CookieMonster::StoreLoadedCookies(
1487 const std::vector<CanonicalCookie*>& cookies) {
[email protected]f48b9432011-01-11 07:25:401488 // Initialize the store and sync in any saved persistent cookies. We don't
1489 // care if it's expired, insert it so it can be garbage collected, removed,
1490 // and sync'd.
[email protected]218aa6a12011-09-13 17:38:381491 base::AutoLock autolock(lock_);
[email protected]f48b9432011-01-11 07:25:401492
[email protected]6210ce52013-09-20 03:33:141493 CookieItVector cookies_with_control_chars;
1494
[email protected]f48b9432011-01-11 07:25:401495 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
1496 it != cookies.end(); ++it) {
1497 int64 cookie_creation_time = (*it)->CreationDate().ToInternalValue();
1498
[email protected]85620342011-10-17 17:35:041499 if (creation_times_.insert(cookie_creation_time).second) {
[email protected]6210ce52013-09-20 03:33:141500 CookieMap::iterator inserted =
1501 InternalInsertCookie(GetKey((*it)->Domain()), *it, false);
[email protected]f48b9432011-01-11 07:25:401502 const Time cookie_access_time((*it)->LastAccessDate());
[email protected]85620342011-10-17 17:35:041503 if (earliest_access_time_.is_null() ||
1504 cookie_access_time < earliest_access_time_)
1505 earliest_access_time_ = cookie_access_time;
[email protected]6210ce52013-09-20 03:33:141506
1507 if (ContainsControlCharacter((*it)->Name()) ||
1508 ContainsControlCharacter((*it)->Value())) {
1509 cookies_with_control_chars.push_back(inserted);
1510 }
[email protected]f48b9432011-01-11 07:25:401511 } else {
1512 LOG(ERROR) << base::StringPrintf("Found cookies with duplicate creation "
1513 "times in backing store: "
1514 "{name='%s', domain='%s', path='%s'}",
1515 (*it)->Name().c_str(),
1516 (*it)->Domain().c_str(),
1517 (*it)->Path().c_str());
1518 // We've been given ownership of the cookie and are throwing it
1519 // away; reclaim the space.
1520 delete (*it);
1521 }
1522 }
[email protected]f48b9432011-01-11 07:25:401523
[email protected]6210ce52013-09-20 03:33:141524 // Any cookies that contain control characters that we have loaded from the
1525 // persistent store should be deleted. See http://crbug.com/238041.
1526 for (CookieItVector::iterator it = cookies_with_control_chars.begin();
1527 it != cookies_with_control_chars.end();) {
1528 CookieItVector::iterator curit = it;
1529 ++it;
1530
1531 InternalDeleteCookie(*curit, true, DELETE_COOKIE_CONTROL_CHAR);
1532 }
1533
[email protected]f48b9432011-01-11 07:25:401534 // After importing cookies from the PersistentCookieStore, verify that
1535 // none of our other constraints are violated.
[email protected]f48b9432011-01-11 07:25:401536 // In particular, the backing store might have given us duplicate cookies.
[email protected]85620342011-10-17 17:35:041537
1538 // This method could be called multiple times due to priority loading, thus
1539 // cookies loaded in previous runs will be validated again, but this is OK
1540 // since they are expected to be much fewer than total DB.
[email protected]f48b9432011-01-11 07:25:401541 EnsureCookiesMapIsValid();
[email protected]218aa6a12011-09-13 17:38:381542}
[email protected]f48b9432011-01-11 07:25:401543
[email protected]218aa6a12011-09-13 17:38:381544void CookieMonster::InvokeQueue() {
1545 while (true) {
1546 scoped_refptr<CookieMonsterTask> request_task;
1547 {
1548 base::AutoLock autolock(lock_);
[email protected]0184df32013-05-14 00:53:551549 if (tasks_pending_.empty()) {
[email protected]218aa6a12011-09-13 17:38:381550 loaded_ = true;
[email protected]85620342011-10-17 17:35:041551 creation_times_.clear();
1552 keys_loaded_.clear();
[email protected]218aa6a12011-09-13 17:38:381553 break;
1554 }
[email protected]0184df32013-05-14 00:53:551555 request_task = tasks_pending_.front();
1556 tasks_pending_.pop();
[email protected]218aa6a12011-09-13 17:38:381557 }
1558 request_task->Run();
1559 }
[email protected]f48b9432011-01-11 07:25:401560}
1561
1562void CookieMonster::EnsureCookiesMapIsValid() {
1563 lock_.AssertAcquired();
1564
1565 int num_duplicates_trimmed = 0;
1566
1567 // Iterate through all the of the cookies, grouped by host.
1568 CookieMap::iterator prev_range_end = cookies_.begin();
1569 while (prev_range_end != cookies_.end()) {
1570 CookieMap::iterator cur_range_begin = prev_range_end;
1571 const std::string key = cur_range_begin->first; // Keep a copy.
1572 CookieMap::iterator cur_range_end = cookies_.upper_bound(key);
1573 prev_range_end = cur_range_end;
1574
1575 // Ensure no equivalent cookies for this host.
1576 num_duplicates_trimmed +=
1577 TrimDuplicateCookiesForKey(key, cur_range_begin, cur_range_end);
1578 }
1579
1580 // Record how many duplicates were found in the database.
1581 // See InitializeHistograms() for details.
1582 histogram_cookie_deletion_cause_->Add(num_duplicates_trimmed);
1583}
1584
1585int CookieMonster::TrimDuplicateCookiesForKey(
1586 const std::string& key,
1587 CookieMap::iterator begin,
1588 CookieMap::iterator end) {
1589 lock_.AssertAcquired();
1590
1591 // Set of cookies ordered by creation time.
1592 typedef std::set<CookieMap::iterator, OrderByCreationTimeDesc> CookieSet;
1593
1594 // Helper map we populate to find the duplicates.
1595 typedef std::map<CookieSignature, CookieSet> EquivalenceMap;
1596 EquivalenceMap equivalent_cookies;
1597
1598 // The number of duplicate cookies that have been found.
1599 int num_duplicates = 0;
1600
1601 // Iterate through all of the cookies in our range, and insert them into
1602 // the equivalence map.
1603 for (CookieMap::iterator it = begin; it != end; ++it) {
1604 DCHECK_EQ(key, it->first);
1605 CanonicalCookie* cookie = it->second;
1606
1607 CookieSignature signature(cookie->Name(), cookie->Domain(),
1608 cookie->Path());
1609 CookieSet& set = equivalent_cookies[signature];
1610
1611 // We found a duplicate!
1612 if (!set.empty())
1613 num_duplicates++;
1614
1615 // We save the iterator into |cookies_| rather than the actual cookie
1616 // pointer, since we may need to delete it later.
1617 bool insert_success = set.insert(it).second;
1618 DCHECK(insert_success) <<
1619 "Duplicate creation times found in duplicate cookie name scan.";
1620 }
1621
1622 // If there were no duplicates, we are done!
1623 if (num_duplicates == 0)
1624 return 0;
1625
1626 // Make sure we find everything below that we did above.
1627 int num_duplicates_found = 0;
1628
1629 // Otherwise, delete all the duplicate cookies, both from our in-memory store
1630 // and from the backing store.
1631 for (EquivalenceMap::iterator it = equivalent_cookies.begin();
1632 it != equivalent_cookies.end();
1633 ++it) {
1634 const CookieSignature& signature = it->first;
1635 CookieSet& dupes = it->second;
1636
1637 if (dupes.size() <= 1)
1638 continue; // This cookiename/path has no duplicates.
1639 num_duplicates_found += dupes.size() - 1;
1640
1641 // Since |dups| is sorted by creation time (descending), the first cookie
1642 // is the most recent one, so we will keep it. The rest are duplicates.
1643 dupes.erase(dupes.begin());
1644
1645 LOG(ERROR) << base::StringPrintf(
1646 "Found %d duplicate cookies for host='%s', "
1647 "with {name='%s', domain='%s', path='%s'}",
1648 static_cast<int>(dupes.size()),
1649 key.c_str(),
1650 signature.name.c_str(),
1651 signature.domain.c_str(),
1652 signature.path.c_str());
1653
1654 // Remove all the cookies identified by |dupes|. It is valid to delete our
1655 // list of iterators one at a time, since |cookies_| is a multimap (they
1656 // don't invalidate existing iterators following deletion).
1657 for (CookieSet::iterator dupes_it = dupes.begin();
1658 dupes_it != dupes.end();
1659 ++dupes_it) {
[email protected]218aa6a12011-09-13 17:38:381660 InternalDeleteCookie(*dupes_it, true,
[email protected]f48b9432011-01-11 07:25:401661 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE);
1662 }
1663 }
1664 DCHECK_EQ(num_duplicates, num_duplicates_found);
1665
1666 return num_duplicates;
1667}
1668
[email protected]ba4ad0e2011-03-15 08:12:471669// Note: file must be the last scheme.
1670const char* CookieMonster::kDefaultCookieableSchemes[] =
1671 { "http", "https", "file" };
1672const int CookieMonster::kDefaultCookieableSchemesCount =
[email protected]5fa4f9a2013-10-03 10:13:161673 arraysize(kDefaultCookieableSchemes);
[email protected]ba4ad0e2011-03-15 08:12:471674
[email protected]f48b9432011-01-11 07:25:401675void CookieMonster::SetDefaultCookieableSchemes() {
[email protected]33ad6ce92013-08-27 14:39:081676 int num_schemes = default_enable_file_scheme_ ?
1677 kDefaultCookieableSchemesCount : kDefaultCookieableSchemesCount - 1;
1678 SetCookieableSchemes(kDefaultCookieableSchemes, num_schemes);
[email protected]f48b9432011-01-11 07:25:401679}
1680
[email protected]f48b9432011-01-11 07:25:401681void CookieMonster::FindCookiesForHostAndDomain(
1682 const GURL& url,
1683 const CookieOptions& options,
1684 bool update_access_time,
1685 std::vector<CanonicalCookie*>* cookies) {
1686 lock_.AssertAcquired();
1687
1688 const Time current_time(CurrentTime());
1689
1690 // Probe to save statistics relatively frequently. We do it here rather
1691 // than in the set path as many websites won't set cookies, and we
1692 // want to collect statistics whenever the browser's being used.
1693 RecordPeriodicStats(current_time);
1694
[email protected]8e1583672012-02-11 04:39:411695 // Can just dispatch to FindCookiesForKey
1696 const std::string key(GetKey(url.host()));
1697 FindCookiesForKey(key, url, options, current_time,
1698 update_access_time, cookies);
[email protected]f48b9432011-01-11 07:25:401699}
1700
[email protected]dedec0b2013-02-28 04:50:101701void CookieMonster::FindCookiesForKey(const std::string& key,
1702 const GURL& url,
1703 const CookieOptions& options,
1704 const Time& current,
1705 bool update_access_time,
1706 std::vector<CanonicalCookie*>* cookies) {
[email protected]f48b9432011-01-11 07:25:401707 lock_.AssertAcquired();
1708
[email protected]f48b9432011-01-11 07:25:401709 for (CookieMapItPair its = cookies_.equal_range(key);
1710 its.first != its.second; ) {
1711 CookieMap::iterator curit = its.first;
1712 CanonicalCookie* cc = curit->second;
1713 ++its.first;
1714
1715 // If the cookie is expired, delete it.
[email protected]ba4ad0e2011-03-15 08:12:471716 if (cc->IsExpired(current) && !keep_expired_cookies_) {
[email protected]f48b9432011-01-11 07:25:401717 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
1718 continue;
1719 }
1720
[email protected]65f4e7e2012-12-12 21:56:541721 // Filter out cookies that should not be included for a request to the
1722 // given |url|. HTTP only cookies are filtered depending on the passed
1723 // cookie |options|.
1724 if (!cc->IncludeForRequestURL(url, options))
[email protected]f48b9432011-01-11 07:25:401725 continue;
1726
[email protected]65f4e7e2012-12-12 21:56:541727 // Add this cookie to the set of matching cookies. Update the access
[email protected]f48b9432011-01-11 07:25:401728 // time if we've been requested to do so.
1729 if (update_access_time) {
1730 InternalUpdateCookieAccessTime(cc, current);
1731 }
1732 cookies->push_back(cc);
1733 }
1734}
1735
1736bool CookieMonster::DeleteAnyEquivalentCookie(const std::string& key,
1737 const CanonicalCookie& ecc,
[email protected]e7c590e52011-03-30 08:33:551738 bool skip_httponly,
1739 bool already_expired) {
[email protected]f48b9432011-01-11 07:25:401740 lock_.AssertAcquired();
1741
1742 bool found_equivalent_cookie = false;
1743 bool skipped_httponly = false;
1744 for (CookieMapItPair its = cookies_.equal_range(key);
1745 its.first != its.second; ) {
1746 CookieMap::iterator curit = its.first;
1747 CanonicalCookie* cc = curit->second;
1748 ++its.first;
1749
1750 if (ecc.IsEquivalent(*cc)) {
1751 // We should never have more than one equivalent cookie, since they should
1752 // overwrite each other.
1753 CHECK(!found_equivalent_cookie) <<
1754 "Duplicate equivalent cookies found, cookie store is corrupted.";
1755 if (skip_httponly && cc->IsHttpOnly()) {
1756 skipped_httponly = true;
1757 } else {
[email protected]e7c590e52011-03-30 08:33:551758 InternalDeleteCookie(curit, true, already_expired ?
1759 DELETE_COOKIE_EXPIRED_OVERWRITE : DELETE_COOKIE_OVERWRITE);
[email protected]f48b9432011-01-11 07:25:401760 }
1761 found_equivalent_cookie = true;
1762 }
1763 }
1764 return skipped_httponly;
1765}
1766
[email protected]6210ce52013-09-20 03:33:141767CookieMonster::CookieMap::iterator CookieMonster::InternalInsertCookie(
1768 const std::string& key,
1769 CanonicalCookie* cc,
1770 bool sync_to_store) {
[email protected]f48b9432011-01-11 07:25:401771 lock_.AssertAcquired();
1772
[email protected]90499482013-06-01 00:39:501773 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() &&
1774 sync_to_store)
[email protected]f48b9432011-01-11 07:25:401775 store_->AddCookie(*cc);
[email protected]6210ce52013-09-20 03:33:141776 CookieMap::iterator inserted =
1777 cookies_.insert(CookieMap::value_type(key, cc));
[email protected]8bb846f2011-03-23 12:08:181778 if (delegate_.get()) {
1779 delegate_->OnCookieChanged(
[email protected]5fa4f9a2013-10-03 10:13:161780 *cc, false, Delegate::CHANGE_COOKIE_EXPLICIT);
[email protected]8bb846f2011-03-23 12:08:181781 }
[email protected]6210ce52013-09-20 03:33:141782
1783 return inserted;
[email protected]f48b9432011-01-11 07:25:401784}
1785
[email protected]34602282010-02-03 22:14:151786bool CookieMonster::SetCookieWithCreationTimeAndOptions(
1787 const GURL& url,
1788 const std::string& cookie_line,
1789 const Time& creation_time_or_null,
1790 const CookieOptions& options) {
[email protected]b866a02d2010-07-28 16:41:041791 lock_.AssertAcquired();
initial.commit586acc5fe2008-07-26 22:42:521792
[email protected]4d3ce782010-10-29 18:31:281793 VLOG(kVlogSetCookies) << "SetCookie() line: " << cookie_line;
initial.commit586acc5fe2008-07-26 22:42:521794
[email protected]34602282010-02-03 22:14:151795 Time creation_time = creation_time_or_null;
1796 if (creation_time.is_null()) {
1797 creation_time = CurrentTime();
1798 last_time_seen_ = creation_time;
1799 }
1800
[email protected]abbd13b2012-11-15 17:54:201801 scoped_ptr<CanonicalCookie> cc(
1802 CanonicalCookie::Create(url, cookie_line, creation_time, options));
initial.commit586acc5fe2008-07-26 22:42:521803
1804 if (!cc.get()) {
[email protected]4d3ce782010-10-29 18:31:281805 VLOG(kVlogSetCookies) << "WARNING: Failed to allocate CanonicalCookie";
initial.commit586acc5fe2008-07-26 22:42:521806 return false;
1807 }
[email protected]fa77eb512010-07-22 16:12:511808 return SetCanonicalCookie(&cc, creation_time, options);
[email protected]f325f1e12010-04-30 22:38:551809}
initial.commit586acc5fe2008-07-26 22:42:521810
[email protected]f325f1e12010-04-30 22:38:551811bool CookieMonster::SetCanonicalCookie(scoped_ptr<CanonicalCookie>* cc,
[email protected]f325f1e12010-04-30 22:38:551812 const Time& creation_time,
1813 const CookieOptions& options) {
[email protected]7a964a72010-09-07 19:33:261814 const std::string key(GetKey((*cc)->Domain()));
[email protected]e7c590e52011-03-30 08:33:551815 bool already_expired = (*cc)->IsExpired(creation_time);
1816 if (DeleteAnyEquivalentCookie(key, **cc, options.exclude_httponly(),
1817 already_expired)) {
[email protected]4d3ce782010-10-29 18:31:281818 VLOG(kVlogSetCookies) << "SetCookie() not clobbering httponly cookie";
[email protected]3a96c742008-11-19 19:46:271819 return false;
1820 }
initial.commit586acc5fe2008-07-26 22:42:521821
[email protected]4d3ce782010-10-29 18:31:281822 VLOG(kVlogSetCookies) << "SetCookie() key: " << key << " cc: "
1823 << (*cc)->DebugString();
initial.commit586acc5fe2008-07-26 22:42:521824
1825 // Realize that we might be setting an expired cookie, and the only point
1826 // was to delete the cookie which we've already done.
[email protected]e7c590e52011-03-30 08:33:551827 if (!already_expired || keep_expired_cookies_) {
[email protected]374f58b2010-07-20 15:29:261828 // See InitializeHistograms() for details.
[email protected]10b691f2012-07-11 15:22:151829 if ((*cc)->IsPersistent()) {
[email protected]8475bee2011-03-17 18:40:241830 histogram_expiration_duration_minutes_->Add(
1831 ((*cc)->ExpiryDate() - creation_time).InMinutes());
1832 }
1833
[email protected]7a964a72010-09-07 19:33:261834 InternalInsertCookie(key, cc->release(), true);
[email protected]348dd662013-03-13 20:25:071835 } else {
1836 VLOG(kVlogSetCookies) << "SetCookie() not storing already expired cookie.";
[email protected]c4058fb2010-06-22 17:25:261837 }
initial.commit586acc5fe2008-07-26 22:42:521838
1839 // We assume that hopefully setting a cookie will be less common than
1840 // querying a cookie. Since setting a cookie can put us over our limits,
1841 // make sure that we garbage collect... We can also make the assumption that
1842 // if a cookie was set, in the common case it will be used soon after,
1843 // and we will purge the expired cookies in GetCookies().
[email protected]7a964a72010-09-07 19:33:261844 GarbageCollect(creation_time, key);
initial.commit586acc5fe2008-07-26 22:42:521845
1846 return true;
1847}
1848
[email protected]7a964a72010-09-07 19:33:261849void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie* cc,
1850 const Time& current) {
[email protected]bb8905722010-05-21 17:29:041851 lock_.AssertAcquired();
1852
[email protected]77e0a462008-11-01 00:43:351853 // Based off the Mozilla code. When a cookie has been accessed recently,
1854 // don't bother updating its access time again. This reduces the number of
1855 // updates we do during pageload, which in turn reduces the chance our storage
1856 // backend will hit its batch thresholds and be forced to update.
[email protected]77e0a462008-11-01 00:43:351857 if ((current - cc->LastAccessDate()) < last_access_threshold_)
1858 return;
1859
[email protected]374f58b2010-07-20 15:29:261860 // See InitializeHistograms() for details.
1861 histogram_between_access_interval_minutes_->Add(
1862 (current - cc->LastAccessDate()).InMinutes());
[email protected]c4058fb2010-06-22 17:25:261863
[email protected]77e0a462008-11-01 00:43:351864 cc->SetLastAccessDate(current);
[email protected]90499482013-06-01 00:39:501865 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get())
[email protected]77e0a462008-11-01 00:43:351866 store_->UpdateCookieAccessTime(*cc);
1867}
1868
[email protected]6210ce52013-09-20 03:33:141869// InternalDeleteCookies must not invalidate iterators other than the one being
1870// deleted.
initial.commit586acc5fe2008-07-26 22:42:521871void CookieMonster::InternalDeleteCookie(CookieMap::iterator it,
[email protected]c4058fb2010-06-22 17:25:261872 bool sync_to_store,
1873 DeletionCause deletion_cause) {
[email protected]bb8905722010-05-21 17:29:041874 lock_.AssertAcquired();
1875
[email protected]8bb846f2011-03-23 12:08:181876 // Ideally, this would be asserted up where we define ChangeCauseMapping,
1877 // but DeletionCause's visibility (or lack thereof) forces us to make
1878 // this check here.
1879 COMPILE_ASSERT(arraysize(ChangeCauseMapping) == DELETE_COOKIE_LAST_ENTRY + 1,
1880 ChangeCauseMapping_size_not_eq_DeletionCause_enum_size);
1881
[email protected]374f58b2010-07-20 15:29:261882 // See InitializeHistograms() for details.
[email protected]7a964a72010-09-07 19:33:261883 if (deletion_cause != DELETE_COOKIE_DONT_RECORD)
1884 histogram_cookie_deletion_cause_->Add(deletion_cause);
[email protected]c4058fb2010-06-22 17:25:261885
initial.commit586acc5fe2008-07-26 22:42:521886 CanonicalCookie* cc = it->second;
[email protected]4d3ce782010-10-29 18:31:281887 VLOG(kVlogSetCookies) << "InternalDeleteCookie() cc: " << cc->DebugString();
[email protected]7a964a72010-09-07 19:33:261888
[email protected]90499482013-06-01 00:39:501889 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() &&
1890 sync_to_store)
initial.commit586acc5fe2008-07-26 22:42:521891 store_->DeleteCookie(*cc);
[email protected]8bb846f2011-03-23 12:08:181892 if (delegate_.get()) {
1893 ChangeCausePair mapping = ChangeCauseMapping[deletion_cause];
1894
1895 if (mapping.notify)
1896 delegate_->OnCookieChanged(*cc, true, mapping.cause);
1897 }
initial.commit586acc5fe2008-07-26 22:42:521898 cookies_.erase(it);
1899 delete cc;
1900}
1901
[email protected]8807b322010-10-01 17:10:141902// Domain expiry behavior is unchanged by key/expiry scheme (the
[email protected]8ad5d462013-05-02 08:45:261903// meaning of the key is different, but that's not visible to this routine).
initial.commit586acc5fe2008-07-26 22:42:521904int CookieMonster::GarbageCollect(const Time& current,
1905 const std::string& key) {
[email protected]bb8905722010-05-21 17:29:041906 lock_.AssertAcquired();
1907
initial.commit586acc5fe2008-07-26 22:42:521908 int num_deleted = 0;
[email protected]8ad5d462013-05-02 08:45:261909 Time safe_date(
1910 Time::Now() - TimeDelta::FromDays(kSafeFromGlobalPurgeDays));
initial.commit586acc5fe2008-07-26 22:42:521911
[email protected]8ad5d462013-05-02 08:45:261912 // Collect garbage for this key, minding cookie priorities.
[email protected]7a964a72010-09-07 19:33:261913 if (cookies_.count(key) > kDomainMaxCookies) {
[email protected]4d3ce782010-10-29 18:31:281914 VLOG(kVlogGarbageCollection) << "GarbageCollect() key: " << key;
[email protected]7a964a72010-09-07 19:33:261915
[email protected]8ad5d462013-05-02 08:45:261916 CookieItVector cookie_its;
[email protected]8807b322010-10-01 17:10:141917 num_deleted += GarbageCollectExpired(
1918 current, cookies_.equal_range(key), &cookie_its);
[email protected]8ad5d462013-05-02 08:45:261919 if (cookie_its.size() > kDomainMaxCookies) {
1920 VLOG(kVlogGarbageCollection) << "Deep Garbage Collect domain.";
1921 size_t purge_goal =
1922 cookie_its.size() - (kDomainMaxCookies - kDomainPurgeCookies);
1923 DCHECK(purge_goal > kDomainPurgeCookies);
1924
1925 // Boundary iterators into |cookie_its| for different priorities.
1926 CookieItVector::iterator it_bdd[4];
1927 // Intialize |it_bdd| while sorting |cookie_its| by priorities.
1928 // Schematic: [MLLHMHHLMM] => [LLL|MMMM|HHH], with 4 boundaries.
1929 it_bdd[0] = cookie_its.begin();
1930 it_bdd[3] = cookie_its.end();
1931 it_bdd[1] = PartitionCookieByPriority(it_bdd[0], it_bdd[3],
1932 COOKIE_PRIORITY_LOW);
1933 it_bdd[2] = PartitionCookieByPriority(it_bdd[1], it_bdd[3],
1934 COOKIE_PRIORITY_MEDIUM);
1935 size_t quota[3] = {
1936 kDomainCookiesQuotaLow,
1937 kDomainCookiesQuotaMedium,
1938 kDomainCookiesQuotaHigh
1939 };
1940
1941 // Purge domain cookies in 3 rounds.
1942 // Round 1: consider low-priority cookies only: evict least-recently
1943 // accessed, while protecting quota[0] of these from deletion.
1944 // Round 2: consider {low, medium}-priority cookies, evict least-recently
1945 // accessed, while protecting quota[0] + quota[1].
1946 // Round 3: consider all cookies, evict least-recently accessed.
1947 size_t accumulated_quota = 0;
1948 CookieItVector::iterator it_purge_begin = it_bdd[0];
1949 for (int i = 0; i < 3 && purge_goal > 0; ++i) {
1950 accumulated_quota += quota[i];
1951
[email protected]8ad5d462013-05-02 08:45:261952 size_t num_considered = it_bdd[i + 1] - it_purge_begin;
1953 if (num_considered <= accumulated_quota)
1954 continue;
1955
1956 // Number of cookies that will be purged in this round.
1957 size_t round_goal =
1958 std::min(purge_goal, num_considered - accumulated_quota);
1959 purge_goal -= round_goal;
1960
1961 SortLeastRecentlyAccessed(it_purge_begin, it_bdd[i + 1], round_goal);
1962 // Cookies accessed on or after |safe_date| would have been safe from
1963 // global purge, and we want to keep track of this.
1964 CookieItVector::iterator it_purge_end = it_purge_begin + round_goal;
1965 CookieItVector::iterator it_purge_middle =
1966 LowerBoundAccessDate(it_purge_begin, it_purge_end, safe_date);
1967 // Delete cookies accessed before |safe_date|.
1968 num_deleted += GarbageCollectDeleteRange(
1969 current,
1970 DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE,
1971 it_purge_begin,
1972 it_purge_middle);
1973 // Delete cookies accessed on or after |safe_date|.
1974 num_deleted += GarbageCollectDeleteRange(
1975 current,
1976 DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE,
1977 it_purge_middle,
1978 it_purge_end);
1979 it_purge_begin = it_purge_end;
1980 }
1981 DCHECK_EQ(0U, purge_goal);
[email protected]8807b322010-10-01 17:10:141982 }
initial.commit586acc5fe2008-07-26 22:42:521983 }
1984
[email protected]8ad5d462013-05-02 08:45:261985 // Collect garbage for everything. With firefox style we want to preserve
1986 // cookies accessed in kSafeFromGlobalPurgeDays, otherwise evict.
[email protected]8807b322010-10-01 17:10:141987 if (cookies_.size() > kMaxCookies &&
[email protected]8ad5d462013-05-02 08:45:261988 earliest_access_time_ < safe_date) {
[email protected]4d3ce782010-10-29 18:31:281989 VLOG(kVlogGarbageCollection) << "GarbageCollect() everything";
[email protected]8ad5d462013-05-02 08:45:261990 CookieItVector cookie_its;
[email protected]7a964a72010-09-07 19:33:261991 num_deleted += GarbageCollectExpired(
1992 current, CookieMapItPair(cookies_.begin(), cookies_.end()),
1993 &cookie_its);
[email protected]8ad5d462013-05-02 08:45:261994 if (cookie_its.size() > kMaxCookies) {
1995 VLOG(kVlogGarbageCollection) << "Deep Garbage Collect everything.";
1996 size_t purge_goal = cookie_its.size() - (kMaxCookies - kPurgeCookies);
1997 DCHECK(purge_goal > kPurgeCookies);
1998 // Sorts up to *and including* |cookie_its[purge_goal]|, so
1999 // |earliest_access_time| will be properly assigned even if
2000 // |global_purge_it| == |cookie_its.begin() + purge_goal|.
2001 SortLeastRecentlyAccessed(cookie_its.begin(), cookie_its.end(),
2002 purge_goal);
2003 // Find boundary to cookies older than safe_date.
2004 CookieItVector::iterator global_purge_it =
2005 LowerBoundAccessDate(cookie_its.begin(),
2006 cookie_its.begin() + purge_goal,
2007 safe_date);
2008 // Only delete the old cookies.
2009 num_deleted += GarbageCollectDeleteRange(
[email protected]8807b322010-10-01 17:10:142010 current,
[email protected]8807b322010-10-01 17:10:142011 DELETE_COOKIE_EVICTED_GLOBAL,
[email protected]8ad5d462013-05-02 08:45:262012 cookie_its.begin(),
2013 global_purge_it);
2014 // Set access day to the oldest cookie that wasn't deleted.
2015 earliest_access_time_ = (*global_purge_it)->second->LastAccessDate();
[email protected]8807b322010-10-01 17:10:142016 }
[email protected]c890ed192008-10-30 23:45:532017 }
2018
2019 return num_deleted;
2020}
2021
[email protected]c890ed192008-10-30 23:45:532022int CookieMonster::GarbageCollectExpired(
2023 const Time& current,
2024 const CookieMapItPair& itpair,
[email protected]8ad5d462013-05-02 08:45:262025 CookieItVector* cookie_its) {
[email protected]ba4ad0e2011-03-15 08:12:472026 if (keep_expired_cookies_)
2027 return 0;
2028
[email protected]bb8905722010-05-21 17:29:042029 lock_.AssertAcquired();
2030
[email protected]c890ed192008-10-30 23:45:532031 int num_deleted = 0;
2032 for (CookieMap::iterator it = itpair.first, end = itpair.second; it != end;) {
2033 CookieMap::iterator curit = it;
2034 ++it;
2035
2036 if (curit->second->IsExpired(current)) {
[email protected]2f3f3592010-07-07 20:11:512037 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
[email protected]c890ed192008-10-30 23:45:532038 ++num_deleted;
2039 } else if (cookie_its) {
2040 cookie_its->push_back(curit);
2041 }
initial.commit586acc5fe2008-07-26 22:42:522042 }
2043
2044 return num_deleted;
2045}
2046
[email protected]8ad5d462013-05-02 08:45:262047int CookieMonster::GarbageCollectDeleteRange(
[email protected]f48b9432011-01-11 07:25:402048 const Time& current,
[email protected]f48b9432011-01-11 07:25:402049 DeletionCause cause,
[email protected]5fa4f9a2013-10-03 10:13:162050 CookieItVector::iterator it_begin,
2051 CookieItVector::iterator it_end) {
[email protected]8ad5d462013-05-02 08:45:262052 for (CookieItVector::iterator it = it_begin; it != it_end; it++) {
2053 histogram_evicted_last_access_minutes_->Add(
2054 (current - (*it)->second->LastAccessDate()).InMinutes());
2055 InternalDeleteCookie((*it), true, cause);
[email protected]c10da4b02010-03-25 14:38:322056 }
[email protected]8ad5d462013-05-02 08:45:262057 return it_end - it_begin;
[email protected]c10da4b02010-03-25 14:38:322058}
2059
[email protected]ed32c212013-05-14 20:49:292060// A wrapper around registry_controlled_domains::GetDomainAndRegistry
[email protected]f48b9432011-01-11 07:25:402061// to make clear we're creating a key for our local map. Here and
2062// in FindCookiesForHostAndDomain() are the only two places where
2063// we need to conditionalize based on key type.
2064//
2065// Note that this key algorithm explicitly ignores the scheme. This is
2066// because when we're entering cookies into the map from the backing store,
2067// we in general won't have the scheme at that point.
2068// In practical terms, this means that file cookies will be stored
2069// in the map either by an empty string or by UNC name (and will be
2070// limited by kMaxCookiesPerHost), and extension cookies will be stored
2071// based on the single extension id, as the extension id won't have the
2072// form of a DNS host and hence GetKey() will return it unchanged.
2073//
2074// Arguably the right thing to do here is to make the key
2075// algorithm dependent on the scheme, and make sure that the scheme is
2076// available everywhere the key must be obtained (specfically at backing
2077// store load time). This would require either changing the backing store
2078// database schema to include the scheme (far more trouble than it's worth), or
2079// separating out file cookies into their own CookieMonster instance and
2080// thus restricting each scheme to a single cookie monster (which might
2081// be worth it, but is still too much trouble to solve what is currently a
2082// non-problem).
2083std::string CookieMonster::GetKey(const std::string& domain) const {
[email protected]f48b9432011-01-11 07:25:402084 std::string effective_domain(
[email protected]ed32c212013-05-14 20:49:292085 registry_controlled_domains::GetDomainAndRegistry(
2086 domain, registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES));
[email protected]f48b9432011-01-11 07:25:402087 if (effective_domain.empty())
2088 effective_domain = domain;
2089
2090 if (!effective_domain.empty() && effective_domain[0] == '.')
2091 return effective_domain.substr(1);
2092 return effective_domain;
2093}
2094
[email protected]97a3b6e2012-06-12 01:53:562095bool CookieMonster::IsCookieableScheme(const std::string& scheme) {
2096 base::AutoLock autolock(lock_);
2097
2098 return std::find(cookieable_schemes_.begin(), cookieable_schemes_.end(),
2099 scheme) != cookieable_schemes_.end();
2100}
2101
[email protected]f48b9432011-01-11 07:25:402102bool CookieMonster::HasCookieableScheme(const GURL& url) {
2103 lock_.AssertAcquired();
2104
2105 // Make sure the request is on a cookie-able url scheme.
2106 for (size_t i = 0; i < cookieable_schemes_.size(); ++i) {
2107 // We matched a scheme.
2108 if (url.SchemeIs(cookieable_schemes_[i].c_str())) {
2109 // We've matched a supported scheme.
initial.commit586acc5fe2008-07-26 22:42:522110 return true;
2111 }
2112 }
[email protected]f48b9432011-01-11 07:25:402113
2114 // The scheme didn't match any in our whitelist.
2115 VLOG(kVlogPerCookieMonster) << "WARNING: Unsupported cookie scheme: "
2116 << url.scheme();
initial.commit586acc5fe2008-07-26 22:42:522117 return false;
2118}
2119
[email protected]c4058fb2010-06-22 17:25:262120// Test to see if stats should be recorded, and record them if so.
2121// The goal here is to get sampling for the average browser-hour of
2122// activity. We won't take samples when the web isn't being surfed,
2123// and when the web is being surfed, we'll take samples about every
2124// kRecordStatisticsIntervalSeconds.
2125// last_statistic_record_time_ is initialized to Now() rather than null
2126// in the constructor so that we won't take statistics right after
2127// startup, to avoid bias from browsers that are started but not used.
2128void CookieMonster::RecordPeriodicStats(const base::Time& current_time) {
2129 const base::TimeDelta kRecordStatisticsIntervalTime(
2130 base::TimeDelta::FromSeconds(kRecordStatisticsIntervalSeconds));
2131
[email protected]7a964a72010-09-07 19:33:262132 // If we've taken statistics recently, return.
2133 if (current_time - last_statistic_record_time_ <=
[email protected]c4058fb2010-06-22 17:25:262134 kRecordStatisticsIntervalTime) {
[email protected]7a964a72010-09-07 19:33:262135 return;
[email protected]c4058fb2010-06-22 17:25:262136 }
[email protected]7a964a72010-09-07 19:33:262137
2138 // See InitializeHistograms() for details.
2139 histogram_count_->Add(cookies_.size());
2140
2141 // More detailed statistics on cookie counts at different granularities.
2142 TimeTicks beginning_of_time(TimeTicks::Now());
2143
2144 for (CookieMap::const_iterator it_key = cookies_.begin();
2145 it_key != cookies_.end(); ) {
2146 const std::string& key(it_key->first);
2147
2148 int key_count = 0;
2149 typedef std::map<std::string, unsigned int> DomainMap;
2150 DomainMap domain_map;
2151 CookieMapItPair its_cookies = cookies_.equal_range(key);
2152 while (its_cookies.first != its_cookies.second) {
2153 key_count++;
2154 const std::string& cookie_domain(its_cookies.first->second->Domain());
2155 domain_map[cookie_domain]++;
2156
2157 its_cookies.first++;
2158 }
2159 histogram_etldp1_count_->Add(key_count);
2160 histogram_domain_per_etldp1_count_->Add(domain_map.size());
2161 for (DomainMap::const_iterator domain_map_it = domain_map.begin();
2162 domain_map_it != domain_map.end(); domain_map_it++)
2163 histogram_domain_count_->Add(domain_map_it->second);
2164
2165 it_key = its_cookies.second;
2166 }
2167
[email protected]4d3ce782010-10-29 18:31:282168 VLOG(kVlogPeriodic)
2169 << "Time for recording cookie stats (us): "
2170 << (TimeTicks::Now() - beginning_of_time).InMicroseconds();
[email protected]7a964a72010-09-07 19:33:262171
2172 last_statistic_record_time_ = current_time;
[email protected]c4058fb2010-06-22 17:25:262173}
2174
[email protected]f48b9432011-01-11 07:25:402175// Initialize all histogram counter variables used in this class.
2176//
2177// Normal histogram usage involves using the macros defined in
2178// histogram.h, which automatically takes care of declaring these
2179// variables (as statics), initializing them, and accumulating into
2180// them, all from a single entry point. Unfortunately, that solution
2181// doesn't work for the CookieMonster, as it's vulnerable to races between
2182// separate threads executing the same functions and hence initializing the
2183// same static variables. There isn't a race danger in the histogram
2184// accumulation calls; they are written to be resilient to simultaneous
2185// calls from multiple threads.
2186//
2187// The solution taken here is to have per-CookieMonster instance
2188// variables that are constructed during CookieMonster construction.
2189// Note that these variables refer to the same underlying histogram,
2190// so we still race (but safely) with other CookieMonster instances
2191// for accumulation.
2192//
2193// To do this we've expanded out the individual histogram macros calls,
2194// with declarations of the variables in the class decl, initialization here
2195// (done from the class constructor) and direct calls to the accumulation
2196// methods where needed. The specific histogram macro calls on which the
2197// initialization is based are included in comments below.
2198void CookieMonster::InitializeHistograms() {
2199 // From UMA_HISTOGRAM_CUSTOM_COUNTS
2200 histogram_expiration_duration_minutes_ = base::Histogram::FactoryGet(
2201 "Cookie.ExpirationDurationMinutes",
2202 1, kMinutesInTenYears, 50,
2203 base::Histogram::kUmaTargetedHistogramFlag);
2204 histogram_between_access_interval_minutes_ = base::Histogram::FactoryGet(
2205 "Cookie.BetweenAccessIntervalMinutes",
2206 1, kMinutesInTenYears, 50,
2207 base::Histogram::kUmaTargetedHistogramFlag);
2208 histogram_evicted_last_access_minutes_ = base::Histogram::FactoryGet(
2209 "Cookie.EvictedLastAccessMinutes",
2210 1, kMinutesInTenYears, 50,
2211 base::Histogram::kUmaTargetedHistogramFlag);
2212 histogram_count_ = base::Histogram::FactoryGet(
2213 "Cookie.Count", 1, 4000, 50,
2214 base::Histogram::kUmaTargetedHistogramFlag);
2215 histogram_domain_count_ = base::Histogram::FactoryGet(
2216 "Cookie.DomainCount", 1, 4000, 50,
2217 base::Histogram::kUmaTargetedHistogramFlag);
2218 histogram_etldp1_count_ = base::Histogram::FactoryGet(
2219 "Cookie.Etldp1Count", 1, 4000, 50,
2220 base::Histogram::kUmaTargetedHistogramFlag);
2221 histogram_domain_per_etldp1_count_ = base::Histogram::FactoryGet(
2222 "Cookie.DomainPerEtldp1Count", 1, 4000, 50,
2223 base::Histogram::kUmaTargetedHistogramFlag);
2224
2225 // From UMA_HISTOGRAM_COUNTS_10000 & UMA_HISTOGRAM_CUSTOM_COUNTS
2226 histogram_number_duplicate_db_cookies_ = base::Histogram::FactoryGet(
2227 "Net.NumDuplicateCookiesInDb", 1, 10000, 50,
2228 base::Histogram::kUmaTargetedHistogramFlag);
2229
2230 // From UMA_HISTOGRAM_ENUMERATION
2231 histogram_cookie_deletion_cause_ = base::LinearHistogram::FactoryGet(
2232 "Cookie.DeletionCause", 1,
2233 DELETE_COOKIE_LAST_ENTRY - 1, DELETE_COOKIE_LAST_ENTRY,
2234 base::Histogram::kUmaTargetedHistogramFlag);
2235
2236 // From UMA_HISTOGRAM_{CUSTOM_,}TIMES
2237 histogram_time_get_ = base::Histogram::FactoryTimeGet("Cookie.TimeGet",
2238 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
2239 50, base::Histogram::kUmaTargetedHistogramFlag);
[email protected]c7593fb22011-11-14 23:54:272240 histogram_time_blocked_on_load_ = base::Histogram::FactoryTimeGet(
2241 "Cookie.TimeBlockedOnLoad",
[email protected]f48b9432011-01-11 07:25:402242 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
2243 50, base::Histogram::kUmaTargetedHistogramFlag);
2244}
2245
2246
2247// The system resolution is not high enough, so we can have multiple
2248// set cookies that result in the same system time. When this happens, we
2249// increment by one Time unit. Let's hope computers don't get too fast.
2250Time CookieMonster::CurrentTime() {
2251 return std::max(Time::Now(),
2252 Time::FromInternalValue(last_time_seen_.ToInternalValue() + 1));
2253}
2254
[email protected]63725312012-07-19 08:24:162255} // namespace net