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 #ifndef NET_HTTP_HTTP_STREAM_PARSER_H_ 6 #define NET_HTTP_HTTP_STREAM_PARSER_H_ 7 8 #include <stddef.h> 9 #include <stdint.h> 10 11 #include <memory> 12 #include <string> 13 14 #include "base/memory/raw_ptr.h" 15 #include "base/memory/scoped_refptr.h" 16 #include "base/memory/weak_ptr.h" 17 #include "base/strings/string_piece.h" 18 #include "base/time/time.h" 19 #include "crypto/ec_private_key.h" 20 #include "net/base/completion_once_callback.h" 21 #include "net/base/completion_repeating_callback.h" 22 #include "net/base/net_errors.h" 23 #include "net/base/net_export.h" 24 #include "net/log/net_log_with_source.h" 25 #include "net/traffic_annotation/network_traffic_annotation.h" 26 27 namespace net { 28 29 class DrainableIOBuffer; 30 class GrowableIOBuffer; 31 class HttpChunkedDecoder; 32 struct HttpRequestInfo; 33 class HttpRequestHeaders; 34 class HttpResponseInfo; 35 class IOBuffer; 36 class SSLCertRequestInfo; 37 class StreamSocket; 38 class UploadDataStream; 39 40 class NET_EXPORT_PRIVATE HttpStreamParser { 41 public: 42 // |connection_is_reused| must be |true| if |stream_socket| has previously 43 // been used successfully for an HTTP/1.x request. 44 // 45 // Any data in |read_buffer| will be used before reading from the socket 46 // and any data left over after parsing the stream will be put into 47 // |read_buffer|. The left over data will start at offset 0 and the 48 // buffer's offset will be set to the first free byte. |read_buffer| may 49 // have its capacity changed. 50 // 51 // It is not safe to call into the HttpStreamParser after destroying the 52 // |stream_socket|. 53 HttpStreamParser(StreamSocket* stream_socket, 54 bool connection_is_reused, 55 const HttpRequestInfo* request, 56 GrowableIOBuffer* read_buffer, 57 const NetLogWithSource& net_log); 58 59 HttpStreamParser(const HttpStreamParser&) = delete; 60 HttpStreamParser& operator=(const HttpStreamParser&) = delete; 61 62 virtual ~HttpStreamParser(); 63 64 // These functions implement the interface described in HttpStream with 65 // some additional functionality 66 int SendRequest(const std::string& request_line, 67 const HttpRequestHeaders& headers, 68 const NetworkTrafficAnnotationTag& traffic_annotation, 69 HttpResponseInfo* response, 70 CompletionOnceCallback callback); 71 72 int ConfirmHandshake(CompletionOnceCallback callback); 73 74 int ReadResponseHeaders(CompletionOnceCallback callback); 75 76 int ReadResponseBody(IOBuffer* buf, 77 int buf_len, 78 CompletionOnceCallback callback); 79 80 bool IsResponseBodyComplete() const; 81 82 bool CanFindEndOfResponse() const; 83 84 bool IsMoreDataBuffered() const; 85 86 // Returns true if the underlying connection can be reused. 87 // The connection can be reused if: 88 // * It's still connected. 89 // * The response headers indicate the connection can be kept alive. 90 // * The end of the response can be found, though it may not have yet been 91 // received. 92 // 93 // Note that if response headers have yet to be received, this will return 94 // false. 95 bool CanReuseConnection() const; 96 97 // Called when stream is closed. 98 void OnConnectionClose(); 99 received_bytes()100 int64_t received_bytes() const { return received_bytes_; } 101 sent_bytes()102 int64_t sent_bytes() const { return sent_bytes_; } 103 first_response_start_time()104 base::TimeTicks first_response_start_time() const { 105 return first_response_start_time_; 106 } non_informational_response_start_time()107 base::TimeTicks non_informational_response_start_time() const { 108 return non_informational_response_start_time_; 109 } first_early_hints_time()110 base::TimeTicks first_early_hints_time() { return first_early_hints_time_; } 111 112 void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info); 113 114 // Encodes the given |payload| in the chunked format to |output|. 115 // Returns the number of bytes written to |output|. |output_size| should 116 // be large enough to store the encoded chunk, which is payload.size() + 117 // kChunkHeaderFooterSize. Returns ERR_INVALID_ARGUMENT if |output_size| 118 // is not large enough. 119 // 120 // The output will look like: "HEX\r\n[payload]\r\n" 121 // where HEX is a length in hexdecimal (without the "0x" prefix). 122 static int EncodeChunk(base::StringPiece payload, 123 char* output, 124 size_t output_size); 125 126 // Returns true if request headers and body should be merged (i.e. the 127 // sum is small enough and the body is in memory, and not chunked). 128 static bool ShouldMergeRequestHeadersAndBody( 129 const std::string& request_headers, 130 const UploadDataStream* request_body); 131 132 // The number of extra bytes required to encode a chunk. 133 static const size_t kChunkHeaderFooterSize; 134 135 private: 136 class SeekableIOBuffer; 137 138 // FOO_COMPLETE states implement the second half of potentially asynchronous 139 // operations and don't necessarily mean that FOO is complete. 140 enum State { 141 // STATE_NONE indicates that this is waiting on an external call before 142 // continuing. 143 STATE_NONE, 144 STATE_SEND_HEADERS, 145 STATE_SEND_HEADERS_COMPLETE, 146 STATE_SEND_BODY, 147 STATE_SEND_BODY_COMPLETE, 148 STATE_SEND_REQUEST_READ_BODY_COMPLETE, 149 STATE_SEND_REQUEST_COMPLETE, 150 STATE_READ_HEADERS, 151 STATE_READ_HEADERS_COMPLETE, 152 STATE_READ_BODY, 153 STATE_READ_BODY_COMPLETE, 154 STATE_DONE 155 }; 156 157 // The number of bytes by which the header buffer is grown when it reaches 158 // capacity. 159 static const int kHeaderBufInitialSize = 4 * 1024; // 4K 160 161 // |kMaxHeaderBufSize| is the number of bytes that the response headers can 162 // grow to. If the body start is not found within this range of the 163 // response, the transaction will fail with ERR_RESPONSE_HEADERS_TOO_BIG. 164 // Note: |kMaxHeaderBufSize| should be a multiple of |kHeaderBufInitialSize|. 165 static const int kMaxHeaderBufSize = kHeaderBufInitialSize * 64; // 256K 166 167 // The maximum sane buffer size. 168 static const int kMaxBufSize = 2 * 1024 * 1024; // 2M 169 170 // Handle callbacks. 171 void OnIOComplete(int result); 172 173 // Try to make progress sending/receiving the request/response. 174 int DoLoop(int result); 175 176 // The implementations of each state of the state machine. 177 int DoSendHeaders(); 178 int DoSendHeadersComplete(int result); 179 int DoSendBody(); 180 int DoSendBodyComplete(int result); 181 int DoSendRequestReadBodyComplete(int result); 182 int DoSendRequestComplete(int result); 183 int DoReadHeaders(); 184 int DoReadHeadersComplete(int result); 185 int DoReadBody(); 186 int DoReadBodyComplete(int result); 187 188 // This handles most of the logic for DoReadHeadersComplete. 189 int HandleReadHeaderResult(int result); 190 191 void RunConfirmHandshakeCallback(int rv); 192 193 // Examines |read_buf_| to find the start and end of the headers. If they are 194 // found, parse them with DoParseResponseHeaders(). Return the offset for 195 // the end of the headers, or -1 if the complete headers were not found, or 196 // with a net::Error if we encountered an error during parsing. 197 // 198 // |new_bytes| is the number of new bytes that have been appended to the end 199 // of |read_buf_| since the last call to this method (which must have returned 200 // -1). 201 int FindAndParseResponseHeaders(int new_bytes); 202 203 // Parse the headers into response_. Returns OK on success or a net::Error on 204 // failure. 205 int ParseResponseHeaders(int end_of_header_offset); 206 207 // Examine the parsed headers to try to determine the response body size. 208 void CalculateResponseBodySize(); 209 210 // Check if buffers used to send the request are empty. 211 bool SendRequestBuffersEmpty(); 212 213 // Next state of the request, when the current one completes. 214 State io_state_ = STATE_NONE; 215 216 // Null when read state machine is invoked. 217 raw_ptr<const HttpRequestInfo, AcrossTasksDanglingUntriaged> request_; 218 219 // The request header data. May include a merged request body. 220 scoped_refptr<DrainableIOBuffer> request_headers_; 221 222 // Size of just the request headers. May be less than the length of 223 // |request_headers_| if the body was merged with the headers. 224 int request_headers_length_ = 0; 225 226 // Temporary buffer for reading. 227 scoped_refptr<GrowableIOBuffer> read_buf_; 228 229 // Offset of the first unused byte in |read_buf_|. May be nonzero due to 230 // body data in the same packet as header data but is zero when reading 231 // headers. 232 int read_buf_unused_offset_ = 0; 233 234 // The amount beyond |read_buf_unused_offset_| where the status line starts; 235 // std::string::npos if not found yet. 236 size_t response_header_start_offset_; 237 238 // The amount of received data. If connection is reused then intermediate 239 // value may be bigger than final. 240 int64_t received_bytes_ = 0; 241 242 // The amount of sent data. 243 int64_t sent_bytes_ = 0; 244 245 // The parsed response headers. Owned by the caller of SendRequest. This 246 // cannot be safely accessed after reading the final set of headers, as the 247 // caller of SendRequest may have been destroyed - this happens in the case an 248 // HttpResponseBodyDrainer is used. 249 raw_ptr<HttpResponseInfo, AcrossTasksDanglingUntriaged> response_ = nullptr; 250 251 // Time at which the first bytes of the first header response including 252 // informational responses (1xx) are about to be parsed. This corresponds to 253 // |LoadTimingInfo::receive_headers_start|. See also comments there. 254 base::TimeTicks first_response_start_time_; 255 256 // Time at which the first bytes of the current header response are about to 257 // be parsed. This is reset every time new response headers including 258 // non-informational responses (1xx) are parsed. 259 base::TimeTicks current_response_start_time_; 260 261 // Time at which the first byte of the non-informational header response 262 // (non-1xx) are about to be parsed. This corresponds to 263 // |LoadTimingInfo::receive_non_informational_headers_start|. See also 264 // comments there. 265 base::TimeTicks non_informational_response_start_time_; 266 267 // Time at which the first 103 Early Hints response is received. This 268 // corresponds to |LoadTimingInfo::first_early_hints_time|. 269 base::TimeTicks first_early_hints_time_; 270 271 // Indicates the content length. If this value is less than zero 272 // (and chunked_decoder_ is null), then we must read until the server 273 // closes the connection. 274 int64_t response_body_length_ = -1; 275 276 // True if reading a keep-alive response. False if not, or if don't yet know. 277 bool response_is_keep_alive_ = false; 278 279 // True if we've seen a response that has an HTTP status line. This is 280 // persistent across multiple response parsing. If we see a status line 281 // for a response, this will remain true forever. 282 bool has_seen_status_line_ = false; 283 284 // Keep track of the number of response body bytes read so far. 285 int64_t response_body_read_ = 0; 286 287 // Helper if the data is chunked. 288 std::unique_ptr<HttpChunkedDecoder> chunked_decoder_; 289 290 // Where the caller wants the body data. 291 scoped_refptr<IOBuffer> user_read_buf_; 292 int user_read_buf_len_ = 0; 293 294 // The callback to notify a user that the handshake has been confirmed. 295 CompletionOnceCallback confirm_handshake_callback_; 296 297 // The callback to notify a user that their request or response is 298 // complete or there was an error 299 CompletionOnceCallback callback_; 300 301 // The underlying socket, owned by the caller. The HttpStreamParser must be 302 // destroyed before the caller destroys the socket, or relinquishes ownership 303 // of it. 304 raw_ptr<StreamSocket, AcrossTasksDanglingUntriaged> stream_socket_; 305 306 // Whether the socket has already been used. Only used in HTTP/0.9 detection 307 // logic. 308 const bool connection_is_reused_; 309 310 NetLogWithSource net_log_; 311 312 // Callback to be used when doing IO. 313 CompletionRepeatingCallback io_callback_; 314 315 // Buffer used to read the request body from UploadDataStream. 316 scoped_refptr<SeekableIOBuffer> request_body_read_buf_; 317 // Buffer used to send the request body. This points the same buffer as 318 // |request_body_read_buf_| unless the data is chunked. 319 scoped_refptr<SeekableIOBuffer> request_body_send_buf_; 320 bool sent_last_chunk_ = false; 321 322 // Error received when uploading the body, if any. 323 int upload_error_ = OK; 324 325 MutableNetworkTrafficAnnotationTag traffic_annotation_; 326 327 base::WeakPtrFactory<HttpStreamParser> weak_ptr_factory_{this}; 328 }; 329 330 } // namespace net 331 332 #endif // NET_HTTP_HTTP_STREAM_PARSER_H_ 333