CacheValidation.cpp [plain text]
#include "config.h"
#include "CacheValidation.h"
#include "HTTPHeaderMap.h"
#include "ResourceResponse.h"
#include <wtf/CurrentTime.h>
namespace WebCore {
const char* const headersToIgnoreAfterRevalidation[] = {
"allow",
"connection",
"etag",
"keep-alive",
"last-modified"
"proxy-authenticate",
"proxy-connection",
"trailer",
"transfer-encoding",
"upgrade",
"www-authenticate",
"x-frame-options",
"x-xss-protection",
};
const char* const headerPrefixesToIgnoreAfterRevalidation[] = {
"content-",
"x-content-",
"x-webkit-"
};
static inline bool shouldUpdateHeaderAfterRevalidation(const String& header)
{
for (size_t i = 0; i < WTF_ARRAY_LENGTH(headersToIgnoreAfterRevalidation); i++) {
if (equalIgnoringCase(header, headersToIgnoreAfterRevalidation[i]))
return false;
}
for (size_t i = 0; i < WTF_ARRAY_LENGTH(headerPrefixesToIgnoreAfterRevalidation); i++) {
if (header.startsWith(headerPrefixesToIgnoreAfterRevalidation[i], false))
return false;
}
return true;
}
void updateResponseHeadersAfterRevalidation(ResourceResponse& response, const ResourceResponse& validatingResponse)
{
for (const auto& header : validatingResponse.httpHeaderFields()) {
if (!shouldUpdateHeaderAfterRevalidation(header.key))
continue;
response.setHTTPHeaderField(header.key, header.value);
}
}
std::chrono::microseconds computeCurrentAge(const ResourceResponse& response, std::chrono::system_clock::time_point responseTime)
{
using namespace std::chrono;
auto dateValue = response.date();
auto apparentAge = dateValue ? std::max(microseconds::zero(), duration_cast<microseconds>(responseTime - dateValue.value())) : microseconds::zero();
auto ageValue = response.age().valueOr(microseconds::zero());
auto correctedInitialAge = std::max(apparentAge, ageValue);
auto residentTime = duration_cast<microseconds>(system_clock::now() - responseTime);
return correctedInitialAge + residentTime;
}
std::chrono::microseconds computeFreshnessLifetimeForHTTPFamily(const ResourceResponse& response, std::chrono::system_clock::time_point responseTime)
{
using namespace std::chrono;
ASSERT(response.url().protocolIsInHTTPFamily());
auto maxAge = response.cacheControlMaxAge();
if (maxAge)
return maxAge.value();
auto expires = response.expires();
auto date = response.date();
auto dateValue = date ? date.value() : responseTime;
if (expires)
return duration_cast<microseconds>(expires.value() - dateValue);
switch (response.httpStatusCode()) {
case 301: case 410: return hours(365 * 24);
default:
auto lastModified = response.lastModified();
if (lastModified)
return duration_cast<microseconds>((dateValue - lastModified.value()) * 0.1);
return microseconds::zero();
}
}
void updateRedirectChainStatus(RedirectChainCacheStatus& redirectChainCacheStatus, const ResourceResponse& response)
{
using namespace std::chrono;
if (redirectChainCacheStatus.status == RedirectChainCacheStatus::NotCachedRedirection)
return;
if (response.cacheControlContainsNoStore() || response.cacheControlContainsNoCache() || response.cacheControlContainsMustRevalidate()) {
redirectChainCacheStatus.status = RedirectChainCacheStatus::NotCachedRedirection;
return;
}
redirectChainCacheStatus.status = RedirectChainCacheStatus::CachedRedirection;
auto responseTimestamp = system_clock::now();
auto endOfValidity = responseTimestamp + computeFreshnessLifetimeForHTTPFamily(response, responseTimestamp) - computeCurrentAge(response, responseTimestamp);
redirectChainCacheStatus.endOfValidity = std::min(redirectChainCacheStatus.endOfValidity, endOfValidity);
}
bool redirectChainAllowsReuse(RedirectChainCacheStatus redirectChainCacheStatus, ReuseExpiredRedirectionOrNot reuseExpiredRedirection)
{
switch (redirectChainCacheStatus.status) {
case RedirectChainCacheStatus::NoRedirection:
return true;
case RedirectChainCacheStatus::NotCachedRedirection:
return false;
case RedirectChainCacheStatus::CachedRedirection:
return reuseExpiredRedirection || std::chrono::system_clock::now() <= redirectChainCacheStatus.endOfValidity;
}
ASSERT_NOT_REACHED();
return false;
}
inline bool isCacheHeaderSeparator(UChar c)
{
switch (c) {
case '(':
case ')':
case '<':
case '>':
case '@':
case ',':
case ';':
case ':':
case '\\':
case '"':
case '/':
case '[':
case ']':
case '?':
case '=':
case '{':
case '}':
case ' ':
case '\t':
return true;
default:
return false;
}
}
inline bool isControlCharacter(UChar c)
{
return c < ' ' || c == 127;
}
inline String trimToNextSeparator(const String& str)
{
return str.substring(0, str.find(isCacheHeaderSeparator));
}
static Vector<std::pair<String, String>> parseCacheHeader(const String& header)
{
Vector<std::pair<String, String>> result;
const String safeHeader = header.removeCharacters(isControlCharacter);
unsigned max = safeHeader.length();
unsigned pos = 0;
while (pos < max) {
size_t nextCommaPosition = safeHeader.find(',', pos);
size_t nextEqualSignPosition = safeHeader.find('=', pos);
if (nextEqualSignPosition == notFound && nextCommaPosition == notFound) {
result.append(std::make_pair(trimToNextSeparator(safeHeader.substring(pos, max - pos).stripWhiteSpace()), ""));
return result;
}
if (nextCommaPosition != notFound && (nextCommaPosition < nextEqualSignPosition || nextEqualSignPosition == notFound)) {
result.append(std::make_pair(trimToNextSeparator(safeHeader.substring(pos, nextCommaPosition - pos).stripWhiteSpace()), ""));
pos += nextCommaPosition - pos + 1;
continue;
}
String directive = trimToNextSeparator(safeHeader.substring(pos, nextEqualSignPosition - pos).stripWhiteSpace());
pos += nextEqualSignPosition - pos + 1;
String value = safeHeader.substring(pos, max - pos).stripWhiteSpace();
if (value[0] == '"') {
size_t nextDoubleQuotePosition = value.find('"', 1);
if (nextDoubleQuotePosition == notFound) {
result.append(std::make_pair(directive, trimToNextSeparator(value.substring(1, value.length() - 1).stripWhiteSpace())));
return result;
}
result.append(std::make_pair(directive, value.substring(1, nextDoubleQuotePosition - 1).stripWhiteSpace()));
pos += (safeHeader.find('"', pos) - pos) + nextDoubleQuotePosition + 1;
size_t nextCommaPosition2 = safeHeader.find(',', pos);
if (nextCommaPosition2 == notFound)
return result; pos += nextCommaPosition2 - pos + 1;
continue;
}
size_t nextCommaPosition2 = value.find(',');
if (nextCommaPosition2 == notFound) {
result.append(std::make_pair(directive, trimToNextSeparator(value)));
return result;
}
result.append(std::make_pair(directive, trimToNextSeparator(value.substring(0, nextCommaPosition2).stripWhiteSpace())));
pos += (safeHeader.find(',', pos) - pos) + 1;
}
return result;
}
CacheControlDirectives parseCacheControlDirectives(const HTTPHeaderMap& headers)
{
using namespace std::chrono;
CacheControlDirectives result;
String cacheControlValue = headers.get(HTTPHeaderName::CacheControl);
if (!cacheControlValue.isEmpty()) {
auto directives = parseCacheHeader(cacheControlValue);
size_t directivesSize = directives.size();
for (size_t i = 0; i < directivesSize; ++i) {
if (equalIgnoringCase(directives[i].first, "no-cache") && directives[i].second.isEmpty())
result.noCache = true;
else if (equalIgnoringCase(directives[i].first, "no-store"))
result.noStore = true;
else if (equalIgnoringCase(directives[i].first, "must-revalidate"))
result.mustRevalidate = true;
else if (equalIgnoringCase(directives[i].first, "max-age")) {
if (result.maxAge) {
continue;
}
bool ok;
double maxAge = directives[i].second.toDouble(&ok);
if (ok)
result.maxAge = duration_cast<microseconds>(duration<double>(maxAge));
} else if (equalIgnoringCase(directives[i].first, "max-stale")) {
if (result.maxStale) {
continue;
}
if (directives[i].second.isEmpty()) {
result.maxStale = microseconds::max();
continue;
}
bool ok;
double maxStale = directives[i].second.toDouble(&ok);
if (ok)
result.maxStale = duration_cast<microseconds>(duration<double>(maxStale));
}
}
}
if (!result.noCache) {
String pragmaValue = headers.get(HTTPHeaderName::Pragma);
result.noCache = pragmaValue.contains("no-cache", false);
}
return result;
}
}