blob: 414bf15e0cfca7a4e1c35bf9cc131cc5b5604300 [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]47accfd62009-05-14 18:46:21116 SetDefaultCookieableSchemes();
initial.commit586acc5fe2008-07-26 22:42:52117}
118
119CookieMonster::~CookieMonster() {
120 DeleteAll(false);
121}
122
123void CookieMonster::InitStore() {
124 DCHECK(store_) << "Store must exist to initialize";
125
126 // Initialize the store and sync in any saved persistent cookies. We don't
127 // care if it's expired, insert it so it can be garbage collected, removed,
128 // and sync'd.
129 std::vector<KeyedCanonicalCookie> cookies;
[email protected]e32306c52008-11-06 16:59:05130 // Reserve space for the maximum amount of cookies a database should have.
131 // This prevents multiple vector growth / copies as we append cookies.
132 cookies.reserve(kNumCookiesTotal);
initial.commit586acc5fe2008-07-26 22:42:52133 store_->Load(&cookies);
134 for (std::vector<KeyedCanonicalCookie>::const_iterator it = cookies.begin();
135 it != cookies.end(); ++it) {
136 InternalInsertCookie(it->first, it->second, false);
137 }
[email protected]297a4ed02010-02-12 08:12:52138
139 // After importing cookies from the PersistentCookieStore, verify that
140 // none of our constraints are violated.
141 //
142 // In particular, the backing store might have given us duplicate cookies.
143 EnsureCookiesMapIsValid();
144}
145
146void CookieMonster::EnsureCookiesMapIsValid() {
[email protected]bb8905722010-05-21 17:29:04147 lock_.AssertAcquired();
148
[email protected]297a4ed02010-02-12 08:12:52149 int num_duplicates_trimmed = 0;
150
151 // Iterate through all the of the cookies, grouped by host.
152 CookieMap::iterator prev_range_end = cookies_.begin();
153 while (prev_range_end != cookies_.end()) {
154 CookieMap::iterator cur_range_begin = prev_range_end;
155 const std::string key = cur_range_begin->first; // Keep a copy.
156 CookieMap::iterator cur_range_end = cookies_.upper_bound(key);
157 prev_range_end = cur_range_end;
158
159 // Ensure no equivalent cookies for this host.
160 num_duplicates_trimmed +=
161 TrimDuplicateCookiesForHost(key, cur_range_begin, cur_range_end);
162 }
163
164 // Record how many duplicates were found in the database.
165 UMA_HISTOGRAM_COUNTS_10000("Net.NumDuplicateCookiesInDb",
166 num_duplicates_trimmed);
167
168 // TODO(eroman): Should also verify that there are no cookies with the same
169 // creation time, since that is assumed to be unique by the rest of the code.
170}
171
172// Our strategy to find duplicates is:
173// (1) Build a map from (cookiename, cookiepath) to
174// {list of cookies with this signature, sorted by creation time}.
175// (2) For each list with more than 1 entry, keep the cookie having the
176// most recent creation time, and delete the others.
177int CookieMonster::TrimDuplicateCookiesForHost(
178 const std::string& key,
179 CookieMap::iterator begin,
180 CookieMap::iterator end) {
[email protected]bb8905722010-05-21 17:29:04181 lock_.AssertAcquired();
[email protected]297a4ed02010-02-12 08:12:52182
183 // Two cookies are considered equivalent if they have the same name and path.
184 typedef std::pair<std::string, std::string> CookieSignature;
185
186 // List of cookies ordered by creation time.
187 typedef std::set<CookieMap::iterator, OrderByCreationTimeDesc> CookieList;
188
189 // Helper map we populate to find the duplicates.
190 typedef std::map<CookieSignature, CookieList> EquivalenceMap;
191 EquivalenceMap equivalent_cookies;
192
193 // The number of duplicate cookies that have been found.
194 int num_duplicates = 0;
195
196 // Iterate through all of the cookies in our range, and insert them into
197 // the equivalence map.
198 for (CookieMap::iterator it = begin; it != end; ++it) {
199 DCHECK_EQ(key, it->first);
200 CanonicalCookie* cookie = it->second;
201
202 CookieSignature signature(cookie->Name(), cookie->Path());
203 CookieList& list = equivalent_cookies[signature];
204
205 // We found a duplicate!
206 if (!list.empty())
207 num_duplicates++;
208
209 // We save the iterator into |cookies_| rather than the actual cookie
210 // pointer, since we may need to delete it later.
211 list.insert(it);
212 }
213
214 // If there were no duplicates, we are done!
215 if (num_duplicates == 0)
216 return 0;
217
218 // Otherwise, delete all the duplicate cookies, both from our in-memory store
219 // and from the backing store.
220 for (EquivalenceMap::iterator it = equivalent_cookies.begin();
221 it != equivalent_cookies.end();
222 ++it) {
223 const CookieSignature& signature = it->first;
224 CookieList& dupes = it->second;
225
226 if (dupes.size() <= 1)
227 continue; // This cookiename/path has no duplicates.
228
229 // Since |dups| is sorted by creation time (descending), the first cookie
230 // is the most recent one, so we will keep it. The rest are duplicates.
231 dupes.erase(dupes.begin());
232
233 LOG(ERROR) << StringPrintf("Found %d duplicate cookies for host='%s', "
234 "with {name='%s', path='%s'}",
235 static_cast<int>(dupes.size()),
236 key.c_str(),
237 signature.first.c_str(),
238 signature.second.c_str());
239
240 // Remove all the cookies identified by |dupes|. It is valid to delete our
241 // list of iterators one at a time, since |cookies_| is a multimap (they
242 // don't invalidate existing iterators following deletion).
243 for (CookieList::iterator dupes_it = dupes.begin();
244 dupes_it != dupes.end();
245 ++dupes_it) {
[email protected]c4058fb2010-06-22 17:25:26246 InternalDeleteCookie(*dupes_it, true /*sync_to_store*/,
[email protected]2f3f3592010-07-07 20:11:51247 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE);
[email protected]297a4ed02010-02-12 08:12:52248 }
249 }
250
251 return num_duplicates;
initial.commit586acc5fe2008-07-26 22:42:52252}
253
[email protected]47accfd62009-05-14 18:46:21254void CookieMonster::SetDefaultCookieableSchemes() {
255 // Note: file must be the last scheme.
256 static const char* kDefaultCookieableSchemes[] = { "http", "https", "file" };
257 int num_schemes = enable_file_scheme_ ? 3 : 2;
258 SetCookieableSchemes(kDefaultCookieableSchemes, num_schemes);
259}
260
initial.commit586acc5fe2008-07-26 22:42:52261// The system resolution is not high enough, so we can have multiple
262// set cookies that result in the same system time. When this happens, we
263// increment by one Time unit. Let's hope computers don't get too fast.
264Time CookieMonster::CurrentTime() {
265 return std::max(Time::Now(),
266 Time::FromInternalValue(last_time_seen_.ToInternalValue() + 1));
267}
268
269// Parse a cookie expiration time. We try to be lenient, but we need to
270// assume some order to distinguish the fields. The basic rules:
271// - The month name must be present and prefix the first 3 letters of the
272// full month name (jan for January, jun for June).
273// - If the year is <= 2 digits, it must occur after the day of month.
274// - The time must be of the format hh:mm:ss.
275// An average cookie expiration will look something like this:
276// Sat, 15-Apr-17 21:01:22 GMT
277Time CookieMonster::ParseCookieTime(const std::string& time_string) {
278 static const char* kMonths[] = { "jan", "feb", "mar", "apr", "may", "jun",
279 "jul", "aug", "sep", "oct", "nov", "dec" };
280 static const int kMonthsLen = arraysize(kMonths);
281 // We want to be pretty liberal, and support most non-ascii and non-digit
282 // characters as a delimiter. We can't treat : as a delimiter, because it
283 // is the delimiter for hh:mm:ss, and we want to keep this field together.
284 // We make sure to include - and +, since they could prefix numbers.
285 // If the cookie attribute came in in quotes (ex expires="XXX"), the quotes
286 // will be preserved, and we will get them here. So we make sure to include
287 // quote characters, and also \ for anything that was internally escaped.
288 static const char* kDelimiters = "\t !\"#$%&'()*+,-./;<=>?@[\\]^_`{|}~";
289
290 Time::Exploded exploded = {0};
291
292 StringTokenizer tokenizer(time_string, kDelimiters);
293
294 bool found_day_of_month = false;
295 bool found_month = false;
296 bool found_time = false;
297 bool found_year = false;
298
299 while (tokenizer.GetNext()) {
300 const std::string token = tokenizer.token();
301 DCHECK(!token.empty());
302 bool numerical = IsAsciiDigit(token[0]);
303
304 // String field
305 if (!numerical) {
306 if (!found_month) {
307 for (int i = 0; i < kMonthsLen; ++i) {
308 // Match prefix, so we could match January, etc
[email protected]7e3dcd92008-12-30 13:13:34309 if (base::strncasecmp(token.c_str(), kMonths[i], 3) == 0) {
initial.commit586acc5fe2008-07-26 22:42:52310 exploded.month = i + 1;
311 found_month = true;
312 break;
313 }
314 }
315 } else {
316 // If we've gotten here, it means we've already found and parsed our
317 // month, and we have another string, which we would expect to be the
318 // the time zone name. According to the RFC and my experiments with
319 // how sites format their expirations, we don't have much of a reason
320 // to support timezones. We don't want to ever barf on user input,
321 // but this DCHECK should pass for well-formed data.
322 // DCHECK(token == "GMT");
323 }
324 // Numeric field w/ a colon
325 } else if (token.find(':') != std::string::npos) {
326 if (!found_time &&
[email protected]d862fd92008-08-21 18:15:35327#ifdef COMPILER_MSVC
328 sscanf_s(
329#else
330 sscanf(
331#endif
332 token.c_str(), "%2u:%2u:%2u", &exploded.hour,
333 &exploded.minute, &exploded.second) == 3) {
initial.commit586acc5fe2008-07-26 22:42:52334 found_time = true;
335 } else {
336 // We should only ever encounter one time-like thing. If we're here,
337 // it means we've found a second, which shouldn't happen. We keep
338 // the first. This check should be ok for well-formed input:
339 // NOTREACHED();
340 }
341 // Numeric field
342 } else {
343 // Overflow with atoi() is unspecified, so we enforce a max length.
344 if (!found_day_of_month && token.length() <= 2) {
345 exploded.day_of_month = atoi(token.c_str());
346 found_day_of_month = true;
347 } else if (!found_year && token.length() <= 5) {
348 exploded.year = atoi(token.c_str());
349 found_year = true;
350 } else {
351 // If we're here, it means we've either found an extra numeric field,
352 // or a numeric field which was too long. For well-formed input, the
353 // following check would be reasonable:
354 // NOTREACHED();
355 }
356 }
357 }
358
359 if (!found_day_of_month || !found_month || !found_time || !found_year) {
360 // We didn't find all of the fields we need. For well-formed input, the
361 // following check would be reasonable:
362 // NOTREACHED() << "Cookie parse expiration failed: " << time_string;
363 return Time();
364 }
365
366 // Normalize the year to expand abbreviated years to the full year.
367 if (exploded.year >= 69 && exploded.year <= 99)
368 exploded.year += 1900;
369 if (exploded.year >= 0 && exploded.year <= 68)
370 exploded.year += 2000;
371
372 // If our values are within their correct ranges, we got our time.
373 if (exploded.day_of_month >= 1 && exploded.day_of_month <= 31 &&
374 exploded.month >= 1 && exploded.month <= 12 &&
375 exploded.year >= 1601 && exploded.year <= 30827 &&
376 exploded.hour <= 23 && exploded.minute <= 59 && exploded.second <= 59) {
377 return Time::FromUTCExploded(exploded);
378 }
379
380 // One of our values was out of expected range. For well-formed input,
381 // the following check would be reasonable:
382 // NOTREACHED() << "Cookie exploded expiration failed: " << time_string;
383
384 return Time();
385}
386
[email protected]f325f1e12010-04-30 22:38:55387bool CookieMonster::DomainIsHostOnly(const std::string& domain_string) {
388 return (domain_string.empty() || domain_string[0] != '.');
389}
390
[email protected]69bb5872010-01-12 20:33:52391// Returns the effective TLD+1 for a given host. This only makes sense for http
392// and https schemes. For other schemes, the host will be returned unchanged
393// (minus any leading .).
394static std::string GetEffectiveDomain(const std::string& scheme,
395 const std::string& host) {
396 if (scheme == "http" || scheme == "https")
397 return RegistryControlledDomainService::GetDomainAndRegistry(host);
398
[email protected]f325f1e12010-04-30 22:38:55399 if (!CookieMonster::DomainIsHostOnly(host))
[email protected]69bb5872010-01-12 20:33:52400 return host.substr(1);
401 return host;
402}
403
[email protected]f325f1e12010-04-30 22:38:55404// Determine the cookie domain key to use for setting a cookie with the
405// specified domain attribute string.
initial.commit586acc5fe2008-07-26 22:42:52406// On success returns true, and sets cookie_domain_key to either a
407// -host cookie key (ex: "google.com")
408// -domain cookie key (ex: ".google.com")
[email protected]f325f1e12010-04-30 22:38:55409static bool GetCookieDomainKeyWithString(const GURL& url,
410 const std::string& domain_string,
411 std::string* cookie_domain_key) {
initial.commit586acc5fe2008-07-26 22:42:52412 const std::string url_host(url.host());
[email protected]c3a756b62009-01-23 10:50:51413
[email protected]f325f1e12010-04-30 22:38:55414 // If no domain was specified in the domain string, default to a host cookie.
[email protected]c3a756b62009-01-23 10:50:51415 // We match IE/Firefox in allowing a domain=IPADDR if it matches the url
416 // ip address hostname exactly. It should be treated as a host cookie.
[email protected]f325f1e12010-04-30 22:38:55417 if (domain_string.empty() ||
418 (url.HostIsIPAddress() && url_host == domain_string)) {
initial.commit586acc5fe2008-07-26 22:42:52419 *cookie_domain_key = url_host;
[email protected]f325f1e12010-04-30 22:38:55420 DCHECK(CookieMonster::DomainIsHostOnly(*cookie_domain_key));
initial.commit586acc5fe2008-07-26 22:42:52421 return true;
422 }
423
424 // Get the normalized domain specified in cookie line.
425 // Note: The RFC says we can reject a cookie if the domain
426 // attribute does not start with a dot. IE/FF/Safari however, allow a cookie
427 // of the form domain=my.domain.com, treating it the same as
428 // domain=.my.domain.com -- for compatibility we do the same here. Firefox
429 // also treats domain=.....my.domain.com like domain=.my.domain.com, but
430 // neither IE nor Safari do this, and we don't either.
[email protected]01dbd932009-06-23 22:52:42431 url_canon::CanonHostInfo ignored;
[email protected]f325f1e12010-04-30 22:38:55432 std::string cookie_domain(net::CanonicalizeHost(domain_string, &ignored));
initial.commit586acc5fe2008-07-26 22:42:52433 if (cookie_domain.empty())
434 return false;
435 if (cookie_domain[0] != '.')
436 cookie_domain = "." + cookie_domain;
437
438 // Ensure |url| and |cookie_domain| have the same domain+registry.
[email protected]69bb5872010-01-12 20:33:52439 const std::string url_scheme(url.scheme());
initial.commit586acc5fe2008-07-26 22:42:52440 const std::string url_domain_and_registry(
[email protected]69bb5872010-01-12 20:33:52441 GetEffectiveDomain(url_scheme, url_host));
initial.commit586acc5fe2008-07-26 22:42:52442 if (url_domain_and_registry.empty())
443 return false; // IP addresses/intranet hosts can't set domain cookies.
444 const std::string cookie_domain_and_registry(
[email protected]69bb5872010-01-12 20:33:52445 GetEffectiveDomain(url_scheme, cookie_domain));
initial.commit586acc5fe2008-07-26 22:42:52446 if (url_domain_and_registry != cookie_domain_and_registry)
447 return false; // Can't set a cookie on a different domain + registry.
448
449 // Ensure |url_host| is |cookie_domain| or one of its subdomains. Given that
450 // we know the domain+registry are the same from the above checks, this is
451 // basically a simple string suffix check.
452 if ((url_host.length() < cookie_domain.length()) ?
453 (cookie_domain != ("." + url_host)) :
454 url_host.compare(url_host.length() - cookie_domain.length(),
455 cookie_domain.length(), cookie_domain))
456 return false;
457
initial.commit586acc5fe2008-07-26 22:42:52458 *cookie_domain_key = cookie_domain;
459 return true;
460}
461
[email protected]f325f1e12010-04-30 22:38:55462// Determine the cookie domain key to use for setting the specified cookie.
463static bool GetCookieDomainKey(const GURL& url,
464 const CookieMonster::ParsedCookie& pc,
465 std::string* cookie_domain_key) {
466 std::string domain_string;
467 if (pc.HasDomain())
468 domain_string = pc.Domain();
469 return GetCookieDomainKeyWithString(url, domain_string, cookie_domain_key);
470}
471
472static std::string CanonPathWithString(const GURL& url,
473 const std::string& path_string) {
initial.commit586acc5fe2008-07-26 22:42:52474 // The RFC says the path should be a prefix of the current URL path.
475 // However, Mozilla allows you to set any path for compatibility with
476 // broken websites. We unfortunately will mimic this behavior. We try
477 // to be generous and accept cookies with an invalid path attribute, and
478 // default the path to something reasonable.
479
480 // The path was supplied in the cookie, we'll take it.
[email protected]f325f1e12010-04-30 22:38:55481 if (!path_string.empty() && path_string[0] == '/')
482 return path_string;
initial.commit586acc5fe2008-07-26 22:42:52483
484 // The path was not supplied in the cookie or invalid, we will default
485 // to the current URL path.
486 // """Defaults to the path of the request URL that generated the
487 // Set-Cookie response, up to, but not including, the
488 // right-most /."""
489 // How would this work for a cookie on /? We will include it then.
490 const std::string& url_path = url.path();
491
[email protected]c890ed192008-10-30 23:45:53492 size_t idx = url_path.find_last_of('/');
initial.commit586acc5fe2008-07-26 22:42:52493
494 // The cookie path was invalid or a single '/'.
495 if (idx == 0 || idx == std::string::npos)
496 return std::string("/");
497
498 // Return up to the rightmost '/'.
499 return url_path.substr(0, idx);
500}
501
[email protected]f325f1e12010-04-30 22:38:55502static std::string CanonPath(const GURL& url,
503 const CookieMonster::ParsedCookie& pc) {
504 std::string path_string;
505 if (pc.HasPath())
506 path_string = pc.Path();
507 return CanonPathWithString(url, path_string);
508}
509
initial.commit586acc5fe2008-07-26 22:42:52510static Time CanonExpiration(const CookieMonster::ParsedCookie& pc,
[email protected]4f79b3f2010-02-05 04:27:47511 const Time& current,
512 const CookieOptions& options) {
513 if (options.force_session())
514 return Time();
515
initial.commit586acc5fe2008-07-26 22:42:52516 // First, try the Max-Age attribute.
517 uint64 max_age = 0;
518 if (pc.HasMaxAge() &&
[email protected]dce5df52009-06-29 17:58:25519#ifdef COMPILER_MSVC
520 sscanf_s(
[email protected]d862fd92008-08-21 18:15:35521#else
[email protected]dce5df52009-06-29 17:58:25522 sscanf(
[email protected]d862fd92008-08-21 18:15:35523#endif
[email protected]dce5df52009-06-29 17:58:25524 pc.MaxAge().c_str(), " %" PRIu64, &max_age) == 1) {
initial.commit586acc5fe2008-07-26 22:42:52525 return current + TimeDelta::FromSeconds(max_age);
526 }
527
528 // Try the Expires attribute.
529 if (pc.HasExpires())
530 return CookieMonster::ParseCookieTime(pc.Expires());
531
532 // Invalid or no expiration, persistent cookie.
533 return Time();
534}
535
[email protected]47accfd62009-05-14 18:46:21536bool CookieMonster::HasCookieableScheme(const GURL& url) {
[email protected]bb8905722010-05-21 17:29:04537 lock_.AssertAcquired();
538
initial.commit586acc5fe2008-07-26 22:42:52539 // Make sure the request is on a cookie-able url scheme.
[email protected]47accfd62009-05-14 18:46:21540 for (size_t i = 0; i < cookieable_schemes_.size(); ++i) {
initial.commit586acc5fe2008-07-26 22:42:52541 // We matched a scheme.
[email protected]47accfd62009-05-14 18:46:21542 if (url.SchemeIs(cookieable_schemes_[i].c_str())) {
initial.commit586acc5fe2008-07-26 22:42:52543 // We've matched a supported scheme.
544 return true;
545 }
546 }
547
548 // The scheme didn't match any in our whitelist.
549 COOKIE_DLOG(WARNING) << "Unsupported cookie scheme: " << url.scheme();
550 return false;
551}
552
[email protected]47accfd62009-05-14 18:46:21553void CookieMonster::SetCookieableSchemes(
554 const char* schemes[], size_t num_schemes) {
[email protected]bb8905722010-05-21 17:29:04555 AutoLock autolock(lock_);
556
[email protected]cf12bd12010-06-17 14:41:30557 // Cookieable Schemes must be set before first use of function.
558 DCHECK(!initialized_);
559
[email protected]47accfd62009-05-14 18:46:21560 cookieable_schemes_.clear();
561 cookieable_schemes_.insert(cookieable_schemes_.end(),
562 schemes, schemes + num_schemes);
563}
564
[email protected]34602282010-02-03 22:14:15565bool CookieMonster::SetCookieWithCreationTimeAndOptions(
566 const GURL& url,
567 const std::string& cookie_line,
568 const Time& creation_time_or_null,
569 const CookieOptions& options) {
[email protected]bb8905722010-05-21 17:29:04570 AutoLock autolock(lock_);
571
initial.commit586acc5fe2008-07-26 22:42:52572 if (!HasCookieableScheme(url)) {
initial.commit586acc5fe2008-07-26 22:42:52573 return false;
574 }
575
initial.commit586acc5fe2008-07-26 22:42:52576 InitIfNecessary();
577
578 COOKIE_DLOG(INFO) << "SetCookie() line: " << cookie_line;
579
[email protected]34602282010-02-03 22:14:15580 Time creation_time = creation_time_or_null;
581 if (creation_time.is_null()) {
582 creation_time = CurrentTime();
583 last_time_seen_ = creation_time;
584 }
585
initial.commit586acc5fe2008-07-26 22:42:52586 // Parse the cookie.
587 ParsedCookie pc(cookie_line);
588
589 if (!pc.IsValid()) {
590 COOKIE_DLOG(WARNING) << "Couldn't parse cookie";
591 return false;
592 }
593
[email protected]3a96c742008-11-19 19:46:27594 if (options.exclude_httponly() && pc.IsHttpOnly()) {
595 COOKIE_DLOG(INFO) << "SetCookie() not setting httponly cookie";
596 return false;
597 }
598
initial.commit586acc5fe2008-07-26 22:42:52599 std::string cookie_domain;
600 if (!GetCookieDomainKey(url, pc, &cookie_domain)) {
601 return false;
602 }
603
604 std::string cookie_path = CanonPath(url, pc);
605
606 scoped_ptr<CanonicalCookie> cc;
[email protected]4f79b3f2010-02-05 04:27:47607 Time cookie_expires = CanonExpiration(pc, creation_time, options);
initial.commit586acc5fe2008-07-26 22:42:52608
609 cc.reset(new CanonicalCookie(pc.Name(), pc.Value(), cookie_path,
610 pc.IsSecure(), pc.IsHttpOnly(),
[email protected]77e0a462008-11-01 00:43:35611 creation_time, creation_time,
612 !cookie_expires.is_null(), cookie_expires));
initial.commit586acc5fe2008-07-26 22:42:52613
614 if (!cc.get()) {
615 COOKIE_DLOG(WARNING) << "Failed to allocate CanonicalCookie";
616 return false;
617 }
[email protected]f325f1e12010-04-30 22:38:55618 return SetCanonicalCookie(&cc, cookie_domain, creation_time, options);
619}
initial.commit586acc5fe2008-07-26 22:42:52620
[email protected]f325f1e12010-04-30 22:38:55621bool CookieMonster::SetCookieWithDetails(
622 const GURL& url, const std::string& name, const std::string& value,
623 const std::string& domain, const std::string& path,
624 const base::Time& expiration_time, bool secure, bool http_only) {
[email protected]f325f1e12010-04-30 22:38:55625
626 // Expect a valid domain attribute with no illegal characters.
627 std::string parsed_domain = ParsedCookie::ParseValueString(domain);
628 if (parsed_domain != domain)
629 return false;
630 std::string cookie_domain;
631 if (!GetCookieDomainKeyWithString(url, parsed_domain, &cookie_domain))
632 return false;
633
634 AutoLock autolock(lock_);
[email protected]bb8905722010-05-21 17:29:04635
636 if (!HasCookieableScheme(url))
637 return false;
638
[email protected]f325f1e12010-04-30 22:38:55639 InitIfNecessary();
640
641 Time creation_time = CurrentTime();
642 last_time_seen_ = creation_time;
643
644 scoped_ptr<CanonicalCookie> cc;
645 cc.reset(CanonicalCookie::Create(
646 url, name, value, path, creation_time, expiration_time,
647 secure, http_only));
648
649 if (!cc.get())
650 return false;
651
652 CookieOptions options;
653 options.set_include_httponly();
654 return SetCanonicalCookie(&cc, cookie_domain, creation_time, options);
655}
656
657bool CookieMonster::SetCanonicalCookie(scoped_ptr<CanonicalCookie>* cc,
658 const std::string& cookie_domain,
659 const Time& creation_time,
660 const CookieOptions& options) {
661 if (DeleteAnyEquivalentCookie(cookie_domain, **cc,
[email protected]3a96c742008-11-19 19:46:27662 options.exclude_httponly())) {
663 COOKIE_DLOG(INFO) << "SetCookie() not clobbering httponly cookie";
664 return false;
665 }
initial.commit586acc5fe2008-07-26 22:42:52666
[email protected]f325f1e12010-04-30 22:38:55667 COOKIE_DLOG(INFO) << "SetCookie() cc: " << (*cc)->DebugString();
initial.commit586acc5fe2008-07-26 22:42:52668
669 // Realize that we might be setting an expired cookie, and the only point
670 // was to delete the cookie which we've already done.
[email protected]c4058fb2010-06-22 17:25:26671 if (!(*cc)->IsExpired(creation_time)) {
672 UMA_HISTOGRAM_CUSTOM_COUNTS(
673 "net.CookieExpirationDurationMinutes",
674 ((*cc)->ExpiryDate() - creation_time).InMinutes(),
675 1, kMinutesInTenYears, 50);
[email protected]f325f1e12010-04-30 22:38:55676 InternalInsertCookie(cookie_domain, cc->release(), true);
[email protected]c4058fb2010-06-22 17:25:26677 }
initial.commit586acc5fe2008-07-26 22:42:52678
679 // We assume that hopefully setting a cookie will be less common than
680 // querying a cookie. Since setting a cookie can put us over our limits,
681 // make sure that we garbage collect... We can also make the assumption that
682 // if a cookie was set, in the common case it will be used soon after,
683 // and we will purge the expired cookies in GetCookies().
684 GarbageCollect(creation_time, cookie_domain);
685
686 return true;
687}
688
initial.commit586acc5fe2008-07-26 22:42:52689void CookieMonster::InternalInsertCookie(const std::string& key,
690 CanonicalCookie* cc,
691 bool sync_to_store) {
[email protected]bb8905722010-05-21 17:29:04692 lock_.AssertAcquired();
693
initial.commit586acc5fe2008-07-26 22:42:52694 if (cc->IsPersistent() && store_ && sync_to_store)
695 store_->AddCookie(key, *cc);
696 cookies_.insert(CookieMap::value_type(key, cc));
[email protected]0f7066e2010-03-25 08:31:47697 if (delegate_.get())
698 delegate_->OnCookieChanged(key, *cc, false);
initial.commit586acc5fe2008-07-26 22:42:52699}
700
[email protected]77e0a462008-11-01 00:43:35701void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie* cc) {
[email protected]bb8905722010-05-21 17:29:04702 lock_.AssertAcquired();
703
[email protected]77e0a462008-11-01 00:43:35704 // Based off the Mozilla code. When a cookie has been accessed recently,
705 // don't bother updating its access time again. This reduces the number of
706 // updates we do during pageload, which in turn reduces the chance our storage
707 // backend will hit its batch thresholds and be forced to update.
708 const Time current = Time::Now();
709 if ((current - cc->LastAccessDate()) < last_access_threshold_)
710 return;
711
[email protected]c4058fb2010-06-22 17:25:26712 UMA_HISTOGRAM_CUSTOM_COUNTS(
713 "net.CookieBetweenAccessIntervalMinutes",
714 (current - cc->LastAccessDate()).InMinutes(),
715 1, kMinutesInTenYears, 50);
716
[email protected]77e0a462008-11-01 00:43:35717 cc->SetLastAccessDate(current);
718 if (cc->IsPersistent() && store_)
719 store_->UpdateCookieAccessTime(*cc);
720}
721
initial.commit586acc5fe2008-07-26 22:42:52722void CookieMonster::InternalDeleteCookie(CookieMap::iterator it,
[email protected]c4058fb2010-06-22 17:25:26723 bool sync_to_store,
724 DeletionCause deletion_cause) {
[email protected]bb8905722010-05-21 17:29:04725 lock_.AssertAcquired();
726
[email protected]c4058fb2010-06-22 17:25:26727 UMA_HISTOGRAM_ENUMERATION("net.CookieDeletionCause", deletion_cause,
[email protected]2f3f3592010-07-07 20:11:51728 DELETE_COOKIE_LAST_ENTRY);
[email protected]c4058fb2010-06-22 17:25:26729
initial.commit586acc5fe2008-07-26 22:42:52730 CanonicalCookie* cc = it->second;
731 COOKIE_DLOG(INFO) << "InternalDeleteCookie() cc: " << cc->DebugString();
732 if (cc->IsPersistent() && store_ && sync_to_store)
733 store_->DeleteCookie(*cc);
[email protected]0f7066e2010-03-25 08:31:47734 if (delegate_.get())
735 delegate_->OnCookieChanged(it->first, *cc, true);
initial.commit586acc5fe2008-07-26 22:42:52736 cookies_.erase(it);
737 delete cc;
738}
739
[email protected]3a96c742008-11-19 19:46:27740bool CookieMonster::DeleteAnyEquivalentCookie(const std::string& key,
741 const CanonicalCookie& ecc,
742 bool skip_httponly) {
[email protected]bb8905722010-05-21 17:29:04743 lock_.AssertAcquired();
744
[email protected]c890ed192008-10-30 23:45:53745 bool found_equivalent_cookie = false;
[email protected]3a96c742008-11-19 19:46:27746 bool skipped_httponly = false;
initial.commit586acc5fe2008-07-26 22:42:52747 for (CookieMapItPair its = cookies_.equal_range(key);
748 its.first != its.second; ) {
749 CookieMap::iterator curit = its.first;
750 CanonicalCookie* cc = curit->second;
751 ++its.first;
752
initial.commit586acc5fe2008-07-26 22:42:52753 if (ecc.IsEquivalent(*cc)) {
[email protected]c890ed192008-10-30 23:45:53754 // We should never have more than one equivalent cookie, since they should
755 // overwrite each other.
[email protected]297a4ed02010-02-12 08:12:52756 CHECK(!found_equivalent_cookie) <<
[email protected]c890ed192008-10-30 23:45:53757 "Duplicate equivalent cookies found, cookie store is corrupted.";
[email protected]3a96c742008-11-19 19:46:27758 if (skip_httponly && cc->IsHttpOnly()) {
759 skipped_httponly = true;
760 } else {
[email protected]2f3f3592010-07-07 20:11:51761 InternalDeleteCookie(curit, true, DELETE_COOKIE_OVERWRITE);
[email protected]3a96c742008-11-19 19:46:27762 }
[email protected]c890ed192008-10-30 23:45:53763 found_equivalent_cookie = true;
initial.commit586acc5fe2008-07-26 22:42:52764 }
765 }
[email protected]3a96c742008-11-19 19:46:27766 return skipped_httponly;
initial.commit586acc5fe2008-07-26 22:42:52767}
768
initial.commit586acc5fe2008-07-26 22:42:52769int CookieMonster::GarbageCollect(const Time& current,
770 const std::string& key) {
[email protected]bb8905722010-05-21 17:29:04771 lock_.AssertAcquired();
772
initial.commit586acc5fe2008-07-26 22:42:52773 int num_deleted = 0;
774
775 // Collect garbage for this key.
776 if (cookies_.count(key) > kNumCookiesPerHost) {
777 COOKIE_DLOG(INFO) << "GarbageCollect() key: " << key;
778 num_deleted += GarbageCollectRange(current, cookies_.equal_range(key),
[email protected]c890ed192008-10-30 23:45:53779 kNumCookiesPerHost, kNumCookiesPerHostPurge);
initial.commit586acc5fe2008-07-26 22:42:52780 }
781
782 // Collect garbage for everything.
783 if (cookies_.size() > kNumCookiesTotal) {
784 COOKIE_DLOG(INFO) << "GarbageCollect() everything";
785 num_deleted += GarbageCollectRange(current,
[email protected]c890ed192008-10-30 23:45:53786 CookieMapItPair(cookies_.begin(), cookies_.end()), kNumCookiesTotal,
787 kNumCookiesTotalPurge);
788 }
789
790 return num_deleted;
791}
792
[email protected]77e0a462008-11-01 00:43:35793static bool LRUCookieSorter(const CookieMonster::CookieMap::iterator& it1,
794 const CookieMonster::CookieMap::iterator& it2) {
795 // Cookies accessed less recently should be deleted first.
796 if (it1->second->LastAccessDate() != it2->second->LastAccessDate())
797 return it1->second->LastAccessDate() < it2->second->LastAccessDate();
798
799 // In rare cases we might have two cookies with identical last access times.
800 // To preserve the stability of the sort, in these cases prefer to delete
801 // older cookies over newer ones. CreationDate() is guaranteed to be unique.
[email protected]c890ed192008-10-30 23:45:53802 return it1->second->CreationDate() < it2->second->CreationDate();
803}
804
805int CookieMonster::GarbageCollectRange(const Time& current,
806 const CookieMapItPair& itpair,
807 size_t num_max,
808 size_t num_purge) {
[email protected]bb8905722010-05-21 17:29:04809 lock_.AssertAcquired();
810
[email protected]c890ed192008-10-30 23:45:53811 // First, delete anything that's expired.
812 std::vector<CookieMap::iterator> cookie_its;
813 int num_deleted = GarbageCollectExpired(current, itpair, &cookie_its);
814
[email protected]77e0a462008-11-01 00:43:35815 // If the range still has too many cookies, delete the least recently used.
[email protected]c890ed192008-10-30 23:45:53816 if (cookie_its.size() > num_max) {
817 COOKIE_DLOG(INFO) << "GarbageCollectRange() Deep Garbage Collect.";
818 // Purge down to (|num_max| - |num_purge|) total cookies.
819 DCHECK(num_purge <= num_max);
820 num_purge += cookie_its.size() - num_max;
821
822 std::partial_sort(cookie_its.begin(), cookie_its.begin() + num_purge,
[email protected]77e0a462008-11-01 00:43:35823 cookie_its.end(), LRUCookieSorter);
[email protected]c4058fb2010-06-22 17:25:26824 for (size_t i = 0; i < num_purge; ++i) {
825 UMA_HISTOGRAM_CUSTOM_COUNTS(
826 "net.CookieEvictedLastAccessMinutes",
827 (current - cookie_its[i]->second->LastAccessDate()).InMinutes(),
828 1, kMinutesInTenYears, 50);
[email protected]2f3f3592010-07-07 20:11:51829 InternalDeleteCookie(cookie_its[i], true, DELETE_COOKIE_EVICTED);
[email protected]c4058fb2010-06-22 17:25:26830 }
[email protected]c890ed192008-10-30 23:45:53831
832 num_deleted += num_purge;
833 }
834
835 return num_deleted;
836}
837
838int CookieMonster::GarbageCollectExpired(
839 const Time& current,
840 const CookieMapItPair& itpair,
841 std::vector<CookieMap::iterator>* cookie_its) {
[email protected]bb8905722010-05-21 17:29:04842 lock_.AssertAcquired();
843
[email protected]c890ed192008-10-30 23:45:53844 int num_deleted = 0;
845 for (CookieMap::iterator it = itpair.first, end = itpair.second; it != end;) {
846 CookieMap::iterator curit = it;
847 ++it;
848
849 if (curit->second->IsExpired(current)) {
[email protected]2f3f3592010-07-07 20:11:51850 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
[email protected]c890ed192008-10-30 23:45:53851 ++num_deleted;
852 } else if (cookie_its) {
853 cookie_its->push_back(curit);
854 }
initial.commit586acc5fe2008-07-26 22:42:52855 }
856
857 return num_deleted;
858}
859
860int CookieMonster::DeleteAll(bool sync_to_store) {
861 AutoLock autolock(lock_);
862 InitIfNecessary();
863
864 int num_deleted = 0;
865 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
866 CookieMap::iterator curit = it;
867 ++it;
[email protected]c4058fb2010-06-22 17:25:26868 InternalDeleteCookie(curit, sync_to_store,
[email protected]2f3f3592010-07-07 20:11:51869 sync_to_store ? DELETE_COOKIE_EXPLICIT :
870 DELETE_COOKIE_DONT_RECORD /* Destruction. */);
initial.commit586acc5fe2008-07-26 22:42:52871 ++num_deleted;
872 }
873
874 return num_deleted;
875}
876
877int CookieMonster::DeleteAllCreatedBetween(const Time& delete_begin,
878 const Time& delete_end,
879 bool sync_to_store) {
880 AutoLock autolock(lock_);
881 InitIfNecessary();
882
883 int num_deleted = 0;
884 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
885 CookieMap::iterator curit = it;
886 CanonicalCookie* cc = curit->second;
887 ++it;
888
889 if (cc->CreationDate() >= delete_begin &&
890 (delete_end.is_null() || cc->CreationDate() < delete_end)) {
[email protected]2f3f3592010-07-07 20:11:51891 InternalDeleteCookie(curit, sync_to_store, DELETE_COOKIE_EXPLICIT);
initial.commit586acc5fe2008-07-26 22:42:52892 ++num_deleted;
893 }
894 }
895
896 return num_deleted;
897}
898
899int CookieMonster::DeleteAllCreatedAfter(const Time& delete_begin,
900 bool sync_to_store) {
901 return DeleteAllCreatedBetween(delete_begin, Time(), sync_to_store);
902}
903
[email protected]c8c7d8a2010-07-07 19:58:36904int CookieMonster::DeleteAllForHost(const GURL& url) {
[email protected]c10da4b02010-03-25 14:38:32905 AutoLock autolock(lock_);
906 InitIfNecessary();
[email protected]bb8905722010-05-21 17:29:04907
[email protected]c8c7d8a2010-07-07 19:58:36908 if (!HasCookieableScheme(url))
909 return 0;
910
911 // We store host cookies in the store by their canonical host name;
912 // domain cookies are stored with a leading ".". So this is a pretty
913 // simple lookup and per-cookie delete.
[email protected]c10da4b02010-03-25 14:38:32914 int num_deleted = 0;
[email protected]c8c7d8a2010-07-07 19:58:36915 for (CookieMapItPair its = cookies_.equal_range(url.host());
916 its.first != its.second;) {
917 CookieMap::iterator curit = its.first;
918 ++its.first;
919 num_deleted++;
920
[email protected]2f3f3592010-07-07 20:11:51921 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT);
[email protected]c10da4b02010-03-25 14:38:32922 }
923 return num_deleted;
924}
925
initial.commit586acc5fe2008-07-26 22:42:52926bool CookieMonster::DeleteCookie(const std::string& domain,
927 const CanonicalCookie& cookie,
928 bool sync_to_store) {
929 AutoLock autolock(lock_);
930 InitIfNecessary();
931
932 for (CookieMapItPair its = cookies_.equal_range(domain);
933 its.first != its.second; ++its.first) {
934 // The creation date acts as our unique index...
935 if (its.first->second->CreationDate() == cookie.CreationDate()) {
[email protected]2f3f3592010-07-07 20:11:51936 InternalDeleteCookie(its.first, sync_to_store, DELETE_COOKIE_EXPLICIT);
initial.commit586acc5fe2008-07-26 22:42:52937 return true;
938 }
939 }
940 return false;
941}
942
943// Mozilla sorts on the path length (longest first), and then it
944// sorts by creation time (oldest first).
945// The RFC says the sort order for the domain attribute is undefined.
946static bool CookieSorter(CookieMonster::CanonicalCookie* cc1,
947 CookieMonster::CanonicalCookie* cc2) {
948 if (cc1->Path().length() == cc2->Path().length())
949 return cc1->CreationDate() < cc2->CreationDate();
950 return cc1->Path().length() > cc2->Path().length();
951}
952
[email protected]34602282010-02-03 22:14:15953bool CookieMonster::SetCookieWithOptions(const GURL& url,
954 const std::string& cookie_line,
955 const CookieOptions& options) {
956 return SetCookieWithCreationTimeAndOptions(url, cookie_line, Time(), options);
957}
958
initial.commit586acc5fe2008-07-26 22:42:52959// Currently our cookie datastructure is based on Mozilla's approach. We have a
960// hash keyed on the cookie's domain, and for any query we walk down the domain
961// components and probe for cookies until we reach the TLD, where we stop.
962// For example, a.b.blah.com, we would probe
963// - a.b.blah.com
964// - .a.b.blah.com (TODO should we check this first or second?)
965// - .b.blah.com
966// - .blah.com
967// There are some alternative datastructures we could try, like a
968// search/prefix trie, where we reverse the hostname and query for all
969// keys that are a prefix of our hostname. I think the hash probing
970// should be fast and simple enough for now.
971std::string CookieMonster::GetCookiesWithOptions(const GURL& url,
[email protected]3a96c742008-11-19 19:46:27972 const CookieOptions& options) {
[email protected]bb8905722010-05-21 17:29:04973 AutoLock autolock(lock_);
974 InitIfNecessary();
975
initial.commit586acc5fe2008-07-26 22:42:52976 if (!HasCookieableScheme(url)) {
initial.commit586acc5fe2008-07-26 22:42:52977 return std::string();
978 }
979
980 // Get the cookies for this host and its domain(s).
981 std::vector<CanonicalCookie*> cookies;
982 FindCookiesForHostAndDomain(url, options, &cookies);
983 std::sort(cookies.begin(), cookies.end(), CookieSorter);
984
985 std::string cookie_line;
986 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
987 it != cookies.end(); ++it) {
988 if (it != cookies.begin())
989 cookie_line += "; ";
990 // In Mozilla if you set a cookie like AAAA, it will have an empty token
991 // and a value of AAAA. When it sends the cookie back, it will send AAAA,
992 // so we need to avoid sending =AAAA for a blank token value.
993 if (!(*it)->Name().empty())
994 cookie_line += (*it)->Name() + "=";
995 cookie_line += (*it)->Value();
996 }
997
998 COOKIE_DLOG(INFO) << "GetCookies() result: " << cookie_line;
999
1000 return cookie_line;
1001}
1002
[email protected]971713e2009-10-29 16:07:211003void CookieMonster::DeleteCookie(const GURL& url,
1004 const std::string& cookie_name) {
[email protected]bb8905722010-05-21 17:29:041005 AutoLock autolock(lock_);
1006 InitIfNecessary();
1007
[email protected]971713e2009-10-29 16:07:211008 if (!HasCookieableScheme(url))
1009 return;
1010
[email protected]e8bac552009-10-30 16:15:391011 CookieOptions options;
1012 options.set_include_httponly();
1013 // Get the cookies for this host and its domain(s).
1014 std::vector<CanonicalCookie*> cookies;
1015 FindCookiesForHostAndDomain(url, options, &cookies);
1016 std::set<CanonicalCookie*> matching_cookies;
1017
1018 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
1019 it != cookies.end(); ++it) {
1020 if ((*it)->Name() != cookie_name)
1021 continue;
1022 if (url.path().find((*it)->Path()))
1023 continue;
1024 matching_cookies.insert(*it);
1025 }
1026
1027 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1028 CookieMap::iterator curit = it;
1029 ++it;
[email protected]c4058fb2010-06-22 17:25:261030 if (matching_cookies.find(curit->second) != matching_cookies.end()) {
[email protected]2f3f3592010-07-07 20:11:511031 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT);
[email protected]c4058fb2010-06-22 17:25:261032 }
[email protected]971713e2009-10-29 16:07:211033 }
1034}
1035
initial.commit586acc5fe2008-07-26 22:42:521036CookieMonster::CookieList CookieMonster::GetAllCookies() {
1037 AutoLock autolock(lock_);
1038 InitIfNecessary();
1039
[email protected]c890ed192008-10-30 23:45:531040 // This function is being called to scrape the cookie list for management UI
1041 // or similar. We shouldn't show expired cookies in this list since it will
1042 // just be confusing to users, and this function is called rarely enough (and
1043 // is already slow enough) that it's OK to take the time to garbage collect
1044 // the expired cookies now.
1045 //
1046 // Note that this does not prune cookies to be below our limits (if we've
1047 // exceeded them) the way that calling GarbageCollect() would.
1048 GarbageCollectExpired(Time::Now(),
1049 CookieMapItPair(cookies_.begin(), cookies_.end()),
1050 NULL);
initial.commit586acc5fe2008-07-26 22:42:521051
[email protected]c890ed192008-10-30 23:45:531052 CookieList cookie_list;
1053 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end(); ++it)
initial.commit586acc5fe2008-07-26 22:42:521054 cookie_list.push_back(CookieListPair(it->first, *it->second));
initial.commit586acc5fe2008-07-26 22:42:521055
1056 return cookie_list;
1057}
1058
[email protected]34602282010-02-03 22:14:151059CookieMonster::CookieList CookieMonster::GetAllCookiesForURL(const GURL& url) {
[email protected]86d9b0d2010-02-03 18:12:071060 AutoLock autolock(lock_);
1061 InitIfNecessary();
[email protected]bb8905722010-05-21 17:29:041062
[email protected]c10da4b02010-03-25 14:38:321063 return InternalGetAllCookiesForURL(url);
[email protected]79a087a2010-02-03 17:08:191064}
1065
initial.commit586acc5fe2008-07-26 22:42:521066void CookieMonster::FindCookiesForHostAndDomain(
1067 const GURL& url,
[email protected]3a96c742008-11-19 19:46:271068 const CookieOptions& options,
initial.commit586acc5fe2008-07-26 22:42:521069 std::vector<CanonicalCookie*>* cookies) {
[email protected]bb8905722010-05-21 17:29:041070 lock_.AssertAcquired();
initial.commit586acc5fe2008-07-26 22:42:521071
1072 const Time current_time(CurrentTime());
1073
[email protected]c4058fb2010-06-22 17:25:261074 // Probe to save statistics relatively frequently. We do it here rather
1075 // than in the set path as many websites won't set cookies, and we
1076 // want to collect statistics whenever the browser's being used.
1077 RecordPeriodicStats(current_time);
1078
initial.commit586acc5fe2008-07-26 22:42:521079 // Query for the full host, For example: 'a.c.blah.com'.
1080 std::string key(url.host());
1081 FindCookiesForKey(key, url, options, current_time, cookies);
1082
1083 // See if we can search for domain cookies, i.e. if the host has a TLD + 1.
[email protected]69bb5872010-01-12 20:33:521084 const std::string domain(GetEffectiveDomain(url.scheme(), key));
initial.commit586acc5fe2008-07-26 22:42:521085 if (domain.empty())
1086 return;
1087 DCHECK_LE(domain.length(), key.length());
1088 DCHECK_EQ(0, key.compare(key.length() - domain.length(), domain.length(),
1089 domain));
1090
1091 // Walk through the string and query at the dot points (GURL should have
1092 // canonicalized the dots, so this should be safe). Stop once we reach the
1093 // domain + registry; we can't write cookies past this point, and with some
1094 // registrars other domains can, in which case we don't want to read their
1095 // cookies.
1096 for (key = "." + key; key.length() > domain.length(); ) {
1097 FindCookiesForKey(key, url, options, current_time, cookies);
1098 const size_t next_dot = key.find('.', 1); // Skip over leading dot.
1099 key.erase(0, next_dot);
1100 }
1101}
1102
1103void CookieMonster::FindCookiesForKey(
1104 const std::string& key,
1105 const GURL& url,
[email protected]3a96c742008-11-19 19:46:271106 const CookieOptions& options,
initial.commit586acc5fe2008-07-26 22:42:521107 const Time& current,
1108 std::vector<CanonicalCookie*>* cookies) {
[email protected]bb8905722010-05-21 17:29:041109 lock_.AssertAcquired();
1110
initial.commit586acc5fe2008-07-26 22:42:521111 bool secure = url.SchemeIsSecure();
1112
1113 for (CookieMapItPair its = cookies_.equal_range(key);
1114 its.first != its.second; ) {
1115 CookieMap::iterator curit = its.first;
1116 CanonicalCookie* cc = curit->second;
1117 ++its.first;
1118
1119 // If the cookie is expired, delete it.
1120 if (cc->IsExpired(current)) {
[email protected]2f3f3592010-07-07 20:11:511121 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
initial.commit586acc5fe2008-07-26 22:42:521122 continue;
1123 }
1124
[email protected]3a96c742008-11-19 19:46:271125 // Filter out HttpOnly cookies, per options.
1126 if (options.exclude_httponly() && cc->IsHttpOnly())
initial.commit586acc5fe2008-07-26 22:42:521127 continue;
1128
1129 // Filter out secure cookies unless we're https.
1130 if (!secure && cc->IsSecure())
1131 continue;
1132
1133 if (!cc->IsOnPath(url.path()))
1134 continue;
1135
[email protected]77e0a462008-11-01 00:43:351136 // Add this cookie to the set of matching cookies. Since we're reading the
1137 // cookie, update its last access time.
1138 InternalUpdateCookieAccessTime(cc);
initial.commit586acc5fe2008-07-26 22:42:521139 cookies->push_back(cc);
1140 }
1141}
1142
[email protected]79a087a2010-02-03 17:08:191143void CookieMonster::FindRawCookies(const std::string& key,
1144 bool include_secure,
[email protected]bfcaed42010-02-04 17:38:201145 const std::string& path,
[email protected]79a087a2010-02-03 17:08:191146 CookieList* list) {
[email protected]bb8905722010-05-21 17:29:041147 lock_.AssertAcquired();
1148
[email protected]79a087a2010-02-03 17:08:191149 for (CookieMapItPair its = cookies_.equal_range(key);
1150 its.first != its.second; ++its.first) {
1151 CanonicalCookie* cc = its.first->second;
[email protected]bfcaed42010-02-04 17:38:201152 if (!include_secure && cc->IsSecure())
1153 continue;
1154 if (!cc->IsOnPath(path))
1155 continue;
1156 list->push_back(CookieListPair(key, *cc));
[email protected]79a087a2010-02-03 17:08:191157 }
1158}
1159
[email protected]c10da4b02010-03-25 14:38:321160CookieMonster::CookieList CookieMonster::InternalGetAllCookiesForURL(
1161 const GURL& url) {
[email protected]bb8905722010-05-21 17:29:041162 lock_.AssertAcquired();
1163
[email protected]c10da4b02010-03-25 14:38:321164 // Do not return removed cookies.
1165 GarbageCollectExpired(Time::Now(),
1166 CookieMapItPair(cookies_.begin(), cookies_.end()),
1167 NULL);
1168
1169 CookieList cookie_list;
1170 if (!HasCookieableScheme(url))
1171 return cookie_list;
1172
1173 bool secure = url.SchemeIsSecure();
1174
1175 // Query for the full host, For example: 'a.c.blah.com'.
1176 std::string key(url.host());
1177 FindRawCookies(key, secure, url.path(), &cookie_list);
1178
1179 // See if we can search for domain cookies, i.e. if the host has a TLD + 1.
1180 const std::string domain(GetEffectiveDomain(url.scheme(), key));
1181 if (domain.empty())
1182 return cookie_list;
1183
1184 // Use same logic as in FindCookiesForHostAndDomain.
1185 DCHECK_LE(domain.length(), key.length());
1186 DCHECK_EQ(0, key.compare(key.length() - domain.length(), domain.length(),
1187 domain));
1188 for (key = "." + key; key.length() > domain.length(); ) {
1189 FindRawCookies(key, secure, url.path(), &cookie_list);
1190 const size_t next_dot = key.find('.', 1); // Skip over leading dot.
1191 key.erase(0, next_dot);
1192 }
1193 return cookie_list;
1194}
initial.commit586acc5fe2008-07-26 22:42:521195
[email protected]c4058fb2010-06-22 17:25:261196// Test to see if stats should be recorded, and record them if so.
1197// The goal here is to get sampling for the average browser-hour of
1198// activity. We won't take samples when the web isn't being surfed,
1199// and when the web is being surfed, we'll take samples about every
1200// kRecordStatisticsIntervalSeconds.
1201// last_statistic_record_time_ is initialized to Now() rather than null
1202// in the constructor so that we won't take statistics right after
1203// startup, to avoid bias from browsers that are started but not used.
1204void CookieMonster::RecordPeriodicStats(const base::Time& current_time) {
1205 const base::TimeDelta kRecordStatisticsIntervalTime(
1206 base::TimeDelta::FromSeconds(kRecordStatisticsIntervalSeconds));
1207
1208 if (current_time - last_statistic_record_time_ >
1209 kRecordStatisticsIntervalTime) {
1210 UMA_HISTOGRAM_CUSTOM_COUNTS("net.CookieCount", cookies_.size(),
1211 1, 4000, 50);
1212 last_statistic_record_time_ = current_time;
1213 }
1214}
1215
initial.commit586acc5fe2008-07-26 22:42:521216CookieMonster::ParsedCookie::ParsedCookie(const std::string& cookie_line)
1217 : is_valid_(false),
1218 path_index_(0),
1219 domain_index_(0),
1220 expires_index_(0),
1221 maxage_index_(0),
1222 secure_index_(0),
1223 httponly_index_(0) {
1224
1225 if (cookie_line.size() > kMaxCookieSize) {
1226 LOG(INFO) << "Not parsing cookie, too large: " << cookie_line.size();
1227 return;
1228 }
1229
1230 ParseTokenValuePairs(cookie_line);
1231 if (pairs_.size() > 0) {
1232 is_valid_ = true;
1233 SetupAttributes();
1234 }
1235}
1236
1237// Returns true if |c| occurs in |chars|
1238// TODO maybe make this take an iterator, could check for end also?
1239static inline bool CharIsA(const char c, const char* chars) {
1240 return strchr(chars, c) != NULL;
1241}
1242// Seek the iterator to the first occurrence of a character in |chars|.
1243// Returns true if it hit the end, false otherwise.
1244static inline bool SeekTo(std::string::const_iterator* it,
1245 const std::string::const_iterator& end,
1246 const char* chars) {
[email protected]f07467d2010-06-16 14:28:301247 for (; *it != end && !CharIsA(**it, chars); ++(*it)) {}
initial.commit586acc5fe2008-07-26 22:42:521248 return *it == end;
1249}
1250// Seek the iterator to the first occurrence of a character not in |chars|.
1251// Returns true if it hit the end, false otherwise.
1252static inline bool SeekPast(std::string::const_iterator* it,
1253 const std::string::const_iterator& end,
1254 const char* chars) {
[email protected]f07467d2010-06-16 14:28:301255 for (; *it != end && CharIsA(**it, chars); ++(*it)) {}
initial.commit586acc5fe2008-07-26 22:42:521256 return *it == end;
1257}
1258static inline bool SeekBackPast(std::string::const_iterator* it,
1259 const std::string::const_iterator& end,
1260 const char* chars) {
[email protected]f07467d2010-06-16 14:28:301261 for (; *it != end && CharIsA(**it, chars); --(*it)) {}
initial.commit586acc5fe2008-07-26 22:42:521262 return *it == end;
1263}
1264
[email protected]f325f1e12010-04-30 22:38:551265const char CookieMonster::ParsedCookie::kTerminator[] = "\n\r\0";
1266const int CookieMonster::ParsedCookie::kTerminatorLen =
1267 sizeof(kTerminator) - 1;
1268const char CookieMonster::ParsedCookie::kWhitespace[] = " \t";
1269const char CookieMonster::ParsedCookie::kValueSeparator[] = ";";
1270const char CookieMonster::ParsedCookie::kTokenSeparator[] = ";=";
1271
1272std::string::const_iterator CookieMonster::ParsedCookie::FindFirstTerminator(
1273 const std::string& s) {
1274 std::string::const_iterator end = s.end();
1275 size_t term_pos =
1276 s.find_first_of(std::string(kTerminator, kTerminatorLen));
1277 if (term_pos != std::string::npos) {
1278 // We found a character we should treat as an end of string.
1279 end = s.begin() + term_pos;
1280 }
1281 return end;
1282}
1283
1284bool CookieMonster::ParsedCookie::ParseToken(
1285 std::string::const_iterator* it,
1286 const std::string::const_iterator& end,
1287 std::string::const_iterator* token_start,
1288 std::string::const_iterator* token_end) {
1289 DCHECK(it && token_start && token_end);
1290 std::string::const_iterator token_real_end;
1291
1292 // Seek past any whitespace before the "token" (the name).
1293 // token_start should point at the first character in the token
1294 if (SeekPast(it, end, kWhitespace))
1295 return false; // No token, whitespace or empty.
1296 *token_start = *it;
1297
1298 // Seek over the token, to the token separator.
1299 // token_real_end should point at the token separator, i.e. '='.
1300 // If it == end after the seek, we probably have a token-value.
1301 SeekTo(it, end, kTokenSeparator);
1302 token_real_end = *it;
1303
1304 // Ignore any whitespace between the token and the token separator.
1305 // token_end should point after the last interesting token character,
1306 // pointing at either whitespace, or at '=' (and equal to token_real_end).
1307 if (*it != *token_start) { // We could have an empty token name.
1308 --(*it); // Go back before the token separator.
1309 // Skip over any whitespace to the first non-whitespace character.
1310 SeekBackPast(it, *token_start, kWhitespace);
1311 // Point after it.
1312 ++(*it);
1313 }
1314 *token_end = *it;
1315
1316 // Seek us back to the end of the token.
1317 *it = token_real_end;
1318 return true;
1319}
1320
1321void CookieMonster::ParsedCookie::ParseValue(
1322 std::string::const_iterator* it,
1323 const std::string::const_iterator& end,
1324 std::string::const_iterator* value_start,
1325 std::string::const_iterator* value_end) {
1326 DCHECK(it && value_start && value_end);
1327
1328 // Seek past any whitespace that might in-between the token and value.
1329 SeekPast(it, end, kWhitespace);
1330 // value_start should point at the first character of the value.
1331 *value_start = *it;
1332
1333 // It is unclear exactly how quoted string values should be handled.
1334 // Major browsers do different things, for example, Firefox supports
1335 // semicolons embedded in a quoted value, while IE does not. Looking at
1336 // the specs, RFC 2109 and 2965 allow for a quoted-string as the value.
1337 // However, these specs were apparently written after browsers had
1338 // implemented cookies, and they seem very distant from the reality of
1339 // what is actually implemented and used on the web. The original spec
1340 // from Netscape is possibly what is closest to the cookies used today.
1341 // This spec didn't have explicit support for double quoted strings, and
1342 // states that ; is not allowed as part of a value. We had originally
1343 // implement the Firefox behavior (A="B;C"; -> A="B;C";). However, since
1344 // there is no standard that makes sense, we decided to follow the behavior
1345 // of IE and Safari, which is closer to the original Netscape proposal.
1346 // This means that A="B;C" -> A="B;. This also makes the code much simpler
1347 // and reduces the possibility for invalid cookies, where other browsers
1348 // like Opera currently reject those invalid cookies (ex A="B" "C";).
1349
1350 // Just look for ';' to terminate ('=' allowed).
1351 // We can hit the end, maybe they didn't terminate.
1352 SeekTo(it, end, kValueSeparator);
1353
1354 // Will be pointed at the ; seperator or the end.
1355 *value_end = *it;
1356
1357 // Ignore any unwanted whitespace after the value.
1358 if (*value_end != *value_start) { // Could have an empty value
1359 --(*value_end);
1360 SeekBackPast(value_end, *value_start, kWhitespace);
1361 ++(*value_end);
1362 }
1363}
1364
1365std::string CookieMonster::ParsedCookie::ParseTokenString(
1366 const std::string& token) {
1367 std::string::const_iterator it = token.begin();
1368 std::string::const_iterator end = FindFirstTerminator(token);
1369
1370 std::string::const_iterator token_start, token_end;
1371 if (ParseToken(&it, end, &token_start, &token_end))
1372 return std::string(token_start, token_end);
1373 return std::string();
1374}
1375
1376std::string CookieMonster::ParsedCookie::ParseValueString(
1377 const std::string& value) {
1378 std::string::const_iterator it = value.begin();
1379 std::string::const_iterator end = FindFirstTerminator(value);
1380
1381 std::string::const_iterator value_start, value_end;
1382 ParseValue(&it, end, &value_start, &value_end);
1383 return std::string(value_start, value_end);
1384}
1385
initial.commit586acc5fe2008-07-26 22:42:521386// Parse all token/value pairs and populate pairs_.
1387void CookieMonster::ParsedCookie::ParseTokenValuePairs(
1388 const std::string& cookie_line) {
initial.commit586acc5fe2008-07-26 22:42:521389 pairs_.clear();
1390
1391 // Ok, here we go. We should be expecting to be starting somewhere
1392 // before the cookie line, not including any header name...
1393 std::string::const_iterator start = cookie_line.begin();
initial.commit586acc5fe2008-07-26 22:42:521394 std::string::const_iterator it = start;
1395
1396 // TODO Make sure we're stripping \r\n in the network code. Then we
1397 // can log any unexpected terminators.
[email protected]f325f1e12010-04-30 22:38:551398 std::string::const_iterator end = FindFirstTerminator(cookie_line);
initial.commit586acc5fe2008-07-26 22:42:521399
1400 for (int pair_num = 0; pair_num < kMaxPairs && it != end; ++pair_num) {
1401 TokenValuePair pair;
initial.commit586acc5fe2008-07-26 22:42:521402
[email protected]f325f1e12010-04-30 22:38:551403 std::string::const_iterator token_start, token_end;
1404 if (!ParseToken(&it, end, &token_start, &token_end))
1405 break;
initial.commit586acc5fe2008-07-26 22:42:521406
1407 if (it == end || *it != '=') {
1408 // We have a token-value, we didn't have any token name.
1409 if (pair_num == 0) {
1410 // For the first time around, we want to treat single values
1411 // as a value with an empty name. (Mozilla bug 169091).
1412 // IE seems to also have this behavior, ex "AAA", and "AAA=10" will
1413 // set 2 different cookies, and setting "BBB" will then replace "AAA".
1414 pair.first = "";
1415 // Rewind to the beginning of what we thought was the token name,
1416 // and let it get parsed as a value.
1417 it = token_start;
1418 } else {
1419 // Any not-first attribute we want to treat a value as a
1420 // name with an empty value... This is so something like
1421 // "secure;" will get parsed as a Token name, and not a value.
1422 pair.first = std::string(token_start, token_end);
1423 }
1424 } else {
1425 // We have a TOKEN=VALUE.
1426 pair.first = std::string(token_start, token_end);
1427 ++it; // Skip past the '='.
1428 }
1429
1430 // OK, now try to parse a value.
1431 std::string::const_iterator value_start, value_end;
[email protected]f325f1e12010-04-30 22:38:551432 ParseValue(&it, end, &value_start, &value_end);
initial.commit586acc5fe2008-07-26 22:42:521433 // OK, we're finished with a Token/Value.
1434 pair.second = std::string(value_start, value_end);
[email protected]f325f1e12010-04-30 22:38:551435
initial.commit586acc5fe2008-07-26 22:42:521436 // From RFC2109: "Attributes (names) (attr) are case-insensitive."
1437 if (pair_num != 0)
1438 StringToLowerASCII(&pair.first);
1439 pairs_.push_back(pair);
1440
1441 // We've processed a token/value pair, we're either at the end of
1442 // the string or a ValueSeparator like ';', which we want to skip.
1443 if (it != end)
1444 ++it;
1445 }
1446}
1447
1448void CookieMonster::ParsedCookie::SetupAttributes() {
1449 static const char kPathTokenName[] = "path";
1450 static const char kDomainTokenName[] = "domain";
1451 static const char kExpiresTokenName[] = "expires";
1452 static const char kMaxAgeTokenName[] = "max-age";
1453 static const char kSecureTokenName[] = "secure";
1454 static const char kHttpOnlyTokenName[] = "httponly";
1455
1456 // We skip over the first token/value, the user supplied one.
1457 for (size_t i = 1; i < pairs_.size(); ++i) {
[email protected]f325f1e12010-04-30 22:38:551458 if (pairs_[i].first == kPathTokenName) {
initial.commit586acc5fe2008-07-26 22:42:521459 path_index_ = i;
[email protected]f325f1e12010-04-30 22:38:551460 } else if (pairs_[i].first == kDomainTokenName) {
initial.commit586acc5fe2008-07-26 22:42:521461 domain_index_ = i;
[email protected]f325f1e12010-04-30 22:38:551462 } else if (pairs_[i].first == kExpiresTokenName) {
initial.commit586acc5fe2008-07-26 22:42:521463 expires_index_ = i;
[email protected]f325f1e12010-04-30 22:38:551464 } else if (pairs_[i].first == kMaxAgeTokenName) {
initial.commit586acc5fe2008-07-26 22:42:521465 maxage_index_ = i;
[email protected]f325f1e12010-04-30 22:38:551466 } else if (pairs_[i].first == kSecureTokenName) {
initial.commit586acc5fe2008-07-26 22:42:521467 secure_index_ = i;
[email protected]f325f1e12010-04-30 22:38:551468 } else if (pairs_[i].first == kHttpOnlyTokenName) {
initial.commit586acc5fe2008-07-26 22:42:521469 httponly_index_ = i;
[email protected]f325f1e12010-04-30 22:38:551470 } else {
1471 /* some attribute we don't know or don't care about. */
1472 }
initial.commit586acc5fe2008-07-26 22:42:521473 }
1474}
1475
1476// Create a cookie-line for the cookie. For debugging only!
1477// If we want to use this for something more than debugging, we
1478// should rewrite it better...
1479std::string CookieMonster::ParsedCookie::DebugString() const {
1480 std::string out;
1481 for (PairList::const_iterator it = pairs_.begin();
1482 it != pairs_.end(); ++it) {
1483 out.append(it->first);
1484 out.append("=");
1485 out.append(it->second);
1486 out.append("; ");
1487 }
1488 return out;
1489}
1490
[email protected]a986cc32010-02-12 23:55:471491CookieMonster::CanonicalCookie::CanonicalCookie(const GURL& url,
1492 const ParsedCookie& pc)
1493 : name_(pc.Name()),
1494 value_(pc.Value()),
1495 path_(CanonPath(url, pc)),
1496 creation_date_(Time::Now()),
1497 last_access_date_(Time()),
1498 has_expires_(pc.HasExpires()),
1499 secure_(pc.IsSecure()),
1500 httponly_(pc.IsHttpOnly()) {
1501 if (has_expires_)
1502 expiry_date_ = CanonExpiration(pc, creation_date_, CookieOptions());
1503}
1504
[email protected]f325f1e12010-04-30 22:38:551505CookieMonster::CanonicalCookie* CookieMonster::CanonicalCookie::Create(
1506 const GURL& url, const std::string& name, const std::string& value,
1507 const std::string& path, const base::Time& creation_time,
1508 const base::Time& expiration_time, bool secure, bool http_only) {
1509 // Expect valid attribute tokens and values, as defined by the ParsedCookie
1510 // logic, otherwise don't create the cookie.
1511 std::string parsed_name = ParsedCookie::ParseTokenString(name);
1512 if (parsed_name != name)
1513 return NULL;
1514 std::string parsed_value = ParsedCookie::ParseValueString(value);
1515 if (parsed_value != value)
1516 return NULL;
1517 std::string parsed_path = ParsedCookie::ParseValueString(path);
1518 if (parsed_path != path)
1519 return NULL;
1520
1521 std::string cookie_path = CanonPathWithString(url, parsed_path);
1522 // Expect that the path was either not specified (empty), or is valid.
1523 if (!parsed_path.empty() && cookie_path != parsed_path)
1524 return NULL;
1525 // Canonicalize path again to make sure it escapes characters as needed.
1526 url_parse::Component path_component(0, cookie_path.length());
1527 url_canon::RawCanonOutputT<char> canon_path;
1528 url_parse::Component canon_path_component;
1529 url_canon::CanonicalizePath(cookie_path.data(), path_component,
1530 &canon_path, &canon_path_component);
1531 cookie_path = std::string(canon_path.data() + canon_path_component.begin,
1532 canon_path_component.len);
1533
1534 return new CanonicalCookie(parsed_name, parsed_value, cookie_path,
1535 secure, http_only, creation_time, creation_time,
1536 !expiration_time.is_null(), expiration_time);
1537}
1538
initial.commit586acc5fe2008-07-26 22:42:521539bool CookieMonster::CanonicalCookie::IsOnPath(
1540 const std::string& url_path) const {
1541
1542 // A zero length would be unsafe for our trailing '/' checks, and
1543 // would also make no sense for our prefix match. The code that
1544 // creates a CanonicalCookie should make sure the path is never zero length,
1545 // but we double check anyway.
1546 if (path_.empty())
1547 return false;
1548
1549 // The Mozilla code broke it into 3 cases, if it's strings lengths
1550 // are less than, equal, or greater. I think this is simpler:
1551
1552 // Make sure the cookie path is a prefix of the url path. If the
1553 // url path is shorter than the cookie path, then the cookie path
1554 // can't be a prefix.
1555 if (url_path.find(path_) != 0)
1556 return false;
1557
1558 // Now we know that url_path is >= cookie_path, and that cookie_path
1559 // is a prefix of url_path. If they are the are the same length then
1560 // they are identical, otherwise we need an additional check:
1561
1562 // In order to avoid in correctly matching a cookie path of /blah
1563 // with a request path of '/blahblah/', we need to make sure that either
1564 // the cookie path ends in a trailing '/', or that we prefix up to a '/'
1565 // in the url path. Since we know that the url path length is greater
1566 // than the cookie path length, it's safe to index one byte past.
1567 if (path_.length() != url_path.length() &&
1568 path_[path_.length() - 1] != '/' &&
1569 url_path[path_.length()] != '/')
1570 return false;
1571
1572 return true;
1573}
1574
1575std::string CookieMonster::CanonicalCookie::DebugString() const {
[email protected]34b2b002009-11-20 06:53:281576 return StringPrintf("name: %s value: %s path: %s creation: %" PRId64,
initial.commit586acc5fe2008-07-26 22:42:521577 name_.c_str(), value_.c_str(), path_.c_str(),
[email protected]34b2b002009-11-20 06:53:281578 static_cast<int64>(creation_date_.ToTimeT()));
initial.commit586acc5fe2008-07-26 22:42:521579}
[email protected]8ac1a752008-07-31 19:40:371580
1581} // namespace