• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
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/parsed_cookie.h"
46 
47 #include "base/logging.h"
48 #include "base/metrics/histogram_macros.h"
49 #include "base/numerics/checked_math.h"
50 #include "base/strings/string_util.h"
51 #include "net/base/features.h"
52 #include "net/cookies/cookie_constants.h"
53 #include "net/cookies/cookie_inclusion_status.h"
54 #include "net/http/http_util.h"
55 
56 namespace {
57 
58 const char kPathTokenName[] = "path";
59 const char kDomainTokenName[] = "domain";
60 const char kExpiresTokenName[] = "expires";
61 const char kMaxAgeTokenName[] = "max-age";
62 const char kSecureTokenName[] = "secure";
63 const char kHttpOnlyTokenName[] = "httponly";
64 const char kSameSiteTokenName[] = "samesite";
65 const char kPriorityTokenName[] = "priority";
66 const char kPartitionedTokenName[] = "partitioned";
67 
68 const char kTerminator[] = "\n\r\0";
69 const int kTerminatorLen = sizeof(kTerminator) - 1;
70 const char kWhitespace[] = " \t";
71 const char kValueSeparator = ';';
72 const char kTokenSeparator[] = ";=";
73 
74 // Returns true if |c| occurs in |chars|
75 // TODO(erikwright): maybe make this take an iterator, could check for end also?
CharIsA(const char c,const char * chars)76 inline bool CharIsA(const char c, const char* chars) {
77   return strchr(chars, c) != nullptr;
78 }
79 
80 // Seek the iterator to the first occurrence of |character|.
81 // Returns true if it hits the end, false otherwise.
SeekToCharacter(std::string_view::iterator * it,const std::string_view::iterator & end,const char character)82 inline bool SeekToCharacter(std::string_view::iterator* it,
83                             const std::string_view::iterator& end,
84                             const char character) {
85   for (; *it != end && **it != character; ++(*it)) {
86   }
87   return *it == end;
88 }
89 
90 // Seek the iterator to the first occurrence of a character in |chars|.
91 // Returns true if it hit the end, false otherwise.
SeekTo(std::string_view::iterator * it,const std::string_view::iterator & end,const char * chars)92 inline bool SeekTo(std::string_view::iterator* it,
93                    const std::string_view::iterator& end,
94                    const char* chars) {
95   for (; *it != end && !CharIsA(**it, chars); ++(*it)) {
96   }
97   return *it == end;
98 }
99 // Seek the iterator to the first occurrence of a character not in |chars|.
100 // Returns true if it hit the end, false otherwise.
SeekPast(std::string_view::iterator * it,const std::string_view::iterator & end,const char * chars)101 inline bool SeekPast(std::string_view::iterator* it,
102                      const std::string_view::iterator& end,
103                      const char* chars) {
104   for (; *it != end && CharIsA(**it, chars); ++(*it)) {
105   }
106   return *it == end;
107 }
SeekBackPast(std::string_view::iterator * it,const std::string_view::iterator & end,const char * chars)108 inline bool SeekBackPast(std::string_view::iterator* it,
109                          const std::string_view::iterator& end,
110                          const char* chars) {
111   for (; *it != end && CharIsA(**it, chars); --(*it)) {
112   }
113   return *it == end;
114 }
115 
116 // Returns the string piece within `value` that is a valid cookie value.
ValidStringPieceForValue(std::string_view value)117 std::string_view ValidStringPieceForValue(std::string_view value) {
118   std::string_view::iterator it = value.begin();
119   std::string_view::iterator end =
120       net::ParsedCookie::FindFirstTerminator(value);
121   std::string_view::iterator value_start;
122   std::string_view::iterator value_end;
123 
124   net::ParsedCookie::ParseValue(&it, end, &value_start, &value_end);
125 
126   return std::string_view(value_start, value_end);
127 }
128 
129 }  // namespace
130 
131 namespace net {
132 
ParsedCookie(std::string_view cookie_line,CookieInclusionStatus * status_out)133 ParsedCookie::ParsedCookie(std::string_view cookie_line,
134                            CookieInclusionStatus* status_out) {
135   // Put a pointer on the stack so the rest of the function can assign to it if
136   // the default nullptr is passed in.
137   CookieInclusionStatus blank_status;
138   if (status_out == nullptr) {
139     status_out = &blank_status;
140   }
141   *status_out = CookieInclusionStatus();
142 
143   ParseTokenValuePairs(cookie_line, *status_out);
144   if (IsValid()) {
145     SetupAttributes();
146   } else {
147     // Status should indicate exclusion if the resulting ParsedCookie is
148     // invalid.
149     CHECK(!status_out->IsInclude());
150   }
151 }
152 
153 ParsedCookie::~ParsedCookie() = default;
154 
IsValid() const155 bool ParsedCookie::IsValid() const {
156   return !pairs_.empty();
157 }
158 
SameSite(CookieSameSiteString * samesite_string) const159 CookieSameSite ParsedCookie::SameSite(
160     CookieSameSiteString* samesite_string) const {
161   CookieSameSite samesite = CookieSameSite::UNSPECIFIED;
162   if (same_site_index_ != 0) {
163     samesite = StringToCookieSameSite(pairs_[same_site_index_].second,
164                                       samesite_string);
165   } else if (samesite_string) {
166     *samesite_string = CookieSameSiteString::kUnspecified;
167   }
168   return samesite;
169 }
170 
Priority() const171 CookiePriority ParsedCookie::Priority() const {
172   return (priority_index_ == 0)
173              ? COOKIE_PRIORITY_DEFAULT
174              : StringToCookiePriority(pairs_[priority_index_].second);
175 }
176 
SetName(const std::string & name)177 bool ParsedCookie::SetName(const std::string& name) {
178   const std::string& value = pairs_.empty() ? "" : pairs_[0].second;
179 
180   // Ensure there are no invalid characters in `name`. This should be done
181   // before calling ParseTokenString because we want terminating characters
182   // ('\r', '\n', and '\0') and '=' in `name` to cause a rejection instead of
183   // truncation.
184   // TODO(crbug.com/40191620) Once we change logic more broadly to reject
185   // cookies containing these characters, we should be able to simplify this
186   // logic since IsValidCookieNameValuePair() also calls IsValidCookieName().
187   // Also, this check will currently fail if `name` has a tab character in the
188   // leading or trailing whitespace, which is inconsistent with what happens
189   // when parsing a cookie line in the constructor (but the old logic for
190   // SetName() behaved this way as well).
191   if (!IsValidCookieName(name)) {
192     return false;
193   }
194 
195   // Use the same whitespace trimming code as the constructor.
196   const std::string& parsed_name = ParseTokenString(name);
197 
198   if (!IsValidCookieNameValuePair(parsed_name, value)) {
199     return false;
200   }
201 
202   if (pairs_.empty())
203     pairs_.emplace_back("", "");
204   pairs_[0].first = parsed_name;
205 
206   return true;
207 }
208 
SetValue(const std::string & value)209 bool ParsedCookie::SetValue(const std::string& value) {
210   const std::string& name = pairs_.empty() ? "" : pairs_[0].first;
211 
212   // Ensure there are no invalid characters in `value`. This should be done
213   // before calling ParseValueString because we want terminating characters
214   // ('\r', '\n', and '\0') in `value` to cause a rejection instead of
215   // truncation.
216   // TODO(crbug.com/40191620) Once we change logic more broadly to reject
217   // cookies containing these characters, we should be able to simplify this
218   // logic since IsValidCookieNameValuePair() also calls IsValidCookieValue().
219   // Also, this check will currently fail if `value` has a tab character in
220   // the leading or trailing whitespace, which is inconsistent with what
221   // happens when parsing a cookie line in the constructor (but the old logic
222   // for SetValue() behaved this way as well).
223   if (!IsValidCookieValue(value)) {
224     return false;
225   }
226 
227   // Use the same whitespace trimming code as the constructor.
228   const std::string& parsed_value = ParseValueString(value);
229 
230   if (!IsValidCookieNameValuePair(name, parsed_value)) {
231     return false;
232   }
233   if (pairs_.empty())
234     pairs_.emplace_back("", "");
235   pairs_[0].second = parsed_value;
236 
237   return true;
238 }
239 
SetPath(const std::string & path)240 bool ParsedCookie::SetPath(const std::string& path) {
241   return SetString(&path_index_, kPathTokenName, path);
242 }
243 
SetDomain(const std::string & domain)244 bool ParsedCookie::SetDomain(const std::string& domain) {
245   return SetString(&domain_index_, kDomainTokenName, domain);
246 }
247 
SetExpires(const std::string & expires)248 bool ParsedCookie::SetExpires(const std::string& expires) {
249   return SetString(&expires_index_, kExpiresTokenName, expires);
250 }
251 
SetMaxAge(const std::string & maxage)252 bool ParsedCookie::SetMaxAge(const std::string& maxage) {
253   return SetString(&maxage_index_, kMaxAgeTokenName, maxage);
254 }
255 
SetIsSecure(bool is_secure)256 bool ParsedCookie::SetIsSecure(bool is_secure) {
257   return SetBool(&secure_index_, kSecureTokenName, is_secure);
258 }
259 
SetIsHttpOnly(bool is_http_only)260 bool ParsedCookie::SetIsHttpOnly(bool is_http_only) {
261   return SetBool(&httponly_index_, kHttpOnlyTokenName, is_http_only);
262 }
263 
SetSameSite(const std::string & same_site)264 bool ParsedCookie::SetSameSite(const std::string& same_site) {
265   return SetString(&same_site_index_, kSameSiteTokenName, same_site);
266 }
267 
SetPriority(const std::string & priority)268 bool ParsedCookie::SetPriority(const std::string& priority) {
269   return SetString(&priority_index_, kPriorityTokenName, priority);
270 }
271 
SetIsPartitioned(bool is_partitioned)272 bool ParsedCookie::SetIsPartitioned(bool is_partitioned) {
273   return SetBool(&partitioned_index_, kPartitionedTokenName, is_partitioned);
274 }
275 
ToCookieLine() const276 std::string ParsedCookie::ToCookieLine() const {
277   std::string out;
278   for (auto it = pairs_.begin(); it != pairs_.end(); ++it) {
279     if (!out.empty())
280       out.append("; ");
281     out.append(it->first);
282     // Determine whether to emit the pair's value component. We should always
283     // print it for the first pair(see crbug.com/977619). After the first pair,
284     // we need to consider whether the name component is a special token.
285     if (it == pairs_.begin() ||
286         (it->first != kSecureTokenName && it->first != kHttpOnlyTokenName &&
287          it->first != kPartitionedTokenName)) {
288       out.append("=");
289       out.append(it->second);
290     }
291   }
292   return out;
293 }
294 
295 // static
FindFirstTerminator(std::string_view s)296 std::string_view::iterator ParsedCookie::FindFirstTerminator(
297     std::string_view s) {
298   std::string_view::iterator end = s.end();
299   size_t term_pos =
300       s.find_first_of(std::string_view(kTerminator, kTerminatorLen));
301   if (term_pos != std::string_view::npos) {
302     // We found a character we should treat as an end of string.
303     end = s.begin() + term_pos;
304   }
305   return end;
306 }
307 
308 // static
ParseToken(std::string_view::iterator * it,const std::string_view::iterator & end,std::string_view::iterator * token_start,std::string_view::iterator * token_end)309 bool ParsedCookie::ParseToken(std::string_view::iterator* it,
310                               const std::string_view::iterator& end,
311                               std::string_view::iterator* token_start,
312                               std::string_view::iterator* token_end) {
313   DCHECK(it && token_start && token_end);
314   std::string_view::iterator token_real_end;
315 
316   // Seek past any whitespace before the "token" (the name).
317   // token_start should point at the first character in the token
318   if (SeekPast(it, end, kWhitespace))
319     return false;  // No token, whitespace or empty.
320   *token_start = *it;
321 
322   // Seek over the token, to the token separator.
323   // token_real_end should point at the token separator, i.e. '='.
324   // If it == end after the seek, we probably have a token-value.
325   SeekTo(it, end, kTokenSeparator);
326   token_real_end = *it;
327 
328   // Ignore any whitespace between the token and the token separator.
329   // token_end should point after the last interesting token character,
330   // pointing at either whitespace, or at '=' (and equal to token_real_end).
331   if (*it != *token_start) {  // We could have an empty token name.
332     --(*it);                  // Go back before the token separator.
333     // Skip over any whitespace to the first non-whitespace character.
334     SeekBackPast(it, *token_start, kWhitespace);
335     // Point after it.
336     ++(*it);
337   }
338   *token_end = *it;
339 
340   // Seek us back to the end of the token.
341   *it = token_real_end;
342   return true;
343 }
344 
345 // static
ParseValue(std::string_view::iterator * it,const std::string_view::iterator & end,std::string_view::iterator * value_start,std::string_view::iterator * value_end)346 void ParsedCookie::ParseValue(std::string_view::iterator* it,
347                               const std::string_view::iterator& end,
348                               std::string_view::iterator* value_start,
349                               std::string_view::iterator* value_end) {
350   DCHECK(it && value_start && value_end);
351 
352   // Seek past any whitespace that might be in-between the token and value.
353   SeekPast(it, end, kWhitespace);
354   // value_start should point at the first character of the value.
355   *value_start = *it;
356 
357   // Just look for ';' to terminate ('=' allowed).
358   // We can hit the end, maybe they didn't terminate.
359   SeekToCharacter(it, end, kValueSeparator);
360 
361   // Will point at the ; separator or the end.
362   *value_end = *it;
363 
364   // Ignore any unwanted whitespace after the value.
365   if (*value_end != *value_start) {  // Could have an empty value
366     --(*value_end);
367     // Skip over any whitespace to the first non-whitespace character.
368     SeekBackPast(value_end, *value_start, kWhitespace);
369     // Point after it.
370     ++(*value_end);
371   }
372 }
373 
374 // static
ParseTokenString(std::string_view token)375 std::string ParsedCookie::ParseTokenString(std::string_view token) {
376   std::string_view::iterator it = token.begin();
377   std::string_view::iterator end = FindFirstTerminator(token);
378 
379   std::string_view::iterator token_start, token_end;
380   if (ParseToken(&it, end, &token_start, &token_end))
381     return std::string(token_start, token_end);
382   return std::string();
383 }
384 
385 // static
ParseValueString(std::string_view value)386 std::string ParsedCookie::ParseValueString(std::string_view value) {
387   return std::string(ValidStringPieceForValue(value));
388 }
389 
390 // static
ValueMatchesParsedValue(const std::string & value)391 bool ParsedCookie::ValueMatchesParsedValue(const std::string& value) {
392   // ValidStringPieceForValue() returns a valid substring of |value|.
393   // If |value| can be fully parsed the result will have the same length
394   // as |value|.
395   return ValidStringPieceForValue(value).length() == value.length();
396 }
397 
398 // static
IsValidCookieName(const std::string & name)399 bool ParsedCookie::IsValidCookieName(const std::string& name) {
400   // IsValidCookieName() returns whether a string matches the following
401   // grammar:
402   //
403   // cookie-name       = *cookie-name-octet
404   // cookie-name-octet = %x20-3A / %x3C / %x3E-7E / %x80-FF
405   //                       ; octets excluding CTLs, ";", and "="
406   //
407   // This can be used to determine whether cookie names and cookie attribute
408   // names contain any invalid characters.
409   //
410   // Note that RFC6265bis section 4.1.1 suggests a stricter grammar for
411   // parsing cookie names, but we choose to allow a wider range of characters
412   // than what's allowed by that grammar (while still conforming to the
413   // requirements of the parsing algorithm defined in section 5.2).
414   //
415   // For reference, see:
416   //  - https://crbug.com/238041
417   for (char i : name) {
418     if (HttpUtil::IsControlChar(i) || i == ';' || i == '=')
419       return false;
420   }
421   return true;
422 }
423 
424 // static
IsValidCookieValue(const std::string & value)425 bool ParsedCookie::IsValidCookieValue(const std::string& value) {
426   // IsValidCookieValue() returns whether a string matches the following
427   // grammar:
428   //
429   // cookie-value       = *cookie-value-octet
430   // cookie-value-octet = %x20-3A / %x3C-7E / %x80-FF
431   //                       ; octets excluding CTLs and ";"
432   //
433   // This can be used to determine whether cookie values contain any invalid
434   // characters.
435   //
436   // Note that RFC6265bis section 4.1.1 suggests a stricter grammar for
437   // parsing cookie values, but we choose to allow a wider range of characters
438   // than what's allowed by that grammar (while still conforming to the
439   // requirements of the parsing algorithm defined in section 5.2).
440   //
441   // For reference, see:
442   //  - https://crbug.com/238041
443   for (char i : value) {
444     if (HttpUtil::IsControlChar(i) || i == ';')
445       return false;
446   }
447   return true;
448 }
449 
450 // static
CookieAttributeValueHasValidCharSet(const std::string & value)451 bool ParsedCookie::CookieAttributeValueHasValidCharSet(
452     const std::string& value) {
453   // A cookie attribute value has the same character set restrictions as cookie
454   // values, so re-use the validation function for that.
455   return IsValidCookieValue(value);
456 }
457 
458 // static
CookieAttributeValueHasValidSize(const std::string & value)459 bool ParsedCookie::CookieAttributeValueHasValidSize(const std::string& value) {
460   return (value.size() <= kMaxCookieAttributeValueSize);
461 }
462 
463 // static
IsValidCookieNameValuePair(const std::string & name,const std::string & value,CookieInclusionStatus * status_out)464 bool ParsedCookie::IsValidCookieNameValuePair(
465     const std::string& name,
466     const std::string& value,
467     CookieInclusionStatus* status_out) {
468   // Ignore cookies with neither name nor value.
469   if (name.empty() && value.empty()) {
470     if (status_out != nullptr) {
471       status_out->AddExclusionReason(
472           CookieInclusionStatus::EXCLUDE_NO_COOKIE_CONTENT);
473     }
474     // TODO(crbug.com/40189703) Note - if the exclusion reasons change to no
475     // longer be the same, we'll need to not return right away and evaluate all
476     // of the checks.
477     return false;
478   }
479 
480   // Enforce a length limit for name + value per RFC6265bis.
481   base::CheckedNumeric<size_t> name_value_pair_size = name.size();
482   name_value_pair_size += value.size();
483   if (!name_value_pair_size.IsValid() ||
484       (name_value_pair_size.ValueOrDie() > kMaxCookieNamePlusValueSize)) {
485     if (status_out != nullptr) {
486       status_out->AddExclusionReason(
487           CookieInclusionStatus::EXCLUDE_NAME_VALUE_PAIR_EXCEEDS_MAX_SIZE);
488     }
489     return false;
490   }
491 
492   // Ignore Set-Cookie directives containing control characters. See
493   // http://crbug.com/238041.
494   if (!IsValidCookieName(name) || !IsValidCookieValue(value)) {
495     if (status_out != nullptr) {
496       status_out->AddExclusionReason(
497           CookieInclusionStatus::EXCLUDE_DISALLOWED_CHARACTER);
498     }
499     return false;
500   }
501   return true;
502 }
503 
504 // Parse all token/value pairs and populate pairs_.
ParseTokenValuePairs(std::string_view cookie_line,CookieInclusionStatus & status_out)505 void ParsedCookie::ParseTokenValuePairs(std::string_view cookie_line,
506                                         CookieInclusionStatus& status_out) {
507   pairs_.clear();
508 
509   // Ok, here we go.  We should be expecting to be starting somewhere
510   // before the cookie line, not including any header name...
511   std::string_view::iterator start = cookie_line.begin();
512   std::string_view::iterator it = start;
513 
514   // TODO(erikwright): Make sure we're stripping \r\n in the network code.
515   // Then we can log any unexpected terminators.
516   std::string_view::iterator end = FindFirstTerminator(cookie_line);
517 
518   // Block cookies that were truncated by control characters.
519   if (end < cookie_line.end()) {
520     status_out.AddExclusionReason(
521         CookieInclusionStatus::EXCLUDE_DISALLOWED_CHARACTER);
522     return;
523   }
524 
525   // Exit early for an empty cookie string.
526   if (it == end) {
527     status_out.AddExclusionReason(
528         CookieInclusionStatus::EXCLUDE_NO_COOKIE_CONTENT);
529     return;
530   }
531 
532   for (int pair_num = 0; it != end; ++pair_num) {
533     TokenValuePair pair;
534 
535     std::string_view::iterator token_start, token_end;
536     if (!ParseToken(&it, end, &token_start, &token_end)) {
537       // Allow first token to be treated as empty-key if unparsable
538       if (pair_num != 0)
539         break;
540 
541       // If parsing failed, start the value parsing at the very beginning.
542       token_start = start;
543     }
544 
545     if (it == end || *it != '=') {
546       // We have a token-value, we didn't have any token name.
547       if (pair_num == 0) {
548         // For the first time around, we want to treat single values
549         // as a value with an empty name. (Mozilla bug 169091).
550         // IE seems to also have this behavior, ex "AAA", and "AAA=10" will
551         // set 2 different cookies, and setting "BBB" will then replace "AAA".
552         pair.first = "";
553         // Rewind to the beginning of what we thought was the token name,
554         // and let it get parsed as a value.
555         it = token_start;
556       } else {
557         // Any not-first attribute we want to treat a value as a
558         // name with an empty value...  This is so something like
559         // "secure;" will get parsed as a Token name, and not a value.
560         pair.first = std::string(token_start, token_end);
561       }
562     } else {
563       // We have a TOKEN=VALUE.
564       pair.first = std::string(token_start, token_end);
565       ++it;  // Skip past the '='.
566     }
567 
568     // OK, now try to parse a value.
569     std::string_view::iterator value_start, value_end;
570     ParseValue(&it, end, &value_start, &value_end);
571 
572     // OK, we're finished with a Token/Value.
573     pair.second = std::string(value_start, value_end);
574 
575     // For metrics, check if either the name or value contain an internal HTAB
576     // (0x9). That is, not leading or trailing.
577     if (pair_num == 0 &&
578         (pair.first.find_first_of("\t") != std::string::npos ||
579          pair.second.find_first_of("\t") != std::string::npos)) {
580       internal_htab_ = true;
581     }
582 
583     bool ignore_pair = false;
584     if (pair_num == 0) {
585       if (!IsValidCookieNameValuePair(pair.first, pair.second, &status_out)) {
586         pairs_.clear();
587         break;
588       }
589     } else {
590       // From RFC2109: "Attributes (names) (attr) are case-insensitive."
591       pair.first = base::ToLowerASCII(pair.first);
592 
593       // Attribute names have the same character set limitations as cookie
594       // names, but only a handful of values are allowed. We don't check that
595       // this attribute name is one of the allowed ones here, so just re-use
596       // the cookie name check.
597       if (!IsValidCookieName(pair.first)) {
598         status_out.AddExclusionReason(
599             CookieInclusionStatus::EXCLUDE_DISALLOWED_CHARACTER);
600         pairs_.clear();
601         break;
602       }
603 
604       if (!CookieAttributeValueHasValidCharSet(pair.second)) {
605         // If the attribute value contains invalid characters, the whole
606         // cookie should be ignored.
607         status_out.AddExclusionReason(
608             CookieInclusionStatus::EXCLUDE_DISALLOWED_CHARACTER);
609         pairs_.clear();
610         break;
611       }
612 
613       if (!CookieAttributeValueHasValidSize(pair.second)) {
614         // If the attribute value is too large, it should be ignored.
615         ignore_pair = true;
616         status_out.AddWarningReason(
617             CookieInclusionStatus::WARN_ATTRIBUTE_VALUE_EXCEEDS_MAX_SIZE);
618       }
619     }
620 
621     if (!ignore_pair) {
622       pairs_.emplace_back(std::move(pair));
623     }
624 
625     // We've processed a token/value pair, we're either at the end of
626     // the string or a ValueSeparator like ';', which we want to skip.
627     if (it != end)
628       ++it;
629   }
630 }
631 
SetupAttributes()632 void ParsedCookie::SetupAttributes() {
633   // We skip over the first token/value, the user supplied one.
634   for (size_t i = 1; i < pairs_.size(); ++i) {
635     if (pairs_[i].first == kPathTokenName) {
636       path_index_ = i;
637     } else if (pairs_[i].first == kDomainTokenName) {
638       domain_index_ = i;
639     } else if (pairs_[i].first == kExpiresTokenName) {
640       expires_index_ = i;
641     } else if (pairs_[i].first == kMaxAgeTokenName) {
642       maxage_index_ = i;
643     } else if (pairs_[i].first == kSecureTokenName) {
644       secure_index_ = i;
645     } else if (pairs_[i].first == kHttpOnlyTokenName) {
646       httponly_index_ = i;
647     } else if (pairs_[i].first == kSameSiteTokenName) {
648       same_site_index_ = i;
649     } else if (pairs_[i].first == kPriorityTokenName) {
650       priority_index_ = i;
651     } else if (pairs_[i].first == kPartitionedTokenName) {
652       partitioned_index_ = i;
653     } else {
654       /* some attribute we don't know or don't care about. */
655     }
656   }
657 }
658 
SetString(size_t * index,const std::string & key,const std::string & untrusted_value)659 bool ParsedCookie::SetString(size_t* index,
660                              const std::string& key,
661                              const std::string& untrusted_value) {
662   // This function should do equivalent input validation to the
663   // constructor. Otherwise, the Set* functions can put this ParsedCookie in a
664   // state where parsing the output of ToCookieLine() produces a different
665   // ParsedCookie.
666   //
667   // Without input validation, invoking pc.SetPath(" baz ") would result in
668   // pc.ToCookieLine() == "path= baz ". Parsing the "path= baz " string would
669   // produce a cookie with "path" attribute equal to "baz" (no spaces). We
670   // should not produce cookie lines that parse to different key/value pairs!
671 
672   // Inputs containing invalid characters or attribute value strings that are
673   // too large should be ignored. Note that we check the attribute value size
674   // after removing leading and trailing whitespace.
675   if (!CookieAttributeValueHasValidCharSet(untrusted_value))
676     return false;
677 
678   // Use the same whitespace trimming code as the constructor.
679   const std::string parsed_value = ParseValueString(untrusted_value);
680 
681   if (!CookieAttributeValueHasValidSize(parsed_value))
682     return false;
683 
684   if (parsed_value.empty()) {
685     ClearAttributePair(*index);
686     return true;
687   } else {
688     return SetAttributePair(index, key, parsed_value);
689   }
690 }
691 
SetBool(size_t * index,const std::string & key,bool value)692 bool ParsedCookie::SetBool(size_t* index, const std::string& key, bool value) {
693   if (!value) {
694     ClearAttributePair(*index);
695     return true;
696   } else {
697     return SetAttributePair(index, key, std::string());
698   }
699 }
700 
SetAttributePair(size_t * index,const std::string & key,const std::string & value)701 bool ParsedCookie::SetAttributePair(size_t* index,
702                                     const std::string& key,
703                                     const std::string& value) {
704   if (!HttpUtil::IsToken(key))
705     return false;
706   if (!IsValid())
707     return false;
708   if (*index) {
709     pairs_[*index].second = value;
710   } else {
711     pairs_.emplace_back(key, value);
712     *index = pairs_.size() - 1;
713   }
714   return true;
715 }
716 
ClearAttributePair(size_t index)717 void ParsedCookie::ClearAttributePair(size_t index) {
718   // The first pair (name/value of cookie at pairs_[0]) cannot be cleared.
719   // Cookie attributes that don't have a value at the moment, are
720   // represented with an index being equal to 0.
721   if (index == 0)
722     return;
723 
724   size_t* indexes[] = {
725       &path_index_,      &domain_index_,   &expires_index_,
726       &maxage_index_,    &secure_index_,   &httponly_index_,
727       &same_site_index_, &priority_index_, &partitioned_index_};
728   for (size_t* attribute_index : indexes) {
729     if (*attribute_index == index)
730       *attribute_index = 0;
731     else if (*attribute_index > index)
732       --(*attribute_index);
733   }
734   pairs_.erase(pairs_.begin() + index);
735 }
736 
737 }  // namespace net
738