• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "net/http/http_stream_parser.h"
6 
7 #include <algorithm>
8 #include <memory>
9 #include <utility>
10 
11 #include "base/compiler_specific.h"
12 #include "base/functional/bind.h"
13 #include "base/logging.h"
14 #include "base/memory/raw_ptr.h"
15 #include "base/metrics/histogram_macros.h"
16 #include "base/numerics/clamped_math.h"
17 #include "base/strings/string_util.h"
18 #include "base/values.h"
19 #include "net/base/io_buffer.h"
20 #include "net/base/ip_endpoint.h"
21 #include "net/base/upload_data_stream.h"
22 #include "net/http/http_chunked_decoder.h"
23 #include "net/http/http_log_util.h"
24 #include "net/http/http_request_headers.h"
25 #include "net/http/http_request_info.h"
26 #include "net/http/http_response_headers.h"
27 #include "net/http/http_response_info.h"
28 #include "net/http/http_status_code.h"
29 #include "net/http/http_util.h"
30 #include "net/log/net_log_event_type.h"
31 #include "net/socket/ssl_client_socket.h"
32 #include "net/socket/stream_socket.h"
33 #include "net/ssl/ssl_cert_request_info.h"
34 #include "net/ssl/ssl_info.h"
35 #include "url/url_canon.h"
36 
37 namespace net {
38 
39 namespace {
40 
41 const uint64_t kMaxMergedHeaderAndBodySize = 1400;
42 const size_t kRequestBodyBufferSize = 1 << 14;  // 16KB
43 
GetResponseHeaderLines(const HttpResponseHeaders & headers)44 std::string GetResponseHeaderLines(const HttpResponseHeaders& headers) {
45   std::string raw_headers = headers.raw_headers();
46   const char* null_separated_headers = raw_headers.c_str();
47   const char* header_line = null_separated_headers;
48   std::string cr_separated_headers;
49   while (header_line[0] != 0) {
50     cr_separated_headers += header_line;
51     cr_separated_headers += "\n";
52     header_line += strlen(header_line) + 1;
53   }
54   return cr_separated_headers;
55 }
56 
NetLogSendRequestBodyParams(uint64_t length,bool is_chunked,bool did_merge)57 base::Value::Dict NetLogSendRequestBodyParams(uint64_t length,
58                                               bool is_chunked,
59                                               bool did_merge) {
60   base::Value::Dict dict;
61   dict.Set("length", static_cast<int>(length));
62   dict.Set("is_chunked", is_chunked);
63   dict.Set("did_merge", did_merge);
64   return dict;
65 }
66 
NetLogSendRequestBody(const NetLogWithSource & net_log,uint64_t length,bool is_chunked,bool did_merge)67 void NetLogSendRequestBody(const NetLogWithSource& net_log,
68                            uint64_t length,
69                            bool is_chunked,
70                            bool did_merge) {
71   net_log.AddEvent(NetLogEventType::HTTP_TRANSACTION_SEND_REQUEST_BODY, [&] {
72     return NetLogSendRequestBodyParams(length, is_chunked, did_merge);
73   });
74 }
75 
76 // Returns true if |error_code| is an error for which we give the server a
77 // chance to send a body containing error information, if the error was received
78 // while trying to upload a request body.
ShouldTryReadingOnUploadError(int error_code)79 bool ShouldTryReadingOnUploadError(int error_code) {
80   return (error_code == ERR_CONNECTION_RESET);
81 }
82 
83 }  // namespace
84 
85 // Similar to DrainableIOBuffer(), but this version comes with its own
86 // storage. The motivation is to avoid repeated allocations of
87 // DrainableIOBuffer.
88 //
89 // Example:
90 //
91 // scoped_refptr<SeekableIOBuffer> buf =
92 //     base::MakeRefCounted<SeekableIOBuffer>(1024);
93 // // capacity() == 1024. size() == BytesRemaining() == BytesConsumed() == 0.
94 // // data() points to the beginning of the buffer.
95 //
96 // // Read() takes an IOBuffer.
97 // int bytes_read = some_reader->Read(buf, buf->capacity());
98 // buf->DidAppend(bytes_read);
99 // // size() == BytesRemaining() == bytes_read. data() is unaffected.
100 //
101 // while (buf->BytesRemaining() > 0) {
102 //   // Write() takes an IOBuffer. If it takes const char*, we could
103 ///  // simply use the regular IOBuffer like buf->data() + offset.
104 //   int bytes_written = Write(buf, buf->BytesRemaining());
105 //   buf->DidConsume(bytes_written);
106 // }
107 // // BytesRemaining() == 0. BytesConsumed() == size().
108 // // data() points to the end of the consumed bytes (exclusive).
109 //
110 // // If you want to reuse the buffer, be sure to clear the buffer.
111 // buf->Clear();
112 // // size() == BytesRemaining() == BytesConsumed() == 0.
113 // // data() points to the beginning of the buffer.
114 //
115 class HttpStreamParser::SeekableIOBuffer : public IOBuffer {
116  public:
SeekableIOBuffer(int capacity)117   explicit SeekableIOBuffer(int capacity)
118       : IOBuffer(capacity), real_data_(data_), capacity_(capacity) {}
119 
120   // DidConsume() changes the |data_| pointer so that |data_| always points
121   // to the first unconsumed byte.
DidConsume(int bytes)122   void DidConsume(int bytes) {
123     SetOffset(used_ + bytes);
124   }
125 
126   // Returns the number of unconsumed bytes.
BytesRemaining() const127   int BytesRemaining() const {
128     return size_ - used_;
129   }
130 
131   // Seeks to an arbitrary point in the buffer. The notion of bytes consumed
132   // and remaining are updated appropriately.
SetOffset(int bytes)133   void SetOffset(int bytes) {
134     DCHECK_GE(bytes, 0);
135     DCHECK_LE(bytes, size_);
136     used_ = bytes;
137     data_ = real_data_ + used_;
138   }
139 
140   // Called after data is added to the buffer. Adds |bytes| added to
141   // |size_|. data() is unaffected.
DidAppend(int bytes)142   void DidAppend(int bytes) {
143     DCHECK_GE(bytes, 0);
144     DCHECK_GE(size_ + bytes, 0);
145     DCHECK_LE(size_ + bytes, capacity_);
146     size_ += bytes;
147   }
148 
149   // Changes the logical size to 0, and the offset to 0.
Clear()150   void Clear() {
151     size_ = 0;
152     SetOffset(0);
153   }
154 
155   // Returns the logical size of the buffer (i.e the number of bytes of data
156   // in the buffer).
size() const157   int size() const { return size_; }
158 
159   // Returns the capacity of the buffer. The capacity is the size used when
160   // the object is created.
capacity() const161   int capacity() const { return capacity_; }
162 
163  private:
~SeekableIOBuffer()164   ~SeekableIOBuffer() override {
165     // data_ will be deleted in IOBuffer::~IOBuffer().
166     data_ = real_data_;
167   }
168 
169   // DanglingUntriaged because it is assigned a DanglingUntriaged pointer.
170   raw_ptr<char, DanglingUntriaged | AllowPtrArithmetic> real_data_;
171   const int capacity_;
172   int size_ = 0;
173   int used_ = 0;
174 };
175 
176 // 2 CRLFs + max of 8 hex chars.
177 const size_t HttpStreamParser::kChunkHeaderFooterSize = 12;
178 
HttpStreamParser(StreamSocket * stream_socket,bool connection_is_reused,const HttpRequestInfo * request,GrowableIOBuffer * read_buffer,const NetLogWithSource & net_log)179 HttpStreamParser::HttpStreamParser(StreamSocket* stream_socket,
180                                    bool connection_is_reused,
181                                    const HttpRequestInfo* request,
182                                    GrowableIOBuffer* read_buffer,
183                                    const NetLogWithSource& net_log)
184     : request_(request),
185       read_buf_(read_buffer),
186       response_header_start_offset_(std::string::npos),
187       stream_socket_(stream_socket),
188       connection_is_reused_(connection_is_reused),
189       net_log_(net_log) {
190   io_callback_ = base::BindRepeating(&HttpStreamParser::OnIOComplete,
191                                      weak_ptr_factory_.GetWeakPtr());
192 }
193 
194 HttpStreamParser::~HttpStreamParser() = default;
195 
SendRequest(const std::string & request_line,const HttpRequestHeaders & headers,const NetworkTrafficAnnotationTag & traffic_annotation,HttpResponseInfo * response,CompletionOnceCallback callback)196 int HttpStreamParser::SendRequest(
197     const std::string& request_line,
198     const HttpRequestHeaders& headers,
199     const NetworkTrafficAnnotationTag& traffic_annotation,
200     HttpResponseInfo* response,
201     CompletionOnceCallback callback) {
202   DCHECK_EQ(STATE_NONE, io_state_);
203   DCHECK(callback_.is_null());
204   DCHECK(!callback.is_null());
205   DCHECK(response);
206 
207   NetLogRequestHeaders(net_log_,
208                        NetLogEventType::HTTP_TRANSACTION_SEND_REQUEST_HEADERS,
209                        request_line, &headers);
210 
211   DVLOG(1) << __func__ << "() request_line = \"" << request_line << "\""
212            << " headers = \"" << headers.ToString() << "\"";
213   traffic_annotation_ = MutableNetworkTrafficAnnotationTag(traffic_annotation);
214   response_ = response;
215 
216   // Put the peer's IP address and port into the response.
217   IPEndPoint ip_endpoint;
218   int result = stream_socket_->GetPeerAddress(&ip_endpoint);
219   if (result != OK)
220     return result;
221   response_->remote_endpoint = ip_endpoint;
222 
223   std::string request = request_line + headers.ToString();
224   request_headers_length_ = request.size();
225 
226   if (request_->upload_data_stream != nullptr) {
227     request_body_send_buf_ =
228         base::MakeRefCounted<SeekableIOBuffer>(kRequestBodyBufferSize);
229     if (request_->upload_data_stream->is_chunked()) {
230       // Read buffer is adjusted to guarantee that |request_body_send_buf_| is
231       // large enough to hold the encoded chunk.
232       request_body_read_buf_ = base::MakeRefCounted<SeekableIOBuffer>(
233           kRequestBodyBufferSize - kChunkHeaderFooterSize);
234     } else {
235       // No need to encode request body, just send the raw data.
236       request_body_read_buf_ = request_body_send_buf_;
237     }
238   }
239 
240   io_state_ = STATE_SEND_HEADERS;
241 
242   // If we have a small request body, then we'll merge with the headers into a
243   // single write.
244   bool did_merge = false;
245   if (ShouldMergeRequestHeadersAndBody(request, request_->upload_data_stream)) {
246     int merged_size = static_cast<int>(
247         request_headers_length_ + request_->upload_data_stream->size());
248     scoped_refptr<IOBuffer> merged_request_headers_and_body =
249         base::MakeRefCounted<IOBuffer>(merged_size);
250     // We'll repurpose |request_headers_| to store the merged headers and
251     // body.
252     request_headers_ = base::MakeRefCounted<DrainableIOBuffer>(
253         merged_request_headers_and_body, merged_size);
254 
255     memcpy(request_headers_->data(), request.data(), request_headers_length_);
256     request_headers_->DidConsume(request_headers_length_);
257 
258     uint64_t todo = request_->upload_data_stream->size();
259     while (todo) {
260       int consumed = request_->upload_data_stream->Read(
261           request_headers_.get(), static_cast<int>(todo),
262           CompletionOnceCallback());
263       // Read() must succeed synchronously if not chunked and in memory.
264       DCHECK_GT(consumed, 0);
265       request_headers_->DidConsume(consumed);
266       todo -= consumed;
267     }
268     DCHECK(request_->upload_data_stream->IsEOF());
269     // Reset the offset, so the buffer can be read from the beginning.
270     request_headers_->SetOffset(0);
271     did_merge = true;
272 
273     NetLogSendRequestBody(net_log_, request_->upload_data_stream->size(),
274                           false, /* not chunked */
275                           true /* merged */);
276   }
277 
278   if (!did_merge) {
279     // If we didn't merge the body with the headers, then |request_headers_|
280     // contains just the HTTP headers.
281     scoped_refptr<StringIOBuffer> headers_io_buf =
282         base::MakeRefCounted<StringIOBuffer>(request);
283     request_headers_ = base::MakeRefCounted<DrainableIOBuffer>(
284         std::move(headers_io_buf), request.size());
285   }
286 
287   result = DoLoop(OK);
288   if (result == ERR_IO_PENDING)
289     callback_ = std::move(callback);
290 
291   return result > 0 ? OK : result;
292 }
293 
ConfirmHandshake(CompletionOnceCallback callback)294 int HttpStreamParser::ConfirmHandshake(CompletionOnceCallback callback) {
295   int ret = stream_socket_->ConfirmHandshake(
296       base::BindOnce(&HttpStreamParser::RunConfirmHandshakeCallback,
297                      weak_ptr_factory_.GetWeakPtr()));
298   if (ret == ERR_IO_PENDING)
299     confirm_handshake_callback_ = std::move(callback);
300   return ret;
301 }
302 
ReadResponseHeaders(CompletionOnceCallback callback)303 int HttpStreamParser::ReadResponseHeaders(CompletionOnceCallback callback) {
304   DCHECK(io_state_ == STATE_NONE || io_state_ == STATE_DONE);
305   DCHECK(callback_.is_null());
306   DCHECK(!callback.is_null());
307   DCHECK_EQ(0, read_buf_unused_offset_);
308   DCHECK(SendRequestBuffersEmpty());
309 
310   // This function can be called with io_state_ == STATE_DONE if the
311   // connection is closed after seeing just a 1xx response code.
312   if (io_state_ == STATE_DONE)
313     return ERR_CONNECTION_CLOSED;
314 
315   int result = OK;
316   io_state_ = STATE_READ_HEADERS;
317 
318   if (read_buf_->offset() > 0) {
319     // Simulate the state where the data was just read from the socket.
320     result = read_buf_->offset();
321     read_buf_->set_offset(0);
322   }
323   if (result > 0)
324     io_state_ = STATE_READ_HEADERS_COMPLETE;
325 
326   result = DoLoop(result);
327   if (result == ERR_IO_PENDING)
328     callback_ = std::move(callback);
329 
330   return result > 0 ? OK : result;
331 }
332 
ReadResponseBody(IOBuffer * buf,int buf_len,CompletionOnceCallback callback)333 int HttpStreamParser::ReadResponseBody(IOBuffer* buf,
334                                        int buf_len,
335                                        CompletionOnceCallback callback) {
336   DCHECK(io_state_ == STATE_NONE || io_state_ == STATE_DONE);
337   DCHECK(callback_.is_null());
338   DCHECK(!callback.is_null());
339   DCHECK_LE(buf_len, kMaxBufSize);
340   DCHECK(SendRequestBuffersEmpty());
341   // Added to investigate crbug.com/499663.
342   CHECK(buf);
343 
344   if (io_state_ == STATE_DONE)
345     return OK;
346 
347   user_read_buf_ = buf;
348   user_read_buf_len_ = buf_len;
349   io_state_ = STATE_READ_BODY;
350 
351   // Invalidate HttpRequestInfo pointer. This is to allow the stream to be
352   // shared across multiple consumers.
353   // It is safe to reset it at this point since request_->upload_data_stream
354   // is also not needed anymore.
355   request_ = nullptr;
356 
357   int result = DoLoop(OK);
358   if (result == ERR_IO_PENDING)
359     callback_ = std::move(callback);
360 
361   return result;
362 }
363 
OnIOComplete(int result)364 void HttpStreamParser::OnIOComplete(int result) {
365   result = DoLoop(result);
366 
367   // The client callback can do anything, including destroying this class,
368   // so any pending callback must be issued after everything else is done.
369   if (result != ERR_IO_PENDING && !callback_.is_null()) {
370     std::move(callback_).Run(result);
371   }
372 }
373 
DoLoop(int result)374 int HttpStreamParser::DoLoop(int result) {
375   do {
376     DCHECK_NE(ERR_IO_PENDING, result);
377     DCHECK_NE(STATE_DONE, io_state_);
378     DCHECK_NE(STATE_NONE, io_state_);
379     State state = io_state_;
380     io_state_ = STATE_NONE;
381     switch (state) {
382       case STATE_SEND_HEADERS:
383         DCHECK_EQ(OK, result);
384         result = DoSendHeaders();
385         DCHECK_NE(STATE_NONE, io_state_);
386         break;
387       case STATE_SEND_HEADERS_COMPLETE:
388         result = DoSendHeadersComplete(result);
389         DCHECK_NE(STATE_NONE, io_state_);
390         break;
391       case STATE_SEND_BODY:
392         DCHECK_EQ(OK, result);
393         result = DoSendBody();
394         DCHECK_NE(STATE_NONE, io_state_);
395         break;
396       case STATE_SEND_BODY_COMPLETE:
397         result = DoSendBodyComplete(result);
398         DCHECK_NE(STATE_NONE, io_state_);
399         break;
400       case STATE_SEND_REQUEST_READ_BODY_COMPLETE:
401         result = DoSendRequestReadBodyComplete(result);
402         DCHECK_NE(STATE_NONE, io_state_);
403         break;
404       case STATE_SEND_REQUEST_COMPLETE:
405         result = DoSendRequestComplete(result);
406         break;
407       case STATE_READ_HEADERS:
408         net_log_.BeginEvent(NetLogEventType::HTTP_STREAM_PARSER_READ_HEADERS);
409         DCHECK_GE(result, 0);
410         result = DoReadHeaders();
411         break;
412       case STATE_READ_HEADERS_COMPLETE:
413         result = DoReadHeadersComplete(result);
414         net_log_.EndEventWithNetErrorCode(
415             NetLogEventType::HTTP_STREAM_PARSER_READ_HEADERS, result);
416         break;
417       case STATE_READ_BODY:
418         DCHECK_GE(result, 0);
419         result = DoReadBody();
420         break;
421       case STATE_READ_BODY_COMPLETE:
422         result = DoReadBodyComplete(result);
423         break;
424       default:
425         NOTREACHED();
426         break;
427     }
428   } while (result != ERR_IO_PENDING &&
429            (io_state_ != STATE_DONE && io_state_ != STATE_NONE));
430 
431   return result;
432 }
433 
DoSendHeaders()434 int HttpStreamParser::DoSendHeaders() {
435   int bytes_remaining = request_headers_->BytesRemaining();
436   DCHECK_GT(bytes_remaining, 0);
437 
438   // Record our best estimate of the 'request time' as the time when we send
439   // out the first bytes of the request headers.
440   if (bytes_remaining == request_headers_->size())
441     response_->request_time = base::Time::Now();
442 
443   io_state_ = STATE_SEND_HEADERS_COMPLETE;
444   return stream_socket_->Write(
445       request_headers_.get(), bytes_remaining, io_callback_,
446       NetworkTrafficAnnotationTag(traffic_annotation_));
447 }
448 
DoSendHeadersComplete(int result)449 int HttpStreamParser::DoSendHeadersComplete(int result) {
450   if (result < 0) {
451     // In the unlikely case that the headers and body were merged, all the
452     // the headers were sent, but not all of the body way, and |result| is
453     // an error that this should try reading after, stash the error for now and
454     // act like the request was successfully sent.
455     io_state_ = STATE_SEND_REQUEST_COMPLETE;
456     if (request_headers_->BytesConsumed() >= request_headers_length_ &&
457         ShouldTryReadingOnUploadError(result)) {
458       upload_error_ = result;
459       return OK;
460     }
461     return result;
462   }
463 
464   sent_bytes_ += result;
465   request_headers_->DidConsume(result);
466   if (request_headers_->BytesRemaining() > 0) {
467     io_state_ = STATE_SEND_HEADERS;
468     return OK;
469   }
470 
471   if (request_->upload_data_stream != nullptr &&
472       (request_->upload_data_stream->is_chunked() ||
473        // !IsEOF() indicates that the body wasn't merged.
474        (request_->upload_data_stream->size() > 0 &&
475         !request_->upload_data_stream->IsEOF()))) {
476     NetLogSendRequestBody(net_log_, request_->upload_data_stream->size(),
477                           request_->upload_data_stream->is_chunked(),
478                           false /* not merged */);
479     io_state_ = STATE_SEND_BODY;
480     return OK;
481   }
482 
483   // Finished sending the request.
484   io_state_ = STATE_SEND_REQUEST_COMPLETE;
485   return OK;
486 }
487 
DoSendBody()488 int HttpStreamParser::DoSendBody() {
489   if (request_body_send_buf_->BytesRemaining() > 0) {
490     io_state_ = STATE_SEND_BODY_COMPLETE;
491     return stream_socket_->Write(
492         request_body_send_buf_.get(), request_body_send_buf_->BytesRemaining(),
493         io_callback_, NetworkTrafficAnnotationTag(traffic_annotation_));
494   }
495 
496   if (request_->upload_data_stream->is_chunked() && sent_last_chunk_) {
497     // Finished sending the request.
498     io_state_ = STATE_SEND_REQUEST_COMPLETE;
499     return OK;
500   }
501 
502   request_body_read_buf_->Clear();
503   io_state_ = STATE_SEND_REQUEST_READ_BODY_COMPLETE;
504   return request_->upload_data_stream->Read(
505       request_body_read_buf_.get(), request_body_read_buf_->capacity(),
506       base::BindOnce(&HttpStreamParser::OnIOComplete,
507                      weak_ptr_factory_.GetWeakPtr()));
508 }
509 
DoSendBodyComplete(int result)510 int HttpStreamParser::DoSendBodyComplete(int result) {
511   if (result < 0) {
512     // If |result| is an error that this should try reading after, stash the
513     // error for now and act like the request was successfully sent.
514     io_state_ = STATE_SEND_REQUEST_COMPLETE;
515     if (ShouldTryReadingOnUploadError(result)) {
516       upload_error_ = result;
517       return OK;
518     }
519     return result;
520   }
521 
522   sent_bytes_ += result;
523   request_body_send_buf_->DidConsume(result);
524 
525   io_state_ = STATE_SEND_BODY;
526   return OK;
527 }
528 
DoSendRequestReadBodyComplete(int result)529 int HttpStreamParser::DoSendRequestReadBodyComplete(int result) {
530   // |result| is the result of read from the request body from the last call to
531   // DoSendBody().
532   if (result < 0) {
533     io_state_ = STATE_SEND_REQUEST_COMPLETE;
534     return result;
535   }
536 
537   // Chunked data needs to be encoded.
538   if (request_->upload_data_stream->is_chunked()) {
539     if (result == 0) {  // Reached the end.
540       DCHECK(request_->upload_data_stream->IsEOF());
541       sent_last_chunk_ = true;
542     }
543     // Encode the buffer as 1 chunk.
544     const base::StringPiece payload(request_body_read_buf_->data(), result);
545     request_body_send_buf_->Clear();
546     result = EncodeChunk(payload,
547                          request_body_send_buf_->data(),
548                          request_body_send_buf_->capacity());
549   }
550 
551   if (result == 0) {  // Reached the end.
552     // Reaching EOF means we can finish sending request body unless the data is
553     // chunked. (i.e. No need to send the terminal chunk.)
554     DCHECK(request_->upload_data_stream->IsEOF());
555     DCHECK(!request_->upload_data_stream->is_chunked());
556     // Finished sending the request.
557     io_state_ = STATE_SEND_REQUEST_COMPLETE;
558   } else if (result > 0) {
559     request_body_send_buf_->DidAppend(result);
560     result = 0;
561     io_state_ = STATE_SEND_BODY;
562   }
563   return result;
564 }
565 
DoSendRequestComplete(int result)566 int HttpStreamParser::DoSendRequestComplete(int result) {
567   DCHECK_NE(result, ERR_IO_PENDING);
568   request_headers_ = nullptr;
569   request_body_send_buf_ = nullptr;
570   request_body_read_buf_ = nullptr;
571 
572   return result;
573 }
574 
DoReadHeaders()575 int HttpStreamParser::DoReadHeaders() {
576   io_state_ = STATE_READ_HEADERS_COMPLETE;
577 
578   // Grow the read buffer if necessary.
579   if (read_buf_->RemainingCapacity() == 0)
580     read_buf_->SetCapacity(read_buf_->capacity() + kHeaderBufInitialSize);
581 
582   // http://crbug.com/16371: We're seeing |user_buf_->data()| return NULL.
583   // See if the user is passing in an IOBuffer with a NULL |data_|.
584   CHECK(read_buf_->data());
585 
586   return stream_socket_->Read(read_buf_.get(), read_buf_->RemainingCapacity(),
587                               io_callback_);
588 }
589 
DoReadHeadersComplete(int result)590 int HttpStreamParser::DoReadHeadersComplete(int result) {
591   // DoReadHeadersComplete is called with the result of Socket::Read, which is a
592   // (byte_count | error), and returns (error | OK).
593 
594   result = HandleReadHeaderResult(result);
595 
596   // TODO(mmenke):  The code below is ugly and hacky.  A much better and more
597   // flexible long term solution would be to separate out the read and write
598   // loops, though this would involve significant changes, both here and
599   // elsewhere (WebSockets, for instance).
600 
601   // If still reading the headers, or there was no error uploading the request
602   // body, just return the result.
603   if (io_state_ == STATE_READ_HEADERS || upload_error_ == OK)
604     return result;
605 
606   // If the result is ERR_IO_PENDING, |io_state_| should be STATE_READ_HEADERS.
607   DCHECK_NE(ERR_IO_PENDING, result);
608 
609   // On errors, use the original error received when sending the request.
610   // The main cases where these are different is when there's a header-related
611   // error code, or when there's an ERR_CONNECTION_CLOSED, which can result in
612   // special handling of partial responses and HTTP/0.9 responses.
613   if (result < 0) {
614     // Nothing else to do.  In the HTTP/0.9 or only partial headers received
615     // cases, can normally go to other states after an error reading headers.
616     io_state_ = STATE_DONE;
617     // Don't let caller see the headers.
618     response_->headers = nullptr;
619     return upload_error_;
620   }
621 
622   // Skip over 1xx responses as usual, and allow 4xx/5xx error responses to
623   // override the error received while uploading the body.
624   int response_code_class = response_->headers->response_code() / 100;
625   if (response_code_class == 1 || response_code_class == 4 ||
626       response_code_class == 5) {
627     return result;
628   }
629 
630   // All other status codes are not allowed after an error during upload, to
631   // make sure the consumer has some indication there was an error.
632 
633   // Nothing else to do.
634   io_state_ = STATE_DONE;
635   // Don't let caller see the headers.
636   response_->headers = nullptr;
637   return upload_error_;
638 }
639 
DoReadBody()640 int HttpStreamParser::DoReadBody() {
641   io_state_ = STATE_READ_BODY_COMPLETE;
642 
643   // Added to investigate crbug.com/499663.
644   CHECK(user_read_buf_.get());
645 
646   // There may be some data left over from reading the response headers.
647   if (read_buf_->offset()) {
648     int available = read_buf_->offset() - read_buf_unused_offset_;
649     if (available) {
650       CHECK_GT(available, 0);
651       int bytes_from_buffer = std::min(available, user_read_buf_len_);
652       memcpy(user_read_buf_->data(),
653              read_buf_->StartOfBuffer() + read_buf_unused_offset_,
654              bytes_from_buffer);
655       read_buf_unused_offset_ += bytes_from_buffer;
656       if (bytes_from_buffer == available) {
657         read_buf_->SetCapacity(0);
658         read_buf_unused_offset_ = 0;
659       }
660       return bytes_from_buffer;
661     } else {
662       read_buf_->SetCapacity(0);
663       read_buf_unused_offset_ = 0;
664     }
665   }
666 
667   // Check to see if we're done reading.
668   if (IsResponseBodyComplete())
669     return 0;
670 
671   DCHECK_EQ(0, read_buf_->offset());
672   return stream_socket_->Read(user_read_buf_.get(), user_read_buf_len_,
673                               io_callback_);
674 }
675 
DoReadBodyComplete(int result)676 int HttpStreamParser::DoReadBodyComplete(int result) {
677   // When the connection is closed, there are numerous ways to interpret it.
678   //
679   //  - If a Content-Length header is present and the body contains exactly that
680   //    number of bytes at connection close, the response is successful.
681   //
682   //  - If a Content-Length header is present and the body contains fewer bytes
683   //    than promised by the header at connection close, it may indicate that
684   //    the connection was closed prematurely, or it may indicate that the
685   //    server sent an invalid Content-Length header. Unfortunately, the invalid
686   //    Content-Length header case does occur in practice and other browsers are
687   //    tolerant of it. We choose to treat it as an error for now, but the
688   //    download system treats it as a non-error, and URLRequestHttpJob also
689   //    treats it as OK if the Content-Length is the post-decoded body content
690   //    length.
691   //
692   //  - If chunked encoding is used and the terminating chunk has been processed
693   //    when the connection is closed, the response is successful.
694   //
695   //  - If chunked encoding is used and the terminating chunk has not been
696   //    processed when the connection is closed, it may indicate that the
697   //    connection was closed prematurely or it may indicate that the server
698   //    sent an invalid chunked encoding. We choose to treat it as
699   //    an invalid chunked encoding.
700   //
701   //  - If a Content-Length is not present and chunked encoding is not used,
702   //    connection close is the only way to signal that the response is
703   //    complete. Unfortunately, this also means that there is no way to detect
704   //    early close of a connection. No error is returned.
705   if (result == 0 && !IsResponseBodyComplete() && CanFindEndOfResponse()) {
706     if (chunked_decoder_.get())
707       result = ERR_INCOMPLETE_CHUNKED_ENCODING;
708     else
709       result = ERR_CONTENT_LENGTH_MISMATCH;
710   }
711 
712   if (result > 0)
713     received_bytes_ += result;
714 
715   // Filter incoming data if appropriate.  FilterBuf may return an error.
716   if (result > 0 && chunked_decoder_.get()) {
717     result = chunked_decoder_->FilterBuf(user_read_buf_->data(), result);
718     if (result == 0 && !chunked_decoder_->reached_eof()) {
719       // Don't signal completion of the Read call yet or else it'll look like
720       // we received end-of-file.  Wait for more data.
721       io_state_ = STATE_READ_BODY;
722       return OK;
723     }
724   }
725 
726   if (result > 0)
727     response_body_read_ += result;
728 
729   if (result <= 0 || IsResponseBodyComplete()) {
730     io_state_ = STATE_DONE;
731 
732     // Save the overflow data, which can be in two places.  There may be
733     // some left over in |user_read_buf_|, plus there may be more
734     // in |read_buf_|.  But the part left over in |user_read_buf_| must have
735     // come from the |read_buf_|, so there's room to put it back at the
736     // start first.
737     int additional_save_amount = read_buf_->offset() - read_buf_unused_offset_;
738     int save_amount = 0;
739     if (chunked_decoder_.get()) {
740       save_amount = chunked_decoder_->bytes_after_eof();
741     } else if (response_body_length_ >= 0) {
742       int64_t extra_data_read = response_body_read_ - response_body_length_;
743       if (extra_data_read > 0) {
744         save_amount = static_cast<int>(extra_data_read);
745         if (result > 0)
746           result -= save_amount;
747       }
748     }
749 
750     CHECK_LE(save_amount + additional_save_amount, kMaxBufSize);
751     if (read_buf_->capacity() < save_amount + additional_save_amount) {
752       read_buf_->SetCapacity(save_amount + additional_save_amount);
753     }
754 
755     if (save_amount) {
756       received_bytes_ -= save_amount;
757       memcpy(read_buf_->StartOfBuffer(), user_read_buf_->data() + result,
758              save_amount);
759     }
760     read_buf_->set_offset(save_amount);
761     if (additional_save_amount) {
762       memmove(read_buf_->data(),
763               read_buf_->StartOfBuffer() + read_buf_unused_offset_,
764               additional_save_amount);
765       read_buf_->set_offset(save_amount + additional_save_amount);
766     }
767     read_buf_unused_offset_ = 0;
768   } else {
769     // Now waiting for more of the body to be read.
770     user_read_buf_ = nullptr;
771     user_read_buf_len_ = 0;
772   }
773 
774   return result;
775 }
776 
HandleReadHeaderResult(int result)777 int HttpStreamParser::HandleReadHeaderResult(int result) {
778   DCHECK_EQ(0, read_buf_unused_offset_);
779 
780   if (result == 0)
781     result = ERR_CONNECTION_CLOSED;
782 
783   if (result == ERR_CONNECTION_CLOSED) {
784     // The connection closed without getting any more data.
785     if (read_buf_->offset() == 0) {
786       io_state_ = STATE_DONE;
787       // If the connection has not been reused, it may have been a 0-length
788       // HTTP/0.9 responses, but it was most likely an error, so just return
789       // ERR_EMPTY_RESPONSE instead. If the connection was reused, just pass
790       // on the original connection close error, as rather than being an
791       // empty HTTP/0.9 response it's much more likely the server closed the
792       // socket before it received the request.
793       if (!connection_is_reused_)
794         return ERR_EMPTY_RESPONSE;
795       return result;
796     }
797 
798     // Accepting truncated headers over HTTPS is a potential security
799     // vulnerability, so just return an error in that case.
800     //
801     // If response_header_start_offset_ is std::string::npos, this may be a < 8
802     // byte HTTP/0.9 response. However, accepting such a response over HTTPS
803     // would allow a MITM to truncate an HTTP/1.x status line to look like a
804     // short HTTP/0.9 response if the peer put a record boundary at the first 8
805     // bytes. To ensure that all response headers received over HTTPS are
806     // pristine, treat such responses as errors.
807     //
808     // TODO(mmenke):  Returning ERR_RESPONSE_HEADERS_TRUNCATED when a response
809     // looks like an HTTP/0.9 response is weird.  Should either come up with
810     // another error code, or, better, disable HTTP/0.9 over HTTPS (and give
811     // that a new error code).
812     if (request_->url.SchemeIsCryptographic()) {
813       io_state_ = STATE_DONE;
814       return ERR_RESPONSE_HEADERS_TRUNCATED;
815     }
816 
817     // Parse things as well as we can and let the caller decide what to do.
818     int end_offset;
819     if (response_header_start_offset_ != std::string::npos) {
820       // The response looks to be a truncated set of HTTP headers.
821       io_state_ = STATE_READ_BODY_COMPLETE;
822       end_offset = read_buf_->offset();
823     } else {
824       // The response is apparently using HTTP/0.9.  Treat the entire response
825       // as the body.
826       end_offset = 0;
827     }
828     int rv = ParseResponseHeaders(end_offset);
829     if (rv < 0)
830       return rv;
831     return result;
832   }
833 
834   if (result < 0) {
835     io_state_ = STATE_DONE;
836     return result;
837   }
838 
839   // Record our best estimate of the 'response time' as the time when we read
840   // the first bytes of the response headers.
841   if (read_buf_->offset() == 0) {
842     response_->response_time = base::Time::Now();
843     // Also keep the time as base::TimeTicks for `first_response_start_time_`
844     // and `non_informational_response_start_time_`.
845     current_response_start_time_ = base::TimeTicks::Now();
846   }
847 
848   // For |first_response_start_time_|, use the time that we received the first
849   // byte of *any* response- including 1XX, as per the resource timing spec for
850   // responseStart (see note at
851   // https://www.w3.org/TR/resource-timing-2/#dom-performanceresourcetiming-responsestart).
852   if (first_response_start_time_.is_null())
853     first_response_start_time_ = current_response_start_time_;
854 
855   read_buf_->set_offset(read_buf_->offset() + result);
856   DCHECK_LE(read_buf_->offset(), read_buf_->capacity());
857   DCHECK_GT(result, 0);
858 
859   int end_of_header_offset = FindAndParseResponseHeaders(result);
860 
861   // Note: -1 is special, it indicates we haven't found the end of headers.
862   // Anything less than -1 is a net::Error, so we bail out.
863   if (end_of_header_offset < -1)
864     return end_of_header_offset;
865 
866   if (end_of_header_offset == -1) {
867     io_state_ = STATE_READ_HEADERS;
868     // Prevent growing the headers buffer indefinitely.
869     if (read_buf_->offset() >= kMaxHeaderBufSize) {
870       io_state_ = STATE_DONE;
871       return ERR_RESPONSE_HEADERS_TOO_BIG;
872     }
873   } else {
874     CalculateResponseBodySize();
875 
876     // If the body is zero length, the caller may not call ReadResponseBody,
877     // which is where any extra data is copied to read_buf_, so we move the
878     // data here.
879     if (response_body_length_ == 0) {
880       int extra_bytes = read_buf_->offset() - end_of_header_offset;
881       if (extra_bytes) {
882         CHECK_GT(extra_bytes, 0);
883         memmove(read_buf_->StartOfBuffer(),
884                 read_buf_->StartOfBuffer() + end_of_header_offset,
885                 extra_bytes);
886       }
887       read_buf_->SetCapacity(extra_bytes);
888       if (response_->headers->response_code() / 100 == 1) {
889         // After processing a 1xx response, the caller will ask for the next
890         // header, so reset state to support that. We don't completely ignore a
891         // 1xx response because it cannot be returned in reply to a CONNECT
892         // request so we return OK here, which lets the caller inspect the
893         // response and reject it in the event that we're setting up a CONNECT
894         // tunnel.
895         response_header_start_offset_ = std::string::npos;
896         response_body_length_ = -1;
897         // Record the timing of the 103 Early Hints response for the experiment
898         // (https://crbug.com/1093693).
899         if (response_->headers->response_code() == net::HTTP_EARLY_HINTS &&
900             first_early_hints_time_.is_null()) {
901           first_early_hints_time_ = current_response_start_time_;
902         }
903         // Now waiting for the second set of headers to be read.
904       } else {
905         // Only set keep-alive based on final set of headers.
906         response_is_keep_alive_ = response_->headers->IsKeepAlive();
907 
908         io_state_ = STATE_DONE;
909       }
910       return OK;
911     }
912 
913     // Record the response start time if this response is not informational
914     // (non-1xx).
915     if (response_->headers->response_code() / 100 != 1) {
916       DCHECK(non_informational_response_start_time_.is_null());
917       non_informational_response_start_time_ = current_response_start_time_;
918     }
919 
920     // Only set keep-alive based on final set of headers.
921     response_is_keep_alive_ = response_->headers->IsKeepAlive();
922 
923     // Note where the headers stop.
924     read_buf_unused_offset_ = end_of_header_offset;
925     // Now waiting for the body to be read.
926   }
927   return OK;
928 }
929 
RunConfirmHandshakeCallback(int rv)930 void HttpStreamParser::RunConfirmHandshakeCallback(int rv) {
931   std::move(confirm_handshake_callback_).Run(rv);
932 }
933 
FindAndParseResponseHeaders(int new_bytes)934 int HttpStreamParser::FindAndParseResponseHeaders(int new_bytes) {
935   DCHECK_GT(new_bytes, 0);
936   DCHECK_EQ(0, read_buf_unused_offset_);
937   size_t end_offset = std::string::npos;
938 
939   // Look for the start of the status line, if it hasn't been found yet.
940   if (response_header_start_offset_ == std::string::npos) {
941     response_header_start_offset_ = HttpUtil::LocateStartOfStatusLine(
942         read_buf_->StartOfBuffer(), read_buf_->offset());
943   }
944 
945   if (response_header_start_offset_ != std::string::npos) {
946     // LocateEndOfHeaders looks for two line breaks in a row (With or without
947     // carriage returns). So the end of the headers includes at most the last 3
948     // bytes of the buffer from the past read. This optimization avoids O(n^2)
949     // performance in the case each read only returns a couple bytes. It's not
950     // too important in production, but for fuzzers with memory instrumentation,
951     // it's needed to avoid timing out.
952     size_t lower_bound =
953         (base::ClampedNumeric<size_t>(read_buf_->offset()) - new_bytes - 3)
954             .RawValue();
955     size_t search_start = std::max(response_header_start_offset_, lower_bound);
956     end_offset = HttpUtil::LocateEndOfHeaders(
957         read_buf_->StartOfBuffer(), read_buf_->offset(), search_start);
958   } else if (read_buf_->offset() >= 8) {
959     // Enough data to decide that this is an HTTP/0.9 response.
960     // 8 bytes = (4 bytes of junk) + "http".length()
961     end_offset = 0;
962   }
963 
964   if (end_offset == std::string::npos)
965     return -1;
966 
967   int rv = ParseResponseHeaders(end_offset);
968   if (rv < 0)
969     return rv;
970   return end_offset;
971 }
972 
ParseResponseHeaders(int end_offset)973 int HttpStreamParser::ParseResponseHeaders(int end_offset) {
974   scoped_refptr<HttpResponseHeaders> headers;
975   DCHECK_EQ(0, read_buf_unused_offset_);
976 
977   if (response_header_start_offset_ != std::string::npos) {
978     received_bytes_ += end_offset;
979     headers = HttpResponseHeaders::TryToCreate(
980         base::StringPiece(read_buf_->StartOfBuffer(), end_offset));
981     if (!headers)
982       return net::ERR_INVALID_HTTP_RESPONSE;
983     has_seen_status_line_ = true;
984   } else {
985     // Enough data was read -- there is no status line, so this is HTTP/0.9, or
986     // the server is broken / doesn't speak HTTP.
987 
988     if (has_seen_status_line_) {
989       // If we saw a status line previously, the server can speak HTTP/1.x so it
990       // is not reasonable to interpret the response as an HTTP/0.9 response.
991       return ERR_INVALID_HTTP_RESPONSE;
992     }
993 
994     base::StringPiece scheme = request_->url.scheme_piece();
995     if (url::DefaultPortForScheme(scheme.data(), scheme.length()) !=
996         request_->url.EffectiveIntPort()) {
997       // If the port is not the default for the scheme, assume it's not a real
998       // HTTP/0.9 response, and fail the request.
999 
1000       // Allow Shoutcast responses over HTTP, as it's somewhat common and relies
1001       // on HTTP/0.9 on weird ports to work.
1002       // See
1003       // https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/qS63pYso4P0
1004       if (read_buf_->offset() < 3 || scheme != "http" ||
1005           !base::EqualsCaseInsensitiveASCII(
1006               base::StringPiece(read_buf_->StartOfBuffer(), 3), "icy")) {
1007         return ERR_INVALID_HTTP_RESPONSE;
1008       }
1009     }
1010 
1011     headers = base::MakeRefCounted<HttpResponseHeaders>(
1012         std::string("HTTP/0.9 200 OK"));
1013   }
1014 
1015   // Check for multiple Content-Length headers when the response is not
1016   // chunked-encoded.  If they exist, and have distinct values, it's a potential
1017   // response smuggling attack.
1018   if (!headers->IsChunkEncoded()) {
1019     if (HttpUtil::HeadersContainMultipleCopiesOfField(*headers,
1020                                                       "Content-Length"))
1021       return ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH;
1022   }
1023 
1024   // Check for multiple Content-Disposition or Location headers.  If they exist,
1025   // it's also a potential response smuggling attack.
1026   if (HttpUtil::HeadersContainMultipleCopiesOfField(*headers,
1027                                                     "Content-Disposition"))
1028     return ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION;
1029   if (HttpUtil::HeadersContainMultipleCopiesOfField(*headers, "Location"))
1030     return ERR_RESPONSE_HEADERS_MULTIPLE_LOCATION;
1031 
1032   response_->headers = headers;
1033   if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
1034     response_->connection_info = HttpResponseInfo::CONNECTION_INFO_HTTP0_9;
1035   } else if (headers->GetHttpVersion() == HttpVersion(1, 0)) {
1036     response_->connection_info = HttpResponseInfo::CONNECTION_INFO_HTTP1_0;
1037   } else if (headers->GetHttpVersion() == HttpVersion(1, 1)) {
1038     response_->connection_info = HttpResponseInfo::CONNECTION_INFO_HTTP1_1;
1039   }
1040   DVLOG(1) << __func__ << "() content_length = \""
1041            << response_->headers->GetContentLength() << "\n\""
1042            << " headers = \"" << GetResponseHeaderLines(*response_->headers)
1043            << "\"";
1044   return OK;
1045 }
1046 
CalculateResponseBodySize()1047 void HttpStreamParser::CalculateResponseBodySize() {
1048   // Figure how to determine EOF:
1049 
1050   // For certain responses, we know the content length is always 0. From
1051   // RFC 7230 Section 3.3 Message Body:
1052   //
1053   // The presence of a message body in a response depends on both the
1054   // request method to which it is responding and the response status code
1055   // (Section 3.1.2).  Responses to the HEAD request method (Section 4.3.2
1056   // of [RFC7231]) never include a message body because the associated
1057   // response header fields (e.g., Transfer-Encoding, Content-Length,
1058   // etc.), if present, indicate only what their values would have been if
1059   // the request method had been GET (Section 4.3.1 of [RFC7231]). 2xx
1060   // (Successful) responses to a CONNECT request method (Section 4.3.6 of
1061   // [RFC7231]) switch to tunnel mode instead of having a message body.
1062   // All 1xx (Informational), 204 (No Content), and 304 (Not Modified)
1063   // responses do not include a message body.  All other responses do
1064   // include a message body, although the body might be of zero length.
1065   //
1066   // From RFC 7231 Section 6.3.6 205 Reset Content:
1067   //
1068   // Since the 205 status code implies that no additional content will be
1069   // provided, a server MUST NOT generate a payload in a 205 response.
1070   if (response_->headers->response_code() / 100 == 1) {
1071     response_body_length_ = 0;
1072   } else {
1073     switch (response_->headers->response_code()) {
1074       case net::HTTP_NO_CONTENT:     // No Content
1075       case net::HTTP_RESET_CONTENT:  // Reset Content
1076       case net::HTTP_NOT_MODIFIED:   // Not Modified
1077         response_body_length_ = 0;
1078         break;
1079     }
1080   }
1081   if (request_->method == "HEAD")
1082     response_body_length_ = 0;
1083 
1084   if (response_body_length_ == -1) {
1085     // "Transfer-Encoding: chunked" trumps "Content-Length: N"
1086     if (response_->headers->IsChunkEncoded()) {
1087       chunked_decoder_ = std::make_unique<HttpChunkedDecoder>();
1088     } else {
1089       response_body_length_ = response_->headers->GetContentLength();
1090       // If response_body_length_ is still -1, then we have to wait
1091       // for the server to close the connection.
1092     }
1093   }
1094 }
1095 
IsResponseBodyComplete() const1096 bool HttpStreamParser::IsResponseBodyComplete() const {
1097   if (chunked_decoder_.get())
1098     return chunked_decoder_->reached_eof();
1099   if (response_body_length_ != -1)
1100     return response_body_read_ >= response_body_length_;
1101 
1102   return false;  // Must read to EOF.
1103 }
1104 
CanFindEndOfResponse() const1105 bool HttpStreamParser::CanFindEndOfResponse() const {
1106   return chunked_decoder_.get() || response_body_length_ >= 0;
1107 }
1108 
IsMoreDataBuffered() const1109 bool HttpStreamParser::IsMoreDataBuffered() const {
1110   return read_buf_->offset() > read_buf_unused_offset_;
1111 }
1112 
CanReuseConnection() const1113 bool HttpStreamParser::CanReuseConnection() const {
1114   if (!CanFindEndOfResponse())
1115     return false;
1116 
1117   if (!response_is_keep_alive_)
1118     return false;
1119 
1120   // Check if extra data was received after reading the entire response body. If
1121   // extra data was received, reusing the socket is not a great idea. This does
1122   // have the down side of papering over certain server bugs, but seems to be
1123   // the best option here.
1124   //
1125   // TODO(mmenke): Consider logging this - hard to decipher socket reuse
1126   //     behavior makes NetLogs harder to read.
1127   if (IsResponseBodyComplete() && IsMoreDataBuffered())
1128     return false;
1129 
1130   return stream_socket_->IsConnected();
1131 }
1132 
OnConnectionClose()1133 void HttpStreamParser::OnConnectionClose() {
1134   // This is to ensure `stream_socket_` doesn't get dangling on connection
1135   // close.
1136   stream_socket_ = nullptr;
1137 }
1138 
GetSSLInfo(SSLInfo * ssl_info)1139 void HttpStreamParser::GetSSLInfo(SSLInfo* ssl_info) {
1140   if (!request_->url.SchemeIsCryptographic() ||
1141       !stream_socket_->GetSSLInfo(ssl_info)) {
1142     ssl_info->Reset();
1143   }
1144 }
1145 
GetSSLCertRequestInfo(SSLCertRequestInfo * cert_request_info)1146 void HttpStreamParser::GetSSLCertRequestInfo(
1147     SSLCertRequestInfo* cert_request_info) {
1148   cert_request_info->Reset();
1149   if (request_->url.SchemeIsCryptographic())
1150     stream_socket_->GetSSLCertRequestInfo(cert_request_info);
1151 }
1152 
EncodeChunk(base::StringPiece payload,char * output,size_t output_size)1153 int HttpStreamParser::EncodeChunk(base::StringPiece payload,
1154                                   char* output,
1155                                   size_t output_size) {
1156   if (output_size < payload.size() + kChunkHeaderFooterSize)
1157     return ERR_INVALID_ARGUMENT;
1158 
1159   char* cursor = output;
1160   // Add the header.
1161   const int num_chars = base::snprintf(output, output_size,
1162                                        "%X\r\n",
1163                                        static_cast<int>(payload.size()));
1164   cursor += num_chars;
1165   // Add the payload if any.
1166   if (payload.size() > 0) {
1167     memcpy(cursor, payload.data(), payload.size());
1168     cursor += payload.size();
1169   }
1170   // Add the trailing CRLF.
1171   memcpy(cursor, "\r\n", 2);
1172   cursor += 2;
1173 
1174   return cursor - output;
1175 }
1176 
1177 // static
ShouldMergeRequestHeadersAndBody(const std::string & request_headers,const UploadDataStream * request_body)1178 bool HttpStreamParser::ShouldMergeRequestHeadersAndBody(
1179     const std::string& request_headers,
1180     const UploadDataStream* request_body) {
1181   if (request_body != nullptr &&
1182       // IsInMemory() ensures that the request body is not chunked.
1183       request_body->IsInMemory() && request_body->size() > 0) {
1184     uint64_t merged_size = request_headers.size() + request_body->size();
1185     if (merged_size <= kMaxMergedHeaderAndBodySize)
1186       return true;
1187   }
1188   return false;
1189 }
1190 
SendRequestBuffersEmpty()1191 bool HttpStreamParser::SendRequestBuffersEmpty() {
1192   return request_headers_ == nullptr && request_body_send_buf_ == nullptr &&
1193          request_body_read_buf_ == nullptr;
1194 }
1195 
1196 }  // namespace net
1197