Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(445)

Side by Side Diff: net/cookies/canonical_cookie.cc

Issue 10785017: Move CanonicalCookie into separate files (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Prune some includes, fix a unit test Created 8 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
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 (dwitte@stanford.edu)
29 * Michiel van Leeuwen (mvl@exedo.nl)
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/cookies/canonical_cookie.h"
46
47 #include "base/basictypes.h"
48 #include "base/format_macros.h"
49 #include "base/logging.h"
50 #include "base/stringprintf.h"
51 #include "googleurl/src/gurl.h"
52 #include "googleurl/src/url_canon.h"
53 #include "net/cookies/cookie_util.h"
54 #include "net/cookies/parsed_cookie.h"
55
56 using base::Time;
57 using base::TimeDelta;
58
59 namespace net {
60
61 namespace {
62
63 // Determine the cookie domain to use for setting the specified cookie.
64 bool GetCookieDomain(const GURL& url,
65 const ParsedCookie& pc,
66 std::string* result) {
67 std::string domain_string;
68 if (pc.HasDomain())
69 domain_string = pc.Domain();
70 return cookie_util::GetCookieDomainWithString(url, domain_string, result);
71 }
72
73 std::string CanonPathWithString(const GURL& url,
74 const std::string& path_string) {
75 // The RFC says the path should be a prefix of the current URL path.
76 // However, Mozilla allows you to set any path for compatibility with
77 // broken websites. We unfortunately will mimic this behavior. We try
78 // to be generous and accept cookies with an invalid path attribute, and
79 // default the path to something reasonable.
80
81 // The path was supplied in the cookie, we'll take it.
82 if (!path_string.empty() && path_string[0] == '/')
83 return path_string;
84
85 // The path was not supplied in the cookie or invalid, we will default
86 // to the current URL path.
87 // """Defaults to the path of the request URL that generated the
88 // Set-Cookie response, up to, but not including, the
89 // right-most /."""
90 // How would this work for a cookie on /? We will include it then.
91 const std::string& url_path = url.path();
92
93 size_t idx = url_path.find_last_of('/');
94
95 // The cookie path was invalid or a single '/'.
96 if (idx == 0 || idx == std::string::npos)
97 return std::string("/");
98
99 // Return up to the rightmost '/'.
100 return url_path.substr(0, idx);
101 }
102
103 } // namespace
104
105 CanonicalCookie::CanonicalCookie()
106 : secure_(false),
107 httponly_(false) {
108 SetSessionCookieExpiryTime();
109 }
110
111 CanonicalCookie::CanonicalCookie(
112 const GURL& url, const std::string& name, const std::string& value,
113 const std::string& domain, const std::string& path,
114 const std::string& mac_key, const std::string& mac_algorithm,
115 const base::Time& creation, const base::Time& expiration,
116 const base::Time& last_access, bool secure, bool httponly)
117 : source_(GetCookieSourceFromURL(url)),
118 name_(name),
119 value_(value),
120 domain_(domain),
121 path_(path),
122 mac_key_(mac_key),
123 mac_algorithm_(mac_algorithm),
124 creation_date_(creation),
125 expiry_date_(expiration),
126 last_access_date_(last_access),
127 secure_(secure),
128 httponly_(httponly) {
129 if (expiration.is_null())
130 SetSessionCookieExpiryTime();
131 }
132
133 CanonicalCookie::CanonicalCookie(const GURL& url, const ParsedCookie& pc)
134 : source_(GetCookieSourceFromURL(url)),
135 name_(pc.Name()),
136 value_(pc.Value()),
137 path_(CanonPath(url, pc)),
138 mac_key_(pc.MACKey()),
139 mac_algorithm_(pc.MACAlgorithm()),
140 creation_date_(Time::Now()),
141 last_access_date_(Time()),
142 secure_(pc.IsSecure()),
143 httponly_(pc.IsHttpOnly()) {
144 if (pc.HasExpires())
145 expiry_date_ = CanonExpiration(pc, creation_date_, creation_date_);
146 else
147 SetSessionCookieExpiryTime();
148
149 // Do the best we can with the domain.
150 std::string cookie_domain;
151 std::string domain_string;
152 if (pc.HasDomain()) {
153 domain_string = pc.Domain();
154 }
155 bool result
156 = cookie_util::GetCookieDomainWithString(url, domain_string,
157 &cookie_domain);
158 // Caller is responsible for passing in good arguments.
159 DCHECK(result);
160 domain_ = cookie_domain;
161 }
162
163 CanonicalCookie::~CanonicalCookie() {
164 }
165
166 std::string CanonicalCookie::GetCookieSourceFromURL(const GURL& url) {
167 if (url.SchemeIsFile())
168 return url.spec();
169
170 url_canon::Replacements<char> replacements;
171 replacements.ClearPort();
172 if (url.SchemeIsSecure())
173 replacements.SetScheme("http", url_parse::Component(0, 4));
174
175 return url.GetOrigin().ReplaceComponents(replacements).spec();
176 }
177
178 // static
179 std::string CanonicalCookie::CanonPath(const GURL& url,
180 const ParsedCookie& pc) {
181 std::string path_string;
182 if (pc.HasPath())
183 path_string = pc.Path();
184 return CanonPathWithString(url, path_string);
185 }
186
187 // static
188 Time CanonicalCookie::CanonExpiration(const ParsedCookie& pc,
189 const Time& current,
190 const Time& server_time) {
191 // First, try the Max-Age attribute.
192 uint64 max_age = 0;
193 if (pc.HasMaxAge() &&
194 #ifdef COMPILER_MSVC
195 sscanf_s(
196 #else
197 sscanf(
198 #endif
199 pc.MaxAge().c_str(), " %" PRIu64, &max_age) == 1) {
200 return current + TimeDelta::FromSeconds(max_age);
201 }
202
203 // Try the Expires attribute.
204 if (pc.HasExpires()) {
205 // Adjust for clock skew between server and host.
206 return current + (ParsedCookie::ParseCookieTime(pc.Expires()) -
207 server_time);
208 }
209
210 // Invalid or no expiration, persistent cookie.
211 return Time();
212 }
213
214 void CanonicalCookie::SetSessionCookieExpiryTime() {
215 #if defined(ENABLE_PERSISTENT_SESSION_COOKIES)
216 // Mobile apps can sometimes be shut down without any warning, so the session
217 // cookie has to be persistent and given a default expiration time.
218 expiry_date_ = base::Time::Now() +
219 base::TimeDelta::FromDays(kPersistentSessionCookieExpiryInDays);
220 #endif
221 }
222
223 CanonicalCookie* CanonicalCookie::Create(const GURL& url,
224 const ParsedCookie& pc) {
225 if (!pc.IsValid()) {
226 return NULL;
227 }
228
229 std::string domain_string;
230 if (!GetCookieDomain(url, pc, &domain_string)) {
231 return NULL;
232 }
233 std::string path_string = CanonPath(url, pc);
234 std::string mac_key = pc.HasMACKey() ? pc.MACKey() : std::string();
235 std::string mac_algorithm = pc.HasMACAlgorithm() ?
236 pc.MACAlgorithm() : std::string();
237 Time creation_time = Time::Now();
238 Time expiration_time;
239 if (pc.HasExpires())
240 expiration_time = ParsedCookie::ParseCookieTime(pc.Expires());
241
242 return (Create(url, pc.Name(), pc.Value(), domain_string, path_string,
243 mac_key, mac_algorithm, creation_time, expiration_time,
244 pc.IsSecure(), pc.IsHttpOnly()));
245 }
246
247 CanonicalCookie* CanonicalCookie::Create(const GURL& url,
248 const std::string& name,
249 const std::string& value,
250 const std::string& domain,
251 const std::string& path,
252 const std::string& mac_key,
253 const std::string& mac_algorithm,
254 const base::Time& creation,
255 const base::Time& expiration,
256 bool secure,
257 bool http_only) {
258 // Expect valid attribute tokens and values, as defined by the ParsedCookie
259 // logic, otherwise don't create the cookie.
260 std::string parsed_name = ParsedCookie::ParseTokenString(name);
261 if (parsed_name != name)
262 return NULL;
263 std::string parsed_value = ParsedCookie::ParseValueString(value);
264 if (parsed_value != value)
265 return NULL;
266
267 std::string parsed_domain = ParsedCookie::ParseValueString(domain);
268 if (parsed_domain != domain)
269 return NULL;
270 std::string cookie_domain;
271 if (!cookie_util::GetCookieDomainWithString(url, parsed_domain,
272 &cookie_domain)) {
273 return NULL;
274 }
275
276 std::string parsed_path = ParsedCookie::ParseValueString(path);
277 if (parsed_path != path)
278 return NULL;
279
280 std::string cookie_path = CanonPathWithString(url, parsed_path);
281 // Expect that the path was either not specified (empty), or is valid.
282 if (!parsed_path.empty() && cookie_path != parsed_path)
283 return NULL;
284 // Canonicalize path again to make sure it escapes characters as needed.
285 url_parse::Component path_component(0, cookie_path.length());
286 url_canon::RawCanonOutputT<char> canon_path;
287 url_parse::Component canon_path_component;
288 url_canon::CanonicalizePath(cookie_path.data(), path_component,
289 &canon_path, &canon_path_component);
290 cookie_path = std::string(canon_path.data() + canon_path_component.begin,
291 canon_path_component.len);
292
293 return new CanonicalCookie(url, parsed_name, parsed_value, cookie_domain,
294 cookie_path, mac_key, mac_algorithm, creation,
295 expiration, creation, secure, http_only);
296 }
297
298 bool CanonicalCookie::IsOnPath(const std::string& url_path) const {
299
300 // A zero length would be unsafe for our trailing '/' checks, and
301 // would also make no sense for our prefix match. The code that
302 // creates a CanonicalCookie should make sure the path is never zero length,
303 // but we double check anyway.
304 if (path_.empty())
305 return false;
306
307 // The Mozilla code broke this into three cases, based on if the cookie path
308 // was longer, the same length, or shorter than the length of the url path.
309 // I think the approach below is simpler.
310
311 // Make sure the cookie path is a prefix of the url path. If the
312 // url path is shorter than the cookie path, then the cookie path
313 // can't be a prefix.
314 if (url_path.find(path_) != 0)
315 return false;
316
317 // Now we know that url_path is >= cookie_path, and that cookie_path
318 // is a prefix of url_path. If they are the are the same length then
319 // they are identical, otherwise we need an additional check:
320
321 // In order to avoid in correctly matching a cookie path of /blah
322 // with a request path of '/blahblah/', we need to make sure that either
323 // the cookie path ends in a trailing '/', or that we prefix up to a '/'
324 // in the url path. Since we know that the url path length is greater
325 // than the cookie path length, it's safe to index one byte past.
326 if (path_.length() != url_path.length() &&
327 path_[path_.length() - 1] != '/' &&
328 url_path[path_.length()] != '/')
329 return false;
330
331 return true;
332 }
333
334 bool CanonicalCookie::IsDomainMatch(const std::string& scheme,
335 const std::string& host) const {
336 // Can domain match in two ways; as a domain cookie (where the cookie
337 // domain begins with ".") or as a host cookie (where it doesn't).
338
339 // Some consumers of the CookieMonster expect to set cookies on
340 // URLs like http://.strange.url. To retrieve cookies in this instance,
341 // we allow matching as a host cookie even when the domain_ starts with
342 // a period.
343 if (host == domain_)
344 return true;
345
346 // Domain cookie must have an initial ".". To match, it must be
347 // equal to url's host with initial period removed, or a suffix of
348 // it.
349
350 // Arguably this should only apply to "http" or "https" cookies, but
351 // extension cookie tests currently use the funtionality, and if we
352 // ever decide to implement that it should be done by preventing
353 // such cookies from being set.
354 if (domain_.empty() || domain_[0] != '.')
355 return false;
356
357 // The host with a "." prefixed.
358 if (domain_.compare(1, std::string::npos, host) == 0)
359 return true;
360
361 // A pure suffix of the host (ok since we know the domain already
362 // starts with a ".")
363 return (host.length() > domain_.length() &&
364 host.compare(host.length() - domain_.length(),
365 domain_.length(), domain_) == 0);
366 }
367
368 std::string CanonicalCookie::DebugString() const {
369 return base::StringPrintf(
370 "name: %s value: %s domain: %s path: %s creation: %"
371 PRId64,
372 name_.c_str(), value_.c_str(),
373 domain_.c_str(), path_.c_str(),
374 static_cast<int64>(creation_date_.ToTimeT()));
375 }
376
377 } // namespace
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698