Revert 254567 "don't create SkDevice directly, use SkBitmap or (..."
[chromium-blink-merge.git] / net / http / http_response_headers.cc
blob0072976ada2e16891a487683d7c2ed1dd214be71
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.
5 // The rules for header parsing were borrowed from Firefox:
6 // http://lxr.mozilla.org/seamonkey/source/netwerk/protocol/http/src/nsHttpResponseHead.cpp
7 // The rules for parsing content-types were also borrowed from Firefox:
8 // http://lxr.mozilla.org/mozilla/source/netwerk/base/src/nsURLHelper.cpp#834
10 #include "net/http/http_response_headers.h"
12 #include <algorithm>
14 #include "base/logging.h"
15 #include "base/metrics/histogram.h"
16 #include "base/pickle.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/string_piece.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/time/time.h"
22 #include "base/values.h"
23 #include "net/base/escape.h"
24 #include "net/http/http_util.h"
26 using base::StringPiece;
27 using base::Time;
28 using base::TimeDelta;
30 namespace net {
32 //-----------------------------------------------------------------------------
34 namespace {
36 // These headers are RFC 2616 hop-by-hop headers;
37 // not to be stored by caches.
38 const char* const kHopByHopResponseHeaders[] = {
39 "connection",
40 "proxy-connection",
41 "keep-alive",
42 "trailer",
43 "transfer-encoding",
44 "upgrade"
47 // These headers are challenge response headers;
48 // not to be stored by caches.
49 const char* const kChallengeResponseHeaders[] = {
50 "www-authenticate",
51 "proxy-authenticate"
54 // These headers are cookie setting headers;
55 // not to be stored by caches or disclosed otherwise.
56 const char* const kCookieResponseHeaders[] = {
57 "set-cookie",
58 "set-cookie2"
61 // By default, do not cache Strict-Transport-Security or Public-Key-Pins.
62 // This avoids erroneously re-processing them on page loads from cache ---
63 // they are defined to be valid only on live and error-free HTTPS
64 // connections.
65 const char* const kSecurityStateHeaders[] = {
66 "strict-transport-security",
67 "public-key-pins"
70 // These response headers are not copied from a 304/206 response to the cached
71 // response headers. This list is based on Mozilla's nsHttpResponseHead.cpp.
72 const char* const kNonUpdatedHeaders[] = {
73 "connection",
74 "proxy-connection",
75 "keep-alive",
76 "www-authenticate",
77 "proxy-authenticate",
78 "trailer",
79 "transfer-encoding",
80 "upgrade",
81 "etag",
82 "x-frame-options",
83 "x-xss-protection",
86 // Some header prefixes mean "Don't copy this header from a 304 response.".
87 // Rather than listing all the relevant headers, we can consolidate them into
88 // this list:
89 const char* const kNonUpdatedHeaderPrefixes[] = {
90 "content-",
91 "x-content-",
92 "x-webkit-"
95 bool ShouldUpdateHeader(const std::string::const_iterator& name_begin,
96 const std::string::const_iterator& name_end) {
97 for (size_t i = 0; i < arraysize(kNonUpdatedHeaders); ++i) {
98 if (LowerCaseEqualsASCII(name_begin, name_end, kNonUpdatedHeaders[i]))
99 return false;
101 for (size_t i = 0; i < arraysize(kNonUpdatedHeaderPrefixes); ++i) {
102 if (StartsWithASCII(std::string(name_begin, name_end),
103 kNonUpdatedHeaderPrefixes[i], false))
104 return false;
106 return true;
109 void CheckDoesNotHaveEmbededNulls(const std::string& str) {
110 // Care needs to be taken when adding values to the raw headers string to
111 // make sure it does not contain embeded NULLs. Any embeded '\0' may be
112 // understood as line terminators and change how header lines get tokenized.
113 CHECK(str.find('\0') == std::string::npos);
116 bool ShouldShowHttpHeaderValue(const std::string& header_name) {
117 #if defined(SPDY_PROXY_AUTH_ORIGIN)
118 if (header_name == "Proxy-Authenticate")
119 return false;
120 #endif
121 return true;
124 } // namespace
126 const char HttpResponseHeaders::kContentRange[] = "Content-Range";
128 struct HttpResponseHeaders::ParsedHeader {
129 // A header "continuation" contains only a subsequent value for the
130 // preceding header. (Header values are comma separated.)
131 bool is_continuation() const { return name_begin == name_end; }
133 std::string::const_iterator name_begin;
134 std::string::const_iterator name_end;
135 std::string::const_iterator value_begin;
136 std::string::const_iterator value_end;
139 //-----------------------------------------------------------------------------
141 HttpResponseHeaders::HttpResponseHeaders(const std::string& raw_input)
142 : response_code_(-1) {
143 Parse(raw_input);
145 // The most important thing to do with this histogram is find out
146 // the existence of unusual HTTP status codes. As it happens
147 // right now, there aren't double-constructions of response headers
148 // using this constructor, so our counts should also be accurate,
149 // without instantiating the histogram in two places. It is also
150 // important that this histogram not collect data in the other
151 // constructor, which rebuilds an histogram from a pickle, since
152 // that would actually create a double call between the original
153 // HttpResponseHeader that was serialized, and initialization of the
154 // new object from that pickle.
155 UMA_HISTOGRAM_CUSTOM_ENUMERATION("Net.HttpResponseCode",
156 HttpUtil::MapStatusCodeForHistogram(
157 response_code_),
158 // Note the third argument is only
159 // evaluated once, see macro
160 // definition for details.
161 HttpUtil::GetStatusCodesForHistogram());
164 HttpResponseHeaders::HttpResponseHeaders(const Pickle& pickle,
165 PickleIterator* iter)
166 : response_code_(-1) {
167 std::string raw_input;
168 if (pickle.ReadString(iter, &raw_input))
169 Parse(raw_input);
172 void HttpResponseHeaders::Persist(Pickle* pickle, PersistOptions options) {
173 if (options == PERSIST_RAW) {
174 pickle->WriteString(raw_headers_);
175 return; // Done.
178 HeaderSet filter_headers;
180 // Construct set of headers to filter out based on options.
181 if ((options & PERSIST_SANS_NON_CACHEABLE) == PERSIST_SANS_NON_CACHEABLE)
182 AddNonCacheableHeaders(&filter_headers);
184 if ((options & PERSIST_SANS_COOKIES) == PERSIST_SANS_COOKIES)
185 AddCookieHeaders(&filter_headers);
187 if ((options & PERSIST_SANS_CHALLENGES) == PERSIST_SANS_CHALLENGES)
188 AddChallengeHeaders(&filter_headers);
190 if ((options & PERSIST_SANS_HOP_BY_HOP) == PERSIST_SANS_HOP_BY_HOP)
191 AddHopByHopHeaders(&filter_headers);
193 if ((options & PERSIST_SANS_RANGES) == PERSIST_SANS_RANGES)
194 AddHopContentRangeHeaders(&filter_headers);
196 if ((options & PERSIST_SANS_SECURITY_STATE) == PERSIST_SANS_SECURITY_STATE)
197 AddSecurityStateHeaders(&filter_headers);
199 std::string blob;
200 blob.reserve(raw_headers_.size());
202 // This copies the status line w/ terminator null.
203 // Note raw_headers_ has embedded nulls instead of \n,
204 // so this just copies the first header line.
205 blob.assign(raw_headers_.c_str(), strlen(raw_headers_.c_str()) + 1);
207 for (size_t i = 0; i < parsed_.size(); ++i) {
208 DCHECK(!parsed_[i].is_continuation());
210 // Locate the start of the next header.
211 size_t k = i;
212 while (++k < parsed_.size() && parsed_[k].is_continuation()) {}
213 --k;
215 std::string header_name(parsed_[i].name_begin, parsed_[i].name_end);
216 StringToLowerASCII(&header_name);
218 if (filter_headers.find(header_name) == filter_headers.end()) {
219 // Make sure there is a null after the value.
220 blob.append(parsed_[i].name_begin, parsed_[k].value_end);
221 blob.push_back('\0');
224 i = k;
226 blob.push_back('\0');
228 pickle->WriteString(blob);
231 void HttpResponseHeaders::Update(const HttpResponseHeaders& new_headers) {
232 DCHECK(new_headers.response_code() == 304 ||
233 new_headers.response_code() == 206);
235 // Copy up to the null byte. This just copies the status line.
236 std::string new_raw_headers(raw_headers_.c_str());
237 new_raw_headers.push_back('\0');
239 HeaderSet updated_headers;
241 // NOTE: we write the new headers then the old headers for convenience. The
242 // order should not matter.
244 // Figure out which headers we want to take from new_headers:
245 for (size_t i = 0; i < new_headers.parsed_.size(); ++i) {
246 const HeaderList& new_parsed = new_headers.parsed_;
248 DCHECK(!new_parsed[i].is_continuation());
250 // Locate the start of the next header.
251 size_t k = i;
252 while (++k < new_parsed.size() && new_parsed[k].is_continuation()) {}
253 --k;
255 const std::string::const_iterator& name_begin = new_parsed[i].name_begin;
256 const std::string::const_iterator& name_end = new_parsed[i].name_end;
257 if (ShouldUpdateHeader(name_begin, name_end)) {
258 std::string name(name_begin, name_end);
259 StringToLowerASCII(&name);
260 updated_headers.insert(name);
262 // Preserve this header line in the merged result, making sure there is
263 // a null after the value.
264 new_raw_headers.append(name_begin, new_parsed[k].value_end);
265 new_raw_headers.push_back('\0');
268 i = k;
271 // Now, build the new raw headers.
272 MergeWithHeaders(new_raw_headers, updated_headers);
275 void HttpResponseHeaders::MergeWithHeaders(const std::string& raw_headers,
276 const HeaderSet& headers_to_remove) {
277 std::string new_raw_headers(raw_headers);
278 for (size_t i = 0; i < parsed_.size(); ++i) {
279 DCHECK(!parsed_[i].is_continuation());
281 // Locate the start of the next header.
282 size_t k = i;
283 while (++k < parsed_.size() && parsed_[k].is_continuation()) {}
284 --k;
286 std::string name(parsed_[i].name_begin, parsed_[i].name_end);
287 StringToLowerASCII(&name);
288 if (headers_to_remove.find(name) == headers_to_remove.end()) {
289 // It's ok to preserve this header in the final result.
290 new_raw_headers.append(parsed_[i].name_begin, parsed_[k].value_end);
291 new_raw_headers.push_back('\0');
294 i = k;
296 new_raw_headers.push_back('\0');
298 // Make this object hold the new data.
299 raw_headers_.clear();
300 parsed_.clear();
301 Parse(new_raw_headers);
304 void HttpResponseHeaders::RemoveHeader(const std::string& name) {
305 // Copy up to the null byte. This just copies the status line.
306 std::string new_raw_headers(raw_headers_.c_str());
307 new_raw_headers.push_back('\0');
309 std::string lowercase_name(name);
310 StringToLowerASCII(&lowercase_name);
311 HeaderSet to_remove;
312 to_remove.insert(lowercase_name);
313 MergeWithHeaders(new_raw_headers, to_remove);
316 void HttpResponseHeaders::RemoveHeaderLine(const std::string& name,
317 const std::string& value) {
318 std::string name_lowercase(name);
319 StringToLowerASCII(&name_lowercase);
321 std::string new_raw_headers(GetStatusLine());
322 new_raw_headers.push_back('\0');
324 new_raw_headers.reserve(raw_headers_.size());
326 void* iter = NULL;
327 std::string old_header_name;
328 std::string old_header_value;
329 while (EnumerateHeaderLines(&iter, &old_header_name, &old_header_value)) {
330 std::string old_header_name_lowercase(name);
331 StringToLowerASCII(&old_header_name_lowercase);
333 if (name_lowercase == old_header_name_lowercase &&
334 value == old_header_value)
335 continue;
337 new_raw_headers.append(old_header_name);
338 new_raw_headers.push_back(':');
339 new_raw_headers.push_back(' ');
340 new_raw_headers.append(old_header_value);
341 new_raw_headers.push_back('\0');
343 new_raw_headers.push_back('\0');
345 // Make this object hold the new data.
346 raw_headers_.clear();
347 parsed_.clear();
348 Parse(new_raw_headers);
351 void HttpResponseHeaders::AddHeader(const std::string& header) {
352 CheckDoesNotHaveEmbededNulls(header);
353 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 2]);
354 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 1]);
355 // Don't copy the last null.
356 std::string new_raw_headers(raw_headers_, 0, raw_headers_.size() - 1);
357 new_raw_headers.append(header);
358 new_raw_headers.push_back('\0');
359 new_raw_headers.push_back('\0');
361 // Make this object hold the new data.
362 raw_headers_.clear();
363 parsed_.clear();
364 Parse(new_raw_headers);
367 void HttpResponseHeaders::ReplaceStatusLine(const std::string& new_status) {
368 CheckDoesNotHaveEmbededNulls(new_status);
369 // Copy up to the null byte. This just copies the status line.
370 std::string new_raw_headers(new_status);
371 new_raw_headers.push_back('\0');
373 HeaderSet empty_to_remove;
374 MergeWithHeaders(new_raw_headers, empty_to_remove);
377 void HttpResponseHeaders::Parse(const std::string& raw_input) {
378 raw_headers_.reserve(raw_input.size());
380 // ParseStatusLine adds a normalized status line to raw_headers_
381 std::string::const_iterator line_begin = raw_input.begin();
382 std::string::const_iterator line_end =
383 std::find(line_begin, raw_input.end(), '\0');
384 // has_headers = true, if there is any data following the status line.
385 // Used by ParseStatusLine() to decide if a HTTP/0.9 is really a HTTP/1.0.
386 bool has_headers = (line_end != raw_input.end() &&
387 (line_end + 1) != raw_input.end() &&
388 *(line_end + 1) != '\0');
389 ParseStatusLine(line_begin, line_end, has_headers);
390 raw_headers_.push_back('\0'); // Terminate status line with a null.
392 if (line_end == raw_input.end()) {
393 raw_headers_.push_back('\0'); // Ensure the headers end with a double null.
395 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 2]);
396 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 1]);
397 return;
400 // Including a terminating null byte.
401 size_t status_line_len = raw_headers_.size();
403 // Now, we add the rest of the raw headers to raw_headers_, and begin parsing
404 // it (to populate our parsed_ vector).
405 raw_headers_.append(line_end + 1, raw_input.end());
407 // Ensure the headers end with a double null.
408 while (raw_headers_.size() < 2 ||
409 raw_headers_[raw_headers_.size() - 2] != '\0' ||
410 raw_headers_[raw_headers_.size() - 1] != '\0') {
411 raw_headers_.push_back('\0');
414 // Adjust to point at the null byte following the status line
415 line_end = raw_headers_.begin() + status_line_len - 1;
417 HttpUtil::HeadersIterator headers(line_end + 1, raw_headers_.end(),
418 std::string(1, '\0'));
419 while (headers.GetNext()) {
420 AddHeader(headers.name_begin(),
421 headers.name_end(),
422 headers.values_begin(),
423 headers.values_end());
426 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 2]);
427 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 1]);
430 // Append all of our headers to the final output string.
431 void HttpResponseHeaders::GetNormalizedHeaders(std::string* output) const {
432 // copy up to the null byte. this just copies the status line.
433 output->assign(raw_headers_.c_str());
435 // headers may appear multiple times (not necessarily in succession) in the
436 // header data, so we build a map from header name to generated header lines.
437 // to preserve the order of the original headers, the actual values are kept
438 // in a separate list. finally, the list of headers is flattened to form
439 // the normalized block of headers.
441 // NOTE: We take special care to preserve the whitespace around any commas
442 // that may occur in the original response headers. Because our consumer may
443 // be a web app, we cannot be certain of the semantics of commas despite the
444 // fact that RFC 2616 says that they should be regarded as value separators.
446 typedef base::hash_map<std::string, size_t> HeadersMap;
447 HeadersMap headers_map;
448 HeadersMap::iterator iter = headers_map.end();
450 std::vector<std::string> headers;
452 for (size_t i = 0; i < parsed_.size(); ++i) {
453 DCHECK(!parsed_[i].is_continuation());
455 std::string name(parsed_[i].name_begin, parsed_[i].name_end);
456 std::string lower_name = StringToLowerASCII(name);
458 iter = headers_map.find(lower_name);
459 if (iter == headers_map.end()) {
460 iter = headers_map.insert(
461 HeadersMap::value_type(lower_name, headers.size())).first;
462 headers.push_back(name + ": ");
463 } else {
464 headers[iter->second].append(", ");
467 std::string::const_iterator value_begin = parsed_[i].value_begin;
468 std::string::const_iterator value_end = parsed_[i].value_end;
469 while (++i < parsed_.size() && parsed_[i].is_continuation())
470 value_end = parsed_[i].value_end;
471 --i;
473 headers[iter->second].append(value_begin, value_end);
476 for (size_t i = 0; i < headers.size(); ++i) {
477 output->push_back('\n');
478 output->append(headers[i]);
481 output->push_back('\n');
484 bool HttpResponseHeaders::GetNormalizedHeader(const std::string& name,
485 std::string* value) const {
486 // If you hit this assertion, please use EnumerateHeader instead!
487 DCHECK(!HttpUtil::IsNonCoalescingHeader(name));
489 value->clear();
491 bool found = false;
492 size_t i = 0;
493 while (i < parsed_.size()) {
494 i = FindHeader(i, name);
495 if (i == std::string::npos)
496 break;
498 found = true;
500 if (!value->empty())
501 value->append(", ");
503 std::string::const_iterator value_begin = parsed_[i].value_begin;
504 std::string::const_iterator value_end = parsed_[i].value_end;
505 while (++i < parsed_.size() && parsed_[i].is_continuation())
506 value_end = parsed_[i].value_end;
507 value->append(value_begin, value_end);
510 return found;
513 std::string HttpResponseHeaders::GetStatusLine() const {
514 // copy up to the null byte.
515 return std::string(raw_headers_.c_str());
518 std::string HttpResponseHeaders::GetStatusText() const {
519 // GetStatusLine() is already normalized, so it has the format:
520 // <http_version> SP <response_code> SP <status_text>
521 std::string status_text = GetStatusLine();
522 std::string::const_iterator begin = status_text.begin();
523 std::string::const_iterator end = status_text.end();
524 for (int i = 0; i < 2; ++i)
525 begin = std::find(begin, end, ' ') + 1;
526 return std::string(begin, end);
529 bool HttpResponseHeaders::EnumerateHeaderLines(void** iter,
530 std::string* name,
531 std::string* value) const {
532 size_t i = reinterpret_cast<size_t>(*iter);
533 if (i == parsed_.size())
534 return false;
536 DCHECK(!parsed_[i].is_continuation());
538 name->assign(parsed_[i].name_begin, parsed_[i].name_end);
540 std::string::const_iterator value_begin = parsed_[i].value_begin;
541 std::string::const_iterator value_end = parsed_[i].value_end;
542 while (++i < parsed_.size() && parsed_[i].is_continuation())
543 value_end = parsed_[i].value_end;
545 value->assign(value_begin, value_end);
547 *iter = reinterpret_cast<void*>(i);
548 return true;
551 bool HttpResponseHeaders::EnumerateHeader(void** iter,
552 const base::StringPiece& name,
553 std::string* value) const {
554 size_t i;
555 if (!iter || !*iter) {
556 i = FindHeader(0, name);
557 } else {
558 i = reinterpret_cast<size_t>(*iter);
559 if (i >= parsed_.size()) {
560 i = std::string::npos;
561 } else if (!parsed_[i].is_continuation()) {
562 i = FindHeader(i, name);
566 if (i == std::string::npos) {
567 value->clear();
568 return false;
571 if (iter)
572 *iter = reinterpret_cast<void*>(i + 1);
573 value->assign(parsed_[i].value_begin, parsed_[i].value_end);
574 return true;
577 bool HttpResponseHeaders::HasHeaderValue(const base::StringPiece& name,
578 const base::StringPiece& value) const {
579 // The value has to be an exact match. This is important since
580 // 'cache-control: no-cache' != 'cache-control: no-cache="foo"'
581 void* iter = NULL;
582 std::string temp;
583 while (EnumerateHeader(&iter, name, &temp)) {
584 if (value.size() == temp.size() &&
585 std::equal(temp.begin(), temp.end(), value.begin(),
586 base::CaseInsensitiveCompare<char>()))
587 return true;
589 return false;
592 bool HttpResponseHeaders::HasHeader(const base::StringPiece& name) const {
593 return FindHeader(0, name) != std::string::npos;
596 HttpResponseHeaders::HttpResponseHeaders() : response_code_(-1) {
599 HttpResponseHeaders::~HttpResponseHeaders() {
602 // Note: this implementation implicitly assumes that line_end points at a valid
603 // sentinel character (such as '\0').
604 // static
605 HttpVersion HttpResponseHeaders::ParseVersion(
606 std::string::const_iterator line_begin,
607 std::string::const_iterator line_end) {
608 std::string::const_iterator p = line_begin;
610 // RFC2616 sec 3.1: HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT
611 // TODO: (1*DIGIT apparently means one or more digits, but we only handle 1).
612 // TODO: handle leading zeros, which is allowed by the rfc1616 sec 3.1.
614 if ((line_end - p < 4) || !LowerCaseEqualsASCII(p, p + 4, "http")) {
615 DVLOG(1) << "missing status line";
616 return HttpVersion();
619 p += 4;
621 if (p >= line_end || *p != '/') {
622 DVLOG(1) << "missing version";
623 return HttpVersion();
626 std::string::const_iterator dot = std::find(p, line_end, '.');
627 if (dot == line_end) {
628 DVLOG(1) << "malformed version";
629 return HttpVersion();
632 ++p; // from / to first digit.
633 ++dot; // from . to second digit.
635 if (!(*p >= '0' && *p <= '9' && *dot >= '0' && *dot <= '9')) {
636 DVLOG(1) << "malformed version number";
637 return HttpVersion();
640 uint16 major = *p - '0';
641 uint16 minor = *dot - '0';
643 return HttpVersion(major, minor);
646 // Note: this implementation implicitly assumes that line_end points at a valid
647 // sentinel character (such as '\0').
648 void HttpResponseHeaders::ParseStatusLine(
649 std::string::const_iterator line_begin,
650 std::string::const_iterator line_end,
651 bool has_headers) {
652 // Extract the version number
653 parsed_http_version_ = ParseVersion(line_begin, line_end);
655 // Clamp the version number to one of: {0.9, 1.0, 1.1}
656 if (parsed_http_version_ == HttpVersion(0, 9) && !has_headers) {
657 http_version_ = HttpVersion(0, 9);
658 raw_headers_ = "HTTP/0.9";
659 } else if (parsed_http_version_ >= HttpVersion(1, 1)) {
660 http_version_ = HttpVersion(1, 1);
661 raw_headers_ = "HTTP/1.1";
662 } else {
663 // Treat everything else like HTTP 1.0
664 http_version_ = HttpVersion(1, 0);
665 raw_headers_ = "HTTP/1.0";
667 if (parsed_http_version_ != http_version_) {
668 DVLOG(1) << "assuming HTTP/" << http_version_.major_value() << "."
669 << http_version_.minor_value();
672 // TODO(eroman): this doesn't make sense if ParseVersion failed.
673 std::string::const_iterator p = std::find(line_begin, line_end, ' ');
675 if (p == line_end) {
676 DVLOG(1) << "missing response status; assuming 200 OK";
677 raw_headers_.append(" 200 OK");
678 response_code_ = 200;
679 return;
682 // Skip whitespace.
683 while (*p == ' ')
684 ++p;
686 std::string::const_iterator code = p;
687 while (*p >= '0' && *p <= '9')
688 ++p;
690 if (p == code) {
691 DVLOG(1) << "missing response status number; assuming 200";
692 raw_headers_.append(" 200 OK");
693 response_code_ = 200;
694 return;
696 raw_headers_.push_back(' ');
697 raw_headers_.append(code, p);
698 raw_headers_.push_back(' ');
699 base::StringToInt(StringPiece(code, p), &response_code_);
701 // Skip whitespace.
702 while (*p == ' ')
703 ++p;
705 // Trim trailing whitespace.
706 while (line_end > p && line_end[-1] == ' ')
707 --line_end;
709 if (p == line_end) {
710 DVLOG(1) << "missing response status text; assuming OK";
711 // Not super critical what we put here. Just use "OK"
712 // even if it isn't descriptive of response_code_.
713 raw_headers_.append("OK");
714 } else {
715 raw_headers_.append(p, line_end);
719 size_t HttpResponseHeaders::FindHeader(size_t from,
720 const base::StringPiece& search) const {
721 for (size_t i = from; i < parsed_.size(); ++i) {
722 if (parsed_[i].is_continuation())
723 continue;
724 const std::string::const_iterator& name_begin = parsed_[i].name_begin;
725 const std::string::const_iterator& name_end = parsed_[i].name_end;
726 if (static_cast<size_t>(name_end - name_begin) == search.size() &&
727 std::equal(name_begin, name_end, search.begin(),
728 base::CaseInsensitiveCompare<char>()))
729 return i;
732 return std::string::npos;
735 void HttpResponseHeaders::AddHeader(std::string::const_iterator name_begin,
736 std::string::const_iterator name_end,
737 std::string::const_iterator values_begin,
738 std::string::const_iterator values_end) {
739 // If the header can be coalesced, then we should split it up.
740 if (values_begin == values_end ||
741 HttpUtil::IsNonCoalescingHeader(name_begin, name_end)) {
742 AddToParsed(name_begin, name_end, values_begin, values_end);
743 } else {
744 HttpUtil::ValuesIterator it(values_begin, values_end, ',');
745 while (it.GetNext()) {
746 AddToParsed(name_begin, name_end, it.value_begin(), it.value_end());
747 // clobber these so that subsequent values are treated as continuations
748 name_begin = name_end = raw_headers_.end();
753 void HttpResponseHeaders::AddToParsed(std::string::const_iterator name_begin,
754 std::string::const_iterator name_end,
755 std::string::const_iterator value_begin,
756 std::string::const_iterator value_end) {
757 ParsedHeader header;
758 header.name_begin = name_begin;
759 header.name_end = name_end;
760 header.value_begin = value_begin;
761 header.value_end = value_end;
762 parsed_.push_back(header);
765 void HttpResponseHeaders::AddNonCacheableHeaders(HeaderSet* result) const {
766 // Add server specified transients. Any 'cache-control: no-cache="foo,bar"'
767 // headers present in the response specify additional headers that we should
768 // not store in the cache.
769 const char kCacheControl[] = "cache-control";
770 const char kPrefix[] = "no-cache=\"";
771 const size_t kPrefixLen = sizeof(kPrefix) - 1;
773 std::string value;
774 void* iter = NULL;
775 while (EnumerateHeader(&iter, kCacheControl, &value)) {
776 // If the value is smaller than the prefix and a terminal quote, skip
777 // it.
778 if (value.size() <= kPrefixLen ||
779 value.compare(0, kPrefixLen, kPrefix) != 0) {
780 continue;
782 // if it doesn't end with a quote, then treat as malformed
783 if (value[value.size()-1] != '\"')
784 continue;
786 // process the value as a comma-separated list of items. Each
787 // item can be wrapped by linear white space.
788 std::string::const_iterator item = value.begin() + kPrefixLen;
789 std::string::const_iterator end = value.end() - 1;
790 while (item != end) {
791 // Find the comma to compute the length of the current item,
792 // and the position of the next one.
793 std::string::const_iterator item_next = std::find(item, end, ',');
794 std::string::const_iterator item_end = end;
795 if (item_next != end) {
796 // Skip over comma for next position.
797 item_end = item_next;
798 item_next++;
800 // trim off leading and trailing whitespace in this item.
801 HttpUtil::TrimLWS(&item, &item_end);
803 // assuming the header is not empty, lowercase and insert into set
804 if (item_end > item) {
805 std::string name(&*item, item_end - item);
806 StringToLowerASCII(&name);
807 result->insert(name);
810 // Continue to next item.
811 item = item_next;
816 void HttpResponseHeaders::AddHopByHopHeaders(HeaderSet* result) {
817 for (size_t i = 0; i < arraysize(kHopByHopResponseHeaders); ++i)
818 result->insert(std::string(kHopByHopResponseHeaders[i]));
821 void HttpResponseHeaders::AddCookieHeaders(HeaderSet* result) {
822 for (size_t i = 0; i < arraysize(kCookieResponseHeaders); ++i)
823 result->insert(std::string(kCookieResponseHeaders[i]));
826 void HttpResponseHeaders::AddChallengeHeaders(HeaderSet* result) {
827 for (size_t i = 0; i < arraysize(kChallengeResponseHeaders); ++i)
828 result->insert(std::string(kChallengeResponseHeaders[i]));
831 void HttpResponseHeaders::AddHopContentRangeHeaders(HeaderSet* result) {
832 result->insert(kContentRange);
835 void HttpResponseHeaders::AddSecurityStateHeaders(HeaderSet* result) {
836 for (size_t i = 0; i < arraysize(kSecurityStateHeaders); ++i)
837 result->insert(std::string(kSecurityStateHeaders[i]));
840 void HttpResponseHeaders::GetMimeTypeAndCharset(std::string* mime_type,
841 std::string* charset) const {
842 mime_type->clear();
843 charset->clear();
845 std::string name = "content-type";
846 std::string value;
848 bool had_charset = false;
850 void* iter = NULL;
851 while (EnumerateHeader(&iter, name, &value))
852 HttpUtil::ParseContentType(value, mime_type, charset, &had_charset, NULL);
855 bool HttpResponseHeaders::GetMimeType(std::string* mime_type) const {
856 std::string unused;
857 GetMimeTypeAndCharset(mime_type, &unused);
858 return !mime_type->empty();
861 bool HttpResponseHeaders::GetCharset(std::string* charset) const {
862 std::string unused;
863 GetMimeTypeAndCharset(&unused, charset);
864 return !charset->empty();
867 bool HttpResponseHeaders::IsRedirect(std::string* location) const {
868 if (!IsRedirectResponseCode(response_code_))
869 return false;
871 // If we lack a Location header, then we can't treat this as a redirect.
872 // We assume that the first non-empty location value is the target URL that
873 // we want to follow. TODO(darin): Is this consistent with other browsers?
874 size_t i = std::string::npos;
875 do {
876 i = FindHeader(++i, "location");
877 if (i == std::string::npos)
878 return false;
879 // If the location value is empty, then it doesn't count.
880 } while (parsed_[i].value_begin == parsed_[i].value_end);
882 if (location) {
883 // Escape any non-ASCII characters to preserve them. The server should
884 // only be returning ASCII here, but for compat we need to do this.
885 *location = EscapeNonASCII(
886 std::string(parsed_[i].value_begin, parsed_[i].value_end));
889 return true;
892 // static
893 bool HttpResponseHeaders::IsRedirectResponseCode(int response_code) {
894 // Users probably want to see 300 (multiple choice) pages, so we don't count
895 // them as redirects that need to be followed.
896 return (response_code == 301 ||
897 response_code == 302 ||
898 response_code == 303 ||
899 response_code == 307);
902 // From RFC 2616 section 13.2.4:
904 // The calculation to determine if a response has expired is quite simple:
906 // response_is_fresh = (freshness_lifetime > current_age)
908 // Of course, there are other factors that can force a response to always be
909 // validated or re-fetched.
911 bool HttpResponseHeaders::RequiresValidation(const Time& request_time,
912 const Time& response_time,
913 const Time& current_time) const {
914 TimeDelta lifetime =
915 GetFreshnessLifetime(response_time);
916 if (lifetime == TimeDelta())
917 return true;
919 return lifetime <= GetCurrentAge(request_time, response_time, current_time);
922 // From RFC 2616 section 13.2.4:
924 // The max-age directive takes priority over Expires, so if max-age is present
925 // in a response, the calculation is simply:
927 // freshness_lifetime = max_age_value
929 // Otherwise, if Expires is present in the response, the calculation is:
931 // freshness_lifetime = expires_value - date_value
933 // Note that neither of these calculations is vulnerable to clock skew, since
934 // all of the information comes from the origin server.
936 // Also, if the response does have a Last-Modified time, the heuristic
937 // expiration value SHOULD be no more than some fraction of the interval since
938 // that time. A typical setting of this fraction might be 10%:
940 // freshness_lifetime = (date_value - last_modified_value) * 0.10
942 TimeDelta HttpResponseHeaders::GetFreshnessLifetime(
943 const Time& response_time) const {
944 // Check for headers that force a response to never be fresh. For backwards
945 // compat, we treat "Pragma: no-cache" as a synonym for "Cache-Control:
946 // no-cache" even though RFC 2616 does not specify it.
947 if (HasHeaderValue("cache-control", "no-cache") ||
948 HasHeaderValue("cache-control", "no-store") ||
949 HasHeaderValue("pragma", "no-cache") ||
950 HasHeaderValue("vary", "*")) // see RFC 2616 section 13.6
951 return TimeDelta(); // not fresh
953 // NOTE: "Cache-Control: max-age" overrides Expires, so we only check the
954 // Expires header after checking for max-age in GetFreshnessLifetime. This
955 // is important since "Expires: <date in the past>" means not fresh, but
956 // it should not trump a max-age value.
958 TimeDelta max_age_value;
959 if (GetMaxAgeValue(&max_age_value))
960 return max_age_value;
962 // If there is no Date header, then assume that the server response was
963 // generated at the time when we received the response.
964 Time date_value;
965 if (!GetDateValue(&date_value))
966 date_value = response_time;
968 Time expires_value;
969 if (GetExpiresValue(&expires_value)) {
970 // The expires value can be a date in the past!
971 if (expires_value > date_value)
972 return expires_value - date_value;
974 return TimeDelta(); // not fresh
977 // From RFC 2616 section 13.4:
979 // A response received with a status code of 200, 203, 206, 300, 301 or 410
980 // MAY be stored by a cache and used in reply to a subsequent request,
981 // subject to the expiration mechanism, unless a cache-control directive
982 // prohibits caching.
983 // ...
984 // A response received with any other status code (e.g. status codes 302
985 // and 307) MUST NOT be returned in a reply to a subsequent request unless
986 // there are cache-control directives or another header(s) that explicitly
987 // allow it.
989 // From RFC 2616 section 14.9.4:
991 // When the must-revalidate directive is present in a response received by
992 // a cache, that cache MUST NOT use the entry after it becomes stale to
993 // respond to a subsequent request without first revalidating it with the
994 // origin server. (I.e., the cache MUST do an end-to-end revalidation every
995 // time, if, based solely on the origin server's Expires or max-age value,
996 // the cached response is stale.)
998 if ((response_code_ == 200 || response_code_ == 203 ||
999 response_code_ == 206) &&
1000 !HasHeaderValue("cache-control", "must-revalidate")) {
1001 // TODO(darin): Implement a smarter heuristic.
1002 Time last_modified_value;
1003 if (GetLastModifiedValue(&last_modified_value)) {
1004 // The last-modified value can be a date in the past!
1005 if (last_modified_value <= date_value)
1006 return (date_value - last_modified_value) / 10;
1010 // These responses are implicitly fresh (unless otherwise overruled):
1011 if (response_code_ == 300 || response_code_ == 301 || response_code_ == 410)
1012 return TimeDelta::FromMicroseconds(kint64max);
1014 return TimeDelta(); // not fresh
1017 // From RFC 2616 section 13.2.3:
1019 // Summary of age calculation algorithm, when a cache receives a response:
1021 // /*
1022 // * age_value
1023 // * is the value of Age: header received by the cache with
1024 // * this response.
1025 // * date_value
1026 // * is the value of the origin server's Date: header
1027 // * request_time
1028 // * is the (local) time when the cache made the request
1029 // * that resulted in this cached response
1030 // * response_time
1031 // * is the (local) time when the cache received the
1032 // * response
1033 // * now
1034 // * is the current (local) time
1035 // */
1036 // apparent_age = max(0, response_time - date_value);
1037 // corrected_received_age = max(apparent_age, age_value);
1038 // response_delay = response_time - request_time;
1039 // corrected_initial_age = corrected_received_age + response_delay;
1040 // resident_time = now - response_time;
1041 // current_age = corrected_initial_age + resident_time;
1043 TimeDelta HttpResponseHeaders::GetCurrentAge(const Time& request_time,
1044 const Time& response_time,
1045 const Time& current_time) const {
1046 // If there is no Date header, then assume that the server response was
1047 // generated at the time when we received the response.
1048 Time date_value;
1049 if (!GetDateValue(&date_value))
1050 date_value = response_time;
1052 // If there is no Age header, then assume age is zero. GetAgeValue does not
1053 // modify its out param if the value does not exist.
1054 TimeDelta age_value;
1055 GetAgeValue(&age_value);
1057 TimeDelta apparent_age = std::max(TimeDelta(), response_time - date_value);
1058 TimeDelta corrected_received_age = std::max(apparent_age, age_value);
1059 TimeDelta response_delay = response_time - request_time;
1060 TimeDelta corrected_initial_age = corrected_received_age + response_delay;
1061 TimeDelta resident_time = current_time - response_time;
1062 TimeDelta current_age = corrected_initial_age + resident_time;
1064 return current_age;
1067 bool HttpResponseHeaders::GetMaxAgeValue(TimeDelta* result) const {
1068 std::string name = "cache-control";
1069 std::string value;
1071 const char kMaxAgePrefix[] = "max-age=";
1072 const size_t kMaxAgePrefixLen = arraysize(kMaxAgePrefix) - 1;
1074 void* iter = NULL;
1075 while (EnumerateHeader(&iter, name, &value)) {
1076 if (value.size() > kMaxAgePrefixLen) {
1077 if (LowerCaseEqualsASCII(value.begin(),
1078 value.begin() + kMaxAgePrefixLen,
1079 kMaxAgePrefix)) {
1080 int64 seconds;
1081 base::StringToInt64(StringPiece(value.begin() + kMaxAgePrefixLen,
1082 value.end()),
1083 &seconds);
1084 *result = TimeDelta::FromSeconds(seconds);
1085 return true;
1090 return false;
1093 bool HttpResponseHeaders::GetAgeValue(TimeDelta* result) const {
1094 std::string value;
1095 if (!EnumerateHeader(NULL, "Age", &value))
1096 return false;
1098 int64 seconds;
1099 base::StringToInt64(value, &seconds);
1100 *result = TimeDelta::FromSeconds(seconds);
1101 return true;
1104 bool HttpResponseHeaders::GetDateValue(Time* result) const {
1105 return GetTimeValuedHeader("Date", result);
1108 bool HttpResponseHeaders::GetLastModifiedValue(Time* result) const {
1109 return GetTimeValuedHeader("Last-Modified", result);
1112 bool HttpResponseHeaders::GetExpiresValue(Time* result) const {
1113 return GetTimeValuedHeader("Expires", result);
1116 bool HttpResponseHeaders::GetTimeValuedHeader(const std::string& name,
1117 Time* result) const {
1118 std::string value;
1119 if (!EnumerateHeader(NULL, name, &value))
1120 return false;
1122 // When parsing HTTP dates it's beneficial to default to GMT because:
1123 // 1. RFC2616 3.3.1 says times should always be specified in GMT
1124 // 2. Only counter-example incorrectly appended "UTC" (crbug.com/153759)
1125 // 3. When adjusting cookie expiration times for clock skew
1126 // (crbug.com/135131) this better matches our cookie expiration
1127 // time parser which ignores timezone specifiers and assumes GMT.
1128 // 4. This is exactly what Firefox does.
1129 // TODO(pauljensen): The ideal solution would be to return false if the
1130 // timezone could not be understood so as to avoid makeing other calculations
1131 // based on an incorrect time. This would require modifying the time
1132 // library or duplicating the code. (http://crbug.com/158327)
1133 return Time::FromUTCString(value.c_str(), result);
1136 bool HttpResponseHeaders::IsKeepAlive() const {
1137 if (http_version_ < HttpVersion(1, 0))
1138 return false;
1140 // NOTE: It is perhaps risky to assume that a Proxy-Connection header is
1141 // meaningful when we don't know that this response was from a proxy, but
1142 // Mozilla also does this, so we'll do the same.
1143 std::string connection_val;
1144 if (!EnumerateHeader(NULL, "connection", &connection_val))
1145 EnumerateHeader(NULL, "proxy-connection", &connection_val);
1147 bool keep_alive;
1149 if (http_version_ == HttpVersion(1, 0)) {
1150 // HTTP/1.0 responses default to NOT keep-alive
1151 keep_alive = LowerCaseEqualsASCII(connection_val, "keep-alive");
1152 } else {
1153 // HTTP/1.1 responses default to keep-alive
1154 keep_alive = !LowerCaseEqualsASCII(connection_val, "close");
1157 return keep_alive;
1160 bool HttpResponseHeaders::HasStrongValidators() const {
1161 std::string etag_header;
1162 EnumerateHeader(NULL, "etag", &etag_header);
1163 std::string last_modified_header;
1164 EnumerateHeader(NULL, "Last-Modified", &last_modified_header);
1165 std::string date_header;
1166 EnumerateHeader(NULL, "Date", &date_header);
1167 return HttpUtil::HasStrongValidators(GetHttpVersion(),
1168 etag_header,
1169 last_modified_header,
1170 date_header);
1173 // From RFC 2616:
1174 // Content-Length = "Content-Length" ":" 1*DIGIT
1175 int64 HttpResponseHeaders::GetContentLength() const {
1176 return GetInt64HeaderValue("content-length");
1179 int64 HttpResponseHeaders::GetInt64HeaderValue(
1180 const std::string& header) const {
1181 void* iter = NULL;
1182 std::string content_length_val;
1183 if (!EnumerateHeader(&iter, header, &content_length_val))
1184 return -1;
1186 if (content_length_val.empty())
1187 return -1;
1189 if (content_length_val[0] == '+')
1190 return -1;
1192 int64 result;
1193 bool ok = base::StringToInt64(content_length_val, &result);
1194 if (!ok || result < 0)
1195 return -1;
1197 return result;
1200 // From RFC 2616 14.16:
1201 // content-range-spec =
1202 // bytes-unit SP byte-range-resp-spec "/" ( instance-length | "*" )
1203 // byte-range-resp-spec = (first-byte-pos "-" last-byte-pos) | "*"
1204 // instance-length = 1*DIGIT
1205 // bytes-unit = "bytes"
1206 bool HttpResponseHeaders::GetContentRange(int64* first_byte_position,
1207 int64* last_byte_position,
1208 int64* instance_length) const {
1209 void* iter = NULL;
1210 std::string content_range_spec;
1211 *first_byte_position = *last_byte_position = *instance_length = -1;
1212 if (!EnumerateHeader(&iter, kContentRange, &content_range_spec))
1213 return false;
1215 // If the header value is empty, we have an invalid header.
1216 if (content_range_spec.empty())
1217 return false;
1219 size_t space_position = content_range_spec.find(' ');
1220 if (space_position == std::string::npos)
1221 return false;
1223 // Invalid header if it doesn't contain "bytes-unit".
1224 std::string::const_iterator content_range_spec_begin =
1225 content_range_spec.begin();
1226 std::string::const_iterator content_range_spec_end =
1227 content_range_spec.begin() + space_position;
1228 HttpUtil::TrimLWS(&content_range_spec_begin, &content_range_spec_end);
1229 if (!LowerCaseEqualsASCII(content_range_spec_begin,
1230 content_range_spec_end,
1231 "bytes")) {
1232 return false;
1235 size_t slash_position = content_range_spec.find('/', space_position + 1);
1236 if (slash_position == std::string::npos)
1237 return false;
1239 // Obtain the part behind the space and before slash.
1240 std::string::const_iterator byte_range_resp_spec_begin =
1241 content_range_spec.begin() + space_position + 1;
1242 std::string::const_iterator byte_range_resp_spec_end =
1243 content_range_spec.begin() + slash_position;
1244 HttpUtil::TrimLWS(&byte_range_resp_spec_begin, &byte_range_resp_spec_end);
1246 // Parse the byte-range-resp-spec part.
1247 std::string byte_range_resp_spec(byte_range_resp_spec_begin,
1248 byte_range_resp_spec_end);
1249 // If byte-range-resp-spec != "*".
1250 if (!LowerCaseEqualsASCII(byte_range_resp_spec, "*")) {
1251 size_t minus_position = byte_range_resp_spec.find('-');
1252 if (minus_position != std::string::npos) {
1253 // Obtain first-byte-pos.
1254 std::string::const_iterator first_byte_pos_begin =
1255 byte_range_resp_spec.begin();
1256 std::string::const_iterator first_byte_pos_end =
1257 byte_range_resp_spec.begin() + minus_position;
1258 HttpUtil::TrimLWS(&first_byte_pos_begin, &first_byte_pos_end);
1260 bool ok = base::StringToInt64(StringPiece(first_byte_pos_begin,
1261 first_byte_pos_end),
1262 first_byte_position);
1264 // Obtain last-byte-pos.
1265 std::string::const_iterator last_byte_pos_begin =
1266 byte_range_resp_spec.begin() + minus_position + 1;
1267 std::string::const_iterator last_byte_pos_end =
1268 byte_range_resp_spec.end();
1269 HttpUtil::TrimLWS(&last_byte_pos_begin, &last_byte_pos_end);
1271 ok &= base::StringToInt64(StringPiece(last_byte_pos_begin,
1272 last_byte_pos_end),
1273 last_byte_position);
1274 if (!ok) {
1275 *first_byte_position = *last_byte_position = -1;
1276 return false;
1278 if (*first_byte_position < 0 || *last_byte_position < 0 ||
1279 *first_byte_position > *last_byte_position)
1280 return false;
1281 } else {
1282 return false;
1286 // Parse the instance-length part.
1287 // If instance-length == "*".
1288 std::string::const_iterator instance_length_begin =
1289 content_range_spec.begin() + slash_position + 1;
1290 std::string::const_iterator instance_length_end =
1291 content_range_spec.end();
1292 HttpUtil::TrimLWS(&instance_length_begin, &instance_length_end);
1294 if (LowerCaseEqualsASCII(instance_length_begin, instance_length_end, "*")) {
1295 return false;
1296 } else if (!base::StringToInt64(StringPiece(instance_length_begin,
1297 instance_length_end),
1298 instance_length)) {
1299 *instance_length = -1;
1300 return false;
1303 // We have all the values; let's verify that they make sense for a 206
1304 // response.
1305 if (*first_byte_position < 0 || *last_byte_position < 0 ||
1306 *instance_length < 0 || *instance_length - 1 < *last_byte_position)
1307 return false;
1309 return true;
1312 base::Value* HttpResponseHeaders::NetLogCallback(
1313 NetLog::LogLevel /* log_level */) const {
1314 base::DictionaryValue* dict = new base::DictionaryValue();
1315 base::ListValue* headers = new base::ListValue();
1316 headers->Append(new base::StringValue(GetStatusLine()));
1317 void* iterator = NULL;
1318 std::string name;
1319 std::string value;
1320 while (EnumerateHeaderLines(&iterator, &name, &value)) {
1321 headers->Append(
1322 new base::StringValue(
1323 base::StringPrintf("%s: %s",
1324 name.c_str(),
1325 (ShouldShowHttpHeaderValue(name) ?
1326 value.c_str() : "[elided]"))));
1328 dict->Set("headers", headers);
1329 return dict;
1332 // static
1333 bool HttpResponseHeaders::FromNetLogParam(
1334 const base::Value* event_param,
1335 scoped_refptr<HttpResponseHeaders>* http_response_headers) {
1336 *http_response_headers = NULL;
1338 const base::DictionaryValue* dict = NULL;
1339 const base::ListValue* header_list = NULL;
1341 if (!event_param ||
1342 !event_param->GetAsDictionary(&dict) ||
1343 !dict->GetList("headers", &header_list)) {
1344 return false;
1347 std::string raw_headers;
1348 for (base::ListValue::const_iterator it = header_list->begin();
1349 it != header_list->end();
1350 ++it) {
1351 std::string header_line;
1352 if (!(*it)->GetAsString(&header_line))
1353 return false;
1355 raw_headers.append(header_line);
1356 raw_headers.push_back('\0');
1358 raw_headers.push_back('\0');
1359 *http_response_headers = new HttpResponseHeaders(raw_headers);
1360 return true;
1363 bool HttpResponseHeaders::IsChunkEncoded() const {
1364 // Ignore spurious chunked responses from HTTP/1.0 servers and proxies.
1365 return GetHttpVersion() >= HttpVersion(1, 1) &&
1366 HasHeaderValue("Transfer-Encoding", "chunked");
1369 #if defined(SPDY_PROXY_AUTH_ORIGIN)
1370 bool HttpResponseHeaders::GetChromeProxyBypassDuration(
1371 const std::string& action_prefix,
1372 base::TimeDelta* duration) const {
1373 void* iter = NULL;
1374 std::string value;
1375 std::string name = "chrome-proxy";
1377 while (EnumerateHeader(&iter, name, &value)) {
1378 if (value.size() > action_prefix.size()) {
1379 if (LowerCaseEqualsASCII(value.begin(),
1380 value.begin() + action_prefix.size(),
1381 action_prefix.c_str())) {
1382 int64 seconds;
1383 if (!base::StringToInt64(
1384 StringPiece(value.begin() + action_prefix.size(), value.end()),
1385 &seconds) || seconds < 0) {
1386 continue; // In case there is a well formed instruction.
1388 *duration = TimeDelta::FromSeconds(seconds);
1389 return true;
1393 return false;
1396 bool HttpResponseHeaders::GetChromeProxyInfo(
1397 ChromeProxyInfo* proxy_info) const {
1398 DCHECK(proxy_info);
1399 proxy_info->bypass_all = false;
1400 proxy_info->bypass_duration = base::TimeDelta();
1402 // Support header of the form Chrome-Proxy: bypass|block=<duration>, where
1403 // <duration> is the number of seconds to wait before retrying
1404 // the proxy. If the duration is 0, then the default proxy retry delay
1405 // (specified in |ProxyList::UpdateRetryInfoOnFallback|) will be used.
1406 // 'bypass' instructs Chrome to bypass the currently connected Chrome proxy,
1407 // whereas 'block' instructs Chrome to bypass all available Chrome proxies.
1409 // 'block' takes precedence over 'bypass', so look for it first.
1410 // TODO(bengr): Reduce checks for 'block' and 'bypass' to a single loop.
1411 if (GetChromeProxyBypassDuration("block=", &proxy_info->bypass_duration)) {
1412 proxy_info->bypass_all = true;
1413 return true;
1416 // Next, look for 'bypass'.
1417 if (GetChromeProxyBypassDuration("bypass=", &proxy_info->bypass_duration))
1418 return true;
1420 return false;
1423 bool HttpResponseHeaders::IsChromeProxyResponse() const {
1424 const size_t kVersionSize = 4;
1425 const char kChromeProxyViaValue[] = "Chrome-Compression-Proxy";
1426 size_t value_len = strlen(kChromeProxyViaValue);
1427 void* iter = NULL;
1428 std::string value;
1430 // Case-sensitive comparison of |value|. Assumes the received protocol and the
1431 // space following it are always |kVersionSize| characters. E.g.,
1432 // 'Via: 1.1 Chrome-Compression-Proxy'
1433 while (EnumerateHeader(&iter, "via", &value)) {
1434 if (!value.compare(kVersionSize, value_len, kChromeProxyViaValue))
1435 return true;
1438 // TODO(bengr): Remove deprecated header value.
1439 const char kDeprecatedChromeProxyViaValue[] = "1.1 Chrome Compression Proxy";
1440 iter = NULL;
1441 while (EnumerateHeader(&iter, "via", &value))
1442 if (value == kDeprecatedChromeProxyViaValue)
1443 return true;
1445 return false;
1447 #endif // defined(SPDY_PROXY_AUTH_ORIGIN)
1449 } // namespace net