blob: 795d3ea8f65dc3fb3672a5d2a7a9ffa177fa2b23 [file] [log] [blame]
[email protected]297a4ed02010-02-12 08:12:521// Copyright (c) 2010 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
45#include "net/base/cookie_monster.h"
46
47#include <algorithm>
48
49#include "base/basictypes.h"
[email protected]dce5df52009-06-29 17:58:2550#include "base/format_macros.h"
initial.commit586acc5fe2008-07-26 22:42:5251#include "base/logging.h"
52#include "base/scoped_ptr.h"
53#include "base/string_tokenizer.h"
54#include "base/string_util.h"
55#include "googleurl/src/gurl.h"
[email protected]f325f1e12010-04-30 22:38:5556#include "googleurl/src/url_canon.h"
initial.commit586acc5fe2008-07-26 22:42:5257#include "net/base/net_util.h"
58#include "net/base/registry_controlled_domain.h"
59
60// #define COOKIE_LOGGING_ENABLED
61#ifdef COOKIE_LOGGING_ENABLED
62#define COOKIE_DLOG(severity) DLOG_IF(INFO, 1)
63#else
64#define COOKIE_DLOG(severity) DLOG_IF(INFO, 0)
65#endif
66
[email protected]e1acf6f2008-10-27 20:43:3367using base::Time;
68using base::TimeDelta;
69
[email protected]c4058fb2010-06-22 17:25:2670static const int kMinutesInTenYears = 10 * 365 * 24 * 60;
71
[email protected]8ac1a752008-07-31 19:40:3772namespace net {
73
[email protected]297a4ed02010-02-12 08:12:5274namespace {
75
[email protected]e32306c52008-11-06 16:59:0576// Cookie garbage collection thresholds. Based off of the Mozilla defaults.
77// It might seem scary to have a high purge value, but really it's not. You
78// just make sure that you increase the max to cover the increase in purge,
79// and we would have been purging the same amount of cookies. We're just
80// going through the garbage collection process less often.
[email protected]297a4ed02010-02-12 08:12:5281const size_t kNumCookiesPerHost = 70; // ~50 cookies
82const size_t kNumCookiesPerHostPurge = 20;
83const size_t kNumCookiesTotal = 3300; // ~3000 cookies
84const size_t kNumCookiesTotalPurge = 300;
[email protected]e32306c52008-11-06 16:59:0585
[email protected]77e0a462008-11-01 00:43:3586// Default minimum delay after updating a cookie's LastAccessDate before we
87// will update it again.
[email protected]297a4ed02010-02-12 08:12:5288const int kDefaultAccessUpdateThresholdSeconds = 60;
89
90// Comparator to sort cookies from highest creation date to lowest
91// creation date.
92struct OrderByCreationTimeDesc {
93 bool operator()(const CookieMonster::CookieMap::iterator& a,
94 const CookieMonster::CookieMap::iterator& b) const {
95 return a->second->CreationDate() > b->second->CreationDate();
96 }
97};
98
99} // namespace
[email protected]77e0a462008-11-01 00:43:35100
[email protected]8ac1a752008-07-31 19:40:37101// static
102bool CookieMonster::enable_file_scheme_ = false;
initial.commit586acc5fe2008-07-26 22:42:52103
104// static
105void CookieMonster::EnableFileScheme() {
106 enable_file_scheme_ = true;
107}
108
[email protected]0f7066e2010-03-25 08:31:47109CookieMonster::CookieMonster(PersistentCookieStore* store, Delegate* delegate)
initial.commit586acc5fe2008-07-26 22:42:52110 : initialized_(false),
[email protected]77e0a462008-11-01 00:43:35111 store_(store),
112 last_access_threshold_(
[email protected]0f7066e2010-03-25 08:31:47113 TimeDelta::FromSeconds(kDefaultAccessUpdateThresholdSeconds)),
[email protected]c4058fb2010-06-22 17:25:26114 delegate_(delegate),
115 last_statistic_record_time_(Time::Now()) {
[email protected]374f58b2010-07-20 15:29:26116 InitializeHistograms();
[email protected]47accfd62009-05-14 18:46:21117 SetDefaultCookieableSchemes();
initial.commit586acc5fe2008-07-26 22:42:52118}
119
120CookieMonster::~CookieMonster() {
121 DeleteAll(false);
122}
123
[email protected]374f58b2010-07-20 15:29:26124// Initialize all histogram counter variables used in this class.
125//
126// Normal histogram usage involves using the macros defined in
127// histogram.h, which automatically takes care of declaring these
128// variables (as statics), initializing them, and accumulating into
129// them, all from a single entry point. Unfortunately, that solution
130// doesn't work for the CookieMonster, as it's vulnerable to races between
131// separate threads executing the same functions and hence initializing the
132// same static variables. There isn't a race danger in the histogram
133// accumulation calls; they are written to be resilient to simultaneous
134// calls from multiple threads.
135//
136// The solution taken here is to have per-CookieMonster instance
137// variables that are constructed during CookieMonster construction.
138// Note that these variables refer to the same underlying histogram,
139// so we still race (but safely) with other CookieMonster instances
140// for accumulation.
141//
142// To do this we've expanded out the individual histogram macros calls,
143// with declarations of the variables in the class decl, initialization here
144// (done from the class constructor) and direct calls to the accumulation
145// methods where needed. The specific histogram macro calls on which the
146// initialization is based are included in comments below.
147void CookieMonster::InitializeHistograms() {
148 // From UMA_HISTOGRAM_CUSTOM_COUNTS
149 histogram_expiration_duration_minutes_ = Histogram::FactoryGet(
150 "net.CookieExpirationDurationMinutes",
151 1, kMinutesInTenYears, 50,
152 Histogram::kUmaTargetedHistogramFlag);
153 histogram_between_access_interval_minutes_ = Histogram::FactoryGet(
154 "net.CookieBetweenAccessIntervalMinutes",
155 1, kMinutesInTenYears, 50,
156 Histogram::kUmaTargetedHistogramFlag);
157 histogram_evicted_last_access_minutes_ = Histogram::FactoryGet(
158 "net.CookieEvictedLastAccessMinutes",
159 1, kMinutesInTenYears, 50,
160 Histogram::kUmaTargetedHistogramFlag);
161 histogram_count_ = Histogram::FactoryGet(
162 "net.CookieCount", 1, 4000, 50,
163 Histogram::kUmaTargetedHistogramFlag);
164
165 // From UMA_HISTOGRAM_COUNTS_10000 & UMA_HISTOGRAM_CUSTOM_COUNTS
166 histogram_number_duplicate_db_cookies_ = Histogram::FactoryGet(
167 "Net.NumDuplicateCookiesInDb", 1, 10000, 50,
168 Histogram::kUmaTargetedHistogramFlag);
169
170 // From UMA_HISTOGRAM_ENUMERATION
171 histogram_cookie_deletion_cause_ = LinearHistogram::FactoryGet(
172 "net.CookieDeletionCause", 1,
173 DELETE_COOKIE_LAST_ENTRY, DELETE_COOKIE_LAST_ENTRY + 1,
174 Histogram::kUmaTargetedHistogramFlag);
175}
176
initial.commit586acc5fe2008-07-26 22:42:52177void CookieMonster::InitStore() {
178 DCHECK(store_) << "Store must exist to initialize";
179
180 // Initialize the store and sync in any saved persistent cookies. We don't
181 // care if it's expired, insert it so it can be garbage collected, removed,
182 // and sync'd.
183 std::vector<KeyedCanonicalCookie> cookies;
[email protected]e32306c52008-11-06 16:59:05184 // Reserve space for the maximum amount of cookies a database should have.
185 // This prevents multiple vector growth / copies as we append cookies.
186 cookies.reserve(kNumCookiesTotal);
initial.commit586acc5fe2008-07-26 22:42:52187 store_->Load(&cookies);
[email protected]b866a02d2010-07-28 16:41:04188
189 // Avoid ever letting cookies with duplicate creation times into the store;
190 // that way we don't have to worry about what sections of code are safe
191 // to call while it's in that state.
192 std::set<int64> creation_times;
initial.commit586acc5fe2008-07-26 22:42:52193 for (std::vector<KeyedCanonicalCookie>::const_iterator it = cookies.begin();
194 it != cookies.end(); ++it) {
[email protected]b866a02d2010-07-28 16:41:04195 int64 cookie_creation_time = it->second->CreationDate().ToInternalValue();
196
197 if (creation_times.insert(cookie_creation_time).second) {
198 InternalInsertCookie(it->first, it->second, false);
199 } else {
200 LOG(ERROR) << StringPrintf("Found cookies with duplicate creation "
201 "times in backing store: "
202 "{name='%s', domain='%s', path='%s'}",
203 it->second->Name().c_str(),
204 it->first.c_str(),
205 it->second->Path().c_str());
206 }
initial.commit586acc5fe2008-07-26 22:42:52207 }
[email protected]297a4ed02010-02-12 08:12:52208
209 // After importing cookies from the PersistentCookieStore, verify that
[email protected]b866a02d2010-07-28 16:41:04210 // none of our other constraints are violated.
[email protected]297a4ed02010-02-12 08:12:52211 //
212 // In particular, the backing store might have given us duplicate cookies.
213 EnsureCookiesMapIsValid();
214}
215
216void CookieMonster::EnsureCookiesMapIsValid() {
[email protected]bb8905722010-05-21 17:29:04217 lock_.AssertAcquired();
218
[email protected]297a4ed02010-02-12 08:12:52219 int num_duplicates_trimmed = 0;
220
221 // Iterate through all the of the cookies, grouped by host.
222 CookieMap::iterator prev_range_end = cookies_.begin();
223 while (prev_range_end != cookies_.end()) {
224 CookieMap::iterator cur_range_begin = prev_range_end;
225 const std::string key = cur_range_begin->first; // Keep a copy.
226 CookieMap::iterator cur_range_end = cookies_.upper_bound(key);
227 prev_range_end = cur_range_end;
228
229 // Ensure no equivalent cookies for this host.
230 num_duplicates_trimmed +=
231 TrimDuplicateCookiesForHost(key, cur_range_begin, cur_range_end);
232 }
233
234 // Record how many duplicates were found in the database.
[email protected]374f58b2010-07-20 15:29:26235 // See InitializeHistograms() for details.
236 histogram_cookie_deletion_cause_->Add(num_duplicates_trimmed);
[email protected]297a4ed02010-02-12 08:12:52237}
238
239// Our strategy to find duplicates is:
240// (1) Build a map from (cookiename, cookiepath) to
241// {list of cookies with this signature, sorted by creation time}.
242// (2) For each list with more than 1 entry, keep the cookie having the
243// most recent creation time, and delete the others.
[email protected]1655ba342010-07-14 18:17:42244namespace {
245// Two cookies are considered equivalent if they have the same domain,
246// name, and path.
247struct CookieSignature {
248 public:
249 CookieSignature(const std::string& name, const std::string& domain,
250 const std::string& path)
251 : name(name),
252 domain(domain),
253 path(path) {}
254
255 // To be a key for a map this class needs to be assignable, copyable,
256 // and have an operator<. The default assignment operator
257 // and copy constructor are exactly what we want.
258
259 bool operator<(const CookieSignature& cs) const {
260 // Name compare dominates, then domain, then path.
261 int diff = name.compare(cs.name);
262 if (diff != 0)
263 return diff < 0;
264
265 diff = domain.compare(cs.domain);
266 if (diff != 0)
267 return diff < 0;
268
269 return path.compare(cs.path) < 0;
270 }
271
272 std::string name;
273 std::string domain;
274 std::string path;
275};
276}
277
[email protected]297a4ed02010-02-12 08:12:52278int CookieMonster::TrimDuplicateCookiesForHost(
279 const std::string& key,
280 CookieMap::iterator begin,
281 CookieMap::iterator end) {
[email protected]bb8905722010-05-21 17:29:04282 lock_.AssertAcquired();
[email protected]297a4ed02010-02-12 08:12:52283
[email protected]65781e92010-07-21 15:29:57284 // Set of cookies ordered by creation time.
285 typedef std::set<CookieMap::iterator, OrderByCreationTimeDesc> CookieSet;
[email protected]297a4ed02010-02-12 08:12:52286
287 // Helper map we populate to find the duplicates.
[email protected]65781e92010-07-21 15:29:57288 typedef std::map<CookieSignature, CookieSet> EquivalenceMap;
[email protected]297a4ed02010-02-12 08:12:52289 EquivalenceMap equivalent_cookies;
290
291 // The number of duplicate cookies that have been found.
292 int num_duplicates = 0;
293
294 // Iterate through all of the cookies in our range, and insert them into
295 // the equivalence map.
296 for (CookieMap::iterator it = begin; it != end; ++it) {
297 DCHECK_EQ(key, it->first);
298 CanonicalCookie* cookie = it->second;
299
[email protected]1655ba342010-07-14 18:17:42300 CookieSignature signature(cookie->Name(), cookie->Domain(),
301 cookie->Path());
[email protected]65781e92010-07-21 15:29:57302 CookieSet& list = equivalent_cookies[signature];
[email protected]297a4ed02010-02-12 08:12:52303
304 // We found a duplicate!
305 if (!list.empty())
306 num_duplicates++;
307
308 // We save the iterator into |cookies_| rather than the actual cookie
309 // pointer, since we may need to delete it later.
[email protected]b866a02d2010-07-28 16:41:04310 bool insert_success = list.insert(it).second;
311 DCHECK(insert_success) <<
312 "Duplicate creation times found in duplicate cookie name scan.";
[email protected]297a4ed02010-02-12 08:12:52313 }
314
315 // If there were no duplicates, we are done!
316 if (num_duplicates == 0)
317 return 0;
318
[email protected]b866a02d2010-07-28 16:41:04319 // Make sure we find everything below that we did above.
320 int num_duplicates_found = 0;
321
[email protected]297a4ed02010-02-12 08:12:52322 // Otherwise, delete all the duplicate cookies, both from our in-memory store
323 // and from the backing store.
324 for (EquivalenceMap::iterator it = equivalent_cookies.begin();
325 it != equivalent_cookies.end();
326 ++it) {
327 const CookieSignature& signature = it->first;
[email protected]65781e92010-07-21 15:29:57328 CookieSet& dupes = it->second;
[email protected]297a4ed02010-02-12 08:12:52329
330 if (dupes.size() <= 1)
331 continue; // This cookiename/path has no duplicates.
[email protected]b866a02d2010-07-28 16:41:04332 num_duplicates_found += dupes.size() - 1;
[email protected]297a4ed02010-02-12 08:12:52333
334 // Since |dups| is sorted by creation time (descending), the first cookie
335 // is the most recent one, so we will keep it. The rest are duplicates.
336 dupes.erase(dupes.begin());
337
338 LOG(ERROR) << StringPrintf("Found %d duplicate cookies for host='%s', "
[email protected]1655ba342010-07-14 18:17:42339 "with {name='%s', domain='%s', path='%s'}",
[email protected]297a4ed02010-02-12 08:12:52340 static_cast<int>(dupes.size()),
341 key.c_str(),
[email protected]1655ba342010-07-14 18:17:42342 signature.name.c_str(),
343 signature.domain.c_str(),
344 signature.path.c_str());
[email protected]297a4ed02010-02-12 08:12:52345
346 // Remove all the cookies identified by |dupes|. It is valid to delete our
347 // list of iterators one at a time, since |cookies_| is a multimap (they
348 // don't invalidate existing iterators following deletion).
[email protected]65781e92010-07-21 15:29:57349 for (CookieSet::iterator dupes_it = dupes.begin();
[email protected]297a4ed02010-02-12 08:12:52350 dupes_it != dupes.end();
351 ++dupes_it) {
[email protected]c4058fb2010-06-22 17:25:26352 InternalDeleteCookie(*dupes_it, true /*sync_to_store*/,
[email protected]2f3f3592010-07-07 20:11:51353 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE);
[email protected]297a4ed02010-02-12 08:12:52354 }
355 }
[email protected]b866a02d2010-07-28 16:41:04356 DCHECK_EQ(num_duplicates, num_duplicates_found);
[email protected]297a4ed02010-02-12 08:12:52357
358 return num_duplicates;
initial.commit586acc5fe2008-07-26 22:42:52359}
360
[email protected]47accfd62009-05-14 18:46:21361void CookieMonster::SetDefaultCookieableSchemes() {
362 // Note: file must be the last scheme.
363 static const char* kDefaultCookieableSchemes[] = { "http", "https", "file" };
364 int num_schemes = enable_file_scheme_ ? 3 : 2;
365 SetCookieableSchemes(kDefaultCookieableSchemes, num_schemes);
366}
367
initial.commit586acc5fe2008-07-26 22:42:52368// The system resolution is not high enough, so we can have multiple
369// set cookies that result in the same system time. When this happens, we
370// increment by one Time unit. Let's hope computers don't get too fast.
371Time CookieMonster::CurrentTime() {
372 return std::max(Time::Now(),
373 Time::FromInternalValue(last_time_seen_.ToInternalValue() + 1));
374}
375
376// Parse a cookie expiration time. We try to be lenient, but we need to
377// assume some order to distinguish the fields. The basic rules:
378// - The month name must be present and prefix the first 3 letters of the
379// full month name (jan for January, jun for June).
380// - If the year is <= 2 digits, it must occur after the day of month.
381// - The time must be of the format hh:mm:ss.
382// An average cookie expiration will look something like this:
383// Sat, 15-Apr-17 21:01:22 GMT
384Time CookieMonster::ParseCookieTime(const std::string& time_string) {
385 static const char* kMonths[] = { "jan", "feb", "mar", "apr", "may", "jun",
386 "jul", "aug", "sep", "oct", "nov", "dec" };
387 static const int kMonthsLen = arraysize(kMonths);
388 // We want to be pretty liberal, and support most non-ascii and non-digit
389 // characters as a delimiter. We can't treat : as a delimiter, because it
390 // is the delimiter for hh:mm:ss, and we want to keep this field together.
391 // We make sure to include - and +, since they could prefix numbers.
392 // If the cookie attribute came in in quotes (ex expires="XXX"), the quotes
393 // will be preserved, and we will get them here. So we make sure to include
394 // quote characters, and also \ for anything that was internally escaped.
395 static const char* kDelimiters = "\t !\"#$%&'()*+,-./;<=>?@[\\]^_`{|}~";
396
397 Time::Exploded exploded = {0};
398
399 StringTokenizer tokenizer(time_string, kDelimiters);
400
401 bool found_day_of_month = false;
402 bool found_month = false;
403 bool found_time = false;
404 bool found_year = false;
405
406 while (tokenizer.GetNext()) {
407 const std::string token = tokenizer.token();
408 DCHECK(!token.empty());
409 bool numerical = IsAsciiDigit(token[0]);
410
411 // String field
412 if (!numerical) {
413 if (!found_month) {
414 for (int i = 0; i < kMonthsLen; ++i) {
415 // Match prefix, so we could match January, etc
[email protected]7e3dcd92008-12-30 13:13:34416 if (base::strncasecmp(token.c_str(), kMonths[i], 3) == 0) {
initial.commit586acc5fe2008-07-26 22:42:52417 exploded.month = i + 1;
418 found_month = true;
419 break;
420 }
421 }
422 } else {
423 // If we've gotten here, it means we've already found and parsed our
424 // month, and we have another string, which we would expect to be the
425 // the time zone name. According to the RFC and my experiments with
426 // how sites format their expirations, we don't have much of a reason
427 // to support timezones. We don't want to ever barf on user input,
428 // but this DCHECK should pass for well-formed data.
429 // DCHECK(token == "GMT");
430 }
431 // Numeric field w/ a colon
432 } else if (token.find(':') != std::string::npos) {
433 if (!found_time &&
[email protected]d862fd92008-08-21 18:15:35434#ifdef COMPILER_MSVC
435 sscanf_s(
436#else
437 sscanf(
438#endif
439 token.c_str(), "%2u:%2u:%2u", &exploded.hour,
440 &exploded.minute, &exploded.second) == 3) {
initial.commit586acc5fe2008-07-26 22:42:52441 found_time = true;
442 } else {
443 // We should only ever encounter one time-like thing. If we're here,
444 // it means we've found a second, which shouldn't happen. We keep
445 // the first. This check should be ok for well-formed input:
446 // NOTREACHED();
447 }
448 // Numeric field
449 } else {
450 // Overflow with atoi() is unspecified, so we enforce a max length.
451 if (!found_day_of_month && token.length() <= 2) {
452 exploded.day_of_month = atoi(token.c_str());
453 found_day_of_month = true;
454 } else if (!found_year && token.length() <= 5) {
455 exploded.year = atoi(token.c_str());
456 found_year = true;
457 } else {
458 // If we're here, it means we've either found an extra numeric field,
459 // or a numeric field which was too long. For well-formed input, the
460 // following check would be reasonable:
461 // NOTREACHED();
462 }
463 }
464 }
465
466 if (!found_day_of_month || !found_month || !found_time || !found_year) {
467 // We didn't find all of the fields we need. For well-formed input, the
468 // following check would be reasonable:
469 // NOTREACHED() << "Cookie parse expiration failed: " << time_string;
470 return Time();
471 }
472
473 // Normalize the year to expand abbreviated years to the full year.
474 if (exploded.year >= 69 && exploded.year <= 99)
475 exploded.year += 1900;
476 if (exploded.year >= 0 && exploded.year <= 68)
477 exploded.year += 2000;
478
479 // If our values are within their correct ranges, we got our time.
480 if (exploded.day_of_month >= 1 && exploded.day_of_month <= 31 &&
481 exploded.month >= 1 && exploded.month <= 12 &&
482 exploded.year >= 1601 && exploded.year <= 30827 &&
483 exploded.hour <= 23 && exploded.minute <= 59 && exploded.second <= 59) {
484 return Time::FromUTCExploded(exploded);
485 }
486
487 // One of our values was out of expected range. For well-formed input,
488 // the following check would be reasonable:
489 // NOTREACHED() << "Cookie exploded expiration failed: " << time_string;
490
491 return Time();
492}
493
[email protected]f325f1e12010-04-30 22:38:55494bool CookieMonster::DomainIsHostOnly(const std::string& domain_string) {
495 return (domain_string.empty() || domain_string[0] != '.');
496}
497
[email protected]69bb5872010-01-12 20:33:52498// Returns the effective TLD+1 for a given host. This only makes sense for http
499// and https schemes. For other schemes, the host will be returned unchanged
500// (minus any leading .).
501static std::string GetEffectiveDomain(const std::string& scheme,
502 const std::string& host) {
503 if (scheme == "http" || scheme == "https")
504 return RegistryControlledDomainService::GetDomainAndRegistry(host);
505
[email protected]f325f1e12010-04-30 22:38:55506 if (!CookieMonster::DomainIsHostOnly(host))
[email protected]69bb5872010-01-12 20:33:52507 return host.substr(1);
508 return host;
509}
510
[email protected]f325f1e12010-04-30 22:38:55511// Determine the cookie domain key to use for setting a cookie with the
512// specified domain attribute string.
initial.commit586acc5fe2008-07-26 22:42:52513// On success returns true, and sets cookie_domain_key to either a
514// -host cookie key (ex: "google.com")
515// -domain cookie key (ex: ".google.com")
[email protected]f325f1e12010-04-30 22:38:55516static bool GetCookieDomainKeyWithString(const GURL& url,
517 const std::string& domain_string,
518 std::string* cookie_domain_key) {
initial.commit586acc5fe2008-07-26 22:42:52519 const std::string url_host(url.host());
[email protected]c3a756b62009-01-23 10:50:51520
[email protected]f325f1e12010-04-30 22:38:55521 // If no domain was specified in the domain string, default to a host cookie.
[email protected]c3a756b62009-01-23 10:50:51522 // We match IE/Firefox in allowing a domain=IPADDR if it matches the url
523 // ip address hostname exactly. It should be treated as a host cookie.
[email protected]f325f1e12010-04-30 22:38:55524 if (domain_string.empty() ||
525 (url.HostIsIPAddress() && url_host == domain_string)) {
initial.commit586acc5fe2008-07-26 22:42:52526 *cookie_domain_key = url_host;
[email protected]f325f1e12010-04-30 22:38:55527 DCHECK(CookieMonster::DomainIsHostOnly(*cookie_domain_key));
initial.commit586acc5fe2008-07-26 22:42:52528 return true;
529 }
530
531 // Get the normalized domain specified in cookie line.
532 // Note: The RFC says we can reject a cookie if the domain
533 // attribute does not start with a dot. IE/FF/Safari however, allow a cookie
534 // of the form domain=my.domain.com, treating it the same as
535 // domain=.my.domain.com -- for compatibility we do the same here. Firefox
536 // also treats domain=.....my.domain.com like domain=.my.domain.com, but
537 // neither IE nor Safari do this, and we don't either.
[email protected]01dbd932009-06-23 22:52:42538 url_canon::CanonHostInfo ignored;
[email protected]f325f1e12010-04-30 22:38:55539 std::string cookie_domain(net::CanonicalizeHost(domain_string, &ignored));
initial.commit586acc5fe2008-07-26 22:42:52540 if (cookie_domain.empty())
541 return false;
542 if (cookie_domain[0] != '.')
543 cookie_domain = "." + cookie_domain;
544
545 // Ensure |url| and |cookie_domain| have the same domain+registry.
[email protected]69bb5872010-01-12 20:33:52546 const std::string url_scheme(url.scheme());
initial.commit586acc5fe2008-07-26 22:42:52547 const std::string url_domain_and_registry(
[email protected]69bb5872010-01-12 20:33:52548 GetEffectiveDomain(url_scheme, url_host));
initial.commit586acc5fe2008-07-26 22:42:52549 if (url_domain_and_registry.empty())
550 return false; // IP addresses/intranet hosts can't set domain cookies.
551 const std::string cookie_domain_and_registry(
[email protected]69bb5872010-01-12 20:33:52552 GetEffectiveDomain(url_scheme, cookie_domain));
initial.commit586acc5fe2008-07-26 22:42:52553 if (url_domain_and_registry != cookie_domain_and_registry)
554 return false; // Can't set a cookie on a different domain + registry.
555
556 // Ensure |url_host| is |cookie_domain| or one of its subdomains. Given that
557 // we know the domain+registry are the same from the above checks, this is
558 // basically a simple string suffix check.
559 if ((url_host.length() < cookie_domain.length()) ?
560 (cookie_domain != ("." + url_host)) :
561 url_host.compare(url_host.length() - cookie_domain.length(),
562 cookie_domain.length(), cookie_domain))
563 return false;
564
initial.commit586acc5fe2008-07-26 22:42:52565 *cookie_domain_key = cookie_domain;
566 return true;
567}
568
[email protected]f325f1e12010-04-30 22:38:55569// Determine the cookie domain key to use for setting the specified cookie.
570static bool GetCookieDomainKey(const GURL& url,
571 const CookieMonster::ParsedCookie& pc,
572 std::string* cookie_domain_key) {
573 std::string domain_string;
574 if (pc.HasDomain())
575 domain_string = pc.Domain();
576 return GetCookieDomainKeyWithString(url, domain_string, cookie_domain_key);
577}
578
579static std::string CanonPathWithString(const GURL& url,
580 const std::string& path_string) {
initial.commit586acc5fe2008-07-26 22:42:52581 // The RFC says the path should be a prefix of the current URL path.
582 // However, Mozilla allows you to set any path for compatibility with
583 // broken websites. We unfortunately will mimic this behavior. We try
584 // to be generous and accept cookies with an invalid path attribute, and
585 // default the path to something reasonable.
586
587 // The path was supplied in the cookie, we'll take it.
[email protected]f325f1e12010-04-30 22:38:55588 if (!path_string.empty() && path_string[0] == '/')
589 return path_string;
initial.commit586acc5fe2008-07-26 22:42:52590
591 // The path was not supplied in the cookie or invalid, we will default
592 // to the current URL path.
593 // """Defaults to the path of the request URL that generated the
594 // Set-Cookie response, up to, but not including, the
595 // right-most /."""
596 // How would this work for a cookie on /? We will include it then.
597 const std::string& url_path = url.path();
598
[email protected]c890ed192008-10-30 23:45:53599 size_t idx = url_path.find_last_of('/');
initial.commit586acc5fe2008-07-26 22:42:52600
601 // The cookie path was invalid or a single '/'.
602 if (idx == 0 || idx == std::string::npos)
603 return std::string("/");
604
605 // Return up to the rightmost '/'.
606 return url_path.substr(0, idx);
607}
608
[email protected]f325f1e12010-04-30 22:38:55609static std::string CanonPath(const GURL& url,
610 const CookieMonster::ParsedCookie& pc) {
611 std::string path_string;
612 if (pc.HasPath())
613 path_string = pc.Path();
614 return CanonPathWithString(url, path_string);
615}
616
initial.commit586acc5fe2008-07-26 22:42:52617static Time CanonExpiration(const CookieMonster::ParsedCookie& pc,
[email protected]4f79b3f2010-02-05 04:27:47618 const Time& current,
619 const CookieOptions& options) {
620 if (options.force_session())
621 return Time();
622
initial.commit586acc5fe2008-07-26 22:42:52623 // First, try the Max-Age attribute.
624 uint64 max_age = 0;
625 if (pc.HasMaxAge() &&
[email protected]dce5df52009-06-29 17:58:25626#ifdef COMPILER_MSVC
627 sscanf_s(
[email protected]d862fd92008-08-21 18:15:35628#else
[email protected]dce5df52009-06-29 17:58:25629 sscanf(
[email protected]d862fd92008-08-21 18:15:35630#endif
[email protected]dce5df52009-06-29 17:58:25631 pc.MaxAge().c_str(), " %" PRIu64, &max_age) == 1) {
initial.commit586acc5fe2008-07-26 22:42:52632 return current + TimeDelta::FromSeconds(max_age);
633 }
634
635 // Try the Expires attribute.
636 if (pc.HasExpires())
637 return CookieMonster::ParseCookieTime(pc.Expires());
638
639 // Invalid or no expiration, persistent cookie.
640 return Time();
641}
642
[email protected]47accfd62009-05-14 18:46:21643bool CookieMonster::HasCookieableScheme(const GURL& url) {
[email protected]bb8905722010-05-21 17:29:04644 lock_.AssertAcquired();
645
initial.commit586acc5fe2008-07-26 22:42:52646 // Make sure the request is on a cookie-able url scheme.
[email protected]47accfd62009-05-14 18:46:21647 for (size_t i = 0; i < cookieable_schemes_.size(); ++i) {
initial.commit586acc5fe2008-07-26 22:42:52648 // We matched a scheme.
[email protected]47accfd62009-05-14 18:46:21649 if (url.SchemeIs(cookieable_schemes_[i].c_str())) {
initial.commit586acc5fe2008-07-26 22:42:52650 // We've matched a supported scheme.
651 return true;
652 }
653 }
654
655 // The scheme didn't match any in our whitelist.
656 COOKIE_DLOG(WARNING) << "Unsupported cookie scheme: " << url.scheme();
657 return false;
658}
659
[email protected]47accfd62009-05-14 18:46:21660void CookieMonster::SetCookieableSchemes(
661 const char* schemes[], size_t num_schemes) {
[email protected]bb8905722010-05-21 17:29:04662 AutoLock autolock(lock_);
663
[email protected]cf12bd12010-06-17 14:41:30664 // Cookieable Schemes must be set before first use of function.
665 DCHECK(!initialized_);
666
[email protected]47accfd62009-05-14 18:46:21667 cookieable_schemes_.clear();
668 cookieable_schemes_.insert(cookieable_schemes_.end(),
669 schemes, schemes + num_schemes);
670}
671
[email protected]34602282010-02-03 22:14:15672bool CookieMonster::SetCookieWithCreationTimeAndOptions(
673 const GURL& url,
674 const std::string& cookie_line,
675 const Time& creation_time_or_null,
676 const CookieOptions& options) {
[email protected]b866a02d2010-07-28 16:41:04677 lock_.AssertAcquired();
initial.commit586acc5fe2008-07-26 22:42:52678
679 COOKIE_DLOG(INFO) << "SetCookie() line: " << cookie_line;
680
[email protected]34602282010-02-03 22:14:15681 Time creation_time = creation_time_or_null;
682 if (creation_time.is_null()) {
683 creation_time = CurrentTime();
684 last_time_seen_ = creation_time;
685 }
686
initial.commit586acc5fe2008-07-26 22:42:52687 // Parse the cookie.
688 ParsedCookie pc(cookie_line);
689
690 if (!pc.IsValid()) {
691 COOKIE_DLOG(WARNING) << "Couldn't parse cookie";
692 return false;
693 }
694
[email protected]3a96c742008-11-19 19:46:27695 if (options.exclude_httponly() && pc.IsHttpOnly()) {
696 COOKIE_DLOG(INFO) << "SetCookie() not setting httponly cookie";
697 return false;
698 }
699
initial.commit586acc5fe2008-07-26 22:42:52700 std::string cookie_domain;
701 if (!GetCookieDomainKey(url, pc, &cookie_domain)) {
702 return false;
703 }
704
705 std::string cookie_path = CanonPath(url, pc);
706
707 scoped_ptr<CanonicalCookie> cc;
[email protected]4f79b3f2010-02-05 04:27:47708 Time cookie_expires = CanonExpiration(pc, creation_time, options);
initial.commit586acc5fe2008-07-26 22:42:52709
[email protected]1655ba342010-07-14 18:17:42710 cc.reset(new CanonicalCookie(pc.Name(), pc.Value(), cookie_domain,
711 cookie_path,
initial.commit586acc5fe2008-07-26 22:42:52712 pc.IsSecure(), pc.IsHttpOnly(),
[email protected]77e0a462008-11-01 00:43:35713 creation_time, creation_time,
714 !cookie_expires.is_null(), cookie_expires));
initial.commit586acc5fe2008-07-26 22:42:52715
716 if (!cc.get()) {
717 COOKIE_DLOG(WARNING) << "Failed to allocate CanonicalCookie";
718 return false;
719 }
[email protected]fa77eb512010-07-22 16:12:51720 return SetCanonicalCookie(&cc, creation_time, options);
[email protected]f325f1e12010-04-30 22:38:55721}
initial.commit586acc5fe2008-07-26 22:42:52722
[email protected]b866a02d2010-07-28 16:41:04723bool CookieMonster::SetCookieWithCreationTime(const GURL& url,
724 const std::string& cookie_line,
725 const base::Time& creation_time) {
726 AutoLock autolock(lock_);
727
728 if (!HasCookieableScheme(url)) {
729 return false;
730 }
731
732 InitIfNecessary();
733 return SetCookieWithCreationTimeAndOptions(url, cookie_line, creation_time,
734 CookieOptions());
735}
736
[email protected]f325f1e12010-04-30 22:38:55737bool CookieMonster::SetCookieWithDetails(
738 const GURL& url, const std::string& name, const std::string& value,
739 const std::string& domain, const std::string& path,
740 const base::Time& expiration_time, bool secure, bool http_only) {
[email protected]f325f1e12010-04-30 22:38:55741
[email protected]f325f1e12010-04-30 22:38:55742 AutoLock autolock(lock_);
[email protected]bb8905722010-05-21 17:29:04743
744 if (!HasCookieableScheme(url))
745 return false;
746
[email protected]f325f1e12010-04-30 22:38:55747 InitIfNecessary();
748
749 Time creation_time = CurrentTime();
750 last_time_seen_ = creation_time;
751
752 scoped_ptr<CanonicalCookie> cc;
753 cc.reset(CanonicalCookie::Create(
[email protected]1655ba342010-07-14 18:17:42754 url, name, value, domain, path,
755 creation_time, expiration_time,
[email protected]f325f1e12010-04-30 22:38:55756 secure, http_only));
757
758 if (!cc.get())
759 return false;
760
761 CookieOptions options;
762 options.set_include_httponly();
[email protected]fa77eb512010-07-22 16:12:51763 return SetCanonicalCookie(&cc, creation_time, options);
[email protected]f325f1e12010-04-30 22:38:55764}
765
766bool CookieMonster::SetCanonicalCookie(scoped_ptr<CanonicalCookie>* cc,
[email protected]f325f1e12010-04-30 22:38:55767 const Time& creation_time,
768 const CookieOptions& options) {
[email protected]fa77eb512010-07-22 16:12:51769 const std::string domain((*cc)->Domain());
770 if (DeleteAnyEquivalentCookie(domain, **cc, options.exclude_httponly())) {
[email protected]3a96c742008-11-19 19:46:27771 COOKIE_DLOG(INFO) << "SetCookie() not clobbering httponly cookie";
772 return false;
773 }
initial.commit586acc5fe2008-07-26 22:42:52774
[email protected]f325f1e12010-04-30 22:38:55775 COOKIE_DLOG(INFO) << "SetCookie() cc: " << (*cc)->DebugString();
initial.commit586acc5fe2008-07-26 22:42:52776
777 // Realize that we might be setting an expired cookie, and the only point
778 // was to delete the cookie which we've already done.
[email protected]c4058fb2010-06-22 17:25:26779 if (!(*cc)->IsExpired(creation_time)) {
[email protected]374f58b2010-07-20 15:29:26780 // See InitializeHistograms() for details.
781 histogram_expiration_duration_minutes_->Add(
782 ((*cc)->ExpiryDate() - creation_time).InMinutes());
[email protected]fa77eb512010-07-22 16:12:51783 InternalInsertCookie(domain, cc->release(), true);
[email protected]c4058fb2010-06-22 17:25:26784 }
initial.commit586acc5fe2008-07-26 22:42:52785
786 // We assume that hopefully setting a cookie will be less common than
787 // querying a cookie. Since setting a cookie can put us over our limits,
788 // make sure that we garbage collect... We can also make the assumption that
789 // if a cookie was set, in the common case it will be used soon after,
790 // and we will purge the expired cookies in GetCookies().
[email protected]fa77eb512010-07-22 16:12:51791 GarbageCollect(creation_time, domain);
initial.commit586acc5fe2008-07-26 22:42:52792
793 return true;
794}
795
initial.commit586acc5fe2008-07-26 22:42:52796void CookieMonster::InternalInsertCookie(const std::string& key,
797 CanonicalCookie* cc,
798 bool sync_to_store) {
[email protected]bb8905722010-05-21 17:29:04799 lock_.AssertAcquired();
800
initial.commit586acc5fe2008-07-26 22:42:52801 if (cc->IsPersistent() && store_ && sync_to_store)
802 store_->AddCookie(key, *cc);
803 cookies_.insert(CookieMap::value_type(key, cc));
[email protected]0f7066e2010-03-25 08:31:47804 if (delegate_.get())
[email protected]65781e92010-07-21 15:29:57805 delegate_->OnCookieChanged(*cc, false);
initial.commit586acc5fe2008-07-26 22:42:52806}
807
[email protected]77e0a462008-11-01 00:43:35808void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie* cc) {
[email protected]bb8905722010-05-21 17:29:04809 lock_.AssertAcquired();
810
[email protected]77e0a462008-11-01 00:43:35811 // Based off the Mozilla code. When a cookie has been accessed recently,
812 // don't bother updating its access time again. This reduces the number of
813 // updates we do during pageload, which in turn reduces the chance our storage
814 // backend will hit its batch thresholds and be forced to update.
815 const Time current = Time::Now();
816 if ((current - cc->LastAccessDate()) < last_access_threshold_)
817 return;
818
[email protected]374f58b2010-07-20 15:29:26819 // See InitializeHistograms() for details.
820 histogram_between_access_interval_minutes_->Add(
821 (current - cc->LastAccessDate()).InMinutes());
[email protected]c4058fb2010-06-22 17:25:26822
[email protected]77e0a462008-11-01 00:43:35823 cc->SetLastAccessDate(current);
824 if (cc->IsPersistent() && store_)
825 store_->UpdateCookieAccessTime(*cc);
826}
827
initial.commit586acc5fe2008-07-26 22:42:52828void CookieMonster::InternalDeleteCookie(CookieMap::iterator it,
[email protected]c4058fb2010-06-22 17:25:26829 bool sync_to_store,
830 DeletionCause deletion_cause) {
[email protected]bb8905722010-05-21 17:29:04831 lock_.AssertAcquired();
832
[email protected]374f58b2010-07-20 15:29:26833 // See InitializeHistograms() for details.
834 histogram_cookie_deletion_cause_->Add(deletion_cause);
[email protected]c4058fb2010-06-22 17:25:26835
initial.commit586acc5fe2008-07-26 22:42:52836 CanonicalCookie* cc = it->second;
837 COOKIE_DLOG(INFO) << "InternalDeleteCookie() cc: " << cc->DebugString();
838 if (cc->IsPersistent() && store_ && sync_to_store)
839 store_->DeleteCookie(*cc);
[email protected]0f7066e2010-03-25 08:31:47840 if (delegate_.get())
[email protected]65781e92010-07-21 15:29:57841 delegate_->OnCookieChanged(*cc, true);
initial.commit586acc5fe2008-07-26 22:42:52842 cookies_.erase(it);
843 delete cc;
844}
845
[email protected]3a96c742008-11-19 19:46:27846bool CookieMonster::DeleteAnyEquivalentCookie(const std::string& key,
847 const CanonicalCookie& ecc,
848 bool skip_httponly) {
[email protected]bb8905722010-05-21 17:29:04849 lock_.AssertAcquired();
850
[email protected]c890ed192008-10-30 23:45:53851 bool found_equivalent_cookie = false;
[email protected]3a96c742008-11-19 19:46:27852 bool skipped_httponly = false;
initial.commit586acc5fe2008-07-26 22:42:52853 for (CookieMapItPair its = cookies_.equal_range(key);
854 its.first != its.second; ) {
855 CookieMap::iterator curit = its.first;
856 CanonicalCookie* cc = curit->second;
857 ++its.first;
858
initial.commit586acc5fe2008-07-26 22:42:52859 if (ecc.IsEquivalent(*cc)) {
[email protected]c890ed192008-10-30 23:45:53860 // We should never have more than one equivalent cookie, since they should
861 // overwrite each other.
[email protected]297a4ed02010-02-12 08:12:52862 CHECK(!found_equivalent_cookie) <<
[email protected]c890ed192008-10-30 23:45:53863 "Duplicate equivalent cookies found, cookie store is corrupted.";
[email protected]3a96c742008-11-19 19:46:27864 if (skip_httponly && cc->IsHttpOnly()) {
865 skipped_httponly = true;
866 } else {
[email protected]2f3f3592010-07-07 20:11:51867 InternalDeleteCookie(curit, true, DELETE_COOKIE_OVERWRITE);
[email protected]3a96c742008-11-19 19:46:27868 }
[email protected]c890ed192008-10-30 23:45:53869 found_equivalent_cookie = true;
initial.commit586acc5fe2008-07-26 22:42:52870 }
871 }
[email protected]3a96c742008-11-19 19:46:27872 return skipped_httponly;
initial.commit586acc5fe2008-07-26 22:42:52873}
874
initial.commit586acc5fe2008-07-26 22:42:52875int CookieMonster::GarbageCollect(const Time& current,
876 const std::string& key) {
[email protected]bb8905722010-05-21 17:29:04877 lock_.AssertAcquired();
878
initial.commit586acc5fe2008-07-26 22:42:52879 int num_deleted = 0;
880
881 // Collect garbage for this key.
882 if (cookies_.count(key) > kNumCookiesPerHost) {
883 COOKIE_DLOG(INFO) << "GarbageCollect() key: " << key;
884 num_deleted += GarbageCollectRange(current, cookies_.equal_range(key),
[email protected]c890ed192008-10-30 23:45:53885 kNumCookiesPerHost, kNumCookiesPerHostPurge);
initial.commit586acc5fe2008-07-26 22:42:52886 }
887
888 // Collect garbage for everything.
889 if (cookies_.size() > kNumCookiesTotal) {
890 COOKIE_DLOG(INFO) << "GarbageCollect() everything";
891 num_deleted += GarbageCollectRange(current,
[email protected]c890ed192008-10-30 23:45:53892 CookieMapItPair(cookies_.begin(), cookies_.end()), kNumCookiesTotal,
893 kNumCookiesTotalPurge);
894 }
895
896 return num_deleted;
897}
898
[email protected]77e0a462008-11-01 00:43:35899static bool LRUCookieSorter(const CookieMonster::CookieMap::iterator& it1,
900 const CookieMonster::CookieMap::iterator& it2) {
901 // Cookies accessed less recently should be deleted first.
902 if (it1->second->LastAccessDate() != it2->second->LastAccessDate())
903 return it1->second->LastAccessDate() < it2->second->LastAccessDate();
904
905 // In rare cases we might have two cookies with identical last access times.
906 // To preserve the stability of the sort, in these cases prefer to delete
907 // older cookies over newer ones. CreationDate() is guaranteed to be unique.
[email protected]c890ed192008-10-30 23:45:53908 return it1->second->CreationDate() < it2->second->CreationDate();
909}
910
911int CookieMonster::GarbageCollectRange(const Time& current,
912 const CookieMapItPair& itpair,
913 size_t num_max,
914 size_t num_purge) {
[email protected]bb8905722010-05-21 17:29:04915 lock_.AssertAcquired();
916
[email protected]c890ed192008-10-30 23:45:53917 // First, delete anything that's expired.
918 std::vector<CookieMap::iterator> cookie_its;
919 int num_deleted = GarbageCollectExpired(current, itpair, &cookie_its);
920
[email protected]77e0a462008-11-01 00:43:35921 // If the range still has too many cookies, delete the least recently used.
[email protected]c890ed192008-10-30 23:45:53922 if (cookie_its.size() > num_max) {
923 COOKIE_DLOG(INFO) << "GarbageCollectRange() Deep Garbage Collect.";
924 // Purge down to (|num_max| - |num_purge|) total cookies.
925 DCHECK(num_purge <= num_max);
926 num_purge += cookie_its.size() - num_max;
927
928 std::partial_sort(cookie_its.begin(), cookie_its.begin() + num_purge,
[email protected]77e0a462008-11-01 00:43:35929 cookie_its.end(), LRUCookieSorter);
[email protected]c4058fb2010-06-22 17:25:26930 for (size_t i = 0; i < num_purge; ++i) {
[email protected]374f58b2010-07-20 15:29:26931 // See InitializeHistograms() for details.
932 histogram_evicted_last_access_minutes_->Add(
933 (current - cookie_its[i]->second->LastAccessDate()).InMinutes());
[email protected]2f3f3592010-07-07 20:11:51934 InternalDeleteCookie(cookie_its[i], true, DELETE_COOKIE_EVICTED);
[email protected]c4058fb2010-06-22 17:25:26935 }
[email protected]c890ed192008-10-30 23:45:53936
937 num_deleted += num_purge;
938 }
939
940 return num_deleted;
941}
942
943int CookieMonster::GarbageCollectExpired(
944 const Time& current,
945 const CookieMapItPair& itpair,
946 std::vector<CookieMap::iterator>* cookie_its) {
[email protected]bb8905722010-05-21 17:29:04947 lock_.AssertAcquired();
948
[email protected]c890ed192008-10-30 23:45:53949 int num_deleted = 0;
950 for (CookieMap::iterator it = itpair.first, end = itpair.second; it != end;) {
951 CookieMap::iterator curit = it;
952 ++it;
953
954 if (curit->second->IsExpired(current)) {
[email protected]2f3f3592010-07-07 20:11:51955 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
[email protected]c890ed192008-10-30 23:45:53956 ++num_deleted;
957 } else if (cookie_its) {
958 cookie_its->push_back(curit);
959 }
initial.commit586acc5fe2008-07-26 22:42:52960 }
961
962 return num_deleted;
963}
964
965int CookieMonster::DeleteAll(bool sync_to_store) {
966 AutoLock autolock(lock_);
967 InitIfNecessary();
968
969 int num_deleted = 0;
970 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
971 CookieMap::iterator curit = it;
972 ++it;
[email protected]c4058fb2010-06-22 17:25:26973 InternalDeleteCookie(curit, sync_to_store,
[email protected]2f3f3592010-07-07 20:11:51974 sync_to_store ? DELETE_COOKIE_EXPLICIT :
975 DELETE_COOKIE_DONT_RECORD /* Destruction. */);
initial.commit586acc5fe2008-07-26 22:42:52976 ++num_deleted;
977 }
978
979 return num_deleted;
980}
981
982int CookieMonster::DeleteAllCreatedBetween(const Time& delete_begin,
983 const Time& delete_end,
984 bool sync_to_store) {
985 AutoLock autolock(lock_);
986 InitIfNecessary();
987
988 int num_deleted = 0;
989 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
990 CookieMap::iterator curit = it;
991 CanonicalCookie* cc = curit->second;
992 ++it;
993
994 if (cc->CreationDate() >= delete_begin &&
995 (delete_end.is_null() || cc->CreationDate() < delete_end)) {
[email protected]2f3f3592010-07-07 20:11:51996 InternalDeleteCookie(curit, sync_to_store, DELETE_COOKIE_EXPLICIT);
initial.commit586acc5fe2008-07-26 22:42:52997 ++num_deleted;
998 }
999 }
1000
1001 return num_deleted;
1002}
1003
1004int CookieMonster::DeleteAllCreatedAfter(const Time& delete_begin,
1005 bool sync_to_store) {
1006 return DeleteAllCreatedBetween(delete_begin, Time(), sync_to_store);
1007}
1008
[email protected]c8c7d8a2010-07-07 19:58:361009int CookieMonster::DeleteAllForHost(const GURL& url) {
[email protected]c10da4b02010-03-25 14:38:321010 AutoLock autolock(lock_);
1011 InitIfNecessary();
[email protected]bb8905722010-05-21 17:29:041012
[email protected]c8c7d8a2010-07-07 19:58:361013 if (!HasCookieableScheme(url))
1014 return 0;
1015
1016 // We store host cookies in the store by their canonical host name;
1017 // domain cookies are stored with a leading ".". So this is a pretty
1018 // simple lookup and per-cookie delete.
[email protected]c10da4b02010-03-25 14:38:321019 int num_deleted = 0;
[email protected]c8c7d8a2010-07-07 19:58:361020 for (CookieMapItPair its = cookies_.equal_range(url.host());
1021 its.first != its.second;) {
1022 CookieMap::iterator curit = its.first;
1023 ++its.first;
1024 num_deleted++;
1025
[email protected]2f3f3592010-07-07 20:11:511026 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT);
[email protected]c10da4b02010-03-25 14:38:321027 }
1028 return num_deleted;
1029}
1030
initial.commit586acc5fe2008-07-26 22:42:521031bool CookieMonster::DeleteCookie(const std::string& domain,
1032 const CanonicalCookie& cookie,
1033 bool sync_to_store) {
1034 AutoLock autolock(lock_);
1035 InitIfNecessary();
1036
1037 for (CookieMapItPair its = cookies_.equal_range(domain);
1038 its.first != its.second; ++its.first) {
1039 // The creation date acts as our unique index...
1040 if (its.first->second->CreationDate() == cookie.CreationDate()) {
[email protected]2f3f3592010-07-07 20:11:511041 InternalDeleteCookie(its.first, sync_to_store, DELETE_COOKIE_EXPLICIT);
initial.commit586acc5fe2008-07-26 22:42:521042 return true;
1043 }
1044 }
1045 return false;
1046}
1047
1048// Mozilla sorts on the path length (longest first), and then it
1049// sorts by creation time (oldest first).
1050// The RFC says the sort order for the domain attribute is undefined.
1051static bool CookieSorter(CookieMonster::CanonicalCookie* cc1,
1052 CookieMonster::CanonicalCookie* cc2) {
1053 if (cc1->Path().length() == cc2->Path().length())
1054 return cc1->CreationDate() < cc2->CreationDate();
1055 return cc1->Path().length() > cc2->Path().length();
1056}
1057
[email protected]34602282010-02-03 22:14:151058bool CookieMonster::SetCookieWithOptions(const GURL& url,
1059 const std::string& cookie_line,
1060 const CookieOptions& options) {
[email protected]b866a02d2010-07-28 16:41:041061 AutoLock autolock(lock_);
1062
1063 if (!HasCookieableScheme(url)) {
1064 return false;
1065 }
1066
1067 InitIfNecessary();
1068
[email protected]34602282010-02-03 22:14:151069 return SetCookieWithCreationTimeAndOptions(url, cookie_line, Time(), options);
1070}
1071
initial.commit586acc5fe2008-07-26 22:42:521072// Currently our cookie datastructure is based on Mozilla's approach. We have a
1073// hash keyed on the cookie's domain, and for any query we walk down the domain
1074// components and probe for cookies until we reach the TLD, where we stop.
1075// For example, a.b.blah.com, we would probe
1076// - a.b.blah.com
1077// - .a.b.blah.com (TODO should we check this first or second?)
1078// - .b.blah.com
1079// - .blah.com
1080// There are some alternative datastructures we could try, like a
1081// search/prefix trie, where we reverse the hostname and query for all
1082// keys that are a prefix of our hostname. I think the hash probing
1083// should be fast and simple enough for now.
1084std::string CookieMonster::GetCookiesWithOptions(const GURL& url,
[email protected]3a96c742008-11-19 19:46:271085 const CookieOptions& options) {
[email protected]bb8905722010-05-21 17:29:041086 AutoLock autolock(lock_);
1087 InitIfNecessary();
1088
initial.commit586acc5fe2008-07-26 22:42:521089 if (!HasCookieableScheme(url)) {
initial.commit586acc5fe2008-07-26 22:42:521090 return std::string();
1091 }
1092
1093 // Get the cookies for this host and its domain(s).
1094 std::vector<CanonicalCookie*> cookies;
[email protected]fa77eb512010-07-22 16:12:511095 FindCookiesForHostAndDomain(url, options, true, &cookies);
initial.commit586acc5fe2008-07-26 22:42:521096 std::sort(cookies.begin(), cookies.end(), CookieSorter);
1097
1098 std::string cookie_line;
1099 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
1100 it != cookies.end(); ++it) {
1101 if (it != cookies.begin())
1102 cookie_line += "; ";
1103 // In Mozilla if you set a cookie like AAAA, it will have an empty token
1104 // and a value of AAAA. When it sends the cookie back, it will send AAAA,
1105 // so we need to avoid sending =AAAA for a blank token value.
1106 if (!(*it)->Name().empty())
1107 cookie_line += (*it)->Name() + "=";
1108 cookie_line += (*it)->Value();
1109 }
1110
1111 COOKIE_DLOG(INFO) << "GetCookies() result: " << cookie_line;
1112
1113 return cookie_line;
1114}
1115
[email protected]971713e2009-10-29 16:07:211116void CookieMonster::DeleteCookie(const GURL& url,
1117 const std::string& cookie_name) {
[email protected]bb8905722010-05-21 17:29:041118 AutoLock autolock(lock_);
1119 InitIfNecessary();
1120
[email protected]971713e2009-10-29 16:07:211121 if (!HasCookieableScheme(url))
1122 return;
1123
[email protected]e8bac552009-10-30 16:15:391124 CookieOptions options;
1125 options.set_include_httponly();
1126 // Get the cookies for this host and its domain(s).
1127 std::vector<CanonicalCookie*> cookies;
[email protected]fa77eb512010-07-22 16:12:511128 FindCookiesForHostAndDomain(url, options, true, &cookies);
[email protected]e8bac552009-10-30 16:15:391129 std::set<CanonicalCookie*> matching_cookies;
1130
1131 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
1132 it != cookies.end(); ++it) {
1133 if ((*it)->Name() != cookie_name)
1134 continue;
1135 if (url.path().find((*it)->Path()))
1136 continue;
1137 matching_cookies.insert(*it);
1138 }
1139
1140 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1141 CookieMap::iterator curit = it;
1142 ++it;
[email protected]c4058fb2010-06-22 17:25:261143 if (matching_cookies.find(curit->second) != matching_cookies.end()) {
[email protected]2f3f3592010-07-07 20:11:511144 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT);
[email protected]c4058fb2010-06-22 17:25:261145 }
[email protected]971713e2009-10-29 16:07:211146 }
1147}
1148
initial.commit586acc5fe2008-07-26 22:42:521149CookieMonster::CookieList CookieMonster::GetAllCookies() {
1150 AutoLock autolock(lock_);
1151 InitIfNecessary();
1152
[email protected]c890ed192008-10-30 23:45:531153 // This function is being called to scrape the cookie list for management UI
1154 // or similar. We shouldn't show expired cookies in this list since it will
1155 // just be confusing to users, and this function is called rarely enough (and
1156 // is already slow enough) that it's OK to take the time to garbage collect
1157 // the expired cookies now.
1158 //
1159 // Note that this does not prune cookies to be below our limits (if we've
1160 // exceeded them) the way that calling GarbageCollect() would.
1161 GarbageCollectExpired(Time::Now(),
1162 CookieMapItPair(cookies_.begin(), cookies_.end()),
1163 NULL);
initial.commit586acc5fe2008-07-26 22:42:521164
[email protected]c890ed192008-10-30 23:45:531165 CookieList cookie_list;
1166 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end(); ++it)
[email protected]65781e92010-07-21 15:29:571167 cookie_list.push_back(*it->second);
initial.commit586acc5fe2008-07-26 22:42:521168
1169 return cookie_list;
1170}
1171
[email protected]34602282010-02-03 22:14:151172CookieMonster::CookieList CookieMonster::GetAllCookiesForURL(const GURL& url) {
[email protected]86d9b0d2010-02-03 18:12:071173 AutoLock autolock(lock_);
1174 InitIfNecessary();
[email protected]bb8905722010-05-21 17:29:041175
[email protected]fa77eb512010-07-22 16:12:511176 CookieOptions options;
1177 options.set_include_httponly();
1178
1179 std::vector<CanonicalCookie*> cookie_ptrs;
1180 FindCookiesForHostAndDomain(url, options, false, &cookie_ptrs);
1181
1182 CookieList cookies;
1183 for (std::vector<CanonicalCookie*>::const_iterator it = cookie_ptrs.begin();
1184 it != cookie_ptrs.end(); it++) {
1185 cookies.push_back(**it);
1186 }
1187 return cookies;
[email protected]79a087a2010-02-03 17:08:191188}
1189
initial.commit586acc5fe2008-07-26 22:42:521190void CookieMonster::FindCookiesForHostAndDomain(
1191 const GURL& url,
[email protected]3a96c742008-11-19 19:46:271192 const CookieOptions& options,
[email protected]fa77eb512010-07-22 16:12:511193 bool update_access_time,
initial.commit586acc5fe2008-07-26 22:42:521194 std::vector<CanonicalCookie*>* cookies) {
[email protected]bb8905722010-05-21 17:29:041195 lock_.AssertAcquired();
initial.commit586acc5fe2008-07-26 22:42:521196
1197 const Time current_time(CurrentTime());
1198
[email protected]c4058fb2010-06-22 17:25:261199 // Probe to save statistics relatively frequently. We do it here rather
1200 // than in the set path as many websites won't set cookies, and we
1201 // want to collect statistics whenever the browser's being used.
1202 RecordPeriodicStats(current_time);
1203
initial.commit586acc5fe2008-07-26 22:42:521204 // Query for the full host, For example: 'a.c.blah.com'.
1205 std::string key(url.host());
[email protected]fa77eb512010-07-22 16:12:511206 FindCookiesForKey(key, url, options, current_time, update_access_time,
1207 cookies);
initial.commit586acc5fe2008-07-26 22:42:521208
1209 // See if we can search for domain cookies, i.e. if the host has a TLD + 1.
[email protected]69bb5872010-01-12 20:33:521210 const std::string domain(GetEffectiveDomain(url.scheme(), key));
initial.commit586acc5fe2008-07-26 22:42:521211 if (domain.empty())
1212 return;
1213 DCHECK_LE(domain.length(), key.length());
1214 DCHECK_EQ(0, key.compare(key.length() - domain.length(), domain.length(),
1215 domain));
1216
1217 // Walk through the string and query at the dot points (GURL should have
1218 // canonicalized the dots, so this should be safe). Stop once we reach the
1219 // domain + registry; we can't write cookies past this point, and with some
1220 // registrars other domains can, in which case we don't want to read their
1221 // cookies.
1222 for (key = "." + key; key.length() > domain.length(); ) {
[email protected]fa77eb512010-07-22 16:12:511223 FindCookiesForKey(key, url, options, current_time, update_access_time,
1224 cookies);
initial.commit586acc5fe2008-07-26 22:42:521225 const size_t next_dot = key.find('.', 1); // Skip over leading dot.
1226 key.erase(0, next_dot);
1227 }
1228}
1229
1230void CookieMonster::FindCookiesForKey(
1231 const std::string& key,
1232 const GURL& url,
[email protected]3a96c742008-11-19 19:46:271233 const CookieOptions& options,
initial.commit586acc5fe2008-07-26 22:42:521234 const Time& current,
[email protected]fa77eb512010-07-22 16:12:511235 bool update_access_time,
initial.commit586acc5fe2008-07-26 22:42:521236 std::vector<CanonicalCookie*>* cookies) {
[email protected]bb8905722010-05-21 17:29:041237 lock_.AssertAcquired();
1238
initial.commit586acc5fe2008-07-26 22:42:521239 bool secure = url.SchemeIsSecure();
1240
1241 for (CookieMapItPair its = cookies_.equal_range(key);
1242 its.first != its.second; ) {
1243 CookieMap::iterator curit = its.first;
1244 CanonicalCookie* cc = curit->second;
1245 ++its.first;
1246
1247 // If the cookie is expired, delete it.
1248 if (cc->IsExpired(current)) {
[email protected]2f3f3592010-07-07 20:11:511249 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
initial.commit586acc5fe2008-07-26 22:42:521250 continue;
1251 }
1252
[email protected]3a96c742008-11-19 19:46:271253 // Filter out HttpOnly cookies, per options.
1254 if (options.exclude_httponly() && cc->IsHttpOnly())
initial.commit586acc5fe2008-07-26 22:42:521255 continue;
1256
1257 // Filter out secure cookies unless we're https.
1258 if (!secure && cc->IsSecure())
1259 continue;
1260
1261 if (!cc->IsOnPath(url.path()))
1262 continue;
1263
[email protected]fa77eb512010-07-22 16:12:511264 // Add this cookie to the set of matching cookies. Update the access
1265 // time if we've been requested to do so.
1266 if (update_access_time) {
1267 InternalUpdateCookieAccessTime(cc);
1268 }
initial.commit586acc5fe2008-07-26 22:42:521269 cookies->push_back(cc);
1270 }
1271}
1272
[email protected]c4058fb2010-06-22 17:25:261273// Test to see if stats should be recorded, and record them if so.
1274// The goal here is to get sampling for the average browser-hour of
1275// activity. We won't take samples when the web isn't being surfed,
1276// and when the web is being surfed, we'll take samples about every
1277// kRecordStatisticsIntervalSeconds.
1278// last_statistic_record_time_ is initialized to Now() rather than null
1279// in the constructor so that we won't take statistics right after
1280// startup, to avoid bias from browsers that are started but not used.
1281void CookieMonster::RecordPeriodicStats(const base::Time& current_time) {
1282 const base::TimeDelta kRecordStatisticsIntervalTime(
1283 base::TimeDelta::FromSeconds(kRecordStatisticsIntervalSeconds));
1284
1285 if (current_time - last_statistic_record_time_ >
1286 kRecordStatisticsIntervalTime) {
[email protected]374f58b2010-07-20 15:29:261287 // See InitializeHistograms() for details.
1288 histogram_count_->Add(cookies_.size());
[email protected]c4058fb2010-06-22 17:25:261289 last_statistic_record_time_ = current_time;
1290 }
1291}
1292
initial.commit586acc5fe2008-07-26 22:42:521293CookieMonster::ParsedCookie::ParsedCookie(const std::string& cookie_line)
1294 : is_valid_(false),
1295 path_index_(0),
1296 domain_index_(0),
1297 expires_index_(0),
1298 maxage_index_(0),
1299 secure_index_(0),
1300 httponly_index_(0) {
1301
1302 if (cookie_line.size() > kMaxCookieSize) {
1303 LOG(INFO) << "Not parsing cookie, too large: " << cookie_line.size();
1304 return;
1305 }
1306
1307 ParseTokenValuePairs(cookie_line);
1308 if (pairs_.size() > 0) {
1309 is_valid_ = true;
1310 SetupAttributes();
1311 }
1312}
1313
1314// Returns true if |c| occurs in |chars|
1315// TODO maybe make this take an iterator, could check for end also?
1316static inline bool CharIsA(const char c, const char* chars) {
1317 return strchr(chars, c) != NULL;
1318}
1319// Seek the iterator to the first occurrence of a character in |chars|.
1320// Returns true if it hit the end, false otherwise.
1321static inline bool SeekTo(std::string::const_iterator* it,
1322 const std::string::const_iterator& end,
1323 const char* chars) {
[email protected]f07467d2010-06-16 14:28:301324 for (; *it != end && !CharIsA(**it, chars); ++(*it)) {}
initial.commit586acc5fe2008-07-26 22:42:521325 return *it == end;
1326}
1327// Seek the iterator to the first occurrence of a character not in |chars|.
1328// Returns true if it hit the end, false otherwise.
1329static inline bool SeekPast(std::string::const_iterator* it,
1330 const std::string::const_iterator& end,
1331 const char* chars) {
[email protected]f07467d2010-06-16 14:28:301332 for (; *it != end && CharIsA(**it, chars); ++(*it)) {}
initial.commit586acc5fe2008-07-26 22:42:521333 return *it == end;
1334}
1335static inline bool SeekBackPast(std::string::const_iterator* it,
1336 const std::string::const_iterator& end,
1337 const char* chars) {
[email protected]f07467d2010-06-16 14:28:301338 for (; *it != end && CharIsA(**it, chars); --(*it)) {}
initial.commit586acc5fe2008-07-26 22:42:521339 return *it == end;
1340}
1341
[email protected]f325f1e12010-04-30 22:38:551342const char CookieMonster::ParsedCookie::kTerminator[] = "\n\r\0";
1343const int CookieMonster::ParsedCookie::kTerminatorLen =
1344 sizeof(kTerminator) - 1;
1345const char CookieMonster::ParsedCookie::kWhitespace[] = " \t";
1346const char CookieMonster::ParsedCookie::kValueSeparator[] = ";";
1347const char CookieMonster::ParsedCookie::kTokenSeparator[] = ";=";
1348
1349std::string::const_iterator CookieMonster::ParsedCookie::FindFirstTerminator(
1350 const std::string& s) {
1351 std::string::const_iterator end = s.end();
1352 size_t term_pos =
1353 s.find_first_of(std::string(kTerminator, kTerminatorLen));
1354 if (term_pos != std::string::npos) {
1355 // We found a character we should treat as an end of string.
1356 end = s.begin() + term_pos;
1357 }
1358 return end;
1359}
1360
1361bool CookieMonster::ParsedCookie::ParseToken(
1362 std::string::const_iterator* it,
1363 const std::string::const_iterator& end,
1364 std::string::const_iterator* token_start,
1365 std::string::const_iterator* token_end) {
1366 DCHECK(it && token_start && token_end);
1367 std::string::const_iterator token_real_end;
1368
1369 // Seek past any whitespace before the "token" (the name).
1370 // token_start should point at the first character in the token
1371 if (SeekPast(it, end, kWhitespace))
1372 return false; // No token, whitespace or empty.
1373 *token_start = *it;
1374
1375 // Seek over the token, to the token separator.
1376 // token_real_end should point at the token separator, i.e. '='.
1377 // If it == end after the seek, we probably have a token-value.
1378 SeekTo(it, end, kTokenSeparator);
1379 token_real_end = *it;
1380
1381 // Ignore any whitespace between the token and the token separator.
1382 // token_end should point after the last interesting token character,
1383 // pointing at either whitespace, or at '=' (and equal to token_real_end).
1384 if (*it != *token_start) { // We could have an empty token name.
1385 --(*it); // Go back before the token separator.
1386 // Skip over any whitespace to the first non-whitespace character.
1387 SeekBackPast(it, *token_start, kWhitespace);
1388 // Point after it.
1389 ++(*it);
1390 }
1391 *token_end = *it;
1392
1393 // Seek us back to the end of the token.
1394 *it = token_real_end;
1395 return true;
1396}
1397
1398void CookieMonster::ParsedCookie::ParseValue(
1399 std::string::const_iterator* it,
1400 const std::string::const_iterator& end,
1401 std::string::const_iterator* value_start,
1402 std::string::const_iterator* value_end) {
1403 DCHECK(it && value_start && value_end);
1404
1405 // Seek past any whitespace that might in-between the token and value.
1406 SeekPast(it, end, kWhitespace);
1407 // value_start should point at the first character of the value.
1408 *value_start = *it;
1409
1410 // It is unclear exactly how quoted string values should be handled.
1411 // Major browsers do different things, for example, Firefox supports
1412 // semicolons embedded in a quoted value, while IE does not. Looking at
1413 // the specs, RFC 2109 and 2965 allow for a quoted-string as the value.
1414 // However, these specs were apparently written after browsers had
1415 // implemented cookies, and they seem very distant from the reality of
1416 // what is actually implemented and used on the web. The original spec
1417 // from Netscape is possibly what is closest to the cookies used today.
1418 // This spec didn't have explicit support for double quoted strings, and
1419 // states that ; is not allowed as part of a value. We had originally
1420 // implement the Firefox behavior (A="B;C"; -> A="B;C";). However, since
1421 // there is no standard that makes sense, we decided to follow the behavior
1422 // of IE and Safari, which is closer to the original Netscape proposal.
1423 // This means that A="B;C" -> A="B;. This also makes the code much simpler
1424 // and reduces the possibility for invalid cookies, where other browsers
1425 // like Opera currently reject those invalid cookies (ex A="B" "C";).
1426
1427 // Just look for ';' to terminate ('=' allowed).
1428 // We can hit the end, maybe they didn't terminate.
1429 SeekTo(it, end, kValueSeparator);
1430
1431 // Will be pointed at the ; seperator or the end.
1432 *value_end = *it;
1433
1434 // Ignore any unwanted whitespace after the value.
1435 if (*value_end != *value_start) { // Could have an empty value
1436 --(*value_end);
1437 SeekBackPast(value_end, *value_start, kWhitespace);
1438 ++(*value_end);
1439 }
1440}
1441
1442std::string CookieMonster::ParsedCookie::ParseTokenString(
1443 const std::string& token) {
1444 std::string::const_iterator it = token.begin();
1445 std::string::const_iterator end = FindFirstTerminator(token);
1446
1447 std::string::const_iterator token_start, token_end;
1448 if (ParseToken(&it, end, &token_start, &token_end))
1449 return std::string(token_start, token_end);
1450 return std::string();
1451}
1452
1453std::string CookieMonster::ParsedCookie::ParseValueString(
1454 const std::string& value) {
1455 std::string::const_iterator it = value.begin();
1456 std::string::const_iterator end = FindFirstTerminator(value);
1457
1458 std::string::const_iterator value_start, value_end;
1459 ParseValue(&it, end, &value_start, &value_end);
1460 return std::string(value_start, value_end);
1461}
1462
initial.commit586acc5fe2008-07-26 22:42:521463// Parse all token/value pairs and populate pairs_.
1464void CookieMonster::ParsedCookie::ParseTokenValuePairs(
1465 const std::string& cookie_line) {
initial.commit586acc5fe2008-07-26 22:42:521466 pairs_.clear();
1467
1468 // Ok, here we go. We should be expecting to be starting somewhere
1469 // before the cookie line, not including any header name...
1470 std::string::const_iterator start = cookie_line.begin();
initial.commit586acc5fe2008-07-26 22:42:521471 std::string::const_iterator it = start;
1472
1473 // TODO Make sure we're stripping \r\n in the network code. Then we
1474 // can log any unexpected terminators.
[email protected]f325f1e12010-04-30 22:38:551475 std::string::const_iterator end = FindFirstTerminator(cookie_line);
initial.commit586acc5fe2008-07-26 22:42:521476
1477 for (int pair_num = 0; pair_num < kMaxPairs && it != end; ++pair_num) {
1478 TokenValuePair pair;
initial.commit586acc5fe2008-07-26 22:42:521479
[email protected]f325f1e12010-04-30 22:38:551480 std::string::const_iterator token_start, token_end;
1481 if (!ParseToken(&it, end, &token_start, &token_end))
1482 break;
initial.commit586acc5fe2008-07-26 22:42:521483
1484 if (it == end || *it != '=') {
1485 // We have a token-value, we didn't have any token name.
1486 if (pair_num == 0) {
1487 // For the first time around, we want to treat single values
1488 // as a value with an empty name. (Mozilla bug 169091).
1489 // IE seems to also have this behavior, ex "AAA", and "AAA=10" will
1490 // set 2 different cookies, and setting "BBB" will then replace "AAA".
1491 pair.first = "";
1492 // Rewind to the beginning of what we thought was the token name,
1493 // and let it get parsed as a value.
1494 it = token_start;
1495 } else {
1496 // Any not-first attribute we want to treat a value as a
1497 // name with an empty value... This is so something like
1498 // "secure;" will get parsed as a Token name, and not a value.
1499 pair.first = std::string(token_start, token_end);
1500 }
1501 } else {
1502 // We have a TOKEN=VALUE.
1503 pair.first = std::string(token_start, token_end);
1504 ++it; // Skip past the '='.
1505 }
1506
1507 // OK, now try to parse a value.
1508 std::string::const_iterator value_start, value_end;
[email protected]f325f1e12010-04-30 22:38:551509 ParseValue(&it, end, &value_start, &value_end);
initial.commit586acc5fe2008-07-26 22:42:521510 // OK, we're finished with a Token/Value.
1511 pair.second = std::string(value_start, value_end);
[email protected]f325f1e12010-04-30 22:38:551512
initial.commit586acc5fe2008-07-26 22:42:521513 // From RFC2109: "Attributes (names) (attr) are case-insensitive."
1514 if (pair_num != 0)
1515 StringToLowerASCII(&pair.first);
1516 pairs_.push_back(pair);
1517
1518 // We've processed a token/value pair, we're either at the end of
1519 // the string or a ValueSeparator like ';', which we want to skip.
1520 if (it != end)
1521 ++it;
1522 }
1523}
1524
1525void CookieMonster::ParsedCookie::SetupAttributes() {
1526 static const char kPathTokenName[] = "path";
1527 static const char kDomainTokenName[] = "domain";
1528 static const char kExpiresTokenName[] = "expires";
1529 static const char kMaxAgeTokenName[] = "max-age";
1530 static const char kSecureTokenName[] = "secure";
1531 static const char kHttpOnlyTokenName[] = "httponly";
1532
1533 // We skip over the first token/value, the user supplied one.
1534 for (size_t i = 1; i < pairs_.size(); ++i) {
[email protected]f325f1e12010-04-30 22:38:551535 if (pairs_[i].first == kPathTokenName) {
initial.commit586acc5fe2008-07-26 22:42:521536 path_index_ = i;
[email protected]f325f1e12010-04-30 22:38:551537 } else if (pairs_[i].first == kDomainTokenName) {
initial.commit586acc5fe2008-07-26 22:42:521538 domain_index_ = i;
[email protected]f325f1e12010-04-30 22:38:551539 } else if (pairs_[i].first == kExpiresTokenName) {
initial.commit586acc5fe2008-07-26 22:42:521540 expires_index_ = i;
[email protected]f325f1e12010-04-30 22:38:551541 } else if (pairs_[i].first == kMaxAgeTokenName) {
initial.commit586acc5fe2008-07-26 22:42:521542 maxage_index_ = i;
[email protected]f325f1e12010-04-30 22:38:551543 } else if (pairs_[i].first == kSecureTokenName) {
initial.commit586acc5fe2008-07-26 22:42:521544 secure_index_ = i;
[email protected]f325f1e12010-04-30 22:38:551545 } else if (pairs_[i].first == kHttpOnlyTokenName) {
initial.commit586acc5fe2008-07-26 22:42:521546 httponly_index_ = i;
[email protected]f325f1e12010-04-30 22:38:551547 } else {
1548 /* some attribute we don't know or don't care about. */
1549 }
initial.commit586acc5fe2008-07-26 22:42:521550 }
1551}
1552
1553// Create a cookie-line for the cookie. For debugging only!
1554// If we want to use this for something more than debugging, we
1555// should rewrite it better...
1556std::string CookieMonster::ParsedCookie::DebugString() const {
1557 std::string out;
1558 for (PairList::const_iterator it = pairs_.begin();
1559 it != pairs_.end(); ++it) {
1560 out.append(it->first);
1561 out.append("=");
1562 out.append(it->second);
1563 out.append("; ");
1564 }
1565 return out;
1566}
1567
[email protected]a986cc32010-02-12 23:55:471568CookieMonster::CanonicalCookie::CanonicalCookie(const GURL& url,
1569 const ParsedCookie& pc)
1570 : name_(pc.Name()),
1571 value_(pc.Value()),
1572 path_(CanonPath(url, pc)),
1573 creation_date_(Time::Now()),
1574 last_access_date_(Time()),
1575 has_expires_(pc.HasExpires()),
1576 secure_(pc.IsSecure()),
1577 httponly_(pc.IsHttpOnly()) {
1578 if (has_expires_)
1579 expiry_date_ = CanonExpiration(pc, creation_date_, CookieOptions());
[email protected]1655ba342010-07-14 18:17:421580
1581 // Do the best we can with the domain.
1582 std::string cookie_domain;
1583 std::string domain_string;
1584 if (pc.HasDomain()) {
1585 domain_string = pc.Domain();
1586 }
1587 bool result
1588 = GetCookieDomainKeyWithString(url, domain_string,
1589 &cookie_domain);
1590 // Caller is responsible for passing in good arguments.
1591 DCHECK(result);
1592 domain_ = cookie_domain;
[email protected]a986cc32010-02-12 23:55:471593}
1594
[email protected]f325f1e12010-04-30 22:38:551595CookieMonster::CanonicalCookie* CookieMonster::CanonicalCookie::Create(
1596 const GURL& url, const std::string& name, const std::string& value,
[email protected]1655ba342010-07-14 18:17:421597 const std::string& domain, const std::string& path,
1598 const base::Time& creation_time, const base::Time& expiration_time,
1599 bool secure, bool http_only) {
[email protected]f325f1e12010-04-30 22:38:551600 // Expect valid attribute tokens and values, as defined by the ParsedCookie
1601 // logic, otherwise don't create the cookie.
1602 std::string parsed_name = ParsedCookie::ParseTokenString(name);
1603 if (parsed_name != name)
1604 return NULL;
1605 std::string parsed_value = ParsedCookie::ParseValueString(value);
1606 if (parsed_value != value)
1607 return NULL;
[email protected]1655ba342010-07-14 18:17:421608
1609 std::string parsed_domain = ParsedCookie::ParseValueString(domain);
1610 if (parsed_domain != domain)
1611 return NULL;
1612 std::string cookie_domain;
1613 if (!GetCookieDomainKeyWithString(url, parsed_domain, &cookie_domain))
1614 return false;
1615
[email protected]f325f1e12010-04-30 22:38:551616 std::string parsed_path = ParsedCookie::ParseValueString(path);
1617 if (parsed_path != path)
1618 return NULL;
1619
1620 std::string cookie_path = CanonPathWithString(url, parsed_path);
1621 // Expect that the path was either not specified (empty), or is valid.
1622 if (!parsed_path.empty() && cookie_path != parsed_path)
1623 return NULL;
1624 // Canonicalize path again to make sure it escapes characters as needed.
1625 url_parse::Component path_component(0, cookie_path.length());
1626 url_canon::RawCanonOutputT<char> canon_path;
1627 url_parse::Component canon_path_component;
1628 url_canon::CanonicalizePath(cookie_path.data(), path_component,
1629 &canon_path, &canon_path_component);
1630 cookie_path = std::string(canon_path.data() + canon_path_component.begin,
1631 canon_path_component.len);
1632
[email protected]1655ba342010-07-14 18:17:421633 return new CanonicalCookie(parsed_name, parsed_value, cookie_domain,
1634 cookie_path, secure, http_only,
1635 creation_time, creation_time,
[email protected]f325f1e12010-04-30 22:38:551636 !expiration_time.is_null(), expiration_time);
1637}
1638
initial.commit586acc5fe2008-07-26 22:42:521639bool CookieMonster::CanonicalCookie::IsOnPath(
1640 const std::string& url_path) const {
1641
1642 // A zero length would be unsafe for our trailing '/' checks, and
1643 // would also make no sense for our prefix match. The code that
1644 // creates a CanonicalCookie should make sure the path is never zero length,
1645 // but we double check anyway.
1646 if (path_.empty())
1647 return false;
1648
1649 // The Mozilla code broke it into 3 cases, if it's strings lengths
1650 // are less than, equal, or greater. I think this is simpler:
1651
1652 // Make sure the cookie path is a prefix of the url path. If the
1653 // url path is shorter than the cookie path, then the cookie path
1654 // can't be a prefix.
1655 if (url_path.find(path_) != 0)
1656 return false;
1657
1658 // Now we know that url_path is >= cookie_path, and that cookie_path
1659 // is a prefix of url_path. If they are the are the same length then
1660 // they are identical, otherwise we need an additional check:
1661
1662 // In order to avoid in correctly matching a cookie path of /blah
1663 // with a request path of '/blahblah/', we need to make sure that either
1664 // the cookie path ends in a trailing '/', or that we prefix up to a '/'
1665 // in the url path. Since we know that the url path length is greater
1666 // than the cookie path length, it's safe to index one byte past.
1667 if (path_.length() != url_path.length() &&
1668 path_[path_.length() - 1] != '/' &&
1669 url_path[path_.length()] != '/')
1670 return false;
1671
1672 return true;
1673}
1674
1675std::string CookieMonster::CanonicalCookie::DebugString() const {
[email protected]1655ba342010-07-14 18:17:421676 return StringPrintf("name: %s value: %s domain: %s path: %s creation: %"
1677 PRId64,
1678 name_.c_str(), value_.c_str(),
1679 domain_.c_str(), path_.c_str(),
[email protected]34b2b002009-11-20 06:53:281680 static_cast<int64>(creation_date_.ToTimeT()));
initial.commit586acc5fe2008-07-26 22:42:521681}
[email protected]8ac1a752008-07-31 19:40:371682
1683} // namespace
[email protected]65781e92010-07-21 15:29:571684