xref: /aosp_15_r20/external/cronet/net/cookies/parsed_cookie.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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 ([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/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::const_iterator * it,const std::string::const_iterator & end,const char character)82 inline bool SeekToCharacter(std::string::const_iterator* it,
83                             const std::string::const_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::const_iterator * it,const std::string::const_iterator & end,const char * chars)92 inline bool SeekTo(std::string::const_iterator* it,
93                    const std::string::const_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::const_iterator * it,const std::string::const_iterator & end,const char * chars)101 inline bool SeekPast(std::string::const_iterator* it,
102                      const std::string::const_iterator& end,
103                      const char* chars) {
104   for (; *it != end && CharIsA(**it, chars); ++(*it)) {
105   }
106   return *it == end;
107 }
SeekBackPast(std::string::const_iterator * it,const std::string::const_iterator & end,const char * chars)108 inline bool SeekBackPast(std::string::const_iterator* it,
109                          const std::string::const_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(const std::string & value)117 std::string_view ValidStringPieceForValue(const std::string& value) {
118   std::string::const_iterator it = value.begin();
119   std::string::const_iterator end =
120       net::ParsedCookie::FindFirstTerminator(value);
121   std::string::const_iterator value_start;
122   std::string::const_iterator value_end;
123 
124   net::ParsedCookie::ParseValue(&it, end, &value_start, &value_end);
125 
126   return base::MakeStringPiece(value_start, value_end);
127 }
128 
129 }  // namespace
130 
131 namespace net {
132 
ParsedCookie(const std::string & cookie_line,bool block_truncated,CookieInclusionStatus * status_out)133 ParsedCookie::ParsedCookie(const std::string& cookie_line,
134                            bool block_truncated,
135                            CookieInclusionStatus* status_out) {
136   // Put a pointer on the stack so the rest of the function can assign to it if
137   // the default nullptr is passed in.
138   CookieInclusionStatus blank_status;
139   if (status_out == nullptr) {
140     status_out = &blank_status;
141   }
142   *status_out = CookieInclusionStatus();
143 
144   ParseTokenValuePairs(cookie_line, block_truncated, *status_out);
145   if (IsValid()) {
146     SetupAttributes();
147   } else {
148     // Status should indicate exclusion if the resulting ParsedCookie is
149     // invalid.
150     CHECK(!status_out->IsInclude());
151   }
152 }
153 
154 ParsedCookie::~ParsedCookie() = default;
155 
IsValid() const156 bool ParsedCookie::IsValid() const {
157   return !pairs_.empty();
158 }
159 
SameSite(CookieSameSiteString * samesite_string) const160 CookieSameSite ParsedCookie::SameSite(
161     CookieSameSiteString* samesite_string) const {
162   CookieSameSite samesite = CookieSameSite::UNSPECIFIED;
163   if (same_site_index_ != 0) {
164     samesite = StringToCookieSameSite(pairs_[same_site_index_].second,
165                                       samesite_string);
166   } else if (samesite_string) {
167     *samesite_string = CookieSameSiteString::kUnspecified;
168   }
169   return samesite;
170 }
171 
Priority() const172 CookiePriority ParsedCookie::Priority() const {
173   return (priority_index_ == 0)
174              ? COOKIE_PRIORITY_DEFAULT
175              : StringToCookiePriority(pairs_[priority_index_].second);
176 }
177 
SetName(const std::string & name)178 bool ParsedCookie::SetName(const std::string& name) {
179   const std::string& value = pairs_.empty() ? "" : pairs_[0].second;
180 
181   // Ensure there are no invalid characters in `name`. This should be done
182   // before calling ParseTokenString because we want terminating characters
183   // ('\r', '\n', and '\0') and '=' in `name` to cause a rejection instead of
184   // truncation.
185   // TODO(crbug.com/1233602) Once we change logic more broadly to reject
186   // cookies containing these characters, we should be able to simplify this
187   // logic since IsValidCookieNameValuePair() also calls IsValidCookieName().
188   // Also, this check will currently fail if `name` has a tab character in the
189   // leading or trailing whitespace, which is inconsistent with what happens
190   // when parsing a cookie line in the constructor (but the old logic for
191   // SetName() behaved this way as well).
192   if (!IsValidCookieName(name)) {
193     return false;
194   }
195 
196   // Use the same whitespace trimming code as the constructor.
197   const std::string& parsed_name = ParseTokenString(name);
198 
199   if (!IsValidCookieNameValuePair(parsed_name, value)) {
200     return false;
201   }
202 
203   if (pairs_.empty())
204     pairs_.emplace_back("", "");
205   pairs_[0].first = parsed_name;
206 
207   return true;
208 }
209 
SetValue(const std::string & value)210 bool ParsedCookie::SetValue(const std::string& value) {
211   const std::string& name = pairs_.empty() ? "" : pairs_[0].first;
212 
213   // Ensure there are no invalid characters in `value`. This should be done
214   // before calling ParseValueString because we want terminating characters
215   // ('\r', '\n', and '\0') in `value` to cause a rejection instead of
216   // truncation.
217   // TODO(crbug.com/1233602) Once we change logic more broadly to reject
218   // cookies containing these characters, we should be able to simplify this
219   // logic since IsValidCookieNameValuePair() also calls IsValidCookieValue().
220   // Also, this check will currently fail if `value` has a tab character in
221   // the leading or trailing whitespace, which is inconsistent with what
222   // happens when parsing a cookie line in the constructor (but the old logic
223   // for SetValue() behaved this way as well).
224   if (!IsValidCookieValue(value)) {
225     return false;
226   }
227 
228   // Use the same whitespace trimming code as the constructor.
229   const std::string& parsed_value = ParseValueString(value);
230 
231   if (!IsValidCookieNameValuePair(name, parsed_value)) {
232     return false;
233   }
234   if (pairs_.empty())
235     pairs_.emplace_back("", "");
236   pairs_[0].second = parsed_value;
237 
238   return true;
239 }
240 
SetPath(const std::string & path)241 bool ParsedCookie::SetPath(const std::string& path) {
242   return SetString(&path_index_, kPathTokenName, path);
243 }
244 
SetDomain(const std::string & domain)245 bool ParsedCookie::SetDomain(const std::string& domain) {
246   return SetString(&domain_index_, kDomainTokenName, domain);
247 }
248 
SetExpires(const std::string & expires)249 bool ParsedCookie::SetExpires(const std::string& expires) {
250   return SetString(&expires_index_, kExpiresTokenName, expires);
251 }
252 
SetMaxAge(const std::string & maxage)253 bool ParsedCookie::SetMaxAge(const std::string& maxage) {
254   return SetString(&maxage_index_, kMaxAgeTokenName, maxage);
255 }
256 
SetIsSecure(bool is_secure)257 bool ParsedCookie::SetIsSecure(bool is_secure) {
258   return SetBool(&secure_index_, kSecureTokenName, is_secure);
259 }
260 
SetIsHttpOnly(bool is_http_only)261 bool ParsedCookie::SetIsHttpOnly(bool is_http_only) {
262   return SetBool(&httponly_index_, kHttpOnlyTokenName, is_http_only);
263 }
264 
SetSameSite(const std::string & same_site)265 bool ParsedCookie::SetSameSite(const std::string& same_site) {
266   return SetString(&same_site_index_, kSameSiteTokenName, same_site);
267 }
268 
SetPriority(const std::string & priority)269 bool ParsedCookie::SetPriority(const std::string& priority) {
270   return SetString(&priority_index_, kPriorityTokenName, priority);
271 }
272 
SetIsPartitioned(bool is_partitioned)273 bool ParsedCookie::SetIsPartitioned(bool is_partitioned) {
274   return SetBool(&partitioned_index_, kPartitionedTokenName, is_partitioned);
275 }
276 
ToCookieLine() const277 std::string ParsedCookie::ToCookieLine() const {
278   std::string out;
279   for (auto it = pairs_.begin(); it != pairs_.end(); ++it) {
280     if (!out.empty())
281       out.append("; ");
282     out.append(it->first);
283     // Determine whether to emit the pair's value component. We should always
284     // print it for the first pair(see crbug.com/977619). After the first pair,
285     // we need to consider whether the name component is a special token.
286     if (it == pairs_.begin() ||
287         (it->first != kSecureTokenName && it->first != kHttpOnlyTokenName &&
288          it->first != kPartitionedTokenName)) {
289       out.append("=");
290       out.append(it->second);
291     }
292   }
293   return out;
294 }
295 
296 // static
FindFirstTerminator(const std::string & s)297 std::string::const_iterator ParsedCookie::FindFirstTerminator(
298     const std::string& s) {
299   std::string::const_iterator end = s.end();
300   size_t term_pos = s.find_first_of(std::string(kTerminator, kTerminatorLen));
301   if (term_pos != std::string::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::const_iterator * it,const std::string::const_iterator & end,std::string::const_iterator * token_start,std::string::const_iterator * token_end)309 bool ParsedCookie::ParseToken(std::string::const_iterator* it,
310                               const std::string::const_iterator& end,
311                               std::string::const_iterator* token_start,
312                               std::string::const_iterator* token_end) {
313   DCHECK(it && token_start && token_end);
314   std::string::const_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::const_iterator * it,const std::string::const_iterator & end,std::string::const_iterator * value_start,std::string::const_iterator * value_end)346 void ParsedCookie::ParseValue(std::string::const_iterator* it,
347                               const std::string::const_iterator& end,
348                               std::string::const_iterator* value_start,
349                               std::string::const_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(const std::string & token)375 std::string ParsedCookie::ParseTokenString(const std::string& token) {
376   std::string::const_iterator it = token.begin();
377   std::string::const_iterator end = FindFirstTerminator(token);
378 
379   std::string::const_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(const std::string & value)386 std::string ParsedCookie::ParseValueString(const std::string& 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/1228815) 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(const std::string & cookie_line,bool block_truncated,CookieInclusionStatus & status_out)505 void ParsedCookie::ParseTokenValuePairs(const std::string& cookie_line,
506                                         bool block_truncated,
507                                         CookieInclusionStatus& status_out) {
508   pairs_.clear();
509 
510   // Ok, here we go.  We should be expecting to be starting somewhere
511   // before the cookie line, not including any header name...
512   std::string::const_iterator start = cookie_line.begin();
513   std::string::const_iterator it = start;
514 
515   // TODO(erikwright): Make sure we're stripping \r\n in the network code.
516   // Then we can log any unexpected terminators.
517   std::string::const_iterator end = FindFirstTerminator(cookie_line);
518 
519   // For metrics on truncating character presence in the cookie line.
520   if (end < cookie_line.end()) {
521     switch (*end) {
522       case '\0':
523         truncating_char_in_cookie_string_type_ =
524             TruncatingCharacterInCookieStringType::kTruncatingCharNull;
525         break;
526       case '\r':
527         truncating_char_in_cookie_string_type_ =
528             TruncatingCharacterInCookieStringType::kTruncatingCharNewline;
529         break;
530       case '\n':
531         truncating_char_in_cookie_string_type_ =
532             TruncatingCharacterInCookieStringType::kTruncatingCharLineFeed;
533         break;
534       default:
535         NOTREACHED();
536     }
537     if (block_truncated &&
538         base::FeatureList::IsEnabled(net::features::kBlockTruncatedCookies)) {
539       status_out.AddExclusionReason(
540           CookieInclusionStatus::EXCLUDE_DISALLOWED_CHARACTER);
541       return;
542     }
543   }
544 
545   // Exit early for an empty cookie string.
546   if (it == end) {
547     status_out.AddExclusionReason(
548         CookieInclusionStatus::EXCLUDE_NO_COOKIE_CONTENT);
549     return;
550   }
551 
552   for (int pair_num = 0; it != end; ++pair_num) {
553     TokenValuePair pair;
554 
555     std::string::const_iterator token_start, token_end;
556     if (!ParseToken(&it, end, &token_start, &token_end)) {
557       // Allow first token to be treated as empty-key if unparsable
558       if (pair_num != 0)
559         break;
560 
561       // If parsing failed, start the value parsing at the very beginning.
562       token_start = start;
563     }
564 
565     if (it == end || *it != '=') {
566       // We have a token-value, we didn't have any token name.
567       if (pair_num == 0) {
568         // For the first time around, we want to treat single values
569         // as a value with an empty name. (Mozilla bug 169091).
570         // IE seems to also have this behavior, ex "AAA", and "AAA=10" will
571         // set 2 different cookies, and setting "BBB" will then replace "AAA".
572         pair.first = "";
573         // Rewind to the beginning of what we thought was the token name,
574         // and let it get parsed as a value.
575         it = token_start;
576       } else {
577         // Any not-first attribute we want to treat a value as a
578         // name with an empty value...  This is so something like
579         // "secure;" will get parsed as a Token name, and not a value.
580         pair.first = std::string(token_start, token_end);
581       }
582     } else {
583       // We have a TOKEN=VALUE.
584       pair.first = std::string(token_start, token_end);
585       ++it;  // Skip past the '='.
586     }
587 
588     // OK, now try to parse a value.
589     std::string::const_iterator value_start, value_end;
590     ParseValue(&it, end, &value_start, &value_end);
591 
592     // OK, we're finished with a Token/Value.
593     pair.second = std::string(value_start, value_end);
594 
595     // For metrics, check if either the name or value contain an internal HTAB
596     // (0x9). That is, not leading or trailing.
597     if (pair_num == 0 &&
598         (pair.first.find_first_of("\t") != std::string::npos ||
599          pair.second.find_first_of("\t") != std::string::npos)) {
600       internal_htab_ = true;
601     }
602 
603     bool ignore_pair = false;
604     if (pair_num == 0) {
605       if (!IsValidCookieNameValuePair(pair.first, pair.second, &status_out)) {
606         pairs_.clear();
607         break;
608       }
609     } else {
610       // From RFC2109: "Attributes (names) (attr) are case-insensitive."
611       pair.first = base::ToLowerASCII(pair.first);
612 
613       // Attribute names have the same character set limitations as cookie
614       // names, but only a handful of values are allowed. We don't check that
615       // this attribute name is one of the allowed ones here, so just re-use
616       // the cookie name check.
617       if (!IsValidCookieName(pair.first)) {
618         status_out.AddExclusionReason(
619             CookieInclusionStatus::EXCLUDE_DISALLOWED_CHARACTER);
620         pairs_.clear();
621         break;
622       }
623 
624       if (!CookieAttributeValueHasValidCharSet(pair.second)) {
625         // If the attribute value contains invalid characters, the whole
626         // cookie should be ignored.
627         status_out.AddExclusionReason(
628             CookieInclusionStatus::EXCLUDE_DISALLOWED_CHARACTER);
629         pairs_.clear();
630         break;
631       }
632 
633       if (!CookieAttributeValueHasValidSize(pair.second)) {
634         // If the attribute value is too large, it should be ignored.
635         ignore_pair = true;
636         status_out.AddWarningReason(
637             CookieInclusionStatus::WARN_ATTRIBUTE_VALUE_EXCEEDS_MAX_SIZE);
638       }
639     }
640 
641     if (!ignore_pair) {
642       pairs_.push_back(pair);
643     }
644 
645     // We've processed a token/value pair, we're either at the end of
646     // the string or a ValueSeparator like ';', which we want to skip.
647     if (it != end)
648       ++it;
649   }
650 }
651 
SetupAttributes()652 void ParsedCookie::SetupAttributes() {
653   // We skip over the first token/value, the user supplied one.
654   for (size_t i = 1; i < pairs_.size(); ++i) {
655     if (pairs_[i].first == kPathTokenName) {
656       path_index_ = i;
657     } else if (pairs_[i].first == kDomainTokenName) {
658       domain_index_ = i;
659     } else if (pairs_[i].first == kExpiresTokenName) {
660       expires_index_ = i;
661     } else if (pairs_[i].first == kMaxAgeTokenName) {
662       maxage_index_ = i;
663     } else if (pairs_[i].first == kSecureTokenName) {
664       secure_index_ = i;
665     } else if (pairs_[i].first == kHttpOnlyTokenName) {
666       httponly_index_ = i;
667     } else if (pairs_[i].first == kSameSiteTokenName) {
668       same_site_index_ = i;
669     } else if (pairs_[i].first == kPriorityTokenName) {
670       priority_index_ = i;
671     } else if (pairs_[i].first == kPartitionedTokenName) {
672       partitioned_index_ = i;
673     } else {
674       /* some attribute we don't know or don't care about. */
675     }
676   }
677 }
678 
SetString(size_t * index,const std::string & key,const std::string & untrusted_value)679 bool ParsedCookie::SetString(size_t* index,
680                              const std::string& key,
681                              const std::string& untrusted_value) {
682   // This function should do equivalent input validation to the
683   // constructor. Otherwise, the Set* functions can put this ParsedCookie in a
684   // state where parsing the output of ToCookieLine() produces a different
685   // ParsedCookie.
686   //
687   // Without input validation, invoking pc.SetPath(" baz ") would result in
688   // pc.ToCookieLine() == "path= baz ". Parsing the "path= baz " string would
689   // produce a cookie with "path" attribute equal to "baz" (no spaces). We
690   // should not produce cookie lines that parse to different key/value pairs!
691 
692   // Inputs containing invalid characters or attribute value strings that are
693   // too large should be ignored. Note that we check the attribute value size
694   // after removing leading and trailing whitespace.
695   if (!CookieAttributeValueHasValidCharSet(untrusted_value))
696     return false;
697 
698   // Use the same whitespace trimming code as the constructor.
699   const std::string parsed_value = ParseValueString(untrusted_value);
700 
701   if (!CookieAttributeValueHasValidSize(parsed_value))
702     return false;
703 
704   if (parsed_value.empty()) {
705     ClearAttributePair(*index);
706     return true;
707   } else {
708     return SetAttributePair(index, key, parsed_value);
709   }
710 }
711 
SetBool(size_t * index,const std::string & key,bool value)712 bool ParsedCookie::SetBool(size_t* index, const std::string& key, bool value) {
713   if (!value) {
714     ClearAttributePair(*index);
715     return true;
716   } else {
717     return SetAttributePair(index, key, std::string());
718   }
719 }
720 
SetAttributePair(size_t * index,const std::string & key,const std::string & value)721 bool ParsedCookie::SetAttributePair(size_t* index,
722                                     const std::string& key,
723                                     const std::string& value) {
724   if (!HttpUtil::IsToken(key))
725     return false;
726   if (!IsValid())
727     return false;
728   if (*index) {
729     pairs_[*index].second = value;
730   } else {
731     pairs_.emplace_back(key, value);
732     *index = pairs_.size() - 1;
733   }
734   return true;
735 }
736 
ClearAttributePair(size_t index)737 void ParsedCookie::ClearAttributePair(size_t index) {
738   // The first pair (name/value of cookie at pairs_[0]) cannot be cleared.
739   // Cookie attributes that don't have a value at the moment, are
740   // represented with an index being equal to 0.
741   if (index == 0)
742     return;
743 
744   size_t* indexes[] = {
745       &path_index_,      &domain_index_,   &expires_index_,
746       &maxage_index_,    &secure_index_,   &httponly_index_,
747       &same_site_index_, &priority_index_, &partitioned_index_};
748   for (size_t* attribute_index : indexes) {
749     if (*attribute_index == index)
750       *attribute_index = 0;
751     else if (*attribute_index > index)
752       --(*attribute_index);
753   }
754   pairs_.erase(pairs_.begin() + index);
755 }
756 
757 }  // namespace net
758