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

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: Addressed comments 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 + (cookie_util::ParseCookieTime(pc.Expires()) - server_time);
207 }
208
209 // Invalid or no expiration, persistent cookie.
210 return Time();
211 }
212
213 void CanonicalCookie::SetSessionCookieExpiryTime() {
214 #if defined(ENABLE_PERSISTENT_SESSION_COOKIES)
215 // Mobile apps can sometimes be shut down without any warning, so the session
216 // cookie has to be persistent and given a default expiration time.
217 expiry_date_ = base::Time::Now() +
218 base::TimeDelta::FromDays(kPersistentSessionCookieExpiryInDays);
219 #endif
220 }
221
222 CanonicalCookie* CanonicalCookie::Create(const GURL& url,
223 const ParsedCookie& pc) {
224 if (!pc.IsValid()) {
225 return NULL;
226 }
227
228 std::string domain_string;
229 if (!GetCookieDomain(url, pc, &domain_string)) {
230 return NULL;
231 }
232 std::string path_string = CanonPath(url, pc);
233 std::string mac_key = pc.HasMACKey() ? pc.MACKey() : std::string();
234 std::string mac_algorithm = pc.HasMACAlgorithm() ?
235 pc.MACAlgorithm() : std::string();
236 Time creation_time = Time::Now();
237 Time expiration_time;
238 if (pc.HasExpires())
239 expiration_time = cookie_util::ParseCookieTime(pc.Expires());
240
241 return (Create(url, pc.Name(), pc.Value(), domain_string, path_string,
242 mac_key, mac_algorithm, creation_time, expiration_time,
243 pc.IsSecure(), pc.IsHttpOnly()));
244 }
245
246 CanonicalCookie* CanonicalCookie::Create(const GURL& url,
247 const std::string& name,
248 const std::string& value,
249 const std::string& domain,
250 const std::string& path,
251 const std::string& mac_key,
252 const std::string& mac_algorithm,
253 const base::Time& creation,
254 const base::Time& expiration,
255 bool secure,
256 bool http_only) {
257 // Expect valid attribute tokens and values, as defined by the ParsedCookie
258 // logic, otherwise don't create the cookie.
259 std::string parsed_name = ParsedCookie::ParseTokenString(name);
260 if (parsed_name != name)
261 return NULL;
262 std::string parsed_value = ParsedCookie::ParseValueString(value);
263 if (parsed_value != value)
264 return NULL;
265
266 std::string parsed_domain = ParsedCookie::ParseValueString(domain);
267 if (parsed_domain != domain)
268 return NULL;
269 std::string cookie_domain;
270 if (!cookie_util::GetCookieDomainWithString(url, parsed_domain,
271 &cookie_domain)) {
272 return NULL;
273 }
274
275 std::string parsed_path = ParsedCookie::ParseValueString(path);
276 if (parsed_path != path)
277 return NULL;
278
279 std::string cookie_path = CanonPathWithString(url, parsed_path);
280 // Expect that the path was either not specified (empty), or is valid.
281 if (!parsed_path.empty() && cookie_path != parsed_path)
282 return NULL;
283 // Canonicalize path again to make sure it escapes characters as needed.
284 url_parse::Component path_component(0, cookie_path.length());
285 url_canon::RawCanonOutputT<char> canon_path;
286 url_parse::Component canon_path_component;
287 url_canon::CanonicalizePath(cookie_path.data(), path_component,
288 &canon_path, &canon_path_component);
289 cookie_path = std::string(canon_path.data() + canon_path_component.begin,
290 canon_path_component.len);
291
292 return new CanonicalCookie(url, parsed_name, parsed_value, cookie_domain,
293 cookie_path, mac_key, mac_algorithm, creation,
294 expiration, creation, secure, http_only);
295 }
296
297 bool CanonicalCookie::IsOnPath(const std::string& url_path) const {
298
299 // A zero length would be unsafe for our trailing '/' checks, and
300 // would also make no sense for our prefix match. The code that
301 // creates a CanonicalCookie should make sure the path is never zero length,
302 // but we double check anyway.
303 if (path_.empty())
304 return false;
305
306 // The Mozilla code broke this into three cases, based on if the cookie path
307 // was longer, the same length, or shorter than the length of the url path.
308 // I think the approach below is simpler.
309
310 // Make sure the cookie path is a prefix of the url path. If the
311 // url path is shorter than the cookie path, then the cookie path
312 // can't be a prefix.
313 if (url_path.find(path_) != 0)
314 return false;
315
316 // Now we know that url_path is >= cookie_path, and that cookie_path
317 // is a prefix of url_path. If they are the are the same length then
318 // they are identical, otherwise we need an additional check:
319
320 // In order to avoid in correctly matching a cookie path of /blah
321 // with a request path of '/blahblah/', we need to make sure that either
322 // the cookie path ends in a trailing '/', or that we prefix up to a '/'
323 // in the url path. Since we know that the url path length is greater
324 // than the cookie path length, it's safe to index one byte past.
325 if (path_.length() != url_path.length() &&
326 path_[path_.length() - 1] != '/' &&
327 url_path[path_.length()] != '/')
328 return false;
329
330 return true;
331 }
332
333 bool CanonicalCookie::IsDomainMatch(const std::string& scheme,
334 const std::string& host) const {
335 // Can domain match in two ways; as a domain cookie (where the cookie
336 // domain begins with ".") or as a host cookie (where it doesn't).
337
338 // Some consumers of the CookieMonster expect to set cookies on
339 // URLs like http://.strange.url. To retrieve cookies in this instance,
340 // we allow matching as a host cookie even when the domain_ starts with
341 // a period.
342 if (host == domain_)
343 return true;
344
345 // Domain cookie must have an initial ".". To match, it must be
346 // equal to url's host with initial period removed, or a suffix of
347 // it.
348
349 // Arguably this should only apply to "http" or "https" cookies, but
350 // extension cookie tests currently use the funtionality, and if we
351 // ever decide to implement that it should be done by preventing
352 // such cookies from being set.
353 if (domain_.empty() || domain_[0] != '.')
354 return false;
355
356 // The host with a "." prefixed.
357 if (domain_.compare(1, std::string::npos, host) == 0)
358 return true;
359
360 // A pure suffix of the host (ok since we know the domain already
361 // starts with a ".")
362 return (host.length() > domain_.length() &&
363 host.compare(host.length() - domain_.length(),
364 domain_.length(), domain_) == 0);
365 }
366
367 std::string CanonicalCookie::DebugString() const {
368 return base::StringPrintf(
369 "name: %s value: %s domain: %s path: %s creation: %"
370 PRId64,
371 name_.c_str(), value_.c_str(),
372 domain_.c_str(), path_.c_str(),
373 static_cast<int64>(creation_date_.ToTimeT()));
374 }
375
376 } // namespace
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698