#include "net/http/http_response_headers.h"
#include <algorithm>
#include <limits>
#include <memory>
#include <unordered_map>
#include <utility>
#include "base/format_macros.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/pickle.h"
#include "base/ranges/algorithm.h"
#include "base/strings/escape.h"
#include "base/strings/strcat.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/parse_number.h"
#include "net/base/tracing.h"
#include "net/http/http_byte_range.h"
#include "net/http/http_log_util.h"
#include "net/http/http_status_code.h"
#include "net/http/http_util.h"
#include "net/log/net_log_capture_mode.h"
#include "net/log/net_log_values.h"
using base::Time;
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",
"clear-site-data",
};
const char* const kSecurityStateHeaders[] = {
"strict-transport-security",
};
const char* const kNonUpdatedHeaders[] = {
"connection",
"proxy-connection",
"keep-alive",
"www-authenticate",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"content-location",
"content-md5",
"etag",
"content-encoding",
"content-range",
"content-type",
"content-length",
"x-frame-options",
"x-xss-protection",
};
const char* const kNonUpdatedHeaderPrefixes[] = {
"x-content-",
"x-webkit-"
};
bool ShouldUpdateHeader(base::StringPiece name) {
for (const auto* header : kNonUpdatedHeaders) {
if (base::EqualsCaseInsensitiveASCII(name, header))
return false;
}
for (const auto* prefix : kNonUpdatedHeaderPrefixes) {
if (base::StartsWith(name, prefix, base::CompareCase::INSENSITIVE_ASCII))
return false;
}
return true;
}
bool HasEmbeddedNulls(base::StringPiece str) {
for (char c : str) {
if (c == '\0')
return true;
}
return false;
}
void CheckDoesNotHaveEmbeddedNulls(base::StringPiece str) {
CHECK(!HasEmbeddedNulls(str));
}
}
const char HttpResponseHeaders::kContentRange[] = "Content-Range";
const char HttpResponseHeaders::kLastModified[] = "Last-Modified";
const char HttpResponseHeaders::kVary[] = "Vary";
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;
void WriteIntoTrace(perfetto::TracedValue context) const {
auto dict = std::move(context).WriteDictionary();
dict.Add("name", base::MakeStringPiece(name_begin, name_end));
dict.Add("value", base::MakeStringPiece(value_begin, 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(base::PickleIterator* iter)
: response_code_(-1) {
std::string raw_input;
if (iter->ReadString(&raw_input))
Parse(raw_input);
}
scoped_refptr<HttpResponseHeaders> HttpResponseHeaders::TryToCreate(
base::StringPiece headers) {
if (HasEmbeddedNulls(headers) ||
headers.size() > std::numeric_limits<int>::max()) {
return nullptr;
}
return base::MakeRefCounted<HttpResponseHeaders>(
HttpUtil::AssembleRawHeaders(headers));
}
void HttpResponseHeaders::Persist(base::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 = base::ToLowerASCII(
base::MakeStringPiece(parsed_[i].name_begin, parsed_[i].name_end));
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() == net::HTTP_NOT_MODIFIED ||
new_headers.response_code() == net::HTTP_PARTIAL_CONTENT);
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;
auto name =
base::MakeStringPiece(new_parsed[i].name_begin, new_parsed[i].name_end);
if (ShouldUpdateHeader(name)) {
std::string name_lower = base::ToLowerASCII(name);
updated_headers.insert(name_lower);
new_raw_headers.append(new_parsed[i].name_begin, new_parsed[k].value_end);
new_raw_headers.push_back('\0');
}
i = k;
}
MergeWithHeaders(std::move(new_raw_headers), updated_headers);
}
void HttpResponseHeaders::MergeWithHeaders(std::string raw_headers,
const HeaderSet& headers_to_remove) {
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 = base::ToLowerASCII(
base::MakeStringPiece(parsed_[i].name_begin, parsed_[i].name_end));
if (headers_to_remove.find(name) == headers_to_remove.end()) {
raw_headers.append(parsed_[i].name_begin, parsed_[k].value_end);
raw_headers.push_back('\0');
}
i = k;
}
raw_headers.push_back('\0');
raw_headers_.clear();
parsed_.clear();
Parse(raw_headers);
}
void HttpResponseHeaders::RemoveHeader(base::StringPiece name) {
std::string new_raw_headers(raw_headers_.c_str());
new_raw_headers.push_back('\0');
HeaderSet to_remove;
to_remove.insert(base::ToLowerASCII(name));
MergeWithHeaders(std::move(new_raw_headers), to_remove);
}
void HttpResponseHeaders::RemoveHeaders(
const std::unordered_set<std::string>& header_names) {
std::string new_raw_headers(raw_headers_.c_str());
new_raw_headers.push_back('\0');
HeaderSet to_remove;
for (const auto& header_name : header_names) {
to_remove.insert(base::ToLowerASCII(header_name));
}
MergeWithHeaders(std::move(new_raw_headers), to_remove);
}
void HttpResponseHeaders::RemoveHeaderLine(const std::string& name,
const std::string& value) {
std::string name_lowercase = base::ToLowerASCII(name);
std::string new_raw_headers(GetStatusLine());
new_raw_headers.push_back('\0');
new_raw_headers.reserve(raw_headers_.size());
size_t iter = 0;
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 = base::ToLowerASCII(old_header_name);
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(base::StringPiece name,
base::StringPiece value) {
DCHECK(HttpUtil::IsValidHeaderName(name));
DCHECK(HttpUtil::IsValidHeaderValue(value));
std::string new_raw_headers(raw_headers_, 0, raw_headers_.size() - 1);
new_raw_headers.append(name.begin(), name.end());
new_raw_headers.append(": ");
new_raw_headers.append(value.begin(), value.end());
new_raw_headers.push_back('\0');
new_raw_headers.push_back('\0');
raw_headers_.clear();
parsed_.clear();
Parse(new_raw_headers);
}
void HttpResponseHeaders::SetHeader(base::StringPiece name,
base::StringPiece value) {
RemoveHeader(name);
AddHeader(name, value);
}
void HttpResponseHeaders::AddCookie(const std::string& cookie_string) {
AddHeader("Set-Cookie", cookie_string);
}
void HttpResponseHeaders::ReplaceStatusLine(const std::string& new_status) {
CheckDoesNotHaveEmbeddedNulls(new_status);
std::string new_raw_headers(new_status);
new_raw_headers.push_back('\0');
HeaderSet empty_to_remove;
MergeWithHeaders(std::move(new_raw_headers), empty_to_remove);
}
void HttpResponseHeaders::UpdateWithNewRange(const HttpByteRange& byte_range,
int64_t 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_t start = byte_range.first_byte_position();
int64_t end = byte_range.last_byte_position();
int64_t range_len = end - start + 1;
if (replace_status_line)
ReplaceStatusLine("HTTP/1.1 206 Partial Content");
AddHeader(kRangeHeader,
base::StringPrintf("bytes %" PRId64 "-%" PRId64 "/%" PRId64, start,
end, resource_size));
AddHeader(kLengthHeader, base::StringPrintf("%" PRId64, 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 = base::ranges::find(raw_input, '\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]);
}
bool HttpResponseHeaders::GetNormalizedHeader(base::StringPiece 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;
if (found)
value->append(", ");
found = true;
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 = base::ranges::find(status_text, ' ');
std::string::const_iterator end = status_text.end();
CHECK(begin != end);
++begin;
CHECK(begin != end);
begin = std::find(begin, end, ' ');
if (begin == end)
return std::string();
++begin;
CHECK(begin != end);
return std::string(begin, end);
}
bool HttpResponseHeaders::EnumerateHeaderLines(size_t* iter,
std::string* name,
std::string* value) const {
size_t i = *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 = i;
return true;
}
bool HttpResponseHeaders::EnumerateHeader(size_t* iter,
base::StringPiece name,
std::string* value) const {
size_t i;
if (!iter || !*iter) {
i = FindHeader(0, name);
} else {
i = *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 = i + 1;
value->assign(parsed_[i].value_begin, parsed_[i].value_end);
return true;
}
bool HttpResponseHeaders::HasHeaderValue(base::StringPiece name,
base::StringPiece value) const {
size_t iter = 0;
std::string temp;
while (EnumerateHeader(&iter, name, &temp)) {
if (base::EqualsCaseInsensitiveASCII(value, temp))
return true;
}
return false;
}
bool HttpResponseHeaders::HasHeader(base::StringPiece name) const {
return FindHeader(0, name) != std::string::npos;
}
HttpResponseHeaders::~HttpResponseHeaders() = default;
HttpVersion HttpResponseHeaders::ParseVersion(
std::string::const_iterator line_begin,
std::string::const_iterator line_end) {
std::string::const_iterator p = line_begin;
if (!base::StartsWith(base::MakeStringPiece(line_begin, line_end), "http",
base::CompareCase::INSENSITIVE_ASCII)) {
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 (!(base::IsAsciiDigit(*p) && base::IsAsciiDigit(*dot))) {
DVLOG(1) << "malformed version number";
return HttpVersion();
}
uint16_t major = *p - '0';
uint16_t 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) {
HttpVersion 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(2, 0)) {
http_version_ = HttpVersion(2, 0);
raw_headers_ = "HTTP/2.0";
} 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_ = net::HTTP_OK;
return;
}
while (p < line_end && *p == ' ')
++p;
std::string::const_iterator code = p;
while (p < line_end && base::IsAsciiDigit(*p))
++p;
if (p == code) {
DVLOG(1) << "missing response status number; assuming 200";
raw_headers_.append(" 200");
response_code_ = net::HTTP_OK;
return;
}
raw_headers_.push_back(' ');
raw_headers_.append(code, p);
base::StringToInt(base::MakeStringPiece(code, p), &response_code_);
while (p < line_end && *p == ' ')
++p;
while (line_end > p && line_end[-1] == ' ')
--line_end;
if (p == line_end)
return;
raw_headers_.push_back(' ');
raw_headers_.append(p, line_end);
}
size_t HttpResponseHeaders::FindHeader(size_t from,
base::StringPiece search) const {
for (size_t i = from; i < parsed_.size(); ++i) {
if (parsed_[i].is_continuation())
continue;
auto name =
base::MakeStringPiece(parsed_[i].name_begin, parsed_[i].name_end);
if (base::EqualsCaseInsensitiveASCII(search, name))
return i;
}
return std::string::npos;
}
bool HttpResponseHeaders::GetCacheControlDirective(
base::StringPiece directive,
base::TimeDelta* result) const {
static constexpr base::StringPiece name("cache-control");
std::string value;
size_t directive_size = directive.size();
size_t iter = 0;
while (EnumerateHeader(&iter, name, &value)) {
if (!base::StartsWith(value, directive,
base::CompareCase::INSENSITIVE_ASCII)) {
continue;
}
if (value.size() == directive_size || value[directive_size] != '=')
continue;
auto start = value.cbegin() + directive_size + 1;
auto end = value.cend();
while (start < end && *start == ' ') {
++start;
}
while (start < end - 1 && *(end - 1) == ' ') {
--end;
}
if (start == end ||
!std::all_of(start, end, [](char c) { return '0' <= c && c <= '9'; })) {
continue;
}
int64_t seconds = 0;
base::StringToInt64(base::MakeStringPiece(start, end), &seconds);
seconds = std::min(seconds, base::TimeDelta::FiniteMax().InSeconds());
*result = base::Seconds(seconds);
return true;
}
return false;
}
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(
base::MakeStringPiece(name_begin, name_end))) {
AddToParsed(name_begin, name_end, values_begin, values_end);
} else {
HttpUtil::ValuesIterator it(values_begin, values_end, ',',
false );
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;
size_t iter = 0;
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) {
result->insert(
base::ToLowerASCII(base::StringPiece(&*item, item_end - item)));
}
item = item_next;
}
}
}
void HttpResponseHeaders::AddHopByHopHeaders(HeaderSet* result) {
for (const auto* header : kHopByHopResponseHeaders)
result->insert(std::string(header));
}
void HttpResponseHeaders::AddCookieHeaders(HeaderSet* result) {
for (const auto* header : kCookieResponseHeaders)
result->insert(std::string(header));
}
void HttpResponseHeaders::AddChallengeHeaders(HeaderSet* result) {
for (const auto* header : kChallengeResponseHeaders)
result->insert(std::string(header));
}
void HttpResponseHeaders::AddHopContentRangeHeaders(HeaderSet* result) {
result->insert(kContentRange);
}
void HttpResponseHeaders::AddSecurityStateHeaders(HeaderSet* result) {
for (const auto* header : kSecurityStateHeaders)
result->insert(std::string(header));
}
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;
size_t iter = 0;
while (EnumerateHeader(&iter, name, &value))
HttpUtil::ParseContentType(value, mime_type, charset, &had_charset,
nullptr);
}
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) {
auto location_strpiece =
base::MakeStringPiece(parsed_[i].value_begin, parsed_[i].value_end);
*location = base::EscapeNonASCII(location_strpiece);
}
return true;
}
bool HttpResponseHeaders::IsRedirectResponseCode(int response_code) {
return (response_code == net::HTTP_MOVED_PERMANENTLY ||
response_code == net::HTTP_FOUND ||
response_code == net::HTTP_SEE_OTHER ||
response_code == net::HTTP_TEMPORARY_REDIRECT ||
response_code == net::HTTP_PERMANENT_REDIRECT);
}
ValidationType HttpResponseHeaders::RequiresValidation(
const Time& request_time,
const Time& response_time,
const Time& current_time) const {
FreshnessLifetimes lifetimes = GetFreshnessLifetimes(response_time);
if (lifetimes.freshness.is_zero() && lifetimes.staleness.is_zero())
return VALIDATION_SYNCHRONOUS;
base::TimeDelta age =
GetCurrentAge(request_time, response_time, current_time);
if (lifetimes.freshness > age)
return VALIDATION_NONE;
if (lifetimes.freshness + lifetimes.staleness > age)
return VALIDATION_ASYNCHRONOUS;
return VALIDATION_SYNCHRONOUS;
}
HttpResponseHeaders::FreshnessLifetimes
HttpResponseHeaders::GetFreshnessLifetimes(const Time& response_time) const {
FreshnessLifetimes lifetimes;
if (HasHeaderValue("cache-control", "no-cache") ||
HasHeaderValue("cache-control", "no-store") ||
HasHeaderValue("pragma", "no-cache")) {
return lifetimes;
}
bool must_revalidate = HasHeaderValue("cache-control", "must-revalidate");
if (must_revalidate || !GetStaleWhileRevalidateValue(&lifetimes.staleness)) {
DCHECK_EQ(base::TimeDelta(), lifetimes.staleness);
}
if (GetMaxAgeValue(&lifetimes.freshness))
return lifetimes;
Time date_value;
if (!GetDateValue(&date_value))
date_value = response_time;
Time expires_value;
if (GetExpiresValue(&expires_value)) {
if (expires_value > date_value) {
lifetimes.freshness = expires_value - date_value;
return lifetimes;
}
DCHECK_EQ(base::TimeDelta(), lifetimes.freshness);
return lifetimes;
}
if ((response_code_ == net::HTTP_OK ||
response_code_ == net::HTTP_NON_AUTHORITATIVE_INFORMATION ||
response_code_ == net::HTTP_PARTIAL_CONTENT) &&
!must_revalidate) {
Time last_modified_value;
if (GetLastModifiedValue(&last_modified_value)) {
if (last_modified_value <= date_value) {
lifetimes.freshness = (date_value - last_modified_value) / 10;
return lifetimes;
}
}
}
if (response_code_ == net::HTTP_MULTIPLE_CHOICES ||
response_code_ == net::HTTP_MOVED_PERMANENTLY ||
response_code_ == net::HTTP_PERMANENT_REDIRECT ||
response_code_ == net::HTTP_GONE) {
lifetimes.freshness = base::TimeDelta::Max();
lifetimes.staleness = base::TimeDelta();
return lifetimes;
}
DCHECK_EQ(base::TimeDelta(), lifetimes.freshness);
return lifetimes;
}
base::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;
base::TimeDelta age_value;
GetAgeValue(&age_value);
base::TimeDelta apparent_age =
std::max(base::TimeDelta(), response_time - date_value);
base::TimeDelta response_delay = response_time - request_time;
base::TimeDelta corrected_age_value = age_value + response_delay;
base::TimeDelta corrected_initial_age =
std::max(apparent_age, corrected_age_value);
base::TimeDelta resident_time = current_time - response_time;
base::TimeDelta current_age = corrected_initial_age + resident_time;
return current_age;
}
bool HttpResponseHeaders::GetMaxAgeValue(base::TimeDelta* result) const {
return GetCacheControlDirective("max-age", result);
}
bool HttpResponseHeaders::GetAgeValue(base::TimeDelta* result) const {
std::string value;
if (!EnumerateHeader(nullptr, "Age", &value))
return false;
uint32_t seconds;
ParseIntError error;
if (!ParseUint32(value, ParseIntFormat::NON_NEGATIVE, &seconds, &error)) {
if (error == ParseIntError::FAILED_OVERFLOW) {
seconds = std::numeric_limits<decltype(seconds)>::max();
} else {
return false;
}
}
*result = base::Seconds(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::GetStaleWhileRevalidateValue(
base::TimeDelta* result) const {
return GetCacheControlDirective("stale-while-revalidate", result);
}
bool HttpResponseHeaders::GetTimeValuedHeader(const std::string& name,
Time* result) const {
std::string value;
if (!EnumerateHeader(nullptr, name, &value))
return false;
return Time::FromUTCString(value.c_str(), result);
}
bool HttpResponseHeaders::IsKeepAlive() const {
static const char* const kConnectionHeaders[] = {"connection",
"proxy-connection"};
struct KeepAliveToken {
const char* const token;
bool keep_alive;
};
static const KeepAliveToken kKeepAliveTokens[] = {{"keep-alive", true},
{"close", false}};
if (http_version_ < HttpVersion(1, 0))
return false;
for (const char* header : kConnectionHeaders) {
size_t iterator = 0;
std::string token;
while (EnumerateHeader(&iterator, header, &token)) {
for (const KeepAliveToken& keep_alive_token : kKeepAliveTokens) {
if (base::EqualsCaseInsensitiveASCII(token, keep_alive_token.token))
return keep_alive_token.keep_alive;
}
}
}
return http_version_ != HttpVersion(1, 0);
}
bool HttpResponseHeaders::HasStrongValidators() const {
std::string etag_header;
EnumerateHeader(nullptr, "etag", &etag_header);
std::string last_modified_header;
EnumerateHeader(nullptr, "Last-Modified", &last_modified_header);
std::string date_header;
EnumerateHeader(nullptr, "Date", &date_header);
return HttpUtil::HasStrongValidators(GetHttpVersion(), etag_header,
last_modified_header, date_header);
}
bool HttpResponseHeaders::HasValidators() const {
std::string etag_header;
EnumerateHeader(nullptr, "etag", &etag_header);
std::string last_modified_header;
EnumerateHeader(nullptr, "Last-Modified", &last_modified_header);
return HttpUtil::HasValidators(GetHttpVersion(), etag_header,
last_modified_header);
}
int64_t HttpResponseHeaders::GetContentLength() const {
return GetInt64HeaderValue("content-length");
}
int64_t HttpResponseHeaders::GetInt64HeaderValue(
const std::string& header) const {
size_t iter = 0;
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_t result;
bool ok = base::StringToInt64(content_length_val, &result);
if (!ok || result < 0)
return -1;
return result;
}
bool HttpResponseHeaders::GetContentRangeFor206(
int64_t* first_byte_position,
int64_t* last_byte_position,
int64_t* instance_length) const {
size_t iter = 0;
std::string content_range_spec;
if (!EnumerateHeader(&iter, kContentRange, &content_range_spec)) {
*first_byte_position = *last_byte_position = *instance_length = -1;
return false;
}
return HttpUtil::ParseContentRangeHeaderFor206(
content_range_spec, first_byte_position, last_byte_position,
instance_length);
}
base::Value::Dict HttpResponseHeaders::NetLogParams(
NetLogCaptureMode capture_mode) const {
base::Value::Dict dict;
base::Value::List headers;
headers.Append(NetLogStringValue(GetStatusLine()));
size_t iterator = 0;
std::string name;
std::string value;
while (EnumerateHeaderLines(&iterator, &name, &value)) {
std::string log_value =
ElideHeaderValueForNetLog(capture_mode, name, value);
headers.Append(NetLogStringValue(base::StrCat({name, ": ", log_value})));
}
dict.Set("headers", std::move(headers));
return dict;
}
bool HttpResponseHeaders::IsChunkEncoded() const {
return GetHttpVersion() >= HttpVersion(1, 1) &&
HasHeaderValue("Transfer-Encoding", "chunked");
}
bool HttpResponseHeaders::IsCookieResponseHeader(base::StringPiece name) {
for (const char* cookie_header : kCookieResponseHeaders) {
if (base::EqualsCaseInsensitiveASCII(cookie_header, name))
return true;
}
return false;
}
void HttpResponseHeaders::WriteIntoTrace(perfetto::TracedValue context) const {
perfetto::TracedDictionary dict = std::move(context).WriteDictionary();
dict.Add("response_code", response_code_);
dict.Add("headers", parsed_);
}
}