Only grant permissions to new extensions from sync if they have the expected version
[chromium-blink-merge.git] / net / http / http_network_transaction_unittest.cc
blob25af22fabeebddd8ece2587a2d6518192ed6179f
1 // Copyright 2013 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.
5 #include "net/http/http_network_transaction.h"
7 #include <math.h> // ceil
8 #include <stdarg.h>
9 #include <stdint.h>
11 #include <string>
12 #include <vector>
14 #include "base/basictypes.h"
15 #include "base/compiler_specific.h"
16 #include "base/files/file_path.h"
17 #include "base/files/file_util.h"
18 #include "base/json/json_writer.h"
19 #include "base/logging.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/memory/weak_ptr.h"
22 #include "base/run_loop.h"
23 #include "base/stl_util.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/test/test_file_util.h"
27 #include "base/thread_task_runner_handle.h"
28 #include "net/base/auth.h"
29 #include "net/base/chunked_upload_data_stream.h"
30 #include "net/base/completion_callback.h"
31 #include "net/base/elements_upload_data_stream.h"
32 #include "net/base/load_timing_info.h"
33 #include "net/base/load_timing_info_test_util.h"
34 #include "net/base/net_errors.h"
35 #include "net/base/request_priority.h"
36 #include "net/base/test_completion_callback.h"
37 #include "net/base/test_data_directory.h"
38 #include "net/base/upload_bytes_element_reader.h"
39 #include "net/base/upload_file_element_reader.h"
40 #include "net/cert/mock_cert_verifier.h"
41 #include "net/dns/host_cache.h"
42 #include "net/dns/mock_host_resolver.h"
43 #include "net/http/http_auth_challenge_tokenizer.h"
44 #include "net/http/http_auth_handler_digest.h"
45 #include "net/http/http_auth_handler_mock.h"
46 #include "net/http/http_auth_handler_ntlm.h"
47 #include "net/http/http_basic_state.h"
48 #include "net/http/http_basic_stream.h"
49 #include "net/http/http_network_session.h"
50 #include "net/http/http_network_session_peer.h"
51 #include "net/http/http_request_headers.h"
52 #include "net/http/http_server_properties_impl.h"
53 #include "net/http/http_stream.h"
54 #include "net/http/http_stream_factory.h"
55 #include "net/http/http_stream_parser.h"
56 #include "net/http/http_transaction_test_util.h"
57 #include "net/log/net_log.h"
58 #include "net/log/test_net_log.h"
59 #include "net/log/test_net_log_entry.h"
60 #include "net/log/test_net_log_util.h"
61 #include "net/proxy/mock_proxy_resolver.h"
62 #include "net/proxy/proxy_config_service_fixed.h"
63 #include "net/proxy/proxy_info.h"
64 #include "net/proxy/proxy_resolver.h"
65 #include "net/proxy/proxy_service.h"
66 #include "net/socket/client_socket_factory.h"
67 #include "net/socket/client_socket_pool_manager.h"
68 #include "net/socket/connection_attempts.h"
69 #include "net/socket/mock_client_socket_pool_manager.h"
70 #include "net/socket/next_proto.h"
71 #include "net/socket/socket_test_util.h"
72 #include "net/socket/ssl_client_socket.h"
73 #include "net/spdy/spdy_framer.h"
74 #include "net/spdy/spdy_session.h"
75 #include "net/spdy/spdy_session_pool.h"
76 #include "net/spdy/spdy_test_util_common.h"
77 #include "net/ssl/ssl_cert_request_info.h"
78 #include "net/ssl/ssl_config_service.h"
79 #include "net/ssl/ssl_config_service_defaults.h"
80 #include "net/ssl/ssl_info.h"
81 #include "net/test/cert_test_util.h"
82 #include "net/websockets/websocket_handshake_stream_base.h"
83 #include "testing/gtest/include/gtest/gtest.h"
84 #include "testing/platform_test.h"
85 #include "url/gurl.h"
87 using base::ASCIIToUTF16;
89 //-----------------------------------------------------------------------------
91 namespace net {
93 namespace {
95 const base::string16 kBar(ASCIIToUTF16("bar"));
96 const base::string16 kBar2(ASCIIToUTF16("bar2"));
97 const base::string16 kBar3(ASCIIToUTF16("bar3"));
98 const base::string16 kBaz(ASCIIToUTF16("baz"));
99 const base::string16 kFirst(ASCIIToUTF16("first"));
100 const base::string16 kFoo(ASCIIToUTF16("foo"));
101 const base::string16 kFoo2(ASCIIToUTF16("foo2"));
102 const base::string16 kFoo3(ASCIIToUTF16("foo3"));
103 const base::string16 kFou(ASCIIToUTF16("fou"));
104 const base::string16 kSecond(ASCIIToUTF16("second"));
105 const base::string16 kTestingNTLM(ASCIIToUTF16("testing-ntlm"));
106 const base::string16 kWrongPassword(ASCIIToUTF16("wrongpassword"));
108 int GetIdleSocketCountInTransportSocketPool(HttpNetworkSession* session) {
109 return session->GetTransportSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL)
110 ->IdleSocketCount();
113 int GetIdleSocketCountInSSLSocketPool(HttpNetworkSession* session) {
114 return session->GetSSLSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL)
115 ->IdleSocketCount();
118 bool IsTransportSocketPoolStalled(HttpNetworkSession* session) {
119 return session->GetTransportSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL)
120 ->IsStalled();
123 // Takes in a Value created from a NetLogHttpResponseParameter, and returns
124 // a JSONified list of headers as a single string. Uses single quotes instead
125 // of double quotes for easier comparison. Returns false on failure.
126 bool GetHeaders(base::DictionaryValue* params, std::string* headers) {
127 if (!params)
128 return false;
129 base::ListValue* header_list;
130 if (!params->GetList("headers", &header_list))
131 return false;
132 std::string double_quote_headers;
133 base::JSONWriter::Write(*header_list, &double_quote_headers);
134 base::ReplaceChars(double_quote_headers, "\"", "'", headers);
135 return true;
138 // Tests LoadTimingInfo in the case a socket is reused and no PAC script is
139 // used.
140 void TestLoadTimingReused(const LoadTimingInfo& load_timing_info) {
141 EXPECT_TRUE(load_timing_info.socket_reused);
142 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
144 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
145 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
147 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
148 EXPECT_FALSE(load_timing_info.send_start.is_null());
150 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
152 // Set at a higher level.
153 EXPECT_TRUE(load_timing_info.request_start_time.is_null());
154 EXPECT_TRUE(load_timing_info.request_start.is_null());
155 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
158 // Tests LoadTimingInfo in the case a new socket is used and no PAC script is
159 // used.
160 void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
161 int connect_timing_flags) {
162 EXPECT_FALSE(load_timing_info.socket_reused);
163 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
165 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
166 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
168 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
169 connect_timing_flags);
170 EXPECT_LE(load_timing_info.connect_timing.connect_end,
171 load_timing_info.send_start);
173 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
175 // Set at a higher level.
176 EXPECT_TRUE(load_timing_info.request_start_time.is_null());
177 EXPECT_TRUE(load_timing_info.request_start.is_null());
178 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
181 // Tests LoadTimingInfo in the case a socket is reused and a PAC script is
182 // used.
183 void TestLoadTimingReusedWithPac(const LoadTimingInfo& load_timing_info) {
184 EXPECT_TRUE(load_timing_info.socket_reused);
185 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
187 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
189 EXPECT_FALSE(load_timing_info.proxy_resolve_start.is_null());
190 EXPECT_LE(load_timing_info.proxy_resolve_start,
191 load_timing_info.proxy_resolve_end);
192 EXPECT_LE(load_timing_info.proxy_resolve_end,
193 load_timing_info.send_start);
194 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
196 // Set at a higher level.
197 EXPECT_TRUE(load_timing_info.request_start_time.is_null());
198 EXPECT_TRUE(load_timing_info.request_start.is_null());
199 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
202 // Tests LoadTimingInfo in the case a new socket is used and a PAC script is
203 // used.
204 void TestLoadTimingNotReusedWithPac(const LoadTimingInfo& load_timing_info,
205 int connect_timing_flags) {
206 EXPECT_FALSE(load_timing_info.socket_reused);
207 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
209 EXPECT_FALSE(load_timing_info.proxy_resolve_start.is_null());
210 EXPECT_LE(load_timing_info.proxy_resolve_start,
211 load_timing_info.proxy_resolve_end);
212 EXPECT_LE(load_timing_info.proxy_resolve_end,
213 load_timing_info.connect_timing.connect_start);
214 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
215 connect_timing_flags);
216 EXPECT_LE(load_timing_info.connect_timing.connect_end,
217 load_timing_info.send_start);
219 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
221 // Set at a higher level.
222 EXPECT_TRUE(load_timing_info.request_start_time.is_null());
223 EXPECT_TRUE(load_timing_info.request_start.is_null());
224 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
227 void AddWebSocketHeaders(HttpRequestHeaders* headers) {
228 headers->SetHeader("Connection", "Upgrade");
229 headers->SetHeader("Upgrade", "websocket");
230 headers->SetHeader("Origin", "http://www.example.org");
231 headers->SetHeader("Sec-WebSocket-Version", "13");
232 headers->SetHeader("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
235 HttpNetworkSession* CreateSession(SpdySessionDependencies* session_deps) {
236 return SpdySessionDependencies::SpdyCreateSession(session_deps);
239 } // namespace
241 class HttpNetworkTransactionTest
242 : public PlatformTest,
243 public ::testing::WithParamInterface<NextProto> {
244 public:
245 virtual ~HttpNetworkTransactionTest() {
246 // Important to restore the per-pool limit first, since the pool limit must
247 // always be greater than group limit, and the tests reduce both limits.
248 ClientSocketPoolManager::set_max_sockets_per_pool(
249 HttpNetworkSession::NORMAL_SOCKET_POOL, old_max_pool_sockets_);
250 ClientSocketPoolManager::set_max_sockets_per_group(
251 HttpNetworkSession::NORMAL_SOCKET_POOL, old_max_group_sockets_);
254 protected:
255 HttpNetworkTransactionTest()
256 : spdy_util_(GetParam()),
257 session_deps_(GetParam()),
258 old_max_group_sockets_(ClientSocketPoolManager::max_sockets_per_group(
259 HttpNetworkSession::NORMAL_SOCKET_POOL)),
260 old_max_pool_sockets_(ClientSocketPoolManager::max_sockets_per_pool(
261 HttpNetworkSession::NORMAL_SOCKET_POOL)) {
264 struct SimpleGetHelperResult {
265 int rv;
266 std::string status_line;
267 std::string response_data;
268 int64_t total_received_bytes;
269 int64_t total_sent_bytes;
270 LoadTimingInfo load_timing_info;
271 ConnectionAttempts connection_attempts;
274 void SetUp() override {
275 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
276 base::MessageLoop::current()->RunUntilIdle();
279 void TearDown() override {
280 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
281 base::MessageLoop::current()->RunUntilIdle();
282 // Empty the current queue.
283 base::MessageLoop::current()->RunUntilIdle();
284 PlatformTest::TearDown();
285 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
286 base::MessageLoop::current()->RunUntilIdle();
289 const char* GetAlternateProtocolFromParam() {
290 return
291 AlternateProtocolToString(AlternateProtocolFromNextProto(GetParam()));
294 std::string GetAlternativeServiceHttpHeader() {
295 return std::string("Alt-Svc: ") + GetAlternateProtocolFromParam() +
296 "=\"www.example.com:443\"\r\n";
299 std::string GetAlternateProtocolHttpHeader() {
300 return std::string("Alternate-Protocol: 443:") +
301 GetAlternateProtocolFromParam() + "\r\n";
304 // Either |write_failure| specifies a write failure or |read_failure|
305 // specifies a read failure when using a reused socket. In either case, the
306 // failure should cause the network transaction to resend the request, and the
307 // other argument should be NULL.
308 void KeepAliveConnectionResendRequestTest(const MockWrite* write_failure,
309 const MockRead* read_failure);
311 // Either |write_failure| specifies a write failure or |read_failure|
312 // specifies a read failure when using a reused socket. In either case, the
313 // failure should cause the network transaction to resend the request, and the
314 // other argument should be NULL.
315 void PreconnectErrorResendRequestTest(const MockWrite* write_failure,
316 const MockRead* read_failure,
317 bool use_spdy);
319 SimpleGetHelperResult SimpleGetHelperForData(StaticSocketDataProvider* data[],
320 size_t data_count) {
321 SimpleGetHelperResult out;
323 HttpRequestInfo request;
324 request.method = "GET";
325 request.url = GURL("http://www.example.org/");
326 request.load_flags = 0;
328 BoundTestNetLog log;
329 session_deps_.net_log = log.bound().net_log();
330 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
331 scoped_ptr<HttpTransaction> trans(
332 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
334 for (size_t i = 0; i < data_count; ++i) {
335 session_deps_.socket_factory->AddSocketDataProvider(data[i]);
338 TestCompletionCallback callback;
340 EXPECT_TRUE(log.bound().IsCapturing());
341 int rv = trans->Start(&request, callback.callback(), log.bound());
342 EXPECT_EQ(ERR_IO_PENDING, rv);
344 out.rv = callback.WaitForResult();
345 out.total_received_bytes = trans->GetTotalReceivedBytes();
346 out.total_sent_bytes = trans->GetTotalSentBytes();
348 // Even in the failure cases that use this function, connections are always
349 // successfully established before the error.
350 EXPECT_TRUE(trans->GetLoadTimingInfo(&out.load_timing_info));
351 TestLoadTimingNotReused(out.load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
353 if (out.rv != OK)
354 return out;
356 const HttpResponseInfo* response = trans->GetResponseInfo();
357 // Can't use ASSERT_* inside helper functions like this, so
358 // return an error.
359 if (response == NULL || response->headers.get() == NULL) {
360 out.rv = ERR_UNEXPECTED;
361 return out;
363 out.status_line = response->headers->GetStatusLine();
365 EXPECT_EQ("127.0.0.1", response->socket_address.host());
366 EXPECT_EQ(80, response->socket_address.port());
368 rv = ReadTransaction(trans.get(), &out.response_data);
369 EXPECT_EQ(OK, rv);
371 TestNetLogEntry::List entries;
372 log.GetEntries(&entries);
373 size_t pos = ExpectLogContainsSomewhere(
374 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST_HEADERS,
375 NetLog::PHASE_NONE);
376 ExpectLogContainsSomewhere(
377 entries, pos,
378 NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS,
379 NetLog::PHASE_NONE);
381 std::string line;
382 EXPECT_TRUE(entries[pos].GetStringValue("line", &line));
383 EXPECT_EQ("GET / HTTP/1.1\r\n", line);
385 HttpRequestHeaders request_headers;
386 EXPECT_TRUE(trans->GetFullRequestHeaders(&request_headers));
387 std::string value;
388 EXPECT_TRUE(request_headers.GetHeader("Host", &value));
389 EXPECT_EQ("www.example.org", value);
390 EXPECT_TRUE(request_headers.GetHeader("Connection", &value));
391 EXPECT_EQ("keep-alive", value);
393 std::string response_headers;
394 EXPECT_TRUE(GetHeaders(entries[pos].params.get(), &response_headers));
395 EXPECT_EQ("['Host: www.example.org','Connection: keep-alive']",
396 response_headers);
398 out.total_received_bytes = trans->GetTotalReceivedBytes();
399 // The total number of sent bytes should not have changed.
400 EXPECT_EQ(out.total_sent_bytes, trans->GetTotalSentBytes());
402 trans->GetConnectionAttempts(&out.connection_attempts);
403 return out;
406 SimpleGetHelperResult SimpleGetHelper(MockRead data_reads[],
407 size_t reads_count) {
408 MockWrite data_writes[] = {
409 MockWrite("GET / HTTP/1.1\r\n"
410 "Host: www.example.org\r\n"
411 "Connection: keep-alive\r\n\r\n"),
414 StaticSocketDataProvider reads(data_reads, reads_count, data_writes,
415 arraysize(data_writes));
416 StaticSocketDataProvider* data[] = {&reads};
417 SimpleGetHelperResult out = SimpleGetHelperForData(data, 1);
419 EXPECT_EQ(CountWriteBytes(data_writes, arraysize(data_writes)),
420 out.total_sent_bytes);
421 return out;
424 void ConnectStatusHelperWithExpectedStatus(const MockRead& status,
425 int expected_status);
427 void ConnectStatusHelper(const MockRead& status);
429 void BypassHostCacheOnRefreshHelper(int load_flags);
431 void CheckErrorIsPassedBack(int error, IoMode mode);
433 SpdyTestUtil spdy_util_;
434 SpdySessionDependencies session_deps_;
436 // Original socket limits. Some tests set these. Safest to always restore
437 // them once each test has been run.
438 int old_max_group_sockets_;
439 int old_max_pool_sockets_;
442 INSTANTIATE_TEST_CASE_P(NextProto,
443 HttpNetworkTransactionTest,
444 testing::Values(kProtoSPDY31,
445 kProtoHTTP2));
447 namespace {
449 class BeforeNetworkStartHandler {
450 public:
451 explicit BeforeNetworkStartHandler(bool defer)
452 : defer_on_before_network_start_(defer),
453 observed_before_network_start_(false) {}
455 void OnBeforeNetworkStart(bool* defer) {
456 *defer = defer_on_before_network_start_;
457 observed_before_network_start_ = true;
460 bool observed_before_network_start() const {
461 return observed_before_network_start_;
464 private:
465 const bool defer_on_before_network_start_;
466 bool observed_before_network_start_;
468 DISALLOW_COPY_AND_ASSIGN(BeforeNetworkStartHandler);
471 class BeforeProxyHeadersSentHandler {
472 public:
473 BeforeProxyHeadersSentHandler()
474 : observed_before_proxy_headers_sent_(false) {}
476 void OnBeforeProxyHeadersSent(const ProxyInfo& proxy_info,
477 HttpRequestHeaders* request_headers) {
478 observed_before_proxy_headers_sent_ = true;
479 observed_proxy_server_uri_ = proxy_info.proxy_server().ToURI();
482 bool observed_before_proxy_headers_sent() const {
483 return observed_before_proxy_headers_sent_;
486 std::string observed_proxy_server_uri() const {
487 return observed_proxy_server_uri_;
490 private:
491 bool observed_before_proxy_headers_sent_;
492 std::string observed_proxy_server_uri_;
494 DISALLOW_COPY_AND_ASSIGN(BeforeProxyHeadersSentHandler);
497 // Fill |str| with a long header list that consumes >= |size| bytes.
498 void FillLargeHeadersString(std::string* str, int size) {
499 const char row[] =
500 "SomeHeaderName: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n";
501 const int sizeof_row = strlen(row);
502 const int num_rows = static_cast<int>(
503 ceil(static_cast<float>(size) / sizeof_row));
504 const int sizeof_data = num_rows * sizeof_row;
505 DCHECK(sizeof_data >= size);
506 str->reserve(sizeof_data);
508 for (int i = 0; i < num_rows; ++i)
509 str->append(row, sizeof_row);
512 #if defined(NTLM_PORTABLE)
513 // Alternative functions that eliminate randomness and dependency on the local
514 // host name so that the generated NTLM messages are reproducible.
515 void MockGenerateRandom1(uint8* output, size_t n) {
516 static const uint8 bytes[] = {
517 0x55, 0x29, 0x66, 0x26, 0x6b, 0x9c, 0x73, 0x54
519 static size_t current_byte = 0;
520 for (size_t i = 0; i < n; ++i) {
521 output[i] = bytes[current_byte++];
522 current_byte %= arraysize(bytes);
526 void MockGenerateRandom2(uint8* output, size_t n) {
527 static const uint8 bytes[] = {
528 0x96, 0x79, 0x85, 0xe7, 0x49, 0x93, 0x70, 0xa1,
529 0x4e, 0xe7, 0x87, 0x45, 0x31, 0x5b, 0xd3, 0x1f
531 static size_t current_byte = 0;
532 for (size_t i = 0; i < n; ++i) {
533 output[i] = bytes[current_byte++];
534 current_byte %= arraysize(bytes);
538 std::string MockGetHostName() {
539 return "WTC-WIN7";
541 #endif // defined(NTLM_PORTABLE)
543 template<typename ParentPool>
544 class CaptureGroupNameSocketPool : public ParentPool {
545 public:
546 CaptureGroupNameSocketPool(HostResolver* host_resolver,
547 CertVerifier* cert_verifier);
549 const std::string last_group_name_received() const {
550 return last_group_name_;
553 int RequestSocket(const std::string& group_name,
554 const void* socket_params,
555 RequestPriority priority,
556 ClientSocketHandle* handle,
557 const CompletionCallback& callback,
558 const BoundNetLog& net_log) override {
559 last_group_name_ = group_name;
560 return ERR_IO_PENDING;
562 void CancelRequest(const std::string& group_name,
563 ClientSocketHandle* handle) override {}
564 void ReleaseSocket(const std::string& group_name,
565 scoped_ptr<StreamSocket> socket,
566 int id) override {}
567 void CloseIdleSockets() override {}
568 int IdleSocketCount() const override { return 0; }
569 int IdleSocketCountInGroup(const std::string& group_name) const override {
570 return 0;
572 LoadState GetLoadState(const std::string& group_name,
573 const ClientSocketHandle* handle) const override {
574 return LOAD_STATE_IDLE;
576 base::TimeDelta ConnectionTimeout() const override {
577 return base::TimeDelta();
580 private:
581 std::string last_group_name_;
584 typedef CaptureGroupNameSocketPool<TransportClientSocketPool>
585 CaptureGroupNameTransportSocketPool;
586 typedef CaptureGroupNameSocketPool<HttpProxyClientSocketPool>
587 CaptureGroupNameHttpProxySocketPool;
588 typedef CaptureGroupNameSocketPool<SOCKSClientSocketPool>
589 CaptureGroupNameSOCKSSocketPool;
590 typedef CaptureGroupNameSocketPool<SSLClientSocketPool>
591 CaptureGroupNameSSLSocketPool;
593 template <typename ParentPool>
594 CaptureGroupNameSocketPool<ParentPool>::CaptureGroupNameSocketPool(
595 HostResolver* host_resolver,
596 CertVerifier* /* cert_verifier */)
597 : ParentPool(0, 0, host_resolver, NULL, NULL) {
600 template <>
601 CaptureGroupNameHttpProxySocketPool::CaptureGroupNameSocketPool(
602 HostResolver* /* host_resolver */,
603 CertVerifier* /* cert_verifier */)
604 : HttpProxyClientSocketPool(0, 0, NULL, NULL, NULL) {
607 template <>
608 CaptureGroupNameSSLSocketPool::CaptureGroupNameSocketPool(
609 HostResolver* /* host_resolver */,
610 CertVerifier* cert_verifier)
611 : SSLClientSocketPool(0,
613 cert_verifier,
614 NULL,
615 NULL,
616 NULL,
617 NULL,
618 std::string(),
619 NULL,
620 NULL,
621 NULL,
622 NULL,
623 NULL,
624 NULL) {
627 //-----------------------------------------------------------------------------
629 // Helper functions for validating that AuthChallengeInfo's are correctly
630 // configured for common cases.
631 bool CheckBasicServerAuth(const AuthChallengeInfo* auth_challenge) {
632 if (!auth_challenge)
633 return false;
634 EXPECT_FALSE(auth_challenge->is_proxy);
635 EXPECT_EQ("www.example.org:80", auth_challenge->challenger.ToString());
636 EXPECT_EQ("MyRealm1", auth_challenge->realm);
637 EXPECT_EQ("basic", auth_challenge->scheme);
638 return true;
641 bool CheckBasicProxyAuth(const AuthChallengeInfo* auth_challenge) {
642 if (!auth_challenge)
643 return false;
644 EXPECT_TRUE(auth_challenge->is_proxy);
645 EXPECT_EQ("myproxy:70", auth_challenge->challenger.ToString());
646 EXPECT_EQ("MyRealm1", auth_challenge->realm);
647 EXPECT_EQ("basic", auth_challenge->scheme);
648 return true;
651 bool CheckDigestServerAuth(const AuthChallengeInfo* auth_challenge) {
652 if (!auth_challenge)
653 return false;
654 EXPECT_FALSE(auth_challenge->is_proxy);
655 EXPECT_EQ("www.example.org:80", auth_challenge->challenger.ToString());
656 EXPECT_EQ("digestive", auth_challenge->realm);
657 EXPECT_EQ("digest", auth_challenge->scheme);
658 return true;
661 #if defined(NTLM_PORTABLE)
662 bool CheckNTLMServerAuth(const AuthChallengeInfo* auth_challenge) {
663 if (!auth_challenge)
664 return false;
665 EXPECT_FALSE(auth_challenge->is_proxy);
666 EXPECT_EQ("172.22.68.17:80", auth_challenge->challenger.ToString());
667 EXPECT_EQ(std::string(), auth_challenge->realm);
668 EXPECT_EQ("ntlm", auth_challenge->scheme);
669 return true;
671 #endif // defined(NTLM_PORTABLE)
673 } // namespace
675 TEST_P(HttpNetworkTransactionTest, Basic) {
676 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
677 scoped_ptr<HttpTransaction> trans(
678 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
681 TEST_P(HttpNetworkTransactionTest, SimpleGET) {
682 MockRead data_reads[] = {
683 MockRead("HTTP/1.0 200 OK\r\n\r\n"),
684 MockRead("hello world"),
685 MockRead(SYNCHRONOUS, OK),
687 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
688 arraysize(data_reads));
689 EXPECT_EQ(OK, out.rv);
690 EXPECT_EQ("HTTP/1.0 200 OK", out.status_line);
691 EXPECT_EQ("hello world", out.response_data);
692 int64_t reads_size = CountReadBytes(data_reads, arraysize(data_reads));
693 EXPECT_EQ(reads_size, out.total_received_bytes);
694 EXPECT_EQ(0u, out.connection_attempts.size());
697 // Response with no status line.
698 TEST_P(HttpNetworkTransactionTest, SimpleGETNoHeaders) {
699 MockRead data_reads[] = {
700 MockRead("hello world"),
701 MockRead(SYNCHRONOUS, OK),
703 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
704 arraysize(data_reads));
705 EXPECT_EQ(OK, out.rv);
706 EXPECT_EQ("HTTP/0.9 200 OK", out.status_line);
707 EXPECT_EQ("hello world", out.response_data);
708 int64_t reads_size = CountReadBytes(data_reads, arraysize(data_reads));
709 EXPECT_EQ(reads_size, out.total_received_bytes);
712 // Allow up to 4 bytes of junk to precede status line.
713 TEST_P(HttpNetworkTransactionTest, StatusLineJunk3Bytes) {
714 MockRead data_reads[] = {
715 MockRead("xxxHTTP/1.0 404 Not Found\nServer: blah\n\nDATA"),
716 MockRead(SYNCHRONOUS, OK),
718 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
719 arraysize(data_reads));
720 EXPECT_EQ(OK, out.rv);
721 EXPECT_EQ("HTTP/1.0 404 Not Found", out.status_line);
722 EXPECT_EQ("DATA", out.response_data);
723 int64_t reads_size = CountReadBytes(data_reads, arraysize(data_reads));
724 EXPECT_EQ(reads_size, out.total_received_bytes);
727 // Allow up to 4 bytes of junk to precede status line.
728 TEST_P(HttpNetworkTransactionTest, StatusLineJunk4Bytes) {
729 MockRead data_reads[] = {
730 MockRead("\n\nQJHTTP/1.0 404 Not Found\nServer: blah\n\nDATA"),
731 MockRead(SYNCHRONOUS, OK),
733 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
734 arraysize(data_reads));
735 EXPECT_EQ(OK, out.rv);
736 EXPECT_EQ("HTTP/1.0 404 Not Found", out.status_line);
737 EXPECT_EQ("DATA", out.response_data);
738 int64_t reads_size = CountReadBytes(data_reads, arraysize(data_reads));
739 EXPECT_EQ(reads_size, out.total_received_bytes);
742 // Beyond 4 bytes of slop and it should fail to find a status line.
743 TEST_P(HttpNetworkTransactionTest, StatusLineJunk5Bytes) {
744 MockRead data_reads[] = {
745 MockRead("xxxxxHTTP/1.1 404 Not Found\nServer: blah"),
746 MockRead(SYNCHRONOUS, OK),
748 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
749 arraysize(data_reads));
750 EXPECT_EQ(OK, out.rv);
751 EXPECT_EQ("HTTP/0.9 200 OK", out.status_line);
752 EXPECT_EQ("xxxxxHTTP/1.1 404 Not Found\nServer: blah", out.response_data);
753 int64_t reads_size = CountReadBytes(data_reads, arraysize(data_reads));
754 EXPECT_EQ(reads_size, out.total_received_bytes);
757 // Same as StatusLineJunk4Bytes, except the read chunks are smaller.
758 TEST_P(HttpNetworkTransactionTest, StatusLineJunk4Bytes_Slow) {
759 MockRead data_reads[] = {
760 MockRead("\n"),
761 MockRead("\n"),
762 MockRead("Q"),
763 MockRead("J"),
764 MockRead("HTTP/1.0 404 Not Found\nServer: blah\n\nDATA"),
765 MockRead(SYNCHRONOUS, OK),
767 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
768 arraysize(data_reads));
769 EXPECT_EQ(OK, out.rv);
770 EXPECT_EQ("HTTP/1.0 404 Not Found", out.status_line);
771 EXPECT_EQ("DATA", out.response_data);
772 int64_t reads_size = CountReadBytes(data_reads, arraysize(data_reads));
773 EXPECT_EQ(reads_size, out.total_received_bytes);
776 // Close the connection before enough bytes to have a status line.
777 TEST_P(HttpNetworkTransactionTest, StatusLinePartial) {
778 MockRead data_reads[] = {
779 MockRead("HTT"),
780 MockRead(SYNCHRONOUS, OK),
782 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
783 arraysize(data_reads));
784 EXPECT_EQ(OK, out.rv);
785 EXPECT_EQ("HTTP/0.9 200 OK", out.status_line);
786 EXPECT_EQ("HTT", out.response_data);
787 int64_t reads_size = CountReadBytes(data_reads, arraysize(data_reads));
788 EXPECT_EQ(reads_size, out.total_received_bytes);
791 // Simulate a 204 response, lacking a Content-Length header, sent over a
792 // persistent connection. The response should still terminate since a 204
793 // cannot have a response body.
794 TEST_P(HttpNetworkTransactionTest, StopsReading204) {
795 char junk[] = "junk";
796 MockRead data_reads[] = {
797 MockRead("HTTP/1.1 204 No Content\r\n\r\n"),
798 MockRead(junk), // Should not be read!!
799 MockRead(SYNCHRONOUS, OK),
801 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
802 arraysize(data_reads));
803 EXPECT_EQ(OK, out.rv);
804 EXPECT_EQ("HTTP/1.1 204 No Content", out.status_line);
805 EXPECT_EQ("", out.response_data);
806 int64_t reads_size = CountReadBytes(data_reads, arraysize(data_reads));
807 int64_t response_size = reads_size - strlen(junk);
808 EXPECT_EQ(response_size, out.total_received_bytes);
811 // A simple request using chunked encoding with some extra data after.
812 TEST_P(HttpNetworkTransactionTest, ChunkedEncoding) {
813 std::string final_chunk = "0\r\n\r\n";
814 std::string extra_data = "HTTP/1.1 200 OK\r\n";
815 std::string last_read = final_chunk + extra_data;
816 MockRead data_reads[] = {
817 MockRead("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"),
818 MockRead("5\r\nHello\r\n"),
819 MockRead("1\r\n"),
820 MockRead(" \r\n"),
821 MockRead("5\r\nworld\r\n"),
822 MockRead(last_read.data()),
823 MockRead(SYNCHRONOUS, OK),
825 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
826 arraysize(data_reads));
827 EXPECT_EQ(OK, out.rv);
828 EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
829 EXPECT_EQ("Hello world", out.response_data);
830 int64_t reads_size = CountReadBytes(data_reads, arraysize(data_reads));
831 int64_t response_size = reads_size - extra_data.size();
832 EXPECT_EQ(response_size, out.total_received_bytes);
835 // Next tests deal with http://crbug.com/56344.
837 TEST_P(HttpNetworkTransactionTest,
838 MultipleContentLengthHeadersNoTransferEncoding) {
839 MockRead data_reads[] = {
840 MockRead("HTTP/1.1 200 OK\r\n"),
841 MockRead("Content-Length: 10\r\n"),
842 MockRead("Content-Length: 5\r\n\r\n"),
844 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
845 arraysize(data_reads));
846 EXPECT_EQ(ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH, out.rv);
849 TEST_P(HttpNetworkTransactionTest,
850 DuplicateContentLengthHeadersNoTransferEncoding) {
851 MockRead data_reads[] = {
852 MockRead("HTTP/1.1 200 OK\r\n"),
853 MockRead("Content-Length: 5\r\n"),
854 MockRead("Content-Length: 5\r\n\r\n"),
855 MockRead("Hello"),
857 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
858 arraysize(data_reads));
859 EXPECT_EQ(OK, out.rv);
860 EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
861 EXPECT_EQ("Hello", out.response_data);
864 TEST_P(HttpNetworkTransactionTest,
865 ComplexContentLengthHeadersNoTransferEncoding) {
866 // More than 2 dupes.
868 MockRead data_reads[] = {
869 MockRead("HTTP/1.1 200 OK\r\n"),
870 MockRead("Content-Length: 5\r\n"),
871 MockRead("Content-Length: 5\r\n"),
872 MockRead("Content-Length: 5\r\n\r\n"),
873 MockRead("Hello"),
875 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
876 arraysize(data_reads));
877 EXPECT_EQ(OK, out.rv);
878 EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
879 EXPECT_EQ("Hello", out.response_data);
881 // HTTP/1.0
883 MockRead data_reads[] = {
884 MockRead("HTTP/1.0 200 OK\r\n"),
885 MockRead("Content-Length: 5\r\n"),
886 MockRead("Content-Length: 5\r\n"),
887 MockRead("Content-Length: 5\r\n\r\n"),
888 MockRead("Hello"),
890 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
891 arraysize(data_reads));
892 EXPECT_EQ(OK, out.rv);
893 EXPECT_EQ("HTTP/1.0 200 OK", out.status_line);
894 EXPECT_EQ("Hello", out.response_data);
896 // 2 dupes and one mismatched.
898 MockRead data_reads[] = {
899 MockRead("HTTP/1.1 200 OK\r\n"),
900 MockRead("Content-Length: 10\r\n"),
901 MockRead("Content-Length: 10\r\n"),
902 MockRead("Content-Length: 5\r\n\r\n"),
904 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
905 arraysize(data_reads));
906 EXPECT_EQ(ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH, out.rv);
910 TEST_P(HttpNetworkTransactionTest,
911 MultipleContentLengthHeadersTransferEncoding) {
912 MockRead data_reads[] = {
913 MockRead("HTTP/1.1 200 OK\r\n"),
914 MockRead("Content-Length: 666\r\n"),
915 MockRead("Content-Length: 1337\r\n"),
916 MockRead("Transfer-Encoding: chunked\r\n\r\n"),
917 MockRead("5\r\nHello\r\n"),
918 MockRead("1\r\n"),
919 MockRead(" \r\n"),
920 MockRead("5\r\nworld\r\n"),
921 MockRead("0\r\n\r\nHTTP/1.1 200 OK\r\n"),
922 MockRead(SYNCHRONOUS, OK),
924 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
925 arraysize(data_reads));
926 EXPECT_EQ(OK, out.rv);
927 EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
928 EXPECT_EQ("Hello world", out.response_data);
931 // Next tests deal with http://crbug.com/98895.
933 // Checks that a single Content-Disposition header results in no error.
934 TEST_P(HttpNetworkTransactionTest, SingleContentDispositionHeader) {
935 MockRead data_reads[] = {
936 MockRead("HTTP/1.1 200 OK\r\n"),
937 MockRead("Content-Disposition: attachment;filename=\"salutations.txt\"r\n"),
938 MockRead("Content-Length: 5\r\n\r\n"),
939 MockRead("Hello"),
941 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
942 arraysize(data_reads));
943 EXPECT_EQ(OK, out.rv);
944 EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
945 EXPECT_EQ("Hello", out.response_data);
948 // Checks that two identical Content-Disposition headers result in no error.
949 TEST_P(HttpNetworkTransactionTest,
950 TwoIdenticalContentDispositionHeaders) {
951 MockRead data_reads[] = {
952 MockRead("HTTP/1.1 200 OK\r\n"),
953 MockRead("Content-Disposition: attachment;filename=\"greetings.txt\"r\n"),
954 MockRead("Content-Disposition: attachment;filename=\"greetings.txt\"r\n"),
955 MockRead("Content-Length: 5\r\n\r\n"),
956 MockRead("Hello"),
958 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
959 arraysize(data_reads));
960 EXPECT_EQ(OK, out.rv);
961 EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
962 EXPECT_EQ("Hello", out.response_data);
965 // Checks that two distinct Content-Disposition headers result in an error.
966 TEST_P(HttpNetworkTransactionTest, TwoDistinctContentDispositionHeaders) {
967 MockRead data_reads[] = {
968 MockRead("HTTP/1.1 200 OK\r\n"),
969 MockRead("Content-Disposition: attachment;filename=\"greetings.txt\"r\n"),
970 MockRead("Content-Disposition: attachment;filename=\"hi.txt\"r\n"),
971 MockRead("Content-Length: 5\r\n\r\n"),
972 MockRead("Hello"),
974 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
975 arraysize(data_reads));
976 EXPECT_EQ(ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION, out.rv);
979 // Checks that two identical Location headers result in no error.
980 // Also tests Location header behavior.
981 TEST_P(HttpNetworkTransactionTest, TwoIdenticalLocationHeaders) {
982 MockRead data_reads[] = {
983 MockRead("HTTP/1.1 302 Redirect\r\n"),
984 MockRead("Location: http://good.com/\r\n"),
985 MockRead("Location: http://good.com/\r\n"),
986 MockRead("Content-Length: 0\r\n\r\n"),
987 MockRead(SYNCHRONOUS, OK),
990 HttpRequestInfo request;
991 request.method = "GET";
992 request.url = GURL("http://redirect.com/");
993 request.load_flags = 0;
995 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
996 scoped_ptr<HttpTransaction> trans(
997 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
999 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1000 session_deps_.socket_factory->AddSocketDataProvider(&data);
1002 TestCompletionCallback callback;
1004 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1005 EXPECT_EQ(ERR_IO_PENDING, rv);
1007 EXPECT_EQ(OK, callback.WaitForResult());
1009 const HttpResponseInfo* response = trans->GetResponseInfo();
1010 ASSERT_TRUE(response != NULL && response->headers.get() != NULL);
1011 EXPECT_EQ("HTTP/1.1 302 Redirect", response->headers->GetStatusLine());
1012 std::string url;
1013 EXPECT_TRUE(response->headers->IsRedirect(&url));
1014 EXPECT_EQ("http://good.com/", url);
1015 EXPECT_TRUE(response->proxy_server.IsEmpty());
1018 // Checks that two distinct Location headers result in an error.
1019 TEST_P(HttpNetworkTransactionTest, TwoDistinctLocationHeaders) {
1020 MockRead data_reads[] = {
1021 MockRead("HTTP/1.1 302 Redirect\r\n"),
1022 MockRead("Location: http://good.com/\r\n"),
1023 MockRead("Location: http://evil.com/\r\n"),
1024 MockRead("Content-Length: 0\r\n\r\n"),
1025 MockRead(SYNCHRONOUS, OK),
1027 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
1028 arraysize(data_reads));
1029 EXPECT_EQ(ERR_RESPONSE_HEADERS_MULTIPLE_LOCATION, out.rv);
1032 // Do a request using the HEAD method. Verify that we don't try to read the
1033 // message body (since HEAD has none).
1034 TEST_P(HttpNetworkTransactionTest, Head) {
1035 HttpRequestInfo request;
1036 request.method = "HEAD";
1037 request.url = GURL("http://www.example.org/");
1038 request.load_flags = 0;
1040 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1041 scoped_ptr<HttpTransaction> trans(
1042 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1043 BeforeProxyHeadersSentHandler proxy_headers_handler;
1044 trans->SetBeforeProxyHeadersSentCallback(
1045 base::Bind(&BeforeProxyHeadersSentHandler::OnBeforeProxyHeadersSent,
1046 base::Unretained(&proxy_headers_handler)));
1048 MockWrite data_writes1[] = {
1049 MockWrite("HEAD / HTTP/1.1\r\n"
1050 "Host: www.example.org\r\n"
1051 "Connection: keep-alive\r\n\r\n"),
1053 MockRead data_reads1[] = {
1054 MockRead("HTTP/1.1 404 Not Found\r\n"),
1055 MockRead("Server: Blah\r\n"),
1056 MockRead("Content-Length: 1234\r\n\r\n"),
1058 // No response body because the test stops reading here.
1059 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
1062 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
1063 data_writes1, arraysize(data_writes1));
1064 session_deps_.socket_factory->AddSocketDataProvider(&data1);
1066 TestCompletionCallback callback1;
1068 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
1069 EXPECT_EQ(ERR_IO_PENDING, rv);
1071 rv = callback1.WaitForResult();
1072 EXPECT_EQ(OK, rv);
1074 const HttpResponseInfo* response = trans->GetResponseInfo();
1075 ASSERT_TRUE(response != NULL);
1077 // Check that the headers got parsed.
1078 EXPECT_TRUE(response->headers.get() != NULL);
1079 EXPECT_EQ(1234, response->headers->GetContentLength());
1080 EXPECT_EQ("HTTP/1.1 404 Not Found", response->headers->GetStatusLine());
1081 EXPECT_TRUE(response->proxy_server.IsEmpty());
1082 EXPECT_FALSE(proxy_headers_handler.observed_before_proxy_headers_sent());
1084 std::string server_header;
1085 void* iter = NULL;
1086 bool has_server_header = response->headers->EnumerateHeader(
1087 &iter, "Server", &server_header);
1088 EXPECT_TRUE(has_server_header);
1089 EXPECT_EQ("Blah", server_header);
1091 // Reading should give EOF right away, since there is no message body
1092 // (despite non-zero content-length).
1093 std::string response_data;
1094 rv = ReadTransaction(trans.get(), &response_data);
1095 EXPECT_EQ(OK, rv);
1096 EXPECT_EQ("", response_data);
1099 TEST_P(HttpNetworkTransactionTest, ReuseConnection) {
1100 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1102 MockRead data_reads[] = {
1103 MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
1104 MockRead("hello"),
1105 MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
1106 MockRead("world"),
1107 MockRead(SYNCHRONOUS, OK),
1109 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1110 session_deps_.socket_factory->AddSocketDataProvider(&data);
1112 const char* const kExpectedResponseData[] = {
1113 "hello", "world"
1116 for (int i = 0; i < 2; ++i) {
1117 HttpRequestInfo request;
1118 request.method = "GET";
1119 request.url = GURL("http://www.example.org/");
1120 request.load_flags = 0;
1122 scoped_ptr<HttpTransaction> trans(
1123 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1125 TestCompletionCallback callback;
1127 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1128 EXPECT_EQ(ERR_IO_PENDING, rv);
1130 rv = callback.WaitForResult();
1131 EXPECT_EQ(OK, rv);
1133 const HttpResponseInfo* response = trans->GetResponseInfo();
1134 ASSERT_TRUE(response != NULL);
1136 EXPECT_TRUE(response->headers.get() != NULL);
1137 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
1138 EXPECT_TRUE(response->proxy_server.IsEmpty());
1140 std::string response_data;
1141 rv = ReadTransaction(trans.get(), &response_data);
1142 EXPECT_EQ(OK, rv);
1143 EXPECT_EQ(kExpectedResponseData[i], response_data);
1147 TEST_P(HttpNetworkTransactionTest, Ignores100) {
1148 ScopedVector<UploadElementReader> element_readers;
1149 element_readers.push_back(new UploadBytesElementReader("foo", 3));
1150 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
1152 HttpRequestInfo request;
1153 request.method = "POST";
1154 request.url = GURL("http://www.foo.com/");
1155 request.upload_data_stream = &upload_data_stream;
1156 request.load_flags = 0;
1158 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1159 scoped_ptr<HttpTransaction> trans(
1160 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1162 MockRead data_reads[] = {
1163 MockRead("HTTP/1.0 100 Continue\r\n\r\n"),
1164 MockRead("HTTP/1.0 200 OK\r\n\r\n"),
1165 MockRead("hello world"),
1166 MockRead(SYNCHRONOUS, OK),
1168 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1169 session_deps_.socket_factory->AddSocketDataProvider(&data);
1171 TestCompletionCallback callback;
1173 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1174 EXPECT_EQ(ERR_IO_PENDING, rv);
1176 rv = callback.WaitForResult();
1177 EXPECT_EQ(OK, rv);
1179 const HttpResponseInfo* response = trans->GetResponseInfo();
1180 ASSERT_TRUE(response != NULL);
1182 EXPECT_TRUE(response->headers.get() != NULL);
1183 EXPECT_EQ("HTTP/1.0 200 OK", response->headers->GetStatusLine());
1185 std::string response_data;
1186 rv = ReadTransaction(trans.get(), &response_data);
1187 EXPECT_EQ(OK, rv);
1188 EXPECT_EQ("hello world", response_data);
1191 // This test is almost the same as Ignores100 above, but the response contains
1192 // a 102 instead of a 100. Also, instead of HTTP/1.0 the response is
1193 // HTTP/1.1 and the two status headers are read in one read.
1194 TEST_P(HttpNetworkTransactionTest, Ignores1xx) {
1195 HttpRequestInfo request;
1196 request.method = "GET";
1197 request.url = GURL("http://www.foo.com/");
1198 request.load_flags = 0;
1200 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1201 scoped_ptr<HttpTransaction> trans(
1202 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1204 MockRead data_reads[] = {
1205 MockRead("HTTP/1.1 102 Unspecified status code\r\n\r\n"
1206 "HTTP/1.1 200 OK\r\n\r\n"),
1207 MockRead("hello world"),
1208 MockRead(SYNCHRONOUS, OK),
1210 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1211 session_deps_.socket_factory->AddSocketDataProvider(&data);
1213 TestCompletionCallback callback;
1215 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1216 EXPECT_EQ(ERR_IO_PENDING, rv);
1218 rv = callback.WaitForResult();
1219 EXPECT_EQ(OK, rv);
1221 const HttpResponseInfo* response = trans->GetResponseInfo();
1222 ASSERT_TRUE(response != NULL);
1224 EXPECT_TRUE(response->headers.get() != NULL);
1225 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
1227 std::string response_data;
1228 rv = ReadTransaction(trans.get(), &response_data);
1229 EXPECT_EQ(OK, rv);
1230 EXPECT_EQ("hello world", response_data);
1233 TEST_P(HttpNetworkTransactionTest, Incomplete100ThenEOF) {
1234 HttpRequestInfo request;
1235 request.method = "POST";
1236 request.url = GURL("http://www.foo.com/");
1237 request.load_flags = 0;
1239 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1240 scoped_ptr<HttpTransaction> trans(
1241 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1243 MockRead data_reads[] = {
1244 MockRead(SYNCHRONOUS, "HTTP/1.0 100 Continue\r\n"),
1245 MockRead(ASYNC, 0),
1247 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1248 session_deps_.socket_factory->AddSocketDataProvider(&data);
1250 TestCompletionCallback callback;
1252 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1253 EXPECT_EQ(ERR_IO_PENDING, rv);
1255 rv = callback.WaitForResult();
1256 EXPECT_EQ(OK, rv);
1258 std::string response_data;
1259 rv = ReadTransaction(trans.get(), &response_data);
1260 EXPECT_EQ(OK, rv);
1261 EXPECT_EQ("", response_data);
1264 TEST_P(HttpNetworkTransactionTest, EmptyResponse) {
1265 HttpRequestInfo request;
1266 request.method = "POST";
1267 request.url = GURL("http://www.foo.com/");
1268 request.load_flags = 0;
1270 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1271 scoped_ptr<HttpTransaction> trans(
1272 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1274 MockRead data_reads[] = {
1275 MockRead(ASYNC, 0),
1277 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1278 session_deps_.socket_factory->AddSocketDataProvider(&data);
1280 TestCompletionCallback callback;
1282 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1283 EXPECT_EQ(ERR_IO_PENDING, rv);
1285 rv = callback.WaitForResult();
1286 EXPECT_EQ(ERR_EMPTY_RESPONSE, rv);
1289 void HttpNetworkTransactionTest::KeepAliveConnectionResendRequestTest(
1290 const MockWrite* write_failure,
1291 const MockRead* read_failure) {
1292 HttpRequestInfo request;
1293 request.method = "GET";
1294 request.url = GURL("http://www.foo.com/");
1295 request.load_flags = 0;
1297 TestNetLog net_log;
1298 session_deps_.net_log = &net_log;
1299 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1301 // Written data for successfully sending both requests.
1302 MockWrite data1_writes[] = {
1303 MockWrite("GET / HTTP/1.1\r\n"
1304 "Host: www.foo.com\r\n"
1305 "Connection: keep-alive\r\n\r\n"),
1306 MockWrite("GET / HTTP/1.1\r\n"
1307 "Host: www.foo.com\r\n"
1308 "Connection: keep-alive\r\n\r\n")
1311 // Read results for the first request.
1312 MockRead data1_reads[] = {
1313 MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
1314 MockRead("hello"),
1315 MockRead(ASYNC, OK),
1318 if (write_failure) {
1319 ASSERT_FALSE(read_failure);
1320 data1_writes[1] = *write_failure;
1321 } else {
1322 ASSERT_TRUE(read_failure);
1323 data1_reads[2] = *read_failure;
1326 StaticSocketDataProvider data1(data1_reads, arraysize(data1_reads),
1327 data1_writes, arraysize(data1_writes));
1328 session_deps_.socket_factory->AddSocketDataProvider(&data1);
1330 MockRead data2_reads[] = {
1331 MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
1332 MockRead("world"),
1333 MockRead(ASYNC, OK),
1335 StaticSocketDataProvider data2(data2_reads, arraysize(data2_reads), NULL, 0);
1336 session_deps_.socket_factory->AddSocketDataProvider(&data2);
1338 const char* const kExpectedResponseData[] = {
1339 "hello", "world"
1342 uint32 first_socket_log_id = NetLog::Source::kInvalidId;
1343 for (int i = 0; i < 2; ++i) {
1344 TestCompletionCallback callback;
1346 scoped_ptr<HttpTransaction> trans(
1347 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1349 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1350 EXPECT_EQ(ERR_IO_PENDING, rv);
1352 rv = callback.WaitForResult();
1353 EXPECT_EQ(OK, rv);
1355 LoadTimingInfo load_timing_info;
1356 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
1357 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
1358 if (i == 0) {
1359 first_socket_log_id = load_timing_info.socket_log_id;
1360 } else {
1361 // The second request should be using a new socket.
1362 EXPECT_NE(first_socket_log_id, load_timing_info.socket_log_id);
1365 const HttpResponseInfo* response = trans->GetResponseInfo();
1366 ASSERT_TRUE(response != NULL);
1368 EXPECT_TRUE(response->headers.get() != NULL);
1369 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
1371 std::string response_data;
1372 rv = ReadTransaction(trans.get(), &response_data);
1373 EXPECT_EQ(OK, rv);
1374 EXPECT_EQ(kExpectedResponseData[i], response_data);
1378 void HttpNetworkTransactionTest::PreconnectErrorResendRequestTest(
1379 const MockWrite* write_failure,
1380 const MockRead* read_failure,
1381 bool use_spdy) {
1382 HttpRequestInfo request;
1383 request.method = "GET";
1384 request.url = GURL("https://www.foo.com/");
1385 request.load_flags = 0;
1387 TestNetLog net_log;
1388 session_deps_.net_log = &net_log;
1389 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1391 SSLSocketDataProvider ssl1(ASYNC, OK);
1392 SSLSocketDataProvider ssl2(ASYNC, OK);
1393 if (use_spdy) {
1394 ssl1.SetNextProto(GetParam());
1395 ssl2.SetNextProto(GetParam());
1397 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
1398 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
1400 // SPDY versions of the request and response.
1401 scoped_ptr<SpdyFrame> spdy_request(spdy_util_.ConstructSpdyGet(
1402 request.url.spec().c_str(), false, 1, DEFAULT_PRIORITY));
1403 scoped_ptr<SpdyFrame> spdy_response(
1404 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
1405 scoped_ptr<SpdyFrame> spdy_data(
1406 spdy_util_.ConstructSpdyBodyFrame(1, "hello", 5, true));
1408 // HTTP/1.1 versions of the request and response.
1409 const char kHttpRequest[] = "GET / HTTP/1.1\r\n"
1410 "Host: www.foo.com\r\n"
1411 "Connection: keep-alive\r\n\r\n";
1412 const char kHttpResponse[] = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n";
1413 const char kHttpData[] = "hello";
1415 std::vector<MockRead> data1_reads;
1416 std::vector<MockWrite> data1_writes;
1417 if (write_failure) {
1418 ASSERT_FALSE(read_failure);
1419 data1_writes.push_back(*write_failure);
1420 data1_reads.push_back(MockRead(ASYNC, OK));
1421 } else {
1422 ASSERT_TRUE(read_failure);
1423 if (use_spdy) {
1424 data1_writes.push_back(CreateMockWrite(*spdy_request));
1425 } else {
1426 data1_writes.push_back(MockWrite(kHttpRequest));
1428 data1_reads.push_back(*read_failure);
1431 StaticSocketDataProvider data1(&data1_reads[0], data1_reads.size(),
1432 &data1_writes[0], data1_writes.size());
1433 session_deps_.socket_factory->AddSocketDataProvider(&data1);
1435 std::vector<MockRead> data2_reads;
1436 std::vector<MockWrite> data2_writes;
1438 if (use_spdy) {
1439 data2_writes.push_back(CreateMockWrite(*spdy_request, 0, ASYNC));
1441 data2_reads.push_back(CreateMockRead(*spdy_response, 1, ASYNC));
1442 data2_reads.push_back(CreateMockRead(*spdy_data, 2, ASYNC));
1443 data2_reads.push_back(MockRead(ASYNC, OK, 3));
1444 } else {
1445 data2_writes.push_back(
1446 MockWrite(ASYNC, kHttpRequest, strlen(kHttpRequest), 0));
1448 data2_reads.push_back(
1449 MockRead(ASYNC, kHttpResponse, strlen(kHttpResponse), 1));
1450 data2_reads.push_back(MockRead(ASYNC, kHttpData, strlen(kHttpData), 2));
1451 data2_reads.push_back(MockRead(ASYNC, OK, 3));
1453 SequencedSocketData data2(&data2_reads[0], data2_reads.size(),
1454 &data2_writes[0], data2_writes.size());
1455 session_deps_.socket_factory->AddSocketDataProvider(&data2);
1457 // Preconnect a socket.
1458 SSLConfig ssl_config;
1459 session->ssl_config_service()->GetSSLConfig(&ssl_config);
1460 session->GetNextProtos(&ssl_config.next_protos);
1461 session->http_stream_factory()->PreconnectStreams(1, request, ssl_config,
1462 ssl_config);
1463 // Wait for the preconnect to complete.
1464 // TODO(davidben): Some way to wait for an idle socket count might be handy.
1465 base::RunLoop().RunUntilIdle();
1466 EXPECT_EQ(1, GetIdleSocketCountInSSLSocketPool(session.get()));
1468 // Make the request.
1469 TestCompletionCallback callback;
1471 scoped_ptr<HttpTransaction> trans(
1472 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1474 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1475 EXPECT_EQ(ERR_IO_PENDING, rv);
1477 rv = callback.WaitForResult();
1478 EXPECT_EQ(OK, rv);
1480 LoadTimingInfo load_timing_info;
1481 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
1482 TestLoadTimingNotReused(
1483 load_timing_info,
1484 CONNECT_TIMING_HAS_DNS_TIMES|CONNECT_TIMING_HAS_SSL_TIMES);
1486 const HttpResponseInfo* response = trans->GetResponseInfo();
1487 ASSERT_TRUE(response != NULL);
1489 EXPECT_TRUE(response->headers.get() != NULL);
1490 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
1492 std::string response_data;
1493 rv = ReadTransaction(trans.get(), &response_data);
1494 EXPECT_EQ(OK, rv);
1495 EXPECT_EQ(kHttpData, response_data);
1498 TEST_P(HttpNetworkTransactionTest,
1499 KeepAliveConnectionNotConnectedOnWrite) {
1500 MockWrite write_failure(ASYNC, ERR_SOCKET_NOT_CONNECTED);
1501 KeepAliveConnectionResendRequestTest(&write_failure, NULL);
1504 TEST_P(HttpNetworkTransactionTest, KeepAliveConnectionReset) {
1505 MockRead read_failure(ASYNC, ERR_CONNECTION_RESET);
1506 KeepAliveConnectionResendRequestTest(NULL, &read_failure);
1509 TEST_P(HttpNetworkTransactionTest, KeepAliveConnectionEOF) {
1510 MockRead read_failure(SYNCHRONOUS, OK); // EOF
1511 KeepAliveConnectionResendRequestTest(NULL, &read_failure);
1514 // Make sure that on a 408 response (Request Timeout), the request is retried,
1515 // if the socket was a reused keep alive socket.
1516 TEST_P(HttpNetworkTransactionTest, KeepAlive408) {
1517 MockRead read_failure(SYNCHRONOUS,
1518 "HTTP/1.1 408 Request Timeout\r\n"
1519 "Connection: Keep-Alive\r\n"
1520 "Content-Length: 6\r\n\r\n"
1521 "Pickle");
1522 KeepAliveConnectionResendRequestTest(NULL, &read_failure);
1525 TEST_P(HttpNetworkTransactionTest,
1526 PreconnectErrorNotConnectedOnWrite) {
1527 MockWrite write_failure(ASYNC, ERR_SOCKET_NOT_CONNECTED);
1528 PreconnectErrorResendRequestTest(&write_failure, NULL, false);
1531 TEST_P(HttpNetworkTransactionTest, PreconnectErrorReset) {
1532 MockRead read_failure(ASYNC, ERR_CONNECTION_RESET);
1533 PreconnectErrorResendRequestTest(NULL, &read_failure, false);
1536 TEST_P(HttpNetworkTransactionTest, PreconnectErrorEOF) {
1537 MockRead read_failure(SYNCHRONOUS, OK); // EOF
1538 PreconnectErrorResendRequestTest(NULL, &read_failure, false);
1541 TEST_P(HttpNetworkTransactionTest, PreconnectErrorAsyncEOF) {
1542 MockRead read_failure(ASYNC, OK); // EOF
1543 PreconnectErrorResendRequestTest(NULL, &read_failure, false);
1546 // Make sure that on a 408 response (Request Timeout), the request is retried,
1547 // if the socket was a preconnected (UNUSED_IDLE) socket.
1548 TEST_P(HttpNetworkTransactionTest, RetryOnIdle408) {
1549 MockRead read_failure(SYNCHRONOUS,
1550 "HTTP/1.1 408 Request Timeout\r\n"
1551 "Connection: Keep-Alive\r\n"
1552 "Content-Length: 6\r\n\r\n"
1553 "Pickle");
1554 KeepAliveConnectionResendRequestTest(NULL, &read_failure);
1555 PreconnectErrorResendRequestTest(NULL, &read_failure, false);
1558 TEST_P(HttpNetworkTransactionTest,
1559 SpdyPreconnectErrorNotConnectedOnWrite) {
1560 MockWrite write_failure(ASYNC, ERR_SOCKET_NOT_CONNECTED);
1561 PreconnectErrorResendRequestTest(&write_failure, NULL, true);
1564 TEST_P(HttpNetworkTransactionTest, SpdyPreconnectErrorReset) {
1565 MockRead read_failure(ASYNC, ERR_CONNECTION_RESET);
1566 PreconnectErrorResendRequestTest(NULL, &read_failure, true);
1569 TEST_P(HttpNetworkTransactionTest, SpdyPreconnectErrorEOF) {
1570 MockRead read_failure(SYNCHRONOUS, OK); // EOF
1571 PreconnectErrorResendRequestTest(NULL, &read_failure, true);
1574 TEST_P(HttpNetworkTransactionTest, SpdyPreconnectErrorAsyncEOF) {
1575 MockRead read_failure(ASYNC, OK); // EOF
1576 PreconnectErrorResendRequestTest(NULL, &read_failure, true);
1579 TEST_P(HttpNetworkTransactionTest, NonKeepAliveConnectionReset) {
1580 HttpRequestInfo request;
1581 request.method = "GET";
1582 request.url = GURL("http://www.example.org/");
1583 request.load_flags = 0;
1585 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1586 scoped_ptr<HttpTransaction> trans(
1587 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1589 MockRead data_reads[] = {
1590 MockRead(ASYNC, ERR_CONNECTION_RESET),
1591 MockRead("HTTP/1.0 200 OK\r\n\r\n"), // Should not be used
1592 MockRead("hello world"),
1593 MockRead(SYNCHRONOUS, OK),
1595 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1596 session_deps_.socket_factory->AddSocketDataProvider(&data);
1598 TestCompletionCallback callback;
1600 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1601 EXPECT_EQ(ERR_IO_PENDING, rv);
1603 rv = callback.WaitForResult();
1604 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1607 // What do various browsers do when the server closes a non-keepalive
1608 // connection without sending any response header or body?
1610 // IE7: error page
1611 // Safari 3.1.2 (Windows): error page
1612 // Firefox 3.0.1: blank page
1613 // Opera 9.52: after five attempts, blank page
1614 // Us with WinHTTP: error page (ERR_INVALID_RESPONSE)
1615 // Us: error page (EMPTY_RESPONSE)
1616 TEST_P(HttpNetworkTransactionTest, NonKeepAliveConnectionEOF) {
1617 MockRead data_reads[] = {
1618 MockRead(SYNCHRONOUS, OK), // EOF
1619 MockRead("HTTP/1.0 200 OK\r\n\r\n"), // Should not be used
1620 MockRead("hello world"),
1621 MockRead(SYNCHRONOUS, OK),
1623 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
1624 arraysize(data_reads));
1625 EXPECT_EQ(ERR_EMPTY_RESPONSE, out.rv);
1628 // Test that network access can be deferred and resumed.
1629 TEST_P(HttpNetworkTransactionTest, ThrottleBeforeNetworkStart) {
1630 HttpRequestInfo request;
1631 request.method = "GET";
1632 request.url = GURL("http://www.example.org/");
1633 request.load_flags = 0;
1635 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1636 scoped_ptr<HttpTransaction> trans(
1637 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1639 // Defer on OnBeforeNetworkStart.
1640 BeforeNetworkStartHandler net_start_handler(true); // defer
1641 trans->SetBeforeNetworkStartCallback(
1642 base::Bind(&BeforeNetworkStartHandler::OnBeforeNetworkStart,
1643 base::Unretained(&net_start_handler)));
1645 MockRead data_reads[] = {
1646 MockRead("HTTP/1.0 200 OK\r\n"),
1647 MockRead("Content-Length: 5\r\n\r\n"),
1648 MockRead("hello"),
1649 MockRead(SYNCHRONOUS, 0),
1651 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1652 session_deps_.socket_factory->AddSocketDataProvider(&data);
1654 TestCompletionCallback callback;
1656 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1657 EXPECT_EQ(ERR_IO_PENDING, rv);
1658 base::MessageLoop::current()->RunUntilIdle();
1660 // Should have deferred for network start.
1661 EXPECT_TRUE(net_start_handler.observed_before_network_start());
1662 EXPECT_EQ(LOAD_STATE_WAITING_FOR_DELEGATE, trans->GetLoadState());
1664 trans->ResumeNetworkStart();
1665 rv = callback.WaitForResult();
1666 EXPECT_EQ(OK, rv);
1667 EXPECT_TRUE(trans->GetResponseInfo() != NULL);
1669 scoped_refptr<IOBufferWithSize> io_buf(new IOBufferWithSize(100));
1670 rv = trans->Read(io_buf.get(), io_buf->size(), callback.callback());
1671 if (rv == ERR_IO_PENDING)
1672 rv = callback.WaitForResult();
1673 EXPECT_EQ(5, rv);
1674 trans.reset();
1677 // Test that network use can be deferred and canceled.
1678 TEST_P(HttpNetworkTransactionTest, ThrottleAndCancelBeforeNetworkStart) {
1679 HttpRequestInfo request;
1680 request.method = "GET";
1681 request.url = GURL("http://www.example.org/");
1682 request.load_flags = 0;
1684 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1685 scoped_ptr<HttpTransaction> trans(
1686 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1688 // Defer on OnBeforeNetworkStart.
1689 BeforeNetworkStartHandler net_start_handler(true); // defer
1690 trans->SetBeforeNetworkStartCallback(
1691 base::Bind(&BeforeNetworkStartHandler::OnBeforeNetworkStart,
1692 base::Unretained(&net_start_handler)));
1694 TestCompletionCallback callback;
1696 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1697 EXPECT_EQ(ERR_IO_PENDING, rv);
1698 base::MessageLoop::current()->RunUntilIdle();
1700 // Should have deferred for network start.
1701 EXPECT_TRUE(net_start_handler.observed_before_network_start());
1702 EXPECT_EQ(LOAD_STATE_WAITING_FOR_DELEGATE, trans->GetLoadState());
1705 // Next 2 cases (KeepAliveEarlyClose and KeepAliveEarlyClose2) are regression
1706 // tests. There was a bug causing HttpNetworkTransaction to hang in the
1707 // destructor in such situations.
1708 // See http://crbug.com/154712 and http://crbug.com/156609.
1709 TEST_P(HttpNetworkTransactionTest, KeepAliveEarlyClose) {
1710 HttpRequestInfo request;
1711 request.method = "GET";
1712 request.url = GURL("http://www.example.org/");
1713 request.load_flags = 0;
1715 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1716 scoped_ptr<HttpTransaction> trans(
1717 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1719 MockRead data_reads[] = {
1720 MockRead("HTTP/1.0 200 OK\r\n"),
1721 MockRead("Connection: keep-alive\r\n"),
1722 MockRead("Content-Length: 100\r\n\r\n"),
1723 MockRead("hello"),
1724 MockRead(SYNCHRONOUS, 0),
1726 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1727 session_deps_.socket_factory->AddSocketDataProvider(&data);
1729 TestCompletionCallback callback;
1731 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1732 EXPECT_EQ(ERR_IO_PENDING, rv);
1734 rv = callback.WaitForResult();
1735 EXPECT_EQ(OK, rv);
1737 scoped_refptr<IOBufferWithSize> io_buf(new IOBufferWithSize(100));
1738 rv = trans->Read(io_buf.get(), io_buf->size(), callback.callback());
1739 if (rv == ERR_IO_PENDING)
1740 rv = callback.WaitForResult();
1741 EXPECT_EQ(5, rv);
1742 rv = trans->Read(io_buf.get(), io_buf->size(), callback.callback());
1743 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, rv);
1745 trans.reset();
1746 base::MessageLoop::current()->RunUntilIdle();
1747 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
1750 TEST_P(HttpNetworkTransactionTest, KeepAliveEarlyClose2) {
1751 HttpRequestInfo request;
1752 request.method = "GET";
1753 request.url = GURL("http://www.example.org/");
1754 request.load_flags = 0;
1756 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1757 scoped_ptr<HttpTransaction> trans(
1758 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1760 MockRead data_reads[] = {
1761 MockRead("HTTP/1.0 200 OK\r\n"),
1762 MockRead("Connection: keep-alive\r\n"),
1763 MockRead("Content-Length: 100\r\n\r\n"),
1764 MockRead(SYNCHRONOUS, 0),
1766 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1767 session_deps_.socket_factory->AddSocketDataProvider(&data);
1769 TestCompletionCallback callback;
1771 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1772 EXPECT_EQ(ERR_IO_PENDING, rv);
1774 rv = callback.WaitForResult();
1775 EXPECT_EQ(OK, rv);
1777 scoped_refptr<IOBufferWithSize> io_buf(new IOBufferWithSize(100));
1778 rv = trans->Read(io_buf.get(), io_buf->size(), callback.callback());
1779 if (rv == ERR_IO_PENDING)
1780 rv = callback.WaitForResult();
1781 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, rv);
1783 trans.reset();
1784 base::MessageLoop::current()->RunUntilIdle();
1785 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
1788 // Test that we correctly reuse a keep-alive connection after not explicitly
1789 // reading the body.
1790 TEST_P(HttpNetworkTransactionTest, KeepAliveAfterUnreadBody) {
1791 HttpRequestInfo request;
1792 request.method = "GET";
1793 request.url = GURL("http://www.foo.com/");
1794 request.load_flags = 0;
1796 TestNetLog net_log;
1797 session_deps_.net_log = &net_log;
1798 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1800 // Note that because all these reads happen in the same
1801 // StaticSocketDataProvider, it shows that the same socket is being reused for
1802 // all transactions.
1803 MockRead data1_reads[] = {
1804 MockRead("HTTP/1.1 204 No Content\r\n\r\n"),
1805 MockRead("HTTP/1.1 205 Reset Content\r\n\r\n"),
1806 MockRead("HTTP/1.1 304 Not Modified\r\n\r\n"),
1807 MockRead("HTTP/1.1 302 Found\r\n"
1808 "Content-Length: 0\r\n\r\n"),
1809 MockRead("HTTP/1.1 302 Found\r\n"
1810 "Content-Length: 5\r\n\r\n"
1811 "hello"),
1812 MockRead("HTTP/1.1 301 Moved Permanently\r\n"
1813 "Content-Length: 0\r\n\r\n"),
1814 MockRead("HTTP/1.1 301 Moved Permanently\r\n"
1815 "Content-Length: 5\r\n\r\n"
1816 "hello"),
1817 MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
1818 MockRead("hello"),
1820 StaticSocketDataProvider data1(data1_reads, arraysize(data1_reads), NULL, 0);
1821 session_deps_.socket_factory->AddSocketDataProvider(&data1);
1823 MockRead data2_reads[] = {
1824 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
1826 StaticSocketDataProvider data2(data2_reads, arraysize(data2_reads), NULL, 0);
1827 session_deps_.socket_factory->AddSocketDataProvider(&data2);
1829 const int kNumUnreadBodies = arraysize(data1_reads) - 2;
1830 std::string response_lines[kNumUnreadBodies];
1832 uint32 first_socket_log_id = NetLog::Source::kInvalidId;
1833 for (size_t i = 0; i < arraysize(data1_reads) - 2; ++i) {
1834 TestCompletionCallback callback;
1836 scoped_ptr<HttpTransaction> trans(
1837 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1839 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1840 EXPECT_EQ(ERR_IO_PENDING, rv);
1842 rv = callback.WaitForResult();
1843 EXPECT_EQ(OK, rv);
1845 LoadTimingInfo load_timing_info;
1846 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
1847 if (i == 0) {
1848 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
1849 first_socket_log_id = load_timing_info.socket_log_id;
1850 } else {
1851 TestLoadTimingReused(load_timing_info);
1852 EXPECT_EQ(first_socket_log_id, load_timing_info.socket_log_id);
1855 const HttpResponseInfo* response = trans->GetResponseInfo();
1856 ASSERT_TRUE(response != NULL);
1858 ASSERT_TRUE(response->headers.get() != NULL);
1859 response_lines[i] = response->headers->GetStatusLine();
1861 // We intentionally don't read the response bodies.
1864 const char* const kStatusLines[] = {
1865 "HTTP/1.1 204 No Content",
1866 "HTTP/1.1 205 Reset Content",
1867 "HTTP/1.1 304 Not Modified",
1868 "HTTP/1.1 302 Found",
1869 "HTTP/1.1 302 Found",
1870 "HTTP/1.1 301 Moved Permanently",
1871 "HTTP/1.1 301 Moved Permanently",
1874 static_assert(kNumUnreadBodies == arraysize(kStatusLines),
1875 "forgot to update kStatusLines");
1877 for (int i = 0; i < kNumUnreadBodies; ++i)
1878 EXPECT_EQ(kStatusLines[i], response_lines[i]);
1880 TestCompletionCallback callback;
1881 scoped_ptr<HttpTransaction> trans(
1882 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1883 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1884 EXPECT_EQ(ERR_IO_PENDING, rv);
1885 rv = callback.WaitForResult();
1886 EXPECT_EQ(OK, rv);
1887 const HttpResponseInfo* response = trans->GetResponseInfo();
1888 ASSERT_TRUE(response != NULL);
1889 ASSERT_TRUE(response->headers.get() != NULL);
1890 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
1891 std::string response_data;
1892 rv = ReadTransaction(trans.get(), &response_data);
1893 EXPECT_EQ(OK, rv);
1894 EXPECT_EQ("hello", response_data);
1897 // Test the request-challenge-retry sequence for basic auth.
1898 // (basic auth is the easiest to mock, because it has no randomness).
1899 TEST_P(HttpNetworkTransactionTest, BasicAuth) {
1900 HttpRequestInfo request;
1901 request.method = "GET";
1902 request.url = GURL("http://www.example.org/");
1903 request.load_flags = 0;
1905 TestNetLog log;
1906 session_deps_.net_log = &log;
1907 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1908 scoped_ptr<HttpTransaction> trans(
1909 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1911 MockWrite data_writes1[] = {
1912 MockWrite(
1913 "GET / HTTP/1.1\r\n"
1914 "Host: www.example.org\r\n"
1915 "Connection: keep-alive\r\n\r\n"),
1918 MockRead data_reads1[] = {
1919 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
1920 // Give a couple authenticate options (only the middle one is actually
1921 // supported).
1922 MockRead("WWW-Authenticate: Basic invalid\r\n"), // Malformed.
1923 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
1924 MockRead("WWW-Authenticate: UNSUPPORTED realm=\"FOO\"\r\n"),
1925 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
1926 // Large content-length -- won't matter, as connection will be reset.
1927 MockRead("Content-Length: 10000\r\n\r\n"),
1928 MockRead(SYNCHRONOUS, ERR_FAILED),
1931 // After calling trans->RestartWithAuth(), this is the request we should
1932 // be issuing -- the final header line contains the credentials.
1933 MockWrite data_writes2[] = {
1934 MockWrite(
1935 "GET / HTTP/1.1\r\n"
1936 "Host: www.example.org\r\n"
1937 "Connection: keep-alive\r\n"
1938 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
1941 // Lastly, the server responds with the actual content.
1942 MockRead data_reads2[] = {
1943 MockRead("HTTP/1.0 200 OK\r\n"),
1944 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
1945 MockRead("Content-Length: 100\r\n\r\n"),
1946 MockRead(SYNCHRONOUS, OK),
1949 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
1950 data_writes1, arraysize(data_writes1));
1951 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
1952 data_writes2, arraysize(data_writes2));
1953 session_deps_.socket_factory->AddSocketDataProvider(&data1);
1954 session_deps_.socket_factory->AddSocketDataProvider(&data2);
1956 TestCompletionCallback callback1;
1958 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
1959 EXPECT_EQ(ERR_IO_PENDING, rv);
1961 rv = callback1.WaitForResult();
1962 EXPECT_EQ(OK, rv);
1964 LoadTimingInfo load_timing_info1;
1965 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info1));
1966 TestLoadTimingNotReused(load_timing_info1, CONNECT_TIMING_HAS_DNS_TIMES);
1968 int64_t writes_size1 = CountWriteBytes(data_writes1, arraysize(data_writes1));
1969 EXPECT_EQ(writes_size1, trans->GetTotalSentBytes());
1970 int64_t reads_size1 = CountReadBytes(data_reads1, arraysize(data_reads1));
1971 EXPECT_EQ(reads_size1, trans->GetTotalReceivedBytes());
1973 const HttpResponseInfo* response = trans->GetResponseInfo();
1974 ASSERT_TRUE(response != NULL);
1975 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
1977 TestCompletionCallback callback2;
1979 rv = trans->RestartWithAuth(
1980 AuthCredentials(kFoo, kBar), callback2.callback());
1981 EXPECT_EQ(ERR_IO_PENDING, rv);
1983 rv = callback2.WaitForResult();
1984 EXPECT_EQ(OK, rv);
1986 LoadTimingInfo load_timing_info2;
1987 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info2));
1988 TestLoadTimingNotReused(load_timing_info2, CONNECT_TIMING_HAS_DNS_TIMES);
1989 // The load timing after restart should have a new socket ID, and times after
1990 // those of the first load timing.
1991 EXPECT_LE(load_timing_info1.receive_headers_end,
1992 load_timing_info2.connect_timing.connect_start);
1993 EXPECT_NE(load_timing_info1.socket_log_id, load_timing_info2.socket_log_id);
1995 int64_t writes_size2 = CountWriteBytes(data_writes2, arraysize(data_writes2));
1996 EXPECT_EQ(writes_size1 + writes_size2, trans->GetTotalSentBytes());
1997 int64_t reads_size2 = CountReadBytes(data_reads2, arraysize(data_reads2));
1998 EXPECT_EQ(reads_size1 + reads_size2, trans->GetTotalReceivedBytes());
2000 response = trans->GetResponseInfo();
2001 ASSERT_TRUE(response != NULL);
2002 EXPECT_TRUE(response->auth_challenge.get() == NULL);
2003 EXPECT_EQ(100, response->headers->GetContentLength());
2006 TEST_P(HttpNetworkTransactionTest, DoNotSendAuth) {
2007 HttpRequestInfo request;
2008 request.method = "GET";
2009 request.url = GURL("http://www.example.org/");
2010 request.load_flags = LOAD_DO_NOT_SEND_AUTH_DATA;
2012 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2013 scoped_ptr<HttpTransaction> trans(
2014 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2016 MockWrite data_writes[] = {
2017 MockWrite(
2018 "GET / HTTP/1.1\r\n"
2019 "Host: www.example.org\r\n"
2020 "Connection: keep-alive\r\n\r\n"),
2023 MockRead data_reads[] = {
2024 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
2025 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2026 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2027 // Large content-length -- won't matter, as connection will be reset.
2028 MockRead("Content-Length: 10000\r\n\r\n"),
2029 MockRead(SYNCHRONOUS, ERR_FAILED),
2032 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
2033 data_writes, arraysize(data_writes));
2034 session_deps_.socket_factory->AddSocketDataProvider(&data);
2035 TestCompletionCallback callback;
2037 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
2038 EXPECT_EQ(ERR_IO_PENDING, rv);
2040 rv = callback.WaitForResult();
2041 EXPECT_EQ(0, rv);
2043 int64_t writes_size = CountWriteBytes(data_writes, arraysize(data_writes));
2044 EXPECT_EQ(writes_size, trans->GetTotalSentBytes());
2045 int64_t reads_size = CountReadBytes(data_reads, arraysize(data_reads));
2046 EXPECT_EQ(reads_size, trans->GetTotalReceivedBytes());
2048 const HttpResponseInfo* response = trans->GetResponseInfo();
2049 ASSERT_TRUE(response != NULL);
2050 EXPECT_TRUE(response->auth_challenge.get() == NULL);
2053 // Test the request-challenge-retry sequence for basic auth, over a keep-alive
2054 // connection.
2055 TEST_P(HttpNetworkTransactionTest, BasicAuthKeepAlive) {
2056 HttpRequestInfo request;
2057 request.method = "GET";
2058 request.url = GURL("http://www.example.org/");
2059 request.load_flags = 0;
2061 TestNetLog log;
2062 session_deps_.net_log = &log;
2063 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2065 MockWrite data_writes1[] = {
2066 MockWrite(
2067 "GET / HTTP/1.1\r\n"
2068 "Host: www.example.org\r\n"
2069 "Connection: keep-alive\r\n\r\n"),
2071 // After calling trans->RestartWithAuth(), this is the request we should
2072 // be issuing -- the final header line contains the credentials.
2073 MockWrite(
2074 "GET / HTTP/1.1\r\n"
2075 "Host: www.example.org\r\n"
2076 "Connection: keep-alive\r\n"
2077 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
2080 MockRead data_reads1[] = {
2081 MockRead("HTTP/1.1 401 Unauthorized\r\n"),
2082 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2083 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2084 MockRead("Content-Length: 14\r\n\r\n"),
2085 MockRead("Unauthorized\r\n"),
2087 // Lastly, the server responds with the actual content.
2088 MockRead("HTTP/1.1 200 OK\r\n"),
2089 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2090 MockRead("Content-Length: 5\r\n\r\n"),
2091 MockRead("Hello"),
2094 // If there is a regression where we disconnect a Keep-Alive
2095 // connection during an auth roundtrip, we'll end up reading this.
2096 MockRead data_reads2[] = {
2097 MockRead(SYNCHRONOUS, ERR_FAILED),
2100 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2101 data_writes1, arraysize(data_writes1));
2102 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
2103 NULL, 0);
2104 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2105 session_deps_.socket_factory->AddSocketDataProvider(&data2);
2107 TestCompletionCallback callback1;
2109 scoped_ptr<HttpTransaction> trans(
2110 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2111 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
2112 EXPECT_EQ(ERR_IO_PENDING, rv);
2114 rv = callback1.WaitForResult();
2115 EXPECT_EQ(OK, rv);
2117 LoadTimingInfo load_timing_info1;
2118 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info1));
2119 TestLoadTimingNotReused(load_timing_info1, CONNECT_TIMING_HAS_DNS_TIMES);
2121 const HttpResponseInfo* response = trans->GetResponseInfo();
2122 ASSERT_TRUE(response != NULL);
2123 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
2125 TestCompletionCallback callback2;
2127 rv = trans->RestartWithAuth(
2128 AuthCredentials(kFoo, kBar), callback2.callback());
2129 EXPECT_EQ(ERR_IO_PENDING, rv);
2131 rv = callback2.WaitForResult();
2132 EXPECT_EQ(OK, rv);
2134 LoadTimingInfo load_timing_info2;
2135 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info2));
2136 TestLoadTimingReused(load_timing_info2);
2137 // The load timing after restart should have the same socket ID, and times
2138 // those of the first load timing.
2139 EXPECT_LE(load_timing_info1.receive_headers_end,
2140 load_timing_info2.send_start);
2141 EXPECT_EQ(load_timing_info1.socket_log_id, load_timing_info2.socket_log_id);
2143 response = trans->GetResponseInfo();
2144 ASSERT_TRUE(response != NULL);
2145 EXPECT_TRUE(response->auth_challenge.get() == NULL);
2146 EXPECT_EQ(5, response->headers->GetContentLength());
2148 std::string response_data;
2149 rv = ReadTransaction(trans.get(), &response_data);
2150 EXPECT_EQ(OK, rv);
2152 int64_t writes_size1 = CountWriteBytes(data_writes1, arraysize(data_writes1));
2153 EXPECT_EQ(writes_size1, trans->GetTotalSentBytes());
2154 int64_t reads_size1 = CountReadBytes(data_reads1, arraysize(data_reads1));
2155 EXPECT_EQ(reads_size1, trans->GetTotalReceivedBytes());
2158 // Test the request-challenge-retry sequence for basic auth, over a keep-alive
2159 // connection and with no response body to drain.
2160 TEST_P(HttpNetworkTransactionTest, BasicAuthKeepAliveNoBody) {
2161 HttpRequestInfo request;
2162 request.method = "GET";
2163 request.url = GURL("http://www.example.org/");
2164 request.load_flags = 0;
2166 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2168 MockWrite data_writes1[] = {
2169 MockWrite(
2170 "GET / HTTP/1.1\r\n"
2171 "Host: www.example.org\r\n"
2172 "Connection: keep-alive\r\n\r\n"),
2174 // After calling trans->RestartWithAuth(), this is the request we should
2175 // be issuing -- the final header line contains the credentials.
2176 MockWrite(
2177 "GET / HTTP/1.1\r\n"
2178 "Host: www.example.org\r\n"
2179 "Connection: keep-alive\r\n"
2180 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
2183 MockRead data_reads1[] = {
2184 MockRead("HTTP/1.1 401 Unauthorized\r\n"),
2185 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2186 MockRead("Content-Length: 0\r\n\r\n"), // No response body.
2188 // Lastly, the server responds with the actual content.
2189 MockRead("HTTP/1.1 200 OK\r\n"),
2190 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2191 MockRead("Content-Length: 5\r\n\r\n"),
2192 MockRead("hello"),
2195 // An incorrect reconnect would cause this to be read.
2196 MockRead data_reads2[] = {
2197 MockRead(SYNCHRONOUS, ERR_FAILED),
2200 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2201 data_writes1, arraysize(data_writes1));
2202 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
2203 NULL, 0);
2204 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2205 session_deps_.socket_factory->AddSocketDataProvider(&data2);
2207 TestCompletionCallback callback1;
2209 scoped_ptr<HttpTransaction> trans(
2210 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2211 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
2212 EXPECT_EQ(ERR_IO_PENDING, rv);
2214 rv = callback1.WaitForResult();
2215 EXPECT_EQ(OK, rv);
2217 const HttpResponseInfo* response = trans->GetResponseInfo();
2218 ASSERT_TRUE(response != NULL);
2219 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
2221 TestCompletionCallback callback2;
2223 rv = trans->RestartWithAuth(
2224 AuthCredentials(kFoo, kBar), callback2.callback());
2225 EXPECT_EQ(ERR_IO_PENDING, rv);
2227 rv = callback2.WaitForResult();
2228 EXPECT_EQ(OK, rv);
2230 response = trans->GetResponseInfo();
2231 ASSERT_TRUE(response != NULL);
2232 EXPECT_TRUE(response->auth_challenge.get() == NULL);
2233 EXPECT_EQ(5, response->headers->GetContentLength());
2236 // Test the request-challenge-retry sequence for basic auth, over a keep-alive
2237 // connection and with a large response body to drain.
2238 TEST_P(HttpNetworkTransactionTest, BasicAuthKeepAliveLargeBody) {
2239 HttpRequestInfo request;
2240 request.method = "GET";
2241 request.url = GURL("http://www.example.org/");
2242 request.load_flags = 0;
2244 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2246 MockWrite data_writes1[] = {
2247 MockWrite(
2248 "GET / HTTP/1.1\r\n"
2249 "Host: www.example.org\r\n"
2250 "Connection: keep-alive\r\n\r\n"),
2252 // After calling trans->RestartWithAuth(), this is the request we should
2253 // be issuing -- the final header line contains the credentials.
2254 MockWrite(
2255 "GET / HTTP/1.1\r\n"
2256 "Host: www.example.org\r\n"
2257 "Connection: keep-alive\r\n"
2258 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
2261 // Respond with 5 kb of response body.
2262 std::string large_body_string("Unauthorized");
2263 large_body_string.append(5 * 1024, ' ');
2264 large_body_string.append("\r\n");
2266 MockRead data_reads1[] = {
2267 MockRead("HTTP/1.1 401 Unauthorized\r\n"),
2268 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2269 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2270 // 5134 = 12 + 5 * 1024 + 2
2271 MockRead("Content-Length: 5134\r\n\r\n"),
2272 MockRead(ASYNC, large_body_string.data(), large_body_string.size()),
2274 // Lastly, the server responds with the actual content.
2275 MockRead("HTTP/1.1 200 OK\r\n"),
2276 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2277 MockRead("Content-Length: 5\r\n\r\n"),
2278 MockRead("hello"),
2281 // An incorrect reconnect would cause this to be read.
2282 MockRead data_reads2[] = {
2283 MockRead(SYNCHRONOUS, ERR_FAILED),
2286 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2287 data_writes1, arraysize(data_writes1));
2288 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
2289 NULL, 0);
2290 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2291 session_deps_.socket_factory->AddSocketDataProvider(&data2);
2293 TestCompletionCallback callback1;
2295 scoped_ptr<HttpTransaction> trans(
2296 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2297 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
2298 EXPECT_EQ(ERR_IO_PENDING, rv);
2300 rv = callback1.WaitForResult();
2301 EXPECT_EQ(OK, rv);
2303 const HttpResponseInfo* response = trans->GetResponseInfo();
2304 ASSERT_TRUE(response != NULL);
2305 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
2307 TestCompletionCallback callback2;
2309 rv = trans->RestartWithAuth(
2310 AuthCredentials(kFoo, kBar), callback2.callback());
2311 EXPECT_EQ(ERR_IO_PENDING, rv);
2313 rv = callback2.WaitForResult();
2314 EXPECT_EQ(OK, rv);
2316 response = trans->GetResponseInfo();
2317 ASSERT_TRUE(response != NULL);
2318 EXPECT_TRUE(response->auth_challenge.get() == NULL);
2319 EXPECT_EQ(5, response->headers->GetContentLength());
2322 // Test the request-challenge-retry sequence for basic auth, over a keep-alive
2323 // connection, but the server gets impatient and closes the connection.
2324 TEST_P(HttpNetworkTransactionTest, BasicAuthKeepAliveImpatientServer) {
2325 HttpRequestInfo request;
2326 request.method = "GET";
2327 request.url = GURL("http://www.example.org/");
2328 request.load_flags = 0;
2330 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2332 MockWrite data_writes1[] = {
2333 MockWrite(
2334 "GET / HTTP/1.1\r\n"
2335 "Host: www.example.org\r\n"
2336 "Connection: keep-alive\r\n\r\n"),
2337 // This simulates the seemingly successful write to a closed connection
2338 // if the bug is not fixed.
2339 MockWrite(
2340 "GET / HTTP/1.1\r\n"
2341 "Host: www.example.org\r\n"
2342 "Connection: keep-alive\r\n"
2343 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
2346 MockRead data_reads1[] = {
2347 MockRead("HTTP/1.1 401 Unauthorized\r\n"),
2348 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2349 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2350 MockRead("Content-Length: 14\r\n\r\n"),
2351 // Tell MockTCPClientSocket to simulate the server closing the connection.
2352 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
2353 MockRead("Unauthorized\r\n"),
2354 MockRead(SYNCHRONOUS, OK), // The server closes the connection.
2357 // After calling trans->RestartWithAuth(), this is the request we should
2358 // be issuing -- the final header line contains the credentials.
2359 MockWrite data_writes2[] = {
2360 MockWrite(
2361 "GET / HTTP/1.1\r\n"
2362 "Host: www.example.org\r\n"
2363 "Connection: keep-alive\r\n"
2364 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
2367 // Lastly, the server responds with the actual content.
2368 MockRead data_reads2[] = {
2369 MockRead("HTTP/1.1 200 OK\r\n"),
2370 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2371 MockRead("Content-Length: 5\r\n\r\n"),
2372 MockRead("hello"),
2375 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2376 data_writes1, arraysize(data_writes1));
2377 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
2378 data_writes2, arraysize(data_writes2));
2379 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2380 session_deps_.socket_factory->AddSocketDataProvider(&data2);
2382 TestCompletionCallback callback1;
2384 scoped_ptr<HttpTransaction> trans(
2385 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2386 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
2387 EXPECT_EQ(ERR_IO_PENDING, rv);
2389 rv = callback1.WaitForResult();
2390 EXPECT_EQ(OK, rv);
2392 const HttpResponseInfo* response = trans->GetResponseInfo();
2393 ASSERT_TRUE(response != NULL);
2394 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
2396 TestCompletionCallback callback2;
2398 rv = trans->RestartWithAuth(
2399 AuthCredentials(kFoo, kBar), callback2.callback());
2400 EXPECT_EQ(ERR_IO_PENDING, rv);
2402 rv = callback2.WaitForResult();
2403 EXPECT_EQ(OK, rv);
2405 response = trans->GetResponseInfo();
2406 ASSERT_TRUE(response != NULL);
2407 EXPECT_TRUE(response->auth_challenge.get() == NULL);
2408 EXPECT_EQ(5, response->headers->GetContentLength());
2411 // Test the request-challenge-retry sequence for basic auth, over a connection
2412 // that requires a restart when setting up an SSL tunnel.
2413 TEST_P(HttpNetworkTransactionTest, BasicAuthProxyNoKeepAliveHttp10) {
2414 HttpRequestInfo request;
2415 request.method = "GET";
2416 request.url = GURL("https://www.example.org/");
2417 // when the no authentication data flag is set.
2418 request.load_flags = LOAD_DO_NOT_SEND_AUTH_DATA;
2420 // Configure against proxy server "myproxy:70".
2421 session_deps_.proxy_service.reset(
2422 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
2423 BoundTestNetLog log;
2424 session_deps_.net_log = log.bound().net_log();
2425 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2427 // Since we have proxy, should try to establish tunnel.
2428 MockWrite data_writes1[] = {
2429 MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
2430 "Host: www.example.org\r\n"
2431 "Proxy-Connection: keep-alive\r\n\r\n"),
2434 // The proxy responds to the connect with a 407, using a non-persistent
2435 // connection.
2436 MockRead data_reads1[] = {
2437 // No credentials.
2438 MockRead("HTTP/1.0 407 Proxy Authentication Required\r\n"),
2439 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n\r\n"),
2442 // Since the first connection couldn't be reused, need to establish another
2443 // once given credentials.
2444 MockWrite data_writes2[] = {
2445 // After calling trans->RestartWithAuth(), this is the request we should
2446 // be issuing -- the final header line contains the credentials.
2447 MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
2448 "Host: www.example.org\r\n"
2449 "Proxy-Connection: keep-alive\r\n"
2450 "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
2452 MockWrite("GET / HTTP/1.1\r\n"
2453 "Host: www.example.org\r\n"
2454 "Connection: keep-alive\r\n\r\n"),
2457 MockRead data_reads2[] = {
2458 MockRead("HTTP/1.0 200 Connection Established\r\n\r\n"),
2460 MockRead("HTTP/1.1 200 OK\r\n"),
2461 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2462 MockRead("Content-Length: 5\r\n\r\n"),
2463 MockRead(SYNCHRONOUS, "hello"),
2466 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2467 data_writes1, arraysize(data_writes1));
2468 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2469 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
2470 data_writes2, arraysize(data_writes2));
2471 session_deps_.socket_factory->AddSocketDataProvider(&data2);
2472 SSLSocketDataProvider ssl(ASYNC, OK);
2473 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
2475 TestCompletionCallback callback1;
2477 scoped_ptr<HttpTransaction> trans(
2478 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2480 int rv = trans->Start(&request, callback1.callback(), log.bound());
2481 EXPECT_EQ(ERR_IO_PENDING, rv);
2483 rv = callback1.WaitForResult();
2484 EXPECT_EQ(OK, rv);
2485 TestNetLogEntry::List entries;
2486 log.GetEntries(&entries);
2487 size_t pos = ExpectLogContainsSomewhere(
2488 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
2489 NetLog::PHASE_NONE);
2490 ExpectLogContainsSomewhere(
2491 entries, pos, NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
2492 NetLog::PHASE_NONE);
2494 const HttpResponseInfo* response = trans->GetResponseInfo();
2495 ASSERT_TRUE(response != NULL);
2496 EXPECT_FALSE(response->headers->IsKeepAlive());
2497 ASSERT_FALSE(response->headers.get() == NULL);
2498 EXPECT_EQ(407, response->headers->response_code());
2499 EXPECT_TRUE(HttpVersion(1, 0) == response->headers->GetHttpVersion());
2500 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
2502 LoadTimingInfo load_timing_info;
2503 // CONNECT requests and responses are handled at the connect job level, so
2504 // the transaction does not yet have a connection.
2505 EXPECT_FALSE(trans->GetLoadTimingInfo(&load_timing_info));
2507 TestCompletionCallback callback2;
2509 rv =
2510 trans->RestartWithAuth(AuthCredentials(kFoo, kBar), callback2.callback());
2511 EXPECT_EQ(ERR_IO_PENDING, rv);
2513 rv = callback2.WaitForResult();
2514 EXPECT_EQ(OK, rv);
2516 response = trans->GetResponseInfo();
2517 ASSERT_TRUE(response != NULL);
2519 EXPECT_TRUE(response->headers->IsKeepAlive());
2520 EXPECT_EQ(200, response->headers->response_code());
2521 EXPECT_EQ(5, response->headers->GetContentLength());
2522 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
2524 // The password prompt info should not be set.
2525 EXPECT_TRUE(response->auth_challenge.get() == NULL);
2527 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
2528 TestLoadTimingNotReusedWithPac(load_timing_info,
2529 CONNECT_TIMING_HAS_SSL_TIMES);
2531 trans.reset();
2532 session->CloseAllConnections();
2535 // Test the request-challenge-retry sequence for basic auth, over a connection
2536 // that requires a restart when setting up an SSL tunnel.
2537 TEST_P(HttpNetworkTransactionTest, BasicAuthProxyNoKeepAliveHttp11) {
2538 HttpRequestInfo request;
2539 request.method = "GET";
2540 request.url = GURL("https://www.example.org/");
2541 // when the no authentication data flag is set.
2542 request.load_flags = LOAD_DO_NOT_SEND_AUTH_DATA;
2544 // Configure against proxy server "myproxy:70".
2545 session_deps_.proxy_service.reset(
2546 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
2547 BoundTestNetLog log;
2548 session_deps_.net_log = log.bound().net_log();
2549 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2551 // Since we have proxy, should try to establish tunnel.
2552 MockWrite data_writes1[] = {
2553 MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
2554 "Host: www.example.org\r\n"
2555 "Proxy-Connection: keep-alive\r\n\r\n"),
2558 // The proxy responds to the connect with a 407, using a non-persistent
2559 // connection.
2560 MockRead data_reads1[] = {
2561 // No credentials.
2562 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
2563 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2564 MockRead("Proxy-Connection: close\r\n\r\n"),
2567 MockWrite data_writes2[] = {
2568 // After calling trans->RestartWithAuth(), this is the request we should
2569 // be issuing -- the final header line contains the credentials.
2570 MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
2571 "Host: www.example.org\r\n"
2572 "Proxy-Connection: keep-alive\r\n"
2573 "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
2575 MockWrite("GET / HTTP/1.1\r\n"
2576 "Host: www.example.org\r\n"
2577 "Connection: keep-alive\r\n\r\n"),
2580 MockRead data_reads2[] = {
2581 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
2583 MockRead("HTTP/1.1 200 OK\r\n"),
2584 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2585 MockRead("Content-Length: 5\r\n\r\n"),
2586 MockRead(SYNCHRONOUS, "hello"),
2589 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2590 data_writes1, arraysize(data_writes1));
2591 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2592 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
2593 data_writes2, arraysize(data_writes2));
2594 session_deps_.socket_factory->AddSocketDataProvider(&data2);
2595 SSLSocketDataProvider ssl(ASYNC, OK);
2596 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
2598 TestCompletionCallback callback1;
2600 scoped_ptr<HttpTransaction> trans(
2601 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2603 int rv = trans->Start(&request, callback1.callback(), log.bound());
2604 EXPECT_EQ(ERR_IO_PENDING, rv);
2606 rv = callback1.WaitForResult();
2607 EXPECT_EQ(OK, rv);
2608 TestNetLogEntry::List entries;
2609 log.GetEntries(&entries);
2610 size_t pos = ExpectLogContainsSomewhere(
2611 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
2612 NetLog::PHASE_NONE);
2613 ExpectLogContainsSomewhere(
2614 entries, pos,
2615 NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
2616 NetLog::PHASE_NONE);
2618 const HttpResponseInfo* response = trans->GetResponseInfo();
2619 ASSERT_TRUE(response != NULL);
2620 EXPECT_FALSE(response->headers->IsKeepAlive());
2621 ASSERT_FALSE(response->headers.get() == NULL);
2622 EXPECT_EQ(407, response->headers->response_code());
2623 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
2624 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
2626 LoadTimingInfo load_timing_info;
2627 // CONNECT requests and responses are handled at the connect job level, so
2628 // the transaction does not yet have a connection.
2629 EXPECT_FALSE(trans->GetLoadTimingInfo(&load_timing_info));
2631 TestCompletionCallback callback2;
2633 rv = trans->RestartWithAuth(
2634 AuthCredentials(kFoo, kBar), callback2.callback());
2635 EXPECT_EQ(ERR_IO_PENDING, rv);
2637 rv = callback2.WaitForResult();
2638 EXPECT_EQ(OK, rv);
2640 response = trans->GetResponseInfo();
2641 ASSERT_TRUE(response != NULL);
2643 EXPECT_TRUE(response->headers->IsKeepAlive());
2644 EXPECT_EQ(200, response->headers->response_code());
2645 EXPECT_EQ(5, response->headers->GetContentLength());
2646 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
2648 // The password prompt info should not be set.
2649 EXPECT_TRUE(response->auth_challenge.get() == NULL);
2651 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
2652 TestLoadTimingNotReusedWithPac(load_timing_info,
2653 CONNECT_TIMING_HAS_SSL_TIMES);
2655 trans.reset();
2656 session->CloseAllConnections();
2659 // Test the request-challenge-retry sequence for basic auth, over a keep-alive
2660 // proxy connection with HTTP/1.0 responses, when setting up an SSL tunnel.
2661 TEST_P(HttpNetworkTransactionTest, BasicAuthProxyKeepAliveHttp10) {
2662 HttpRequestInfo request;
2663 request.method = "GET";
2664 request.url = GURL("https://www.example.org/");
2665 // Ensure that proxy authentication is attempted even
2666 // when the no authentication data flag is set.
2667 request.load_flags = LOAD_DO_NOT_SEND_AUTH_DATA;
2669 // Configure against proxy server "myproxy:70".
2670 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
2671 BoundTestNetLog log;
2672 session_deps_.net_log = log.bound().net_log();
2673 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2675 scoped_ptr<HttpTransaction> trans(
2676 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2678 // Since we have proxy, should try to establish tunnel.
2679 MockWrite data_writes1[] = {
2680 MockWrite(
2681 "CONNECT www.example.org:443 HTTP/1.1\r\n"
2682 "Host: www.example.org\r\n"
2683 "Proxy-Connection: keep-alive\r\n\r\n"),
2685 // After calling trans->RestartWithAuth(), this is the request we should
2686 // be issuing -- the final header line contains the credentials.
2687 MockWrite(
2688 "CONNECT www.example.org:443 HTTP/1.1\r\n"
2689 "Host: www.example.org\r\n"
2690 "Proxy-Connection: keep-alive\r\n"
2691 "Proxy-Authorization: Basic Zm9vOmJheg==\r\n\r\n"),
2694 // The proxy responds to the connect with a 407, using a persistent
2695 // connection. (Since it's HTTP/1.0, keep-alive has to be explicit.)
2696 MockRead data_reads1[] = {
2697 // No credentials.
2698 MockRead("HTTP/1.0 407 Proxy Authentication Required\r\n"),
2699 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2700 MockRead("Proxy-Connection: keep-alive\r\n"),
2701 MockRead("Content-Length: 10\r\n\r\n"),
2702 MockRead("0123456789"),
2704 // Wrong credentials (wrong password).
2705 MockRead("HTTP/1.0 407 Proxy Authentication Required\r\n"),
2706 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2707 MockRead("Proxy-Connection: keep-alive\r\n"),
2708 MockRead("Content-Length: 10\r\n\r\n"),
2709 // No response body because the test stops reading here.
2710 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
2713 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2714 data_writes1, arraysize(data_writes1));
2715 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2717 TestCompletionCallback callback1;
2719 int rv = trans->Start(&request, callback1.callback(), log.bound());
2720 EXPECT_EQ(ERR_IO_PENDING, rv);
2722 rv = callback1.WaitForResult();
2723 EXPECT_EQ(OK, rv);
2724 TestNetLogEntry::List entries;
2725 log.GetEntries(&entries);
2726 size_t pos = ExpectLogContainsSomewhere(
2727 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
2728 NetLog::PHASE_NONE);
2729 ExpectLogContainsSomewhere(
2730 entries, pos, NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
2731 NetLog::PHASE_NONE);
2733 const HttpResponseInfo* response = trans->GetResponseInfo();
2734 ASSERT_TRUE(response);
2735 ASSERT_TRUE(response->headers);
2736 EXPECT_TRUE(response->headers->IsKeepAlive());
2737 EXPECT_EQ(407, response->headers->response_code());
2738 EXPECT_EQ(10, response->headers->GetContentLength());
2739 EXPECT_TRUE(HttpVersion(1, 0) == response->headers->GetHttpVersion());
2740 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
2742 TestCompletionCallback callback2;
2744 // Wrong password (should be "bar").
2745 rv =
2746 trans->RestartWithAuth(AuthCredentials(kFoo, kBaz), callback2.callback());
2747 EXPECT_EQ(ERR_IO_PENDING, rv);
2749 rv = callback2.WaitForResult();
2750 EXPECT_EQ(OK, rv);
2752 response = trans->GetResponseInfo();
2753 ASSERT_TRUE(response);
2754 ASSERT_TRUE(response->headers);
2755 EXPECT_TRUE(response->headers->IsKeepAlive());
2756 EXPECT_EQ(407, response->headers->response_code());
2757 EXPECT_EQ(10, response->headers->GetContentLength());
2758 EXPECT_TRUE(HttpVersion(1, 0) == response->headers->GetHttpVersion());
2759 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
2761 // Flush the idle socket before the NetLog and HttpNetworkTransaction go
2762 // out of scope.
2763 session->CloseAllConnections();
2766 // Test the request-challenge-retry sequence for basic auth, over a keep-alive
2767 // proxy connection with HTTP/1.1 responses, when setting up an SSL tunnel.
2768 TEST_P(HttpNetworkTransactionTest, BasicAuthProxyKeepAliveHttp11) {
2769 HttpRequestInfo request;
2770 request.method = "GET";
2771 request.url = GURL("https://www.example.org/");
2772 // Ensure that proxy authentication is attempted even
2773 // when the no authentication data flag is set.
2774 request.load_flags = LOAD_DO_NOT_SEND_AUTH_DATA;
2776 // Configure against proxy server "myproxy:70".
2777 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
2778 BoundTestNetLog log;
2779 session_deps_.net_log = log.bound().net_log();
2780 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2782 scoped_ptr<HttpTransaction> trans(
2783 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2785 // Since we have proxy, should try to establish tunnel.
2786 MockWrite data_writes1[] = {
2787 MockWrite(
2788 "CONNECT www.example.org:443 HTTP/1.1\r\n"
2789 "Host: www.example.org\r\n"
2790 "Proxy-Connection: keep-alive\r\n\r\n"),
2792 // After calling trans->RestartWithAuth(), this is the request we should
2793 // be issuing -- the final header line contains the credentials.
2794 MockWrite(
2795 "CONNECT www.example.org:443 HTTP/1.1\r\n"
2796 "Host: www.example.org\r\n"
2797 "Proxy-Connection: keep-alive\r\n"
2798 "Proxy-Authorization: Basic Zm9vOmJheg==\r\n\r\n"),
2801 // The proxy responds to the connect with a 407, using a persistent
2802 // connection.
2803 MockRead data_reads1[] = {
2804 // No credentials.
2805 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
2806 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2807 MockRead("Content-Length: 10\r\n\r\n"),
2808 MockRead("0123456789"),
2810 // Wrong credentials (wrong password).
2811 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
2812 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2813 MockRead("Content-Length: 10\r\n\r\n"),
2814 // No response body because the test stops reading here.
2815 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
2818 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2819 data_writes1, arraysize(data_writes1));
2820 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2822 TestCompletionCallback callback1;
2824 int rv = trans->Start(&request, callback1.callback(), log.bound());
2825 EXPECT_EQ(ERR_IO_PENDING, rv);
2827 rv = callback1.WaitForResult();
2828 EXPECT_EQ(OK, rv);
2829 TestNetLogEntry::List entries;
2830 log.GetEntries(&entries);
2831 size_t pos = ExpectLogContainsSomewhere(
2832 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
2833 NetLog::PHASE_NONE);
2834 ExpectLogContainsSomewhere(
2835 entries, pos,
2836 NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
2837 NetLog::PHASE_NONE);
2839 const HttpResponseInfo* response = trans->GetResponseInfo();
2840 ASSERT_TRUE(response);
2841 ASSERT_TRUE(response->headers);
2842 EXPECT_TRUE(response->headers->IsKeepAlive());
2843 EXPECT_EQ(407, response->headers->response_code());
2844 EXPECT_EQ(10, response->headers->GetContentLength());
2845 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
2846 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
2848 TestCompletionCallback callback2;
2850 // Wrong password (should be "bar").
2851 rv = trans->RestartWithAuth(
2852 AuthCredentials(kFoo, kBaz), callback2.callback());
2853 EXPECT_EQ(ERR_IO_PENDING, rv);
2855 rv = callback2.WaitForResult();
2856 EXPECT_EQ(OK, rv);
2858 response = trans->GetResponseInfo();
2859 ASSERT_TRUE(response);
2860 ASSERT_TRUE(response->headers);
2861 EXPECT_TRUE(response->headers->IsKeepAlive());
2862 EXPECT_EQ(407, response->headers->response_code());
2863 EXPECT_EQ(10, response->headers->GetContentLength());
2864 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
2865 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
2867 // Flush the idle socket before the NetLog and HttpNetworkTransaction go
2868 // out of scope.
2869 session->CloseAllConnections();
2872 // Test the case a proxy closes a socket while the challenge body is being
2873 // drained.
2874 TEST_P(HttpNetworkTransactionTest, BasicAuthProxyKeepAliveHangupDuringBody) {
2875 HttpRequestInfo request;
2876 request.method = "GET";
2877 request.url = GURL("https://www.example.org/");
2878 // Ensure that proxy authentication is attempted even
2879 // when the no authentication data flag is set.
2880 request.load_flags = LOAD_DO_NOT_SEND_AUTH_DATA;
2882 // Configure against proxy server "myproxy:70".
2883 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
2884 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2886 scoped_ptr<HttpTransaction> trans(
2887 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2889 // Since we have proxy, should try to establish tunnel.
2890 MockWrite data_writes1[] = {
2891 MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
2892 "Host: www.example.org\r\n"
2893 "Proxy-Connection: keep-alive\r\n\r\n"),
2896 // The proxy responds to the connect with a 407, using a persistent
2897 // connection.
2898 MockRead data_reads1[] = {
2899 // No credentials.
2900 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
2901 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2902 MockRead("Content-Length: 10\r\n\r\n"), MockRead("spam!"),
2903 // Server hands up in the middle of the body.
2904 MockRead(ASYNC, ERR_CONNECTION_CLOSED),
2907 MockWrite data_writes2[] = {
2908 // After calling trans->RestartWithAuth(), this is the request we should
2909 // be issuing -- the final header line contains the credentials.
2910 MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
2911 "Host: www.example.org\r\n"
2912 "Proxy-Connection: keep-alive\r\n"
2913 "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
2915 MockWrite("GET / HTTP/1.1\r\n"
2916 "Host: www.example.org\r\n"
2917 "Connection: keep-alive\r\n\r\n"),
2920 MockRead data_reads2[] = {
2921 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
2923 MockRead("HTTP/1.1 200 OK\r\n"),
2924 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2925 MockRead("Content-Length: 5\r\n\r\n"),
2926 MockRead(SYNCHRONOUS, "hello"),
2929 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2930 data_writes1, arraysize(data_writes1));
2931 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2932 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
2933 data_writes2, arraysize(data_writes2));
2934 session_deps_.socket_factory->AddSocketDataProvider(&data2);
2935 SSLSocketDataProvider ssl(ASYNC, OK);
2936 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
2938 TestCompletionCallback callback;
2940 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
2941 EXPECT_EQ(OK, callback.GetResult(rv));
2943 const HttpResponseInfo* response = trans->GetResponseInfo();
2944 ASSERT_TRUE(response);
2945 ASSERT_TRUE(response->headers);
2946 EXPECT_TRUE(response->headers->IsKeepAlive());
2947 EXPECT_EQ(407, response->headers->response_code());
2948 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
2950 rv = trans->RestartWithAuth(AuthCredentials(kFoo, kBar), callback.callback());
2951 EXPECT_EQ(OK, callback.GetResult(rv));
2953 response = trans->GetResponseInfo();
2954 ASSERT_TRUE(response);
2955 ASSERT_TRUE(response->headers);
2956 EXPECT_TRUE(response->headers->IsKeepAlive());
2957 EXPECT_EQ(200, response->headers->response_code());
2958 std::string body;
2959 EXPECT_EQ(OK, ReadTransaction(trans.get(), &body));
2960 EXPECT_EQ("hello", body);
2963 // Test that we don't read the response body when we fail to establish a tunnel,
2964 // even if the user cancels the proxy's auth attempt.
2965 TEST_P(HttpNetworkTransactionTest, BasicAuthProxyCancelTunnel) {
2966 HttpRequestInfo request;
2967 request.method = "GET";
2968 request.url = GURL("https://www.example.org/");
2969 request.load_flags = 0;
2971 // Configure against proxy server "myproxy:70".
2972 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
2974 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2976 scoped_ptr<HttpTransaction> trans(
2977 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2979 // Since we have proxy, should try to establish tunnel.
2980 MockWrite data_writes[] = {
2981 MockWrite(
2982 "CONNECT www.example.org:443 HTTP/1.1\r\n"
2983 "Host: www.example.org\r\n"
2984 "Proxy-Connection: keep-alive\r\n\r\n"),
2987 // The proxy responds to the connect with a 407.
2988 MockRead data_reads[] = {
2989 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
2990 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2991 MockRead("Content-Length: 10\r\n\r\n"),
2992 MockRead("0123456789"), // Should not be reached.
2993 MockRead(SYNCHRONOUS, ERR_UNEXPECTED),
2996 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
2997 data_writes, arraysize(data_writes));
2998 session_deps_.socket_factory->AddSocketDataProvider(&data);
3000 TestCompletionCallback callback;
3002 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
3003 EXPECT_EQ(ERR_IO_PENDING, rv);
3005 rv = callback.WaitForResult();
3006 EXPECT_EQ(OK, rv);
3008 const HttpResponseInfo* response = trans->GetResponseInfo();
3009 ASSERT_TRUE(response);
3010 ASSERT_TRUE(response->headers);
3011 EXPECT_TRUE(response->headers->IsKeepAlive());
3012 EXPECT_EQ(407, response->headers->response_code());
3013 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
3015 std::string response_data;
3016 rv = ReadTransaction(trans.get(), &response_data);
3017 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, rv);
3019 // Flush the idle socket before the HttpNetworkTransaction goes out of scope.
3020 session->CloseAllConnections();
3023 // Test that we don't pass extraneous headers from the proxy's response to the
3024 // caller when the proxy responds to CONNECT with 407.
3025 TEST_P(HttpNetworkTransactionTest, SanitizeProxyAuthHeaders) {
3026 HttpRequestInfo request;
3027 request.method = "GET";
3028 request.url = GURL("https://www.example.org/");
3029 request.load_flags = 0;
3031 // Configure against proxy server "myproxy:70".
3032 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
3034 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3036 scoped_ptr<HttpTransaction> trans(
3037 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3039 // Since we have proxy, should try to establish tunnel.
3040 MockWrite data_writes[] = {
3041 MockWrite(
3042 "CONNECT www.example.org:443 HTTP/1.1\r\n"
3043 "Host: www.example.org\r\n"
3044 "Proxy-Connection: keep-alive\r\n\r\n"),
3047 // The proxy responds to the connect with a 407.
3048 MockRead data_reads[] = {
3049 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
3050 MockRead("X-Foo: bar\r\n"),
3051 MockRead("Set-Cookie: foo=bar\r\n"),
3052 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
3053 MockRead("Content-Length: 10\r\n\r\n"),
3054 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
3057 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
3058 arraysize(data_writes));
3059 session_deps_.socket_factory->AddSocketDataProvider(&data);
3061 TestCompletionCallback callback;
3063 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
3064 EXPECT_EQ(ERR_IO_PENDING, rv);
3066 rv = callback.WaitForResult();
3067 EXPECT_EQ(OK, rv);
3069 const HttpResponseInfo* response = trans->GetResponseInfo();
3070 ASSERT_TRUE(response);
3071 ASSERT_TRUE(response->headers);
3072 EXPECT_TRUE(response->headers->IsKeepAlive());
3073 EXPECT_EQ(407, response->headers->response_code());
3074 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
3075 EXPECT_FALSE(response->headers->HasHeader("X-Foo"));
3076 EXPECT_FALSE(response->headers->HasHeader("Set-Cookie"));
3078 std::string response_data;
3079 rv = ReadTransaction(trans.get(), &response_data);
3080 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, rv);
3082 // Flush the idle socket before the HttpNetworkTransaction goes out of scope.
3083 session->CloseAllConnections();
3086 // Test when a server (non-proxy) returns a 407 (proxy-authenticate).
3087 // The request should fail with ERR_UNEXPECTED_PROXY_AUTH.
3088 TEST_P(HttpNetworkTransactionTest, UnexpectedProxyAuth) {
3089 HttpRequestInfo request;
3090 request.method = "GET";
3091 request.url = GURL("http://www.example.org/");
3092 request.load_flags = 0;
3094 // We are using a DIRECT connection (i.e. no proxy) for this session.
3095 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3096 scoped_ptr<HttpTransaction> trans(
3097 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3099 MockWrite data_writes1[] = {
3100 MockWrite(
3101 "GET / HTTP/1.1\r\n"
3102 "Host: www.example.org\r\n"
3103 "Connection: keep-alive\r\n\r\n"),
3106 MockRead data_reads1[] = {
3107 MockRead("HTTP/1.0 407 Proxy Auth required\r\n"),
3108 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
3109 // Large content-length -- won't matter, as connection will be reset.
3110 MockRead("Content-Length: 10000\r\n\r\n"),
3111 MockRead(SYNCHRONOUS, ERR_FAILED),
3114 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
3115 data_writes1, arraysize(data_writes1));
3116 session_deps_.socket_factory->AddSocketDataProvider(&data1);
3118 TestCompletionCallback callback;
3120 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
3121 EXPECT_EQ(ERR_IO_PENDING, rv);
3123 rv = callback.WaitForResult();
3124 EXPECT_EQ(ERR_UNEXPECTED_PROXY_AUTH, rv);
3127 // Tests when an HTTPS server (non-proxy) returns a 407 (proxy-authentication)
3128 // through a non-authenticating proxy. The request should fail with
3129 // ERR_UNEXPECTED_PROXY_AUTH.
3130 // Note that it is impossible to detect if an HTTP server returns a 407 through
3131 // a non-authenticating proxy - there is nothing to indicate whether the
3132 // response came from the proxy or the server, so it is treated as if the proxy
3133 // issued the challenge.
3134 TEST_P(HttpNetworkTransactionTest,
3135 HttpsServerRequestsProxyAuthThroughProxy) {
3136 HttpRequestInfo request;
3137 request.method = "GET";
3138 request.url = GURL("https://www.example.org/");
3140 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
3141 BoundTestNetLog log;
3142 session_deps_.net_log = log.bound().net_log();
3143 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3145 // Since we have proxy, should try to establish tunnel.
3146 MockWrite data_writes1[] = {
3147 MockWrite(
3148 "CONNECT www.example.org:443 HTTP/1.1\r\n"
3149 "Host: www.example.org\r\n"
3150 "Proxy-Connection: keep-alive\r\n\r\n"),
3152 MockWrite(
3153 "GET / HTTP/1.1\r\n"
3154 "Host: www.example.org\r\n"
3155 "Connection: keep-alive\r\n\r\n"),
3158 MockRead data_reads1[] = {
3159 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
3161 MockRead("HTTP/1.1 407 Unauthorized\r\n"),
3162 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
3163 MockRead("\r\n"),
3164 MockRead(SYNCHRONOUS, OK),
3167 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
3168 data_writes1, arraysize(data_writes1));
3169 session_deps_.socket_factory->AddSocketDataProvider(&data1);
3170 SSLSocketDataProvider ssl(ASYNC, OK);
3171 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3173 TestCompletionCallback callback1;
3175 scoped_ptr<HttpTransaction> trans(
3176 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3178 int rv = trans->Start(&request, callback1.callback(), log.bound());
3179 EXPECT_EQ(ERR_IO_PENDING, rv);
3181 rv = callback1.WaitForResult();
3182 EXPECT_EQ(ERR_UNEXPECTED_PROXY_AUTH, rv);
3183 TestNetLogEntry::List entries;
3184 log.GetEntries(&entries);
3185 size_t pos = ExpectLogContainsSomewhere(
3186 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
3187 NetLog::PHASE_NONE);
3188 ExpectLogContainsSomewhere(
3189 entries, pos,
3190 NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
3191 NetLog::PHASE_NONE);
3194 // Test the load timing for HTTPS requests with an HTTP proxy.
3195 TEST_P(HttpNetworkTransactionTest, HttpProxyLoadTimingNoPacTwoRequests) {
3196 HttpRequestInfo request1;
3197 request1.method = "GET";
3198 request1.url = GURL("https://www.example.org/1");
3200 HttpRequestInfo request2;
3201 request2.method = "GET";
3202 request2.url = GURL("https://www.example.org/2");
3204 // Configure against proxy server "myproxy:70".
3205 session_deps_.proxy_service.reset(
3206 ProxyService::CreateFixed("PROXY myproxy:70"));
3207 BoundTestNetLog log;
3208 session_deps_.net_log = log.bound().net_log();
3209 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3211 // Since we have proxy, should try to establish tunnel.
3212 MockWrite data_writes1[] = {
3213 MockWrite(
3214 "CONNECT www.example.org:443 HTTP/1.1\r\n"
3215 "Host: www.example.org\r\n"
3216 "Proxy-Connection: keep-alive\r\n\r\n"),
3218 MockWrite(
3219 "GET /1 HTTP/1.1\r\n"
3220 "Host: www.example.org\r\n"
3221 "Connection: keep-alive\r\n\r\n"),
3223 MockWrite(
3224 "GET /2 HTTP/1.1\r\n"
3225 "Host: www.example.org\r\n"
3226 "Connection: keep-alive\r\n\r\n"),
3229 // The proxy responds to the connect with a 407, using a persistent
3230 // connection.
3231 MockRead data_reads1[] = {
3232 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
3234 MockRead("HTTP/1.1 200 OK\r\n"),
3235 MockRead("Content-Length: 1\r\n\r\n"),
3236 MockRead(SYNCHRONOUS, "1"),
3238 MockRead("HTTP/1.1 200 OK\r\n"),
3239 MockRead("Content-Length: 2\r\n\r\n"),
3240 MockRead(SYNCHRONOUS, "22"),
3243 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
3244 data_writes1, arraysize(data_writes1));
3245 session_deps_.socket_factory->AddSocketDataProvider(&data1);
3246 SSLSocketDataProvider ssl(ASYNC, OK);
3247 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3249 TestCompletionCallback callback1;
3250 scoped_ptr<HttpTransaction> trans1(
3251 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3253 int rv = trans1->Start(&request1, callback1.callback(), log.bound());
3254 EXPECT_EQ(ERR_IO_PENDING, rv);
3256 rv = callback1.WaitForResult();
3257 EXPECT_EQ(OK, rv);
3259 const HttpResponseInfo* response1 = trans1->GetResponseInfo();
3260 ASSERT_TRUE(response1 != NULL);
3261 ASSERT_TRUE(response1->headers.get() != NULL);
3262 EXPECT_EQ(1, response1->headers->GetContentLength());
3264 LoadTimingInfo load_timing_info1;
3265 EXPECT_TRUE(trans1->GetLoadTimingInfo(&load_timing_info1));
3266 TestLoadTimingNotReused(load_timing_info1, CONNECT_TIMING_HAS_SSL_TIMES);
3268 trans1.reset();
3270 TestCompletionCallback callback2;
3271 scoped_ptr<HttpTransaction> trans2(
3272 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3274 rv = trans2->Start(&request2, callback2.callback(), log.bound());
3275 EXPECT_EQ(ERR_IO_PENDING, rv);
3277 rv = callback2.WaitForResult();
3278 EXPECT_EQ(OK, rv);
3280 const HttpResponseInfo* response2 = trans2->GetResponseInfo();
3281 ASSERT_TRUE(response2 != NULL);
3282 ASSERT_TRUE(response2->headers.get() != NULL);
3283 EXPECT_EQ(2, response2->headers->GetContentLength());
3285 LoadTimingInfo load_timing_info2;
3286 EXPECT_TRUE(trans2->GetLoadTimingInfo(&load_timing_info2));
3287 TestLoadTimingReused(load_timing_info2);
3289 EXPECT_EQ(load_timing_info1.socket_log_id, load_timing_info2.socket_log_id);
3291 trans2.reset();
3292 session->CloseAllConnections();
3295 // Test the load timing for HTTPS requests with an HTTP proxy and a PAC script.
3296 TEST_P(HttpNetworkTransactionTest, HttpProxyLoadTimingWithPacTwoRequests) {
3297 HttpRequestInfo request1;
3298 request1.method = "GET";
3299 request1.url = GURL("https://www.example.org/1");
3301 HttpRequestInfo request2;
3302 request2.method = "GET";
3303 request2.url = GURL("https://www.example.org/2");
3305 // Configure against proxy server "myproxy:70".
3306 session_deps_.proxy_service.reset(
3307 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
3308 BoundTestNetLog log;
3309 session_deps_.net_log = log.bound().net_log();
3310 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3312 // Since we have proxy, should try to establish tunnel.
3313 MockWrite data_writes1[] = {
3314 MockWrite(
3315 "CONNECT www.example.org:443 HTTP/1.1\r\n"
3316 "Host: www.example.org\r\n"
3317 "Proxy-Connection: keep-alive\r\n\r\n"),
3319 MockWrite(
3320 "GET /1 HTTP/1.1\r\n"
3321 "Host: www.example.org\r\n"
3322 "Connection: keep-alive\r\n\r\n"),
3324 MockWrite(
3325 "GET /2 HTTP/1.1\r\n"
3326 "Host: www.example.org\r\n"
3327 "Connection: keep-alive\r\n\r\n"),
3330 // The proxy responds to the connect with a 407, using a persistent
3331 // connection.
3332 MockRead data_reads1[] = {
3333 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
3335 MockRead("HTTP/1.1 200 OK\r\n"),
3336 MockRead("Content-Length: 1\r\n\r\n"),
3337 MockRead(SYNCHRONOUS, "1"),
3339 MockRead("HTTP/1.1 200 OK\r\n"),
3340 MockRead("Content-Length: 2\r\n\r\n"),
3341 MockRead(SYNCHRONOUS, "22"),
3344 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
3345 data_writes1, arraysize(data_writes1));
3346 session_deps_.socket_factory->AddSocketDataProvider(&data1);
3347 SSLSocketDataProvider ssl(ASYNC, OK);
3348 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3350 TestCompletionCallback callback1;
3351 scoped_ptr<HttpTransaction> trans1(
3352 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3354 int rv = trans1->Start(&request1, callback1.callback(), log.bound());
3355 EXPECT_EQ(ERR_IO_PENDING, rv);
3357 rv = callback1.WaitForResult();
3358 EXPECT_EQ(OK, rv);
3360 const HttpResponseInfo* response1 = trans1->GetResponseInfo();
3361 ASSERT_TRUE(response1 != NULL);
3362 ASSERT_TRUE(response1->headers.get() != NULL);
3363 EXPECT_EQ(1, response1->headers->GetContentLength());
3365 LoadTimingInfo load_timing_info1;
3366 EXPECT_TRUE(trans1->GetLoadTimingInfo(&load_timing_info1));
3367 TestLoadTimingNotReusedWithPac(load_timing_info1,
3368 CONNECT_TIMING_HAS_SSL_TIMES);
3370 trans1.reset();
3372 TestCompletionCallback callback2;
3373 scoped_ptr<HttpTransaction> trans2(
3374 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3376 rv = trans2->Start(&request2, callback2.callback(), log.bound());
3377 EXPECT_EQ(ERR_IO_PENDING, rv);
3379 rv = callback2.WaitForResult();
3380 EXPECT_EQ(OK, rv);
3382 const HttpResponseInfo* response2 = trans2->GetResponseInfo();
3383 ASSERT_TRUE(response2 != NULL);
3384 ASSERT_TRUE(response2->headers.get() != NULL);
3385 EXPECT_EQ(2, response2->headers->GetContentLength());
3387 LoadTimingInfo load_timing_info2;
3388 EXPECT_TRUE(trans2->GetLoadTimingInfo(&load_timing_info2));
3389 TestLoadTimingReusedWithPac(load_timing_info2);
3391 EXPECT_EQ(load_timing_info1.socket_log_id, load_timing_info2.socket_log_id);
3393 trans2.reset();
3394 session->CloseAllConnections();
3397 // Test a simple get through an HTTPS Proxy.
3398 TEST_P(HttpNetworkTransactionTest, HttpsProxyGet) {
3399 HttpRequestInfo request;
3400 request.method = "GET";
3401 request.url = GURL("http://www.example.org/");
3403 // Configure against https proxy server "proxy:70".
3404 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
3405 "https://proxy:70"));
3406 BoundTestNetLog log;
3407 session_deps_.net_log = log.bound().net_log();
3408 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3410 // Since we have proxy, should use full url
3411 MockWrite data_writes1[] = {
3412 MockWrite(
3413 "GET http://www.example.org/ HTTP/1.1\r\n"
3414 "Host: www.example.org\r\n"
3415 "Proxy-Connection: keep-alive\r\n\r\n"),
3418 MockRead data_reads1[] = {
3419 MockRead("HTTP/1.1 200 OK\r\n"),
3420 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
3421 MockRead("Content-Length: 100\r\n\r\n"),
3422 MockRead(SYNCHRONOUS, OK),
3425 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
3426 data_writes1, arraysize(data_writes1));
3427 session_deps_.socket_factory->AddSocketDataProvider(&data1);
3428 SSLSocketDataProvider ssl(ASYNC, OK);
3429 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3431 TestCompletionCallback callback1;
3433 scoped_ptr<HttpTransaction> trans(
3434 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3436 int rv = trans->Start(&request, callback1.callback(), log.bound());
3437 EXPECT_EQ(ERR_IO_PENDING, rv);
3439 rv = callback1.WaitForResult();
3440 EXPECT_EQ(OK, rv);
3442 LoadTimingInfo load_timing_info;
3443 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
3444 TestLoadTimingNotReused(load_timing_info,
3445 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
3447 const HttpResponseInfo* response = trans->GetResponseInfo();
3448 ASSERT_TRUE(response != NULL);
3450 EXPECT_TRUE(response->headers->IsKeepAlive());
3451 EXPECT_EQ(200, response->headers->response_code());
3452 EXPECT_EQ(100, response->headers->GetContentLength());
3453 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
3455 // The password prompt info should not be set.
3456 EXPECT_TRUE(response->auth_challenge.get() == NULL);
3459 // Test a SPDY get through an HTTPS Proxy.
3460 TEST_P(HttpNetworkTransactionTest, HttpsProxySpdyGet) {
3461 HttpRequestInfo request;
3462 request.method = "GET";
3463 request.url = GURL("http://www.example.org/");
3464 request.load_flags = 0;
3466 // Configure against https proxy server "proxy:70".
3467 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
3468 "https://proxy:70"));
3469 BoundTestNetLog log;
3470 session_deps_.net_log = log.bound().net_log();
3471 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3473 // fetch http://www.example.org/ via SPDY
3474 scoped_ptr<SpdyFrame> req(
3475 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, false));
3476 MockWrite spdy_writes[] = {CreateMockWrite(*req, 0)};
3478 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
3479 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
3480 MockRead spdy_reads[] = {
3481 CreateMockRead(*resp, 1), CreateMockRead(*data, 2), MockRead(ASYNC, 0, 3),
3484 SequencedSocketData spdy_data(spdy_reads, arraysize(spdy_reads), spdy_writes,
3485 arraysize(spdy_writes));
3486 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
3488 SSLSocketDataProvider ssl(ASYNC, OK);
3489 ssl.SetNextProto(GetParam());
3490 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3492 TestCompletionCallback callback1;
3494 scoped_ptr<HttpTransaction> trans(
3495 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3497 int rv = trans->Start(&request, callback1.callback(), log.bound());
3498 EXPECT_EQ(ERR_IO_PENDING, rv);
3500 rv = callback1.WaitForResult();
3501 EXPECT_EQ(OK, rv);
3503 LoadTimingInfo load_timing_info;
3504 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
3505 TestLoadTimingNotReused(load_timing_info,
3506 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
3508 const HttpResponseInfo* response = trans->GetResponseInfo();
3509 ASSERT_TRUE(response != NULL);
3510 ASSERT_TRUE(response->headers.get() != NULL);
3511 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
3513 std::string response_data;
3514 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
3515 EXPECT_EQ(kUploadData, response_data);
3518 // Verifies that a session which races and wins against the owning transaction
3519 // (completing prior to host resolution), doesn't fail the transaction.
3520 // Regression test for crbug.com/334413.
3521 TEST_P(HttpNetworkTransactionTest, HttpsProxySpdyGetWithSessionRace) {
3522 HttpRequestInfo request;
3523 request.method = "GET";
3524 request.url = GURL("http://www.example.org/");
3525 request.load_flags = 0;
3527 // Configure SPDY proxy server "proxy:70".
3528 session_deps_.proxy_service.reset(
3529 ProxyService::CreateFixed("https://proxy:70"));
3530 BoundTestNetLog log;
3531 session_deps_.net_log = log.bound().net_log();
3532 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3534 // Fetch http://www.example.org/ through the SPDY proxy.
3535 scoped_ptr<SpdyFrame> req(
3536 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, false));
3537 MockWrite spdy_writes[] = {CreateMockWrite(*req, 0)};
3539 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
3540 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
3541 MockRead spdy_reads[] = {
3542 CreateMockRead(*resp, 1), CreateMockRead(*data, 2), MockRead(ASYNC, 0, 3),
3545 SequencedSocketData spdy_data(spdy_reads, arraysize(spdy_reads), spdy_writes,
3546 arraysize(spdy_writes));
3547 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
3549 SSLSocketDataProvider ssl(ASYNC, OK);
3550 ssl.SetNextProto(GetParam());
3551 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3553 TestCompletionCallback callback1;
3555 scoped_ptr<HttpTransaction> trans(
3556 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3558 // Stall the hostname resolution begun by the transaction.
3559 session_deps_.host_resolver->set_synchronous_mode(false);
3560 session_deps_.host_resolver->set_ondemand_mode(true);
3562 int rv = trans->Start(&request, callback1.callback(), log.bound());
3563 EXPECT_EQ(ERR_IO_PENDING, rv);
3565 // Race a session to the proxy, which completes first.
3566 session_deps_.host_resolver->set_ondemand_mode(false);
3567 SpdySessionKey key(
3568 HostPortPair("proxy", 70), ProxyServer::Direct(), PRIVACY_MODE_DISABLED);
3569 base::WeakPtr<SpdySession> spdy_session =
3570 CreateSecureSpdySession(session, key, log.bound());
3572 // Unstall the resolution begun by the transaction.
3573 session_deps_.host_resolver->set_ondemand_mode(true);
3574 session_deps_.host_resolver->ResolveAllPending();
3576 EXPECT_FALSE(callback1.have_result());
3577 rv = callback1.WaitForResult();
3578 EXPECT_EQ(OK, rv);
3580 const HttpResponseInfo* response = trans->GetResponseInfo();
3581 ASSERT_TRUE(response != NULL);
3582 ASSERT_TRUE(response->headers.get() != NULL);
3583 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
3585 std::string response_data;
3586 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
3587 EXPECT_EQ(kUploadData, response_data);
3590 // Test a SPDY get through an HTTPS Proxy.
3591 TEST_P(HttpNetworkTransactionTest, HttpsProxySpdyGetWithProxyAuth) {
3592 HttpRequestInfo request;
3593 request.method = "GET";
3594 request.url = GURL("http://www.example.org/");
3595 request.load_flags = 0;
3597 // Configure against https proxy server "myproxy:70".
3598 session_deps_.proxy_service.reset(
3599 ProxyService::CreateFixed("https://myproxy:70"));
3600 BoundTestNetLog log;
3601 session_deps_.net_log = log.bound().net_log();
3602 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3604 // The first request will be a bare GET, the second request will be a
3605 // GET with a Proxy-Authorization header.
3606 scoped_ptr<SpdyFrame> req_get(
3607 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, false));
3608 const char* const kExtraAuthorizationHeaders[] = {
3609 "proxy-authorization", "Basic Zm9vOmJhcg=="
3611 scoped_ptr<SpdyFrame> req_get_authorization(
3612 spdy_util_.ConstructSpdyGet(kExtraAuthorizationHeaders,
3613 arraysize(kExtraAuthorizationHeaders) / 2,
3614 false,
3616 LOWEST,
3617 false));
3618 MockWrite spdy_writes[] = {
3619 CreateMockWrite(*req_get, 0), CreateMockWrite(*req_get_authorization, 3),
3622 // The first response is a 407 proxy authentication challenge, and the second
3623 // response will be a 200 response since the second request includes a valid
3624 // Authorization header.
3625 const char* const kExtraAuthenticationHeaders[] = {
3626 "proxy-authenticate", "Basic realm=\"MyRealm1\""
3628 scoped_ptr<SpdyFrame> resp_authentication(
3629 spdy_util_.ConstructSpdySynReplyError(
3630 "407 Proxy Authentication Required",
3631 kExtraAuthenticationHeaders, arraysize(kExtraAuthenticationHeaders)/2,
3632 1));
3633 scoped_ptr<SpdyFrame> body_authentication(
3634 spdy_util_.ConstructSpdyBodyFrame(1, true));
3635 scoped_ptr<SpdyFrame> resp_data(
3636 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
3637 scoped_ptr<SpdyFrame> body_data(spdy_util_.ConstructSpdyBodyFrame(3, true));
3638 MockRead spdy_reads[] = {
3639 CreateMockRead(*resp_authentication, 1),
3640 CreateMockRead(*body_authentication, 2),
3641 CreateMockRead(*resp_data, 4),
3642 CreateMockRead(*body_data, 5),
3643 MockRead(ASYNC, 0, 6),
3646 SequencedSocketData data(spdy_reads, arraysize(spdy_reads), spdy_writes,
3647 arraysize(spdy_writes));
3648 session_deps_.socket_factory->AddSocketDataProvider(&data);
3650 SSLSocketDataProvider ssl(ASYNC, OK);
3651 ssl.SetNextProto(GetParam());
3652 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3654 TestCompletionCallback callback1;
3656 scoped_ptr<HttpTransaction> trans(
3657 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3659 int rv = trans->Start(&request, callback1.callback(), log.bound());
3660 EXPECT_EQ(ERR_IO_PENDING, rv);
3662 rv = callback1.WaitForResult();
3663 EXPECT_EQ(OK, rv);
3665 const HttpResponseInfo* const response = trans->GetResponseInfo();
3667 ASSERT_TRUE(response != NULL);
3668 ASSERT_TRUE(response->headers.get() != NULL);
3669 EXPECT_EQ(407, response->headers->response_code());
3670 EXPECT_TRUE(response->was_fetched_via_spdy);
3671 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
3673 TestCompletionCallback callback2;
3675 rv = trans->RestartWithAuth(
3676 AuthCredentials(kFoo, kBar), callback2.callback());
3677 EXPECT_EQ(ERR_IO_PENDING, rv);
3679 rv = callback2.WaitForResult();
3680 EXPECT_EQ(OK, rv);
3682 const HttpResponseInfo* const response_restart = trans->GetResponseInfo();
3684 ASSERT_TRUE(response_restart != NULL);
3685 ASSERT_TRUE(response_restart->headers.get() != NULL);
3686 EXPECT_EQ(200, response_restart->headers->response_code());
3687 // The password prompt info should not be set.
3688 EXPECT_TRUE(response_restart->auth_challenge.get() == NULL);
3691 // Test a SPDY CONNECT through an HTTPS Proxy to an HTTPS (non-SPDY) Server.
3692 TEST_P(HttpNetworkTransactionTest, HttpsProxySpdyConnectHttps) {
3693 HttpRequestInfo request;
3694 request.method = "GET";
3695 request.url = GURL("https://www.example.org/");
3696 request.load_flags = 0;
3698 // Configure against https proxy server "proxy:70".
3699 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
3700 "https://proxy:70"));
3701 BoundTestNetLog log;
3702 session_deps_.net_log = log.bound().net_log();
3703 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3705 scoped_ptr<HttpTransaction> trans(
3706 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3708 // CONNECT to www.example.org:443 via SPDY
3709 scoped_ptr<SpdyFrame> connect(spdy_util_.ConstructSpdyConnect(
3710 NULL, 0, 1, LOWEST, HostPortPair("www.example.org", 443)));
3711 // fetch https://www.example.org/ via HTTP
3713 const char get[] =
3714 "GET / HTTP/1.1\r\n"
3715 "Host: www.example.org\r\n"
3716 "Connection: keep-alive\r\n\r\n";
3717 scoped_ptr<SpdyFrame> wrapped_get(
3718 spdy_util_.ConstructSpdyBodyFrame(1, get, strlen(get), false));
3719 scoped_ptr<SpdyFrame> conn_resp(
3720 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
3721 const char resp[] = "HTTP/1.1 200 OK\r\n"
3722 "Content-Length: 10\r\n\r\n";
3723 scoped_ptr<SpdyFrame> wrapped_get_resp(
3724 spdy_util_.ConstructSpdyBodyFrame(1, resp, strlen(resp), false));
3725 scoped_ptr<SpdyFrame> wrapped_body(
3726 spdy_util_.ConstructSpdyBodyFrame(1, "1234567890", 10, false));
3727 scoped_ptr<SpdyFrame> window_update(
3728 spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_get_resp->size()));
3730 MockWrite spdy_writes[] = {
3731 CreateMockWrite(*connect, 0),
3732 CreateMockWrite(*wrapped_get, 2),
3733 CreateMockWrite(*window_update, 6),
3736 MockRead spdy_reads[] = {
3737 CreateMockRead(*conn_resp, 1, ASYNC),
3738 CreateMockRead(*wrapped_get_resp, 3, ASYNC),
3739 CreateMockRead(*wrapped_body, 4, ASYNC),
3740 CreateMockRead(*wrapped_body, 5, ASYNC),
3741 MockRead(ASYNC, 0, 7),
3744 SequencedSocketData spdy_data(spdy_reads, arraysize(spdy_reads), spdy_writes,
3745 arraysize(spdy_writes));
3746 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
3748 SSLSocketDataProvider ssl(ASYNC, OK);
3749 ssl.SetNextProto(GetParam());
3750 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3751 SSLSocketDataProvider ssl2(ASYNC, OK);
3752 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
3754 TestCompletionCallback callback1;
3756 int rv = trans->Start(&request, callback1.callback(), log.bound());
3757 EXPECT_EQ(ERR_IO_PENDING, rv);
3759 rv = callback1.WaitForResult();
3760 ASSERT_EQ(OK, rv);
3762 LoadTimingInfo load_timing_info;
3763 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
3764 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_SSL_TIMES);
3766 const HttpResponseInfo* response = trans->GetResponseInfo();
3767 ASSERT_TRUE(response != NULL);
3768 ASSERT_TRUE(response->headers.get() != NULL);
3769 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
3771 std::string response_data;
3772 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
3773 EXPECT_EQ("1234567890", response_data);
3776 // Test a SPDY CONNECT through an HTTPS Proxy to a SPDY server.
3777 TEST_P(HttpNetworkTransactionTest, HttpsProxySpdyConnectSpdy) {
3778 HttpRequestInfo request;
3779 request.method = "GET";
3780 request.url = GURL("https://www.example.org/");
3781 request.load_flags = 0;
3783 // Configure against https proxy server "proxy:70".
3784 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
3785 "https://proxy:70"));
3786 BoundTestNetLog log;
3787 session_deps_.net_log = log.bound().net_log();
3788 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3790 scoped_ptr<HttpTransaction> trans(
3791 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3793 // CONNECT to www.example.org:443 via SPDY
3794 scoped_ptr<SpdyFrame> connect(spdy_util_.ConstructSpdyConnect(
3795 NULL, 0, 1, LOWEST, HostPortPair("www.example.org", 443)));
3796 // fetch https://www.example.org/ via SPDY
3797 const char kMyUrl[] = "https://www.example.org/";
3798 scoped_ptr<SpdyFrame> get(
3799 spdy_util_.ConstructSpdyGet(kMyUrl, false, 1, LOWEST));
3800 scoped_ptr<SpdyFrame> wrapped_get(
3801 spdy_util_.ConstructWrappedSpdyFrame(get, 1));
3802 scoped_ptr<SpdyFrame> conn_resp(
3803 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
3804 scoped_ptr<SpdyFrame> get_resp(
3805 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
3806 scoped_ptr<SpdyFrame> wrapped_get_resp(
3807 spdy_util_.ConstructWrappedSpdyFrame(get_resp, 1));
3808 scoped_ptr<SpdyFrame> body(spdy_util_.ConstructSpdyBodyFrame(1, true));
3809 scoped_ptr<SpdyFrame> wrapped_body(
3810 spdy_util_.ConstructWrappedSpdyFrame(body, 1));
3811 scoped_ptr<SpdyFrame> window_update_get_resp(
3812 spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_get_resp->size()));
3813 scoped_ptr<SpdyFrame> window_update_body(
3814 spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_body->size()));
3816 MockWrite spdy_writes[] = {
3817 CreateMockWrite(*connect, 0),
3818 CreateMockWrite(*wrapped_get, 2),
3819 CreateMockWrite(*window_update_get_resp, 6),
3820 CreateMockWrite(*window_update_body, 7),
3823 MockRead spdy_reads[] = {
3824 CreateMockRead(*conn_resp, 1, ASYNC),
3825 MockRead(ASYNC, ERR_IO_PENDING, 3),
3826 CreateMockRead(*wrapped_get_resp, 4, ASYNC),
3827 CreateMockRead(*wrapped_body, 5, ASYNC),
3828 MockRead(ASYNC, 0, 8),
3831 SequencedSocketData spdy_data(spdy_reads, arraysize(spdy_reads), spdy_writes,
3832 arraysize(spdy_writes));
3833 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
3835 SSLSocketDataProvider ssl(ASYNC, OK);
3836 ssl.SetNextProto(GetParam());
3837 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3838 SSLSocketDataProvider ssl2(ASYNC, OK);
3839 ssl2.SetNextProto(GetParam());
3840 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
3842 TestCompletionCallback callback1;
3844 int rv = trans->Start(&request, callback1.callback(), log.bound());
3845 EXPECT_EQ(ERR_IO_PENDING, rv);
3847 // Allow the SpdyProxyClientSocket's write callback to complete.
3848 base::MessageLoop::current()->RunUntilIdle();
3849 // Now allow the read of the response to complete.
3850 spdy_data.CompleteRead();
3851 rv = callback1.WaitForResult();
3852 EXPECT_EQ(OK, rv);
3854 LoadTimingInfo load_timing_info;
3855 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
3856 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_SSL_TIMES);
3858 const HttpResponseInfo* response = trans->GetResponseInfo();
3859 ASSERT_TRUE(response != NULL);
3860 ASSERT_TRUE(response->headers.get() != NULL);
3861 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
3863 std::string response_data;
3864 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
3865 EXPECT_EQ(kUploadData, response_data);
3868 // Test a SPDY CONNECT failure through an HTTPS Proxy.
3869 TEST_P(HttpNetworkTransactionTest, HttpsProxySpdyConnectFailure) {
3870 HttpRequestInfo request;
3871 request.method = "GET";
3872 request.url = GURL("https://www.example.org/");
3873 request.load_flags = 0;
3875 // Configure against https proxy server "proxy:70".
3876 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
3877 "https://proxy:70"));
3878 BoundTestNetLog log;
3879 session_deps_.net_log = log.bound().net_log();
3880 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3882 scoped_ptr<HttpTransaction> trans(
3883 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3885 // CONNECT to www.example.org:443 via SPDY
3886 scoped_ptr<SpdyFrame> connect(spdy_util_.ConstructSpdyConnect(
3887 NULL, 0, 1, LOWEST, HostPortPair("www.example.org", 443)));
3888 scoped_ptr<SpdyFrame> get(
3889 spdy_util_.ConstructSpdyRstStream(1, RST_STREAM_CANCEL));
3891 MockWrite spdy_writes[] = {
3892 CreateMockWrite(*connect, 0), CreateMockWrite(*get, 2),
3895 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdySynReplyError(1));
3896 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
3897 MockRead spdy_reads[] = {
3898 CreateMockRead(*resp, 1, ASYNC), MockRead(ASYNC, 0, 3),
3901 SequencedSocketData spdy_data(spdy_reads, arraysize(spdy_reads), spdy_writes,
3902 arraysize(spdy_writes));
3903 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
3905 SSLSocketDataProvider ssl(ASYNC, OK);
3906 ssl.SetNextProto(GetParam());
3907 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3908 SSLSocketDataProvider ssl2(ASYNC, OK);
3909 ssl2.SetNextProto(GetParam());
3910 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
3912 TestCompletionCallback callback1;
3914 int rv = trans->Start(&request, callback1.callback(), log.bound());
3915 EXPECT_EQ(ERR_IO_PENDING, rv);
3917 rv = callback1.WaitForResult();
3918 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, rv);
3920 // TODO(ttuttle): Anything else to check here?
3923 // Test load timing in the case of two HTTPS (non-SPDY) requests through a SPDY
3924 // HTTPS Proxy to different servers.
3925 TEST_P(HttpNetworkTransactionTest,
3926 HttpsProxySpdyConnectHttpsLoadTimingTwoRequestsTwoServers) {
3927 // Configure against https proxy server "proxy:70".
3928 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
3929 "https://proxy:70"));
3930 BoundTestNetLog log;
3931 session_deps_.net_log = log.bound().net_log();
3932 scoped_refptr<HttpNetworkSession> session(
3933 SpdySessionDependencies::SpdyCreateSession(&session_deps_));
3935 HttpRequestInfo request1;
3936 request1.method = "GET";
3937 request1.url = GURL("https://www.example.org/");
3938 request1.load_flags = 0;
3940 HttpRequestInfo request2;
3941 request2.method = "GET";
3942 request2.url = GURL("https://mail.example.org/");
3943 request2.load_flags = 0;
3945 // CONNECT to www.example.org:443 via SPDY.
3946 scoped_ptr<SpdyFrame> connect1(spdy_util_.ConstructSpdyConnect(
3947 NULL, 0, 1, LOWEST, HostPortPair("www.example.org", 443)));
3948 scoped_ptr<SpdyFrame> conn_resp1(
3949 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
3951 // Fetch https://www.example.org/ via HTTP.
3952 const char get1[] =
3953 "GET / HTTP/1.1\r\n"
3954 "Host: www.example.org\r\n"
3955 "Connection: keep-alive\r\n\r\n";
3956 scoped_ptr<SpdyFrame> wrapped_get1(
3957 spdy_util_.ConstructSpdyBodyFrame(1, get1, strlen(get1), false));
3958 const char resp1[] = "HTTP/1.1 200 OK\r\n"
3959 "Content-Length: 1\r\n\r\n";
3960 scoped_ptr<SpdyFrame> wrapped_get_resp1(
3961 spdy_util_.ConstructSpdyBodyFrame(1, resp1, strlen(resp1), false));
3962 scoped_ptr<SpdyFrame> wrapped_body1(
3963 spdy_util_.ConstructSpdyBodyFrame(1, "1", 1, false));
3964 scoped_ptr<SpdyFrame> window_update(
3965 spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_get_resp1->size()));
3967 // CONNECT to mail.example.org:443 via SPDY.
3968 SpdyHeaderBlock connect2_block;
3969 connect2_block[spdy_util_.GetMethodKey()] = "CONNECT";
3970 if (GetParam() == kProtoHTTP2) {
3971 connect2_block[spdy_util_.GetHostKey()] = "mail.example.org:443";
3972 } else {
3973 connect2_block[spdy_util_.GetPathKey()] = "mail.example.org:443";
3974 connect2_block[spdy_util_.GetHostKey()] = "mail.example.org";
3976 spdy_util_.MaybeAddVersionHeader(&connect2_block);
3977 scoped_ptr<SpdyFrame> connect2(
3978 spdy_util_.ConstructSpdySyn(3, connect2_block, LOWEST, false, false));
3980 scoped_ptr<SpdyFrame> conn_resp2(
3981 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
3983 // Fetch https://mail.example.org/ via HTTP.
3984 const char get2[] =
3985 "GET / HTTP/1.1\r\n"
3986 "Host: mail.example.org\r\n"
3987 "Connection: keep-alive\r\n\r\n";
3988 scoped_ptr<SpdyFrame> wrapped_get2(
3989 spdy_util_.ConstructSpdyBodyFrame(3, get2, strlen(get2), false));
3990 const char resp2[] = "HTTP/1.1 200 OK\r\n"
3991 "Content-Length: 2\r\n\r\n";
3992 scoped_ptr<SpdyFrame> wrapped_get_resp2(
3993 spdy_util_.ConstructSpdyBodyFrame(3, resp2, strlen(resp2), false));
3994 scoped_ptr<SpdyFrame> wrapped_body2(
3995 spdy_util_.ConstructSpdyBodyFrame(3, "22", 2, false));
3997 MockWrite spdy_writes[] = {
3998 CreateMockWrite(*connect1, 0),
3999 CreateMockWrite(*wrapped_get1, 2),
4000 CreateMockWrite(*connect2, 5),
4001 CreateMockWrite(*wrapped_get2, 7),
4004 MockRead spdy_reads[] = {
4005 CreateMockRead(*conn_resp1, 1, ASYNC),
4006 CreateMockRead(*wrapped_get_resp1, 3, ASYNC),
4007 CreateMockRead(*wrapped_body1, 4, ASYNC),
4008 CreateMockRead(*conn_resp2, 6, ASYNC),
4009 CreateMockRead(*wrapped_get_resp2, 8, ASYNC),
4010 CreateMockRead(*wrapped_body2, 9, ASYNC),
4011 MockRead(ASYNC, 0, 10),
4014 SequencedSocketData spdy_data(spdy_reads, arraysize(spdy_reads), spdy_writes,
4015 arraysize(spdy_writes));
4016 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
4018 SSLSocketDataProvider ssl(ASYNC, OK);
4019 ssl.SetNextProto(GetParam());
4020 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
4021 SSLSocketDataProvider ssl2(ASYNC, OK);
4022 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
4023 SSLSocketDataProvider ssl3(ASYNC, OK);
4024 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl3);
4026 TestCompletionCallback callback;
4028 scoped_ptr<HttpTransaction> trans(
4029 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4030 int rv = trans->Start(&request1, callback.callback(), BoundNetLog());
4031 EXPECT_EQ(OK, callback.GetResult(rv));
4033 LoadTimingInfo load_timing_info;
4034 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
4035 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_SSL_TIMES);
4037 const HttpResponseInfo* response = trans->GetResponseInfo();
4038 ASSERT_TRUE(response != NULL);
4039 ASSERT_TRUE(response->headers.get() != NULL);
4040 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
4042 std::string response_data;
4043 scoped_refptr<IOBuffer> buf(new IOBuffer(256));
4044 rv = trans->Read(buf.get(), 256, callback.callback());
4045 EXPECT_EQ(1, callback.GetResult(rv));
4047 scoped_ptr<HttpTransaction> trans2(
4048 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4049 rv = trans2->Start(&request2, callback.callback(), BoundNetLog());
4050 EXPECT_EQ(OK, callback.GetResult(rv));
4052 LoadTimingInfo load_timing_info2;
4053 EXPECT_TRUE(trans2->GetLoadTimingInfo(&load_timing_info2));
4054 // Even though the SPDY connection is reused, a new tunnelled connection has
4055 // to be created, so the socket's load timing looks like a fresh connection.
4056 TestLoadTimingNotReused(load_timing_info2, CONNECT_TIMING_HAS_SSL_TIMES);
4058 // The requests should have different IDs, since they each are using their own
4059 // separate stream.
4060 EXPECT_NE(load_timing_info.socket_log_id, load_timing_info2.socket_log_id);
4062 rv = trans2->Read(buf.get(), 256, callback.callback());
4063 EXPECT_EQ(2, callback.GetResult(rv));
4066 // Test load timing in the case of two HTTPS (non-SPDY) requests through a SPDY
4067 // HTTPS Proxy to the same server.
4068 TEST_P(HttpNetworkTransactionTest,
4069 HttpsProxySpdyConnectHttpsLoadTimingTwoRequestsSameServer) {
4070 // Configure against https proxy server "proxy:70".
4071 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
4072 "https://proxy:70"));
4073 BoundTestNetLog log;
4074 session_deps_.net_log = log.bound().net_log();
4075 scoped_refptr<HttpNetworkSession> session(
4076 SpdySessionDependencies::SpdyCreateSession(&session_deps_));
4078 HttpRequestInfo request1;
4079 request1.method = "GET";
4080 request1.url = GURL("https://www.example.org/");
4081 request1.load_flags = 0;
4083 HttpRequestInfo request2;
4084 request2.method = "GET";
4085 request2.url = GURL("https://www.example.org/2");
4086 request2.load_flags = 0;
4088 // CONNECT to www.example.org:443 via SPDY.
4089 scoped_ptr<SpdyFrame> connect1(spdy_util_.ConstructSpdyConnect(
4090 NULL, 0, 1, LOWEST, HostPortPair("www.example.org", 443)));
4091 scoped_ptr<SpdyFrame> conn_resp1(
4092 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
4094 // Fetch https://www.example.org/ via HTTP.
4095 const char get1[] =
4096 "GET / HTTP/1.1\r\n"
4097 "Host: www.example.org\r\n"
4098 "Connection: keep-alive\r\n\r\n";
4099 scoped_ptr<SpdyFrame> wrapped_get1(
4100 spdy_util_.ConstructSpdyBodyFrame(1, get1, strlen(get1), false));
4101 const char resp1[] = "HTTP/1.1 200 OK\r\n"
4102 "Content-Length: 1\r\n\r\n";
4103 scoped_ptr<SpdyFrame> wrapped_get_resp1(
4104 spdy_util_.ConstructSpdyBodyFrame(1, resp1, strlen(resp1), false));
4105 scoped_ptr<SpdyFrame> wrapped_body1(
4106 spdy_util_.ConstructSpdyBodyFrame(1, "1", 1, false));
4107 scoped_ptr<SpdyFrame> window_update(
4108 spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_get_resp1->size()));
4110 // Fetch https://www.example.org/2 via HTTP.
4111 const char get2[] =
4112 "GET /2 HTTP/1.1\r\n"
4113 "Host: www.example.org\r\n"
4114 "Connection: keep-alive\r\n\r\n";
4115 scoped_ptr<SpdyFrame> wrapped_get2(
4116 spdy_util_.ConstructSpdyBodyFrame(1, get2, strlen(get2), false));
4117 const char resp2[] = "HTTP/1.1 200 OK\r\n"
4118 "Content-Length: 2\r\n\r\n";
4119 scoped_ptr<SpdyFrame> wrapped_get_resp2(
4120 spdy_util_.ConstructSpdyBodyFrame(1, resp2, strlen(resp2), false));
4121 scoped_ptr<SpdyFrame> wrapped_body2(
4122 spdy_util_.ConstructSpdyBodyFrame(1, "22", 2, false));
4124 MockWrite spdy_writes[] = {
4125 CreateMockWrite(*connect1, 0),
4126 CreateMockWrite(*wrapped_get1, 2),
4127 CreateMockWrite(*wrapped_get2, 5),
4130 MockRead spdy_reads[] = {
4131 CreateMockRead(*conn_resp1, 1, ASYNC),
4132 CreateMockRead(*wrapped_get_resp1, 3, ASYNC),
4133 CreateMockRead(*wrapped_body1, 4, ASYNC),
4134 CreateMockRead(*wrapped_get_resp2, 6, ASYNC),
4135 CreateMockRead(*wrapped_body2, 7, ASYNC),
4136 MockRead(ASYNC, 0, 8),
4139 SequencedSocketData spdy_data(spdy_reads, arraysize(spdy_reads), spdy_writes,
4140 arraysize(spdy_writes));
4141 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
4143 SSLSocketDataProvider ssl(ASYNC, OK);
4144 ssl.SetNextProto(GetParam());
4145 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
4146 SSLSocketDataProvider ssl2(ASYNC, OK);
4147 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
4149 TestCompletionCallback callback;
4151 scoped_ptr<HttpTransaction> trans(
4152 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4153 int rv = trans->Start(&request1, callback.callback(), BoundNetLog());
4154 EXPECT_EQ(ERR_IO_PENDING, rv);
4156 rv = callback.WaitForResult();
4157 EXPECT_EQ(OK, rv);
4159 LoadTimingInfo load_timing_info;
4160 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
4161 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_SSL_TIMES);
4163 const HttpResponseInfo* response = trans->GetResponseInfo();
4164 ASSERT_TRUE(response != NULL);
4165 ASSERT_TRUE(response->headers.get() != NULL);
4166 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
4168 std::string response_data;
4169 scoped_refptr<IOBuffer> buf(new IOBuffer(256));
4170 EXPECT_EQ(1, trans->Read(buf.get(), 256, callback.callback()));
4171 trans.reset();
4173 scoped_ptr<HttpTransaction> trans2(
4174 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4175 rv = trans2->Start(&request2, callback.callback(), BoundNetLog());
4176 EXPECT_EQ(ERR_IO_PENDING, rv);
4178 rv = callback.WaitForResult();
4179 EXPECT_EQ(OK, rv);
4181 LoadTimingInfo load_timing_info2;
4182 EXPECT_TRUE(trans2->GetLoadTimingInfo(&load_timing_info2));
4183 TestLoadTimingReused(load_timing_info2);
4185 // The requests should have the same ID.
4186 EXPECT_EQ(load_timing_info.socket_log_id, load_timing_info2.socket_log_id);
4188 EXPECT_EQ(2, trans2->Read(buf.get(), 256, callback.callback()));
4191 // Test load timing in the case of of two HTTP requests through a SPDY HTTPS
4192 // Proxy to different servers.
4193 TEST_P(HttpNetworkTransactionTest, HttpsProxySpdyLoadTimingTwoHttpRequests) {
4194 // Configure against https proxy server "proxy:70".
4195 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
4196 "https://proxy:70"));
4197 BoundTestNetLog log;
4198 session_deps_.net_log = log.bound().net_log();
4199 scoped_refptr<HttpNetworkSession> session(
4200 SpdySessionDependencies::SpdyCreateSession(&session_deps_));
4202 HttpRequestInfo request1;
4203 request1.method = "GET";
4204 request1.url = GURL("http://www.example.org/");
4205 request1.load_flags = 0;
4207 HttpRequestInfo request2;
4208 request2.method = "GET";
4209 request2.url = GURL("http://mail.example.org/");
4210 request2.load_flags = 0;
4212 // http://www.example.org/
4213 scoped_ptr<SpdyHeaderBlock> headers(
4214 spdy_util_.ConstructGetHeaderBlockForProxy("http://www.example.org/"));
4215 scoped_ptr<SpdyFrame> get1(
4216 spdy_util_.ConstructSpdySyn(1, *headers, LOWEST, false, true));
4217 scoped_ptr<SpdyFrame> get_resp1(
4218 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
4219 scoped_ptr<SpdyFrame> body1(
4220 spdy_util_.ConstructSpdyBodyFrame(1, "1", 1, true));
4222 // http://mail.example.org/
4223 scoped_ptr<SpdyHeaderBlock> headers2(
4224 spdy_util_.ConstructGetHeaderBlockForProxy("http://mail.example.org/"));
4225 scoped_ptr<SpdyFrame> get2(
4226 spdy_util_.ConstructSpdySyn(3, *headers2, LOWEST, false, true));
4227 scoped_ptr<SpdyFrame> get_resp2(
4228 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
4229 scoped_ptr<SpdyFrame> body2(
4230 spdy_util_.ConstructSpdyBodyFrame(3, "22", 2, true));
4232 MockWrite spdy_writes[] = {
4233 CreateMockWrite(*get1, 0),
4234 CreateMockWrite(*get2, 3),
4237 MockRead spdy_reads[] = {
4238 CreateMockRead(*get_resp1, 1, ASYNC),
4239 CreateMockRead(*body1, 2, ASYNC),
4240 CreateMockRead(*get_resp2, 4, ASYNC),
4241 CreateMockRead(*body2, 5, ASYNC),
4242 MockRead(ASYNC, 0, 6),
4245 SequencedSocketData spdy_data(spdy_reads, arraysize(spdy_reads), spdy_writes,
4246 arraysize(spdy_writes));
4247 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
4249 SSLSocketDataProvider ssl(ASYNC, OK);
4250 ssl.SetNextProto(GetParam());
4251 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
4253 TestCompletionCallback callback;
4255 scoped_ptr<HttpTransaction> trans(
4256 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4257 int rv = trans->Start(&request1, callback.callback(), BoundNetLog());
4258 EXPECT_EQ(OK, callback.GetResult(rv));
4260 LoadTimingInfo load_timing_info;
4261 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
4262 TestLoadTimingNotReused(load_timing_info,
4263 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
4265 const HttpResponseInfo* response = trans->GetResponseInfo();
4266 ASSERT_TRUE(response != NULL);
4267 ASSERT_TRUE(response->headers.get() != NULL);
4268 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
4270 std::string response_data;
4271 scoped_refptr<IOBuffer> buf(new IOBuffer(256));
4272 rv = trans->Read(buf.get(), 256, callback.callback());
4273 EXPECT_EQ(1, callback.GetResult(rv));
4274 // Delete the first request, so the second one can reuse the socket.
4275 trans.reset();
4277 scoped_ptr<HttpTransaction> trans2(
4278 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4279 rv = trans2->Start(&request2, callback.callback(), BoundNetLog());
4280 EXPECT_EQ(OK, callback.GetResult(rv));
4282 LoadTimingInfo load_timing_info2;
4283 EXPECT_TRUE(trans2->GetLoadTimingInfo(&load_timing_info2));
4284 TestLoadTimingReused(load_timing_info2);
4286 // The requests should have the same ID.
4287 EXPECT_EQ(load_timing_info.socket_log_id, load_timing_info2.socket_log_id);
4289 rv = trans2->Read(buf.get(), 256, callback.callback());
4290 EXPECT_EQ(2, callback.GetResult(rv));
4293 // Test the challenge-response-retry sequence through an HTTPS Proxy
4294 TEST_P(HttpNetworkTransactionTest, HttpsProxyAuthRetry) {
4295 HttpRequestInfo request;
4296 request.method = "GET";
4297 request.url = GURL("http://www.example.org/");
4298 // when the no authentication data flag is set.
4299 request.load_flags = LOAD_DO_NOT_SEND_AUTH_DATA;
4301 // Configure against https proxy server "myproxy:70".
4302 session_deps_.proxy_service.reset(
4303 ProxyService::CreateFixed("https://myproxy:70"));
4304 BoundTestNetLog log;
4305 session_deps_.net_log = log.bound().net_log();
4306 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
4308 // Since we have proxy, should use full url
4309 MockWrite data_writes1[] = {
4310 MockWrite(
4311 "GET http://www.example.org/ HTTP/1.1\r\n"
4312 "Host: www.example.org\r\n"
4313 "Proxy-Connection: keep-alive\r\n\r\n"),
4315 // After calling trans->RestartWithAuth(), this is the request we should
4316 // be issuing -- the final header line contains the credentials.
4317 MockWrite(
4318 "GET http://www.example.org/ HTTP/1.1\r\n"
4319 "Host: www.example.org\r\n"
4320 "Proxy-Connection: keep-alive\r\n"
4321 "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
4324 // The proxy responds to the GET with a 407, using a persistent
4325 // connection.
4326 MockRead data_reads1[] = {
4327 // No credentials.
4328 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
4329 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
4330 MockRead("Proxy-Connection: keep-alive\r\n"),
4331 MockRead("Content-Length: 0\r\n\r\n"),
4333 MockRead("HTTP/1.1 200 OK\r\n"),
4334 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
4335 MockRead("Content-Length: 100\r\n\r\n"),
4336 MockRead(SYNCHRONOUS, OK),
4339 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
4340 data_writes1, arraysize(data_writes1));
4341 session_deps_.socket_factory->AddSocketDataProvider(&data1);
4342 SSLSocketDataProvider ssl(ASYNC, OK);
4343 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
4345 TestCompletionCallback callback1;
4347 scoped_ptr<HttpTransaction> trans(
4348 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4350 int rv = trans->Start(&request, callback1.callback(), log.bound());
4351 EXPECT_EQ(ERR_IO_PENDING, rv);
4353 rv = callback1.WaitForResult();
4354 EXPECT_EQ(OK, rv);
4356 LoadTimingInfo load_timing_info;
4357 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
4358 TestLoadTimingNotReused(load_timing_info,
4359 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
4361 const HttpResponseInfo* response = trans->GetResponseInfo();
4362 ASSERT_TRUE(response != NULL);
4363 ASSERT_FALSE(response->headers.get() == NULL);
4364 EXPECT_EQ(407, response->headers->response_code());
4365 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
4366 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
4368 TestCompletionCallback callback2;
4370 rv = trans->RestartWithAuth(
4371 AuthCredentials(kFoo, kBar), callback2.callback());
4372 EXPECT_EQ(ERR_IO_PENDING, rv);
4374 rv = callback2.WaitForResult();
4375 EXPECT_EQ(OK, rv);
4377 load_timing_info = LoadTimingInfo();
4378 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
4379 // Retrying with HTTP AUTH is considered to be reusing a socket.
4380 TestLoadTimingReused(load_timing_info);
4382 response = trans->GetResponseInfo();
4383 ASSERT_TRUE(response != NULL);
4385 EXPECT_TRUE(response->headers->IsKeepAlive());
4386 EXPECT_EQ(200, response->headers->response_code());
4387 EXPECT_EQ(100, response->headers->GetContentLength());
4388 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
4390 // The password prompt info should not be set.
4391 EXPECT_TRUE(response->auth_challenge.get() == NULL);
4394 void HttpNetworkTransactionTest::ConnectStatusHelperWithExpectedStatus(
4395 const MockRead& status, int expected_status) {
4396 HttpRequestInfo request;
4397 request.method = "GET";
4398 request.url = GURL("https://www.example.org/");
4399 request.load_flags = 0;
4401 // Configure against proxy server "myproxy:70".
4402 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
4403 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
4405 // Since we have proxy, should try to establish tunnel.
4406 MockWrite data_writes[] = {
4407 MockWrite(
4408 "CONNECT www.example.org:443 HTTP/1.1\r\n"
4409 "Host: www.example.org\r\n"
4410 "Proxy-Connection: keep-alive\r\n\r\n"),
4413 MockRead data_reads[] = {
4414 status,
4415 MockRead("Content-Length: 10\r\n\r\n"),
4416 // No response body because the test stops reading here.
4417 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
4420 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
4421 data_writes, arraysize(data_writes));
4422 session_deps_.socket_factory->AddSocketDataProvider(&data);
4424 TestCompletionCallback callback;
4426 scoped_ptr<HttpTransaction> trans(
4427 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4429 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
4430 EXPECT_EQ(ERR_IO_PENDING, rv);
4432 rv = callback.WaitForResult();
4433 EXPECT_EQ(expected_status, rv);
4436 void HttpNetworkTransactionTest::ConnectStatusHelper(
4437 const MockRead& status) {
4438 ConnectStatusHelperWithExpectedStatus(
4439 status, ERR_TUNNEL_CONNECTION_FAILED);
4442 TEST_P(HttpNetworkTransactionTest, ConnectStatus100) {
4443 ConnectStatusHelper(MockRead("HTTP/1.1 100 Continue\r\n"));
4446 TEST_P(HttpNetworkTransactionTest, ConnectStatus101) {
4447 ConnectStatusHelper(MockRead("HTTP/1.1 101 Switching Protocols\r\n"));
4450 TEST_P(HttpNetworkTransactionTest, ConnectStatus201) {
4451 ConnectStatusHelper(MockRead("HTTP/1.1 201 Created\r\n"));
4454 TEST_P(HttpNetworkTransactionTest, ConnectStatus202) {
4455 ConnectStatusHelper(MockRead("HTTP/1.1 202 Accepted\r\n"));
4458 TEST_P(HttpNetworkTransactionTest, ConnectStatus203) {
4459 ConnectStatusHelper(
4460 MockRead("HTTP/1.1 203 Non-Authoritative Information\r\n"));
4463 TEST_P(HttpNetworkTransactionTest, ConnectStatus204) {
4464 ConnectStatusHelper(MockRead("HTTP/1.1 204 No Content\r\n"));
4467 TEST_P(HttpNetworkTransactionTest, ConnectStatus205) {
4468 ConnectStatusHelper(MockRead("HTTP/1.1 205 Reset Content\r\n"));
4471 TEST_P(HttpNetworkTransactionTest, ConnectStatus206) {
4472 ConnectStatusHelper(MockRead("HTTP/1.1 206 Partial Content\r\n"));
4475 TEST_P(HttpNetworkTransactionTest, ConnectStatus300) {
4476 ConnectStatusHelper(MockRead("HTTP/1.1 300 Multiple Choices\r\n"));
4479 TEST_P(HttpNetworkTransactionTest, ConnectStatus301) {
4480 ConnectStatusHelper(MockRead("HTTP/1.1 301 Moved Permanently\r\n"));
4483 TEST_P(HttpNetworkTransactionTest, ConnectStatus302) {
4484 ConnectStatusHelper(MockRead("HTTP/1.1 302 Found\r\n"));
4487 TEST_P(HttpNetworkTransactionTest, ConnectStatus303) {
4488 ConnectStatusHelper(MockRead("HTTP/1.1 303 See Other\r\n"));
4491 TEST_P(HttpNetworkTransactionTest, ConnectStatus304) {
4492 ConnectStatusHelper(MockRead("HTTP/1.1 304 Not Modified\r\n"));
4495 TEST_P(HttpNetworkTransactionTest, ConnectStatus305) {
4496 ConnectStatusHelper(MockRead("HTTP/1.1 305 Use Proxy\r\n"));
4499 TEST_P(HttpNetworkTransactionTest, ConnectStatus306) {
4500 ConnectStatusHelper(MockRead("HTTP/1.1 306\r\n"));
4503 TEST_P(HttpNetworkTransactionTest, ConnectStatus307) {
4504 ConnectStatusHelper(MockRead("HTTP/1.1 307 Temporary Redirect\r\n"));
4507 TEST_P(HttpNetworkTransactionTest, ConnectStatus308) {
4508 ConnectStatusHelper(MockRead("HTTP/1.1 308 Permanent Redirect\r\n"));
4511 TEST_P(HttpNetworkTransactionTest, ConnectStatus400) {
4512 ConnectStatusHelper(MockRead("HTTP/1.1 400 Bad Request\r\n"));
4515 TEST_P(HttpNetworkTransactionTest, ConnectStatus401) {
4516 ConnectStatusHelper(MockRead("HTTP/1.1 401 Unauthorized\r\n"));
4519 TEST_P(HttpNetworkTransactionTest, ConnectStatus402) {
4520 ConnectStatusHelper(MockRead("HTTP/1.1 402 Payment Required\r\n"));
4523 TEST_P(HttpNetworkTransactionTest, ConnectStatus403) {
4524 ConnectStatusHelper(MockRead("HTTP/1.1 403 Forbidden\r\n"));
4527 TEST_P(HttpNetworkTransactionTest, ConnectStatus404) {
4528 ConnectStatusHelper(MockRead("HTTP/1.1 404 Not Found\r\n"));
4531 TEST_P(HttpNetworkTransactionTest, ConnectStatus405) {
4532 ConnectStatusHelper(MockRead("HTTP/1.1 405 Method Not Allowed\r\n"));
4535 TEST_P(HttpNetworkTransactionTest, ConnectStatus406) {
4536 ConnectStatusHelper(MockRead("HTTP/1.1 406 Not Acceptable\r\n"));
4539 TEST_P(HttpNetworkTransactionTest, ConnectStatus407) {
4540 ConnectStatusHelperWithExpectedStatus(
4541 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
4542 ERR_PROXY_AUTH_UNSUPPORTED);
4545 TEST_P(HttpNetworkTransactionTest, ConnectStatus408) {
4546 ConnectStatusHelper(MockRead("HTTP/1.1 408 Request Timeout\r\n"));
4549 TEST_P(HttpNetworkTransactionTest, ConnectStatus409) {
4550 ConnectStatusHelper(MockRead("HTTP/1.1 409 Conflict\r\n"));
4553 TEST_P(HttpNetworkTransactionTest, ConnectStatus410) {
4554 ConnectStatusHelper(MockRead("HTTP/1.1 410 Gone\r\n"));
4557 TEST_P(HttpNetworkTransactionTest, ConnectStatus411) {
4558 ConnectStatusHelper(MockRead("HTTP/1.1 411 Length Required\r\n"));
4561 TEST_P(HttpNetworkTransactionTest, ConnectStatus412) {
4562 ConnectStatusHelper(MockRead("HTTP/1.1 412 Precondition Failed\r\n"));
4565 TEST_P(HttpNetworkTransactionTest, ConnectStatus413) {
4566 ConnectStatusHelper(MockRead("HTTP/1.1 413 Request Entity Too Large\r\n"));
4569 TEST_P(HttpNetworkTransactionTest, ConnectStatus414) {
4570 ConnectStatusHelper(MockRead("HTTP/1.1 414 Request-URI Too Long\r\n"));
4573 TEST_P(HttpNetworkTransactionTest, ConnectStatus415) {
4574 ConnectStatusHelper(MockRead("HTTP/1.1 415 Unsupported Media Type\r\n"));
4577 TEST_P(HttpNetworkTransactionTest, ConnectStatus416) {
4578 ConnectStatusHelper(
4579 MockRead("HTTP/1.1 416 Requested Range Not Satisfiable\r\n"));
4582 TEST_P(HttpNetworkTransactionTest, ConnectStatus417) {
4583 ConnectStatusHelper(MockRead("HTTP/1.1 417 Expectation Failed\r\n"));
4586 TEST_P(HttpNetworkTransactionTest, ConnectStatus500) {
4587 ConnectStatusHelper(MockRead("HTTP/1.1 500 Internal Server Error\r\n"));
4590 TEST_P(HttpNetworkTransactionTest, ConnectStatus501) {
4591 ConnectStatusHelper(MockRead("HTTP/1.1 501 Not Implemented\r\n"));
4594 TEST_P(HttpNetworkTransactionTest, ConnectStatus502) {
4595 ConnectStatusHelper(MockRead("HTTP/1.1 502 Bad Gateway\r\n"));
4598 TEST_P(HttpNetworkTransactionTest, ConnectStatus503) {
4599 ConnectStatusHelper(MockRead("HTTP/1.1 503 Service Unavailable\r\n"));
4602 TEST_P(HttpNetworkTransactionTest, ConnectStatus504) {
4603 ConnectStatusHelper(MockRead("HTTP/1.1 504 Gateway Timeout\r\n"));
4606 TEST_P(HttpNetworkTransactionTest, ConnectStatus505) {
4607 ConnectStatusHelper(MockRead("HTTP/1.1 505 HTTP Version Not Supported\r\n"));
4610 // Test the flow when both the proxy server AND origin server require
4611 // authentication. Again, this uses basic auth for both since that is
4612 // the simplest to mock.
4613 TEST_P(HttpNetworkTransactionTest, BasicAuthProxyThenServer) {
4614 HttpRequestInfo request;
4615 request.method = "GET";
4616 request.url = GURL("http://www.example.org/");
4617 request.load_flags = 0;
4619 // Configure against proxy server "myproxy:70".
4620 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
4621 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
4623 scoped_ptr<HttpTransaction> trans(
4624 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4626 MockWrite data_writes1[] = {
4627 MockWrite(
4628 "GET http://www.example.org/ HTTP/1.1\r\n"
4629 "Host: www.example.org\r\n"
4630 "Proxy-Connection: keep-alive\r\n\r\n"),
4633 MockRead data_reads1[] = {
4634 MockRead("HTTP/1.0 407 Unauthorized\r\n"),
4635 // Give a couple authenticate options (only the middle one is actually
4636 // supported).
4637 MockRead("Proxy-Authenticate: Basic invalid\r\n"), // Malformed.
4638 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
4639 MockRead("Proxy-Authenticate: UNSUPPORTED realm=\"FOO\"\r\n"),
4640 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
4641 // Large content-length -- won't matter, as connection will be reset.
4642 MockRead("Content-Length: 10000\r\n\r\n"),
4643 MockRead(SYNCHRONOUS, ERR_FAILED),
4646 // After calling trans->RestartWithAuth() the first time, this is the
4647 // request we should be issuing -- the final header line contains the
4648 // proxy's credentials.
4649 MockWrite data_writes2[] = {
4650 MockWrite(
4651 "GET http://www.example.org/ HTTP/1.1\r\n"
4652 "Host: www.example.org\r\n"
4653 "Proxy-Connection: keep-alive\r\n"
4654 "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
4657 // Now the proxy server lets the request pass through to origin server.
4658 // The origin server responds with a 401.
4659 MockRead data_reads2[] = {
4660 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
4661 // Note: We are using the same realm-name as the proxy server. This is
4662 // completely valid, as realms are unique across hosts.
4663 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
4664 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
4665 MockRead("Content-Length: 2000\r\n\r\n"),
4666 MockRead(SYNCHRONOUS, ERR_FAILED), // Won't be reached.
4669 // After calling trans->RestartWithAuth() the second time, we should send
4670 // the credentials for both the proxy and origin server.
4671 MockWrite data_writes3[] = {
4672 MockWrite(
4673 "GET http://www.example.org/ HTTP/1.1\r\n"
4674 "Host: www.example.org\r\n"
4675 "Proxy-Connection: keep-alive\r\n"
4676 "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n"
4677 "Authorization: Basic Zm9vMjpiYXIy\r\n\r\n"),
4680 // Lastly we get the desired content.
4681 MockRead data_reads3[] = {
4682 MockRead("HTTP/1.0 200 OK\r\n"),
4683 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
4684 MockRead("Content-Length: 100\r\n\r\n"),
4685 MockRead(SYNCHRONOUS, OK),
4688 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
4689 data_writes1, arraysize(data_writes1));
4690 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
4691 data_writes2, arraysize(data_writes2));
4692 StaticSocketDataProvider data3(data_reads3, arraysize(data_reads3),
4693 data_writes3, arraysize(data_writes3));
4694 session_deps_.socket_factory->AddSocketDataProvider(&data1);
4695 session_deps_.socket_factory->AddSocketDataProvider(&data2);
4696 session_deps_.socket_factory->AddSocketDataProvider(&data3);
4698 TestCompletionCallback callback1;
4700 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
4701 EXPECT_EQ(ERR_IO_PENDING, rv);
4703 rv = callback1.WaitForResult();
4704 EXPECT_EQ(OK, rv);
4706 const HttpResponseInfo* response = trans->GetResponseInfo();
4707 ASSERT_TRUE(response != NULL);
4708 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
4710 TestCompletionCallback callback2;
4712 rv = trans->RestartWithAuth(
4713 AuthCredentials(kFoo, kBar), callback2.callback());
4714 EXPECT_EQ(ERR_IO_PENDING, rv);
4716 rv = callback2.WaitForResult();
4717 EXPECT_EQ(OK, rv);
4719 response = trans->GetResponseInfo();
4720 ASSERT_TRUE(response != NULL);
4721 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
4723 TestCompletionCallback callback3;
4725 rv = trans->RestartWithAuth(
4726 AuthCredentials(kFoo2, kBar2), callback3.callback());
4727 EXPECT_EQ(ERR_IO_PENDING, rv);
4729 rv = callback3.WaitForResult();
4730 EXPECT_EQ(OK, rv);
4732 response = trans->GetResponseInfo();
4733 EXPECT_TRUE(response->auth_challenge.get() == NULL);
4734 EXPECT_EQ(100, response->headers->GetContentLength());
4737 // For the NTLM implementation using SSPI, we skip the NTLM tests since we
4738 // can't hook into its internals to cause it to generate predictable NTLM
4739 // authorization headers.
4740 #if defined(NTLM_PORTABLE)
4741 // The NTLM authentication unit tests were generated by capturing the HTTP
4742 // requests and responses using Fiddler 2 and inspecting the generated random
4743 // bytes in the debugger.
4745 // Enter the correct password and authenticate successfully.
4746 TEST_P(HttpNetworkTransactionTest, NTLMAuth1) {
4747 HttpRequestInfo request;
4748 request.method = "GET";
4749 request.url = GURL("http://172.22.68.17/kids/login.aspx");
4751 // Ensure load is not disrupted by flags which suppress behaviour specific
4752 // to other auth schemes.
4753 request.load_flags = LOAD_DO_NOT_USE_EMBEDDED_IDENTITY;
4755 HttpAuthHandlerNTLM::ScopedProcSetter proc_setter(MockGenerateRandom1,
4756 MockGetHostName);
4757 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
4759 MockWrite data_writes1[] = {
4760 MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
4761 "Host: 172.22.68.17\r\n"
4762 "Connection: keep-alive\r\n\r\n"),
4765 MockRead data_reads1[] = {
4766 MockRead("HTTP/1.1 401 Access Denied\r\n"),
4767 // Negotiate and NTLM are often requested together. However, we only want
4768 // to test NTLM. Since Negotiate is preferred over NTLM, we have to skip
4769 // the header that requests Negotiate for this test.
4770 MockRead("WWW-Authenticate: NTLM\r\n"),
4771 MockRead("Connection: close\r\n"),
4772 MockRead("Content-Length: 42\r\n"),
4773 MockRead("Content-Type: text/html\r\n\r\n"),
4774 // Missing content -- won't matter, as connection will be reset.
4775 MockRead(SYNCHRONOUS, ERR_UNEXPECTED),
4778 MockWrite data_writes2[] = {
4779 // After restarting with a null identity, this is the
4780 // request we should be issuing -- the final header line contains a Type
4781 // 1 message.
4782 MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
4783 "Host: 172.22.68.17\r\n"
4784 "Connection: keep-alive\r\n"
4785 "Authorization: NTLM "
4786 "TlRMTVNTUAABAAAAB4IIAAAAAAAAAAAAAAAAAAAAAAA=\r\n\r\n"),
4788 // After calling trans->RestartWithAuth(), we should send a Type 3 message
4789 // (the credentials for the origin server). The second request continues
4790 // on the same connection.
4791 MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
4792 "Host: 172.22.68.17\r\n"
4793 "Connection: keep-alive\r\n"
4794 "Authorization: NTLM TlRMTVNTUAADAAAAGAAYAGgAAAAYABgAgA"
4795 "AAAAAAAABAAAAAGAAYAEAAAAAQABAAWAAAAAAAAAAAAAAABYIIAHQA"
4796 "ZQBzAHQAaQBuAGcALQBuAHQAbABtAFcAVABDAC0AVwBJAE4ANwBVKW"
4797 "Yma5xzVAAAAAAAAAAAAAAAAAAAAACH+gWcm+YsP9Tqb9zCR3WAeZZX"
4798 "ahlhx5I=\r\n\r\n"),
4801 MockRead data_reads2[] = {
4802 // The origin server responds with a Type 2 message.
4803 MockRead("HTTP/1.1 401 Access Denied\r\n"),
4804 MockRead("WWW-Authenticate: NTLM "
4805 "TlRMTVNTUAACAAAADAAMADgAAAAFgokCjGpMpPGlYKkAAAAAAAAAALo"
4806 "AugBEAAAABQEoCgAAAA9HAE8ATwBHAEwARQACAAwARwBPAE8ARwBMAE"
4807 "UAAQAaAEEASwBFAEUAUwBBAFIAQQAtAEMATwBSAFAABAAeAGMAbwByA"
4808 "HAALgBnAG8AbwBnAGwAZQAuAGMAbwBtAAMAQABhAGsAZQBlAHMAYQBy"
4809 "AGEALQBjAG8AcgBwAC4AYQBkAC4AYwBvAHIAcAAuAGcAbwBvAGcAbAB"
4810 "lAC4AYwBvAG0ABQAeAGMAbwByAHAALgBnAG8AbwBnAGwAZQAuAGMAbw"
4811 "BtAAAAAAA=\r\n"),
4812 MockRead("Content-Length: 42\r\n"),
4813 MockRead("Content-Type: text/html\r\n\r\n"),
4814 MockRead("You are not authorized to view this page\r\n"),
4816 // Lastly we get the desired content.
4817 MockRead("HTTP/1.1 200 OK\r\n"),
4818 MockRead("Content-Type: text/html; charset=utf-8\r\n"),
4819 MockRead("Content-Length: 13\r\n\r\n"),
4820 MockRead("Please Login\r\n"),
4821 MockRead(SYNCHRONOUS, OK),
4824 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
4825 data_writes1, arraysize(data_writes1));
4826 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
4827 data_writes2, arraysize(data_writes2));
4828 session_deps_.socket_factory->AddSocketDataProvider(&data1);
4829 session_deps_.socket_factory->AddSocketDataProvider(&data2);
4831 TestCompletionCallback callback1;
4833 scoped_ptr<HttpTransaction> trans(
4834 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4836 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
4837 EXPECT_EQ(ERR_IO_PENDING, rv);
4839 rv = callback1.WaitForResult();
4840 EXPECT_EQ(OK, rv);
4842 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
4844 const HttpResponseInfo* response = trans->GetResponseInfo();
4845 ASSERT_FALSE(response == NULL);
4846 EXPECT_TRUE(CheckNTLMServerAuth(response->auth_challenge.get()));
4848 TestCompletionCallback callback2;
4850 rv = trans->RestartWithAuth(AuthCredentials(kTestingNTLM, kTestingNTLM),
4851 callback2.callback());
4852 EXPECT_EQ(ERR_IO_PENDING, rv);
4854 rv = callback2.WaitForResult();
4855 EXPECT_EQ(OK, rv);
4857 EXPECT_TRUE(trans->IsReadyToRestartForAuth());
4859 response = trans->GetResponseInfo();
4860 ASSERT_TRUE(response != NULL);
4861 EXPECT_TRUE(response->auth_challenge.get() == NULL);
4863 TestCompletionCallback callback3;
4865 rv = trans->RestartWithAuth(AuthCredentials(), callback3.callback());
4866 EXPECT_EQ(ERR_IO_PENDING, rv);
4868 rv = callback3.WaitForResult();
4869 EXPECT_EQ(OK, rv);
4871 response = trans->GetResponseInfo();
4872 ASSERT_TRUE(response != NULL);
4873 EXPECT_TRUE(response->auth_challenge.get() == NULL);
4874 EXPECT_EQ(13, response->headers->GetContentLength());
4877 // Enter a wrong password, and then the correct one.
4878 TEST_P(HttpNetworkTransactionTest, NTLMAuth2) {
4879 HttpRequestInfo request;
4880 request.method = "GET";
4881 request.url = GURL("http://172.22.68.17/kids/login.aspx");
4882 request.load_flags = 0;
4884 HttpAuthHandlerNTLM::ScopedProcSetter proc_setter(MockGenerateRandom2,
4885 MockGetHostName);
4886 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
4888 MockWrite data_writes1[] = {
4889 MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
4890 "Host: 172.22.68.17\r\n"
4891 "Connection: keep-alive\r\n\r\n"),
4894 MockRead data_reads1[] = {
4895 MockRead("HTTP/1.1 401 Access Denied\r\n"),
4896 // Negotiate and NTLM are often requested together. However, we only want
4897 // to test NTLM. Since Negotiate is preferred over NTLM, we have to skip
4898 // the header that requests Negotiate for this test.
4899 MockRead("WWW-Authenticate: NTLM\r\n"),
4900 MockRead("Connection: close\r\n"),
4901 MockRead("Content-Length: 42\r\n"),
4902 MockRead("Content-Type: text/html\r\n\r\n"),
4903 // Missing content -- won't matter, as connection will be reset.
4904 MockRead(SYNCHRONOUS, ERR_UNEXPECTED),
4907 MockWrite data_writes2[] = {
4908 // After restarting with a null identity, this is the
4909 // request we should be issuing -- the final header line contains a Type
4910 // 1 message.
4911 MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
4912 "Host: 172.22.68.17\r\n"
4913 "Connection: keep-alive\r\n"
4914 "Authorization: NTLM "
4915 "TlRMTVNTUAABAAAAB4IIAAAAAAAAAAAAAAAAAAAAAAA=\r\n\r\n"),
4917 // After calling trans->RestartWithAuth(), we should send a Type 3 message
4918 // (the credentials for the origin server). The second request continues
4919 // on the same connection.
4920 MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
4921 "Host: 172.22.68.17\r\n"
4922 "Connection: keep-alive\r\n"
4923 "Authorization: NTLM TlRMTVNTUAADAAAAGAAYAGgAAAAYABgAgA"
4924 "AAAAAAAABAAAAAGAAYAEAAAAAQABAAWAAAAAAAAAAAAAAABYIIAHQA"
4925 "ZQBzAHQAaQBuAGcALQBuAHQAbABtAFcAVABDAC0AVwBJAE4ANwCWeY"
4926 "XnSZNwoQAAAAAAAAAAAAAAAAAAAADLa34/phTTKzNTWdub+uyFleOj"
4927 "4Ww7b7E=\r\n\r\n"),
4930 MockRead data_reads2[] = {
4931 // The origin server responds with a Type 2 message.
4932 MockRead("HTTP/1.1 401 Access Denied\r\n"),
4933 MockRead("WWW-Authenticate: NTLM "
4934 "TlRMTVNTUAACAAAADAAMADgAAAAFgokCbVWUZezVGpAAAAAAAAAAALo"
4935 "AugBEAAAABQEoCgAAAA9HAE8ATwBHAEwARQACAAwARwBPAE8ARwBMAE"
4936 "UAAQAaAEEASwBFAEUAUwBBAFIAQQAtAEMATwBSAFAABAAeAGMAbwByA"
4937 "HAALgBnAG8AbwBnAGwAZQAuAGMAbwBtAAMAQABhAGsAZQBlAHMAYQBy"
4938 "AGEALQBjAG8AcgBwAC4AYQBkAC4AYwBvAHIAcAAuAGcAbwBvAGcAbAB"
4939 "lAC4AYwBvAG0ABQAeAGMAbwByAHAALgBnAG8AbwBnAGwAZQAuAGMAbw"
4940 "BtAAAAAAA=\r\n"),
4941 MockRead("Content-Length: 42\r\n"),
4942 MockRead("Content-Type: text/html\r\n\r\n"),
4943 MockRead("You are not authorized to view this page\r\n"),
4945 // Wrong password.
4946 MockRead("HTTP/1.1 401 Access Denied\r\n"),
4947 MockRead("WWW-Authenticate: NTLM\r\n"),
4948 MockRead("Connection: close\r\n"),
4949 MockRead("Content-Length: 42\r\n"),
4950 MockRead("Content-Type: text/html\r\n\r\n"),
4951 // Missing content -- won't matter, as connection will be reset.
4952 MockRead(SYNCHRONOUS, ERR_UNEXPECTED),
4955 MockWrite data_writes3[] = {
4956 // After restarting with a null identity, this is the
4957 // request we should be issuing -- the final header line contains a Type
4958 // 1 message.
4959 MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
4960 "Host: 172.22.68.17\r\n"
4961 "Connection: keep-alive\r\n"
4962 "Authorization: NTLM "
4963 "TlRMTVNTUAABAAAAB4IIAAAAAAAAAAAAAAAAAAAAAAA=\r\n\r\n"),
4965 // After calling trans->RestartWithAuth(), we should send a Type 3 message
4966 // (the credentials for the origin server). The second request continues
4967 // on the same connection.
4968 MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
4969 "Host: 172.22.68.17\r\n"
4970 "Connection: keep-alive\r\n"
4971 "Authorization: NTLM TlRMTVNTUAADAAAAGAAYAGgAAAAYABgAgA"
4972 "AAAAAAAABAAAAAGAAYAEAAAAAQABAAWAAAAAAAAAAAAAAABYIIAHQA"
4973 "ZQBzAHQAaQBuAGcALQBuAHQAbABtAFcAVABDAC0AVwBJAE4ANwBO54"
4974 "dFMVvTHwAAAAAAAAAAAAAAAAAAAACS7sT6Uzw7L0L//WUqlIaVWpbI"
4975 "+4MUm7c=\r\n\r\n"),
4978 MockRead data_reads3[] = {
4979 // The origin server responds with a Type 2 message.
4980 MockRead("HTTP/1.1 401 Access Denied\r\n"),
4981 MockRead("WWW-Authenticate: NTLM "
4982 "TlRMTVNTUAACAAAADAAMADgAAAAFgokCL24VN8dgOR8AAAAAAAAAALo"
4983 "AugBEAAAABQEoCgAAAA9HAE8ATwBHAEwARQACAAwARwBPAE8ARwBMAE"
4984 "UAAQAaAEEASwBFAEUAUwBBAFIAQQAtAEMATwBSAFAABAAeAGMAbwByA"
4985 "HAALgBnAG8AbwBnAGwAZQAuAGMAbwBtAAMAQABhAGsAZQBlAHMAYQBy"
4986 "AGEALQBjAG8AcgBwAC4AYQBkAC4AYwBvAHIAcAAuAGcAbwBvAGcAbAB"
4987 "lAC4AYwBvAG0ABQAeAGMAbwByAHAALgBnAG8AbwBnAGwAZQAuAGMAbw"
4988 "BtAAAAAAA=\r\n"),
4989 MockRead("Content-Length: 42\r\n"),
4990 MockRead("Content-Type: text/html\r\n\r\n"),
4991 MockRead("You are not authorized to view this page\r\n"),
4993 // Lastly we get the desired content.
4994 MockRead("HTTP/1.1 200 OK\r\n"),
4995 MockRead("Content-Type: text/html; charset=utf-8\r\n"),
4996 MockRead("Content-Length: 13\r\n\r\n"),
4997 MockRead("Please Login\r\n"),
4998 MockRead(SYNCHRONOUS, OK),
5001 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
5002 data_writes1, arraysize(data_writes1));
5003 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
5004 data_writes2, arraysize(data_writes2));
5005 StaticSocketDataProvider data3(data_reads3, arraysize(data_reads3),
5006 data_writes3, arraysize(data_writes3));
5007 session_deps_.socket_factory->AddSocketDataProvider(&data1);
5008 session_deps_.socket_factory->AddSocketDataProvider(&data2);
5009 session_deps_.socket_factory->AddSocketDataProvider(&data3);
5011 TestCompletionCallback callback1;
5013 scoped_ptr<HttpTransaction> trans(
5014 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5016 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
5017 EXPECT_EQ(ERR_IO_PENDING, rv);
5019 rv = callback1.WaitForResult();
5020 EXPECT_EQ(OK, rv);
5022 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
5024 const HttpResponseInfo* response = trans->GetResponseInfo();
5025 ASSERT_TRUE(response != NULL);
5026 EXPECT_TRUE(CheckNTLMServerAuth(response->auth_challenge.get()));
5028 TestCompletionCallback callback2;
5030 // Enter the wrong password.
5031 rv = trans->RestartWithAuth(AuthCredentials(kTestingNTLM, kWrongPassword),
5032 callback2.callback());
5033 EXPECT_EQ(ERR_IO_PENDING, rv);
5035 rv = callback2.WaitForResult();
5036 EXPECT_EQ(OK, rv);
5038 EXPECT_TRUE(trans->IsReadyToRestartForAuth());
5039 TestCompletionCallback callback3;
5040 rv = trans->RestartWithAuth(AuthCredentials(), callback3.callback());
5041 EXPECT_EQ(ERR_IO_PENDING, rv);
5042 rv = callback3.WaitForResult();
5043 EXPECT_EQ(OK, rv);
5044 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
5046 response = trans->GetResponseInfo();
5047 ASSERT_FALSE(response == NULL);
5048 EXPECT_TRUE(CheckNTLMServerAuth(response->auth_challenge.get()));
5050 TestCompletionCallback callback4;
5052 // Now enter the right password.
5053 rv = trans->RestartWithAuth(AuthCredentials(kTestingNTLM, kTestingNTLM),
5054 callback4.callback());
5055 EXPECT_EQ(ERR_IO_PENDING, rv);
5057 rv = callback4.WaitForResult();
5058 EXPECT_EQ(OK, rv);
5060 EXPECT_TRUE(trans->IsReadyToRestartForAuth());
5062 TestCompletionCallback callback5;
5064 // One more roundtrip
5065 rv = trans->RestartWithAuth(AuthCredentials(), callback5.callback());
5066 EXPECT_EQ(ERR_IO_PENDING, rv);
5068 rv = callback5.WaitForResult();
5069 EXPECT_EQ(OK, rv);
5071 response = trans->GetResponseInfo();
5072 EXPECT_TRUE(response->auth_challenge.get() == NULL);
5073 EXPECT_EQ(13, response->headers->GetContentLength());
5075 #endif // NTLM_PORTABLE
5077 // Test reading a server response which has only headers, and no body.
5078 // After some maximum number of bytes is consumed, the transaction should
5079 // fail with ERR_RESPONSE_HEADERS_TOO_BIG.
5080 TEST_P(HttpNetworkTransactionTest, LargeHeadersNoBody) {
5081 HttpRequestInfo request;
5082 request.method = "GET";
5083 request.url = GURL("http://www.example.org/");
5084 request.load_flags = 0;
5086 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5087 scoped_ptr<HttpTransaction> trans(
5088 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5090 // Respond with 300 kb of headers (we should fail after 256 kb).
5091 std::string large_headers_string;
5092 FillLargeHeadersString(&large_headers_string, 300 * 1024);
5094 MockRead data_reads[] = {
5095 MockRead("HTTP/1.0 200 OK\r\n"),
5096 MockRead(ASYNC, large_headers_string.data(), large_headers_string.size()),
5097 MockRead("\r\nBODY"),
5098 MockRead(SYNCHRONOUS, OK),
5100 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
5101 session_deps_.socket_factory->AddSocketDataProvider(&data);
5103 TestCompletionCallback callback;
5105 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
5106 EXPECT_EQ(ERR_IO_PENDING, rv);
5108 rv = callback.WaitForResult();
5109 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, rv);
5112 // Make sure that we don't try to reuse a TCPClientSocket when failing to
5113 // establish tunnel.
5114 // http://code.google.com/p/chromium/issues/detail?id=3772
5115 TEST_P(HttpNetworkTransactionTest,
5116 DontRecycleTransportSocketForSSLTunnel) {
5117 HttpRequestInfo request;
5118 request.method = "GET";
5119 request.url = GURL("https://www.example.org/");
5120 request.load_flags = 0;
5122 // Configure against proxy server "myproxy:70".
5123 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
5125 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5127 scoped_ptr<HttpTransaction> trans(
5128 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5130 // Since we have proxy, should try to establish tunnel.
5131 MockWrite data_writes1[] = {
5132 MockWrite(
5133 "CONNECT www.example.org:443 HTTP/1.1\r\n"
5134 "Host: www.example.org\r\n"
5135 "Proxy-Connection: keep-alive\r\n\r\n"),
5138 // The proxy responds to the connect with a 404, using a persistent
5139 // connection. Usually a proxy would return 501 (not implemented),
5140 // or 200 (tunnel established).
5141 MockRead data_reads1[] = {
5142 MockRead("HTTP/1.1 404 Not Found\r\n"),
5143 MockRead("Content-Length: 10\r\n\r\n"),
5144 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
5147 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
5148 data_writes1, arraysize(data_writes1));
5149 session_deps_.socket_factory->AddSocketDataProvider(&data1);
5151 TestCompletionCallback callback1;
5153 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
5154 EXPECT_EQ(ERR_IO_PENDING, rv);
5156 rv = callback1.WaitForResult();
5157 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, rv);
5159 // Empty the current queue. This is necessary because idle sockets are
5160 // added to the connection pool asynchronously with a PostTask.
5161 base::MessageLoop::current()->RunUntilIdle();
5163 // We now check to make sure the TCPClientSocket was not added back to
5164 // the pool.
5165 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
5166 trans.reset();
5167 base::MessageLoop::current()->RunUntilIdle();
5168 // Make sure that the socket didn't get recycled after calling the destructor.
5169 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
5172 // Make sure that we recycle a socket after reading all of the response body.
5173 TEST_P(HttpNetworkTransactionTest, RecycleSocket) {
5174 HttpRequestInfo request;
5175 request.method = "GET";
5176 request.url = GURL("http://www.example.org/");
5177 request.load_flags = 0;
5179 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5181 scoped_ptr<HttpTransaction> trans(
5182 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5184 MockRead data_reads[] = {
5185 // A part of the response body is received with the response headers.
5186 MockRead("HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nhel"),
5187 // The rest of the response body is received in two parts.
5188 MockRead("lo"),
5189 MockRead(" world"),
5190 MockRead("junk"), // Should not be read!!
5191 MockRead(SYNCHRONOUS, OK),
5194 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
5195 session_deps_.socket_factory->AddSocketDataProvider(&data);
5197 TestCompletionCallback callback;
5199 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
5200 EXPECT_EQ(ERR_IO_PENDING, rv);
5202 rv = callback.WaitForResult();
5203 EXPECT_EQ(OK, rv);
5205 const HttpResponseInfo* response = trans->GetResponseInfo();
5206 ASSERT_TRUE(response != NULL);
5208 EXPECT_TRUE(response->headers.get() != NULL);
5209 std::string status_line = response->headers->GetStatusLine();
5210 EXPECT_EQ("HTTP/1.1 200 OK", status_line);
5212 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
5214 std::string response_data;
5215 rv = ReadTransaction(trans.get(), &response_data);
5216 EXPECT_EQ(OK, rv);
5217 EXPECT_EQ("hello world", response_data);
5219 // Empty the current queue. This is necessary because idle sockets are
5220 // added to the connection pool asynchronously with a PostTask.
5221 base::MessageLoop::current()->RunUntilIdle();
5223 // We now check to make sure the socket was added back to the pool.
5224 EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
5227 // Make sure that we recycle a SSL socket after reading all of the response
5228 // body.
5229 TEST_P(HttpNetworkTransactionTest, RecycleSSLSocket) {
5230 HttpRequestInfo request;
5231 request.method = "GET";
5232 request.url = GURL("https://www.example.org/");
5233 request.load_flags = 0;
5235 MockWrite data_writes[] = {
5236 MockWrite(
5237 "GET / HTTP/1.1\r\n"
5238 "Host: www.example.org\r\n"
5239 "Connection: keep-alive\r\n\r\n"),
5242 MockRead data_reads[] = {
5243 MockRead("HTTP/1.1 200 OK\r\n"),
5244 MockRead("Content-Length: 11\r\n\r\n"),
5245 MockRead("hello world"),
5246 MockRead(SYNCHRONOUS, OK),
5249 SSLSocketDataProvider ssl(ASYNC, OK);
5250 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
5252 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
5253 data_writes, arraysize(data_writes));
5254 session_deps_.socket_factory->AddSocketDataProvider(&data);
5256 TestCompletionCallback callback;
5258 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5259 scoped_ptr<HttpTransaction> trans(
5260 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5262 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
5264 EXPECT_EQ(ERR_IO_PENDING, rv);
5265 EXPECT_EQ(OK, callback.WaitForResult());
5267 const HttpResponseInfo* response = trans->GetResponseInfo();
5268 ASSERT_TRUE(response != NULL);
5269 ASSERT_TRUE(response->headers.get() != NULL);
5270 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
5272 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
5274 std::string response_data;
5275 rv = ReadTransaction(trans.get(), &response_data);
5276 EXPECT_EQ(OK, rv);
5277 EXPECT_EQ("hello world", response_data);
5279 // Empty the current queue. This is necessary because idle sockets are
5280 // added to the connection pool asynchronously with a PostTask.
5281 base::MessageLoop::current()->RunUntilIdle();
5283 // We now check to make sure the socket was added back to the pool.
5284 EXPECT_EQ(1, GetIdleSocketCountInSSLSocketPool(session.get()));
5287 // Grab a SSL socket, use it, and put it back into the pool. Then, reuse it
5288 // from the pool and make sure that we recover okay.
5289 TEST_P(HttpNetworkTransactionTest, RecycleDeadSSLSocket) {
5290 HttpRequestInfo request;
5291 request.method = "GET";
5292 request.url = GURL("https://www.example.org/");
5293 request.load_flags = 0;
5295 MockWrite data_writes[] = {
5296 MockWrite(
5297 "GET / HTTP/1.1\r\n"
5298 "Host: www.example.org\r\n"
5299 "Connection: keep-alive\r\n\r\n"),
5300 MockWrite(
5301 "GET / HTTP/1.1\r\n"
5302 "Host: www.example.org\r\n"
5303 "Connection: keep-alive\r\n\r\n"),
5306 MockRead data_reads[] = {
5307 MockRead("HTTP/1.1 200 OK\r\n"),
5308 MockRead("Content-Length: 11\r\n\r\n"),
5309 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
5310 MockRead("hello world"),
5311 MockRead(ASYNC, 0, 0) // EOF
5314 SSLSocketDataProvider ssl(ASYNC, OK);
5315 SSLSocketDataProvider ssl2(ASYNC, OK);
5316 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
5317 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
5319 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
5320 data_writes, arraysize(data_writes));
5321 StaticSocketDataProvider data2(data_reads, arraysize(data_reads),
5322 data_writes, arraysize(data_writes));
5323 session_deps_.socket_factory->AddSocketDataProvider(&data);
5324 session_deps_.socket_factory->AddSocketDataProvider(&data2);
5326 TestCompletionCallback callback;
5328 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5329 scoped_ptr<HttpTransaction> trans(
5330 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5332 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
5334 EXPECT_EQ(ERR_IO_PENDING, rv);
5335 EXPECT_EQ(OK, callback.WaitForResult());
5337 const HttpResponseInfo* response = trans->GetResponseInfo();
5338 ASSERT_TRUE(response != NULL);
5339 ASSERT_TRUE(response->headers.get() != NULL);
5340 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
5342 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
5344 std::string response_data;
5345 rv = ReadTransaction(trans.get(), &response_data);
5346 EXPECT_EQ(OK, rv);
5347 EXPECT_EQ("hello world", response_data);
5349 // Empty the current queue. This is necessary because idle sockets are
5350 // added to the connection pool asynchronously with a PostTask.
5351 base::MessageLoop::current()->RunUntilIdle();
5353 // We now check to make sure the socket was added back to the pool.
5354 EXPECT_EQ(1, GetIdleSocketCountInSSLSocketPool(session.get()));
5356 // Now start the second transaction, which should reuse the previous socket.
5358 trans.reset(new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5360 rv = trans->Start(&request, callback.callback(), BoundNetLog());
5362 EXPECT_EQ(ERR_IO_PENDING, rv);
5363 EXPECT_EQ(OK, callback.WaitForResult());
5365 response = trans->GetResponseInfo();
5366 ASSERT_TRUE(response != NULL);
5367 ASSERT_TRUE(response->headers.get() != NULL);
5368 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
5370 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
5372 rv = ReadTransaction(trans.get(), &response_data);
5373 EXPECT_EQ(OK, rv);
5374 EXPECT_EQ("hello world", response_data);
5376 // Empty the current queue. This is necessary because idle sockets are
5377 // added to the connection pool asynchronously with a PostTask.
5378 base::MessageLoop::current()->RunUntilIdle();
5380 // We now check to make sure the socket was added back to the pool.
5381 EXPECT_EQ(1, GetIdleSocketCountInSSLSocketPool(session.get()));
5384 // Make sure that we recycle a socket after a zero-length response.
5385 // http://crbug.com/9880
5386 TEST_P(HttpNetworkTransactionTest, RecycleSocketAfterZeroContentLength) {
5387 HttpRequestInfo request;
5388 request.method = "GET";
5389 request.url = GURL(
5390 "http://www.example.org/csi?v=3&s=web&action=&"
5391 "tran=undefined&ei=mAXcSeegAo-SMurloeUN&"
5392 "e=17259,18167,19592,19773,19981,20133,20173,20233&"
5393 "rt=prt.2642,ol.2649,xjs.2951");
5394 request.load_flags = 0;
5396 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5398 scoped_ptr<HttpTransaction> trans(
5399 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5401 MockRead data_reads[] = {
5402 MockRead("HTTP/1.1 204 No Content\r\n"
5403 "Content-Length: 0\r\n"
5404 "Content-Type: text/html\r\n\r\n"),
5405 MockRead("junk"), // Should not be read!!
5406 MockRead(SYNCHRONOUS, OK),
5409 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
5410 session_deps_.socket_factory->AddSocketDataProvider(&data);
5412 TestCompletionCallback callback;
5414 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
5415 EXPECT_EQ(ERR_IO_PENDING, rv);
5417 rv = callback.WaitForResult();
5418 EXPECT_EQ(OK, rv);
5420 const HttpResponseInfo* response = trans->GetResponseInfo();
5421 ASSERT_TRUE(response != NULL);
5423 EXPECT_TRUE(response->headers.get() != NULL);
5424 std::string status_line = response->headers->GetStatusLine();
5425 EXPECT_EQ("HTTP/1.1 204 No Content", status_line);
5427 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
5429 std::string response_data;
5430 rv = ReadTransaction(trans.get(), &response_data);
5431 EXPECT_EQ(OK, rv);
5432 EXPECT_EQ("", response_data);
5434 // Empty the current queue. This is necessary because idle sockets are
5435 // added to the connection pool asynchronously with a PostTask.
5436 base::MessageLoop::current()->RunUntilIdle();
5438 // We now check to make sure the socket was added back to the pool.
5439 EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
5442 TEST_P(HttpNetworkTransactionTest, ResendRequestOnWriteBodyError) {
5443 ScopedVector<UploadElementReader> element_readers;
5444 element_readers.push_back(new UploadBytesElementReader("foo", 3));
5445 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
5447 HttpRequestInfo request[2];
5448 // Transaction 1: a GET request that succeeds. The socket is recycled
5449 // after use.
5450 request[0].method = "GET";
5451 request[0].url = GURL("http://www.google.com/");
5452 request[0].load_flags = 0;
5453 // Transaction 2: a POST request. Reuses the socket kept alive from
5454 // transaction 1. The first attempts fails when writing the POST data.
5455 // This causes the transaction to retry with a new socket. The second
5456 // attempt succeeds.
5457 request[1].method = "POST";
5458 request[1].url = GURL("http://www.google.com/login.cgi");
5459 request[1].upload_data_stream = &upload_data_stream;
5460 request[1].load_flags = 0;
5462 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5464 // The first socket is used for transaction 1 and the first attempt of
5465 // transaction 2.
5467 // The response of transaction 1.
5468 MockRead data_reads1[] = {
5469 MockRead("HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\n"),
5470 MockRead("hello world"),
5471 MockRead(SYNCHRONOUS, OK),
5473 // The mock write results of transaction 1 and the first attempt of
5474 // transaction 2.
5475 MockWrite data_writes1[] = {
5476 MockWrite(SYNCHRONOUS, 64), // GET
5477 MockWrite(SYNCHRONOUS, 93), // POST
5478 MockWrite(SYNCHRONOUS, ERR_CONNECTION_ABORTED), // POST data
5480 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
5481 data_writes1, arraysize(data_writes1));
5483 // The second socket is used for the second attempt of transaction 2.
5485 // The response of transaction 2.
5486 MockRead data_reads2[] = {
5487 MockRead("HTTP/1.1 200 OK\r\nContent-Length: 7\r\n\r\n"),
5488 MockRead("welcome"),
5489 MockRead(SYNCHRONOUS, OK),
5491 // The mock write results of the second attempt of transaction 2.
5492 MockWrite data_writes2[] = {
5493 MockWrite(SYNCHRONOUS, 93), // POST
5494 MockWrite(SYNCHRONOUS, 3), // POST data
5496 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
5497 data_writes2, arraysize(data_writes2));
5499 session_deps_.socket_factory->AddSocketDataProvider(&data1);
5500 session_deps_.socket_factory->AddSocketDataProvider(&data2);
5502 const char* const kExpectedResponseData[] = {
5503 "hello world", "welcome"
5506 for (int i = 0; i < 2; ++i) {
5507 scoped_ptr<HttpTransaction> trans(
5508 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5510 TestCompletionCallback callback;
5512 int rv = trans->Start(&request[i], callback.callback(), BoundNetLog());
5513 EXPECT_EQ(ERR_IO_PENDING, rv);
5515 rv = callback.WaitForResult();
5516 EXPECT_EQ(OK, rv);
5518 const HttpResponseInfo* response = trans->GetResponseInfo();
5519 ASSERT_TRUE(response != NULL);
5521 EXPECT_TRUE(response->headers.get() != NULL);
5522 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
5524 std::string response_data;
5525 rv = ReadTransaction(trans.get(), &response_data);
5526 EXPECT_EQ(OK, rv);
5527 EXPECT_EQ(kExpectedResponseData[i], response_data);
5531 // Test the request-challenge-retry sequence for basic auth when there is
5532 // an identity in the URL. The request should be sent as normal, but when
5533 // it fails the identity from the URL is used to answer the challenge.
5534 TEST_P(HttpNetworkTransactionTest, AuthIdentityInURL) {
5535 HttpRequestInfo request;
5536 request.method = "GET";
5537 request.url = GURL("http://foo:b@r@www.example.org/");
5538 request.load_flags = LOAD_NORMAL;
5540 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5541 scoped_ptr<HttpTransaction> trans(
5542 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5544 // The password contains an escaped character -- for this test to pass it
5545 // will need to be unescaped by HttpNetworkTransaction.
5546 EXPECT_EQ("b%40r", request.url.password());
5548 MockWrite data_writes1[] = {
5549 MockWrite(
5550 "GET / HTTP/1.1\r\n"
5551 "Host: www.example.org\r\n"
5552 "Connection: keep-alive\r\n\r\n"),
5555 MockRead data_reads1[] = {
5556 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
5557 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
5558 MockRead("Content-Length: 10\r\n\r\n"),
5559 MockRead(SYNCHRONOUS, ERR_FAILED),
5562 // After the challenge above, the transaction will be restarted using the
5563 // identity from the url (foo, b@r) to answer the challenge.
5564 MockWrite data_writes2[] = {
5565 MockWrite(
5566 "GET / HTTP/1.1\r\n"
5567 "Host: www.example.org\r\n"
5568 "Connection: keep-alive\r\n"
5569 "Authorization: Basic Zm9vOmJAcg==\r\n\r\n"),
5572 MockRead data_reads2[] = {
5573 MockRead("HTTP/1.0 200 OK\r\n"),
5574 MockRead("Content-Length: 100\r\n\r\n"),
5575 MockRead(SYNCHRONOUS, OK),
5578 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
5579 data_writes1, arraysize(data_writes1));
5580 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
5581 data_writes2, arraysize(data_writes2));
5582 session_deps_.socket_factory->AddSocketDataProvider(&data1);
5583 session_deps_.socket_factory->AddSocketDataProvider(&data2);
5585 TestCompletionCallback callback1;
5586 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
5587 EXPECT_EQ(ERR_IO_PENDING, rv);
5588 rv = callback1.WaitForResult();
5589 EXPECT_EQ(OK, rv);
5590 EXPECT_TRUE(trans->IsReadyToRestartForAuth());
5592 TestCompletionCallback callback2;
5593 rv = trans->RestartWithAuth(AuthCredentials(), callback2.callback());
5594 EXPECT_EQ(ERR_IO_PENDING, rv);
5595 rv = callback2.WaitForResult();
5596 EXPECT_EQ(OK, rv);
5597 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
5599 const HttpResponseInfo* response = trans->GetResponseInfo();
5600 ASSERT_TRUE(response != NULL);
5602 // There is no challenge info, since the identity in URL worked.
5603 EXPECT_TRUE(response->auth_challenge.get() == NULL);
5605 EXPECT_EQ(100, response->headers->GetContentLength());
5607 // Empty the current queue.
5608 base::MessageLoop::current()->RunUntilIdle();
5611 // Test the request-challenge-retry sequence for basic auth when there is an
5612 // incorrect identity in the URL. The identity from the URL should be used only
5613 // once.
5614 TEST_P(HttpNetworkTransactionTest, WrongAuthIdentityInURL) {
5615 HttpRequestInfo request;
5616 request.method = "GET";
5617 // Note: the URL has a username:password in it. The password "baz" is
5618 // wrong (should be "bar").
5619 request.url = GURL("http://foo:baz@www.example.org/");
5621 request.load_flags = LOAD_NORMAL;
5623 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5624 scoped_ptr<HttpTransaction> trans(
5625 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5627 MockWrite data_writes1[] = {
5628 MockWrite(
5629 "GET / HTTP/1.1\r\n"
5630 "Host: www.example.org\r\n"
5631 "Connection: keep-alive\r\n\r\n"),
5634 MockRead data_reads1[] = {
5635 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
5636 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
5637 MockRead("Content-Length: 10\r\n\r\n"),
5638 MockRead(SYNCHRONOUS, ERR_FAILED),
5641 // After the challenge above, the transaction will be restarted using the
5642 // identity from the url (foo, baz) to answer the challenge.
5643 MockWrite data_writes2[] = {
5644 MockWrite(
5645 "GET / HTTP/1.1\r\n"
5646 "Host: www.example.org\r\n"
5647 "Connection: keep-alive\r\n"
5648 "Authorization: Basic Zm9vOmJheg==\r\n\r\n"),
5651 MockRead data_reads2[] = {
5652 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
5653 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
5654 MockRead("Content-Length: 10\r\n\r\n"),
5655 MockRead(SYNCHRONOUS, ERR_FAILED),
5658 // After the challenge above, the transaction will be restarted using the
5659 // identity supplied by the user (foo, bar) to answer the challenge.
5660 MockWrite data_writes3[] = {
5661 MockWrite(
5662 "GET / HTTP/1.1\r\n"
5663 "Host: www.example.org\r\n"
5664 "Connection: keep-alive\r\n"
5665 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
5668 MockRead data_reads3[] = {
5669 MockRead("HTTP/1.0 200 OK\r\n"),
5670 MockRead("Content-Length: 100\r\n\r\n"),
5671 MockRead(SYNCHRONOUS, OK),
5674 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
5675 data_writes1, arraysize(data_writes1));
5676 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
5677 data_writes2, arraysize(data_writes2));
5678 StaticSocketDataProvider data3(data_reads3, arraysize(data_reads3),
5679 data_writes3, arraysize(data_writes3));
5680 session_deps_.socket_factory->AddSocketDataProvider(&data1);
5681 session_deps_.socket_factory->AddSocketDataProvider(&data2);
5682 session_deps_.socket_factory->AddSocketDataProvider(&data3);
5684 TestCompletionCallback callback1;
5686 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
5687 EXPECT_EQ(ERR_IO_PENDING, rv);
5689 rv = callback1.WaitForResult();
5690 EXPECT_EQ(OK, rv);
5692 EXPECT_TRUE(trans->IsReadyToRestartForAuth());
5693 TestCompletionCallback callback2;
5694 rv = trans->RestartWithAuth(AuthCredentials(), callback2.callback());
5695 EXPECT_EQ(ERR_IO_PENDING, rv);
5696 rv = callback2.WaitForResult();
5697 EXPECT_EQ(OK, rv);
5698 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
5700 const HttpResponseInfo* response = trans->GetResponseInfo();
5701 ASSERT_TRUE(response != NULL);
5702 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
5704 TestCompletionCallback callback3;
5705 rv = trans->RestartWithAuth(
5706 AuthCredentials(kFoo, kBar), callback3.callback());
5707 EXPECT_EQ(ERR_IO_PENDING, rv);
5708 rv = callback3.WaitForResult();
5709 EXPECT_EQ(OK, rv);
5710 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
5712 response = trans->GetResponseInfo();
5713 ASSERT_TRUE(response != NULL);
5715 // There is no challenge info, since the identity worked.
5716 EXPECT_TRUE(response->auth_challenge.get() == NULL);
5718 EXPECT_EQ(100, response->headers->GetContentLength());
5720 // Empty the current queue.
5721 base::MessageLoop::current()->RunUntilIdle();
5725 // Test the request-challenge-retry sequence for basic auth when there is a
5726 // correct identity in the URL, but its use is being suppressed. The identity
5727 // from the URL should never be used.
5728 TEST_P(HttpNetworkTransactionTest, AuthIdentityInURLSuppressed) {
5729 HttpRequestInfo request;
5730 request.method = "GET";
5731 request.url = GURL("http://foo:bar@www.example.org/");
5732 request.load_flags = LOAD_DO_NOT_USE_EMBEDDED_IDENTITY;
5734 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5735 scoped_ptr<HttpTransaction> trans(
5736 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5738 MockWrite data_writes1[] = {
5739 MockWrite(
5740 "GET / HTTP/1.1\r\n"
5741 "Host: www.example.org\r\n"
5742 "Connection: keep-alive\r\n\r\n"),
5745 MockRead data_reads1[] = {
5746 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
5747 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
5748 MockRead("Content-Length: 10\r\n\r\n"),
5749 MockRead(SYNCHRONOUS, ERR_FAILED),
5752 // After the challenge above, the transaction will be restarted using the
5753 // identity supplied by the user, not the one in the URL, to answer the
5754 // challenge.
5755 MockWrite data_writes3[] = {
5756 MockWrite(
5757 "GET / HTTP/1.1\r\n"
5758 "Host: www.example.org\r\n"
5759 "Connection: keep-alive\r\n"
5760 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
5763 MockRead data_reads3[] = {
5764 MockRead("HTTP/1.0 200 OK\r\n"),
5765 MockRead("Content-Length: 100\r\n\r\n"),
5766 MockRead(SYNCHRONOUS, OK),
5769 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
5770 data_writes1, arraysize(data_writes1));
5771 StaticSocketDataProvider data3(data_reads3, arraysize(data_reads3),
5772 data_writes3, arraysize(data_writes3));
5773 session_deps_.socket_factory->AddSocketDataProvider(&data1);
5774 session_deps_.socket_factory->AddSocketDataProvider(&data3);
5776 TestCompletionCallback callback1;
5777 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
5778 EXPECT_EQ(ERR_IO_PENDING, rv);
5779 rv = callback1.WaitForResult();
5780 EXPECT_EQ(OK, rv);
5781 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
5783 const HttpResponseInfo* response = trans->GetResponseInfo();
5784 ASSERT_TRUE(response != NULL);
5785 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
5787 TestCompletionCallback callback3;
5788 rv = trans->RestartWithAuth(
5789 AuthCredentials(kFoo, kBar), callback3.callback());
5790 EXPECT_EQ(ERR_IO_PENDING, rv);
5791 rv = callback3.WaitForResult();
5792 EXPECT_EQ(OK, rv);
5793 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
5795 response = trans->GetResponseInfo();
5796 ASSERT_TRUE(response != NULL);
5798 // There is no challenge info, since the identity worked.
5799 EXPECT_TRUE(response->auth_challenge.get() == NULL);
5800 EXPECT_EQ(100, response->headers->GetContentLength());
5802 // Empty the current queue.
5803 base::MessageLoop::current()->RunUntilIdle();
5806 // Test that previously tried username/passwords for a realm get re-used.
5807 TEST_P(HttpNetworkTransactionTest, BasicAuthCacheAndPreauth) {
5808 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5810 // Transaction 1: authenticate (foo, bar) on MyRealm1
5812 HttpRequestInfo request;
5813 request.method = "GET";
5814 request.url = GURL("http://www.example.org/x/y/z");
5815 request.load_flags = 0;
5817 scoped_ptr<HttpTransaction> trans(
5818 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5820 MockWrite data_writes1[] = {
5821 MockWrite(
5822 "GET /x/y/z HTTP/1.1\r\n"
5823 "Host: www.example.org\r\n"
5824 "Connection: keep-alive\r\n\r\n"),
5827 MockRead data_reads1[] = {
5828 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
5829 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
5830 MockRead("Content-Length: 10000\r\n\r\n"),
5831 MockRead(SYNCHRONOUS, ERR_FAILED),
5834 // Resend with authorization (username=foo, password=bar)
5835 MockWrite data_writes2[] = {
5836 MockWrite(
5837 "GET /x/y/z HTTP/1.1\r\n"
5838 "Host: www.example.org\r\n"
5839 "Connection: keep-alive\r\n"
5840 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
5843 // Sever accepts the authorization.
5844 MockRead data_reads2[] = {
5845 MockRead("HTTP/1.0 200 OK\r\n"),
5846 MockRead("Content-Length: 100\r\n\r\n"),
5847 MockRead(SYNCHRONOUS, OK),
5850 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
5851 data_writes1, arraysize(data_writes1));
5852 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
5853 data_writes2, arraysize(data_writes2));
5854 session_deps_.socket_factory->AddSocketDataProvider(&data1);
5855 session_deps_.socket_factory->AddSocketDataProvider(&data2);
5857 TestCompletionCallback callback1;
5859 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
5860 EXPECT_EQ(ERR_IO_PENDING, rv);
5862 rv = callback1.WaitForResult();
5863 EXPECT_EQ(OK, rv);
5865 const HttpResponseInfo* response = trans->GetResponseInfo();
5866 ASSERT_TRUE(response != NULL);
5867 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
5869 TestCompletionCallback callback2;
5871 rv = trans->RestartWithAuth(
5872 AuthCredentials(kFoo, kBar), callback2.callback());
5873 EXPECT_EQ(ERR_IO_PENDING, rv);
5875 rv = callback2.WaitForResult();
5876 EXPECT_EQ(OK, rv);
5878 response = trans->GetResponseInfo();
5879 ASSERT_TRUE(response != NULL);
5880 EXPECT_TRUE(response->auth_challenge.get() == NULL);
5881 EXPECT_EQ(100, response->headers->GetContentLength());
5884 // ------------------------------------------------------------------------
5886 // Transaction 2: authenticate (foo2, bar2) on MyRealm2
5888 HttpRequestInfo request;
5889 request.method = "GET";
5890 // Note that Transaction 1 was at /x/y/z, so this is in the same
5891 // protection space as MyRealm1.
5892 request.url = GURL("http://www.example.org/x/y/a/b");
5893 request.load_flags = 0;
5895 scoped_ptr<HttpTransaction> trans(
5896 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5898 MockWrite data_writes1[] = {
5899 MockWrite(
5900 "GET /x/y/a/b HTTP/1.1\r\n"
5901 "Host: www.example.org\r\n"
5902 "Connection: keep-alive\r\n"
5903 // Send preemptive authorization for MyRealm1
5904 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
5907 // The server didn't like the preemptive authorization, and
5908 // challenges us for a different realm (MyRealm2).
5909 MockRead data_reads1[] = {
5910 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
5911 MockRead("WWW-Authenticate: Basic realm=\"MyRealm2\"\r\n"),
5912 MockRead("Content-Length: 10000\r\n\r\n"),
5913 MockRead(SYNCHRONOUS, ERR_FAILED),
5916 // Resend with authorization for MyRealm2 (username=foo2, password=bar2)
5917 MockWrite data_writes2[] = {
5918 MockWrite(
5919 "GET /x/y/a/b HTTP/1.1\r\n"
5920 "Host: www.example.org\r\n"
5921 "Connection: keep-alive\r\n"
5922 "Authorization: Basic Zm9vMjpiYXIy\r\n\r\n"),
5925 // Sever accepts the authorization.
5926 MockRead data_reads2[] = {
5927 MockRead("HTTP/1.0 200 OK\r\n"),
5928 MockRead("Content-Length: 100\r\n\r\n"),
5929 MockRead(SYNCHRONOUS, OK),
5932 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
5933 data_writes1, arraysize(data_writes1));
5934 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
5935 data_writes2, arraysize(data_writes2));
5936 session_deps_.socket_factory->AddSocketDataProvider(&data1);
5937 session_deps_.socket_factory->AddSocketDataProvider(&data2);
5939 TestCompletionCallback callback1;
5941 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
5942 EXPECT_EQ(ERR_IO_PENDING, rv);
5944 rv = callback1.WaitForResult();
5945 EXPECT_EQ(OK, rv);
5947 const HttpResponseInfo* response = trans->GetResponseInfo();
5948 ASSERT_TRUE(response != NULL);
5949 ASSERT_TRUE(response->auth_challenge.get());
5950 EXPECT_FALSE(response->auth_challenge->is_proxy);
5951 EXPECT_EQ("www.example.org:80",
5952 response->auth_challenge->challenger.ToString());
5953 EXPECT_EQ("MyRealm2", response->auth_challenge->realm);
5954 EXPECT_EQ("basic", response->auth_challenge->scheme);
5956 TestCompletionCallback callback2;
5958 rv = trans->RestartWithAuth(
5959 AuthCredentials(kFoo2, kBar2), callback2.callback());
5960 EXPECT_EQ(ERR_IO_PENDING, rv);
5962 rv = callback2.WaitForResult();
5963 EXPECT_EQ(OK, rv);
5965 response = trans->GetResponseInfo();
5966 ASSERT_TRUE(response != NULL);
5967 EXPECT_TRUE(response->auth_challenge.get() == NULL);
5968 EXPECT_EQ(100, response->headers->GetContentLength());
5971 // ------------------------------------------------------------------------
5973 // Transaction 3: Resend a request in MyRealm's protection space --
5974 // succeed with preemptive authorization.
5976 HttpRequestInfo request;
5977 request.method = "GET";
5978 request.url = GURL("http://www.example.org/x/y/z2");
5979 request.load_flags = 0;
5981 scoped_ptr<HttpTransaction> trans(
5982 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5984 MockWrite data_writes1[] = {
5985 MockWrite(
5986 "GET /x/y/z2 HTTP/1.1\r\n"
5987 "Host: www.example.org\r\n"
5988 "Connection: keep-alive\r\n"
5989 // The authorization for MyRealm1 gets sent preemptively
5990 // (since the url is in the same protection space)
5991 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
5994 // Sever accepts the preemptive authorization
5995 MockRead data_reads1[] = {
5996 MockRead("HTTP/1.0 200 OK\r\n"),
5997 MockRead("Content-Length: 100\r\n\r\n"),
5998 MockRead(SYNCHRONOUS, OK),
6001 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
6002 data_writes1, arraysize(data_writes1));
6003 session_deps_.socket_factory->AddSocketDataProvider(&data1);
6005 TestCompletionCallback callback1;
6007 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
6008 EXPECT_EQ(ERR_IO_PENDING, rv);
6010 rv = callback1.WaitForResult();
6011 EXPECT_EQ(OK, rv);
6013 const HttpResponseInfo* response = trans->GetResponseInfo();
6014 ASSERT_TRUE(response != NULL);
6016 EXPECT_TRUE(response->auth_challenge.get() == NULL);
6017 EXPECT_EQ(100, response->headers->GetContentLength());
6020 // ------------------------------------------------------------------------
6022 // Transaction 4: request another URL in MyRealm (however the
6023 // url is not known to belong to the protection space, so no pre-auth).
6025 HttpRequestInfo request;
6026 request.method = "GET";
6027 request.url = GURL("http://www.example.org/x/1");
6028 request.load_flags = 0;
6030 scoped_ptr<HttpTransaction> trans(
6031 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6033 MockWrite data_writes1[] = {
6034 MockWrite(
6035 "GET /x/1 HTTP/1.1\r\n"
6036 "Host: www.example.org\r\n"
6037 "Connection: keep-alive\r\n\r\n"),
6040 MockRead data_reads1[] = {
6041 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
6042 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
6043 MockRead("Content-Length: 10000\r\n\r\n"),
6044 MockRead(SYNCHRONOUS, ERR_FAILED),
6047 // Resend with authorization from MyRealm's cache.
6048 MockWrite data_writes2[] = {
6049 MockWrite(
6050 "GET /x/1 HTTP/1.1\r\n"
6051 "Host: www.example.org\r\n"
6052 "Connection: keep-alive\r\n"
6053 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
6056 // Sever accepts the authorization.
6057 MockRead data_reads2[] = {
6058 MockRead("HTTP/1.0 200 OK\r\n"),
6059 MockRead("Content-Length: 100\r\n\r\n"),
6060 MockRead(SYNCHRONOUS, OK),
6063 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
6064 data_writes1, arraysize(data_writes1));
6065 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
6066 data_writes2, arraysize(data_writes2));
6067 session_deps_.socket_factory->AddSocketDataProvider(&data1);
6068 session_deps_.socket_factory->AddSocketDataProvider(&data2);
6070 TestCompletionCallback callback1;
6072 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
6073 EXPECT_EQ(ERR_IO_PENDING, rv);
6075 rv = callback1.WaitForResult();
6076 EXPECT_EQ(OK, rv);
6078 EXPECT_TRUE(trans->IsReadyToRestartForAuth());
6079 TestCompletionCallback callback2;
6080 rv = trans->RestartWithAuth(AuthCredentials(), callback2.callback());
6081 EXPECT_EQ(ERR_IO_PENDING, rv);
6082 rv = callback2.WaitForResult();
6083 EXPECT_EQ(OK, rv);
6084 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
6086 const HttpResponseInfo* response = trans->GetResponseInfo();
6087 ASSERT_TRUE(response != NULL);
6088 EXPECT_TRUE(response->auth_challenge.get() == NULL);
6089 EXPECT_EQ(100, response->headers->GetContentLength());
6092 // ------------------------------------------------------------------------
6094 // Transaction 5: request a URL in MyRealm, but the server rejects the
6095 // cached identity. Should invalidate and re-prompt.
6097 HttpRequestInfo request;
6098 request.method = "GET";
6099 request.url = GURL("http://www.example.org/p/q/t");
6100 request.load_flags = 0;
6102 scoped_ptr<HttpTransaction> trans(
6103 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6105 MockWrite data_writes1[] = {
6106 MockWrite(
6107 "GET /p/q/t HTTP/1.1\r\n"
6108 "Host: www.example.org\r\n"
6109 "Connection: keep-alive\r\n\r\n"),
6112 MockRead data_reads1[] = {
6113 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
6114 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
6115 MockRead("Content-Length: 10000\r\n\r\n"),
6116 MockRead(SYNCHRONOUS, ERR_FAILED),
6119 // Resend with authorization from cache for MyRealm.
6120 MockWrite data_writes2[] = {
6121 MockWrite(
6122 "GET /p/q/t HTTP/1.1\r\n"
6123 "Host: www.example.org\r\n"
6124 "Connection: keep-alive\r\n"
6125 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
6128 // Sever rejects the authorization.
6129 MockRead data_reads2[] = {
6130 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
6131 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
6132 MockRead("Content-Length: 10000\r\n\r\n"),
6133 MockRead(SYNCHRONOUS, ERR_FAILED),
6136 // At this point we should prompt for new credentials for MyRealm.
6137 // Restart with username=foo3, password=foo4.
6138 MockWrite data_writes3[] = {
6139 MockWrite(
6140 "GET /p/q/t HTTP/1.1\r\n"
6141 "Host: www.example.org\r\n"
6142 "Connection: keep-alive\r\n"
6143 "Authorization: Basic Zm9vMzpiYXIz\r\n\r\n"),
6146 // Sever accepts the authorization.
6147 MockRead data_reads3[] = {
6148 MockRead("HTTP/1.0 200 OK\r\n"),
6149 MockRead("Content-Length: 100\r\n\r\n"),
6150 MockRead(SYNCHRONOUS, OK),
6153 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
6154 data_writes1, arraysize(data_writes1));
6155 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
6156 data_writes2, arraysize(data_writes2));
6157 StaticSocketDataProvider data3(data_reads3, arraysize(data_reads3),
6158 data_writes3, arraysize(data_writes3));
6159 session_deps_.socket_factory->AddSocketDataProvider(&data1);
6160 session_deps_.socket_factory->AddSocketDataProvider(&data2);
6161 session_deps_.socket_factory->AddSocketDataProvider(&data3);
6163 TestCompletionCallback callback1;
6165 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
6166 EXPECT_EQ(ERR_IO_PENDING, rv);
6168 rv = callback1.WaitForResult();
6169 EXPECT_EQ(OK, rv);
6171 EXPECT_TRUE(trans->IsReadyToRestartForAuth());
6172 TestCompletionCallback callback2;
6173 rv = trans->RestartWithAuth(AuthCredentials(), callback2.callback());
6174 EXPECT_EQ(ERR_IO_PENDING, rv);
6175 rv = callback2.WaitForResult();
6176 EXPECT_EQ(OK, rv);
6177 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
6179 const HttpResponseInfo* response = trans->GetResponseInfo();
6180 ASSERT_TRUE(response != NULL);
6181 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
6183 TestCompletionCallback callback3;
6185 rv = trans->RestartWithAuth(
6186 AuthCredentials(kFoo3, kBar3), callback3.callback());
6187 EXPECT_EQ(ERR_IO_PENDING, rv);
6189 rv = callback3.WaitForResult();
6190 EXPECT_EQ(OK, rv);
6192 response = trans->GetResponseInfo();
6193 ASSERT_TRUE(response != NULL);
6194 EXPECT_TRUE(response->auth_challenge.get() == NULL);
6195 EXPECT_EQ(100, response->headers->GetContentLength());
6199 // Tests that nonce count increments when multiple auth attempts
6200 // are started with the same nonce.
6201 TEST_P(HttpNetworkTransactionTest, DigestPreAuthNonceCount) {
6202 HttpAuthHandlerDigest::Factory* digest_factory =
6203 new HttpAuthHandlerDigest::Factory();
6204 HttpAuthHandlerDigest::FixedNonceGenerator* nonce_generator =
6205 new HttpAuthHandlerDigest::FixedNonceGenerator("0123456789abcdef");
6206 digest_factory->set_nonce_generator(nonce_generator);
6207 session_deps_.http_auth_handler_factory.reset(digest_factory);
6208 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6210 // Transaction 1: authenticate (foo, bar) on MyRealm1
6212 HttpRequestInfo request;
6213 request.method = "GET";
6214 request.url = GURL("http://www.example.org/x/y/z");
6215 request.load_flags = 0;
6217 scoped_ptr<HttpTransaction> trans(
6218 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6220 MockWrite data_writes1[] = {
6221 MockWrite(
6222 "GET /x/y/z HTTP/1.1\r\n"
6223 "Host: www.example.org\r\n"
6224 "Connection: keep-alive\r\n\r\n"),
6227 MockRead data_reads1[] = {
6228 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
6229 MockRead("WWW-Authenticate: Digest realm=\"digestive\", nonce=\"OU812\", "
6230 "algorithm=MD5, qop=\"auth\"\r\n\r\n"),
6231 MockRead(SYNCHRONOUS, OK),
6234 // Resend with authorization (username=foo, password=bar)
6235 MockWrite data_writes2[] = {
6236 MockWrite(
6237 "GET /x/y/z HTTP/1.1\r\n"
6238 "Host: www.example.org\r\n"
6239 "Connection: keep-alive\r\n"
6240 "Authorization: Digest username=\"foo\", realm=\"digestive\", "
6241 "nonce=\"OU812\", uri=\"/x/y/z\", algorithm=MD5, "
6242 "response=\"03ffbcd30add722589c1de345d7a927f\", qop=auth, "
6243 "nc=00000001, cnonce=\"0123456789abcdef\"\r\n\r\n"),
6246 // Sever accepts the authorization.
6247 MockRead data_reads2[] = {
6248 MockRead("HTTP/1.0 200 OK\r\n"),
6249 MockRead(SYNCHRONOUS, OK),
6252 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
6253 data_writes1, arraysize(data_writes1));
6254 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
6255 data_writes2, arraysize(data_writes2));
6256 session_deps_.socket_factory->AddSocketDataProvider(&data1);
6257 session_deps_.socket_factory->AddSocketDataProvider(&data2);
6259 TestCompletionCallback callback1;
6261 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
6262 EXPECT_EQ(ERR_IO_PENDING, rv);
6264 rv = callback1.WaitForResult();
6265 EXPECT_EQ(OK, rv);
6267 const HttpResponseInfo* response = trans->GetResponseInfo();
6268 ASSERT_TRUE(response != NULL);
6269 EXPECT_TRUE(CheckDigestServerAuth(response->auth_challenge.get()));
6271 TestCompletionCallback callback2;
6273 rv = trans->RestartWithAuth(
6274 AuthCredentials(kFoo, kBar), callback2.callback());
6275 EXPECT_EQ(ERR_IO_PENDING, rv);
6277 rv = callback2.WaitForResult();
6278 EXPECT_EQ(OK, rv);
6280 response = trans->GetResponseInfo();
6281 ASSERT_TRUE(response != NULL);
6282 EXPECT_TRUE(response->auth_challenge.get() == NULL);
6285 // ------------------------------------------------------------------------
6287 // Transaction 2: Request another resource in digestive's protection space.
6288 // This will preemptively add an Authorization header which should have an
6289 // "nc" value of 2 (as compared to 1 in the first use.
6291 HttpRequestInfo request;
6292 request.method = "GET";
6293 // Note that Transaction 1 was at /x/y/z, so this is in the same
6294 // protection space as digest.
6295 request.url = GURL("http://www.example.org/x/y/a/b");
6296 request.load_flags = 0;
6298 scoped_ptr<HttpTransaction> trans(
6299 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6301 MockWrite data_writes1[] = {
6302 MockWrite(
6303 "GET /x/y/a/b HTTP/1.1\r\n"
6304 "Host: www.example.org\r\n"
6305 "Connection: keep-alive\r\n"
6306 "Authorization: Digest username=\"foo\", realm=\"digestive\", "
6307 "nonce=\"OU812\", uri=\"/x/y/a/b\", algorithm=MD5, "
6308 "response=\"d6f9a2c07d1c5df7b89379dca1269b35\", qop=auth, "
6309 "nc=00000002, cnonce=\"0123456789abcdef\"\r\n\r\n"),
6312 // Sever accepts the authorization.
6313 MockRead data_reads1[] = {
6314 MockRead("HTTP/1.0 200 OK\r\n"),
6315 MockRead("Content-Length: 100\r\n\r\n"),
6316 MockRead(SYNCHRONOUS, OK),
6319 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
6320 data_writes1, arraysize(data_writes1));
6321 session_deps_.socket_factory->AddSocketDataProvider(&data1);
6323 TestCompletionCallback callback1;
6325 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
6326 EXPECT_EQ(ERR_IO_PENDING, rv);
6328 rv = callback1.WaitForResult();
6329 EXPECT_EQ(OK, rv);
6331 const HttpResponseInfo* response = trans->GetResponseInfo();
6332 ASSERT_TRUE(response != NULL);
6333 EXPECT_TRUE(response->auth_challenge.get() == NULL);
6337 // Test the ResetStateForRestart() private method.
6338 TEST_P(HttpNetworkTransactionTest, ResetStateForRestart) {
6339 // Create a transaction (the dependencies aren't important).
6340 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6341 scoped_ptr<HttpNetworkTransaction> trans(
6342 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6344 // Setup some state (which we expect ResetStateForRestart() will clear).
6345 trans->read_buf_ = new IOBuffer(15);
6346 trans->read_buf_len_ = 15;
6347 trans->request_headers_.SetHeader("Authorization", "NTLM");
6349 // Setup state in response_
6350 HttpResponseInfo* response = &trans->response_;
6351 response->auth_challenge = new AuthChallengeInfo();
6352 response->ssl_info.cert_status = static_cast<CertStatus>(-1); // Nonsensical.
6353 response->response_time = base::Time::Now();
6354 response->was_cached = true; // (Wouldn't ever actually be true...)
6356 { // Setup state for response_.vary_data
6357 HttpRequestInfo request;
6358 std::string temp("HTTP/1.1 200 OK\nVary: foo, bar\n\n");
6359 std::replace(temp.begin(), temp.end(), '\n', '\0');
6360 scoped_refptr<HttpResponseHeaders> headers(new HttpResponseHeaders(temp));
6361 request.extra_headers.SetHeader("Foo", "1");
6362 request.extra_headers.SetHeader("bar", "23");
6363 EXPECT_TRUE(response->vary_data.Init(request, *headers.get()));
6366 // Cause the above state to be reset.
6367 trans->ResetStateForRestart();
6369 // Verify that the state that needed to be reset, has been reset.
6370 EXPECT_TRUE(trans->read_buf_.get() == NULL);
6371 EXPECT_EQ(0, trans->read_buf_len_);
6372 EXPECT_TRUE(trans->request_headers_.IsEmpty());
6373 EXPECT_TRUE(response->auth_challenge.get() == NULL);
6374 EXPECT_TRUE(response->headers.get() == NULL);
6375 EXPECT_FALSE(response->was_cached);
6376 EXPECT_EQ(0U, response->ssl_info.cert_status);
6377 EXPECT_FALSE(response->vary_data.is_valid());
6380 // Test HTTPS connections to a site with a bad certificate
6381 TEST_P(HttpNetworkTransactionTest, HTTPSBadCertificate) {
6382 HttpRequestInfo request;
6383 request.method = "GET";
6384 request.url = GURL("https://www.example.org/");
6385 request.load_flags = 0;
6387 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6388 scoped_ptr<HttpTransaction> trans(
6389 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6391 MockWrite data_writes[] = {
6392 MockWrite(
6393 "GET / HTTP/1.1\r\n"
6394 "Host: www.example.org\r\n"
6395 "Connection: keep-alive\r\n\r\n"),
6398 MockRead data_reads[] = {
6399 MockRead("HTTP/1.0 200 OK\r\n"),
6400 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
6401 MockRead("Content-Length: 100\r\n\r\n"),
6402 MockRead(SYNCHRONOUS, OK),
6405 StaticSocketDataProvider ssl_bad_certificate;
6406 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
6407 data_writes, arraysize(data_writes));
6408 SSLSocketDataProvider ssl_bad(ASYNC, ERR_CERT_AUTHORITY_INVALID);
6409 SSLSocketDataProvider ssl(ASYNC, OK);
6411 session_deps_.socket_factory->AddSocketDataProvider(&ssl_bad_certificate);
6412 session_deps_.socket_factory->AddSocketDataProvider(&data);
6413 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_bad);
6414 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
6416 TestCompletionCallback callback;
6418 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6419 EXPECT_EQ(ERR_IO_PENDING, rv);
6421 rv = callback.WaitForResult();
6422 EXPECT_EQ(ERR_CERT_AUTHORITY_INVALID, rv);
6424 rv = trans->RestartIgnoringLastError(callback.callback());
6425 EXPECT_EQ(ERR_IO_PENDING, rv);
6427 rv = callback.WaitForResult();
6428 EXPECT_EQ(OK, rv);
6430 const HttpResponseInfo* response = trans->GetResponseInfo();
6432 ASSERT_TRUE(response != NULL);
6433 EXPECT_EQ(100, response->headers->GetContentLength());
6436 // Test HTTPS connections to a site with a bad certificate, going through a
6437 // proxy
6438 TEST_P(HttpNetworkTransactionTest, HTTPSBadCertificateViaProxy) {
6439 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
6441 HttpRequestInfo request;
6442 request.method = "GET";
6443 request.url = GURL("https://www.example.org/");
6444 request.load_flags = 0;
6446 MockWrite proxy_writes[] = {
6447 MockWrite(
6448 "CONNECT www.example.org:443 HTTP/1.1\r\n"
6449 "Host: www.example.org\r\n"
6450 "Proxy-Connection: keep-alive\r\n\r\n"),
6453 MockRead proxy_reads[] = {
6454 MockRead("HTTP/1.0 200 Connected\r\n\r\n"),
6455 MockRead(SYNCHRONOUS, OK)
6458 MockWrite data_writes[] = {
6459 MockWrite(
6460 "CONNECT www.example.org:443 HTTP/1.1\r\n"
6461 "Host: www.example.org\r\n"
6462 "Proxy-Connection: keep-alive\r\n\r\n"),
6463 MockWrite(
6464 "GET / HTTP/1.1\r\n"
6465 "Host: www.example.org\r\n"
6466 "Connection: keep-alive\r\n\r\n"),
6469 MockRead data_reads[] = {
6470 MockRead("HTTP/1.0 200 Connected\r\n\r\n"),
6471 MockRead("HTTP/1.0 200 OK\r\n"),
6472 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
6473 MockRead("Content-Length: 100\r\n\r\n"),
6474 MockRead(SYNCHRONOUS, OK),
6477 StaticSocketDataProvider ssl_bad_certificate(
6478 proxy_reads, arraysize(proxy_reads),
6479 proxy_writes, arraysize(proxy_writes));
6480 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
6481 data_writes, arraysize(data_writes));
6482 SSLSocketDataProvider ssl_bad(ASYNC, ERR_CERT_AUTHORITY_INVALID);
6483 SSLSocketDataProvider ssl(ASYNC, OK);
6485 session_deps_.socket_factory->AddSocketDataProvider(&ssl_bad_certificate);
6486 session_deps_.socket_factory->AddSocketDataProvider(&data);
6487 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_bad);
6488 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
6490 TestCompletionCallback callback;
6492 for (int i = 0; i < 2; i++) {
6493 session_deps_.socket_factory->ResetNextMockIndexes();
6495 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6496 scoped_ptr<HttpTransaction> trans(
6497 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6499 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6500 EXPECT_EQ(ERR_IO_PENDING, rv);
6502 rv = callback.WaitForResult();
6503 EXPECT_EQ(ERR_CERT_AUTHORITY_INVALID, rv);
6505 rv = trans->RestartIgnoringLastError(callback.callback());
6506 EXPECT_EQ(ERR_IO_PENDING, rv);
6508 rv = callback.WaitForResult();
6509 EXPECT_EQ(OK, rv);
6511 const HttpResponseInfo* response = trans->GetResponseInfo();
6513 ASSERT_TRUE(response != NULL);
6514 EXPECT_EQ(100, response->headers->GetContentLength());
6519 // Test HTTPS connections to a site, going through an HTTPS proxy
6520 TEST_P(HttpNetworkTransactionTest, HTTPSViaHttpsProxy) {
6521 session_deps_.proxy_service.reset(
6522 ProxyService::CreateFixedFromPacResult("HTTPS proxy:70"));
6523 TestNetLog net_log;
6524 session_deps_.net_log = &net_log;
6526 HttpRequestInfo request;
6527 request.method = "GET";
6528 request.url = GURL("https://www.example.org/");
6529 request.load_flags = 0;
6531 MockWrite data_writes[] = {
6532 MockWrite(
6533 "CONNECT www.example.org:443 HTTP/1.1\r\n"
6534 "Host: www.example.org\r\n"
6535 "Proxy-Connection: keep-alive\r\n\r\n"),
6536 MockWrite(
6537 "GET / HTTP/1.1\r\n"
6538 "Host: www.example.org\r\n"
6539 "Connection: keep-alive\r\n\r\n"),
6542 MockRead data_reads[] = {
6543 MockRead("HTTP/1.0 200 Connected\r\n\r\n"),
6544 MockRead("HTTP/1.1 200 OK\r\n"),
6545 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
6546 MockRead("Content-Length: 100\r\n\r\n"),
6547 MockRead(SYNCHRONOUS, OK),
6550 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
6551 data_writes, arraysize(data_writes));
6552 SSLSocketDataProvider proxy_ssl(ASYNC, OK); // SSL to the proxy
6553 SSLSocketDataProvider tunnel_ssl(ASYNC, OK); // SSL through the tunnel
6555 session_deps_.socket_factory->AddSocketDataProvider(&data);
6556 session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy_ssl);
6557 session_deps_.socket_factory->AddSSLSocketDataProvider(&tunnel_ssl);
6559 TestCompletionCallback callback;
6561 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6562 scoped_ptr<HttpTransaction> trans(
6563 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6565 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6566 EXPECT_EQ(ERR_IO_PENDING, rv);
6568 rv = callback.WaitForResult();
6569 EXPECT_EQ(OK, rv);
6570 const HttpResponseInfo* response = trans->GetResponseInfo();
6572 ASSERT_TRUE(response != NULL);
6574 EXPECT_TRUE(response->headers->IsKeepAlive());
6575 EXPECT_EQ(200, response->headers->response_code());
6576 EXPECT_EQ(100, response->headers->GetContentLength());
6577 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
6579 LoadTimingInfo load_timing_info;
6580 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
6581 TestLoadTimingNotReusedWithPac(load_timing_info,
6582 CONNECT_TIMING_HAS_SSL_TIMES);
6585 // Test an HTTPS Proxy's ability to redirect a CONNECT request
6586 TEST_P(HttpNetworkTransactionTest, RedirectOfHttpsConnectViaHttpsProxy) {
6587 session_deps_.proxy_service.reset(
6588 ProxyService::CreateFixedFromPacResult("HTTPS proxy:70"));
6589 TestNetLog net_log;
6590 session_deps_.net_log = &net_log;
6592 HttpRequestInfo request;
6593 request.method = "GET";
6594 request.url = GURL("https://www.example.org/");
6595 request.load_flags = 0;
6597 MockWrite data_writes[] = {
6598 MockWrite(
6599 "CONNECT www.example.org:443 HTTP/1.1\r\n"
6600 "Host: www.example.org\r\n"
6601 "Proxy-Connection: keep-alive\r\n\r\n"),
6604 MockRead data_reads[] = {
6605 MockRead("HTTP/1.1 302 Redirect\r\n"),
6606 MockRead("Location: http://login.example.com/\r\n"),
6607 MockRead("Content-Length: 0\r\n\r\n"),
6608 MockRead(SYNCHRONOUS, OK),
6611 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
6612 data_writes, arraysize(data_writes));
6613 SSLSocketDataProvider proxy_ssl(ASYNC, OK); // SSL to the proxy
6615 session_deps_.socket_factory->AddSocketDataProvider(&data);
6616 session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy_ssl);
6618 TestCompletionCallback callback;
6620 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6621 scoped_ptr<HttpTransaction> trans(
6622 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6624 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6625 EXPECT_EQ(ERR_IO_PENDING, rv);
6627 rv = callback.WaitForResult();
6628 EXPECT_EQ(OK, rv);
6629 const HttpResponseInfo* response = trans->GetResponseInfo();
6631 ASSERT_TRUE(response != NULL);
6633 EXPECT_EQ(302, response->headers->response_code());
6634 std::string url;
6635 EXPECT_TRUE(response->headers->IsRedirect(&url));
6636 EXPECT_EQ("http://login.example.com/", url);
6638 // In the case of redirects from proxies, HttpNetworkTransaction returns
6639 // timing for the proxy connection instead of the connection to the host,
6640 // and no send / receive times.
6641 // See HttpNetworkTransaction::OnHttpsProxyTunnelResponse.
6642 LoadTimingInfo load_timing_info;
6643 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
6645 EXPECT_FALSE(load_timing_info.socket_reused);
6646 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
6648 EXPECT_FALSE(load_timing_info.proxy_resolve_start.is_null());
6649 EXPECT_LE(load_timing_info.proxy_resolve_start,
6650 load_timing_info.proxy_resolve_end);
6651 EXPECT_LE(load_timing_info.proxy_resolve_end,
6652 load_timing_info.connect_timing.connect_start);
6653 ExpectConnectTimingHasTimes(
6654 load_timing_info.connect_timing,
6655 CONNECT_TIMING_HAS_DNS_TIMES | CONNECT_TIMING_HAS_SSL_TIMES);
6657 EXPECT_TRUE(load_timing_info.send_start.is_null());
6658 EXPECT_TRUE(load_timing_info.send_end.is_null());
6659 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
6662 // Test an HTTPS (SPDY) Proxy's ability to redirect a CONNECT request
6663 TEST_P(HttpNetworkTransactionTest, RedirectOfHttpsConnectViaSpdyProxy) {
6664 session_deps_.proxy_service.reset(
6665 ProxyService::CreateFixed("https://proxy:70"));
6667 HttpRequestInfo request;
6668 request.method = "GET";
6669 request.url = GURL("https://www.example.org/");
6670 request.load_flags = 0;
6672 scoped_ptr<SpdyFrame> conn(spdy_util_.ConstructSpdyConnect(
6673 NULL, 0, 1, LOWEST, HostPortPair("www.example.org", 443)));
6674 scoped_ptr<SpdyFrame> goaway(
6675 spdy_util_.ConstructSpdyRstStream(1, RST_STREAM_CANCEL));
6676 MockWrite data_writes[] = {
6677 CreateMockWrite(*conn.get(), 0, SYNCHRONOUS),
6678 CreateMockWrite(*goaway.get(), 2, SYNCHRONOUS),
6681 static const char* const kExtraHeaders[] = {
6682 "location",
6683 "http://login.example.com/",
6685 scoped_ptr<SpdyFrame> resp(
6686 spdy_util_.ConstructSpdySynReplyError("302 Redirect", kExtraHeaders,
6687 arraysize(kExtraHeaders)/2, 1));
6688 MockRead data_reads[] = {
6689 CreateMockRead(*resp.get(), 1), MockRead(ASYNC, 0, 3), // EOF
6692 SequencedSocketData data(data_reads, arraysize(data_reads), data_writes,
6693 arraysize(data_writes));
6694 SSLSocketDataProvider proxy_ssl(ASYNC, OK); // SSL to the proxy
6695 proxy_ssl.SetNextProto(GetParam());
6697 session_deps_.socket_factory->AddSocketDataProvider(&data);
6698 session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy_ssl);
6700 TestCompletionCallback callback;
6702 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6703 scoped_ptr<HttpTransaction> trans(
6704 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6706 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6707 EXPECT_EQ(ERR_IO_PENDING, rv);
6709 rv = callback.WaitForResult();
6710 EXPECT_EQ(OK, rv);
6711 const HttpResponseInfo* response = trans->GetResponseInfo();
6713 ASSERT_TRUE(response != NULL);
6715 EXPECT_EQ(302, response->headers->response_code());
6716 std::string url;
6717 EXPECT_TRUE(response->headers->IsRedirect(&url));
6718 EXPECT_EQ("http://login.example.com/", url);
6721 // Test that an HTTPS proxy's response to a CONNECT request is filtered.
6722 TEST_P(HttpNetworkTransactionTest,
6723 ErrorResponseToHttpsConnectViaHttpsProxy) {
6724 session_deps_.proxy_service.reset(
6725 ProxyService::CreateFixed("https://proxy:70"));
6727 HttpRequestInfo request;
6728 request.method = "GET";
6729 request.url = GURL("https://www.example.org/");
6730 request.load_flags = 0;
6732 MockWrite data_writes[] = {
6733 MockWrite(
6734 "CONNECT www.example.org:443 HTTP/1.1\r\n"
6735 "Host: www.example.org\r\n"
6736 "Proxy-Connection: keep-alive\r\n\r\n"),
6739 MockRead data_reads[] = {
6740 MockRead("HTTP/1.1 404 Not Found\r\n"),
6741 MockRead("Content-Length: 23\r\n\r\n"),
6742 MockRead("The host does not exist"),
6743 MockRead(SYNCHRONOUS, OK),
6746 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
6747 data_writes, arraysize(data_writes));
6748 SSLSocketDataProvider proxy_ssl(ASYNC, OK); // SSL to the proxy
6750 session_deps_.socket_factory->AddSocketDataProvider(&data);
6751 session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy_ssl);
6753 TestCompletionCallback callback;
6755 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6756 scoped_ptr<HttpTransaction> trans(
6757 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6759 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6760 EXPECT_EQ(ERR_IO_PENDING, rv);
6762 rv = callback.WaitForResult();
6763 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, rv);
6765 // TODO(ttuttle): Anything else to check here?
6768 // Test that a SPDY proxy's response to a CONNECT request is filtered.
6769 TEST_P(HttpNetworkTransactionTest,
6770 ErrorResponseToHttpsConnectViaSpdyProxy) {
6771 session_deps_.proxy_service.reset(
6772 ProxyService::CreateFixed("https://proxy:70"));
6774 HttpRequestInfo request;
6775 request.method = "GET";
6776 request.url = GURL("https://www.example.org/");
6777 request.load_flags = 0;
6779 scoped_ptr<SpdyFrame> conn(spdy_util_.ConstructSpdyConnect(
6780 NULL, 0, 1, LOWEST, HostPortPair("www.example.org", 443)));
6781 scoped_ptr<SpdyFrame> rst(
6782 spdy_util_.ConstructSpdyRstStream(1, RST_STREAM_CANCEL));
6783 MockWrite data_writes[] = {
6784 CreateMockWrite(*conn.get(), 0), CreateMockWrite(*rst.get(), 3),
6787 static const char* const kExtraHeaders[] = {
6788 "location",
6789 "http://login.example.com/",
6791 scoped_ptr<SpdyFrame> resp(
6792 spdy_util_.ConstructSpdySynReplyError("404 Not Found", kExtraHeaders,
6793 arraysize(kExtraHeaders)/2, 1));
6794 scoped_ptr<SpdyFrame> body(
6795 spdy_util_.ConstructSpdyBodyFrame(
6796 1, "The host does not exist", 23, true));
6797 MockRead data_reads[] = {
6798 CreateMockRead(*resp.get(), 1),
6799 CreateMockRead(*body.get(), 2),
6800 MockRead(ASYNC, 0, 4), // EOF
6803 SequencedSocketData data(data_reads, arraysize(data_reads), data_writes,
6804 arraysize(data_writes));
6805 SSLSocketDataProvider proxy_ssl(ASYNC, OK); // SSL to the proxy
6806 proxy_ssl.SetNextProto(GetParam());
6808 session_deps_.socket_factory->AddSocketDataProvider(&data);
6809 session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy_ssl);
6811 TestCompletionCallback callback;
6813 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6814 scoped_ptr<HttpTransaction> trans(
6815 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6817 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6818 EXPECT_EQ(ERR_IO_PENDING, rv);
6820 rv = callback.WaitForResult();
6821 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, rv);
6823 // TODO(ttuttle): Anything else to check here?
6826 // Test the request-challenge-retry sequence for basic auth, through
6827 // a SPDY proxy over a single SPDY session.
6828 TEST_P(HttpNetworkTransactionTest, BasicAuthSpdyProxy) {
6829 HttpRequestInfo request;
6830 request.method = "GET";
6831 request.url = GURL("https://www.example.org/");
6832 // when the no authentication data flag is set.
6833 request.load_flags = LOAD_DO_NOT_SEND_AUTH_DATA;
6835 // Configure against https proxy server "myproxy:70".
6836 session_deps_.proxy_service.reset(
6837 ProxyService::CreateFixedFromPacResult("HTTPS myproxy:70"));
6838 BoundTestNetLog log;
6839 session_deps_.net_log = log.bound().net_log();
6840 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6842 // Since we have proxy, should try to establish tunnel.
6843 scoped_ptr<SpdyFrame> req(spdy_util_.ConstructSpdyConnect(
6844 NULL, 0, 1, LOWEST, HostPortPair("www.example.org", 443)));
6845 scoped_ptr<SpdyFrame> rst(
6846 spdy_util_.ConstructSpdyRstStream(1, RST_STREAM_CANCEL));
6848 // After calling trans->RestartWithAuth(), this is the request we should
6849 // be issuing -- the final header line contains the credentials.
6850 const char* const kAuthCredentials[] = {
6851 "proxy-authorization", "Basic Zm9vOmJhcg==",
6853 scoped_ptr<SpdyFrame> connect2(spdy_util_.ConstructSpdyConnect(
6854 kAuthCredentials, arraysize(kAuthCredentials) / 2, 3, LOWEST,
6855 HostPortPair("www.example.org", 443)));
6856 // fetch https://www.example.org/ via HTTP
6857 const char get[] =
6858 "GET / HTTP/1.1\r\n"
6859 "Host: www.example.org\r\n"
6860 "Connection: keep-alive\r\n\r\n";
6861 scoped_ptr<SpdyFrame> wrapped_get(
6862 spdy_util_.ConstructSpdyBodyFrame(3, get, strlen(get), false));
6864 MockWrite spdy_writes[] = {
6865 CreateMockWrite(*req, 0, ASYNC),
6866 CreateMockWrite(*rst, 2, ASYNC),
6867 CreateMockWrite(*connect2, 3),
6868 CreateMockWrite(*wrapped_get, 5),
6871 // The proxy responds to the connect with a 407, using a persistent
6872 // connection.
6873 const char kAuthStatus[] = "407";
6874 const char* const kAuthChallenge[] = {
6875 "proxy-authenticate", "Basic realm=\"MyRealm1\"",
6877 scoped_ptr<SpdyFrame> conn_auth_resp(spdy_util_.ConstructSpdySynReplyError(
6878 kAuthStatus, kAuthChallenge, arraysize(kAuthChallenge) / 2, 1));
6880 scoped_ptr<SpdyFrame> conn_resp(
6881 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
6882 const char resp[] = "HTTP/1.1 200 OK\r\n"
6883 "Content-Length: 5\r\n\r\n";
6885 scoped_ptr<SpdyFrame> wrapped_get_resp(
6886 spdy_util_.ConstructSpdyBodyFrame(3, resp, strlen(resp), false));
6887 scoped_ptr<SpdyFrame> wrapped_body(
6888 spdy_util_.ConstructSpdyBodyFrame(3, "hello", 5, false));
6889 MockRead spdy_reads[] = {
6890 CreateMockRead(*conn_auth_resp, 1, ASYNC),
6891 CreateMockRead(*conn_resp, 4, ASYNC),
6892 CreateMockRead(*wrapped_get_resp, 6, ASYNC),
6893 CreateMockRead(*wrapped_body, 7, ASYNC),
6894 MockRead(ASYNC, OK, 8), // EOF. May or may not be read.
6897 SequencedSocketData spdy_data(spdy_reads, arraysize(spdy_reads), spdy_writes,
6898 arraysize(spdy_writes));
6899 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
6900 // Negotiate SPDY to the proxy
6901 SSLSocketDataProvider proxy(ASYNC, OK);
6902 proxy.SetNextProto(GetParam());
6903 session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy);
6904 // Vanilla SSL to the server
6905 SSLSocketDataProvider server(ASYNC, OK);
6906 session_deps_.socket_factory->AddSSLSocketDataProvider(&server);
6908 TestCompletionCallback callback1;
6910 scoped_ptr<HttpTransaction> trans(
6911 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6913 int rv = trans->Start(&request, callback1.callback(), log.bound());
6914 EXPECT_EQ(ERR_IO_PENDING, rv);
6916 rv = callback1.WaitForResult();
6917 EXPECT_EQ(OK, rv);
6918 TestNetLogEntry::List entries;
6919 log.GetEntries(&entries);
6920 size_t pos = ExpectLogContainsSomewhere(
6921 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
6922 NetLog::PHASE_NONE);
6923 ExpectLogContainsSomewhere(
6924 entries, pos,
6925 NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
6926 NetLog::PHASE_NONE);
6928 const HttpResponseInfo* response = trans->GetResponseInfo();
6929 ASSERT_TRUE(response != NULL);
6930 ASSERT_FALSE(response->headers.get() == NULL);
6931 EXPECT_EQ(407, response->headers->response_code());
6932 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
6933 EXPECT_TRUE(response->auth_challenge.get() != NULL);
6934 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
6936 TestCompletionCallback callback2;
6938 rv = trans->RestartWithAuth(AuthCredentials(kFoo, kBar),
6939 callback2.callback());
6940 EXPECT_EQ(ERR_IO_PENDING, rv);
6942 rv = callback2.WaitForResult();
6943 EXPECT_EQ(OK, rv);
6945 response = trans->GetResponseInfo();
6946 ASSERT_TRUE(response != NULL);
6948 EXPECT_TRUE(response->headers->IsKeepAlive());
6949 EXPECT_EQ(200, response->headers->response_code());
6950 EXPECT_EQ(5, response->headers->GetContentLength());
6951 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
6953 // The password prompt info should not be set.
6954 EXPECT_TRUE(response->auth_challenge.get() == NULL);
6956 LoadTimingInfo load_timing_info;
6957 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
6958 TestLoadTimingNotReusedWithPac(load_timing_info,
6959 CONNECT_TIMING_HAS_SSL_TIMES);
6961 trans.reset();
6962 session->CloseAllConnections();
6965 // Test that an explicitly trusted SPDY proxy can push a resource from an
6966 // origin that is different from that of its associated resource.
6967 TEST_P(HttpNetworkTransactionTest, CrossOriginProxyPush) {
6968 HttpRequestInfo request;
6969 HttpRequestInfo push_request;
6971 request.method = "GET";
6972 request.url = GURL("http://www.example.org/");
6973 push_request.method = "GET";
6974 push_request.url = GURL("http://www.another-origin.com/foo.dat");
6976 // Configure against https proxy server "myproxy:70".
6977 session_deps_.proxy_service.reset(
6978 ProxyService::CreateFixedFromPacResult("HTTPS myproxy:70"));
6979 BoundTestNetLog log;
6980 session_deps_.net_log = log.bound().net_log();
6982 // Enable cross-origin push.
6983 session_deps_.trusted_spdy_proxy = "myproxy:70";
6985 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6987 scoped_ptr<SpdyFrame> stream1_syn(
6988 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, false));
6990 MockWrite spdy_writes[] = {
6991 CreateMockWrite(*stream1_syn, 0, ASYNC),
6994 scoped_ptr<SpdyFrame>
6995 stream1_reply(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
6997 scoped_ptr<SpdyFrame>
6998 stream1_body(spdy_util_.ConstructSpdyBodyFrame(1, true));
7000 scoped_ptr<SpdyFrame>
7001 stream2_syn(spdy_util_.ConstructSpdyPush(NULL,
7005 "http://www.another-origin.com/foo.dat"));
7006 const char kPushedData[] = "pushed";
7007 scoped_ptr<SpdyFrame> stream2_body(
7008 spdy_util_.ConstructSpdyBodyFrame(
7009 2, kPushedData, strlen(kPushedData), true));
7011 MockRead spdy_reads[] = {
7012 CreateMockRead(*stream1_reply, 1, ASYNC),
7013 CreateMockRead(*stream2_syn, 2, ASYNC),
7014 CreateMockRead(*stream1_body, 3, ASYNC),
7015 CreateMockRead(*stream2_body, 4, ASYNC),
7016 MockRead(ASYNC, ERR_IO_PENDING, 5), // Force a pause
7019 SequencedSocketData spdy_data(spdy_reads, arraysize(spdy_reads), spdy_writes,
7020 arraysize(spdy_writes));
7021 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
7022 // Negotiate SPDY to the proxy
7023 SSLSocketDataProvider proxy(ASYNC, OK);
7024 proxy.SetNextProto(GetParam());
7025 session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy);
7027 scoped_ptr<HttpTransaction> trans(
7028 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7029 TestCompletionCallback callback;
7030 int rv = trans->Start(&request, callback.callback(), log.bound());
7031 EXPECT_EQ(ERR_IO_PENDING, rv);
7033 rv = callback.WaitForResult();
7034 EXPECT_EQ(OK, rv);
7035 const HttpResponseInfo* response = trans->GetResponseInfo();
7037 scoped_ptr<HttpTransaction> push_trans(
7038 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7039 rv = push_trans->Start(&push_request, callback.callback(), log.bound());
7040 EXPECT_EQ(ERR_IO_PENDING, rv);
7042 rv = callback.WaitForResult();
7043 EXPECT_EQ(OK, rv);
7044 const HttpResponseInfo* push_response = push_trans->GetResponseInfo();
7046 ASSERT_TRUE(response != NULL);
7047 EXPECT_TRUE(response->headers->IsKeepAlive());
7049 EXPECT_EQ(200, response->headers->response_code());
7050 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
7052 std::string response_data;
7053 rv = ReadTransaction(trans.get(), &response_data);
7054 EXPECT_EQ(OK, rv);
7055 EXPECT_EQ("hello!", response_data);
7057 LoadTimingInfo load_timing_info;
7058 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
7059 TestLoadTimingNotReusedWithPac(load_timing_info,
7060 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
7062 // Verify the pushed stream.
7063 EXPECT_TRUE(push_response->headers.get() != NULL);
7064 EXPECT_EQ(200, push_response->headers->response_code());
7066 rv = ReadTransaction(push_trans.get(), &response_data);
7067 EXPECT_EQ(OK, rv);
7068 EXPECT_EQ("pushed", response_data);
7070 LoadTimingInfo push_load_timing_info;
7071 EXPECT_TRUE(push_trans->GetLoadTimingInfo(&push_load_timing_info));
7072 TestLoadTimingReusedWithPac(push_load_timing_info);
7073 // The transactions should share a socket ID, despite being for different
7074 // origins.
7075 EXPECT_EQ(load_timing_info.socket_log_id,
7076 push_load_timing_info.socket_log_id);
7078 trans.reset();
7079 push_trans.reset();
7080 session->CloseAllConnections();
7083 // Test that an explicitly trusted SPDY proxy cannot push HTTPS content.
7084 TEST_P(HttpNetworkTransactionTest, CrossOriginProxyPushCorrectness) {
7085 HttpRequestInfo request;
7087 request.method = "GET";
7088 request.url = GURL("http://www.example.org/");
7090 // Configure against https proxy server "myproxy:70".
7091 session_deps_.proxy_service.reset(
7092 ProxyService::CreateFixed("https://myproxy:70"));
7093 BoundTestNetLog log;
7094 session_deps_.net_log = log.bound().net_log();
7096 // Enable cross-origin push.
7097 session_deps_.trusted_spdy_proxy = "myproxy:70";
7099 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7101 scoped_ptr<SpdyFrame> stream1_syn(
7102 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, false));
7104 scoped_ptr<SpdyFrame> push_rst(
7105 spdy_util_.ConstructSpdyRstStream(2, RST_STREAM_REFUSED_STREAM));
7107 MockWrite spdy_writes[] = {
7108 CreateMockWrite(*stream1_syn, 0, ASYNC), CreateMockWrite(*push_rst, 3),
7111 scoped_ptr<SpdyFrame>
7112 stream1_reply(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
7114 scoped_ptr<SpdyFrame>
7115 stream1_body(spdy_util_.ConstructSpdyBodyFrame(1, true));
7117 scoped_ptr<SpdyFrame>
7118 stream2_syn(spdy_util_.ConstructSpdyPush(NULL,
7122 "https://www.another-origin.com/foo.dat"));
7124 MockRead spdy_reads[] = {
7125 CreateMockRead(*stream1_reply, 1, ASYNC),
7126 CreateMockRead(*stream2_syn, 2, ASYNC),
7127 CreateMockRead(*stream1_body, 4, ASYNC),
7128 MockRead(ASYNC, ERR_IO_PENDING, 5), // Force a pause
7131 SequencedSocketData spdy_data(spdy_reads, arraysize(spdy_reads), spdy_writes,
7132 arraysize(spdy_writes));
7133 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
7134 // Negotiate SPDY to the proxy
7135 SSLSocketDataProvider proxy(ASYNC, OK);
7136 proxy.SetNextProto(GetParam());
7137 session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy);
7139 scoped_ptr<HttpTransaction> trans(
7140 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7141 TestCompletionCallback callback;
7142 int rv = trans->Start(&request, callback.callback(), log.bound());
7143 EXPECT_EQ(ERR_IO_PENDING, rv);
7145 rv = callback.WaitForResult();
7146 EXPECT_EQ(OK, rv);
7147 const HttpResponseInfo* response = trans->GetResponseInfo();
7149 ASSERT_TRUE(response != NULL);
7150 EXPECT_TRUE(response->headers->IsKeepAlive());
7152 EXPECT_EQ(200, response->headers->response_code());
7153 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
7155 std::string response_data;
7156 rv = ReadTransaction(trans.get(), &response_data);
7157 EXPECT_EQ(OK, rv);
7158 EXPECT_EQ("hello!", response_data);
7160 trans.reset();
7161 session->CloseAllConnections();
7164 // Test HTTPS connections to a site with a bad certificate, going through an
7165 // HTTPS proxy
7166 TEST_P(HttpNetworkTransactionTest, HTTPSBadCertificateViaHttpsProxy) {
7167 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
7168 "https://proxy:70"));
7170 HttpRequestInfo request;
7171 request.method = "GET";
7172 request.url = GURL("https://www.example.org/");
7173 request.load_flags = 0;
7175 // Attempt to fetch the URL from a server with a bad cert
7176 MockWrite bad_cert_writes[] = {
7177 MockWrite(
7178 "CONNECT www.example.org:443 HTTP/1.1\r\n"
7179 "Host: www.example.org\r\n"
7180 "Proxy-Connection: keep-alive\r\n\r\n"),
7183 MockRead bad_cert_reads[] = {
7184 MockRead("HTTP/1.0 200 Connected\r\n\r\n"),
7185 MockRead(SYNCHRONOUS, OK)
7188 // Attempt to fetch the URL with a good cert
7189 MockWrite good_data_writes[] = {
7190 MockWrite(
7191 "CONNECT www.example.org:443 HTTP/1.1\r\n"
7192 "Host: www.example.org\r\n"
7193 "Proxy-Connection: keep-alive\r\n\r\n"),
7194 MockWrite(
7195 "GET / HTTP/1.1\r\n"
7196 "Host: www.example.org\r\n"
7197 "Connection: keep-alive\r\n\r\n"),
7200 MockRead good_cert_reads[] = {
7201 MockRead("HTTP/1.0 200 Connected\r\n\r\n"),
7202 MockRead("HTTP/1.0 200 OK\r\n"),
7203 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7204 MockRead("Content-Length: 100\r\n\r\n"),
7205 MockRead(SYNCHRONOUS, OK),
7208 StaticSocketDataProvider ssl_bad_certificate(
7209 bad_cert_reads, arraysize(bad_cert_reads),
7210 bad_cert_writes, arraysize(bad_cert_writes));
7211 StaticSocketDataProvider data(good_cert_reads, arraysize(good_cert_reads),
7212 good_data_writes, arraysize(good_data_writes));
7213 SSLSocketDataProvider ssl_bad(ASYNC, ERR_CERT_AUTHORITY_INVALID);
7214 SSLSocketDataProvider ssl(ASYNC, OK);
7216 // SSL to the proxy, then CONNECT request, then SSL with bad certificate
7217 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
7218 session_deps_.socket_factory->AddSocketDataProvider(&ssl_bad_certificate);
7219 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_bad);
7221 // SSL to the proxy, then CONNECT request, then valid SSL certificate
7222 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
7223 session_deps_.socket_factory->AddSocketDataProvider(&data);
7224 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
7226 TestCompletionCallback callback;
7228 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7229 scoped_ptr<HttpTransaction> trans(
7230 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7232 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7233 EXPECT_EQ(ERR_IO_PENDING, rv);
7235 rv = callback.WaitForResult();
7236 EXPECT_EQ(ERR_CERT_AUTHORITY_INVALID, rv);
7238 rv = trans->RestartIgnoringLastError(callback.callback());
7239 EXPECT_EQ(ERR_IO_PENDING, rv);
7241 rv = callback.WaitForResult();
7242 EXPECT_EQ(OK, rv);
7244 const HttpResponseInfo* response = trans->GetResponseInfo();
7246 ASSERT_TRUE(response != NULL);
7247 EXPECT_EQ(100, response->headers->GetContentLength());
7250 TEST_P(HttpNetworkTransactionTest, BuildRequest_UserAgent) {
7251 HttpRequestInfo request;
7252 request.method = "GET";
7253 request.url = GURL("http://www.example.org/");
7254 request.extra_headers.SetHeader(HttpRequestHeaders::kUserAgent,
7255 "Chromium Ultra Awesome X Edition");
7257 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7258 scoped_ptr<HttpTransaction> trans(
7259 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7261 MockWrite data_writes[] = {
7262 MockWrite(
7263 "GET / HTTP/1.1\r\n"
7264 "Host: www.example.org\r\n"
7265 "Connection: keep-alive\r\n"
7266 "User-Agent: Chromium Ultra Awesome X Edition\r\n\r\n"),
7269 // Lastly, the server responds with the actual content.
7270 MockRead data_reads[] = {
7271 MockRead("HTTP/1.0 200 OK\r\n"),
7272 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7273 MockRead("Content-Length: 100\r\n\r\n"),
7274 MockRead(SYNCHRONOUS, OK),
7277 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7278 data_writes, arraysize(data_writes));
7279 session_deps_.socket_factory->AddSocketDataProvider(&data);
7281 TestCompletionCallback callback;
7283 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7284 EXPECT_EQ(ERR_IO_PENDING, rv);
7286 rv = callback.WaitForResult();
7287 EXPECT_EQ(OK, rv);
7290 TEST_P(HttpNetworkTransactionTest, BuildRequest_UserAgentOverTunnel) {
7291 HttpRequestInfo request;
7292 request.method = "GET";
7293 request.url = GURL("https://www.example.org/");
7294 request.extra_headers.SetHeader(HttpRequestHeaders::kUserAgent,
7295 "Chromium Ultra Awesome X Edition");
7297 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
7298 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7299 scoped_ptr<HttpTransaction> trans(
7300 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7302 MockWrite data_writes[] = {
7303 MockWrite(
7304 "CONNECT www.example.org:443 HTTP/1.1\r\n"
7305 "Host: www.example.org\r\n"
7306 "Proxy-Connection: keep-alive\r\n"
7307 "User-Agent: Chromium Ultra Awesome X Edition\r\n\r\n"),
7309 MockRead data_reads[] = {
7310 // Return an error, so the transaction stops here (this test isn't
7311 // interested in the rest).
7312 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
7313 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
7314 MockRead("Proxy-Connection: close\r\n\r\n"),
7317 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7318 data_writes, arraysize(data_writes));
7319 session_deps_.socket_factory->AddSocketDataProvider(&data);
7321 TestCompletionCallback callback;
7323 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7324 EXPECT_EQ(ERR_IO_PENDING, rv);
7326 rv = callback.WaitForResult();
7327 EXPECT_EQ(OK, rv);
7330 TEST_P(HttpNetworkTransactionTest, BuildRequest_Referer) {
7331 HttpRequestInfo request;
7332 request.method = "GET";
7333 request.url = GURL("http://www.example.org/");
7334 request.load_flags = 0;
7335 request.extra_headers.SetHeader(HttpRequestHeaders::kReferer,
7336 "http://the.previous.site.com/");
7338 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7339 scoped_ptr<HttpTransaction> trans(
7340 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7342 MockWrite data_writes[] = {
7343 MockWrite(
7344 "GET / HTTP/1.1\r\n"
7345 "Host: www.example.org\r\n"
7346 "Connection: keep-alive\r\n"
7347 "Referer: http://the.previous.site.com/\r\n\r\n"),
7350 // Lastly, the server responds with the actual content.
7351 MockRead data_reads[] = {
7352 MockRead("HTTP/1.0 200 OK\r\n"),
7353 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7354 MockRead("Content-Length: 100\r\n\r\n"),
7355 MockRead(SYNCHRONOUS, OK),
7358 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7359 data_writes, arraysize(data_writes));
7360 session_deps_.socket_factory->AddSocketDataProvider(&data);
7362 TestCompletionCallback callback;
7364 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7365 EXPECT_EQ(ERR_IO_PENDING, rv);
7367 rv = callback.WaitForResult();
7368 EXPECT_EQ(OK, rv);
7371 TEST_P(HttpNetworkTransactionTest, BuildRequest_PostContentLengthZero) {
7372 HttpRequestInfo request;
7373 request.method = "POST";
7374 request.url = GURL("http://www.example.org/");
7376 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7377 scoped_ptr<HttpTransaction> trans(
7378 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7380 MockWrite data_writes[] = {
7381 MockWrite(
7382 "POST / HTTP/1.1\r\n"
7383 "Host: www.example.org\r\n"
7384 "Connection: keep-alive\r\n"
7385 "Content-Length: 0\r\n\r\n"),
7388 // Lastly, the server responds with the actual content.
7389 MockRead data_reads[] = {
7390 MockRead("HTTP/1.0 200 OK\r\n"),
7391 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7392 MockRead("Content-Length: 100\r\n\r\n"),
7393 MockRead(SYNCHRONOUS, OK),
7396 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7397 data_writes, arraysize(data_writes));
7398 session_deps_.socket_factory->AddSocketDataProvider(&data);
7400 TestCompletionCallback callback;
7402 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7403 EXPECT_EQ(ERR_IO_PENDING, rv);
7405 rv = callback.WaitForResult();
7406 EXPECT_EQ(OK, rv);
7409 TEST_P(HttpNetworkTransactionTest, BuildRequest_PutContentLengthZero) {
7410 HttpRequestInfo request;
7411 request.method = "PUT";
7412 request.url = GURL("http://www.example.org/");
7414 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7415 scoped_ptr<HttpTransaction> trans(
7416 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7418 MockWrite data_writes[] = {
7419 MockWrite(
7420 "PUT / HTTP/1.1\r\n"
7421 "Host: www.example.org\r\n"
7422 "Connection: keep-alive\r\n"
7423 "Content-Length: 0\r\n\r\n"),
7426 // Lastly, the server responds with the actual content.
7427 MockRead data_reads[] = {
7428 MockRead("HTTP/1.0 200 OK\r\n"),
7429 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7430 MockRead("Content-Length: 100\r\n\r\n"),
7431 MockRead(SYNCHRONOUS, OK),
7434 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7435 data_writes, arraysize(data_writes));
7436 session_deps_.socket_factory->AddSocketDataProvider(&data);
7438 TestCompletionCallback callback;
7440 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7441 EXPECT_EQ(ERR_IO_PENDING, rv);
7443 rv = callback.WaitForResult();
7444 EXPECT_EQ(OK, rv);
7447 TEST_P(HttpNetworkTransactionTest, BuildRequest_HeadContentLengthZero) {
7448 HttpRequestInfo request;
7449 request.method = "HEAD";
7450 request.url = GURL("http://www.example.org/");
7452 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7453 scoped_ptr<HttpTransaction> trans(
7454 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7456 MockWrite data_writes[] = {
7457 MockWrite("HEAD / HTTP/1.1\r\n"
7458 "Host: www.example.org\r\n"
7459 "Connection: keep-alive\r\n\r\n"),
7462 // Lastly, the server responds with the actual content.
7463 MockRead data_reads[] = {
7464 MockRead("HTTP/1.0 200 OK\r\n"),
7465 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7466 MockRead("Content-Length: 100\r\n\r\n"),
7467 MockRead(SYNCHRONOUS, OK),
7470 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7471 data_writes, arraysize(data_writes));
7472 session_deps_.socket_factory->AddSocketDataProvider(&data);
7474 TestCompletionCallback callback;
7476 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7477 EXPECT_EQ(ERR_IO_PENDING, rv);
7479 rv = callback.WaitForResult();
7480 EXPECT_EQ(OK, rv);
7483 TEST_P(HttpNetworkTransactionTest, BuildRequest_CacheControlNoCache) {
7484 HttpRequestInfo request;
7485 request.method = "GET";
7486 request.url = GURL("http://www.example.org/");
7487 request.load_flags = LOAD_BYPASS_CACHE;
7489 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7490 scoped_ptr<HttpTransaction> trans(
7491 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7493 MockWrite data_writes[] = {
7494 MockWrite(
7495 "GET / HTTP/1.1\r\n"
7496 "Host: www.example.org\r\n"
7497 "Connection: keep-alive\r\n"
7498 "Pragma: no-cache\r\n"
7499 "Cache-Control: no-cache\r\n\r\n"),
7502 // Lastly, the server responds with the actual content.
7503 MockRead data_reads[] = {
7504 MockRead("HTTP/1.0 200 OK\r\n"),
7505 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7506 MockRead("Content-Length: 100\r\n\r\n"),
7507 MockRead(SYNCHRONOUS, OK),
7510 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7511 data_writes, arraysize(data_writes));
7512 session_deps_.socket_factory->AddSocketDataProvider(&data);
7514 TestCompletionCallback callback;
7516 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7517 EXPECT_EQ(ERR_IO_PENDING, rv);
7519 rv = callback.WaitForResult();
7520 EXPECT_EQ(OK, rv);
7523 TEST_P(HttpNetworkTransactionTest,
7524 BuildRequest_CacheControlValidateCache) {
7525 HttpRequestInfo request;
7526 request.method = "GET";
7527 request.url = GURL("http://www.example.org/");
7528 request.load_flags = LOAD_VALIDATE_CACHE;
7530 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7531 scoped_ptr<HttpTransaction> trans(
7532 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7534 MockWrite data_writes[] = {
7535 MockWrite(
7536 "GET / HTTP/1.1\r\n"
7537 "Host: www.example.org\r\n"
7538 "Connection: keep-alive\r\n"
7539 "Cache-Control: max-age=0\r\n\r\n"),
7542 // Lastly, the server responds with the actual content.
7543 MockRead data_reads[] = {
7544 MockRead("HTTP/1.0 200 OK\r\n"),
7545 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7546 MockRead("Content-Length: 100\r\n\r\n"),
7547 MockRead(SYNCHRONOUS, OK),
7550 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7551 data_writes, arraysize(data_writes));
7552 session_deps_.socket_factory->AddSocketDataProvider(&data);
7554 TestCompletionCallback callback;
7556 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7557 EXPECT_EQ(ERR_IO_PENDING, rv);
7559 rv = callback.WaitForResult();
7560 EXPECT_EQ(OK, rv);
7563 TEST_P(HttpNetworkTransactionTest, BuildRequest_ExtraHeaders) {
7564 HttpRequestInfo request;
7565 request.method = "GET";
7566 request.url = GURL("http://www.example.org/");
7567 request.extra_headers.SetHeader("FooHeader", "Bar");
7569 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7570 scoped_ptr<HttpTransaction> trans(
7571 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7573 MockWrite data_writes[] = {
7574 MockWrite(
7575 "GET / HTTP/1.1\r\n"
7576 "Host: www.example.org\r\n"
7577 "Connection: keep-alive\r\n"
7578 "FooHeader: Bar\r\n\r\n"),
7581 // Lastly, the server responds with the actual content.
7582 MockRead data_reads[] = {
7583 MockRead("HTTP/1.0 200 OK\r\n"),
7584 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7585 MockRead("Content-Length: 100\r\n\r\n"),
7586 MockRead(SYNCHRONOUS, OK),
7589 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7590 data_writes, arraysize(data_writes));
7591 session_deps_.socket_factory->AddSocketDataProvider(&data);
7593 TestCompletionCallback callback;
7595 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7596 EXPECT_EQ(ERR_IO_PENDING, rv);
7598 rv = callback.WaitForResult();
7599 EXPECT_EQ(OK, rv);
7602 TEST_P(HttpNetworkTransactionTest, BuildRequest_ExtraHeadersStripped) {
7603 HttpRequestInfo request;
7604 request.method = "GET";
7605 request.url = GURL("http://www.example.org/");
7606 request.extra_headers.SetHeader("referer", "www.foo.com");
7607 request.extra_headers.SetHeader("hEllo", "Kitty");
7608 request.extra_headers.SetHeader("FoO", "bar");
7610 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7611 scoped_ptr<HttpTransaction> trans(
7612 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7614 MockWrite data_writes[] = {
7615 MockWrite(
7616 "GET / HTTP/1.1\r\n"
7617 "Host: www.example.org\r\n"
7618 "Connection: keep-alive\r\n"
7619 "referer: www.foo.com\r\n"
7620 "hEllo: Kitty\r\n"
7621 "FoO: bar\r\n\r\n"),
7624 // Lastly, the server responds with the actual content.
7625 MockRead data_reads[] = {
7626 MockRead("HTTP/1.0 200 OK\r\n"),
7627 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7628 MockRead("Content-Length: 100\r\n\r\n"),
7629 MockRead(SYNCHRONOUS, OK),
7632 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7633 data_writes, arraysize(data_writes));
7634 session_deps_.socket_factory->AddSocketDataProvider(&data);
7636 TestCompletionCallback callback;
7638 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7639 EXPECT_EQ(ERR_IO_PENDING, rv);
7641 rv = callback.WaitForResult();
7642 EXPECT_EQ(OK, rv);
7645 TEST_P(HttpNetworkTransactionTest, SOCKS4_HTTP_GET) {
7646 HttpRequestInfo request;
7647 request.method = "GET";
7648 request.url = GURL("http://www.example.org/");
7649 request.load_flags = 0;
7651 session_deps_.proxy_service.reset(
7652 ProxyService::CreateFixedFromPacResult("SOCKS myproxy:1080"));
7653 TestNetLog net_log;
7654 session_deps_.net_log = &net_log;
7656 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7657 scoped_ptr<HttpTransaction> trans(
7658 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7660 char write_buffer[] = { 0x04, 0x01, 0x00, 0x50, 127, 0, 0, 1, 0 };
7661 char read_buffer[] = { 0x00, 0x5A, 0x00, 0x00, 0, 0, 0, 0 };
7663 MockWrite data_writes[] = {
7664 MockWrite(ASYNC, write_buffer, arraysize(write_buffer)),
7665 MockWrite(
7666 "GET / HTTP/1.1\r\n"
7667 "Host: www.example.org\r\n"
7668 "Connection: keep-alive\r\n\r\n")};
7670 MockRead data_reads[] = {
7671 MockRead(ASYNC, read_buffer, arraysize(read_buffer)),
7672 MockRead("HTTP/1.0 200 OK\r\n"),
7673 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
7674 MockRead("Payload"),
7675 MockRead(SYNCHRONOUS, OK)
7678 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7679 data_writes, arraysize(data_writes));
7680 session_deps_.socket_factory->AddSocketDataProvider(&data);
7682 TestCompletionCallback callback;
7684 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7685 EXPECT_EQ(ERR_IO_PENDING, rv);
7687 rv = callback.WaitForResult();
7688 EXPECT_EQ(OK, rv);
7690 const HttpResponseInfo* response = trans->GetResponseInfo();
7691 ASSERT_TRUE(response != NULL);
7693 LoadTimingInfo load_timing_info;
7694 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
7695 TestLoadTimingNotReusedWithPac(load_timing_info,
7696 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
7698 std::string response_text;
7699 rv = ReadTransaction(trans.get(), &response_text);
7700 EXPECT_EQ(OK, rv);
7701 EXPECT_EQ("Payload", response_text);
7704 TEST_P(HttpNetworkTransactionTest, SOCKS4_SSL_GET) {
7705 HttpRequestInfo request;
7706 request.method = "GET";
7707 request.url = GURL("https://www.example.org/");
7708 request.load_flags = 0;
7710 session_deps_.proxy_service.reset(
7711 ProxyService::CreateFixedFromPacResult("SOCKS myproxy:1080"));
7712 TestNetLog net_log;
7713 session_deps_.net_log = &net_log;
7715 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7716 scoped_ptr<HttpTransaction> trans(
7717 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7719 unsigned char write_buffer[] = { 0x04, 0x01, 0x01, 0xBB, 127, 0, 0, 1, 0 };
7720 unsigned char read_buffer[] = { 0x00, 0x5A, 0x00, 0x00, 0, 0, 0, 0 };
7722 MockWrite data_writes[] = {
7723 MockWrite(ASYNC, reinterpret_cast<char*>(write_buffer),
7724 arraysize(write_buffer)),
7725 MockWrite(
7726 "GET / HTTP/1.1\r\n"
7727 "Host: www.example.org\r\n"
7728 "Connection: keep-alive\r\n\r\n")};
7730 MockRead data_reads[] = {
7731 MockRead(ASYNC, reinterpret_cast<char*>(read_buffer),
7732 arraysize(read_buffer)),
7733 MockRead("HTTP/1.0 200 OK\r\n"),
7734 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
7735 MockRead("Payload"),
7736 MockRead(SYNCHRONOUS, OK)
7739 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7740 data_writes, arraysize(data_writes));
7741 session_deps_.socket_factory->AddSocketDataProvider(&data);
7743 SSLSocketDataProvider ssl(ASYNC, OK);
7744 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
7746 TestCompletionCallback callback;
7748 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7749 EXPECT_EQ(ERR_IO_PENDING, rv);
7751 rv = callback.WaitForResult();
7752 EXPECT_EQ(OK, rv);
7754 LoadTimingInfo load_timing_info;
7755 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
7756 TestLoadTimingNotReusedWithPac(load_timing_info,
7757 CONNECT_TIMING_HAS_SSL_TIMES);
7759 const HttpResponseInfo* response = trans->GetResponseInfo();
7760 ASSERT_TRUE(response != NULL);
7762 std::string response_text;
7763 rv = ReadTransaction(trans.get(), &response_text);
7764 EXPECT_EQ(OK, rv);
7765 EXPECT_EQ("Payload", response_text);
7768 TEST_P(HttpNetworkTransactionTest, SOCKS4_HTTP_GET_no_PAC) {
7769 HttpRequestInfo request;
7770 request.method = "GET";
7771 request.url = GURL("http://www.example.org/");
7772 request.load_flags = 0;
7774 session_deps_.proxy_service.reset(
7775 ProxyService::CreateFixed("socks4://myproxy:1080"));
7776 TestNetLog net_log;
7777 session_deps_.net_log = &net_log;
7779 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7780 scoped_ptr<HttpTransaction> trans(
7781 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7783 char write_buffer[] = { 0x04, 0x01, 0x00, 0x50, 127, 0, 0, 1, 0 };
7784 char read_buffer[] = { 0x00, 0x5A, 0x00, 0x00, 0, 0, 0, 0 };
7786 MockWrite data_writes[] = {
7787 MockWrite(ASYNC, write_buffer, arraysize(write_buffer)),
7788 MockWrite(
7789 "GET / HTTP/1.1\r\n"
7790 "Host: www.example.org\r\n"
7791 "Connection: keep-alive\r\n\r\n")};
7793 MockRead data_reads[] = {
7794 MockRead(ASYNC, read_buffer, arraysize(read_buffer)),
7795 MockRead("HTTP/1.0 200 OK\r\n"),
7796 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
7797 MockRead("Payload"),
7798 MockRead(SYNCHRONOUS, OK)
7801 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7802 data_writes, arraysize(data_writes));
7803 session_deps_.socket_factory->AddSocketDataProvider(&data);
7805 TestCompletionCallback callback;
7807 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7808 EXPECT_EQ(ERR_IO_PENDING, rv);
7810 rv = callback.WaitForResult();
7811 EXPECT_EQ(OK, rv);
7813 const HttpResponseInfo* response = trans->GetResponseInfo();
7814 ASSERT_TRUE(response != NULL);
7816 LoadTimingInfo load_timing_info;
7817 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
7818 TestLoadTimingNotReused(load_timing_info,
7819 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
7821 std::string response_text;
7822 rv = ReadTransaction(trans.get(), &response_text);
7823 EXPECT_EQ(OK, rv);
7824 EXPECT_EQ("Payload", response_text);
7827 TEST_P(HttpNetworkTransactionTest, SOCKS5_HTTP_GET) {
7828 HttpRequestInfo request;
7829 request.method = "GET";
7830 request.url = GURL("http://www.example.org/");
7831 request.load_flags = 0;
7833 session_deps_.proxy_service.reset(
7834 ProxyService::CreateFixedFromPacResult("SOCKS5 myproxy:1080"));
7835 TestNetLog net_log;
7836 session_deps_.net_log = &net_log;
7838 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7839 scoped_ptr<HttpTransaction> trans(
7840 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7842 const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 };
7843 const char kSOCKS5GreetResponse[] = { 0x05, 0x00 };
7844 const char kSOCKS5OkRequest[] = {
7845 0x05, // Version
7846 0x01, // Command (CONNECT)
7847 0x00, // Reserved.
7848 0x03, // Address type (DOMAINNAME).
7849 0x0F, // Length of domain (15)
7850 'w', 'w', 'w', '.', 'e', 'x', 'a', 'm', 'p', 'l', 'e', // Domain string
7851 '.', 'o', 'r', 'g', 0x00, 0x50, // 16-bit port (80)
7853 const char kSOCKS5OkResponse[] =
7854 { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
7856 MockWrite data_writes[] = {
7857 MockWrite(ASYNC, kSOCKS5GreetRequest, arraysize(kSOCKS5GreetRequest)),
7858 MockWrite(ASYNC, kSOCKS5OkRequest, arraysize(kSOCKS5OkRequest)),
7859 MockWrite(
7860 "GET / HTTP/1.1\r\n"
7861 "Host: www.example.org\r\n"
7862 "Connection: keep-alive\r\n\r\n")};
7864 MockRead data_reads[] = {
7865 MockRead(ASYNC, kSOCKS5GreetResponse, arraysize(kSOCKS5GreetResponse)),
7866 MockRead(ASYNC, kSOCKS5OkResponse, arraysize(kSOCKS5OkResponse)),
7867 MockRead("HTTP/1.0 200 OK\r\n"),
7868 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
7869 MockRead("Payload"),
7870 MockRead(SYNCHRONOUS, OK)
7873 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7874 data_writes, arraysize(data_writes));
7875 session_deps_.socket_factory->AddSocketDataProvider(&data);
7877 TestCompletionCallback callback;
7879 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7880 EXPECT_EQ(ERR_IO_PENDING, rv);
7882 rv = callback.WaitForResult();
7883 EXPECT_EQ(OK, rv);
7885 const HttpResponseInfo* response = trans->GetResponseInfo();
7886 ASSERT_TRUE(response != NULL);
7888 LoadTimingInfo load_timing_info;
7889 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
7890 TestLoadTimingNotReusedWithPac(load_timing_info,
7891 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
7893 std::string response_text;
7894 rv = ReadTransaction(trans.get(), &response_text);
7895 EXPECT_EQ(OK, rv);
7896 EXPECT_EQ("Payload", response_text);
7899 TEST_P(HttpNetworkTransactionTest, SOCKS5_SSL_GET) {
7900 HttpRequestInfo request;
7901 request.method = "GET";
7902 request.url = GURL("https://www.example.org/");
7903 request.load_flags = 0;
7905 session_deps_.proxy_service.reset(
7906 ProxyService::CreateFixedFromPacResult("SOCKS5 myproxy:1080"));
7907 TestNetLog net_log;
7908 session_deps_.net_log = &net_log;
7910 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7911 scoped_ptr<HttpTransaction> trans(
7912 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7914 const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 };
7915 const char kSOCKS5GreetResponse[] = { 0x05, 0x00 };
7916 const unsigned char kSOCKS5OkRequest[] = {
7917 0x05, // Version
7918 0x01, // Command (CONNECT)
7919 0x00, // Reserved.
7920 0x03, // Address type (DOMAINNAME).
7921 0x0F, // Length of domain (15)
7922 'w', 'w', 'w', '.', 'e', 'x', 'a', 'm', 'p', 'l', 'e', // Domain string
7923 '.', 'o', 'r', 'g', 0x01, 0xBB, // 16-bit port (443)
7926 const char kSOCKS5OkResponse[] =
7927 { 0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0x00, 0x00 };
7929 MockWrite data_writes[] = {
7930 MockWrite(ASYNC, kSOCKS5GreetRequest, arraysize(kSOCKS5GreetRequest)),
7931 MockWrite(ASYNC, reinterpret_cast<const char*>(kSOCKS5OkRequest),
7932 arraysize(kSOCKS5OkRequest)),
7933 MockWrite(
7934 "GET / HTTP/1.1\r\n"
7935 "Host: www.example.org\r\n"
7936 "Connection: keep-alive\r\n\r\n")};
7938 MockRead data_reads[] = {
7939 MockRead(ASYNC, kSOCKS5GreetResponse, arraysize(kSOCKS5GreetResponse)),
7940 MockRead(ASYNC, kSOCKS5OkResponse, arraysize(kSOCKS5OkResponse)),
7941 MockRead("HTTP/1.0 200 OK\r\n"),
7942 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
7943 MockRead("Payload"),
7944 MockRead(SYNCHRONOUS, OK)
7947 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7948 data_writes, arraysize(data_writes));
7949 session_deps_.socket_factory->AddSocketDataProvider(&data);
7951 SSLSocketDataProvider ssl(ASYNC, OK);
7952 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
7954 TestCompletionCallback callback;
7956 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7957 EXPECT_EQ(ERR_IO_PENDING, rv);
7959 rv = callback.WaitForResult();
7960 EXPECT_EQ(OK, rv);
7962 const HttpResponseInfo* response = trans->GetResponseInfo();
7963 ASSERT_TRUE(response != NULL);
7965 LoadTimingInfo load_timing_info;
7966 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
7967 TestLoadTimingNotReusedWithPac(load_timing_info,
7968 CONNECT_TIMING_HAS_SSL_TIMES);
7970 std::string response_text;
7971 rv = ReadTransaction(trans.get(), &response_text);
7972 EXPECT_EQ(OK, rv);
7973 EXPECT_EQ("Payload", response_text);
7976 namespace {
7978 // Tests that for connection endpoints the group names are correctly set.
7980 struct GroupNameTest {
7981 std::string proxy_server;
7982 std::string url;
7983 std::string expected_group_name;
7984 bool ssl;
7987 scoped_refptr<HttpNetworkSession> SetupSessionForGroupNameTests(
7988 NextProto next_proto,
7989 SpdySessionDependencies* session_deps_) {
7990 scoped_refptr<HttpNetworkSession> session(CreateSession(session_deps_));
7992 base::WeakPtr<HttpServerProperties> http_server_properties =
7993 session->http_server_properties();
7994 AlternativeService alternative_service(
7995 AlternateProtocolFromNextProto(next_proto), "", 443);
7996 base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
7997 http_server_properties->SetAlternativeService(
7998 HostPortPair("host.with.alternate", 80), alternative_service, 1.0,
7999 expiration);
8001 return session;
8004 int GroupNameTransactionHelper(
8005 const std::string& url,
8006 const scoped_refptr<HttpNetworkSession>& session) {
8007 HttpRequestInfo request;
8008 request.method = "GET";
8009 request.url = GURL(url);
8010 request.load_flags = 0;
8012 scoped_ptr<HttpTransaction> trans(
8013 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8015 TestCompletionCallback callback;
8017 // We do not complete this request, the dtor will clean the transaction up.
8018 return trans->Start(&request, callback.callback(), BoundNetLog());
8021 } // namespace
8023 TEST_P(HttpNetworkTransactionTest, GroupNameForDirectConnections) {
8024 const GroupNameTest tests[] = {
8026 "", // unused
8027 "http://www.example.org/direct",
8028 "www.example.org:80",
8029 false,
8032 "", // unused
8033 "http://[2001:1418:13:1::25]/direct",
8034 "[2001:1418:13:1::25]:80",
8035 false,
8038 // SSL Tests
8040 "", // unused
8041 "https://www.example.org/direct_ssl",
8042 "ssl/www.example.org:443",
8043 true,
8046 "", // unused
8047 "https://[2001:1418:13:1::25]/direct",
8048 "ssl/[2001:1418:13:1::25]:443",
8049 true,
8052 "", // unused
8053 "http://host.with.alternate/direct",
8054 "ssl/host.with.alternate:443",
8055 true,
8059 session_deps_.use_alternative_services = true;
8061 for (size_t i = 0; i < arraysize(tests); ++i) {
8062 session_deps_.proxy_service.reset(
8063 ProxyService::CreateFixed(tests[i].proxy_server));
8064 scoped_refptr<HttpNetworkSession> session(
8065 SetupSessionForGroupNameTests(GetParam(), &session_deps_));
8067 HttpNetworkSessionPeer peer(session);
8068 CaptureGroupNameTransportSocketPool* transport_conn_pool =
8069 new CaptureGroupNameTransportSocketPool(NULL, NULL);
8070 CaptureGroupNameSSLSocketPool* ssl_conn_pool =
8071 new CaptureGroupNameSSLSocketPool(NULL, NULL);
8072 scoped_ptr<MockClientSocketPoolManager> mock_pool_manager(
8073 new MockClientSocketPoolManager);
8074 mock_pool_manager->SetTransportSocketPool(transport_conn_pool);
8075 mock_pool_manager->SetSSLSocketPool(ssl_conn_pool);
8076 peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
8078 EXPECT_EQ(ERR_IO_PENDING,
8079 GroupNameTransactionHelper(tests[i].url, session));
8080 if (tests[i].ssl)
8081 EXPECT_EQ(tests[i].expected_group_name,
8082 ssl_conn_pool->last_group_name_received());
8083 else
8084 EXPECT_EQ(tests[i].expected_group_name,
8085 transport_conn_pool->last_group_name_received());
8089 TEST_P(HttpNetworkTransactionTest, GroupNameForHTTPProxyConnections) {
8090 const GroupNameTest tests[] = {
8092 "http_proxy",
8093 "http://www.example.org/http_proxy_normal",
8094 "www.example.org:80",
8095 false,
8098 // SSL Tests
8100 "http_proxy",
8101 "https://www.example.org/http_connect_ssl",
8102 "ssl/www.example.org:443",
8103 true,
8107 "http_proxy",
8108 "http://host.with.alternate/direct",
8109 "ssl/host.with.alternate:443",
8110 true,
8114 "http_proxy",
8115 "ftp://ftp.google.com/http_proxy_normal",
8116 "ftp/ftp.google.com:21",
8117 false,
8121 session_deps_.use_alternative_services = true;
8123 for (size_t i = 0; i < arraysize(tests); ++i) {
8124 session_deps_.proxy_service.reset(
8125 ProxyService::CreateFixed(tests[i].proxy_server));
8126 scoped_refptr<HttpNetworkSession> session(
8127 SetupSessionForGroupNameTests(GetParam(), &session_deps_));
8129 HttpNetworkSessionPeer peer(session);
8131 HostPortPair proxy_host("http_proxy", 80);
8132 CaptureGroupNameHttpProxySocketPool* http_proxy_pool =
8133 new CaptureGroupNameHttpProxySocketPool(NULL, NULL);
8134 CaptureGroupNameSSLSocketPool* ssl_conn_pool =
8135 new CaptureGroupNameSSLSocketPool(NULL, NULL);
8137 scoped_ptr<MockClientSocketPoolManager> mock_pool_manager(
8138 new MockClientSocketPoolManager);
8139 mock_pool_manager->SetSocketPoolForHTTPProxy(proxy_host, http_proxy_pool);
8140 mock_pool_manager->SetSocketPoolForSSLWithProxy(proxy_host, ssl_conn_pool);
8141 peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
8143 EXPECT_EQ(ERR_IO_PENDING,
8144 GroupNameTransactionHelper(tests[i].url, session));
8145 if (tests[i].ssl)
8146 EXPECT_EQ(tests[i].expected_group_name,
8147 ssl_conn_pool->last_group_name_received());
8148 else
8149 EXPECT_EQ(tests[i].expected_group_name,
8150 http_proxy_pool->last_group_name_received());
8154 TEST_P(HttpNetworkTransactionTest, GroupNameForSOCKSConnections) {
8155 const GroupNameTest tests[] = {
8157 "socks4://socks_proxy:1080",
8158 "http://www.example.org/socks4_direct",
8159 "socks4/www.example.org:80",
8160 false,
8163 "socks5://socks_proxy:1080",
8164 "http://www.example.org/socks5_direct",
8165 "socks5/www.example.org:80",
8166 false,
8169 // SSL Tests
8171 "socks4://socks_proxy:1080",
8172 "https://www.example.org/socks4_ssl",
8173 "socks4/ssl/www.example.org:443",
8174 true,
8177 "socks5://socks_proxy:1080",
8178 "https://www.example.org/socks5_ssl",
8179 "socks5/ssl/www.example.org:443",
8180 true,
8184 "socks4://socks_proxy:1080",
8185 "http://host.with.alternate/direct",
8186 "socks4/ssl/host.with.alternate:443",
8187 true,
8191 session_deps_.use_alternative_services = true;
8193 for (size_t i = 0; i < arraysize(tests); ++i) {
8194 session_deps_.proxy_service.reset(
8195 ProxyService::CreateFixed(tests[i].proxy_server));
8196 scoped_refptr<HttpNetworkSession> session(
8197 SetupSessionForGroupNameTests(GetParam(), &session_deps_));
8199 HttpNetworkSessionPeer peer(session);
8201 HostPortPair proxy_host("socks_proxy", 1080);
8202 CaptureGroupNameSOCKSSocketPool* socks_conn_pool =
8203 new CaptureGroupNameSOCKSSocketPool(NULL, NULL);
8204 CaptureGroupNameSSLSocketPool* ssl_conn_pool =
8205 new CaptureGroupNameSSLSocketPool(NULL, NULL);
8207 scoped_ptr<MockClientSocketPoolManager> mock_pool_manager(
8208 new MockClientSocketPoolManager);
8209 mock_pool_manager->SetSocketPoolForSOCKSProxy(proxy_host, socks_conn_pool);
8210 mock_pool_manager->SetSocketPoolForSSLWithProxy(proxy_host, ssl_conn_pool);
8211 peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
8213 scoped_ptr<HttpTransaction> trans(
8214 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8216 EXPECT_EQ(ERR_IO_PENDING,
8217 GroupNameTransactionHelper(tests[i].url, session));
8218 if (tests[i].ssl)
8219 EXPECT_EQ(tests[i].expected_group_name,
8220 ssl_conn_pool->last_group_name_received());
8221 else
8222 EXPECT_EQ(tests[i].expected_group_name,
8223 socks_conn_pool->last_group_name_received());
8227 TEST_P(HttpNetworkTransactionTest, ReconsiderProxyAfterFailedConnection) {
8228 HttpRequestInfo request;
8229 request.method = "GET";
8230 request.url = GURL("http://www.example.org/");
8232 session_deps_.proxy_service.reset(
8233 ProxyService::CreateFixed("myproxy:70;foobar:80"));
8235 // This simulates failure resolving all hostnames; that means we will fail
8236 // connecting to both proxies (myproxy:70 and foobar:80).
8237 session_deps_.host_resolver->rules()->AddSimulatedFailure("*");
8239 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8240 scoped_ptr<HttpTransaction> trans(
8241 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8243 TestCompletionCallback callback;
8245 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8246 EXPECT_EQ(ERR_IO_PENDING, rv);
8248 rv = callback.WaitForResult();
8249 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, rv);
8252 // Base test to make sure that when the load flags for a request specify to
8253 // bypass the cache, the DNS cache is not used.
8254 void HttpNetworkTransactionTest::BypassHostCacheOnRefreshHelper(
8255 int load_flags) {
8256 // Issue a request, asking to bypass the cache(s).
8257 HttpRequestInfo request;
8258 request.method = "GET";
8259 request.load_flags = load_flags;
8260 request.url = GURL("http://www.example.org/");
8262 // Select a host resolver that does caching.
8263 session_deps_.host_resolver.reset(new MockCachingHostResolver);
8265 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8266 scoped_ptr<HttpTransaction> trans(
8267 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8269 // Warm up the host cache so it has an entry for "www.example.org".
8270 AddressList addrlist;
8271 TestCompletionCallback callback;
8272 int rv = session_deps_.host_resolver->Resolve(
8273 HostResolver::RequestInfo(HostPortPair("www.example.org", 80)),
8274 DEFAULT_PRIORITY, &addrlist, callback.callback(), NULL, BoundNetLog());
8275 EXPECT_EQ(ERR_IO_PENDING, rv);
8276 rv = callback.WaitForResult();
8277 EXPECT_EQ(OK, rv);
8279 // Verify that it was added to host cache, by doing a subsequent async lookup
8280 // and confirming it completes synchronously.
8281 rv = session_deps_.host_resolver->Resolve(
8282 HostResolver::RequestInfo(HostPortPair("www.example.org", 80)),
8283 DEFAULT_PRIORITY, &addrlist, callback.callback(), NULL, BoundNetLog());
8284 ASSERT_EQ(OK, rv);
8286 // Inject a failure the next time that "www.example.org" is resolved. This way
8287 // we can tell if the next lookup hit the cache, or the "network".
8288 // (cache --> success, "network" --> failure).
8289 session_deps_.host_resolver->rules()->AddSimulatedFailure("www.example.org");
8291 // Connect up a mock socket which will fail with ERR_UNEXPECTED during the
8292 // first read -- this won't be reached as the host resolution will fail first.
8293 MockRead data_reads[] = { MockRead(SYNCHRONOUS, ERR_UNEXPECTED) };
8294 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
8295 session_deps_.socket_factory->AddSocketDataProvider(&data);
8297 // Run the request.
8298 rv = trans->Start(&request, callback.callback(), BoundNetLog());
8299 ASSERT_EQ(ERR_IO_PENDING, rv);
8300 rv = callback.WaitForResult();
8302 // If we bypassed the cache, we would have gotten a failure while resolving
8303 // "www.example.org".
8304 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, rv);
8307 // There are multiple load flags that should trigger the host cache bypass.
8308 // Test each in isolation:
8309 TEST_P(HttpNetworkTransactionTest, BypassHostCacheOnRefresh1) {
8310 BypassHostCacheOnRefreshHelper(LOAD_BYPASS_CACHE);
8313 TEST_P(HttpNetworkTransactionTest, BypassHostCacheOnRefresh2) {
8314 BypassHostCacheOnRefreshHelper(LOAD_VALIDATE_CACHE);
8317 TEST_P(HttpNetworkTransactionTest, BypassHostCacheOnRefresh3) {
8318 BypassHostCacheOnRefreshHelper(LOAD_DISABLE_CACHE);
8321 // Make sure we can handle an error when writing the request.
8322 TEST_P(HttpNetworkTransactionTest, RequestWriteError) {
8323 HttpRequestInfo request;
8324 request.method = "GET";
8325 request.url = GURL("http://www.foo.com/");
8326 request.load_flags = 0;
8328 MockWrite write_failure[] = {
8329 MockWrite(ASYNC, ERR_CONNECTION_RESET),
8331 StaticSocketDataProvider data(NULL, 0,
8332 write_failure, arraysize(write_failure));
8333 session_deps_.socket_factory->AddSocketDataProvider(&data);
8334 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8336 TestCompletionCallback callback;
8338 scoped_ptr<HttpTransaction> trans(
8339 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8341 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8342 EXPECT_EQ(ERR_IO_PENDING, rv);
8344 rv = callback.WaitForResult();
8345 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
8348 // Check that a connection closed after the start of the headers finishes ok.
8349 TEST_P(HttpNetworkTransactionTest, ConnectionClosedAfterStartOfHeaders) {
8350 HttpRequestInfo request;
8351 request.method = "GET";
8352 request.url = GURL("http://www.foo.com/");
8353 request.load_flags = 0;
8355 MockRead data_reads[] = {
8356 MockRead("HTTP/1."),
8357 MockRead(SYNCHRONOUS, OK),
8360 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
8361 session_deps_.socket_factory->AddSocketDataProvider(&data);
8362 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8364 TestCompletionCallback callback;
8366 scoped_ptr<HttpTransaction> trans(
8367 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8369 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8370 EXPECT_EQ(ERR_IO_PENDING, rv);
8372 rv = callback.WaitForResult();
8373 EXPECT_EQ(OK, rv);
8375 const HttpResponseInfo* response = trans->GetResponseInfo();
8376 ASSERT_TRUE(response != NULL);
8378 EXPECT_TRUE(response->headers.get() != NULL);
8379 EXPECT_EQ("HTTP/1.0 200 OK", response->headers->GetStatusLine());
8381 std::string response_data;
8382 rv = ReadTransaction(trans.get(), &response_data);
8383 EXPECT_EQ(OK, rv);
8384 EXPECT_EQ("", response_data);
8387 // Make sure that a dropped connection while draining the body for auth
8388 // restart does the right thing.
8389 TEST_P(HttpNetworkTransactionTest, DrainResetOK) {
8390 HttpRequestInfo request;
8391 request.method = "GET";
8392 request.url = GURL("http://www.example.org/");
8393 request.load_flags = 0;
8395 MockWrite data_writes1[] = {
8396 MockWrite(
8397 "GET / HTTP/1.1\r\n"
8398 "Host: www.example.org\r\n"
8399 "Connection: keep-alive\r\n\r\n"),
8402 MockRead data_reads1[] = {
8403 MockRead("HTTP/1.1 401 Unauthorized\r\n"),
8404 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
8405 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
8406 MockRead("Content-Length: 14\r\n\r\n"),
8407 MockRead("Unauth"),
8408 MockRead(ASYNC, ERR_CONNECTION_RESET),
8411 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
8412 data_writes1, arraysize(data_writes1));
8413 session_deps_.socket_factory->AddSocketDataProvider(&data1);
8415 // After calling trans->RestartWithAuth(), this is the request we should
8416 // be issuing -- the final header line contains the credentials.
8417 MockWrite data_writes2[] = {
8418 MockWrite(
8419 "GET / HTTP/1.1\r\n"
8420 "Host: www.example.org\r\n"
8421 "Connection: keep-alive\r\n"
8422 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
8425 // Lastly, the server responds with the actual content.
8426 MockRead data_reads2[] = {
8427 MockRead("HTTP/1.1 200 OK\r\n"),
8428 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
8429 MockRead("Content-Length: 100\r\n\r\n"),
8430 MockRead(SYNCHRONOUS, OK),
8433 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
8434 data_writes2, arraysize(data_writes2));
8435 session_deps_.socket_factory->AddSocketDataProvider(&data2);
8436 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8438 TestCompletionCallback callback1;
8440 scoped_ptr<HttpTransaction> trans(
8441 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8443 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
8444 EXPECT_EQ(ERR_IO_PENDING, rv);
8446 rv = callback1.WaitForResult();
8447 EXPECT_EQ(OK, rv);
8449 const HttpResponseInfo* response = trans->GetResponseInfo();
8450 ASSERT_TRUE(response != NULL);
8451 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
8453 TestCompletionCallback callback2;
8455 rv = trans->RestartWithAuth(
8456 AuthCredentials(kFoo, kBar), callback2.callback());
8457 EXPECT_EQ(ERR_IO_PENDING, rv);
8459 rv = callback2.WaitForResult();
8460 EXPECT_EQ(OK, rv);
8462 response = trans->GetResponseInfo();
8463 ASSERT_TRUE(response != NULL);
8464 EXPECT_TRUE(response->auth_challenge.get() == NULL);
8465 EXPECT_EQ(100, response->headers->GetContentLength());
8468 // Test HTTPS connections going through a proxy that sends extra data.
8469 TEST_P(HttpNetworkTransactionTest, HTTPSViaProxyWithExtraData) {
8470 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
8472 HttpRequestInfo request;
8473 request.method = "GET";
8474 request.url = GURL("https://www.example.org/");
8475 request.load_flags = 0;
8477 MockRead proxy_reads[] = {
8478 MockRead("HTTP/1.0 200 Connected\r\n\r\nExtra data"),
8479 MockRead(SYNCHRONOUS, OK)
8482 StaticSocketDataProvider data(proxy_reads, arraysize(proxy_reads), NULL, 0);
8483 SSLSocketDataProvider ssl(ASYNC, OK);
8485 session_deps_.socket_factory->AddSocketDataProvider(&data);
8486 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
8488 TestCompletionCallback callback;
8490 session_deps_.socket_factory->ResetNextMockIndexes();
8492 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8493 scoped_ptr<HttpTransaction> trans(
8494 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8496 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8497 EXPECT_EQ(ERR_IO_PENDING, rv);
8499 rv = callback.WaitForResult();
8500 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, rv);
8503 TEST_P(HttpNetworkTransactionTest, LargeContentLengthThenClose) {
8504 HttpRequestInfo request;
8505 request.method = "GET";
8506 request.url = GURL("http://www.example.org/");
8507 request.load_flags = 0;
8509 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8510 scoped_ptr<HttpTransaction> trans(
8511 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8513 MockRead data_reads[] = {
8514 MockRead("HTTP/1.0 200 OK\r\nContent-Length:6719476739\r\n\r\n"),
8515 MockRead(SYNCHRONOUS, OK),
8518 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
8519 session_deps_.socket_factory->AddSocketDataProvider(&data);
8521 TestCompletionCallback callback;
8523 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8524 EXPECT_EQ(ERR_IO_PENDING, rv);
8526 EXPECT_EQ(OK, callback.WaitForResult());
8528 const HttpResponseInfo* response = trans->GetResponseInfo();
8529 ASSERT_TRUE(response != NULL);
8531 EXPECT_TRUE(response->headers.get() != NULL);
8532 EXPECT_EQ("HTTP/1.0 200 OK", response->headers->GetStatusLine());
8534 std::string response_data;
8535 rv = ReadTransaction(trans.get(), &response_data);
8536 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, rv);
8539 TEST_P(HttpNetworkTransactionTest, UploadFileSmallerThanLength) {
8540 base::FilePath temp_file_path;
8541 ASSERT_TRUE(base::CreateTemporaryFile(&temp_file_path));
8542 const uint64 kFakeSize = 100000; // file is actually blank
8543 UploadFileElementReader::ScopedOverridingContentLengthForTests
8544 overriding_content_length(kFakeSize);
8546 ScopedVector<UploadElementReader> element_readers;
8547 element_readers.push_back(
8548 new UploadFileElementReader(base::ThreadTaskRunnerHandle::Get().get(),
8549 temp_file_path, 0, kuint64max, base::Time()));
8550 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
8552 HttpRequestInfo request;
8553 request.method = "POST";
8554 request.url = GURL("http://www.example.org/upload");
8555 request.upload_data_stream = &upload_data_stream;
8556 request.load_flags = 0;
8558 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8559 scoped_ptr<HttpTransaction> trans(
8560 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8562 MockRead data_reads[] = {
8563 MockRead("HTTP/1.0 200 OK\r\n\r\n"),
8564 MockRead("hello world"),
8565 MockRead(SYNCHRONOUS, OK),
8567 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
8568 session_deps_.socket_factory->AddSocketDataProvider(&data);
8570 TestCompletionCallback callback;
8572 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8573 EXPECT_EQ(ERR_IO_PENDING, rv);
8575 rv = callback.WaitForResult();
8576 EXPECT_EQ(OK, rv);
8578 const HttpResponseInfo* response = trans->GetResponseInfo();
8579 ASSERT_TRUE(response != NULL);
8581 EXPECT_TRUE(response->headers.get() != NULL);
8582 EXPECT_EQ("HTTP/1.0 200 OK", response->headers->GetStatusLine());
8584 std::string response_data;
8585 rv = ReadTransaction(trans.get(), &response_data);
8586 EXPECT_EQ(OK, rv);
8587 EXPECT_EQ("hello world", response_data);
8589 base::DeleteFile(temp_file_path, false);
8592 TEST_P(HttpNetworkTransactionTest, UploadUnreadableFile) {
8593 base::FilePath temp_file;
8594 ASSERT_TRUE(base::CreateTemporaryFile(&temp_file));
8595 std::string temp_file_content("Unreadable file.");
8596 ASSERT_TRUE(base::WriteFile(temp_file, temp_file_content.c_str(),
8597 temp_file_content.length()));
8598 ASSERT_TRUE(base::MakeFileUnreadable(temp_file));
8600 ScopedVector<UploadElementReader> element_readers;
8601 element_readers.push_back(
8602 new UploadFileElementReader(base::ThreadTaskRunnerHandle::Get().get(),
8603 temp_file, 0, kuint64max, base::Time()));
8604 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
8606 HttpRequestInfo request;
8607 request.method = "POST";
8608 request.url = GURL("http://www.example.org/upload");
8609 request.upload_data_stream = &upload_data_stream;
8610 request.load_flags = 0;
8612 // If we try to upload an unreadable file, the transaction should fail.
8613 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8614 scoped_ptr<HttpTransaction> trans(
8615 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8617 StaticSocketDataProvider data(NULL, 0, NULL, 0);
8618 session_deps_.socket_factory->AddSocketDataProvider(&data);
8620 TestCompletionCallback callback;
8622 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8623 EXPECT_EQ(ERR_IO_PENDING, rv);
8625 rv = callback.WaitForResult();
8626 EXPECT_EQ(ERR_ACCESS_DENIED, rv);
8628 base::DeleteFile(temp_file, false);
8631 TEST_P(HttpNetworkTransactionTest, CancelDuringInitRequestBody) {
8632 class FakeUploadElementReader : public UploadElementReader {
8633 public:
8634 FakeUploadElementReader() {}
8635 ~FakeUploadElementReader() override {}
8637 const CompletionCallback& callback() const { return callback_; }
8639 // UploadElementReader overrides:
8640 int Init(const CompletionCallback& callback) override {
8641 callback_ = callback;
8642 return ERR_IO_PENDING;
8644 uint64 GetContentLength() const override { return 0; }
8645 uint64 BytesRemaining() const override { return 0; }
8646 int Read(IOBuffer* buf,
8647 int buf_length,
8648 const CompletionCallback& callback) override {
8649 return ERR_FAILED;
8652 private:
8653 CompletionCallback callback_;
8656 FakeUploadElementReader* fake_reader = new FakeUploadElementReader;
8657 ScopedVector<UploadElementReader> element_readers;
8658 element_readers.push_back(fake_reader);
8659 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
8661 HttpRequestInfo request;
8662 request.method = "POST";
8663 request.url = GURL("http://www.example.org/upload");
8664 request.upload_data_stream = &upload_data_stream;
8665 request.load_flags = 0;
8667 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8668 scoped_ptr<HttpTransaction> trans(
8669 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8671 StaticSocketDataProvider data;
8672 session_deps_.socket_factory->AddSocketDataProvider(&data);
8674 TestCompletionCallback callback;
8675 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8676 EXPECT_EQ(ERR_IO_PENDING, rv);
8677 base::MessageLoop::current()->RunUntilIdle();
8679 // Transaction is pending on request body initialization.
8680 ASSERT_FALSE(fake_reader->callback().is_null());
8682 // Return Init()'s result after the transaction gets destroyed.
8683 trans.reset();
8684 fake_reader->callback().Run(OK); // Should not crash.
8687 // Tests that changes to Auth realms are treated like auth rejections.
8688 TEST_P(HttpNetworkTransactionTest, ChangeAuthRealms) {
8689 HttpRequestInfo request;
8690 request.method = "GET";
8691 request.url = GURL("http://www.example.org/");
8692 request.load_flags = 0;
8694 // First transaction will request a resource and receive a Basic challenge
8695 // with realm="first_realm".
8696 MockWrite data_writes1[] = {
8697 MockWrite(
8698 "GET / HTTP/1.1\r\n"
8699 "Host: www.example.org\r\n"
8700 "Connection: keep-alive\r\n"
8701 "\r\n"),
8703 MockRead data_reads1[] = {
8704 MockRead("HTTP/1.1 401 Unauthorized\r\n"
8705 "WWW-Authenticate: Basic realm=\"first_realm\"\r\n"
8706 "\r\n"),
8709 // After calling trans->RestartWithAuth(), provide an Authentication header
8710 // for first_realm. The server will reject and provide a challenge with
8711 // second_realm.
8712 MockWrite data_writes2[] = {
8713 MockWrite(
8714 "GET / HTTP/1.1\r\n"
8715 "Host: www.example.org\r\n"
8716 "Connection: keep-alive\r\n"
8717 "Authorization: Basic Zmlyc3Q6YmF6\r\n"
8718 "\r\n"),
8720 MockRead data_reads2[] = {
8721 MockRead("HTTP/1.1 401 Unauthorized\r\n"
8722 "WWW-Authenticate: Basic realm=\"second_realm\"\r\n"
8723 "\r\n"),
8726 // This again fails, and goes back to first_realm. Make sure that the
8727 // entry is removed from cache.
8728 MockWrite data_writes3[] = {
8729 MockWrite(
8730 "GET / HTTP/1.1\r\n"
8731 "Host: www.example.org\r\n"
8732 "Connection: keep-alive\r\n"
8733 "Authorization: Basic c2Vjb25kOmZvdQ==\r\n"
8734 "\r\n"),
8736 MockRead data_reads3[] = {
8737 MockRead("HTTP/1.1 401 Unauthorized\r\n"
8738 "WWW-Authenticate: Basic realm=\"first_realm\"\r\n"
8739 "\r\n"),
8742 // Try one last time (with the correct password) and get the resource.
8743 MockWrite data_writes4[] = {
8744 MockWrite(
8745 "GET / HTTP/1.1\r\n"
8746 "Host: www.example.org\r\n"
8747 "Connection: keep-alive\r\n"
8748 "Authorization: Basic Zmlyc3Q6YmFy\r\n"
8749 "\r\n"),
8751 MockRead data_reads4[] = {
8752 MockRead("HTTP/1.1 200 OK\r\n"
8753 "Content-Type: text/html; charset=iso-8859-1\r\n"
8754 "Content-Length: 5\r\n"
8755 "\r\n"
8756 "hello"),
8759 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
8760 data_writes1, arraysize(data_writes1));
8761 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
8762 data_writes2, arraysize(data_writes2));
8763 StaticSocketDataProvider data3(data_reads3, arraysize(data_reads3),
8764 data_writes3, arraysize(data_writes3));
8765 StaticSocketDataProvider data4(data_reads4, arraysize(data_reads4),
8766 data_writes4, arraysize(data_writes4));
8767 session_deps_.socket_factory->AddSocketDataProvider(&data1);
8768 session_deps_.socket_factory->AddSocketDataProvider(&data2);
8769 session_deps_.socket_factory->AddSocketDataProvider(&data3);
8770 session_deps_.socket_factory->AddSocketDataProvider(&data4);
8772 TestCompletionCallback callback1;
8774 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8775 scoped_ptr<HttpTransaction> trans(
8776 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8778 // Issue the first request with Authorize headers. There should be a
8779 // password prompt for first_realm waiting to be filled in after the
8780 // transaction completes.
8781 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
8782 EXPECT_EQ(ERR_IO_PENDING, rv);
8783 rv = callback1.WaitForResult();
8784 EXPECT_EQ(OK, rv);
8785 const HttpResponseInfo* response = trans->GetResponseInfo();
8786 ASSERT_TRUE(response != NULL);
8787 const AuthChallengeInfo* challenge = response->auth_challenge.get();
8788 ASSERT_FALSE(challenge == NULL);
8789 EXPECT_FALSE(challenge->is_proxy);
8790 EXPECT_EQ("www.example.org:80", challenge->challenger.ToString());
8791 EXPECT_EQ("first_realm", challenge->realm);
8792 EXPECT_EQ("basic", challenge->scheme);
8794 // Issue the second request with an incorrect password. There should be a
8795 // password prompt for second_realm waiting to be filled in after the
8796 // transaction completes.
8797 TestCompletionCallback callback2;
8798 rv = trans->RestartWithAuth(
8799 AuthCredentials(kFirst, kBaz), callback2.callback());
8800 EXPECT_EQ(ERR_IO_PENDING, rv);
8801 rv = callback2.WaitForResult();
8802 EXPECT_EQ(OK, rv);
8803 response = trans->GetResponseInfo();
8804 ASSERT_TRUE(response != NULL);
8805 challenge = response->auth_challenge.get();
8806 ASSERT_FALSE(challenge == NULL);
8807 EXPECT_FALSE(challenge->is_proxy);
8808 EXPECT_EQ("www.example.org:80", challenge->challenger.ToString());
8809 EXPECT_EQ("second_realm", challenge->realm);
8810 EXPECT_EQ("basic", challenge->scheme);
8812 // Issue the third request with another incorrect password. There should be
8813 // a password prompt for first_realm waiting to be filled in. If the password
8814 // prompt is not present, it indicates that the HttpAuthCacheEntry for
8815 // first_realm was not correctly removed.
8816 TestCompletionCallback callback3;
8817 rv = trans->RestartWithAuth(
8818 AuthCredentials(kSecond, kFou), callback3.callback());
8819 EXPECT_EQ(ERR_IO_PENDING, rv);
8820 rv = callback3.WaitForResult();
8821 EXPECT_EQ(OK, rv);
8822 response = trans->GetResponseInfo();
8823 ASSERT_TRUE(response != NULL);
8824 challenge = response->auth_challenge.get();
8825 ASSERT_FALSE(challenge == NULL);
8826 EXPECT_FALSE(challenge->is_proxy);
8827 EXPECT_EQ("www.example.org:80", challenge->challenger.ToString());
8828 EXPECT_EQ("first_realm", challenge->realm);
8829 EXPECT_EQ("basic", challenge->scheme);
8831 // Issue the fourth request with the correct password and username.
8832 TestCompletionCallback callback4;
8833 rv = trans->RestartWithAuth(
8834 AuthCredentials(kFirst, kBar), callback4.callback());
8835 EXPECT_EQ(ERR_IO_PENDING, rv);
8836 rv = callback4.WaitForResult();
8837 EXPECT_EQ(OK, rv);
8838 response = trans->GetResponseInfo();
8839 ASSERT_TRUE(response != NULL);
8840 EXPECT_TRUE(response->auth_challenge.get() == NULL);
8843 TEST_P(HttpNetworkTransactionTest, HonorAlternativeServiceHeader) {
8844 session_deps_.next_protos = SpdyNextProtos();
8845 session_deps_.use_alternative_services = true;
8847 std::string alternative_service_http_header =
8848 GetAlternativeServiceHttpHeader();
8850 MockRead data_reads[] = {
8851 MockRead("HTTP/1.1 200 OK\r\n"),
8852 MockRead(alternative_service_http_header.c_str()),
8853 MockRead("\r\n"),
8854 MockRead("hello world"),
8855 MockRead(SYNCHRONOUS, OK),
8858 HttpRequestInfo request;
8859 request.method = "GET";
8860 request.url = GURL("http://www.example.org/");
8861 request.load_flags = 0;
8863 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
8865 session_deps_.socket_factory->AddSocketDataProvider(&data);
8867 TestCompletionCallback callback;
8869 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8870 scoped_ptr<HttpTransaction> trans(
8871 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8873 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8874 EXPECT_EQ(ERR_IO_PENDING, rv);
8876 HostPortPair http_host_port_pair("www.example.org", 80);
8877 HttpServerProperties& http_server_properties =
8878 *session->http_server_properties();
8879 AlternativeServiceVector alternative_service_vector =
8880 http_server_properties.GetAlternativeServices(http_host_port_pair);
8881 EXPECT_TRUE(alternative_service_vector.empty());
8883 EXPECT_EQ(OK, callback.WaitForResult());
8885 const HttpResponseInfo* response = trans->GetResponseInfo();
8886 ASSERT_TRUE(response != NULL);
8887 ASSERT_TRUE(response->headers.get() != NULL);
8888 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
8889 EXPECT_FALSE(response->was_fetched_via_spdy);
8890 EXPECT_FALSE(response->was_npn_negotiated);
8892 std::string response_data;
8893 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
8894 EXPECT_EQ("hello world", response_data);
8896 alternative_service_vector =
8897 http_server_properties.GetAlternativeServices(http_host_port_pair);
8898 ASSERT_EQ(1u, alternative_service_vector.size());
8899 EXPECT_EQ(AlternateProtocolFromNextProto(GetParam()),
8900 alternative_service_vector[0].protocol);
8901 EXPECT_EQ("www.example.com", alternative_service_vector[0].host);
8902 EXPECT_EQ(443, alternative_service_vector[0].port);
8905 // Alternative Service headers must be ignored when |use_alternative_services|
8906 // is false.
8907 TEST_P(HttpNetworkTransactionTest, DoNotHonorAlternativeServiceHeader) {
8908 session_deps_.next_protos = SpdyNextProtos();
8909 session_deps_.use_alternative_services = false;
8911 std::string alternative_service_http_header =
8912 GetAlternativeServiceHttpHeader();
8914 MockRead data_reads[] = {
8915 MockRead("HTTP/1.1 200 OK\r\n"),
8916 MockRead(alternative_service_http_header.c_str()),
8917 MockRead("\r\n"),
8918 MockRead("hello world"),
8919 MockRead(SYNCHRONOUS, OK),
8922 HttpRequestInfo request;
8923 request.method = "GET";
8924 request.url = GURL("http://www.example.org/");
8925 request.load_flags = 0;
8927 StaticSocketDataProvider data(data_reads, arraysize(data_reads), nullptr, 0);
8929 session_deps_.socket_factory->AddSocketDataProvider(&data);
8931 TestCompletionCallback callback;
8933 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8934 scoped_ptr<HttpTransaction> trans(
8935 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8937 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8938 EXPECT_EQ(ERR_IO_PENDING, rv);
8940 HostPortPair http_host_port_pair("www.example.org", 80);
8941 HttpServerProperties& http_server_properties =
8942 *session->http_server_properties();
8943 AlternativeServiceVector alternative_service_vector =
8944 http_server_properties.GetAlternativeServices(http_host_port_pair);
8945 EXPECT_TRUE(alternative_service_vector.empty());
8947 EXPECT_EQ(OK, callback.WaitForResult());
8949 const HttpResponseInfo* response = trans->GetResponseInfo();
8950 ASSERT_TRUE(response != nullptr);
8951 ASSERT_TRUE(response->headers.get() != nullptr);
8952 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
8953 EXPECT_FALSE(response->was_fetched_via_spdy);
8954 EXPECT_FALSE(response->was_npn_negotiated);
8956 std::string response_data;
8957 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
8958 EXPECT_EQ("hello world", response_data);
8960 alternative_service_vector =
8961 http_server_properties.GetAlternativeServices(http_host_port_pair);
8962 EXPECT_TRUE(alternative_service_vector.empty());
8965 TEST_P(HttpNetworkTransactionTest, HonorMultipleAlternativeServiceHeader) {
8966 session_deps_.next_protos = SpdyNextProtos();
8967 session_deps_.use_alternative_services = true;
8969 MockRead data_reads[] = {
8970 MockRead("HTTP/1.1 200 OK\r\n"),
8971 MockRead("Alt-Svc: "),
8972 MockRead(GetAlternateProtocolFromParam()),
8973 MockRead("=\"www.example.com:443\";p=1.0,"),
8974 MockRead("quic=\":1234\"\r\n\r\n"),
8975 MockRead("hello world"),
8976 MockRead(SYNCHRONOUS, OK),
8979 HttpRequestInfo request;
8980 request.method = "GET";
8981 request.url = GURL("http://www.example.org/");
8982 request.load_flags = 0;
8984 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
8986 session_deps_.socket_factory->AddSocketDataProvider(&data);
8988 TestCompletionCallback callback;
8990 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8991 scoped_ptr<HttpTransaction> trans(
8992 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8994 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8995 EXPECT_EQ(ERR_IO_PENDING, rv);
8997 HostPortPair http_host_port_pair("www.example.org", 80);
8998 HttpServerProperties& http_server_properties =
8999 *session->http_server_properties();
9000 AlternativeServiceVector alternative_service_vector =
9001 http_server_properties.GetAlternativeServices(http_host_port_pair);
9002 EXPECT_TRUE(alternative_service_vector.empty());
9004 EXPECT_EQ(OK, callback.WaitForResult());
9006 const HttpResponseInfo* response = trans->GetResponseInfo();
9007 ASSERT_TRUE(response != NULL);
9008 ASSERT_TRUE(response->headers.get() != NULL);
9009 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9010 EXPECT_FALSE(response->was_fetched_via_spdy);
9011 EXPECT_FALSE(response->was_npn_negotiated);
9013 std::string response_data;
9014 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9015 EXPECT_EQ("hello world", response_data);
9017 alternative_service_vector =
9018 http_server_properties.GetAlternativeServices(http_host_port_pair);
9019 ASSERT_EQ(2u, alternative_service_vector.size());
9020 EXPECT_EQ(AlternateProtocolFromNextProto(GetParam()),
9021 alternative_service_vector[0].protocol);
9022 EXPECT_EQ("www.example.com", alternative_service_vector[0].host);
9023 EXPECT_EQ(443, alternative_service_vector[0].port);
9024 EXPECT_EQ(QUIC, alternative_service_vector[1].protocol);
9025 EXPECT_EQ("www.example.org", alternative_service_vector[1].host);
9026 EXPECT_EQ(1234, alternative_service_vector[1].port);
9029 // Alternate Protocol headers must be honored even if |use_alternative_services|
9030 // is false.
9031 TEST_P(HttpNetworkTransactionTest, HonorAlternateProtocolHeader) {
9032 session_deps_.next_protos = SpdyNextProtos();
9033 session_deps_.use_alternative_services = false;
9035 std::string alternate_protocol_http_header =
9036 GetAlternateProtocolHttpHeader();
9038 MockRead data_reads[] = {
9039 MockRead("HTTP/1.1 200 OK\r\n"),
9040 MockRead(alternate_protocol_http_header.c_str()),
9041 MockRead("\r\n"),
9042 MockRead("hello world"),
9043 MockRead(SYNCHRONOUS, OK),
9046 HttpRequestInfo request;
9047 request.method = "GET";
9048 request.url = GURL("http://www.example.org/");
9049 request.load_flags = 0;
9051 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
9053 session_deps_.socket_factory->AddSocketDataProvider(&data);
9055 TestCompletionCallback callback;
9057 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9058 scoped_ptr<HttpTransaction> trans(
9059 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9061 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
9062 EXPECT_EQ(ERR_IO_PENDING, rv);
9064 HostPortPair http_host_port_pair("www.example.org", 80);
9065 HttpServerProperties& http_server_properties =
9066 *session->http_server_properties();
9067 AlternativeServiceVector alternative_service_vector =
9068 http_server_properties.GetAlternativeServices(http_host_port_pair);
9069 EXPECT_TRUE(alternative_service_vector.empty());
9071 EXPECT_EQ(OK, callback.WaitForResult());
9073 const HttpResponseInfo* response = trans->GetResponseInfo();
9074 ASSERT_TRUE(response != NULL);
9075 ASSERT_TRUE(response->headers.get() != NULL);
9076 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9077 EXPECT_FALSE(response->was_fetched_via_spdy);
9078 EXPECT_FALSE(response->was_npn_negotiated);
9080 std::string response_data;
9081 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9082 EXPECT_EQ("hello world", response_data);
9084 alternative_service_vector =
9085 http_server_properties.GetAlternativeServices(http_host_port_pair);
9086 ASSERT_EQ(1u, alternative_service_vector.size());
9087 EXPECT_EQ(443, alternative_service_vector[0].port);
9088 EXPECT_EQ(AlternateProtocolFromNextProto(GetParam()),
9089 alternative_service_vector[0].protocol);
9092 TEST_P(HttpNetworkTransactionTest, EmptyAlternateProtocolHeader) {
9093 session_deps_.next_protos = SpdyNextProtos();
9094 session_deps_.use_alternative_services = true;
9096 MockRead data_reads[] = {
9097 MockRead("HTTP/1.1 200 OK\r\n"),
9098 MockRead("Alternate-Protocol: \r\n\r\n"),
9099 MockRead("hello world"),
9100 MockRead(SYNCHRONOUS, OK),
9103 HttpRequestInfo request;
9104 request.method = "GET";
9105 request.url = GURL("http://www.example.org/");
9106 request.load_flags = 0;
9108 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
9110 session_deps_.socket_factory->AddSocketDataProvider(&data);
9112 TestCompletionCallback callback;
9114 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9116 HostPortPair http_host_port_pair("www.example.org", 80);
9117 HttpServerProperties& http_server_properties =
9118 *session->http_server_properties();
9119 AlternativeService alternative_service(QUIC, "", 80);
9120 base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
9121 http_server_properties.SetAlternativeService(
9122 http_host_port_pair, alternative_service, 1.0, expiration);
9124 AlternativeServiceVector alternative_service_vector =
9125 http_server_properties.GetAlternativeServices(http_host_port_pair);
9126 ASSERT_EQ(1u, alternative_service_vector.size());
9127 EXPECT_EQ(QUIC, alternative_service_vector[0].protocol);
9129 scoped_ptr<HttpTransaction> trans(
9130 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9132 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
9133 EXPECT_EQ(ERR_IO_PENDING, rv);
9135 EXPECT_EQ(OK, callback.WaitForResult());
9137 const HttpResponseInfo* response = trans->GetResponseInfo();
9138 ASSERT_TRUE(response != NULL);
9139 ASSERT_TRUE(response->headers.get() != NULL);
9140 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9141 EXPECT_FALSE(response->was_fetched_via_spdy);
9142 EXPECT_FALSE(response->was_npn_negotiated);
9144 std::string response_data;
9145 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9146 EXPECT_EQ("hello world", response_data);
9148 alternative_service_vector =
9149 http_server_properties.GetAlternativeServices(http_host_port_pair);
9150 EXPECT_TRUE(alternative_service_vector.empty());
9153 TEST_P(HttpNetworkTransactionTest, AltSvcOverwritesAlternateProtocol) {
9154 session_deps_.next_protos = SpdyNextProtos();
9155 session_deps_.use_alternative_services = true;
9157 std::string alternative_service_http_header =
9158 GetAlternativeServiceHttpHeader();
9159 std::string alternate_protocol_http_header = GetAlternateProtocolHttpHeader();
9161 MockRead data_reads[] = {
9162 MockRead("HTTP/1.1 200 OK\r\n"),
9163 MockRead(alternative_service_http_header.c_str()),
9164 MockRead(alternate_protocol_http_header.c_str()),
9165 MockRead("\r\n"),
9166 MockRead("hello world"),
9167 MockRead(SYNCHRONOUS, OK),
9170 HttpRequestInfo request;
9171 request.method = "GET";
9172 request.url = GURL("http://www.example.org/");
9173 request.load_flags = 0;
9175 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
9177 session_deps_.socket_factory->AddSocketDataProvider(&data);
9179 TestCompletionCallback callback;
9181 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9182 scoped_ptr<HttpTransaction> trans(
9183 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9185 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
9186 EXPECT_EQ(ERR_IO_PENDING, rv);
9188 HostPortPair http_host_port_pair("www.example.org", 80);
9189 HttpServerProperties& http_server_properties =
9190 *session->http_server_properties();
9191 AlternativeServiceVector alternative_service_vector =
9192 http_server_properties.GetAlternativeServices(http_host_port_pair);
9193 EXPECT_TRUE(alternative_service_vector.empty());
9195 EXPECT_EQ(OK, callback.WaitForResult());
9197 const HttpResponseInfo* response = trans->GetResponseInfo();
9198 ASSERT_TRUE(response != NULL);
9199 ASSERT_TRUE(response->headers.get() != NULL);
9200 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9201 EXPECT_FALSE(response->was_fetched_via_spdy);
9202 EXPECT_FALSE(response->was_npn_negotiated);
9204 std::string response_data;
9205 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9206 EXPECT_EQ("hello world", response_data);
9208 alternative_service_vector =
9209 http_server_properties.GetAlternativeServices(http_host_port_pair);
9210 ASSERT_EQ(1u, alternative_service_vector.size());
9211 EXPECT_EQ(AlternateProtocolFromNextProto(GetParam()),
9212 alternative_service_vector[0].protocol);
9213 EXPECT_EQ("www.example.com", alternative_service_vector[0].host);
9214 EXPECT_EQ(443, alternative_service_vector[0].port);
9217 // When |use_alternative_services| is false, do not observe alternative service
9218 // entries that point to a different host.
9219 TEST_P(HttpNetworkTransactionTest, DisableAlternativeServiceToDifferentHost) {
9220 session_deps_.use_alternative_services = false;
9222 HttpRequestInfo request;
9223 request.method = "GET";
9224 request.url = GURL("http://www.example.org/");
9225 request.load_flags = 0;
9227 MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
9228 StaticSocketDataProvider first_data;
9229 first_data.set_connect_data(mock_connect);
9230 session_deps_.socket_factory->AddSocketDataProvider(&first_data);
9232 MockRead data_reads[] = {
9233 MockRead("HTTP/1.1 200 OK\r\n\r\n"), MockRead("hello world"),
9234 MockRead(ASYNC, OK),
9236 StaticSocketDataProvider second_data(data_reads, arraysize(data_reads),
9237 nullptr, 0);
9238 session_deps_.socket_factory->AddSocketDataProvider(&second_data);
9240 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9242 base::WeakPtr<HttpServerProperties> http_server_properties =
9243 session->http_server_properties();
9244 AlternativeService alternative_service(
9245 AlternateProtocolFromNextProto(GetParam()), "different.example.org", 80);
9246 base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
9247 http_server_properties->SetAlternativeService(
9248 HostPortPair::FromURL(request.url), alternative_service, 1.0, expiration);
9250 scoped_ptr<HttpTransaction> trans(
9251 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9252 TestCompletionCallback callback;
9254 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
9255 // The connetion to origin was refused, and the alternative service should not
9256 // be used (even though mock data are there), therefore the request should
9257 // fail.
9258 EXPECT_EQ(ERR_CONNECTION_REFUSED, callback.GetResult(rv));
9261 TEST_P(HttpNetworkTransactionTest,
9262 MarkBrokenAlternateProtocolAndFallback) {
9263 session_deps_.use_alternative_services = true;
9265 HttpRequestInfo request;
9266 request.method = "GET";
9267 request.url = GURL("http://www.example.org/");
9268 request.load_flags = 0;
9270 MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
9271 StaticSocketDataProvider first_data;
9272 first_data.set_connect_data(mock_connect);
9273 session_deps_.socket_factory->AddSocketDataProvider(&first_data);
9275 MockRead data_reads[] = {
9276 MockRead("HTTP/1.1 200 OK\r\n\r\n"),
9277 MockRead("hello world"),
9278 MockRead(ASYNC, OK),
9280 StaticSocketDataProvider second_data(
9281 data_reads, arraysize(data_reads), NULL, 0);
9282 session_deps_.socket_factory->AddSocketDataProvider(&second_data);
9284 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9286 base::WeakPtr<HttpServerProperties> http_server_properties =
9287 session->http_server_properties();
9288 const HostPortPair host_port_pair = HostPortPair::FromURL(request.url);
9289 // Port must be < 1024, or the header will be ignored (since initial port was
9290 // port 80 (another restricted port).
9291 const AlternativeService alternative_service(
9292 AlternateProtocolFromNextProto(GetParam()), "www.example.org",
9293 666); // Port is ignored by MockConnect anyway.
9294 base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
9295 http_server_properties->SetAlternativeService(
9296 host_port_pair, alternative_service, 1.0, expiration);
9298 scoped_ptr<HttpTransaction> trans(
9299 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9300 TestCompletionCallback callback;
9302 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
9303 EXPECT_EQ(ERR_IO_PENDING, rv);
9304 EXPECT_EQ(OK, callback.WaitForResult());
9306 const HttpResponseInfo* response = trans->GetResponseInfo();
9307 ASSERT_TRUE(response != NULL);
9308 ASSERT_TRUE(response->headers.get() != NULL);
9309 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9311 std::string response_data;
9312 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9313 EXPECT_EQ("hello world", response_data);
9315 const AlternativeServiceVector alternative_service_vector =
9316 http_server_properties->GetAlternativeServices(host_port_pair);
9317 ASSERT_EQ(1u, alternative_service_vector.size());
9318 EXPECT_EQ(alternative_service, alternative_service_vector[0]);
9319 EXPECT_TRUE(http_server_properties->IsAlternativeServiceBroken(
9320 alternative_service_vector[0]));
9323 // Ensure that we are not allowed to redirect traffic via an alternate protocol
9324 // to an unrestricted (port >= 1024) when the original traffic was on a
9325 // restricted port (port < 1024). Ensure that we can redirect in all other
9326 // cases.
9327 TEST_P(HttpNetworkTransactionTest,
9328 AlternateProtocolPortRestrictedBlocked) {
9329 session_deps_.use_alternative_services = true;
9331 HttpRequestInfo restricted_port_request;
9332 restricted_port_request.method = "GET";
9333 restricted_port_request.url = GURL("http://www.example.org:1023/");
9334 restricted_port_request.load_flags = 0;
9336 MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
9337 StaticSocketDataProvider first_data;
9338 first_data.set_connect_data(mock_connect);
9339 session_deps_.socket_factory->AddSocketDataProvider(&first_data);
9341 MockRead data_reads[] = {
9342 MockRead("HTTP/1.1 200 OK\r\n\r\n"),
9343 MockRead("hello world"),
9344 MockRead(ASYNC, OK),
9346 StaticSocketDataProvider second_data(
9347 data_reads, arraysize(data_reads), NULL, 0);
9348 session_deps_.socket_factory->AddSocketDataProvider(&second_data);
9350 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9352 base::WeakPtr<HttpServerProperties> http_server_properties =
9353 session->http_server_properties();
9354 const int kUnrestrictedAlternatePort = 1024;
9355 AlternativeService alternative_service(
9356 AlternateProtocolFromNextProto(GetParam()), "www.example.org",
9357 kUnrestrictedAlternatePort);
9358 base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
9359 http_server_properties->SetAlternativeService(
9360 HostPortPair::FromURL(restricted_port_request.url), alternative_service,
9361 1.0, expiration);
9363 scoped_ptr<HttpTransaction> trans(
9364 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9365 TestCompletionCallback callback;
9367 int rv = trans->Start(
9368 &restricted_port_request,
9369 callback.callback(), BoundNetLog());
9370 EXPECT_EQ(ERR_IO_PENDING, rv);
9371 // Invalid change to unrestricted port should fail.
9372 EXPECT_EQ(ERR_CONNECTION_REFUSED, callback.WaitForResult());
9375 // Ensure that we are allowed to redirect traffic via an alternate protocol to
9376 // an unrestricted (port >= 1024) when the original traffic was on a restricted
9377 // port (port < 1024) if we set |enable_user_alternate_protocol_ports|.
9378 TEST_P(HttpNetworkTransactionTest,
9379 AlternateProtocolPortRestrictedPermitted) {
9380 session_deps_.use_alternative_services = true;
9381 session_deps_.enable_user_alternate_protocol_ports = true;
9383 HttpRequestInfo restricted_port_request;
9384 restricted_port_request.method = "GET";
9385 restricted_port_request.url = GURL("http://www.example.org:1023/");
9386 restricted_port_request.load_flags = 0;
9388 MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
9389 StaticSocketDataProvider first_data;
9390 first_data.set_connect_data(mock_connect);
9391 session_deps_.socket_factory->AddSocketDataProvider(&first_data);
9393 MockRead data_reads[] = {
9394 MockRead("HTTP/1.1 200 OK\r\n\r\n"),
9395 MockRead("hello world"),
9396 MockRead(ASYNC, OK),
9398 StaticSocketDataProvider second_data(
9399 data_reads, arraysize(data_reads), NULL, 0);
9400 session_deps_.socket_factory->AddSocketDataProvider(&second_data);
9402 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9404 base::WeakPtr<HttpServerProperties> http_server_properties =
9405 session->http_server_properties();
9406 const int kUnrestrictedAlternatePort = 1024;
9407 AlternativeService alternative_service(
9408 AlternateProtocolFromNextProto(GetParam()), "www.example.org",
9409 kUnrestrictedAlternatePort);
9410 base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
9411 http_server_properties->SetAlternativeService(
9412 HostPortPair::FromURL(restricted_port_request.url), alternative_service,
9413 1.0, expiration);
9415 scoped_ptr<HttpTransaction> trans(
9416 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9417 TestCompletionCallback callback;
9419 EXPECT_EQ(ERR_IO_PENDING, trans->Start(
9420 &restricted_port_request,
9421 callback.callback(), BoundNetLog()));
9422 // Change to unrestricted port should succeed.
9423 EXPECT_EQ(OK, callback.WaitForResult());
9426 // Ensure that we are not allowed to redirect traffic via an alternate protocol
9427 // to an unrestricted (port >= 1024) when the original traffic was on a
9428 // restricted port (port < 1024). Ensure that we can redirect in all other
9429 // cases.
9430 TEST_P(HttpNetworkTransactionTest,
9431 AlternateProtocolPortRestrictedAllowed) {
9432 session_deps_.use_alternative_services = true;
9434 HttpRequestInfo restricted_port_request;
9435 restricted_port_request.method = "GET";
9436 restricted_port_request.url = GURL("http://www.example.org:1023/");
9437 restricted_port_request.load_flags = 0;
9439 MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
9440 StaticSocketDataProvider first_data;
9441 first_data.set_connect_data(mock_connect);
9442 session_deps_.socket_factory->AddSocketDataProvider(&first_data);
9444 MockRead data_reads[] = {
9445 MockRead("HTTP/1.1 200 OK\r\n\r\n"),
9446 MockRead("hello world"),
9447 MockRead(ASYNC, OK),
9449 StaticSocketDataProvider second_data(
9450 data_reads, arraysize(data_reads), NULL, 0);
9451 session_deps_.socket_factory->AddSocketDataProvider(&second_data);
9453 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9455 base::WeakPtr<HttpServerProperties> http_server_properties =
9456 session->http_server_properties();
9457 const int kRestrictedAlternatePort = 80;
9458 AlternativeService alternative_service(
9459 AlternateProtocolFromNextProto(GetParam()), "www.example.org",
9460 kRestrictedAlternatePort);
9461 base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
9462 http_server_properties->SetAlternativeService(
9463 HostPortPair::FromURL(restricted_port_request.url), alternative_service,
9464 1.0, expiration);
9466 scoped_ptr<HttpTransaction> trans(
9467 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9468 TestCompletionCallback callback;
9470 int rv = trans->Start(
9471 &restricted_port_request,
9472 callback.callback(), BoundNetLog());
9473 EXPECT_EQ(ERR_IO_PENDING, rv);
9474 // Valid change to restricted port should pass.
9475 EXPECT_EQ(OK, callback.WaitForResult());
9478 // Ensure that we are not allowed to redirect traffic via an alternate protocol
9479 // to an unrestricted (port >= 1024) when the original traffic was on a
9480 // restricted port (port < 1024). Ensure that we can redirect in all other
9481 // cases.
9482 TEST_P(HttpNetworkTransactionTest,
9483 AlternateProtocolPortUnrestrictedAllowed1) {
9484 session_deps_.use_alternative_services = true;
9486 HttpRequestInfo unrestricted_port_request;
9487 unrestricted_port_request.method = "GET";
9488 unrestricted_port_request.url = GURL("http://www.example.org:1024/");
9489 unrestricted_port_request.load_flags = 0;
9491 MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
9492 StaticSocketDataProvider first_data;
9493 first_data.set_connect_data(mock_connect);
9494 session_deps_.socket_factory->AddSocketDataProvider(&first_data);
9496 MockRead data_reads[] = {
9497 MockRead("HTTP/1.1 200 OK\r\n\r\n"),
9498 MockRead("hello world"),
9499 MockRead(ASYNC, OK),
9501 StaticSocketDataProvider second_data(
9502 data_reads, arraysize(data_reads), NULL, 0);
9503 session_deps_.socket_factory->AddSocketDataProvider(&second_data);
9505 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9507 base::WeakPtr<HttpServerProperties> http_server_properties =
9508 session->http_server_properties();
9509 const int kRestrictedAlternatePort = 80;
9510 AlternativeService alternative_service(
9511 AlternateProtocolFromNextProto(GetParam()), "www.example.org",
9512 kRestrictedAlternatePort);
9513 base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
9514 http_server_properties->SetAlternativeService(
9515 HostPortPair::FromURL(unrestricted_port_request.url), alternative_service,
9516 1.0, expiration);
9518 scoped_ptr<HttpTransaction> trans(
9519 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9520 TestCompletionCallback callback;
9522 int rv = trans->Start(
9523 &unrestricted_port_request, callback.callback(), BoundNetLog());
9524 EXPECT_EQ(ERR_IO_PENDING, rv);
9525 // Valid change to restricted port should pass.
9526 EXPECT_EQ(OK, callback.WaitForResult());
9529 // Ensure that we are not allowed to redirect traffic via an alternate protocol
9530 // to an unrestricted (port >= 1024) when the original traffic was on a
9531 // restricted port (port < 1024). Ensure that we can redirect in all other
9532 // cases.
9533 TEST_P(HttpNetworkTransactionTest,
9534 AlternateProtocolPortUnrestrictedAllowed2) {
9535 session_deps_.use_alternative_services = true;
9537 HttpRequestInfo unrestricted_port_request;
9538 unrestricted_port_request.method = "GET";
9539 unrestricted_port_request.url = GURL("http://www.example.org:1024/");
9540 unrestricted_port_request.load_flags = 0;
9542 MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
9543 StaticSocketDataProvider first_data;
9544 first_data.set_connect_data(mock_connect);
9545 session_deps_.socket_factory->AddSocketDataProvider(&first_data);
9547 MockRead data_reads[] = {
9548 MockRead("HTTP/1.1 200 OK\r\n\r\n"),
9549 MockRead("hello world"),
9550 MockRead(ASYNC, OK),
9552 StaticSocketDataProvider second_data(
9553 data_reads, arraysize(data_reads), NULL, 0);
9554 session_deps_.socket_factory->AddSocketDataProvider(&second_data);
9556 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9558 base::WeakPtr<HttpServerProperties> http_server_properties =
9559 session->http_server_properties();
9560 const int kUnrestrictedAlternatePort = 1025;
9561 AlternativeService alternative_service(
9562 AlternateProtocolFromNextProto(GetParam()), "www.example.org",
9563 kUnrestrictedAlternatePort);
9564 base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
9565 http_server_properties->SetAlternativeService(
9566 HostPortPair::FromURL(unrestricted_port_request.url), alternative_service,
9567 1.0, expiration);
9569 scoped_ptr<HttpTransaction> trans(
9570 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9571 TestCompletionCallback callback;
9573 int rv = trans->Start(
9574 &unrestricted_port_request, callback.callback(), BoundNetLog());
9575 EXPECT_EQ(ERR_IO_PENDING, rv);
9576 // Valid change to an unrestricted port should pass.
9577 EXPECT_EQ(OK, callback.WaitForResult());
9580 // Ensure that we are not allowed to redirect traffic via an alternate protocol
9581 // to an unsafe port, and that we resume the second HttpStreamFactoryImpl::Job
9582 // once the alternate protocol request fails.
9583 TEST_P(HttpNetworkTransactionTest, AlternateProtocolUnsafeBlocked) {
9584 session_deps_.use_alternative_services = true;
9586 HttpRequestInfo request;
9587 request.method = "GET";
9588 request.url = GURL("http://www.example.org/");
9589 request.load_flags = 0;
9591 // The alternate protocol request will error out before we attempt to connect,
9592 // so only the standard HTTP request will try to connect.
9593 MockRead data_reads[] = {
9594 MockRead("HTTP/1.1 200 OK\r\n\r\n"),
9595 MockRead("hello world"),
9596 MockRead(ASYNC, OK),
9598 StaticSocketDataProvider data(
9599 data_reads, arraysize(data_reads), NULL, 0);
9600 session_deps_.socket_factory->AddSocketDataProvider(&data);
9602 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9604 base::WeakPtr<HttpServerProperties> http_server_properties =
9605 session->http_server_properties();
9606 const int kUnsafePort = 7;
9607 AlternativeService alternative_service(
9608 AlternateProtocolFromNextProto(GetParam()), "www.example.org",
9609 kUnsafePort);
9610 base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
9611 http_server_properties->SetAlternativeService(
9612 HostPortPair::FromURL(request.url), alternative_service, 1.0, expiration);
9614 scoped_ptr<HttpTransaction> trans(
9615 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9616 TestCompletionCallback callback;
9618 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
9619 EXPECT_EQ(ERR_IO_PENDING, rv);
9620 // The HTTP request should succeed.
9621 EXPECT_EQ(OK, callback.WaitForResult());
9623 const HttpResponseInfo* response = trans->GetResponseInfo();
9624 ASSERT_TRUE(response != NULL);
9625 ASSERT_TRUE(response->headers.get() != NULL);
9626 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9628 std::string response_data;
9629 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9630 EXPECT_EQ("hello world", response_data);
9633 TEST_P(HttpNetworkTransactionTest, UseAlternateProtocolForNpnSpdy) {
9634 session_deps_.use_alternative_services = true;
9635 session_deps_.next_protos = SpdyNextProtos();
9637 HttpRequestInfo request;
9638 request.method = "GET";
9639 request.url = GURL("http://www.example.org/");
9640 request.load_flags = 0;
9642 std::string alternate_protocol_http_header =
9643 GetAlternateProtocolHttpHeader();
9645 MockRead data_reads[] = {
9646 MockRead("HTTP/1.1 200 OK\r\n"),
9647 MockRead(alternate_protocol_http_header.c_str()),
9648 MockRead("\r\n"),
9649 MockRead("hello world"),
9650 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
9651 MockRead(ASYNC, OK)};
9653 StaticSocketDataProvider first_transaction(
9654 data_reads, arraysize(data_reads), NULL, 0);
9655 session_deps_.socket_factory->AddSocketDataProvider(&first_transaction);
9657 SSLSocketDataProvider ssl(ASYNC, OK);
9658 ssl.SetNextProto(GetParam());
9659 ssl.cert = ImportCertFromFile(GetTestCertsDirectory(), "spdy_pooling.pem");
9660 ASSERT_TRUE(ssl.cert.get());
9661 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
9663 scoped_ptr<SpdyFrame> req(
9664 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, true));
9665 MockWrite spdy_writes[] = {CreateMockWrite(*req, 0)};
9667 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
9668 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
9669 MockRead spdy_reads[] = {
9670 CreateMockRead(*resp, 1), CreateMockRead(*data, 2), MockRead(ASYNC, 0, 3),
9673 SequencedSocketData spdy_data(spdy_reads, arraysize(spdy_reads), spdy_writes,
9674 arraysize(spdy_writes));
9675 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
9677 MockConnect never_finishing_connect(SYNCHRONOUS, ERR_IO_PENDING);
9678 StaticSocketDataProvider hanging_non_alternate_protocol_socket(
9679 NULL, 0, NULL, 0);
9680 hanging_non_alternate_protocol_socket.set_connect_data(
9681 never_finishing_connect);
9682 session_deps_.socket_factory->AddSocketDataProvider(
9683 &hanging_non_alternate_protocol_socket);
9685 TestCompletionCallback callback;
9687 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9688 scoped_ptr<HttpTransaction> trans(
9689 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9691 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
9692 EXPECT_EQ(ERR_IO_PENDING, rv);
9693 EXPECT_EQ(OK, callback.WaitForResult());
9695 const HttpResponseInfo* response = trans->GetResponseInfo();
9696 ASSERT_TRUE(response != NULL);
9697 ASSERT_TRUE(response->headers.get() != NULL);
9698 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9700 std::string response_data;
9701 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9702 EXPECT_EQ("hello world", response_data);
9704 trans.reset(new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9706 rv = trans->Start(&request, callback.callback(), BoundNetLog());
9707 EXPECT_EQ(ERR_IO_PENDING, rv);
9708 EXPECT_EQ(OK, callback.WaitForResult());
9710 response = trans->GetResponseInfo();
9711 ASSERT_TRUE(response != NULL);
9712 ASSERT_TRUE(response->headers.get() != NULL);
9713 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9714 EXPECT_TRUE(response->was_fetched_via_spdy);
9715 EXPECT_TRUE(response->was_npn_negotiated);
9717 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9718 EXPECT_EQ("hello!", response_data);
9721 TEST_P(HttpNetworkTransactionTest, AlternateProtocolWithSpdyLateBinding) {
9722 session_deps_.use_alternative_services = true;
9723 session_deps_.next_protos = SpdyNextProtos();
9725 HttpRequestInfo request;
9726 request.method = "GET";
9727 request.url = GURL("http://www.example.org/");
9728 request.load_flags = 0;
9730 std::string alternate_protocol_http_header =
9731 GetAlternateProtocolHttpHeader();
9733 MockRead data_reads[] = {
9734 MockRead("HTTP/1.1 200 OK\r\n"),
9735 MockRead(alternate_protocol_http_header.c_str()),
9736 MockRead("\r\n"),
9737 MockRead("hello world"),
9738 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
9739 MockRead(ASYNC, OK),
9742 StaticSocketDataProvider first_transaction(
9743 data_reads, arraysize(data_reads), NULL, 0);
9744 // Socket 1 is the HTTP transaction with the Alternate-Protocol header.
9745 session_deps_.socket_factory->AddSocketDataProvider(&first_transaction);
9747 MockConnect never_finishing_connect(SYNCHRONOUS, ERR_IO_PENDING);
9748 StaticSocketDataProvider hanging_socket(
9749 NULL, 0, NULL, 0);
9750 hanging_socket.set_connect_data(never_finishing_connect);
9751 // Socket 2 and 3 are the hanging Alternate-Protocol and
9752 // non-Alternate-Protocol jobs from the 2nd transaction.
9753 session_deps_.socket_factory->AddSocketDataProvider(&hanging_socket);
9754 session_deps_.socket_factory->AddSocketDataProvider(&hanging_socket);
9756 SSLSocketDataProvider ssl(ASYNC, OK);
9757 ssl.SetNextProto(GetParam());
9758 ssl.cert = ImportCertFromFile(GetTestCertsDirectory(), "spdy_pooling.pem");
9759 ASSERT_TRUE(ssl.cert.get());
9760 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
9762 scoped_ptr<SpdyFrame> req1(
9763 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, true));
9764 scoped_ptr<SpdyFrame> req2(
9765 spdy_util_.ConstructSpdyGet(NULL, 0, false, 3, LOWEST, true));
9766 MockWrite spdy_writes[] = {
9767 CreateMockWrite(*req1, 0), CreateMockWrite(*req2, 1),
9769 scoped_ptr<SpdyFrame> resp1(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
9770 scoped_ptr<SpdyFrame> data1(spdy_util_.ConstructSpdyBodyFrame(1, true));
9771 scoped_ptr<SpdyFrame> resp2(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
9772 scoped_ptr<SpdyFrame> data2(spdy_util_.ConstructSpdyBodyFrame(3, true));
9773 MockRead spdy_reads[] = {
9774 CreateMockRead(*resp1, 2),
9775 CreateMockRead(*data1, 3),
9776 CreateMockRead(*resp2, 4),
9777 CreateMockRead(*data2, 5),
9778 MockRead(ASYNC, 0, 6),
9781 SequencedSocketData spdy_data(spdy_reads, arraysize(spdy_reads), spdy_writes,
9782 arraysize(spdy_writes));
9783 // Socket 4 is the successful Alternate-Protocol for transaction 3.
9784 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
9786 // Socket 5 is the unsuccessful non-Alternate-Protocol for transaction 3.
9787 session_deps_.socket_factory->AddSocketDataProvider(&hanging_socket);
9789 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9790 TestCompletionCallback callback1;
9791 HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
9793 int rv = trans1.Start(&request, callback1.callback(), BoundNetLog());
9794 EXPECT_EQ(ERR_IO_PENDING, rv);
9795 EXPECT_EQ(OK, callback1.WaitForResult());
9797 const HttpResponseInfo* response = trans1.GetResponseInfo();
9798 ASSERT_TRUE(response != NULL);
9799 ASSERT_TRUE(response->headers.get() != NULL);
9800 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9802 std::string response_data;
9803 ASSERT_EQ(OK, ReadTransaction(&trans1, &response_data));
9804 EXPECT_EQ("hello world", response_data);
9806 TestCompletionCallback callback2;
9807 HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
9808 rv = trans2.Start(&request, callback2.callback(), BoundNetLog());
9809 EXPECT_EQ(ERR_IO_PENDING, rv);
9811 TestCompletionCallback callback3;
9812 HttpNetworkTransaction trans3(DEFAULT_PRIORITY, session.get());
9813 rv = trans3.Start(&request, callback3.callback(), BoundNetLog());
9814 EXPECT_EQ(ERR_IO_PENDING, rv);
9816 EXPECT_EQ(OK, callback2.WaitForResult());
9817 EXPECT_EQ(OK, callback3.WaitForResult());
9819 response = trans2.GetResponseInfo();
9820 ASSERT_TRUE(response != NULL);
9821 ASSERT_TRUE(response->headers.get() != NULL);
9822 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9823 EXPECT_TRUE(response->was_fetched_via_spdy);
9824 EXPECT_TRUE(response->was_npn_negotiated);
9825 ASSERT_EQ(OK, ReadTransaction(&trans2, &response_data));
9826 EXPECT_EQ("hello!", response_data);
9828 response = trans3.GetResponseInfo();
9829 ASSERT_TRUE(response != NULL);
9830 ASSERT_TRUE(response->headers.get() != NULL);
9831 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9832 EXPECT_TRUE(response->was_fetched_via_spdy);
9833 EXPECT_TRUE(response->was_npn_negotiated);
9834 ASSERT_EQ(OK, ReadTransaction(&trans3, &response_data));
9835 EXPECT_EQ("hello!", response_data);
9838 TEST_P(HttpNetworkTransactionTest, StallAlternateProtocolForNpnSpdy) {
9839 session_deps_.use_alternative_services = true;
9840 session_deps_.next_protos = SpdyNextProtos();
9842 HttpRequestInfo request;
9843 request.method = "GET";
9844 request.url = GURL("http://www.example.org/");
9845 request.load_flags = 0;
9847 std::string alternate_protocol_http_header =
9848 GetAlternateProtocolHttpHeader();
9850 MockRead data_reads[] = {
9851 MockRead("HTTP/1.1 200 OK\r\n"),
9852 MockRead(alternate_protocol_http_header.c_str()),
9853 MockRead("\r\n"),
9854 MockRead("hello world"),
9855 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
9856 MockRead(ASYNC, OK),
9859 StaticSocketDataProvider first_transaction(
9860 data_reads, arraysize(data_reads), NULL, 0);
9861 session_deps_.socket_factory->AddSocketDataProvider(&first_transaction);
9863 SSLSocketDataProvider ssl(ASYNC, OK);
9864 ssl.SetNextProto(GetParam());
9865 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
9867 MockConnect never_finishing_connect(SYNCHRONOUS, ERR_IO_PENDING);
9868 StaticSocketDataProvider hanging_alternate_protocol_socket(
9869 NULL, 0, NULL, 0);
9870 hanging_alternate_protocol_socket.set_connect_data(
9871 never_finishing_connect);
9872 session_deps_.socket_factory->AddSocketDataProvider(
9873 &hanging_alternate_protocol_socket);
9875 // 2nd request is just a copy of the first one, over HTTP again.
9876 session_deps_.socket_factory->AddSocketDataProvider(&first_transaction);
9878 TestCompletionCallback callback;
9880 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9881 scoped_ptr<HttpTransaction> trans(
9882 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9884 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
9885 EXPECT_EQ(ERR_IO_PENDING, rv);
9886 EXPECT_EQ(OK, callback.WaitForResult());
9888 const HttpResponseInfo* response = trans->GetResponseInfo();
9889 ASSERT_TRUE(response != NULL);
9890 ASSERT_TRUE(response->headers.get() != NULL);
9891 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9893 std::string response_data;
9894 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9895 EXPECT_EQ("hello world", response_data);
9897 trans.reset(new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9899 rv = trans->Start(&request, callback.callback(), BoundNetLog());
9900 EXPECT_EQ(ERR_IO_PENDING, rv);
9901 EXPECT_EQ(OK, callback.WaitForResult());
9903 response = trans->GetResponseInfo();
9904 ASSERT_TRUE(response != NULL);
9905 ASSERT_TRUE(response->headers.get() != NULL);
9906 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9907 EXPECT_FALSE(response->was_fetched_via_spdy);
9908 EXPECT_FALSE(response->was_npn_negotiated);
9910 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9911 EXPECT_EQ("hello world", response_data);
9914 class CapturingProxyResolver : public ProxyResolver {
9915 public:
9916 CapturingProxyResolver() {}
9917 ~CapturingProxyResolver() override {}
9919 int GetProxyForURL(const GURL& url,
9920 ProxyInfo* results,
9921 const CompletionCallback& callback,
9922 RequestHandle* request,
9923 const BoundNetLog& net_log) override {
9924 ProxyServer proxy_server(ProxyServer::SCHEME_HTTP,
9925 HostPortPair("myproxy", 80));
9926 results->UseProxyServer(proxy_server);
9927 resolved_.push_back(url);
9928 return OK;
9931 void CancelRequest(RequestHandle request) override { NOTREACHED(); }
9933 LoadState GetLoadState(RequestHandle request) const override {
9934 NOTREACHED();
9935 return LOAD_STATE_IDLE;
9938 const std::vector<GURL>& resolved() const { return resolved_; }
9940 private:
9941 std::vector<GURL> resolved_;
9943 DISALLOW_COPY_AND_ASSIGN(CapturingProxyResolver);
9946 class CapturingProxyResolverFactory : public ProxyResolverFactory {
9947 public:
9948 explicit CapturingProxyResolverFactory(CapturingProxyResolver* resolver)
9949 : ProxyResolverFactory(false), resolver_(resolver) {}
9951 int CreateProxyResolver(
9952 const scoped_refptr<ProxyResolverScriptData>& pac_script,
9953 scoped_ptr<ProxyResolver>* resolver,
9954 const net::CompletionCallback& callback,
9955 scoped_ptr<Request>* request) override {
9956 resolver->reset(new ForwardingProxyResolver(resolver_));
9957 return OK;
9960 private:
9961 ProxyResolver* resolver_;
9964 TEST_P(HttpNetworkTransactionTest,
9965 UseAlternateProtocolForTunneledNpnSpdy) {
9966 session_deps_.use_alternative_services = true;
9967 session_deps_.next_protos = SpdyNextProtos();
9969 ProxyConfig proxy_config;
9970 proxy_config.set_auto_detect(true);
9971 proxy_config.set_pac_url(GURL("http://fooproxyurl"));
9973 CapturingProxyResolver capturing_proxy_resolver;
9974 session_deps_.proxy_service.reset(new ProxyService(
9975 new ProxyConfigServiceFixed(proxy_config),
9976 make_scoped_ptr(
9977 new CapturingProxyResolverFactory(&capturing_proxy_resolver)),
9978 NULL));
9979 TestNetLog net_log;
9980 session_deps_.net_log = &net_log;
9982 HttpRequestInfo request;
9983 request.method = "GET";
9984 request.url = GURL("http://www.example.org/");
9985 request.load_flags = 0;
9987 std::string alternate_protocol_http_header =
9988 GetAlternateProtocolHttpHeader();
9990 MockRead data_reads[] = {
9991 MockRead("HTTP/1.1 200 OK\r\n"),
9992 MockRead(alternate_protocol_http_header.c_str()),
9993 MockRead("\r\n"),
9994 MockRead("hello world"),
9995 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
9996 MockRead(ASYNC, OK),
9999 StaticSocketDataProvider first_transaction(
10000 data_reads, arraysize(data_reads), NULL, 0);
10001 session_deps_.socket_factory->AddSocketDataProvider(&first_transaction);
10003 SSLSocketDataProvider ssl(ASYNC, OK);
10004 ssl.SetNextProto(GetParam());
10005 ssl.cert = ImportCertFromFile(GetTestCertsDirectory(), "spdy_pooling.pem");
10006 ASSERT_TRUE(ssl.cert.get());
10007 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
10009 scoped_ptr<SpdyFrame> req(
10010 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, true));
10011 MockWrite spdy_writes[] = {
10012 MockWrite(ASYNC, 0,
10013 "CONNECT www.example.org:443 HTTP/1.1\r\n"
10014 "Host: www.example.org\r\n"
10015 "Proxy-Connection: keep-alive\r\n\r\n"),
10016 CreateMockWrite(*req, 2),
10019 const char kCONNECTResponse[] = "HTTP/1.1 200 Connected\r\n\r\n";
10021 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
10022 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
10023 MockRead spdy_reads[] = {
10024 MockRead(ASYNC, 1, kCONNECTResponse),
10025 CreateMockRead(*resp.get(), 3),
10026 CreateMockRead(*data.get(), 4),
10027 MockRead(ASYNC, ERR_IO_PENDING, 5),
10030 SequencedSocketData spdy_data(spdy_reads, arraysize(spdy_reads), spdy_writes,
10031 arraysize(spdy_writes));
10032 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
10034 MockConnect never_finishing_connect(SYNCHRONOUS, ERR_IO_PENDING);
10035 StaticSocketDataProvider hanging_non_alternate_protocol_socket(
10036 NULL, 0, NULL, 0);
10037 hanging_non_alternate_protocol_socket.set_connect_data(
10038 never_finishing_connect);
10039 session_deps_.socket_factory->AddSocketDataProvider(
10040 &hanging_non_alternate_protocol_socket);
10042 TestCompletionCallback callback;
10044 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10045 scoped_ptr<HttpTransaction> trans(
10046 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10048 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
10049 EXPECT_EQ(ERR_IO_PENDING, rv);
10050 EXPECT_EQ(OK, callback.WaitForResult());
10052 const HttpResponseInfo* response = trans->GetResponseInfo();
10053 ASSERT_TRUE(response != NULL);
10054 ASSERT_TRUE(response->headers.get() != NULL);
10055 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
10056 EXPECT_FALSE(response->was_fetched_via_spdy);
10057 EXPECT_FALSE(response->was_npn_negotiated);
10059 std::string response_data;
10060 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
10061 EXPECT_EQ("hello world", response_data);
10063 trans.reset(new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10065 rv = trans->Start(&request, callback.callback(), BoundNetLog());
10066 EXPECT_EQ(ERR_IO_PENDING, rv);
10067 EXPECT_EQ(OK, callback.WaitForResult());
10069 response = trans->GetResponseInfo();
10070 ASSERT_TRUE(response != NULL);
10071 ASSERT_TRUE(response->headers.get() != NULL);
10072 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
10073 EXPECT_TRUE(response->was_fetched_via_spdy);
10074 EXPECT_TRUE(response->was_npn_negotiated);
10076 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
10077 EXPECT_EQ("hello!", response_data);
10078 ASSERT_EQ(3u, capturing_proxy_resolver.resolved().size());
10079 EXPECT_EQ("http://www.example.org/",
10080 capturing_proxy_resolver.resolved()[0].spec());
10081 EXPECT_EQ("https://www.example.org/",
10082 capturing_proxy_resolver.resolved()[1].spec());
10084 LoadTimingInfo load_timing_info;
10085 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
10086 TestLoadTimingNotReusedWithPac(load_timing_info,
10087 CONNECT_TIMING_HAS_SSL_TIMES);
10090 TEST_P(HttpNetworkTransactionTest,
10091 UseAlternateProtocolForNpnSpdyWithExistingSpdySession) {
10092 session_deps_.use_alternative_services = true;
10093 session_deps_.next_protos = SpdyNextProtos();
10095 HttpRequestInfo request;
10096 request.method = "GET";
10097 request.url = GURL("http://www.example.org/");
10098 request.load_flags = 0;
10100 std::string alternate_protocol_http_header =
10101 GetAlternateProtocolHttpHeader();
10103 MockRead data_reads[] = {
10104 MockRead("HTTP/1.1 200 OK\r\n"),
10105 MockRead(alternate_protocol_http_header.c_str()),
10106 MockRead("\r\n"),
10107 MockRead("hello world"),
10108 MockRead(ASYNC, OK),
10111 StaticSocketDataProvider first_transaction(
10112 data_reads, arraysize(data_reads), NULL, 0);
10113 session_deps_.socket_factory->AddSocketDataProvider(&first_transaction);
10115 SSLSocketDataProvider ssl(ASYNC, OK);
10116 ssl.SetNextProto(GetParam());
10117 ssl.cert = ImportCertFromFile(GetTestCertsDirectory(), "spdy_pooling.pem");
10118 ASSERT_TRUE(ssl.cert.get());
10119 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
10121 scoped_ptr<SpdyFrame> req(
10122 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, true));
10123 MockWrite spdy_writes[] = {CreateMockWrite(*req, 0)};
10125 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
10126 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
10127 MockRead spdy_reads[] = {
10128 CreateMockRead(*resp, 1), CreateMockRead(*data, 2), MockRead(ASYNC, 0, 3),
10131 SequencedSocketData spdy_data(spdy_reads, arraysize(spdy_reads), spdy_writes,
10132 arraysize(spdy_writes));
10133 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
10135 TestCompletionCallback callback;
10137 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10139 scoped_ptr<HttpTransaction> trans(
10140 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10142 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
10143 EXPECT_EQ(ERR_IO_PENDING, rv);
10144 EXPECT_EQ(OK, callback.WaitForResult());
10146 const HttpResponseInfo* response = trans->GetResponseInfo();
10147 ASSERT_TRUE(response != NULL);
10148 ASSERT_TRUE(response->headers.get() != NULL);
10149 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
10151 std::string response_data;
10152 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
10153 EXPECT_EQ("hello world", response_data);
10155 // Set up an initial SpdySession in the pool to reuse.
10156 HostPortPair host_port_pair("www.example.org", 443);
10157 SpdySessionKey key(host_port_pair, ProxyServer::Direct(),
10158 PRIVACY_MODE_DISABLED);
10159 base::WeakPtr<SpdySession> spdy_session =
10160 CreateSecureSpdySession(session, key, BoundNetLog());
10162 trans.reset(new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10164 rv = trans->Start(&request, callback.callback(), BoundNetLog());
10165 EXPECT_EQ(ERR_IO_PENDING, rv);
10166 EXPECT_EQ(OK, callback.WaitForResult());
10168 response = trans->GetResponseInfo();
10169 ASSERT_TRUE(response != NULL);
10170 ASSERT_TRUE(response->headers.get() != NULL);
10171 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
10172 EXPECT_TRUE(response->was_fetched_via_spdy);
10173 EXPECT_TRUE(response->was_npn_negotiated);
10175 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
10176 EXPECT_EQ("hello!", response_data);
10179 // GenerateAuthToken is a mighty big test.
10180 // It tests all permutation of GenerateAuthToken behavior:
10181 // - Synchronous and Asynchronous completion.
10182 // - OK or error on completion.
10183 // - Direct connection, non-authenticating proxy, and authenticating proxy.
10184 // - HTTP or HTTPS backend (to include proxy tunneling).
10185 // - Non-authenticating and authenticating backend.
10187 // In all, there are 44 reasonable permuations (for example, if there are
10188 // problems generating an auth token for an authenticating proxy, we don't
10189 // need to test all permutations of the backend server).
10191 // The test proceeds by going over each of the configuration cases, and
10192 // potentially running up to three rounds in each of the tests. The TestConfig
10193 // specifies both the configuration for the test as well as the expectations
10194 // for the results.
10195 TEST_P(HttpNetworkTransactionTest, GenerateAuthToken) {
10196 static const char kServer[] = "http://www.example.com";
10197 static const char kSecureServer[] = "https://www.example.com";
10198 static const char kProxy[] = "myproxy:70";
10199 const int kAuthErr = ERR_INVALID_AUTH_CREDENTIALS;
10201 enum AuthTiming {
10202 AUTH_NONE,
10203 AUTH_SYNC,
10204 AUTH_ASYNC,
10207 const MockWrite kGet(
10208 "GET / HTTP/1.1\r\n"
10209 "Host: www.example.com\r\n"
10210 "Connection: keep-alive\r\n\r\n");
10211 const MockWrite kGetProxy(
10212 "GET http://www.example.com/ HTTP/1.1\r\n"
10213 "Host: www.example.com\r\n"
10214 "Proxy-Connection: keep-alive\r\n\r\n");
10215 const MockWrite kGetAuth(
10216 "GET / HTTP/1.1\r\n"
10217 "Host: www.example.com\r\n"
10218 "Connection: keep-alive\r\n"
10219 "Authorization: auth_token\r\n\r\n");
10220 const MockWrite kGetProxyAuth(
10221 "GET http://www.example.com/ HTTP/1.1\r\n"
10222 "Host: www.example.com\r\n"
10223 "Proxy-Connection: keep-alive\r\n"
10224 "Proxy-Authorization: auth_token\r\n\r\n");
10225 const MockWrite kGetAuthThroughProxy(
10226 "GET http://www.example.com/ HTTP/1.1\r\n"
10227 "Host: www.example.com\r\n"
10228 "Proxy-Connection: keep-alive\r\n"
10229 "Authorization: auth_token\r\n\r\n");
10230 const MockWrite kGetAuthWithProxyAuth(
10231 "GET http://www.example.com/ HTTP/1.1\r\n"
10232 "Host: www.example.com\r\n"
10233 "Proxy-Connection: keep-alive\r\n"
10234 "Proxy-Authorization: auth_token\r\n"
10235 "Authorization: auth_token\r\n\r\n");
10236 const MockWrite kConnect(
10237 "CONNECT www.example.com:443 HTTP/1.1\r\n"
10238 "Host: www.example.com\r\n"
10239 "Proxy-Connection: keep-alive\r\n\r\n");
10240 const MockWrite kConnectProxyAuth(
10241 "CONNECT www.example.com:443 HTTP/1.1\r\n"
10242 "Host: www.example.com\r\n"
10243 "Proxy-Connection: keep-alive\r\n"
10244 "Proxy-Authorization: auth_token\r\n\r\n");
10246 const MockRead kSuccess(
10247 "HTTP/1.1 200 OK\r\n"
10248 "Content-Type: text/html; charset=iso-8859-1\r\n"
10249 "Content-Length: 3\r\n\r\n"
10250 "Yes");
10251 const MockRead kFailure(
10252 "Should not be called.");
10253 const MockRead kServerChallenge(
10254 "HTTP/1.1 401 Unauthorized\r\n"
10255 "WWW-Authenticate: Mock realm=server\r\n"
10256 "Content-Type: text/html; charset=iso-8859-1\r\n"
10257 "Content-Length: 14\r\n\r\n"
10258 "Unauthorized\r\n");
10259 const MockRead kProxyChallenge(
10260 "HTTP/1.1 407 Unauthorized\r\n"
10261 "Proxy-Authenticate: Mock realm=proxy\r\n"
10262 "Proxy-Connection: close\r\n"
10263 "Content-Type: text/html; charset=iso-8859-1\r\n"
10264 "Content-Length: 14\r\n\r\n"
10265 "Unauthorized\r\n");
10266 const MockRead kProxyConnected(
10267 "HTTP/1.1 200 Connection Established\r\n\r\n");
10269 // NOTE(cbentzel): I wanted TestReadWriteRound to be a simple struct with
10270 // no constructors, but the C++ compiler on Windows warns about
10271 // unspecified data in compound literals. So, moved to using constructors,
10272 // and TestRound's created with the default constructor should not be used.
10273 struct TestRound {
10274 TestRound()
10275 : expected_rv(ERR_UNEXPECTED),
10276 extra_write(NULL),
10277 extra_read(NULL) {
10279 TestRound(const MockWrite& write_arg, const MockRead& read_arg,
10280 int expected_rv_arg)
10281 : write(write_arg),
10282 read(read_arg),
10283 expected_rv(expected_rv_arg),
10284 extra_write(NULL),
10285 extra_read(NULL) {
10287 TestRound(const MockWrite& write_arg, const MockRead& read_arg,
10288 int expected_rv_arg, const MockWrite* extra_write_arg,
10289 const MockRead* extra_read_arg)
10290 : write(write_arg),
10291 read(read_arg),
10292 expected_rv(expected_rv_arg),
10293 extra_write(extra_write_arg),
10294 extra_read(extra_read_arg) {
10296 MockWrite write;
10297 MockRead read;
10298 int expected_rv;
10299 const MockWrite* extra_write;
10300 const MockRead* extra_read;
10303 static const int kNoSSL = 500;
10305 struct TestConfig {
10306 const char* const proxy_url;
10307 AuthTiming proxy_auth_timing;
10308 int proxy_auth_rv;
10309 const char* const server_url;
10310 AuthTiming server_auth_timing;
10311 int server_auth_rv;
10312 int num_auth_rounds;
10313 int first_ssl_round;
10314 TestRound rounds[3];
10315 } test_configs[] = {
10316 // Non-authenticating HTTP server with a direct connection.
10317 { NULL, AUTH_NONE, OK, kServer, AUTH_NONE, OK, 1, kNoSSL,
10318 { TestRound(kGet, kSuccess, OK)}},
10319 // Authenticating HTTP server with a direct connection.
10320 { NULL, AUTH_NONE, OK, kServer, AUTH_SYNC, OK, 2, kNoSSL,
10321 { TestRound(kGet, kServerChallenge, OK),
10322 TestRound(kGetAuth, kSuccess, OK)}},
10323 { NULL, AUTH_NONE, OK, kServer, AUTH_SYNC, kAuthErr, 2, kNoSSL,
10324 { TestRound(kGet, kServerChallenge, OK),
10325 TestRound(kGetAuth, kFailure, kAuthErr)}},
10326 { NULL, AUTH_NONE, OK, kServer, AUTH_ASYNC, OK, 2, kNoSSL,
10327 { TestRound(kGet, kServerChallenge, OK),
10328 TestRound(kGetAuth, kSuccess, OK)}},
10329 { NULL, AUTH_NONE, OK, kServer, AUTH_ASYNC, kAuthErr, 2, kNoSSL,
10330 { TestRound(kGet, kServerChallenge, OK),
10331 TestRound(kGetAuth, kFailure, kAuthErr)}},
10332 // Non-authenticating HTTP server through a non-authenticating proxy.
10333 { kProxy, AUTH_NONE, OK, kServer, AUTH_NONE, OK, 1, kNoSSL,
10334 { TestRound(kGetProxy, kSuccess, OK)}},
10335 // Authenticating HTTP server through a non-authenticating proxy.
10336 { kProxy, AUTH_NONE, OK, kServer, AUTH_SYNC, OK, 2, kNoSSL,
10337 { TestRound(kGetProxy, kServerChallenge, OK),
10338 TestRound(kGetAuthThroughProxy, kSuccess, OK)}},
10339 { kProxy, AUTH_NONE, OK, kServer, AUTH_SYNC, kAuthErr, 2, kNoSSL,
10340 { TestRound(kGetProxy, kServerChallenge, OK),
10341 TestRound(kGetAuthThroughProxy, kFailure, kAuthErr)}},
10342 { kProxy, AUTH_NONE, OK, kServer, AUTH_ASYNC, OK, 2, kNoSSL,
10343 { TestRound(kGetProxy, kServerChallenge, OK),
10344 TestRound(kGetAuthThroughProxy, kSuccess, OK)}},
10345 { kProxy, AUTH_NONE, OK, kServer, AUTH_ASYNC, kAuthErr, 2, kNoSSL,
10346 { TestRound(kGetProxy, kServerChallenge, OK),
10347 TestRound(kGetAuthThroughProxy, kFailure, kAuthErr)}},
10348 // Non-authenticating HTTP server through an authenticating proxy.
10349 { kProxy, AUTH_SYNC, OK, kServer, AUTH_NONE, OK, 2, kNoSSL,
10350 { TestRound(kGetProxy, kProxyChallenge, OK),
10351 TestRound(kGetProxyAuth, kSuccess, OK)}},
10352 { kProxy, AUTH_SYNC, kAuthErr, kServer, AUTH_NONE, OK, 2, kNoSSL,
10353 { TestRound(kGetProxy, kProxyChallenge, OK),
10354 TestRound(kGetProxyAuth, kFailure, kAuthErr)}},
10355 { kProxy, AUTH_ASYNC, OK, kServer, AUTH_NONE, OK, 2, kNoSSL,
10356 { TestRound(kGetProxy, kProxyChallenge, OK),
10357 TestRound(kGetProxyAuth, kSuccess, OK)}},
10358 { kProxy, AUTH_ASYNC, kAuthErr, kServer, AUTH_NONE, OK, 2, kNoSSL,
10359 { TestRound(kGetProxy, kProxyChallenge, OK),
10360 TestRound(kGetProxyAuth, kFailure, kAuthErr)}},
10361 // Authenticating HTTP server through an authenticating proxy.
10362 { kProxy, AUTH_SYNC, OK, kServer, AUTH_SYNC, OK, 3, kNoSSL,
10363 { TestRound(kGetProxy, kProxyChallenge, OK),
10364 TestRound(kGetProxyAuth, kServerChallenge, OK),
10365 TestRound(kGetAuthWithProxyAuth, kSuccess, OK)}},
10366 { kProxy, AUTH_SYNC, OK, kServer, AUTH_SYNC, kAuthErr, 3, kNoSSL,
10367 { TestRound(kGetProxy, kProxyChallenge, OK),
10368 TestRound(kGetProxyAuth, kServerChallenge, OK),
10369 TestRound(kGetAuthWithProxyAuth, kFailure, kAuthErr)}},
10370 { kProxy, AUTH_ASYNC, OK, kServer, AUTH_SYNC, OK, 3, kNoSSL,
10371 { TestRound(kGetProxy, kProxyChallenge, OK),
10372 TestRound(kGetProxyAuth, kServerChallenge, OK),
10373 TestRound(kGetAuthWithProxyAuth, kSuccess, OK)}},
10374 { kProxy, AUTH_ASYNC, OK, kServer, AUTH_SYNC, kAuthErr, 3, kNoSSL,
10375 { TestRound(kGetProxy, kProxyChallenge, OK),
10376 TestRound(kGetProxyAuth, kServerChallenge, OK),
10377 TestRound(kGetAuthWithProxyAuth, kFailure, kAuthErr)}},
10378 { kProxy, AUTH_SYNC, OK, kServer, AUTH_ASYNC, OK, 3, kNoSSL,
10379 { TestRound(kGetProxy, kProxyChallenge, OK),
10380 TestRound(kGetProxyAuth, kServerChallenge, OK),
10381 TestRound(kGetAuthWithProxyAuth, kSuccess, OK)}},
10382 { kProxy, AUTH_SYNC, OK, kServer, AUTH_ASYNC, kAuthErr, 3, kNoSSL,
10383 { TestRound(kGetProxy, kProxyChallenge, OK),
10384 TestRound(kGetProxyAuth, kServerChallenge, OK),
10385 TestRound(kGetAuthWithProxyAuth, kFailure, kAuthErr)}},
10386 { kProxy, AUTH_ASYNC, OK, kServer, AUTH_ASYNC, OK, 3, kNoSSL,
10387 { TestRound(kGetProxy, kProxyChallenge, OK),
10388 TestRound(kGetProxyAuth, kServerChallenge, OK),
10389 TestRound(kGetAuthWithProxyAuth, kSuccess, OK)}},
10390 { kProxy, AUTH_ASYNC, OK, kServer, AUTH_ASYNC, kAuthErr, 3, kNoSSL,
10391 { TestRound(kGetProxy, kProxyChallenge, OK),
10392 TestRound(kGetProxyAuth, kServerChallenge, OK),
10393 TestRound(kGetAuthWithProxyAuth, kFailure, kAuthErr)}},
10394 // Non-authenticating HTTPS server with a direct connection.
10395 { NULL, AUTH_NONE, OK, kSecureServer, AUTH_NONE, OK, 1, 0,
10396 { TestRound(kGet, kSuccess, OK)}},
10397 // Authenticating HTTPS server with a direct connection.
10398 { NULL, AUTH_NONE, OK, kSecureServer, AUTH_SYNC, OK, 2, 0,
10399 { TestRound(kGet, kServerChallenge, OK),
10400 TestRound(kGetAuth, kSuccess, OK)}},
10401 { NULL, AUTH_NONE, OK, kSecureServer, AUTH_SYNC, kAuthErr, 2, 0,
10402 { TestRound(kGet, kServerChallenge, OK),
10403 TestRound(kGetAuth, kFailure, kAuthErr)}},
10404 { NULL, AUTH_NONE, OK, kSecureServer, AUTH_ASYNC, OK, 2, 0,
10405 { TestRound(kGet, kServerChallenge, OK),
10406 TestRound(kGetAuth, kSuccess, OK)}},
10407 { NULL, AUTH_NONE, OK, kSecureServer, AUTH_ASYNC, kAuthErr, 2, 0,
10408 { TestRound(kGet, kServerChallenge, OK),
10409 TestRound(kGetAuth, kFailure, kAuthErr)}},
10410 // Non-authenticating HTTPS server with a non-authenticating proxy.
10411 { kProxy, AUTH_NONE, OK, kSecureServer, AUTH_NONE, OK, 1, 0,
10412 { TestRound(kConnect, kProxyConnected, OK, &kGet, &kSuccess)}},
10413 // Authenticating HTTPS server through a non-authenticating proxy.
10414 { kProxy, AUTH_NONE, OK, kSecureServer, AUTH_SYNC, OK, 2, 0,
10415 { TestRound(kConnect, kProxyConnected, OK, &kGet, &kServerChallenge),
10416 TestRound(kGetAuth, kSuccess, OK)}},
10417 { kProxy, AUTH_NONE, OK, kSecureServer, AUTH_SYNC, kAuthErr, 2, 0,
10418 { TestRound(kConnect, kProxyConnected, OK, &kGet, &kServerChallenge),
10419 TestRound(kGetAuth, kFailure, kAuthErr)}},
10420 { kProxy, AUTH_NONE, OK, kSecureServer, AUTH_ASYNC, OK, 2, 0,
10421 { TestRound(kConnect, kProxyConnected, OK, &kGet, &kServerChallenge),
10422 TestRound(kGetAuth, kSuccess, OK)}},
10423 { kProxy, AUTH_NONE, OK, kSecureServer, AUTH_ASYNC, kAuthErr, 2, 0,
10424 { TestRound(kConnect, kProxyConnected, OK, &kGet, &kServerChallenge),
10425 TestRound(kGetAuth, kFailure, kAuthErr)}},
10426 // Non-Authenticating HTTPS server through an authenticating proxy.
10427 { kProxy, AUTH_SYNC, OK, kSecureServer, AUTH_NONE, OK, 2, 1,
10428 { TestRound(kConnect, kProxyChallenge, OK),
10429 TestRound(kConnectProxyAuth, kProxyConnected, OK, &kGet, &kSuccess)}},
10430 { kProxy, AUTH_SYNC, kAuthErr, kSecureServer, AUTH_NONE, OK, 2, kNoSSL,
10431 { TestRound(kConnect, kProxyChallenge, OK),
10432 TestRound(kConnectProxyAuth, kFailure, kAuthErr)}},
10433 { kProxy, AUTH_ASYNC, OK, kSecureServer, AUTH_NONE, OK, 2, 1,
10434 { TestRound(kConnect, kProxyChallenge, OK),
10435 TestRound(kConnectProxyAuth, kProxyConnected, OK, &kGet, &kSuccess)}},
10436 { kProxy, AUTH_ASYNC, kAuthErr, kSecureServer, AUTH_NONE, OK, 2, kNoSSL,
10437 { TestRound(kConnect, kProxyChallenge, OK),
10438 TestRound(kConnectProxyAuth, kFailure, kAuthErr)}},
10439 // Authenticating HTTPS server through an authenticating proxy.
10440 { kProxy, AUTH_SYNC, OK, kSecureServer, AUTH_SYNC, OK, 3, 1,
10441 { TestRound(kConnect, kProxyChallenge, OK),
10442 TestRound(kConnectProxyAuth, kProxyConnected, OK,
10443 &kGet, &kServerChallenge),
10444 TestRound(kGetAuth, kSuccess, OK)}},
10445 { kProxy, AUTH_SYNC, OK, kSecureServer, AUTH_SYNC, kAuthErr, 3, 1,
10446 { TestRound(kConnect, kProxyChallenge, OK),
10447 TestRound(kConnectProxyAuth, kProxyConnected, OK,
10448 &kGet, &kServerChallenge),
10449 TestRound(kGetAuth, kFailure, kAuthErr)}},
10450 { kProxy, AUTH_ASYNC, OK, kSecureServer, AUTH_SYNC, OK, 3, 1,
10451 { TestRound(kConnect, kProxyChallenge, OK),
10452 TestRound(kConnectProxyAuth, kProxyConnected, OK,
10453 &kGet, &kServerChallenge),
10454 TestRound(kGetAuth, kSuccess, OK)}},
10455 { kProxy, AUTH_ASYNC, OK, kSecureServer, AUTH_SYNC, kAuthErr, 3, 1,
10456 { TestRound(kConnect, kProxyChallenge, OK),
10457 TestRound(kConnectProxyAuth, kProxyConnected, OK,
10458 &kGet, &kServerChallenge),
10459 TestRound(kGetAuth, kFailure, kAuthErr)}},
10460 { kProxy, AUTH_SYNC, OK, kSecureServer, AUTH_ASYNC, OK, 3, 1,
10461 { TestRound(kConnect, kProxyChallenge, OK),
10462 TestRound(kConnectProxyAuth, kProxyConnected, OK,
10463 &kGet, &kServerChallenge),
10464 TestRound(kGetAuth, kSuccess, OK)}},
10465 { kProxy, AUTH_SYNC, OK, kSecureServer, AUTH_ASYNC, kAuthErr, 3, 1,
10466 { TestRound(kConnect, kProxyChallenge, OK),
10467 TestRound(kConnectProxyAuth, kProxyConnected, OK,
10468 &kGet, &kServerChallenge),
10469 TestRound(kGetAuth, kFailure, kAuthErr)}},
10470 { kProxy, AUTH_ASYNC, OK, kSecureServer, AUTH_ASYNC, OK, 3, 1,
10471 { TestRound(kConnect, kProxyChallenge, OK),
10472 TestRound(kConnectProxyAuth, kProxyConnected, OK,
10473 &kGet, &kServerChallenge),
10474 TestRound(kGetAuth, kSuccess, OK)}},
10475 { kProxy, AUTH_ASYNC, OK, kSecureServer, AUTH_ASYNC, kAuthErr, 3, 1,
10476 { TestRound(kConnect, kProxyChallenge, OK),
10477 TestRound(kConnectProxyAuth, kProxyConnected, OK,
10478 &kGet, &kServerChallenge),
10479 TestRound(kGetAuth, kFailure, kAuthErr)}},
10482 for (size_t i = 0; i < arraysize(test_configs); ++i) {
10483 HttpAuthHandlerMock::Factory* auth_factory(
10484 new HttpAuthHandlerMock::Factory());
10485 session_deps_.http_auth_handler_factory.reset(auth_factory);
10486 const TestConfig& test_config = test_configs[i];
10488 // Set up authentication handlers as necessary.
10489 if (test_config.proxy_auth_timing != AUTH_NONE) {
10490 for (int n = 0; n < 2; n++) {
10491 HttpAuthHandlerMock* auth_handler(new HttpAuthHandlerMock());
10492 std::string auth_challenge = "Mock realm=proxy";
10493 GURL origin(test_config.proxy_url);
10494 HttpAuthChallengeTokenizer tokenizer(auth_challenge.begin(),
10495 auth_challenge.end());
10496 auth_handler->InitFromChallenge(&tokenizer, HttpAuth::AUTH_PROXY,
10497 origin, BoundNetLog());
10498 auth_handler->SetGenerateExpectation(
10499 test_config.proxy_auth_timing == AUTH_ASYNC,
10500 test_config.proxy_auth_rv);
10501 auth_factory->AddMockHandler(auth_handler, HttpAuth::AUTH_PROXY);
10504 if (test_config.server_auth_timing != AUTH_NONE) {
10505 HttpAuthHandlerMock* auth_handler(new HttpAuthHandlerMock());
10506 std::string auth_challenge = "Mock realm=server";
10507 GURL origin(test_config.server_url);
10508 HttpAuthChallengeTokenizer tokenizer(auth_challenge.begin(),
10509 auth_challenge.end());
10510 auth_handler->InitFromChallenge(&tokenizer, HttpAuth::AUTH_SERVER,
10511 origin, BoundNetLog());
10512 auth_handler->SetGenerateExpectation(
10513 test_config.server_auth_timing == AUTH_ASYNC,
10514 test_config.server_auth_rv);
10515 auth_factory->AddMockHandler(auth_handler, HttpAuth::AUTH_SERVER);
10517 if (test_config.proxy_url) {
10518 session_deps_.proxy_service.reset(
10519 ProxyService::CreateFixed(test_config.proxy_url));
10520 } else {
10521 session_deps_.proxy_service.reset(ProxyService::CreateDirect());
10524 HttpRequestInfo request;
10525 request.method = "GET";
10526 request.url = GURL(test_config.server_url);
10527 request.load_flags = 0;
10529 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10530 HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
10532 SSLSocketDataProvider ssl_socket_data_provider(SYNCHRONOUS, OK);
10534 std::vector<std::vector<MockRead>> mock_reads(1);
10535 std::vector<std::vector<MockWrite>> mock_writes(1);
10536 for (int round = 0; round < test_config.num_auth_rounds; ++round) {
10537 const TestRound& read_write_round = test_config.rounds[round];
10539 // Set up expected reads and writes.
10540 mock_reads.back().push_back(read_write_round.read);
10541 mock_writes.back().push_back(read_write_round.write);
10543 // kProxyChallenge uses Proxy-Connection: close which means that the
10544 // socket is closed and a new one will be created for the next request.
10545 if (read_write_round.read.data == kProxyChallenge.data) {
10546 mock_reads.push_back(std::vector<MockRead>());
10547 mock_writes.push_back(std::vector<MockWrite>());
10550 if (read_write_round.extra_read) {
10551 mock_reads.back().push_back(*read_write_round.extra_read);
10553 if (read_write_round.extra_write) {
10554 mock_writes.back().push_back(*read_write_round.extra_write);
10557 // Add an SSL sequence if necessary.
10558 if (round >= test_config.first_ssl_round)
10559 session_deps_.socket_factory->AddSSLSocketDataProvider(
10560 &ssl_socket_data_provider);
10563 ScopedVector<StaticSocketDataProvider> data_providers;
10564 for (size_t i = 0; i < mock_reads.size(); ++i) {
10565 data_providers.push_back(new StaticSocketDataProvider(
10566 vector_as_array(&mock_reads[i]), mock_reads[i].size(),
10567 vector_as_array(&mock_writes[i]), mock_writes[i].size()));
10568 session_deps_.socket_factory->AddSocketDataProvider(
10569 data_providers.back());
10572 for (int round = 0; round < test_config.num_auth_rounds; ++round) {
10573 const TestRound& read_write_round = test_config.rounds[round];
10574 // Start or restart the transaction.
10575 TestCompletionCallback callback;
10576 int rv;
10577 if (round == 0) {
10578 rv = trans.Start(&request, callback.callback(), BoundNetLog());
10579 } else {
10580 rv = trans.RestartWithAuth(
10581 AuthCredentials(kFoo, kBar), callback.callback());
10583 if (rv == ERR_IO_PENDING)
10584 rv = callback.WaitForResult();
10586 // Compare results with expected data.
10587 EXPECT_EQ(read_write_round.expected_rv, rv);
10588 const HttpResponseInfo* response = trans.GetResponseInfo();
10589 if (read_write_round.expected_rv != OK) {
10590 EXPECT_EQ(round + 1, test_config.num_auth_rounds);
10591 continue;
10593 if (round + 1 < test_config.num_auth_rounds) {
10594 EXPECT_FALSE(response->auth_challenge.get() == NULL);
10595 } else {
10596 EXPECT_TRUE(response->auth_challenge.get() == NULL);
10602 TEST_P(HttpNetworkTransactionTest, MultiRoundAuth) {
10603 // Do multi-round authentication and make sure it works correctly.
10604 HttpAuthHandlerMock::Factory* auth_factory(
10605 new HttpAuthHandlerMock::Factory());
10606 session_deps_.http_auth_handler_factory.reset(auth_factory);
10607 session_deps_.proxy_service.reset(ProxyService::CreateDirect());
10608 session_deps_.host_resolver->rules()->AddRule("www.example.com", "10.0.0.1");
10609 session_deps_.host_resolver->set_synchronous_mode(true);
10611 HttpAuthHandlerMock* auth_handler(new HttpAuthHandlerMock());
10612 auth_handler->set_connection_based(true);
10613 std::string auth_challenge = "Mock realm=server";
10614 GURL origin("http://www.example.com");
10615 HttpAuthChallengeTokenizer tokenizer(auth_challenge.begin(),
10616 auth_challenge.end());
10617 auth_handler->InitFromChallenge(&tokenizer, HttpAuth::AUTH_SERVER,
10618 origin, BoundNetLog());
10619 auth_factory->AddMockHandler(auth_handler, HttpAuth::AUTH_SERVER);
10621 int rv = OK;
10622 const HttpResponseInfo* response = NULL;
10623 HttpRequestInfo request;
10624 request.method = "GET";
10625 request.url = origin;
10626 request.load_flags = 0;
10628 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10630 // Use a TCP Socket Pool with only one connection per group. This is used
10631 // to validate that the TCP socket is not released to the pool between
10632 // each round of multi-round authentication.
10633 HttpNetworkSessionPeer session_peer(session);
10634 TransportClientSocketPool* transport_pool = new TransportClientSocketPool(
10635 50, // Max sockets for pool
10636 1, // Max sockets per group
10637 session_deps_.host_resolver.get(),
10638 session_deps_.socket_factory.get(),
10639 session_deps_.net_log);
10640 scoped_ptr<MockClientSocketPoolManager> mock_pool_manager(
10641 new MockClientSocketPoolManager);
10642 mock_pool_manager->SetTransportSocketPool(transport_pool);
10643 session_peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
10645 scoped_ptr<HttpTransaction> trans(
10646 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10647 TestCompletionCallback callback;
10649 const MockWrite kGet(
10650 "GET / HTTP/1.1\r\n"
10651 "Host: www.example.com\r\n"
10652 "Connection: keep-alive\r\n\r\n");
10653 const MockWrite kGetAuth(
10654 "GET / HTTP/1.1\r\n"
10655 "Host: www.example.com\r\n"
10656 "Connection: keep-alive\r\n"
10657 "Authorization: auth_token\r\n\r\n");
10659 const MockRead kServerChallenge(
10660 "HTTP/1.1 401 Unauthorized\r\n"
10661 "WWW-Authenticate: Mock realm=server\r\n"
10662 "Content-Type: text/html; charset=iso-8859-1\r\n"
10663 "Content-Length: 14\r\n\r\n"
10664 "Unauthorized\r\n");
10665 const MockRead kSuccess(
10666 "HTTP/1.1 200 OK\r\n"
10667 "Content-Type: text/html; charset=iso-8859-1\r\n"
10668 "Content-Length: 3\r\n\r\n"
10669 "Yes");
10671 MockWrite writes[] = {
10672 // First round
10673 kGet,
10674 // Second round
10675 kGetAuth,
10676 // Third round
10677 kGetAuth,
10678 // Fourth round
10679 kGetAuth,
10680 // Competing request
10681 kGet,
10683 MockRead reads[] = {
10684 // First round
10685 kServerChallenge,
10686 // Second round
10687 kServerChallenge,
10688 // Third round
10689 kServerChallenge,
10690 // Fourth round
10691 kSuccess,
10692 // Competing response
10693 kSuccess,
10695 StaticSocketDataProvider data_provider(reads, arraysize(reads),
10696 writes, arraysize(writes));
10697 session_deps_.socket_factory->AddSocketDataProvider(&data_provider);
10699 const char kSocketGroup[] = "www.example.com:80";
10701 // First round of authentication.
10702 auth_handler->SetGenerateExpectation(false, OK);
10703 rv = trans->Start(&request, callback.callback(), BoundNetLog());
10704 if (rv == ERR_IO_PENDING)
10705 rv = callback.WaitForResult();
10706 EXPECT_EQ(OK, rv);
10707 response = trans->GetResponseInfo();
10708 ASSERT_TRUE(response != NULL);
10709 EXPECT_FALSE(response->auth_challenge.get() == NULL);
10710 EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10712 // In between rounds, another request comes in for the same domain.
10713 // It should not be able to grab the TCP socket that trans has already
10714 // claimed.
10715 scoped_ptr<HttpTransaction> trans_compete(
10716 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10717 TestCompletionCallback callback_compete;
10718 rv = trans_compete->Start(
10719 &request, callback_compete.callback(), BoundNetLog());
10720 EXPECT_EQ(ERR_IO_PENDING, rv);
10721 // callback_compete.WaitForResult at this point would stall forever,
10722 // since the HttpNetworkTransaction does not release the request back to
10723 // the pool until after authentication completes.
10725 // Second round of authentication.
10726 auth_handler->SetGenerateExpectation(false, OK);
10727 rv = trans->RestartWithAuth(AuthCredentials(kFoo, kBar), callback.callback());
10728 if (rv == ERR_IO_PENDING)
10729 rv = callback.WaitForResult();
10730 EXPECT_EQ(OK, rv);
10731 response = trans->GetResponseInfo();
10732 ASSERT_TRUE(response != NULL);
10733 EXPECT_TRUE(response->auth_challenge.get() == NULL);
10734 EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10736 // Third round of authentication.
10737 auth_handler->SetGenerateExpectation(false, OK);
10738 rv = trans->RestartWithAuth(AuthCredentials(), callback.callback());
10739 if (rv == ERR_IO_PENDING)
10740 rv = callback.WaitForResult();
10741 EXPECT_EQ(OK, rv);
10742 response = trans->GetResponseInfo();
10743 ASSERT_TRUE(response != NULL);
10744 EXPECT_TRUE(response->auth_challenge.get() == NULL);
10745 EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10747 // Fourth round of authentication, which completes successfully.
10748 auth_handler->SetGenerateExpectation(false, OK);
10749 rv = trans->RestartWithAuth(AuthCredentials(), callback.callback());
10750 if (rv == ERR_IO_PENDING)
10751 rv = callback.WaitForResult();
10752 EXPECT_EQ(OK, rv);
10753 response = trans->GetResponseInfo();
10754 ASSERT_TRUE(response != NULL);
10755 EXPECT_TRUE(response->auth_challenge.get() == NULL);
10756 EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10758 // Read the body since the fourth round was successful. This will also
10759 // release the socket back to the pool.
10760 scoped_refptr<IOBufferWithSize> io_buf(new IOBufferWithSize(50));
10761 rv = trans->Read(io_buf.get(), io_buf->size(), callback.callback());
10762 if (rv == ERR_IO_PENDING)
10763 rv = callback.WaitForResult();
10764 EXPECT_EQ(3, rv);
10765 rv = trans->Read(io_buf.get(), io_buf->size(), callback.callback());
10766 EXPECT_EQ(0, rv);
10767 // There are still 0 idle sockets, since the trans_compete transaction
10768 // will be handed it immediately after trans releases it to the group.
10769 EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10771 // The competing request can now finish. Wait for the headers and then
10772 // read the body.
10773 rv = callback_compete.WaitForResult();
10774 EXPECT_EQ(OK, rv);
10775 rv = trans_compete->Read(io_buf.get(), io_buf->size(), callback.callback());
10776 if (rv == ERR_IO_PENDING)
10777 rv = callback.WaitForResult();
10778 EXPECT_EQ(3, rv);
10779 rv = trans_compete->Read(io_buf.get(), io_buf->size(), callback.callback());
10780 EXPECT_EQ(0, rv);
10782 // Finally, the socket is released to the group.
10783 EXPECT_EQ(1, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10786 // This tests the case that a request is issued via http instead of spdy after
10787 // npn is negotiated.
10788 TEST_P(HttpNetworkTransactionTest, NpnWithHttpOverSSL) {
10789 session_deps_.use_alternative_services = true;
10790 NextProtoVector next_protos;
10791 next_protos.push_back(kProtoHTTP11);
10792 session_deps_.next_protos = next_protos;
10794 HttpRequestInfo request;
10795 request.method = "GET";
10796 request.url = GURL("https://www.example.org/");
10797 request.load_flags = 0;
10799 MockWrite data_writes[] = {
10800 MockWrite(
10801 "GET / HTTP/1.1\r\n"
10802 "Host: www.example.org\r\n"
10803 "Connection: keep-alive\r\n\r\n"),
10806 std::string alternate_protocol_http_header =
10807 GetAlternateProtocolHttpHeader();
10809 MockRead data_reads[] = {
10810 MockRead("HTTP/1.1 200 OK\r\n"),
10811 MockRead(alternate_protocol_http_header.c_str()),
10812 MockRead("\r\n"),
10813 MockRead("hello world"),
10814 MockRead(SYNCHRONOUS, OK),
10817 SSLSocketDataProvider ssl(ASYNC, OK);
10818 ssl.SetNextProto(kProtoHTTP11);
10820 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
10822 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
10823 data_writes, arraysize(data_writes));
10824 session_deps_.socket_factory->AddSocketDataProvider(&data);
10826 TestCompletionCallback callback;
10828 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10829 scoped_ptr<HttpTransaction> trans(
10830 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10832 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
10834 EXPECT_EQ(ERR_IO_PENDING, rv);
10835 EXPECT_EQ(OK, callback.WaitForResult());
10837 const HttpResponseInfo* response = trans->GetResponseInfo();
10838 ASSERT_TRUE(response != NULL);
10839 ASSERT_TRUE(response->headers.get() != NULL);
10840 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
10842 std::string response_data;
10843 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
10844 EXPECT_EQ("hello world", response_data);
10846 EXPECT_FALSE(response->was_fetched_via_spdy);
10847 EXPECT_TRUE(response->was_npn_negotiated);
10850 // Simulate the SSL handshake completing with an NPN negotiation followed by an
10851 // immediate server closing of the socket.
10852 // Regression test for https://crbug.com/46369.
10853 TEST_P(HttpNetworkTransactionTest, SpdyPostNPNServerHangup) {
10854 session_deps_.use_alternative_services = true;
10855 session_deps_.next_protos = SpdyNextProtos();
10857 HttpRequestInfo request;
10858 request.method = "GET";
10859 request.url = GURL("https://www.example.org/");
10860 request.load_flags = 0;
10862 SSLSocketDataProvider ssl(ASYNC, OK);
10863 ssl.SetNextProto(GetParam());
10864 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
10866 scoped_ptr<SpdyFrame> req(
10867 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, true));
10868 MockWrite spdy_writes[] = {CreateMockWrite(*req, 1)};
10870 MockRead spdy_reads[] = {
10871 MockRead(SYNCHRONOUS, 0, 0) // Not async - return 0 immediately.
10874 SequencedSocketData spdy_data(spdy_reads, arraysize(spdy_reads), spdy_writes,
10875 arraysize(spdy_writes));
10876 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
10878 TestCompletionCallback callback;
10880 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10881 scoped_ptr<HttpTransaction> trans(
10882 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10884 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
10885 EXPECT_EQ(ERR_IO_PENDING, rv);
10886 EXPECT_EQ(ERR_CONNECTION_CLOSED, callback.WaitForResult());
10889 // A subclass of HttpAuthHandlerMock that records the request URL when
10890 // it gets it. This is needed since the auth handler may get destroyed
10891 // before we get a chance to query it.
10892 class UrlRecordingHttpAuthHandlerMock : public HttpAuthHandlerMock {
10893 public:
10894 explicit UrlRecordingHttpAuthHandlerMock(GURL* url) : url_(url) {}
10896 ~UrlRecordingHttpAuthHandlerMock() override {}
10898 protected:
10899 int GenerateAuthTokenImpl(const AuthCredentials* credentials,
10900 const HttpRequestInfo* request,
10901 const CompletionCallback& callback,
10902 std::string* auth_token) override {
10903 *url_ = request->url;
10904 return HttpAuthHandlerMock::GenerateAuthTokenImpl(
10905 credentials, request, callback, auth_token);
10908 private:
10909 GURL* url_;
10912 // This test ensures that the URL passed into the proxy is upgraded to https
10913 // when doing an Alternate Protocol upgrade.
10914 TEST_P(HttpNetworkTransactionTest, SpdyAlternateProtocolThroughProxy) {
10915 session_deps_.use_alternative_services = true;
10916 session_deps_.next_protos = SpdyNextProtos();
10918 session_deps_.proxy_service.reset(
10919 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
10920 TestNetLog net_log;
10921 session_deps_.net_log = &net_log;
10922 GURL request_url;
10924 HttpAuthHandlerMock::Factory* auth_factory =
10925 new HttpAuthHandlerMock::Factory();
10926 UrlRecordingHttpAuthHandlerMock* auth_handler =
10927 new UrlRecordingHttpAuthHandlerMock(&request_url);
10928 auth_factory->AddMockHandler(auth_handler, HttpAuth::AUTH_PROXY);
10929 auth_factory->set_do_init_from_challenge(true);
10930 session_deps_.http_auth_handler_factory.reset(auth_factory);
10933 HttpRequestInfo request;
10934 request.method = "GET";
10935 request.url = GURL("http://www.example.org");
10936 request.load_flags = 0;
10938 // First round goes unauthenticated through the proxy.
10939 MockWrite data_writes_1[] = {
10940 MockWrite(
10941 "GET http://www.example.org/ HTTP/1.1\r\n"
10942 "Host: www.example.org\r\n"
10943 "Proxy-Connection: keep-alive\r\n"
10944 "\r\n"),
10946 MockRead data_reads_1[] = {
10947 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
10948 MockRead("HTTP/1.1 200 OK\r\n"),
10949 MockRead("Alternate-Protocol: 443:"),
10950 MockRead(GetAlternateProtocolFromParam()),
10951 MockRead("\r\n"),
10952 MockRead("Proxy-Connection: close\r\n"),
10953 MockRead("\r\n"),
10955 StaticSocketDataProvider data_1(data_reads_1, arraysize(data_reads_1),
10956 data_writes_1, arraysize(data_writes_1));
10958 // Second round tries to tunnel to www.example.org due to the
10959 // Alternate-Protocol announcement in the first round. It fails due
10960 // to a proxy authentication challenge.
10961 // After the failure, a tunnel is established to www.example.org using
10962 // Proxy-Authorization headers. There is then a SPDY request round.
10964 // NOTE: Despite the "Proxy-Connection: Close", these are done on the
10965 // same MockTCPClientSocket since the underlying HttpNetworkClientSocket
10966 // does a Disconnect and Connect on the same socket, rather than trying
10967 // to obtain a new one.
10969 // NOTE: Originally, the proxy response to the second CONNECT request
10970 // simply returned another 407 so the unit test could skip the SSL connection
10971 // establishment and SPDY framing issues. Alas, the
10972 // retry-http-when-alternate-protocol fails logic kicks in, which was more
10973 // complicated to set up expectations for than the SPDY session.
10975 scoped_ptr<SpdyFrame> req(
10976 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, true));
10977 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
10978 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
10980 MockWrite data_writes_2[] = {
10981 // First connection attempt without Proxy-Authorization.
10982 MockWrite(ASYNC, 0,
10983 "CONNECT www.example.org:443 HTTP/1.1\r\n"
10984 "Host: www.example.org\r\n"
10985 "Proxy-Connection: keep-alive\r\n"
10986 "\r\n"),
10988 // Second connection attempt with Proxy-Authorization.
10989 MockWrite(ASYNC, 2,
10990 "CONNECT www.example.org:443 HTTP/1.1\r\n"
10991 "Host: www.example.org\r\n"
10992 "Proxy-Connection: keep-alive\r\n"
10993 "Proxy-Authorization: auth_token\r\n"
10994 "\r\n"),
10996 // SPDY request
10997 CreateMockWrite(*req, 4),
10999 MockRead data_reads_2[] = {
11000 // First connection attempt fails
11001 MockRead(ASYNC, 1,
11002 "HTTP/1.1 407 Unauthorized\r\n"
11003 "Proxy-Authenticate: Mock\r\n"
11004 "Content-Length: 0\r\n"
11005 "Proxy-Connection: keep-alive\r\n"
11006 "\r\n"),
11008 // Second connection attempt passes
11009 MockRead(ASYNC, 3, "HTTP/1.1 200 Connected\r\n\r\n"),
11011 // SPDY response
11012 CreateMockRead(*resp.get(), 5), CreateMockRead(*data.get(), 6),
11013 MockRead(ASYNC, 0, 0, 7),
11015 SequencedSocketData data_2(data_reads_2, arraysize(data_reads_2),
11016 data_writes_2, arraysize(data_writes_2));
11018 SSLSocketDataProvider ssl(ASYNC, OK);
11019 ssl.SetNextProto(GetParam());
11020 ssl.cert = ImportCertFromFile(GetTestCertsDirectory(), "spdy_pooling.pem");
11021 ASSERT_TRUE(ssl.cert.get());
11023 MockConnect never_finishing_connect(SYNCHRONOUS, ERR_IO_PENDING);
11024 StaticSocketDataProvider hanging_non_alternate_protocol_socket(
11025 NULL, 0, NULL, 0);
11026 hanging_non_alternate_protocol_socket.set_connect_data(
11027 never_finishing_connect);
11029 session_deps_.socket_factory->AddSocketDataProvider(&data_1);
11030 session_deps_.socket_factory->AddSocketDataProvider(&data_2);
11031 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
11032 session_deps_.socket_factory->AddSocketDataProvider(
11033 &hanging_non_alternate_protocol_socket);
11034 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11036 // First round should work and provide the Alternate-Protocol state.
11037 TestCompletionCallback callback_1;
11038 scoped_ptr<HttpTransaction> trans_1(
11039 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
11040 int rv = trans_1->Start(&request, callback_1.callback(), BoundNetLog());
11041 EXPECT_EQ(ERR_IO_PENDING, rv);
11042 EXPECT_EQ(OK, callback_1.WaitForResult());
11044 // Second round should attempt a tunnel connect and get an auth challenge.
11045 TestCompletionCallback callback_2;
11046 scoped_ptr<HttpTransaction> trans_2(
11047 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
11048 rv = trans_2->Start(&request, callback_2.callback(), BoundNetLog());
11049 EXPECT_EQ(ERR_IO_PENDING, rv);
11050 EXPECT_EQ(OK, callback_2.WaitForResult());
11051 const HttpResponseInfo* response = trans_2->GetResponseInfo();
11052 ASSERT_TRUE(response != NULL);
11053 ASSERT_FALSE(response->auth_challenge.get() == NULL);
11055 // Restart with auth. Tunnel should work and response received.
11056 TestCompletionCallback callback_3;
11057 rv = trans_2->RestartWithAuth(
11058 AuthCredentials(kFoo, kBar), callback_3.callback());
11059 EXPECT_EQ(ERR_IO_PENDING, rv);
11060 EXPECT_EQ(OK, callback_3.WaitForResult());
11062 // After all that work, these two lines (or actually, just the scheme) are
11063 // what this test is all about. Make sure it happens correctly.
11064 EXPECT_EQ("https", request_url.scheme());
11065 EXPECT_EQ("www.example.org", request_url.host());
11067 LoadTimingInfo load_timing_info;
11068 EXPECT_TRUE(trans_2->GetLoadTimingInfo(&load_timing_info));
11069 TestLoadTimingNotReusedWithPac(load_timing_info,
11070 CONNECT_TIMING_HAS_SSL_TIMES);
11073 // Test that if we cancel the transaction as the connection is completing, that
11074 // everything tears down correctly.
11075 TEST_P(HttpNetworkTransactionTest, SimpleCancel) {
11076 // Setup everything about the connection to complete synchronously, so that
11077 // after calling HttpNetworkTransaction::Start, the only thing we're waiting
11078 // for is the callback from the HttpStreamRequest.
11079 // Then cancel the transaction.
11080 // Verify that we don't crash.
11081 MockConnect mock_connect(SYNCHRONOUS, OK);
11082 MockRead data_reads[] = {
11083 MockRead(SYNCHRONOUS, "HTTP/1.0 200 OK\r\n\r\n"),
11084 MockRead(SYNCHRONOUS, "hello world"),
11085 MockRead(SYNCHRONOUS, OK),
11088 HttpRequestInfo request;
11089 request.method = "GET";
11090 request.url = GURL("http://www.example.org/");
11091 request.load_flags = 0;
11093 session_deps_.host_resolver->set_synchronous_mode(true);
11094 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11095 scoped_ptr<HttpTransaction> trans(
11096 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
11098 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
11099 data.set_connect_data(mock_connect);
11100 session_deps_.socket_factory->AddSocketDataProvider(&data);
11102 TestCompletionCallback callback;
11104 BoundTestNetLog log;
11105 int rv = trans->Start(&request, callback.callback(), log.bound());
11106 EXPECT_EQ(ERR_IO_PENDING, rv);
11107 trans.reset(); // Cancel the transaction here.
11109 base::MessageLoop::current()->RunUntilIdle();
11112 // Test that if a transaction is cancelled after receiving the headers, the
11113 // stream is drained properly and added back to the socket pool. The main
11114 // purpose of this test is to make sure that an HttpStreamParser can be read
11115 // from after the HttpNetworkTransaction and the objects it owns have been
11116 // deleted.
11117 // See http://crbug.com/368418
11118 TEST_P(HttpNetworkTransactionTest, CancelAfterHeaders) {
11119 MockRead data_reads[] = {
11120 MockRead(ASYNC, "HTTP/1.1 200 OK\r\n"),
11121 MockRead(ASYNC, "Content-Length: 2\r\n"),
11122 MockRead(ASYNC, "Connection: Keep-Alive\r\n\r\n"),
11123 MockRead(ASYNC, "1"),
11124 // 2 async reads are necessary to trigger a ReadResponseBody call after the
11125 // HttpNetworkTransaction has been deleted.
11126 MockRead(ASYNC, "2"),
11127 MockRead(SYNCHRONOUS, ERR_IO_PENDING), // Should never read this.
11129 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
11130 session_deps_.socket_factory->AddSocketDataProvider(&data);
11132 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11135 HttpRequestInfo request;
11136 request.method = "GET";
11137 request.url = GURL("http://www.example.org/");
11138 request.load_flags = 0;
11140 HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
11141 TestCompletionCallback callback;
11143 int rv = trans.Start(&request, callback.callback(), BoundNetLog());
11144 EXPECT_EQ(ERR_IO_PENDING, rv);
11145 callback.WaitForResult();
11147 const HttpResponseInfo* response = trans.GetResponseInfo();
11148 ASSERT_TRUE(response != NULL);
11149 EXPECT_TRUE(response->headers.get() != NULL);
11150 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
11152 // The transaction and HttpRequestInfo are deleted.
11155 // Let the HttpResponseBodyDrainer drain the socket.
11156 base::MessageLoop::current()->RunUntilIdle();
11158 // Socket should now be idle, waiting to be reused.
11159 EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
11162 // Test a basic GET request through a proxy.
11163 TEST_P(HttpNetworkTransactionTest, ProxyGet) {
11164 session_deps_.proxy_service.reset(
11165 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
11166 BoundTestNetLog log;
11167 session_deps_.net_log = log.bound().net_log();
11168 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11170 HttpRequestInfo request;
11171 request.method = "GET";
11172 request.url = GURL("http://www.example.org/");
11174 MockWrite data_writes1[] = {
11175 MockWrite(
11176 "GET http://www.example.org/ HTTP/1.1\r\n"
11177 "Host: www.example.org\r\n"
11178 "Proxy-Connection: keep-alive\r\n\r\n"),
11181 MockRead data_reads1[] = {
11182 MockRead("HTTP/1.1 200 OK\r\n"),
11183 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
11184 MockRead("Content-Length: 100\r\n\r\n"),
11185 MockRead(SYNCHRONOUS, OK),
11188 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
11189 data_writes1, arraysize(data_writes1));
11190 session_deps_.socket_factory->AddSocketDataProvider(&data1);
11192 TestCompletionCallback callback1;
11194 scoped_ptr<HttpTransaction> trans(
11195 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
11196 BeforeProxyHeadersSentHandler proxy_headers_handler;
11197 trans->SetBeforeProxyHeadersSentCallback(
11198 base::Bind(&BeforeProxyHeadersSentHandler::OnBeforeProxyHeadersSent,
11199 base::Unretained(&proxy_headers_handler)));
11201 int rv = trans->Start(&request, callback1.callback(), log.bound());
11202 EXPECT_EQ(ERR_IO_PENDING, rv);
11204 rv = callback1.WaitForResult();
11205 EXPECT_EQ(OK, rv);
11207 const HttpResponseInfo* response = trans->GetResponseInfo();
11208 ASSERT_TRUE(response != NULL);
11210 EXPECT_TRUE(response->headers->IsKeepAlive());
11211 EXPECT_EQ(200, response->headers->response_code());
11212 EXPECT_EQ(100, response->headers->GetContentLength());
11213 EXPECT_TRUE(response->was_fetched_via_proxy);
11214 EXPECT_TRUE(
11215 response->proxy_server.Equals(HostPortPair::FromString("myproxy:70")));
11216 EXPECT_TRUE(proxy_headers_handler.observed_before_proxy_headers_sent());
11217 EXPECT_EQ("myproxy:70", proxy_headers_handler.observed_proxy_server_uri());
11218 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
11220 LoadTimingInfo load_timing_info;
11221 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
11222 TestLoadTimingNotReusedWithPac(load_timing_info,
11223 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
11226 // Test a basic HTTPS GET request through a proxy.
11227 TEST_P(HttpNetworkTransactionTest, ProxyTunnelGet) {
11228 session_deps_.proxy_service.reset(
11229 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
11230 BoundTestNetLog log;
11231 session_deps_.net_log = log.bound().net_log();
11232 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11234 HttpRequestInfo request;
11235 request.method = "GET";
11236 request.url = GURL("https://www.example.org/");
11238 // Since we have proxy, should try to establish tunnel.
11239 MockWrite data_writes1[] = {
11240 MockWrite(
11241 "CONNECT www.example.org:443 HTTP/1.1\r\n"
11242 "Host: www.example.org\r\n"
11243 "Proxy-Connection: keep-alive\r\n\r\n"),
11245 MockWrite(
11246 "GET / HTTP/1.1\r\n"
11247 "Host: www.example.org\r\n"
11248 "Connection: keep-alive\r\n\r\n"),
11251 MockRead data_reads1[] = {
11252 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
11254 MockRead("HTTP/1.1 200 OK\r\n"),
11255 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
11256 MockRead("Content-Length: 100\r\n\r\n"),
11257 MockRead(SYNCHRONOUS, OK),
11260 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
11261 data_writes1, arraysize(data_writes1));
11262 session_deps_.socket_factory->AddSocketDataProvider(&data1);
11263 SSLSocketDataProvider ssl(ASYNC, OK);
11264 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
11266 TestCompletionCallback callback1;
11268 scoped_ptr<HttpTransaction> trans(
11269 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
11271 int rv = trans->Start(&request, callback1.callback(), log.bound());
11272 EXPECT_EQ(ERR_IO_PENDING, rv);
11274 rv = callback1.WaitForResult();
11275 EXPECT_EQ(OK, rv);
11276 TestNetLogEntry::List entries;
11277 log.GetEntries(&entries);
11278 size_t pos = ExpectLogContainsSomewhere(
11279 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
11280 NetLog::PHASE_NONE);
11281 ExpectLogContainsSomewhere(
11282 entries, pos,
11283 NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
11284 NetLog::PHASE_NONE);
11286 const HttpResponseInfo* response = trans->GetResponseInfo();
11287 ASSERT_TRUE(response != NULL);
11289 EXPECT_TRUE(response->headers->IsKeepAlive());
11290 EXPECT_EQ(200, response->headers->response_code());
11291 EXPECT_EQ(100, response->headers->GetContentLength());
11292 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
11293 EXPECT_TRUE(response->was_fetched_via_proxy);
11294 EXPECT_TRUE(
11295 response->proxy_server.Equals(HostPortPair::FromString("myproxy:70")));
11297 LoadTimingInfo load_timing_info;
11298 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
11299 TestLoadTimingNotReusedWithPac(load_timing_info,
11300 CONNECT_TIMING_HAS_SSL_TIMES);
11303 // Test a basic HTTPS GET request through a proxy, but the server hangs up
11304 // while establishing the tunnel.
11305 TEST_P(HttpNetworkTransactionTest, ProxyTunnelGetHangup) {
11306 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
11307 BoundTestNetLog log;
11308 session_deps_.net_log = log.bound().net_log();
11309 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11311 HttpRequestInfo request;
11312 request.method = "GET";
11313 request.url = GURL("https://www.example.org/");
11315 // Since we have proxy, should try to establish tunnel.
11316 MockWrite data_writes1[] = {
11317 MockWrite(
11318 "CONNECT www.example.org:443 HTTP/1.1\r\n"
11319 "Host: www.example.org\r\n"
11320 "Proxy-Connection: keep-alive\r\n\r\n"),
11322 MockWrite(
11323 "GET / HTTP/1.1\r\n"
11324 "Host: www.example.org\r\n"
11325 "Connection: keep-alive\r\n\r\n"),
11328 MockRead data_reads1[] = {
11329 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
11330 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
11331 MockRead(ASYNC, 0, 0), // EOF
11334 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
11335 data_writes1, arraysize(data_writes1));
11336 session_deps_.socket_factory->AddSocketDataProvider(&data1);
11337 SSLSocketDataProvider ssl(ASYNC, OK);
11338 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
11340 TestCompletionCallback callback1;
11342 scoped_ptr<HttpTransaction> trans(
11343 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
11345 int rv = trans->Start(&request, callback1.callback(), log.bound());
11346 EXPECT_EQ(ERR_IO_PENDING, rv);
11348 rv = callback1.WaitForResult();
11349 EXPECT_EQ(ERR_EMPTY_RESPONSE, rv);
11350 TestNetLogEntry::List entries;
11351 log.GetEntries(&entries);
11352 size_t pos = ExpectLogContainsSomewhere(
11353 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
11354 NetLog::PHASE_NONE);
11355 ExpectLogContainsSomewhere(
11356 entries, pos,
11357 NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
11358 NetLog::PHASE_NONE);
11361 // Test for crbug.com/55424.
11362 TEST_P(HttpNetworkTransactionTest, PreconnectWithExistingSpdySession) {
11363 scoped_ptr<SpdyFrame> req(
11364 spdy_util_.ConstructSpdyGet("https://www.example.org", false, 1, LOWEST));
11365 MockWrite spdy_writes[] = {CreateMockWrite(*req, 0)};
11367 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11368 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
11369 MockRead spdy_reads[] = {
11370 CreateMockRead(*resp, 1), CreateMockRead(*data, 2), MockRead(ASYNC, 0, 3),
11373 SequencedSocketData spdy_data(spdy_reads, arraysize(spdy_reads), spdy_writes,
11374 arraysize(spdy_writes));
11375 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
11377 SSLSocketDataProvider ssl(ASYNC, OK);
11378 ssl.SetNextProto(GetParam());
11379 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
11381 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11383 // Set up an initial SpdySession in the pool to reuse.
11384 HostPortPair host_port_pair("www.example.org", 443);
11385 SpdySessionKey key(host_port_pair, ProxyServer::Direct(),
11386 PRIVACY_MODE_DISABLED);
11387 base::WeakPtr<SpdySession> spdy_session =
11388 CreateInsecureSpdySession(session, key, BoundNetLog());
11390 HttpRequestInfo request;
11391 request.method = "GET";
11392 request.url = GURL("https://www.example.org/");
11393 request.load_flags = 0;
11395 // This is the important line that marks this as a preconnect.
11396 request.motivation = HttpRequestInfo::PRECONNECT_MOTIVATED;
11398 scoped_ptr<HttpTransaction> trans(
11399 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
11401 TestCompletionCallback callback;
11402 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
11403 EXPECT_EQ(ERR_IO_PENDING, rv);
11404 EXPECT_EQ(OK, callback.WaitForResult());
11407 // Given a net error, cause that error to be returned from the first Write()
11408 // call and verify that the HttpTransaction fails with that error.
11409 void HttpNetworkTransactionTest::CheckErrorIsPassedBack(
11410 int error, IoMode mode) {
11411 HttpRequestInfo request_info;
11412 request_info.url = GURL("https://www.example.com/");
11413 request_info.method = "GET";
11414 request_info.load_flags = LOAD_NORMAL;
11416 SSLSocketDataProvider ssl_data(mode, OK);
11417 MockWrite data_writes[] = {
11418 MockWrite(mode, error),
11420 StaticSocketDataProvider data(NULL, 0, data_writes, arraysize(data_writes));
11421 session_deps_.socket_factory->AddSocketDataProvider(&data);
11422 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data);
11424 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11425 scoped_ptr<HttpTransaction> trans(
11426 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
11428 TestCompletionCallback callback;
11429 int rv = trans->Start(&request_info, callback.callback(), BoundNetLog());
11430 if (rv == ERR_IO_PENDING)
11431 rv = callback.WaitForResult();
11432 ASSERT_EQ(error, rv);
11435 TEST_P(HttpNetworkTransactionTest, SSLWriteCertError) {
11436 // Just check a grab bag of cert errors.
11437 static const int kErrors[] = {
11438 ERR_CERT_COMMON_NAME_INVALID,
11439 ERR_CERT_AUTHORITY_INVALID,
11440 ERR_CERT_DATE_INVALID,
11442 for (size_t i = 0; i < arraysize(kErrors); i++) {
11443 CheckErrorIsPassedBack(kErrors[i], ASYNC);
11444 CheckErrorIsPassedBack(kErrors[i], SYNCHRONOUS);
11448 // Ensure that a client certificate is removed from the SSL client auth
11449 // cache when:
11450 // 1) No proxy is involved.
11451 // 2) TLS False Start is disabled.
11452 // 3) The initial TLS handshake requests a client certificate.
11453 // 4) The client supplies an invalid/unacceptable certificate.
11454 TEST_P(HttpNetworkTransactionTest,
11455 ClientAuthCertCache_Direct_NoFalseStart) {
11456 HttpRequestInfo request_info;
11457 request_info.url = GURL("https://www.example.com/");
11458 request_info.method = "GET";
11459 request_info.load_flags = LOAD_NORMAL;
11461 scoped_refptr<SSLCertRequestInfo> cert_request(new SSLCertRequestInfo());
11462 cert_request->host_and_port = HostPortPair("www.example.com", 443);
11464 // [ssl_]data1 contains the data for the first SSL handshake. When a
11465 // CertificateRequest is received for the first time, the handshake will
11466 // be aborted to allow the caller to provide a certificate.
11467 SSLSocketDataProvider ssl_data1(ASYNC, ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
11468 ssl_data1.cert_request_info = cert_request.get();
11469 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data1);
11470 StaticSocketDataProvider data1(NULL, 0, NULL, 0);
11471 session_deps_.socket_factory->AddSocketDataProvider(&data1);
11473 // [ssl_]data2 contains the data for the second SSL handshake. When TLS
11474 // False Start is not being used, the result of the SSL handshake will be
11475 // returned as part of the SSLClientSocket::Connect() call. This test
11476 // matches the result of a server sending a handshake_failure alert,
11477 // rather than a Finished message, because it requires a client
11478 // certificate and none was supplied.
11479 SSLSocketDataProvider ssl_data2(ASYNC, ERR_SSL_PROTOCOL_ERROR);
11480 ssl_data2.cert_request_info = cert_request.get();
11481 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data2);
11482 StaticSocketDataProvider data2(NULL, 0, NULL, 0);
11483 session_deps_.socket_factory->AddSocketDataProvider(&data2);
11485 // [ssl_]data3 contains the data for the third SSL handshake. When a
11486 // connection to a server fails during an SSL handshake,
11487 // HttpNetworkTransaction will attempt to fallback to TLSv1.1 if the previous
11488 // connection was attempted with TLSv1.2. This is transparent to the caller
11489 // of the HttpNetworkTransaction. Because this test failure is due to
11490 // requiring a client certificate, this fallback handshake should also
11491 // fail.
11492 SSLSocketDataProvider ssl_data3(ASYNC, ERR_SSL_PROTOCOL_ERROR);
11493 ssl_data3.cert_request_info = cert_request.get();
11494 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data3);
11495 StaticSocketDataProvider data3(NULL, 0, NULL, 0);
11496 session_deps_.socket_factory->AddSocketDataProvider(&data3);
11498 // [ssl_]data4 contains the data for the fourth SSL handshake. When a
11499 // connection to a server fails during an SSL handshake,
11500 // HttpNetworkTransaction will attempt to fallback to TLSv1 if the previous
11501 // connection was attempted with TLSv1.1. This is transparent to the caller
11502 // of the HttpNetworkTransaction. Because this test failure is due to
11503 // requiring a client certificate, this fallback handshake should also
11504 // fail.
11505 SSLSocketDataProvider ssl_data4(ASYNC, ERR_SSL_PROTOCOL_ERROR);
11506 ssl_data4.cert_request_info = cert_request.get();
11507 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data4);
11508 StaticSocketDataProvider data4(NULL, 0, NULL, 0);
11509 session_deps_.socket_factory->AddSocketDataProvider(&data4);
11511 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11512 scoped_ptr<HttpTransaction> trans(
11513 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
11515 // Begin the SSL handshake with the peer. This consumes ssl_data1.
11516 TestCompletionCallback callback;
11517 int rv = trans->Start(&request_info, callback.callback(), BoundNetLog());
11518 ASSERT_EQ(ERR_IO_PENDING, rv);
11520 // Complete the SSL handshake, which should abort due to requiring a
11521 // client certificate.
11522 rv = callback.WaitForResult();
11523 ASSERT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
11525 // Indicate that no certificate should be supplied. From the perspective
11526 // of SSLClientCertCache, NULL is just as meaningful as a real
11527 // certificate, so this is the same as supply a
11528 // legitimate-but-unacceptable certificate.
11529 rv = trans->RestartWithCertificate(NULL, callback.callback());
11530 ASSERT_EQ(ERR_IO_PENDING, rv);
11532 // Ensure the certificate was added to the client auth cache before
11533 // allowing the connection to continue restarting.
11534 scoped_refptr<X509Certificate> client_cert;
11535 ASSERT_TRUE(session->ssl_client_auth_cache()->Lookup(
11536 HostPortPair("www.example.com", 443), &client_cert));
11537 ASSERT_EQ(NULL, client_cert.get());
11539 // Restart the handshake. This will consume ssl_data2, which fails, and
11540 // then consume ssl_data3 and ssl_data4, both of which should also fail.
11541 // The result code is checked against what ssl_data4 should return.
11542 rv = callback.WaitForResult();
11543 ASSERT_EQ(ERR_SSL_PROTOCOL_ERROR, rv);
11545 // Ensure that the client certificate is removed from the cache on a
11546 // handshake failure.
11547 ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
11548 HostPortPair("www.example.com", 443), &client_cert));
11551 // Ensure that a client certificate is removed from the SSL client auth
11552 // cache when:
11553 // 1) No proxy is involved.
11554 // 2) TLS False Start is enabled.
11555 // 3) The initial TLS handshake requests a client certificate.
11556 // 4) The client supplies an invalid/unacceptable certificate.
11557 TEST_P(HttpNetworkTransactionTest,
11558 ClientAuthCertCache_Direct_FalseStart) {
11559 HttpRequestInfo request_info;
11560 request_info.url = GURL("https://www.example.com/");
11561 request_info.method = "GET";
11562 request_info.load_flags = LOAD_NORMAL;
11564 scoped_refptr<SSLCertRequestInfo> cert_request(new SSLCertRequestInfo());
11565 cert_request->host_and_port = HostPortPair("www.example.com", 443);
11567 // When TLS False Start is used, SSLClientSocket::Connect() calls will
11568 // return successfully after reading up to the peer's Certificate message.
11569 // This is to allow the caller to call SSLClientSocket::Write(), which can
11570 // enqueue application data to be sent in the same packet as the
11571 // ChangeCipherSpec and Finished messages.
11572 // The actual handshake will be finished when SSLClientSocket::Read() is
11573 // called, which expects to process the peer's ChangeCipherSpec and
11574 // Finished messages. If there was an error negotiating with the peer,
11575 // such as due to the peer requiring a client certificate when none was
11576 // supplied, the alert sent by the peer won't be processed until Read() is
11577 // called.
11579 // Like the non-False Start case, when a client certificate is requested by
11580 // the peer, the handshake is aborted during the Connect() call.
11581 // [ssl_]data1 represents the initial SSL handshake with the peer.
11582 SSLSocketDataProvider ssl_data1(ASYNC, ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
11583 ssl_data1.cert_request_info = cert_request.get();
11584 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data1);
11585 StaticSocketDataProvider data1(NULL, 0, NULL, 0);
11586 session_deps_.socket_factory->AddSocketDataProvider(&data1);
11588 // When a client certificate is supplied, Connect() will not be aborted
11589 // when the peer requests the certificate. Instead, the handshake will
11590 // artificially succeed, allowing the caller to write the HTTP request to
11591 // the socket. The handshake messages are not processed until Read() is
11592 // called, which then detects that the handshake was aborted, due to the
11593 // peer sending a handshake_failure because it requires a client
11594 // certificate.
11595 SSLSocketDataProvider ssl_data2(ASYNC, OK);
11596 ssl_data2.cert_request_info = cert_request.get();
11597 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data2);
11598 MockRead data2_reads[] = {
11599 MockRead(ASYNC /* async */, ERR_SSL_PROTOCOL_ERROR),
11601 StaticSocketDataProvider data2(data2_reads, arraysize(data2_reads), NULL, 0);
11602 session_deps_.socket_factory->AddSocketDataProvider(&data2);
11604 // As described in ClientAuthCertCache_Direct_NoFalseStart, [ssl_]data3 is
11605 // the data for the SSL handshake once the TLSv1.1 connection falls back to
11606 // TLSv1. It has the same behaviour as [ssl_]data2.
11607 SSLSocketDataProvider ssl_data3(ASYNC, OK);
11608 ssl_data3.cert_request_info = cert_request.get();
11609 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data3);
11610 StaticSocketDataProvider data3(data2_reads, arraysize(data2_reads), NULL, 0);
11611 session_deps_.socket_factory->AddSocketDataProvider(&data3);
11613 // [ssl_]data4 is the data for the SSL handshake once the TLSv1 connection
11614 // falls back to SSLv3. It has the same behaviour as [ssl_]data2.
11615 SSLSocketDataProvider ssl_data4(ASYNC, OK);
11616 ssl_data4.cert_request_info = cert_request.get();
11617 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data4);
11618 StaticSocketDataProvider data4(data2_reads, arraysize(data2_reads), NULL, 0);
11619 session_deps_.socket_factory->AddSocketDataProvider(&data4);
11621 // Need one more if TLSv1.2 is enabled.
11622 SSLSocketDataProvider ssl_data5(ASYNC, OK);
11623 ssl_data5.cert_request_info = cert_request.get();
11624 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data5);
11625 StaticSocketDataProvider data5(data2_reads, arraysize(data2_reads), NULL, 0);
11626 session_deps_.socket_factory->AddSocketDataProvider(&data5);
11628 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11629 scoped_ptr<HttpTransaction> trans(
11630 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
11632 // Begin the initial SSL handshake.
11633 TestCompletionCallback callback;
11634 int rv = trans->Start(&request_info, callback.callback(), BoundNetLog());
11635 ASSERT_EQ(ERR_IO_PENDING, rv);
11637 // Complete the SSL handshake, which should abort due to requiring a
11638 // client certificate.
11639 rv = callback.WaitForResult();
11640 ASSERT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
11642 // Indicate that no certificate should be supplied. From the perspective
11643 // of SSLClientCertCache, NULL is just as meaningful as a real
11644 // certificate, so this is the same as supply a
11645 // legitimate-but-unacceptable certificate.
11646 rv = trans->RestartWithCertificate(NULL, callback.callback());
11647 ASSERT_EQ(ERR_IO_PENDING, rv);
11649 // Ensure the certificate was added to the client auth cache before
11650 // allowing the connection to continue restarting.
11651 scoped_refptr<X509Certificate> client_cert;
11652 ASSERT_TRUE(session->ssl_client_auth_cache()->Lookup(
11653 HostPortPair("www.example.com", 443), &client_cert));
11654 ASSERT_EQ(NULL, client_cert.get());
11656 // Restart the handshake. This will consume ssl_data2, which fails, and
11657 // then consume ssl_data3 and ssl_data4, both of which should also fail.
11658 // The result code is checked against what ssl_data4 should return.
11659 rv = callback.WaitForResult();
11660 ASSERT_EQ(ERR_SSL_PROTOCOL_ERROR, rv);
11662 // Ensure that the client certificate is removed from the cache on a
11663 // handshake failure.
11664 ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
11665 HostPortPair("www.example.com", 443), &client_cert));
11668 // Ensure that a client certificate is removed from the SSL client auth
11669 // cache when:
11670 // 1) An HTTPS proxy is involved.
11671 // 3) The HTTPS proxy requests a client certificate.
11672 // 4) The client supplies an invalid/unacceptable certificate for the
11673 // proxy.
11674 // The test is repeated twice, first for connecting to an HTTPS endpoint,
11675 // then for connecting to an HTTP endpoint.
11676 TEST_P(HttpNetworkTransactionTest, ClientAuthCertCache_Proxy_Fail) {
11677 session_deps_.proxy_service.reset(
11678 ProxyService::CreateFixed("https://proxy:70"));
11679 BoundTestNetLog log;
11680 session_deps_.net_log = log.bound().net_log();
11682 scoped_refptr<SSLCertRequestInfo> cert_request(new SSLCertRequestInfo());
11683 cert_request->host_and_port = HostPortPair("proxy", 70);
11685 // See ClientAuthCertCache_Direct_NoFalseStart for the explanation of
11686 // [ssl_]data[1-3]. Rather than represending the endpoint
11687 // (www.example.com:443), they represent failures with the HTTPS proxy
11688 // (proxy:70).
11689 SSLSocketDataProvider ssl_data1(ASYNC, ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
11690 ssl_data1.cert_request_info = cert_request.get();
11691 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data1);
11692 StaticSocketDataProvider data1(NULL, 0, NULL, 0);
11693 session_deps_.socket_factory->AddSocketDataProvider(&data1);
11695 SSLSocketDataProvider ssl_data2(ASYNC, ERR_SSL_PROTOCOL_ERROR);
11696 ssl_data2.cert_request_info = cert_request.get();
11697 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data2);
11698 StaticSocketDataProvider data2(NULL, 0, NULL, 0);
11699 session_deps_.socket_factory->AddSocketDataProvider(&data2);
11701 // TODO(wtc): find out why this unit test doesn't need [ssl_]data3.
11702 #if 0
11703 SSLSocketDataProvider ssl_data3(ASYNC, ERR_SSL_PROTOCOL_ERROR);
11704 ssl_data3.cert_request_info = cert_request.get();
11705 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data3);
11706 StaticSocketDataProvider data3(NULL, 0, NULL, 0);
11707 session_deps_.socket_factory->AddSocketDataProvider(&data3);
11708 #endif
11710 HttpRequestInfo requests[2];
11711 requests[0].url = GURL("https://www.example.com/");
11712 requests[0].method = "GET";
11713 requests[0].load_flags = LOAD_NORMAL;
11715 requests[1].url = GURL("http://www.example.com/");
11716 requests[1].method = "GET";
11717 requests[1].load_flags = LOAD_NORMAL;
11719 for (size_t i = 0; i < arraysize(requests); ++i) {
11720 session_deps_.socket_factory->ResetNextMockIndexes();
11721 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11722 scoped_ptr<HttpNetworkTransaction> trans(
11723 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
11725 // Begin the SSL handshake with the proxy.
11726 TestCompletionCallback callback;
11727 int rv = trans->Start(&requests[i], callback.callback(), BoundNetLog());
11728 ASSERT_EQ(ERR_IO_PENDING, rv);
11730 // Complete the SSL handshake, which should abort due to requiring a
11731 // client certificate.
11732 rv = callback.WaitForResult();
11733 ASSERT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
11735 // Indicate that no certificate should be supplied. From the perspective
11736 // of SSLClientCertCache, NULL is just as meaningful as a real
11737 // certificate, so this is the same as supply a
11738 // legitimate-but-unacceptable certificate.
11739 rv = trans->RestartWithCertificate(NULL, callback.callback());
11740 ASSERT_EQ(ERR_IO_PENDING, rv);
11742 // Ensure the certificate was added to the client auth cache before
11743 // allowing the connection to continue restarting.
11744 scoped_refptr<X509Certificate> client_cert;
11745 ASSERT_TRUE(session->ssl_client_auth_cache()->Lookup(
11746 HostPortPair("proxy", 70), &client_cert));
11747 ASSERT_EQ(NULL, client_cert.get());
11748 // Ensure the certificate was NOT cached for the endpoint. This only
11749 // applies to HTTPS requests, but is fine to check for HTTP requests.
11750 ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
11751 HostPortPair("www.example.com", 443), &client_cert));
11753 // Restart the handshake. This will consume ssl_data2, which fails, and
11754 // then consume ssl_data3, which should also fail. The result code is
11755 // checked against what ssl_data3 should return.
11756 rv = callback.WaitForResult();
11757 ASSERT_EQ(ERR_PROXY_CONNECTION_FAILED, rv);
11759 // Now that the new handshake has failed, ensure that the client
11760 // certificate was removed from the client auth cache.
11761 ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
11762 HostPortPair("proxy", 70), &client_cert));
11763 ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
11764 HostPortPair("www.example.com", 443), &client_cert));
11768 TEST_P(HttpNetworkTransactionTest, UseIPConnectionPooling) {
11769 session_deps_.use_alternative_services = true;
11770 session_deps_.next_protos = SpdyNextProtos();
11772 // Set up a special HttpNetworkSession with a MockCachingHostResolver.
11773 session_deps_.host_resolver.reset(new MockCachingHostResolver());
11774 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11775 SpdySessionPoolPeer pool_peer(session->spdy_session_pool());
11776 pool_peer.DisableDomainAuthenticationVerification();
11778 SSLSocketDataProvider ssl(ASYNC, OK);
11779 ssl.SetNextProto(GetParam());
11780 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
11782 scoped_ptr<SpdyFrame> host1_req(
11783 spdy_util_.ConstructSpdyGet("https://www.example.org", false, 1, LOWEST));
11784 scoped_ptr<SpdyFrame> host2_req(
11785 spdy_util_.ConstructSpdyGet("https://www.gmail.com", false, 3, LOWEST));
11786 MockWrite spdy_writes[] = {
11787 CreateMockWrite(*host1_req, 0), CreateMockWrite(*host2_req, 3),
11789 scoped_ptr<SpdyFrame> host1_resp(
11790 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11791 scoped_ptr<SpdyFrame> host1_resp_body(
11792 spdy_util_.ConstructSpdyBodyFrame(1, true));
11793 scoped_ptr<SpdyFrame> host2_resp(
11794 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
11795 scoped_ptr<SpdyFrame> host2_resp_body(
11796 spdy_util_.ConstructSpdyBodyFrame(3, true));
11797 MockRead spdy_reads[] = {
11798 CreateMockRead(*host1_resp, 1),
11799 CreateMockRead(*host1_resp_body, 2),
11800 CreateMockRead(*host2_resp, 4),
11801 CreateMockRead(*host2_resp_body, 5),
11802 MockRead(ASYNC, 0, 6),
11805 IPAddressNumber ip;
11806 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &ip));
11807 IPEndPoint peer_addr = IPEndPoint(ip, 443);
11808 MockConnect connect(ASYNC, OK, peer_addr);
11809 SequencedSocketData spdy_data(connect, spdy_reads, arraysize(spdy_reads),
11810 spdy_writes, arraysize(spdy_writes));
11811 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
11813 TestCompletionCallback callback;
11814 HttpRequestInfo request1;
11815 request1.method = "GET";
11816 request1.url = GURL("https://www.example.org/");
11817 request1.load_flags = 0;
11818 HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
11820 int rv = trans1.Start(&request1, callback.callback(), BoundNetLog());
11821 EXPECT_EQ(ERR_IO_PENDING, rv);
11822 EXPECT_EQ(OK, callback.WaitForResult());
11824 const HttpResponseInfo* response = trans1.GetResponseInfo();
11825 ASSERT_TRUE(response != NULL);
11826 ASSERT_TRUE(response->headers.get() != NULL);
11827 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
11829 std::string response_data;
11830 ASSERT_EQ(OK, ReadTransaction(&trans1, &response_data));
11831 EXPECT_EQ("hello!", response_data);
11833 // Preload www.gmail.com into HostCache.
11834 HostPortPair host_port("www.gmail.com", 443);
11835 HostResolver::RequestInfo resolve_info(host_port);
11836 AddressList ignored;
11837 rv = session_deps_.host_resolver->Resolve(resolve_info,
11838 DEFAULT_PRIORITY,
11839 &ignored,
11840 callback.callback(),
11841 NULL,
11842 BoundNetLog());
11843 EXPECT_EQ(ERR_IO_PENDING, rv);
11844 rv = callback.WaitForResult();
11845 EXPECT_EQ(OK, rv);
11847 HttpRequestInfo request2;
11848 request2.method = "GET";
11849 request2.url = GURL("https://www.gmail.com/");
11850 request2.load_flags = 0;
11851 HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
11853 rv = trans2.Start(&request2, callback.callback(), BoundNetLog());
11854 EXPECT_EQ(ERR_IO_PENDING, rv);
11855 EXPECT_EQ(OK, callback.WaitForResult());
11857 response = trans2.GetResponseInfo();
11858 ASSERT_TRUE(response != NULL);
11859 ASSERT_TRUE(response->headers.get() != NULL);
11860 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
11861 EXPECT_TRUE(response->was_fetched_via_spdy);
11862 EXPECT_TRUE(response->was_npn_negotiated);
11863 ASSERT_EQ(OK, ReadTransaction(&trans2, &response_data));
11864 EXPECT_EQ("hello!", response_data);
11867 TEST_P(HttpNetworkTransactionTest, UseIPConnectionPoolingAfterResolution) {
11868 session_deps_.use_alternative_services = true;
11869 session_deps_.next_protos = SpdyNextProtos();
11871 // Set up a special HttpNetworkSession with a MockCachingHostResolver.
11872 session_deps_.host_resolver.reset(new MockCachingHostResolver());
11873 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11874 SpdySessionPoolPeer pool_peer(session->spdy_session_pool());
11875 pool_peer.DisableDomainAuthenticationVerification();
11877 SSLSocketDataProvider ssl(ASYNC, OK);
11878 ssl.SetNextProto(GetParam());
11879 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
11881 scoped_ptr<SpdyFrame> host1_req(
11882 spdy_util_.ConstructSpdyGet("https://www.example.org", false, 1, LOWEST));
11883 scoped_ptr<SpdyFrame> host2_req(
11884 spdy_util_.ConstructSpdyGet("https://www.gmail.com", false, 3, LOWEST));
11885 MockWrite spdy_writes[] = {
11886 CreateMockWrite(*host1_req, 0), CreateMockWrite(*host2_req, 3),
11888 scoped_ptr<SpdyFrame> host1_resp(
11889 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11890 scoped_ptr<SpdyFrame> host1_resp_body(
11891 spdy_util_.ConstructSpdyBodyFrame(1, true));
11892 scoped_ptr<SpdyFrame> host2_resp(
11893 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
11894 scoped_ptr<SpdyFrame> host2_resp_body(
11895 spdy_util_.ConstructSpdyBodyFrame(3, true));
11896 MockRead spdy_reads[] = {
11897 CreateMockRead(*host1_resp, 1),
11898 CreateMockRead(*host1_resp_body, 2),
11899 CreateMockRead(*host2_resp, 4),
11900 CreateMockRead(*host2_resp_body, 5),
11901 MockRead(ASYNC, 0, 6),
11904 IPAddressNumber ip;
11905 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &ip));
11906 IPEndPoint peer_addr = IPEndPoint(ip, 443);
11907 MockConnect connect(ASYNC, OK, peer_addr);
11908 SequencedSocketData spdy_data(connect, spdy_reads, arraysize(spdy_reads),
11909 spdy_writes, arraysize(spdy_writes));
11910 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
11912 TestCompletionCallback callback;
11913 HttpRequestInfo request1;
11914 request1.method = "GET";
11915 request1.url = GURL("https://www.example.org/");
11916 request1.load_flags = 0;
11917 HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
11919 int rv = trans1.Start(&request1, callback.callback(), BoundNetLog());
11920 EXPECT_EQ(ERR_IO_PENDING, rv);
11921 EXPECT_EQ(OK, callback.WaitForResult());
11923 const HttpResponseInfo* response = trans1.GetResponseInfo();
11924 ASSERT_TRUE(response != NULL);
11925 ASSERT_TRUE(response->headers.get() != NULL);
11926 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
11928 std::string response_data;
11929 ASSERT_EQ(OK, ReadTransaction(&trans1, &response_data));
11930 EXPECT_EQ("hello!", response_data);
11932 HttpRequestInfo request2;
11933 request2.method = "GET";
11934 request2.url = GURL("https://www.gmail.com/");
11935 request2.load_flags = 0;
11936 HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
11938 rv = trans2.Start(&request2, callback.callback(), BoundNetLog());
11939 EXPECT_EQ(ERR_IO_PENDING, rv);
11940 EXPECT_EQ(OK, callback.WaitForResult());
11942 response = trans2.GetResponseInfo();
11943 ASSERT_TRUE(response != NULL);
11944 ASSERT_TRUE(response->headers.get() != NULL);
11945 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
11946 EXPECT_TRUE(response->was_fetched_via_spdy);
11947 EXPECT_TRUE(response->was_npn_negotiated);
11948 ASSERT_EQ(OK, ReadTransaction(&trans2, &response_data));
11949 EXPECT_EQ("hello!", response_data);
11952 class OneTimeCachingHostResolver : public HostResolver {
11953 public:
11954 explicit OneTimeCachingHostResolver(const HostPortPair& host_port)
11955 : host_port_(host_port) {}
11956 ~OneTimeCachingHostResolver() override {}
11958 RuleBasedHostResolverProc* rules() { return host_resolver_.rules(); }
11960 // HostResolver methods:
11961 int Resolve(const RequestInfo& info,
11962 RequestPriority priority,
11963 AddressList* addresses,
11964 const CompletionCallback& callback,
11965 RequestHandle* out_req,
11966 const BoundNetLog& net_log) override {
11967 return host_resolver_.Resolve(
11968 info, priority, addresses, callback, out_req, net_log);
11971 int ResolveFromCache(const RequestInfo& info,
11972 AddressList* addresses,
11973 const BoundNetLog& net_log) override {
11974 int rv = host_resolver_.ResolveFromCache(info, addresses, net_log);
11975 if (rv == OK && info.host_port_pair().Equals(host_port_))
11976 host_resolver_.GetHostCache()->clear();
11977 return rv;
11980 void CancelRequest(RequestHandle req) override {
11981 host_resolver_.CancelRequest(req);
11984 MockCachingHostResolver* GetMockHostResolver() {
11985 return &host_resolver_;
11988 private:
11989 MockCachingHostResolver host_resolver_;
11990 const HostPortPair host_port_;
11993 TEST_P(HttpNetworkTransactionTest,
11994 UseIPConnectionPoolingWithHostCacheExpiration) {
11995 session_deps_.use_alternative_services = true;
11996 session_deps_.next_protos = SpdyNextProtos();
11998 // Set up a special HttpNetworkSession with a OneTimeCachingHostResolver.
11999 OneTimeCachingHostResolver host_resolver(HostPortPair("www.gmail.com", 443));
12000 HttpNetworkSession::Params params =
12001 SpdySessionDependencies::CreateSessionParams(&session_deps_);
12002 params.host_resolver = &host_resolver;
12003 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12004 SpdySessionPoolPeer pool_peer(session->spdy_session_pool());
12005 pool_peer.DisableDomainAuthenticationVerification();
12007 SSLSocketDataProvider ssl(ASYNC, OK);
12008 ssl.SetNextProto(GetParam());
12009 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
12011 scoped_ptr<SpdyFrame> host1_req(
12012 spdy_util_.ConstructSpdyGet("https://www.example.org", false, 1, LOWEST));
12013 scoped_ptr<SpdyFrame> host2_req(
12014 spdy_util_.ConstructSpdyGet("https://www.gmail.com", false, 3, LOWEST));
12015 MockWrite spdy_writes[] = {
12016 CreateMockWrite(*host1_req, 0), CreateMockWrite(*host2_req, 3),
12018 scoped_ptr<SpdyFrame> host1_resp(
12019 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
12020 scoped_ptr<SpdyFrame> host1_resp_body(
12021 spdy_util_.ConstructSpdyBodyFrame(1, true));
12022 scoped_ptr<SpdyFrame> host2_resp(
12023 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
12024 scoped_ptr<SpdyFrame> host2_resp_body(
12025 spdy_util_.ConstructSpdyBodyFrame(3, true));
12026 MockRead spdy_reads[] = {
12027 CreateMockRead(*host1_resp, 1),
12028 CreateMockRead(*host1_resp_body, 2),
12029 CreateMockRead(*host2_resp, 4),
12030 CreateMockRead(*host2_resp_body, 5),
12031 MockRead(ASYNC, 0, 6),
12034 IPAddressNumber ip;
12035 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &ip));
12036 IPEndPoint peer_addr = IPEndPoint(ip, 443);
12037 MockConnect connect(ASYNC, OK, peer_addr);
12038 SequencedSocketData spdy_data(connect, spdy_reads, arraysize(spdy_reads),
12039 spdy_writes, arraysize(spdy_writes));
12040 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
12042 TestCompletionCallback callback;
12043 HttpRequestInfo request1;
12044 request1.method = "GET";
12045 request1.url = GURL("https://www.example.org/");
12046 request1.load_flags = 0;
12047 HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
12049 int rv = trans1.Start(&request1, callback.callback(), BoundNetLog());
12050 EXPECT_EQ(ERR_IO_PENDING, rv);
12051 EXPECT_EQ(OK, callback.WaitForResult());
12053 const HttpResponseInfo* response = trans1.GetResponseInfo();
12054 ASSERT_TRUE(response != NULL);
12055 ASSERT_TRUE(response->headers.get() != NULL);
12056 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
12058 std::string response_data;
12059 ASSERT_EQ(OK, ReadTransaction(&trans1, &response_data));
12060 EXPECT_EQ("hello!", response_data);
12062 // Preload cache entries into HostCache.
12063 HostResolver::RequestInfo resolve_info(HostPortPair("www.gmail.com", 443));
12064 AddressList ignored;
12065 rv = host_resolver.Resolve(resolve_info,
12066 DEFAULT_PRIORITY,
12067 &ignored,
12068 callback.callback(),
12069 NULL,
12070 BoundNetLog());
12071 EXPECT_EQ(ERR_IO_PENDING, rv);
12072 rv = callback.WaitForResult();
12073 EXPECT_EQ(OK, rv);
12075 HttpRequestInfo request2;
12076 request2.method = "GET";
12077 request2.url = GURL("https://www.gmail.com/");
12078 request2.load_flags = 0;
12079 HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
12081 rv = trans2.Start(&request2, callback.callback(), BoundNetLog());
12082 EXPECT_EQ(ERR_IO_PENDING, rv);
12083 EXPECT_EQ(OK, callback.WaitForResult());
12085 response = trans2.GetResponseInfo();
12086 ASSERT_TRUE(response != NULL);
12087 ASSERT_TRUE(response->headers.get() != NULL);
12088 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
12089 EXPECT_TRUE(response->was_fetched_via_spdy);
12090 EXPECT_TRUE(response->was_npn_negotiated);
12091 ASSERT_EQ(OK, ReadTransaction(&trans2, &response_data));
12092 EXPECT_EQ("hello!", response_data);
12095 TEST_P(HttpNetworkTransactionTest, DoNotUseSpdySessionForHttp) {
12096 const std::string https_url = "https://www.example.org:8080/";
12097 const std::string http_url = "http://www.example.org:8080/";
12099 // SPDY GET for HTTPS URL
12100 scoped_ptr<SpdyFrame> req1(
12101 spdy_util_.ConstructSpdyGet(https_url.c_str(), false, 1, LOWEST));
12103 MockWrite writes1[] = {
12104 CreateMockWrite(*req1, 0),
12107 scoped_ptr<SpdyFrame> resp1(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
12108 scoped_ptr<SpdyFrame> body1(spdy_util_.ConstructSpdyBodyFrame(1, true));
12109 MockRead reads1[] = {
12110 CreateMockRead(*resp1, 1),
12111 CreateMockRead(*body1, 2),
12112 MockRead(ASYNC, ERR_IO_PENDING, 3)
12115 SequencedSocketData data1(reads1, arraysize(reads1), writes1,
12116 arraysize(writes1));
12117 MockConnect connect_data1(ASYNC, OK);
12118 data1.set_connect_data(connect_data1);
12120 // HTTP GET for the HTTP URL
12121 MockWrite writes2[] = {
12122 MockWrite(ASYNC, 0,
12123 "GET / HTTP/1.1\r\n"
12124 "Host: www.example.org:8080\r\n"
12125 "Connection: keep-alive\r\n\r\n"),
12128 MockRead reads2[] = {
12129 MockRead(ASYNC, 1, "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
12130 MockRead(ASYNC, 2, "hello"),
12131 MockRead(ASYNC, OK, 3),
12134 SequencedSocketData data2(reads2, arraysize(reads2), writes2,
12135 arraysize(writes2));
12137 SSLSocketDataProvider ssl(ASYNC, OK);
12138 ssl.SetNextProto(GetParam());
12139 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
12140 session_deps_.socket_factory->AddSocketDataProvider(&data1);
12141 session_deps_.socket_factory->AddSocketDataProvider(&data2);
12143 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12145 // Start the first transaction to set up the SpdySession
12146 HttpRequestInfo request1;
12147 request1.method = "GET";
12148 request1.url = GURL(https_url);
12149 request1.load_flags = 0;
12150 HttpNetworkTransaction trans1(LOWEST, session.get());
12151 TestCompletionCallback callback1;
12152 EXPECT_EQ(ERR_IO_PENDING,
12153 trans1.Start(&request1, callback1.callback(), BoundNetLog()));
12154 base::MessageLoop::current()->RunUntilIdle();
12156 EXPECT_EQ(OK, callback1.WaitForResult());
12157 EXPECT_TRUE(trans1.GetResponseInfo()->was_fetched_via_spdy);
12159 // Now, start the HTTP request
12160 HttpRequestInfo request2;
12161 request2.method = "GET";
12162 request2.url = GURL(http_url);
12163 request2.load_flags = 0;
12164 HttpNetworkTransaction trans2(MEDIUM, session.get());
12165 TestCompletionCallback callback2;
12166 EXPECT_EQ(ERR_IO_PENDING,
12167 trans2.Start(&request2, callback2.callback(), BoundNetLog()));
12168 base::MessageLoop::current()->RunUntilIdle();
12170 EXPECT_EQ(OK, callback2.WaitForResult());
12171 EXPECT_FALSE(trans2.GetResponseInfo()->was_fetched_via_spdy);
12174 class AltSvcCertificateVerificationTest : public HttpNetworkTransactionTest {
12175 public:
12176 void Run(bool pooling, bool valid) {
12177 HostPortPair origin(valid ? "mail.example.org" : "invalid.example.org",
12178 443);
12179 HostPortPair alternative("www.example.org", 443);
12181 base::FilePath certs_dir = GetTestCertsDirectory();
12182 scoped_refptr<X509Certificate> cert(
12183 ImportCertFromFile(certs_dir, "spdy_pooling.pem"));
12184 ASSERT_TRUE(cert.get());
12185 bool common_name_fallback_used;
12186 EXPECT_EQ(valid,
12187 cert->VerifyNameMatch(origin.host(), &common_name_fallback_used));
12188 EXPECT_TRUE(
12189 cert->VerifyNameMatch(alternative.host(), &common_name_fallback_used));
12190 SSLSocketDataProvider ssl(ASYNC, OK);
12191 ssl.SetNextProto(GetParam());
12192 ssl.cert = cert;
12193 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
12195 // If pooling, then start a request to alternative first to create a
12196 // SpdySession.
12197 std::string url0 = "https://www.example.org:443";
12198 // Second request to origin, which has an alternative service, and could
12199 // open a connection to the alternative host or pool to the existing one.
12200 std::string url1("https://");
12201 url1.append(origin.host());
12202 url1.append(":443");
12204 scoped_ptr<SpdyFrame> req0;
12205 scoped_ptr<SpdyFrame> req1;
12206 scoped_ptr<SpdyFrame> resp0;
12207 scoped_ptr<SpdyFrame> body0;
12208 scoped_ptr<SpdyFrame> resp1;
12209 scoped_ptr<SpdyFrame> body1;
12210 std::vector<MockWrite> writes;
12211 std::vector<MockRead> reads;
12213 if (pooling) {
12214 req0.reset(spdy_util_.ConstructSpdyGet(url0.c_str(), false, 1, LOWEST));
12215 req1.reset(spdy_util_.ConstructSpdyGet(url1.c_str(), false, 3, LOWEST));
12217 writes.push_back(CreateMockWrite(*req0, 0));
12218 writes.push_back(CreateMockWrite(*req1, 3));
12220 resp0.reset(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
12221 body0.reset(spdy_util_.ConstructSpdyBodyFrame(1, true));
12222 resp1.reset(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
12223 body1.reset(spdy_util_.ConstructSpdyBodyFrame(3, true));
12225 reads.push_back(CreateMockRead(*resp0, 1));
12226 reads.push_back(CreateMockRead(*body0, 2));
12227 reads.push_back(MockRead(ASYNC, ERR_IO_PENDING, 4));
12228 reads.push_back(CreateMockRead(*resp1, 5));
12229 reads.push_back(CreateMockRead(*body1, 6));
12230 reads.push_back(MockRead(ASYNC, OK, 7));
12231 } else {
12232 req1.reset(spdy_util_.ConstructSpdyGet(url1.c_str(), false, 1, LOWEST));
12234 writes.push_back(CreateMockWrite(*req1, 0));
12236 resp1.reset(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
12237 body1.reset(spdy_util_.ConstructSpdyBodyFrame(1, true));
12239 reads.push_back(CreateMockRead(*resp1, 1));
12240 reads.push_back(CreateMockRead(*body1, 2));
12241 reads.push_back(MockRead(ASYNC, OK, 3));
12244 SequencedSocketData data(vector_as_array(&reads), reads.size(),
12245 vector_as_array(&writes), writes.size());
12246 session_deps_.socket_factory->AddSocketDataProvider(&data);
12248 // Connection to the origin fails.
12249 MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
12250 StaticSocketDataProvider data_refused;
12251 data_refused.set_connect_data(mock_connect);
12252 session_deps_.socket_factory->AddSocketDataProvider(&data_refused);
12254 session_deps_.use_alternative_services = true;
12255 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12256 base::WeakPtr<HttpServerProperties> http_server_properties =
12257 session->http_server_properties();
12258 AlternativeService alternative_service(
12259 AlternateProtocolFromNextProto(GetParam()), alternative);
12260 base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
12261 http_server_properties->SetAlternativeService(origin, alternative_service,
12262 1.0, expiration);
12264 // First request to alternative.
12265 if (pooling) {
12266 scoped_ptr<HttpTransaction> trans0(
12267 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12268 HttpRequestInfo request0;
12269 request0.method = "GET";
12270 request0.url = GURL(url0);
12271 request0.load_flags = 0;
12272 TestCompletionCallback callback0;
12274 int rv = trans0->Start(&request0, callback0.callback(), BoundNetLog());
12275 EXPECT_EQ(ERR_IO_PENDING, rv);
12276 rv = callback0.WaitForResult();
12277 EXPECT_EQ(OK, rv);
12280 // Second request to origin.
12281 scoped_ptr<HttpTransaction> trans1(
12282 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12283 HttpRequestInfo request1;
12284 request1.method = "GET";
12285 request1.url = GURL(url1);
12286 request1.load_flags = 0;
12287 TestCompletionCallback callback1;
12289 int rv = trans1->Start(&request1, callback1.callback(), BoundNetLog());
12290 EXPECT_EQ(ERR_IO_PENDING, rv);
12291 base::MessageLoop::current()->RunUntilIdle();
12292 if (data.IsReadPaused()) {
12293 data.CompleteRead();
12295 rv = callback1.WaitForResult();
12296 if (valid) {
12297 EXPECT_EQ(OK, rv);
12298 } else {
12299 if (pooling) {
12300 EXPECT_EQ(ERR_CONNECTION_REFUSED, rv);
12301 } else {
12302 EXPECT_EQ(ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN, rv);
12308 INSTANTIATE_TEST_CASE_P(NextProto,
12309 AltSvcCertificateVerificationTest,
12310 testing::Values(kProtoSPDY31,
12311 kProtoHTTP2));
12313 // The alternative service host must exhibit a certificate that is valid for the
12314 // origin host. Test that this is enforced when pooling to an existing
12315 // connection.
12316 TEST_P(AltSvcCertificateVerificationTest, PoolingValid) {
12317 Run(true, true);
12320 TEST_P(AltSvcCertificateVerificationTest, PoolingInvalid) {
12321 Run(true, false);
12324 // The alternative service host must exhibit a certificate that is valid for the
12325 // origin host. Test that this is enforced when opening a new connection.
12326 TEST_P(AltSvcCertificateVerificationTest, NewConnectionValid) {
12327 Run(false, true);
12330 TEST_P(AltSvcCertificateVerificationTest, NewConnectionInvalid) {
12331 Run(false, false);
12334 // Alternative service requires HTTP/2 (or SPDY), but HTTP/1.1 is negotiated
12335 // with the alternative server. That connection should not be used.
12336 TEST_P(HttpNetworkTransactionTest, AlternativeServiceNotOnHttp11) {
12337 HostPortPair origin("origin.example.org", 443);
12338 HostPortPair alternative("alternative.example.org", 443);
12340 // Negotiate HTTP/1.1 with alternative.example.org.
12341 SSLSocketDataProvider ssl(ASYNC, OK);
12342 ssl.SetNextProto(kProtoHTTP11);
12343 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
12345 // No data should be read from the alternative, because HTTP/1.1 is
12346 // negotiated.
12347 StaticSocketDataProvider data;
12348 session_deps_.socket_factory->AddSocketDataProvider(&data);
12350 // This test documents that an alternate Job should not be used if HTTP/1.1 is
12351 // negotiated. In order to test this, a failed connection to the origin is
12352 // mocked. This way the request relies on the alternate Job.
12353 StaticSocketDataProvider data_refused;
12354 data_refused.set_connect_data(MockConnect(ASYNC, ERR_CONNECTION_REFUSED));
12355 session_deps_.socket_factory->AddSocketDataProvider(&data_refused);
12357 // Set up alternative service for origin.
12358 session_deps_.use_alternative_services = true;
12359 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12360 base::WeakPtr<HttpServerProperties> http_server_properties =
12361 session->http_server_properties();
12362 AlternativeService alternative_service(
12363 AlternateProtocolFromNextProto(GetParam()), alternative);
12364 base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
12365 http_server_properties->SetAlternativeService(origin, alternative_service,
12366 1.0, expiration);
12368 scoped_ptr<HttpTransaction> trans(
12369 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12370 HttpRequestInfo request;
12371 request.method = "GET";
12372 request.url = GURL("https://origin.example.org:443");
12373 request.load_flags = 0;
12374 TestCompletionCallback callback;
12376 // HTTP/2 (or SPDY) is required for alternative service, if HTTP/1.1 is
12377 // negotiated, the alternate Job should fail with ERR_NPN_NEGOTIATION_FAILED.
12378 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
12379 EXPECT_EQ(ERR_NPN_NEGOTIATION_FAILED, callback.GetResult(rv));
12382 // A request to a server with an alternative service fires two Jobs: one to the
12383 // origin, and an alternate one to the alternative server. If the former
12384 // succeeds, the request should succeed, even if the latter fails because
12385 // HTTP/1.1 is negotiated which is insufficient for alternative service.
12386 TEST_P(HttpNetworkTransactionTest, FailedAlternativeServiceIsNotUserVisible) {
12387 HostPortPair origin("origin.example.org", 443);
12388 HostPortPair alternative("alternative.example.org", 443);
12390 // Negotiate HTTP/1.1 with alternative.
12391 SSLSocketDataProvider alternative_ssl(ASYNC, OK);
12392 alternative_ssl.SetNextProto(kProtoHTTP11);
12393 session_deps_.socket_factory->AddSSLSocketDataProvider(&alternative_ssl);
12395 // No data should be read from the alternative, because HTTP/1.1 is
12396 // negotiated.
12397 StaticSocketDataProvider data;
12398 session_deps_.socket_factory->AddSocketDataProvider(&data);
12400 // Negotiate HTTP/1.1 with origin.
12401 SSLSocketDataProvider origin_ssl(ASYNC, OK);
12402 origin_ssl.SetNextProto(kProtoHTTP11);
12403 session_deps_.socket_factory->AddSSLSocketDataProvider(&origin_ssl);
12405 MockWrite http_writes[] = {
12406 MockWrite(
12407 "GET / HTTP/1.1\r\n"
12408 "Host: origin.example.org\r\n"
12409 "Connection: keep-alive\r\n\r\n"),
12410 MockWrite(
12411 "GET /second HTTP/1.1\r\n"
12412 "Host: origin.example.org\r\n"
12413 "Connection: keep-alive\r\n\r\n"),
12416 MockRead http_reads[] = {
12417 MockRead("HTTP/1.1 200 OK\r\n"),
12418 MockRead("Content-Type: text/html\r\n"),
12419 MockRead("Content-Length: 6\r\n\r\n"),
12420 MockRead("foobar"),
12421 MockRead("HTTP/1.1 200 OK\r\n"),
12422 MockRead("Content-Type: text/html\r\n"),
12423 MockRead("Content-Length: 7\r\n\r\n"),
12424 MockRead("another"),
12426 StaticSocketDataProvider http_data(http_reads, arraysize(http_reads),
12427 http_writes, arraysize(http_writes));
12428 session_deps_.socket_factory->AddSocketDataProvider(&http_data);
12430 // Set up alternative service for origin.
12431 session_deps_.use_alternative_services = true;
12432 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12433 base::WeakPtr<HttpServerProperties> http_server_properties =
12434 session->http_server_properties();
12435 AlternativeService alternative_service(
12436 AlternateProtocolFromNextProto(GetParam()), alternative);
12437 base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
12438 http_server_properties->SetAlternativeService(origin, alternative_service,
12439 1.0, expiration);
12441 HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
12442 HttpRequestInfo request1;
12443 request1.method = "GET";
12444 request1.url = GURL("https://origin.example.org:443");
12445 request1.load_flags = 0;
12446 TestCompletionCallback callback1;
12448 int rv = trans1.Start(&request1, callback1.callback(), BoundNetLog());
12449 rv = callback1.GetResult(rv);
12450 EXPECT_EQ(OK, rv);
12452 const HttpResponseInfo* response1 = trans1.GetResponseInfo();
12453 ASSERT_TRUE(response1 != nullptr);
12454 ASSERT_TRUE(response1->headers.get() != nullptr);
12455 EXPECT_EQ("HTTP/1.1 200 OK", response1->headers->GetStatusLine());
12457 std::string response_data1;
12458 ASSERT_EQ(OK, ReadTransaction(&trans1, &response_data1));
12459 EXPECT_EQ("foobar", response_data1);
12461 // Alternative should be marked as broken, because HTTP/1.1 is not sufficient
12462 // for alternative service.
12463 EXPECT_TRUE(
12464 http_server_properties->IsAlternativeServiceBroken(alternative_service));
12466 // Since |alternative_service| is broken, a second transaction to origin
12467 // should not start an alternate Job. It should pool to existing connection
12468 // to origin.
12469 HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
12470 HttpRequestInfo request2;
12471 request2.method = "GET";
12472 request2.url = GURL("https://origin.example.org:443/second");
12473 request2.load_flags = 0;
12474 TestCompletionCallback callback2;
12476 rv = trans2.Start(&request2, callback2.callback(), BoundNetLog());
12477 rv = callback2.GetResult(rv);
12478 EXPECT_EQ(OK, rv);
12480 const HttpResponseInfo* response2 = trans2.GetResponseInfo();
12481 ASSERT_TRUE(response2 != nullptr);
12482 ASSERT_TRUE(response2->headers.get() != nullptr);
12483 EXPECT_EQ("HTTP/1.1 200 OK", response2->headers->GetStatusLine());
12485 std::string response_data2;
12486 ASSERT_EQ(OK, ReadTransaction(&trans2, &response_data2));
12487 EXPECT_EQ("another", response_data2);
12490 // Alternative service requires HTTP/2 (or SPDY), but there is already a
12491 // HTTP/1.1 socket open to the alternative server. That socket should not be
12492 // used.
12493 TEST_P(HttpNetworkTransactionTest, AlternativeServiceShouldNotPoolToHttp11) {
12494 HostPortPair origin("origin.example.org", 443);
12495 HostPortPair alternative("alternative.example.org", 443);
12496 std::string origin_url = "https://origin.example.org:443";
12497 std::string alternative_url = "https://alternative.example.org:443";
12499 // Negotiate HTTP/1.1 with alternative.example.org.
12500 SSLSocketDataProvider ssl(ASYNC, OK);
12501 ssl.SetNextProto(kProtoHTTP11);
12502 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
12504 // HTTP/1.1 data for |request1| and |request2|.
12505 MockWrite http_writes[] = {
12506 MockWrite(
12507 "GET / HTTP/1.1\r\n"
12508 "Host: alternative.example.org\r\n"
12509 "Connection: keep-alive\r\n\r\n"),
12510 MockWrite(
12511 "GET / HTTP/1.1\r\n"
12512 "Host: alternative.example.org\r\n"
12513 "Connection: keep-alive\r\n\r\n"),
12516 MockRead http_reads[] = {
12517 MockRead(
12518 "HTTP/1.1 200 OK\r\n"
12519 "Content-Type: text/html; charset=iso-8859-1\r\n"
12520 "Content-Length: 40\r\n\r\n"
12521 "first HTTP/1.1 response from alternative"),
12522 MockRead(
12523 "HTTP/1.1 200 OK\r\n"
12524 "Content-Type: text/html; charset=iso-8859-1\r\n"
12525 "Content-Length: 41\r\n\r\n"
12526 "second HTTP/1.1 response from alternative"),
12528 StaticSocketDataProvider http_data(http_reads, arraysize(http_reads),
12529 http_writes, arraysize(http_writes));
12530 session_deps_.socket_factory->AddSocketDataProvider(&http_data);
12532 // This test documents that an alternate Job should not pool to an already
12533 // existing HTTP/1.1 connection. In order to test this, a failed connection
12534 // to the origin is mocked. This way |request2| relies on the alternate Job.
12535 StaticSocketDataProvider data_refused;
12536 data_refused.set_connect_data(MockConnect(ASYNC, ERR_CONNECTION_REFUSED));
12537 session_deps_.socket_factory->AddSocketDataProvider(&data_refused);
12539 // Set up alternative service for origin.
12540 session_deps_.use_alternative_services = true;
12541 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12542 base::WeakPtr<HttpServerProperties> http_server_properties =
12543 session->http_server_properties();
12544 AlternativeService alternative_service(
12545 AlternateProtocolFromNextProto(GetParam()), alternative);
12546 base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
12547 http_server_properties->SetAlternativeService(origin, alternative_service,
12548 1.0, expiration);
12550 // First transaction to alternative to open an HTTP/1.1 socket.
12551 scoped_ptr<HttpTransaction> trans1(
12552 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12553 HttpRequestInfo request1;
12554 request1.method = "GET";
12555 request1.url = GURL(alternative_url);
12556 request1.load_flags = 0;
12557 TestCompletionCallback callback1;
12559 int rv = trans1->Start(&request1, callback1.callback(), BoundNetLog());
12560 EXPECT_EQ(OK, callback1.GetResult(rv));
12561 const HttpResponseInfo* response1 = trans1->GetResponseInfo();
12562 ASSERT_TRUE(response1);
12563 ASSERT_TRUE(response1->headers.get());
12564 EXPECT_EQ("HTTP/1.1 200 OK", response1->headers->GetStatusLine());
12565 EXPECT_TRUE(response1->was_npn_negotiated);
12566 EXPECT_FALSE(response1->was_fetched_via_spdy);
12567 std::string response_data1;
12568 ASSERT_EQ(OK, ReadTransaction(trans1.get(), &response_data1));
12569 EXPECT_EQ("first HTTP/1.1 response from alternative", response_data1);
12571 // Request for origin.example.org, which has an alternative service. This
12572 // will start two Jobs: the alternative looks for connections to pool to,
12573 // finds one which is HTTP/1.1, and should ignore it, and should not try to
12574 // open other connections to alternative server. The Job to origin fails, so
12575 // this request fails.
12576 scoped_ptr<HttpTransaction> trans2(
12577 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12578 HttpRequestInfo request2;
12579 request2.method = "GET";
12580 request2.url = GURL(origin_url);
12581 request2.load_flags = 0;
12582 TestCompletionCallback callback2;
12584 rv = trans2->Start(&request2, callback2.callback(), BoundNetLog());
12585 EXPECT_EQ(ERR_CONNECTION_REFUSED, callback2.GetResult(rv));
12587 // Another transaction to alternative. This is to test that the HTTP/1.1
12588 // socket is still open and in the pool.
12589 scoped_ptr<HttpTransaction> trans3(
12590 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12591 HttpRequestInfo request3;
12592 request3.method = "GET";
12593 request3.url = GURL(alternative_url);
12594 request3.load_flags = 0;
12595 TestCompletionCallback callback3;
12597 rv = trans3->Start(&request3, callback3.callback(), BoundNetLog());
12598 EXPECT_EQ(OK, callback3.GetResult(rv));
12599 const HttpResponseInfo* response3 = trans3->GetResponseInfo();
12600 ASSERT_TRUE(response3);
12601 ASSERT_TRUE(response3->headers.get());
12602 EXPECT_EQ("HTTP/1.1 200 OK", response3->headers->GetStatusLine());
12603 EXPECT_TRUE(response3->was_npn_negotiated);
12604 EXPECT_FALSE(response3->was_fetched_via_spdy);
12605 std::string response_data3;
12606 ASSERT_EQ(OK, ReadTransaction(trans3.get(), &response_data3));
12607 EXPECT_EQ("second HTTP/1.1 response from alternative", response_data3);
12610 TEST_P(HttpNetworkTransactionTest, DoNotUseSpdySessionForHttpOverTunnel) {
12611 const std::string https_url = "https://www.example.org:8080/";
12612 const std::string http_url = "http://www.example.org:8080/";
12614 // SPDY GET for HTTPS URL (through CONNECT tunnel)
12615 const HostPortPair host_port_pair("www.example.org", 8080);
12616 scoped_ptr<SpdyFrame> connect(
12617 spdy_util_.ConstructSpdyConnect(NULL, 0, 1, LOWEST, host_port_pair));
12618 scoped_ptr<SpdyFrame> req1(
12619 spdy_util_.ConstructSpdyGet(https_url.c_str(), false, 1, LOWEST));
12620 scoped_ptr<SpdyFrame> wrapped_req1(
12621 spdy_util_.ConstructWrappedSpdyFrame(req1, 1));
12623 // SPDY GET for HTTP URL (through the proxy, but not the tunnel).
12624 SpdyHeaderBlock req2_block;
12625 req2_block[spdy_util_.GetMethodKey()] = "GET";
12626 req2_block[spdy_util_.GetPathKey()] = "/";
12627 req2_block[spdy_util_.GetHostKey()] = "www.example.org:8080";
12628 req2_block[spdy_util_.GetSchemeKey()] = "http";
12629 spdy_util_.MaybeAddVersionHeader(&req2_block);
12630 scoped_ptr<SpdyFrame> req2(
12631 spdy_util_.ConstructSpdySyn(3, req2_block, MEDIUM, false, true));
12633 MockWrite writes1[] = {
12634 CreateMockWrite(*connect, 0),
12635 CreateMockWrite(*wrapped_req1, 2),
12636 CreateMockWrite(*req2, 5),
12639 scoped_ptr<SpdyFrame> conn_resp(
12640 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
12641 scoped_ptr<SpdyFrame> resp1(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
12642 scoped_ptr<SpdyFrame> body1(spdy_util_.ConstructSpdyBodyFrame(1, true));
12643 scoped_ptr<SpdyFrame> wrapped_resp1(
12644 spdy_util_.ConstructWrappedSpdyFrame(resp1, 1));
12645 scoped_ptr<SpdyFrame> wrapped_body1(
12646 spdy_util_.ConstructWrappedSpdyFrame(body1, 1));
12647 scoped_ptr<SpdyFrame> resp2(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
12648 scoped_ptr<SpdyFrame> body2(spdy_util_.ConstructSpdyBodyFrame(3, true));
12649 MockRead reads1[] = {
12650 CreateMockRead(*conn_resp, 1),
12651 CreateMockRead(*wrapped_resp1, 3),
12652 CreateMockRead(*wrapped_body1, 4),
12653 CreateMockRead(*resp2, 6),
12654 CreateMockRead(*body2, 7),
12655 MockRead(ASYNC, ERR_IO_PENDING, 8)
12658 DeterministicSocketData data1(reads1, arraysize(reads1),
12659 writes1, arraysize(writes1));
12660 MockConnect connect_data1(ASYNC, OK);
12661 data1.set_connect_data(connect_data1);
12663 session_deps_.proxy_service.reset(
12664 ProxyService::CreateFixedFromPacResult("HTTPS proxy:70"));
12665 TestNetLog log;
12666 session_deps_.net_log = &log;
12667 SSLSocketDataProvider ssl1(ASYNC, OK); // to the proxy
12668 ssl1.SetNextProto(GetParam());
12669 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl1);
12670 SSLSocketDataProvider ssl2(ASYNC, OK); // to the server
12671 ssl2.SetNextProto(GetParam());
12672 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl2);
12673 session_deps_.deterministic_socket_factory->AddSocketDataProvider(&data1);
12675 scoped_refptr<HttpNetworkSession> session(
12676 SpdySessionDependencies::SpdyCreateSessionDeterministic(&session_deps_));
12678 // Start the first transaction to set up the SpdySession
12679 HttpRequestInfo request1;
12680 request1.method = "GET";
12681 request1.url = GURL(https_url);
12682 request1.load_flags = 0;
12683 HttpNetworkTransaction trans1(LOWEST, session.get());
12684 TestCompletionCallback callback1;
12685 EXPECT_EQ(ERR_IO_PENDING,
12686 trans1.Start(&request1, callback1.callback(), BoundNetLog()));
12687 base::MessageLoop::current()->RunUntilIdle();
12688 data1.RunFor(4);
12690 EXPECT_EQ(OK, callback1.WaitForResult());
12691 EXPECT_TRUE(trans1.GetResponseInfo()->was_fetched_via_spdy);
12693 LoadTimingInfo load_timing_info1;
12694 EXPECT_TRUE(trans1.GetLoadTimingInfo(&load_timing_info1));
12695 TestLoadTimingNotReusedWithPac(load_timing_info1,
12696 CONNECT_TIMING_HAS_SSL_TIMES);
12698 // Now, start the HTTP request
12699 HttpRequestInfo request2;
12700 request2.method = "GET";
12701 request2.url = GURL(http_url);
12702 request2.load_flags = 0;
12703 HttpNetworkTransaction trans2(MEDIUM, session.get());
12704 TestCompletionCallback callback2;
12705 EXPECT_EQ(ERR_IO_PENDING,
12706 trans2.Start(&request2, callback2.callback(), BoundNetLog()));
12707 base::MessageLoop::current()->RunUntilIdle();
12708 data1.RunFor(3);
12710 EXPECT_EQ(OK, callback2.WaitForResult());
12711 EXPECT_TRUE(trans2.GetResponseInfo()->was_fetched_via_spdy);
12713 LoadTimingInfo load_timing_info2;
12714 EXPECT_TRUE(trans2.GetLoadTimingInfo(&load_timing_info2));
12715 // The established SPDY sessions is considered reused by the HTTP request.
12716 TestLoadTimingReusedWithPac(load_timing_info2);
12717 // HTTP requests over a SPDY session should have a different connection
12718 // socket_log_id than requests over a tunnel.
12719 EXPECT_NE(load_timing_info1.socket_log_id, load_timing_info2.socket_log_id);
12722 // Test that in the case where we have a SPDY session to a SPDY proxy
12723 // that we do not pool other origins that resolve to the same IP when
12724 // the certificate does not match the new origin.
12725 // http://crbug.com/134690
12726 TEST_P(HttpNetworkTransactionTest, DoNotUseSpdySessionIfCertDoesNotMatch) {
12727 const std::string url1 = "http://www.example.org/";
12728 const std::string url2 = "https://news.example.org/";
12729 const std::string ip_addr = "1.2.3.4";
12731 // SPDY GET for HTTP URL (through SPDY proxy)
12732 scoped_ptr<SpdyHeaderBlock> headers(
12733 spdy_util_.ConstructGetHeaderBlockForProxy("http://www.example.org/"));
12734 scoped_ptr<SpdyFrame> req1(
12735 spdy_util_.ConstructSpdySyn(1, *headers, LOWEST, false, true));
12737 MockWrite writes1[] = {
12738 CreateMockWrite(*req1, 0),
12741 scoped_ptr<SpdyFrame> resp1(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
12742 scoped_ptr<SpdyFrame> body1(spdy_util_.ConstructSpdyBodyFrame(1, true));
12743 MockRead reads1[] = {
12744 CreateMockRead(*resp1, 1),
12745 CreateMockRead(*body1, 2),
12746 MockRead(ASYNC, OK, 3) // EOF
12749 scoped_ptr<DeterministicSocketData> data1(
12750 new DeterministicSocketData(reads1, arraysize(reads1),
12751 writes1, arraysize(writes1)));
12752 IPAddressNumber ip;
12753 ASSERT_TRUE(ParseIPLiteralToNumber(ip_addr, &ip));
12754 IPEndPoint peer_addr = IPEndPoint(ip, 443);
12755 MockConnect connect_data1(ASYNC, OK, peer_addr);
12756 data1->set_connect_data(connect_data1);
12758 // SPDY GET for HTTPS URL (direct)
12759 scoped_ptr<SpdyFrame> req2(
12760 spdy_util_.ConstructSpdyGet(url2.c_str(), false, 1, MEDIUM));
12762 MockWrite writes2[] = {
12763 CreateMockWrite(*req2, 0),
12766 scoped_ptr<SpdyFrame> resp2(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
12767 scoped_ptr<SpdyFrame> body2(spdy_util_.ConstructSpdyBodyFrame(1, true));
12768 MockRead reads2[] = {
12769 CreateMockRead(*resp2, 1),
12770 CreateMockRead(*body2, 2),
12771 MockRead(ASYNC, OK, 3) // EOF
12774 scoped_ptr<DeterministicSocketData> data2(
12775 new DeterministicSocketData(reads2, arraysize(reads2),
12776 writes2, arraysize(writes2)));
12777 MockConnect connect_data2(ASYNC, OK);
12778 data2->set_connect_data(connect_data2);
12780 // Set up a proxy config that sends HTTP requests to a proxy, and
12781 // all others direct.
12782 ProxyConfig proxy_config;
12783 proxy_config.proxy_rules().ParseFromString("http=https://proxy:443");
12784 session_deps_.proxy_service.reset(new ProxyService(
12785 new ProxyConfigServiceFixed(proxy_config), nullptr, NULL));
12787 SSLSocketDataProvider ssl1(ASYNC, OK); // to the proxy
12788 ssl1.SetNextProto(GetParam());
12789 // Load a valid cert. Note, that this does not need to
12790 // be valid for proxy because the MockSSLClientSocket does
12791 // not actually verify it. But SpdySession will use this
12792 // to see if it is valid for the new origin
12793 ssl1.cert = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
12794 ASSERT_TRUE(ssl1.cert.get());
12795 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl1);
12796 session_deps_.deterministic_socket_factory->AddSocketDataProvider(
12797 data1.get());
12799 SSLSocketDataProvider ssl2(ASYNC, OK); // to the server
12800 ssl2.SetNextProto(GetParam());
12801 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl2);
12802 session_deps_.deterministic_socket_factory->AddSocketDataProvider(
12803 data2.get());
12805 session_deps_.host_resolver.reset(new MockCachingHostResolver());
12806 session_deps_.host_resolver->rules()->AddRule("news.example.org", ip_addr);
12807 session_deps_.host_resolver->rules()->AddRule("proxy", ip_addr);
12809 scoped_refptr<HttpNetworkSession> session(
12810 SpdySessionDependencies::SpdyCreateSessionDeterministic(&session_deps_));
12812 // Start the first transaction to set up the SpdySession
12813 HttpRequestInfo request1;
12814 request1.method = "GET";
12815 request1.url = GURL(url1);
12816 request1.load_flags = 0;
12817 HttpNetworkTransaction trans1(LOWEST, session.get());
12818 TestCompletionCallback callback1;
12819 ASSERT_EQ(ERR_IO_PENDING,
12820 trans1.Start(&request1, callback1.callback(), BoundNetLog()));
12821 data1->RunFor(3);
12823 ASSERT_TRUE(callback1.have_result());
12824 EXPECT_EQ(OK, callback1.WaitForResult());
12825 EXPECT_TRUE(trans1.GetResponseInfo()->was_fetched_via_spdy);
12827 // Now, start the HTTP request
12828 HttpRequestInfo request2;
12829 request2.method = "GET";
12830 request2.url = GURL(url2);
12831 request2.load_flags = 0;
12832 HttpNetworkTransaction trans2(MEDIUM, session.get());
12833 TestCompletionCallback callback2;
12834 EXPECT_EQ(ERR_IO_PENDING,
12835 trans2.Start(&request2, callback2.callback(), BoundNetLog()));
12836 base::MessageLoop::current()->RunUntilIdle();
12837 data2->RunFor(3);
12839 ASSERT_TRUE(callback2.have_result());
12840 EXPECT_EQ(OK, callback2.WaitForResult());
12841 EXPECT_TRUE(trans2.GetResponseInfo()->was_fetched_via_spdy);
12844 // Test to verify that a failed socket read (due to an ERR_CONNECTION_CLOSED
12845 // error) in SPDY session, removes the socket from pool and closes the SPDY
12846 // session. Verify that new url's from the same HttpNetworkSession (and a new
12847 // SpdySession) do work. http://crbug.com/224701
12848 TEST_P(HttpNetworkTransactionTest, ErrorSocketNotConnected) {
12849 const std::string https_url = "https://www.example.org/";
12851 MockRead reads1[] = {
12852 MockRead(SYNCHRONOUS, ERR_CONNECTION_CLOSED, 0)
12855 SequencedSocketData data1(reads1, arraysize(reads1), NULL, 0);
12857 scoped_ptr<SpdyFrame> req2(
12858 spdy_util_.ConstructSpdyGet(https_url.c_str(), false, 1, MEDIUM));
12859 MockWrite writes2[] = {
12860 CreateMockWrite(*req2, 0),
12863 scoped_ptr<SpdyFrame> resp2(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
12864 scoped_ptr<SpdyFrame> body2(spdy_util_.ConstructSpdyBodyFrame(1, true));
12865 MockRead reads2[] = {
12866 CreateMockRead(*resp2, 1),
12867 CreateMockRead(*body2, 2),
12868 MockRead(ASYNC, OK, 3) // EOF
12871 SequencedSocketData data2(reads2, arraysize(reads2), writes2,
12872 arraysize(writes2));
12874 SSLSocketDataProvider ssl1(ASYNC, OK);
12875 ssl1.SetNextProto(GetParam());
12876 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
12877 session_deps_.socket_factory->AddSocketDataProvider(&data1);
12879 SSLSocketDataProvider ssl2(ASYNC, OK);
12880 ssl2.SetNextProto(GetParam());
12881 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
12882 session_deps_.socket_factory->AddSocketDataProvider(&data2);
12884 scoped_refptr<HttpNetworkSession> session(
12885 SpdySessionDependencies::SpdyCreateSession(&session_deps_));
12887 // Start the first transaction to set up the SpdySession and verify that
12888 // connection was closed.
12889 HttpRequestInfo request1;
12890 request1.method = "GET";
12891 request1.url = GURL(https_url);
12892 request1.load_flags = 0;
12893 HttpNetworkTransaction trans1(MEDIUM, session.get());
12894 TestCompletionCallback callback1;
12895 EXPECT_EQ(ERR_IO_PENDING,
12896 trans1.Start(&request1, callback1.callback(), BoundNetLog()));
12897 EXPECT_EQ(ERR_CONNECTION_CLOSED, callback1.WaitForResult());
12899 // Now, start the second request and make sure it succeeds.
12900 HttpRequestInfo request2;
12901 request2.method = "GET";
12902 request2.url = GURL(https_url);
12903 request2.load_flags = 0;
12904 HttpNetworkTransaction trans2(MEDIUM, session.get());
12905 TestCompletionCallback callback2;
12906 EXPECT_EQ(ERR_IO_PENDING,
12907 trans2.Start(&request2, callback2.callback(), BoundNetLog()));
12909 ASSERT_EQ(OK, callback2.WaitForResult());
12910 EXPECT_TRUE(trans2.GetResponseInfo()->was_fetched_via_spdy);
12913 TEST_P(HttpNetworkTransactionTest, CloseIdleSpdySessionToOpenNewOne) {
12914 session_deps_.next_protos = SpdyNextProtos();
12915 ClientSocketPoolManager::set_max_sockets_per_group(
12916 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
12917 ClientSocketPoolManager::set_max_sockets_per_pool(
12918 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
12920 // Use two different hosts with different IPs so they don't get pooled.
12921 session_deps_.host_resolver->rules()->AddRule("www.a.com", "10.0.0.1");
12922 session_deps_.host_resolver->rules()->AddRule("www.b.com", "10.0.0.2");
12923 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12925 SSLSocketDataProvider ssl1(ASYNC, OK);
12926 ssl1.SetNextProto(GetParam());
12927 SSLSocketDataProvider ssl2(ASYNC, OK);
12928 ssl2.SetNextProto(GetParam());
12929 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
12930 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
12932 scoped_ptr<SpdyFrame> host1_req(spdy_util_.ConstructSpdyGet(
12933 "https://www.a.com", false, 1, DEFAULT_PRIORITY));
12934 MockWrite spdy1_writes[] = {
12935 CreateMockWrite(*host1_req, 0),
12937 scoped_ptr<SpdyFrame> host1_resp(
12938 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
12939 scoped_ptr<SpdyFrame> host1_resp_body(
12940 spdy_util_.ConstructSpdyBodyFrame(1, true));
12941 MockRead spdy1_reads[] = {
12942 CreateMockRead(*host1_resp, 1),
12943 CreateMockRead(*host1_resp_body, 2),
12944 MockRead(ASYNC, ERR_IO_PENDING, 3),
12947 scoped_ptr<SequencedSocketData> spdy1_data(
12948 new SequencedSocketData(spdy1_reads, arraysize(spdy1_reads), spdy1_writes,
12949 arraysize(spdy1_writes)));
12950 session_deps_.socket_factory->AddSocketDataProvider(spdy1_data.get());
12952 scoped_ptr<SpdyFrame> host2_req(spdy_util_.ConstructSpdyGet(
12953 "https://www.b.com", false, 1, DEFAULT_PRIORITY));
12954 MockWrite spdy2_writes[] = {
12955 CreateMockWrite(*host2_req, 0),
12957 scoped_ptr<SpdyFrame> host2_resp(
12958 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
12959 scoped_ptr<SpdyFrame> host2_resp_body(
12960 spdy_util_.ConstructSpdyBodyFrame(1, true));
12961 MockRead spdy2_reads[] = {
12962 CreateMockRead(*host2_resp, 1),
12963 CreateMockRead(*host2_resp_body, 2),
12964 MockRead(ASYNC, ERR_IO_PENDING, 3),
12967 scoped_ptr<SequencedSocketData> spdy2_data(
12968 new SequencedSocketData(spdy2_reads, arraysize(spdy2_reads), spdy2_writes,
12969 arraysize(spdy2_writes)));
12970 session_deps_.socket_factory->AddSocketDataProvider(spdy2_data.get());
12972 MockWrite http_write[] = {
12973 MockWrite("GET / HTTP/1.1\r\n"
12974 "Host: www.a.com\r\n"
12975 "Connection: keep-alive\r\n\r\n"),
12978 MockRead http_read[] = {
12979 MockRead("HTTP/1.1 200 OK\r\n"),
12980 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
12981 MockRead("Content-Length: 6\r\n\r\n"),
12982 MockRead("hello!"),
12984 StaticSocketDataProvider http_data(http_read, arraysize(http_read),
12985 http_write, arraysize(http_write));
12986 session_deps_.socket_factory->AddSocketDataProvider(&http_data);
12988 HostPortPair host_port_pair_a("www.a.com", 443);
12989 SpdySessionKey spdy_session_key_a(
12990 host_port_pair_a, ProxyServer::Direct(), PRIVACY_MODE_DISABLED);
12991 EXPECT_FALSE(
12992 HasSpdySession(session->spdy_session_pool(), spdy_session_key_a));
12994 TestCompletionCallback callback;
12995 HttpRequestInfo request1;
12996 request1.method = "GET";
12997 request1.url = GURL("https://www.a.com/");
12998 request1.load_flags = 0;
12999 scoped_ptr<HttpNetworkTransaction> trans(
13000 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13002 int rv = trans->Start(&request1, callback.callback(), BoundNetLog());
13003 EXPECT_EQ(ERR_IO_PENDING, rv);
13004 EXPECT_EQ(OK, callback.WaitForResult());
13006 const HttpResponseInfo* response = trans->GetResponseInfo();
13007 ASSERT_TRUE(response != NULL);
13008 ASSERT_TRUE(response->headers.get() != NULL);
13009 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
13010 EXPECT_TRUE(response->was_fetched_via_spdy);
13011 EXPECT_TRUE(response->was_npn_negotiated);
13013 std::string response_data;
13014 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
13015 EXPECT_EQ("hello!", response_data);
13016 trans.reset();
13017 EXPECT_TRUE(
13018 HasSpdySession(session->spdy_session_pool(), spdy_session_key_a));
13020 HostPortPair host_port_pair_b("www.b.com", 443);
13021 SpdySessionKey spdy_session_key_b(
13022 host_port_pair_b, ProxyServer::Direct(), PRIVACY_MODE_DISABLED);
13023 EXPECT_FALSE(
13024 HasSpdySession(session->spdy_session_pool(), spdy_session_key_b));
13025 HttpRequestInfo request2;
13026 request2.method = "GET";
13027 request2.url = GURL("https://www.b.com/");
13028 request2.load_flags = 0;
13029 trans.reset(new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13031 rv = trans->Start(&request2, callback.callback(), BoundNetLog());
13032 EXPECT_EQ(ERR_IO_PENDING, rv);
13033 EXPECT_EQ(OK, callback.WaitForResult());
13035 response = trans->GetResponseInfo();
13036 ASSERT_TRUE(response != NULL);
13037 ASSERT_TRUE(response->headers.get() != NULL);
13038 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
13039 EXPECT_TRUE(response->was_fetched_via_spdy);
13040 EXPECT_TRUE(response->was_npn_negotiated);
13041 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
13042 EXPECT_EQ("hello!", response_data);
13043 EXPECT_FALSE(
13044 HasSpdySession(session->spdy_session_pool(), spdy_session_key_a));
13045 EXPECT_TRUE(
13046 HasSpdySession(session->spdy_session_pool(), spdy_session_key_b));
13048 HostPortPair host_port_pair_a1("www.a.com", 80);
13049 SpdySessionKey spdy_session_key_a1(
13050 host_port_pair_a1, ProxyServer::Direct(), PRIVACY_MODE_DISABLED);
13051 EXPECT_FALSE(
13052 HasSpdySession(session->spdy_session_pool(), spdy_session_key_a1));
13053 HttpRequestInfo request3;
13054 request3.method = "GET";
13055 request3.url = GURL("http://www.a.com/");
13056 request3.load_flags = 0;
13057 trans.reset(new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13059 rv = trans->Start(&request3, callback.callback(), BoundNetLog());
13060 EXPECT_EQ(ERR_IO_PENDING, rv);
13061 EXPECT_EQ(OK, callback.WaitForResult());
13063 response = trans->GetResponseInfo();
13064 ASSERT_TRUE(response != NULL);
13065 ASSERT_TRUE(response->headers.get() != NULL);
13066 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
13067 EXPECT_FALSE(response->was_fetched_via_spdy);
13068 EXPECT_FALSE(response->was_npn_negotiated);
13069 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
13070 EXPECT_EQ("hello!", response_data);
13071 EXPECT_FALSE(
13072 HasSpdySession(session->spdy_session_pool(), spdy_session_key_a));
13073 EXPECT_FALSE(
13074 HasSpdySession(session->spdy_session_pool(), spdy_session_key_b));
13077 TEST_P(HttpNetworkTransactionTest, HttpSyncConnectError) {
13078 HttpRequestInfo request;
13079 request.method = "GET";
13080 request.url = GURL("http://www.example.org/");
13081 request.load_flags = 0;
13083 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13084 scoped_ptr<HttpTransaction> trans(
13085 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13087 MockConnect mock_connect(SYNCHRONOUS, ERR_CONNECTION_REFUSED);
13088 StaticSocketDataProvider data;
13089 data.set_connect_data(mock_connect);
13090 session_deps_.socket_factory->AddSocketDataProvider(&data);
13092 TestCompletionCallback callback;
13094 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13095 EXPECT_EQ(ERR_IO_PENDING, rv);
13097 rv = callback.WaitForResult();
13098 EXPECT_EQ(ERR_CONNECTION_REFUSED, rv);
13100 // We don't care whether this succeeds or fails, but it shouldn't crash.
13101 HttpRequestHeaders request_headers;
13102 trans->GetFullRequestHeaders(&request_headers);
13104 ConnectionAttempts attempts;
13105 trans->GetConnectionAttempts(&attempts);
13106 ASSERT_EQ(1u, attempts.size());
13107 EXPECT_EQ(ERR_CONNECTION_REFUSED, attempts[0].result);
13110 TEST_P(HttpNetworkTransactionTest, HttpAsyncConnectError) {
13111 HttpRequestInfo request;
13112 request.method = "GET";
13113 request.url = GURL("http://www.example.org/");
13114 request.load_flags = 0;
13116 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13117 scoped_ptr<HttpTransaction> trans(
13118 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13120 MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
13121 StaticSocketDataProvider data;
13122 data.set_connect_data(mock_connect);
13123 session_deps_.socket_factory->AddSocketDataProvider(&data);
13125 TestCompletionCallback callback;
13127 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13128 EXPECT_EQ(ERR_IO_PENDING, rv);
13130 rv = callback.WaitForResult();
13131 EXPECT_EQ(ERR_CONNECTION_REFUSED, rv);
13133 // We don't care whether this succeeds or fails, but it shouldn't crash.
13134 HttpRequestHeaders request_headers;
13135 trans->GetFullRequestHeaders(&request_headers);
13137 ConnectionAttempts attempts;
13138 trans->GetConnectionAttempts(&attempts);
13139 ASSERT_EQ(1u, attempts.size());
13140 EXPECT_EQ(ERR_CONNECTION_REFUSED, attempts[0].result);
13143 TEST_P(HttpNetworkTransactionTest, HttpSyncWriteError) {
13144 HttpRequestInfo request;
13145 request.method = "GET";
13146 request.url = GURL("http://www.example.org/");
13147 request.load_flags = 0;
13149 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13150 scoped_ptr<HttpTransaction> trans(
13151 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13153 MockWrite data_writes[] = {
13154 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13156 MockRead data_reads[] = {
13157 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
13160 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
13161 data_writes, arraysize(data_writes));
13162 session_deps_.socket_factory->AddSocketDataProvider(&data);
13164 TestCompletionCallback callback;
13166 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13167 EXPECT_EQ(ERR_IO_PENDING, rv);
13169 rv = callback.WaitForResult();
13170 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
13172 HttpRequestHeaders request_headers;
13173 EXPECT_TRUE(trans->GetFullRequestHeaders(&request_headers));
13174 EXPECT_TRUE(request_headers.HasHeader("Host"));
13177 TEST_P(HttpNetworkTransactionTest, HttpAsyncWriteError) {
13178 HttpRequestInfo request;
13179 request.method = "GET";
13180 request.url = GURL("http://www.example.org/");
13181 request.load_flags = 0;
13183 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13184 scoped_ptr<HttpTransaction> trans(
13185 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13187 MockWrite data_writes[] = {
13188 MockWrite(ASYNC, ERR_CONNECTION_RESET),
13190 MockRead data_reads[] = {
13191 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
13194 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
13195 data_writes, arraysize(data_writes));
13196 session_deps_.socket_factory->AddSocketDataProvider(&data);
13198 TestCompletionCallback callback;
13200 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13201 EXPECT_EQ(ERR_IO_PENDING, rv);
13203 rv = callback.WaitForResult();
13204 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
13206 HttpRequestHeaders request_headers;
13207 EXPECT_TRUE(trans->GetFullRequestHeaders(&request_headers));
13208 EXPECT_TRUE(request_headers.HasHeader("Host"));
13211 TEST_P(HttpNetworkTransactionTest, HttpSyncReadError) {
13212 HttpRequestInfo request;
13213 request.method = "GET";
13214 request.url = GURL("http://www.example.org/");
13215 request.load_flags = 0;
13217 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13218 scoped_ptr<HttpTransaction> trans(
13219 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13221 MockWrite data_writes[] = {
13222 MockWrite(
13223 "GET / HTTP/1.1\r\n"
13224 "Host: www.example.org\r\n"
13225 "Connection: keep-alive\r\n\r\n"),
13227 MockRead data_reads[] = {
13228 MockRead(SYNCHRONOUS, ERR_CONNECTION_RESET),
13231 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
13232 data_writes, arraysize(data_writes));
13233 session_deps_.socket_factory->AddSocketDataProvider(&data);
13235 TestCompletionCallback callback;
13237 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13238 EXPECT_EQ(ERR_IO_PENDING, rv);
13240 rv = callback.WaitForResult();
13241 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
13243 HttpRequestHeaders request_headers;
13244 EXPECT_TRUE(trans->GetFullRequestHeaders(&request_headers));
13245 EXPECT_TRUE(request_headers.HasHeader("Host"));
13248 TEST_P(HttpNetworkTransactionTest, HttpAsyncReadError) {
13249 HttpRequestInfo request;
13250 request.method = "GET";
13251 request.url = GURL("http://www.example.org/");
13252 request.load_flags = 0;
13254 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13255 scoped_ptr<HttpTransaction> trans(
13256 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13258 MockWrite data_writes[] = {
13259 MockWrite(
13260 "GET / HTTP/1.1\r\n"
13261 "Host: www.example.org\r\n"
13262 "Connection: keep-alive\r\n\r\n"),
13264 MockRead data_reads[] = {
13265 MockRead(ASYNC, ERR_CONNECTION_RESET),
13268 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
13269 data_writes, arraysize(data_writes));
13270 session_deps_.socket_factory->AddSocketDataProvider(&data);
13272 TestCompletionCallback callback;
13274 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13275 EXPECT_EQ(ERR_IO_PENDING, rv);
13277 rv = callback.WaitForResult();
13278 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
13280 HttpRequestHeaders request_headers;
13281 EXPECT_TRUE(trans->GetFullRequestHeaders(&request_headers));
13282 EXPECT_TRUE(request_headers.HasHeader("Host"));
13285 TEST_P(HttpNetworkTransactionTest, GetFullRequestHeadersIncludesExtraHeader) {
13286 HttpRequestInfo request;
13287 request.method = "GET";
13288 request.url = GURL("http://www.example.org/");
13289 request.load_flags = 0;
13290 request.extra_headers.SetHeader("X-Foo", "bar");
13292 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13293 scoped_ptr<HttpTransaction> trans(
13294 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13296 MockWrite data_writes[] = {
13297 MockWrite(
13298 "GET / HTTP/1.1\r\n"
13299 "Host: www.example.org\r\n"
13300 "Connection: keep-alive\r\n"
13301 "X-Foo: bar\r\n\r\n"),
13303 MockRead data_reads[] = {
13304 MockRead("HTTP/1.1 200 OK\r\n"
13305 "Content-Length: 5\r\n\r\n"
13306 "hello"),
13307 MockRead(ASYNC, ERR_UNEXPECTED),
13310 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
13311 data_writes, arraysize(data_writes));
13312 session_deps_.socket_factory->AddSocketDataProvider(&data);
13314 TestCompletionCallback callback;
13316 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13317 EXPECT_EQ(ERR_IO_PENDING, rv);
13319 rv = callback.WaitForResult();
13320 EXPECT_EQ(OK, rv);
13322 HttpRequestHeaders request_headers;
13323 EXPECT_TRUE(trans->GetFullRequestHeaders(&request_headers));
13324 std::string foo;
13325 EXPECT_TRUE(request_headers.GetHeader("X-Foo", &foo));
13326 EXPECT_EQ("bar", foo);
13329 namespace {
13331 // Fake HttpStream that simply records calls to SetPriority().
13332 class FakeStream : public HttpStream,
13333 public base::SupportsWeakPtr<FakeStream> {
13334 public:
13335 explicit FakeStream(RequestPriority priority) : priority_(priority) {}
13336 ~FakeStream() override {}
13338 RequestPriority priority() const { return priority_; }
13340 int InitializeStream(const HttpRequestInfo* request_info,
13341 RequestPriority priority,
13342 const BoundNetLog& net_log,
13343 const CompletionCallback& callback) override {
13344 return ERR_IO_PENDING;
13347 int SendRequest(const HttpRequestHeaders& request_headers,
13348 HttpResponseInfo* response,
13349 const CompletionCallback& callback) override {
13350 ADD_FAILURE();
13351 return ERR_UNEXPECTED;
13354 int ReadResponseHeaders(const CompletionCallback& callback) override {
13355 ADD_FAILURE();
13356 return ERR_UNEXPECTED;
13359 int ReadResponseBody(IOBuffer* buf,
13360 int buf_len,
13361 const CompletionCallback& callback) override {
13362 ADD_FAILURE();
13363 return ERR_UNEXPECTED;
13366 void Close(bool not_reusable) override {}
13368 bool IsResponseBodyComplete() const override {
13369 ADD_FAILURE();
13370 return false;
13373 bool IsConnectionReused() const override {
13374 ADD_FAILURE();
13375 return false;
13378 void SetConnectionReused() override { ADD_FAILURE(); }
13380 bool CanReuseConnection() const override { return false; }
13382 int64 GetTotalReceivedBytes() const override {
13383 ADD_FAILURE();
13384 return 0;
13387 int64_t GetTotalSentBytes() const override {
13388 ADD_FAILURE();
13389 return 0;
13392 bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const override {
13393 ADD_FAILURE();
13394 return false;
13397 void GetSSLInfo(SSLInfo* ssl_info) override { ADD_FAILURE(); }
13399 void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override {
13400 ADD_FAILURE();
13403 void Drain(HttpNetworkSession* session) override { ADD_FAILURE(); }
13405 void SetPriority(RequestPriority priority) override { priority_ = priority; }
13407 UploadProgress GetUploadProgress() const override { return UploadProgress(); }
13409 HttpStream* RenewStreamForAuth() override { return NULL; }
13411 private:
13412 RequestPriority priority_;
13414 DISALLOW_COPY_AND_ASSIGN(FakeStream);
13417 // Fake HttpStreamRequest that simply records calls to SetPriority()
13418 // and vends FakeStreams with its current priority.
13419 class FakeStreamRequest : public HttpStreamRequest,
13420 public base::SupportsWeakPtr<FakeStreamRequest> {
13421 public:
13422 FakeStreamRequest(RequestPriority priority,
13423 HttpStreamRequest::Delegate* delegate)
13424 : priority_(priority),
13425 delegate_(delegate),
13426 websocket_stream_create_helper_(NULL) {}
13428 FakeStreamRequest(RequestPriority priority,
13429 HttpStreamRequest::Delegate* delegate,
13430 WebSocketHandshakeStreamBase::CreateHelper* create_helper)
13431 : priority_(priority),
13432 delegate_(delegate),
13433 websocket_stream_create_helper_(create_helper) {}
13435 ~FakeStreamRequest() override {}
13437 RequestPriority priority() const { return priority_; }
13439 const WebSocketHandshakeStreamBase::CreateHelper*
13440 websocket_stream_create_helper() const {
13441 return websocket_stream_create_helper_;
13444 // Create a new FakeStream and pass it to the request's
13445 // delegate. Returns a weak pointer to the FakeStream.
13446 base::WeakPtr<FakeStream> FinishStreamRequest() {
13447 FakeStream* fake_stream = new FakeStream(priority_);
13448 // Do this before calling OnStreamReady() as OnStreamReady() may
13449 // immediately delete |fake_stream|.
13450 base::WeakPtr<FakeStream> weak_stream = fake_stream->AsWeakPtr();
13451 delegate_->OnStreamReady(SSLConfig(), ProxyInfo(), fake_stream);
13452 return weak_stream;
13455 int RestartTunnelWithProxyAuth(const AuthCredentials& credentials) override {
13456 ADD_FAILURE();
13457 return ERR_UNEXPECTED;
13460 LoadState GetLoadState() const override {
13461 ADD_FAILURE();
13462 return LoadState();
13465 void SetPriority(RequestPriority priority) override { priority_ = priority; }
13467 bool was_npn_negotiated() const override { return false; }
13469 NextProto protocol_negotiated() const override { return kProtoUnknown; }
13471 bool using_spdy() const override { return false; }
13473 const ConnectionAttempts& connection_attempts() const override {
13474 static ConnectionAttempts no_attempts;
13475 return no_attempts;
13478 private:
13479 RequestPriority priority_;
13480 HttpStreamRequest::Delegate* const delegate_;
13481 WebSocketHandshakeStreamBase::CreateHelper* websocket_stream_create_helper_;
13483 DISALLOW_COPY_AND_ASSIGN(FakeStreamRequest);
13486 // Fake HttpStreamFactory that vends FakeStreamRequests.
13487 class FakeStreamFactory : public HttpStreamFactory {
13488 public:
13489 FakeStreamFactory() {}
13490 ~FakeStreamFactory() override {}
13492 // Returns a WeakPtr<> to the last HttpStreamRequest returned by
13493 // RequestStream() (which may be NULL if it was destroyed already).
13494 base::WeakPtr<FakeStreamRequest> last_stream_request() {
13495 return last_stream_request_;
13498 HttpStreamRequest* RequestStream(const HttpRequestInfo& info,
13499 RequestPriority priority,
13500 const SSLConfig& server_ssl_config,
13501 const SSLConfig& proxy_ssl_config,
13502 HttpStreamRequest::Delegate* delegate,
13503 const BoundNetLog& net_log) override {
13504 FakeStreamRequest* fake_request = new FakeStreamRequest(priority, delegate);
13505 last_stream_request_ = fake_request->AsWeakPtr();
13506 return fake_request;
13509 HttpStreamRequest* RequestWebSocketHandshakeStream(
13510 const HttpRequestInfo& info,
13511 RequestPriority priority,
13512 const SSLConfig& server_ssl_config,
13513 const SSLConfig& proxy_ssl_config,
13514 HttpStreamRequest::Delegate* delegate,
13515 WebSocketHandshakeStreamBase::CreateHelper* create_helper,
13516 const BoundNetLog& net_log) override {
13517 FakeStreamRequest* fake_request =
13518 new FakeStreamRequest(priority, delegate, create_helper);
13519 last_stream_request_ = fake_request->AsWeakPtr();
13520 return fake_request;
13523 void PreconnectStreams(int num_streams,
13524 const HttpRequestInfo& info,
13525 const SSLConfig& server_ssl_config,
13526 const SSLConfig& proxy_ssl_config) override {
13527 ADD_FAILURE();
13530 const HostMappingRules* GetHostMappingRules() const override {
13531 ADD_FAILURE();
13532 return NULL;
13535 private:
13536 base::WeakPtr<FakeStreamRequest> last_stream_request_;
13538 DISALLOW_COPY_AND_ASSIGN(FakeStreamFactory);
13541 // TODO(ricea): Maybe unify this with the one in
13542 // url_request_http_job_unittest.cc ?
13543 class FakeWebSocketBasicHandshakeStream : public WebSocketHandshakeStreamBase {
13544 public:
13545 FakeWebSocketBasicHandshakeStream(scoped_ptr<ClientSocketHandle> connection,
13546 bool using_proxy)
13547 : state_(connection.release(), using_proxy) {}
13549 // Fake implementation of HttpStreamBase methods.
13550 // This ends up being quite "real" because this object has to really send data
13551 // on the mock socket. It might be easier to use the real implementation, but
13552 // the fact that the WebSocket code is not compiled on iOS makes that
13553 // difficult.
13554 int InitializeStream(const HttpRequestInfo* request_info,
13555 RequestPriority priority,
13556 const BoundNetLog& net_log,
13557 const CompletionCallback& callback) override {
13558 state_.Initialize(request_info, priority, net_log, callback);
13559 return OK;
13562 int SendRequest(const HttpRequestHeaders& request_headers,
13563 HttpResponseInfo* response,
13564 const CompletionCallback& callback) override {
13565 return parser()->SendRequest(state_.GenerateRequestLine(), request_headers,
13566 response, callback);
13569 int ReadResponseHeaders(const CompletionCallback& callback) override {
13570 return parser()->ReadResponseHeaders(callback);
13573 int ReadResponseBody(IOBuffer* buf,
13574 int buf_len,
13575 const CompletionCallback& callback) override {
13576 NOTREACHED();
13577 return ERR_IO_PENDING;
13580 void Close(bool not_reusable) override {
13581 if (parser())
13582 parser()->Close(true);
13585 bool IsResponseBodyComplete() const override {
13586 NOTREACHED();
13587 return false;
13590 bool IsConnectionReused() const override {
13591 NOTREACHED();
13592 return false;
13594 void SetConnectionReused() override { NOTREACHED(); }
13596 bool CanReuseConnection() const override { return false; }
13598 int64 GetTotalReceivedBytes() const override {
13599 NOTREACHED();
13600 return 0;
13603 int64_t GetTotalSentBytes() const override {
13604 NOTREACHED();
13605 return 0;
13608 bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const override {
13609 NOTREACHED();
13610 return false;
13613 void GetSSLInfo(SSLInfo* ssl_info) override {}
13615 void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override {
13616 NOTREACHED();
13619 void Drain(HttpNetworkSession* session) override { NOTREACHED(); }
13621 void SetPriority(RequestPriority priority) override { NOTREACHED(); }
13623 UploadProgress GetUploadProgress() const override {
13624 NOTREACHED();
13625 return UploadProgress();
13628 HttpStream* RenewStreamForAuth() override {
13629 NOTREACHED();
13630 return nullptr;
13633 // Fake implementation of WebSocketHandshakeStreamBase method(s)
13634 scoped_ptr<WebSocketStream> Upgrade() override {
13635 NOTREACHED();
13636 return scoped_ptr<WebSocketStream>();
13639 private:
13640 HttpStreamParser* parser() const { return state_.parser(); }
13641 HttpBasicState state_;
13643 DISALLOW_COPY_AND_ASSIGN(FakeWebSocketBasicHandshakeStream);
13646 // TODO(yhirano): Split this class out into a net/websockets file, if it is
13647 // worth doing.
13648 class FakeWebSocketStreamCreateHelper :
13649 public WebSocketHandshakeStreamBase::CreateHelper {
13650 public:
13651 WebSocketHandshakeStreamBase* CreateBasicStream(
13652 scoped_ptr<ClientSocketHandle> connection,
13653 bool using_proxy) override {
13654 return new FakeWebSocketBasicHandshakeStream(connection.Pass(),
13655 using_proxy);
13658 WebSocketHandshakeStreamBase* CreateSpdyStream(
13659 const base::WeakPtr<SpdySession>& session,
13660 bool use_relative_url) override {
13661 NOTREACHED();
13662 return NULL;
13665 ~FakeWebSocketStreamCreateHelper() override {}
13667 virtual scoped_ptr<WebSocketStream> Upgrade() {
13668 NOTREACHED();
13669 return scoped_ptr<WebSocketStream>();
13673 } // namespace
13675 // Make sure that HttpNetworkTransaction passes on its priority to its
13676 // stream request on start.
13677 TEST_P(HttpNetworkTransactionTest, SetStreamRequestPriorityOnStart) {
13678 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13679 HttpNetworkSessionPeer peer(session);
13680 FakeStreamFactory* fake_factory = new FakeStreamFactory();
13681 peer.SetHttpStreamFactory(scoped_ptr<HttpStreamFactory>(fake_factory));
13683 HttpNetworkTransaction trans(LOW, session.get());
13685 ASSERT_TRUE(fake_factory->last_stream_request() == NULL);
13687 HttpRequestInfo request;
13688 TestCompletionCallback callback;
13689 EXPECT_EQ(ERR_IO_PENDING,
13690 trans.Start(&request, callback.callback(), BoundNetLog()));
13692 base::WeakPtr<FakeStreamRequest> fake_request =
13693 fake_factory->last_stream_request();
13694 ASSERT_TRUE(fake_request != NULL);
13695 EXPECT_EQ(LOW, fake_request->priority());
13698 // Make sure that HttpNetworkTransaction passes on its priority
13699 // updates to its stream request.
13700 TEST_P(HttpNetworkTransactionTest, SetStreamRequestPriority) {
13701 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13702 HttpNetworkSessionPeer peer(session);
13703 FakeStreamFactory* fake_factory = new FakeStreamFactory();
13704 peer.SetHttpStreamFactory(scoped_ptr<HttpStreamFactory>(fake_factory));
13706 HttpNetworkTransaction trans(LOW, session.get());
13708 HttpRequestInfo request;
13709 TestCompletionCallback callback;
13710 EXPECT_EQ(ERR_IO_PENDING,
13711 trans.Start(&request, callback.callback(), BoundNetLog()));
13713 base::WeakPtr<FakeStreamRequest> fake_request =
13714 fake_factory->last_stream_request();
13715 ASSERT_TRUE(fake_request != NULL);
13716 EXPECT_EQ(LOW, fake_request->priority());
13718 trans.SetPriority(LOWEST);
13719 ASSERT_TRUE(fake_request != NULL);
13720 EXPECT_EQ(LOWEST, fake_request->priority());
13723 // Make sure that HttpNetworkTransaction passes on its priority
13724 // updates to its stream.
13725 TEST_P(HttpNetworkTransactionTest, SetStreamPriority) {
13726 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13727 HttpNetworkSessionPeer peer(session);
13728 FakeStreamFactory* fake_factory = new FakeStreamFactory();
13729 peer.SetHttpStreamFactory(scoped_ptr<HttpStreamFactory>(fake_factory));
13731 HttpNetworkTransaction trans(LOW, session.get());
13733 HttpRequestInfo request;
13734 TestCompletionCallback callback;
13735 EXPECT_EQ(ERR_IO_PENDING,
13736 trans.Start(&request, callback.callback(), BoundNetLog()));
13738 base::WeakPtr<FakeStreamRequest> fake_request =
13739 fake_factory->last_stream_request();
13740 ASSERT_TRUE(fake_request != NULL);
13741 base::WeakPtr<FakeStream> fake_stream = fake_request->FinishStreamRequest();
13742 ASSERT_TRUE(fake_stream != NULL);
13743 EXPECT_EQ(LOW, fake_stream->priority());
13745 trans.SetPriority(LOWEST);
13746 EXPECT_EQ(LOWEST, fake_stream->priority());
13749 TEST_P(HttpNetworkTransactionTest, CreateWebSocketHandshakeStream) {
13750 // The same logic needs to be tested for both ws: and wss: schemes, but this
13751 // test is already parameterised on NextProto, so it uses a loop to verify
13752 // that the different schemes work.
13753 std::string test_cases[] = {"ws://www.example.org/",
13754 "wss://www.example.org/"};
13755 for (size_t i = 0; i < arraysize(test_cases); ++i) {
13756 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13757 HttpNetworkSessionPeer peer(session);
13758 FakeStreamFactory* fake_factory = new FakeStreamFactory();
13759 FakeWebSocketStreamCreateHelper websocket_stream_create_helper;
13760 peer.SetHttpStreamFactoryForWebSocket(
13761 scoped_ptr<HttpStreamFactory>(fake_factory));
13763 HttpNetworkTransaction trans(LOW, session.get());
13764 trans.SetWebSocketHandshakeStreamCreateHelper(
13765 &websocket_stream_create_helper);
13767 HttpRequestInfo request;
13768 TestCompletionCallback callback;
13769 request.method = "GET";
13770 request.url = GURL(test_cases[i]);
13772 EXPECT_EQ(ERR_IO_PENDING,
13773 trans.Start(&request, callback.callback(), BoundNetLog()));
13775 base::WeakPtr<FakeStreamRequest> fake_request =
13776 fake_factory->last_stream_request();
13777 ASSERT_TRUE(fake_request != NULL);
13778 EXPECT_EQ(&websocket_stream_create_helper,
13779 fake_request->websocket_stream_create_helper());
13783 // Tests that when a used socket is returned to the SSL socket pool, it's closed
13784 // if the transport socket pool is stalled on the global socket limit.
13785 TEST_P(HttpNetworkTransactionTest, CloseSSLSocketOnIdleForHttpRequest) {
13786 ClientSocketPoolManager::set_max_sockets_per_group(
13787 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
13788 ClientSocketPoolManager::set_max_sockets_per_pool(
13789 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
13791 // Set up SSL request.
13793 HttpRequestInfo ssl_request;
13794 ssl_request.method = "GET";
13795 ssl_request.url = GURL("https://www.example.org/");
13797 MockWrite ssl_writes[] = {
13798 MockWrite(
13799 "GET / HTTP/1.1\r\n"
13800 "Host: www.example.org\r\n"
13801 "Connection: keep-alive\r\n\r\n"),
13803 MockRead ssl_reads[] = {
13804 MockRead("HTTP/1.1 200 OK\r\n"),
13805 MockRead("Content-Length: 11\r\n\r\n"),
13806 MockRead("hello world"),
13807 MockRead(SYNCHRONOUS, OK),
13809 StaticSocketDataProvider ssl_data(ssl_reads, arraysize(ssl_reads),
13810 ssl_writes, arraysize(ssl_writes));
13811 session_deps_.socket_factory->AddSocketDataProvider(&ssl_data);
13813 SSLSocketDataProvider ssl(ASYNC, OK);
13814 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
13816 // Set up HTTP request.
13818 HttpRequestInfo http_request;
13819 http_request.method = "GET";
13820 http_request.url = GURL("http://www.example.org/");
13822 MockWrite http_writes[] = {
13823 MockWrite(
13824 "GET / HTTP/1.1\r\n"
13825 "Host: www.example.org\r\n"
13826 "Connection: keep-alive\r\n\r\n"),
13828 MockRead http_reads[] = {
13829 MockRead("HTTP/1.1 200 OK\r\n"),
13830 MockRead("Content-Length: 7\r\n\r\n"),
13831 MockRead("falafel"),
13832 MockRead(SYNCHRONOUS, OK),
13834 StaticSocketDataProvider http_data(http_reads, arraysize(http_reads),
13835 http_writes, arraysize(http_writes));
13836 session_deps_.socket_factory->AddSocketDataProvider(&http_data);
13838 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13840 // Start the SSL request.
13841 TestCompletionCallback ssl_callback;
13842 scoped_ptr<HttpTransaction> ssl_trans(
13843 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13844 ASSERT_EQ(ERR_IO_PENDING,
13845 ssl_trans->Start(&ssl_request, ssl_callback.callback(),
13846 BoundNetLog()));
13848 // Start the HTTP request. Pool should stall.
13849 TestCompletionCallback http_callback;
13850 scoped_ptr<HttpTransaction> http_trans(
13851 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13852 ASSERT_EQ(ERR_IO_PENDING,
13853 http_trans->Start(&http_request, http_callback.callback(),
13854 BoundNetLog()));
13855 EXPECT_TRUE(IsTransportSocketPoolStalled(session.get()));
13857 // Wait for response from SSL request.
13858 ASSERT_EQ(OK, ssl_callback.WaitForResult());
13859 std::string response_data;
13860 ASSERT_EQ(OK, ReadTransaction(ssl_trans.get(), &response_data));
13861 EXPECT_EQ("hello world", response_data);
13863 // The SSL socket should automatically be closed, so the HTTP request can
13864 // start.
13865 EXPECT_EQ(0, GetIdleSocketCountInSSLSocketPool(session.get()));
13866 ASSERT_FALSE(IsTransportSocketPoolStalled(session.get()));
13868 // The HTTP request can now complete.
13869 ASSERT_EQ(OK, http_callback.WaitForResult());
13870 ASSERT_EQ(OK, ReadTransaction(http_trans.get(), &response_data));
13871 EXPECT_EQ("falafel", response_data);
13873 EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
13876 // Tests that when a SSL connection is established but there's no corresponding
13877 // request that needs it, the new socket is closed if the transport socket pool
13878 // is stalled on the global socket limit.
13879 TEST_P(HttpNetworkTransactionTest, CloseSSLSocketOnIdleForHttpRequest2) {
13880 ClientSocketPoolManager::set_max_sockets_per_group(
13881 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
13882 ClientSocketPoolManager::set_max_sockets_per_pool(
13883 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
13885 // Set up an ssl request.
13887 HttpRequestInfo ssl_request;
13888 ssl_request.method = "GET";
13889 ssl_request.url = GURL("https://www.foopy.com/");
13891 // No data will be sent on the SSL socket.
13892 StaticSocketDataProvider ssl_data;
13893 session_deps_.socket_factory->AddSocketDataProvider(&ssl_data);
13895 SSLSocketDataProvider ssl(ASYNC, OK);
13896 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
13898 // Set up HTTP request.
13900 HttpRequestInfo http_request;
13901 http_request.method = "GET";
13902 http_request.url = GURL("http://www.example.org/");
13904 MockWrite http_writes[] = {
13905 MockWrite(
13906 "GET / HTTP/1.1\r\n"
13907 "Host: www.example.org\r\n"
13908 "Connection: keep-alive\r\n\r\n"),
13910 MockRead http_reads[] = {
13911 MockRead("HTTP/1.1 200 OK\r\n"),
13912 MockRead("Content-Length: 7\r\n\r\n"),
13913 MockRead("falafel"),
13914 MockRead(SYNCHRONOUS, OK),
13916 StaticSocketDataProvider http_data(http_reads, arraysize(http_reads),
13917 http_writes, arraysize(http_writes));
13918 session_deps_.socket_factory->AddSocketDataProvider(&http_data);
13920 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13922 // Preconnect an SSL socket. A preconnect is needed because connect jobs are
13923 // cancelled when a normal transaction is cancelled.
13924 HttpStreamFactory* http_stream_factory = session->http_stream_factory();
13925 SSLConfig ssl_config;
13926 session->ssl_config_service()->GetSSLConfig(&ssl_config);
13927 http_stream_factory->PreconnectStreams(1, ssl_request, ssl_config,
13928 ssl_config);
13929 EXPECT_EQ(0, GetIdleSocketCountInSSLSocketPool(session.get()));
13931 // Start the HTTP request. Pool should stall.
13932 TestCompletionCallback http_callback;
13933 scoped_ptr<HttpTransaction> http_trans(
13934 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13935 ASSERT_EQ(ERR_IO_PENDING,
13936 http_trans->Start(&http_request, http_callback.callback(),
13937 BoundNetLog()));
13938 EXPECT_TRUE(IsTransportSocketPoolStalled(session.get()));
13940 // The SSL connection will automatically be closed once the connection is
13941 // established, to let the HTTP request start.
13942 ASSERT_EQ(OK, http_callback.WaitForResult());
13943 std::string response_data;
13944 ASSERT_EQ(OK, ReadTransaction(http_trans.get(), &response_data));
13945 EXPECT_EQ("falafel", response_data);
13947 EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
13950 TEST_P(HttpNetworkTransactionTest, PostReadsErrorResponseAfterReset) {
13951 ScopedVector<UploadElementReader> element_readers;
13952 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13953 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
13955 HttpRequestInfo request;
13956 request.method = "POST";
13957 request.url = GURL("http://www.foo.com/");
13958 request.upload_data_stream = &upload_data_stream;
13959 request.load_flags = 0;
13961 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13962 scoped_ptr<HttpTransaction> trans(
13963 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13964 // Send headers successfully, but get an error while sending the body.
13965 MockWrite data_writes[] = {
13966 MockWrite("POST / HTTP/1.1\r\n"
13967 "Host: www.foo.com\r\n"
13968 "Connection: keep-alive\r\n"
13969 "Content-Length: 3\r\n\r\n"),
13970 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13973 MockRead data_reads[] = {
13974 MockRead("HTTP/1.0 400 Not OK\r\n\r\n"),
13975 MockRead("hello world"),
13976 MockRead(SYNCHRONOUS, OK),
13978 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13979 arraysize(data_writes));
13980 session_deps_.socket_factory->AddSocketDataProvider(&data);
13982 TestCompletionCallback callback;
13984 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13985 EXPECT_EQ(ERR_IO_PENDING, rv);
13987 rv = callback.WaitForResult();
13988 EXPECT_EQ(OK, rv);
13990 const HttpResponseInfo* response = trans->GetResponseInfo();
13991 ASSERT_TRUE(response != NULL);
13993 EXPECT_TRUE(response->headers.get() != NULL);
13994 EXPECT_EQ("HTTP/1.0 400 Not OK", response->headers->GetStatusLine());
13996 std::string response_data;
13997 rv = ReadTransaction(trans.get(), &response_data);
13998 EXPECT_EQ(OK, rv);
13999 EXPECT_EQ("hello world", response_data);
14002 // This test makes sure the retry logic doesn't trigger when reading an error
14003 // response from a server that rejected a POST with a CONNECTION_RESET.
14004 TEST_P(HttpNetworkTransactionTest,
14005 PostReadsErrorResponseAfterResetOnReusedSocket) {
14006 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
14007 MockWrite data_writes[] = {
14008 MockWrite("GET / HTTP/1.1\r\n"
14009 "Host: www.foo.com\r\n"
14010 "Connection: keep-alive\r\n\r\n"),
14011 MockWrite("POST / HTTP/1.1\r\n"
14012 "Host: www.foo.com\r\n"
14013 "Connection: keep-alive\r\n"
14014 "Content-Length: 3\r\n\r\n"),
14015 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
14018 MockRead data_reads[] = {
14019 MockRead("HTTP/1.1 200 Peachy\r\n"
14020 "Content-Length: 14\r\n\r\n"),
14021 MockRead("first response"),
14022 MockRead("HTTP/1.1 400 Not OK\r\n"
14023 "Content-Length: 15\r\n\r\n"),
14024 MockRead("second response"),
14025 MockRead(SYNCHRONOUS, OK),
14027 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
14028 arraysize(data_writes));
14029 session_deps_.socket_factory->AddSocketDataProvider(&data);
14031 TestCompletionCallback callback;
14032 HttpRequestInfo request1;
14033 request1.method = "GET";
14034 request1.url = GURL("http://www.foo.com/");
14035 request1.load_flags = 0;
14037 scoped_ptr<HttpTransaction> trans1(
14038 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
14039 int rv = trans1->Start(&request1, callback.callback(), BoundNetLog());
14040 EXPECT_EQ(ERR_IO_PENDING, rv);
14042 rv = callback.WaitForResult();
14043 EXPECT_EQ(OK, rv);
14045 const HttpResponseInfo* response1 = trans1->GetResponseInfo();
14046 ASSERT_TRUE(response1 != NULL);
14048 EXPECT_TRUE(response1->headers.get() != NULL);
14049 EXPECT_EQ("HTTP/1.1 200 Peachy", response1->headers->GetStatusLine());
14051 std::string response_data1;
14052 rv = ReadTransaction(trans1.get(), &response_data1);
14053 EXPECT_EQ(OK, rv);
14054 EXPECT_EQ("first response", response_data1);
14055 // Delete the transaction to release the socket back into the socket pool.
14056 trans1.reset();
14058 ScopedVector<UploadElementReader> element_readers;
14059 element_readers.push_back(new UploadBytesElementReader("foo", 3));
14060 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
14062 HttpRequestInfo request2;
14063 request2.method = "POST";
14064 request2.url = GURL("http://www.foo.com/");
14065 request2.upload_data_stream = &upload_data_stream;
14066 request2.load_flags = 0;
14068 scoped_ptr<HttpTransaction> trans2(
14069 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
14070 rv = trans2->Start(&request2, callback.callback(), BoundNetLog());
14071 EXPECT_EQ(ERR_IO_PENDING, rv);
14073 rv = callback.WaitForResult();
14074 EXPECT_EQ(OK, rv);
14076 const HttpResponseInfo* response2 = trans2->GetResponseInfo();
14077 ASSERT_TRUE(response2 != NULL);
14079 EXPECT_TRUE(response2->headers.get() != NULL);
14080 EXPECT_EQ("HTTP/1.1 400 Not OK", response2->headers->GetStatusLine());
14082 std::string response_data2;
14083 rv = ReadTransaction(trans2.get(), &response_data2);
14084 EXPECT_EQ(OK, rv);
14085 EXPECT_EQ("second response", response_data2);
14088 TEST_P(HttpNetworkTransactionTest,
14089 PostReadsErrorResponseAfterResetPartialBodySent) {
14090 ScopedVector<UploadElementReader> element_readers;
14091 element_readers.push_back(new UploadBytesElementReader("foo", 3));
14092 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
14094 HttpRequestInfo request;
14095 request.method = "POST";
14096 request.url = GURL("http://www.foo.com/");
14097 request.upload_data_stream = &upload_data_stream;
14098 request.load_flags = 0;
14100 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
14101 scoped_ptr<HttpTransaction> trans(
14102 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
14103 // Send headers successfully, but get an error while sending the body.
14104 MockWrite data_writes[] = {
14105 MockWrite("POST / HTTP/1.1\r\n"
14106 "Host: www.foo.com\r\n"
14107 "Connection: keep-alive\r\n"
14108 "Content-Length: 3\r\n\r\n"
14109 "fo"),
14110 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
14113 MockRead data_reads[] = {
14114 MockRead("HTTP/1.0 400 Not OK\r\n\r\n"),
14115 MockRead("hello world"),
14116 MockRead(SYNCHRONOUS, OK),
14118 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
14119 arraysize(data_writes));
14120 session_deps_.socket_factory->AddSocketDataProvider(&data);
14122 TestCompletionCallback callback;
14124 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
14125 EXPECT_EQ(ERR_IO_PENDING, rv);
14127 rv = callback.WaitForResult();
14128 EXPECT_EQ(OK, rv);
14130 const HttpResponseInfo* response = trans->GetResponseInfo();
14131 ASSERT_TRUE(response != NULL);
14133 EXPECT_TRUE(response->headers.get() != NULL);
14134 EXPECT_EQ("HTTP/1.0 400 Not OK", response->headers->GetStatusLine());
14136 std::string response_data;
14137 rv = ReadTransaction(trans.get(), &response_data);
14138 EXPECT_EQ(OK, rv);
14139 EXPECT_EQ("hello world", response_data);
14142 // This tests the more common case than the previous test, where headers and
14143 // body are not merged into a single request.
14144 TEST_P(HttpNetworkTransactionTest, ChunkedPostReadsErrorResponseAfterReset) {
14145 ScopedVector<UploadElementReader> element_readers;
14146 element_readers.push_back(new UploadBytesElementReader("foo", 3));
14147 ChunkedUploadDataStream upload_data_stream(0);
14149 HttpRequestInfo request;
14150 request.method = "POST";
14151 request.url = GURL("http://www.foo.com/");
14152 request.upload_data_stream = &upload_data_stream;
14153 request.load_flags = 0;
14155 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
14156 scoped_ptr<HttpTransaction> trans(
14157 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
14158 // Send headers successfully, but get an error while sending the body.
14159 MockWrite data_writes[] = {
14160 MockWrite("POST / HTTP/1.1\r\n"
14161 "Host: www.foo.com\r\n"
14162 "Connection: keep-alive\r\n"
14163 "Transfer-Encoding: chunked\r\n\r\n"),
14164 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
14167 MockRead data_reads[] = {
14168 MockRead("HTTP/1.0 400 Not OK\r\n\r\n"),
14169 MockRead("hello world"),
14170 MockRead(SYNCHRONOUS, OK),
14172 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
14173 arraysize(data_writes));
14174 session_deps_.socket_factory->AddSocketDataProvider(&data);
14176 TestCompletionCallback callback;
14178 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
14179 EXPECT_EQ(ERR_IO_PENDING, rv);
14180 // Make sure the headers are sent before adding a chunk. This ensures that
14181 // they can't be merged with the body in a single send. Not currently
14182 // necessary since a chunked body is never merged with headers, but this makes
14183 // the test more future proof.
14184 base::RunLoop().RunUntilIdle();
14186 upload_data_stream.AppendData("last chunk", 10, true);
14188 rv = callback.WaitForResult();
14189 EXPECT_EQ(OK, rv);
14191 const HttpResponseInfo* response = trans->GetResponseInfo();
14192 ASSERT_TRUE(response != NULL);
14194 EXPECT_TRUE(response->headers.get() != NULL);
14195 EXPECT_EQ("HTTP/1.0 400 Not OK", response->headers->GetStatusLine());
14197 std::string response_data;
14198 rv = ReadTransaction(trans.get(), &response_data);
14199 EXPECT_EQ(OK, rv);
14200 EXPECT_EQ("hello world", response_data);
14203 TEST_P(HttpNetworkTransactionTest, PostReadsErrorResponseAfterResetAnd100) {
14204 ScopedVector<UploadElementReader> element_readers;
14205 element_readers.push_back(new UploadBytesElementReader("foo", 3));
14206 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
14208 HttpRequestInfo request;
14209 request.method = "POST";
14210 request.url = GURL("http://www.foo.com/");
14211 request.upload_data_stream = &upload_data_stream;
14212 request.load_flags = 0;
14214 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
14215 scoped_ptr<HttpTransaction> trans(
14216 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
14218 MockWrite data_writes[] = {
14219 MockWrite("POST / HTTP/1.1\r\n"
14220 "Host: www.foo.com\r\n"
14221 "Connection: keep-alive\r\n"
14222 "Content-Length: 3\r\n\r\n"),
14223 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
14226 MockRead data_reads[] = {
14227 MockRead("HTTP/1.0 100 Continue\r\n\r\n"),
14228 MockRead("HTTP/1.0 400 Not OK\r\n\r\n"),
14229 MockRead("hello world"),
14230 MockRead(SYNCHRONOUS, OK),
14232 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
14233 arraysize(data_writes));
14234 session_deps_.socket_factory->AddSocketDataProvider(&data);
14236 TestCompletionCallback callback;
14238 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
14239 EXPECT_EQ(ERR_IO_PENDING, rv);
14241 rv = callback.WaitForResult();
14242 EXPECT_EQ(OK, rv);
14244 const HttpResponseInfo* response = trans->GetResponseInfo();
14245 ASSERT_TRUE(response != NULL);
14247 EXPECT_TRUE(response->headers.get() != NULL);
14248 EXPECT_EQ("HTTP/1.0 400 Not OK", response->headers->GetStatusLine());
14250 std::string response_data;
14251 rv = ReadTransaction(trans.get(), &response_data);
14252 EXPECT_EQ(OK, rv);
14253 EXPECT_EQ("hello world", response_data);
14256 TEST_P(HttpNetworkTransactionTest, PostIgnoresNonErrorResponseAfterReset) {
14257 ScopedVector<UploadElementReader> element_readers;
14258 element_readers.push_back(new UploadBytesElementReader("foo", 3));
14259 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
14261 HttpRequestInfo request;
14262 request.method = "POST";
14263 request.url = GURL("http://www.foo.com/");
14264 request.upload_data_stream = &upload_data_stream;
14265 request.load_flags = 0;
14267 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
14268 scoped_ptr<HttpTransaction> trans(
14269 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
14270 // Send headers successfully, but get an error while sending the body.
14271 MockWrite data_writes[] = {
14272 MockWrite("POST / HTTP/1.1\r\n"
14273 "Host: www.foo.com\r\n"
14274 "Connection: keep-alive\r\n"
14275 "Content-Length: 3\r\n\r\n"),
14276 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
14279 MockRead data_reads[] = {
14280 MockRead("HTTP/1.0 200 Just Dandy\r\n\r\n"),
14281 MockRead("hello world"),
14282 MockRead(SYNCHRONOUS, OK),
14284 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
14285 arraysize(data_writes));
14286 session_deps_.socket_factory->AddSocketDataProvider(&data);
14288 TestCompletionCallback callback;
14290 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
14291 EXPECT_EQ(ERR_IO_PENDING, rv);
14293 rv = callback.WaitForResult();
14294 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
14297 TEST_P(HttpNetworkTransactionTest,
14298 PostIgnoresNonErrorResponseAfterResetAnd100) {
14299 ScopedVector<UploadElementReader> element_readers;
14300 element_readers.push_back(new UploadBytesElementReader("foo", 3));
14301 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
14303 HttpRequestInfo request;
14304 request.method = "POST";
14305 request.url = GURL("http://www.foo.com/");
14306 request.upload_data_stream = &upload_data_stream;
14307 request.load_flags = 0;
14309 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
14310 scoped_ptr<HttpTransaction> trans(
14311 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
14312 // Send headers successfully, but get an error while sending the body.
14313 MockWrite data_writes[] = {
14314 MockWrite("POST / HTTP/1.1\r\n"
14315 "Host: www.foo.com\r\n"
14316 "Connection: keep-alive\r\n"
14317 "Content-Length: 3\r\n\r\n"),
14318 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
14321 MockRead data_reads[] = {
14322 MockRead("HTTP/1.0 100 Continue\r\n\r\n"),
14323 MockRead("HTTP/1.0 302 Redirect\r\n"),
14324 MockRead("Location: http://somewhere-else.com/\r\n"),
14325 MockRead("Content-Length: 0\r\n\r\n"),
14326 MockRead(SYNCHRONOUS, OK),
14328 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
14329 arraysize(data_writes));
14330 session_deps_.socket_factory->AddSocketDataProvider(&data);
14332 TestCompletionCallback callback;
14334 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
14335 EXPECT_EQ(ERR_IO_PENDING, rv);
14337 rv = callback.WaitForResult();
14338 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
14341 TEST_P(HttpNetworkTransactionTest, PostIgnoresHttp09ResponseAfterReset) {
14342 ScopedVector<UploadElementReader> element_readers;
14343 element_readers.push_back(new UploadBytesElementReader("foo", 3));
14344 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
14346 HttpRequestInfo request;
14347 request.method = "POST";
14348 request.url = GURL("http://www.foo.com/");
14349 request.upload_data_stream = &upload_data_stream;
14350 request.load_flags = 0;
14352 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
14353 scoped_ptr<HttpTransaction> trans(
14354 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
14355 // Send headers successfully, but get an error while sending the body.
14356 MockWrite data_writes[] = {
14357 MockWrite("POST / HTTP/1.1\r\n"
14358 "Host: www.foo.com\r\n"
14359 "Connection: keep-alive\r\n"
14360 "Content-Length: 3\r\n\r\n"),
14361 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
14364 MockRead data_reads[] = {
14365 MockRead("HTTP 0.9 rocks!"),
14366 MockRead(SYNCHRONOUS, OK),
14368 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
14369 arraysize(data_writes));
14370 session_deps_.socket_factory->AddSocketDataProvider(&data);
14372 TestCompletionCallback callback;
14374 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
14375 EXPECT_EQ(ERR_IO_PENDING, rv);
14377 rv = callback.WaitForResult();
14378 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
14381 TEST_P(HttpNetworkTransactionTest, PostIgnoresPartial400HeadersAfterReset) {
14382 ScopedVector<UploadElementReader> element_readers;
14383 element_readers.push_back(new UploadBytesElementReader("foo", 3));
14384 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
14386 HttpRequestInfo request;
14387 request.method = "POST";
14388 request.url = GURL("http://www.foo.com/");
14389 request.upload_data_stream = &upload_data_stream;
14390 request.load_flags = 0;
14392 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
14393 scoped_ptr<HttpTransaction> trans(
14394 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
14395 // Send headers successfully, but get an error while sending the body.
14396 MockWrite data_writes[] = {
14397 MockWrite("POST / HTTP/1.1\r\n"
14398 "Host: www.foo.com\r\n"
14399 "Connection: keep-alive\r\n"
14400 "Content-Length: 3\r\n\r\n"),
14401 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
14404 MockRead data_reads[] = {
14405 MockRead("HTTP/1.0 400 Not a Full Response\r\n"),
14406 MockRead(SYNCHRONOUS, OK),
14408 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
14409 arraysize(data_writes));
14410 session_deps_.socket_factory->AddSocketDataProvider(&data);
14412 TestCompletionCallback callback;
14414 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
14415 EXPECT_EQ(ERR_IO_PENDING, rv);
14417 rv = callback.WaitForResult();
14418 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
14421 // Verify that proxy headers are not sent to the destination server when
14422 // establishing a tunnel for a secure WebSocket connection.
14423 TEST_P(HttpNetworkTransactionTest, ProxyHeadersNotSentOverWssTunnel) {
14424 HttpRequestInfo request;
14425 request.method = "GET";
14426 request.url = GURL("wss://www.example.org/");
14427 AddWebSocketHeaders(&request.extra_headers);
14429 // Configure against proxy server "myproxy:70".
14430 session_deps_.proxy_service.reset(
14431 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
14433 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
14435 // Since a proxy is configured, try to establish a tunnel.
14436 MockWrite data_writes[] = {
14437 MockWrite(
14438 "CONNECT www.example.org:443 HTTP/1.1\r\n"
14439 "Host: www.example.org\r\n"
14440 "Proxy-Connection: keep-alive\r\n\r\n"),
14442 // After calling trans->RestartWithAuth(), this is the request we should
14443 // be issuing -- the final header line contains the credentials.
14444 MockWrite(
14445 "CONNECT www.example.org:443 HTTP/1.1\r\n"
14446 "Host: www.example.org\r\n"
14447 "Proxy-Connection: keep-alive\r\n"
14448 "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
14450 MockWrite(
14451 "GET / HTTP/1.1\r\n"
14452 "Host: www.example.org\r\n"
14453 "Connection: Upgrade\r\n"
14454 "Upgrade: websocket\r\n"
14455 "Origin: http://www.example.org\r\n"
14456 "Sec-WebSocket-Version: 13\r\n"
14457 "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n"),
14460 // The proxy responds to the connect with a 407, using a persistent
14461 // connection.
14462 MockRead data_reads[] = {
14463 // No credentials.
14464 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
14465 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
14466 MockRead("Content-Length: 0\r\n"),
14467 MockRead("Proxy-Connection: keep-alive\r\n\r\n"),
14469 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
14471 MockRead("HTTP/1.1 101 Switching Protocols\r\n"),
14472 MockRead("Upgrade: websocket\r\n"),
14473 MockRead("Connection: Upgrade\r\n"),
14474 MockRead("Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n"),
14477 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
14478 arraysize(data_writes));
14479 session_deps_.socket_factory->AddSocketDataProvider(&data);
14480 SSLSocketDataProvider ssl(ASYNC, OK);
14481 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
14483 scoped_ptr<HttpTransaction> trans(
14484 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
14485 FakeWebSocketStreamCreateHelper websocket_stream_create_helper;
14486 trans->SetWebSocketHandshakeStreamCreateHelper(
14487 &websocket_stream_create_helper);
14490 TestCompletionCallback callback;
14492 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
14493 EXPECT_EQ(ERR_IO_PENDING, rv);
14495 rv = callback.WaitForResult();
14496 EXPECT_EQ(OK, rv);
14499 const HttpResponseInfo* response = trans->GetResponseInfo();
14500 ASSERT_TRUE(response);
14501 ASSERT_TRUE(response->headers.get());
14502 EXPECT_EQ(407, response->headers->response_code());
14505 TestCompletionCallback callback;
14507 int rv = trans->RestartWithAuth(AuthCredentials(kFoo, kBar),
14508 callback.callback());
14509 EXPECT_EQ(ERR_IO_PENDING, rv);
14511 rv = callback.WaitForResult();
14512 EXPECT_EQ(OK, rv);
14515 response = trans->GetResponseInfo();
14516 ASSERT_TRUE(response);
14517 ASSERT_TRUE(response->headers.get());
14519 EXPECT_EQ(101, response->headers->response_code());
14521 trans.reset();
14522 session->CloseAllConnections();
14525 // Verify that proxy headers are not sent to the destination server when
14526 // establishing a tunnel for an insecure WebSocket connection.
14527 // This requires the authentication info to be injected into the auth cache
14528 // due to crbug.com/395064
14529 // TODO(ricea): Change to use a 407 response once issue 395064 is fixed.
14530 TEST_P(HttpNetworkTransactionTest, ProxyHeadersNotSentOverWsTunnel) {
14531 HttpRequestInfo request;
14532 request.method = "GET";
14533 request.url = GURL("ws://www.example.org/");
14534 AddWebSocketHeaders(&request.extra_headers);
14536 // Configure against proxy server "myproxy:70".
14537 session_deps_.proxy_service.reset(
14538 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
14540 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
14542 MockWrite data_writes[] = {
14543 // Try to establish a tunnel for the WebSocket connection, with
14544 // credentials. Because WebSockets have a separate set of socket pools,
14545 // they cannot and will not use the same TCP/IP connection as the
14546 // preflight HTTP request.
14547 MockWrite(
14548 "CONNECT www.example.org:80 HTTP/1.1\r\n"
14549 "Host: www.example.org:80\r\n"
14550 "Proxy-Connection: keep-alive\r\n"
14551 "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
14553 MockWrite(
14554 "GET / HTTP/1.1\r\n"
14555 "Host: www.example.org\r\n"
14556 "Connection: Upgrade\r\n"
14557 "Upgrade: websocket\r\n"
14558 "Origin: http://www.example.org\r\n"
14559 "Sec-WebSocket-Version: 13\r\n"
14560 "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n"),
14563 MockRead data_reads[] = {
14564 // HTTP CONNECT with credentials.
14565 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
14567 // WebSocket connection established inside tunnel.
14568 MockRead("HTTP/1.1 101 Switching Protocols\r\n"),
14569 MockRead("Upgrade: websocket\r\n"),
14570 MockRead("Connection: Upgrade\r\n"),
14571 MockRead("Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n"),
14574 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
14575 arraysize(data_writes));
14576 session_deps_.socket_factory->AddSocketDataProvider(&data);
14578 session->http_auth_cache()->Add(
14579 GURL("http://myproxy:70/"), "MyRealm1", HttpAuth::AUTH_SCHEME_BASIC,
14580 "Basic realm=MyRealm1", AuthCredentials(kFoo, kBar), "/");
14582 scoped_ptr<HttpTransaction> trans(
14583 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
14584 FakeWebSocketStreamCreateHelper websocket_stream_create_helper;
14585 trans->SetWebSocketHandshakeStreamCreateHelper(
14586 &websocket_stream_create_helper);
14588 TestCompletionCallback callback;
14590 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
14591 EXPECT_EQ(ERR_IO_PENDING, rv);
14593 rv = callback.WaitForResult();
14594 EXPECT_EQ(OK, rv);
14596 const HttpResponseInfo* response = trans->GetResponseInfo();
14597 ASSERT_TRUE(response);
14598 ASSERT_TRUE(response->headers.get());
14600 EXPECT_EQ(101, response->headers->response_code());
14602 trans.reset();
14603 session->CloseAllConnections();
14606 TEST_P(HttpNetworkTransactionTest, TotalNetworkBytesPost) {
14607 ScopedVector<UploadElementReader> element_readers;
14608 element_readers.push_back(new UploadBytesElementReader("foo", 3));
14609 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
14611 HttpRequestInfo request;
14612 request.method = "POST";
14613 request.url = GURL("http://www.foo.com/");
14614 request.upload_data_stream = &upload_data_stream;
14616 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
14617 scoped_ptr<HttpTransaction> trans(
14618 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
14619 MockWrite data_writes[] = {
14620 MockWrite("POST / HTTP/1.1\r\n"
14621 "Host: www.foo.com\r\n"
14622 "Connection: keep-alive\r\n"
14623 "Content-Length: 3\r\n\r\n"),
14624 MockWrite("foo"),
14627 MockRead data_reads[] = {
14628 MockRead("HTTP/1.1 200 OK\r\n\r\n"), MockRead("hello world"),
14629 MockRead(SYNCHRONOUS, OK),
14631 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
14632 arraysize(data_writes));
14633 session_deps_.socket_factory->AddSocketDataProvider(&data);
14635 TestCompletionCallback callback;
14637 EXPECT_EQ(ERR_IO_PENDING,
14638 trans->Start(&request, callback.callback(), BoundNetLog()));
14639 EXPECT_EQ(OK, callback.WaitForResult());
14641 std::string response_data;
14642 EXPECT_EQ(OK, ReadTransaction(trans.get(), &response_data));
14644 EXPECT_EQ(CountWriteBytes(data_writes, arraysize(data_writes)),
14645 trans->GetTotalSentBytes());
14646 EXPECT_EQ(CountReadBytes(data_reads, arraysize(data_reads)),
14647 trans->GetTotalReceivedBytes());
14650 TEST_P(HttpNetworkTransactionTest, TotalNetworkBytesPost100Continue) {
14651 ScopedVector<UploadElementReader> element_readers;
14652 element_readers.push_back(new UploadBytesElementReader("foo", 3));
14653 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
14655 HttpRequestInfo request;
14656 request.method = "POST";
14657 request.url = GURL("http://www.foo.com/");
14658 request.upload_data_stream = &upload_data_stream;
14660 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
14661 scoped_ptr<HttpTransaction> trans(
14662 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
14663 MockWrite data_writes[] = {
14664 MockWrite("POST / HTTP/1.1\r\n"
14665 "Host: www.foo.com\r\n"
14666 "Connection: keep-alive\r\n"
14667 "Content-Length: 3\r\n\r\n"),
14668 MockWrite("foo"),
14671 MockRead data_reads[] = {
14672 MockRead("HTTP/1.1 100 Continue\r\n\r\n"),
14673 MockRead("HTTP/1.1 200 OK\r\n\r\n"), MockRead("hello world"),
14674 MockRead(SYNCHRONOUS, OK),
14676 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
14677 arraysize(data_writes));
14678 session_deps_.socket_factory->AddSocketDataProvider(&data);
14680 TestCompletionCallback callback;
14682 EXPECT_EQ(ERR_IO_PENDING,
14683 trans->Start(&request, callback.callback(), BoundNetLog()));
14684 EXPECT_EQ(OK, callback.WaitForResult());
14686 std::string response_data;
14687 EXPECT_EQ(OK, ReadTransaction(trans.get(), &response_data));
14689 EXPECT_EQ(CountWriteBytes(data_writes, arraysize(data_writes)),
14690 trans->GetTotalSentBytes());
14691 EXPECT_EQ(CountReadBytes(data_reads, arraysize(data_reads)),
14692 trans->GetTotalReceivedBytes());
14695 TEST_P(HttpNetworkTransactionTest, TotalNetworkBytesChunkedPost) {
14696 ScopedVector<UploadElementReader> element_readers;
14697 element_readers.push_back(new UploadBytesElementReader("foo", 3));
14698 ChunkedUploadDataStream upload_data_stream(0);
14700 HttpRequestInfo request;
14701 request.method = "POST";
14702 request.url = GURL("http://www.foo.com/");
14703 request.upload_data_stream = &upload_data_stream;
14705 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
14706 scoped_ptr<HttpTransaction> trans(
14707 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
14708 // Send headers successfully, but get an error while sending the body.
14709 MockWrite data_writes[] = {
14710 MockWrite("POST / HTTP/1.1\r\n"
14711 "Host: www.foo.com\r\n"
14712 "Connection: keep-alive\r\n"
14713 "Transfer-Encoding: chunked\r\n\r\n"),
14714 MockWrite("1\r\nf\r\n"), MockWrite("2\r\noo\r\n"), MockWrite("0\r\n\r\n"),
14717 MockRead data_reads[] = {
14718 MockRead("HTTP/1.1 200 OK\r\n\r\n"), MockRead("hello world"),
14719 MockRead(SYNCHRONOUS, OK),
14721 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
14722 arraysize(data_writes));
14723 session_deps_.socket_factory->AddSocketDataProvider(&data);
14725 TestCompletionCallback callback;
14727 EXPECT_EQ(ERR_IO_PENDING,
14728 trans->Start(&request, callback.callback(), BoundNetLog()));
14730 base::RunLoop().RunUntilIdle();
14731 upload_data_stream.AppendData("f", 1, false);
14733 base::RunLoop().RunUntilIdle();
14734 upload_data_stream.AppendData("oo", 2, true);
14736 EXPECT_EQ(OK, callback.WaitForResult());
14738 std::string response_data;
14739 EXPECT_EQ(OK, ReadTransaction(trans.get(), &response_data));
14741 EXPECT_EQ(CountWriteBytes(data_writes, arraysize(data_writes)),
14742 trans->GetTotalSentBytes());
14743 EXPECT_EQ(CountReadBytes(data_reads, arraysize(data_reads)),
14744 trans->GetTotalReceivedBytes());
14747 } // namespace net