This source file includes following definitions.
- FindStringEnd
- FindDelimiter
- ParseContentType
- ParseRanges
- ParseRangeHeader
- HasHeader
- IsSafeHeader
- StripHeaders
- IsNonCoalescingHeader
- IsLWS
- TrimLWS
- IsQuote
- IsToken
- Unquote
- Unquote
- Quote
- LocateStartOfStatusLine
- LocateEndOfHeaders
- IsLineSegmentContinuable
- FindStatusLineEnd
- FindFirstNonLWS
- AssembleRawHeaders
- ConvertHeadersBackToHTTPResponse
- GenerateAcceptLanguageHeader
- AppendHeaderIfMissing
- HasStrongValidators
- GetStatusCodesForHistogram
- MapStatusCodeForHistogram
- GetNext
- AdvanceTo
- GetNext
- value_is_quoted_
- GetNext
#include "net/http/http_util.h"
#include <algorithm>
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
namespace net {
static size_t FindStringEnd(const std::string& line, size_t start, char delim) {
DCHECK_LT(start, line.length());
DCHECK_EQ(line[start], delim);
DCHECK((delim == '"') || (delim == '\''));
const char set[] = { delim, '\\', '\0' };
for (size_t end = line.find_first_of(set, start + 1);
end != std::string::npos; end = line.find_first_of(set, end + 2)) {
if (line[end] != '\\')
return end;
}
return line.length();
}
size_t HttpUtil::FindDelimiter(const std::string& line,
size_t search_start,
char delimiter) {
do {
const char delim_str[] = { delimiter, '"', '\'', '\0' };
size_t cur_delim_pos = line.find_first_of(delim_str, search_start);
if (cur_delim_pos == std::string::npos)
return line.length();
char ch = line[cur_delim_pos];
if (ch == delimiter) {
return cur_delim_pos;
}
search_start = FindStringEnd(line, cur_delim_pos, ch);
if (search_start == line.length())
return search_start;
++search_start;
} while (true);
NOTREACHED();
return line.length();
}
void HttpUtil::ParseContentType(const std::string& content_type_str,
std::string* mime_type,
std::string* charset,
bool* had_charset,
std::string* boundary) {
const std::string::const_iterator begin = content_type_str.begin();
size_t type_val = content_type_str.find_first_not_of(HTTP_LWS);
type_val = std::min(type_val, content_type_str.length());
size_t type_end = content_type_str.find_first_of(HTTP_LWS ";(", type_val);
if (type_end == std::string::npos)
type_end = content_type_str.length();
size_t charset_val = 0;
size_t charset_end = 0;
bool type_has_charset = false;
size_t param_start = content_type_str.find_first_of(';', type_end);
if (param_start != std::string::npos) {
base::StringTokenizer tokenizer(begin + param_start, content_type_str.end(),
";");
tokenizer.set_quote_chars("\"");
while (tokenizer.GetNext()) {
std::string::const_iterator equals_sign =
std::find(tokenizer.token_begin(), tokenizer.token_end(), '=');
if (equals_sign == tokenizer.token_end())
continue;
std::string::const_iterator param_name_begin = tokenizer.token_begin();
std::string::const_iterator param_name_end = equals_sign;
TrimLWS(¶m_name_begin, ¶m_name_end);
std::string::const_iterator param_value_begin = equals_sign + 1;
std::string::const_iterator param_value_end = tokenizer.token_end();
DCHECK(param_value_begin <= tokenizer.token_end());
TrimLWS(¶m_value_begin, ¶m_value_end);
if (LowerCaseEqualsASCII(param_name_begin, param_name_end, "charset")) {
charset_val = param_value_begin - begin;
charset_end = param_value_end - begin;
type_has_charset = true;
} else if (LowerCaseEqualsASCII(param_name_begin, param_name_end,
"boundary")) {
if (boundary)
boundary->assign(param_value_begin, param_value_end);
}
}
}
if (type_has_charset) {
charset_val = content_type_str.find_first_not_of(HTTP_LWS, charset_val);
charset_val = std::min(charset_val, charset_end);
char first_char = content_type_str[charset_val];
if (first_char == '"' || first_char == '\'') {
charset_end = FindStringEnd(content_type_str, charset_val, first_char);
++charset_val;
DCHECK(charset_end >= charset_val);
} else {
charset_end = std::min(content_type_str.find_first_of(HTTP_LWS ";(",
charset_val),
charset_end);
}
}
if (content_type_str.length() != 0 &&
content_type_str != "*/*" &&
content_type_str.find_first_of('/') != std::string::npos) {
bool eq = !mime_type->empty() && LowerCaseEqualsASCII(begin + type_val,
begin + type_end,
mime_type->data());
if (!eq) {
mime_type->assign(begin + type_val, begin + type_end);
StringToLowerASCII(mime_type);
}
if ((!eq && *had_charset) || type_has_charset) {
*had_charset = true;
charset->assign(begin + charset_val, begin + charset_end);
StringToLowerASCII(charset);
}
}
}
bool HttpUtil::ParseRanges(const std::string& headers,
std::vector<HttpByteRange>* ranges) {
std::string ranges_specifier;
HttpUtil::HeadersIterator it(headers.begin(), headers.end(), "\r\n");
while (it.GetNext()) {
if (!LowerCaseEqualsASCII(it.name(), "range"))
continue;
ranges_specifier = it.values();
break;
}
if (ranges_specifier.empty())
return false;
return ParseRangeHeader(ranges_specifier, ranges);
}
bool HttpUtil::ParseRangeHeader(const std::string& ranges_specifier,
std::vector<HttpByteRange>* ranges) {
size_t equal_char_offset = ranges_specifier.find('=');
if (equal_char_offset == std::string::npos)
return false;
std::string::const_iterator bytes_unit_begin = ranges_specifier.begin();
std::string::const_iterator bytes_unit_end = bytes_unit_begin +
equal_char_offset;
std::string::const_iterator byte_range_set_begin = bytes_unit_end + 1;
std::string::const_iterator byte_range_set_end = ranges_specifier.end();
TrimLWS(&bytes_unit_begin, &bytes_unit_end);
if (!LowerCaseEqualsASCII(bytes_unit_begin, bytes_unit_end, "bytes"))
return false;
ValuesIterator byte_range_set_iterator(byte_range_set_begin,
byte_range_set_end, ',');
while (byte_range_set_iterator.GetNext()) {
size_t minus_char_offset = byte_range_set_iterator.value().find('-');
if (minus_char_offset == std::string::npos)
return false;
std::string::const_iterator first_byte_pos_begin =
byte_range_set_iterator.value_begin();
std::string::const_iterator first_byte_pos_end =
first_byte_pos_begin + minus_char_offset;
TrimLWS(&first_byte_pos_begin, &first_byte_pos_end);
std::string first_byte_pos(first_byte_pos_begin, first_byte_pos_end);
HttpByteRange range;
if (!first_byte_pos.empty()) {
int64 first_byte_position = -1;
if (!base::StringToInt64(first_byte_pos, &first_byte_position))
return false;
range.set_first_byte_position(first_byte_position);
}
std::string::const_iterator last_byte_pos_begin =
byte_range_set_iterator.value_begin() + minus_char_offset + 1;
std::string::const_iterator last_byte_pos_end =
byte_range_set_iterator.value_end();
TrimLWS(&last_byte_pos_begin, &last_byte_pos_end);
std::string last_byte_pos(last_byte_pos_begin, last_byte_pos_end);
if (!last_byte_pos.empty()) {
int64 last_byte_position;
if (!base::StringToInt64(last_byte_pos, &last_byte_position))
return false;
if (range.HasFirstBytePosition())
range.set_last_byte_position(last_byte_position);
else
range.set_suffix_length(last_byte_position);
} else if (!range.HasFirstBytePosition()) {
return false;
}
if (!range.IsValid())
return false;
ranges->push_back(range);
}
return !ranges->empty();
}
bool HttpUtil::HasHeader(const std::string& headers, const char* name) {
size_t name_len = strlen(name);
std::string::const_iterator it =
std::search(headers.begin(),
headers.end(),
name,
name + name_len,
base::CaseInsensitiveCompareASCII<char>());
if (it == headers.end())
return false;
if (it != headers.begin() && it[-1] != '\n')
return false;
if (it + name_len >= headers.end() || it[name_len] != ':')
return false;
return true;
}
namespace {
const char* const kForbiddenHeaderFields[] = {
"accept-charset",
"accept-encoding",
"access-control-request-headers",
"access-control-request-method",
"connection",
"content-length",
"cookie",
"cookie2",
"content-transfer-encoding",
"date",
"expect",
"host",
"keep-alive",
"origin",
"referer",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"user-agent",
"via",
};
}
bool HttpUtil::IsSafeHeader(const std::string& name) {
std::string lower_name(StringToLowerASCII(name));
if (StartsWithASCII(lower_name, "proxy-", true) ||
StartsWithASCII(lower_name, "sec-", true))
return false;
for (size_t i = 0; i < arraysize(kForbiddenHeaderFields); ++i) {
if (lower_name == kForbiddenHeaderFields[i])
return false;
}
return true;
}
std::string HttpUtil::StripHeaders(const std::string& headers,
const char* const headers_to_remove[],
size_t headers_to_remove_len) {
std::string stripped_headers;
net::HttpUtil::HeadersIterator it(headers.begin(), headers.end(), "\r\n");
while (it.GetNext()) {
bool should_remove = false;
for (size_t i = 0; i < headers_to_remove_len; ++i) {
if (LowerCaseEqualsASCII(it.name_begin(), it.name_end(),
headers_to_remove[i])) {
should_remove = true;
break;
}
}
if (!should_remove) {
stripped_headers.append(it.name_begin(), it.values_end());
stripped_headers.append("\r\n");
}
}
return stripped_headers;
}
bool HttpUtil::IsNonCoalescingHeader(std::string::const_iterator name_begin,
std::string::const_iterator name_end) {
const char* kNonCoalescingHeaders[] = {
"date",
"expires",
"last-modified",
"location",
"retry-after",
"set-cookie",
"www-authenticate",
"proxy-authenticate",
"strict-transport-security"
};
for (size_t i = 0; i < arraysize(kNonCoalescingHeaders); ++i) {
if (LowerCaseEqualsASCII(name_begin, name_end, kNonCoalescingHeaders[i]))
return true;
}
return false;
}
bool HttpUtil::IsLWS(char c) {
return strchr(HTTP_LWS, c) != NULL;
}
void HttpUtil::TrimLWS(std::string::const_iterator* begin,
std::string::const_iterator* end) {
while (*begin < *end && IsLWS((*begin)[0]))
++(*begin);
while (*begin < *end && IsLWS((*end)[-1]))
--(*end);
}
bool HttpUtil::IsQuote(char c) {
return c == '"' || c == '\'';
}
bool HttpUtil::IsToken(std::string::const_iterator begin,
std::string::const_iterator end) {
if (begin == end)
return false;
for (std::string::const_iterator iter = begin; iter != end; ++iter) {
unsigned char c = *iter;
if (c >= 0x80 || c <= 0x1F || c == 0x7F ||
c == '(' || c == ')' || c == '<' || c == '>' || c == '@' ||
c == ',' || c == ';' || c == ':' || c == '\\' || c == '"' ||
c == '/' || c == '[' || c == ']' || c == '?' || c == '=' ||
c == '{' || c == '}' || c == ' ' || c == '\t')
return false;
}
return true;
}
std::string HttpUtil::Unquote(std::string::const_iterator begin,
std::string::const_iterator end) {
if (begin == end)
return std::string();
if (!IsQuote(*begin))
return std::string(begin, end);
if (end - begin < 2 || *begin != *(end - 1))
return std::string(begin, end);
++begin;
--end;
std::string unescaped;
bool prev_escape = false;
for (; begin != end; ++begin) {
char c = *begin;
if (c == '\\' && !prev_escape) {
prev_escape = true;
continue;
}
prev_escape = false;
unescaped.push_back(c);
}
return unescaped;
}
std::string HttpUtil::Unquote(const std::string& str) {
return Unquote(str.begin(), str.end());
}
std::string HttpUtil::Quote(const std::string& str) {
std::string escaped;
escaped.reserve(2 + str.size());
std::string::const_iterator begin = str.begin();
std::string::const_iterator end = str.end();
escaped.push_back('"');
for (; begin != end; ++begin) {
char c = *begin;
if (c == '"' || c == '\\')
escaped.push_back('\\');
escaped.push_back(c);
}
escaped.push_back('"');
return escaped;
}
int HttpUtil::LocateStartOfStatusLine(const char* buf, int buf_len) {
const int slop = 4;
const int http_len = 4;
if (buf_len >= http_len) {
int i_max = std::min(buf_len - http_len, slop);
for (int i = 0; i <= i_max; ++i) {
if (LowerCaseEqualsASCII(buf + i, buf + i + http_len, "http"))
return i;
}
}
return -1;
}
int HttpUtil::LocateEndOfHeaders(const char* buf, int buf_len, int i) {
bool was_lf = false;
char last_c = '\0';
for (; i < buf_len; ++i) {
char c = buf[i];
if (c == '\n') {
if (was_lf)
return i + 1;
was_lf = true;
} else if (c != '\r' || last_c != '\n') {
was_lf = false;
}
last_c = c;
}
return -1;
}
static bool IsLineSegmentContinuable(const char* begin, const char* end) {
if (begin == end)
return false;
const char* colon = std::find(begin, end, ':');
if (colon == end)
return false;
const char* name_begin = begin;
const char* name_end = colon;
if (name_begin == name_end)
return false;
if (HttpUtil::IsLWS(*name_begin))
return false;
return true;
}
static const char* FindStatusLineEnd(const char* begin, const char* end) {
size_t i = base::StringPiece(begin, end - begin).find_first_of("\r\n");
if (i == base::StringPiece::npos)
return end;
return begin + i;
}
static const char* FindFirstNonLWS(const char* begin, const char* end) {
for (const char* cur = begin; cur != end; ++cur) {
if (!HttpUtil::IsLWS(*cur))
return cur;
}
return end;
}
std::string HttpUtil::AssembleRawHeaders(const char* input_begin,
int input_len) {
std::string raw_headers;
raw_headers.reserve(input_len);
const char* input_end = input_begin + input_len;
int status_begin_offset = LocateStartOfStatusLine(input_begin, input_len);
if (status_begin_offset != -1)
input_begin += status_begin_offset;
const char* status_line_end = FindStatusLineEnd(input_begin, input_end);
raw_headers.append(input_begin, status_line_end);
base::CStringTokenizer lines(status_line_end, input_end, "\r\n");
bool prev_line_continuable = false;
while (lines.GetNext()) {
const char* line_begin = lines.token_begin();
const char* line_end = lines.token_end();
if (prev_line_continuable && IsLWS(*line_begin)) {
raw_headers.push_back(' ');
raw_headers.append(FindFirstNonLWS(line_begin, line_end), line_end);
} else {
raw_headers.push_back('\n');
raw_headers.append(line_begin, line_end);
prev_line_continuable = IsLineSegmentContinuable(line_begin, line_end);
}
}
raw_headers.append("\n\n", 2);
raw_headers.erase(std::remove(raw_headers.begin(), raw_headers.end(), '\0'),
raw_headers.end());
std::replace(raw_headers.begin(), raw_headers.end(), '\n', '\0');
return raw_headers;
}
std::string HttpUtil::ConvertHeadersBackToHTTPResponse(const std::string& str) {
std::string disassembled_headers;
base::StringTokenizer tokenizer(str, std::string(1, '\0'));
while (tokenizer.GetNext()) {
disassembled_headers.append(tokenizer.token_begin(), tokenizer.token_end());
disassembled_headers.append("\r\n");
}
disassembled_headers.append("\r\n");
return disassembled_headers;
}
std::string HttpUtil::GenerateAcceptLanguageHeader(
const std::string& raw_language_list) {
const unsigned int kQvalueDecrement10 = 2;
unsigned int qvalue10 = 10;
base::StringTokenizer t(raw_language_list, ",");
std::string lang_list_with_q;
while (t.GetNext()) {
std::string language = t.token();
if (qvalue10 == 10) {
lang_list_with_q = language;
} else {
DCHECK_LT(qvalue10, 10U);
base::StringAppendF(&lang_list_with_q, ",%s;q=0.%d", language.c_str(),
qvalue10);
}
if (qvalue10 > kQvalueDecrement10)
qvalue10 -= kQvalueDecrement10;
}
return lang_list_with_q;
}
void HttpUtil::AppendHeaderIfMissing(const char* header_name,
const std::string& header_value,
std::string* headers) {
if (header_value.empty())
return;
if (net::HttpUtil::HasHeader(*headers, header_name))
return;
*headers += std::string(header_name) + ": " + header_value + "\r\n";
}
bool HttpUtil::HasStrongValidators(HttpVersion version,
const std::string& etag_header,
const std::string& last_modified_header,
const std::string& date_header) {
if (version < HttpVersion(1, 1))
return false;
if (!etag_header.empty()) {
size_t slash = etag_header.find('/');
if (slash == std::string::npos || slash == 0)
return true;
std::string::const_iterator i = etag_header.begin();
std::string::const_iterator j = etag_header.begin() + slash;
TrimLWS(&i, &j);
if (!LowerCaseEqualsASCII(i, j, "w"))
return true;
}
base::Time last_modified;
if (!base::Time::FromString(last_modified_header.c_str(), &last_modified))
return false;
base::Time date;
if (!base::Time::FromString(date_header.c_str(), &date))
return false;
return ((date - last_modified).InSeconds() >= 60);
}
enum {
HISTOGRAM_MIN_HTTP_STATUS_CODE = 100,
HISTOGRAM_MAX_HTTP_STATUS_CODE = 599,
};
std::vector<int> HttpUtil::GetStatusCodesForHistogram() {
std::vector<int> codes;
codes.reserve(
HISTOGRAM_MAX_HTTP_STATUS_CODE - HISTOGRAM_MIN_HTTP_STATUS_CODE + 2);
codes.push_back(0);
for (int i = HISTOGRAM_MIN_HTTP_STATUS_CODE;
i <= HISTOGRAM_MAX_HTTP_STATUS_CODE; ++i)
codes.push_back(i);
return codes;
}
int HttpUtil::MapStatusCodeForHistogram(int code) {
if (HISTOGRAM_MIN_HTTP_STATUS_CODE <= code &&
code <= HISTOGRAM_MAX_HTTP_STATUS_CODE)
return code;
return 0;
}
HttpUtil::HeadersIterator::HeadersIterator(
std::string::const_iterator headers_begin,
std::string::const_iterator headers_end,
const std::string& line_delimiter)
: lines_(headers_begin, headers_end, line_delimiter) {
}
HttpUtil::HeadersIterator::~HeadersIterator() {
}
bool HttpUtil::HeadersIterator::GetNext() {
while (lines_.GetNext()) {
name_begin_ = lines_.token_begin();
values_end_ = lines_.token_end();
std::string::const_iterator colon(std::find(name_begin_, values_end_, ':'));
if (colon == values_end_)
continue;
name_end_ = colon;
if (name_begin_ == name_end_ || IsLWS(*name_begin_))
continue;
TrimLWS(&name_begin_, &name_end_);
if (name_begin_ == name_end_)
continue;
values_begin_ = colon + 1;
TrimLWS(&values_begin_, &values_end_);
return true;
}
return false;
}
bool HttpUtil::HeadersIterator::AdvanceTo(const char* name) {
DCHECK(name != NULL);
DCHECK_EQ(0, StringToLowerASCII<std::string>(name).compare(name))
<< "the header name must be in all lower case";
while (GetNext()) {
if (LowerCaseEqualsASCII(name_begin_, name_end_, name)) {
return true;
}
}
return false;
}
HttpUtil::ValuesIterator::ValuesIterator(
std::string::const_iterator values_begin,
std::string::const_iterator values_end,
char delimiter)
: values_(values_begin, values_end, std::string(1, delimiter)) {
values_.set_quote_chars("\'\"");
}
HttpUtil::ValuesIterator::~ValuesIterator() {
}
bool HttpUtil::ValuesIterator::GetNext() {
while (values_.GetNext()) {
value_begin_ = values_.token_begin();
value_end_ = values_.token_end();
TrimLWS(&value_begin_, &value_end_);
if (value_begin_ != value_end_)
return true;
}
return false;
}
HttpUtil::NameValuePairsIterator::NameValuePairsIterator(
std::string::const_iterator begin,
std::string::const_iterator end,
char delimiter)
: props_(begin, end, delimiter),
valid_(true),
name_begin_(end),
name_end_(end),
value_begin_(end),
value_end_(end),
value_is_quoted_(false) {
}
HttpUtil::NameValuePairsIterator::~NameValuePairsIterator() {}
bool HttpUtil::NameValuePairsIterator::GetNext() {
if (!props_.GetNext())
return false;
value_begin_ = props_.value_begin();
value_end_ = props_.value_end();
name_begin_ = name_end_ = value_end_;
std::string::const_iterator equals = std::find(value_begin_, value_end_, '=');
if (equals == value_end_ || equals == value_begin_)
return valid_ = false;
for (std::string::const_iterator it = value_begin_; it != equals; ++it) {
if (HttpUtil::IsQuote(*it))
return valid_ = false;
}
name_begin_ = value_begin_;
name_end_ = equals;
value_begin_ = equals + 1;
TrimLWS(&name_begin_, &name_end_);
TrimLWS(&value_begin_, &value_end_);
value_is_quoted_ = false;
unquoted_value_.clear();
if (value_begin_ == value_end_)
return valid_ = false;
if (HttpUtil::IsQuote(*value_begin_)) {
if (*value_begin_ != *(value_end_ - 1) || value_begin_ + 1 == value_end_) {
++value_begin_;
} else {
value_is_quoted_ = true;
unquoted_value_ = HttpUtil::Unquote(value_begin_, value_end_);
}
}
return true;
}
}