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"
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
;
31 using base::TimeDelta
;
35 //-----------------------------------------------------------------------------
39 // These headers are RFC 2616 hop-by-hop headers;
40 // not to be stored by caches.
41 const char* const kHopByHopResponseHeaders
[] = {
50 // These headers are challenge response headers;
51 // not to be stored by caches.
52 const char* const kChallengeResponseHeaders
[] = {
57 // These headers are cookie setting headers;
58 // not to be stored by caches or disclosed otherwise.
59 const char* const kCookieResponseHeaders
[] = {
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
68 const char* const kSecurityStateHeaders
[] = {
69 "strict-transport-security",
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
[] = {
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
92 const char* const kNonUpdatedHeaderPrefixes
[] = {
98 bool ShouldUpdateHeader(const std::string::const_iterator
& name_begin
,
99 const std::string::const_iterator
& name_end
) {
100 for (size_t i
= 0; i
< arraysize(kNonUpdatedHeaders
); ++i
) {
101 if (base::LowerCaseEqualsASCII(name_begin
, name_end
, kNonUpdatedHeaders
[i
]))
104 for (size_t i
= 0; i
< arraysize(kNonUpdatedHeaderPrefixes
); ++i
) {
105 if (base::StartsWith(base::StringPiece(name_begin
, name_end
),
106 kNonUpdatedHeaderPrefixes
[i
],
107 base::CompareCase::INSENSITIVE_ASCII
))
113 void CheckDoesNotHaveEmbededNulls(const std::string
& str
) {
114 // Care needs to be taken when adding values to the raw headers string to
115 // make sure it does not contain embeded NULLs. Any embeded '\0' may be
116 // understood as line terminators and change how header lines get tokenized.
117 CHECK(str
.find('\0') == std::string::npos
);
122 const char HttpResponseHeaders::kContentRange
[] = "Content-Range";
124 struct HttpResponseHeaders::ParsedHeader
{
125 // A header "continuation" contains only a subsequent value for the
126 // preceding header. (Header values are comma separated.)
127 bool is_continuation() const { return name_begin
== name_end
; }
129 std::string::const_iterator name_begin
;
130 std::string::const_iterator name_end
;
131 std::string::const_iterator value_begin
;
132 std::string::const_iterator value_end
;
135 //-----------------------------------------------------------------------------
137 HttpResponseHeaders::HttpResponseHeaders(const std::string
& raw_input
)
138 : response_code_(-1) {
141 // The most important thing to do with this histogram is find out
142 // the existence of unusual HTTP status codes. As it happens
143 // right now, there aren't double-constructions of response headers
144 // using this constructor, so our counts should also be accurate,
145 // without instantiating the histogram in two places. It is also
146 // important that this histogram not collect data in the other
147 // constructor, which rebuilds an histogram from a pickle, since
148 // that would actually create a double call between the original
149 // HttpResponseHeader that was serialized, and initialization of the
150 // new object from that pickle.
151 UMA_HISTOGRAM_CUSTOM_ENUMERATION("Net.HttpResponseCode",
152 HttpUtil::MapStatusCodeForHistogram(
154 // Note the third argument is only
155 // evaluated once, see macro
156 // definition for details.
157 HttpUtil::GetStatusCodesForHistogram());
160 HttpResponseHeaders::HttpResponseHeaders(base::PickleIterator
* iter
)
161 : response_code_(-1) {
162 std::string raw_input
;
163 if (iter
->ReadString(&raw_input
))
167 void HttpResponseHeaders::Persist(base::Pickle
* pickle
,
168 PersistOptions options
) {
169 if (options
== PERSIST_RAW
) {
170 pickle
->WriteString(raw_headers_
);
174 HeaderSet filter_headers
;
176 // Construct set of headers to filter out based on options.
177 if ((options
& PERSIST_SANS_NON_CACHEABLE
) == PERSIST_SANS_NON_CACHEABLE
)
178 AddNonCacheableHeaders(&filter_headers
);
180 if ((options
& PERSIST_SANS_COOKIES
) == PERSIST_SANS_COOKIES
)
181 AddCookieHeaders(&filter_headers
);
183 if ((options
& PERSIST_SANS_CHALLENGES
) == PERSIST_SANS_CHALLENGES
)
184 AddChallengeHeaders(&filter_headers
);
186 if ((options
& PERSIST_SANS_HOP_BY_HOP
) == PERSIST_SANS_HOP_BY_HOP
)
187 AddHopByHopHeaders(&filter_headers
);
189 if ((options
& PERSIST_SANS_RANGES
) == PERSIST_SANS_RANGES
)
190 AddHopContentRangeHeaders(&filter_headers
);
192 if ((options
& PERSIST_SANS_SECURITY_STATE
) == PERSIST_SANS_SECURITY_STATE
)
193 AddSecurityStateHeaders(&filter_headers
);
196 blob
.reserve(raw_headers_
.size());
198 // This copies the status line w/ terminator null.
199 // Note raw_headers_ has embedded nulls instead of \n,
200 // so this just copies the first header line.
201 blob
.assign(raw_headers_
.c_str(), strlen(raw_headers_
.c_str()) + 1);
203 for (size_t i
= 0; i
< parsed_
.size(); ++i
) {
204 DCHECK(!parsed_
[i
].is_continuation());
206 // Locate the start of the next header.
208 while (++k
< parsed_
.size() && parsed_
[k
].is_continuation()) {}
211 std::string
header_name(parsed_
[i
].name_begin
, parsed_
[i
].name_end
);
212 base::StringToLowerASCII(&header_name
);
214 if (filter_headers
.find(header_name
) == filter_headers
.end()) {
215 // Make sure there is a null after the value.
216 blob
.append(parsed_
[i
].name_begin
, parsed_
[k
].value_end
);
217 blob
.push_back('\0');
222 blob
.push_back('\0');
224 pickle
->WriteString(blob
);
227 void HttpResponseHeaders::Update(const HttpResponseHeaders
& new_headers
) {
228 DCHECK(new_headers
.response_code() == 304 ||
229 new_headers
.response_code() == 206);
231 // Copy up to the null byte. This just copies the status line.
232 std::string
new_raw_headers(raw_headers_
.c_str());
233 new_raw_headers
.push_back('\0');
235 HeaderSet updated_headers
;
237 // NOTE: we write the new headers then the old headers for convenience. The
238 // order should not matter.
240 // Figure out which headers we want to take from new_headers:
241 for (size_t i
= 0; i
< new_headers
.parsed_
.size(); ++i
) {
242 const HeaderList
& new_parsed
= new_headers
.parsed_
;
244 DCHECK(!new_parsed
[i
].is_continuation());
246 // Locate the start of the next header.
248 while (++k
< new_parsed
.size() && new_parsed
[k
].is_continuation()) {}
251 const std::string::const_iterator
& name_begin
= new_parsed
[i
].name_begin
;
252 const std::string::const_iterator
& name_end
= new_parsed
[i
].name_end
;
253 if (ShouldUpdateHeader(name_begin
, name_end
)) {
254 std::string
name(name_begin
, name_end
);
255 base::StringToLowerASCII(&name
);
256 updated_headers
.insert(name
);
258 // Preserve this header line in the merged result, making sure there is
259 // a null after the value.
260 new_raw_headers
.append(name_begin
, new_parsed
[k
].value_end
);
261 new_raw_headers
.push_back('\0');
267 // Now, build the new raw headers.
268 MergeWithHeaders(new_raw_headers
, updated_headers
);
271 void HttpResponseHeaders::MergeWithHeaders(const std::string
& raw_headers
,
272 const HeaderSet
& headers_to_remove
) {
273 std::string
new_raw_headers(raw_headers
);
274 for (size_t i
= 0; i
< parsed_
.size(); ++i
) {
275 DCHECK(!parsed_
[i
].is_continuation());
277 // Locate the start of the next header.
279 while (++k
< parsed_
.size() && parsed_
[k
].is_continuation()) {}
282 std::string
name(parsed_
[i
].name_begin
, parsed_
[i
].name_end
);
283 base::StringToLowerASCII(&name
);
284 if (headers_to_remove
.find(name
) == headers_to_remove
.end()) {
285 // It's ok to preserve this header in the final result.
286 new_raw_headers
.append(parsed_
[i
].name_begin
, parsed_
[k
].value_end
);
287 new_raw_headers
.push_back('\0');
292 new_raw_headers
.push_back('\0');
294 // Make this object hold the new data.
295 raw_headers_
.clear();
297 Parse(new_raw_headers
);
300 void HttpResponseHeaders::RemoveHeader(const std::string
& name
) {
301 // Copy up to the null byte. This just copies the status line.
302 std::string
new_raw_headers(raw_headers_
.c_str());
303 new_raw_headers
.push_back('\0');
305 std::string
lowercase_name(name
);
306 base::StringToLowerASCII(&lowercase_name
);
308 to_remove
.insert(lowercase_name
);
309 MergeWithHeaders(new_raw_headers
, to_remove
);
312 void HttpResponseHeaders::RemoveHeaderLine(const std::string
& name
,
313 const std::string
& value
) {
314 std::string
name_lowercase(name
);
315 base::StringToLowerASCII(&name_lowercase
);
317 std::string
new_raw_headers(GetStatusLine());
318 new_raw_headers
.push_back('\0');
320 new_raw_headers
.reserve(raw_headers_
.size());
323 std::string old_header_name
;
324 std::string old_header_value
;
325 while (EnumerateHeaderLines(&iter
, &old_header_name
, &old_header_value
)) {
326 std::string
old_header_name_lowercase(name
);
327 base::StringToLowerASCII(&old_header_name_lowercase
);
329 if (name_lowercase
== old_header_name_lowercase
&&
330 value
== old_header_value
)
333 new_raw_headers
.append(old_header_name
);
334 new_raw_headers
.push_back(':');
335 new_raw_headers
.push_back(' ');
336 new_raw_headers
.append(old_header_value
);
337 new_raw_headers
.push_back('\0');
339 new_raw_headers
.push_back('\0');
341 // Make this object hold the new data.
342 raw_headers_
.clear();
344 Parse(new_raw_headers
);
347 void HttpResponseHeaders::AddHeader(const std::string
& header
) {
348 CheckDoesNotHaveEmbededNulls(header
);
349 DCHECK_EQ('\0', raw_headers_
[raw_headers_
.size() - 2]);
350 DCHECK_EQ('\0', raw_headers_
[raw_headers_
.size() - 1]);
351 // Don't copy the last null.
352 std::string
new_raw_headers(raw_headers_
, 0, raw_headers_
.size() - 1);
353 new_raw_headers
.append(header
);
354 new_raw_headers
.push_back('\0');
355 new_raw_headers
.push_back('\0');
357 // Make this object hold the new data.
358 raw_headers_
.clear();
360 Parse(new_raw_headers
);
363 void HttpResponseHeaders::ReplaceStatusLine(const std::string
& new_status
) {
364 CheckDoesNotHaveEmbededNulls(new_status
);
365 // Copy up to the null byte. This just copies the status line.
366 std::string
new_raw_headers(new_status
);
367 new_raw_headers
.push_back('\0');
369 HeaderSet empty_to_remove
;
370 MergeWithHeaders(new_raw_headers
, empty_to_remove
);
373 void HttpResponseHeaders::UpdateWithNewRange(
374 const HttpByteRange
& byte_range
,
376 bool replace_status_line
) {
377 DCHECK(byte_range
.IsValid());
378 DCHECK(byte_range
.HasFirstBytePosition());
379 DCHECK(byte_range
.HasLastBytePosition());
381 const char kLengthHeader
[] = "Content-Length";
382 const char kRangeHeader
[] = "Content-Range";
384 RemoveHeader(kLengthHeader
);
385 RemoveHeader(kRangeHeader
);
387 int64 start
= byte_range
.first_byte_position();
388 int64 end
= byte_range
.last_byte_position();
389 int64 range_len
= end
- start
+ 1;
391 if (replace_status_line
)
392 ReplaceStatusLine("HTTP/1.1 206 Partial Content");
394 AddHeader(base::StringPrintf("%s: bytes %" PRId64
"-%" PRId64
"/%" PRId64
,
395 kRangeHeader
, start
, end
, resource_size
));
396 AddHeader(base::StringPrintf("%s: %" PRId64
, kLengthHeader
, range_len
));
399 void HttpResponseHeaders::Parse(const std::string
& raw_input
) {
400 raw_headers_
.reserve(raw_input
.size());
402 // ParseStatusLine adds a normalized status line to raw_headers_
403 std::string::const_iterator line_begin
= raw_input
.begin();
404 std::string::const_iterator line_end
=
405 std::find(line_begin
, raw_input
.end(), '\0');
406 // has_headers = true, if there is any data following the status line.
407 // Used by ParseStatusLine() to decide if a HTTP/0.9 is really a HTTP/1.0.
408 bool has_headers
= (line_end
!= raw_input
.end() &&
409 (line_end
+ 1) != raw_input
.end() &&
410 *(line_end
+ 1) != '\0');
411 ParseStatusLine(line_begin
, line_end
, has_headers
);
412 raw_headers_
.push_back('\0'); // Terminate status line with a null.
414 if (line_end
== raw_input
.end()) {
415 raw_headers_
.push_back('\0'); // Ensure the headers end with a double null.
417 DCHECK_EQ('\0', raw_headers_
[raw_headers_
.size() - 2]);
418 DCHECK_EQ('\0', raw_headers_
[raw_headers_
.size() - 1]);
422 // Including a terminating null byte.
423 size_t status_line_len
= raw_headers_
.size();
425 // Now, we add the rest of the raw headers to raw_headers_, and begin parsing
426 // it (to populate our parsed_ vector).
427 raw_headers_
.append(line_end
+ 1, raw_input
.end());
429 // Ensure the headers end with a double null.
430 while (raw_headers_
.size() < 2 ||
431 raw_headers_
[raw_headers_
.size() - 2] != '\0' ||
432 raw_headers_
[raw_headers_
.size() - 1] != '\0') {
433 raw_headers_
.push_back('\0');
436 // Adjust to point at the null byte following the status line
437 line_end
= raw_headers_
.begin() + status_line_len
- 1;
439 HttpUtil::HeadersIterator
headers(line_end
+ 1, raw_headers_
.end(),
440 std::string(1, '\0'));
441 while (headers
.GetNext()) {
442 AddHeader(headers
.name_begin(),
444 headers
.values_begin(),
445 headers
.values_end());
448 DCHECK_EQ('\0', raw_headers_
[raw_headers_
.size() - 2]);
449 DCHECK_EQ('\0', raw_headers_
[raw_headers_
.size() - 1]);
452 // Append all of our headers to the final output string.
453 void HttpResponseHeaders::GetNormalizedHeaders(std::string
* output
) const {
454 // copy up to the null byte. this just copies the status line.
455 output
->assign(raw_headers_
.c_str());
457 // headers may appear multiple times (not necessarily in succession) in the
458 // header data, so we build a map from header name to generated header lines.
459 // to preserve the order of the original headers, the actual values are kept
460 // in a separate list. finally, the list of headers is flattened to form
461 // the normalized block of headers.
463 // NOTE: We take special care to preserve the whitespace around any commas
464 // that may occur in the original response headers. Because our consumer may
465 // be a web app, we cannot be certain of the semantics of commas despite the
466 // fact that RFC 2616 says that they should be regarded as value separators.
468 typedef base::hash_map
<std::string
, size_t> HeadersMap
;
469 HeadersMap headers_map
;
470 HeadersMap::iterator iter
= headers_map
.end();
472 std::vector
<std::string
> headers
;
474 for (size_t i
= 0; i
< parsed_
.size(); ++i
) {
475 DCHECK(!parsed_
[i
].is_continuation());
477 std::string
name(parsed_
[i
].name_begin
, parsed_
[i
].name_end
);
478 std::string lower_name
= base::StringToLowerASCII(name
);
480 iter
= headers_map
.find(lower_name
);
481 if (iter
== headers_map
.end()) {
482 iter
= headers_map
.insert(
483 HeadersMap::value_type(lower_name
, headers
.size())).first
;
484 headers
.push_back(name
+ ": ");
486 headers
[iter
->second
].append(", ");
489 std::string::const_iterator value_begin
= parsed_
[i
].value_begin
;
490 std::string::const_iterator value_end
= parsed_
[i
].value_end
;
491 while (++i
< parsed_
.size() && parsed_
[i
].is_continuation())
492 value_end
= parsed_
[i
].value_end
;
495 headers
[iter
->second
].append(value_begin
, value_end
);
498 for (size_t i
= 0; i
< headers
.size(); ++i
) {
499 output
->push_back('\n');
500 output
->append(headers
[i
]);
503 output
->push_back('\n');
506 bool HttpResponseHeaders::GetNormalizedHeader(const std::string
& name
,
507 std::string
* value
) const {
508 // If you hit this assertion, please use EnumerateHeader instead!
509 DCHECK(!HttpUtil::IsNonCoalescingHeader(name
));
515 while (i
< parsed_
.size()) {
516 i
= FindHeader(i
, name
);
517 if (i
== std::string::npos
)
525 std::string::const_iterator value_begin
= parsed_
[i
].value_begin
;
526 std::string::const_iterator value_end
= parsed_
[i
].value_end
;
527 while (++i
< parsed_
.size() && parsed_
[i
].is_continuation())
528 value_end
= parsed_
[i
].value_end
;
529 value
->append(value_begin
, value_end
);
535 std::string
HttpResponseHeaders::GetStatusLine() const {
536 // copy up to the null byte.
537 return std::string(raw_headers_
.c_str());
540 std::string
HttpResponseHeaders::GetStatusText() const {
541 // GetStatusLine() is already normalized, so it has the format:
542 // <http_version> SP <response_code> SP <status_text>
543 std::string status_text
= GetStatusLine();
544 std::string::const_iterator begin
= status_text
.begin();
545 std::string::const_iterator end
= status_text
.end();
546 for (int i
= 0; i
< 2; ++i
)
547 begin
= std::find(begin
, end
, ' ') + 1;
548 return std::string(begin
, end
);
551 bool HttpResponseHeaders::EnumerateHeaderLines(void** iter
,
553 std::string
* value
) const {
554 size_t i
= reinterpret_cast<size_t>(*iter
);
555 if (i
== parsed_
.size())
558 DCHECK(!parsed_
[i
].is_continuation());
560 name
->assign(parsed_
[i
].name_begin
, parsed_
[i
].name_end
);
562 std::string::const_iterator value_begin
= parsed_
[i
].value_begin
;
563 std::string::const_iterator value_end
= parsed_
[i
].value_end
;
564 while (++i
< parsed_
.size() && parsed_
[i
].is_continuation())
565 value_end
= parsed_
[i
].value_end
;
567 value
->assign(value_begin
, value_end
);
569 *iter
= reinterpret_cast<void*>(i
);
573 bool HttpResponseHeaders::EnumerateHeader(void** iter
,
574 const base::StringPiece
& name
,
575 std::string
* value
) const {
577 if (!iter
|| !*iter
) {
578 i
= FindHeader(0, name
);
580 i
= reinterpret_cast<size_t>(*iter
);
581 if (i
>= parsed_
.size()) {
582 i
= std::string::npos
;
583 } else if (!parsed_
[i
].is_continuation()) {
584 i
= FindHeader(i
, name
);
588 if (i
== std::string::npos
) {
594 *iter
= reinterpret_cast<void*>(i
+ 1);
595 value
->assign(parsed_
[i
].value_begin
, parsed_
[i
].value_end
);
599 bool HttpResponseHeaders::HasHeaderValue(const base::StringPiece
& name
,
600 const base::StringPiece
& value
) const {
601 // The value has to be an exact match. This is important since
602 // 'cache-control: no-cache' != 'cache-control: no-cache="foo"'
605 while (EnumerateHeader(&iter
, name
, &temp
)) {
606 if (base::EqualsCaseInsensitiveASCII(value
, temp
))
612 bool HttpResponseHeaders::HasHeader(const base::StringPiece
& name
) const {
613 return FindHeader(0, name
) != std::string::npos
;
616 HttpResponseHeaders::HttpResponseHeaders() : response_code_(-1) {
619 HttpResponseHeaders::~HttpResponseHeaders() {
622 // Note: this implementation implicitly assumes that line_end points at a valid
623 // sentinel character (such as '\0').
625 HttpVersion
HttpResponseHeaders::ParseVersion(
626 std::string::const_iterator line_begin
,
627 std::string::const_iterator line_end
) {
628 std::string::const_iterator p
= line_begin
;
630 // RFC2616 sec 3.1: HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT
631 // TODO: (1*DIGIT apparently means one or more digits, but we only handle 1).
632 // TODO: handle leading zeros, which is allowed by the rfc1616 sec 3.1.
634 if ((line_end
- p
< 4) || !base::LowerCaseEqualsASCII(p
, p
+ 4, "http")) {
635 DVLOG(1) << "missing status line";
636 return HttpVersion();
641 if (p
>= line_end
|| *p
!= '/') {
642 DVLOG(1) << "missing version";
643 return HttpVersion();
646 std::string::const_iterator dot
= std::find(p
, line_end
, '.');
647 if (dot
== line_end
) {
648 DVLOG(1) << "malformed version";
649 return HttpVersion();
652 ++p
; // from / to first digit.
653 ++dot
; // from . to second digit.
655 if (!(*p
>= '0' && *p
<= '9' && *dot
>= '0' && *dot
<= '9')) {
656 DVLOG(1) << "malformed version number";
657 return HttpVersion();
660 uint16 major
= *p
- '0';
661 uint16 minor
= *dot
- '0';
663 return HttpVersion(major
, minor
);
666 // Note: this implementation implicitly assumes that line_end points at a valid
667 // sentinel character (such as '\0').
668 void HttpResponseHeaders::ParseStatusLine(
669 std::string::const_iterator line_begin
,
670 std::string::const_iterator line_end
,
672 // Extract the version number
673 parsed_http_version_
= ParseVersion(line_begin
, line_end
);
675 // Clamp the version number to one of: {0.9, 1.0, 1.1}
676 if (parsed_http_version_
== HttpVersion(0, 9) && !has_headers
) {
677 http_version_
= HttpVersion(0, 9);
678 raw_headers_
= "HTTP/0.9";
679 } else if (parsed_http_version_
>= HttpVersion(1, 1)) {
680 http_version_
= HttpVersion(1, 1);
681 raw_headers_
= "HTTP/1.1";
683 // Treat everything else like HTTP 1.0
684 http_version_
= HttpVersion(1, 0);
685 raw_headers_
= "HTTP/1.0";
687 if (parsed_http_version_
!= http_version_
) {
688 DVLOG(1) << "assuming HTTP/" << http_version_
.major_value() << "."
689 << http_version_
.minor_value();
692 // TODO(eroman): this doesn't make sense if ParseVersion failed.
693 std::string::const_iterator p
= std::find(line_begin
, line_end
, ' ');
696 DVLOG(1) << "missing response status; assuming 200 OK";
697 raw_headers_
.append(" 200 OK");
698 response_code_
= 200;
706 std::string::const_iterator code
= p
;
707 while (*p
>= '0' && *p
<= '9')
711 DVLOG(1) << "missing response status number; assuming 200";
712 raw_headers_
.append(" 200 OK");
713 response_code_
= 200;
716 raw_headers_
.push_back(' ');
717 raw_headers_
.append(code
, p
);
718 raw_headers_
.push_back(' ');
719 base::StringToInt(StringPiece(code
, p
), &response_code_
);
725 // Trim trailing whitespace.
726 while (line_end
> p
&& line_end
[-1] == ' ')
730 DVLOG(1) << "missing response status text; assuming OK";
731 // Not super critical what we put here. Just use "OK"
732 // even if it isn't descriptive of response_code_.
733 raw_headers_
.append("OK");
735 raw_headers_
.append(p
, line_end
);
739 size_t HttpResponseHeaders::FindHeader(size_t from
,
740 const base::StringPiece
& search
) const {
741 for (size_t i
= from
; i
< parsed_
.size(); ++i
) {
742 if (parsed_
[i
].is_continuation())
744 base::StringPiece
name(parsed_
[i
].name_begin
, parsed_
[i
].name_end
);
745 if (base::EqualsCaseInsensitiveASCII(search
, name
))
749 return std::string::npos
;
752 bool HttpResponseHeaders::GetCacheControlDirective(const StringPiece
& directive
,
753 TimeDelta
* result
) const {
754 StringPiece
name("cache-control");
757 size_t directive_size
= directive
.size();
760 while (EnumerateHeader(&iter
, name
, &value
)) {
761 if (value
.size() > directive_size
+ 1 &&
762 base::LowerCaseEqualsASCII(
763 value
.begin(), value
.begin() + directive_size
, directive
.begin()) &&
764 value
[directive_size
] == '=') {
767 StringPiece(value
.begin() + directive_size
+ 1, value
.end()),
769 *result
= TimeDelta::FromSeconds(seconds
);
777 void HttpResponseHeaders::AddHeader(std::string::const_iterator name_begin
,
778 std::string::const_iterator name_end
,
779 std::string::const_iterator values_begin
,
780 std::string::const_iterator values_end
) {
781 // If the header can be coalesced, then we should split it up.
782 if (values_begin
== values_end
||
783 HttpUtil::IsNonCoalescingHeader(name_begin
, name_end
)) {
784 AddToParsed(name_begin
, name_end
, values_begin
, values_end
);
786 HttpUtil::ValuesIterator
it(values_begin
, values_end
, ',');
787 while (it
.GetNext()) {
788 AddToParsed(name_begin
, name_end
, it
.value_begin(), it
.value_end());
789 // clobber these so that subsequent values are treated as continuations
790 name_begin
= name_end
= raw_headers_
.end();
795 void HttpResponseHeaders::AddToParsed(std::string::const_iterator name_begin
,
796 std::string::const_iterator name_end
,
797 std::string::const_iterator value_begin
,
798 std::string::const_iterator value_end
) {
800 header
.name_begin
= name_begin
;
801 header
.name_end
= name_end
;
802 header
.value_begin
= value_begin
;
803 header
.value_end
= value_end
;
804 parsed_
.push_back(header
);
807 void HttpResponseHeaders::AddNonCacheableHeaders(HeaderSet
* result
) const {
808 // Add server specified transients. Any 'cache-control: no-cache="foo,bar"'
809 // headers present in the response specify additional headers that we should
810 // not store in the cache.
811 const char kCacheControl
[] = "cache-control";
812 const char kPrefix
[] = "no-cache=\"";
813 const size_t kPrefixLen
= sizeof(kPrefix
) - 1;
817 while (EnumerateHeader(&iter
, kCacheControl
, &value
)) {
818 // If the value is smaller than the prefix and a terminal quote, skip
820 if (value
.size() <= kPrefixLen
||
821 value
.compare(0, kPrefixLen
, kPrefix
) != 0) {
824 // if it doesn't end with a quote, then treat as malformed
825 if (value
[value
.size()-1] != '\"')
828 // process the value as a comma-separated list of items. Each
829 // item can be wrapped by linear white space.
830 std::string::const_iterator item
= value
.begin() + kPrefixLen
;
831 std::string::const_iterator end
= value
.end() - 1;
832 while (item
!= end
) {
833 // Find the comma to compute the length of the current item,
834 // and the position of the next one.
835 std::string::const_iterator item_next
= std::find(item
, end
, ',');
836 std::string::const_iterator item_end
= end
;
837 if (item_next
!= end
) {
838 // Skip over comma for next position.
839 item_end
= item_next
;
842 // trim off leading and trailing whitespace in this item.
843 HttpUtil::TrimLWS(&item
, &item_end
);
845 // assuming the header is not empty, lowercase and insert into set
846 if (item_end
> item
) {
847 std::string
name(&*item
, item_end
- item
);
848 base::StringToLowerASCII(&name
);
849 result
->insert(name
);
852 // Continue to next item.
858 void HttpResponseHeaders::AddHopByHopHeaders(HeaderSet
* result
) {
859 for (size_t i
= 0; i
< arraysize(kHopByHopResponseHeaders
); ++i
)
860 result
->insert(std::string(kHopByHopResponseHeaders
[i
]));
863 void HttpResponseHeaders::AddCookieHeaders(HeaderSet
* result
) {
864 for (size_t i
= 0; i
< arraysize(kCookieResponseHeaders
); ++i
)
865 result
->insert(std::string(kCookieResponseHeaders
[i
]));
868 void HttpResponseHeaders::AddChallengeHeaders(HeaderSet
* result
) {
869 for (size_t i
= 0; i
< arraysize(kChallengeResponseHeaders
); ++i
)
870 result
->insert(std::string(kChallengeResponseHeaders
[i
]));
873 void HttpResponseHeaders::AddHopContentRangeHeaders(HeaderSet
* result
) {
874 result
->insert(kContentRange
);
877 void HttpResponseHeaders::AddSecurityStateHeaders(HeaderSet
* result
) {
878 for (size_t i
= 0; i
< arraysize(kSecurityStateHeaders
); ++i
)
879 result
->insert(std::string(kSecurityStateHeaders
[i
]));
882 void HttpResponseHeaders::GetMimeTypeAndCharset(std::string
* mime_type
,
883 std::string
* charset
) const {
887 std::string name
= "content-type";
890 bool had_charset
= false;
893 while (EnumerateHeader(&iter
, name
, &value
))
894 HttpUtil::ParseContentType(value
, mime_type
, charset
, &had_charset
, NULL
);
897 bool HttpResponseHeaders::GetMimeType(std::string
* mime_type
) const {
899 GetMimeTypeAndCharset(mime_type
, &unused
);
900 return !mime_type
->empty();
903 bool HttpResponseHeaders::GetCharset(std::string
* charset
) const {
905 GetMimeTypeAndCharset(&unused
, charset
);
906 return !charset
->empty();
909 bool HttpResponseHeaders::IsRedirect(std::string
* location
) const {
910 if (!IsRedirectResponseCode(response_code_
))
913 // If we lack a Location header, then we can't treat this as a redirect.
914 // We assume that the first non-empty location value is the target URL that
915 // we want to follow. TODO(darin): Is this consistent with other browsers?
916 size_t i
= std::string::npos
;
918 i
= FindHeader(++i
, "location");
919 if (i
== std::string::npos
)
921 // If the location value is empty, then it doesn't count.
922 } while (parsed_
[i
].value_begin
== parsed_
[i
].value_end
);
925 // Escape any non-ASCII characters to preserve them. The server should
926 // only be returning ASCII here, but for compat we need to do this.
927 *location
= EscapeNonASCII(
928 std::string(parsed_
[i
].value_begin
, parsed_
[i
].value_end
));
935 bool HttpResponseHeaders::IsRedirectResponseCode(int response_code
) {
936 // Users probably want to see 300 (multiple choice) pages, so we don't count
937 // them as redirects that need to be followed.
938 return (response_code
== 301 ||
939 response_code
== 302 ||
940 response_code
== 303 ||
941 response_code
== 307 ||
942 response_code
== 308);
945 // From RFC 2616 section 13.2.4:
947 // The calculation to determine if a response has expired is quite simple:
949 // response_is_fresh = (freshness_lifetime > current_age)
951 // Of course, there are other factors that can force a response to always be
952 // validated or re-fetched.
954 // From RFC 5861 section 3, a stale response may be used while revalidation is
955 // performed in the background if
957 // freshness_lifetime + stale_while_revalidate > current_age
959 ValidationType
HttpResponseHeaders::RequiresValidation(
960 const Time
& request_time
,
961 const Time
& response_time
,
962 const Time
& current_time
) const {
963 FreshnessLifetimes lifetimes
= GetFreshnessLifetimes(response_time
);
964 if (lifetimes
.freshness
== TimeDelta() && lifetimes
.staleness
== TimeDelta())
965 return VALIDATION_SYNCHRONOUS
;
967 TimeDelta age
= GetCurrentAge(request_time
, response_time
, current_time
);
969 if (lifetimes
.freshness
> age
)
970 return VALIDATION_NONE
;
972 if (lifetimes
.freshness
+ lifetimes
.staleness
> age
)
973 return VALIDATION_ASYNCHRONOUS
;
975 return VALIDATION_SYNCHRONOUS
;
978 // From RFC 2616 section 13.2.4:
980 // The max-age directive takes priority over Expires, so if max-age is present
981 // in a response, the calculation is simply:
983 // freshness_lifetime = max_age_value
985 // Otherwise, if Expires is present in the response, the calculation is:
987 // freshness_lifetime = expires_value - date_value
989 // Note that neither of these calculations is vulnerable to clock skew, since
990 // all of the information comes from the origin server.
992 // Also, if the response does have a Last-Modified time, the heuristic
993 // expiration value SHOULD be no more than some fraction of the interval since
994 // that time. A typical setting of this fraction might be 10%:
996 // freshness_lifetime = (date_value - last_modified_value) * 0.10
998 // If the stale-while-revalidate directive is present, then it is used to set
999 // the |staleness| time, unless it overridden by another directive.
1001 HttpResponseHeaders::FreshnessLifetimes
1002 HttpResponseHeaders::GetFreshnessLifetimes(const Time
& response_time
) const {
1003 FreshnessLifetimes lifetimes
;
1004 // Check for headers that force a response to never be fresh. For backwards
1005 // compat, we treat "Pragma: no-cache" as a synonym for "Cache-Control:
1006 // no-cache" even though RFC 2616 does not specify it.
1007 if (HasHeaderValue("cache-control", "no-cache") ||
1008 HasHeaderValue("cache-control", "no-store") ||
1009 HasHeaderValue("pragma", "no-cache") ||
1010 // Vary: * is never usable: see RFC 2616 section 13.6.
1011 HasHeaderValue("vary", "*")) {
1015 // Cache-Control directive must_revalidate overrides stale-while-revalidate.
1016 bool must_revalidate
= HasHeaderValue("cache-control", "must-revalidate");
1018 if (must_revalidate
|| !GetStaleWhileRevalidateValue(&lifetimes
.staleness
)) {
1019 DCHECK_EQ(TimeDelta(), lifetimes
.staleness
);
1022 // NOTE: "Cache-Control: max-age" overrides Expires, so we only check the
1023 // Expires header after checking for max-age in GetFreshnessLifetimes. This
1024 // is important since "Expires: <date in the past>" means not fresh, but
1025 // it should not trump a max-age value.
1026 if (GetMaxAgeValue(&lifetimes
.freshness
))
1029 // If there is no Date header, then assume that the server response was
1030 // generated at the time when we received the response.
1032 if (!GetDateValue(&date_value
))
1033 date_value
= response_time
;
1036 if (GetExpiresValue(&expires_value
)) {
1037 // The expires value can be a date in the past!
1038 if (expires_value
> date_value
) {
1039 lifetimes
.freshness
= expires_value
- date_value
;
1043 DCHECK_EQ(TimeDelta(), lifetimes
.freshness
);
1047 // From RFC 2616 section 13.4:
1049 // A response received with a status code of 200, 203, 206, 300, 301 or 410
1050 // MAY be stored by a cache and used in reply to a subsequent request,
1051 // subject to the expiration mechanism, unless a cache-control directive
1052 // prohibits caching.
1054 // A response received with any other status code (e.g. status codes 302
1055 // and 307) MUST NOT be returned in a reply to a subsequent request unless
1056 // there are cache-control directives or another header(s) that explicitly
1059 // From RFC 2616 section 14.9.4:
1061 // When the must-revalidate directive is present in a response received by
1062 // a cache, that cache MUST NOT use the entry after it becomes stale to
1063 // respond to a subsequent request without first revalidating it with the
1064 // origin server. (I.e., the cache MUST do an end-to-end revalidation every
1065 // time, if, based solely on the origin server's Expires or max-age value,
1066 // the cached response is stale.)
1068 // https://datatracker.ietf.org/doc/draft-reschke-http-status-308/ is an
1069 // experimental RFC that adds 308 permanent redirect as well, for which "any
1070 // future references ... SHOULD use one of the returned URIs."
1071 if ((response_code_
== 200 || response_code_
== 203 ||
1072 response_code_
== 206) && !must_revalidate
) {
1073 // TODO(darin): Implement a smarter heuristic.
1074 Time last_modified_value
;
1075 if (GetLastModifiedValue(&last_modified_value
)) {
1076 // The last-modified value can be a date in the future!
1077 if (last_modified_value
<= date_value
) {
1078 lifetimes
.freshness
= (date_value
- last_modified_value
) / 10;
1084 // These responses are implicitly fresh (unless otherwise overruled):
1085 if (response_code_
== 300 || response_code_
== 301 || response_code_
== 308 ||
1086 response_code_
== 410) {
1087 lifetimes
.freshness
= TimeDelta::Max();
1088 lifetimes
.staleness
= TimeDelta(); // It should never be stale.
1092 // Our heuristic freshness estimate for this resource is 0 seconds, in
1093 // accordance with common browser behaviour. However, stale-while-revalidate
1095 DCHECK_EQ(TimeDelta(), lifetimes
.freshness
);
1099 // From RFC 2616 section 13.2.3:
1101 // Summary of age calculation algorithm, when a cache receives a response:
1105 // * is the value of Age: header received by the cache with
1108 // * is the value of the origin server's Date: header
1110 // * is the (local) time when the cache made the request
1111 // * that resulted in this cached response
1113 // * is the (local) time when the cache received the
1116 // * is the current (local) time
1118 // apparent_age = max(0, response_time - date_value);
1119 // corrected_received_age = max(apparent_age, age_value);
1120 // response_delay = response_time - request_time;
1121 // corrected_initial_age = corrected_received_age + response_delay;
1122 // resident_time = now - response_time;
1123 // current_age = corrected_initial_age + resident_time;
1125 TimeDelta
HttpResponseHeaders::GetCurrentAge(const Time
& request_time
,
1126 const Time
& response_time
,
1127 const Time
& current_time
) const {
1128 // If there is no Date header, then assume that the server response was
1129 // generated at the time when we received the response.
1131 if (!GetDateValue(&date_value
))
1132 date_value
= response_time
;
1134 // If there is no Age header, then assume age is zero. GetAgeValue does not
1135 // modify its out param if the value does not exist.
1136 TimeDelta age_value
;
1137 GetAgeValue(&age_value
);
1139 TimeDelta apparent_age
= std::max(TimeDelta(), response_time
- date_value
);
1140 TimeDelta corrected_received_age
= std::max(apparent_age
, age_value
);
1141 TimeDelta response_delay
= response_time
- request_time
;
1142 TimeDelta corrected_initial_age
= corrected_received_age
+ response_delay
;
1143 TimeDelta resident_time
= current_time
- response_time
;
1144 TimeDelta current_age
= corrected_initial_age
+ resident_time
;
1149 bool HttpResponseHeaders::GetMaxAgeValue(TimeDelta
* result
) const {
1150 return GetCacheControlDirective("max-age", result
);
1153 bool HttpResponseHeaders::GetAgeValue(TimeDelta
* result
) const {
1155 if (!EnumerateHeader(NULL
, "Age", &value
))
1159 base::StringToInt64(value
, &seconds
);
1160 *result
= TimeDelta::FromSeconds(seconds
);
1164 bool HttpResponseHeaders::GetDateValue(Time
* result
) const {
1165 return GetTimeValuedHeader("Date", result
);
1168 bool HttpResponseHeaders::GetLastModifiedValue(Time
* result
) const {
1169 return GetTimeValuedHeader("Last-Modified", result
);
1172 bool HttpResponseHeaders::GetExpiresValue(Time
* result
) const {
1173 return GetTimeValuedHeader("Expires", result
);
1176 bool HttpResponseHeaders::GetStaleWhileRevalidateValue(
1177 TimeDelta
* result
) const {
1178 return GetCacheControlDirective("stale-while-revalidate", result
);
1181 bool HttpResponseHeaders::GetTimeValuedHeader(const std::string
& name
,
1182 Time
* result
) const {
1184 if (!EnumerateHeader(NULL
, name
, &value
))
1187 // When parsing HTTP dates it's beneficial to default to GMT because:
1188 // 1. RFC2616 3.3.1 says times should always be specified in GMT
1189 // 2. Only counter-example incorrectly appended "UTC" (crbug.com/153759)
1190 // 3. When adjusting cookie expiration times for clock skew
1191 // (crbug.com/135131) this better matches our cookie expiration
1192 // time parser which ignores timezone specifiers and assumes GMT.
1193 // 4. This is exactly what Firefox does.
1194 // TODO(pauljensen): The ideal solution would be to return false if the
1195 // timezone could not be understood so as to avoid makeing other calculations
1196 // based on an incorrect time. This would require modifying the time
1197 // library or duplicating the code. (http://crbug.com/158327)
1198 return Time::FromUTCString(value
.c_str(), result
);
1201 // We accept the first value of "close" or "keep-alive" in a Connection or
1202 // Proxy-Connection header, in that order. Obeying "keep-alive" in HTTP/1.1 or
1203 // "close" in 1.0 is not strictly standards-compliant, but we'd like to
1204 // avoid looking at the Proxy-Connection header whenever it is reasonable to do
1206 // TODO(ricea): Measure real-world usage of the "Proxy-Connection" header,
1207 // with a view to reducing support for it in order to make our Connection header
1208 // handling more RFC 7230 compliant.
1209 bool HttpResponseHeaders::IsKeepAlive() const {
1210 // NOTE: It is perhaps risky to assume that a Proxy-Connection header is
1211 // meaningful when we don't know that this response was from a proxy, but
1212 // Mozilla also does this, so we'll do the same.
1213 static const char* const kConnectionHeaders
[] = {
1214 "connection", "proxy-connection"};
1215 struct KeepAliveToken
{
1216 const char* const token
;
1219 static const KeepAliveToken kKeepAliveTokens
[] = {{"keep-alive", true},
1222 if (http_version_
< HttpVersion(1, 0))
1225 for (const char* header
: kConnectionHeaders
) {
1226 void* iterator
= nullptr;
1228 while (EnumerateHeader(&iterator
, header
, &token
)) {
1229 for (const KeepAliveToken
& keep_alive_token
: kKeepAliveTokens
) {
1230 if (base::LowerCaseEqualsASCII(token
, keep_alive_token
.token
))
1231 return keep_alive_token
.keep_alive
;
1235 return http_version_
!= HttpVersion(1, 0);
1238 bool HttpResponseHeaders::HasStrongValidators() const {
1239 std::string etag_header
;
1240 EnumerateHeader(NULL
, "etag", &etag_header
);
1241 std::string last_modified_header
;
1242 EnumerateHeader(NULL
, "Last-Modified", &last_modified_header
);
1243 std::string date_header
;
1244 EnumerateHeader(NULL
, "Date", &date_header
);
1245 return HttpUtil::HasStrongValidators(GetHttpVersion(),
1247 last_modified_header
,
1252 // Content-Length = "Content-Length" ":" 1*DIGIT
1253 int64
HttpResponseHeaders::GetContentLength() const {
1254 return GetInt64HeaderValue("content-length");
1257 int64
HttpResponseHeaders::GetInt64HeaderValue(
1258 const std::string
& header
) const {
1260 std::string content_length_val
;
1261 if (!EnumerateHeader(&iter
, header
, &content_length_val
))
1264 if (content_length_val
.empty())
1267 if (content_length_val
[0] == '+')
1271 bool ok
= base::StringToInt64(content_length_val
, &result
);
1272 if (!ok
|| result
< 0)
1278 // From RFC 2616 14.16:
1279 // content-range-spec =
1280 // bytes-unit SP byte-range-resp-spec "/" ( instance-length | "*" )
1281 // byte-range-resp-spec = (first-byte-pos "-" last-byte-pos) | "*"
1282 // instance-length = 1*DIGIT
1283 // bytes-unit = "bytes"
1284 bool HttpResponseHeaders::GetContentRange(int64
* first_byte_position
,
1285 int64
* last_byte_position
,
1286 int64
* instance_length
) const {
1288 std::string content_range_spec
;
1289 *first_byte_position
= *last_byte_position
= *instance_length
= -1;
1290 if (!EnumerateHeader(&iter
, kContentRange
, &content_range_spec
))
1293 // If the header value is empty, we have an invalid header.
1294 if (content_range_spec
.empty())
1297 size_t space_position
= content_range_spec
.find(' ');
1298 if (space_position
== std::string::npos
)
1301 // Invalid header if it doesn't contain "bytes-unit".
1302 std::string::const_iterator content_range_spec_begin
=
1303 content_range_spec
.begin();
1304 std::string::const_iterator content_range_spec_end
=
1305 content_range_spec
.begin() + space_position
;
1306 HttpUtil::TrimLWS(&content_range_spec_begin
, &content_range_spec_end
);
1307 if (!base::LowerCaseEqualsASCII(content_range_spec_begin
,
1308 content_range_spec_end
, "bytes")) {
1312 size_t slash_position
= content_range_spec
.find('/', space_position
+ 1);
1313 if (slash_position
== std::string::npos
)
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
,
1350 last_byte_position
);
1352 *first_byte_position
= *last_byte_position
= -1;
1355 if (*first_byte_position
< 0 || *last_byte_position
< 0 ||
1356 *first_byte_position
> *last_byte_position
)
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::LowerCaseEqualsASCII(instance_length_begin
, instance_length_end
,
1374 } else if (!base::StringToInt64(StringPiece(instance_length_begin
,
1375 instance_length_end
),
1377 *instance_length
= -1;
1381 // We have all the values; let's verify that they make sense for a 206
1383 if (*first_byte_position
< 0 || *last_byte_position
< 0 ||
1384 *instance_length
< 0 || *instance_length
- 1 < *last_byte_position
)
1390 scoped_ptr
<base::Value
> HttpResponseHeaders::NetLogCallback(
1391 NetLogCaptureMode capture_mode
) const {
1392 scoped_ptr
<base::DictionaryValue
> dict(new base::DictionaryValue());
1393 base::ListValue
* headers
= new base::ListValue();
1394 headers
->Append(new base::StringValue(GetStatusLine()));
1395 void* iterator
= NULL
;
1398 while (EnumerateHeaderLines(&iterator
, &name
, &value
)) {
1399 std::string log_value
=
1400 ElideHeaderValueForNetLog(capture_mode
, name
, value
);
1401 std::string escaped_name
= EscapeNonASCII(name
);
1402 std::string escaped_value
= EscapeNonASCII(log_value
);
1404 new base::StringValue(
1405 base::StringPrintf("%s: %s", escaped_name
.c_str(),
1406 escaped_value
.c_str())));
1408 dict
->Set("headers", headers
);
1413 bool HttpResponseHeaders::FromNetLogParam(
1414 const base::Value
* event_param
,
1415 scoped_refptr
<HttpResponseHeaders
>* http_response_headers
) {
1416 *http_response_headers
= NULL
;
1418 const base::DictionaryValue
* dict
= NULL
;
1419 const base::ListValue
* header_list
= NULL
;
1422 !event_param
->GetAsDictionary(&dict
) ||
1423 !dict
->GetList("headers", &header_list
)) {
1427 std::string raw_headers
;
1428 for (base::ListValue::const_iterator it
= header_list
->begin();
1429 it
!= header_list
->end();
1431 std::string header_line
;
1432 if (!(*it
)->GetAsString(&header_line
))
1435 raw_headers
.append(header_line
);
1436 raw_headers
.push_back('\0');
1438 raw_headers
.push_back('\0');
1439 *http_response_headers
= new HttpResponseHeaders(raw_headers
);
1443 bool HttpResponseHeaders::IsChunkEncoded() const {
1444 // Ignore spurious chunked responses from HTTP/1.0 servers and proxies.
1445 return GetHttpVersion() >= HttpVersion(1, 1) &&
1446 HasHeaderValue("Transfer-Encoding", "chunked");