This source file includes following definitions.
- ShouldUpdateHeader
- CheckDoesNotHaveEmbededNulls
- Persist
- Update
- MergeWithHeaders
- RemoveHeader
- RemoveHeaderLine
- AddHeader
- ReplaceStatusLine
- UpdateWithNewRange
- Parse
- GetNormalizedHeaders
- GetNormalizedHeader
- GetStatusLine
- GetStatusText
- EnumerateHeaderLines
- EnumerateHeader
- HasHeaderValue
- HasHeader
- ParseVersion
- ParseStatusLine
- FindHeader
- AddHeader
- AddToParsed
- AddNonCacheableHeaders
- AddHopByHopHeaders
- AddCookieHeaders
- AddChallengeHeaders
- AddHopContentRangeHeaders
- AddSecurityStateHeaders
- GetMimeTypeAndCharset
- GetMimeType
- GetCharset
- IsRedirect
- IsRedirectResponseCode
- RequiresValidation
- GetFreshnessLifetime
- GetCurrentAge
- GetMaxAgeValue
- GetAgeValue
- GetDateValue
- GetLastModifiedValue
- GetExpiresValue
- GetTimeValuedHeader
- IsKeepAlive
- HasStrongValidators
- GetContentLength
- GetInt64HeaderValue
- GetContentRange
- NetLogCallback
- FromNetLogParam
- IsChunkEncoded
- GetChromeProxyBypassDuration
- GetChromeProxyInfo
- IsChromeProxyResponse
- GetChromeProxyBypassEventType
#include "net/http/http_response_headers.h"
#include <algorithm>
#include "base/format_macros.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/pickle.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "base/values.h"
#include "net/base/escape.h"
#include "net/http/http_byte_range.h"
#include "net/http/http_log_util.h"
#include "net/http/http_util.h"
#if defined(SPDY_PROXY_AUTH_ORIGIN)
#include "net/http/http_status_code.h"
#include "net/proxy/proxy_service.h"
#endif
using base::StringPiece;
using base::Time;
using base::TimeDelta;
namespace net {
namespace {
const char* const kHopByHopResponseHeaders[] = {
"connection",
"proxy-connection",
"keep-alive",
"trailer",
"transfer-encoding",
"upgrade"
};
const char* const kChallengeResponseHeaders[] = {
"www-authenticate",
"proxy-authenticate"
};
const char* const kCookieResponseHeaders[] = {
"set-cookie",
"set-cookie2"
};
const char* const kSecurityStateHeaders[] = {
"strict-transport-security",
"public-key-pins"
};
const char* const kNonUpdatedHeaders[] = {
"connection",
"proxy-connection",
"keep-alive",
"www-authenticate",
"proxy-authenticate",
"trailer",
"transfer-encoding",
"upgrade",
"etag",
"x-frame-options",
"x-xss-protection",
};
const char* const kNonUpdatedHeaderPrefixes[] = {
"content-",
"x-content-",
"x-webkit-"
};
bool ShouldUpdateHeader(const std::string::const_iterator& name_begin,
const std::string::const_iterator& name_end) {
for (size_t i = 0; i < arraysize(kNonUpdatedHeaders); ++i) {
if (LowerCaseEqualsASCII(name_begin, name_end, kNonUpdatedHeaders[i]))
return false;
}
for (size_t i = 0; i < arraysize(kNonUpdatedHeaderPrefixes); ++i) {
if (StartsWithASCII(std::string(name_begin, name_end),
kNonUpdatedHeaderPrefixes[i], false))
return false;
}
return true;
}
void CheckDoesNotHaveEmbededNulls(const std::string& str) {
CHECK(str.find('\0') == std::string::npos);
}
}
const char HttpResponseHeaders::kContentRange[] = "Content-Range";
struct HttpResponseHeaders::ParsedHeader {
bool is_continuation() const { return name_begin == name_end; }
std::string::const_iterator name_begin;
std::string::const_iterator name_end;
std::string::const_iterator value_begin;
std::string::const_iterator value_end;
};
HttpResponseHeaders::HttpResponseHeaders(const std::string& raw_input)
: response_code_(-1) {
Parse(raw_input);
UMA_HISTOGRAM_CUSTOM_ENUMERATION("Net.HttpResponseCode",
HttpUtil::MapStatusCodeForHistogram(
response_code_),
HttpUtil::GetStatusCodesForHistogram());
}
HttpResponseHeaders::HttpResponseHeaders(const Pickle& pickle,
PickleIterator* iter)
: response_code_(-1) {
std::string raw_input;
if (pickle.ReadString(iter, &raw_input))
Parse(raw_input);
}
void HttpResponseHeaders::Persist(Pickle* pickle, PersistOptions options) {
if (options == PERSIST_RAW) {
pickle->WriteString(raw_headers_);
return;
}
HeaderSet filter_headers;
if ((options & PERSIST_SANS_NON_CACHEABLE) == PERSIST_SANS_NON_CACHEABLE)
AddNonCacheableHeaders(&filter_headers);
if ((options & PERSIST_SANS_COOKIES) == PERSIST_SANS_COOKIES)
AddCookieHeaders(&filter_headers);
if ((options & PERSIST_SANS_CHALLENGES) == PERSIST_SANS_CHALLENGES)
AddChallengeHeaders(&filter_headers);
if ((options & PERSIST_SANS_HOP_BY_HOP) == PERSIST_SANS_HOP_BY_HOP)
AddHopByHopHeaders(&filter_headers);
if ((options & PERSIST_SANS_RANGES) == PERSIST_SANS_RANGES)
AddHopContentRangeHeaders(&filter_headers);
if ((options & PERSIST_SANS_SECURITY_STATE) == PERSIST_SANS_SECURITY_STATE)
AddSecurityStateHeaders(&filter_headers);
std::string blob;
blob.reserve(raw_headers_.size());
blob.assign(raw_headers_.c_str(), strlen(raw_headers_.c_str()) + 1);
for (size_t i = 0; i < parsed_.size(); ++i) {
DCHECK(!parsed_[i].is_continuation());
size_t k = i;
while (++k < parsed_.size() && parsed_[k].is_continuation()) {}
--k;
std::string header_name(parsed_[i].name_begin, parsed_[i].name_end);
StringToLowerASCII(&header_name);
if (filter_headers.find(header_name) == filter_headers.end()) {
blob.append(parsed_[i].name_begin, parsed_[k].value_end);
blob.push_back('\0');
}
i = k;
}
blob.push_back('\0');
pickle->WriteString(blob);
}
void HttpResponseHeaders::Update(const HttpResponseHeaders& new_headers) {
DCHECK(new_headers.response_code() == 304 ||
new_headers.response_code() == 206);
std::string new_raw_headers(raw_headers_.c_str());
new_raw_headers.push_back('\0');
HeaderSet updated_headers;
for (size_t i = 0; i < new_headers.parsed_.size(); ++i) {
const HeaderList& new_parsed = new_headers.parsed_;
DCHECK(!new_parsed[i].is_continuation());
size_t k = i;
while (++k < new_parsed.size() && new_parsed[k].is_continuation()) {}
--k;
const std::string::const_iterator& name_begin = new_parsed[i].name_begin;
const std::string::const_iterator& name_end = new_parsed[i].name_end;
if (ShouldUpdateHeader(name_begin, name_end)) {
std::string name(name_begin, name_end);
StringToLowerASCII(&name);
updated_headers.insert(name);
new_raw_headers.append(name_begin, new_parsed[k].value_end);
new_raw_headers.push_back('\0');
}
i = k;
}
MergeWithHeaders(new_raw_headers, updated_headers);
}
void HttpResponseHeaders::MergeWithHeaders(const std::string& raw_headers,
const HeaderSet& headers_to_remove) {
std::string new_raw_headers(raw_headers);
for (size_t i = 0; i < parsed_.size(); ++i) {
DCHECK(!parsed_[i].is_continuation());
size_t k = i;
while (++k < parsed_.size() && parsed_[k].is_continuation()) {}
--k;
std::string name(parsed_[i].name_begin, parsed_[i].name_end);
StringToLowerASCII(&name);
if (headers_to_remove.find(name) == headers_to_remove.end()) {
new_raw_headers.append(parsed_[i].name_begin, parsed_[k].value_end);
new_raw_headers.push_back('\0');
}
i = k;
}
new_raw_headers.push_back('\0');
raw_headers_.clear();
parsed_.clear();
Parse(new_raw_headers);
}
void HttpResponseHeaders::RemoveHeader(const std::string& name) {
std::string new_raw_headers(raw_headers_.c_str());
new_raw_headers.push_back('\0');
std::string lowercase_name(name);
StringToLowerASCII(&lowercase_name);
HeaderSet to_remove;
to_remove.insert(lowercase_name);
MergeWithHeaders(new_raw_headers, to_remove);
}
void HttpResponseHeaders::RemoveHeaderLine(const std::string& name,
const std::string& value) {
std::string name_lowercase(name);
StringToLowerASCII(&name_lowercase);
std::string new_raw_headers(GetStatusLine());
new_raw_headers.push_back('\0');
new_raw_headers.reserve(raw_headers_.size());
void* iter = NULL;
std::string old_header_name;
std::string old_header_value;
while (EnumerateHeaderLines(&iter, &old_header_name, &old_header_value)) {
std::string old_header_name_lowercase(name);
StringToLowerASCII(&old_header_name_lowercase);
if (name_lowercase == old_header_name_lowercase &&
value == old_header_value)
continue;
new_raw_headers.append(old_header_name);
new_raw_headers.push_back(':');
new_raw_headers.push_back(' ');
new_raw_headers.append(old_header_value);
new_raw_headers.push_back('\0');
}
new_raw_headers.push_back('\0');
raw_headers_.clear();
parsed_.clear();
Parse(new_raw_headers);
}
void HttpResponseHeaders::AddHeader(const std::string& header) {
CheckDoesNotHaveEmbededNulls(header);
DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 2]);
DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 1]);
std::string new_raw_headers(raw_headers_, 0, raw_headers_.size() - 1);
new_raw_headers.append(header);
new_raw_headers.push_back('\0');
new_raw_headers.push_back('\0');
raw_headers_.clear();
parsed_.clear();
Parse(new_raw_headers);
}
void HttpResponseHeaders::ReplaceStatusLine(const std::string& new_status) {
CheckDoesNotHaveEmbededNulls(new_status);
std::string new_raw_headers(new_status);
new_raw_headers.push_back('\0');
HeaderSet empty_to_remove;
MergeWithHeaders(new_raw_headers, empty_to_remove);
}
void HttpResponseHeaders::UpdateWithNewRange(
const HttpByteRange& byte_range,
int64 resource_size,
bool replace_status_line) {
DCHECK(byte_range.IsValid());
DCHECK(byte_range.HasFirstBytePosition());
DCHECK(byte_range.HasLastBytePosition());
const char kLengthHeader[] = "Content-Length";
const char kRangeHeader[] = "Content-Range";
RemoveHeader(kLengthHeader);
RemoveHeader(kRangeHeader);
int64 start = byte_range.first_byte_position();
int64 end = byte_range.last_byte_position();
int64 range_len = end - start + 1;
if (replace_status_line)
ReplaceStatusLine("HTTP/1.1 206 Partial Content");
AddHeader(base::StringPrintf("%s: bytes %" PRId64 "-%" PRId64 "/%" PRId64,
kRangeHeader, start, end, resource_size));
AddHeader(base::StringPrintf("%s: %" PRId64, kLengthHeader, range_len));
}
void HttpResponseHeaders::Parse(const std::string& raw_input) {
raw_headers_.reserve(raw_input.size());
std::string::const_iterator line_begin = raw_input.begin();
std::string::const_iterator line_end =
std::find(line_begin, raw_input.end(), '\0');
bool has_headers = (line_end != raw_input.end() &&
(line_end + 1) != raw_input.end() &&
*(line_end + 1) != '\0');
ParseStatusLine(line_begin, line_end, has_headers);
raw_headers_.push_back('\0');
if (line_end == raw_input.end()) {
raw_headers_.push_back('\0');
DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 2]);
DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 1]);
return;
}
size_t status_line_len = raw_headers_.size();
raw_headers_.append(line_end + 1, raw_input.end());
while (raw_headers_.size() < 2 ||
raw_headers_[raw_headers_.size() - 2] != '\0' ||
raw_headers_[raw_headers_.size() - 1] != '\0') {
raw_headers_.push_back('\0');
}
line_end = raw_headers_.begin() + status_line_len - 1;
HttpUtil::HeadersIterator headers(line_end + 1, raw_headers_.end(),
std::string(1, '\0'));
while (headers.GetNext()) {
AddHeader(headers.name_begin(),
headers.name_end(),
headers.values_begin(),
headers.values_end());
}
DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 2]);
DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 1]);
}
void HttpResponseHeaders::GetNormalizedHeaders(std::string* output) const {
output->assign(raw_headers_.c_str());
typedef base::hash_map<std::string, size_t> HeadersMap;
HeadersMap headers_map;
HeadersMap::iterator iter = headers_map.end();
std::vector<std::string> headers;
for (size_t i = 0; i < parsed_.size(); ++i) {
DCHECK(!parsed_[i].is_continuation());
std::string name(parsed_[i].name_begin, parsed_[i].name_end);
std::string lower_name = StringToLowerASCII(name);
iter = headers_map.find(lower_name);
if (iter == headers_map.end()) {
iter = headers_map.insert(
HeadersMap::value_type(lower_name, headers.size())).first;
headers.push_back(name + ": ");
} else {
headers[iter->second].append(", ");
}
std::string::const_iterator value_begin = parsed_[i].value_begin;
std::string::const_iterator value_end = parsed_[i].value_end;
while (++i < parsed_.size() && parsed_[i].is_continuation())
value_end = parsed_[i].value_end;
--i;
headers[iter->second].append(value_begin, value_end);
}
for (size_t i = 0; i < headers.size(); ++i) {
output->push_back('\n');
output->append(headers[i]);
}
output->push_back('\n');
}
bool HttpResponseHeaders::GetNormalizedHeader(const std::string& name,
std::string* value) const {
DCHECK(!HttpUtil::IsNonCoalescingHeader(name));
value->clear();
bool found = false;
size_t i = 0;
while (i < parsed_.size()) {
i = FindHeader(i, name);
if (i == std::string::npos)
break;
found = true;
if (!value->empty())
value->append(", ");
std::string::const_iterator value_begin = parsed_[i].value_begin;
std::string::const_iterator value_end = parsed_[i].value_end;
while (++i < parsed_.size() && parsed_[i].is_continuation())
value_end = parsed_[i].value_end;
value->append(value_begin, value_end);
}
return found;
}
std::string HttpResponseHeaders::GetStatusLine() const {
return std::string(raw_headers_.c_str());
}
std::string HttpResponseHeaders::GetStatusText() const {
std::string status_text = GetStatusLine();
std::string::const_iterator begin = status_text.begin();
std::string::const_iterator end = status_text.end();
for (int i = 0; i < 2; ++i)
begin = std::find(begin, end, ' ') + 1;
return std::string(begin, end);
}
bool HttpResponseHeaders::EnumerateHeaderLines(void** iter,
std::string* name,
std::string* value) const {
size_t i = reinterpret_cast<size_t>(*iter);
if (i == parsed_.size())
return false;
DCHECK(!parsed_[i].is_continuation());
name->assign(parsed_[i].name_begin, parsed_[i].name_end);
std::string::const_iterator value_begin = parsed_[i].value_begin;
std::string::const_iterator value_end = parsed_[i].value_end;
while (++i < parsed_.size() && parsed_[i].is_continuation())
value_end = parsed_[i].value_end;
value->assign(value_begin, value_end);
*iter = reinterpret_cast<void*>(i);
return true;
}
bool HttpResponseHeaders::EnumerateHeader(void** iter,
const base::StringPiece& name,
std::string* value) const {
size_t i;
if (!iter || !*iter) {
i = FindHeader(0, name);
} else {
i = reinterpret_cast<size_t>(*iter);
if (i >= parsed_.size()) {
i = std::string::npos;
} else if (!parsed_[i].is_continuation()) {
i = FindHeader(i, name);
}
}
if (i == std::string::npos) {
value->clear();
return false;
}
if (iter)
*iter = reinterpret_cast<void*>(i + 1);
value->assign(parsed_[i].value_begin, parsed_[i].value_end);
return true;
}
bool HttpResponseHeaders::HasHeaderValue(const base::StringPiece& name,
const base::StringPiece& value) const {
void* iter = NULL;
std::string temp;
while (EnumerateHeader(&iter, name, &temp)) {
if (value.size() == temp.size() &&
std::equal(temp.begin(), temp.end(), value.begin(),
base::CaseInsensitiveCompare<char>()))
return true;
}
return false;
}
bool HttpResponseHeaders::HasHeader(const base::StringPiece& name) const {
return FindHeader(0, name) != std::string::npos;
}
HttpResponseHeaders::HttpResponseHeaders() : response_code_(-1) {
}
HttpResponseHeaders::~HttpResponseHeaders() {
}
HttpVersion HttpResponseHeaders::ParseVersion(
std::string::const_iterator line_begin,
std::string::const_iterator line_end) {
std::string::const_iterator p = line_begin;
if ((line_end - p < 4) || !LowerCaseEqualsASCII(p, p + 4, "http")) {
DVLOG(1) << "missing status line";
return HttpVersion();
}
p += 4;
if (p >= line_end || *p != '/') {
DVLOG(1) << "missing version";
return HttpVersion();
}
std::string::const_iterator dot = std::find(p, line_end, '.');
if (dot == line_end) {
DVLOG(1) << "malformed version";
return HttpVersion();
}
++p;
++dot;
if (!(*p >= '0' && *p <= '9' && *dot >= '0' && *dot <= '9')) {
DVLOG(1) << "malformed version number";
return HttpVersion();
}
uint16 major = *p - '0';
uint16 minor = *dot - '0';
return HttpVersion(major, minor);
}
void HttpResponseHeaders::ParseStatusLine(
std::string::const_iterator line_begin,
std::string::const_iterator line_end,
bool has_headers) {
parsed_http_version_ = ParseVersion(line_begin, line_end);
if (parsed_http_version_ == HttpVersion(0, 9) && !has_headers) {
http_version_ = HttpVersion(0, 9);
raw_headers_ = "HTTP/0.9";
} else if (parsed_http_version_ >= HttpVersion(1, 1)) {
http_version_ = HttpVersion(1, 1);
raw_headers_ = "HTTP/1.1";
} else {
http_version_ = HttpVersion(1, 0);
raw_headers_ = "HTTP/1.0";
}
if (parsed_http_version_ != http_version_) {
DVLOG(1) << "assuming HTTP/" << http_version_.major_value() << "."
<< http_version_.minor_value();
}
std::string::const_iterator p = std::find(line_begin, line_end, ' ');
if (p == line_end) {
DVLOG(1) << "missing response status; assuming 200 OK";
raw_headers_.append(" 200 OK");
response_code_ = 200;
return;
}
while (*p == ' ')
++p;
std::string::const_iterator code = p;
while (*p >= '0' && *p <= '9')
++p;
if (p == code) {
DVLOG(1) << "missing response status number; assuming 200";
raw_headers_.append(" 200 OK");
response_code_ = 200;
return;
}
raw_headers_.push_back(' ');
raw_headers_.append(code, p);
raw_headers_.push_back(' ');
base::StringToInt(StringPiece(code, p), &response_code_);
while (*p == ' ')
++p;
while (line_end > p && line_end[-1] == ' ')
--line_end;
if (p == line_end) {
DVLOG(1) << "missing response status text; assuming OK";
raw_headers_.append("OK");
} else {
raw_headers_.append(p, line_end);
}
}
size_t HttpResponseHeaders::FindHeader(size_t from,
const base::StringPiece& search) const {
for (size_t i = from; i < parsed_.size(); ++i) {
if (parsed_[i].is_continuation())
continue;
const std::string::const_iterator& name_begin = parsed_[i].name_begin;
const std::string::const_iterator& name_end = parsed_[i].name_end;
if (static_cast<size_t>(name_end - name_begin) == search.size() &&
std::equal(name_begin, name_end, search.begin(),
base::CaseInsensitiveCompare<char>()))
return i;
}
return std::string::npos;
}
void HttpResponseHeaders::AddHeader(std::string::const_iterator name_begin,
std::string::const_iterator name_end,
std::string::const_iterator values_begin,
std::string::const_iterator values_end) {
if (values_begin == values_end ||
HttpUtil::IsNonCoalescingHeader(name_begin, name_end)) {
AddToParsed(name_begin, name_end, values_begin, values_end);
} else {
HttpUtil::ValuesIterator it(values_begin, values_end, ',');
while (it.GetNext()) {
AddToParsed(name_begin, name_end, it.value_begin(), it.value_end());
name_begin = name_end = raw_headers_.end();
}
}
}
void HttpResponseHeaders::AddToParsed(std::string::const_iterator name_begin,
std::string::const_iterator name_end,
std::string::const_iterator value_begin,
std::string::const_iterator value_end) {
ParsedHeader header;
header.name_begin = name_begin;
header.name_end = name_end;
header.value_begin = value_begin;
header.value_end = value_end;
parsed_.push_back(header);
}
void HttpResponseHeaders::AddNonCacheableHeaders(HeaderSet* result) const {
const char kCacheControl[] = "cache-control";
const char kPrefix[] = "no-cache=\"";
const size_t kPrefixLen = sizeof(kPrefix) - 1;
std::string value;
void* iter = NULL;
while (EnumerateHeader(&iter, kCacheControl, &value)) {
if (value.size() <= kPrefixLen ||
value.compare(0, kPrefixLen, kPrefix) != 0) {
continue;
}
if (value[value.size()-1] != '\"')
continue;
std::string::const_iterator item = value.begin() + kPrefixLen;
std::string::const_iterator end = value.end() - 1;
while (item != end) {
std::string::const_iterator item_next = std::find(item, end, ',');
std::string::const_iterator item_end = end;
if (item_next != end) {
item_end = item_next;
item_next++;
}
HttpUtil::TrimLWS(&item, &item_end);
if (item_end > item) {
std::string name(&*item, item_end - item);
StringToLowerASCII(&name);
result->insert(name);
}
item = item_next;
}
}
}
void HttpResponseHeaders::AddHopByHopHeaders(HeaderSet* result) {
for (size_t i = 0; i < arraysize(kHopByHopResponseHeaders); ++i)
result->insert(std::string(kHopByHopResponseHeaders[i]));
}
void HttpResponseHeaders::AddCookieHeaders(HeaderSet* result) {
for (size_t i = 0; i < arraysize(kCookieResponseHeaders); ++i)
result->insert(std::string(kCookieResponseHeaders[i]));
}
void HttpResponseHeaders::AddChallengeHeaders(HeaderSet* result) {
for (size_t i = 0; i < arraysize(kChallengeResponseHeaders); ++i)
result->insert(std::string(kChallengeResponseHeaders[i]));
}
void HttpResponseHeaders::AddHopContentRangeHeaders(HeaderSet* result) {
result->insert(kContentRange);
}
void HttpResponseHeaders::AddSecurityStateHeaders(HeaderSet* result) {
for (size_t i = 0; i < arraysize(kSecurityStateHeaders); ++i)
result->insert(std::string(kSecurityStateHeaders[i]));
}
void HttpResponseHeaders::GetMimeTypeAndCharset(std::string* mime_type,
std::string* charset) const {
mime_type->clear();
charset->clear();
std::string name = "content-type";
std::string value;
bool had_charset = false;
void* iter = NULL;
while (EnumerateHeader(&iter, name, &value))
HttpUtil::ParseContentType(value, mime_type, charset, &had_charset, NULL);
}
bool HttpResponseHeaders::GetMimeType(std::string* mime_type) const {
std::string unused;
GetMimeTypeAndCharset(mime_type, &unused);
return !mime_type->empty();
}
bool HttpResponseHeaders::GetCharset(std::string* charset) const {
std::string unused;
GetMimeTypeAndCharset(&unused, charset);
return !charset->empty();
}
bool HttpResponseHeaders::IsRedirect(std::string* location) const {
if (!IsRedirectResponseCode(response_code_))
return false;
size_t i = std::string::npos;
do {
i = FindHeader(++i, "location");
if (i == std::string::npos)
return false;
} while (parsed_[i].value_begin == parsed_[i].value_end);
if (location) {
*location = EscapeNonASCII(
std::string(parsed_[i].value_begin, parsed_[i].value_end));
}
return true;
}
bool HttpResponseHeaders::IsRedirectResponseCode(int response_code) {
return (response_code == 301 ||
response_code == 302 ||
response_code == 303 ||
response_code == 307);
}
bool HttpResponseHeaders::RequiresValidation(const Time& request_time,
const Time& response_time,
const Time& current_time) const {
TimeDelta lifetime =
GetFreshnessLifetime(response_time);
if (lifetime == TimeDelta())
return true;
return lifetime <= GetCurrentAge(request_time, response_time, current_time);
}
TimeDelta HttpResponseHeaders::GetFreshnessLifetime(
const Time& response_time) const {
if (HasHeaderValue("cache-control", "no-cache") ||
HasHeaderValue("cache-control", "no-store") ||
HasHeaderValue("pragma", "no-cache") ||
HasHeaderValue("vary", "*"))
return TimeDelta();
TimeDelta max_age_value;
if (GetMaxAgeValue(&max_age_value))
return max_age_value;
Time date_value;
if (!GetDateValue(&date_value))
date_value = response_time;
Time expires_value;
if (GetExpiresValue(&expires_value)) {
if (expires_value > date_value)
return expires_value - date_value;
return TimeDelta();
}
if ((response_code_ == 200 || response_code_ == 203 ||
response_code_ == 206) &&
!HasHeaderValue("cache-control", "must-revalidate")) {
Time last_modified_value;
if (GetLastModifiedValue(&last_modified_value)) {
if (last_modified_value <= date_value)
return (date_value - last_modified_value) / 10;
}
}
if (response_code_ == 300 || response_code_ == 301 || response_code_ == 410)
return TimeDelta::Max();
return TimeDelta();
}
TimeDelta HttpResponseHeaders::GetCurrentAge(const Time& request_time,
const Time& response_time,
const Time& current_time) const {
Time date_value;
if (!GetDateValue(&date_value))
date_value = response_time;
TimeDelta age_value;
GetAgeValue(&age_value);
TimeDelta apparent_age = std::max(TimeDelta(), response_time - date_value);
TimeDelta corrected_received_age = std::max(apparent_age, age_value);
TimeDelta response_delay = response_time - request_time;
TimeDelta corrected_initial_age = corrected_received_age + response_delay;
TimeDelta resident_time = current_time - response_time;
TimeDelta current_age = corrected_initial_age + resident_time;
return current_age;
}
bool HttpResponseHeaders::GetMaxAgeValue(TimeDelta* result) const {
std::string name = "cache-control";
std::string value;
const char kMaxAgePrefix[] = "max-age=";
const size_t kMaxAgePrefixLen = arraysize(kMaxAgePrefix) - 1;
void* iter = NULL;
while (EnumerateHeader(&iter, name, &value)) {
if (value.size() > kMaxAgePrefixLen) {
if (LowerCaseEqualsASCII(value.begin(),
value.begin() + kMaxAgePrefixLen,
kMaxAgePrefix)) {
int64 seconds;
base::StringToInt64(StringPiece(value.begin() + kMaxAgePrefixLen,
value.end()),
&seconds);
*result = TimeDelta::FromSeconds(seconds);
return true;
}
}
}
return false;
}
bool HttpResponseHeaders::GetAgeValue(TimeDelta* result) const {
std::string value;
if (!EnumerateHeader(NULL, "Age", &value))
return false;
int64 seconds;
base::StringToInt64(value, &seconds);
*result = TimeDelta::FromSeconds(seconds);
return true;
}
bool HttpResponseHeaders::GetDateValue(Time* result) const {
return GetTimeValuedHeader("Date", result);
}
bool HttpResponseHeaders::GetLastModifiedValue(Time* result) const {
return GetTimeValuedHeader("Last-Modified", result);
}
bool HttpResponseHeaders::GetExpiresValue(Time* result) const {
return GetTimeValuedHeader("Expires", result);
}
bool HttpResponseHeaders::GetTimeValuedHeader(const std::string& name,
Time* result) const {
std::string value;
if (!EnumerateHeader(NULL, name, &value))
return false;
return Time::FromUTCString(value.c_str(), result);
}
bool HttpResponseHeaders::IsKeepAlive() const {
if (http_version_ < HttpVersion(1, 0))
return false;
std::string connection_val;
if (!EnumerateHeader(NULL, "connection", &connection_val))
EnumerateHeader(NULL, "proxy-connection", &connection_val);
bool keep_alive;
if (http_version_ == HttpVersion(1, 0)) {
keep_alive = LowerCaseEqualsASCII(connection_val, "keep-alive");
} else {
keep_alive = !LowerCaseEqualsASCII(connection_val, "close");
}
return keep_alive;
}
bool HttpResponseHeaders::HasStrongValidators() const {
std::string etag_header;
EnumerateHeader(NULL, "etag", &etag_header);
std::string last_modified_header;
EnumerateHeader(NULL, "Last-Modified", &last_modified_header);
std::string date_header;
EnumerateHeader(NULL, "Date", &date_header);
return HttpUtil::HasStrongValidators(GetHttpVersion(),
etag_header,
last_modified_header,
date_header);
}
int64 HttpResponseHeaders::GetContentLength() const {
return GetInt64HeaderValue("content-length");
}
int64 HttpResponseHeaders::GetInt64HeaderValue(
const std::string& header) const {
void* iter = NULL;
std::string content_length_val;
if (!EnumerateHeader(&iter, header, &content_length_val))
return -1;
if (content_length_val.empty())
return -1;
if (content_length_val[0] == '+')
return -1;
int64 result;
bool ok = base::StringToInt64(content_length_val, &result);
if (!ok || result < 0)
return -1;
return result;
}
bool HttpResponseHeaders::GetContentRange(int64* first_byte_position,
int64* last_byte_position,
int64* instance_length) const {
void* iter = NULL;
std::string content_range_spec;
*first_byte_position = *last_byte_position = *instance_length = -1;
if (!EnumerateHeader(&iter, kContentRange, &content_range_spec))
return false;
if (content_range_spec.empty())
return false;
size_t space_position = content_range_spec.find(' ');
if (space_position == std::string::npos)
return false;
std::string::const_iterator content_range_spec_begin =
content_range_spec.begin();
std::string::const_iterator content_range_spec_end =
content_range_spec.begin() + space_position;
HttpUtil::TrimLWS(&content_range_spec_begin, &content_range_spec_end);
if (!LowerCaseEqualsASCII(content_range_spec_begin,
content_range_spec_end,
"bytes")) {
return false;
}
size_t slash_position = content_range_spec.find('/', space_position + 1);
if (slash_position == std::string::npos)
return false;
std::string::const_iterator byte_range_resp_spec_begin =
content_range_spec.begin() + space_position + 1;
std::string::const_iterator byte_range_resp_spec_end =
content_range_spec.begin() + slash_position;
HttpUtil::TrimLWS(&byte_range_resp_spec_begin, &byte_range_resp_spec_end);
std::string byte_range_resp_spec(byte_range_resp_spec_begin,
byte_range_resp_spec_end);
if (!LowerCaseEqualsASCII(byte_range_resp_spec, "*")) {
size_t minus_position = byte_range_resp_spec.find('-');
if (minus_position != std::string::npos) {
std::string::const_iterator first_byte_pos_begin =
byte_range_resp_spec.begin();
std::string::const_iterator first_byte_pos_end =
byte_range_resp_spec.begin() + minus_position;
HttpUtil::TrimLWS(&first_byte_pos_begin, &first_byte_pos_end);
bool ok = base::StringToInt64(StringPiece(first_byte_pos_begin,
first_byte_pos_end),
first_byte_position);
std::string::const_iterator last_byte_pos_begin =
byte_range_resp_spec.begin() + minus_position + 1;
std::string::const_iterator last_byte_pos_end =
byte_range_resp_spec.end();
HttpUtil::TrimLWS(&last_byte_pos_begin, &last_byte_pos_end);
ok &= base::StringToInt64(StringPiece(last_byte_pos_begin,
last_byte_pos_end),
last_byte_position);
if (!ok) {
*first_byte_position = *last_byte_position = -1;
return false;
}
if (*first_byte_position < 0 || *last_byte_position < 0 ||
*first_byte_position > *last_byte_position)
return false;
} else {
return false;
}
}
std::string::const_iterator instance_length_begin =
content_range_spec.begin() + slash_position + 1;
std::string::const_iterator instance_length_end =
content_range_spec.end();
HttpUtil::TrimLWS(&instance_length_begin, &instance_length_end);
if (LowerCaseEqualsASCII(instance_length_begin, instance_length_end, "*")) {
return false;
} else if (!base::StringToInt64(StringPiece(instance_length_begin,
instance_length_end),
instance_length)) {
*instance_length = -1;
return false;
}
if (*first_byte_position < 0 || *last_byte_position < 0 ||
*instance_length < 0 || *instance_length - 1 < *last_byte_position)
return false;
return true;
}
base::Value* HttpResponseHeaders::NetLogCallback(
NetLog::LogLevel log_level) const {
base::DictionaryValue* dict = new base::DictionaryValue();
base::ListValue* headers = new base::ListValue();
headers->Append(new base::StringValue(GetStatusLine()));
void* iterator = NULL;
std::string name;
std::string value;
while (EnumerateHeaderLines(&iterator, &name, &value)) {
std::string log_value = ElideHeaderValueForNetLog(log_level, name, value);
headers->Append(
new base::StringValue(
base::StringPrintf("%s: %s", name.c_str(), log_value.c_str())));
}
dict->Set("headers", headers);
return dict;
}
bool HttpResponseHeaders::FromNetLogParam(
const base::Value* event_param,
scoped_refptr<HttpResponseHeaders>* http_response_headers) {
*http_response_headers = NULL;
const base::DictionaryValue* dict = NULL;
const base::ListValue* header_list = NULL;
if (!event_param ||
!event_param->GetAsDictionary(&dict) ||
!dict->GetList("headers", &header_list)) {
return false;
}
std::string raw_headers;
for (base::ListValue::const_iterator it = header_list->begin();
it != header_list->end();
++it) {
std::string header_line;
if (!(*it)->GetAsString(&header_line))
return false;
raw_headers.append(header_line);
raw_headers.push_back('\0');
}
raw_headers.push_back('\0');
*http_response_headers = new HttpResponseHeaders(raw_headers);
return true;
}
bool HttpResponseHeaders::IsChunkEncoded() const {
return GetHttpVersion() >= HttpVersion(1, 1) &&
HasHeaderValue("Transfer-Encoding", "chunked");
}
#if defined(SPDY_PROXY_AUTH_ORIGIN)
bool HttpResponseHeaders::GetChromeProxyBypassDuration(
const std::string& action_prefix,
base::TimeDelta* duration) const {
void* iter = NULL;
std::string value;
std::string name = "chrome-proxy";
while (EnumerateHeader(&iter, name, &value)) {
if (value.size() > action_prefix.size()) {
if (LowerCaseEqualsASCII(value.begin(),
value.begin() + action_prefix.size(),
action_prefix.c_str())) {
int64 seconds;
if (!base::StringToInt64(
StringPiece(value.begin() + action_prefix.size(), value.end()),
&seconds) || seconds < 0) {
continue;
}
*duration = TimeDelta::FromSeconds(seconds);
return true;
}
}
}
return false;
}
bool HttpResponseHeaders::GetChromeProxyInfo(
ChromeProxyInfo* proxy_info) const {
DCHECK(proxy_info);
proxy_info->bypass_all = false;
proxy_info->bypass_duration = base::TimeDelta();
if (GetChromeProxyBypassDuration("block=", &proxy_info->bypass_duration)) {
proxy_info->bypass_all = true;
return true;
}
if (GetChromeProxyBypassDuration("bypass=", &proxy_info->bypass_duration))
return true;
return false;
}
bool HttpResponseHeaders::IsChromeProxyResponse() const {
const size_t kVersionSize = 4;
const char kChromeProxyViaValue[] = "Chrome-Compression-Proxy";
size_t value_len = strlen(kChromeProxyViaValue);
void* iter = NULL;
std::string value;
while (EnumerateHeader(&iter, "via", &value)) {
if (value.size() >= kVersionSize + value_len &&
!value.compare(kVersionSize, value_len, kChromeProxyViaValue))
return true;
}
const char kDeprecatedChromeProxyViaValue[] = "1.1 Chrome Compression Proxy";
iter = NULL;
while (EnumerateHeader(&iter, "via", &value))
if (value == kDeprecatedChromeProxyViaValue)
return true;
return false;
}
ProxyService::DataReductionProxyBypassEventType
HttpResponseHeaders::GetChromeProxyBypassEventType(
ChromeProxyInfo* chrome_proxy_info) const {
DCHECK(chrome_proxy_info);
if (GetChromeProxyInfo(chrome_proxy_info)) {
if (chrome_proxy_info->bypass_duration < TimeDelta::FromMinutes(30))
return ProxyService::SHORT_BYPASS;
return ProxyService::LONG_BYPASS;
}
if (response_code() == HTTP_INTERNAL_SERVER_ERROR ||
response_code() == HTTP_BAD_GATEWAY ||
response_code() == HTTP_SERVICE_UNAVAILABLE) {
return ProxyService::INTERNAL_SERVER_ERROR_BYPASS;
}
if (!IsChromeProxyResponse() && (response_code() != HTTP_NOT_MODIFIED)) {
return ProxyService::MISSING_VIA_HEADER;
}
return ProxyService::BYPASS_EVENT_TYPE_MAX;
}
#endif
}