Switch global error menu icon to vectorized MD asset
[chromium-blink-merge.git] / net / http / http_response_headers.cc
blobc535e0ab64e1d815972aede695d53b071770fa96
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/format_macros.h"
15 #include "base/logging.h"
16 #include "base/metrics/histogram_macros.h"
17 #include "base/pickle.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_piece.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/stringprintf.h"
22 #include "base/time/time.h"
23 #include "base/values.h"
24 #include "net/base/escape.h"
25 #include "net/http/http_byte_range.h"
26 #include "net/http/http_log_util.h"
27 #include "net/http/http_util.h"
29 using base::StringPiece;
30 using base::Time;
31 using base::TimeDelta;
33 namespace net {
35 //-----------------------------------------------------------------------------
37 namespace {
39 // These headers are RFC 2616 hop-by-hop headers;
40 // not to be stored by caches.
41 const char* const kHopByHopResponseHeaders[] = {
42 "connection",
43 "proxy-connection",
44 "keep-alive",
45 "trailer",
46 "transfer-encoding",
47 "upgrade"
50 // These headers are challenge response headers;
51 // not to be stored by caches.
52 const char* const kChallengeResponseHeaders[] = {
53 "www-authenticate",
54 "proxy-authenticate"
57 // These headers are cookie setting headers;
58 // not to be stored by caches or disclosed otherwise.
59 const char* const kCookieResponseHeaders[] = {
60 "set-cookie",
61 "set-cookie2"
64 // By default, do not cache Strict-Transport-Security or Public-Key-Pins.
65 // This avoids erroneously re-processing them on page loads from cache ---
66 // they are defined to be valid only on live and error-free HTTPS
67 // connections.
68 const char* const kSecurityStateHeaders[] = {
69 "strict-transport-security",
70 "public-key-pins"
73 // These response headers are not copied from a 304/206 response to the cached
74 // response headers. This list is based on Mozilla's nsHttpResponseHead.cpp.
75 const char* const kNonUpdatedHeaders[] = {
76 "connection",
77 "proxy-connection",
78 "keep-alive",
79 "www-authenticate",
80 "proxy-authenticate",
81 "trailer",
82 "transfer-encoding",
83 "upgrade",
84 "etag",
85 "x-frame-options",
86 "x-xss-protection",
89 // Some header prefixes mean "Don't copy this header from a 304 response.".
90 // Rather than listing all the relevant headers, we can consolidate them into
91 // this list:
92 const char* const kNonUpdatedHeaderPrefixes[] = {
93 "content-",
94 "x-content-",
95 "x-webkit-"
98 bool ShouldUpdateHeader(base::StringPiece name) {
99 for (size_t i = 0; i < arraysize(kNonUpdatedHeaders); ++i) {
100 if (base::LowerCaseEqualsASCII(name, kNonUpdatedHeaders[i]))
101 return false;
103 for (size_t i = 0; i < arraysize(kNonUpdatedHeaderPrefixes); ++i) {
104 if (base::StartsWith(name, kNonUpdatedHeaderPrefixes[i],
105 base::CompareCase::INSENSITIVE_ASCII))
106 return false;
108 return true;
111 void CheckDoesNotHaveEmbededNulls(const std::string& str) {
112 // Care needs to be taken when adding values to the raw headers string to
113 // make sure it does not contain embeded NULLs. Any embeded '\0' may be
114 // understood as line terminators and change how header lines get tokenized.
115 CHECK(str.find('\0') == std::string::npos);
118 } // namespace
120 const char HttpResponseHeaders::kContentRange[] = "Content-Range";
122 struct HttpResponseHeaders::ParsedHeader {
123 // A header "continuation" contains only a subsequent value for the
124 // preceding header. (Header values are comma separated.)
125 bool is_continuation() const { return name_begin == name_end; }
127 std::string::const_iterator name_begin;
128 std::string::const_iterator name_end;
129 std::string::const_iterator value_begin;
130 std::string::const_iterator value_end;
133 //-----------------------------------------------------------------------------
135 HttpResponseHeaders::HttpResponseHeaders(const std::string& raw_input)
136 : response_code_(-1) {
137 Parse(raw_input);
139 // The most important thing to do with this histogram is find out
140 // the existence of unusual HTTP status codes. As it happens
141 // right now, there aren't double-constructions of response headers
142 // using this constructor, so our counts should also be accurate,
143 // without instantiating the histogram in two places. It is also
144 // important that this histogram not collect data in the other
145 // constructor, which rebuilds an histogram from a pickle, since
146 // that would actually create a double call between the original
147 // HttpResponseHeader that was serialized, and initialization of the
148 // new object from that pickle.
149 UMA_HISTOGRAM_CUSTOM_ENUMERATION("Net.HttpResponseCode",
150 HttpUtil::MapStatusCodeForHistogram(
151 response_code_),
152 // Note the third argument is only
153 // evaluated once, see macro
154 // definition for details.
155 HttpUtil::GetStatusCodesForHistogram());
158 HttpResponseHeaders::HttpResponseHeaders(base::PickleIterator* iter)
159 : response_code_(-1) {
160 std::string raw_input;
161 if (iter->ReadString(&raw_input))
162 Parse(raw_input);
165 void HttpResponseHeaders::Persist(base::Pickle* pickle,
166 PersistOptions options) {
167 if (options == PERSIST_RAW) {
168 pickle->WriteString(raw_headers_);
169 return; // Done.
172 HeaderSet filter_headers;
174 // Construct set of headers to filter out based on options.
175 if ((options & PERSIST_SANS_NON_CACHEABLE) == PERSIST_SANS_NON_CACHEABLE)
176 AddNonCacheableHeaders(&filter_headers);
178 if ((options & PERSIST_SANS_COOKIES) == PERSIST_SANS_COOKIES)
179 AddCookieHeaders(&filter_headers);
181 if ((options & PERSIST_SANS_CHALLENGES) == PERSIST_SANS_CHALLENGES)
182 AddChallengeHeaders(&filter_headers);
184 if ((options & PERSIST_SANS_HOP_BY_HOP) == PERSIST_SANS_HOP_BY_HOP)
185 AddHopByHopHeaders(&filter_headers);
187 if ((options & PERSIST_SANS_RANGES) == PERSIST_SANS_RANGES)
188 AddHopContentRangeHeaders(&filter_headers);
190 if ((options & PERSIST_SANS_SECURITY_STATE) == PERSIST_SANS_SECURITY_STATE)
191 AddSecurityStateHeaders(&filter_headers);
193 std::string blob;
194 blob.reserve(raw_headers_.size());
196 // This copies the status line w/ terminator null.
197 // Note raw_headers_ has embedded nulls instead of \n,
198 // so this just copies the first header line.
199 blob.assign(raw_headers_.c_str(), strlen(raw_headers_.c_str()) + 1);
201 for (size_t i = 0; i < parsed_.size(); ++i) {
202 DCHECK(!parsed_[i].is_continuation());
204 // Locate the start of the next header.
205 size_t k = i;
206 while (++k < parsed_.size() && parsed_[k].is_continuation()) {}
207 --k;
209 std::string header_name = base::ToLowerASCII(
210 base::StringPiece(parsed_[i].name_begin, parsed_[i].name_end));
211 if (filter_headers.find(header_name) == filter_headers.end()) {
212 // Make sure there is a null after the value.
213 blob.append(parsed_[i].name_begin, parsed_[k].value_end);
214 blob.push_back('\0');
217 i = k;
219 blob.push_back('\0');
221 pickle->WriteString(blob);
224 void HttpResponseHeaders::Update(const HttpResponseHeaders& new_headers) {
225 DCHECK(new_headers.response_code() == 304 ||
226 new_headers.response_code() == 206);
228 // Copy up to the null byte. This just copies the status line.
229 std::string new_raw_headers(raw_headers_.c_str());
230 new_raw_headers.push_back('\0');
232 HeaderSet updated_headers;
234 // NOTE: we write the new headers then the old headers for convenience. The
235 // order should not matter.
237 // Figure out which headers we want to take from new_headers:
238 for (size_t i = 0; i < new_headers.parsed_.size(); ++i) {
239 const HeaderList& new_parsed = new_headers.parsed_;
241 DCHECK(!new_parsed[i].is_continuation());
243 // Locate the start of the next header.
244 size_t k = i;
245 while (++k < new_parsed.size() && new_parsed[k].is_continuation()) {}
246 --k;
248 base::StringPiece name(new_parsed[i].name_begin, new_parsed[i].name_end);
249 if (ShouldUpdateHeader(name)) {
250 std::string name_lower = base::ToLowerASCII(name);
251 updated_headers.insert(name_lower);
253 // Preserve this header line in the merged result, making sure there is
254 // a null after the value.
255 new_raw_headers.append(new_parsed[i].name_begin, new_parsed[k].value_end);
256 new_raw_headers.push_back('\0');
259 i = k;
262 // Now, build the new raw headers.
263 MergeWithHeaders(new_raw_headers, updated_headers);
266 void HttpResponseHeaders::MergeWithHeaders(const std::string& raw_headers,
267 const HeaderSet& headers_to_remove) {
268 std::string new_raw_headers(raw_headers);
269 for (size_t i = 0; i < parsed_.size(); ++i) {
270 DCHECK(!parsed_[i].is_continuation());
272 // Locate the start of the next header.
273 size_t k = i;
274 while (++k < parsed_.size() && parsed_[k].is_continuation()) {}
275 --k;
277 std::string name = base::ToLowerASCII(
278 base::StringPiece(parsed_[i].name_begin, parsed_[i].name_end));
279 if (headers_to_remove.find(name) == headers_to_remove.end()) {
280 // It's ok to preserve this header in the final result.
281 new_raw_headers.append(parsed_[i].name_begin, parsed_[k].value_end);
282 new_raw_headers.push_back('\0');
285 i = k;
287 new_raw_headers.push_back('\0');
289 // Make this object hold the new data.
290 raw_headers_.clear();
291 parsed_.clear();
292 Parse(new_raw_headers);
295 void HttpResponseHeaders::RemoveHeader(const std::string& name) {
296 // Copy up to the null byte. This just copies the status line.
297 std::string new_raw_headers(raw_headers_.c_str());
298 new_raw_headers.push_back('\0');
300 std::string lowercase_name = base::ToLowerASCII(name);
301 HeaderSet to_remove;
302 to_remove.insert(lowercase_name);
303 MergeWithHeaders(new_raw_headers, to_remove);
306 void HttpResponseHeaders::RemoveHeaderLine(const std::string& name,
307 const std::string& value) {
308 std::string name_lowercase = base::ToLowerASCII(name);
310 std::string new_raw_headers(GetStatusLine());
311 new_raw_headers.push_back('\0');
313 new_raw_headers.reserve(raw_headers_.size());
315 void* iter = NULL;
316 std::string old_header_name;
317 std::string old_header_value;
318 while (EnumerateHeaderLines(&iter, &old_header_name, &old_header_value)) {
319 std::string old_header_name_lowercase = base::ToLowerASCII(old_header_name);
320 if (name_lowercase == old_header_name_lowercase &&
321 value == old_header_value)
322 continue;
324 new_raw_headers.append(old_header_name);
325 new_raw_headers.push_back(':');
326 new_raw_headers.push_back(' ');
327 new_raw_headers.append(old_header_value);
328 new_raw_headers.push_back('\0');
330 new_raw_headers.push_back('\0');
332 // Make this object hold the new data.
333 raw_headers_.clear();
334 parsed_.clear();
335 Parse(new_raw_headers);
338 void HttpResponseHeaders::AddHeader(const std::string& header) {
339 CheckDoesNotHaveEmbededNulls(header);
340 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 2]);
341 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 1]);
342 // Don't copy the last null.
343 std::string new_raw_headers(raw_headers_, 0, raw_headers_.size() - 1);
344 new_raw_headers.append(header);
345 new_raw_headers.push_back('\0');
346 new_raw_headers.push_back('\0');
348 // Make this object hold the new data.
349 raw_headers_.clear();
350 parsed_.clear();
351 Parse(new_raw_headers);
354 void HttpResponseHeaders::ReplaceStatusLine(const std::string& new_status) {
355 CheckDoesNotHaveEmbededNulls(new_status);
356 // Copy up to the null byte. This just copies the status line.
357 std::string new_raw_headers(new_status);
358 new_raw_headers.push_back('\0');
360 HeaderSet empty_to_remove;
361 MergeWithHeaders(new_raw_headers, empty_to_remove);
364 void HttpResponseHeaders::UpdateWithNewRange(
365 const HttpByteRange& byte_range,
366 int64 resource_size,
367 bool replace_status_line) {
368 DCHECK(byte_range.IsValid());
369 DCHECK(byte_range.HasFirstBytePosition());
370 DCHECK(byte_range.HasLastBytePosition());
372 const char kLengthHeader[] = "Content-Length";
373 const char kRangeHeader[] = "Content-Range";
375 RemoveHeader(kLengthHeader);
376 RemoveHeader(kRangeHeader);
378 int64 start = byte_range.first_byte_position();
379 int64 end = byte_range.last_byte_position();
380 int64 range_len = end - start + 1;
382 if (replace_status_line)
383 ReplaceStatusLine("HTTP/1.1 206 Partial Content");
385 AddHeader(base::StringPrintf("%s: bytes %" PRId64 "-%" PRId64 "/%" PRId64,
386 kRangeHeader, start, end, resource_size));
387 AddHeader(base::StringPrintf("%s: %" PRId64, kLengthHeader, range_len));
390 void HttpResponseHeaders::Parse(const std::string& raw_input) {
391 raw_headers_.reserve(raw_input.size());
393 // ParseStatusLine adds a normalized status line to raw_headers_
394 std::string::const_iterator line_begin = raw_input.begin();
395 std::string::const_iterator line_end =
396 std::find(line_begin, raw_input.end(), '\0');
397 // has_headers = true, if there is any data following the status line.
398 // Used by ParseStatusLine() to decide if a HTTP/0.9 is really a HTTP/1.0.
399 bool has_headers = (line_end != raw_input.end() &&
400 (line_end + 1) != raw_input.end() &&
401 *(line_end + 1) != '\0');
402 ParseStatusLine(line_begin, line_end, has_headers);
403 raw_headers_.push_back('\0'); // Terminate status line with a null.
405 if (line_end == raw_input.end()) {
406 raw_headers_.push_back('\0'); // Ensure the headers end with a double null.
408 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 2]);
409 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 1]);
410 return;
413 // Including a terminating null byte.
414 size_t status_line_len = raw_headers_.size();
416 // Now, we add the rest of the raw headers to raw_headers_, and begin parsing
417 // it (to populate our parsed_ vector).
418 raw_headers_.append(line_end + 1, raw_input.end());
420 // Ensure the headers end with a double null.
421 while (raw_headers_.size() < 2 ||
422 raw_headers_[raw_headers_.size() - 2] != '\0' ||
423 raw_headers_[raw_headers_.size() - 1] != '\0') {
424 raw_headers_.push_back('\0');
427 // Adjust to point at the null byte following the status line
428 line_end = raw_headers_.begin() + status_line_len - 1;
430 HttpUtil::HeadersIterator headers(line_end + 1, raw_headers_.end(),
431 std::string(1, '\0'));
432 while (headers.GetNext()) {
433 AddHeader(headers.name_begin(),
434 headers.name_end(),
435 headers.values_begin(),
436 headers.values_end());
439 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 2]);
440 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 1]);
443 // Append all of our headers to the final output string.
444 void HttpResponseHeaders::GetNormalizedHeaders(std::string* output) const {
445 // copy up to the null byte. this just copies the status line.
446 output->assign(raw_headers_.c_str());
448 // headers may appear multiple times (not necessarily in succession) in the
449 // header data, so we build a map from header name to generated header lines.
450 // to preserve the order of the original headers, the actual values are kept
451 // in a separate list. finally, the list of headers is flattened to form
452 // the normalized block of headers.
454 // NOTE: We take special care to preserve the whitespace around any commas
455 // that may occur in the original response headers. Because our consumer may
456 // be a web app, we cannot be certain of the semantics of commas despite the
457 // fact that RFC 2616 says that they should be regarded as value separators.
459 typedef base::hash_map<std::string, size_t> HeadersMap;
460 HeadersMap headers_map;
461 HeadersMap::iterator iter = headers_map.end();
463 std::vector<std::string> headers;
465 for (size_t i = 0; i < parsed_.size(); ++i) {
466 DCHECK(!parsed_[i].is_continuation());
468 std::string name(parsed_[i].name_begin, parsed_[i].name_end);
469 std::string lower_name = base::ToLowerASCII(name);
471 iter = headers_map.find(lower_name);
472 if (iter == headers_map.end()) {
473 iter = headers_map.insert(
474 HeadersMap::value_type(lower_name, headers.size())).first;
475 headers.push_back(name + ": ");
476 } else {
477 headers[iter->second].append(", ");
480 std::string::const_iterator value_begin = parsed_[i].value_begin;
481 std::string::const_iterator value_end = parsed_[i].value_end;
482 while (++i < parsed_.size() && parsed_[i].is_continuation())
483 value_end = parsed_[i].value_end;
484 --i;
486 headers[iter->second].append(value_begin, value_end);
489 for (size_t i = 0; i < headers.size(); ++i) {
490 output->push_back('\n');
491 output->append(headers[i]);
494 output->push_back('\n');
497 bool HttpResponseHeaders::GetNormalizedHeader(const std::string& name,
498 std::string* value) const {
499 // If you hit this assertion, please use EnumerateHeader instead!
500 DCHECK(!HttpUtil::IsNonCoalescingHeader(name));
502 value->clear();
504 bool found = false;
505 size_t i = 0;
506 while (i < parsed_.size()) {
507 i = FindHeader(i, name);
508 if (i == std::string::npos)
509 break;
511 found = true;
513 if (!value->empty())
514 value->append(", ");
516 std::string::const_iterator value_begin = parsed_[i].value_begin;
517 std::string::const_iterator value_end = parsed_[i].value_end;
518 while (++i < parsed_.size() && parsed_[i].is_continuation())
519 value_end = parsed_[i].value_end;
520 value->append(value_begin, value_end);
523 return found;
526 std::string HttpResponseHeaders::GetStatusLine() const {
527 // copy up to the null byte.
528 return std::string(raw_headers_.c_str());
531 std::string HttpResponseHeaders::GetStatusText() const {
532 // GetStatusLine() is already normalized, so it has the format:
533 // <http_version> SP <response_code> SP <status_text>
534 std::string status_text = GetStatusLine();
535 std::string::const_iterator begin = status_text.begin();
536 std::string::const_iterator end = status_text.end();
537 for (int i = 0; i < 2; ++i)
538 begin = std::find(begin, end, ' ') + 1;
539 return std::string(begin, end);
542 bool HttpResponseHeaders::EnumerateHeaderLines(void** iter,
543 std::string* name,
544 std::string* value) const {
545 size_t i = reinterpret_cast<size_t>(*iter);
546 if (i == parsed_.size())
547 return false;
549 DCHECK(!parsed_[i].is_continuation());
551 name->assign(parsed_[i].name_begin, parsed_[i].name_end);
553 std::string::const_iterator value_begin = parsed_[i].value_begin;
554 std::string::const_iterator value_end = parsed_[i].value_end;
555 while (++i < parsed_.size() && parsed_[i].is_continuation())
556 value_end = parsed_[i].value_end;
558 value->assign(value_begin, value_end);
560 *iter = reinterpret_cast<void*>(i);
561 return true;
564 bool HttpResponseHeaders::EnumerateHeader(void** iter,
565 const base::StringPiece& name,
566 std::string* value) const {
567 size_t i;
568 if (!iter || !*iter) {
569 i = FindHeader(0, name);
570 } else {
571 i = reinterpret_cast<size_t>(*iter);
572 if (i >= parsed_.size()) {
573 i = std::string::npos;
574 } else if (!parsed_[i].is_continuation()) {
575 i = FindHeader(i, name);
579 if (i == std::string::npos) {
580 value->clear();
581 return false;
584 if (iter)
585 *iter = reinterpret_cast<void*>(i + 1);
586 value->assign(parsed_[i].value_begin, parsed_[i].value_end);
587 return true;
590 bool HttpResponseHeaders::HasHeaderValue(const base::StringPiece& name,
591 const base::StringPiece& value) const {
592 // The value has to be an exact match. This is important since
593 // 'cache-control: no-cache' != 'cache-control: no-cache="foo"'
594 void* iter = NULL;
595 std::string temp;
596 while (EnumerateHeader(&iter, name, &temp)) {
597 if (base::EqualsCaseInsensitiveASCII(value, temp))
598 return true;
600 return false;
603 bool HttpResponseHeaders::HasHeader(const base::StringPiece& name) const {
604 return FindHeader(0, name) != std::string::npos;
607 HttpResponseHeaders::HttpResponseHeaders() : response_code_(-1) {
610 HttpResponseHeaders::~HttpResponseHeaders() {
613 // Note: this implementation implicitly assumes that line_end points at a valid
614 // sentinel character (such as '\0').
615 // static
616 HttpVersion HttpResponseHeaders::ParseVersion(
617 std::string::const_iterator line_begin,
618 std::string::const_iterator line_end) {
619 std::string::const_iterator p = line_begin;
621 // RFC2616 sec 3.1: HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT
622 // TODO: (1*DIGIT apparently means one or more digits, but we only handle 1).
623 // TODO: handle leading zeros, which is allowed by the rfc1616 sec 3.1.
625 if (!base::StartsWith(base::StringPiece(line_begin, line_end), "http",
626 base::CompareCase::INSENSITIVE_ASCII)) {
627 DVLOG(1) << "missing status line";
628 return HttpVersion();
631 p += 4;
633 if (p >= line_end || *p != '/') {
634 DVLOG(1) << "missing version";
635 return HttpVersion();
638 std::string::const_iterator dot = std::find(p, line_end, '.');
639 if (dot == line_end) {
640 DVLOG(1) << "malformed version";
641 return HttpVersion();
644 ++p; // from / to first digit.
645 ++dot; // from . to second digit.
647 if (!(*p >= '0' && *p <= '9' && *dot >= '0' && *dot <= '9')) {
648 DVLOG(1) << "malformed version number";
649 return HttpVersion();
652 uint16 major = *p - '0';
653 uint16 minor = *dot - '0';
655 return HttpVersion(major, minor);
658 // Note: this implementation implicitly assumes that line_end points at a valid
659 // sentinel character (such as '\0').
660 void HttpResponseHeaders::ParseStatusLine(
661 std::string::const_iterator line_begin,
662 std::string::const_iterator line_end,
663 bool has_headers) {
664 // Extract the version number
665 parsed_http_version_ = ParseVersion(line_begin, line_end);
667 // Clamp the version number to one of: {0.9, 1.0, 1.1}
668 if (parsed_http_version_ == HttpVersion(0, 9) && !has_headers) {
669 http_version_ = HttpVersion(0, 9);
670 raw_headers_ = "HTTP/0.9";
671 } else if (parsed_http_version_ >= HttpVersion(1, 1)) {
672 http_version_ = HttpVersion(1, 1);
673 raw_headers_ = "HTTP/1.1";
674 } else {
675 // Treat everything else like HTTP 1.0
676 http_version_ = HttpVersion(1, 0);
677 raw_headers_ = "HTTP/1.0";
679 if (parsed_http_version_ != http_version_) {
680 DVLOG(1) << "assuming HTTP/" << http_version_.major_value() << "."
681 << http_version_.minor_value();
684 // TODO(eroman): this doesn't make sense if ParseVersion failed.
685 std::string::const_iterator p = std::find(line_begin, line_end, ' ');
687 if (p == line_end) {
688 DVLOG(1) << "missing response status; assuming 200 OK";
689 raw_headers_.append(" 200 OK");
690 response_code_ = 200;
691 return;
694 // Skip whitespace.
695 while (*p == ' ')
696 ++p;
698 std::string::const_iterator code = p;
699 while (*p >= '0' && *p <= '9')
700 ++p;
702 if (p == code) {
703 DVLOG(1) << "missing response status number; assuming 200";
704 raw_headers_.append(" 200 OK");
705 response_code_ = 200;
706 return;
708 raw_headers_.push_back(' ');
709 raw_headers_.append(code, p);
710 raw_headers_.push_back(' ');
711 base::StringToInt(StringPiece(code, p), &response_code_);
713 // Skip whitespace.
714 while (*p == ' ')
715 ++p;
717 // Trim trailing whitespace.
718 while (line_end > p && line_end[-1] == ' ')
719 --line_end;
721 if (p == line_end) {
722 DVLOG(1) << "missing response status text; assuming OK";
723 // Not super critical what we put here. Just use "OK"
724 // even if it isn't descriptive of response_code_.
725 raw_headers_.append("OK");
726 } else {
727 raw_headers_.append(p, line_end);
731 size_t HttpResponseHeaders::FindHeader(size_t from,
732 const base::StringPiece& search) const {
733 for (size_t i = from; i < parsed_.size(); ++i) {
734 if (parsed_[i].is_continuation())
735 continue;
736 base::StringPiece name(parsed_[i].name_begin, parsed_[i].name_end);
737 if (base::EqualsCaseInsensitiveASCII(search, name))
738 return i;
741 return std::string::npos;
744 bool HttpResponseHeaders::GetCacheControlDirective(const StringPiece& directive,
745 TimeDelta* result) const {
746 StringPiece name("cache-control");
747 std::string value;
749 size_t directive_size = directive.size();
751 void* iter = NULL;
752 while (EnumerateHeader(&iter, name, &value)) {
753 if (value.size() > directive_size + 1 &&
754 base::StartsWith(value, directive,
755 base::CompareCase::INSENSITIVE_ASCII) &&
756 value[directive_size] == '=') {
757 int64 seconds;
758 base::StringToInt64(
759 StringPiece(value.begin() + directive_size + 1, value.end()),
760 &seconds);
761 *result = TimeDelta::FromSeconds(seconds);
762 return true;
766 return false;
769 void HttpResponseHeaders::AddHeader(std::string::const_iterator name_begin,
770 std::string::const_iterator name_end,
771 std::string::const_iterator values_begin,
772 std::string::const_iterator values_end) {
773 // If the header can be coalesced, then we should split it up.
774 if (values_begin == values_end ||
775 HttpUtil::IsNonCoalescingHeader(name_begin, name_end)) {
776 AddToParsed(name_begin, name_end, values_begin, values_end);
777 } else {
778 HttpUtil::ValuesIterator it(values_begin, values_end, ',');
779 while (it.GetNext()) {
780 AddToParsed(name_begin, name_end, it.value_begin(), it.value_end());
781 // clobber these so that subsequent values are treated as continuations
782 name_begin = name_end = raw_headers_.end();
787 void HttpResponseHeaders::AddToParsed(std::string::const_iterator name_begin,
788 std::string::const_iterator name_end,
789 std::string::const_iterator value_begin,
790 std::string::const_iterator value_end) {
791 ParsedHeader header;
792 header.name_begin = name_begin;
793 header.name_end = name_end;
794 header.value_begin = value_begin;
795 header.value_end = value_end;
796 parsed_.push_back(header);
799 void HttpResponseHeaders::AddNonCacheableHeaders(HeaderSet* result) const {
800 // Add server specified transients. Any 'cache-control: no-cache="foo,bar"'
801 // headers present in the response specify additional headers that we should
802 // not store in the cache.
803 const char kCacheControl[] = "cache-control";
804 const char kPrefix[] = "no-cache=\"";
805 const size_t kPrefixLen = sizeof(kPrefix) - 1;
807 std::string value;
808 void* iter = NULL;
809 while (EnumerateHeader(&iter, kCacheControl, &value)) {
810 // If the value is smaller than the prefix and a terminal quote, skip
811 // it.
812 if (value.size() <= kPrefixLen ||
813 value.compare(0, kPrefixLen, kPrefix) != 0) {
814 continue;
816 // if it doesn't end with a quote, then treat as malformed
817 if (value[value.size()-1] != '\"')
818 continue;
820 // process the value as a comma-separated list of items. Each
821 // item can be wrapped by linear white space.
822 std::string::const_iterator item = value.begin() + kPrefixLen;
823 std::string::const_iterator end = value.end() - 1;
824 while (item != end) {
825 // Find the comma to compute the length of the current item,
826 // and the position of the next one.
827 std::string::const_iterator item_next = std::find(item, end, ',');
828 std::string::const_iterator item_end = end;
829 if (item_next != end) {
830 // Skip over comma for next position.
831 item_end = item_next;
832 item_next++;
834 // trim off leading and trailing whitespace in this item.
835 HttpUtil::TrimLWS(&item, &item_end);
837 // assuming the header is not empty, lowercase and insert into set
838 if (item_end > item) {
839 result->insert(
840 base::ToLowerASCII(base::StringPiece(&*item, item_end - item)));
843 // Continue to next item.
844 item = item_next;
849 void HttpResponseHeaders::AddHopByHopHeaders(HeaderSet* result) {
850 for (size_t i = 0; i < arraysize(kHopByHopResponseHeaders); ++i)
851 result->insert(std::string(kHopByHopResponseHeaders[i]));
854 void HttpResponseHeaders::AddCookieHeaders(HeaderSet* result) {
855 for (size_t i = 0; i < arraysize(kCookieResponseHeaders); ++i)
856 result->insert(std::string(kCookieResponseHeaders[i]));
859 void HttpResponseHeaders::AddChallengeHeaders(HeaderSet* result) {
860 for (size_t i = 0; i < arraysize(kChallengeResponseHeaders); ++i)
861 result->insert(std::string(kChallengeResponseHeaders[i]));
864 void HttpResponseHeaders::AddHopContentRangeHeaders(HeaderSet* result) {
865 result->insert(kContentRange);
868 void HttpResponseHeaders::AddSecurityStateHeaders(HeaderSet* result) {
869 for (size_t i = 0; i < arraysize(kSecurityStateHeaders); ++i)
870 result->insert(std::string(kSecurityStateHeaders[i]));
873 void HttpResponseHeaders::GetMimeTypeAndCharset(std::string* mime_type,
874 std::string* charset) const {
875 mime_type->clear();
876 charset->clear();
878 std::string name = "content-type";
879 std::string value;
881 bool had_charset = false;
883 void* iter = NULL;
884 while (EnumerateHeader(&iter, name, &value))
885 HttpUtil::ParseContentType(value, mime_type, charset, &had_charset, NULL);
888 bool HttpResponseHeaders::GetMimeType(std::string* mime_type) const {
889 std::string unused;
890 GetMimeTypeAndCharset(mime_type, &unused);
891 return !mime_type->empty();
894 bool HttpResponseHeaders::GetCharset(std::string* charset) const {
895 std::string unused;
896 GetMimeTypeAndCharset(&unused, charset);
897 return !charset->empty();
900 bool HttpResponseHeaders::IsRedirect(std::string* location) const {
901 if (!IsRedirectResponseCode(response_code_))
902 return false;
904 // If we lack a Location header, then we can't treat this as a redirect.
905 // We assume that the first non-empty location value is the target URL that
906 // we want to follow. TODO(darin): Is this consistent with other browsers?
907 size_t i = std::string::npos;
908 do {
909 i = FindHeader(++i, "location");
910 if (i == std::string::npos)
911 return false;
912 // If the location value is empty, then it doesn't count.
913 } while (parsed_[i].value_begin == parsed_[i].value_end);
915 if (location) {
916 // Escape any non-ASCII characters to preserve them. The server should
917 // only be returning ASCII here, but for compat we need to do this.
918 *location = EscapeNonASCII(
919 std::string(parsed_[i].value_begin, parsed_[i].value_end));
922 return true;
925 // static
926 bool HttpResponseHeaders::IsRedirectResponseCode(int response_code) {
927 // Users probably want to see 300 (multiple choice) pages, so we don't count
928 // them as redirects that need to be followed.
929 return (response_code == 301 ||
930 response_code == 302 ||
931 response_code == 303 ||
932 response_code == 307 ||
933 response_code == 308);
936 // From RFC 2616 section 13.2.4:
938 // The calculation to determine if a response has expired is quite simple:
940 // response_is_fresh = (freshness_lifetime > current_age)
942 // Of course, there are other factors that can force a response to always be
943 // validated or re-fetched.
945 // From RFC 5861 section 3, a stale response may be used while revalidation is
946 // performed in the background if
948 // freshness_lifetime + stale_while_revalidate > current_age
950 ValidationType HttpResponseHeaders::RequiresValidation(
951 const Time& request_time,
952 const Time& response_time,
953 const Time& current_time) const {
954 FreshnessLifetimes lifetimes = GetFreshnessLifetimes(response_time);
955 if (lifetimes.freshness == TimeDelta() && lifetimes.staleness == TimeDelta())
956 return VALIDATION_SYNCHRONOUS;
958 TimeDelta age = GetCurrentAge(request_time, response_time, current_time);
960 if (lifetimes.freshness > age)
961 return VALIDATION_NONE;
963 if (lifetimes.freshness + lifetimes.staleness > age)
964 return VALIDATION_ASYNCHRONOUS;
966 return VALIDATION_SYNCHRONOUS;
969 // From RFC 2616 section 13.2.4:
971 // The max-age directive takes priority over Expires, so if max-age is present
972 // in a response, the calculation is simply:
974 // freshness_lifetime = max_age_value
976 // Otherwise, if Expires is present in the response, the calculation is:
978 // freshness_lifetime = expires_value - date_value
980 // Note that neither of these calculations is vulnerable to clock skew, since
981 // all of the information comes from the origin server.
983 // Also, if the response does have a Last-Modified time, the heuristic
984 // expiration value SHOULD be no more than some fraction of the interval since
985 // that time. A typical setting of this fraction might be 10%:
987 // freshness_lifetime = (date_value - last_modified_value) * 0.10
989 // If the stale-while-revalidate directive is present, then it is used to set
990 // the |staleness| time, unless it overridden by another directive.
992 HttpResponseHeaders::FreshnessLifetimes
993 HttpResponseHeaders::GetFreshnessLifetimes(const Time& response_time) const {
994 FreshnessLifetimes lifetimes;
995 // Check for headers that force a response to never be fresh. For backwards
996 // compat, we treat "Pragma: no-cache" as a synonym for "Cache-Control:
997 // no-cache" even though RFC 2616 does not specify it.
998 if (HasHeaderValue("cache-control", "no-cache") ||
999 HasHeaderValue("cache-control", "no-store") ||
1000 HasHeaderValue("pragma", "no-cache") ||
1001 // Vary: * is never usable: see RFC 2616 section 13.6.
1002 HasHeaderValue("vary", "*")) {
1003 return lifetimes;
1006 // Cache-Control directive must_revalidate overrides stale-while-revalidate.
1007 bool must_revalidate = HasHeaderValue("cache-control", "must-revalidate");
1009 if (must_revalidate || !GetStaleWhileRevalidateValue(&lifetimes.staleness)) {
1010 DCHECK_EQ(TimeDelta(), lifetimes.staleness);
1013 // NOTE: "Cache-Control: max-age" overrides Expires, so we only check the
1014 // Expires header after checking for max-age in GetFreshnessLifetimes. This
1015 // is important since "Expires: <date in the past>" means not fresh, but
1016 // it should not trump a max-age value.
1017 if (GetMaxAgeValue(&lifetimes.freshness))
1018 return lifetimes;
1020 // If there is no Date header, then assume that the server response was
1021 // generated at the time when we received the response.
1022 Time date_value;
1023 if (!GetDateValue(&date_value))
1024 date_value = response_time;
1026 Time expires_value;
1027 if (GetExpiresValue(&expires_value)) {
1028 // The expires value can be a date in the past!
1029 if (expires_value > date_value) {
1030 lifetimes.freshness = expires_value - date_value;
1031 return lifetimes;
1034 DCHECK_EQ(TimeDelta(), lifetimes.freshness);
1035 return lifetimes;
1038 // From RFC 2616 section 13.4:
1040 // A response received with a status code of 200, 203, 206, 300, 301 or 410
1041 // MAY be stored by a cache and used in reply to a subsequent request,
1042 // subject to the expiration mechanism, unless a cache-control directive
1043 // prohibits caching.
1044 // ...
1045 // A response received with any other status code (e.g. status codes 302
1046 // and 307) MUST NOT be returned in a reply to a subsequent request unless
1047 // there are cache-control directives or another header(s) that explicitly
1048 // allow it.
1050 // From RFC 2616 section 14.9.4:
1052 // When the must-revalidate directive is present in a response received by
1053 // a cache, that cache MUST NOT use the entry after it becomes stale to
1054 // respond to a subsequent request without first revalidating it with the
1055 // origin server. (I.e., the cache MUST do an end-to-end revalidation every
1056 // time, if, based solely on the origin server's Expires or max-age value,
1057 // the cached response is stale.)
1059 // https://datatracker.ietf.org/doc/draft-reschke-http-status-308/ is an
1060 // experimental RFC that adds 308 permanent redirect as well, for which "any
1061 // future references ... SHOULD use one of the returned URIs."
1062 if ((response_code_ == 200 || response_code_ == 203 ||
1063 response_code_ == 206) && !must_revalidate) {
1064 // TODO(darin): Implement a smarter heuristic.
1065 Time last_modified_value;
1066 if (GetLastModifiedValue(&last_modified_value)) {
1067 // The last-modified value can be a date in the future!
1068 if (last_modified_value <= date_value) {
1069 lifetimes.freshness = (date_value - last_modified_value) / 10;
1070 return lifetimes;
1075 // These responses are implicitly fresh (unless otherwise overruled):
1076 if (response_code_ == 300 || response_code_ == 301 || response_code_ == 308 ||
1077 response_code_ == 410) {
1078 lifetimes.freshness = TimeDelta::Max();
1079 lifetimes.staleness = TimeDelta(); // It should never be stale.
1080 return lifetimes;
1083 // Our heuristic freshness estimate for this resource is 0 seconds, in
1084 // accordance with common browser behaviour. However, stale-while-revalidate
1085 // may still apply.
1086 DCHECK_EQ(TimeDelta(), lifetimes.freshness);
1087 return lifetimes;
1090 // From RFC 2616 section 13.2.3:
1092 // Summary of age calculation algorithm, when a cache receives a response:
1094 // /*
1095 // * age_value
1096 // * is the value of Age: header received by the cache with
1097 // * this response.
1098 // * date_value
1099 // * is the value of the origin server's Date: header
1100 // * request_time
1101 // * is the (local) time when the cache made the request
1102 // * that resulted in this cached response
1103 // * response_time
1104 // * is the (local) time when the cache received the
1105 // * response
1106 // * now
1107 // * is the current (local) time
1108 // */
1109 // apparent_age = max(0, response_time - date_value);
1110 // corrected_received_age = max(apparent_age, age_value);
1111 // response_delay = response_time - request_time;
1112 // corrected_initial_age = corrected_received_age + response_delay;
1113 // resident_time = now - response_time;
1114 // current_age = corrected_initial_age + resident_time;
1116 TimeDelta HttpResponseHeaders::GetCurrentAge(const Time& request_time,
1117 const Time& response_time,
1118 const Time& current_time) const {
1119 // If there is no Date header, then assume that the server response was
1120 // generated at the time when we received the response.
1121 Time date_value;
1122 if (!GetDateValue(&date_value))
1123 date_value = response_time;
1125 // If there is no Age header, then assume age is zero. GetAgeValue does not
1126 // modify its out param if the value does not exist.
1127 TimeDelta age_value;
1128 GetAgeValue(&age_value);
1130 TimeDelta apparent_age = std::max(TimeDelta(), response_time - date_value);
1131 TimeDelta corrected_received_age = std::max(apparent_age, age_value);
1132 TimeDelta response_delay = response_time - request_time;
1133 TimeDelta corrected_initial_age = corrected_received_age + response_delay;
1134 TimeDelta resident_time = current_time - response_time;
1135 TimeDelta current_age = corrected_initial_age + resident_time;
1137 return current_age;
1140 bool HttpResponseHeaders::GetMaxAgeValue(TimeDelta* result) const {
1141 return GetCacheControlDirective("max-age", result);
1144 bool HttpResponseHeaders::GetAgeValue(TimeDelta* result) const {
1145 std::string value;
1146 if (!EnumerateHeader(NULL, "Age", &value))
1147 return false;
1149 int64 seconds;
1150 base::StringToInt64(value, &seconds);
1151 *result = TimeDelta::FromSeconds(seconds);
1152 return true;
1155 bool HttpResponseHeaders::GetDateValue(Time* result) const {
1156 return GetTimeValuedHeader("Date", result);
1159 bool HttpResponseHeaders::GetLastModifiedValue(Time* result) const {
1160 return GetTimeValuedHeader("Last-Modified", result);
1163 bool HttpResponseHeaders::GetExpiresValue(Time* result) const {
1164 return GetTimeValuedHeader("Expires", result);
1167 bool HttpResponseHeaders::GetStaleWhileRevalidateValue(
1168 TimeDelta* result) const {
1169 return GetCacheControlDirective("stale-while-revalidate", result);
1172 bool HttpResponseHeaders::GetTimeValuedHeader(const std::string& name,
1173 Time* result) const {
1174 std::string value;
1175 if (!EnumerateHeader(NULL, name, &value))
1176 return false;
1178 // When parsing HTTP dates it's beneficial to default to GMT because:
1179 // 1. RFC2616 3.3.1 says times should always be specified in GMT
1180 // 2. Only counter-example incorrectly appended "UTC" (crbug.com/153759)
1181 // 3. When adjusting cookie expiration times for clock skew
1182 // (crbug.com/135131) this better matches our cookie expiration
1183 // time parser which ignores timezone specifiers and assumes GMT.
1184 // 4. This is exactly what Firefox does.
1185 // TODO(pauljensen): The ideal solution would be to return false if the
1186 // timezone could not be understood so as to avoid makeing other calculations
1187 // based on an incorrect time. This would require modifying the time
1188 // library or duplicating the code. (http://crbug.com/158327)
1189 return Time::FromUTCString(value.c_str(), result);
1192 // We accept the first value of "close" or "keep-alive" in a Connection or
1193 // Proxy-Connection header, in that order. Obeying "keep-alive" in HTTP/1.1 or
1194 // "close" in 1.0 is not strictly standards-compliant, but we'd like to
1195 // avoid looking at the Proxy-Connection header whenever it is reasonable to do
1196 // so.
1197 // TODO(ricea): Measure real-world usage of the "Proxy-Connection" header,
1198 // with a view to reducing support for it in order to make our Connection header
1199 // handling more RFC 7230 compliant.
1200 bool HttpResponseHeaders::IsKeepAlive() const {
1201 // NOTE: It is perhaps risky to assume that a Proxy-Connection header is
1202 // meaningful when we don't know that this response was from a proxy, but
1203 // Mozilla also does this, so we'll do the same.
1204 static const char* const kConnectionHeaders[] = {
1205 "connection", "proxy-connection"};
1206 struct KeepAliveToken {
1207 const char* const token;
1208 bool keep_alive;
1210 static const KeepAliveToken kKeepAliveTokens[] = {{"keep-alive", true},
1211 {"close", false}};
1213 if (http_version_ < HttpVersion(1, 0))
1214 return false;
1216 for (const char* header : kConnectionHeaders) {
1217 void* iterator = nullptr;
1218 std::string token;
1219 while (EnumerateHeader(&iterator, header, &token)) {
1220 for (const KeepAliveToken& keep_alive_token : kKeepAliveTokens) {
1221 if (base::LowerCaseEqualsASCII(token, keep_alive_token.token))
1222 return keep_alive_token.keep_alive;
1226 return http_version_ != HttpVersion(1, 0);
1229 bool HttpResponseHeaders::HasStrongValidators() const {
1230 std::string etag_header;
1231 EnumerateHeader(NULL, "etag", &etag_header);
1232 std::string last_modified_header;
1233 EnumerateHeader(NULL, "Last-Modified", &last_modified_header);
1234 std::string date_header;
1235 EnumerateHeader(NULL, "Date", &date_header);
1236 return HttpUtil::HasStrongValidators(GetHttpVersion(),
1237 etag_header,
1238 last_modified_header,
1239 date_header);
1242 // From RFC 2616:
1243 // Content-Length = "Content-Length" ":" 1*DIGIT
1244 int64 HttpResponseHeaders::GetContentLength() const {
1245 return GetInt64HeaderValue("content-length");
1248 int64 HttpResponseHeaders::GetInt64HeaderValue(
1249 const std::string& header) const {
1250 void* iter = NULL;
1251 std::string content_length_val;
1252 if (!EnumerateHeader(&iter, header, &content_length_val))
1253 return -1;
1255 if (content_length_val.empty())
1256 return -1;
1258 if (content_length_val[0] == '+')
1259 return -1;
1261 int64 result;
1262 bool ok = base::StringToInt64(content_length_val, &result);
1263 if (!ok || result < 0)
1264 return -1;
1266 return result;
1269 // From RFC 2616 14.16:
1270 // content-range-spec =
1271 // bytes-unit SP byte-range-resp-spec "/" ( instance-length | "*" )
1272 // byte-range-resp-spec = (first-byte-pos "-" last-byte-pos) | "*"
1273 // instance-length = 1*DIGIT
1274 // bytes-unit = "bytes"
1275 bool HttpResponseHeaders::GetContentRange(int64* first_byte_position,
1276 int64* last_byte_position,
1277 int64* instance_length) const {
1278 void* iter = NULL;
1279 std::string content_range_spec;
1280 *first_byte_position = *last_byte_position = *instance_length = -1;
1281 if (!EnumerateHeader(&iter, kContentRange, &content_range_spec))
1282 return false;
1284 // If the header value is empty, we have an invalid header.
1285 if (content_range_spec.empty())
1286 return false;
1288 size_t space_position = content_range_spec.find(' ');
1289 if (space_position == std::string::npos)
1290 return false;
1292 // Invalid header if it doesn't contain "bytes-unit".
1293 std::string::const_iterator content_range_spec_begin =
1294 content_range_spec.begin();
1295 std::string::const_iterator content_range_spec_end =
1296 content_range_spec.begin() + space_position;
1297 HttpUtil::TrimLWS(&content_range_spec_begin, &content_range_spec_end);
1298 if (!base::LowerCaseEqualsASCII(
1299 base::StringPiece(content_range_spec_begin, content_range_spec_end),
1300 "bytes")) {
1301 return false;
1304 size_t slash_position = content_range_spec.find('/', space_position + 1);
1305 if (slash_position == std::string::npos)
1306 return false;
1308 // Obtain the part behind the space and before slash.
1309 std::string::const_iterator byte_range_resp_spec_begin =
1310 content_range_spec.begin() + space_position + 1;
1311 std::string::const_iterator byte_range_resp_spec_end =
1312 content_range_spec.begin() + slash_position;
1313 HttpUtil::TrimLWS(&byte_range_resp_spec_begin, &byte_range_resp_spec_end);
1315 // Parse the byte-range-resp-spec part.
1316 std::string byte_range_resp_spec(byte_range_resp_spec_begin,
1317 byte_range_resp_spec_end);
1318 // If byte-range-resp-spec != "*".
1319 if (!base::LowerCaseEqualsASCII(byte_range_resp_spec, "*")) {
1320 size_t minus_position = byte_range_resp_spec.find('-');
1321 if (minus_position != std::string::npos) {
1322 // Obtain first-byte-pos.
1323 std::string::const_iterator first_byte_pos_begin =
1324 byte_range_resp_spec.begin();
1325 std::string::const_iterator first_byte_pos_end =
1326 byte_range_resp_spec.begin() + minus_position;
1327 HttpUtil::TrimLWS(&first_byte_pos_begin, &first_byte_pos_end);
1329 bool ok = base::StringToInt64(StringPiece(first_byte_pos_begin,
1330 first_byte_pos_end),
1331 first_byte_position);
1333 // Obtain last-byte-pos.
1334 std::string::const_iterator last_byte_pos_begin =
1335 byte_range_resp_spec.begin() + minus_position + 1;
1336 std::string::const_iterator last_byte_pos_end =
1337 byte_range_resp_spec.end();
1338 HttpUtil::TrimLWS(&last_byte_pos_begin, &last_byte_pos_end);
1340 ok &= base::StringToInt64(StringPiece(last_byte_pos_begin,
1341 last_byte_pos_end),
1342 last_byte_position);
1343 if (!ok) {
1344 *first_byte_position = *last_byte_position = -1;
1345 return false;
1347 if (*first_byte_position < 0 || *last_byte_position < 0 ||
1348 *first_byte_position > *last_byte_position)
1349 return false;
1350 } else {
1351 return false;
1355 // Parse the instance-length part.
1356 // If instance-length == "*".
1357 std::string::const_iterator instance_length_begin =
1358 content_range_spec.begin() + slash_position + 1;
1359 std::string::const_iterator instance_length_end =
1360 content_range_spec.end();
1361 HttpUtil::TrimLWS(&instance_length_begin, &instance_length_end);
1363 if (base::StartsWith(
1364 base::StringPiece(instance_length_begin, instance_length_end), "*",
1365 base::CompareCase::SENSITIVE)) {
1366 return false;
1367 } else if (!base::StringToInt64(StringPiece(instance_length_begin,
1368 instance_length_end),
1369 instance_length)) {
1370 *instance_length = -1;
1371 return false;
1374 // We have all the values; let's verify that they make sense for a 206
1375 // response.
1376 if (*first_byte_position < 0 || *last_byte_position < 0 ||
1377 *instance_length < 0 || *instance_length - 1 < *last_byte_position)
1378 return false;
1380 return true;
1383 scoped_ptr<base::Value> HttpResponseHeaders::NetLogCallback(
1384 NetLogCaptureMode capture_mode) const {
1385 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
1386 base::ListValue* headers = new base::ListValue();
1387 headers->Append(new base::StringValue(GetStatusLine()));
1388 void* iterator = NULL;
1389 std::string name;
1390 std::string value;
1391 while (EnumerateHeaderLines(&iterator, &name, &value)) {
1392 std::string log_value =
1393 ElideHeaderValueForNetLog(capture_mode, name, value);
1394 std::string escaped_name = EscapeNonASCII(name);
1395 std::string escaped_value = EscapeNonASCII(log_value);
1396 headers->Append(
1397 new base::StringValue(
1398 base::StringPrintf("%s: %s", escaped_name.c_str(),
1399 escaped_value.c_str())));
1401 dict->Set("headers", headers);
1402 return dict.Pass();
1405 // static
1406 bool HttpResponseHeaders::FromNetLogParam(
1407 const base::Value* event_param,
1408 scoped_refptr<HttpResponseHeaders>* http_response_headers) {
1409 *http_response_headers = NULL;
1411 const base::DictionaryValue* dict = NULL;
1412 const base::ListValue* header_list = NULL;
1414 if (!event_param ||
1415 !event_param->GetAsDictionary(&dict) ||
1416 !dict->GetList("headers", &header_list)) {
1417 return false;
1420 std::string raw_headers;
1421 for (base::ListValue::const_iterator it = header_list->begin();
1422 it != header_list->end();
1423 ++it) {
1424 std::string header_line;
1425 if (!(*it)->GetAsString(&header_line))
1426 return false;
1428 raw_headers.append(header_line);
1429 raw_headers.push_back('\0');
1431 raw_headers.push_back('\0');
1432 *http_response_headers = new HttpResponseHeaders(raw_headers);
1433 return true;
1436 bool HttpResponseHeaders::IsChunkEncoded() const {
1437 // Ignore spurious chunked responses from HTTP/1.0 servers and proxies.
1438 return GetHttpVersion() >= HttpVersion(1, 1) &&
1439 HasHeaderValue("Transfer-Encoding", "chunked");
1442 } // namespace net