blob: 76f998a0e97a78d3c9db169712bbdc6a197961e1 [file] [log] [blame]
[email protected]6db833d12012-01-21 00:45:191// Copyright (c) 2012 The Chromium Authors. All rights reserved.
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
[email protected]3cb5fc22013-12-12 19:40:567#include <algorithm>
8#include <string>
9#include <vector>
10
[email protected]57999812013-02-24 05:40:5211#include "base/files/file_path.h"
thestigd8df0332014-09-04 06:33:2912#include "base/files/file_util.h"
[email protected]ea1a3f62012-11-16 20:34:2313#include "base/files/scoped_temp_dir.h"
[email protected]4750937f2012-06-15 20:44:2114#include "base/memory/ref_counted.h"
[email protected]0f972882013-09-20 04:34:2015#include "base/run_loop.h"
[email protected]d069c11a2013-04-13 00:01:5516#include "base/strings/string_piece.h"
[email protected]125ef482013-06-11 18:32:4717#include "base/strings/stringprintf.h"
skyostil4891b25b2015-06-11 11:43:4518#include "base/thread_task_runner_handle.h"
mmenkecbc2b712014-10-09 20:29:0719#include "net/base/chunked_upload_data_stream.h"
20#include "net/base/elements_upload_data_stream.h"
[email protected]4750937f2012-06-15 20:44:2121#include "net/base/io_buffer.h"
[email protected]6db833d12012-01-21 00:45:1922#include "net/base/net_errors.h"
[email protected]4750937f2012-06-15 20:44:2123#include "net/base/test_completion_callback.h"
[email protected]b2d26cfd2012-12-11 10:36:0624#include "net/base/upload_bytes_element_reader.h"
[email protected]b2d26cfd2012-12-11 10:36:0625#include "net/base/upload_file_element_reader.h"
[email protected]4750937f2012-06-15 20:44:2126#include "net/http/http_request_headers.h"
27#include "net/http/http_request_info.h"
[email protected]df8e6382013-11-07 00:19:0628#include "net/http/http_response_headers.h"
[email protected]4750937f2012-06-15 20:44:2129#include "net/http/http_response_info.h"
30#include "net/socket/client_socket_handle.h"
31#include "net/socket/socket_test_util.h"
[email protected]6db833d12012-01-21 00:45:1932#include "testing/gtest/include/gtest/gtest.h"
[email protected]f89276a72013-07-12 06:41:5433#include "url/gurl.h"
[email protected]6db833d12012-01-21 00:45:1934
35namespace net {
36
[email protected]390489b2013-12-09 10:49:0137namespace {
38
[email protected]6db833d12012-01-21 00:45:1939const size_t kOutputSize = 1024; // Just large enough for this test.
40// The number of bytes that can fit in a buffer of kOutputSize.
41const size_t kMaxPayloadSize =
42 kOutputSize - HttpStreamParser::kChunkHeaderFooterSize;
43
mmenke3dc8c88b2015-02-19 15:11:2744// Helper method to create a connected ClientSocketHandle using |data|.
45// Modifies |data|.
46scoped_ptr<ClientSocketHandle> CreateConnectedSocketHandle(
mmenkef22be0ee2015-06-05 15:39:0247 SequencedSocketData* data) {
mmenke3dc8c88b2015-02-19 15:11:2748 data->set_connect_data(MockConnect(SYNCHRONOUS, OK));
49
mmenkef22be0ee2015-06-05 15:39:0250 scoped_ptr<MockTCPClientSocket> socket(
51 new MockTCPClientSocket(net::AddressList(), nullptr, data));
52 data->set_socket(socket.get());
mmenke3dc8c88b2015-02-19 15:11:2753
54 TestCompletionCallback callback;
mmenkef22be0ee2015-06-05 15:39:0255 EXPECT_EQ(OK, socket->Connect(callback.callback()));
mmenke3dc8c88b2015-02-19 15:11:2756
57 scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle);
mmenkef22be0ee2015-06-05 15:39:0258 socket_handle->SetSocket(socket.Pass());
mmenke3dc8c88b2015-02-19 15:11:2759 return socket_handle.Pass();
60}
61
[email protected]6db833d12012-01-21 00:45:1962// The empty payload is how the last chunk is encoded.
63TEST(HttpStreamParser, EncodeChunk_EmptyPayload) {
64 char output[kOutputSize];
65
66 const base::StringPiece kPayload = "";
67 const base::StringPiece kExpected = "0\r\n\r\n";
68 const int num_bytes_written =
69 HttpStreamParser::EncodeChunk(kPayload, output, sizeof(output));
70 ASSERT_EQ(kExpected.size(), static_cast<size_t>(num_bytes_written));
71 EXPECT_EQ(kExpected, base::StringPiece(output, num_bytes_written));
72}
73
74TEST(HttpStreamParser, EncodeChunk_ShortPayload) {
75 char output[kOutputSize];
76
77 const std::string kPayload("foo\x00\x11\x22", 6);
78 // 11 = payload size + sizeof("6") + CRLF x 2.
79 const std::string kExpected("6\r\nfoo\x00\x11\x22\r\n", 11);
80 const int num_bytes_written =
81 HttpStreamParser::EncodeChunk(kPayload, output, sizeof(output));
82 ASSERT_EQ(kExpected.size(), static_cast<size_t>(num_bytes_written));
83 EXPECT_EQ(kExpected, base::StringPiece(output, num_bytes_written));
84}
85
86TEST(HttpStreamParser, EncodeChunk_LargePayload) {
87 char output[kOutputSize];
88
89 const std::string kPayload(1000, '\xff'); // '\xff' x 1000.
90 // 3E8 = 1000 in hex.
91 const std::string kExpected = "3E8\r\n" + kPayload + "\r\n";
92 const int num_bytes_written =
93 HttpStreamParser::EncodeChunk(kPayload, output, sizeof(output));
94 ASSERT_EQ(kExpected.size(), static_cast<size_t>(num_bytes_written));
95 EXPECT_EQ(kExpected, base::StringPiece(output, num_bytes_written));
96}
97
98TEST(HttpStreamParser, EncodeChunk_FullPayload) {
99 char output[kOutputSize];
100
101 const std::string kPayload(kMaxPayloadSize, '\xff');
102 // 3F4 = 1012 in hex.
103 const std::string kExpected = "3F4\r\n" + kPayload + "\r\n";
104 const int num_bytes_written =
105 HttpStreamParser::EncodeChunk(kPayload, output, sizeof(output));
106 ASSERT_EQ(kExpected.size(), static_cast<size_t>(num_bytes_written));
107 EXPECT_EQ(kExpected, base::StringPiece(output, num_bytes_written));
108}
109
110TEST(HttpStreamParser, EncodeChunk_TooLargePayload) {
111 char output[kOutputSize];
112
113 // The payload is one byte larger the output buffer size.
114 const std::string kPayload(kMaxPayloadSize + 1, '\xff');
115 const int num_bytes_written =
116 HttpStreamParser::EncodeChunk(kPayload, output, sizeof(output));
117 ASSERT_EQ(ERR_INVALID_ARGUMENT, num_bytes_written);
118}
119
[email protected]75577ec2012-01-24 23:41:50120TEST(HttpStreamParser, ShouldMergeRequestHeadersAndBody_NoBody) {
[email protected]7a1fcff2012-01-24 01:07:49121 // Shouldn't be merged if upload data is non-existent.
[email protected]75577ec2012-01-24 23:41:50122 ASSERT_FALSE(HttpStreamParser::ShouldMergeRequestHeadersAndBody(
123 "some header", NULL));
[email protected]7a1fcff2012-01-24 01:07:49124}
125
[email protected]75577ec2012-01-24 23:41:50126TEST(HttpStreamParser, ShouldMergeRequestHeadersAndBody_EmptyBody) {
[email protected]b2d26cfd2012-12-11 10:36:06127 ScopedVector<UploadElementReader> element_readers;
[email protected]96c77a72013-09-24 09:49:20128 scoped_ptr<UploadDataStream> body(
mmenkecbc2b712014-10-09 20:29:07129 new ElementsUploadDataStream(element_readers.Pass(), 0));
[email protected]4db27d82012-12-20 11:50:24130 ASSERT_EQ(OK, body->Init(CompletionCallback()));
[email protected]7a1fcff2012-01-24 01:07:49131 // Shouldn't be merged if upload data is empty.
[email protected]75577ec2012-01-24 23:41:50132 ASSERT_FALSE(HttpStreamParser::ShouldMergeRequestHeadersAndBody(
133 "some header", body.get()));
[email protected]7a1fcff2012-01-24 01:07:49134}
135
[email protected]75577ec2012-01-24 23:41:50136TEST(HttpStreamParser, ShouldMergeRequestHeadersAndBody_ChunkedBody) {
[email protected]7a1fcff2012-01-24 01:07:49137 const std::string payload = "123";
mmenkecbc2b712014-10-09 20:29:07138 scoped_ptr<ChunkedUploadDataStream> body(new ChunkedUploadDataStream(0));
139 body->AppendData(payload.data(), payload.size(), true);
140 ASSERT_EQ(OK, body->Init(TestCompletionCallback().callback()));
[email protected]7a1fcff2012-01-24 01:07:49141 // Shouldn't be merged if upload data carries chunked data.
[email protected]75577ec2012-01-24 23:41:50142 ASSERT_FALSE(HttpStreamParser::ShouldMergeRequestHeadersAndBody(
143 "some header", body.get()));
[email protected]7a1fcff2012-01-24 01:07:49144}
145
[email protected]75577ec2012-01-24 23:41:50146TEST(HttpStreamParser, ShouldMergeRequestHeadersAndBody_FileBody) {
[email protected]0f972882013-09-20 04:34:20147 {
148 ScopedVector<UploadElementReader> element_readers;
[email protected]7a1fcff2012-01-24 01:07:49149
[email protected]0f972882013-09-20 04:34:20150 // Create an empty temporary file.
151 base::ScopedTempDir temp_dir;
152 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
153 base::FilePath temp_file_path;
[email protected]03d9afc02013-12-03 17:55:52154 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(),
155 &temp_file_path));
[email protected]7a1fcff2012-01-24 01:07:49156
[email protected]0f972882013-09-20 04:34:20157 element_readers.push_back(
skyostil4891b25b2015-06-11 11:43:45158 new UploadFileElementReader(base::ThreadTaskRunnerHandle::Get().get(),
159 temp_file_path, 0, 0, base::Time()));
[email protected]7a1fcff2012-01-24 01:07:49160
[email protected]0f972882013-09-20 04:34:20161 scoped_ptr<UploadDataStream> body(
mmenkecbc2b712014-10-09 20:29:07162 new ElementsUploadDataStream(element_readers.Pass(), 0));
[email protected]0f972882013-09-20 04:34:20163 TestCompletionCallback callback;
164 ASSERT_EQ(ERR_IO_PENDING, body->Init(callback.callback()));
165 ASSERT_EQ(OK, callback.WaitForResult());
166 // Shouldn't be merged if upload data carries a file, as it's not in-memory.
167 ASSERT_FALSE(HttpStreamParser::ShouldMergeRequestHeadersAndBody(
168 "some header", body.get()));
169 }
170 // UploadFileElementReaders may post clean-up tasks on destruction.
171 base::RunLoop().RunUntilIdle();
[email protected]7a1fcff2012-01-24 01:07:49172}
173
[email protected]75577ec2012-01-24 23:41:50174TEST(HttpStreamParser, ShouldMergeRequestHeadersAndBody_SmallBodyInMemory) {
[email protected]b2d26cfd2012-12-11 10:36:06175 ScopedVector<UploadElementReader> element_readers;
[email protected]7a1fcff2012-01-24 01:07:49176 const std::string payload = "123";
[email protected]b2d26cfd2012-12-11 10:36:06177 element_readers.push_back(new UploadBytesElementReader(
178 payload.data(), payload.size()));
[email protected]7a1fcff2012-01-24 01:07:49179
[email protected]96c77a72013-09-24 09:49:20180 scoped_ptr<UploadDataStream> body(
mmenkecbc2b712014-10-09 20:29:07181 new ElementsUploadDataStream(element_readers.Pass(), 0));
[email protected]4db27d82012-12-20 11:50:24182 ASSERT_EQ(OK, body->Init(CompletionCallback()));
[email protected]7a1fcff2012-01-24 01:07:49183 // Yes, should be merged if the in-memory body is small here.
[email protected]75577ec2012-01-24 23:41:50184 ASSERT_TRUE(HttpStreamParser::ShouldMergeRequestHeadersAndBody(
185 "some header", body.get()));
[email protected]7a1fcff2012-01-24 01:07:49186}
187
[email protected]75577ec2012-01-24 23:41:50188TEST(HttpStreamParser, ShouldMergeRequestHeadersAndBody_LargeBodyInMemory) {
[email protected]b2d26cfd2012-12-11 10:36:06189 ScopedVector<UploadElementReader> element_readers;
[email protected]7a1fcff2012-01-24 01:07:49190 const std::string payload(10000, 'a'); // 'a' x 10000.
[email protected]b2d26cfd2012-12-11 10:36:06191 element_readers.push_back(new UploadBytesElementReader(
192 payload.data(), payload.size()));
[email protected]7a1fcff2012-01-24 01:07:49193
[email protected]96c77a72013-09-24 09:49:20194 scoped_ptr<UploadDataStream> body(
mmenkecbc2b712014-10-09 20:29:07195 new ElementsUploadDataStream(element_readers.Pass(), 0));
[email protected]4db27d82012-12-20 11:50:24196 ASSERT_EQ(OK, body->Init(CompletionCallback()));
[email protected]7a1fcff2012-01-24 01:07:49197 // Shouldn't be merged if the in-memory body is large here.
[email protected]75577ec2012-01-24 23:41:50198 ASSERT_FALSE(HttpStreamParser::ShouldMergeRequestHeadersAndBody(
199 "some header", body.get()));
[email protected]7a1fcff2012-01-24 01:07:49200}
201
[email protected]4750937f2012-06-15 20:44:21202// Test to ensure the HttpStreamParser state machine does not get confused
mmenke3dc8c88b2015-02-19 15:11:27203// when sending a request with a chunked body with only one chunk that becomes
204// available asynchronously.
205TEST(HttpStreamParser, AsyncSingleChunkAndAsyncSocket) {
206 static const char kChunk[] = "Chunk";
207
208 MockWrite writes[] = {
209 MockWrite(ASYNC, 0,
210 "GET /one.html HTTP/1.1\r\n"
211 "Transfer-Encoding: chunked\r\n\r\n"),
212 MockWrite(ASYNC, 1, "5\r\nChunk\r\n"),
213 MockWrite(ASYNC, 2, "0\r\n\r\n"),
214 };
215
216 // The size of the response body, as reflected in the Content-Length of the
217 // MockRead below.
218 static const int kBodySize = 8;
219
220 MockRead reads[] = {
221 MockRead(ASYNC, 3, "HTTP/1.1 200 OK\r\n"),
222 MockRead(ASYNC, 4, "Content-Length: 8\r\n\r\n"),
223 MockRead(ASYNC, 5, "one.html"),
224 MockRead(SYNCHRONOUS, 0, 6), // EOF
225 };
226
227 ChunkedUploadDataStream upload_stream(0);
228 ASSERT_EQ(OK, upload_stream.Init(TestCompletionCallback().callback()));
229
mmenkef22be0ee2015-06-05 15:39:02230 SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes));
mmenke3dc8c88b2015-02-19 15:11:27231 scoped_ptr<ClientSocketHandle> socket_handle =
232 CreateConnectedSocketHandle(&data);
233
234 HttpRequestInfo request_info;
235 request_info.method = "GET";
236 request_info.url = GURL("http://localhost");
237 request_info.upload_data_stream = &upload_stream;
238
239 scoped_refptr<GrowableIOBuffer> read_buffer(new GrowableIOBuffer);
240 HttpStreamParser parser(socket_handle.get(), &request_info, read_buffer.get(),
241 BoundNetLog());
242
243 HttpRequestHeaders request_headers;
244 request_headers.SetHeader("Transfer-Encoding", "chunked");
245
246 HttpResponseInfo response_info;
247 TestCompletionCallback callback;
248 // This will attempt to Write() the initial request and headers, which will
249 // complete asynchronously.
250 ASSERT_EQ(ERR_IO_PENDING,
251 parser.SendRequest("GET /one.html HTTP/1.1\r\n", request_headers,
252 &response_info, callback.callback()));
253
mmenkef22be0ee2015-06-05 15:39:02254 // Complete the initial request write. Callback should not have been invoked.
255 base::RunLoop().RunUntilIdle();
mmenke3dc8c88b2015-02-19 15:11:27256 ASSERT_FALSE(callback.have_result());
257
mmenkef22be0ee2015-06-05 15:39:02258 // Now append the only chunk and wait for the callback.
mmenke3dc8c88b2015-02-19 15:11:27259 upload_stream.AppendData(kChunk, arraysize(kChunk) - 1, true);
mmenke3dc8c88b2015-02-19 15:11:27260 ASSERT_EQ(OK, callback.WaitForResult());
261
262 // Attempt to read the response status and the response headers.
263 ASSERT_EQ(ERR_IO_PENDING, parser.ReadResponseHeaders(callback.callback()));
mmenke3dc8c88b2015-02-19 15:11:27264 ASSERT_GT(callback.WaitForResult(), 0);
265
266 // Finally, attempt to read the response body.
267 scoped_refptr<IOBuffer> body_buffer(new IOBuffer(kBodySize));
268 ASSERT_EQ(ERR_IO_PENDING,
269 parser.ReadResponseBody(body_buffer.get(), kBodySize,
270 callback.callback()));
mmenke3dc8c88b2015-02-19 15:11:27271 ASSERT_EQ(kBodySize, callback.WaitForResult());
272}
273
274// Test to ensure the HttpStreamParser state machine does not get confused
275// when sending a request with a chunked body with only one chunk that is
276// available synchronously.
277TEST(HttpStreamParser, SyncSingleChunkAndAsyncSocket) {
278 static const char kChunk[] = "Chunk";
279
280 MockWrite writes[] = {
281 MockWrite(ASYNC, 0,
282 "GET /one.html HTTP/1.1\r\n"
283 "Transfer-Encoding: chunked\r\n\r\n"),
284 MockWrite(ASYNC, 1, "5\r\nChunk\r\n"),
285 MockWrite(ASYNC, 2, "0\r\n\r\n"),
286 };
287
288 // The size of the response body, as reflected in the Content-Length of the
289 // MockRead below.
290 static const int kBodySize = 8;
291
292 MockRead reads[] = {
293 MockRead(ASYNC, 3, "HTTP/1.1 200 OK\r\n"),
294 MockRead(ASYNC, 4, "Content-Length: 8\r\n\r\n"),
295 MockRead(ASYNC, 5, "one.html"),
296 MockRead(SYNCHRONOUS, 0, 6), // EOF
297 };
298
299 ChunkedUploadDataStream upload_stream(0);
300 ASSERT_EQ(OK, upload_stream.Init(TestCompletionCallback().callback()));
301 // Append the only chunk.
302 upload_stream.AppendData(kChunk, arraysize(kChunk) - 1, true);
303
mmenkef22be0ee2015-06-05 15:39:02304 SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes));
mmenke3dc8c88b2015-02-19 15:11:27305 scoped_ptr<ClientSocketHandle> socket_handle =
306 CreateConnectedSocketHandle(&data);
307
308 HttpRequestInfo request_info;
309 request_info.method = "GET";
310 request_info.url = GURL("http://localhost");
311 request_info.upload_data_stream = &upload_stream;
312
313 scoped_refptr<GrowableIOBuffer> read_buffer(new GrowableIOBuffer);
314 HttpStreamParser parser(socket_handle.get(), &request_info, read_buffer.get(),
315 BoundNetLog());
316
317 HttpRequestHeaders request_headers;
318 request_headers.SetHeader("Transfer-Encoding", "chunked");
319
320 HttpResponseInfo response_info;
321 TestCompletionCallback callback;
322 // This will attempt to Write() the initial request and headers, which will
323 // complete asynchronously.
324 ASSERT_EQ(ERR_IO_PENDING,
325 parser.SendRequest("GET /one.html HTTP/1.1\r\n", request_headers,
326 &response_info, callback.callback()));
mmenke3dc8c88b2015-02-19 15:11:27327 ASSERT_EQ(OK, callback.WaitForResult());
328
329 // Attempt to read the response status and the response headers.
330 ASSERT_EQ(ERR_IO_PENDING, parser.ReadResponseHeaders(callback.callback()));
mmenke3dc8c88b2015-02-19 15:11:27331 ASSERT_GT(callback.WaitForResult(), 0);
332
333 // Finally, attempt to read the response body.
334 scoped_refptr<IOBuffer> body_buffer(new IOBuffer(kBodySize));
335 ASSERT_EQ(ERR_IO_PENDING,
336 parser.ReadResponseBody(body_buffer.get(), kBodySize,
337 callback.callback()));
mmenke3dc8c88b2015-02-19 15:11:27338 ASSERT_EQ(kBodySize, callback.WaitForResult());
339}
340
341// Test to ensure the HttpStreamParser state machine does not get confused
[email protected]4750937f2012-06-15 20:44:21342// when sending a request with a chunked body, where chunks become available
343// asynchronously, over a socket where writes may also complete
344// asynchronously.
345// This is a regression test for http://crbug.com/132243
mmenke3dc8c88b2015-02-19 15:11:27346TEST(HttpStreamParser, AsyncChunkAndAsyncSocketWithMultipleChunks) {
[email protected]4750937f2012-06-15 20:44:21347 // The chunks that will be written in the request, as reflected in the
348 // MockWrites below.
349 static const char kChunk1[] = "Chunk 1";
350 static const char kChunk2[] = "Chunky 2";
351 static const char kChunk3[] = "Test 3";
352
353 MockWrite writes[] = {
mmenke3dc8c88b2015-02-19 15:11:27354 MockWrite(ASYNC, 0,
355 "GET /one.html HTTP/1.1\r\n"
356 "Transfer-Encoding: chunked\r\n\r\n"),
357 MockWrite(ASYNC, 1, "7\r\nChunk 1\r\n"),
358 MockWrite(ASYNC, 2, "8\r\nChunky 2\r\n"),
359 MockWrite(ASYNC, 3, "6\r\nTest 3\r\n"),
360 MockWrite(ASYNC, 4, "0\r\n\r\n"),
[email protected]4750937f2012-06-15 20:44:21361 };
362
363 // The size of the response body, as reflected in the Content-Length of the
364 // MockRead below.
365 static const int kBodySize = 8;
366
367 MockRead reads[] = {
368 MockRead(ASYNC, 5, "HTTP/1.1 200 OK\r\n"),
369 MockRead(ASYNC, 6, "Content-Length: 8\r\n\r\n"),
370 MockRead(ASYNC, 7, "one.html"),
[email protected]d55b30a2012-07-21 00:35:39371 MockRead(SYNCHRONOUS, 0, 8), // EOF
[email protected]4750937f2012-06-15 20:44:21372 };
373
mmenkecbc2b712014-10-09 20:29:07374 ChunkedUploadDataStream upload_stream(0);
375 upload_stream.AppendData(kChunk1, arraysize(kChunk1) - 1, false);
376 ASSERT_EQ(OK, upload_stream.Init(TestCompletionCallback().callback()));
[email protected]9a963892012-11-01 11:48:13377
mmenkef22be0ee2015-06-05 15:39:02378 SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes));
mmenke3dc8c88b2015-02-19 15:11:27379 scoped_ptr<ClientSocketHandle> socket_handle =
380 CreateConnectedSocketHandle(&data);
[email protected]4750937f2012-06-15 20:44:21381
382 HttpRequestInfo request_info;
383 request_info.method = "GET";
384 request_info.url = GURL("http://localhost");
[email protected]bf3eb002012-11-15 05:50:11385 request_info.upload_data_stream = &upload_stream;
[email protected]4750937f2012-06-15 20:44:21386
387 scoped_refptr<GrowableIOBuffer> read_buffer(new GrowableIOBuffer);
[email protected]90499482013-06-01 00:39:50388 HttpStreamParser parser(
389 socket_handle.get(), &request_info, read_buffer.get(), BoundNetLog());
[email protected]4750937f2012-06-15 20:44:21390
[email protected]4750937f2012-06-15 20:44:21391 HttpRequestHeaders request_headers;
[email protected]4750937f2012-06-15 20:44:21392 request_headers.SetHeader("Transfer-Encoding", "chunked");
[email protected]4750937f2012-06-15 20:44:21393
394 HttpResponseInfo response_info;
mmenke3dc8c88b2015-02-19 15:11:27395 TestCompletionCallback callback;
[email protected]4750937f2012-06-15 20:44:21396 // This will attempt to Write() the initial request and headers, which will
397 // complete asynchronously.
mmenke3dc8c88b2015-02-19 15:11:27398 ASSERT_EQ(ERR_IO_PENDING,
399 parser.SendRequest("GET /one.html HTTP/1.1\r\n", request_headers,
400 &response_info, callback.callback()));
[email protected]4750937f2012-06-15 20:44:21401 ASSERT_FALSE(callback.have_result());
402
mmenkef22be0ee2015-06-05 15:39:02403 // Sending the request and the first chunk completes.
404 base::RunLoop().RunUntilIdle();
405 ASSERT_FALSE(callback.have_result());
406
407 // Now append another chunk.
mmenkecbc2b712014-10-09 20:29:07408 upload_stream.AppendData(kChunk2, arraysize(kChunk2) - 1, false);
[email protected]4750937f2012-06-15 20:44:21409 ASSERT_FALSE(callback.have_result());
410
mmenkef22be0ee2015-06-05 15:39:02411 // Add the final chunk, while the write for the second is still pending,
412 // which should not confuse the state machine.
mmenkecbc2b712014-10-09 20:29:07413 upload_stream.AppendData(kChunk3, arraysize(kChunk3) - 1, true);
[email protected]4750937f2012-06-15 20:44:21414 ASSERT_FALSE(callback.have_result());
415
mmenkef22be0ee2015-06-05 15:39:02416 // Wait for writes to complete.
mmenke3dc8c88b2015-02-19 15:11:27417 ASSERT_EQ(OK, callback.WaitForResult());
[email protected]4750937f2012-06-15 20:44:21418
419 // Attempt to read the response status and the response headers.
mmenke3dc8c88b2015-02-19 15:11:27420 ASSERT_EQ(ERR_IO_PENDING, parser.ReadResponseHeaders(callback.callback()));
mmenke3dc8c88b2015-02-19 15:11:27421 ASSERT_GT(callback.WaitForResult(), 0);
[email protected]4750937f2012-06-15 20:44:21422
423 // Finally, attempt to read the response body.
424 scoped_refptr<IOBuffer> body_buffer(new IOBuffer(kBodySize));
mmenke3dc8c88b2015-02-19 15:11:27425 ASSERT_EQ(ERR_IO_PENDING,
426 parser.ReadResponseBody(body_buffer.get(), kBodySize,
427 callback.callback()));
mmenke3dc8c88b2015-02-19 15:11:27428 ASSERT_EQ(kBodySize, callback.WaitForResult());
429}
430
431// Test to ensure the HttpStreamParser state machine does not get confused
432// when there's only one "chunk" with 0 bytes, and is received from the
433// UploadStream only after sending the request headers successfully.
434TEST(HttpStreamParser, AsyncEmptyChunkedUpload) {
435 MockWrite writes[] = {
436 MockWrite(ASYNC, 0,
437 "GET /one.html HTTP/1.1\r\n"
438 "Transfer-Encoding: chunked\r\n\r\n"),
439 MockWrite(ASYNC, 1, "0\r\n\r\n"),
440 };
441
442 // The size of the response body, as reflected in the Content-Length of the
443 // MockRead below.
444 const int kBodySize = 8;
445
446 MockRead reads[] = {
447 MockRead(ASYNC, 2, "HTTP/1.1 200 OK\r\n"),
448 MockRead(ASYNC, 3, "Content-Length: 8\r\n\r\n"),
449 MockRead(ASYNC, 4, "one.html"),
450 MockRead(SYNCHRONOUS, 0, 5), // EOF
451 };
452
453 ChunkedUploadDataStream upload_stream(0);
454 ASSERT_EQ(OK, upload_stream.Init(TestCompletionCallback().callback()));
455
mmenkef22be0ee2015-06-05 15:39:02456 SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes));
mmenke3dc8c88b2015-02-19 15:11:27457 scoped_ptr<ClientSocketHandle> socket_handle =
458 CreateConnectedSocketHandle(&data);
459
460 HttpRequestInfo request_info;
461 request_info.method = "GET";
462 request_info.url = GURL("http://localhost");
463 request_info.upload_data_stream = &upload_stream;
464
465 scoped_refptr<GrowableIOBuffer> read_buffer(new GrowableIOBuffer);
466 HttpStreamParser parser(socket_handle.get(), &request_info, read_buffer.get(),
467 BoundNetLog());
468
469 HttpRequestHeaders request_headers;
470 request_headers.SetHeader("Transfer-Encoding", "chunked");
471
472 HttpResponseInfo response_info;
473 TestCompletionCallback callback;
474 // This will attempt to Write() the initial request and headers, which will
475 // complete asynchronously.
476 ASSERT_EQ(ERR_IO_PENDING,
477 parser.SendRequest("GET /one.html HTTP/1.1\r\n", request_headers,
478 &response_info, callback.callback()));
479
mmenke3dc8c88b2015-02-19 15:11:27480 // Now append the terminal 0-byte "chunk".
481 upload_stream.AppendData(nullptr, 0, true);
482 ASSERT_FALSE(callback.have_result());
483
mmenke3dc8c88b2015-02-19 15:11:27484 ASSERT_EQ(OK, callback.WaitForResult());
485
486 // Attempt to read the response status and the response headers.
487 ASSERT_EQ(ERR_IO_PENDING, parser.ReadResponseHeaders(callback.callback()));
mmenke3dc8c88b2015-02-19 15:11:27488 ASSERT_GT(callback.WaitForResult(), 0);
489
490 // Finally, attempt to read the response body.
491 scoped_refptr<IOBuffer> body_buffer(new IOBuffer(kBodySize));
492 ASSERT_EQ(ERR_IO_PENDING,
493 parser.ReadResponseBody(body_buffer.get(), kBodySize,
494 callback.callback()));
mmenke3dc8c88b2015-02-19 15:11:27495 ASSERT_EQ(kBodySize, callback.WaitForResult());
496}
497
498// Test to ensure the HttpStreamParser state machine does not get confused
499// when there's only one "chunk" with 0 bytes, which was already appended before
500// the request was started.
501TEST(HttpStreamParser, SyncEmptyChunkedUpload) {
502 MockWrite writes[] = {
503 MockWrite(ASYNC, 0,
504 "GET /one.html HTTP/1.1\r\n"
505 "Transfer-Encoding: chunked\r\n\r\n"),
506 MockWrite(ASYNC, 1, "0\r\n\r\n"),
507 };
508
509 // The size of the response body, as reflected in the Content-Length of the
510 // MockRead below.
511 const int kBodySize = 8;
512
513 MockRead reads[] = {
514 MockRead(ASYNC, 2, "HTTP/1.1 200 OK\r\n"),
515 MockRead(ASYNC, 3, "Content-Length: 8\r\n\r\n"),
516 MockRead(ASYNC, 4, "one.html"),
517 MockRead(SYNCHRONOUS, 0, 5), // EOF
518 };
519
520 ChunkedUploadDataStream upload_stream(0);
521 ASSERT_EQ(OK, upload_stream.Init(TestCompletionCallback().callback()));
522 // Append final empty chunk.
523 upload_stream.AppendData(nullptr, 0, true);
524
mmenkef22be0ee2015-06-05 15:39:02525 SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes));
mmenke3dc8c88b2015-02-19 15:11:27526 scoped_ptr<ClientSocketHandle> socket_handle =
527 CreateConnectedSocketHandle(&data);
528
529 HttpRequestInfo request_info;
530 request_info.method = "GET";
531 request_info.url = GURL("http://localhost");
532 request_info.upload_data_stream = &upload_stream;
533
534 scoped_refptr<GrowableIOBuffer> read_buffer(new GrowableIOBuffer);
535 HttpStreamParser parser(socket_handle.get(), &request_info, read_buffer.get(),
536 BoundNetLog());
537
538 HttpRequestHeaders request_headers;
539 request_headers.SetHeader("Transfer-Encoding", "chunked");
540
541 HttpResponseInfo response_info;
542 TestCompletionCallback callback;
543 // This will attempt to Write() the initial request and headers, which will
544 // complete asynchronously.
545 ASSERT_EQ(ERR_IO_PENDING,
546 parser.SendRequest("GET /one.html HTTP/1.1\r\n", request_headers,
547 &response_info, callback.callback()));
548
549 // Complete writing the request headers and body.
mmenke3dc8c88b2015-02-19 15:11:27550 ASSERT_EQ(OK, callback.WaitForResult());
551
552 // Attempt to read the response status and the response headers.
553 ASSERT_EQ(ERR_IO_PENDING, parser.ReadResponseHeaders(callback.callback()));
mmenke3dc8c88b2015-02-19 15:11:27554 ASSERT_GT(callback.WaitForResult(), 0);
555
556 // Finally, attempt to read the response body.
557 scoped_refptr<IOBuffer> body_buffer(new IOBuffer(kBodySize));
558 ASSERT_EQ(ERR_IO_PENDING,
559 parser.ReadResponseBody(body_buffer.get(), kBodySize,
560 callback.callback()));
mmenke3dc8c88b2015-02-19 15:11:27561 ASSERT_EQ(kBodySize, callback.WaitForResult());
[email protected]4750937f2012-06-15 20:44:21562}
563
[email protected]9c18dbc2013-05-29 19:06:53564TEST(HttpStreamParser, TruncatedHeaders) {
565 MockRead truncated_status_reads[] = {
566 MockRead(SYNCHRONOUS, 1, "HTTP/1.1 20"),
567 MockRead(SYNCHRONOUS, 0, 2), // EOF
568 };
569
570 MockRead truncated_after_status_reads[] = {
571 MockRead(SYNCHRONOUS, 1, "HTTP/1.1 200 Ok\r\n"),
572 MockRead(SYNCHRONOUS, 0, 2), // EOF
573 };
574
575 MockRead truncated_in_header_reads[] = {
576 MockRead(SYNCHRONOUS, 1, "HTTP/1.1 200 Ok\r\nHead"),
577 MockRead(SYNCHRONOUS, 0, 2), // EOF
578 };
579
580 MockRead truncated_after_header_reads[] = {
581 MockRead(SYNCHRONOUS, 1, "HTTP/1.1 200 Ok\r\nHeader: foo\r\n"),
582 MockRead(SYNCHRONOUS, 0, 2), // EOF
583 };
584
585 MockRead truncated_after_final_newline_reads[] = {
586 MockRead(SYNCHRONOUS, 1, "HTTP/1.1 200 Ok\r\nHeader: foo\r\n\r"),
587 MockRead(SYNCHRONOUS, 0, 2), // EOF
588 };
589
590 MockRead not_truncated_reads[] = {
591 MockRead(SYNCHRONOUS, 1, "HTTP/1.1 200 Ok\r\nHeader: foo\r\n\r\n"),
592 MockRead(SYNCHRONOUS, 0, 2), // EOF
593 };
594
595 MockRead* reads[] = {
596 truncated_status_reads,
597 truncated_after_status_reads,
598 truncated_in_header_reads,
599 truncated_after_header_reads,
600 truncated_after_final_newline_reads,
601 not_truncated_reads,
602 };
603
604 MockWrite writes[] = {
605 MockWrite(SYNCHRONOUS, 0, "GET / HTTP/1.1\r\n\r\n"),
606 };
607
zmo9528c9f42015-08-04 22:12:08608 enum {
609 HTTP = 0,
610 HTTPS,
611 NUM_PROTOCOLS,
612 };
[email protected]9c18dbc2013-05-29 19:06:53613
zmo9528c9f42015-08-04 22:12:08614 for (size_t protocol = 0; protocol < NUM_PROTOCOLS; protocol++) {
615 SCOPED_TRACE(protocol);
[email protected]9c18dbc2013-05-29 19:06:53616
zmo9528c9f42015-08-04 22:12:08617 for (size_t i = 0; i < arraysize(reads); i++) {
618 SCOPED_TRACE(i);
619 SequencedSocketData data(reads[i], 2, writes, arraysize(writes));
620 scoped_ptr<ClientSocketHandle> socket_handle(
621 CreateConnectedSocketHandle(&data));
[email protected]9c18dbc2013-05-29 19:06:53622
zmo9528c9f42015-08-04 22:12:08623 HttpRequestInfo request_info;
624 request_info.method = "GET";
625 if (protocol == HTTP) {
626 request_info.url = GURL("http://localhost");
627 } else {
628 request_info.url = GURL("https://localhost");
629 }
630 request_info.load_flags = LOAD_NORMAL;
[email protected]9c18dbc2013-05-29 19:06:53631
zmo9528c9f42015-08-04 22:12:08632 scoped_refptr<GrowableIOBuffer> read_buffer(new GrowableIOBuffer);
633 HttpStreamParser parser(
634 socket_handle.get(), &request_info, read_buffer.get(), BoundNetLog());
635
636 HttpRequestHeaders request_headers;
637 HttpResponseInfo response_info;
638 TestCompletionCallback callback;
639 ASSERT_EQ(OK, parser.SendRequest("GET / HTTP/1.1\r\n", request_headers,
640 &response_info, callback.callback()));
641
642 int rv = parser.ReadResponseHeaders(callback.callback());
643 if (i == arraysize(reads) - 1) {
644 EXPECT_EQ(OK, rv);
645 EXPECT_TRUE(response_info.headers.get());
646 } else {
647 if (protocol == HTTP) {
648 EXPECT_EQ(ERR_CONNECTION_CLOSED, rv);
649 EXPECT_TRUE(response_info.headers.get());
650 } else {
651 EXPECT_EQ(ERR_RESPONSE_HEADERS_TRUNCATED, rv);
652 EXPECT_FALSE(response_info.headers.get());
653 }
654 }
[email protected]9c18dbc2013-05-29 19:06:53655 }
656 }
657}
658
[email protected]df8e6382013-11-07 00:19:06659// Confirm that on 101 response, the headers are parsed but the data that
660// follows remains in the buffer.
661TEST(HttpStreamParser, Websocket101Response) {
662 MockRead reads[] = {
663 MockRead(SYNCHRONOUS, 1,
664 "HTTP/1.1 101 Switching Protocols\r\n"
665 "Upgrade: websocket\r\n"
666 "Connection: Upgrade\r\n"
667 "\r\n"
668 "a fake websocket frame"),
669 };
670
671 MockWrite writes[] = {
672 MockWrite(SYNCHRONOUS, 0, "GET / HTTP/1.1\r\n\r\n"),
673 };
674
mmenkef22be0ee2015-06-05 15:39:02675 SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes));
676 scoped_ptr<ClientSocketHandle> socket_handle =
677 CreateConnectedSocketHandle(&data);
[email protected]df8e6382013-11-07 00:19:06678
679 HttpRequestInfo request_info;
680 request_info.method = "GET";
681 request_info.url = GURL("http://localhost");
682 request_info.load_flags = LOAD_NORMAL;
683
684 scoped_refptr<GrowableIOBuffer> read_buffer(new GrowableIOBuffer);
685 HttpStreamParser parser(
686 socket_handle.get(), &request_info, read_buffer.get(), BoundNetLog());
687
688 HttpRequestHeaders request_headers;
689 HttpResponseInfo response_info;
mmenkef22be0ee2015-06-05 15:39:02690 TestCompletionCallback callback;
691 ASSERT_EQ(OK, parser.SendRequest("GET / HTTP/1.1\r\n", request_headers,
692 &response_info, callback.callback()));
[email protected]df8e6382013-11-07 00:19:06693
mmenkef22be0ee2015-06-05 15:39:02694 EXPECT_EQ(OK, parser.ReadResponseHeaders(callback.callback()));
[email protected]df8e6382013-11-07 00:19:06695 ASSERT_TRUE(response_info.headers.get());
696 EXPECT_EQ(101, response_info.headers->response_code());
697 EXPECT_TRUE(response_info.headers->HasHeaderValue("Connection", "Upgrade"));
698 EXPECT_TRUE(response_info.headers->HasHeaderValue("Upgrade", "websocket"));
699 EXPECT_EQ(read_buffer->capacity(), read_buffer->offset());
700 EXPECT_EQ("a fake websocket frame",
701 base::StringPiece(read_buffer->StartOfBuffer(),
702 read_buffer->capacity()));
703}
704
[email protected]390489b2013-12-09 10:49:01705// Helper class for constructing HttpStreamParser and running GET requests.
706class SimpleGetRunner {
707 public:
708 SimpleGetRunner() : read_buffer_(new GrowableIOBuffer), sequence_number_(0) {
709 writes_.push_back(MockWrite(
710 SYNCHRONOUS, sequence_number_++, "GET / HTTP/1.1\r\n\r\n"));
711 }
712
713 HttpStreamParser* parser() { return parser_.get(); }
714 GrowableIOBuffer* read_buffer() { return read_buffer_.get(); }
715 HttpResponseInfo* response_info() { return &response_info_; }
716
717 void AddInitialData(const std::string& data) {
718 int offset = read_buffer_->offset();
719 int size = data.size();
720 read_buffer_->SetCapacity(offset + size);
721 memcpy(read_buffer_->StartOfBuffer() + offset, data.data(), size);
722 read_buffer_->set_offset(offset + size);
723 }
724
725 void AddRead(const std::string& data) {
726 reads_.push_back(MockRead(SYNCHRONOUS, sequence_number_++, data.data()));
727 }
728
729 void SetupParserAndSendRequest() {
730 reads_.push_back(MockRead(SYNCHRONOUS, 0, sequence_number_++)); // EOF
731
mmenkef22be0ee2015-06-05 15:39:02732 data_.reset(new SequencedSocketData(&reads_.front(), reads_.size(),
733 &writes_.front(), writes_.size()));
734 socket_handle_ = CreateConnectedSocketHandle(data_.get());
[email protected]390489b2013-12-09 10:49:01735
736 request_info_.method = "GET";
737 request_info_.url = GURL("http://localhost");
738 request_info_.load_flags = LOAD_NORMAL;
739
740 parser_.reset(new HttpStreamParser(
741 socket_handle_.get(), &request_info_, read_buffer(), BoundNetLog()));
742
mmenkef22be0ee2015-06-05 15:39:02743 TestCompletionCallback callback;
744 ASSERT_EQ(OK, parser_->SendRequest("GET / HTTP/1.1\r\n", request_headers_,
745 &response_info_, callback.callback()));
[email protected]390489b2013-12-09 10:49:01746 }
747
748 void ReadHeaders() {
749 TestCompletionCallback callback;
750 EXPECT_EQ(OK, parser_->ReadResponseHeaders(callback.callback()));
751 }
752
753 void ReadBody(int user_buf_len, int* read_lengths) {
754 TestCompletionCallback callback;
755 scoped_refptr<IOBuffer> buffer = new IOBuffer(user_buf_len);
756 int rv;
757 int i = 0;
758 while (true) {
dcheng48459ac22014-08-26 00:46:41759 rv = parser_->ReadResponseBody(
760 buffer.get(), user_buf_len, callback.callback());
[email protected]390489b2013-12-09 10:49:01761 EXPECT_EQ(read_lengths[i], rv);
762 i++;
763 if (rv <= 0)
764 return;
765 }
766 }
767
768 private:
769 HttpRequestHeaders request_headers_;
770 HttpResponseInfo response_info_;
771 HttpRequestInfo request_info_;
772 scoped_refptr<GrowableIOBuffer> read_buffer_;
773 std::vector<MockRead> reads_;
774 std::vector<MockWrite> writes_;
775 scoped_ptr<ClientSocketHandle> socket_handle_;
mmenkef22be0ee2015-06-05 15:39:02776 scoped_ptr<SequencedSocketData> data_;
[email protected]390489b2013-12-09 10:49:01777 scoped_ptr<HttpStreamParser> parser_;
778 int sequence_number_;
779};
780
781// Test that HTTP/0.9 response size is correctly calculated.
782TEST(HttpStreamParser, ReceivedBytesNoHeaders) {
783 std::string response = "hello\r\nworld\r\n";
784
785 SimpleGetRunner get_runner;
786 get_runner.AddRead(response);
787 get_runner.SetupParserAndSendRequest();
788 get_runner.ReadHeaders();
789 EXPECT_EQ(0, get_runner.parser()->received_bytes());
[email protected]3cb5fc22013-12-12 19:40:56790 int response_size = response.size();
[email protected]390489b2013-12-09 10:49:01791 int read_lengths[] = {response_size, 0};
792 get_runner.ReadBody(response_size, read_lengths);
793 EXPECT_EQ(response_size, get_runner.parser()->received_bytes());
794}
795
796// Test basic case where there is no keep-alive or extra data from the socket,
797// and the entire response is received in a single read.
798TEST(HttpStreamParser, ReceivedBytesNormal) {
799 std::string headers = "HTTP/1.1 200 OK\r\n"
800 "Content-Length: 7\r\n\r\n";
801 std::string body = "content";
802 std::string response = headers + body;
803
804 SimpleGetRunner get_runner;
805 get_runner.AddRead(response);
806 get_runner.SetupParserAndSendRequest();
807 get_runner.ReadHeaders();
808 int64 headers_size = headers.size();
809 EXPECT_EQ(headers_size, get_runner.parser()->received_bytes());
[email protected]3cb5fc22013-12-12 19:40:56810 int body_size = body.size();
[email protected]390489b2013-12-09 10:49:01811 int read_lengths[] = {body_size, 0};
812 get_runner.ReadBody(body_size, read_lengths);
813 int64 response_size = response.size();
814 EXPECT_EQ(response_size, get_runner.parser()->received_bytes());
815}
816
817// Test that bytes that represent "next" response are not counted
818// as current response "received_bytes".
819TEST(HttpStreamParser, ReceivedBytesExcludesNextResponse) {
820 std::string headers = "HTTP/1.1 200 OK\r\n"
821 "Content-Length: 8\r\n\r\n";
822 std::string body = "content8";
823 std::string response = headers + body;
824 std::string next_response = "HTTP/1.1 200 OK\r\n\r\nFOO";
825 std::string data = response + next_response;
826
827 SimpleGetRunner get_runner;
828 get_runner.AddRead(data);
829 get_runner.SetupParserAndSendRequest();
830 get_runner.ReadHeaders();
831 EXPECT_EQ(39, get_runner.parser()->received_bytes());
832 int64 headers_size = headers.size();
833 EXPECT_EQ(headers_size, get_runner.parser()->received_bytes());
[email protected]3cb5fc22013-12-12 19:40:56834 int body_size = body.size();
[email protected]390489b2013-12-09 10:49:01835 int read_lengths[] = {body_size, 0};
836 get_runner.ReadBody(body_size, read_lengths);
837 int64 response_size = response.size();
838 EXPECT_EQ(response_size, get_runner.parser()->received_bytes());
839 int64 next_response_size = next_response.size();
840 EXPECT_EQ(next_response_size, get_runner.read_buffer()->offset());
841}
842
843// Test that "received_bytes" calculation works fine when last read
844// contains more data than requested by user.
845// We send data in two reads:
846// 1) Headers + beginning of response
847// 2) remaining part of response + next response start
848// We setup user read buffer so it fully accepts the beginnig of response
849// body, but it is larger that remaining part of body.
850TEST(HttpStreamParser, ReceivedBytesMultiReadExcludesNextResponse) {
851 std::string headers = "HTTP/1.1 200 OK\r\n"
852 "Content-Length: 36\r\n\r\n";
853 int64 user_buf_len = 32;
854 std::string body_start = std::string(user_buf_len, '#');
[email protected]3cb5fc22013-12-12 19:40:56855 int body_start_size = body_start.size();
[email protected]390489b2013-12-09 10:49:01856 EXPECT_EQ(user_buf_len, body_start_size);
857 std::string response_start = headers + body_start;
858 std::string body_end = "abcd";
859 std::string next_response = "HTTP/1.1 200 OK\r\n\r\nFOO";
860 std::string response_end = body_end + next_response;
861
862 SimpleGetRunner get_runner;
863 get_runner.AddRead(response_start);
864 get_runner.AddRead(response_end);
865 get_runner.SetupParserAndSendRequest();
866 get_runner.ReadHeaders();
867 int64 headers_size = headers.size();
868 EXPECT_EQ(headers_size, get_runner.parser()->received_bytes());
[email protected]3cb5fc22013-12-12 19:40:56869 int body_end_size = body_end.size();
[email protected]390489b2013-12-09 10:49:01870 int read_lengths[] = {body_start_size, body_end_size, 0};
871 get_runner.ReadBody(body_start_size, read_lengths);
872 int64 response_size = response_start.size() + body_end_size;
873 EXPECT_EQ(response_size, get_runner.parser()->received_bytes());
874 int64 next_response_size = next_response.size();
875 EXPECT_EQ(next_response_size, get_runner.read_buffer()->offset());
876}
877
878// Test that "received_bytes" calculation works fine when there is no
879// network activity at all; that is when all data is read from read buffer.
880// In this case read buffer contains two responses. We expect that only
881// bytes that correspond to the first one are taken into account.
882TEST(HttpStreamParser, ReceivedBytesFromReadBufExcludesNextResponse) {
883 std::string headers = "HTTP/1.1 200 OK\r\n"
884 "Content-Length: 7\r\n\r\n";
885 std::string body = "content";
886 std::string response = headers + body;
887 std::string next_response = "HTTP/1.1 200 OK\r\n\r\nFOO";
888 std::string data = response + next_response;
889
890 SimpleGetRunner get_runner;
891 get_runner.AddInitialData(data);
892 get_runner.SetupParserAndSendRequest();
893 get_runner.ReadHeaders();
894 int64 headers_size = headers.size();
895 EXPECT_EQ(headers_size, get_runner.parser()->received_bytes());
[email protected]3cb5fc22013-12-12 19:40:56896 int body_size = body.size();
[email protected]390489b2013-12-09 10:49:01897 int read_lengths[] = {body_size, 0};
898 get_runner.ReadBody(body_size, read_lengths);
899 int64 response_size = response.size();
900 EXPECT_EQ(response_size, get_runner.parser()->received_bytes());
901 int64 next_response_size = next_response.size();
902 EXPECT_EQ(next_response_size, get_runner.read_buffer()->offset());
903}
904
905// Test calculating "received_bytes" when part of request has been already
906// loaded and placed to read buffer by previous stream parser.
907TEST(HttpStreamParser, ReceivedBytesUseReadBuf) {
908 std::string buffer = "HTTP/1.1 200 OK\r\n";
909 std::string remaining_headers = "Content-Length: 7\r\n\r\n";
910 int64 headers_size = buffer.size() + remaining_headers.size();
911 std::string body = "content";
912 std::string response = remaining_headers + body;
913
914 SimpleGetRunner get_runner;
915 get_runner.AddInitialData(buffer);
916 get_runner.AddRead(response);
917 get_runner.SetupParserAndSendRequest();
918 get_runner.ReadHeaders();
919 EXPECT_EQ(headers_size, get_runner.parser()->received_bytes());
[email protected]3cb5fc22013-12-12 19:40:56920 int body_size = body.size();
[email protected]390489b2013-12-09 10:49:01921 int read_lengths[] = {body_size, 0};
922 get_runner.ReadBody(body_size, read_lengths);
923 EXPECT_EQ(headers_size + body_size, get_runner.parser()->received_bytes());
924 EXPECT_EQ(0, get_runner.read_buffer()->offset());
925}
926
927// Test the case when the resulting read_buf contains both unused bytes and
928// bytes ejected by chunked-encoding filter.
929TEST(HttpStreamParser, ReceivedBytesChunkedTransferExcludesNextResponse) {
930 std::string response = "HTTP/1.1 200 OK\r\n"
931 "Transfer-Encoding: chunked\r\n\r\n"
932 "7\r\nChunk 1\r\n"
933 "8\r\nChunky 2\r\n"
934 "6\r\nTest 3\r\n"
935 "0\r\n\r\n";
936 std::string next_response = "foo bar\r\n";
937 std::string data = response + next_response;
938
939 SimpleGetRunner get_runner;
940 get_runner.AddInitialData(data);
941 get_runner.SetupParserAndSendRequest();
942 get_runner.ReadHeaders();
943 int read_lengths[] = {4, 3, 6, 2, 6, 0};
944 get_runner.ReadBody(7, read_lengths);
945 int64 response_size = response.size();
946 EXPECT_EQ(response_size, get_runner.parser()->received_bytes());
947 int64 next_response_size = next_response.size();
948 EXPECT_EQ(next_response_size, get_runner.read_buffer()->offset());
949}
950
951// Test that data transfered in multiple reads is correctly processed.
952// We feed data into 4-bytes reads. Also we set length of read
953// buffer to 5-bytes to test all possible buffer misaligments.
954TEST(HttpStreamParser, ReceivedBytesMultipleReads) {
955 std::string headers = "HTTP/1.1 200 OK\r\n"
956 "Content-Length: 33\r\n\r\n";
957 std::string body = "foo bar baz\r\n"
958 "sputnik mir babushka";
959 std::string response = headers + body;
960
961 size_t receive_length = 4;
962 std::vector<std::string> blocks;
963 for (size_t i = 0; i < response.size(); i += receive_length) {
964 size_t length = std::min(receive_length, response.size() - i);
965 blocks.push_back(response.substr(i, length));
966 }
967
968 SimpleGetRunner get_runner;
[email protected]3cb5fc22013-12-12 19:40:56969 for (std::vector<std::string>::size_type i = 0; i < blocks.size(); ++i)
[email protected]390489b2013-12-09 10:49:01970 get_runner.AddRead(blocks[i]);
971 get_runner.SetupParserAndSendRequest();
972 get_runner.ReadHeaders();
973 int64 headers_size = headers.size();
974 EXPECT_EQ(headers_size, get_runner.parser()->received_bytes());
975 int read_lengths[] = {1, 4, 4, 4, 4, 4, 4, 4, 4, 0};
976 get_runner.ReadBody(receive_length + 1, read_lengths);
977 int64 response_size = response.size();
978 EXPECT_EQ(response_size, get_runner.parser()->received_bytes());
979}
980
981// Test that "continue" HTTP header is counted as "received_bytes".
982TEST(HttpStreamParser, ReceivedBytesIncludesContinueHeader) {
983 std::string status100 = "HTTP/1.1 100 OK\r\n\r\n";
984 std::string headers = "HTTP/1.1 200 OK\r\n"
985 "Content-Length: 7\r\n\r\n";
986 int64 headers_size = status100.size() + headers.size();
987 std::string body = "content";
988 std::string response = headers + body;
989
990 SimpleGetRunner get_runner;
991 get_runner.AddRead(status100);
992 get_runner.AddRead(response);
993 get_runner.SetupParserAndSendRequest();
994 get_runner.ReadHeaders();
995 EXPECT_EQ(100, get_runner.response_info()->headers->response_code());
996 int64 status100_size = status100.size();
997 EXPECT_EQ(status100_size, get_runner.parser()->received_bytes());
998 get_runner.ReadHeaders();
999 EXPECT_EQ(200, get_runner.response_info()->headers->response_code());
1000 EXPECT_EQ(headers_size, get_runner.parser()->received_bytes());
1001 int64 response_size = headers_size + body.size();
[email protected]3cb5fc22013-12-12 19:40:561002 int body_size = body.size();
[email protected]390489b2013-12-09 10:49:011003 int read_lengths[] = {body_size, 0};
1004 get_runner.ReadBody(body_size, read_lengths);
1005 EXPECT_EQ(response_size, get_runner.parser()->received_bytes());
1006}
1007
[email protected]ecab6e052014-05-16 14:58:121008// Test that an HttpStreamParser can be read from after it's received headers
1009// and data structures owned by its owner have been deleted. This happens
1010// when a ResponseBodyDrainer is used.
1011TEST(HttpStreamParser, ReadAfterUnownedObjectsDestroyed) {
1012 MockWrite writes[] = {
1013 MockWrite(SYNCHRONOUS, 0,
1014 "GET /foo.html HTTP/1.1\r\n\r\n"),
[email protected]ecab6e052014-05-16 14:58:121015 };
1016
1017 const int kBodySize = 1;
1018 MockRead reads[] = {
mmenkef22be0ee2015-06-05 15:39:021019 MockRead(SYNCHRONOUS, 1, "HTTP/1.1 200 OK\r\n"),
1020 MockRead(SYNCHRONOUS, 2, "Content-Length: 1\r\n\r\n"),
1021 MockRead(SYNCHRONOUS, 3, "Connection: Keep-Alive\r\n\r\n"),
1022 MockRead(SYNCHRONOUS, 4, "1"),
1023 MockRead(SYNCHRONOUS, 0, 5), // EOF
[email protected]ecab6e052014-05-16 14:58:121024 };
1025
mmenkef22be0ee2015-06-05 15:39:021026 SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes));
1027 scoped_ptr<ClientSocketHandle> socket_handle =
1028 CreateConnectedSocketHandle(&data);
[email protected]ecab6e052014-05-16 14:58:121029
1030 scoped_ptr<HttpRequestInfo> request_info(new HttpRequestInfo());
1031 request_info->method = "GET";
1032 request_info->url = GURL("http://somewhere/foo.html");
1033
1034 scoped_refptr<GrowableIOBuffer> read_buffer(new GrowableIOBuffer);
1035 HttpStreamParser parser(socket_handle.get(), request_info.get(),
1036 read_buffer.get(), BoundNetLog());
1037
1038 scoped_ptr<HttpRequestHeaders> request_headers(new HttpRequestHeaders());
1039 scoped_ptr<HttpResponseInfo> response_info(new HttpResponseInfo());
mmenkef22be0ee2015-06-05 15:39:021040 TestCompletionCallback callback;
[email protected]ecab6e052014-05-16 14:58:121041 ASSERT_EQ(OK, parser.SendRequest("GET /foo.html HTTP/1.1\r\n",
1042 *request_headers, response_info.get(), callback.callback()));
1043 ASSERT_EQ(OK, parser.ReadResponseHeaders(callback.callback()));
1044
1045 // If the object that owns the HttpStreamParser is deleted, it takes the
1046 // objects passed to the HttpStreamParser with it.
1047 request_info.reset();
1048 request_headers.reset();
1049 response_info.reset();
1050
1051 scoped_refptr<IOBuffer> body_buffer(new IOBuffer(kBodySize));
1052 ASSERT_EQ(kBodySize, parser.ReadResponseBody(
1053 body_buffer.get(), kBodySize, callback.callback()));
1054}
1055
[email protected]390489b2013-12-09 10:49:011056} // namespace
[email protected]df8e6382013-11-07 00:19:061057
[email protected]6db833d12012-01-21 00:45:191058} // namespace net