File: http_request.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (275 lines) | stat: -rw-r--r-- 9,454 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/test/embedded_test_server/http_request.h"

#include <algorithm>
#include <string_view>
#include <utility>

#include "base/logging.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "net/base/host_port_pair.h"
#include "net/http/http_chunked_decoder.h"
#include "url/gurl.h"

namespace net::test_server {

namespace {

size_t kRequestSizeLimit = 64 * 1024 * 1024;  // 64 mb.

// Helper function used to trim tokens in http request headers.
std::string Trim(const std::string& value) {
  std::string result;
  base::TrimString(value, " \t", &result);
  return result;
}

}  // namespace

HttpRequest::HttpRequest() = default;

HttpRequest::HttpRequest(const HttpRequest& other) = default;

HttpRequest::~HttpRequest() = default;

GURL HttpRequest::GetURL() const {
  if (base_url.is_valid())
    return base_url.Resolve(relative_url);
  return GURL("http://localhost" + relative_url);
}

HttpRequestParser::HttpRequestParser()
    : http_request_(std::make_unique<HttpRequest>()) {}

HttpRequestParser::~HttpRequestParser() = default;

void HttpRequestParser::ProcessChunk(std::string_view data) {
  buffer_.append(data);
  DCHECK_LE(buffer_.size() + data.size(), kRequestSizeLimit) <<
      "The HTTP request is too large.";
}

std::string HttpRequestParser::ShiftLine() {
  size_t eoln_position = buffer_.find("\r\n", buffer_position_);
  DCHECK_NE(std::string::npos, eoln_position);
  const int line_length = eoln_position - buffer_position_;
  std::string result = buffer_.substr(buffer_position_, line_length);
  buffer_position_ += line_length + 2;
  return result;
}

HttpRequestParser::ParseResult HttpRequestParser::ParseRequest() {
  DCHECK_NE(STATE_ACCEPTED, state_);
  // Parse the request from beginning. However, entire request may not be
  // available in the buffer.
  if (state_ == STATE_HEADERS) {
    if (ParseHeaders() == ACCEPTED)
      return ACCEPTED;
  }
  // This should not be 'else if' of the previous block, as |state_| can be
  // changed in ParseHeaders().
  if (state_ == STATE_CONTENT) {
    if (ParseContent() == ACCEPTED)
      return ACCEPTED;
  }
  return WAITING;
}

HttpRequestParser::ParseResult HttpRequestParser::ParseHeaders() {
  // Check if the all request headers are available.
  if (buffer_.find("\r\n\r\n", buffer_position_) == std::string::npos)
    return WAITING;

  // Parse request's the first header line.
  // Request main main header, eg. GET /foobar.html HTTP/1.1
  std::string request_headers;
  {
    const std::string header_line = ShiftLine();
    http_request_->all_headers += header_line + "\r\n";
    std::vector<std::string> header_line_tokens = base::SplitString(
        header_line, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
    DCHECK_EQ(3u, header_line_tokens.size());
    // Method.
    http_request_->method_string = header_line_tokens[0];
    http_request_->method = GetMethodType(http_request_->method_string);
    // Target resource. See
    // https://www.rfc-editor.org/rfc/rfc9112#name-request-line
    // https://www.rfc-editor.org/rfc/rfc9110#name-determining-the-target-reso
    if (http_request_->method == METHOD_CONNECT) {
      // CONNECT uses a special authority-form. Just report the value as
      // `relative_url`.
      // https://www.rfc-editor.org/rfc/rfc9112#section-3.2.3
      CHECK(!HostPortPair::FromString(header_line_tokens[1]).IsEmpty());
      http_request_->relative_url = header_line_tokens[1];
    } else if (http_request_->method == METHOD_OPTIONS &&
               header_line_tokens[1] == "*") {
      // OPTIONS allows a special asterisk-form for the request target.
      // https://www.rfc-editor.org/rfc/rfc9112#section-3.2.4
      http_request_->relative_url = "*";
    } else {
      // The request target should be origin-form, unless connecting through a
      // proxy, in which case it is absolute-form.
      // https://www.rfc-editor.org/rfc/rfc9112#name-origin-form
      // https://www.rfc-editor.org/rfc/rfc9112#name-absolute-form
      if (!header_line_tokens[1].empty() &&
          header_line_tokens[1].front() == '/') {
        http_request_->relative_url = header_line_tokens[1];
      } else {
        GURL url(header_line_tokens[1]);
        CHECK(url.is_valid());
        // TODO(crbug.com/40242862): This should retain the entire URL.
        http_request_->relative_url = url.PathForRequest();
      }
    }

    // Protocol.
    const std::string protocol = base::ToLowerASCII(header_line_tokens[2]);
    CHECK(protocol == "http/1.0" || protocol == "http/1.1") <<
        "Protocol not supported: " << protocol;
  }

  // Parse further headers.
  {
    std::string header_name;
    while (true) {
      std::string header_line = ShiftLine();
      if (header_line.empty())
        break;

      http_request_->all_headers += header_line + "\r\n";
      if (header_line[0] == ' ' || header_line[0] == '\t') {
        // Continuation of the previous multi-line header.
        std::string header_value =
            Trim(header_line.substr(1, header_line.size() - 1));
        http_request_->headers[header_name] += " " + header_value;
      } else {
        // New header.
        size_t delimiter_pos = header_line.find(":");
        DCHECK_NE(std::string::npos, delimiter_pos) << "Syntax error.";
        header_name = Trim(header_line.substr(0, delimiter_pos));
        std::string header_value = Trim(header_line.substr(
            delimiter_pos + 1,
            header_line.size() - delimiter_pos - 1));
        http_request_->headers[header_name] = header_value;
      }
    }
  }

  // Headers done. Is any content data attached to the request?
  declared_content_length_ = 0;
  if (http_request_->headers.count("Content-Length") > 0) {
    http_request_->has_content = true;
    const bool success = base::StringToSizeT(
        http_request_->headers["Content-Length"],
        &declared_content_length_);
    if (!success) {
      declared_content_length_ = 0;
      LOG(WARNING) << "Malformed Content-Length header's value.";
    }
  } else if (http_request_->headers.count("Transfer-Encoding") > 0) {
    if (base::EqualsCaseInsensitiveASCII(
            http_request_->headers["Transfer-Encoding"], "chunked")) {
      http_request_->has_content = true;
      chunked_decoder_ = std::make_unique<HttpChunkedDecoder>();
      state_ = STATE_CONTENT;
      return WAITING;
    }
  }
  if (declared_content_length_ == 0) {
    // No content data, so parsing is finished.
    state_ = STATE_ACCEPTED;
    return ACCEPTED;
  }

  // The request has not yet been parsed yet, content data is still to be
  // processed.
  state_ = STATE_CONTENT;
  return WAITING;
}

HttpRequestParser::ParseResult HttpRequestParser::ParseContent() {
  const size_t available_bytes = buffer_.size() - buffer_position_;
  if (chunked_decoder_.get()) {
    base::span<uint8_t> available_data =
        base::as_writable_byte_span(buffer_).subspan(buffer_position_,
                                                     available_bytes);
    int bytes_written = chunked_decoder_->FilterBuf(available_data);
    base::span<const char> extracted_chunk = base::as_chars(
        available_data.first(base::checked_cast<size_t>(bytes_written)));
    http_request_->content.append(extracted_chunk.begin(),
                                  extracted_chunk.end());

    if (chunked_decoder_->reached_eof()) {
      buffer_ =
          buffer_.substr(buffer_.size() - chunked_decoder_->bytes_after_eof());
      buffer_position_ = 0;
      state_ = STATE_ACCEPTED;
      return ACCEPTED;
    }
    buffer_ = "";
    buffer_position_ = 0;
    state_ = STATE_CONTENT;
    return WAITING;
  }

  const size_t fetch_bytes = std::min(
      available_bytes,
      declared_content_length_ - http_request_->content.size());
  base::span<char> payload_portion =
      base::span(buffer_).subspan(buffer_position_, fetch_bytes);
  http_request_->content.append(payload_portion.begin(), payload_portion.end());
  buffer_position_ += fetch_bytes;

  if (declared_content_length_ == http_request_->content.size()) {
    state_ = STATE_ACCEPTED;
    return ACCEPTED;
  }

  state_ = STATE_CONTENT;
  return WAITING;
}

std::unique_ptr<HttpRequest> HttpRequestParser::GetRequest() {
  DCHECK_EQ(STATE_ACCEPTED, state_);
  std::unique_ptr<HttpRequest> result = std::move(http_request_);

  // Prepare for parsing a new request.
  state_ = STATE_HEADERS;
  http_request_ = std::make_unique<HttpRequest>();
  buffer_.clear();
  buffer_position_ = 0;
  declared_content_length_ = 0;

  return result;
}

// static
HttpMethod HttpRequestParser::GetMethodType(std::string_view token) {
  if (token == "GET") {
    return METHOD_GET;
  } else if (token == "HEAD") {
    return METHOD_HEAD;
  } else if (token == "POST") {
    return METHOD_POST;
  } else if (token == "PUT") {
    return METHOD_PUT;
  } else if (token == "DELETE") {
    return METHOD_DELETE;
  } else if (token == "PATCH") {
    return METHOD_PATCH;
  } else if (token == "CONNECT") {
    return METHOD_CONNECT;
  } else if (token == "OPTIONS") {
    return METHOD_OPTIONS;
  }
  LOG(WARNING) << "Method not implemented: " << token;
  return METHOD_UNKNOWN;
}

}  // namespace net::test_server