Upgrade ReadPixels to ES3 semantic in command buffer.
[chromium-blink-merge.git] / net / http / http_response_headers.cc
blob119ec527ef51acb38ec0e2cd71f0f17f4c3cef78
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(parsed_[i].name_begin, parsed_[i].name_end);
210 base::StringToLowerASCII(&header_name);
212 if (filter_headers.find(header_name) == filter_headers.end()) {
213 // Make sure there is a null after the value.
214 blob.append(parsed_[i].name_begin, parsed_[k].value_end);
215 blob.push_back('\0');
218 i = k;
220 blob.push_back('\0');
222 pickle->WriteString(blob);
225 void HttpResponseHeaders::Update(const HttpResponseHeaders& new_headers) {
226 DCHECK(new_headers.response_code() == 304 ||
227 new_headers.response_code() == 206);
229 // Copy up to the null byte. This just copies the status line.
230 std::string new_raw_headers(raw_headers_.c_str());
231 new_raw_headers.push_back('\0');
233 HeaderSet updated_headers;
235 // NOTE: we write the new headers then the old headers for convenience. The
236 // order should not matter.
238 // Figure out which headers we want to take from new_headers:
239 for (size_t i = 0; i < new_headers.parsed_.size(); ++i) {
240 const HeaderList& new_parsed = new_headers.parsed_;
242 DCHECK(!new_parsed[i].is_continuation());
244 // Locate the start of the next header.
245 size_t k = i;
246 while (++k < new_parsed.size() && new_parsed[k].is_continuation()) {}
247 --k;
249 base::StringPiece name(new_parsed[i].name_begin, new_parsed[i].name_end);
250 if (ShouldUpdateHeader(name)) {
251 std::string name_lower;
252 name.CopyToString(&name_lower);
253 base::StringToLowerASCII(&name_lower);
254 updated_headers.insert(name_lower);
256 // Preserve this header line in the merged result, making sure there is
257 // a null after the value.
258 new_raw_headers.append(new_parsed[i].name_begin, new_parsed[k].value_end);
259 new_raw_headers.push_back('\0');
262 i = k;
265 // Now, build the new raw headers.
266 MergeWithHeaders(new_raw_headers, updated_headers);
269 void HttpResponseHeaders::MergeWithHeaders(const std::string& raw_headers,
270 const HeaderSet& headers_to_remove) {
271 std::string new_raw_headers(raw_headers);
272 for (size_t i = 0; i < parsed_.size(); ++i) {
273 DCHECK(!parsed_[i].is_continuation());
275 // Locate the start of the next header.
276 size_t k = i;
277 while (++k < parsed_.size() && parsed_[k].is_continuation()) {}
278 --k;
280 std::string name(parsed_[i].name_begin, parsed_[i].name_end);
281 base::StringToLowerASCII(&name);
282 if (headers_to_remove.find(name) == headers_to_remove.end()) {
283 // It's ok to preserve this header in the final result.
284 new_raw_headers.append(parsed_[i].name_begin, parsed_[k].value_end);
285 new_raw_headers.push_back('\0');
288 i = k;
290 new_raw_headers.push_back('\0');
292 // Make this object hold the new data.
293 raw_headers_.clear();
294 parsed_.clear();
295 Parse(new_raw_headers);
298 void HttpResponseHeaders::RemoveHeader(const std::string& name) {
299 // Copy up to the null byte. This just copies the status line.
300 std::string new_raw_headers(raw_headers_.c_str());
301 new_raw_headers.push_back('\0');
303 std::string lowercase_name(name);
304 base::StringToLowerASCII(&lowercase_name);
305 HeaderSet to_remove;
306 to_remove.insert(lowercase_name);
307 MergeWithHeaders(new_raw_headers, to_remove);
310 void HttpResponseHeaders::RemoveHeaderLine(const std::string& name,
311 const std::string& value) {
312 std::string name_lowercase(name);
313 base::StringToLowerASCII(&name_lowercase);
315 std::string new_raw_headers(GetStatusLine());
316 new_raw_headers.push_back('\0');
318 new_raw_headers.reserve(raw_headers_.size());
320 void* iter = NULL;
321 std::string old_header_name;
322 std::string old_header_value;
323 while (EnumerateHeaderLines(&iter, &old_header_name, &old_header_value)) {
324 std::string old_header_name_lowercase(name);
325 base::StringToLowerASCII(&old_header_name_lowercase);
327 if (name_lowercase == old_header_name_lowercase &&
328 value == old_header_value)
329 continue;
331 new_raw_headers.append(old_header_name);
332 new_raw_headers.push_back(':');
333 new_raw_headers.push_back(' ');
334 new_raw_headers.append(old_header_value);
335 new_raw_headers.push_back('\0');
337 new_raw_headers.push_back('\0');
339 // Make this object hold the new data.
340 raw_headers_.clear();
341 parsed_.clear();
342 Parse(new_raw_headers);
345 void HttpResponseHeaders::AddHeader(const std::string& header) {
346 CheckDoesNotHaveEmbededNulls(header);
347 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 2]);
348 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 1]);
349 // Don't copy the last null.
350 std::string new_raw_headers(raw_headers_, 0, raw_headers_.size() - 1);
351 new_raw_headers.append(header);
352 new_raw_headers.push_back('\0');
353 new_raw_headers.push_back('\0');
355 // Make this object hold the new data.
356 raw_headers_.clear();
357 parsed_.clear();
358 Parse(new_raw_headers);
361 void HttpResponseHeaders::ReplaceStatusLine(const std::string& new_status) {
362 CheckDoesNotHaveEmbededNulls(new_status);
363 // Copy up to the null byte. This just copies the status line.
364 std::string new_raw_headers(new_status);
365 new_raw_headers.push_back('\0');
367 HeaderSet empty_to_remove;
368 MergeWithHeaders(new_raw_headers, empty_to_remove);
371 void HttpResponseHeaders::UpdateWithNewRange(
372 const HttpByteRange& byte_range,
373 int64 resource_size,
374 bool replace_status_line) {
375 DCHECK(byte_range.IsValid());
376 DCHECK(byte_range.HasFirstBytePosition());
377 DCHECK(byte_range.HasLastBytePosition());
379 const char kLengthHeader[] = "Content-Length";
380 const char kRangeHeader[] = "Content-Range";
382 RemoveHeader(kLengthHeader);
383 RemoveHeader(kRangeHeader);
385 int64 start = byte_range.first_byte_position();
386 int64 end = byte_range.last_byte_position();
387 int64 range_len = end - start + 1;
389 if (replace_status_line)
390 ReplaceStatusLine("HTTP/1.1 206 Partial Content");
392 AddHeader(base::StringPrintf("%s: bytes %" PRId64 "-%" PRId64 "/%" PRId64,
393 kRangeHeader, start, end, resource_size));
394 AddHeader(base::StringPrintf("%s: %" PRId64, kLengthHeader, range_len));
397 void HttpResponseHeaders::Parse(const std::string& raw_input) {
398 raw_headers_.reserve(raw_input.size());
400 // ParseStatusLine adds a normalized status line to raw_headers_
401 std::string::const_iterator line_begin = raw_input.begin();
402 std::string::const_iterator line_end =
403 std::find(line_begin, raw_input.end(), '\0');
404 // has_headers = true, if there is any data following the status line.
405 // Used by ParseStatusLine() to decide if a HTTP/0.9 is really a HTTP/1.0.
406 bool has_headers = (line_end != raw_input.end() &&
407 (line_end + 1) != raw_input.end() &&
408 *(line_end + 1) != '\0');
409 ParseStatusLine(line_begin, line_end, has_headers);
410 raw_headers_.push_back('\0'); // Terminate status line with a null.
412 if (line_end == raw_input.end()) {
413 raw_headers_.push_back('\0'); // Ensure the headers end with a double null.
415 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 2]);
416 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 1]);
417 return;
420 // Including a terminating null byte.
421 size_t status_line_len = raw_headers_.size();
423 // Now, we add the rest of the raw headers to raw_headers_, and begin parsing
424 // it (to populate our parsed_ vector).
425 raw_headers_.append(line_end + 1, raw_input.end());
427 // Ensure the headers end with a double null.
428 while (raw_headers_.size() < 2 ||
429 raw_headers_[raw_headers_.size() - 2] != '\0' ||
430 raw_headers_[raw_headers_.size() - 1] != '\0') {
431 raw_headers_.push_back('\0');
434 // Adjust to point at the null byte following the status line
435 line_end = raw_headers_.begin() + status_line_len - 1;
437 HttpUtil::HeadersIterator headers(line_end + 1, raw_headers_.end(),
438 std::string(1, '\0'));
439 while (headers.GetNext()) {
440 AddHeader(headers.name_begin(),
441 headers.name_end(),
442 headers.values_begin(),
443 headers.values_end());
446 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 2]);
447 DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 1]);
450 // Append all of our headers to the final output string.
451 void HttpResponseHeaders::GetNormalizedHeaders(std::string* output) const {
452 // copy up to the null byte. this just copies the status line.
453 output->assign(raw_headers_.c_str());
455 // headers may appear multiple times (not necessarily in succession) in the
456 // header data, so we build a map from header name to generated header lines.
457 // to preserve the order of the original headers, the actual values are kept
458 // in a separate list. finally, the list of headers is flattened to form
459 // the normalized block of headers.
461 // NOTE: We take special care to preserve the whitespace around any commas
462 // that may occur in the original response headers. Because our consumer may
463 // be a web app, we cannot be certain of the semantics of commas despite the
464 // fact that RFC 2616 says that they should be regarded as value separators.
466 typedef base::hash_map<std::string, size_t> HeadersMap;
467 HeadersMap headers_map;
468 HeadersMap::iterator iter = headers_map.end();
470 std::vector<std::string> headers;
472 for (size_t i = 0; i < parsed_.size(); ++i) {
473 DCHECK(!parsed_[i].is_continuation());
475 std::string name(parsed_[i].name_begin, parsed_[i].name_end);
476 std::string lower_name = base::StringToLowerASCII(name);
478 iter = headers_map.find(lower_name);
479 if (iter == headers_map.end()) {
480 iter = headers_map.insert(
481 HeadersMap::value_type(lower_name, headers.size())).first;
482 headers.push_back(name + ": ");
483 } else {
484 headers[iter->second].append(", ");
487 std::string::const_iterator value_begin = parsed_[i].value_begin;
488 std::string::const_iterator value_end = parsed_[i].value_end;
489 while (++i < parsed_.size() && parsed_[i].is_continuation())
490 value_end = parsed_[i].value_end;
491 --i;
493 headers[iter->second].append(value_begin, value_end);
496 for (size_t i = 0; i < headers.size(); ++i) {
497 output->push_back('\n');
498 output->append(headers[i]);
501 output->push_back('\n');
504 bool HttpResponseHeaders::GetNormalizedHeader(const std::string& name,
505 std::string* value) const {
506 // If you hit this assertion, please use EnumerateHeader instead!
507 DCHECK(!HttpUtil::IsNonCoalescingHeader(name));
509 value->clear();
511 bool found = false;
512 size_t i = 0;
513 while (i < parsed_.size()) {
514 i = FindHeader(i, name);
515 if (i == std::string::npos)
516 break;
518 found = true;
520 if (!value->empty())
521 value->append(", ");
523 std::string::const_iterator value_begin = parsed_[i].value_begin;
524 std::string::const_iterator value_end = parsed_[i].value_end;
525 while (++i < parsed_.size() && parsed_[i].is_continuation())
526 value_end = parsed_[i].value_end;
527 value->append(value_begin, value_end);
530 return found;
533 std::string HttpResponseHeaders::GetStatusLine() const {
534 // copy up to the null byte.
535 return std::string(raw_headers_.c_str());
538 std::string HttpResponseHeaders::GetStatusText() const {
539 // GetStatusLine() is already normalized, so it has the format:
540 // <http_version> SP <response_code> SP <status_text>
541 std::string status_text = GetStatusLine();
542 std::string::const_iterator begin = status_text.begin();
543 std::string::const_iterator end = status_text.end();
544 for (int i = 0; i < 2; ++i)
545 begin = std::find(begin, end, ' ') + 1;
546 return std::string(begin, end);
549 bool HttpResponseHeaders::EnumerateHeaderLines(void** iter,
550 std::string* name,
551 std::string* value) const {
552 size_t i = reinterpret_cast<size_t>(*iter);
553 if (i == parsed_.size())
554 return false;
556 DCHECK(!parsed_[i].is_continuation());
558 name->assign(parsed_[i].name_begin, parsed_[i].name_end);
560 std::string::const_iterator value_begin = parsed_[i].value_begin;
561 std::string::const_iterator value_end = parsed_[i].value_end;
562 while (++i < parsed_.size() && parsed_[i].is_continuation())
563 value_end = parsed_[i].value_end;
565 value->assign(value_begin, value_end);
567 *iter = reinterpret_cast<void*>(i);
568 return true;
571 bool HttpResponseHeaders::EnumerateHeader(void** iter,
572 const base::StringPiece& name,
573 std::string* value) const {
574 size_t i;
575 if (!iter || !*iter) {
576 i = FindHeader(0, name);
577 } else {
578 i = reinterpret_cast<size_t>(*iter);
579 if (i >= parsed_.size()) {
580 i = std::string::npos;
581 } else if (!parsed_[i].is_continuation()) {
582 i = FindHeader(i, name);
586 if (i == std::string::npos) {
587 value->clear();
588 return false;
591 if (iter)
592 *iter = reinterpret_cast<void*>(i + 1);
593 value->assign(parsed_[i].value_begin, parsed_[i].value_end);
594 return true;
597 bool HttpResponseHeaders::HasHeaderValue(const base::StringPiece& name,
598 const base::StringPiece& value) const {
599 // The value has to be an exact match. This is important since
600 // 'cache-control: no-cache' != 'cache-control: no-cache="foo"'
601 void* iter = NULL;
602 std::string temp;
603 while (EnumerateHeader(&iter, name, &temp)) {
604 if (base::EqualsCaseInsensitiveASCII(value, temp))
605 return true;
607 return false;
610 bool HttpResponseHeaders::HasHeader(const base::StringPiece& name) const {
611 return FindHeader(0, name) != std::string::npos;
614 HttpResponseHeaders::HttpResponseHeaders() : response_code_(-1) {
617 HttpResponseHeaders::~HttpResponseHeaders() {
620 // Note: this implementation implicitly assumes that line_end points at a valid
621 // sentinel character (such as '\0').
622 // static
623 HttpVersion HttpResponseHeaders::ParseVersion(
624 std::string::const_iterator line_begin,
625 std::string::const_iterator line_end) {
626 std::string::const_iterator p = line_begin;
628 // RFC2616 sec 3.1: HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT
629 // TODO: (1*DIGIT apparently means one or more digits, but we only handle 1).
630 // TODO: handle leading zeros, which is allowed by the rfc1616 sec 3.1.
632 if (!base::StartsWith(base::StringPiece(line_begin, line_end), "http",
633 base::CompareCase::INSENSITIVE_ASCII)) {
634 DVLOG(1) << "missing status line";
635 return HttpVersion();
638 p += 4;
640 if (p >= line_end || *p != '/') {
641 DVLOG(1) << "missing version";
642 return HttpVersion();
645 std::string::const_iterator dot = std::find(p, line_end, '.');
646 if (dot == line_end) {
647 DVLOG(1) << "malformed version";
648 return HttpVersion();
651 ++p; // from / to first digit.
652 ++dot; // from . to second digit.
654 if (!(*p >= '0' && *p <= '9' && *dot >= '0' && *dot <= '9')) {
655 DVLOG(1) << "malformed version number";
656 return HttpVersion();
659 uint16 major = *p - '0';
660 uint16 minor = *dot - '0';
662 return HttpVersion(major, minor);
665 // Note: this implementation implicitly assumes that line_end points at a valid
666 // sentinel character (such as '\0').
667 void HttpResponseHeaders::ParseStatusLine(
668 std::string::const_iterator line_begin,
669 std::string::const_iterator line_end,
670 bool has_headers) {
671 // Extract the version number
672 parsed_http_version_ = ParseVersion(line_begin, line_end);
674 // Clamp the version number to one of: {0.9, 1.0, 1.1}
675 if (parsed_http_version_ == HttpVersion(0, 9) && !has_headers) {
676 http_version_ = HttpVersion(0, 9);
677 raw_headers_ = "HTTP/0.9";
678 } else if (parsed_http_version_ >= HttpVersion(1, 1)) {
679 http_version_ = HttpVersion(1, 1);
680 raw_headers_ = "HTTP/1.1";
681 } else {
682 // Treat everything else like HTTP 1.0
683 http_version_ = HttpVersion(1, 0);
684 raw_headers_ = "HTTP/1.0";
686 if (parsed_http_version_ != http_version_) {
687 DVLOG(1) << "assuming HTTP/" << http_version_.major_value() << "."
688 << http_version_.minor_value();
691 // TODO(eroman): this doesn't make sense if ParseVersion failed.
692 std::string::const_iterator p = std::find(line_begin, line_end, ' ');
694 if (p == line_end) {
695 DVLOG(1) << "missing response status; assuming 200 OK";
696 raw_headers_.append(" 200 OK");
697 response_code_ = 200;
698 return;
701 // Skip whitespace.
702 while (*p == ' ')
703 ++p;
705 std::string::const_iterator code = p;
706 while (*p >= '0' && *p <= '9')
707 ++p;
709 if (p == code) {
710 DVLOG(1) << "missing response status number; assuming 200";
711 raw_headers_.append(" 200 OK");
712 response_code_ = 200;
713 return;
715 raw_headers_.push_back(' ');
716 raw_headers_.append(code, p);
717 raw_headers_.push_back(' ');
718 base::StringToInt(StringPiece(code, p), &response_code_);
720 // Skip whitespace.
721 while (*p == ' ')
722 ++p;
724 // Trim trailing whitespace.
725 while (line_end > p && line_end[-1] == ' ')
726 --line_end;
728 if (p == line_end) {
729 DVLOG(1) << "missing response status text; assuming OK";
730 // Not super critical what we put here. Just use "OK"
731 // even if it isn't descriptive of response_code_.
732 raw_headers_.append("OK");
733 } else {
734 raw_headers_.append(p, line_end);
738 size_t HttpResponseHeaders::FindHeader(size_t from,
739 const base::StringPiece& search) const {
740 for (size_t i = from; i < parsed_.size(); ++i) {
741 if (parsed_[i].is_continuation())
742 continue;
743 base::StringPiece name(parsed_[i].name_begin, parsed_[i].name_end);
744 if (base::EqualsCaseInsensitiveASCII(search, name))
745 return i;
748 return std::string::npos;
751 bool HttpResponseHeaders::GetCacheControlDirective(const StringPiece& directive,
752 TimeDelta* result) const {
753 StringPiece name("cache-control");
754 std::string value;
756 size_t directive_size = directive.size();
758 void* iter = NULL;
759 while (EnumerateHeader(&iter, name, &value)) {
760 if (value.size() > directive_size + 1 &&
761 base::StartsWith(value, directive,
762 base::CompareCase::INSENSITIVE_ASCII) &&
763 value[directive_size] == '=') {
764 int64 seconds;
765 base::StringToInt64(
766 StringPiece(value.begin() + directive_size + 1, value.end()),
767 &seconds);
768 *result = TimeDelta::FromSeconds(seconds);
769 return true;
773 return false;
776 void HttpResponseHeaders::AddHeader(std::string::const_iterator name_begin,
777 std::string::const_iterator name_end,
778 std::string::const_iterator values_begin,
779 std::string::const_iterator values_end) {
780 // If the header can be coalesced, then we should split it up.
781 if (values_begin == values_end ||
782 HttpUtil::IsNonCoalescingHeader(name_begin, name_end)) {
783 AddToParsed(name_begin, name_end, values_begin, values_end);
784 } else {
785 HttpUtil::ValuesIterator it(values_begin, values_end, ',');
786 while (it.GetNext()) {
787 AddToParsed(name_begin, name_end, it.value_begin(), it.value_end());
788 // clobber these so that subsequent values are treated as continuations
789 name_begin = name_end = raw_headers_.end();
794 void HttpResponseHeaders::AddToParsed(std::string::const_iterator name_begin,
795 std::string::const_iterator name_end,
796 std::string::const_iterator value_begin,
797 std::string::const_iterator value_end) {
798 ParsedHeader header;
799 header.name_begin = name_begin;
800 header.name_end = name_end;
801 header.value_begin = value_begin;
802 header.value_end = value_end;
803 parsed_.push_back(header);
806 void HttpResponseHeaders::AddNonCacheableHeaders(HeaderSet* result) const {
807 // Add server specified transients. Any 'cache-control: no-cache="foo,bar"'
808 // headers present in the response specify additional headers that we should
809 // not store in the cache.
810 const char kCacheControl[] = "cache-control";
811 const char kPrefix[] = "no-cache=\"";
812 const size_t kPrefixLen = sizeof(kPrefix) - 1;
814 std::string value;
815 void* iter = NULL;
816 while (EnumerateHeader(&iter, kCacheControl, &value)) {
817 // If the value is smaller than the prefix and a terminal quote, skip
818 // it.
819 if (value.size() <= kPrefixLen ||
820 value.compare(0, kPrefixLen, kPrefix) != 0) {
821 continue;
823 // if it doesn't end with a quote, then treat as malformed
824 if (value[value.size()-1] != '\"')
825 continue;
827 // process the value as a comma-separated list of items. Each
828 // item can be wrapped by linear white space.
829 std::string::const_iterator item = value.begin() + kPrefixLen;
830 std::string::const_iterator end = value.end() - 1;
831 while (item != end) {
832 // Find the comma to compute the length of the current item,
833 // and the position of the next one.
834 std::string::const_iterator item_next = std::find(item, end, ',');
835 std::string::const_iterator item_end = end;
836 if (item_next != end) {
837 // Skip over comma for next position.
838 item_end = item_next;
839 item_next++;
841 // trim off leading and trailing whitespace in this item.
842 HttpUtil::TrimLWS(&item, &item_end);
844 // assuming the header is not empty, lowercase and insert into set
845 if (item_end > item) {
846 std::string name(&*item, item_end - item);
847 base::StringToLowerASCII(&name);
848 result->insert(name);
851 // Continue to next item.
852 item = item_next;
857 void HttpResponseHeaders::AddHopByHopHeaders(HeaderSet* result) {
858 for (size_t i = 0; i < arraysize(kHopByHopResponseHeaders); ++i)
859 result->insert(std::string(kHopByHopResponseHeaders[i]));
862 void HttpResponseHeaders::AddCookieHeaders(HeaderSet* result) {
863 for (size_t i = 0; i < arraysize(kCookieResponseHeaders); ++i)
864 result->insert(std::string(kCookieResponseHeaders[i]));
867 void HttpResponseHeaders::AddChallengeHeaders(HeaderSet* result) {
868 for (size_t i = 0; i < arraysize(kChallengeResponseHeaders); ++i)
869 result->insert(std::string(kChallengeResponseHeaders[i]));
872 void HttpResponseHeaders::AddHopContentRangeHeaders(HeaderSet* result) {
873 result->insert(kContentRange);
876 void HttpResponseHeaders::AddSecurityStateHeaders(HeaderSet* result) {
877 for (size_t i = 0; i < arraysize(kSecurityStateHeaders); ++i)
878 result->insert(std::string(kSecurityStateHeaders[i]));
881 void HttpResponseHeaders::GetMimeTypeAndCharset(std::string* mime_type,
882 std::string* charset) const {
883 mime_type->clear();
884 charset->clear();
886 std::string name = "content-type";
887 std::string value;
889 bool had_charset = false;
891 void* iter = NULL;
892 while (EnumerateHeader(&iter, name, &value))
893 HttpUtil::ParseContentType(value, mime_type, charset, &had_charset, NULL);
896 bool HttpResponseHeaders::GetMimeType(std::string* mime_type) const {
897 std::string unused;
898 GetMimeTypeAndCharset(mime_type, &unused);
899 return !mime_type->empty();
902 bool HttpResponseHeaders::GetCharset(std::string* charset) const {
903 std::string unused;
904 GetMimeTypeAndCharset(&unused, charset);
905 return !charset->empty();
908 bool HttpResponseHeaders::IsRedirect(std::string* location) const {
909 if (!IsRedirectResponseCode(response_code_))
910 return false;
912 // If we lack a Location header, then we can't treat this as a redirect.
913 // We assume that the first non-empty location value is the target URL that
914 // we want to follow. TODO(darin): Is this consistent with other browsers?
915 size_t i = std::string::npos;
916 do {
917 i = FindHeader(++i, "location");
918 if (i == std::string::npos)
919 return false;
920 // If the location value is empty, then it doesn't count.
921 } while (parsed_[i].value_begin == parsed_[i].value_end);
923 if (location) {
924 // Escape any non-ASCII characters to preserve them. The server should
925 // only be returning ASCII here, but for compat we need to do this.
926 *location = EscapeNonASCII(
927 std::string(parsed_[i].value_begin, parsed_[i].value_end));
930 return true;
933 // static
934 bool HttpResponseHeaders::IsRedirectResponseCode(int response_code) {
935 // Users probably want to see 300 (multiple choice) pages, so we don't count
936 // them as redirects that need to be followed.
937 return (response_code == 301 ||
938 response_code == 302 ||
939 response_code == 303 ||
940 response_code == 307 ||
941 response_code == 308);
944 // From RFC 2616 section 13.2.4:
946 // The calculation to determine if a response has expired is quite simple:
948 // response_is_fresh = (freshness_lifetime > current_age)
950 // Of course, there are other factors that can force a response to always be
951 // validated or re-fetched.
953 // From RFC 5861 section 3, a stale response may be used while revalidation is
954 // performed in the background if
956 // freshness_lifetime + stale_while_revalidate > current_age
958 ValidationType HttpResponseHeaders::RequiresValidation(
959 const Time& request_time,
960 const Time& response_time,
961 const Time& current_time) const {
962 FreshnessLifetimes lifetimes = GetFreshnessLifetimes(response_time);
963 if (lifetimes.freshness == TimeDelta() && lifetimes.staleness == TimeDelta())
964 return VALIDATION_SYNCHRONOUS;
966 TimeDelta age = GetCurrentAge(request_time, response_time, current_time);
968 if (lifetimes.freshness > age)
969 return VALIDATION_NONE;
971 if (lifetimes.freshness + lifetimes.staleness > age)
972 return VALIDATION_ASYNCHRONOUS;
974 return VALIDATION_SYNCHRONOUS;
977 // From RFC 2616 section 13.2.4:
979 // The max-age directive takes priority over Expires, so if max-age is present
980 // in a response, the calculation is simply:
982 // freshness_lifetime = max_age_value
984 // Otherwise, if Expires is present in the response, the calculation is:
986 // freshness_lifetime = expires_value - date_value
988 // Note that neither of these calculations is vulnerable to clock skew, since
989 // all of the information comes from the origin server.
991 // Also, if the response does have a Last-Modified time, the heuristic
992 // expiration value SHOULD be no more than some fraction of the interval since
993 // that time. A typical setting of this fraction might be 10%:
995 // freshness_lifetime = (date_value - last_modified_value) * 0.10
997 // If the stale-while-revalidate directive is present, then it is used to set
998 // the |staleness| time, unless it overridden by another directive.
1000 HttpResponseHeaders::FreshnessLifetimes
1001 HttpResponseHeaders::GetFreshnessLifetimes(const Time& response_time) const {
1002 FreshnessLifetimes lifetimes;
1003 // Check for headers that force a response to never be fresh. For backwards
1004 // compat, we treat "Pragma: no-cache" as a synonym for "Cache-Control:
1005 // no-cache" even though RFC 2616 does not specify it.
1006 if (HasHeaderValue("cache-control", "no-cache") ||
1007 HasHeaderValue("cache-control", "no-store") ||
1008 HasHeaderValue("pragma", "no-cache") ||
1009 // Vary: * is never usable: see RFC 2616 section 13.6.
1010 HasHeaderValue("vary", "*")) {
1011 return lifetimes;
1014 // Cache-Control directive must_revalidate overrides stale-while-revalidate.
1015 bool must_revalidate = HasHeaderValue("cache-control", "must-revalidate");
1017 if (must_revalidate || !GetStaleWhileRevalidateValue(&lifetimes.staleness)) {
1018 DCHECK_EQ(TimeDelta(), lifetimes.staleness);
1021 // NOTE: "Cache-Control: max-age" overrides Expires, so we only check the
1022 // Expires header after checking for max-age in GetFreshnessLifetimes. This
1023 // is important since "Expires: <date in the past>" means not fresh, but
1024 // it should not trump a max-age value.
1025 if (GetMaxAgeValue(&lifetimes.freshness))
1026 return lifetimes;
1028 // If there is no Date header, then assume that the server response was
1029 // generated at the time when we received the response.
1030 Time date_value;
1031 if (!GetDateValue(&date_value))
1032 date_value = response_time;
1034 Time expires_value;
1035 if (GetExpiresValue(&expires_value)) {
1036 // The expires value can be a date in the past!
1037 if (expires_value > date_value) {
1038 lifetimes.freshness = expires_value - date_value;
1039 return lifetimes;
1042 DCHECK_EQ(TimeDelta(), lifetimes.freshness);
1043 return lifetimes;
1046 // From RFC 2616 section 13.4:
1048 // A response received with a status code of 200, 203, 206, 300, 301 or 410
1049 // MAY be stored by a cache and used in reply to a subsequent request,
1050 // subject to the expiration mechanism, unless a cache-control directive
1051 // prohibits caching.
1052 // ...
1053 // A response received with any other status code (e.g. status codes 302
1054 // and 307) MUST NOT be returned in a reply to a subsequent request unless
1055 // there are cache-control directives or another header(s) that explicitly
1056 // allow it.
1058 // From RFC 2616 section 14.9.4:
1060 // When the must-revalidate directive is present in a response received by
1061 // a cache, that cache MUST NOT use the entry after it becomes stale to
1062 // respond to a subsequent request without first revalidating it with the
1063 // origin server. (I.e., the cache MUST do an end-to-end revalidation every
1064 // time, if, based solely on the origin server's Expires or max-age value,
1065 // the cached response is stale.)
1067 // https://datatracker.ietf.org/doc/draft-reschke-http-status-308/ is an
1068 // experimental RFC that adds 308 permanent redirect as well, for which "any
1069 // future references ... SHOULD use one of the returned URIs."
1070 if ((response_code_ == 200 || response_code_ == 203 ||
1071 response_code_ == 206) && !must_revalidate) {
1072 // TODO(darin): Implement a smarter heuristic.
1073 Time last_modified_value;
1074 if (GetLastModifiedValue(&last_modified_value)) {
1075 // The last-modified value can be a date in the future!
1076 if (last_modified_value <= date_value) {
1077 lifetimes.freshness = (date_value - last_modified_value) / 10;
1078 return lifetimes;
1083 // These responses are implicitly fresh (unless otherwise overruled):
1084 if (response_code_ == 300 || response_code_ == 301 || response_code_ == 308 ||
1085 response_code_ == 410) {
1086 lifetimes.freshness = TimeDelta::Max();
1087 lifetimes.staleness = TimeDelta(); // It should never be stale.
1088 return lifetimes;
1091 // Our heuristic freshness estimate for this resource is 0 seconds, in
1092 // accordance with common browser behaviour. However, stale-while-revalidate
1093 // may still apply.
1094 DCHECK_EQ(TimeDelta(), lifetimes.freshness);
1095 return lifetimes;
1098 // From RFC 2616 section 13.2.3:
1100 // Summary of age calculation algorithm, when a cache receives a response:
1102 // /*
1103 // * age_value
1104 // * is the value of Age: header received by the cache with
1105 // * this response.
1106 // * date_value
1107 // * is the value of the origin server's Date: header
1108 // * request_time
1109 // * is the (local) time when the cache made the request
1110 // * that resulted in this cached response
1111 // * response_time
1112 // * is the (local) time when the cache received the
1113 // * response
1114 // * now
1115 // * is the current (local) time
1116 // */
1117 // apparent_age = max(0, response_time - date_value);
1118 // corrected_received_age = max(apparent_age, age_value);
1119 // response_delay = response_time - request_time;
1120 // corrected_initial_age = corrected_received_age + response_delay;
1121 // resident_time = now - response_time;
1122 // current_age = corrected_initial_age + resident_time;
1124 TimeDelta HttpResponseHeaders::GetCurrentAge(const Time& request_time,
1125 const Time& response_time,
1126 const Time& current_time) const {
1127 // If there is no Date header, then assume that the server response was
1128 // generated at the time when we received the response.
1129 Time date_value;
1130 if (!GetDateValue(&date_value))
1131 date_value = response_time;
1133 // If there is no Age header, then assume age is zero. GetAgeValue does not
1134 // modify its out param if the value does not exist.
1135 TimeDelta age_value;
1136 GetAgeValue(&age_value);
1138 TimeDelta apparent_age = std::max(TimeDelta(), response_time - date_value);
1139 TimeDelta corrected_received_age = std::max(apparent_age, age_value);
1140 TimeDelta response_delay = response_time - request_time;
1141 TimeDelta corrected_initial_age = corrected_received_age + response_delay;
1142 TimeDelta resident_time = current_time - response_time;
1143 TimeDelta current_age = corrected_initial_age + resident_time;
1145 return current_age;
1148 bool HttpResponseHeaders::GetMaxAgeValue(TimeDelta* result) const {
1149 return GetCacheControlDirective("max-age", result);
1152 bool HttpResponseHeaders::GetAgeValue(TimeDelta* result) const {
1153 std::string value;
1154 if (!EnumerateHeader(NULL, "Age", &value))
1155 return false;
1157 int64 seconds;
1158 base::StringToInt64(value, &seconds);
1159 *result = TimeDelta::FromSeconds(seconds);
1160 return true;
1163 bool HttpResponseHeaders::GetDateValue(Time* result) const {
1164 return GetTimeValuedHeader("Date", result);
1167 bool HttpResponseHeaders::GetLastModifiedValue(Time* result) const {
1168 return GetTimeValuedHeader("Last-Modified", result);
1171 bool HttpResponseHeaders::GetExpiresValue(Time* result) const {
1172 return GetTimeValuedHeader("Expires", result);
1175 bool HttpResponseHeaders::GetStaleWhileRevalidateValue(
1176 TimeDelta* result) const {
1177 return GetCacheControlDirective("stale-while-revalidate", result);
1180 bool HttpResponseHeaders::GetTimeValuedHeader(const std::string& name,
1181 Time* result) const {
1182 std::string value;
1183 if (!EnumerateHeader(NULL, name, &value))
1184 return false;
1186 // When parsing HTTP dates it's beneficial to default to GMT because:
1187 // 1. RFC2616 3.3.1 says times should always be specified in GMT
1188 // 2. Only counter-example incorrectly appended "UTC" (crbug.com/153759)
1189 // 3. When adjusting cookie expiration times for clock skew
1190 // (crbug.com/135131) this better matches our cookie expiration
1191 // time parser which ignores timezone specifiers and assumes GMT.
1192 // 4. This is exactly what Firefox does.
1193 // TODO(pauljensen): The ideal solution would be to return false if the
1194 // timezone could not be understood so as to avoid makeing other calculations
1195 // based on an incorrect time. This would require modifying the time
1196 // library or duplicating the code. (http://crbug.com/158327)
1197 return Time::FromUTCString(value.c_str(), result);
1200 // We accept the first value of "close" or "keep-alive" in a Connection or
1201 // Proxy-Connection header, in that order. Obeying "keep-alive" in HTTP/1.1 or
1202 // "close" in 1.0 is not strictly standards-compliant, but we'd like to
1203 // avoid looking at the Proxy-Connection header whenever it is reasonable to do
1204 // so.
1205 // TODO(ricea): Measure real-world usage of the "Proxy-Connection" header,
1206 // with a view to reducing support for it in order to make our Connection header
1207 // handling more RFC 7230 compliant.
1208 bool HttpResponseHeaders::IsKeepAlive() const {
1209 // NOTE: It is perhaps risky to assume that a Proxy-Connection header is
1210 // meaningful when we don't know that this response was from a proxy, but
1211 // Mozilla also does this, so we'll do the same.
1212 static const char* const kConnectionHeaders[] = {
1213 "connection", "proxy-connection"};
1214 struct KeepAliveToken {
1215 const char* const token;
1216 bool keep_alive;
1218 static const KeepAliveToken kKeepAliveTokens[] = {{"keep-alive", true},
1219 {"close", false}};
1221 if (http_version_ < HttpVersion(1, 0))
1222 return false;
1224 for (const char* header : kConnectionHeaders) {
1225 void* iterator = nullptr;
1226 std::string token;
1227 while (EnumerateHeader(&iterator, header, &token)) {
1228 for (const KeepAliveToken& keep_alive_token : kKeepAliveTokens) {
1229 if (base::LowerCaseEqualsASCII(token, keep_alive_token.token))
1230 return keep_alive_token.keep_alive;
1234 return http_version_ != HttpVersion(1, 0);
1237 bool HttpResponseHeaders::HasStrongValidators() const {
1238 std::string etag_header;
1239 EnumerateHeader(NULL, "etag", &etag_header);
1240 std::string last_modified_header;
1241 EnumerateHeader(NULL, "Last-Modified", &last_modified_header);
1242 std::string date_header;
1243 EnumerateHeader(NULL, "Date", &date_header);
1244 return HttpUtil::HasStrongValidators(GetHttpVersion(),
1245 etag_header,
1246 last_modified_header,
1247 date_header);
1250 // From RFC 2616:
1251 // Content-Length = "Content-Length" ":" 1*DIGIT
1252 int64 HttpResponseHeaders::GetContentLength() const {
1253 return GetInt64HeaderValue("content-length");
1256 int64 HttpResponseHeaders::GetInt64HeaderValue(
1257 const std::string& header) const {
1258 void* iter = NULL;
1259 std::string content_length_val;
1260 if (!EnumerateHeader(&iter, header, &content_length_val))
1261 return -1;
1263 if (content_length_val.empty())
1264 return -1;
1266 if (content_length_val[0] == '+')
1267 return -1;
1269 int64 result;
1270 bool ok = base::StringToInt64(content_length_val, &result);
1271 if (!ok || result < 0)
1272 return -1;
1274 return result;
1277 // From RFC 2616 14.16:
1278 // content-range-spec =
1279 // bytes-unit SP byte-range-resp-spec "/" ( instance-length | "*" )
1280 // byte-range-resp-spec = (first-byte-pos "-" last-byte-pos) | "*"
1281 // instance-length = 1*DIGIT
1282 // bytes-unit = "bytes"
1283 bool HttpResponseHeaders::GetContentRange(int64* first_byte_position,
1284 int64* last_byte_position,
1285 int64* instance_length) const {
1286 void* iter = NULL;
1287 std::string content_range_spec;
1288 *first_byte_position = *last_byte_position = *instance_length = -1;
1289 if (!EnumerateHeader(&iter, kContentRange, &content_range_spec))
1290 return false;
1292 // If the header value is empty, we have an invalid header.
1293 if (content_range_spec.empty())
1294 return false;
1296 size_t space_position = content_range_spec.find(' ');
1297 if (space_position == std::string::npos)
1298 return false;
1300 // Invalid header if it doesn't contain "bytes-unit".
1301 std::string::const_iterator content_range_spec_begin =
1302 content_range_spec.begin();
1303 std::string::const_iterator content_range_spec_end =
1304 content_range_spec.begin() + space_position;
1305 HttpUtil::TrimLWS(&content_range_spec_begin, &content_range_spec_end);
1306 if (!base::LowerCaseEqualsASCII(
1307 base::StringPiece(content_range_spec_begin, content_range_spec_end),
1308 "bytes")) {
1309 return false;
1312 size_t slash_position = content_range_spec.find('/', space_position + 1);
1313 if (slash_position == std::string::npos)
1314 return false;
1316 // Obtain the part behind the space and before slash.
1317 std::string::const_iterator byte_range_resp_spec_begin =
1318 content_range_spec.begin() + space_position + 1;
1319 std::string::const_iterator byte_range_resp_spec_end =
1320 content_range_spec.begin() + slash_position;
1321 HttpUtil::TrimLWS(&byte_range_resp_spec_begin, &byte_range_resp_spec_end);
1323 // Parse the byte-range-resp-spec part.
1324 std::string byte_range_resp_spec(byte_range_resp_spec_begin,
1325 byte_range_resp_spec_end);
1326 // If byte-range-resp-spec != "*".
1327 if (!base::LowerCaseEqualsASCII(byte_range_resp_spec, "*")) {
1328 size_t minus_position = byte_range_resp_spec.find('-');
1329 if (minus_position != std::string::npos) {
1330 // Obtain first-byte-pos.
1331 std::string::const_iterator first_byte_pos_begin =
1332 byte_range_resp_spec.begin();
1333 std::string::const_iterator first_byte_pos_end =
1334 byte_range_resp_spec.begin() + minus_position;
1335 HttpUtil::TrimLWS(&first_byte_pos_begin, &first_byte_pos_end);
1337 bool ok = base::StringToInt64(StringPiece(first_byte_pos_begin,
1338 first_byte_pos_end),
1339 first_byte_position);
1341 // Obtain last-byte-pos.
1342 std::string::const_iterator last_byte_pos_begin =
1343 byte_range_resp_spec.begin() + minus_position + 1;
1344 std::string::const_iterator last_byte_pos_end =
1345 byte_range_resp_spec.end();
1346 HttpUtil::TrimLWS(&last_byte_pos_begin, &last_byte_pos_end);
1348 ok &= base::StringToInt64(StringPiece(last_byte_pos_begin,
1349 last_byte_pos_end),
1350 last_byte_position);
1351 if (!ok) {
1352 *first_byte_position = *last_byte_position = -1;
1353 return false;
1355 if (*first_byte_position < 0 || *last_byte_position < 0 ||
1356 *first_byte_position > *last_byte_position)
1357 return false;
1358 } else {
1359 return false;
1363 // Parse the instance-length part.
1364 // If instance-length == "*".
1365 std::string::const_iterator instance_length_begin =
1366 content_range_spec.begin() + slash_position + 1;
1367 std::string::const_iterator instance_length_end =
1368 content_range_spec.end();
1369 HttpUtil::TrimLWS(&instance_length_begin, &instance_length_end);
1371 if (base::StartsWith(
1372 base::StringPiece(instance_length_begin, instance_length_end), "*",
1373 base::CompareCase::SENSITIVE)) {
1374 return false;
1375 } else if (!base::StringToInt64(StringPiece(instance_length_begin,
1376 instance_length_end),
1377 instance_length)) {
1378 *instance_length = -1;
1379 return false;
1382 // We have all the values; let's verify that they make sense for a 206
1383 // response.
1384 if (*first_byte_position < 0 || *last_byte_position < 0 ||
1385 *instance_length < 0 || *instance_length - 1 < *last_byte_position)
1386 return false;
1388 return true;
1391 scoped_ptr<base::Value> HttpResponseHeaders::NetLogCallback(
1392 NetLogCaptureMode capture_mode) const {
1393 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
1394 base::ListValue* headers = new base::ListValue();
1395 headers->Append(new base::StringValue(GetStatusLine()));
1396 void* iterator = NULL;
1397 std::string name;
1398 std::string value;
1399 while (EnumerateHeaderLines(&iterator, &name, &value)) {
1400 std::string log_value =
1401 ElideHeaderValueForNetLog(capture_mode, name, value);
1402 std::string escaped_name = EscapeNonASCII(name);
1403 std::string escaped_value = EscapeNonASCII(log_value);
1404 headers->Append(
1405 new base::StringValue(
1406 base::StringPrintf("%s: %s", escaped_name.c_str(),
1407 escaped_value.c_str())));
1409 dict->Set("headers", headers);
1410 return dict.Pass();
1413 // static
1414 bool HttpResponseHeaders::FromNetLogParam(
1415 const base::Value* event_param,
1416 scoped_refptr<HttpResponseHeaders>* http_response_headers) {
1417 *http_response_headers = NULL;
1419 const base::DictionaryValue* dict = NULL;
1420 const base::ListValue* header_list = NULL;
1422 if (!event_param ||
1423 !event_param->GetAsDictionary(&dict) ||
1424 !dict->GetList("headers", &header_list)) {
1425 return false;
1428 std::string raw_headers;
1429 for (base::ListValue::const_iterator it = header_list->begin();
1430 it != header_list->end();
1431 ++it) {
1432 std::string header_line;
1433 if (!(*it)->GetAsString(&header_line))
1434 return false;
1436 raw_headers.append(header_line);
1437 raw_headers.push_back('\0');
1439 raw_headers.push_back('\0');
1440 *http_response_headers = new HttpResponseHeaders(raw_headers);
1441 return true;
1444 bool HttpResponseHeaders::IsChunkEncoded() const {
1445 // Ignore spurious chunked responses from HTTP/1.0 servers and proxies.
1446 return GetHttpVersion() >= HttpVersion(1, 1) &&
1447 HasHeaderValue("Transfer-Encoding", "chunked");
1450 } // namespace net