Move android_app_version_* into an inner variables dict.
[chromium-blink-merge.git] / net / http / http_network_transaction_unittest.cc
blob1662d86eef6cdc95aa48032a00ecf6801119e179
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 <string>
10 #include <vector>
12 #include "base/basictypes.h"
13 #include "base/compiler_specific.h"
14 #include "base/files/file_path.h"
15 #include "base/files/file_util.h"
16 #include "base/json/json_writer.h"
17 #include "base/logging.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/memory/weak_ptr.h"
20 #include "base/run_loop.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/test/test_file_util.h"
24 #include "net/base/auth.h"
25 #include "net/base/capturing_net_log.h"
26 #include "net/base/chunked_upload_data_stream.h"
27 #include "net/base/completion_callback.h"
28 #include "net/base/elements_upload_data_stream.h"
29 #include "net/base/load_timing_info.h"
30 #include "net/base/load_timing_info_test_util.h"
31 #include "net/base/net_errors.h"
32 #include "net/base/net_log.h"
33 #include "net/base/net_log_unittest.h"
34 #include "net/base/request_priority.h"
35 #include "net/base/test_completion_callback.h"
36 #include "net/base/test_data_directory.h"
37 #include "net/base/upload_bytes_element_reader.h"
38 #include "net/base/upload_file_element_reader.h"
39 #include "net/cert/mock_cert_verifier.h"
40 #include "net/dns/host_cache.h"
41 #include "net/dns/mock_host_resolver.h"
42 #include "net/http/http_auth_challenge_tokenizer.h"
43 #include "net/http/http_auth_handler_digest.h"
44 #include "net/http/http_auth_handler_mock.h"
45 #include "net/http/http_auth_handler_ntlm.h"
46 #include "net/http/http_basic_state.h"
47 #include "net/http/http_basic_stream.h"
48 #include "net/http/http_network_session.h"
49 #include "net/http/http_network_session_peer.h"
50 #include "net/http/http_request_headers.h"
51 #include "net/http/http_server_properties_impl.h"
52 #include "net/http/http_stream.h"
53 #include "net/http/http_stream_factory.h"
54 #include "net/http/http_stream_parser.h"
55 #include "net/http/http_transaction_test_util.h"
56 #include "net/proxy/proxy_config_service_fixed.h"
57 #include "net/proxy/proxy_info.h"
58 #include "net/proxy/proxy_resolver.h"
59 #include "net/proxy/proxy_service.h"
60 #include "net/socket/client_socket_factory.h"
61 #include "net/socket/client_socket_pool_manager.h"
62 #include "net/socket/mock_client_socket_pool_manager.h"
63 #include "net/socket/next_proto.h"
64 #include "net/socket/socket_test_util.h"
65 #include "net/socket/ssl_client_socket.h"
66 #include "net/spdy/spdy_framer.h"
67 #include "net/spdy/spdy_session.h"
68 #include "net/spdy/spdy_session_pool.h"
69 #include "net/spdy/spdy_test_util_common.h"
70 #include "net/ssl/ssl_cert_request_info.h"
71 #include "net/ssl/ssl_config_service.h"
72 #include "net/ssl/ssl_config_service_defaults.h"
73 #include "net/ssl/ssl_info.h"
74 #include "net/test/cert_test_util.h"
75 #include "net/websockets/websocket_handshake_stream_base.h"
76 #include "testing/gtest/include/gtest/gtest.h"
77 #include "testing/platform_test.h"
78 #include "url/gurl.h"
80 using base::ASCIIToUTF16;
82 //-----------------------------------------------------------------------------
84 namespace {
86 const base::string16 kBar(ASCIIToUTF16("bar"));
87 const base::string16 kBar2(ASCIIToUTF16("bar2"));
88 const base::string16 kBar3(ASCIIToUTF16("bar3"));
89 const base::string16 kBaz(ASCIIToUTF16("baz"));
90 const base::string16 kFirst(ASCIIToUTF16("first"));
91 const base::string16 kFoo(ASCIIToUTF16("foo"));
92 const base::string16 kFoo2(ASCIIToUTF16("foo2"));
93 const base::string16 kFoo3(ASCIIToUTF16("foo3"));
94 const base::string16 kFou(ASCIIToUTF16("fou"));
95 const base::string16 kSecond(ASCIIToUTF16("second"));
96 const base::string16 kTestingNTLM(ASCIIToUTF16("testing-ntlm"));
97 const base::string16 kWrongPassword(ASCIIToUTF16("wrongpassword"));
99 int GetIdleSocketCountInTransportSocketPool(net::HttpNetworkSession* session) {
100 return session->GetTransportSocketPool(
101 net::HttpNetworkSession::NORMAL_SOCKET_POOL)->IdleSocketCount();
104 int GetIdleSocketCountInSSLSocketPool(net::HttpNetworkSession* session) {
105 return session->GetSSLSocketPool(
106 net::HttpNetworkSession::NORMAL_SOCKET_POOL)->IdleSocketCount();
109 bool IsTransportSocketPoolStalled(net::HttpNetworkSession* session) {
110 return session->GetTransportSocketPool(
111 net::HttpNetworkSession::NORMAL_SOCKET_POOL)->IsStalled();
114 // Takes in a Value created from a NetLogHttpResponseParameter, and returns
115 // a JSONified list of headers as a single string. Uses single quotes instead
116 // of double quotes for easier comparison. Returns false on failure.
117 bool GetHeaders(base::DictionaryValue* params, std::string* headers) {
118 if (!params)
119 return false;
120 base::ListValue* header_list;
121 if (!params->GetList("headers", &header_list))
122 return false;
123 std::string double_quote_headers;
124 base::JSONWriter::Write(header_list, &double_quote_headers);
125 base::ReplaceChars(double_quote_headers, "\"", "'", headers);
126 return true;
129 // Tests LoadTimingInfo in the case a socket is reused and no PAC script is
130 // used.
131 void TestLoadTimingReused(const net::LoadTimingInfo& load_timing_info) {
132 EXPECT_TRUE(load_timing_info.socket_reused);
133 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
135 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
136 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
138 net::ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
139 EXPECT_FALSE(load_timing_info.send_start.is_null());
141 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
143 // Set at a higher level.
144 EXPECT_TRUE(load_timing_info.request_start_time.is_null());
145 EXPECT_TRUE(load_timing_info.request_start.is_null());
146 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
149 // Tests LoadTimingInfo in the case a new socket is used and no PAC script is
150 // used.
151 void TestLoadTimingNotReused(const net::LoadTimingInfo& load_timing_info,
152 int connect_timing_flags) {
153 EXPECT_FALSE(load_timing_info.socket_reused);
154 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
156 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
157 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
159 net::ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
160 connect_timing_flags);
161 EXPECT_LE(load_timing_info.connect_timing.connect_end,
162 load_timing_info.send_start);
164 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
166 // Set at a higher level.
167 EXPECT_TRUE(load_timing_info.request_start_time.is_null());
168 EXPECT_TRUE(load_timing_info.request_start.is_null());
169 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
172 // Tests LoadTimingInfo in the case a socket is reused and a PAC script is
173 // used.
174 void TestLoadTimingReusedWithPac(const net::LoadTimingInfo& load_timing_info) {
175 EXPECT_TRUE(load_timing_info.socket_reused);
176 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
178 net::ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
180 EXPECT_FALSE(load_timing_info.proxy_resolve_start.is_null());
181 EXPECT_LE(load_timing_info.proxy_resolve_start,
182 load_timing_info.proxy_resolve_end);
183 EXPECT_LE(load_timing_info.proxy_resolve_end,
184 load_timing_info.send_start);
185 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
187 // Set at a higher level.
188 EXPECT_TRUE(load_timing_info.request_start_time.is_null());
189 EXPECT_TRUE(load_timing_info.request_start.is_null());
190 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
193 // Tests LoadTimingInfo in the case a new socket is used and a PAC script is
194 // used.
195 void TestLoadTimingNotReusedWithPac(const net::LoadTimingInfo& load_timing_info,
196 int connect_timing_flags) {
197 EXPECT_FALSE(load_timing_info.socket_reused);
198 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
200 EXPECT_FALSE(load_timing_info.proxy_resolve_start.is_null());
201 EXPECT_LE(load_timing_info.proxy_resolve_start,
202 load_timing_info.proxy_resolve_end);
203 EXPECT_LE(load_timing_info.proxy_resolve_end,
204 load_timing_info.connect_timing.connect_start);
205 net::ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
206 connect_timing_flags);
207 EXPECT_LE(load_timing_info.connect_timing.connect_end,
208 load_timing_info.send_start);
210 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
212 // Set at a higher level.
213 EXPECT_TRUE(load_timing_info.request_start_time.is_null());
214 EXPECT_TRUE(load_timing_info.request_start.is_null());
215 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
218 void AddWebSocketHeaders(net::HttpRequestHeaders* headers) {
219 headers->SetHeader("Connection", "Upgrade");
220 headers->SetHeader("Upgrade", "websocket");
221 headers->SetHeader("Origin", "http://www.google.com");
222 headers->SetHeader("Sec-WebSocket-Version", "13");
223 headers->SetHeader("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
226 } // namespace
228 namespace net {
230 namespace {
232 HttpNetworkSession* CreateSession(SpdySessionDependencies* session_deps) {
233 return SpdySessionDependencies::SpdyCreateSession(session_deps);
236 } // namespace
238 class HttpNetworkTransactionTest
239 : public PlatformTest,
240 public ::testing::WithParamInterface<NextProto> {
241 public:
242 virtual ~HttpNetworkTransactionTest() {
243 // Important to restore the per-pool limit first, since the pool limit must
244 // always be greater than group limit, and the tests reduce both limits.
245 ClientSocketPoolManager::set_max_sockets_per_pool(
246 HttpNetworkSession::NORMAL_SOCKET_POOL, old_max_pool_sockets_);
247 ClientSocketPoolManager::set_max_sockets_per_group(
248 HttpNetworkSession::NORMAL_SOCKET_POOL, old_max_group_sockets_);
251 protected:
252 HttpNetworkTransactionTest()
253 : spdy_util_(GetParam()),
254 session_deps_(GetParam()),
255 old_max_group_sockets_(ClientSocketPoolManager::max_sockets_per_group(
256 HttpNetworkSession::NORMAL_SOCKET_POOL)),
257 old_max_pool_sockets_(ClientSocketPoolManager::max_sockets_per_pool(
258 HttpNetworkSession::NORMAL_SOCKET_POOL)) {
261 struct SimpleGetHelperResult {
262 int rv;
263 std::string status_line;
264 std::string response_data;
265 int64 totalReceivedBytes;
266 LoadTimingInfo load_timing_info;
269 void SetUp() override {
270 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
271 base::MessageLoop::current()->RunUntilIdle();
274 void TearDown() override {
275 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
276 base::MessageLoop::current()->RunUntilIdle();
277 // Empty the current queue.
278 base::MessageLoop::current()->RunUntilIdle();
279 PlatformTest::TearDown();
280 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
281 base::MessageLoop::current()->RunUntilIdle();
284 const char* GetAlternateProtocolFromParam() {
285 return
286 AlternateProtocolToString(AlternateProtocolFromNextProto(GetParam()));
289 // This is the expected return from a current server advertising SPDY.
290 std::string GetAlternateProtocolHttpHeader() {
291 return std::string("Alternate-Protocol: 443:") +
292 GetAlternateProtocolFromParam() + "\r\n\r\n";
295 // Either |write_failure| specifies a write failure or |read_failure|
296 // specifies a read failure when using a reused socket. In either case, the
297 // failure should cause the network transaction to resend the request, and the
298 // other argument should be NULL.
299 void KeepAliveConnectionResendRequestTest(const MockWrite* write_failure,
300 const MockRead* read_failure);
302 // Either |write_failure| specifies a write failure or |read_failure|
303 // specifies a read failure when using a reused socket. In either case, the
304 // failure should cause the network transaction to resend the request, and the
305 // other argument should be NULL.
306 void PreconnectErrorResendRequestTest(const MockWrite* write_failure,
307 const MockRead* read_failure,
308 bool use_spdy);
310 SimpleGetHelperResult SimpleGetHelperForData(StaticSocketDataProvider* data[],
311 size_t data_count) {
312 SimpleGetHelperResult out;
314 HttpRequestInfo request;
315 request.method = "GET";
316 request.url = GURL("http://www.google.com/");
317 request.load_flags = 0;
319 CapturingBoundNetLog log;
320 session_deps_.net_log = log.bound().net_log();
321 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
322 scoped_ptr<HttpTransaction> trans(
323 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
325 for (size_t i = 0; i < data_count; ++i) {
326 session_deps_.socket_factory->AddSocketDataProvider(data[i]);
329 TestCompletionCallback callback;
331 EXPECT_TRUE(log.bound().IsLogging());
332 int rv = trans->Start(&request, callback.callback(), log.bound());
333 EXPECT_EQ(ERR_IO_PENDING, rv);
335 out.rv = callback.WaitForResult();
337 // Even in the failure cases that use this function, connections are always
338 // successfully established before the error.
339 EXPECT_TRUE(trans->GetLoadTimingInfo(&out.load_timing_info));
340 TestLoadTimingNotReused(out.load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
342 if (out.rv != OK)
343 return out;
345 const HttpResponseInfo* response = trans->GetResponseInfo();
346 // Can't use ASSERT_* inside helper functions like this, so
347 // return an error.
348 if (response == NULL || response->headers.get() == NULL) {
349 out.rv = ERR_UNEXPECTED;
350 return out;
352 out.status_line = response->headers->GetStatusLine();
354 EXPECT_EQ("127.0.0.1", response->socket_address.host());
355 EXPECT_EQ(80, response->socket_address.port());
357 rv = ReadTransaction(trans.get(), &out.response_data);
358 EXPECT_EQ(OK, rv);
360 net::CapturingNetLog::CapturedEntryList entries;
361 log.GetEntries(&entries);
362 size_t pos = ExpectLogContainsSomewhere(
363 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST_HEADERS,
364 NetLog::PHASE_NONE);
365 ExpectLogContainsSomewhere(
366 entries, pos,
367 NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS,
368 NetLog::PHASE_NONE);
370 std::string line;
371 EXPECT_TRUE(entries[pos].GetStringValue("line", &line));
372 EXPECT_EQ("GET / HTTP/1.1\r\n", line);
374 HttpRequestHeaders request_headers;
375 EXPECT_TRUE(trans->GetFullRequestHeaders(&request_headers));
376 std::string value;
377 EXPECT_TRUE(request_headers.GetHeader("Host", &value));
378 EXPECT_EQ("www.google.com", value);
379 EXPECT_TRUE(request_headers.GetHeader("Connection", &value));
380 EXPECT_EQ("keep-alive", value);
382 std::string response_headers;
383 EXPECT_TRUE(GetHeaders(entries[pos].params.get(), &response_headers));
384 EXPECT_EQ("['Host: www.google.com','Connection: keep-alive']",
385 response_headers);
387 out.totalReceivedBytes = trans->GetTotalReceivedBytes();
388 return out;
391 SimpleGetHelperResult SimpleGetHelper(MockRead data_reads[],
392 size_t reads_count) {
393 StaticSocketDataProvider reads(data_reads, reads_count, NULL, 0);
394 StaticSocketDataProvider* data[] = { &reads };
395 return SimpleGetHelperForData(data, 1);
398 int64 ReadsSize(MockRead data_reads[], size_t reads_count) {
399 int64 size = 0;
400 for (size_t i = 0; i < reads_count; ++i)
401 size += data_reads[i].data_len;
402 return size;
405 void ConnectStatusHelperWithExpectedStatus(const MockRead& status,
406 int expected_status);
408 void ConnectStatusHelper(const MockRead& status);
410 void BypassHostCacheOnRefreshHelper(int load_flags);
412 void CheckErrorIsPassedBack(int error, IoMode mode);
414 SpdyTestUtil spdy_util_;
415 SpdySessionDependencies session_deps_;
417 // Original socket limits. Some tests set these. Safest to always restore
418 // them once each test has been run.
419 int old_max_group_sockets_;
420 int old_max_pool_sockets_;
423 INSTANTIATE_TEST_CASE_P(NextProto,
424 HttpNetworkTransactionTest,
425 testing::Values(kProtoSPDY31,
426 kProtoSPDY4_14,
427 kProtoSPDY4));
429 namespace {
431 class BeforeNetworkStartHandler {
432 public:
433 explicit BeforeNetworkStartHandler(bool defer)
434 : defer_on_before_network_start_(defer),
435 observed_before_network_start_(false) {}
437 void OnBeforeNetworkStart(bool* defer) {
438 *defer = defer_on_before_network_start_;
439 observed_before_network_start_ = true;
442 bool observed_before_network_start() const {
443 return observed_before_network_start_;
446 private:
447 const bool defer_on_before_network_start_;
448 bool observed_before_network_start_;
450 DISALLOW_COPY_AND_ASSIGN(BeforeNetworkStartHandler);
453 class BeforeProxyHeadersSentHandler {
454 public:
455 BeforeProxyHeadersSentHandler()
456 : observed_before_proxy_headers_sent_(false) {}
458 void OnBeforeProxyHeadersSent(const ProxyInfo& proxy_info,
459 HttpRequestHeaders* request_headers) {
460 observed_before_proxy_headers_sent_ = true;
461 observed_proxy_server_uri_ = proxy_info.proxy_server().ToURI();
464 bool observed_before_proxy_headers_sent() const {
465 return observed_before_proxy_headers_sent_;
468 std::string observed_proxy_server_uri() const {
469 return observed_proxy_server_uri_;
472 private:
473 bool observed_before_proxy_headers_sent_;
474 std::string observed_proxy_server_uri_;
476 DISALLOW_COPY_AND_ASSIGN(BeforeProxyHeadersSentHandler);
479 // Fill |str| with a long header list that consumes >= |size| bytes.
480 void FillLargeHeadersString(std::string* str, int size) {
481 const char row[] =
482 "SomeHeaderName: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n";
483 const int sizeof_row = strlen(row);
484 const int num_rows = static_cast<int>(
485 ceil(static_cast<float>(size) / sizeof_row));
486 const int sizeof_data = num_rows * sizeof_row;
487 DCHECK(sizeof_data >= size);
488 str->reserve(sizeof_data);
490 for (int i = 0; i < num_rows; ++i)
491 str->append(row, sizeof_row);
494 // Alternative functions that eliminate randomness and dependency on the local
495 // host name so that the generated NTLM messages are reproducible.
496 void MockGenerateRandom1(uint8* output, size_t n) {
497 static const uint8 bytes[] = {
498 0x55, 0x29, 0x66, 0x26, 0x6b, 0x9c, 0x73, 0x54
500 static size_t current_byte = 0;
501 for (size_t i = 0; i < n; ++i) {
502 output[i] = bytes[current_byte++];
503 current_byte %= arraysize(bytes);
507 void MockGenerateRandom2(uint8* output, size_t n) {
508 static const uint8 bytes[] = {
509 0x96, 0x79, 0x85, 0xe7, 0x49, 0x93, 0x70, 0xa1,
510 0x4e, 0xe7, 0x87, 0x45, 0x31, 0x5b, 0xd3, 0x1f
512 static size_t current_byte = 0;
513 for (size_t i = 0; i < n; ++i) {
514 output[i] = bytes[current_byte++];
515 current_byte %= arraysize(bytes);
519 std::string MockGetHostName() {
520 return "WTC-WIN7";
523 template<typename ParentPool>
524 class CaptureGroupNameSocketPool : public ParentPool {
525 public:
526 CaptureGroupNameSocketPool(HostResolver* host_resolver,
527 CertVerifier* cert_verifier);
529 const std::string last_group_name_received() const {
530 return last_group_name_;
533 int RequestSocket(const std::string& group_name,
534 const void* socket_params,
535 RequestPriority priority,
536 ClientSocketHandle* handle,
537 const CompletionCallback& callback,
538 const BoundNetLog& net_log) override {
539 last_group_name_ = group_name;
540 return ERR_IO_PENDING;
542 void CancelRequest(const std::string& group_name,
543 ClientSocketHandle* handle) override {}
544 void ReleaseSocket(const std::string& group_name,
545 scoped_ptr<StreamSocket> socket,
546 int id) override {}
547 void CloseIdleSockets() override {}
548 int IdleSocketCount() const override { return 0; }
549 int IdleSocketCountInGroup(const std::string& group_name) const override {
550 return 0;
552 LoadState GetLoadState(const std::string& group_name,
553 const ClientSocketHandle* handle) const override {
554 return LOAD_STATE_IDLE;
556 base::TimeDelta ConnectionTimeout() const override {
557 return base::TimeDelta();
560 private:
561 std::string last_group_name_;
564 typedef CaptureGroupNameSocketPool<TransportClientSocketPool>
565 CaptureGroupNameTransportSocketPool;
566 typedef CaptureGroupNameSocketPool<HttpProxyClientSocketPool>
567 CaptureGroupNameHttpProxySocketPool;
568 typedef CaptureGroupNameSocketPool<SOCKSClientSocketPool>
569 CaptureGroupNameSOCKSSocketPool;
570 typedef CaptureGroupNameSocketPool<SSLClientSocketPool>
571 CaptureGroupNameSSLSocketPool;
573 template <typename ParentPool>
574 CaptureGroupNameSocketPool<ParentPool>::CaptureGroupNameSocketPool(
575 HostResolver* host_resolver,
576 CertVerifier* /* cert_verifier */)
577 : ParentPool(0, 0, host_resolver, NULL, NULL) {
580 template <>
581 CaptureGroupNameHttpProxySocketPool::CaptureGroupNameSocketPool(
582 HostResolver* /* host_resolver */,
583 CertVerifier* /* cert_verifier */)
584 : HttpProxyClientSocketPool(0, 0, NULL, NULL, NULL) {
587 template <>
588 CaptureGroupNameSSLSocketPool::CaptureGroupNameSocketPool(
589 HostResolver* /* host_resolver */,
590 CertVerifier* cert_verifier)
591 : SSLClientSocketPool(0,
593 cert_verifier,
594 NULL,
595 NULL,
596 NULL,
597 NULL,
598 std::string(),
599 NULL,
600 NULL,
601 NULL,
602 NULL,
603 NULL,
604 NULL) {
607 //-----------------------------------------------------------------------------
609 // Helper functions for validating that AuthChallengeInfo's are correctly
610 // configured for common cases.
611 bool CheckBasicServerAuth(const AuthChallengeInfo* auth_challenge) {
612 if (!auth_challenge)
613 return false;
614 EXPECT_FALSE(auth_challenge->is_proxy);
615 EXPECT_EQ("www.google.com:80", auth_challenge->challenger.ToString());
616 EXPECT_EQ("MyRealm1", auth_challenge->realm);
617 EXPECT_EQ("basic", auth_challenge->scheme);
618 return true;
621 bool CheckBasicProxyAuth(const AuthChallengeInfo* auth_challenge) {
622 if (!auth_challenge)
623 return false;
624 EXPECT_TRUE(auth_challenge->is_proxy);
625 EXPECT_EQ("myproxy:70", auth_challenge->challenger.ToString());
626 EXPECT_EQ("MyRealm1", auth_challenge->realm);
627 EXPECT_EQ("basic", auth_challenge->scheme);
628 return true;
631 bool CheckDigestServerAuth(const AuthChallengeInfo* auth_challenge) {
632 if (!auth_challenge)
633 return false;
634 EXPECT_FALSE(auth_challenge->is_proxy);
635 EXPECT_EQ("www.google.com:80", auth_challenge->challenger.ToString());
636 EXPECT_EQ("digestive", auth_challenge->realm);
637 EXPECT_EQ("digest", auth_challenge->scheme);
638 return true;
641 bool CheckNTLMServerAuth(const AuthChallengeInfo* auth_challenge) {
642 if (!auth_challenge)
643 return false;
644 EXPECT_FALSE(auth_challenge->is_proxy);
645 EXPECT_EQ("172.22.68.17:80", auth_challenge->challenger.ToString());
646 EXPECT_EQ(std::string(), auth_challenge->realm);
647 EXPECT_EQ("ntlm", auth_challenge->scheme);
648 return true;
651 } // namespace
653 TEST_P(HttpNetworkTransactionTest, Basic) {
654 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
655 scoped_ptr<HttpTransaction> trans(
656 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
659 TEST_P(HttpNetworkTransactionTest, SimpleGET) {
660 MockRead data_reads[] = {
661 MockRead("HTTP/1.0 200 OK\r\n\r\n"),
662 MockRead("hello world"),
663 MockRead(SYNCHRONOUS, OK),
665 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
666 arraysize(data_reads));
667 EXPECT_EQ(OK, out.rv);
668 EXPECT_EQ("HTTP/1.0 200 OK", out.status_line);
669 EXPECT_EQ("hello world", out.response_data);
670 int64 reads_size = ReadsSize(data_reads, arraysize(data_reads));
671 EXPECT_EQ(reads_size, out.totalReceivedBytes);
674 // Response with no status line.
675 TEST_P(HttpNetworkTransactionTest, SimpleGETNoHeaders) {
676 MockRead data_reads[] = {
677 MockRead("hello world"),
678 MockRead(SYNCHRONOUS, OK),
680 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
681 arraysize(data_reads));
682 EXPECT_EQ(OK, out.rv);
683 EXPECT_EQ("HTTP/0.9 200 OK", out.status_line);
684 EXPECT_EQ("hello world", out.response_data);
685 int64 reads_size = ReadsSize(data_reads, arraysize(data_reads));
686 EXPECT_EQ(reads_size, out.totalReceivedBytes);
689 // Allow up to 4 bytes of junk to precede status line.
690 TEST_P(HttpNetworkTransactionTest, StatusLineJunk3Bytes) {
691 MockRead data_reads[] = {
692 MockRead("xxxHTTP/1.0 404 Not Found\nServer: blah\n\nDATA"),
693 MockRead(SYNCHRONOUS, OK),
695 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
696 arraysize(data_reads));
697 EXPECT_EQ(OK, out.rv);
698 EXPECT_EQ("HTTP/1.0 404 Not Found", out.status_line);
699 EXPECT_EQ("DATA", out.response_data);
700 int64 reads_size = ReadsSize(data_reads, arraysize(data_reads));
701 EXPECT_EQ(reads_size, out.totalReceivedBytes);
704 // Allow up to 4 bytes of junk to precede status line.
705 TEST_P(HttpNetworkTransactionTest, StatusLineJunk4Bytes) {
706 MockRead data_reads[] = {
707 MockRead("\n\nQJHTTP/1.0 404 Not Found\nServer: blah\n\nDATA"),
708 MockRead(SYNCHRONOUS, OK),
710 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
711 arraysize(data_reads));
712 EXPECT_EQ(OK, out.rv);
713 EXPECT_EQ("HTTP/1.0 404 Not Found", out.status_line);
714 EXPECT_EQ("DATA", out.response_data);
715 int64 reads_size = ReadsSize(data_reads, arraysize(data_reads));
716 EXPECT_EQ(reads_size, out.totalReceivedBytes);
719 // Beyond 4 bytes of slop and it should fail to find a status line.
720 TEST_P(HttpNetworkTransactionTest, StatusLineJunk5Bytes) {
721 MockRead data_reads[] = {
722 MockRead("xxxxxHTTP/1.1 404 Not Found\nServer: blah"),
723 MockRead(SYNCHRONOUS, OK),
725 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
726 arraysize(data_reads));
727 EXPECT_EQ(OK, out.rv);
728 EXPECT_EQ("HTTP/0.9 200 OK", out.status_line);
729 EXPECT_EQ("xxxxxHTTP/1.1 404 Not Found\nServer: blah", out.response_data);
730 int64 reads_size = ReadsSize(data_reads, arraysize(data_reads));
731 EXPECT_EQ(reads_size, out.totalReceivedBytes);
734 // Same as StatusLineJunk4Bytes, except the read chunks are smaller.
735 TEST_P(HttpNetworkTransactionTest, StatusLineJunk4Bytes_Slow) {
736 MockRead data_reads[] = {
737 MockRead("\n"),
738 MockRead("\n"),
739 MockRead("Q"),
740 MockRead("J"),
741 MockRead("HTTP/1.0 404 Not Found\nServer: blah\n\nDATA"),
742 MockRead(SYNCHRONOUS, OK),
744 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
745 arraysize(data_reads));
746 EXPECT_EQ(OK, out.rv);
747 EXPECT_EQ("HTTP/1.0 404 Not Found", out.status_line);
748 EXPECT_EQ("DATA", out.response_data);
749 int64 reads_size = ReadsSize(data_reads, arraysize(data_reads));
750 EXPECT_EQ(reads_size, out.totalReceivedBytes);
753 // Close the connection before enough bytes to have a status line.
754 TEST_P(HttpNetworkTransactionTest, StatusLinePartial) {
755 MockRead data_reads[] = {
756 MockRead("HTT"),
757 MockRead(SYNCHRONOUS, OK),
759 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
760 arraysize(data_reads));
761 EXPECT_EQ(OK, out.rv);
762 EXPECT_EQ("HTTP/0.9 200 OK", out.status_line);
763 EXPECT_EQ("HTT", out.response_data);
764 int64 reads_size = ReadsSize(data_reads, arraysize(data_reads));
765 EXPECT_EQ(reads_size, out.totalReceivedBytes);
768 // Simulate a 204 response, lacking a Content-Length header, sent over a
769 // persistent connection. The response should still terminate since a 204
770 // cannot have a response body.
771 TEST_P(HttpNetworkTransactionTest, StopsReading204) {
772 char junk[] = "junk";
773 MockRead data_reads[] = {
774 MockRead("HTTP/1.1 204 No Content\r\n\r\n"),
775 MockRead(junk), // Should not be read!!
776 MockRead(SYNCHRONOUS, OK),
778 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
779 arraysize(data_reads));
780 EXPECT_EQ(OK, out.rv);
781 EXPECT_EQ("HTTP/1.1 204 No Content", out.status_line);
782 EXPECT_EQ("", out.response_data);
783 int64 reads_size = ReadsSize(data_reads, arraysize(data_reads));
784 int64 response_size = reads_size - strlen(junk);
785 EXPECT_EQ(response_size, out.totalReceivedBytes);
788 // A simple request using chunked encoding with some extra data after.
789 TEST_P(HttpNetworkTransactionTest, ChunkedEncoding) {
790 std::string final_chunk = "0\r\n\r\n";
791 std::string extra_data = "HTTP/1.1 200 OK\r\n";
792 std::string last_read = final_chunk + extra_data;
793 MockRead data_reads[] = {
794 MockRead("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"),
795 MockRead("5\r\nHello\r\n"),
796 MockRead("1\r\n"),
797 MockRead(" \r\n"),
798 MockRead("5\r\nworld\r\n"),
799 MockRead(last_read.data()),
800 MockRead(SYNCHRONOUS, OK),
802 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
803 arraysize(data_reads));
804 EXPECT_EQ(OK, out.rv);
805 EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
806 EXPECT_EQ("Hello world", out.response_data);
807 int64 reads_size = ReadsSize(data_reads, arraysize(data_reads));
808 int64 response_size = reads_size - extra_data.size();
809 EXPECT_EQ(response_size, out.totalReceivedBytes);
812 // Next tests deal with http://crbug.com/56344.
814 TEST_P(HttpNetworkTransactionTest,
815 MultipleContentLengthHeadersNoTransferEncoding) {
816 MockRead data_reads[] = {
817 MockRead("HTTP/1.1 200 OK\r\n"),
818 MockRead("Content-Length: 10\r\n"),
819 MockRead("Content-Length: 5\r\n\r\n"),
821 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
822 arraysize(data_reads));
823 EXPECT_EQ(ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH, out.rv);
826 TEST_P(HttpNetworkTransactionTest,
827 DuplicateContentLengthHeadersNoTransferEncoding) {
828 MockRead data_reads[] = {
829 MockRead("HTTP/1.1 200 OK\r\n"),
830 MockRead("Content-Length: 5\r\n"),
831 MockRead("Content-Length: 5\r\n\r\n"),
832 MockRead("Hello"),
834 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
835 arraysize(data_reads));
836 EXPECT_EQ(OK, out.rv);
837 EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
838 EXPECT_EQ("Hello", out.response_data);
841 TEST_P(HttpNetworkTransactionTest,
842 ComplexContentLengthHeadersNoTransferEncoding) {
843 // More than 2 dupes.
845 MockRead data_reads[] = {
846 MockRead("HTTP/1.1 200 OK\r\n"),
847 MockRead("Content-Length: 5\r\n"),
848 MockRead("Content-Length: 5\r\n"),
849 MockRead("Content-Length: 5\r\n\r\n"),
850 MockRead("Hello"),
852 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
853 arraysize(data_reads));
854 EXPECT_EQ(OK, out.rv);
855 EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
856 EXPECT_EQ("Hello", out.response_data);
858 // HTTP/1.0
860 MockRead data_reads[] = {
861 MockRead("HTTP/1.0 200 OK\r\n"),
862 MockRead("Content-Length: 5\r\n"),
863 MockRead("Content-Length: 5\r\n"),
864 MockRead("Content-Length: 5\r\n\r\n"),
865 MockRead("Hello"),
867 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
868 arraysize(data_reads));
869 EXPECT_EQ(OK, out.rv);
870 EXPECT_EQ("HTTP/1.0 200 OK", out.status_line);
871 EXPECT_EQ("Hello", out.response_data);
873 // 2 dupes and one mismatched.
875 MockRead data_reads[] = {
876 MockRead("HTTP/1.1 200 OK\r\n"),
877 MockRead("Content-Length: 10\r\n"),
878 MockRead("Content-Length: 10\r\n"),
879 MockRead("Content-Length: 5\r\n\r\n"),
881 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
882 arraysize(data_reads));
883 EXPECT_EQ(ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH, out.rv);
887 TEST_P(HttpNetworkTransactionTest,
888 MultipleContentLengthHeadersTransferEncoding) {
889 MockRead data_reads[] = {
890 MockRead("HTTP/1.1 200 OK\r\n"),
891 MockRead("Content-Length: 666\r\n"),
892 MockRead("Content-Length: 1337\r\n"),
893 MockRead("Transfer-Encoding: chunked\r\n\r\n"),
894 MockRead("5\r\nHello\r\n"),
895 MockRead("1\r\n"),
896 MockRead(" \r\n"),
897 MockRead("5\r\nworld\r\n"),
898 MockRead("0\r\n\r\nHTTP/1.1 200 OK\r\n"),
899 MockRead(SYNCHRONOUS, OK),
901 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
902 arraysize(data_reads));
903 EXPECT_EQ(OK, out.rv);
904 EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
905 EXPECT_EQ("Hello world", out.response_data);
908 // Next tests deal with http://crbug.com/98895.
910 // Checks that a single Content-Disposition header results in no error.
911 TEST_P(HttpNetworkTransactionTest, SingleContentDispositionHeader) {
912 MockRead data_reads[] = {
913 MockRead("HTTP/1.1 200 OK\r\n"),
914 MockRead("Content-Disposition: attachment;filename=\"salutations.txt\"r\n"),
915 MockRead("Content-Length: 5\r\n\r\n"),
916 MockRead("Hello"),
918 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
919 arraysize(data_reads));
920 EXPECT_EQ(OK, out.rv);
921 EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
922 EXPECT_EQ("Hello", out.response_data);
925 // Checks that two identical Content-Disposition headers result in no error.
926 TEST_P(HttpNetworkTransactionTest,
927 TwoIdenticalContentDispositionHeaders) {
928 MockRead data_reads[] = {
929 MockRead("HTTP/1.1 200 OK\r\n"),
930 MockRead("Content-Disposition: attachment;filename=\"greetings.txt\"r\n"),
931 MockRead("Content-Disposition: attachment;filename=\"greetings.txt\"r\n"),
932 MockRead("Content-Length: 5\r\n\r\n"),
933 MockRead("Hello"),
935 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
936 arraysize(data_reads));
937 EXPECT_EQ(OK, out.rv);
938 EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
939 EXPECT_EQ("Hello", out.response_data);
942 // Checks that two distinct Content-Disposition headers result in an error.
943 TEST_P(HttpNetworkTransactionTest, TwoDistinctContentDispositionHeaders) {
944 MockRead data_reads[] = {
945 MockRead("HTTP/1.1 200 OK\r\n"),
946 MockRead("Content-Disposition: attachment;filename=\"greetings.txt\"r\n"),
947 MockRead("Content-Disposition: attachment;filename=\"hi.txt\"r\n"),
948 MockRead("Content-Length: 5\r\n\r\n"),
949 MockRead("Hello"),
951 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
952 arraysize(data_reads));
953 EXPECT_EQ(ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION, out.rv);
956 // Checks that two identical Location headers result in no error.
957 // Also tests Location header behavior.
958 TEST_P(HttpNetworkTransactionTest, TwoIdenticalLocationHeaders) {
959 MockRead data_reads[] = {
960 MockRead("HTTP/1.1 302 Redirect\r\n"),
961 MockRead("Location: http://good.com/\r\n"),
962 MockRead("Location: http://good.com/\r\n"),
963 MockRead("Content-Length: 0\r\n\r\n"),
964 MockRead(SYNCHRONOUS, OK),
967 HttpRequestInfo request;
968 request.method = "GET";
969 request.url = GURL("http://redirect.com/");
970 request.load_flags = 0;
972 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
973 scoped_ptr<HttpTransaction> trans(
974 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
976 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
977 session_deps_.socket_factory->AddSocketDataProvider(&data);
979 TestCompletionCallback callback;
981 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
982 EXPECT_EQ(ERR_IO_PENDING, rv);
984 EXPECT_EQ(OK, callback.WaitForResult());
986 const HttpResponseInfo* response = trans->GetResponseInfo();
987 ASSERT_TRUE(response != NULL && response->headers.get() != NULL);
988 EXPECT_EQ("HTTP/1.1 302 Redirect", response->headers->GetStatusLine());
989 std::string url;
990 EXPECT_TRUE(response->headers->IsRedirect(&url));
991 EXPECT_EQ("http://good.com/", url);
992 EXPECT_TRUE(response->proxy_server.IsEmpty());
995 // Checks that two distinct Location headers result in an error.
996 TEST_P(HttpNetworkTransactionTest, TwoDistinctLocationHeaders) {
997 MockRead data_reads[] = {
998 MockRead("HTTP/1.1 302 Redirect\r\n"),
999 MockRead("Location: http://good.com/\r\n"),
1000 MockRead("Location: http://evil.com/\r\n"),
1001 MockRead("Content-Length: 0\r\n\r\n"),
1002 MockRead(SYNCHRONOUS, OK),
1004 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
1005 arraysize(data_reads));
1006 EXPECT_EQ(ERR_RESPONSE_HEADERS_MULTIPLE_LOCATION, out.rv);
1009 // Do a request using the HEAD method. Verify that we don't try to read the
1010 // message body (since HEAD has none).
1011 TEST_P(HttpNetworkTransactionTest, Head) {
1012 HttpRequestInfo request;
1013 request.method = "HEAD";
1014 request.url = GURL("http://www.google.com/");
1015 request.load_flags = 0;
1017 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1018 scoped_ptr<HttpTransaction> trans(
1019 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1020 BeforeProxyHeadersSentHandler proxy_headers_handler;
1021 trans->SetBeforeProxyHeadersSentCallback(
1022 base::Bind(&BeforeProxyHeadersSentHandler::OnBeforeProxyHeadersSent,
1023 base::Unretained(&proxy_headers_handler)));
1025 MockWrite data_writes1[] = {
1026 MockWrite("HEAD / HTTP/1.1\r\n"
1027 "Host: www.google.com\r\n"
1028 "Connection: keep-alive\r\n"
1029 "Content-Length: 0\r\n\r\n"),
1031 MockRead data_reads1[] = {
1032 MockRead("HTTP/1.1 404 Not Found\r\n"),
1033 MockRead("Server: Blah\r\n"),
1034 MockRead("Content-Length: 1234\r\n\r\n"),
1036 // No response body because the test stops reading here.
1037 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
1040 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
1041 data_writes1, arraysize(data_writes1));
1042 session_deps_.socket_factory->AddSocketDataProvider(&data1);
1044 TestCompletionCallback callback1;
1046 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
1047 EXPECT_EQ(ERR_IO_PENDING, rv);
1049 rv = callback1.WaitForResult();
1050 EXPECT_EQ(OK, rv);
1052 const HttpResponseInfo* response = trans->GetResponseInfo();
1053 ASSERT_TRUE(response != NULL);
1055 // Check that the headers got parsed.
1056 EXPECT_TRUE(response->headers.get() != NULL);
1057 EXPECT_EQ(1234, response->headers->GetContentLength());
1058 EXPECT_EQ("HTTP/1.1 404 Not Found", response->headers->GetStatusLine());
1059 EXPECT_TRUE(response->proxy_server.IsEmpty());
1060 EXPECT_FALSE(proxy_headers_handler.observed_before_proxy_headers_sent());
1062 std::string server_header;
1063 void* iter = NULL;
1064 bool has_server_header = response->headers->EnumerateHeader(
1065 &iter, "Server", &server_header);
1066 EXPECT_TRUE(has_server_header);
1067 EXPECT_EQ("Blah", server_header);
1069 // Reading should give EOF right away, since there is no message body
1070 // (despite non-zero content-length).
1071 std::string response_data;
1072 rv = ReadTransaction(trans.get(), &response_data);
1073 EXPECT_EQ(OK, rv);
1074 EXPECT_EQ("", response_data);
1077 TEST_P(HttpNetworkTransactionTest, ReuseConnection) {
1078 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1080 MockRead data_reads[] = {
1081 MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
1082 MockRead("hello"),
1083 MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
1084 MockRead("world"),
1085 MockRead(SYNCHRONOUS, OK),
1087 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1088 session_deps_.socket_factory->AddSocketDataProvider(&data);
1090 const char* const kExpectedResponseData[] = {
1091 "hello", "world"
1094 for (int i = 0; i < 2; ++i) {
1095 HttpRequestInfo request;
1096 request.method = "GET";
1097 request.url = GURL("http://www.google.com/");
1098 request.load_flags = 0;
1100 scoped_ptr<HttpTransaction> trans(
1101 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1103 TestCompletionCallback callback;
1105 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1106 EXPECT_EQ(ERR_IO_PENDING, rv);
1108 rv = callback.WaitForResult();
1109 EXPECT_EQ(OK, rv);
1111 const HttpResponseInfo* response = trans->GetResponseInfo();
1112 ASSERT_TRUE(response != NULL);
1114 EXPECT_TRUE(response->headers.get() != NULL);
1115 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
1116 EXPECT_TRUE(response->proxy_server.IsEmpty());
1118 std::string response_data;
1119 rv = ReadTransaction(trans.get(), &response_data);
1120 EXPECT_EQ(OK, rv);
1121 EXPECT_EQ(kExpectedResponseData[i], response_data);
1125 TEST_P(HttpNetworkTransactionTest, Ignores100) {
1126 ScopedVector<UploadElementReader> element_readers;
1127 element_readers.push_back(new UploadBytesElementReader("foo", 3));
1128 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
1130 HttpRequestInfo request;
1131 request.method = "POST";
1132 request.url = GURL("http://www.foo.com/");
1133 request.upload_data_stream = &upload_data_stream;
1134 request.load_flags = 0;
1136 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1137 scoped_ptr<HttpTransaction> trans(
1138 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1140 MockRead data_reads[] = {
1141 MockRead("HTTP/1.0 100 Continue\r\n\r\n"),
1142 MockRead("HTTP/1.0 200 OK\r\n\r\n"),
1143 MockRead("hello world"),
1144 MockRead(SYNCHRONOUS, OK),
1146 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1147 session_deps_.socket_factory->AddSocketDataProvider(&data);
1149 TestCompletionCallback callback;
1151 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1152 EXPECT_EQ(ERR_IO_PENDING, rv);
1154 rv = callback.WaitForResult();
1155 EXPECT_EQ(OK, rv);
1157 const HttpResponseInfo* response = trans->GetResponseInfo();
1158 ASSERT_TRUE(response != NULL);
1160 EXPECT_TRUE(response->headers.get() != NULL);
1161 EXPECT_EQ("HTTP/1.0 200 OK", response->headers->GetStatusLine());
1163 std::string response_data;
1164 rv = ReadTransaction(trans.get(), &response_data);
1165 EXPECT_EQ(OK, rv);
1166 EXPECT_EQ("hello world", response_data);
1169 // This test is almost the same as Ignores100 above, but the response contains
1170 // a 102 instead of a 100. Also, instead of HTTP/1.0 the response is
1171 // HTTP/1.1 and the two status headers are read in one read.
1172 TEST_P(HttpNetworkTransactionTest, Ignores1xx) {
1173 HttpRequestInfo request;
1174 request.method = "GET";
1175 request.url = GURL("http://www.foo.com/");
1176 request.load_flags = 0;
1178 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1179 scoped_ptr<HttpTransaction> trans(
1180 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1182 MockRead data_reads[] = {
1183 MockRead("HTTP/1.1 102 Unspecified status code\r\n\r\n"
1184 "HTTP/1.1 200 OK\r\n\r\n"),
1185 MockRead("hello world"),
1186 MockRead(SYNCHRONOUS, OK),
1188 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1189 session_deps_.socket_factory->AddSocketDataProvider(&data);
1191 TestCompletionCallback callback;
1193 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1194 EXPECT_EQ(ERR_IO_PENDING, rv);
1196 rv = callback.WaitForResult();
1197 EXPECT_EQ(OK, rv);
1199 const HttpResponseInfo* response = trans->GetResponseInfo();
1200 ASSERT_TRUE(response != NULL);
1202 EXPECT_TRUE(response->headers.get() != NULL);
1203 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
1205 std::string response_data;
1206 rv = ReadTransaction(trans.get(), &response_data);
1207 EXPECT_EQ(OK, rv);
1208 EXPECT_EQ("hello world", response_data);
1211 TEST_P(HttpNetworkTransactionTest, Incomplete100ThenEOF) {
1212 HttpRequestInfo request;
1213 request.method = "POST";
1214 request.url = GURL("http://www.foo.com/");
1215 request.load_flags = 0;
1217 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1218 scoped_ptr<HttpTransaction> trans(
1219 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1221 MockRead data_reads[] = {
1222 MockRead(SYNCHRONOUS, "HTTP/1.0 100 Continue\r\n"),
1223 MockRead(ASYNC, 0),
1225 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1226 session_deps_.socket_factory->AddSocketDataProvider(&data);
1228 TestCompletionCallback callback;
1230 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1231 EXPECT_EQ(ERR_IO_PENDING, rv);
1233 rv = callback.WaitForResult();
1234 EXPECT_EQ(OK, rv);
1236 std::string response_data;
1237 rv = ReadTransaction(trans.get(), &response_data);
1238 EXPECT_EQ(OK, rv);
1239 EXPECT_EQ("", response_data);
1242 TEST_P(HttpNetworkTransactionTest, EmptyResponse) {
1243 HttpRequestInfo request;
1244 request.method = "POST";
1245 request.url = GURL("http://www.foo.com/");
1246 request.load_flags = 0;
1248 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1249 scoped_ptr<HttpTransaction> trans(
1250 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1252 MockRead data_reads[] = {
1253 MockRead(ASYNC, 0),
1255 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1256 session_deps_.socket_factory->AddSocketDataProvider(&data);
1258 TestCompletionCallback callback;
1260 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1261 EXPECT_EQ(ERR_IO_PENDING, rv);
1263 rv = callback.WaitForResult();
1264 EXPECT_EQ(ERR_EMPTY_RESPONSE, rv);
1267 void HttpNetworkTransactionTest::KeepAliveConnectionResendRequestTest(
1268 const MockWrite* write_failure,
1269 const MockRead* read_failure) {
1270 HttpRequestInfo request;
1271 request.method = "GET";
1272 request.url = GURL("http://www.foo.com/");
1273 request.load_flags = 0;
1275 CapturingNetLog net_log;
1276 session_deps_.net_log = &net_log;
1277 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1279 // Written data for successfully sending both requests.
1280 MockWrite data1_writes[] = {
1281 MockWrite("GET / HTTP/1.1\r\n"
1282 "Host: www.foo.com\r\n"
1283 "Connection: keep-alive\r\n\r\n"),
1284 MockWrite("GET / HTTP/1.1\r\n"
1285 "Host: www.foo.com\r\n"
1286 "Connection: keep-alive\r\n\r\n")
1289 // Read results for the first request.
1290 MockRead data1_reads[] = {
1291 MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
1292 MockRead("hello"),
1293 MockRead(ASYNC, OK),
1296 if (write_failure) {
1297 ASSERT_FALSE(read_failure);
1298 data1_writes[1] = *write_failure;
1299 } else {
1300 ASSERT_TRUE(read_failure);
1301 data1_reads[2] = *read_failure;
1304 StaticSocketDataProvider data1(data1_reads, arraysize(data1_reads),
1305 data1_writes, arraysize(data1_writes));
1306 session_deps_.socket_factory->AddSocketDataProvider(&data1);
1308 MockRead data2_reads[] = {
1309 MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
1310 MockRead("world"),
1311 MockRead(ASYNC, OK),
1313 StaticSocketDataProvider data2(data2_reads, arraysize(data2_reads), NULL, 0);
1314 session_deps_.socket_factory->AddSocketDataProvider(&data2);
1316 const char* const kExpectedResponseData[] = {
1317 "hello", "world"
1320 uint32 first_socket_log_id = NetLog::Source::kInvalidId;
1321 for (int i = 0; i < 2; ++i) {
1322 TestCompletionCallback callback;
1324 scoped_ptr<HttpTransaction> trans(
1325 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1327 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1328 EXPECT_EQ(ERR_IO_PENDING, rv);
1330 rv = callback.WaitForResult();
1331 EXPECT_EQ(OK, rv);
1333 LoadTimingInfo load_timing_info;
1334 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
1335 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
1336 if (i == 0) {
1337 first_socket_log_id = load_timing_info.socket_log_id;
1338 } else {
1339 // The second request should be using a new socket.
1340 EXPECT_NE(first_socket_log_id, load_timing_info.socket_log_id);
1343 const HttpResponseInfo* response = trans->GetResponseInfo();
1344 ASSERT_TRUE(response != NULL);
1346 EXPECT_TRUE(response->headers.get() != NULL);
1347 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
1349 std::string response_data;
1350 rv = ReadTransaction(trans.get(), &response_data);
1351 EXPECT_EQ(OK, rv);
1352 EXPECT_EQ(kExpectedResponseData[i], response_data);
1356 void HttpNetworkTransactionTest::PreconnectErrorResendRequestTest(
1357 const MockWrite* write_failure,
1358 const MockRead* read_failure,
1359 bool use_spdy) {
1360 HttpRequestInfo request;
1361 request.method = "GET";
1362 request.url = GURL("https://www.foo.com/");
1363 request.load_flags = 0;
1365 CapturingNetLog net_log;
1366 session_deps_.net_log = &net_log;
1367 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1369 SSLSocketDataProvider ssl1(ASYNC, OK);
1370 SSLSocketDataProvider ssl2(ASYNC, OK);
1371 if (use_spdy) {
1372 ssl1.SetNextProto(GetParam());
1373 ssl2.SetNextProto(GetParam());
1375 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
1376 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
1378 // SPDY versions of the request and response.
1379 scoped_ptr<SpdyFrame> spdy_request(spdy_util_.ConstructSpdyGet(
1380 request.url.spec().c_str(), false, 1, DEFAULT_PRIORITY));
1381 scoped_ptr<SpdyFrame> spdy_response(
1382 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
1383 scoped_ptr<SpdyFrame> spdy_data(
1384 spdy_util_.ConstructSpdyBodyFrame(1, "hello", 5, true));
1386 // HTTP/1.1 versions of the request and response.
1387 const char kHttpRequest[] = "GET / HTTP/1.1\r\n"
1388 "Host: www.foo.com\r\n"
1389 "Connection: keep-alive\r\n\r\n";
1390 const char kHttpResponse[] = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n";
1391 const char kHttpData[] = "hello";
1393 std::vector<MockRead> data1_reads;
1394 std::vector<MockWrite> data1_writes;
1395 if (write_failure) {
1396 ASSERT_FALSE(read_failure);
1397 data1_writes.push_back(*write_failure);
1398 data1_reads.push_back(MockRead(ASYNC, OK));
1399 } else {
1400 ASSERT_TRUE(read_failure);
1401 if (use_spdy) {
1402 data1_writes.push_back(CreateMockWrite(*spdy_request));
1403 } else {
1404 data1_writes.push_back(MockWrite(kHttpRequest));
1406 data1_reads.push_back(*read_failure);
1409 StaticSocketDataProvider data1(&data1_reads[0], data1_reads.size(),
1410 &data1_writes[0], data1_writes.size());
1411 session_deps_.socket_factory->AddSocketDataProvider(&data1);
1413 std::vector<MockRead> data2_reads;
1414 std::vector<MockWrite> data2_writes;
1416 if (use_spdy) {
1417 data2_writes.push_back(CreateMockWrite(*spdy_request, 0, ASYNC));
1419 data2_reads.push_back(CreateMockRead(*spdy_response, 1, ASYNC));
1420 data2_reads.push_back(CreateMockRead(*spdy_data, 2, ASYNC));
1421 data2_reads.push_back(MockRead(ASYNC, OK, 3));
1422 } else {
1423 data2_writes.push_back(
1424 MockWrite(ASYNC, kHttpRequest, strlen(kHttpRequest), 0));
1426 data2_reads.push_back(
1427 MockRead(ASYNC, kHttpResponse, strlen(kHttpResponse), 1));
1428 data2_reads.push_back(MockRead(ASYNC, kHttpData, strlen(kHttpData), 2));
1429 data2_reads.push_back(MockRead(ASYNC, OK, 3));
1431 OrderedSocketData data2(&data2_reads[0], data2_reads.size(),
1432 &data2_writes[0], data2_writes.size());
1433 session_deps_.socket_factory->AddSocketDataProvider(&data2);
1435 // Preconnect a socket.
1436 net::SSLConfig ssl_config;
1437 session->ssl_config_service()->GetSSLConfig(&ssl_config);
1438 session->GetNextProtos(&ssl_config.next_protos);
1439 session->http_stream_factory()->PreconnectStreams(
1440 1, request, DEFAULT_PRIORITY, ssl_config, ssl_config);
1441 // Wait for the preconnect to complete.
1442 // TODO(davidben): Some way to wait for an idle socket count might be handy.
1443 base::RunLoop().RunUntilIdle();
1444 EXPECT_EQ(1, GetIdleSocketCountInSSLSocketPool(session.get()));
1446 // Make the request.
1447 TestCompletionCallback callback;
1449 scoped_ptr<HttpTransaction> trans(
1450 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1452 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1453 EXPECT_EQ(ERR_IO_PENDING, rv);
1455 rv = callback.WaitForResult();
1456 EXPECT_EQ(OK, rv);
1458 LoadTimingInfo load_timing_info;
1459 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
1460 TestLoadTimingNotReused(
1461 load_timing_info,
1462 CONNECT_TIMING_HAS_DNS_TIMES|CONNECT_TIMING_HAS_SSL_TIMES);
1464 const HttpResponseInfo* response = trans->GetResponseInfo();
1465 ASSERT_TRUE(response != NULL);
1467 EXPECT_TRUE(response->headers.get() != NULL);
1468 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
1470 std::string response_data;
1471 rv = ReadTransaction(trans.get(), &response_data);
1472 EXPECT_EQ(OK, rv);
1473 EXPECT_EQ(kHttpData, response_data);
1476 TEST_P(HttpNetworkTransactionTest,
1477 KeepAliveConnectionNotConnectedOnWrite) {
1478 MockWrite write_failure(ASYNC, ERR_SOCKET_NOT_CONNECTED);
1479 KeepAliveConnectionResendRequestTest(&write_failure, NULL);
1482 TEST_P(HttpNetworkTransactionTest, KeepAliveConnectionReset) {
1483 MockRead read_failure(ASYNC, ERR_CONNECTION_RESET);
1484 KeepAliveConnectionResendRequestTest(NULL, &read_failure);
1487 TEST_P(HttpNetworkTransactionTest, KeepAliveConnectionEOF) {
1488 MockRead read_failure(SYNCHRONOUS, OK); // EOF
1489 KeepAliveConnectionResendRequestTest(NULL, &read_failure);
1492 // Make sure that on a 408 response (Request Timeout), the request is retried,
1493 // if the socket was a reused keep alive socket.
1494 TEST_P(HttpNetworkTransactionTest, KeepAlive408) {
1495 MockRead read_failure(SYNCHRONOUS,
1496 "HTTP/1.1 408 Request Timeout\r\n"
1497 "Connection: Keep-Alive\r\n"
1498 "Content-Length: 6\r\n\r\n"
1499 "Pickle");
1500 KeepAliveConnectionResendRequestTest(NULL, &read_failure);
1503 TEST_P(HttpNetworkTransactionTest,
1504 PreconnectErrorNotConnectedOnWrite) {
1505 MockWrite write_failure(ASYNC, ERR_SOCKET_NOT_CONNECTED);
1506 PreconnectErrorResendRequestTest(&write_failure, NULL, false);
1509 TEST_P(HttpNetworkTransactionTest, PreconnectErrorReset) {
1510 MockRead read_failure(ASYNC, ERR_CONNECTION_RESET);
1511 PreconnectErrorResendRequestTest(NULL, &read_failure, false);
1514 TEST_P(HttpNetworkTransactionTest, PreconnectErrorEOF) {
1515 MockRead read_failure(SYNCHRONOUS, OK); // EOF
1516 PreconnectErrorResendRequestTest(NULL, &read_failure, false);
1519 TEST_P(HttpNetworkTransactionTest, PreconnectErrorAsyncEOF) {
1520 MockRead read_failure(ASYNC, OK); // EOF
1521 PreconnectErrorResendRequestTest(NULL, &read_failure, false);
1524 // Make sure that on a 408 response (Request Timeout), the request is retried,
1525 // if the socket was a preconnected (UNUSED_IDLE) socket.
1526 TEST_P(HttpNetworkTransactionTest, RetryOnIdle408) {
1527 MockRead read_failure(SYNCHRONOUS,
1528 "HTTP/1.1 408 Request Timeout\r\n"
1529 "Connection: Keep-Alive\r\n"
1530 "Content-Length: 6\r\n\r\n"
1531 "Pickle");
1532 KeepAliveConnectionResendRequestTest(NULL, &read_failure);
1533 PreconnectErrorResendRequestTest(NULL, &read_failure, false);
1536 TEST_P(HttpNetworkTransactionTest,
1537 SpdyPreconnectErrorNotConnectedOnWrite) {
1538 MockWrite write_failure(ASYNC, ERR_SOCKET_NOT_CONNECTED);
1539 PreconnectErrorResendRequestTest(&write_failure, NULL, true);
1542 TEST_P(HttpNetworkTransactionTest, SpdyPreconnectErrorReset) {
1543 MockRead read_failure(ASYNC, ERR_CONNECTION_RESET);
1544 PreconnectErrorResendRequestTest(NULL, &read_failure, true);
1547 TEST_P(HttpNetworkTransactionTest, SpdyPreconnectErrorEOF) {
1548 MockRead read_failure(SYNCHRONOUS, OK); // EOF
1549 PreconnectErrorResendRequestTest(NULL, &read_failure, true);
1552 TEST_P(HttpNetworkTransactionTest, SpdyPreconnectErrorAsyncEOF) {
1553 MockRead read_failure(ASYNC, OK); // EOF
1554 PreconnectErrorResendRequestTest(NULL, &read_failure, true);
1557 TEST_P(HttpNetworkTransactionTest, NonKeepAliveConnectionReset) {
1558 HttpRequestInfo request;
1559 request.method = "GET";
1560 request.url = GURL("http://www.google.com/");
1561 request.load_flags = 0;
1563 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1564 scoped_ptr<HttpTransaction> trans(
1565 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1567 MockRead data_reads[] = {
1568 MockRead(ASYNC, ERR_CONNECTION_RESET),
1569 MockRead("HTTP/1.0 200 OK\r\n\r\n"), // Should not be used
1570 MockRead("hello world"),
1571 MockRead(SYNCHRONOUS, OK),
1573 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1574 session_deps_.socket_factory->AddSocketDataProvider(&data);
1576 TestCompletionCallback callback;
1578 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1579 EXPECT_EQ(ERR_IO_PENDING, rv);
1581 rv = callback.WaitForResult();
1582 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1584 const HttpResponseInfo* response = trans->GetResponseInfo();
1585 EXPECT_TRUE(response == NULL);
1588 // What do various browsers do when the server closes a non-keepalive
1589 // connection without sending any response header or body?
1591 // IE7: error page
1592 // Safari 3.1.2 (Windows): error page
1593 // Firefox 3.0.1: blank page
1594 // Opera 9.52: after five attempts, blank page
1595 // Us with WinHTTP: error page (ERR_INVALID_RESPONSE)
1596 // Us: error page (EMPTY_RESPONSE)
1597 TEST_P(HttpNetworkTransactionTest, NonKeepAliveConnectionEOF) {
1598 MockRead data_reads[] = {
1599 MockRead(SYNCHRONOUS, OK), // EOF
1600 MockRead("HTTP/1.0 200 OK\r\n\r\n"), // Should not be used
1601 MockRead("hello world"),
1602 MockRead(SYNCHRONOUS, OK),
1604 SimpleGetHelperResult out = SimpleGetHelper(data_reads,
1605 arraysize(data_reads));
1606 EXPECT_EQ(ERR_EMPTY_RESPONSE, out.rv);
1609 // Test that network access can be deferred and resumed.
1610 TEST_P(HttpNetworkTransactionTest, ThrottleBeforeNetworkStart) {
1611 HttpRequestInfo request;
1612 request.method = "GET";
1613 request.url = GURL("http://www.google.com/");
1614 request.load_flags = 0;
1616 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1617 scoped_ptr<HttpTransaction> trans(
1618 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1620 // Defer on OnBeforeNetworkStart.
1621 BeforeNetworkStartHandler net_start_handler(true); // defer
1622 trans->SetBeforeNetworkStartCallback(
1623 base::Bind(&BeforeNetworkStartHandler::OnBeforeNetworkStart,
1624 base::Unretained(&net_start_handler)));
1626 MockRead data_reads[] = {
1627 MockRead("HTTP/1.0 200 OK\r\n"),
1628 MockRead("Content-Length: 5\r\n\r\n"),
1629 MockRead("hello"),
1630 MockRead(SYNCHRONOUS, 0),
1632 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1633 session_deps_.socket_factory->AddSocketDataProvider(&data);
1635 TestCompletionCallback callback;
1637 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1638 EXPECT_EQ(ERR_IO_PENDING, rv);
1639 base::MessageLoop::current()->RunUntilIdle();
1641 // Should have deferred for network start.
1642 EXPECT_TRUE(net_start_handler.observed_before_network_start());
1643 EXPECT_EQ(LOAD_STATE_WAITING_FOR_DELEGATE, trans->GetLoadState());
1644 EXPECT_TRUE(trans->GetResponseInfo() == NULL);
1646 trans->ResumeNetworkStart();
1647 rv = callback.WaitForResult();
1648 EXPECT_EQ(OK, rv);
1649 EXPECT_TRUE(trans->GetResponseInfo() != NULL);
1651 scoped_refptr<IOBufferWithSize> io_buf(new IOBufferWithSize(100));
1652 rv = trans->Read(io_buf.get(), io_buf->size(), callback.callback());
1653 if (rv == ERR_IO_PENDING)
1654 rv = callback.WaitForResult();
1655 EXPECT_EQ(5, rv);
1656 trans.reset();
1659 // Test that network use can be deferred and canceled.
1660 TEST_P(HttpNetworkTransactionTest, ThrottleAndCancelBeforeNetworkStart) {
1661 HttpRequestInfo request;
1662 request.method = "GET";
1663 request.url = GURL("http://www.google.com/");
1664 request.load_flags = 0;
1666 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1667 scoped_ptr<HttpTransaction> trans(
1668 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1670 // Defer on OnBeforeNetworkStart.
1671 BeforeNetworkStartHandler net_start_handler(true); // defer
1672 trans->SetBeforeNetworkStartCallback(
1673 base::Bind(&BeforeNetworkStartHandler::OnBeforeNetworkStart,
1674 base::Unretained(&net_start_handler)));
1676 TestCompletionCallback callback;
1678 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1679 EXPECT_EQ(ERR_IO_PENDING, rv);
1680 base::MessageLoop::current()->RunUntilIdle();
1682 // Should have deferred for network start.
1683 EXPECT_TRUE(net_start_handler.observed_before_network_start());
1684 EXPECT_EQ(LOAD_STATE_WAITING_FOR_DELEGATE, trans->GetLoadState());
1685 EXPECT_TRUE(trans->GetResponseInfo() == NULL);
1688 // Next 2 cases (KeepAliveEarlyClose and KeepAliveEarlyClose2) are regression
1689 // tests. There was a bug causing HttpNetworkTransaction to hang in the
1690 // destructor in such situations.
1691 // See http://crbug.com/154712 and http://crbug.com/156609.
1692 TEST_P(HttpNetworkTransactionTest, KeepAliveEarlyClose) {
1693 HttpRequestInfo request;
1694 request.method = "GET";
1695 request.url = GURL("http://www.google.com/");
1696 request.load_flags = 0;
1698 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1699 scoped_ptr<HttpTransaction> trans(
1700 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1702 MockRead data_reads[] = {
1703 MockRead("HTTP/1.0 200 OK\r\n"),
1704 MockRead("Connection: keep-alive\r\n"),
1705 MockRead("Content-Length: 100\r\n\r\n"),
1706 MockRead("hello"),
1707 MockRead(SYNCHRONOUS, 0),
1709 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1710 session_deps_.socket_factory->AddSocketDataProvider(&data);
1712 TestCompletionCallback callback;
1714 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1715 EXPECT_EQ(ERR_IO_PENDING, rv);
1717 rv = callback.WaitForResult();
1718 EXPECT_EQ(OK, rv);
1720 scoped_refptr<IOBufferWithSize> io_buf(new IOBufferWithSize(100));
1721 rv = trans->Read(io_buf.get(), io_buf->size(), callback.callback());
1722 if (rv == ERR_IO_PENDING)
1723 rv = callback.WaitForResult();
1724 EXPECT_EQ(5, rv);
1725 rv = trans->Read(io_buf.get(), io_buf->size(), callback.callback());
1726 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, rv);
1728 trans.reset();
1729 base::MessageLoop::current()->RunUntilIdle();
1730 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
1733 TEST_P(HttpNetworkTransactionTest, KeepAliveEarlyClose2) {
1734 HttpRequestInfo request;
1735 request.method = "GET";
1736 request.url = GURL("http://www.google.com/");
1737 request.load_flags = 0;
1739 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1740 scoped_ptr<HttpTransaction> trans(
1741 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1743 MockRead data_reads[] = {
1744 MockRead("HTTP/1.0 200 OK\r\n"),
1745 MockRead("Connection: keep-alive\r\n"),
1746 MockRead("Content-Length: 100\r\n\r\n"),
1747 MockRead(SYNCHRONOUS, 0),
1749 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1750 session_deps_.socket_factory->AddSocketDataProvider(&data);
1752 TestCompletionCallback callback;
1754 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1755 EXPECT_EQ(ERR_IO_PENDING, rv);
1757 rv = callback.WaitForResult();
1758 EXPECT_EQ(OK, rv);
1760 scoped_refptr<IOBufferWithSize> io_buf(new IOBufferWithSize(100));
1761 rv = trans->Read(io_buf.get(), io_buf->size(), callback.callback());
1762 if (rv == ERR_IO_PENDING)
1763 rv = callback.WaitForResult();
1764 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, rv);
1766 trans.reset();
1767 base::MessageLoop::current()->RunUntilIdle();
1768 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
1771 // Test that we correctly reuse a keep-alive connection after not explicitly
1772 // reading the body.
1773 TEST_P(HttpNetworkTransactionTest, KeepAliveAfterUnreadBody) {
1774 HttpRequestInfo request;
1775 request.method = "GET";
1776 request.url = GURL("http://www.foo.com/");
1777 request.load_flags = 0;
1779 CapturingNetLog net_log;
1780 session_deps_.net_log = &net_log;
1781 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1783 // Note that because all these reads happen in the same
1784 // StaticSocketDataProvider, it shows that the same socket is being reused for
1785 // all transactions.
1786 MockRead data1_reads[] = {
1787 MockRead("HTTP/1.1 204 No Content\r\n\r\n"),
1788 MockRead("HTTP/1.1 205 Reset Content\r\n\r\n"),
1789 MockRead("HTTP/1.1 304 Not Modified\r\n\r\n"),
1790 MockRead("HTTP/1.1 302 Found\r\n"
1791 "Content-Length: 0\r\n\r\n"),
1792 MockRead("HTTP/1.1 302 Found\r\n"
1793 "Content-Length: 5\r\n\r\n"
1794 "hello"),
1795 MockRead("HTTP/1.1 301 Moved Permanently\r\n"
1796 "Content-Length: 0\r\n\r\n"),
1797 MockRead("HTTP/1.1 301 Moved Permanently\r\n"
1798 "Content-Length: 5\r\n\r\n"
1799 "hello"),
1800 MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
1801 MockRead("hello"),
1803 StaticSocketDataProvider data1(data1_reads, arraysize(data1_reads), NULL, 0);
1804 session_deps_.socket_factory->AddSocketDataProvider(&data1);
1806 MockRead data2_reads[] = {
1807 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
1809 StaticSocketDataProvider data2(data2_reads, arraysize(data2_reads), NULL, 0);
1810 session_deps_.socket_factory->AddSocketDataProvider(&data2);
1812 const int kNumUnreadBodies = arraysize(data1_reads) - 2;
1813 std::string response_lines[kNumUnreadBodies];
1815 uint32 first_socket_log_id = NetLog::Source::kInvalidId;
1816 for (size_t i = 0; i < arraysize(data1_reads) - 2; ++i) {
1817 TestCompletionCallback callback;
1819 scoped_ptr<HttpTransaction> trans(
1820 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1822 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1823 EXPECT_EQ(ERR_IO_PENDING, rv);
1825 rv = callback.WaitForResult();
1826 EXPECT_EQ(OK, rv);
1828 LoadTimingInfo load_timing_info;
1829 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
1830 if (i == 0) {
1831 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
1832 first_socket_log_id = load_timing_info.socket_log_id;
1833 } else {
1834 TestLoadTimingReused(load_timing_info);
1835 EXPECT_EQ(first_socket_log_id, load_timing_info.socket_log_id);
1838 const HttpResponseInfo* response = trans->GetResponseInfo();
1839 ASSERT_TRUE(response != NULL);
1841 ASSERT_TRUE(response->headers.get() != NULL);
1842 response_lines[i] = response->headers->GetStatusLine();
1844 // We intentionally don't read the response bodies.
1847 const char* const kStatusLines[] = {
1848 "HTTP/1.1 204 No Content",
1849 "HTTP/1.1 205 Reset Content",
1850 "HTTP/1.1 304 Not Modified",
1851 "HTTP/1.1 302 Found",
1852 "HTTP/1.1 302 Found",
1853 "HTTP/1.1 301 Moved Permanently",
1854 "HTTP/1.1 301 Moved Permanently",
1857 static_assert(kNumUnreadBodies == arraysize(kStatusLines),
1858 "forgot to update kStatusLines");
1860 for (int i = 0; i < kNumUnreadBodies; ++i)
1861 EXPECT_EQ(kStatusLines[i], response_lines[i]);
1863 TestCompletionCallback callback;
1864 scoped_ptr<HttpTransaction> trans(
1865 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1866 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1867 EXPECT_EQ(ERR_IO_PENDING, rv);
1868 rv = callback.WaitForResult();
1869 EXPECT_EQ(OK, rv);
1870 const HttpResponseInfo* response = trans->GetResponseInfo();
1871 ASSERT_TRUE(response != NULL);
1872 ASSERT_TRUE(response->headers.get() != NULL);
1873 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
1874 std::string response_data;
1875 rv = ReadTransaction(trans.get(), &response_data);
1876 EXPECT_EQ(OK, rv);
1877 EXPECT_EQ("hello", response_data);
1880 // Test the request-challenge-retry sequence for basic auth.
1881 // (basic auth is the easiest to mock, because it has no randomness).
1882 TEST_P(HttpNetworkTransactionTest, BasicAuth) {
1883 HttpRequestInfo request;
1884 request.method = "GET";
1885 request.url = GURL("http://www.google.com/");
1886 request.load_flags = 0;
1888 CapturingNetLog log;
1889 session_deps_.net_log = &log;
1890 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1891 scoped_ptr<HttpTransaction> trans(
1892 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1894 MockWrite data_writes1[] = {
1895 MockWrite("GET / HTTP/1.1\r\n"
1896 "Host: www.google.com\r\n"
1897 "Connection: keep-alive\r\n\r\n"),
1900 MockRead data_reads1[] = {
1901 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
1902 // Give a couple authenticate options (only the middle one is actually
1903 // supported).
1904 MockRead("WWW-Authenticate: Basic invalid\r\n"), // Malformed.
1905 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
1906 MockRead("WWW-Authenticate: UNSUPPORTED realm=\"FOO\"\r\n"),
1907 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
1908 // Large content-length -- won't matter, as connection will be reset.
1909 MockRead("Content-Length: 10000\r\n\r\n"),
1910 MockRead(SYNCHRONOUS, ERR_FAILED),
1913 // After calling trans->RestartWithAuth(), this is the request we should
1914 // be issuing -- the final header line contains the credentials.
1915 MockWrite data_writes2[] = {
1916 MockWrite("GET / HTTP/1.1\r\n"
1917 "Host: www.google.com\r\n"
1918 "Connection: keep-alive\r\n"
1919 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
1922 // Lastly, the server responds with the actual content.
1923 MockRead data_reads2[] = {
1924 MockRead("HTTP/1.0 200 OK\r\n"),
1925 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
1926 MockRead("Content-Length: 100\r\n\r\n"),
1927 MockRead(SYNCHRONOUS, OK),
1930 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
1931 data_writes1, arraysize(data_writes1));
1932 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
1933 data_writes2, arraysize(data_writes2));
1934 session_deps_.socket_factory->AddSocketDataProvider(&data1);
1935 session_deps_.socket_factory->AddSocketDataProvider(&data2);
1937 TestCompletionCallback callback1;
1939 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
1940 EXPECT_EQ(ERR_IO_PENDING, rv);
1942 rv = callback1.WaitForResult();
1943 EXPECT_EQ(OK, rv);
1945 LoadTimingInfo load_timing_info1;
1946 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info1));
1947 TestLoadTimingNotReused(load_timing_info1, CONNECT_TIMING_HAS_DNS_TIMES);
1949 int64 reads_size1 = ReadsSize(data_reads1, arraysize(data_reads1));
1950 EXPECT_EQ(reads_size1, trans->GetTotalReceivedBytes());
1952 const HttpResponseInfo* response = trans->GetResponseInfo();
1953 ASSERT_TRUE(response != NULL);
1954 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
1956 TestCompletionCallback callback2;
1958 rv = trans->RestartWithAuth(
1959 AuthCredentials(kFoo, kBar), callback2.callback());
1960 EXPECT_EQ(ERR_IO_PENDING, rv);
1962 rv = callback2.WaitForResult();
1963 EXPECT_EQ(OK, rv);
1965 LoadTimingInfo load_timing_info2;
1966 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info2));
1967 TestLoadTimingNotReused(load_timing_info2, CONNECT_TIMING_HAS_DNS_TIMES);
1968 // The load timing after restart should have a new socket ID, and times after
1969 // those of the first load timing.
1970 EXPECT_LE(load_timing_info1.receive_headers_end,
1971 load_timing_info2.connect_timing.connect_start);
1972 EXPECT_NE(load_timing_info1.socket_log_id, load_timing_info2.socket_log_id);
1974 int64 reads_size2 = ReadsSize(data_reads2, arraysize(data_reads2));
1975 EXPECT_EQ(reads_size1 + reads_size2, trans->GetTotalReceivedBytes());
1977 response = trans->GetResponseInfo();
1978 ASSERT_TRUE(response != NULL);
1979 EXPECT_TRUE(response->auth_challenge.get() == NULL);
1980 EXPECT_EQ(100, response->headers->GetContentLength());
1983 TEST_P(HttpNetworkTransactionTest, DoNotSendAuth) {
1984 HttpRequestInfo request;
1985 request.method = "GET";
1986 request.url = GURL("http://www.google.com/");
1987 request.load_flags = net::LOAD_DO_NOT_SEND_AUTH_DATA;
1989 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
1990 scoped_ptr<HttpTransaction> trans(
1991 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
1993 MockWrite data_writes[] = {
1994 MockWrite("GET / HTTP/1.1\r\n"
1995 "Host: www.google.com\r\n"
1996 "Connection: keep-alive\r\n\r\n"),
1999 MockRead data_reads[] = {
2000 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
2001 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2002 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2003 // Large content-length -- won't matter, as connection will be reset.
2004 MockRead("Content-Length: 10000\r\n\r\n"),
2005 MockRead(SYNCHRONOUS, ERR_FAILED),
2008 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
2009 data_writes, arraysize(data_writes));
2010 session_deps_.socket_factory->AddSocketDataProvider(&data);
2011 TestCompletionCallback callback;
2013 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
2014 EXPECT_EQ(ERR_IO_PENDING, rv);
2016 rv = callback.WaitForResult();
2017 EXPECT_EQ(0, rv);
2019 int64 reads_size = ReadsSize(data_reads, arraysize(data_reads));
2020 EXPECT_EQ(reads_size, trans->GetTotalReceivedBytes());
2022 const HttpResponseInfo* response = trans->GetResponseInfo();
2023 ASSERT_TRUE(response != NULL);
2024 EXPECT_TRUE(response->auth_challenge.get() == NULL);
2027 // Test the request-challenge-retry sequence for basic auth, over a keep-alive
2028 // connection.
2029 TEST_P(HttpNetworkTransactionTest, BasicAuthKeepAlive) {
2030 HttpRequestInfo request;
2031 request.method = "GET";
2032 request.url = GURL("http://www.google.com/");
2033 request.load_flags = 0;
2035 CapturingNetLog log;
2036 session_deps_.net_log = &log;
2037 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2039 MockWrite data_writes1[] = {
2040 MockWrite("GET / HTTP/1.1\r\n"
2041 "Host: www.google.com\r\n"
2042 "Connection: keep-alive\r\n\r\n"),
2044 // After calling trans->RestartWithAuth(), this is the request we should
2045 // be issuing -- the final header line contains the credentials.
2046 MockWrite("GET / HTTP/1.1\r\n"
2047 "Host: www.google.com\r\n"
2048 "Connection: keep-alive\r\n"
2049 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
2052 MockRead data_reads1[] = {
2053 MockRead("HTTP/1.1 401 Unauthorized\r\n"),
2054 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2055 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2056 MockRead("Content-Length: 14\r\n\r\n"),
2057 MockRead("Unauthorized\r\n"),
2059 // Lastly, the server responds with the actual content.
2060 MockRead("HTTP/1.1 200 OK\r\n"),
2061 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2062 MockRead("Content-Length: 5\r\n\r\n"),
2063 MockRead("Hello"),
2066 // If there is a regression where we disconnect a Keep-Alive
2067 // connection during an auth roundtrip, we'll end up reading this.
2068 MockRead data_reads2[] = {
2069 MockRead(SYNCHRONOUS, ERR_FAILED),
2072 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2073 data_writes1, arraysize(data_writes1));
2074 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
2075 NULL, 0);
2076 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2077 session_deps_.socket_factory->AddSocketDataProvider(&data2);
2079 TestCompletionCallback callback1;
2081 scoped_ptr<HttpTransaction> trans(
2082 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2083 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
2084 EXPECT_EQ(ERR_IO_PENDING, rv);
2086 rv = callback1.WaitForResult();
2087 EXPECT_EQ(OK, rv);
2089 LoadTimingInfo load_timing_info1;
2090 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info1));
2091 TestLoadTimingNotReused(load_timing_info1, CONNECT_TIMING_HAS_DNS_TIMES);
2093 const HttpResponseInfo* response = trans->GetResponseInfo();
2094 ASSERT_TRUE(response != NULL);
2095 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
2097 TestCompletionCallback callback2;
2099 rv = trans->RestartWithAuth(
2100 AuthCredentials(kFoo, kBar), callback2.callback());
2101 EXPECT_EQ(ERR_IO_PENDING, rv);
2103 rv = callback2.WaitForResult();
2104 EXPECT_EQ(OK, rv);
2106 LoadTimingInfo load_timing_info2;
2107 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info2));
2108 TestLoadTimingReused(load_timing_info2);
2109 // The load timing after restart should have the same socket ID, and times
2110 // those of the first load timing.
2111 EXPECT_LE(load_timing_info1.receive_headers_end,
2112 load_timing_info2.send_start);
2113 EXPECT_EQ(load_timing_info1.socket_log_id, load_timing_info2.socket_log_id);
2115 response = trans->GetResponseInfo();
2116 ASSERT_TRUE(response != NULL);
2117 EXPECT_TRUE(response->auth_challenge.get() == NULL);
2118 EXPECT_EQ(5, response->headers->GetContentLength());
2120 std::string response_data;
2121 rv = ReadTransaction(trans.get(), &response_data);
2122 EXPECT_EQ(OK, rv);
2123 int64 reads_size1 = ReadsSize(data_reads1, arraysize(data_reads1));
2124 EXPECT_EQ(reads_size1, trans->GetTotalReceivedBytes());
2127 // Test the request-challenge-retry sequence for basic auth, over a keep-alive
2128 // connection and with no response body to drain.
2129 TEST_P(HttpNetworkTransactionTest, BasicAuthKeepAliveNoBody) {
2130 HttpRequestInfo request;
2131 request.method = "GET";
2132 request.url = GURL("http://www.google.com/");
2133 request.load_flags = 0;
2135 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2137 MockWrite data_writes1[] = {
2138 MockWrite("GET / HTTP/1.1\r\n"
2139 "Host: www.google.com\r\n"
2140 "Connection: keep-alive\r\n\r\n"),
2142 // After calling trans->RestartWithAuth(), this is the request we should
2143 // be issuing -- the final header line contains the credentials.
2144 MockWrite("GET / HTTP/1.1\r\n"
2145 "Host: www.google.com\r\n"
2146 "Connection: keep-alive\r\n"
2147 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
2150 MockRead data_reads1[] = {
2151 MockRead("HTTP/1.1 401 Unauthorized\r\n"),
2152 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2153 MockRead("Content-Length: 0\r\n\r\n"), // No response body.
2155 // Lastly, the server responds with the actual content.
2156 MockRead("HTTP/1.1 200 OK\r\n"),
2157 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2158 MockRead("Content-Length: 5\r\n\r\n"),
2159 MockRead("hello"),
2162 // An incorrect reconnect would cause this to be read.
2163 MockRead data_reads2[] = {
2164 MockRead(SYNCHRONOUS, ERR_FAILED),
2167 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2168 data_writes1, arraysize(data_writes1));
2169 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
2170 NULL, 0);
2171 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2172 session_deps_.socket_factory->AddSocketDataProvider(&data2);
2174 TestCompletionCallback callback1;
2176 scoped_ptr<HttpTransaction> trans(
2177 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2178 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
2179 EXPECT_EQ(ERR_IO_PENDING, rv);
2181 rv = callback1.WaitForResult();
2182 EXPECT_EQ(OK, rv);
2184 const HttpResponseInfo* response = trans->GetResponseInfo();
2185 ASSERT_TRUE(response != NULL);
2186 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
2188 TestCompletionCallback callback2;
2190 rv = trans->RestartWithAuth(
2191 AuthCredentials(kFoo, kBar), callback2.callback());
2192 EXPECT_EQ(ERR_IO_PENDING, rv);
2194 rv = callback2.WaitForResult();
2195 EXPECT_EQ(OK, rv);
2197 response = trans->GetResponseInfo();
2198 ASSERT_TRUE(response != NULL);
2199 EXPECT_TRUE(response->auth_challenge.get() == NULL);
2200 EXPECT_EQ(5, response->headers->GetContentLength());
2203 // Test the request-challenge-retry sequence for basic auth, over a keep-alive
2204 // connection and with a large response body to drain.
2205 TEST_P(HttpNetworkTransactionTest, BasicAuthKeepAliveLargeBody) {
2206 HttpRequestInfo request;
2207 request.method = "GET";
2208 request.url = GURL("http://www.google.com/");
2209 request.load_flags = 0;
2211 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2213 MockWrite data_writes1[] = {
2214 MockWrite("GET / HTTP/1.1\r\n"
2215 "Host: www.google.com\r\n"
2216 "Connection: keep-alive\r\n\r\n"),
2218 // After calling trans->RestartWithAuth(), this is the request we should
2219 // be issuing -- the final header line contains the credentials.
2220 MockWrite("GET / HTTP/1.1\r\n"
2221 "Host: www.google.com\r\n"
2222 "Connection: keep-alive\r\n"
2223 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
2226 // Respond with 5 kb of response body.
2227 std::string large_body_string("Unauthorized");
2228 large_body_string.append(5 * 1024, ' ');
2229 large_body_string.append("\r\n");
2231 MockRead data_reads1[] = {
2232 MockRead("HTTP/1.1 401 Unauthorized\r\n"),
2233 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2234 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2235 // 5134 = 12 + 5 * 1024 + 2
2236 MockRead("Content-Length: 5134\r\n\r\n"),
2237 MockRead(ASYNC, large_body_string.data(), large_body_string.size()),
2239 // Lastly, the server responds with the actual content.
2240 MockRead("HTTP/1.1 200 OK\r\n"),
2241 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2242 MockRead("Content-Length: 5\r\n\r\n"),
2243 MockRead("hello"),
2246 // An incorrect reconnect would cause this to be read.
2247 MockRead data_reads2[] = {
2248 MockRead(SYNCHRONOUS, ERR_FAILED),
2251 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2252 data_writes1, arraysize(data_writes1));
2253 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
2254 NULL, 0);
2255 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2256 session_deps_.socket_factory->AddSocketDataProvider(&data2);
2258 TestCompletionCallback callback1;
2260 scoped_ptr<HttpTransaction> trans(
2261 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2262 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
2263 EXPECT_EQ(ERR_IO_PENDING, rv);
2265 rv = callback1.WaitForResult();
2266 EXPECT_EQ(OK, rv);
2268 const HttpResponseInfo* response = trans->GetResponseInfo();
2269 ASSERT_TRUE(response != NULL);
2270 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
2272 TestCompletionCallback callback2;
2274 rv = trans->RestartWithAuth(
2275 AuthCredentials(kFoo, kBar), callback2.callback());
2276 EXPECT_EQ(ERR_IO_PENDING, rv);
2278 rv = callback2.WaitForResult();
2279 EXPECT_EQ(OK, rv);
2281 response = trans->GetResponseInfo();
2282 ASSERT_TRUE(response != NULL);
2283 EXPECT_TRUE(response->auth_challenge.get() == NULL);
2284 EXPECT_EQ(5, response->headers->GetContentLength());
2287 // Test the request-challenge-retry sequence for basic auth, over a keep-alive
2288 // connection, but the server gets impatient and closes the connection.
2289 TEST_P(HttpNetworkTransactionTest, BasicAuthKeepAliveImpatientServer) {
2290 HttpRequestInfo request;
2291 request.method = "GET";
2292 request.url = GURL("http://www.google.com/");
2293 request.load_flags = 0;
2295 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2297 MockWrite data_writes1[] = {
2298 MockWrite("GET / HTTP/1.1\r\n"
2299 "Host: www.google.com\r\n"
2300 "Connection: keep-alive\r\n\r\n"),
2301 // This simulates the seemingly successful write to a closed connection
2302 // if the bug is not fixed.
2303 MockWrite("GET / HTTP/1.1\r\n"
2304 "Host: www.google.com\r\n"
2305 "Connection: keep-alive\r\n"
2306 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
2309 MockRead data_reads1[] = {
2310 MockRead("HTTP/1.1 401 Unauthorized\r\n"),
2311 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2312 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2313 MockRead("Content-Length: 14\r\n\r\n"),
2314 // Tell MockTCPClientSocket to simulate the server closing the connection.
2315 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
2316 MockRead("Unauthorized\r\n"),
2317 MockRead(SYNCHRONOUS, OK), // The server closes the connection.
2320 // After calling trans->RestartWithAuth(), this is the request we should
2321 // be issuing -- the final header line contains the credentials.
2322 MockWrite data_writes2[] = {
2323 MockWrite("GET / HTTP/1.1\r\n"
2324 "Host: www.google.com\r\n"
2325 "Connection: keep-alive\r\n"
2326 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
2329 // Lastly, the server responds with the actual content.
2330 MockRead data_reads2[] = {
2331 MockRead("HTTP/1.1 200 OK\r\n"),
2332 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2333 MockRead("Content-Length: 5\r\n\r\n"),
2334 MockRead("hello"),
2337 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2338 data_writes1, arraysize(data_writes1));
2339 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
2340 data_writes2, arraysize(data_writes2));
2341 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2342 session_deps_.socket_factory->AddSocketDataProvider(&data2);
2344 TestCompletionCallback callback1;
2346 scoped_ptr<HttpTransaction> trans(
2347 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2348 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
2349 EXPECT_EQ(ERR_IO_PENDING, rv);
2351 rv = callback1.WaitForResult();
2352 EXPECT_EQ(OK, rv);
2354 const HttpResponseInfo* response = trans->GetResponseInfo();
2355 ASSERT_TRUE(response != NULL);
2356 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
2358 TestCompletionCallback callback2;
2360 rv = trans->RestartWithAuth(
2361 AuthCredentials(kFoo, kBar), callback2.callback());
2362 EXPECT_EQ(ERR_IO_PENDING, rv);
2364 rv = callback2.WaitForResult();
2365 EXPECT_EQ(OK, rv);
2367 response = trans->GetResponseInfo();
2368 ASSERT_TRUE(response != NULL);
2369 EXPECT_TRUE(response->auth_challenge.get() == NULL);
2370 EXPECT_EQ(5, response->headers->GetContentLength());
2373 // Test the request-challenge-retry sequence for basic auth, over a connection
2374 // that requires a restart when setting up an SSL tunnel.
2375 TEST_P(HttpNetworkTransactionTest, BasicAuthProxyNoKeepAliveHttp10) {
2376 HttpRequestInfo request;
2377 request.method = "GET";
2378 request.url = GURL("https://www.google.com/");
2379 // when the no authentication data flag is set.
2380 request.load_flags = net::LOAD_DO_NOT_SEND_AUTH_DATA;
2382 // Configure against proxy server "myproxy:70".
2383 session_deps_.proxy_service.reset(
2384 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
2385 CapturingBoundNetLog log;
2386 session_deps_.net_log = log.bound().net_log();
2387 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2389 // Since we have proxy, should try to establish tunnel.
2390 MockWrite data_writes1[] = {
2391 MockWrite(
2392 "CONNECT www.google.com:443 HTTP/1.1\r\n"
2393 "Host: www.google.com\r\n"
2394 "Proxy-Connection: keep-alive\r\n\r\n"),
2396 // After calling trans->RestartWithAuth(), this is the request we should
2397 // be issuing -- the final header line contains the credentials.
2398 MockWrite(
2399 "CONNECT www.google.com:443 HTTP/1.1\r\n"
2400 "Host: www.google.com\r\n"
2401 "Proxy-Connection: keep-alive\r\n"
2402 "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
2404 MockWrite(
2405 "GET / HTTP/1.1\r\n"
2406 "Host: www.google.com\r\n"
2407 "Connection: keep-alive\r\n\r\n"),
2410 // The proxy responds to the connect with a 407, using a persistent
2411 // connection.
2412 MockRead data_reads1[] = {
2413 // No credentials.
2414 MockRead("HTTP/1.0 407 Proxy Authentication Required\r\n"),
2415 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n\r\n"),
2417 MockRead("HTTP/1.0 200 Connection Established\r\n\r\n"),
2419 MockRead("HTTP/1.1 200 OK\r\n"),
2420 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2421 MockRead("Content-Length: 5\r\n\r\n"),
2422 MockRead(SYNCHRONOUS, "hello"),
2425 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2426 data_writes1, arraysize(data_writes1));
2427 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2428 SSLSocketDataProvider ssl(ASYNC, OK);
2429 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
2431 TestCompletionCallback callback1;
2433 scoped_ptr<HttpTransaction> trans(
2434 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2436 int rv = trans->Start(&request, callback1.callback(), log.bound());
2437 EXPECT_EQ(ERR_IO_PENDING, rv);
2439 rv = callback1.WaitForResult();
2440 EXPECT_EQ(OK, rv);
2441 net::CapturingNetLog::CapturedEntryList entries;
2442 log.GetEntries(&entries);
2443 size_t pos = ExpectLogContainsSomewhere(
2444 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
2445 NetLog::PHASE_NONE);
2446 ExpectLogContainsSomewhere(
2447 entries, pos, NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
2448 NetLog::PHASE_NONE);
2450 const HttpResponseInfo* response = trans->GetResponseInfo();
2451 ASSERT_TRUE(response != NULL);
2452 EXPECT_FALSE(response->headers->IsKeepAlive());
2453 ASSERT_FALSE(response->headers.get() == NULL);
2454 EXPECT_EQ(407, response->headers->response_code());
2455 EXPECT_TRUE(HttpVersion(1, 0) == response->headers->GetHttpVersion());
2456 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
2458 LoadTimingInfo load_timing_info;
2459 // CONNECT requests and responses are handled at the connect job level, so
2460 // the transaction does not yet have a connection.
2461 EXPECT_FALSE(trans->GetLoadTimingInfo(&load_timing_info));
2463 TestCompletionCallback callback2;
2465 rv =
2466 trans->RestartWithAuth(AuthCredentials(kFoo, kBar), callback2.callback());
2467 EXPECT_EQ(ERR_IO_PENDING, rv);
2469 rv = callback2.WaitForResult();
2470 EXPECT_EQ(OK, rv);
2472 response = trans->GetResponseInfo();
2473 ASSERT_TRUE(response != NULL);
2475 EXPECT_TRUE(response->headers->IsKeepAlive());
2476 EXPECT_EQ(200, response->headers->response_code());
2477 EXPECT_EQ(5, response->headers->GetContentLength());
2478 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
2480 // The password prompt info should not be set.
2481 EXPECT_TRUE(response->auth_challenge.get() == NULL);
2483 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
2484 TestLoadTimingNotReusedWithPac(load_timing_info,
2485 CONNECT_TIMING_HAS_SSL_TIMES);
2487 trans.reset();
2488 session->CloseAllConnections();
2491 // Test the request-challenge-retry sequence for basic auth, over a connection
2492 // that requires a restart when setting up an SSL tunnel.
2493 TEST_P(HttpNetworkTransactionTest, BasicAuthProxyNoKeepAliveHttp11) {
2494 HttpRequestInfo request;
2495 request.method = "GET";
2496 request.url = GURL("https://www.google.com/");
2497 // when the no authentication data flag is set.
2498 request.load_flags = net::LOAD_DO_NOT_SEND_AUTH_DATA;
2500 // Configure against proxy server "myproxy:70".
2501 session_deps_.proxy_service.reset(
2502 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
2503 CapturingBoundNetLog log;
2504 session_deps_.net_log = log.bound().net_log();
2505 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2507 // Since we have proxy, should try to establish tunnel.
2508 MockWrite data_writes1[] = {
2509 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
2510 "Host: www.google.com\r\n"
2511 "Proxy-Connection: keep-alive\r\n\r\n"),
2513 // After calling trans->RestartWithAuth(), this is the request we should
2514 // be issuing -- the final header line contains the credentials.
2515 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
2516 "Host: www.google.com\r\n"
2517 "Proxy-Connection: keep-alive\r\n"
2518 "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
2520 MockWrite("GET / HTTP/1.1\r\n"
2521 "Host: www.google.com\r\n"
2522 "Connection: keep-alive\r\n\r\n"),
2525 // The proxy responds to the connect with a 407, using a persistent
2526 // connection.
2527 MockRead data_reads1[] = {
2528 // No credentials.
2529 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
2530 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2531 MockRead("Proxy-Connection: close\r\n\r\n"),
2533 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
2535 MockRead("HTTP/1.1 200 OK\r\n"),
2536 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
2537 MockRead("Content-Length: 5\r\n\r\n"),
2538 MockRead(SYNCHRONOUS, "hello"),
2541 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2542 data_writes1, arraysize(data_writes1));
2543 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2544 SSLSocketDataProvider ssl(ASYNC, OK);
2545 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
2547 TestCompletionCallback callback1;
2549 scoped_ptr<HttpTransaction> trans(
2550 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2552 int rv = trans->Start(&request, callback1.callback(), log.bound());
2553 EXPECT_EQ(ERR_IO_PENDING, rv);
2555 rv = callback1.WaitForResult();
2556 EXPECT_EQ(OK, rv);
2557 net::CapturingNetLog::CapturedEntryList entries;
2558 log.GetEntries(&entries);
2559 size_t pos = ExpectLogContainsSomewhere(
2560 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
2561 NetLog::PHASE_NONE);
2562 ExpectLogContainsSomewhere(
2563 entries, pos,
2564 NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
2565 NetLog::PHASE_NONE);
2567 const HttpResponseInfo* response = trans->GetResponseInfo();
2568 ASSERT_TRUE(response != NULL);
2569 EXPECT_FALSE(response->headers->IsKeepAlive());
2570 ASSERT_FALSE(response->headers.get() == NULL);
2571 EXPECT_EQ(407, response->headers->response_code());
2572 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
2573 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
2575 LoadTimingInfo load_timing_info;
2576 // CONNECT requests and responses are handled at the connect job level, so
2577 // the transaction does not yet have a connection.
2578 EXPECT_FALSE(trans->GetLoadTimingInfo(&load_timing_info));
2580 TestCompletionCallback callback2;
2582 rv = trans->RestartWithAuth(
2583 AuthCredentials(kFoo, kBar), callback2.callback());
2584 EXPECT_EQ(ERR_IO_PENDING, rv);
2586 rv = callback2.WaitForResult();
2587 EXPECT_EQ(OK, rv);
2589 response = trans->GetResponseInfo();
2590 ASSERT_TRUE(response != NULL);
2592 EXPECT_TRUE(response->headers->IsKeepAlive());
2593 EXPECT_EQ(200, response->headers->response_code());
2594 EXPECT_EQ(5, response->headers->GetContentLength());
2595 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
2597 // The password prompt info should not be set.
2598 EXPECT_TRUE(response->auth_challenge.get() == NULL);
2600 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
2601 TestLoadTimingNotReusedWithPac(load_timing_info,
2602 CONNECT_TIMING_HAS_SSL_TIMES);
2604 trans.reset();
2605 session->CloseAllConnections();
2608 // Test the request-challenge-retry sequence for basic auth, over a keep-alive
2609 // proxy connection with HTTP/1.0 responses, when setting up an SSL tunnel.
2610 TEST_P(HttpNetworkTransactionTest, BasicAuthProxyKeepAliveHttp10) {
2611 HttpRequestInfo request;
2612 request.method = "GET";
2613 request.url = GURL("https://www.google.com/");
2614 // Ensure that proxy authentication is attempted even
2615 // when the no authentication data flag is set.
2616 request.load_flags = net::LOAD_DO_NOT_SEND_AUTH_DATA;
2618 // Configure against proxy server "myproxy:70".
2619 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
2620 CapturingBoundNetLog log;
2621 session_deps_.net_log = log.bound().net_log();
2622 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2624 scoped_ptr<HttpTransaction> trans(
2625 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2627 // Since we have proxy, should try to establish tunnel.
2628 MockWrite data_writes1[] = {
2629 MockWrite(
2630 "CONNECT www.google.com:443 HTTP/1.1\r\n"
2631 "Host: www.google.com\r\n"
2632 "Proxy-Connection: keep-alive\r\n\r\n"),
2634 // After calling trans->RestartWithAuth(), this is the request we should
2635 // be issuing -- the final header line contains the credentials.
2636 MockWrite(
2637 "CONNECT www.google.com:443 HTTP/1.1\r\n"
2638 "Host: www.google.com\r\n"
2639 "Proxy-Connection: keep-alive\r\n"
2640 "Proxy-Authorization: Basic Zm9vOmJheg==\r\n\r\n"),
2643 // The proxy responds to the connect with a 407, using a persistent
2644 // connection. (Since it's HTTP/1.0, keep-alive has to be explicit.)
2645 MockRead data_reads1[] = {
2646 // No credentials.
2647 MockRead("HTTP/1.0 407 Proxy Authentication Required\r\n"),
2648 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2649 MockRead("Proxy-Connection: keep-alive\r\n"),
2650 MockRead("Content-Length: 10\r\n\r\n"),
2651 MockRead("0123456789"),
2653 // Wrong credentials (wrong password).
2654 MockRead("HTTP/1.0 407 Proxy Authentication Required\r\n"),
2655 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2656 MockRead("Proxy-Connection: keep-alive\r\n"),
2657 MockRead("Content-Length: 10\r\n\r\n"),
2658 // No response body because the test stops reading here.
2659 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
2662 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2663 data_writes1, arraysize(data_writes1));
2664 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2666 TestCompletionCallback callback1;
2668 int rv = trans->Start(&request, callback1.callback(), log.bound());
2669 EXPECT_EQ(ERR_IO_PENDING, rv);
2671 rv = callback1.WaitForResult();
2672 EXPECT_EQ(OK, rv);
2673 net::CapturingNetLog::CapturedEntryList entries;
2674 log.GetEntries(&entries);
2675 size_t pos = ExpectLogContainsSomewhere(
2676 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
2677 NetLog::PHASE_NONE);
2678 ExpectLogContainsSomewhere(
2679 entries, pos, NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
2680 NetLog::PHASE_NONE);
2682 const HttpResponseInfo* response = trans->GetResponseInfo();
2683 ASSERT_TRUE(response);
2684 ASSERT_TRUE(response->headers);
2685 EXPECT_TRUE(response->headers->IsKeepAlive());
2686 EXPECT_EQ(407, response->headers->response_code());
2687 EXPECT_EQ(10, response->headers->GetContentLength());
2688 EXPECT_TRUE(HttpVersion(1, 0) == response->headers->GetHttpVersion());
2689 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
2691 TestCompletionCallback callback2;
2693 // Wrong password (should be "bar").
2694 rv =
2695 trans->RestartWithAuth(AuthCredentials(kFoo, kBaz), callback2.callback());
2696 EXPECT_EQ(ERR_IO_PENDING, rv);
2698 rv = callback2.WaitForResult();
2699 EXPECT_EQ(OK, rv);
2701 response = trans->GetResponseInfo();
2702 ASSERT_TRUE(response);
2703 ASSERT_TRUE(response->headers);
2704 EXPECT_TRUE(response->headers->IsKeepAlive());
2705 EXPECT_EQ(407, response->headers->response_code());
2706 EXPECT_EQ(10, response->headers->GetContentLength());
2707 EXPECT_TRUE(HttpVersion(1, 0) == response->headers->GetHttpVersion());
2708 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
2710 // Flush the idle socket before the NetLog and HttpNetworkTransaction go
2711 // out of scope.
2712 session->CloseAllConnections();
2715 // Test the request-challenge-retry sequence for basic auth, over a keep-alive
2716 // proxy connection with HTTP/1.1 responses, when setting up an SSL tunnel.
2717 TEST_P(HttpNetworkTransactionTest, BasicAuthProxyKeepAliveHttp11) {
2718 HttpRequestInfo request;
2719 request.method = "GET";
2720 request.url = GURL("https://www.google.com/");
2721 // Ensure that proxy authentication is attempted even
2722 // when the no authentication data flag is set.
2723 request.load_flags = net::LOAD_DO_NOT_SEND_AUTH_DATA;
2725 // Configure against proxy server "myproxy:70".
2726 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
2727 CapturingBoundNetLog log;
2728 session_deps_.net_log = log.bound().net_log();
2729 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2731 scoped_ptr<HttpTransaction> trans(
2732 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2734 // Since we have proxy, should try to establish tunnel.
2735 MockWrite data_writes1[] = {
2736 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
2737 "Host: www.google.com\r\n"
2738 "Proxy-Connection: keep-alive\r\n\r\n"),
2740 // After calling trans->RestartWithAuth(), this is the request we should
2741 // be issuing -- the final header line contains the credentials.
2742 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
2743 "Host: www.google.com\r\n"
2744 "Proxy-Connection: keep-alive\r\n"
2745 "Proxy-Authorization: Basic Zm9vOmJheg==\r\n\r\n"),
2748 // The proxy responds to the connect with a 407, using a persistent
2749 // connection.
2750 MockRead data_reads1[] = {
2751 // No credentials.
2752 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
2753 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2754 MockRead("Content-Length: 10\r\n\r\n"),
2755 MockRead("0123456789"),
2757 // Wrong credentials (wrong password).
2758 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
2759 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2760 MockRead("Content-Length: 10\r\n\r\n"),
2761 // No response body because the test stops reading here.
2762 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
2765 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2766 data_writes1, arraysize(data_writes1));
2767 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2769 TestCompletionCallback callback1;
2771 int rv = trans->Start(&request, callback1.callback(), log.bound());
2772 EXPECT_EQ(ERR_IO_PENDING, rv);
2774 rv = callback1.WaitForResult();
2775 EXPECT_EQ(OK, rv);
2776 net::CapturingNetLog::CapturedEntryList entries;
2777 log.GetEntries(&entries);
2778 size_t pos = ExpectLogContainsSomewhere(
2779 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
2780 NetLog::PHASE_NONE);
2781 ExpectLogContainsSomewhere(
2782 entries, pos,
2783 NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
2784 NetLog::PHASE_NONE);
2786 const HttpResponseInfo* response = trans->GetResponseInfo();
2787 ASSERT_TRUE(response);
2788 ASSERT_TRUE(response->headers);
2789 EXPECT_TRUE(response->headers->IsKeepAlive());
2790 EXPECT_EQ(407, response->headers->response_code());
2791 EXPECT_EQ(10, response->headers->GetContentLength());
2792 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
2793 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
2795 TestCompletionCallback callback2;
2797 // Wrong password (should be "bar").
2798 rv = trans->RestartWithAuth(
2799 AuthCredentials(kFoo, kBaz), callback2.callback());
2800 EXPECT_EQ(ERR_IO_PENDING, rv);
2802 rv = callback2.WaitForResult();
2803 EXPECT_EQ(OK, rv);
2805 response = trans->GetResponseInfo();
2806 ASSERT_TRUE(response);
2807 ASSERT_TRUE(response->headers);
2808 EXPECT_TRUE(response->headers->IsKeepAlive());
2809 EXPECT_EQ(407, response->headers->response_code());
2810 EXPECT_EQ(10, response->headers->GetContentLength());
2811 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
2812 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
2814 // Flush the idle socket before the NetLog and HttpNetworkTransaction go
2815 // out of scope.
2816 session->CloseAllConnections();
2819 // Test that we don't read the response body when we fail to establish a tunnel,
2820 // even if the user cancels the proxy's auth attempt.
2821 TEST_P(HttpNetworkTransactionTest, BasicAuthProxyCancelTunnel) {
2822 HttpRequestInfo request;
2823 request.method = "GET";
2824 request.url = GURL("https://www.google.com/");
2825 request.load_flags = 0;
2827 // Configure against proxy server "myproxy:70".
2828 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
2830 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2832 scoped_ptr<HttpTransaction> trans(
2833 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2835 // Since we have proxy, should try to establish tunnel.
2836 MockWrite data_writes[] = {
2837 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
2838 "Host: www.google.com\r\n"
2839 "Proxy-Connection: keep-alive\r\n\r\n"),
2842 // The proxy responds to the connect with a 407.
2843 MockRead data_reads[] = {
2844 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
2845 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2846 MockRead("Content-Length: 10\r\n\r\n"),
2847 MockRead("0123456789"), // Should not be reached.
2848 MockRead(SYNCHRONOUS, ERR_UNEXPECTED),
2851 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
2852 data_writes, arraysize(data_writes));
2853 session_deps_.socket_factory->AddSocketDataProvider(&data);
2855 TestCompletionCallback callback;
2857 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
2858 EXPECT_EQ(ERR_IO_PENDING, rv);
2860 rv = callback.WaitForResult();
2861 EXPECT_EQ(OK, rv);
2863 const HttpResponseInfo* response = trans->GetResponseInfo();
2864 ASSERT_TRUE(response);
2865 ASSERT_TRUE(response->headers);
2866 EXPECT_TRUE(response->headers->IsKeepAlive());
2867 EXPECT_EQ(407, response->headers->response_code());
2868 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
2870 std::string response_data;
2871 rv = ReadTransaction(trans.get(), &response_data);
2872 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, rv);
2874 // Flush the idle socket before the HttpNetworkTransaction goes out of scope.
2875 session->CloseAllConnections();
2878 // Test that we don't pass extraneous headers from the proxy's response to the
2879 // caller when the proxy responds to CONNECT with 407.
2880 TEST_P(HttpNetworkTransactionTest, SanitizeProxyAuthHeaders) {
2881 HttpRequestInfo request;
2882 request.method = "GET";
2883 request.url = GURL("https://www.google.com/");
2884 request.load_flags = 0;
2886 // Configure against proxy server "myproxy:70".
2887 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
2889 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2891 scoped_ptr<HttpTransaction> trans(
2892 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2894 // Since we have proxy, should try to establish tunnel.
2895 MockWrite data_writes[] = {
2896 MockWrite(
2897 "CONNECT www.google.com:443 HTTP/1.1\r\n"
2898 "Host: www.google.com\r\n"
2899 "Proxy-Connection: keep-alive\r\n\r\n"),
2902 // The proxy responds to the connect with a 407.
2903 MockRead data_reads[] = {
2904 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
2905 MockRead("X-Foo: bar\r\n"),
2906 MockRead("Set-Cookie: foo=bar\r\n"),
2907 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2908 MockRead("Content-Length: 10\r\n\r\n"),
2909 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
2912 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
2913 arraysize(data_writes));
2914 session_deps_.socket_factory->AddSocketDataProvider(&data);
2916 TestCompletionCallback callback;
2918 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
2919 EXPECT_EQ(ERR_IO_PENDING, rv);
2921 rv = callback.WaitForResult();
2922 EXPECT_EQ(OK, rv);
2924 const HttpResponseInfo* response = trans->GetResponseInfo();
2925 ASSERT_TRUE(response);
2926 ASSERT_TRUE(response->headers);
2927 EXPECT_TRUE(response->headers->IsKeepAlive());
2928 EXPECT_EQ(407, response->headers->response_code());
2929 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
2930 EXPECT_FALSE(response->headers->HasHeader("X-Foo"));
2931 EXPECT_FALSE(response->headers->HasHeader("Set-Cookie"));
2933 std::string response_data;
2934 rv = ReadTransaction(trans.get(), &response_data);
2935 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, rv);
2937 // Flush the idle socket before the HttpNetworkTransaction goes out of scope.
2938 session->CloseAllConnections();
2941 // Test when a server (non-proxy) returns a 407 (proxy-authenticate).
2942 // The request should fail with ERR_UNEXPECTED_PROXY_AUTH.
2943 TEST_P(HttpNetworkTransactionTest, UnexpectedProxyAuth) {
2944 HttpRequestInfo request;
2945 request.method = "GET";
2946 request.url = GURL("http://www.google.com/");
2947 request.load_flags = 0;
2949 // We are using a DIRECT connection (i.e. no proxy) for this session.
2950 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2951 scoped_ptr<HttpTransaction> trans(
2952 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
2954 MockWrite data_writes1[] = {
2955 MockWrite("GET / HTTP/1.1\r\n"
2956 "Host: www.google.com\r\n"
2957 "Connection: keep-alive\r\n\r\n"),
2960 MockRead data_reads1[] = {
2961 MockRead("HTTP/1.0 407 Proxy Auth required\r\n"),
2962 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
2963 // Large content-length -- won't matter, as connection will be reset.
2964 MockRead("Content-Length: 10000\r\n\r\n"),
2965 MockRead(SYNCHRONOUS, ERR_FAILED),
2968 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
2969 data_writes1, arraysize(data_writes1));
2970 session_deps_.socket_factory->AddSocketDataProvider(&data1);
2972 TestCompletionCallback callback;
2974 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
2975 EXPECT_EQ(ERR_IO_PENDING, rv);
2977 rv = callback.WaitForResult();
2978 EXPECT_EQ(ERR_UNEXPECTED_PROXY_AUTH, rv);
2981 // Tests when an HTTPS server (non-proxy) returns a 407 (proxy-authentication)
2982 // through a non-authenticating proxy. The request should fail with
2983 // ERR_UNEXPECTED_PROXY_AUTH.
2984 // Note that it is impossible to detect if an HTTP server returns a 407 through
2985 // a non-authenticating proxy - there is nothing to indicate whether the
2986 // response came from the proxy or the server, so it is treated as if the proxy
2987 // issued the challenge.
2988 TEST_P(HttpNetworkTransactionTest,
2989 HttpsServerRequestsProxyAuthThroughProxy) {
2990 HttpRequestInfo request;
2991 request.method = "GET";
2992 request.url = GURL("https://www.google.com/");
2994 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
2995 CapturingBoundNetLog log;
2996 session_deps_.net_log = log.bound().net_log();
2997 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
2999 // Since we have proxy, should try to establish tunnel.
3000 MockWrite data_writes1[] = {
3001 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
3002 "Host: www.google.com\r\n"
3003 "Proxy-Connection: keep-alive\r\n\r\n"),
3005 MockWrite("GET / HTTP/1.1\r\n"
3006 "Host: www.google.com\r\n"
3007 "Connection: keep-alive\r\n\r\n"),
3010 MockRead data_reads1[] = {
3011 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
3013 MockRead("HTTP/1.1 407 Unauthorized\r\n"),
3014 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
3015 MockRead("\r\n"),
3016 MockRead(SYNCHRONOUS, OK),
3019 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
3020 data_writes1, arraysize(data_writes1));
3021 session_deps_.socket_factory->AddSocketDataProvider(&data1);
3022 SSLSocketDataProvider ssl(ASYNC, OK);
3023 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3025 TestCompletionCallback callback1;
3027 scoped_ptr<HttpTransaction> trans(
3028 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3030 int rv = trans->Start(&request, callback1.callback(), log.bound());
3031 EXPECT_EQ(ERR_IO_PENDING, rv);
3033 rv = callback1.WaitForResult();
3034 EXPECT_EQ(ERR_UNEXPECTED_PROXY_AUTH, rv);
3035 net::CapturingNetLog::CapturedEntryList entries;
3036 log.GetEntries(&entries);
3037 size_t pos = ExpectLogContainsSomewhere(
3038 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
3039 NetLog::PHASE_NONE);
3040 ExpectLogContainsSomewhere(
3041 entries, pos,
3042 NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
3043 NetLog::PHASE_NONE);
3046 // Test the load timing for HTTPS requests with an HTTP proxy.
3047 TEST_P(HttpNetworkTransactionTest, HttpProxyLoadTimingNoPacTwoRequests) {
3048 HttpRequestInfo request1;
3049 request1.method = "GET";
3050 request1.url = GURL("https://www.google.com/1");
3052 HttpRequestInfo request2;
3053 request2.method = "GET";
3054 request2.url = GURL("https://www.google.com/2");
3056 // Configure against proxy server "myproxy:70".
3057 session_deps_.proxy_service.reset(
3058 ProxyService::CreateFixed("PROXY myproxy:70"));
3059 CapturingBoundNetLog log;
3060 session_deps_.net_log = log.bound().net_log();
3061 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3063 // Since we have proxy, should try to establish tunnel.
3064 MockWrite data_writes1[] = {
3065 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
3066 "Host: www.google.com\r\n"
3067 "Proxy-Connection: keep-alive\r\n\r\n"),
3069 MockWrite("GET /1 HTTP/1.1\r\n"
3070 "Host: www.google.com\r\n"
3071 "Connection: keep-alive\r\n\r\n"),
3073 MockWrite("GET /2 HTTP/1.1\r\n"
3074 "Host: www.google.com\r\n"
3075 "Connection: keep-alive\r\n\r\n"),
3078 // The proxy responds to the connect with a 407, using a persistent
3079 // connection.
3080 MockRead data_reads1[] = {
3081 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
3083 MockRead("HTTP/1.1 200 OK\r\n"),
3084 MockRead("Content-Length: 1\r\n\r\n"),
3085 MockRead(SYNCHRONOUS, "1"),
3087 MockRead("HTTP/1.1 200 OK\r\n"),
3088 MockRead("Content-Length: 2\r\n\r\n"),
3089 MockRead(SYNCHRONOUS, "22"),
3092 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
3093 data_writes1, arraysize(data_writes1));
3094 session_deps_.socket_factory->AddSocketDataProvider(&data1);
3095 SSLSocketDataProvider ssl(ASYNC, OK);
3096 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3098 TestCompletionCallback callback1;
3099 scoped_ptr<HttpTransaction> trans1(
3100 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3102 int rv = trans1->Start(&request1, callback1.callback(), log.bound());
3103 EXPECT_EQ(ERR_IO_PENDING, rv);
3105 rv = callback1.WaitForResult();
3106 EXPECT_EQ(OK, rv);
3108 const HttpResponseInfo* response1 = trans1->GetResponseInfo();
3109 ASSERT_TRUE(response1 != NULL);
3110 ASSERT_TRUE(response1->headers.get() != NULL);
3111 EXPECT_EQ(1, response1->headers->GetContentLength());
3113 LoadTimingInfo load_timing_info1;
3114 EXPECT_TRUE(trans1->GetLoadTimingInfo(&load_timing_info1));
3115 TestLoadTimingNotReused(load_timing_info1, CONNECT_TIMING_HAS_SSL_TIMES);
3117 trans1.reset();
3119 TestCompletionCallback callback2;
3120 scoped_ptr<HttpTransaction> trans2(
3121 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3123 rv = trans2->Start(&request2, callback2.callback(), log.bound());
3124 EXPECT_EQ(ERR_IO_PENDING, rv);
3126 rv = callback2.WaitForResult();
3127 EXPECT_EQ(OK, rv);
3129 const HttpResponseInfo* response2 = trans2->GetResponseInfo();
3130 ASSERT_TRUE(response2 != NULL);
3131 ASSERT_TRUE(response2->headers.get() != NULL);
3132 EXPECT_EQ(2, response2->headers->GetContentLength());
3134 LoadTimingInfo load_timing_info2;
3135 EXPECT_TRUE(trans2->GetLoadTimingInfo(&load_timing_info2));
3136 TestLoadTimingReused(load_timing_info2);
3138 EXPECT_EQ(load_timing_info1.socket_log_id, load_timing_info2.socket_log_id);
3140 trans2.reset();
3141 session->CloseAllConnections();
3144 // Test the load timing for HTTPS requests with an HTTP proxy and a PAC script.
3145 TEST_P(HttpNetworkTransactionTest, HttpProxyLoadTimingWithPacTwoRequests) {
3146 HttpRequestInfo request1;
3147 request1.method = "GET";
3148 request1.url = GURL("https://www.google.com/1");
3150 HttpRequestInfo request2;
3151 request2.method = "GET";
3152 request2.url = GURL("https://www.google.com/2");
3154 // Configure against proxy server "myproxy:70".
3155 session_deps_.proxy_service.reset(
3156 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
3157 CapturingBoundNetLog log;
3158 session_deps_.net_log = log.bound().net_log();
3159 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3161 // Since we have proxy, should try to establish tunnel.
3162 MockWrite data_writes1[] = {
3163 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
3164 "Host: www.google.com\r\n"
3165 "Proxy-Connection: keep-alive\r\n\r\n"),
3167 MockWrite("GET /1 HTTP/1.1\r\n"
3168 "Host: www.google.com\r\n"
3169 "Connection: keep-alive\r\n\r\n"),
3171 MockWrite("GET /2 HTTP/1.1\r\n"
3172 "Host: www.google.com\r\n"
3173 "Connection: keep-alive\r\n\r\n"),
3176 // The proxy responds to the connect with a 407, using a persistent
3177 // connection.
3178 MockRead data_reads1[] = {
3179 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
3181 MockRead("HTTP/1.1 200 OK\r\n"),
3182 MockRead("Content-Length: 1\r\n\r\n"),
3183 MockRead(SYNCHRONOUS, "1"),
3185 MockRead("HTTP/1.1 200 OK\r\n"),
3186 MockRead("Content-Length: 2\r\n\r\n"),
3187 MockRead(SYNCHRONOUS, "22"),
3190 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
3191 data_writes1, arraysize(data_writes1));
3192 session_deps_.socket_factory->AddSocketDataProvider(&data1);
3193 SSLSocketDataProvider ssl(ASYNC, OK);
3194 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3196 TestCompletionCallback callback1;
3197 scoped_ptr<HttpTransaction> trans1(
3198 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3200 int rv = trans1->Start(&request1, callback1.callback(), log.bound());
3201 EXPECT_EQ(ERR_IO_PENDING, rv);
3203 rv = callback1.WaitForResult();
3204 EXPECT_EQ(OK, rv);
3206 const HttpResponseInfo* response1 = trans1->GetResponseInfo();
3207 ASSERT_TRUE(response1 != NULL);
3208 ASSERT_TRUE(response1->headers.get() != NULL);
3209 EXPECT_EQ(1, response1->headers->GetContentLength());
3211 LoadTimingInfo load_timing_info1;
3212 EXPECT_TRUE(trans1->GetLoadTimingInfo(&load_timing_info1));
3213 TestLoadTimingNotReusedWithPac(load_timing_info1,
3214 CONNECT_TIMING_HAS_SSL_TIMES);
3216 trans1.reset();
3218 TestCompletionCallback callback2;
3219 scoped_ptr<HttpTransaction> trans2(
3220 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3222 rv = trans2->Start(&request2, callback2.callback(), log.bound());
3223 EXPECT_EQ(ERR_IO_PENDING, rv);
3225 rv = callback2.WaitForResult();
3226 EXPECT_EQ(OK, rv);
3228 const HttpResponseInfo* response2 = trans2->GetResponseInfo();
3229 ASSERT_TRUE(response2 != NULL);
3230 ASSERT_TRUE(response2->headers.get() != NULL);
3231 EXPECT_EQ(2, response2->headers->GetContentLength());
3233 LoadTimingInfo load_timing_info2;
3234 EXPECT_TRUE(trans2->GetLoadTimingInfo(&load_timing_info2));
3235 TestLoadTimingReusedWithPac(load_timing_info2);
3237 EXPECT_EQ(load_timing_info1.socket_log_id, load_timing_info2.socket_log_id);
3239 trans2.reset();
3240 session->CloseAllConnections();
3243 // Test a simple get through an HTTPS Proxy.
3244 TEST_P(HttpNetworkTransactionTest, HttpsProxyGet) {
3245 HttpRequestInfo request;
3246 request.method = "GET";
3247 request.url = GURL("http://www.google.com/");
3249 // Configure against https proxy server "proxy:70".
3250 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
3251 "https://proxy:70"));
3252 CapturingBoundNetLog log;
3253 session_deps_.net_log = log.bound().net_log();
3254 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3256 // Since we have proxy, should use full url
3257 MockWrite data_writes1[] = {
3258 MockWrite("GET http://www.google.com/ HTTP/1.1\r\n"
3259 "Host: www.google.com\r\n"
3260 "Proxy-Connection: keep-alive\r\n\r\n"),
3263 MockRead data_reads1[] = {
3264 MockRead("HTTP/1.1 200 OK\r\n"),
3265 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
3266 MockRead("Content-Length: 100\r\n\r\n"),
3267 MockRead(SYNCHRONOUS, OK),
3270 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
3271 data_writes1, arraysize(data_writes1));
3272 session_deps_.socket_factory->AddSocketDataProvider(&data1);
3273 SSLSocketDataProvider ssl(ASYNC, OK);
3274 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3276 TestCompletionCallback callback1;
3278 scoped_ptr<HttpTransaction> trans(
3279 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3281 int rv = trans->Start(&request, callback1.callback(), log.bound());
3282 EXPECT_EQ(ERR_IO_PENDING, rv);
3284 rv = callback1.WaitForResult();
3285 EXPECT_EQ(OK, rv);
3287 LoadTimingInfo load_timing_info;
3288 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
3289 TestLoadTimingNotReused(load_timing_info,
3290 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
3292 const HttpResponseInfo* response = trans->GetResponseInfo();
3293 ASSERT_TRUE(response != NULL);
3295 EXPECT_TRUE(response->headers->IsKeepAlive());
3296 EXPECT_EQ(200, response->headers->response_code());
3297 EXPECT_EQ(100, response->headers->GetContentLength());
3298 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
3300 // The password prompt info should not be set.
3301 EXPECT_TRUE(response->auth_challenge.get() == NULL);
3304 // Test a SPDY get through an HTTPS Proxy.
3305 TEST_P(HttpNetworkTransactionTest, HttpsProxySpdyGet) {
3306 HttpRequestInfo request;
3307 request.method = "GET";
3308 request.url = GURL("http://www.google.com/");
3309 request.load_flags = 0;
3311 // Configure against https proxy server "proxy:70".
3312 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
3313 "https://proxy:70"));
3314 CapturingBoundNetLog log;
3315 session_deps_.net_log = log.bound().net_log();
3316 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3318 // fetch http://www.google.com/ via SPDY
3319 scoped_ptr<SpdyFrame> req(
3320 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, false));
3321 MockWrite spdy_writes[] = { CreateMockWrite(*req) };
3323 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
3324 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
3325 MockRead spdy_reads[] = {
3326 CreateMockRead(*resp),
3327 CreateMockRead(*data),
3328 MockRead(ASYNC, 0, 0),
3331 DelayedSocketData spdy_data(
3332 1, // wait for one write to finish before reading.
3333 spdy_reads, arraysize(spdy_reads),
3334 spdy_writes, arraysize(spdy_writes));
3335 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
3337 SSLSocketDataProvider ssl(ASYNC, OK);
3338 ssl.SetNextProto(GetParam());
3339 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3341 TestCompletionCallback callback1;
3343 scoped_ptr<HttpTransaction> trans(
3344 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3346 int rv = trans->Start(&request, callback1.callback(), log.bound());
3347 EXPECT_EQ(ERR_IO_PENDING, rv);
3349 rv = callback1.WaitForResult();
3350 EXPECT_EQ(OK, rv);
3352 LoadTimingInfo load_timing_info;
3353 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
3354 TestLoadTimingNotReused(load_timing_info,
3355 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
3357 const HttpResponseInfo* response = trans->GetResponseInfo();
3358 ASSERT_TRUE(response != NULL);
3359 ASSERT_TRUE(response->headers.get() != NULL);
3360 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
3362 std::string response_data;
3363 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
3364 EXPECT_EQ(kUploadData, response_data);
3367 // Verifies that a session which races and wins against the owning transaction
3368 // (completing prior to host resolution), doesn't fail the transaction.
3369 // Regression test for crbug.com/334413.
3370 TEST_P(HttpNetworkTransactionTest, HttpsProxySpdyGetWithSessionRace) {
3371 HttpRequestInfo request;
3372 request.method = "GET";
3373 request.url = GURL("http://www.google.com/");
3374 request.load_flags = 0;
3376 // Configure SPDY proxy server "proxy:70".
3377 session_deps_.proxy_service.reset(
3378 ProxyService::CreateFixed("https://proxy:70"));
3379 CapturingBoundNetLog log;
3380 session_deps_.net_log = log.bound().net_log();
3381 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3383 // Fetch http://www.google.com/ through the SPDY proxy.
3384 scoped_ptr<SpdyFrame> req(
3385 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, false));
3386 MockWrite spdy_writes[] = {CreateMockWrite(*req)};
3388 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
3389 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
3390 MockRead spdy_reads[] = {
3391 CreateMockRead(*resp), CreateMockRead(*data), MockRead(ASYNC, 0, 0),
3394 DelayedSocketData spdy_data(
3395 1, // wait for one write to finish before reading.
3396 spdy_reads,
3397 arraysize(spdy_reads),
3398 spdy_writes,
3399 arraysize(spdy_writes));
3400 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
3402 SSLSocketDataProvider ssl(ASYNC, OK);
3403 ssl.SetNextProto(GetParam());
3404 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3406 TestCompletionCallback callback1;
3408 scoped_ptr<HttpTransaction> trans(
3409 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3411 // Stall the hostname resolution begun by the transaction.
3412 session_deps_.host_resolver->set_synchronous_mode(false);
3413 session_deps_.host_resolver->set_ondemand_mode(true);
3415 int rv = trans->Start(&request, callback1.callback(), log.bound());
3416 EXPECT_EQ(ERR_IO_PENDING, rv);
3418 // Race a session to the proxy, which completes first.
3419 session_deps_.host_resolver->set_ondemand_mode(false);
3420 SpdySessionKey key(
3421 HostPortPair("proxy", 70), ProxyServer::Direct(), PRIVACY_MODE_DISABLED);
3422 base::WeakPtr<SpdySession> spdy_session =
3423 CreateSecureSpdySession(session, key, log.bound());
3425 // Unstall the resolution begun by the transaction.
3426 session_deps_.host_resolver->set_ondemand_mode(true);
3427 session_deps_.host_resolver->ResolveAllPending();
3429 EXPECT_FALSE(callback1.have_result());
3430 rv = callback1.WaitForResult();
3431 EXPECT_EQ(OK, rv);
3433 const HttpResponseInfo* response = trans->GetResponseInfo();
3434 ASSERT_TRUE(response != NULL);
3435 ASSERT_TRUE(response->headers.get() != NULL);
3436 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
3438 std::string response_data;
3439 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
3440 EXPECT_EQ(kUploadData, response_data);
3443 // Test a SPDY get through an HTTPS Proxy.
3444 TEST_P(HttpNetworkTransactionTest, HttpsProxySpdyGetWithProxyAuth) {
3445 HttpRequestInfo request;
3446 request.method = "GET";
3447 request.url = GURL("http://www.google.com/");
3448 request.load_flags = 0;
3450 // Configure against https proxy server "myproxy:70".
3451 session_deps_.proxy_service.reset(
3452 ProxyService::CreateFixed("https://myproxy:70"));
3453 CapturingBoundNetLog log;
3454 session_deps_.net_log = log.bound().net_log();
3455 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3457 // The first request will be a bare GET, the second request will be a
3458 // GET with a Proxy-Authorization header.
3459 scoped_ptr<SpdyFrame> req_get(
3460 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, false));
3461 const char* const kExtraAuthorizationHeaders[] = {
3462 "proxy-authorization", "Basic Zm9vOmJhcg=="
3464 scoped_ptr<SpdyFrame> req_get_authorization(
3465 spdy_util_.ConstructSpdyGet(kExtraAuthorizationHeaders,
3466 arraysize(kExtraAuthorizationHeaders) / 2,
3467 false,
3469 LOWEST,
3470 false));
3471 MockWrite spdy_writes[] = {
3472 CreateMockWrite(*req_get, 1),
3473 CreateMockWrite(*req_get_authorization, 4),
3476 // The first response is a 407 proxy authentication challenge, and the second
3477 // response will be a 200 response since the second request includes a valid
3478 // Authorization header.
3479 const char* const kExtraAuthenticationHeaders[] = {
3480 "proxy-authenticate", "Basic realm=\"MyRealm1\""
3482 scoped_ptr<SpdyFrame> resp_authentication(
3483 spdy_util_.ConstructSpdySynReplyError(
3484 "407 Proxy Authentication Required",
3485 kExtraAuthenticationHeaders, arraysize(kExtraAuthenticationHeaders)/2,
3486 1));
3487 scoped_ptr<SpdyFrame> body_authentication(
3488 spdy_util_.ConstructSpdyBodyFrame(1, true));
3489 scoped_ptr<SpdyFrame> resp_data(
3490 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
3491 scoped_ptr<SpdyFrame> body_data(spdy_util_.ConstructSpdyBodyFrame(3, true));
3492 MockRead spdy_reads[] = {
3493 CreateMockRead(*resp_authentication, 2),
3494 CreateMockRead(*body_authentication, 3),
3495 CreateMockRead(*resp_data, 5),
3496 CreateMockRead(*body_data, 6),
3497 MockRead(ASYNC, 0, 7),
3500 OrderedSocketData data(
3501 spdy_reads, arraysize(spdy_reads),
3502 spdy_writes, arraysize(spdy_writes));
3503 session_deps_.socket_factory->AddSocketDataProvider(&data);
3505 SSLSocketDataProvider ssl(ASYNC, OK);
3506 ssl.SetNextProto(GetParam());
3507 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3509 TestCompletionCallback callback1;
3511 scoped_ptr<HttpTransaction> trans(
3512 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3514 int rv = trans->Start(&request, callback1.callback(), log.bound());
3515 EXPECT_EQ(ERR_IO_PENDING, rv);
3517 rv = callback1.WaitForResult();
3518 EXPECT_EQ(OK, rv);
3520 const HttpResponseInfo* const response = trans->GetResponseInfo();
3522 ASSERT_TRUE(response != NULL);
3523 ASSERT_TRUE(response->headers.get() != NULL);
3524 EXPECT_EQ(407, response->headers->response_code());
3525 EXPECT_TRUE(response->was_fetched_via_spdy);
3526 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
3528 TestCompletionCallback callback2;
3530 rv = trans->RestartWithAuth(
3531 AuthCredentials(kFoo, kBar), callback2.callback());
3532 EXPECT_EQ(ERR_IO_PENDING, rv);
3534 rv = callback2.WaitForResult();
3535 EXPECT_EQ(OK, rv);
3537 const HttpResponseInfo* const response_restart = trans->GetResponseInfo();
3539 ASSERT_TRUE(response_restart != NULL);
3540 ASSERT_TRUE(response_restart->headers.get() != NULL);
3541 EXPECT_EQ(200, response_restart->headers->response_code());
3542 // The password prompt info should not be set.
3543 EXPECT_TRUE(response_restart->auth_challenge.get() == NULL);
3546 // Test a SPDY CONNECT through an HTTPS Proxy to an HTTPS (non-SPDY) Server.
3547 TEST_P(HttpNetworkTransactionTest, HttpsProxySpdyConnectHttps) {
3548 HttpRequestInfo request;
3549 request.method = "GET";
3550 request.url = GURL("https://www.google.com/");
3551 request.load_flags = 0;
3553 // Configure against https proxy server "proxy:70".
3554 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
3555 "https://proxy:70"));
3556 CapturingBoundNetLog log;
3557 session_deps_.net_log = log.bound().net_log();
3558 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3560 scoped_ptr<HttpTransaction> trans(
3561 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3563 // CONNECT to www.google.com:443 via SPDY
3564 scoped_ptr<SpdyFrame> connect(spdy_util_.ConstructSpdyConnect(
3565 NULL, 0, 1, LOWEST, HostPortPair("www.google.com", 443)));
3566 // fetch https://www.google.com/ via HTTP
3568 const char get[] = "GET / HTTP/1.1\r\n"
3569 "Host: www.google.com\r\n"
3570 "Connection: keep-alive\r\n\r\n";
3571 scoped_ptr<SpdyFrame> wrapped_get(
3572 spdy_util_.ConstructSpdyBodyFrame(1, get, strlen(get), false));
3573 scoped_ptr<SpdyFrame> conn_resp(
3574 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
3575 const char resp[] = "HTTP/1.1 200 OK\r\n"
3576 "Content-Length: 10\r\n\r\n";
3577 scoped_ptr<SpdyFrame> wrapped_get_resp(
3578 spdy_util_.ConstructSpdyBodyFrame(1, resp, strlen(resp), false));
3579 scoped_ptr<SpdyFrame> wrapped_body(
3580 spdy_util_.ConstructSpdyBodyFrame(1, "1234567890", 10, false));
3581 scoped_ptr<SpdyFrame> window_update(
3582 spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_get_resp->size()));
3584 MockWrite spdy_writes[] = {
3585 CreateMockWrite(*connect, 1),
3586 CreateMockWrite(*wrapped_get, 3),
3587 CreateMockWrite(*window_update, 5),
3590 MockRead spdy_reads[] = {
3591 CreateMockRead(*conn_resp, 2, ASYNC),
3592 CreateMockRead(*wrapped_get_resp, 4, ASYNC),
3593 CreateMockRead(*wrapped_body, 6, ASYNC),
3594 CreateMockRead(*wrapped_body, 7, ASYNC),
3595 MockRead(ASYNC, 0, 8),
3598 OrderedSocketData spdy_data(
3599 spdy_reads, arraysize(spdy_reads),
3600 spdy_writes, arraysize(spdy_writes));
3601 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
3603 SSLSocketDataProvider ssl(ASYNC, OK);
3604 ssl.SetNextProto(GetParam());
3605 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3606 SSLSocketDataProvider ssl2(ASYNC, OK);
3607 ssl2.was_npn_negotiated = false;
3608 ssl2.protocol_negotiated = kProtoUnknown;
3609 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
3611 TestCompletionCallback callback1;
3613 int rv = trans->Start(&request, callback1.callback(), log.bound());
3614 EXPECT_EQ(ERR_IO_PENDING, rv);
3616 rv = callback1.WaitForResult();
3617 EXPECT_EQ(OK, rv);
3619 LoadTimingInfo load_timing_info;
3620 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
3621 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_SSL_TIMES);
3623 const HttpResponseInfo* response = trans->GetResponseInfo();
3624 ASSERT_TRUE(response != NULL);
3625 ASSERT_TRUE(response->headers.get() != NULL);
3626 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
3628 std::string response_data;
3629 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
3630 EXPECT_EQ("1234567890", response_data);
3633 // Test a SPDY CONNECT through an HTTPS Proxy to a SPDY server.
3634 TEST_P(HttpNetworkTransactionTest, HttpsProxySpdyConnectSpdy) {
3635 HttpRequestInfo request;
3636 request.method = "GET";
3637 request.url = GURL("https://www.google.com/");
3638 request.load_flags = 0;
3640 // Configure against https proxy server "proxy:70".
3641 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
3642 "https://proxy:70"));
3643 CapturingBoundNetLog log;
3644 session_deps_.net_log = log.bound().net_log();
3645 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3647 scoped_ptr<HttpTransaction> trans(
3648 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3650 // CONNECT to www.google.com:443 via SPDY
3651 scoped_ptr<SpdyFrame> connect(spdy_util_.ConstructSpdyConnect(
3652 NULL, 0, 1, LOWEST, HostPortPair("www.google.com", 443)));
3653 // fetch https://www.google.com/ via SPDY
3654 const char kMyUrl[] = "https://www.google.com/";
3655 scoped_ptr<SpdyFrame> get(
3656 spdy_util_.ConstructSpdyGet(kMyUrl, false, 1, LOWEST));
3657 scoped_ptr<SpdyFrame> wrapped_get(
3658 spdy_util_.ConstructWrappedSpdyFrame(get, 1));
3659 scoped_ptr<SpdyFrame> conn_resp(
3660 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
3661 scoped_ptr<SpdyFrame> get_resp(
3662 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
3663 scoped_ptr<SpdyFrame> wrapped_get_resp(
3664 spdy_util_.ConstructWrappedSpdyFrame(get_resp, 1));
3665 scoped_ptr<SpdyFrame> body(spdy_util_.ConstructSpdyBodyFrame(1, true));
3666 scoped_ptr<SpdyFrame> wrapped_body(
3667 spdy_util_.ConstructWrappedSpdyFrame(body, 1));
3668 scoped_ptr<SpdyFrame> window_update_get_resp(
3669 spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_get_resp->size()));
3670 scoped_ptr<SpdyFrame> window_update_body(
3671 spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_body->size()));
3673 MockWrite spdy_writes[] = {
3674 CreateMockWrite(*connect, 1),
3675 CreateMockWrite(*wrapped_get, 3),
3676 CreateMockWrite(*window_update_get_resp, 5),
3677 CreateMockWrite(*window_update_body, 7),
3680 MockRead spdy_reads[] = {
3681 CreateMockRead(*conn_resp, 2, ASYNC),
3682 CreateMockRead(*wrapped_get_resp, 4, ASYNC),
3683 CreateMockRead(*wrapped_body, 6, ASYNC),
3684 MockRead(ASYNC, 0, 8),
3687 OrderedSocketData spdy_data(
3688 spdy_reads, arraysize(spdy_reads),
3689 spdy_writes, arraysize(spdy_writes));
3690 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
3692 SSLSocketDataProvider ssl(ASYNC, OK);
3693 ssl.SetNextProto(GetParam());
3694 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3695 SSLSocketDataProvider ssl2(ASYNC, OK);
3696 ssl2.SetNextProto(GetParam());
3697 ssl2.protocol_negotiated = GetParam();
3698 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
3700 TestCompletionCallback callback1;
3702 int rv = trans->Start(&request, callback1.callback(), log.bound());
3703 EXPECT_EQ(ERR_IO_PENDING, rv);
3705 rv = callback1.WaitForResult();
3706 EXPECT_EQ(OK, rv);
3708 LoadTimingInfo load_timing_info;
3709 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
3710 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_SSL_TIMES);
3712 const HttpResponseInfo* response = trans->GetResponseInfo();
3713 ASSERT_TRUE(response != NULL);
3714 ASSERT_TRUE(response->headers.get() != NULL);
3715 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
3717 std::string response_data;
3718 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
3719 EXPECT_EQ(kUploadData, response_data);
3722 // Test a SPDY CONNECT failure through an HTTPS Proxy.
3723 TEST_P(HttpNetworkTransactionTest, HttpsProxySpdyConnectFailure) {
3724 HttpRequestInfo request;
3725 request.method = "GET";
3726 request.url = GURL("https://www.google.com/");
3727 request.load_flags = 0;
3729 // Configure against https proxy server "proxy:70".
3730 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
3731 "https://proxy:70"));
3732 CapturingBoundNetLog log;
3733 session_deps_.net_log = log.bound().net_log();
3734 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
3736 scoped_ptr<HttpTransaction> trans(
3737 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3739 // CONNECT to www.google.com:443 via SPDY
3740 scoped_ptr<SpdyFrame> connect(spdy_util_.ConstructSpdyConnect(
3741 NULL, 0, 1, LOWEST, HostPortPair("www.google.com", 443)));
3742 scoped_ptr<SpdyFrame> get(
3743 spdy_util_.ConstructSpdyRstStream(1, RST_STREAM_CANCEL));
3745 MockWrite spdy_writes[] = {
3746 CreateMockWrite(*connect, 1),
3747 CreateMockWrite(*get, 3),
3750 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdySynReplyError(1));
3751 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
3752 MockRead spdy_reads[] = {
3753 CreateMockRead(*resp, 2, ASYNC),
3754 MockRead(ASYNC, 0, 4),
3757 OrderedSocketData spdy_data(
3758 spdy_reads, arraysize(spdy_reads),
3759 spdy_writes, arraysize(spdy_writes));
3760 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
3762 SSLSocketDataProvider ssl(ASYNC, OK);
3763 ssl.SetNextProto(GetParam());
3764 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
3765 SSLSocketDataProvider ssl2(ASYNC, OK);
3766 ssl2.SetNextProto(GetParam());
3767 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
3769 TestCompletionCallback callback1;
3771 int rv = trans->Start(&request, callback1.callback(), log.bound());
3772 EXPECT_EQ(ERR_IO_PENDING, rv);
3774 rv = callback1.WaitForResult();
3775 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, rv);
3777 // TODO(ttuttle): Anything else to check here?
3780 // Test load timing in the case of two HTTPS (non-SPDY) requests through a SPDY
3781 // HTTPS Proxy to different servers.
3782 TEST_P(HttpNetworkTransactionTest,
3783 HttpsProxySpdyConnectHttpsLoadTimingTwoRequestsTwoServers) {
3784 // Configure against https proxy server "proxy:70".
3785 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
3786 "https://proxy:70"));
3787 CapturingBoundNetLog log;
3788 session_deps_.net_log = log.bound().net_log();
3789 scoped_refptr<HttpNetworkSession> session(
3790 SpdySessionDependencies::SpdyCreateSessionDeterministic(&session_deps_));
3792 HttpRequestInfo request1;
3793 request1.method = "GET";
3794 request1.url = GURL("https://www.google.com/");
3795 request1.load_flags = 0;
3797 HttpRequestInfo request2;
3798 request2.method = "GET";
3799 request2.url = GURL("https://news.google.com/");
3800 request2.load_flags = 0;
3802 // CONNECT to www.google.com:443 via SPDY.
3803 scoped_ptr<SpdyFrame> connect1(spdy_util_.ConstructSpdyConnect(
3804 NULL, 0, 1, LOWEST, HostPortPair("www.google.com", 443)));
3805 scoped_ptr<SpdyFrame> conn_resp1(
3806 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
3808 // Fetch https://www.google.com/ via HTTP.
3809 const char get1[] = "GET / HTTP/1.1\r\n"
3810 "Host: www.google.com\r\n"
3811 "Connection: keep-alive\r\n\r\n";
3812 scoped_ptr<SpdyFrame> wrapped_get1(
3813 spdy_util_.ConstructSpdyBodyFrame(1, get1, strlen(get1), false));
3814 const char resp1[] = "HTTP/1.1 200 OK\r\n"
3815 "Content-Length: 1\r\n\r\n";
3816 scoped_ptr<SpdyFrame> wrapped_get_resp1(
3817 spdy_util_.ConstructSpdyBodyFrame(1, resp1, strlen(resp1), false));
3818 scoped_ptr<SpdyFrame> wrapped_body1(
3819 spdy_util_.ConstructSpdyBodyFrame(1, "1", 1, false));
3820 scoped_ptr<SpdyFrame> window_update(
3821 spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_get_resp1->size()));
3823 // CONNECT to news.google.com:443 via SPDY.
3824 SpdyHeaderBlock connect2_block;
3825 connect2_block[spdy_util_.GetMethodKey()] = "CONNECT";
3826 connect2_block[spdy_util_.GetPathKey()] = "news.google.com:443";
3827 connect2_block[spdy_util_.GetHostKey()] = "news.google.com";
3828 spdy_util_.MaybeAddVersionHeader(&connect2_block);
3829 scoped_ptr<SpdyFrame> connect2(
3830 spdy_util_.ConstructSpdySyn(3, connect2_block, LOWEST, false, false));
3832 scoped_ptr<SpdyFrame> conn_resp2(
3833 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
3835 // Fetch https://news.google.com/ via HTTP.
3836 const char get2[] = "GET / HTTP/1.1\r\n"
3837 "Host: news.google.com\r\n"
3838 "Connection: keep-alive\r\n\r\n";
3839 scoped_ptr<SpdyFrame> wrapped_get2(
3840 spdy_util_.ConstructSpdyBodyFrame(3, get2, strlen(get2), false));
3841 const char resp2[] = "HTTP/1.1 200 OK\r\n"
3842 "Content-Length: 2\r\n\r\n";
3843 scoped_ptr<SpdyFrame> wrapped_get_resp2(
3844 spdy_util_.ConstructSpdyBodyFrame(3, resp2, strlen(resp2), false));
3845 scoped_ptr<SpdyFrame> wrapped_body2(
3846 spdy_util_.ConstructSpdyBodyFrame(3, "22", 2, false));
3848 MockWrite spdy_writes[] = {
3849 CreateMockWrite(*connect1, 0),
3850 CreateMockWrite(*wrapped_get1, 2),
3851 CreateMockWrite(*connect2, 5),
3852 CreateMockWrite(*wrapped_get2, 7),
3855 MockRead spdy_reads[] = {
3856 CreateMockRead(*conn_resp1, 1, ASYNC),
3857 CreateMockRead(*wrapped_get_resp1, 3, ASYNC),
3858 CreateMockRead(*wrapped_body1, 4, ASYNC),
3859 CreateMockRead(*conn_resp2, 6, ASYNC),
3860 CreateMockRead(*wrapped_get_resp2, 8, ASYNC),
3861 CreateMockRead(*wrapped_body2, 9, ASYNC),
3862 MockRead(ASYNC, 0, 10),
3865 DeterministicSocketData spdy_data(
3866 spdy_reads, arraysize(spdy_reads),
3867 spdy_writes, arraysize(spdy_writes));
3868 session_deps_.deterministic_socket_factory->AddSocketDataProvider(&spdy_data);
3870 SSLSocketDataProvider ssl(ASYNC, OK);
3871 ssl.SetNextProto(GetParam());
3872 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl);
3873 SSLSocketDataProvider ssl2(ASYNC, OK);
3874 ssl2.was_npn_negotiated = false;
3875 ssl2.protocol_negotiated = kProtoUnknown;
3876 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl2);
3877 SSLSocketDataProvider ssl3(ASYNC, OK);
3878 ssl3.was_npn_negotiated = false;
3879 ssl3.protocol_negotiated = kProtoUnknown;
3880 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl3);
3882 TestCompletionCallback callback;
3884 scoped_ptr<HttpTransaction> trans(
3885 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3886 int rv = trans->Start(&request1, callback.callback(), BoundNetLog());
3887 EXPECT_EQ(ERR_IO_PENDING, rv);
3888 // The first connect and request, each of their responses, and the body.
3889 spdy_data.RunFor(5);
3891 rv = callback.WaitForResult();
3892 EXPECT_EQ(OK, rv);
3894 LoadTimingInfo load_timing_info;
3895 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
3896 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_SSL_TIMES);
3898 const HttpResponseInfo* response = trans->GetResponseInfo();
3899 ASSERT_TRUE(response != NULL);
3900 ASSERT_TRUE(response->headers.get() != NULL);
3901 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
3903 std::string response_data;
3904 scoped_refptr<net::IOBuffer> buf(new net::IOBuffer(256));
3905 EXPECT_EQ(1, trans->Read(buf.get(), 256, callback.callback()));
3907 scoped_ptr<HttpTransaction> trans2(
3908 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
3909 rv = trans2->Start(&request2, callback.callback(), BoundNetLog());
3910 EXPECT_EQ(ERR_IO_PENDING, rv);
3912 // The second connect and request, each of their responses, and the body.
3913 spdy_data.RunFor(5);
3914 rv = callback.WaitForResult();
3915 EXPECT_EQ(OK, rv);
3917 LoadTimingInfo load_timing_info2;
3918 EXPECT_TRUE(trans2->GetLoadTimingInfo(&load_timing_info2));
3919 // Even though the SPDY connection is reused, a new tunnelled connection has
3920 // to be created, so the socket's load timing looks like a fresh connection.
3921 TestLoadTimingNotReused(load_timing_info2, CONNECT_TIMING_HAS_SSL_TIMES);
3923 // The requests should have different IDs, since they each are using their own
3924 // separate stream.
3925 EXPECT_NE(load_timing_info.socket_log_id, load_timing_info2.socket_log_id);
3927 EXPECT_EQ(2, trans2->Read(buf.get(), 256, callback.callback()));
3930 // Test load timing in the case of two HTTPS (non-SPDY) requests through a SPDY
3931 // HTTPS Proxy to the same server.
3932 TEST_P(HttpNetworkTransactionTest,
3933 HttpsProxySpdyConnectHttpsLoadTimingTwoRequestsSameServer) {
3934 // Configure against https proxy server "proxy:70".
3935 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
3936 "https://proxy:70"));
3937 CapturingBoundNetLog log;
3938 session_deps_.net_log = log.bound().net_log();
3939 scoped_refptr<HttpNetworkSession> session(
3940 SpdySessionDependencies::SpdyCreateSessionDeterministic(&session_deps_));
3942 HttpRequestInfo request1;
3943 request1.method = "GET";
3944 request1.url = GURL("https://www.google.com/");
3945 request1.load_flags = 0;
3947 HttpRequestInfo request2;
3948 request2.method = "GET";
3949 request2.url = GURL("https://www.google.com/2");
3950 request2.load_flags = 0;
3952 // CONNECT to www.google.com:443 via SPDY.
3953 scoped_ptr<SpdyFrame> connect1(spdy_util_.ConstructSpdyConnect(
3954 NULL, 0, 1, LOWEST, HostPortPair("www.google.com", 443)));
3955 scoped_ptr<SpdyFrame> conn_resp1(
3956 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
3958 // Fetch https://www.google.com/ via HTTP.
3959 const char get1[] = "GET / HTTP/1.1\r\n"
3960 "Host: www.google.com\r\n"
3961 "Connection: keep-alive\r\n\r\n";
3962 scoped_ptr<SpdyFrame> wrapped_get1(
3963 spdy_util_.ConstructSpdyBodyFrame(1, get1, strlen(get1), false));
3964 const char resp1[] = "HTTP/1.1 200 OK\r\n"
3965 "Content-Length: 1\r\n\r\n";
3966 scoped_ptr<SpdyFrame> wrapped_get_resp1(
3967 spdy_util_.ConstructSpdyBodyFrame(1, resp1, strlen(resp1), false));
3968 scoped_ptr<SpdyFrame> wrapped_body1(
3969 spdy_util_.ConstructSpdyBodyFrame(1, "1", 1, false));
3970 scoped_ptr<SpdyFrame> window_update(
3971 spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_get_resp1->size()));
3973 // Fetch https://www.google.com/2 via HTTP.
3974 const char get2[] = "GET /2 HTTP/1.1\r\n"
3975 "Host: www.google.com\r\n"
3976 "Connection: keep-alive\r\n\r\n";
3977 scoped_ptr<SpdyFrame> wrapped_get2(
3978 spdy_util_.ConstructSpdyBodyFrame(1, get2, strlen(get2), false));
3979 const char resp2[] = "HTTP/1.1 200 OK\r\n"
3980 "Content-Length: 2\r\n\r\n";
3981 scoped_ptr<SpdyFrame> wrapped_get_resp2(
3982 spdy_util_.ConstructSpdyBodyFrame(1, resp2, strlen(resp2), false));
3983 scoped_ptr<SpdyFrame> wrapped_body2(
3984 spdy_util_.ConstructSpdyBodyFrame(1, "22", 2, false));
3986 MockWrite spdy_writes[] = {
3987 CreateMockWrite(*connect1, 0),
3988 CreateMockWrite(*wrapped_get1, 2),
3989 CreateMockWrite(*wrapped_get2, 5),
3992 MockRead spdy_reads[] = {
3993 CreateMockRead(*conn_resp1, 1, ASYNC),
3994 CreateMockRead(*wrapped_get_resp1, 3, ASYNC),
3995 CreateMockRead(*wrapped_body1, 4, ASYNC),
3996 CreateMockRead(*wrapped_get_resp2, 6, ASYNC),
3997 CreateMockRead(*wrapped_body2, 7, ASYNC),
3998 MockRead(ASYNC, 0, 8),
4001 DeterministicSocketData spdy_data(
4002 spdy_reads, arraysize(spdy_reads),
4003 spdy_writes, arraysize(spdy_writes));
4004 session_deps_.deterministic_socket_factory->AddSocketDataProvider(&spdy_data);
4006 SSLSocketDataProvider ssl(ASYNC, OK);
4007 ssl.SetNextProto(GetParam());
4008 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl);
4009 SSLSocketDataProvider ssl2(ASYNC, OK);
4010 ssl2.was_npn_negotiated = false;
4011 ssl2.protocol_negotiated = kProtoUnknown;
4012 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl2);
4014 TestCompletionCallback callback;
4016 scoped_ptr<HttpTransaction> trans(
4017 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4018 int rv = trans->Start(&request1, callback.callback(), BoundNetLog());
4019 EXPECT_EQ(ERR_IO_PENDING, rv);
4020 // The first connect and request, each of their responses, and the body.
4021 spdy_data.RunFor(5);
4023 rv = callback.WaitForResult();
4024 EXPECT_EQ(OK, rv);
4026 LoadTimingInfo load_timing_info;
4027 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
4028 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_SSL_TIMES);
4030 const HttpResponseInfo* response = trans->GetResponseInfo();
4031 ASSERT_TRUE(response != NULL);
4032 ASSERT_TRUE(response->headers.get() != NULL);
4033 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
4035 std::string response_data;
4036 scoped_refptr<net::IOBuffer> buf(new net::IOBuffer(256));
4037 EXPECT_EQ(1, trans->Read(buf.get(), 256, callback.callback()));
4038 trans.reset();
4040 scoped_ptr<HttpTransaction> trans2(
4041 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4042 rv = trans2->Start(&request2, callback.callback(), BoundNetLog());
4043 EXPECT_EQ(ERR_IO_PENDING, rv);
4045 // The second request, response, and body. There should not be a second
4046 // connect.
4047 spdy_data.RunFor(3);
4048 rv = callback.WaitForResult();
4049 EXPECT_EQ(OK, rv);
4051 LoadTimingInfo load_timing_info2;
4052 EXPECT_TRUE(trans2->GetLoadTimingInfo(&load_timing_info2));
4053 TestLoadTimingReused(load_timing_info2);
4055 // The requests should have the same ID.
4056 EXPECT_EQ(load_timing_info.socket_log_id, load_timing_info2.socket_log_id);
4058 EXPECT_EQ(2, trans2->Read(buf.get(), 256, callback.callback()));
4061 // Test load timing in the case of of two HTTP requests through a SPDY HTTPS
4062 // Proxy to different servers.
4063 TEST_P(HttpNetworkTransactionTest,
4064 HttpsProxySpdyLoadTimingTwoHttpRequests) {
4065 // Configure against https proxy server "proxy:70".
4066 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
4067 "https://proxy:70"));
4068 CapturingBoundNetLog log;
4069 session_deps_.net_log = log.bound().net_log();
4070 scoped_refptr<HttpNetworkSession> session(
4071 SpdySessionDependencies::SpdyCreateSessionDeterministic(&session_deps_));
4073 HttpRequestInfo request1;
4074 request1.method = "GET";
4075 request1.url = GURL("http://www.google.com/");
4076 request1.load_flags = 0;
4078 HttpRequestInfo request2;
4079 request2.method = "GET";
4080 request2.url = GURL("http://news.google.com/");
4081 request2.load_flags = 0;
4083 // http://www.google.com/
4084 scoped_ptr<SpdyHeaderBlock> headers(
4085 spdy_util_.ConstructGetHeaderBlockForProxy("http://www.google.com/"));
4086 scoped_ptr<SpdyFrame> get1(
4087 spdy_util_.ConstructSpdySyn(1, *headers, LOWEST, false, true));
4088 scoped_ptr<SpdyFrame> get_resp1(
4089 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
4090 scoped_ptr<SpdyFrame> body1(
4091 spdy_util_.ConstructSpdyBodyFrame(1, "1", 1, true));
4093 // http://news.google.com/
4094 scoped_ptr<SpdyHeaderBlock> headers2(
4095 spdy_util_.ConstructGetHeaderBlockForProxy("http://news.google.com/"));
4096 scoped_ptr<SpdyFrame> get2(
4097 spdy_util_.ConstructSpdySyn(3, *headers2, LOWEST, false, true));
4098 scoped_ptr<SpdyFrame> get_resp2(
4099 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
4100 scoped_ptr<SpdyFrame> body2(
4101 spdy_util_.ConstructSpdyBodyFrame(3, "22", 2, true));
4103 MockWrite spdy_writes[] = {
4104 CreateMockWrite(*get1, 0),
4105 CreateMockWrite(*get2, 3),
4108 MockRead spdy_reads[] = {
4109 CreateMockRead(*get_resp1, 1, ASYNC),
4110 CreateMockRead(*body1, 2, ASYNC),
4111 CreateMockRead(*get_resp2, 4, ASYNC),
4112 CreateMockRead(*body2, 5, ASYNC),
4113 MockRead(ASYNC, 0, 6),
4116 DeterministicSocketData spdy_data(
4117 spdy_reads, arraysize(spdy_reads),
4118 spdy_writes, arraysize(spdy_writes));
4119 session_deps_.deterministic_socket_factory->AddSocketDataProvider(&spdy_data);
4121 SSLSocketDataProvider ssl(ASYNC, OK);
4122 ssl.SetNextProto(GetParam());
4123 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl);
4125 TestCompletionCallback callback;
4127 scoped_ptr<HttpTransaction> trans(
4128 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4129 int rv = trans->Start(&request1, callback.callback(), BoundNetLog());
4130 EXPECT_EQ(ERR_IO_PENDING, rv);
4131 spdy_data.RunFor(2);
4133 rv = callback.WaitForResult();
4134 EXPECT_EQ(OK, rv);
4136 LoadTimingInfo load_timing_info;
4137 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
4138 TestLoadTimingNotReused(load_timing_info,
4139 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
4141 const HttpResponseInfo* response = trans->GetResponseInfo();
4142 ASSERT_TRUE(response != NULL);
4143 ASSERT_TRUE(response->headers.get() != NULL);
4144 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
4146 std::string response_data;
4147 scoped_refptr<net::IOBuffer> buf(new net::IOBuffer(256));
4148 EXPECT_EQ(ERR_IO_PENDING, trans->Read(buf.get(), 256, callback.callback()));
4149 spdy_data.RunFor(1);
4150 EXPECT_EQ(1, callback.WaitForResult());
4151 // Delete the first request, so the second one can reuse the socket.
4152 trans.reset();
4154 scoped_ptr<HttpTransaction> trans2(
4155 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4156 rv = trans2->Start(&request2, callback.callback(), BoundNetLog());
4157 EXPECT_EQ(ERR_IO_PENDING, rv);
4159 spdy_data.RunFor(2);
4160 rv = callback.WaitForResult();
4161 EXPECT_EQ(OK, rv);
4163 LoadTimingInfo load_timing_info2;
4164 EXPECT_TRUE(trans2->GetLoadTimingInfo(&load_timing_info2));
4165 TestLoadTimingReused(load_timing_info2);
4167 // The requests should have the same ID.
4168 EXPECT_EQ(load_timing_info.socket_log_id, load_timing_info2.socket_log_id);
4170 EXPECT_EQ(ERR_IO_PENDING, trans2->Read(buf.get(), 256, callback.callback()));
4171 spdy_data.RunFor(1);
4172 EXPECT_EQ(2, callback.WaitForResult());
4175 // Test the challenge-response-retry sequence through an HTTPS Proxy
4176 TEST_P(HttpNetworkTransactionTest, HttpsProxyAuthRetry) {
4177 HttpRequestInfo request;
4178 request.method = "GET";
4179 request.url = GURL("http://www.google.com/");
4180 // when the no authentication data flag is set.
4181 request.load_flags = net::LOAD_DO_NOT_SEND_AUTH_DATA;
4183 // Configure against https proxy server "myproxy:70".
4184 session_deps_.proxy_service.reset(
4185 ProxyService::CreateFixed("https://myproxy:70"));
4186 CapturingBoundNetLog log;
4187 session_deps_.net_log = log.bound().net_log();
4188 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
4190 // Since we have proxy, should use full url
4191 MockWrite data_writes1[] = {
4192 MockWrite("GET http://www.google.com/ HTTP/1.1\r\n"
4193 "Host: www.google.com\r\n"
4194 "Proxy-Connection: keep-alive\r\n\r\n"),
4196 // After calling trans->RestartWithAuth(), this is the request we should
4197 // be issuing -- the final header line contains the credentials.
4198 MockWrite("GET http://www.google.com/ HTTP/1.1\r\n"
4199 "Host: www.google.com\r\n"
4200 "Proxy-Connection: keep-alive\r\n"
4201 "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
4204 // The proxy responds to the GET with a 407, using a persistent
4205 // connection.
4206 MockRead data_reads1[] = {
4207 // No credentials.
4208 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
4209 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
4210 MockRead("Proxy-Connection: keep-alive\r\n"),
4211 MockRead("Content-Length: 0\r\n\r\n"),
4213 MockRead("HTTP/1.1 200 OK\r\n"),
4214 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
4215 MockRead("Content-Length: 100\r\n\r\n"),
4216 MockRead(SYNCHRONOUS, OK),
4219 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
4220 data_writes1, arraysize(data_writes1));
4221 session_deps_.socket_factory->AddSocketDataProvider(&data1);
4222 SSLSocketDataProvider ssl(ASYNC, OK);
4223 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
4225 TestCompletionCallback callback1;
4227 scoped_ptr<HttpTransaction> trans(
4228 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4230 int rv = trans->Start(&request, callback1.callback(), log.bound());
4231 EXPECT_EQ(ERR_IO_PENDING, rv);
4233 rv = callback1.WaitForResult();
4234 EXPECT_EQ(OK, rv);
4236 LoadTimingInfo load_timing_info;
4237 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
4238 TestLoadTimingNotReused(load_timing_info,
4239 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
4241 const HttpResponseInfo* response = trans->GetResponseInfo();
4242 ASSERT_TRUE(response != NULL);
4243 ASSERT_FALSE(response->headers.get() == NULL);
4244 EXPECT_EQ(407, response->headers->response_code());
4245 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
4246 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
4248 TestCompletionCallback callback2;
4250 rv = trans->RestartWithAuth(
4251 AuthCredentials(kFoo, kBar), callback2.callback());
4252 EXPECT_EQ(ERR_IO_PENDING, rv);
4254 rv = callback2.WaitForResult();
4255 EXPECT_EQ(OK, rv);
4257 load_timing_info = LoadTimingInfo();
4258 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
4259 // Retrying with HTTP AUTH is considered to be reusing a socket.
4260 TestLoadTimingReused(load_timing_info);
4262 response = trans->GetResponseInfo();
4263 ASSERT_TRUE(response != NULL);
4265 EXPECT_TRUE(response->headers->IsKeepAlive());
4266 EXPECT_EQ(200, response->headers->response_code());
4267 EXPECT_EQ(100, response->headers->GetContentLength());
4268 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
4270 // The password prompt info should not be set.
4271 EXPECT_TRUE(response->auth_challenge.get() == NULL);
4274 void HttpNetworkTransactionTest::ConnectStatusHelperWithExpectedStatus(
4275 const MockRead& status, int expected_status) {
4276 HttpRequestInfo request;
4277 request.method = "GET";
4278 request.url = GURL("https://www.google.com/");
4279 request.load_flags = 0;
4281 // Configure against proxy server "myproxy:70".
4282 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
4283 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
4285 // Since we have proxy, should try to establish tunnel.
4286 MockWrite data_writes[] = {
4287 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
4288 "Host: www.google.com\r\n"
4289 "Proxy-Connection: keep-alive\r\n\r\n"),
4292 MockRead data_reads[] = {
4293 status,
4294 MockRead("Content-Length: 10\r\n\r\n"),
4295 // No response body because the test stops reading here.
4296 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
4299 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
4300 data_writes, arraysize(data_writes));
4301 session_deps_.socket_factory->AddSocketDataProvider(&data);
4303 TestCompletionCallback callback;
4305 scoped_ptr<HttpTransaction> trans(
4306 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4308 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
4309 EXPECT_EQ(ERR_IO_PENDING, rv);
4311 rv = callback.WaitForResult();
4312 EXPECT_EQ(expected_status, rv);
4315 void HttpNetworkTransactionTest::ConnectStatusHelper(
4316 const MockRead& status) {
4317 ConnectStatusHelperWithExpectedStatus(
4318 status, ERR_TUNNEL_CONNECTION_FAILED);
4321 TEST_P(HttpNetworkTransactionTest, ConnectStatus100) {
4322 ConnectStatusHelper(MockRead("HTTP/1.1 100 Continue\r\n"));
4325 TEST_P(HttpNetworkTransactionTest, ConnectStatus101) {
4326 ConnectStatusHelper(MockRead("HTTP/1.1 101 Switching Protocols\r\n"));
4329 TEST_P(HttpNetworkTransactionTest, ConnectStatus201) {
4330 ConnectStatusHelper(MockRead("HTTP/1.1 201 Created\r\n"));
4333 TEST_P(HttpNetworkTransactionTest, ConnectStatus202) {
4334 ConnectStatusHelper(MockRead("HTTP/1.1 202 Accepted\r\n"));
4337 TEST_P(HttpNetworkTransactionTest, ConnectStatus203) {
4338 ConnectStatusHelper(
4339 MockRead("HTTP/1.1 203 Non-Authoritative Information\r\n"));
4342 TEST_P(HttpNetworkTransactionTest, ConnectStatus204) {
4343 ConnectStatusHelper(MockRead("HTTP/1.1 204 No Content\r\n"));
4346 TEST_P(HttpNetworkTransactionTest, ConnectStatus205) {
4347 ConnectStatusHelper(MockRead("HTTP/1.1 205 Reset Content\r\n"));
4350 TEST_P(HttpNetworkTransactionTest, ConnectStatus206) {
4351 ConnectStatusHelper(MockRead("HTTP/1.1 206 Partial Content\r\n"));
4354 TEST_P(HttpNetworkTransactionTest, ConnectStatus300) {
4355 ConnectStatusHelper(MockRead("HTTP/1.1 300 Multiple Choices\r\n"));
4358 TEST_P(HttpNetworkTransactionTest, ConnectStatus301) {
4359 ConnectStatusHelper(MockRead("HTTP/1.1 301 Moved Permanently\r\n"));
4362 TEST_P(HttpNetworkTransactionTest, ConnectStatus302) {
4363 ConnectStatusHelper(MockRead("HTTP/1.1 302 Found\r\n"));
4366 TEST_P(HttpNetworkTransactionTest, ConnectStatus303) {
4367 ConnectStatusHelper(MockRead("HTTP/1.1 303 See Other\r\n"));
4370 TEST_P(HttpNetworkTransactionTest, ConnectStatus304) {
4371 ConnectStatusHelper(MockRead("HTTP/1.1 304 Not Modified\r\n"));
4374 TEST_P(HttpNetworkTransactionTest, ConnectStatus305) {
4375 ConnectStatusHelper(MockRead("HTTP/1.1 305 Use Proxy\r\n"));
4378 TEST_P(HttpNetworkTransactionTest, ConnectStatus306) {
4379 ConnectStatusHelper(MockRead("HTTP/1.1 306\r\n"));
4382 TEST_P(HttpNetworkTransactionTest, ConnectStatus307) {
4383 ConnectStatusHelper(MockRead("HTTP/1.1 307 Temporary Redirect\r\n"));
4386 TEST_P(HttpNetworkTransactionTest, ConnectStatus308) {
4387 ConnectStatusHelper(MockRead("HTTP/1.1 308 Permanent Redirect\r\n"));
4390 TEST_P(HttpNetworkTransactionTest, ConnectStatus400) {
4391 ConnectStatusHelper(MockRead("HTTP/1.1 400 Bad Request\r\n"));
4394 TEST_P(HttpNetworkTransactionTest, ConnectStatus401) {
4395 ConnectStatusHelper(MockRead("HTTP/1.1 401 Unauthorized\r\n"));
4398 TEST_P(HttpNetworkTransactionTest, ConnectStatus402) {
4399 ConnectStatusHelper(MockRead("HTTP/1.1 402 Payment Required\r\n"));
4402 TEST_P(HttpNetworkTransactionTest, ConnectStatus403) {
4403 ConnectStatusHelper(MockRead("HTTP/1.1 403 Forbidden\r\n"));
4406 TEST_P(HttpNetworkTransactionTest, ConnectStatus404) {
4407 ConnectStatusHelper(MockRead("HTTP/1.1 404 Not Found\r\n"));
4410 TEST_P(HttpNetworkTransactionTest, ConnectStatus405) {
4411 ConnectStatusHelper(MockRead("HTTP/1.1 405 Method Not Allowed\r\n"));
4414 TEST_P(HttpNetworkTransactionTest, ConnectStatus406) {
4415 ConnectStatusHelper(MockRead("HTTP/1.1 406 Not Acceptable\r\n"));
4418 TEST_P(HttpNetworkTransactionTest, ConnectStatus407) {
4419 ConnectStatusHelperWithExpectedStatus(
4420 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
4421 ERR_PROXY_AUTH_UNSUPPORTED);
4424 TEST_P(HttpNetworkTransactionTest, ConnectStatus408) {
4425 ConnectStatusHelper(MockRead("HTTP/1.1 408 Request Timeout\r\n"));
4428 TEST_P(HttpNetworkTransactionTest, ConnectStatus409) {
4429 ConnectStatusHelper(MockRead("HTTP/1.1 409 Conflict\r\n"));
4432 TEST_P(HttpNetworkTransactionTest, ConnectStatus410) {
4433 ConnectStatusHelper(MockRead("HTTP/1.1 410 Gone\r\n"));
4436 TEST_P(HttpNetworkTransactionTest, ConnectStatus411) {
4437 ConnectStatusHelper(MockRead("HTTP/1.1 411 Length Required\r\n"));
4440 TEST_P(HttpNetworkTransactionTest, ConnectStatus412) {
4441 ConnectStatusHelper(MockRead("HTTP/1.1 412 Precondition Failed\r\n"));
4444 TEST_P(HttpNetworkTransactionTest, ConnectStatus413) {
4445 ConnectStatusHelper(MockRead("HTTP/1.1 413 Request Entity Too Large\r\n"));
4448 TEST_P(HttpNetworkTransactionTest, ConnectStatus414) {
4449 ConnectStatusHelper(MockRead("HTTP/1.1 414 Request-URI Too Long\r\n"));
4452 TEST_P(HttpNetworkTransactionTest, ConnectStatus415) {
4453 ConnectStatusHelper(MockRead("HTTP/1.1 415 Unsupported Media Type\r\n"));
4456 TEST_P(HttpNetworkTransactionTest, ConnectStatus416) {
4457 ConnectStatusHelper(
4458 MockRead("HTTP/1.1 416 Requested Range Not Satisfiable\r\n"));
4461 TEST_P(HttpNetworkTransactionTest, ConnectStatus417) {
4462 ConnectStatusHelper(MockRead("HTTP/1.1 417 Expectation Failed\r\n"));
4465 TEST_P(HttpNetworkTransactionTest, ConnectStatus500) {
4466 ConnectStatusHelper(MockRead("HTTP/1.1 500 Internal Server Error\r\n"));
4469 TEST_P(HttpNetworkTransactionTest, ConnectStatus501) {
4470 ConnectStatusHelper(MockRead("HTTP/1.1 501 Not Implemented\r\n"));
4473 TEST_P(HttpNetworkTransactionTest, ConnectStatus502) {
4474 ConnectStatusHelper(MockRead("HTTP/1.1 502 Bad Gateway\r\n"));
4477 TEST_P(HttpNetworkTransactionTest, ConnectStatus503) {
4478 ConnectStatusHelper(MockRead("HTTP/1.1 503 Service Unavailable\r\n"));
4481 TEST_P(HttpNetworkTransactionTest, ConnectStatus504) {
4482 ConnectStatusHelper(MockRead("HTTP/1.1 504 Gateway Timeout\r\n"));
4485 TEST_P(HttpNetworkTransactionTest, ConnectStatus505) {
4486 ConnectStatusHelper(MockRead("HTTP/1.1 505 HTTP Version Not Supported\r\n"));
4489 // Test the flow when both the proxy server AND origin server require
4490 // authentication. Again, this uses basic auth for both since that is
4491 // the simplest to mock.
4492 TEST_P(HttpNetworkTransactionTest, BasicAuthProxyThenServer) {
4493 HttpRequestInfo request;
4494 request.method = "GET";
4495 request.url = GURL("http://www.google.com/");
4496 request.load_flags = 0;
4498 // Configure against proxy server "myproxy:70".
4499 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
4500 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
4502 scoped_ptr<HttpTransaction> trans(
4503 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4505 MockWrite data_writes1[] = {
4506 MockWrite("GET http://www.google.com/ HTTP/1.1\r\n"
4507 "Host: www.google.com\r\n"
4508 "Proxy-Connection: keep-alive\r\n\r\n"),
4511 MockRead data_reads1[] = {
4512 MockRead("HTTP/1.0 407 Unauthorized\r\n"),
4513 // Give a couple authenticate options (only the middle one is actually
4514 // supported).
4515 MockRead("Proxy-Authenticate: Basic invalid\r\n"), // Malformed.
4516 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
4517 MockRead("Proxy-Authenticate: UNSUPPORTED realm=\"FOO\"\r\n"),
4518 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
4519 // Large content-length -- won't matter, as connection will be reset.
4520 MockRead("Content-Length: 10000\r\n\r\n"),
4521 MockRead(SYNCHRONOUS, ERR_FAILED),
4524 // After calling trans->RestartWithAuth() the first time, this is the
4525 // request we should be issuing -- the final header line contains the
4526 // proxy's credentials.
4527 MockWrite data_writes2[] = {
4528 MockWrite("GET http://www.google.com/ HTTP/1.1\r\n"
4529 "Host: www.google.com\r\n"
4530 "Proxy-Connection: keep-alive\r\n"
4531 "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
4534 // Now the proxy server lets the request pass through to origin server.
4535 // The origin server responds with a 401.
4536 MockRead data_reads2[] = {
4537 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
4538 // Note: We are using the same realm-name as the proxy server. This is
4539 // completely valid, as realms are unique across hosts.
4540 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
4541 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
4542 MockRead("Content-Length: 2000\r\n\r\n"),
4543 MockRead(SYNCHRONOUS, ERR_FAILED), // Won't be reached.
4546 // After calling trans->RestartWithAuth() the second time, we should send
4547 // the credentials for both the proxy and origin server.
4548 MockWrite data_writes3[] = {
4549 MockWrite("GET http://www.google.com/ HTTP/1.1\r\n"
4550 "Host: www.google.com\r\n"
4551 "Proxy-Connection: keep-alive\r\n"
4552 "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n"
4553 "Authorization: Basic Zm9vMjpiYXIy\r\n\r\n"),
4556 // Lastly we get the desired content.
4557 MockRead data_reads3[] = {
4558 MockRead("HTTP/1.0 200 OK\r\n"),
4559 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
4560 MockRead("Content-Length: 100\r\n\r\n"),
4561 MockRead(SYNCHRONOUS, OK),
4564 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
4565 data_writes1, arraysize(data_writes1));
4566 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
4567 data_writes2, arraysize(data_writes2));
4568 StaticSocketDataProvider data3(data_reads3, arraysize(data_reads3),
4569 data_writes3, arraysize(data_writes3));
4570 session_deps_.socket_factory->AddSocketDataProvider(&data1);
4571 session_deps_.socket_factory->AddSocketDataProvider(&data2);
4572 session_deps_.socket_factory->AddSocketDataProvider(&data3);
4574 TestCompletionCallback callback1;
4576 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
4577 EXPECT_EQ(ERR_IO_PENDING, rv);
4579 rv = callback1.WaitForResult();
4580 EXPECT_EQ(OK, rv);
4582 const HttpResponseInfo* response = trans->GetResponseInfo();
4583 ASSERT_TRUE(response != NULL);
4584 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
4586 TestCompletionCallback callback2;
4588 rv = trans->RestartWithAuth(
4589 AuthCredentials(kFoo, kBar), callback2.callback());
4590 EXPECT_EQ(ERR_IO_PENDING, rv);
4592 rv = callback2.WaitForResult();
4593 EXPECT_EQ(OK, rv);
4595 response = trans->GetResponseInfo();
4596 ASSERT_TRUE(response != NULL);
4597 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
4599 TestCompletionCallback callback3;
4601 rv = trans->RestartWithAuth(
4602 AuthCredentials(kFoo2, kBar2), callback3.callback());
4603 EXPECT_EQ(ERR_IO_PENDING, rv);
4605 rv = callback3.WaitForResult();
4606 EXPECT_EQ(OK, rv);
4608 response = trans->GetResponseInfo();
4609 EXPECT_TRUE(response->auth_challenge.get() == NULL);
4610 EXPECT_EQ(100, response->headers->GetContentLength());
4613 // For the NTLM implementation using SSPI, we skip the NTLM tests since we
4614 // can't hook into its internals to cause it to generate predictable NTLM
4615 // authorization headers.
4616 #if defined(NTLM_PORTABLE)
4617 // The NTLM authentication unit tests were generated by capturing the HTTP
4618 // requests and responses using Fiddler 2 and inspecting the generated random
4619 // bytes in the debugger.
4621 // Enter the correct password and authenticate successfully.
4622 TEST_P(HttpNetworkTransactionTest, NTLMAuth1) {
4623 HttpRequestInfo request;
4624 request.method = "GET";
4625 request.url = GURL("http://172.22.68.17/kids/login.aspx");
4627 // Ensure load is not disrupted by flags which suppress behaviour specific
4628 // to other auth schemes.
4629 request.load_flags = LOAD_DO_NOT_USE_EMBEDDED_IDENTITY;
4631 HttpAuthHandlerNTLM::ScopedProcSetter proc_setter(MockGenerateRandom1,
4632 MockGetHostName);
4633 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
4635 MockWrite data_writes1[] = {
4636 MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
4637 "Host: 172.22.68.17\r\n"
4638 "Connection: keep-alive\r\n\r\n"),
4641 MockRead data_reads1[] = {
4642 MockRead("HTTP/1.1 401 Access Denied\r\n"),
4643 // Negotiate and NTLM are often requested together. However, we only want
4644 // to test NTLM. Since Negotiate is preferred over NTLM, we have to skip
4645 // the header that requests Negotiate for this test.
4646 MockRead("WWW-Authenticate: NTLM\r\n"),
4647 MockRead("Connection: close\r\n"),
4648 MockRead("Content-Length: 42\r\n"),
4649 MockRead("Content-Type: text/html\r\n\r\n"),
4650 // Missing content -- won't matter, as connection will be reset.
4651 MockRead(SYNCHRONOUS, ERR_UNEXPECTED),
4654 MockWrite data_writes2[] = {
4655 // After restarting with a null identity, this is the
4656 // request we should be issuing -- the final header line contains a Type
4657 // 1 message.
4658 MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
4659 "Host: 172.22.68.17\r\n"
4660 "Connection: keep-alive\r\n"
4661 "Authorization: NTLM "
4662 "TlRMTVNTUAABAAAAB4IIAAAAAAAAAAAAAAAAAAAAAAA=\r\n\r\n"),
4664 // After calling trans->RestartWithAuth(), we should send a Type 3 message
4665 // (the credentials for the origin server). The second request continues
4666 // on the same connection.
4667 MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
4668 "Host: 172.22.68.17\r\n"
4669 "Connection: keep-alive\r\n"
4670 "Authorization: NTLM TlRMTVNTUAADAAAAGAAYAGgAAAAYABgAgA"
4671 "AAAAAAAABAAAAAGAAYAEAAAAAQABAAWAAAAAAAAAAAAAAABYIIAHQA"
4672 "ZQBzAHQAaQBuAGcALQBuAHQAbABtAFcAVABDAC0AVwBJAE4ANwBVKW"
4673 "Yma5xzVAAAAAAAAAAAAAAAAAAAAACH+gWcm+YsP9Tqb9zCR3WAeZZX"
4674 "ahlhx5I=\r\n\r\n"),
4677 MockRead data_reads2[] = {
4678 // The origin server responds with a Type 2 message.
4679 MockRead("HTTP/1.1 401 Access Denied\r\n"),
4680 MockRead("WWW-Authenticate: NTLM "
4681 "TlRMTVNTUAACAAAADAAMADgAAAAFgokCjGpMpPGlYKkAAAAAAAAAALo"
4682 "AugBEAAAABQEoCgAAAA9HAE8ATwBHAEwARQACAAwARwBPAE8ARwBMAE"
4683 "UAAQAaAEEASwBFAEUAUwBBAFIAQQAtAEMATwBSAFAABAAeAGMAbwByA"
4684 "HAALgBnAG8AbwBnAGwAZQAuAGMAbwBtAAMAQABhAGsAZQBlAHMAYQBy"
4685 "AGEALQBjAG8AcgBwAC4AYQBkAC4AYwBvAHIAcAAuAGcAbwBvAGcAbAB"
4686 "lAC4AYwBvAG0ABQAeAGMAbwByAHAALgBnAG8AbwBnAGwAZQAuAGMAbw"
4687 "BtAAAAAAA=\r\n"),
4688 MockRead("Content-Length: 42\r\n"),
4689 MockRead("Content-Type: text/html\r\n\r\n"),
4690 MockRead("You are not authorized to view this page\r\n"),
4692 // Lastly we get the desired content.
4693 MockRead("HTTP/1.1 200 OK\r\n"),
4694 MockRead("Content-Type: text/html; charset=utf-8\r\n"),
4695 MockRead("Content-Length: 13\r\n\r\n"),
4696 MockRead("Please Login\r\n"),
4697 MockRead(SYNCHRONOUS, OK),
4700 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
4701 data_writes1, arraysize(data_writes1));
4702 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
4703 data_writes2, arraysize(data_writes2));
4704 session_deps_.socket_factory->AddSocketDataProvider(&data1);
4705 session_deps_.socket_factory->AddSocketDataProvider(&data2);
4707 TestCompletionCallback callback1;
4709 scoped_ptr<HttpTransaction> trans(
4710 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4712 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
4713 EXPECT_EQ(ERR_IO_PENDING, rv);
4715 rv = callback1.WaitForResult();
4716 EXPECT_EQ(OK, rv);
4718 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
4720 const HttpResponseInfo* response = trans->GetResponseInfo();
4721 ASSERT_FALSE(response == NULL);
4722 EXPECT_TRUE(CheckNTLMServerAuth(response->auth_challenge.get()));
4724 TestCompletionCallback callback2;
4726 rv = trans->RestartWithAuth(AuthCredentials(kTestingNTLM, kTestingNTLM),
4727 callback2.callback());
4728 EXPECT_EQ(ERR_IO_PENDING, rv);
4730 rv = callback2.WaitForResult();
4731 EXPECT_EQ(OK, rv);
4733 EXPECT_TRUE(trans->IsReadyToRestartForAuth());
4735 response = trans->GetResponseInfo();
4736 ASSERT_TRUE(response != NULL);
4737 EXPECT_TRUE(response->auth_challenge.get() == NULL);
4739 TestCompletionCallback callback3;
4741 rv = trans->RestartWithAuth(AuthCredentials(), callback3.callback());
4742 EXPECT_EQ(ERR_IO_PENDING, rv);
4744 rv = callback3.WaitForResult();
4745 EXPECT_EQ(OK, rv);
4747 response = trans->GetResponseInfo();
4748 ASSERT_TRUE(response != NULL);
4749 EXPECT_TRUE(response->auth_challenge.get() == NULL);
4750 EXPECT_EQ(13, response->headers->GetContentLength());
4753 // Enter a wrong password, and then the correct one.
4754 TEST_P(HttpNetworkTransactionTest, NTLMAuth2) {
4755 HttpRequestInfo request;
4756 request.method = "GET";
4757 request.url = GURL("http://172.22.68.17/kids/login.aspx");
4758 request.load_flags = 0;
4760 HttpAuthHandlerNTLM::ScopedProcSetter proc_setter(MockGenerateRandom2,
4761 MockGetHostName);
4762 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
4764 MockWrite data_writes1[] = {
4765 MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
4766 "Host: 172.22.68.17\r\n"
4767 "Connection: keep-alive\r\n\r\n"),
4770 MockRead data_reads1[] = {
4771 MockRead("HTTP/1.1 401 Access Denied\r\n"),
4772 // Negotiate and NTLM are often requested together. However, we only want
4773 // to test NTLM. Since Negotiate is preferred over NTLM, we have to skip
4774 // the header that requests Negotiate for this test.
4775 MockRead("WWW-Authenticate: NTLM\r\n"),
4776 MockRead("Connection: close\r\n"),
4777 MockRead("Content-Length: 42\r\n"),
4778 MockRead("Content-Type: text/html\r\n\r\n"),
4779 // Missing content -- won't matter, as connection will be reset.
4780 MockRead(SYNCHRONOUS, ERR_UNEXPECTED),
4783 MockWrite data_writes2[] = {
4784 // After restarting with a null identity, this is the
4785 // request we should be issuing -- the final header line contains a Type
4786 // 1 message.
4787 MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
4788 "Host: 172.22.68.17\r\n"
4789 "Connection: keep-alive\r\n"
4790 "Authorization: NTLM "
4791 "TlRMTVNTUAABAAAAB4IIAAAAAAAAAAAAAAAAAAAAAAA=\r\n\r\n"),
4793 // After calling trans->RestartWithAuth(), we should send a Type 3 message
4794 // (the credentials for the origin server). The second request continues
4795 // on the same connection.
4796 MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
4797 "Host: 172.22.68.17\r\n"
4798 "Connection: keep-alive\r\n"
4799 "Authorization: NTLM TlRMTVNTUAADAAAAGAAYAGgAAAAYABgAgA"
4800 "AAAAAAAABAAAAAGAAYAEAAAAAQABAAWAAAAAAAAAAAAAAABYIIAHQA"
4801 "ZQBzAHQAaQBuAGcALQBuAHQAbABtAFcAVABDAC0AVwBJAE4ANwCWeY"
4802 "XnSZNwoQAAAAAAAAAAAAAAAAAAAADLa34/phTTKzNTWdub+uyFleOj"
4803 "4Ww7b7E=\r\n\r\n"),
4806 MockRead data_reads2[] = {
4807 // The origin server responds with a Type 2 message.
4808 MockRead("HTTP/1.1 401 Access Denied\r\n"),
4809 MockRead("WWW-Authenticate: NTLM "
4810 "TlRMTVNTUAACAAAADAAMADgAAAAFgokCbVWUZezVGpAAAAAAAAAAALo"
4811 "AugBEAAAABQEoCgAAAA9HAE8ATwBHAEwARQACAAwARwBPAE8ARwBMAE"
4812 "UAAQAaAEEASwBFAEUAUwBBAFIAQQAtAEMATwBSAFAABAAeAGMAbwByA"
4813 "HAALgBnAG8AbwBnAGwAZQAuAGMAbwBtAAMAQABhAGsAZQBlAHMAYQBy"
4814 "AGEALQBjAG8AcgBwAC4AYQBkAC4AYwBvAHIAcAAuAGcAbwBvAGcAbAB"
4815 "lAC4AYwBvAG0ABQAeAGMAbwByAHAALgBnAG8AbwBnAGwAZQAuAGMAbw"
4816 "BtAAAAAAA=\r\n"),
4817 MockRead("Content-Length: 42\r\n"),
4818 MockRead("Content-Type: text/html\r\n\r\n"),
4819 MockRead("You are not authorized to view this page\r\n"),
4821 // Wrong password.
4822 MockRead("HTTP/1.1 401 Access Denied\r\n"),
4823 MockRead("WWW-Authenticate: NTLM\r\n"),
4824 MockRead("Connection: close\r\n"),
4825 MockRead("Content-Length: 42\r\n"),
4826 MockRead("Content-Type: text/html\r\n\r\n"),
4827 // Missing content -- won't matter, as connection will be reset.
4828 MockRead(SYNCHRONOUS, ERR_UNEXPECTED),
4831 MockWrite data_writes3[] = {
4832 // After restarting with a null identity, this is the
4833 // request we should be issuing -- the final header line contains a Type
4834 // 1 message.
4835 MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
4836 "Host: 172.22.68.17\r\n"
4837 "Connection: keep-alive\r\n"
4838 "Authorization: NTLM "
4839 "TlRMTVNTUAABAAAAB4IIAAAAAAAAAAAAAAAAAAAAAAA=\r\n\r\n"),
4841 // After calling trans->RestartWithAuth(), we should send a Type 3 message
4842 // (the credentials for the origin server). The second request continues
4843 // on the same connection.
4844 MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
4845 "Host: 172.22.68.17\r\n"
4846 "Connection: keep-alive\r\n"
4847 "Authorization: NTLM TlRMTVNTUAADAAAAGAAYAGgAAAAYABgAgA"
4848 "AAAAAAAABAAAAAGAAYAEAAAAAQABAAWAAAAAAAAAAAAAAABYIIAHQA"
4849 "ZQBzAHQAaQBuAGcALQBuAHQAbABtAFcAVABDAC0AVwBJAE4ANwBO54"
4850 "dFMVvTHwAAAAAAAAAAAAAAAAAAAACS7sT6Uzw7L0L//WUqlIaVWpbI"
4851 "+4MUm7c=\r\n\r\n"),
4854 MockRead data_reads3[] = {
4855 // The origin server responds with a Type 2 message.
4856 MockRead("HTTP/1.1 401 Access Denied\r\n"),
4857 MockRead("WWW-Authenticate: NTLM "
4858 "TlRMTVNTUAACAAAADAAMADgAAAAFgokCL24VN8dgOR8AAAAAAAAAALo"
4859 "AugBEAAAABQEoCgAAAA9HAE8ATwBHAEwARQACAAwARwBPAE8ARwBMAE"
4860 "UAAQAaAEEASwBFAEUAUwBBAFIAQQAtAEMATwBSAFAABAAeAGMAbwByA"
4861 "HAALgBnAG8AbwBnAGwAZQAuAGMAbwBtAAMAQABhAGsAZQBlAHMAYQBy"
4862 "AGEALQBjAG8AcgBwAC4AYQBkAC4AYwBvAHIAcAAuAGcAbwBvAGcAbAB"
4863 "lAC4AYwBvAG0ABQAeAGMAbwByAHAALgBnAG8AbwBnAGwAZQAuAGMAbw"
4864 "BtAAAAAAA=\r\n"),
4865 MockRead("Content-Length: 42\r\n"),
4866 MockRead("Content-Type: text/html\r\n\r\n"),
4867 MockRead("You are not authorized to view this page\r\n"),
4869 // Lastly we get the desired content.
4870 MockRead("HTTP/1.1 200 OK\r\n"),
4871 MockRead("Content-Type: text/html; charset=utf-8\r\n"),
4872 MockRead("Content-Length: 13\r\n\r\n"),
4873 MockRead("Please Login\r\n"),
4874 MockRead(SYNCHRONOUS, OK),
4877 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
4878 data_writes1, arraysize(data_writes1));
4879 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
4880 data_writes2, arraysize(data_writes2));
4881 StaticSocketDataProvider data3(data_reads3, arraysize(data_reads3),
4882 data_writes3, arraysize(data_writes3));
4883 session_deps_.socket_factory->AddSocketDataProvider(&data1);
4884 session_deps_.socket_factory->AddSocketDataProvider(&data2);
4885 session_deps_.socket_factory->AddSocketDataProvider(&data3);
4887 TestCompletionCallback callback1;
4889 scoped_ptr<HttpTransaction> trans(
4890 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4892 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
4893 EXPECT_EQ(ERR_IO_PENDING, rv);
4895 rv = callback1.WaitForResult();
4896 EXPECT_EQ(OK, rv);
4898 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
4900 const HttpResponseInfo* response = trans->GetResponseInfo();
4901 ASSERT_TRUE(response != NULL);
4902 EXPECT_TRUE(CheckNTLMServerAuth(response->auth_challenge.get()));
4904 TestCompletionCallback callback2;
4906 // Enter the wrong password.
4907 rv = trans->RestartWithAuth(AuthCredentials(kTestingNTLM, kWrongPassword),
4908 callback2.callback());
4909 EXPECT_EQ(ERR_IO_PENDING, rv);
4911 rv = callback2.WaitForResult();
4912 EXPECT_EQ(OK, rv);
4914 EXPECT_TRUE(trans->IsReadyToRestartForAuth());
4915 TestCompletionCallback callback3;
4916 rv = trans->RestartWithAuth(AuthCredentials(), callback3.callback());
4917 EXPECT_EQ(ERR_IO_PENDING, rv);
4918 rv = callback3.WaitForResult();
4919 EXPECT_EQ(OK, rv);
4920 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
4922 response = trans->GetResponseInfo();
4923 ASSERT_FALSE(response == NULL);
4924 EXPECT_TRUE(CheckNTLMServerAuth(response->auth_challenge.get()));
4926 TestCompletionCallback callback4;
4928 // Now enter the right password.
4929 rv = trans->RestartWithAuth(AuthCredentials(kTestingNTLM, kTestingNTLM),
4930 callback4.callback());
4931 EXPECT_EQ(ERR_IO_PENDING, rv);
4933 rv = callback4.WaitForResult();
4934 EXPECT_EQ(OK, rv);
4936 EXPECT_TRUE(trans->IsReadyToRestartForAuth());
4938 TestCompletionCallback callback5;
4940 // One more roundtrip
4941 rv = trans->RestartWithAuth(AuthCredentials(), callback5.callback());
4942 EXPECT_EQ(ERR_IO_PENDING, rv);
4944 rv = callback5.WaitForResult();
4945 EXPECT_EQ(OK, rv);
4947 response = trans->GetResponseInfo();
4948 EXPECT_TRUE(response->auth_challenge.get() == NULL);
4949 EXPECT_EQ(13, response->headers->GetContentLength());
4951 #endif // NTLM_PORTABLE
4953 // Test reading a server response which has only headers, and no body.
4954 // After some maximum number of bytes is consumed, the transaction should
4955 // fail with ERR_RESPONSE_HEADERS_TOO_BIG.
4956 TEST_P(HttpNetworkTransactionTest, LargeHeadersNoBody) {
4957 HttpRequestInfo request;
4958 request.method = "GET";
4959 request.url = GURL("http://www.google.com/");
4960 request.load_flags = 0;
4962 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
4963 scoped_ptr<HttpTransaction> trans(
4964 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
4966 // Respond with 300 kb of headers (we should fail after 256 kb).
4967 std::string large_headers_string;
4968 FillLargeHeadersString(&large_headers_string, 300 * 1024);
4970 MockRead data_reads[] = {
4971 MockRead("HTTP/1.0 200 OK\r\n"),
4972 MockRead(ASYNC, large_headers_string.data(), large_headers_string.size()),
4973 MockRead("\r\nBODY"),
4974 MockRead(SYNCHRONOUS, OK),
4976 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
4977 session_deps_.socket_factory->AddSocketDataProvider(&data);
4979 TestCompletionCallback callback;
4981 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
4982 EXPECT_EQ(ERR_IO_PENDING, rv);
4984 rv = callback.WaitForResult();
4985 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, rv);
4987 const HttpResponseInfo* response = trans->GetResponseInfo();
4988 EXPECT_TRUE(response == NULL);
4991 // Make sure that we don't try to reuse a TCPClientSocket when failing to
4992 // establish tunnel.
4993 // http://code.google.com/p/chromium/issues/detail?id=3772
4994 TEST_P(HttpNetworkTransactionTest,
4995 DontRecycleTransportSocketForSSLTunnel) {
4996 HttpRequestInfo request;
4997 request.method = "GET";
4998 request.url = GURL("https://www.google.com/");
4999 request.load_flags = 0;
5001 // Configure against proxy server "myproxy:70".
5002 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
5004 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5006 scoped_ptr<HttpTransaction> trans(
5007 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5009 // Since we have proxy, should try to establish tunnel.
5010 MockWrite data_writes1[] = {
5011 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
5012 "Host: www.google.com\r\n"
5013 "Proxy-Connection: keep-alive\r\n\r\n"),
5016 // The proxy responds to the connect with a 404, using a persistent
5017 // connection. Usually a proxy would return 501 (not implemented),
5018 // or 200 (tunnel established).
5019 MockRead data_reads1[] = {
5020 MockRead("HTTP/1.1 404 Not Found\r\n"),
5021 MockRead("Content-Length: 10\r\n\r\n"),
5022 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
5025 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
5026 data_writes1, arraysize(data_writes1));
5027 session_deps_.socket_factory->AddSocketDataProvider(&data1);
5029 TestCompletionCallback callback1;
5031 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
5032 EXPECT_EQ(ERR_IO_PENDING, rv);
5034 rv = callback1.WaitForResult();
5035 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, rv);
5037 const HttpResponseInfo* response = trans->GetResponseInfo();
5038 EXPECT_TRUE(response == NULL);
5040 // Empty the current queue. This is necessary because idle sockets are
5041 // added to the connection pool asynchronously with a PostTask.
5042 base::MessageLoop::current()->RunUntilIdle();
5044 // We now check to make sure the TCPClientSocket was not added back to
5045 // the pool.
5046 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
5047 trans.reset();
5048 base::MessageLoop::current()->RunUntilIdle();
5049 // Make sure that the socket didn't get recycled after calling the destructor.
5050 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
5053 // Make sure that we recycle a socket after reading all of the response body.
5054 TEST_P(HttpNetworkTransactionTest, RecycleSocket) {
5055 HttpRequestInfo request;
5056 request.method = "GET";
5057 request.url = GURL("http://www.google.com/");
5058 request.load_flags = 0;
5060 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5062 scoped_ptr<HttpTransaction> trans(
5063 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5065 MockRead data_reads[] = {
5066 // A part of the response body is received with the response headers.
5067 MockRead("HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nhel"),
5068 // The rest of the response body is received in two parts.
5069 MockRead("lo"),
5070 MockRead(" world"),
5071 MockRead("junk"), // Should not be read!!
5072 MockRead(SYNCHRONOUS, OK),
5075 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
5076 session_deps_.socket_factory->AddSocketDataProvider(&data);
5078 TestCompletionCallback callback;
5080 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
5081 EXPECT_EQ(ERR_IO_PENDING, rv);
5083 rv = callback.WaitForResult();
5084 EXPECT_EQ(OK, rv);
5086 const HttpResponseInfo* response = trans->GetResponseInfo();
5087 ASSERT_TRUE(response != NULL);
5089 EXPECT_TRUE(response->headers.get() != NULL);
5090 std::string status_line = response->headers->GetStatusLine();
5091 EXPECT_EQ("HTTP/1.1 200 OK", status_line);
5093 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
5095 std::string response_data;
5096 rv = ReadTransaction(trans.get(), &response_data);
5097 EXPECT_EQ(OK, rv);
5098 EXPECT_EQ("hello world", response_data);
5100 // Empty the current queue. This is necessary because idle sockets are
5101 // added to the connection pool asynchronously with a PostTask.
5102 base::MessageLoop::current()->RunUntilIdle();
5104 // We now check to make sure the socket was added back to the pool.
5105 EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
5108 // Make sure that we recycle a SSL socket after reading all of the response
5109 // body.
5110 TEST_P(HttpNetworkTransactionTest, RecycleSSLSocket) {
5111 HttpRequestInfo request;
5112 request.method = "GET";
5113 request.url = GURL("https://www.google.com/");
5114 request.load_flags = 0;
5116 MockWrite data_writes[] = {
5117 MockWrite("GET / HTTP/1.1\r\n"
5118 "Host: www.google.com\r\n"
5119 "Connection: keep-alive\r\n\r\n"),
5122 MockRead data_reads[] = {
5123 MockRead("HTTP/1.1 200 OK\r\n"),
5124 MockRead("Content-Length: 11\r\n\r\n"),
5125 MockRead("hello world"),
5126 MockRead(SYNCHRONOUS, OK),
5129 SSLSocketDataProvider ssl(ASYNC, OK);
5130 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
5132 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
5133 data_writes, arraysize(data_writes));
5134 session_deps_.socket_factory->AddSocketDataProvider(&data);
5136 TestCompletionCallback callback;
5138 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5139 scoped_ptr<HttpTransaction> trans(
5140 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5142 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
5144 EXPECT_EQ(ERR_IO_PENDING, rv);
5145 EXPECT_EQ(OK, callback.WaitForResult());
5147 const HttpResponseInfo* response = trans->GetResponseInfo();
5148 ASSERT_TRUE(response != NULL);
5149 ASSERT_TRUE(response->headers.get() != NULL);
5150 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
5152 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
5154 std::string response_data;
5155 rv = ReadTransaction(trans.get(), &response_data);
5156 EXPECT_EQ(OK, rv);
5157 EXPECT_EQ("hello world", response_data);
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 socket was added back to the pool.
5164 EXPECT_EQ(1, GetIdleSocketCountInSSLSocketPool(session.get()));
5167 // Grab a SSL socket, use it, and put it back into the pool. Then, reuse it
5168 // from the pool and make sure that we recover okay.
5169 TEST_P(HttpNetworkTransactionTest, RecycleDeadSSLSocket) {
5170 HttpRequestInfo request;
5171 request.method = "GET";
5172 request.url = GURL("https://www.google.com/");
5173 request.load_flags = 0;
5175 MockWrite data_writes[] = {
5176 MockWrite("GET / HTTP/1.1\r\n"
5177 "Host: www.google.com\r\n"
5178 "Connection: keep-alive\r\n\r\n"),
5179 MockWrite("GET / HTTP/1.1\r\n"
5180 "Host: www.google.com\r\n"
5181 "Connection: keep-alive\r\n\r\n"),
5184 MockRead data_reads[] = {
5185 MockRead("HTTP/1.1 200 OK\r\n"),
5186 MockRead("Content-Length: 11\r\n\r\n"),
5187 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
5188 MockRead("hello world"),
5189 MockRead(ASYNC, 0, 0) // EOF
5192 SSLSocketDataProvider ssl(ASYNC, OK);
5193 SSLSocketDataProvider ssl2(ASYNC, OK);
5194 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
5195 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
5197 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
5198 data_writes, arraysize(data_writes));
5199 StaticSocketDataProvider data2(data_reads, arraysize(data_reads),
5200 data_writes, arraysize(data_writes));
5201 session_deps_.socket_factory->AddSocketDataProvider(&data);
5202 session_deps_.socket_factory->AddSocketDataProvider(&data2);
5204 TestCompletionCallback callback;
5206 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5207 scoped_ptr<HttpTransaction> trans(
5208 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5210 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
5212 EXPECT_EQ(ERR_IO_PENDING, rv);
5213 EXPECT_EQ(OK, callback.WaitForResult());
5215 const HttpResponseInfo* response = trans->GetResponseInfo();
5216 ASSERT_TRUE(response != NULL);
5217 ASSERT_TRUE(response->headers.get() != NULL);
5218 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
5220 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
5222 std::string response_data;
5223 rv = ReadTransaction(trans.get(), &response_data);
5224 EXPECT_EQ(OK, rv);
5225 EXPECT_EQ("hello world", response_data);
5227 // Empty the current queue. This is necessary because idle sockets are
5228 // added to the connection pool asynchronously with a PostTask.
5229 base::MessageLoop::current()->RunUntilIdle();
5231 // We now check to make sure the socket was added back to the pool.
5232 EXPECT_EQ(1, GetIdleSocketCountInSSLSocketPool(session.get()));
5234 // Now start the second transaction, which should reuse the previous socket.
5236 trans.reset(new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5238 rv = trans->Start(&request, callback.callback(), BoundNetLog());
5240 EXPECT_EQ(ERR_IO_PENDING, rv);
5241 EXPECT_EQ(OK, callback.WaitForResult());
5243 response = trans->GetResponseInfo();
5244 ASSERT_TRUE(response != NULL);
5245 ASSERT_TRUE(response->headers.get() != NULL);
5246 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
5248 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
5250 rv = ReadTransaction(trans.get(), &response_data);
5251 EXPECT_EQ(OK, rv);
5252 EXPECT_EQ("hello world", response_data);
5254 // Empty the current queue. This is necessary because idle sockets are
5255 // added to the connection pool asynchronously with a PostTask.
5256 base::MessageLoop::current()->RunUntilIdle();
5258 // We now check to make sure the socket was added back to the pool.
5259 EXPECT_EQ(1, GetIdleSocketCountInSSLSocketPool(session.get()));
5262 // Make sure that we recycle a socket after a zero-length response.
5263 // http://crbug.com/9880
5264 TEST_P(HttpNetworkTransactionTest, RecycleSocketAfterZeroContentLength) {
5265 HttpRequestInfo request;
5266 request.method = "GET";
5267 request.url = GURL("http://www.google.com/csi?v=3&s=web&action=&"
5268 "tran=undefined&ei=mAXcSeegAo-SMurloeUN&"
5269 "e=17259,18167,19592,19773,19981,20133,20173,20233&"
5270 "rt=prt.2642,ol.2649,xjs.2951");
5271 request.load_flags = 0;
5273 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5275 scoped_ptr<HttpTransaction> trans(
5276 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5278 MockRead data_reads[] = {
5279 MockRead("HTTP/1.1 204 No Content\r\n"
5280 "Content-Length: 0\r\n"
5281 "Content-Type: text/html\r\n\r\n"),
5282 MockRead("junk"), // Should not be read!!
5283 MockRead(SYNCHRONOUS, OK),
5286 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
5287 session_deps_.socket_factory->AddSocketDataProvider(&data);
5289 TestCompletionCallback callback;
5291 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
5292 EXPECT_EQ(ERR_IO_PENDING, rv);
5294 rv = callback.WaitForResult();
5295 EXPECT_EQ(OK, rv);
5297 const HttpResponseInfo* response = trans->GetResponseInfo();
5298 ASSERT_TRUE(response != NULL);
5300 EXPECT_TRUE(response->headers.get() != NULL);
5301 std::string status_line = response->headers->GetStatusLine();
5302 EXPECT_EQ("HTTP/1.1 204 No Content", status_line);
5304 EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
5306 std::string response_data;
5307 rv = ReadTransaction(trans.get(), &response_data);
5308 EXPECT_EQ(OK, rv);
5309 EXPECT_EQ("", response_data);
5311 // Empty the current queue. This is necessary because idle sockets are
5312 // added to the connection pool asynchronously with a PostTask.
5313 base::MessageLoop::current()->RunUntilIdle();
5315 // We now check to make sure the socket was added back to the pool.
5316 EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
5319 TEST_P(HttpNetworkTransactionTest, ResendRequestOnWriteBodyError) {
5320 ScopedVector<UploadElementReader> element_readers;
5321 element_readers.push_back(new UploadBytesElementReader("foo", 3));
5322 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
5324 HttpRequestInfo request[2];
5325 // Transaction 1: a GET request that succeeds. The socket is recycled
5326 // after use.
5327 request[0].method = "GET";
5328 request[0].url = GURL("http://www.google.com/");
5329 request[0].load_flags = 0;
5330 // Transaction 2: a POST request. Reuses the socket kept alive from
5331 // transaction 1. The first attempts fails when writing the POST data.
5332 // This causes the transaction to retry with a new socket. The second
5333 // attempt succeeds.
5334 request[1].method = "POST";
5335 request[1].url = GURL("http://www.google.com/login.cgi");
5336 request[1].upload_data_stream = &upload_data_stream;
5337 request[1].load_flags = 0;
5339 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5341 // The first socket is used for transaction 1 and the first attempt of
5342 // transaction 2.
5344 // The response of transaction 1.
5345 MockRead data_reads1[] = {
5346 MockRead("HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\n"),
5347 MockRead("hello world"),
5348 MockRead(SYNCHRONOUS, OK),
5350 // The mock write results of transaction 1 and the first attempt of
5351 // transaction 2.
5352 MockWrite data_writes1[] = {
5353 MockWrite(SYNCHRONOUS, 64), // GET
5354 MockWrite(SYNCHRONOUS, 93), // POST
5355 MockWrite(SYNCHRONOUS, ERR_CONNECTION_ABORTED), // POST data
5357 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
5358 data_writes1, arraysize(data_writes1));
5360 // The second socket is used for the second attempt of transaction 2.
5362 // The response of transaction 2.
5363 MockRead data_reads2[] = {
5364 MockRead("HTTP/1.1 200 OK\r\nContent-Length: 7\r\n\r\n"),
5365 MockRead("welcome"),
5366 MockRead(SYNCHRONOUS, OK),
5368 // The mock write results of the second attempt of transaction 2.
5369 MockWrite data_writes2[] = {
5370 MockWrite(SYNCHRONOUS, 93), // POST
5371 MockWrite(SYNCHRONOUS, 3), // POST data
5373 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
5374 data_writes2, arraysize(data_writes2));
5376 session_deps_.socket_factory->AddSocketDataProvider(&data1);
5377 session_deps_.socket_factory->AddSocketDataProvider(&data2);
5379 const char* const kExpectedResponseData[] = {
5380 "hello world", "welcome"
5383 for (int i = 0; i < 2; ++i) {
5384 scoped_ptr<HttpTransaction> trans(
5385 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5387 TestCompletionCallback callback;
5389 int rv = trans->Start(&request[i], callback.callback(), BoundNetLog());
5390 EXPECT_EQ(ERR_IO_PENDING, rv);
5392 rv = callback.WaitForResult();
5393 EXPECT_EQ(OK, rv);
5395 const HttpResponseInfo* response = trans->GetResponseInfo();
5396 ASSERT_TRUE(response != NULL);
5398 EXPECT_TRUE(response->headers.get() != NULL);
5399 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
5401 std::string response_data;
5402 rv = ReadTransaction(trans.get(), &response_data);
5403 EXPECT_EQ(OK, rv);
5404 EXPECT_EQ(kExpectedResponseData[i], response_data);
5408 // Test the request-challenge-retry sequence for basic auth when there is
5409 // an identity in the URL. The request should be sent as normal, but when
5410 // it fails the identity from the URL is used to answer the challenge.
5411 TEST_P(HttpNetworkTransactionTest, AuthIdentityInURL) {
5412 HttpRequestInfo request;
5413 request.method = "GET";
5414 request.url = GURL("http://foo:b@r@www.google.com/");
5415 request.load_flags = LOAD_NORMAL;
5417 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5418 scoped_ptr<HttpTransaction> trans(
5419 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5421 // The password contains an escaped character -- for this test to pass it
5422 // will need to be unescaped by HttpNetworkTransaction.
5423 EXPECT_EQ("b%40r", request.url.password());
5425 MockWrite data_writes1[] = {
5426 MockWrite("GET / HTTP/1.1\r\n"
5427 "Host: www.google.com\r\n"
5428 "Connection: keep-alive\r\n\r\n"),
5431 MockRead data_reads1[] = {
5432 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
5433 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
5434 MockRead("Content-Length: 10\r\n\r\n"),
5435 MockRead(SYNCHRONOUS, ERR_FAILED),
5438 // After the challenge above, the transaction will be restarted using the
5439 // identity from the url (foo, b@r) to answer the challenge.
5440 MockWrite data_writes2[] = {
5441 MockWrite("GET / HTTP/1.1\r\n"
5442 "Host: www.google.com\r\n"
5443 "Connection: keep-alive\r\n"
5444 "Authorization: Basic Zm9vOmJAcg==\r\n\r\n"),
5447 MockRead data_reads2[] = {
5448 MockRead("HTTP/1.0 200 OK\r\n"),
5449 MockRead("Content-Length: 100\r\n\r\n"),
5450 MockRead(SYNCHRONOUS, OK),
5453 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
5454 data_writes1, arraysize(data_writes1));
5455 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
5456 data_writes2, arraysize(data_writes2));
5457 session_deps_.socket_factory->AddSocketDataProvider(&data1);
5458 session_deps_.socket_factory->AddSocketDataProvider(&data2);
5460 TestCompletionCallback callback1;
5461 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
5462 EXPECT_EQ(ERR_IO_PENDING, rv);
5463 rv = callback1.WaitForResult();
5464 EXPECT_EQ(OK, rv);
5465 EXPECT_TRUE(trans->IsReadyToRestartForAuth());
5467 TestCompletionCallback callback2;
5468 rv = trans->RestartWithAuth(AuthCredentials(), callback2.callback());
5469 EXPECT_EQ(ERR_IO_PENDING, rv);
5470 rv = callback2.WaitForResult();
5471 EXPECT_EQ(OK, rv);
5472 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
5474 const HttpResponseInfo* response = trans->GetResponseInfo();
5475 ASSERT_TRUE(response != NULL);
5477 // There is no challenge info, since the identity in URL worked.
5478 EXPECT_TRUE(response->auth_challenge.get() == NULL);
5480 EXPECT_EQ(100, response->headers->GetContentLength());
5482 // Empty the current queue.
5483 base::MessageLoop::current()->RunUntilIdle();
5486 // Test the request-challenge-retry sequence for basic auth when there is an
5487 // incorrect identity in the URL. The identity from the URL should be used only
5488 // once.
5489 TEST_P(HttpNetworkTransactionTest, WrongAuthIdentityInURL) {
5490 HttpRequestInfo request;
5491 request.method = "GET";
5492 // Note: the URL has a username:password in it. The password "baz" is
5493 // wrong (should be "bar").
5494 request.url = GURL("http://foo:baz@www.google.com/");
5496 request.load_flags = LOAD_NORMAL;
5498 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5499 scoped_ptr<HttpTransaction> trans(
5500 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5502 MockWrite data_writes1[] = {
5503 MockWrite("GET / HTTP/1.1\r\n"
5504 "Host: www.google.com\r\n"
5505 "Connection: keep-alive\r\n\r\n"),
5508 MockRead data_reads1[] = {
5509 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
5510 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
5511 MockRead("Content-Length: 10\r\n\r\n"),
5512 MockRead(SYNCHRONOUS, ERR_FAILED),
5515 // After the challenge above, the transaction will be restarted using the
5516 // identity from the url (foo, baz) to answer the challenge.
5517 MockWrite data_writes2[] = {
5518 MockWrite("GET / HTTP/1.1\r\n"
5519 "Host: www.google.com\r\n"
5520 "Connection: keep-alive\r\n"
5521 "Authorization: Basic Zm9vOmJheg==\r\n\r\n"),
5524 MockRead data_reads2[] = {
5525 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
5526 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
5527 MockRead("Content-Length: 10\r\n\r\n"),
5528 MockRead(SYNCHRONOUS, ERR_FAILED),
5531 // After the challenge above, the transaction will be restarted using the
5532 // identity supplied by the user (foo, bar) to answer the challenge.
5533 MockWrite data_writes3[] = {
5534 MockWrite("GET / HTTP/1.1\r\n"
5535 "Host: www.google.com\r\n"
5536 "Connection: keep-alive\r\n"
5537 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
5540 MockRead data_reads3[] = {
5541 MockRead("HTTP/1.0 200 OK\r\n"),
5542 MockRead("Content-Length: 100\r\n\r\n"),
5543 MockRead(SYNCHRONOUS, OK),
5546 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
5547 data_writes1, arraysize(data_writes1));
5548 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
5549 data_writes2, arraysize(data_writes2));
5550 StaticSocketDataProvider data3(data_reads3, arraysize(data_reads3),
5551 data_writes3, arraysize(data_writes3));
5552 session_deps_.socket_factory->AddSocketDataProvider(&data1);
5553 session_deps_.socket_factory->AddSocketDataProvider(&data2);
5554 session_deps_.socket_factory->AddSocketDataProvider(&data3);
5556 TestCompletionCallback callback1;
5558 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
5559 EXPECT_EQ(ERR_IO_PENDING, rv);
5561 rv = callback1.WaitForResult();
5562 EXPECT_EQ(OK, rv);
5564 EXPECT_TRUE(trans->IsReadyToRestartForAuth());
5565 TestCompletionCallback callback2;
5566 rv = trans->RestartWithAuth(AuthCredentials(), callback2.callback());
5567 EXPECT_EQ(ERR_IO_PENDING, rv);
5568 rv = callback2.WaitForResult();
5569 EXPECT_EQ(OK, rv);
5570 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
5572 const HttpResponseInfo* response = trans->GetResponseInfo();
5573 ASSERT_TRUE(response != NULL);
5574 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
5576 TestCompletionCallback callback3;
5577 rv = trans->RestartWithAuth(
5578 AuthCredentials(kFoo, kBar), callback3.callback());
5579 EXPECT_EQ(ERR_IO_PENDING, rv);
5580 rv = callback3.WaitForResult();
5581 EXPECT_EQ(OK, rv);
5582 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
5584 response = trans->GetResponseInfo();
5585 ASSERT_TRUE(response != NULL);
5587 // There is no challenge info, since the identity worked.
5588 EXPECT_TRUE(response->auth_challenge.get() == NULL);
5590 EXPECT_EQ(100, response->headers->GetContentLength());
5592 // Empty the current queue.
5593 base::MessageLoop::current()->RunUntilIdle();
5597 // Test the request-challenge-retry sequence for basic auth when there is a
5598 // correct identity in the URL, but its use is being suppressed. The identity
5599 // from the URL should never be used.
5600 TEST_P(HttpNetworkTransactionTest, AuthIdentityInURLSuppressed) {
5601 HttpRequestInfo request;
5602 request.method = "GET";
5603 request.url = GURL("http://foo:bar@www.google.com/");
5604 request.load_flags = LOAD_DO_NOT_USE_EMBEDDED_IDENTITY;
5606 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5607 scoped_ptr<HttpTransaction> trans(
5608 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5610 MockWrite data_writes1[] = {
5611 MockWrite("GET / HTTP/1.1\r\n"
5612 "Host: www.google.com\r\n"
5613 "Connection: keep-alive\r\n\r\n"),
5616 MockRead data_reads1[] = {
5617 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
5618 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
5619 MockRead("Content-Length: 10\r\n\r\n"),
5620 MockRead(SYNCHRONOUS, ERR_FAILED),
5623 // After the challenge above, the transaction will be restarted using the
5624 // identity supplied by the user, not the one in the URL, to answer the
5625 // challenge.
5626 MockWrite data_writes3[] = {
5627 MockWrite("GET / HTTP/1.1\r\n"
5628 "Host: www.google.com\r\n"
5629 "Connection: keep-alive\r\n"
5630 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
5633 MockRead data_reads3[] = {
5634 MockRead("HTTP/1.0 200 OK\r\n"),
5635 MockRead("Content-Length: 100\r\n\r\n"),
5636 MockRead(SYNCHRONOUS, OK),
5639 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
5640 data_writes1, arraysize(data_writes1));
5641 StaticSocketDataProvider data3(data_reads3, arraysize(data_reads3),
5642 data_writes3, arraysize(data_writes3));
5643 session_deps_.socket_factory->AddSocketDataProvider(&data1);
5644 session_deps_.socket_factory->AddSocketDataProvider(&data3);
5646 TestCompletionCallback callback1;
5647 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
5648 EXPECT_EQ(ERR_IO_PENDING, rv);
5649 rv = callback1.WaitForResult();
5650 EXPECT_EQ(OK, rv);
5651 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
5653 const HttpResponseInfo* response = trans->GetResponseInfo();
5654 ASSERT_TRUE(response != NULL);
5655 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
5657 TestCompletionCallback callback3;
5658 rv = trans->RestartWithAuth(
5659 AuthCredentials(kFoo, kBar), callback3.callback());
5660 EXPECT_EQ(ERR_IO_PENDING, rv);
5661 rv = callback3.WaitForResult();
5662 EXPECT_EQ(OK, rv);
5663 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
5665 response = trans->GetResponseInfo();
5666 ASSERT_TRUE(response != NULL);
5668 // There is no challenge info, since the identity worked.
5669 EXPECT_TRUE(response->auth_challenge.get() == NULL);
5670 EXPECT_EQ(100, response->headers->GetContentLength());
5672 // Empty the current queue.
5673 base::MessageLoop::current()->RunUntilIdle();
5676 // Test that previously tried username/passwords for a realm get re-used.
5677 TEST_P(HttpNetworkTransactionTest, BasicAuthCacheAndPreauth) {
5678 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
5680 // Transaction 1: authenticate (foo, bar) on MyRealm1
5682 HttpRequestInfo request;
5683 request.method = "GET";
5684 request.url = GURL("http://www.google.com/x/y/z");
5685 request.load_flags = 0;
5687 scoped_ptr<HttpTransaction> trans(
5688 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5690 MockWrite data_writes1[] = {
5691 MockWrite("GET /x/y/z HTTP/1.1\r\n"
5692 "Host: www.google.com\r\n"
5693 "Connection: keep-alive\r\n\r\n"),
5696 MockRead data_reads1[] = {
5697 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
5698 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
5699 MockRead("Content-Length: 10000\r\n\r\n"),
5700 MockRead(SYNCHRONOUS, ERR_FAILED),
5703 // Resend with authorization (username=foo, password=bar)
5704 MockWrite data_writes2[] = {
5705 MockWrite("GET /x/y/z HTTP/1.1\r\n"
5706 "Host: www.google.com\r\n"
5707 "Connection: keep-alive\r\n"
5708 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
5711 // Sever accepts the authorization.
5712 MockRead data_reads2[] = {
5713 MockRead("HTTP/1.0 200 OK\r\n"),
5714 MockRead("Content-Length: 100\r\n\r\n"),
5715 MockRead(SYNCHRONOUS, OK),
5718 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
5719 data_writes1, arraysize(data_writes1));
5720 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
5721 data_writes2, arraysize(data_writes2));
5722 session_deps_.socket_factory->AddSocketDataProvider(&data1);
5723 session_deps_.socket_factory->AddSocketDataProvider(&data2);
5725 TestCompletionCallback callback1;
5727 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
5728 EXPECT_EQ(ERR_IO_PENDING, rv);
5730 rv = callback1.WaitForResult();
5731 EXPECT_EQ(OK, rv);
5733 const HttpResponseInfo* response = trans->GetResponseInfo();
5734 ASSERT_TRUE(response != NULL);
5735 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
5737 TestCompletionCallback callback2;
5739 rv = trans->RestartWithAuth(
5740 AuthCredentials(kFoo, kBar), callback2.callback());
5741 EXPECT_EQ(ERR_IO_PENDING, rv);
5743 rv = callback2.WaitForResult();
5744 EXPECT_EQ(OK, rv);
5746 response = trans->GetResponseInfo();
5747 ASSERT_TRUE(response != NULL);
5748 EXPECT_TRUE(response->auth_challenge.get() == NULL);
5749 EXPECT_EQ(100, response->headers->GetContentLength());
5752 // ------------------------------------------------------------------------
5754 // Transaction 2: authenticate (foo2, bar2) on MyRealm2
5756 HttpRequestInfo request;
5757 request.method = "GET";
5758 // Note that Transaction 1 was at /x/y/z, so this is in the same
5759 // protection space as MyRealm1.
5760 request.url = GURL("http://www.google.com/x/y/a/b");
5761 request.load_flags = 0;
5763 scoped_ptr<HttpTransaction> trans(
5764 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5766 MockWrite data_writes1[] = {
5767 MockWrite("GET /x/y/a/b HTTP/1.1\r\n"
5768 "Host: www.google.com\r\n"
5769 "Connection: keep-alive\r\n"
5770 // Send preemptive authorization for MyRealm1
5771 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
5774 // The server didn't like the preemptive authorization, and
5775 // challenges us for a different realm (MyRealm2).
5776 MockRead data_reads1[] = {
5777 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
5778 MockRead("WWW-Authenticate: Basic realm=\"MyRealm2\"\r\n"),
5779 MockRead("Content-Length: 10000\r\n\r\n"),
5780 MockRead(SYNCHRONOUS, ERR_FAILED),
5783 // Resend with authorization for MyRealm2 (username=foo2, password=bar2)
5784 MockWrite data_writes2[] = {
5785 MockWrite("GET /x/y/a/b HTTP/1.1\r\n"
5786 "Host: www.google.com\r\n"
5787 "Connection: keep-alive\r\n"
5788 "Authorization: Basic Zm9vMjpiYXIy\r\n\r\n"),
5791 // Sever accepts the authorization.
5792 MockRead data_reads2[] = {
5793 MockRead("HTTP/1.0 200 OK\r\n"),
5794 MockRead("Content-Length: 100\r\n\r\n"),
5795 MockRead(SYNCHRONOUS, OK),
5798 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
5799 data_writes1, arraysize(data_writes1));
5800 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
5801 data_writes2, arraysize(data_writes2));
5802 session_deps_.socket_factory->AddSocketDataProvider(&data1);
5803 session_deps_.socket_factory->AddSocketDataProvider(&data2);
5805 TestCompletionCallback callback1;
5807 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
5808 EXPECT_EQ(ERR_IO_PENDING, rv);
5810 rv = callback1.WaitForResult();
5811 EXPECT_EQ(OK, rv);
5813 const HttpResponseInfo* response = trans->GetResponseInfo();
5814 ASSERT_TRUE(response != NULL);
5815 ASSERT_TRUE(response->auth_challenge.get());
5816 EXPECT_FALSE(response->auth_challenge->is_proxy);
5817 EXPECT_EQ("www.google.com:80",
5818 response->auth_challenge->challenger.ToString());
5819 EXPECT_EQ("MyRealm2", response->auth_challenge->realm);
5820 EXPECT_EQ("basic", response->auth_challenge->scheme);
5822 TestCompletionCallback callback2;
5824 rv = trans->RestartWithAuth(
5825 AuthCredentials(kFoo2, kBar2), callback2.callback());
5826 EXPECT_EQ(ERR_IO_PENDING, rv);
5828 rv = callback2.WaitForResult();
5829 EXPECT_EQ(OK, rv);
5831 response = trans->GetResponseInfo();
5832 ASSERT_TRUE(response != NULL);
5833 EXPECT_TRUE(response->auth_challenge.get() == NULL);
5834 EXPECT_EQ(100, response->headers->GetContentLength());
5837 // ------------------------------------------------------------------------
5839 // Transaction 3: Resend a request in MyRealm's protection space --
5840 // succeed with preemptive authorization.
5842 HttpRequestInfo request;
5843 request.method = "GET";
5844 request.url = GURL("http://www.google.com/x/y/z2");
5845 request.load_flags = 0;
5847 scoped_ptr<HttpTransaction> trans(
5848 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5850 MockWrite data_writes1[] = {
5851 MockWrite("GET /x/y/z2 HTTP/1.1\r\n"
5852 "Host: www.google.com\r\n"
5853 "Connection: keep-alive\r\n"
5854 // The authorization for MyRealm1 gets sent preemptively
5855 // (since the url is in the same protection space)
5856 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
5859 // Sever accepts the preemptive authorization
5860 MockRead data_reads1[] = {
5861 MockRead("HTTP/1.0 200 OK\r\n"),
5862 MockRead("Content-Length: 100\r\n\r\n"),
5863 MockRead(SYNCHRONOUS, OK),
5866 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
5867 data_writes1, arraysize(data_writes1));
5868 session_deps_.socket_factory->AddSocketDataProvider(&data1);
5870 TestCompletionCallback callback1;
5872 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
5873 EXPECT_EQ(ERR_IO_PENDING, rv);
5875 rv = callback1.WaitForResult();
5876 EXPECT_EQ(OK, rv);
5878 const HttpResponseInfo* response = trans->GetResponseInfo();
5879 ASSERT_TRUE(response != NULL);
5881 EXPECT_TRUE(response->auth_challenge.get() == NULL);
5882 EXPECT_EQ(100, response->headers->GetContentLength());
5885 // ------------------------------------------------------------------------
5887 // Transaction 4: request another URL in MyRealm (however the
5888 // url is not known to belong to the protection space, so no pre-auth).
5890 HttpRequestInfo request;
5891 request.method = "GET";
5892 request.url = GURL("http://www.google.com/x/1");
5893 request.load_flags = 0;
5895 scoped_ptr<HttpTransaction> trans(
5896 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5898 MockWrite data_writes1[] = {
5899 MockWrite("GET /x/1 HTTP/1.1\r\n"
5900 "Host: www.google.com\r\n"
5901 "Connection: keep-alive\r\n\r\n"),
5904 MockRead data_reads1[] = {
5905 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
5906 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
5907 MockRead("Content-Length: 10000\r\n\r\n"),
5908 MockRead(SYNCHRONOUS, ERR_FAILED),
5911 // Resend with authorization from MyRealm's cache.
5912 MockWrite data_writes2[] = {
5913 MockWrite("GET /x/1 HTTP/1.1\r\n"
5914 "Host: www.google.com\r\n"
5915 "Connection: keep-alive\r\n"
5916 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
5919 // Sever accepts the authorization.
5920 MockRead data_reads2[] = {
5921 MockRead("HTTP/1.0 200 OK\r\n"),
5922 MockRead("Content-Length: 100\r\n\r\n"),
5923 MockRead(SYNCHRONOUS, OK),
5926 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
5927 data_writes1, arraysize(data_writes1));
5928 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
5929 data_writes2, arraysize(data_writes2));
5930 session_deps_.socket_factory->AddSocketDataProvider(&data1);
5931 session_deps_.socket_factory->AddSocketDataProvider(&data2);
5933 TestCompletionCallback callback1;
5935 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
5936 EXPECT_EQ(ERR_IO_PENDING, rv);
5938 rv = callback1.WaitForResult();
5939 EXPECT_EQ(OK, rv);
5941 EXPECT_TRUE(trans->IsReadyToRestartForAuth());
5942 TestCompletionCallback callback2;
5943 rv = trans->RestartWithAuth(AuthCredentials(), callback2.callback());
5944 EXPECT_EQ(ERR_IO_PENDING, rv);
5945 rv = callback2.WaitForResult();
5946 EXPECT_EQ(OK, rv);
5947 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
5949 const HttpResponseInfo* response = trans->GetResponseInfo();
5950 ASSERT_TRUE(response != NULL);
5951 EXPECT_TRUE(response->auth_challenge.get() == NULL);
5952 EXPECT_EQ(100, response->headers->GetContentLength());
5955 // ------------------------------------------------------------------------
5957 // Transaction 5: request a URL in MyRealm, but the server rejects the
5958 // cached identity. Should invalidate and re-prompt.
5960 HttpRequestInfo request;
5961 request.method = "GET";
5962 request.url = GURL("http://www.google.com/p/q/t");
5963 request.load_flags = 0;
5965 scoped_ptr<HttpTransaction> trans(
5966 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
5968 MockWrite data_writes1[] = {
5969 MockWrite("GET /p/q/t HTTP/1.1\r\n"
5970 "Host: www.google.com\r\n"
5971 "Connection: keep-alive\r\n\r\n"),
5974 MockRead data_reads1[] = {
5975 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
5976 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
5977 MockRead("Content-Length: 10000\r\n\r\n"),
5978 MockRead(SYNCHRONOUS, ERR_FAILED),
5981 // Resend with authorization from cache for MyRealm.
5982 MockWrite data_writes2[] = {
5983 MockWrite("GET /p/q/t HTTP/1.1\r\n"
5984 "Host: www.google.com\r\n"
5985 "Connection: keep-alive\r\n"
5986 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
5989 // Sever rejects the authorization.
5990 MockRead data_reads2[] = {
5991 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
5992 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
5993 MockRead("Content-Length: 10000\r\n\r\n"),
5994 MockRead(SYNCHRONOUS, ERR_FAILED),
5997 // At this point we should prompt for new credentials for MyRealm.
5998 // Restart with username=foo3, password=foo4.
5999 MockWrite data_writes3[] = {
6000 MockWrite("GET /p/q/t HTTP/1.1\r\n"
6001 "Host: www.google.com\r\n"
6002 "Connection: keep-alive\r\n"
6003 "Authorization: Basic Zm9vMzpiYXIz\r\n\r\n"),
6006 // Sever accepts the authorization.
6007 MockRead data_reads3[] = {
6008 MockRead("HTTP/1.0 200 OK\r\n"),
6009 MockRead("Content-Length: 100\r\n\r\n"),
6010 MockRead(SYNCHRONOUS, OK),
6013 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
6014 data_writes1, arraysize(data_writes1));
6015 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
6016 data_writes2, arraysize(data_writes2));
6017 StaticSocketDataProvider data3(data_reads3, arraysize(data_reads3),
6018 data_writes3, arraysize(data_writes3));
6019 session_deps_.socket_factory->AddSocketDataProvider(&data1);
6020 session_deps_.socket_factory->AddSocketDataProvider(&data2);
6021 session_deps_.socket_factory->AddSocketDataProvider(&data3);
6023 TestCompletionCallback callback1;
6025 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
6026 EXPECT_EQ(ERR_IO_PENDING, rv);
6028 rv = callback1.WaitForResult();
6029 EXPECT_EQ(OK, rv);
6031 EXPECT_TRUE(trans->IsReadyToRestartForAuth());
6032 TestCompletionCallback callback2;
6033 rv = trans->RestartWithAuth(AuthCredentials(), callback2.callback());
6034 EXPECT_EQ(ERR_IO_PENDING, rv);
6035 rv = callback2.WaitForResult();
6036 EXPECT_EQ(OK, rv);
6037 EXPECT_FALSE(trans->IsReadyToRestartForAuth());
6039 const HttpResponseInfo* response = trans->GetResponseInfo();
6040 ASSERT_TRUE(response != NULL);
6041 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
6043 TestCompletionCallback callback3;
6045 rv = trans->RestartWithAuth(
6046 AuthCredentials(kFoo3, kBar3), callback3.callback());
6047 EXPECT_EQ(ERR_IO_PENDING, rv);
6049 rv = callback3.WaitForResult();
6050 EXPECT_EQ(OK, rv);
6052 response = trans->GetResponseInfo();
6053 ASSERT_TRUE(response != NULL);
6054 EXPECT_TRUE(response->auth_challenge.get() == NULL);
6055 EXPECT_EQ(100, response->headers->GetContentLength());
6059 // Tests that nonce count increments when multiple auth attempts
6060 // are started with the same nonce.
6061 TEST_P(HttpNetworkTransactionTest, DigestPreAuthNonceCount) {
6062 HttpAuthHandlerDigest::Factory* digest_factory =
6063 new HttpAuthHandlerDigest::Factory();
6064 HttpAuthHandlerDigest::FixedNonceGenerator* nonce_generator =
6065 new HttpAuthHandlerDigest::FixedNonceGenerator("0123456789abcdef");
6066 digest_factory->set_nonce_generator(nonce_generator);
6067 session_deps_.http_auth_handler_factory.reset(digest_factory);
6068 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6070 // Transaction 1: authenticate (foo, bar) on MyRealm1
6072 HttpRequestInfo request;
6073 request.method = "GET";
6074 request.url = GURL("http://www.google.com/x/y/z");
6075 request.load_flags = 0;
6077 scoped_ptr<HttpTransaction> trans(
6078 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6080 MockWrite data_writes1[] = {
6081 MockWrite("GET /x/y/z HTTP/1.1\r\n"
6082 "Host: www.google.com\r\n"
6083 "Connection: keep-alive\r\n\r\n"),
6086 MockRead data_reads1[] = {
6087 MockRead("HTTP/1.0 401 Unauthorized\r\n"),
6088 MockRead("WWW-Authenticate: Digest realm=\"digestive\", nonce=\"OU812\", "
6089 "algorithm=MD5, qop=\"auth\"\r\n\r\n"),
6090 MockRead(SYNCHRONOUS, OK),
6093 // Resend with authorization (username=foo, password=bar)
6094 MockWrite data_writes2[] = {
6095 MockWrite("GET /x/y/z HTTP/1.1\r\n"
6096 "Host: www.google.com\r\n"
6097 "Connection: keep-alive\r\n"
6098 "Authorization: Digest username=\"foo\", realm=\"digestive\", "
6099 "nonce=\"OU812\", uri=\"/x/y/z\", algorithm=MD5, "
6100 "response=\"03ffbcd30add722589c1de345d7a927f\", qop=auth, "
6101 "nc=00000001, cnonce=\"0123456789abcdef\"\r\n\r\n"),
6104 // Sever accepts the authorization.
6105 MockRead data_reads2[] = {
6106 MockRead("HTTP/1.0 200 OK\r\n"),
6107 MockRead(SYNCHRONOUS, OK),
6110 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
6111 data_writes1, arraysize(data_writes1));
6112 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
6113 data_writes2, arraysize(data_writes2));
6114 session_deps_.socket_factory->AddSocketDataProvider(&data1);
6115 session_deps_.socket_factory->AddSocketDataProvider(&data2);
6117 TestCompletionCallback callback1;
6119 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
6120 EXPECT_EQ(ERR_IO_PENDING, rv);
6122 rv = callback1.WaitForResult();
6123 EXPECT_EQ(OK, rv);
6125 const HttpResponseInfo* response = trans->GetResponseInfo();
6126 ASSERT_TRUE(response != NULL);
6127 EXPECT_TRUE(CheckDigestServerAuth(response->auth_challenge.get()));
6129 TestCompletionCallback callback2;
6131 rv = trans->RestartWithAuth(
6132 AuthCredentials(kFoo, kBar), callback2.callback());
6133 EXPECT_EQ(ERR_IO_PENDING, rv);
6135 rv = callback2.WaitForResult();
6136 EXPECT_EQ(OK, rv);
6138 response = trans->GetResponseInfo();
6139 ASSERT_TRUE(response != NULL);
6140 EXPECT_TRUE(response->auth_challenge.get() == NULL);
6143 // ------------------------------------------------------------------------
6145 // Transaction 2: Request another resource in digestive's protection space.
6146 // This will preemptively add an Authorization header which should have an
6147 // "nc" value of 2 (as compared to 1 in the first use.
6149 HttpRequestInfo request;
6150 request.method = "GET";
6151 // Note that Transaction 1 was at /x/y/z, so this is in the same
6152 // protection space as digest.
6153 request.url = GURL("http://www.google.com/x/y/a/b");
6154 request.load_flags = 0;
6156 scoped_ptr<HttpTransaction> trans(
6157 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6159 MockWrite data_writes1[] = {
6160 MockWrite("GET /x/y/a/b HTTP/1.1\r\n"
6161 "Host: www.google.com\r\n"
6162 "Connection: keep-alive\r\n"
6163 "Authorization: Digest username=\"foo\", realm=\"digestive\", "
6164 "nonce=\"OU812\", uri=\"/x/y/a/b\", algorithm=MD5, "
6165 "response=\"d6f9a2c07d1c5df7b89379dca1269b35\", qop=auth, "
6166 "nc=00000002, cnonce=\"0123456789abcdef\"\r\n\r\n"),
6169 // Sever accepts the authorization.
6170 MockRead data_reads1[] = {
6171 MockRead("HTTP/1.0 200 OK\r\n"),
6172 MockRead("Content-Length: 100\r\n\r\n"),
6173 MockRead(SYNCHRONOUS, OK),
6176 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
6177 data_writes1, arraysize(data_writes1));
6178 session_deps_.socket_factory->AddSocketDataProvider(&data1);
6180 TestCompletionCallback callback1;
6182 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
6183 EXPECT_EQ(ERR_IO_PENDING, rv);
6185 rv = callback1.WaitForResult();
6186 EXPECT_EQ(OK, rv);
6188 const HttpResponseInfo* response = trans->GetResponseInfo();
6189 ASSERT_TRUE(response != NULL);
6190 EXPECT_TRUE(response->auth_challenge.get() == NULL);
6194 // Test the ResetStateForRestart() private method.
6195 TEST_P(HttpNetworkTransactionTest, ResetStateForRestart) {
6196 // Create a transaction (the dependencies aren't important).
6197 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6198 scoped_ptr<HttpNetworkTransaction> trans(
6199 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6201 // Setup some state (which we expect ResetStateForRestart() will clear).
6202 trans->read_buf_ = new IOBuffer(15);
6203 trans->read_buf_len_ = 15;
6204 trans->request_headers_.SetHeader("Authorization", "NTLM");
6206 // Setup state in response_
6207 HttpResponseInfo* response = &trans->response_;
6208 response->auth_challenge = new AuthChallengeInfo();
6209 response->ssl_info.cert_status = static_cast<CertStatus>(-1); // Nonsensical.
6210 response->response_time = base::Time::Now();
6211 response->was_cached = true; // (Wouldn't ever actually be true...)
6213 { // Setup state for response_.vary_data
6214 HttpRequestInfo request;
6215 std::string temp("HTTP/1.1 200 OK\nVary: foo, bar\n\n");
6216 std::replace(temp.begin(), temp.end(), '\n', '\0');
6217 scoped_refptr<HttpResponseHeaders> headers(new HttpResponseHeaders(temp));
6218 request.extra_headers.SetHeader("Foo", "1");
6219 request.extra_headers.SetHeader("bar", "23");
6220 EXPECT_TRUE(response->vary_data.Init(request, *headers.get()));
6223 // Cause the above state to be reset.
6224 trans->ResetStateForRestart();
6226 // Verify that the state that needed to be reset, has been reset.
6227 EXPECT_TRUE(trans->read_buf_.get() == NULL);
6228 EXPECT_EQ(0, trans->read_buf_len_);
6229 EXPECT_TRUE(trans->request_headers_.IsEmpty());
6230 EXPECT_TRUE(response->auth_challenge.get() == NULL);
6231 EXPECT_TRUE(response->headers.get() == NULL);
6232 EXPECT_FALSE(response->was_cached);
6233 EXPECT_EQ(0U, response->ssl_info.cert_status);
6234 EXPECT_FALSE(response->vary_data.is_valid());
6237 // Test HTTPS connections to a site with a bad certificate
6238 TEST_P(HttpNetworkTransactionTest, HTTPSBadCertificate) {
6239 HttpRequestInfo request;
6240 request.method = "GET";
6241 request.url = GURL("https://www.google.com/");
6242 request.load_flags = 0;
6244 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6245 scoped_ptr<HttpTransaction> trans(
6246 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6248 MockWrite data_writes[] = {
6249 MockWrite("GET / HTTP/1.1\r\n"
6250 "Host: www.google.com\r\n"
6251 "Connection: keep-alive\r\n\r\n"),
6254 MockRead data_reads[] = {
6255 MockRead("HTTP/1.0 200 OK\r\n"),
6256 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
6257 MockRead("Content-Length: 100\r\n\r\n"),
6258 MockRead(SYNCHRONOUS, OK),
6261 StaticSocketDataProvider ssl_bad_certificate;
6262 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
6263 data_writes, arraysize(data_writes));
6264 SSLSocketDataProvider ssl_bad(ASYNC, ERR_CERT_AUTHORITY_INVALID);
6265 SSLSocketDataProvider ssl(ASYNC, OK);
6267 session_deps_.socket_factory->AddSocketDataProvider(&ssl_bad_certificate);
6268 session_deps_.socket_factory->AddSocketDataProvider(&data);
6269 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_bad);
6270 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
6272 TestCompletionCallback callback;
6274 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6275 EXPECT_EQ(ERR_IO_PENDING, rv);
6277 rv = callback.WaitForResult();
6278 EXPECT_EQ(ERR_CERT_AUTHORITY_INVALID, rv);
6280 rv = trans->RestartIgnoringLastError(callback.callback());
6281 EXPECT_EQ(ERR_IO_PENDING, rv);
6283 rv = callback.WaitForResult();
6284 EXPECT_EQ(OK, rv);
6286 const HttpResponseInfo* response = trans->GetResponseInfo();
6288 ASSERT_TRUE(response != NULL);
6289 EXPECT_EQ(100, response->headers->GetContentLength());
6292 // Test HTTPS connections to a site with a bad certificate, going through a
6293 // proxy
6294 TEST_P(HttpNetworkTransactionTest, HTTPSBadCertificateViaProxy) {
6295 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
6297 HttpRequestInfo request;
6298 request.method = "GET";
6299 request.url = GURL("https://www.google.com/");
6300 request.load_flags = 0;
6302 MockWrite proxy_writes[] = {
6303 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
6304 "Host: www.google.com\r\n"
6305 "Proxy-Connection: keep-alive\r\n\r\n"),
6308 MockRead proxy_reads[] = {
6309 MockRead("HTTP/1.0 200 Connected\r\n\r\n"),
6310 MockRead(SYNCHRONOUS, OK)
6313 MockWrite data_writes[] = {
6314 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
6315 "Host: www.google.com\r\n"
6316 "Proxy-Connection: keep-alive\r\n\r\n"),
6317 MockWrite("GET / HTTP/1.1\r\n"
6318 "Host: www.google.com\r\n"
6319 "Connection: keep-alive\r\n\r\n"),
6322 MockRead data_reads[] = {
6323 MockRead("HTTP/1.0 200 Connected\r\n\r\n"),
6324 MockRead("HTTP/1.0 200 OK\r\n"),
6325 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
6326 MockRead("Content-Length: 100\r\n\r\n"),
6327 MockRead(SYNCHRONOUS, OK),
6330 StaticSocketDataProvider ssl_bad_certificate(
6331 proxy_reads, arraysize(proxy_reads),
6332 proxy_writes, arraysize(proxy_writes));
6333 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
6334 data_writes, arraysize(data_writes));
6335 SSLSocketDataProvider ssl_bad(ASYNC, ERR_CERT_AUTHORITY_INVALID);
6336 SSLSocketDataProvider ssl(ASYNC, OK);
6338 session_deps_.socket_factory->AddSocketDataProvider(&ssl_bad_certificate);
6339 session_deps_.socket_factory->AddSocketDataProvider(&data);
6340 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_bad);
6341 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
6343 TestCompletionCallback callback;
6345 for (int i = 0; i < 2; i++) {
6346 session_deps_.socket_factory->ResetNextMockIndexes();
6348 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6349 scoped_ptr<HttpTransaction> trans(
6350 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6352 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6353 EXPECT_EQ(ERR_IO_PENDING, rv);
6355 rv = callback.WaitForResult();
6356 EXPECT_EQ(ERR_CERT_AUTHORITY_INVALID, rv);
6358 rv = trans->RestartIgnoringLastError(callback.callback());
6359 EXPECT_EQ(ERR_IO_PENDING, rv);
6361 rv = callback.WaitForResult();
6362 EXPECT_EQ(OK, rv);
6364 const HttpResponseInfo* response = trans->GetResponseInfo();
6366 ASSERT_TRUE(response != NULL);
6367 EXPECT_EQ(100, response->headers->GetContentLength());
6372 // Test HTTPS connections to a site, going through an HTTPS proxy
6373 TEST_P(HttpNetworkTransactionTest, HTTPSViaHttpsProxy) {
6374 session_deps_.proxy_service.reset(
6375 ProxyService::CreateFixedFromPacResult("HTTPS proxy:70"));
6376 CapturingNetLog net_log;
6377 session_deps_.net_log = &net_log;
6379 HttpRequestInfo request;
6380 request.method = "GET";
6381 request.url = GURL("https://www.google.com/");
6382 request.load_flags = 0;
6384 MockWrite data_writes[] = {
6385 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
6386 "Host: www.google.com\r\n"
6387 "Proxy-Connection: keep-alive\r\n\r\n"),
6388 MockWrite("GET / HTTP/1.1\r\n"
6389 "Host: www.google.com\r\n"
6390 "Connection: keep-alive\r\n\r\n"),
6393 MockRead data_reads[] = {
6394 MockRead("HTTP/1.0 200 Connected\r\n\r\n"),
6395 MockRead("HTTP/1.1 200 OK\r\n"),
6396 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
6397 MockRead("Content-Length: 100\r\n\r\n"),
6398 MockRead(SYNCHRONOUS, OK),
6401 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
6402 data_writes, arraysize(data_writes));
6403 SSLSocketDataProvider proxy_ssl(ASYNC, OK); // SSL to the proxy
6404 SSLSocketDataProvider tunnel_ssl(ASYNC, OK); // SSL through the tunnel
6406 session_deps_.socket_factory->AddSocketDataProvider(&data);
6407 session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy_ssl);
6408 session_deps_.socket_factory->AddSSLSocketDataProvider(&tunnel_ssl);
6410 TestCompletionCallback callback;
6412 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6413 scoped_ptr<HttpTransaction> trans(
6414 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6416 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6417 EXPECT_EQ(ERR_IO_PENDING, rv);
6419 rv = callback.WaitForResult();
6420 EXPECT_EQ(OK, rv);
6421 const HttpResponseInfo* response = trans->GetResponseInfo();
6423 ASSERT_TRUE(response != NULL);
6425 EXPECT_TRUE(response->headers->IsKeepAlive());
6426 EXPECT_EQ(200, response->headers->response_code());
6427 EXPECT_EQ(100, response->headers->GetContentLength());
6428 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
6430 LoadTimingInfo load_timing_info;
6431 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
6432 TestLoadTimingNotReusedWithPac(load_timing_info,
6433 CONNECT_TIMING_HAS_SSL_TIMES);
6436 // Test an HTTPS Proxy's ability to redirect a CONNECT request
6437 TEST_P(HttpNetworkTransactionTest, RedirectOfHttpsConnectViaHttpsProxy) {
6438 session_deps_.proxy_service.reset(
6439 ProxyService::CreateFixedFromPacResult("HTTPS proxy:70"));
6440 CapturingNetLog net_log;
6441 session_deps_.net_log = &net_log;
6443 HttpRequestInfo request;
6444 request.method = "GET";
6445 request.url = GURL("https://www.google.com/");
6446 request.load_flags = 0;
6448 MockWrite data_writes[] = {
6449 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
6450 "Host: www.google.com\r\n"
6451 "Proxy-Connection: keep-alive\r\n\r\n"),
6454 MockRead data_reads[] = {
6455 MockRead("HTTP/1.1 302 Redirect\r\n"),
6456 MockRead("Location: http://login.example.com/\r\n"),
6457 MockRead("Content-Length: 0\r\n\r\n"),
6458 MockRead(SYNCHRONOUS, OK),
6461 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
6462 data_writes, arraysize(data_writes));
6463 SSLSocketDataProvider proxy_ssl(ASYNC, OK); // SSL to the proxy
6465 session_deps_.socket_factory->AddSocketDataProvider(&data);
6466 session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy_ssl);
6468 TestCompletionCallback callback;
6470 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6471 scoped_ptr<HttpTransaction> trans(
6472 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6474 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6475 EXPECT_EQ(ERR_IO_PENDING, rv);
6477 rv = callback.WaitForResult();
6478 EXPECT_EQ(OK, rv);
6479 const HttpResponseInfo* response = trans->GetResponseInfo();
6481 ASSERT_TRUE(response != NULL);
6483 EXPECT_EQ(302, response->headers->response_code());
6484 std::string url;
6485 EXPECT_TRUE(response->headers->IsRedirect(&url));
6486 EXPECT_EQ("http://login.example.com/", url);
6488 // In the case of redirects from proxies, HttpNetworkTransaction returns
6489 // timing for the proxy connection instead of the connection to the host,
6490 // and no send / receive times.
6491 // See HttpNetworkTransaction::OnHttpsProxyTunnelResponse.
6492 LoadTimingInfo load_timing_info;
6493 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
6495 EXPECT_FALSE(load_timing_info.socket_reused);
6496 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
6498 EXPECT_FALSE(load_timing_info.proxy_resolve_start.is_null());
6499 EXPECT_LE(load_timing_info.proxy_resolve_start,
6500 load_timing_info.proxy_resolve_end);
6501 EXPECT_LE(load_timing_info.proxy_resolve_end,
6502 load_timing_info.connect_timing.connect_start);
6503 ExpectConnectTimingHasTimes(
6504 load_timing_info.connect_timing,
6505 CONNECT_TIMING_HAS_DNS_TIMES | CONNECT_TIMING_HAS_SSL_TIMES);
6507 EXPECT_TRUE(load_timing_info.send_start.is_null());
6508 EXPECT_TRUE(load_timing_info.send_end.is_null());
6509 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
6512 // Test an HTTPS (SPDY) Proxy's ability to redirect a CONNECT request
6513 TEST_P(HttpNetworkTransactionTest, RedirectOfHttpsConnectViaSpdyProxy) {
6514 session_deps_.proxy_service.reset(
6515 ProxyService::CreateFixed("https://proxy:70"));
6517 HttpRequestInfo request;
6518 request.method = "GET";
6519 request.url = GURL("https://www.google.com/");
6520 request.load_flags = 0;
6522 scoped_ptr<SpdyFrame> conn(spdy_util_.ConstructSpdyConnect(
6523 NULL, 0, 1, LOWEST, HostPortPair("www.google.com", 443)));
6524 scoped_ptr<SpdyFrame> goaway(
6525 spdy_util_.ConstructSpdyRstStream(1, RST_STREAM_CANCEL));
6526 MockWrite data_writes[] = {
6527 CreateMockWrite(*conn.get(), 0, SYNCHRONOUS),
6528 CreateMockWrite(*goaway.get(), 3, SYNCHRONOUS),
6531 static const char* const kExtraHeaders[] = {
6532 "location",
6533 "http://login.example.com/",
6535 scoped_ptr<SpdyFrame> resp(
6536 spdy_util_.ConstructSpdySynReplyError("302 Redirect", kExtraHeaders,
6537 arraysize(kExtraHeaders)/2, 1));
6538 MockRead data_reads[] = {
6539 CreateMockRead(*resp.get(), 1, SYNCHRONOUS),
6540 MockRead(ASYNC, 0, 2), // EOF
6543 DelayedSocketData data(
6544 1, // wait for one write to finish before reading.
6545 data_reads, arraysize(data_reads),
6546 data_writes, arraysize(data_writes));
6547 SSLSocketDataProvider proxy_ssl(ASYNC, OK); // SSL to the proxy
6548 proxy_ssl.SetNextProto(GetParam());
6550 session_deps_.socket_factory->AddSocketDataProvider(&data);
6551 session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy_ssl);
6553 TestCompletionCallback callback;
6555 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6556 scoped_ptr<HttpTransaction> trans(
6557 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6559 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6560 EXPECT_EQ(ERR_IO_PENDING, rv);
6562 rv = callback.WaitForResult();
6563 EXPECT_EQ(OK, rv);
6564 const HttpResponseInfo* response = trans->GetResponseInfo();
6566 ASSERT_TRUE(response != NULL);
6568 EXPECT_EQ(302, response->headers->response_code());
6569 std::string url;
6570 EXPECT_TRUE(response->headers->IsRedirect(&url));
6571 EXPECT_EQ("http://login.example.com/", url);
6574 // Test that an HTTPS proxy's response to a CONNECT request is filtered.
6575 TEST_P(HttpNetworkTransactionTest,
6576 ErrorResponseToHttpsConnectViaHttpsProxy) {
6577 session_deps_.proxy_service.reset(
6578 ProxyService::CreateFixed("https://proxy:70"));
6580 HttpRequestInfo request;
6581 request.method = "GET";
6582 request.url = GURL("https://www.google.com/");
6583 request.load_flags = 0;
6585 MockWrite data_writes[] = {
6586 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
6587 "Host: www.google.com\r\n"
6588 "Proxy-Connection: keep-alive\r\n\r\n"),
6591 MockRead data_reads[] = {
6592 MockRead("HTTP/1.1 404 Not Found\r\n"),
6593 MockRead("Content-Length: 23\r\n\r\n"),
6594 MockRead("The host does not exist"),
6595 MockRead(SYNCHRONOUS, OK),
6598 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
6599 data_writes, arraysize(data_writes));
6600 SSLSocketDataProvider proxy_ssl(ASYNC, OK); // SSL to the proxy
6602 session_deps_.socket_factory->AddSocketDataProvider(&data);
6603 session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy_ssl);
6605 TestCompletionCallback callback;
6607 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6608 scoped_ptr<HttpTransaction> trans(
6609 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6611 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6612 EXPECT_EQ(ERR_IO_PENDING, rv);
6614 rv = callback.WaitForResult();
6615 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, rv);
6617 // TODO(ttuttle): Anything else to check here?
6620 // Test that a SPDY proxy's response to a CONNECT request is filtered.
6621 TEST_P(HttpNetworkTransactionTest,
6622 ErrorResponseToHttpsConnectViaSpdyProxy) {
6623 session_deps_.proxy_service.reset(
6624 ProxyService::CreateFixed("https://proxy:70"));
6626 HttpRequestInfo request;
6627 request.method = "GET";
6628 request.url = GURL("https://www.google.com/");
6629 request.load_flags = 0;
6631 scoped_ptr<SpdyFrame> conn(spdy_util_.ConstructSpdyConnect(
6632 NULL, 0, 1, LOWEST, HostPortPair("www.google.com", 443)));
6633 scoped_ptr<SpdyFrame> rst(
6634 spdy_util_.ConstructSpdyRstStream(1, RST_STREAM_CANCEL));
6635 MockWrite data_writes[] = {
6636 CreateMockWrite(*conn.get(), 0, SYNCHRONOUS),
6637 CreateMockWrite(*rst.get(), 3, SYNCHRONOUS),
6640 static const char* const kExtraHeaders[] = {
6641 "location",
6642 "http://login.example.com/",
6644 scoped_ptr<SpdyFrame> resp(
6645 spdy_util_.ConstructSpdySynReplyError("404 Not Found", kExtraHeaders,
6646 arraysize(kExtraHeaders)/2, 1));
6647 scoped_ptr<SpdyFrame> body(
6648 spdy_util_.ConstructSpdyBodyFrame(
6649 1, "The host does not exist", 23, true));
6650 MockRead data_reads[] = {
6651 CreateMockRead(*resp.get(), 1, SYNCHRONOUS),
6652 CreateMockRead(*body.get(), 2, SYNCHRONOUS),
6653 MockRead(ASYNC, 0, 4), // EOF
6656 DelayedSocketData data(
6657 1, // wait for one write to finish before reading.
6658 data_reads, arraysize(data_reads),
6659 data_writes, arraysize(data_writes));
6660 SSLSocketDataProvider proxy_ssl(ASYNC, OK); // SSL to the proxy
6661 proxy_ssl.SetNextProto(GetParam());
6663 session_deps_.socket_factory->AddSocketDataProvider(&data);
6664 session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy_ssl);
6666 TestCompletionCallback callback;
6668 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6669 scoped_ptr<HttpTransaction> trans(
6670 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6672 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6673 EXPECT_EQ(ERR_IO_PENDING, rv);
6675 rv = callback.WaitForResult();
6676 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, rv);
6678 // TODO(ttuttle): Anything else to check here?
6681 // Test the request-challenge-retry sequence for basic auth, through
6682 // a SPDY proxy over a single SPDY session.
6683 TEST_P(HttpNetworkTransactionTest, BasicAuthSpdyProxy) {
6684 HttpRequestInfo request;
6685 request.method = "GET";
6686 request.url = GURL("https://www.google.com/");
6687 // when the no authentication data flag is set.
6688 request.load_flags = net::LOAD_DO_NOT_SEND_AUTH_DATA;
6690 // Configure against https proxy server "myproxy:70".
6691 session_deps_.proxy_service.reset(
6692 ProxyService::CreateFixedFromPacResult("HTTPS myproxy:70"));
6693 CapturingBoundNetLog log;
6694 session_deps_.net_log = log.bound().net_log();
6695 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6697 // Since we have proxy, should try to establish tunnel.
6698 scoped_ptr<SpdyFrame> req(spdy_util_.ConstructSpdyConnect(
6699 NULL, 0, 1, LOWEST, HostPortPair("www.google.com", 443)));
6700 scoped_ptr<SpdyFrame> rst(
6701 spdy_util_.ConstructSpdyRstStream(1, RST_STREAM_CANCEL));
6703 // After calling trans->RestartWithAuth(), this is the request we should
6704 // be issuing -- the final header line contains the credentials.
6705 const char* const kAuthCredentials[] = {
6706 "proxy-authorization", "Basic Zm9vOmJhcg==",
6708 scoped_ptr<SpdyFrame> connect2(spdy_util_.ConstructSpdyConnect(
6709 kAuthCredentials, arraysize(kAuthCredentials) / 2, 3, LOWEST,
6710 HostPortPair("www.google.com", 443)));
6711 // fetch https://www.google.com/ via HTTP
6712 const char get[] = "GET / HTTP/1.1\r\n"
6713 "Host: www.google.com\r\n"
6714 "Connection: keep-alive\r\n\r\n";
6715 scoped_ptr<SpdyFrame> wrapped_get(
6716 spdy_util_.ConstructSpdyBodyFrame(3, get, strlen(get), false));
6718 MockWrite spdy_writes[] = {
6719 CreateMockWrite(*req, 1, ASYNC),
6720 CreateMockWrite(*rst, 4, ASYNC),
6721 CreateMockWrite(*connect2, 5),
6722 CreateMockWrite(*wrapped_get, 8),
6725 // The proxy responds to the connect with a 407, using a persistent
6726 // connection.
6727 const char kAuthStatus[] = "407";
6728 const char* const kAuthChallenge[] = {
6729 "proxy-authenticate", "Basic realm=\"MyRealm1\"",
6731 scoped_ptr<SpdyFrame> conn_auth_resp(spdy_util_.ConstructSpdySynReplyError(
6732 kAuthStatus, kAuthChallenge, arraysize(kAuthChallenge) / 2, 1));
6734 scoped_ptr<SpdyFrame> conn_resp(
6735 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
6736 const char resp[] = "HTTP/1.1 200 OK\r\n"
6737 "Content-Length: 5\r\n\r\n";
6739 scoped_ptr<SpdyFrame> wrapped_get_resp(
6740 spdy_util_.ConstructSpdyBodyFrame(3, resp, strlen(resp), false));
6741 scoped_ptr<SpdyFrame> wrapped_body(
6742 spdy_util_.ConstructSpdyBodyFrame(3, "hello", 5, false));
6743 MockRead spdy_reads[] = {
6744 CreateMockRead(*conn_auth_resp, 2, ASYNC),
6745 CreateMockRead(*conn_resp, 6, ASYNC),
6746 CreateMockRead(*wrapped_get_resp, 9, ASYNC),
6747 CreateMockRead(*wrapped_body, 10, ASYNC),
6748 MockRead(ASYNC, OK, 11), // EOF. May or may not be read.
6751 OrderedSocketData spdy_data(
6752 spdy_reads, arraysize(spdy_reads),
6753 spdy_writes, arraysize(spdy_writes));
6754 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
6755 // Negotiate SPDY to the proxy
6756 SSLSocketDataProvider proxy(ASYNC, OK);
6757 proxy.SetNextProto(GetParam());
6758 session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy);
6759 // Vanilla SSL to the server
6760 SSLSocketDataProvider server(ASYNC, OK);
6761 session_deps_.socket_factory->AddSSLSocketDataProvider(&server);
6763 TestCompletionCallback callback1;
6765 scoped_ptr<HttpTransaction> trans(
6766 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6768 int rv = trans->Start(&request, callback1.callback(), log.bound());
6769 EXPECT_EQ(ERR_IO_PENDING, rv);
6771 rv = callback1.WaitForResult();
6772 EXPECT_EQ(OK, rv);
6773 net::CapturingNetLog::CapturedEntryList entries;
6774 log.GetEntries(&entries);
6775 size_t pos = ExpectLogContainsSomewhere(
6776 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
6777 NetLog::PHASE_NONE);
6778 ExpectLogContainsSomewhere(
6779 entries, pos,
6780 NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
6781 NetLog::PHASE_NONE);
6783 const HttpResponseInfo* response = trans->GetResponseInfo();
6784 ASSERT_TRUE(response != NULL);
6785 ASSERT_FALSE(response->headers.get() == NULL);
6786 EXPECT_EQ(407, response->headers->response_code());
6787 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
6788 EXPECT_TRUE(response->auth_challenge.get() != NULL);
6789 EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge.get()));
6791 TestCompletionCallback callback2;
6793 rv = trans->RestartWithAuth(AuthCredentials(kFoo, kBar),
6794 callback2.callback());
6795 EXPECT_EQ(ERR_IO_PENDING, rv);
6797 rv = callback2.WaitForResult();
6798 EXPECT_EQ(OK, rv);
6800 response = trans->GetResponseInfo();
6801 ASSERT_TRUE(response != NULL);
6803 EXPECT_TRUE(response->headers->IsKeepAlive());
6804 EXPECT_EQ(200, response->headers->response_code());
6805 EXPECT_EQ(5, response->headers->GetContentLength());
6806 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
6808 // The password prompt info should not be set.
6809 EXPECT_TRUE(response->auth_challenge.get() == NULL);
6811 LoadTimingInfo load_timing_info;
6812 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
6813 TestLoadTimingNotReusedWithPac(load_timing_info,
6814 CONNECT_TIMING_HAS_SSL_TIMES);
6816 trans.reset();
6817 session->CloseAllConnections();
6820 // Test that an explicitly trusted SPDY proxy can push a resource from an
6821 // origin that is different from that of its associated resource.
6822 TEST_P(HttpNetworkTransactionTest, CrossOriginProxyPush) {
6823 HttpRequestInfo request;
6824 HttpRequestInfo push_request;
6826 request.method = "GET";
6827 request.url = GURL("http://www.google.com/");
6828 push_request.method = "GET";
6829 push_request.url = GURL("http://www.another-origin.com/foo.dat");
6831 // Configure against https proxy server "myproxy:70".
6832 session_deps_.proxy_service.reset(
6833 ProxyService::CreateFixedFromPacResult("HTTPS myproxy:70"));
6834 CapturingBoundNetLog log;
6835 session_deps_.net_log = log.bound().net_log();
6837 // Enable cross-origin push.
6838 session_deps_.trusted_spdy_proxy = "myproxy:70";
6840 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6842 scoped_ptr<SpdyFrame> stream1_syn(
6843 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, false));
6845 MockWrite spdy_writes[] = {
6846 CreateMockWrite(*stream1_syn, 1, ASYNC),
6849 scoped_ptr<SpdyFrame>
6850 stream1_reply(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
6852 scoped_ptr<SpdyFrame>
6853 stream1_body(spdy_util_.ConstructSpdyBodyFrame(1, true));
6855 scoped_ptr<SpdyFrame>
6856 stream2_syn(spdy_util_.ConstructSpdyPush(NULL,
6860 "http://www.another-origin.com/foo.dat"));
6861 const char kPushedData[] = "pushed";
6862 scoped_ptr<SpdyFrame> stream2_body(
6863 spdy_util_.ConstructSpdyBodyFrame(
6864 2, kPushedData, strlen(kPushedData), true));
6866 MockRead spdy_reads[] = {
6867 CreateMockRead(*stream1_reply, 2, ASYNC),
6868 CreateMockRead(*stream2_syn, 3, ASYNC),
6869 CreateMockRead(*stream1_body, 4, ASYNC),
6870 CreateMockRead(*stream2_body, 5, ASYNC),
6871 MockRead(ASYNC, ERR_IO_PENDING, 6), // Force a pause
6874 OrderedSocketData spdy_data(
6875 spdy_reads, arraysize(spdy_reads),
6876 spdy_writes, arraysize(spdy_writes));
6877 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
6878 // Negotiate SPDY to the proxy
6879 SSLSocketDataProvider proxy(ASYNC, OK);
6880 proxy.SetNextProto(GetParam());
6881 session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy);
6883 scoped_ptr<HttpTransaction> trans(
6884 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6885 TestCompletionCallback callback;
6886 int rv = trans->Start(&request, callback.callback(), log.bound());
6887 EXPECT_EQ(ERR_IO_PENDING, rv);
6889 rv = callback.WaitForResult();
6890 EXPECT_EQ(OK, rv);
6891 const HttpResponseInfo* response = trans->GetResponseInfo();
6893 scoped_ptr<HttpTransaction> push_trans(
6894 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6895 rv = push_trans->Start(&push_request, callback.callback(), log.bound());
6896 EXPECT_EQ(ERR_IO_PENDING, rv);
6898 rv = callback.WaitForResult();
6899 EXPECT_EQ(OK, rv);
6900 const HttpResponseInfo* push_response = push_trans->GetResponseInfo();
6902 ASSERT_TRUE(response != NULL);
6903 EXPECT_TRUE(response->headers->IsKeepAlive());
6905 EXPECT_EQ(200, response->headers->response_code());
6906 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
6908 std::string response_data;
6909 rv = ReadTransaction(trans.get(), &response_data);
6910 EXPECT_EQ(OK, rv);
6911 EXPECT_EQ("hello!", response_data);
6913 LoadTimingInfo load_timing_info;
6914 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
6915 TestLoadTimingNotReusedWithPac(load_timing_info,
6916 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
6918 // Verify the pushed stream.
6919 EXPECT_TRUE(push_response->headers.get() != NULL);
6920 EXPECT_EQ(200, push_response->headers->response_code());
6922 rv = ReadTransaction(push_trans.get(), &response_data);
6923 EXPECT_EQ(OK, rv);
6924 EXPECT_EQ("pushed", response_data);
6926 LoadTimingInfo push_load_timing_info;
6927 EXPECT_TRUE(push_trans->GetLoadTimingInfo(&push_load_timing_info));
6928 TestLoadTimingReusedWithPac(push_load_timing_info);
6929 // The transactions should share a socket ID, despite being for different
6930 // origins.
6931 EXPECT_EQ(load_timing_info.socket_log_id,
6932 push_load_timing_info.socket_log_id);
6934 trans.reset();
6935 push_trans.reset();
6936 session->CloseAllConnections();
6939 // Test that an explicitly trusted SPDY proxy cannot push HTTPS content.
6940 TEST_P(HttpNetworkTransactionTest, CrossOriginProxyPushCorrectness) {
6941 HttpRequestInfo request;
6943 request.method = "GET";
6944 request.url = GURL("http://www.google.com/");
6946 // Configure against https proxy server "myproxy:70".
6947 session_deps_.proxy_service.reset(
6948 ProxyService::CreateFixed("https://myproxy:70"));
6949 CapturingBoundNetLog log;
6950 session_deps_.net_log = log.bound().net_log();
6952 // Enable cross-origin push.
6953 session_deps_.trusted_spdy_proxy = "myproxy:70";
6955 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
6957 scoped_ptr<SpdyFrame> stream1_syn(
6958 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, false));
6960 scoped_ptr<SpdyFrame> push_rst(
6961 spdy_util_.ConstructSpdyRstStream(2, RST_STREAM_REFUSED_STREAM));
6963 MockWrite spdy_writes[] = {
6964 CreateMockWrite(*stream1_syn, 1, ASYNC),
6965 CreateMockWrite(*push_rst, 4),
6968 scoped_ptr<SpdyFrame>
6969 stream1_reply(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
6971 scoped_ptr<SpdyFrame>
6972 stream1_body(spdy_util_.ConstructSpdyBodyFrame(1, true));
6974 scoped_ptr<SpdyFrame>
6975 stream2_syn(spdy_util_.ConstructSpdyPush(NULL,
6979 "https://www.another-origin.com/foo.dat"));
6981 MockRead spdy_reads[] = {
6982 CreateMockRead(*stream1_reply, 2, ASYNC),
6983 CreateMockRead(*stream2_syn, 3, ASYNC),
6984 CreateMockRead(*stream1_body, 5, ASYNC),
6985 MockRead(ASYNC, ERR_IO_PENDING, 6), // Force a pause
6988 OrderedSocketData spdy_data(
6989 spdy_reads, arraysize(spdy_reads),
6990 spdy_writes, arraysize(spdy_writes));
6991 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
6992 // Negotiate SPDY to the proxy
6993 SSLSocketDataProvider proxy(ASYNC, OK);
6994 proxy.SetNextProto(GetParam());
6995 session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy);
6997 scoped_ptr<HttpTransaction> trans(
6998 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
6999 TestCompletionCallback callback;
7000 int rv = trans->Start(&request, callback.callback(), log.bound());
7001 EXPECT_EQ(ERR_IO_PENDING, rv);
7003 rv = callback.WaitForResult();
7004 EXPECT_EQ(OK, rv);
7005 const HttpResponseInfo* response = trans->GetResponseInfo();
7007 ASSERT_TRUE(response != NULL);
7008 EXPECT_TRUE(response->headers->IsKeepAlive());
7010 EXPECT_EQ(200, response->headers->response_code());
7011 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
7013 std::string response_data;
7014 rv = ReadTransaction(trans.get(), &response_data);
7015 EXPECT_EQ(OK, rv);
7016 EXPECT_EQ("hello!", response_data);
7018 trans.reset();
7019 session->CloseAllConnections();
7022 // Test HTTPS connections to a site with a bad certificate, going through an
7023 // HTTPS proxy
7024 TEST_P(HttpNetworkTransactionTest, HTTPSBadCertificateViaHttpsProxy) {
7025 session_deps_.proxy_service.reset(ProxyService::CreateFixed(
7026 "https://proxy:70"));
7028 HttpRequestInfo request;
7029 request.method = "GET";
7030 request.url = GURL("https://www.google.com/");
7031 request.load_flags = 0;
7033 // Attempt to fetch the URL from a server with a bad cert
7034 MockWrite bad_cert_writes[] = {
7035 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
7036 "Host: www.google.com\r\n"
7037 "Proxy-Connection: keep-alive\r\n\r\n"),
7040 MockRead bad_cert_reads[] = {
7041 MockRead("HTTP/1.0 200 Connected\r\n\r\n"),
7042 MockRead(SYNCHRONOUS, OK)
7045 // Attempt to fetch the URL with a good cert
7046 MockWrite good_data_writes[] = {
7047 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
7048 "Host: www.google.com\r\n"
7049 "Proxy-Connection: keep-alive\r\n\r\n"),
7050 MockWrite("GET / HTTP/1.1\r\n"
7051 "Host: www.google.com\r\n"
7052 "Connection: keep-alive\r\n\r\n"),
7055 MockRead good_cert_reads[] = {
7056 MockRead("HTTP/1.0 200 Connected\r\n\r\n"),
7057 MockRead("HTTP/1.0 200 OK\r\n"),
7058 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7059 MockRead("Content-Length: 100\r\n\r\n"),
7060 MockRead(SYNCHRONOUS, OK),
7063 StaticSocketDataProvider ssl_bad_certificate(
7064 bad_cert_reads, arraysize(bad_cert_reads),
7065 bad_cert_writes, arraysize(bad_cert_writes));
7066 StaticSocketDataProvider data(good_cert_reads, arraysize(good_cert_reads),
7067 good_data_writes, arraysize(good_data_writes));
7068 SSLSocketDataProvider ssl_bad(ASYNC, ERR_CERT_AUTHORITY_INVALID);
7069 SSLSocketDataProvider ssl(ASYNC, OK);
7071 // SSL to the proxy, then CONNECT request, then SSL with bad certificate
7072 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
7073 session_deps_.socket_factory->AddSocketDataProvider(&ssl_bad_certificate);
7074 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_bad);
7076 // SSL to the proxy, then CONNECT request, then valid SSL certificate
7077 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
7078 session_deps_.socket_factory->AddSocketDataProvider(&data);
7079 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
7081 TestCompletionCallback callback;
7083 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7084 scoped_ptr<HttpTransaction> trans(
7085 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7087 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7088 EXPECT_EQ(ERR_IO_PENDING, rv);
7090 rv = callback.WaitForResult();
7091 EXPECT_EQ(ERR_CERT_AUTHORITY_INVALID, rv);
7093 rv = trans->RestartIgnoringLastError(callback.callback());
7094 EXPECT_EQ(ERR_IO_PENDING, rv);
7096 rv = callback.WaitForResult();
7097 EXPECT_EQ(OK, rv);
7099 const HttpResponseInfo* response = trans->GetResponseInfo();
7101 ASSERT_TRUE(response != NULL);
7102 EXPECT_EQ(100, response->headers->GetContentLength());
7105 TEST_P(HttpNetworkTransactionTest, BuildRequest_UserAgent) {
7106 HttpRequestInfo request;
7107 request.method = "GET";
7108 request.url = GURL("http://www.google.com/");
7109 request.extra_headers.SetHeader(HttpRequestHeaders::kUserAgent,
7110 "Chromium Ultra Awesome X Edition");
7112 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7113 scoped_ptr<HttpTransaction> trans(
7114 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7116 MockWrite data_writes[] = {
7117 MockWrite("GET / HTTP/1.1\r\n"
7118 "Host: www.google.com\r\n"
7119 "Connection: keep-alive\r\n"
7120 "User-Agent: Chromium Ultra Awesome X Edition\r\n\r\n"),
7123 // Lastly, the server responds with the actual content.
7124 MockRead data_reads[] = {
7125 MockRead("HTTP/1.0 200 OK\r\n"),
7126 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7127 MockRead("Content-Length: 100\r\n\r\n"),
7128 MockRead(SYNCHRONOUS, OK),
7131 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7132 data_writes, arraysize(data_writes));
7133 session_deps_.socket_factory->AddSocketDataProvider(&data);
7135 TestCompletionCallback callback;
7137 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7138 EXPECT_EQ(ERR_IO_PENDING, rv);
7140 rv = callback.WaitForResult();
7141 EXPECT_EQ(OK, rv);
7144 TEST_P(HttpNetworkTransactionTest, BuildRequest_UserAgentOverTunnel) {
7145 HttpRequestInfo request;
7146 request.method = "GET";
7147 request.url = GURL("https://www.google.com/");
7148 request.extra_headers.SetHeader(HttpRequestHeaders::kUserAgent,
7149 "Chromium Ultra Awesome X Edition");
7151 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
7152 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7153 scoped_ptr<HttpTransaction> trans(
7154 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7156 MockWrite data_writes[] = {
7157 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
7158 "Host: www.google.com\r\n"
7159 "Proxy-Connection: keep-alive\r\n"
7160 "User-Agent: Chromium Ultra Awesome X Edition\r\n\r\n"),
7162 MockRead data_reads[] = {
7163 // Return an error, so the transaction stops here (this test isn't
7164 // interested in the rest).
7165 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
7166 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
7167 MockRead("Proxy-Connection: close\r\n\r\n"),
7170 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7171 data_writes, arraysize(data_writes));
7172 session_deps_.socket_factory->AddSocketDataProvider(&data);
7174 TestCompletionCallback callback;
7176 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7177 EXPECT_EQ(ERR_IO_PENDING, rv);
7179 rv = callback.WaitForResult();
7180 EXPECT_EQ(OK, rv);
7183 TEST_P(HttpNetworkTransactionTest, BuildRequest_Referer) {
7184 HttpRequestInfo request;
7185 request.method = "GET";
7186 request.url = GURL("http://www.google.com/");
7187 request.load_flags = 0;
7188 request.extra_headers.SetHeader(HttpRequestHeaders::kReferer,
7189 "http://the.previous.site.com/");
7191 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7192 scoped_ptr<HttpTransaction> trans(
7193 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7195 MockWrite data_writes[] = {
7196 MockWrite("GET / HTTP/1.1\r\n"
7197 "Host: www.google.com\r\n"
7198 "Connection: keep-alive\r\n"
7199 "Referer: http://the.previous.site.com/\r\n\r\n"),
7202 // Lastly, the server responds with the actual content.
7203 MockRead data_reads[] = {
7204 MockRead("HTTP/1.0 200 OK\r\n"),
7205 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7206 MockRead("Content-Length: 100\r\n\r\n"),
7207 MockRead(SYNCHRONOUS, OK),
7210 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7211 data_writes, arraysize(data_writes));
7212 session_deps_.socket_factory->AddSocketDataProvider(&data);
7214 TestCompletionCallback callback;
7216 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7217 EXPECT_EQ(ERR_IO_PENDING, rv);
7219 rv = callback.WaitForResult();
7220 EXPECT_EQ(OK, rv);
7223 TEST_P(HttpNetworkTransactionTest, BuildRequest_PostContentLengthZero) {
7224 HttpRequestInfo request;
7225 request.method = "POST";
7226 request.url = GURL("http://www.google.com/");
7228 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7229 scoped_ptr<HttpTransaction> trans(
7230 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7232 MockWrite data_writes[] = {
7233 MockWrite("POST / HTTP/1.1\r\n"
7234 "Host: www.google.com\r\n"
7235 "Connection: keep-alive\r\n"
7236 "Content-Length: 0\r\n\r\n"),
7239 // Lastly, the server responds with the actual content.
7240 MockRead data_reads[] = {
7241 MockRead("HTTP/1.0 200 OK\r\n"),
7242 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7243 MockRead("Content-Length: 100\r\n\r\n"),
7244 MockRead(SYNCHRONOUS, OK),
7247 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7248 data_writes, arraysize(data_writes));
7249 session_deps_.socket_factory->AddSocketDataProvider(&data);
7251 TestCompletionCallback callback;
7253 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7254 EXPECT_EQ(ERR_IO_PENDING, rv);
7256 rv = callback.WaitForResult();
7257 EXPECT_EQ(OK, rv);
7260 TEST_P(HttpNetworkTransactionTest, BuildRequest_PutContentLengthZero) {
7261 HttpRequestInfo request;
7262 request.method = "PUT";
7263 request.url = GURL("http://www.google.com/");
7265 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7266 scoped_ptr<HttpTransaction> trans(
7267 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7269 MockWrite data_writes[] = {
7270 MockWrite("PUT / HTTP/1.1\r\n"
7271 "Host: www.google.com\r\n"
7272 "Connection: keep-alive\r\n"
7273 "Content-Length: 0\r\n\r\n"),
7276 // Lastly, the server responds with the actual content.
7277 MockRead data_reads[] = {
7278 MockRead("HTTP/1.0 200 OK\r\n"),
7279 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7280 MockRead("Content-Length: 100\r\n\r\n"),
7281 MockRead(SYNCHRONOUS, OK),
7284 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7285 data_writes, arraysize(data_writes));
7286 session_deps_.socket_factory->AddSocketDataProvider(&data);
7288 TestCompletionCallback callback;
7290 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7291 EXPECT_EQ(ERR_IO_PENDING, rv);
7293 rv = callback.WaitForResult();
7294 EXPECT_EQ(OK, rv);
7297 TEST_P(HttpNetworkTransactionTest, BuildRequest_HeadContentLengthZero) {
7298 HttpRequestInfo request;
7299 request.method = "HEAD";
7300 request.url = GURL("http://www.google.com/");
7302 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7303 scoped_ptr<HttpTransaction> trans(
7304 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7306 MockWrite data_writes[] = {
7307 MockWrite("HEAD / HTTP/1.1\r\n"
7308 "Host: www.google.com\r\n"
7309 "Connection: keep-alive\r\n"
7310 "Content-Length: 0\r\n\r\n"),
7313 // Lastly, the server responds with the actual content.
7314 MockRead data_reads[] = {
7315 MockRead("HTTP/1.0 200 OK\r\n"),
7316 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7317 MockRead("Content-Length: 100\r\n\r\n"),
7318 MockRead(SYNCHRONOUS, OK),
7321 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7322 data_writes, arraysize(data_writes));
7323 session_deps_.socket_factory->AddSocketDataProvider(&data);
7325 TestCompletionCallback callback;
7327 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7328 EXPECT_EQ(ERR_IO_PENDING, rv);
7330 rv = callback.WaitForResult();
7331 EXPECT_EQ(OK, rv);
7334 TEST_P(HttpNetworkTransactionTest, BuildRequest_CacheControlNoCache) {
7335 HttpRequestInfo request;
7336 request.method = "GET";
7337 request.url = GURL("http://www.google.com/");
7338 request.load_flags = LOAD_BYPASS_CACHE;
7340 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7341 scoped_ptr<HttpTransaction> trans(
7342 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7344 MockWrite data_writes[] = {
7345 MockWrite("GET / HTTP/1.1\r\n"
7346 "Host: www.google.com\r\n"
7347 "Connection: keep-alive\r\n"
7348 "Pragma: no-cache\r\n"
7349 "Cache-Control: no-cache\r\n\r\n"),
7352 // Lastly, the server responds with the actual content.
7353 MockRead data_reads[] = {
7354 MockRead("HTTP/1.0 200 OK\r\n"),
7355 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7356 MockRead("Content-Length: 100\r\n\r\n"),
7357 MockRead(SYNCHRONOUS, OK),
7360 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7361 data_writes, arraysize(data_writes));
7362 session_deps_.socket_factory->AddSocketDataProvider(&data);
7364 TestCompletionCallback callback;
7366 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7367 EXPECT_EQ(ERR_IO_PENDING, rv);
7369 rv = callback.WaitForResult();
7370 EXPECT_EQ(OK, rv);
7373 TEST_P(HttpNetworkTransactionTest,
7374 BuildRequest_CacheControlValidateCache) {
7375 HttpRequestInfo request;
7376 request.method = "GET";
7377 request.url = GURL("http://www.google.com/");
7378 request.load_flags = LOAD_VALIDATE_CACHE;
7380 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7381 scoped_ptr<HttpTransaction> trans(
7382 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7384 MockWrite data_writes[] = {
7385 MockWrite("GET / HTTP/1.1\r\n"
7386 "Host: www.google.com\r\n"
7387 "Connection: keep-alive\r\n"
7388 "Cache-Control: max-age=0\r\n\r\n"),
7391 // Lastly, the server responds with the actual content.
7392 MockRead data_reads[] = {
7393 MockRead("HTTP/1.0 200 OK\r\n"),
7394 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7395 MockRead("Content-Length: 100\r\n\r\n"),
7396 MockRead(SYNCHRONOUS, OK),
7399 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7400 data_writes, arraysize(data_writes));
7401 session_deps_.socket_factory->AddSocketDataProvider(&data);
7403 TestCompletionCallback callback;
7405 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7406 EXPECT_EQ(ERR_IO_PENDING, rv);
7408 rv = callback.WaitForResult();
7409 EXPECT_EQ(OK, rv);
7412 TEST_P(HttpNetworkTransactionTest, BuildRequest_ExtraHeaders) {
7413 HttpRequestInfo request;
7414 request.method = "GET";
7415 request.url = GURL("http://www.google.com/");
7416 request.extra_headers.SetHeader("FooHeader", "Bar");
7418 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7419 scoped_ptr<HttpTransaction> trans(
7420 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7422 MockWrite data_writes[] = {
7423 MockWrite("GET / HTTP/1.1\r\n"
7424 "Host: www.google.com\r\n"
7425 "Connection: keep-alive\r\n"
7426 "FooHeader: Bar\r\n\r\n"),
7429 // Lastly, the server responds with the actual content.
7430 MockRead data_reads[] = {
7431 MockRead("HTTP/1.0 200 OK\r\n"),
7432 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7433 MockRead("Content-Length: 100\r\n\r\n"),
7434 MockRead(SYNCHRONOUS, OK),
7437 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7438 data_writes, arraysize(data_writes));
7439 session_deps_.socket_factory->AddSocketDataProvider(&data);
7441 TestCompletionCallback callback;
7443 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7444 EXPECT_EQ(ERR_IO_PENDING, rv);
7446 rv = callback.WaitForResult();
7447 EXPECT_EQ(OK, rv);
7450 TEST_P(HttpNetworkTransactionTest, BuildRequest_ExtraHeadersStripped) {
7451 HttpRequestInfo request;
7452 request.method = "GET";
7453 request.url = GURL("http://www.google.com/");
7454 request.extra_headers.SetHeader("referer", "www.foo.com");
7455 request.extra_headers.SetHeader("hEllo", "Kitty");
7456 request.extra_headers.SetHeader("FoO", "bar");
7458 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7459 scoped_ptr<HttpTransaction> trans(
7460 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7462 MockWrite data_writes[] = {
7463 MockWrite("GET / HTTP/1.1\r\n"
7464 "Host: www.google.com\r\n"
7465 "Connection: keep-alive\r\n"
7466 "referer: www.foo.com\r\n"
7467 "hEllo: Kitty\r\n"
7468 "FoO: bar\r\n\r\n"),
7471 // Lastly, the server responds with the actual content.
7472 MockRead data_reads[] = {
7473 MockRead("HTTP/1.0 200 OK\r\n"),
7474 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
7475 MockRead("Content-Length: 100\r\n\r\n"),
7476 MockRead(SYNCHRONOUS, OK),
7479 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7480 data_writes, arraysize(data_writes));
7481 session_deps_.socket_factory->AddSocketDataProvider(&data);
7483 TestCompletionCallback callback;
7485 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7486 EXPECT_EQ(ERR_IO_PENDING, rv);
7488 rv = callback.WaitForResult();
7489 EXPECT_EQ(OK, rv);
7492 TEST_P(HttpNetworkTransactionTest, SOCKS4_HTTP_GET) {
7493 HttpRequestInfo request;
7494 request.method = "GET";
7495 request.url = GURL("http://www.google.com/");
7496 request.load_flags = 0;
7498 session_deps_.proxy_service.reset(
7499 ProxyService::CreateFixedFromPacResult("SOCKS myproxy:1080"));
7500 CapturingNetLog net_log;
7501 session_deps_.net_log = &net_log;
7503 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7504 scoped_ptr<HttpTransaction> trans(
7505 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7507 char write_buffer[] = { 0x04, 0x01, 0x00, 0x50, 127, 0, 0, 1, 0 };
7508 char read_buffer[] = { 0x00, 0x5A, 0x00, 0x00, 0, 0, 0, 0 };
7510 MockWrite data_writes[] = {
7511 MockWrite(ASYNC, write_buffer, arraysize(write_buffer)),
7512 MockWrite("GET / HTTP/1.1\r\n"
7513 "Host: www.google.com\r\n"
7514 "Connection: keep-alive\r\n\r\n")
7517 MockRead data_reads[] = {
7518 MockRead(ASYNC, read_buffer, arraysize(read_buffer)),
7519 MockRead("HTTP/1.0 200 OK\r\n"),
7520 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
7521 MockRead("Payload"),
7522 MockRead(SYNCHRONOUS, OK)
7525 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7526 data_writes, arraysize(data_writes));
7527 session_deps_.socket_factory->AddSocketDataProvider(&data);
7529 TestCompletionCallback callback;
7531 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7532 EXPECT_EQ(ERR_IO_PENDING, rv);
7534 rv = callback.WaitForResult();
7535 EXPECT_EQ(OK, rv);
7537 const HttpResponseInfo* response = trans->GetResponseInfo();
7538 ASSERT_TRUE(response != NULL);
7540 LoadTimingInfo load_timing_info;
7541 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
7542 TestLoadTimingNotReusedWithPac(load_timing_info,
7543 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
7545 std::string response_text;
7546 rv = ReadTransaction(trans.get(), &response_text);
7547 EXPECT_EQ(OK, rv);
7548 EXPECT_EQ("Payload", response_text);
7551 TEST_P(HttpNetworkTransactionTest, SOCKS4_SSL_GET) {
7552 HttpRequestInfo request;
7553 request.method = "GET";
7554 request.url = GURL("https://www.google.com/");
7555 request.load_flags = 0;
7557 session_deps_.proxy_service.reset(
7558 ProxyService::CreateFixedFromPacResult("SOCKS myproxy:1080"));
7559 CapturingNetLog net_log;
7560 session_deps_.net_log = &net_log;
7562 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7563 scoped_ptr<HttpTransaction> trans(
7564 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7566 unsigned char write_buffer[] = { 0x04, 0x01, 0x01, 0xBB, 127, 0, 0, 1, 0 };
7567 unsigned char read_buffer[] = { 0x00, 0x5A, 0x00, 0x00, 0, 0, 0, 0 };
7569 MockWrite data_writes[] = {
7570 MockWrite(ASYNC, reinterpret_cast<char*>(write_buffer),
7571 arraysize(write_buffer)),
7572 MockWrite("GET / HTTP/1.1\r\n"
7573 "Host: www.google.com\r\n"
7574 "Connection: keep-alive\r\n\r\n")
7577 MockRead data_reads[] = {
7578 MockRead(ASYNC, reinterpret_cast<char*>(read_buffer),
7579 arraysize(read_buffer)),
7580 MockRead("HTTP/1.0 200 OK\r\n"),
7581 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
7582 MockRead("Payload"),
7583 MockRead(SYNCHRONOUS, OK)
7586 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7587 data_writes, arraysize(data_writes));
7588 session_deps_.socket_factory->AddSocketDataProvider(&data);
7590 SSLSocketDataProvider ssl(ASYNC, OK);
7591 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
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);
7601 LoadTimingInfo load_timing_info;
7602 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
7603 TestLoadTimingNotReusedWithPac(load_timing_info,
7604 CONNECT_TIMING_HAS_SSL_TIMES);
7606 const HttpResponseInfo* response = trans->GetResponseInfo();
7607 ASSERT_TRUE(response != NULL);
7609 std::string response_text;
7610 rv = ReadTransaction(trans.get(), &response_text);
7611 EXPECT_EQ(OK, rv);
7612 EXPECT_EQ("Payload", response_text);
7615 TEST_P(HttpNetworkTransactionTest, SOCKS4_HTTP_GET_no_PAC) {
7616 HttpRequestInfo request;
7617 request.method = "GET";
7618 request.url = GURL("http://www.google.com/");
7619 request.load_flags = 0;
7621 session_deps_.proxy_service.reset(
7622 ProxyService::CreateFixed("socks4://myproxy:1080"));
7623 CapturingNetLog net_log;
7624 session_deps_.net_log = &net_log;
7626 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7627 scoped_ptr<HttpTransaction> trans(
7628 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7630 char write_buffer[] = { 0x04, 0x01, 0x00, 0x50, 127, 0, 0, 1, 0 };
7631 char read_buffer[] = { 0x00, 0x5A, 0x00, 0x00, 0, 0, 0, 0 };
7633 MockWrite data_writes[] = {
7634 MockWrite(ASYNC, write_buffer, arraysize(write_buffer)),
7635 MockWrite("GET / HTTP/1.1\r\n"
7636 "Host: www.google.com\r\n"
7637 "Connection: keep-alive\r\n\r\n")
7640 MockRead data_reads[] = {
7641 MockRead(ASYNC, read_buffer, arraysize(read_buffer)),
7642 MockRead("HTTP/1.0 200 OK\r\n"),
7643 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
7644 MockRead("Payload"),
7645 MockRead(SYNCHRONOUS, OK)
7648 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7649 data_writes, arraysize(data_writes));
7650 session_deps_.socket_factory->AddSocketDataProvider(&data);
7652 TestCompletionCallback callback;
7654 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7655 EXPECT_EQ(ERR_IO_PENDING, rv);
7657 rv = callback.WaitForResult();
7658 EXPECT_EQ(OK, rv);
7660 const HttpResponseInfo* response = trans->GetResponseInfo();
7661 ASSERT_TRUE(response != NULL);
7663 LoadTimingInfo load_timing_info;
7664 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
7665 TestLoadTimingNotReused(load_timing_info,
7666 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
7668 std::string response_text;
7669 rv = ReadTransaction(trans.get(), &response_text);
7670 EXPECT_EQ(OK, rv);
7671 EXPECT_EQ("Payload", response_text);
7674 TEST_P(HttpNetworkTransactionTest, SOCKS5_HTTP_GET) {
7675 HttpRequestInfo request;
7676 request.method = "GET";
7677 request.url = GURL("http://www.google.com/");
7678 request.load_flags = 0;
7680 session_deps_.proxy_service.reset(
7681 ProxyService::CreateFixedFromPacResult("SOCKS5 myproxy:1080"));
7682 CapturingNetLog net_log;
7683 session_deps_.net_log = &net_log;
7685 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7686 scoped_ptr<HttpTransaction> trans(
7687 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7689 const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 };
7690 const char kSOCKS5GreetResponse[] = { 0x05, 0x00 };
7691 const char kSOCKS5OkRequest[] = {
7692 0x05, // Version
7693 0x01, // Command (CONNECT)
7694 0x00, // Reserved.
7695 0x03, // Address type (DOMAINNAME).
7696 0x0E, // Length of domain (14)
7697 // Domain string:
7698 'w', 'w', 'w', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'c', 'o', 'm',
7699 0x00, 0x50, // 16-bit port (80)
7701 const char kSOCKS5OkResponse[] =
7702 { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
7704 MockWrite data_writes[] = {
7705 MockWrite(ASYNC, kSOCKS5GreetRequest, arraysize(kSOCKS5GreetRequest)),
7706 MockWrite(ASYNC, kSOCKS5OkRequest, arraysize(kSOCKS5OkRequest)),
7707 MockWrite("GET / HTTP/1.1\r\n"
7708 "Host: www.google.com\r\n"
7709 "Connection: keep-alive\r\n\r\n")
7712 MockRead data_reads[] = {
7713 MockRead(ASYNC, kSOCKS5GreetResponse, arraysize(kSOCKS5GreetResponse)),
7714 MockRead(ASYNC, kSOCKS5OkResponse, arraysize(kSOCKS5OkResponse)),
7715 MockRead("HTTP/1.0 200 OK\r\n"),
7716 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
7717 MockRead("Payload"),
7718 MockRead(SYNCHRONOUS, OK)
7721 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7722 data_writes, arraysize(data_writes));
7723 session_deps_.socket_factory->AddSocketDataProvider(&data);
7725 TestCompletionCallback callback;
7727 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7728 EXPECT_EQ(ERR_IO_PENDING, rv);
7730 rv = callback.WaitForResult();
7731 EXPECT_EQ(OK, rv);
7733 const HttpResponseInfo* response = trans->GetResponseInfo();
7734 ASSERT_TRUE(response != NULL);
7736 LoadTimingInfo load_timing_info;
7737 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
7738 TestLoadTimingNotReusedWithPac(load_timing_info,
7739 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
7741 std::string response_text;
7742 rv = ReadTransaction(trans.get(), &response_text);
7743 EXPECT_EQ(OK, rv);
7744 EXPECT_EQ("Payload", response_text);
7747 TEST_P(HttpNetworkTransactionTest, SOCKS5_SSL_GET) {
7748 HttpRequestInfo request;
7749 request.method = "GET";
7750 request.url = GURL("https://www.google.com/");
7751 request.load_flags = 0;
7753 session_deps_.proxy_service.reset(
7754 ProxyService::CreateFixedFromPacResult("SOCKS5 myproxy:1080"));
7755 CapturingNetLog net_log;
7756 session_deps_.net_log = &net_log;
7758 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
7759 scoped_ptr<HttpTransaction> trans(
7760 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7762 const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 };
7763 const char kSOCKS5GreetResponse[] = { 0x05, 0x00 };
7764 const unsigned char kSOCKS5OkRequest[] = {
7765 0x05, // Version
7766 0x01, // Command (CONNECT)
7767 0x00, // Reserved.
7768 0x03, // Address type (DOMAINNAME).
7769 0x0E, // Length of domain (14)
7770 // Domain string:
7771 'w', 'w', 'w', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'c', 'o', 'm',
7772 0x01, 0xBB, // 16-bit port (443)
7775 const char kSOCKS5OkResponse[] =
7776 { 0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0x00, 0x00 };
7778 MockWrite data_writes[] = {
7779 MockWrite(ASYNC, kSOCKS5GreetRequest, arraysize(kSOCKS5GreetRequest)),
7780 MockWrite(ASYNC, reinterpret_cast<const char*>(kSOCKS5OkRequest),
7781 arraysize(kSOCKS5OkRequest)),
7782 MockWrite("GET / HTTP/1.1\r\n"
7783 "Host: www.google.com\r\n"
7784 "Connection: keep-alive\r\n\r\n")
7787 MockRead data_reads[] = {
7788 MockRead(ASYNC, kSOCKS5GreetResponse, arraysize(kSOCKS5GreetResponse)),
7789 MockRead(ASYNC, kSOCKS5OkResponse, arraysize(kSOCKS5OkResponse)),
7790 MockRead("HTTP/1.0 200 OK\r\n"),
7791 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
7792 MockRead("Payload"),
7793 MockRead(SYNCHRONOUS, OK)
7796 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
7797 data_writes, arraysize(data_writes));
7798 session_deps_.socket_factory->AddSocketDataProvider(&data);
7800 SSLSocketDataProvider ssl(ASYNC, OK);
7801 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
7803 TestCompletionCallback callback;
7805 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
7806 EXPECT_EQ(ERR_IO_PENDING, rv);
7808 rv = callback.WaitForResult();
7809 EXPECT_EQ(OK, rv);
7811 const HttpResponseInfo* response = trans->GetResponseInfo();
7812 ASSERT_TRUE(response != NULL);
7814 LoadTimingInfo load_timing_info;
7815 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
7816 TestLoadTimingNotReusedWithPac(load_timing_info,
7817 CONNECT_TIMING_HAS_SSL_TIMES);
7819 std::string response_text;
7820 rv = ReadTransaction(trans.get(), &response_text);
7821 EXPECT_EQ(OK, rv);
7822 EXPECT_EQ("Payload", response_text);
7825 namespace {
7827 // Tests that for connection endpoints the group names are correctly set.
7829 struct GroupNameTest {
7830 std::string proxy_server;
7831 std::string url;
7832 std::string expected_group_name;
7833 bool ssl;
7836 scoped_refptr<HttpNetworkSession> SetupSessionForGroupNameTests(
7837 NextProto next_proto,
7838 SpdySessionDependencies* session_deps_) {
7839 scoped_refptr<HttpNetworkSession> session(CreateSession(session_deps_));
7841 base::WeakPtr<HttpServerProperties> http_server_properties =
7842 session->http_server_properties();
7843 AlternativeService alternative_service(
7844 AlternateProtocolFromNextProto(next_proto), "", 443);
7845 http_server_properties->SetAlternativeService(
7846 HostPortPair("host.with.alternate", 80), alternative_service, 1.0);
7848 return session;
7851 int GroupNameTransactionHelper(
7852 const std::string& url,
7853 const scoped_refptr<HttpNetworkSession>& session) {
7854 HttpRequestInfo request;
7855 request.method = "GET";
7856 request.url = GURL(url);
7857 request.load_flags = 0;
7859 scoped_ptr<HttpTransaction> trans(
7860 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
7862 TestCompletionCallback callback;
7864 // We do not complete this request, the dtor will clean the transaction up.
7865 return trans->Start(&request, callback.callback(), BoundNetLog());
7868 } // namespace
7870 TEST_P(HttpNetworkTransactionTest, GroupNameForDirectConnections) {
7871 const GroupNameTest tests[] = {
7873 "", // unused
7874 "http://www.google.com/direct",
7875 "www.google.com:80",
7876 false,
7879 "", // unused
7880 "http://[2001:1418:13:1::25]/direct",
7881 "[2001:1418:13:1::25]:80",
7882 false,
7885 // SSL Tests
7887 "", // unused
7888 "https://www.google.com/direct_ssl",
7889 "ssl/www.google.com:443",
7890 true,
7893 "", // unused
7894 "https://[2001:1418:13:1::25]/direct",
7895 "ssl/[2001:1418:13:1::25]:443",
7896 true,
7899 "", // unused
7900 "http://host.with.alternate/direct",
7901 "ssl/host.with.alternate:443",
7902 true,
7906 session_deps_.use_alternate_protocols = true;
7908 for (size_t i = 0; i < arraysize(tests); ++i) {
7909 session_deps_.proxy_service.reset(
7910 ProxyService::CreateFixed(tests[i].proxy_server));
7911 scoped_refptr<HttpNetworkSession> session(
7912 SetupSessionForGroupNameTests(GetParam(), &session_deps_));
7914 HttpNetworkSessionPeer peer(session);
7915 CaptureGroupNameTransportSocketPool* transport_conn_pool =
7916 new CaptureGroupNameTransportSocketPool(NULL, NULL);
7917 CaptureGroupNameSSLSocketPool* ssl_conn_pool =
7918 new CaptureGroupNameSSLSocketPool(NULL, NULL);
7919 scoped_ptr<MockClientSocketPoolManager> mock_pool_manager(
7920 new MockClientSocketPoolManager);
7921 mock_pool_manager->SetTransportSocketPool(transport_conn_pool);
7922 mock_pool_manager->SetSSLSocketPool(ssl_conn_pool);
7923 peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
7925 EXPECT_EQ(ERR_IO_PENDING,
7926 GroupNameTransactionHelper(tests[i].url, session));
7927 if (tests[i].ssl)
7928 EXPECT_EQ(tests[i].expected_group_name,
7929 ssl_conn_pool->last_group_name_received());
7930 else
7931 EXPECT_EQ(tests[i].expected_group_name,
7932 transport_conn_pool->last_group_name_received());
7937 TEST_P(HttpNetworkTransactionTest, GroupNameForHTTPProxyConnections) {
7938 const GroupNameTest tests[] = {
7940 "http_proxy",
7941 "http://www.google.com/http_proxy_normal",
7942 "www.google.com:80",
7943 false,
7946 // SSL Tests
7948 "http_proxy",
7949 "https://www.google.com/http_connect_ssl",
7950 "ssl/www.google.com:443",
7951 true,
7955 "http_proxy",
7956 "http://host.with.alternate/direct",
7957 "ssl/host.with.alternate:443",
7958 true,
7962 "http_proxy",
7963 "ftp://ftp.google.com/http_proxy_normal",
7964 "ftp/ftp.google.com:21",
7965 false,
7969 session_deps_.use_alternate_protocols = true;
7971 for (size_t i = 0; i < arraysize(tests); ++i) {
7972 session_deps_.proxy_service.reset(
7973 ProxyService::CreateFixed(tests[i].proxy_server));
7974 scoped_refptr<HttpNetworkSession> session(
7975 SetupSessionForGroupNameTests(GetParam(), &session_deps_));
7977 HttpNetworkSessionPeer peer(session);
7979 HostPortPair proxy_host("http_proxy", 80);
7980 CaptureGroupNameHttpProxySocketPool* http_proxy_pool =
7981 new CaptureGroupNameHttpProxySocketPool(NULL, NULL);
7982 CaptureGroupNameSSLSocketPool* ssl_conn_pool =
7983 new CaptureGroupNameSSLSocketPool(NULL, NULL);
7985 scoped_ptr<MockClientSocketPoolManager> mock_pool_manager(
7986 new MockClientSocketPoolManager);
7987 mock_pool_manager->SetSocketPoolForHTTPProxy(proxy_host, http_proxy_pool);
7988 mock_pool_manager->SetSocketPoolForSSLWithProxy(proxy_host, ssl_conn_pool);
7989 peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
7991 EXPECT_EQ(ERR_IO_PENDING,
7992 GroupNameTransactionHelper(tests[i].url, session));
7993 if (tests[i].ssl)
7994 EXPECT_EQ(tests[i].expected_group_name,
7995 ssl_conn_pool->last_group_name_received());
7996 else
7997 EXPECT_EQ(tests[i].expected_group_name,
7998 http_proxy_pool->last_group_name_received());
8002 TEST_P(HttpNetworkTransactionTest, GroupNameForSOCKSConnections) {
8003 const GroupNameTest tests[] = {
8005 "socks4://socks_proxy:1080",
8006 "http://www.google.com/socks4_direct",
8007 "socks4/www.google.com:80",
8008 false,
8011 "socks5://socks_proxy:1080",
8012 "http://www.google.com/socks5_direct",
8013 "socks5/www.google.com:80",
8014 false,
8017 // SSL Tests
8019 "socks4://socks_proxy:1080",
8020 "https://www.google.com/socks4_ssl",
8021 "socks4/ssl/www.google.com:443",
8022 true,
8025 "socks5://socks_proxy:1080",
8026 "https://www.google.com/socks5_ssl",
8027 "socks5/ssl/www.google.com:443",
8028 true,
8032 "socks4://socks_proxy:1080",
8033 "http://host.with.alternate/direct",
8034 "socks4/ssl/host.with.alternate:443",
8035 true,
8039 session_deps_.use_alternate_protocols = true;
8041 for (size_t i = 0; i < arraysize(tests); ++i) {
8042 session_deps_.proxy_service.reset(
8043 ProxyService::CreateFixed(tests[i].proxy_server));
8044 scoped_refptr<HttpNetworkSession> session(
8045 SetupSessionForGroupNameTests(GetParam(), &session_deps_));
8047 HttpNetworkSessionPeer peer(session);
8049 HostPortPair proxy_host("socks_proxy", 1080);
8050 CaptureGroupNameSOCKSSocketPool* socks_conn_pool =
8051 new CaptureGroupNameSOCKSSocketPool(NULL, NULL);
8052 CaptureGroupNameSSLSocketPool* ssl_conn_pool =
8053 new CaptureGroupNameSSLSocketPool(NULL, NULL);
8055 scoped_ptr<MockClientSocketPoolManager> mock_pool_manager(
8056 new MockClientSocketPoolManager);
8057 mock_pool_manager->SetSocketPoolForSOCKSProxy(proxy_host, socks_conn_pool);
8058 mock_pool_manager->SetSocketPoolForSSLWithProxy(proxy_host, ssl_conn_pool);
8059 peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
8061 scoped_ptr<HttpTransaction> trans(
8062 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8064 EXPECT_EQ(ERR_IO_PENDING,
8065 GroupNameTransactionHelper(tests[i].url, session));
8066 if (tests[i].ssl)
8067 EXPECT_EQ(tests[i].expected_group_name,
8068 ssl_conn_pool->last_group_name_received());
8069 else
8070 EXPECT_EQ(tests[i].expected_group_name,
8071 socks_conn_pool->last_group_name_received());
8075 TEST_P(HttpNetworkTransactionTest, ReconsiderProxyAfterFailedConnection) {
8076 HttpRequestInfo request;
8077 request.method = "GET";
8078 request.url = GURL("http://www.google.com/");
8080 session_deps_.proxy_service.reset(
8081 ProxyService::CreateFixed("myproxy:70;foobar:80"));
8083 // This simulates failure resolving all hostnames; that means we will fail
8084 // connecting to both proxies (myproxy:70 and foobar:80).
8085 session_deps_.host_resolver->rules()->AddSimulatedFailure("*");
8087 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8088 scoped_ptr<HttpTransaction> trans(
8089 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8091 TestCompletionCallback callback;
8093 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8094 EXPECT_EQ(ERR_IO_PENDING, rv);
8096 rv = callback.WaitForResult();
8097 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, rv);
8100 // Base test to make sure that when the load flags for a request specify to
8101 // bypass the cache, the DNS cache is not used.
8102 void HttpNetworkTransactionTest::BypassHostCacheOnRefreshHelper(
8103 int load_flags) {
8104 // Issue a request, asking to bypass the cache(s).
8105 HttpRequestInfo request;
8106 request.method = "GET";
8107 request.load_flags = load_flags;
8108 request.url = GURL("http://www.google.com/");
8110 // Select a host resolver that does caching.
8111 session_deps_.host_resolver.reset(new MockCachingHostResolver);
8113 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8114 scoped_ptr<HttpTransaction> trans(
8115 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8117 // Warm up the host cache so it has an entry for "www.google.com".
8118 AddressList addrlist;
8119 TestCompletionCallback callback;
8120 int rv = session_deps_.host_resolver->Resolve(
8121 HostResolver::RequestInfo(HostPortPair("www.google.com", 80)),
8122 DEFAULT_PRIORITY,
8123 &addrlist,
8124 callback.callback(),
8125 NULL,
8126 BoundNetLog());
8127 EXPECT_EQ(ERR_IO_PENDING, rv);
8128 rv = callback.WaitForResult();
8129 EXPECT_EQ(OK, rv);
8131 // Verify that it was added to host cache, by doing a subsequent async lookup
8132 // and confirming it completes synchronously.
8133 rv = session_deps_.host_resolver->Resolve(
8134 HostResolver::RequestInfo(HostPortPair("www.google.com", 80)),
8135 DEFAULT_PRIORITY,
8136 &addrlist,
8137 callback.callback(),
8138 NULL,
8139 BoundNetLog());
8140 ASSERT_EQ(OK, rv);
8142 // Inject a failure the next time that "www.google.com" is resolved. This way
8143 // we can tell if the next lookup hit the cache, or the "network".
8144 // (cache --> success, "network" --> failure).
8145 session_deps_.host_resolver->rules()->AddSimulatedFailure("www.google.com");
8147 // Connect up a mock socket which will fail with ERR_UNEXPECTED during the
8148 // first read -- this won't be reached as the host resolution will fail first.
8149 MockRead data_reads[] = { MockRead(SYNCHRONOUS, ERR_UNEXPECTED) };
8150 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
8151 session_deps_.socket_factory->AddSocketDataProvider(&data);
8153 // Run the request.
8154 rv = trans->Start(&request, callback.callback(), BoundNetLog());
8155 ASSERT_EQ(ERR_IO_PENDING, rv);
8156 rv = callback.WaitForResult();
8158 // If we bypassed the cache, we would have gotten a failure while resolving
8159 // "www.google.com".
8160 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, rv);
8163 // There are multiple load flags that should trigger the host cache bypass.
8164 // Test each in isolation:
8165 TEST_P(HttpNetworkTransactionTest, BypassHostCacheOnRefresh1) {
8166 BypassHostCacheOnRefreshHelper(LOAD_BYPASS_CACHE);
8169 TEST_P(HttpNetworkTransactionTest, BypassHostCacheOnRefresh2) {
8170 BypassHostCacheOnRefreshHelper(LOAD_VALIDATE_CACHE);
8173 TEST_P(HttpNetworkTransactionTest, BypassHostCacheOnRefresh3) {
8174 BypassHostCacheOnRefreshHelper(LOAD_DISABLE_CACHE);
8177 // Make sure we can handle an error when writing the request.
8178 TEST_P(HttpNetworkTransactionTest, RequestWriteError) {
8179 HttpRequestInfo request;
8180 request.method = "GET";
8181 request.url = GURL("http://www.foo.com/");
8182 request.load_flags = 0;
8184 MockWrite write_failure[] = {
8185 MockWrite(ASYNC, ERR_CONNECTION_RESET),
8187 StaticSocketDataProvider data(NULL, 0,
8188 write_failure, arraysize(write_failure));
8189 session_deps_.socket_factory->AddSocketDataProvider(&data);
8190 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8192 TestCompletionCallback callback;
8194 scoped_ptr<HttpTransaction> trans(
8195 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8197 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8198 EXPECT_EQ(ERR_IO_PENDING, rv);
8200 rv = callback.WaitForResult();
8201 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
8204 // Check that a connection closed after the start of the headers finishes ok.
8205 TEST_P(HttpNetworkTransactionTest, ConnectionClosedAfterStartOfHeaders) {
8206 HttpRequestInfo request;
8207 request.method = "GET";
8208 request.url = GURL("http://www.foo.com/");
8209 request.load_flags = 0;
8211 MockRead data_reads[] = {
8212 MockRead("HTTP/1."),
8213 MockRead(SYNCHRONOUS, OK),
8216 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
8217 session_deps_.socket_factory->AddSocketDataProvider(&data);
8218 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8220 TestCompletionCallback callback;
8222 scoped_ptr<HttpTransaction> trans(
8223 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8225 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8226 EXPECT_EQ(ERR_IO_PENDING, rv);
8228 rv = callback.WaitForResult();
8229 EXPECT_EQ(OK, rv);
8231 const HttpResponseInfo* response = trans->GetResponseInfo();
8232 ASSERT_TRUE(response != NULL);
8234 EXPECT_TRUE(response->headers.get() != NULL);
8235 EXPECT_EQ("HTTP/1.0 200 OK", response->headers->GetStatusLine());
8237 std::string response_data;
8238 rv = ReadTransaction(trans.get(), &response_data);
8239 EXPECT_EQ(OK, rv);
8240 EXPECT_EQ("", response_data);
8243 // Make sure that a dropped connection while draining the body for auth
8244 // restart does the right thing.
8245 TEST_P(HttpNetworkTransactionTest, DrainResetOK) {
8246 HttpRequestInfo request;
8247 request.method = "GET";
8248 request.url = GURL("http://www.google.com/");
8249 request.load_flags = 0;
8251 MockWrite data_writes1[] = {
8252 MockWrite("GET / HTTP/1.1\r\n"
8253 "Host: www.google.com\r\n"
8254 "Connection: keep-alive\r\n\r\n"),
8257 MockRead data_reads1[] = {
8258 MockRead("HTTP/1.1 401 Unauthorized\r\n"),
8259 MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
8260 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
8261 MockRead("Content-Length: 14\r\n\r\n"),
8262 MockRead("Unauth"),
8263 MockRead(ASYNC, ERR_CONNECTION_RESET),
8266 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
8267 data_writes1, arraysize(data_writes1));
8268 session_deps_.socket_factory->AddSocketDataProvider(&data1);
8270 // After calling trans->RestartWithAuth(), this is the request we should
8271 // be issuing -- the final header line contains the credentials.
8272 MockWrite data_writes2[] = {
8273 MockWrite("GET / HTTP/1.1\r\n"
8274 "Host: www.google.com\r\n"
8275 "Connection: keep-alive\r\n"
8276 "Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
8279 // Lastly, the server responds with the actual content.
8280 MockRead data_reads2[] = {
8281 MockRead("HTTP/1.1 200 OK\r\n"),
8282 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
8283 MockRead("Content-Length: 100\r\n\r\n"),
8284 MockRead(SYNCHRONOUS, OK),
8287 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
8288 data_writes2, arraysize(data_writes2));
8289 session_deps_.socket_factory->AddSocketDataProvider(&data2);
8290 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8292 TestCompletionCallback callback1;
8294 scoped_ptr<HttpTransaction> trans(
8295 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8297 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
8298 EXPECT_EQ(ERR_IO_PENDING, rv);
8300 rv = callback1.WaitForResult();
8301 EXPECT_EQ(OK, rv);
8303 const HttpResponseInfo* response = trans->GetResponseInfo();
8304 ASSERT_TRUE(response != NULL);
8305 EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge.get()));
8307 TestCompletionCallback callback2;
8309 rv = trans->RestartWithAuth(
8310 AuthCredentials(kFoo, kBar), callback2.callback());
8311 EXPECT_EQ(ERR_IO_PENDING, rv);
8313 rv = callback2.WaitForResult();
8314 EXPECT_EQ(OK, rv);
8316 response = trans->GetResponseInfo();
8317 ASSERT_TRUE(response != NULL);
8318 EXPECT_TRUE(response->auth_challenge.get() == NULL);
8319 EXPECT_EQ(100, response->headers->GetContentLength());
8322 // Test HTTPS connections going through a proxy that sends extra data.
8323 TEST_P(HttpNetworkTransactionTest, HTTPSViaProxyWithExtraData) {
8324 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
8326 HttpRequestInfo request;
8327 request.method = "GET";
8328 request.url = GURL("https://www.google.com/");
8329 request.load_flags = 0;
8331 MockRead proxy_reads[] = {
8332 MockRead("HTTP/1.0 200 Connected\r\n\r\nExtra data"),
8333 MockRead(SYNCHRONOUS, OK)
8336 StaticSocketDataProvider data(proxy_reads, arraysize(proxy_reads), NULL, 0);
8337 SSLSocketDataProvider ssl(ASYNC, OK);
8339 session_deps_.socket_factory->AddSocketDataProvider(&data);
8340 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
8342 TestCompletionCallback callback;
8344 session_deps_.socket_factory->ResetNextMockIndexes();
8346 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8347 scoped_ptr<HttpTransaction> trans(
8348 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8350 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8351 EXPECT_EQ(ERR_IO_PENDING, rv);
8353 rv = callback.WaitForResult();
8354 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, rv);
8357 TEST_P(HttpNetworkTransactionTest, LargeContentLengthThenClose) {
8358 HttpRequestInfo request;
8359 request.method = "GET";
8360 request.url = GURL("http://www.google.com/");
8361 request.load_flags = 0;
8363 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8364 scoped_ptr<HttpTransaction> trans(
8365 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8367 MockRead data_reads[] = {
8368 MockRead("HTTP/1.0 200 OK\r\nContent-Length:6719476739\r\n\r\n"),
8369 MockRead(SYNCHRONOUS, OK),
8372 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
8373 session_deps_.socket_factory->AddSocketDataProvider(&data);
8375 TestCompletionCallback callback;
8377 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8378 EXPECT_EQ(ERR_IO_PENDING, rv);
8380 EXPECT_EQ(OK, callback.WaitForResult());
8382 const HttpResponseInfo* response = trans->GetResponseInfo();
8383 ASSERT_TRUE(response != NULL);
8385 EXPECT_TRUE(response->headers.get() != NULL);
8386 EXPECT_EQ("HTTP/1.0 200 OK", response->headers->GetStatusLine());
8388 std::string response_data;
8389 rv = ReadTransaction(trans.get(), &response_data);
8390 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, rv);
8393 TEST_P(HttpNetworkTransactionTest, UploadFileSmallerThanLength) {
8394 base::FilePath temp_file_path;
8395 ASSERT_TRUE(base::CreateTemporaryFile(&temp_file_path));
8396 const uint64 kFakeSize = 100000; // file is actually blank
8397 UploadFileElementReader::ScopedOverridingContentLengthForTests
8398 overriding_content_length(kFakeSize);
8400 ScopedVector<UploadElementReader> element_readers;
8401 element_readers.push_back(
8402 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
8403 temp_file_path,
8405 kuint64max,
8406 base::Time()));
8407 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
8409 HttpRequestInfo request;
8410 request.method = "POST";
8411 request.url = GURL("http://www.google.com/upload");
8412 request.upload_data_stream = &upload_data_stream;
8413 request.load_flags = 0;
8415 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8416 scoped_ptr<HttpTransaction> trans(
8417 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8419 MockRead data_reads[] = {
8420 MockRead("HTTP/1.0 200 OK\r\n\r\n"),
8421 MockRead("hello world"),
8422 MockRead(SYNCHRONOUS, OK),
8424 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
8425 session_deps_.socket_factory->AddSocketDataProvider(&data);
8427 TestCompletionCallback callback;
8429 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8430 EXPECT_EQ(ERR_IO_PENDING, rv);
8432 rv = callback.WaitForResult();
8433 EXPECT_EQ(OK, rv);
8435 const HttpResponseInfo* response = trans->GetResponseInfo();
8436 ASSERT_TRUE(response != NULL);
8438 EXPECT_TRUE(response->headers.get() != NULL);
8439 EXPECT_EQ("HTTP/1.0 200 OK", response->headers->GetStatusLine());
8441 std::string response_data;
8442 rv = ReadTransaction(trans.get(), &response_data);
8443 EXPECT_EQ(OK, rv);
8444 EXPECT_EQ("hello world", response_data);
8446 base::DeleteFile(temp_file_path, false);
8449 TEST_P(HttpNetworkTransactionTest, UploadUnreadableFile) {
8450 base::FilePath temp_file;
8451 ASSERT_TRUE(base::CreateTemporaryFile(&temp_file));
8452 std::string temp_file_content("Unreadable file.");
8453 ASSERT_TRUE(base::WriteFile(temp_file, temp_file_content.c_str(),
8454 temp_file_content.length()));
8455 ASSERT_TRUE(base::MakeFileUnreadable(temp_file));
8457 ScopedVector<UploadElementReader> element_readers;
8458 element_readers.push_back(
8459 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
8460 temp_file,
8462 kuint64max,
8463 base::Time()));
8464 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
8466 HttpRequestInfo request;
8467 request.method = "POST";
8468 request.url = GURL("http://www.google.com/upload");
8469 request.upload_data_stream = &upload_data_stream;
8470 request.load_flags = 0;
8472 // If we try to upload an unreadable file, the transaction should fail.
8473 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8474 scoped_ptr<HttpTransaction> trans(
8475 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8477 StaticSocketDataProvider data(NULL, 0, NULL, 0);
8478 session_deps_.socket_factory->AddSocketDataProvider(&data);
8480 TestCompletionCallback callback;
8482 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8483 EXPECT_EQ(ERR_IO_PENDING, rv);
8485 rv = callback.WaitForResult();
8486 EXPECT_EQ(ERR_ACCESS_DENIED, rv);
8488 const HttpResponseInfo* response = trans->GetResponseInfo();
8489 EXPECT_FALSE(response);
8491 base::DeleteFile(temp_file, false);
8494 TEST_P(HttpNetworkTransactionTest, CancelDuringInitRequestBody) {
8495 class FakeUploadElementReader : public UploadElementReader {
8496 public:
8497 FakeUploadElementReader() {}
8498 ~FakeUploadElementReader() override {}
8500 const CompletionCallback& callback() const { return callback_; }
8502 // UploadElementReader overrides:
8503 int Init(const CompletionCallback& callback) override {
8504 callback_ = callback;
8505 return ERR_IO_PENDING;
8507 uint64 GetContentLength() const override { return 0; }
8508 uint64 BytesRemaining() const override { return 0; }
8509 int Read(IOBuffer* buf,
8510 int buf_length,
8511 const CompletionCallback& callback) override {
8512 return ERR_FAILED;
8515 private:
8516 CompletionCallback callback_;
8519 FakeUploadElementReader* fake_reader = new FakeUploadElementReader;
8520 ScopedVector<UploadElementReader> element_readers;
8521 element_readers.push_back(fake_reader);
8522 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
8524 HttpRequestInfo request;
8525 request.method = "POST";
8526 request.url = GURL("http://www.google.com/upload");
8527 request.upload_data_stream = &upload_data_stream;
8528 request.load_flags = 0;
8530 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8531 scoped_ptr<HttpTransaction> trans(
8532 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8534 StaticSocketDataProvider data;
8535 session_deps_.socket_factory->AddSocketDataProvider(&data);
8537 TestCompletionCallback callback;
8538 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8539 EXPECT_EQ(ERR_IO_PENDING, rv);
8540 base::MessageLoop::current()->RunUntilIdle();
8542 // Transaction is pending on request body initialization.
8543 ASSERT_FALSE(fake_reader->callback().is_null());
8545 // Return Init()'s result after the transaction gets destroyed.
8546 trans.reset();
8547 fake_reader->callback().Run(OK); // Should not crash.
8550 // Tests that changes to Auth realms are treated like auth rejections.
8551 TEST_P(HttpNetworkTransactionTest, ChangeAuthRealms) {
8553 HttpRequestInfo request;
8554 request.method = "GET";
8555 request.url = GURL("http://www.google.com/");
8556 request.load_flags = 0;
8558 // First transaction will request a resource and receive a Basic challenge
8559 // with realm="first_realm".
8560 MockWrite data_writes1[] = {
8561 MockWrite("GET / HTTP/1.1\r\n"
8562 "Host: www.google.com\r\n"
8563 "Connection: keep-alive\r\n"
8564 "\r\n"),
8566 MockRead data_reads1[] = {
8567 MockRead("HTTP/1.1 401 Unauthorized\r\n"
8568 "WWW-Authenticate: Basic realm=\"first_realm\"\r\n"
8569 "\r\n"),
8572 // After calling trans->RestartWithAuth(), provide an Authentication header
8573 // for first_realm. The server will reject and provide a challenge with
8574 // second_realm.
8575 MockWrite data_writes2[] = {
8576 MockWrite("GET / HTTP/1.1\r\n"
8577 "Host: www.google.com\r\n"
8578 "Connection: keep-alive\r\n"
8579 "Authorization: Basic Zmlyc3Q6YmF6\r\n"
8580 "\r\n"),
8582 MockRead data_reads2[] = {
8583 MockRead("HTTP/1.1 401 Unauthorized\r\n"
8584 "WWW-Authenticate: Basic realm=\"second_realm\"\r\n"
8585 "\r\n"),
8588 // This again fails, and goes back to first_realm. Make sure that the
8589 // entry is removed from cache.
8590 MockWrite data_writes3[] = {
8591 MockWrite("GET / HTTP/1.1\r\n"
8592 "Host: www.google.com\r\n"
8593 "Connection: keep-alive\r\n"
8594 "Authorization: Basic c2Vjb25kOmZvdQ==\r\n"
8595 "\r\n"),
8597 MockRead data_reads3[] = {
8598 MockRead("HTTP/1.1 401 Unauthorized\r\n"
8599 "WWW-Authenticate: Basic realm=\"first_realm\"\r\n"
8600 "\r\n"),
8603 // Try one last time (with the correct password) and get the resource.
8604 MockWrite data_writes4[] = {
8605 MockWrite("GET / HTTP/1.1\r\n"
8606 "Host: www.google.com\r\n"
8607 "Connection: keep-alive\r\n"
8608 "Authorization: Basic Zmlyc3Q6YmFy\r\n"
8609 "\r\n"),
8611 MockRead data_reads4[] = {
8612 MockRead("HTTP/1.1 200 OK\r\n"
8613 "Content-Type: text/html; charset=iso-8859-1\r\n"
8614 "Content-Length: 5\r\n"
8615 "\r\n"
8616 "hello"),
8619 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
8620 data_writes1, arraysize(data_writes1));
8621 StaticSocketDataProvider data2(data_reads2, arraysize(data_reads2),
8622 data_writes2, arraysize(data_writes2));
8623 StaticSocketDataProvider data3(data_reads3, arraysize(data_reads3),
8624 data_writes3, arraysize(data_writes3));
8625 StaticSocketDataProvider data4(data_reads4, arraysize(data_reads4),
8626 data_writes4, arraysize(data_writes4));
8627 session_deps_.socket_factory->AddSocketDataProvider(&data1);
8628 session_deps_.socket_factory->AddSocketDataProvider(&data2);
8629 session_deps_.socket_factory->AddSocketDataProvider(&data3);
8630 session_deps_.socket_factory->AddSocketDataProvider(&data4);
8632 TestCompletionCallback callback1;
8634 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8635 scoped_ptr<HttpTransaction> trans(
8636 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8638 // Issue the first request with Authorize headers. There should be a
8639 // password prompt for first_realm waiting to be filled in after the
8640 // transaction completes.
8641 int rv = trans->Start(&request, callback1.callback(), BoundNetLog());
8642 EXPECT_EQ(ERR_IO_PENDING, rv);
8643 rv = callback1.WaitForResult();
8644 EXPECT_EQ(OK, rv);
8645 const HttpResponseInfo* response = trans->GetResponseInfo();
8646 ASSERT_TRUE(response != NULL);
8647 const AuthChallengeInfo* challenge = response->auth_challenge.get();
8648 ASSERT_FALSE(challenge == NULL);
8649 EXPECT_FALSE(challenge->is_proxy);
8650 EXPECT_EQ("www.google.com:80", challenge->challenger.ToString());
8651 EXPECT_EQ("first_realm", challenge->realm);
8652 EXPECT_EQ("basic", challenge->scheme);
8654 // Issue the second request with an incorrect password. There should be a
8655 // password prompt for second_realm waiting to be filled in after the
8656 // transaction completes.
8657 TestCompletionCallback callback2;
8658 rv = trans->RestartWithAuth(
8659 AuthCredentials(kFirst, kBaz), callback2.callback());
8660 EXPECT_EQ(ERR_IO_PENDING, rv);
8661 rv = callback2.WaitForResult();
8662 EXPECT_EQ(OK, rv);
8663 response = trans->GetResponseInfo();
8664 ASSERT_TRUE(response != NULL);
8665 challenge = response->auth_challenge.get();
8666 ASSERT_FALSE(challenge == NULL);
8667 EXPECT_FALSE(challenge->is_proxy);
8668 EXPECT_EQ("www.google.com:80", challenge->challenger.ToString());
8669 EXPECT_EQ("second_realm", challenge->realm);
8670 EXPECT_EQ("basic", challenge->scheme);
8672 // Issue the third request with another incorrect password. There should be
8673 // a password prompt for first_realm waiting to be filled in. If the password
8674 // prompt is not present, it indicates that the HttpAuthCacheEntry for
8675 // first_realm was not correctly removed.
8676 TestCompletionCallback callback3;
8677 rv = trans->RestartWithAuth(
8678 AuthCredentials(kSecond, kFou), callback3.callback());
8679 EXPECT_EQ(ERR_IO_PENDING, rv);
8680 rv = callback3.WaitForResult();
8681 EXPECT_EQ(OK, rv);
8682 response = trans->GetResponseInfo();
8683 ASSERT_TRUE(response != NULL);
8684 challenge = response->auth_challenge.get();
8685 ASSERT_FALSE(challenge == NULL);
8686 EXPECT_FALSE(challenge->is_proxy);
8687 EXPECT_EQ("www.google.com:80", challenge->challenger.ToString());
8688 EXPECT_EQ("first_realm", challenge->realm);
8689 EXPECT_EQ("basic", challenge->scheme);
8691 // Issue the fourth request with the correct password and username.
8692 TestCompletionCallback callback4;
8693 rv = trans->RestartWithAuth(
8694 AuthCredentials(kFirst, kBar), callback4.callback());
8695 EXPECT_EQ(ERR_IO_PENDING, rv);
8696 rv = callback4.WaitForResult();
8697 EXPECT_EQ(OK, rv);
8698 response = trans->GetResponseInfo();
8699 ASSERT_TRUE(response != NULL);
8700 EXPECT_TRUE(response->auth_challenge.get() == NULL);
8703 TEST_P(HttpNetworkTransactionTest, HonorAlternateProtocolHeader) {
8704 session_deps_.next_protos = SpdyNextProtos();
8705 session_deps_.use_alternate_protocols = true;
8707 std::string alternate_protocol_http_header =
8708 GetAlternateProtocolHttpHeader();
8710 MockRead data_reads[] = {
8711 MockRead("HTTP/1.1 200 OK\r\n"),
8712 MockRead(alternate_protocol_http_header.c_str()),
8713 MockRead("hello world"),
8714 MockRead(SYNCHRONOUS, OK),
8717 HttpRequestInfo request;
8718 request.method = "GET";
8719 request.url = GURL("http://www.google.com/");
8720 request.load_flags = 0;
8722 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
8724 session_deps_.socket_factory->AddSocketDataProvider(&data);
8726 TestCompletionCallback callback;
8728 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8729 scoped_ptr<HttpTransaction> trans(
8730 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8732 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8733 EXPECT_EQ(ERR_IO_PENDING, rv);
8735 HostPortPair http_host_port_pair("www.google.com", 80);
8736 HttpServerProperties& http_server_properties =
8737 *session->http_server_properties();
8738 AlternativeService alternative_service =
8739 http_server_properties.GetAlternativeService(http_host_port_pair);
8740 EXPECT_EQ(alternative_service.protocol, UNINITIALIZED_ALTERNATE_PROTOCOL);
8742 EXPECT_EQ(OK, callback.WaitForResult());
8744 const HttpResponseInfo* response = trans->GetResponseInfo();
8745 ASSERT_TRUE(response != NULL);
8746 ASSERT_TRUE(response->headers.get() != NULL);
8747 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
8748 EXPECT_FALSE(response->was_fetched_via_spdy);
8749 EXPECT_FALSE(response->was_npn_negotiated);
8751 std::string response_data;
8752 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
8753 EXPECT_EQ("hello world", response_data);
8755 alternative_service =
8756 http_server_properties.GetAlternativeService(http_host_port_pair);
8757 EXPECT_EQ(443, alternative_service.port);
8758 EXPECT_EQ(AlternateProtocolFromNextProto(GetParam()),
8759 alternative_service.protocol);
8762 TEST_P(HttpNetworkTransactionTest, EmptyAlternateProtocolHeader) {
8763 session_deps_.next_protos = SpdyNextProtos();
8764 session_deps_.use_alternate_protocols = true;
8766 MockRead data_reads[] = {
8767 MockRead("HTTP/1.1 200 OK\r\n"),
8768 MockRead("Alternate-Protocol: \r\n\r\n"),
8769 MockRead("hello world"),
8770 MockRead(SYNCHRONOUS, OK),
8773 HttpRequestInfo request;
8774 request.method = "GET";
8775 request.url = GURL("http://www.google.com/");
8776 request.load_flags = 0;
8778 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
8780 session_deps_.socket_factory->AddSocketDataProvider(&data);
8782 TestCompletionCallback callback;
8784 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8786 HostPortPair http_host_port_pair("www.google.com", 80);
8787 HttpServerProperties& http_server_properties =
8788 *session->http_server_properties();
8789 AlternativeService alternative_service(QUIC, "", 80);
8790 http_server_properties.SetAlternativeService(http_host_port_pair,
8791 alternative_service, 1.0);
8793 alternative_service =
8794 http_server_properties.GetAlternativeService(http_host_port_pair);
8795 EXPECT_EQ(alternative_service.protocol, QUIC);
8797 scoped_ptr<HttpTransaction> trans(
8798 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8800 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8801 EXPECT_EQ(ERR_IO_PENDING, rv);
8803 EXPECT_EQ(OK, callback.WaitForResult());
8805 const HttpResponseInfo* response = trans->GetResponseInfo();
8806 ASSERT_TRUE(response != NULL);
8807 ASSERT_TRUE(response->headers.get() != NULL);
8808 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
8809 EXPECT_FALSE(response->was_fetched_via_spdy);
8810 EXPECT_FALSE(response->was_npn_negotiated);
8812 std::string response_data;
8813 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
8814 EXPECT_EQ("hello world", response_data);
8816 alternative_service =
8817 http_server_properties.GetAlternativeService(http_host_port_pair);
8818 EXPECT_EQ(alternative_service.protocol, UNINITIALIZED_ALTERNATE_PROTOCOL);
8821 TEST_P(HttpNetworkTransactionTest,
8822 MarkBrokenAlternateProtocolAndFallback) {
8823 session_deps_.use_alternate_protocols = true;
8825 HttpRequestInfo request;
8826 request.method = "GET";
8827 request.url = GURL("http://www.google.com/");
8828 request.load_flags = 0;
8830 MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
8831 StaticSocketDataProvider first_data;
8832 first_data.set_connect_data(mock_connect);
8833 session_deps_.socket_factory->AddSocketDataProvider(&first_data);
8835 MockRead data_reads[] = {
8836 MockRead("HTTP/1.1 200 OK\r\n\r\n"),
8837 MockRead("hello world"),
8838 MockRead(ASYNC, OK),
8840 StaticSocketDataProvider second_data(
8841 data_reads, arraysize(data_reads), NULL, 0);
8842 session_deps_.socket_factory->AddSocketDataProvider(&second_data);
8844 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8846 base::WeakPtr<HttpServerProperties> http_server_properties =
8847 session->http_server_properties();
8848 const HostPortPair host_port_pair = HostPortPair::FromURL(request.url);
8849 // Port must be < 1024, or the header will be ignored (since initial port was
8850 // port 80 (another restricted port).
8851 AlternativeService alternative_service(
8852 AlternateProtocolFromNextProto(GetParam()), "www.google.com",
8853 666); /* port is ignored by MockConnect anyway */
8854 http_server_properties->SetAlternativeService(host_port_pair,
8855 alternative_service, 1.0);
8857 scoped_ptr<HttpTransaction> trans(
8858 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8859 TestCompletionCallback callback;
8861 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
8862 EXPECT_EQ(ERR_IO_PENDING, rv);
8863 EXPECT_EQ(OK, callback.WaitForResult());
8865 const HttpResponseInfo* response = trans->GetResponseInfo();
8866 ASSERT_TRUE(response != NULL);
8867 ASSERT_TRUE(response->headers.get() != NULL);
8868 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
8870 std::string response_data;
8871 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
8872 EXPECT_EQ("hello world", response_data);
8874 alternative_service =
8875 http_server_properties->GetAlternativeService(host_port_pair);
8876 EXPECT_NE(UNINITIALIZED_ALTERNATE_PROTOCOL, alternative_service.protocol);
8877 EXPECT_TRUE(
8878 http_server_properties->IsAlternativeServiceBroken(alternative_service));
8881 TEST_P(HttpNetworkTransactionTest,
8882 AlternateProtocolPortRestrictedBlocked) {
8883 // Ensure that we're not allowed to redirect traffic via an alternate
8884 // protocol to an unrestricted (port >= 1024) when the original traffic was
8885 // on a restricted port (port < 1024). Ensure that we can redirect in all
8886 // other cases.
8887 session_deps_.use_alternate_protocols = true;
8889 HttpRequestInfo restricted_port_request;
8890 restricted_port_request.method = "GET";
8891 restricted_port_request.url = GURL("http://www.google.com:1023/");
8892 restricted_port_request.load_flags = 0;
8894 MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
8895 StaticSocketDataProvider first_data;
8896 first_data.set_connect_data(mock_connect);
8897 session_deps_.socket_factory->AddSocketDataProvider(&first_data);
8899 MockRead data_reads[] = {
8900 MockRead("HTTP/1.1 200 OK\r\n\r\n"),
8901 MockRead("hello world"),
8902 MockRead(ASYNC, OK),
8904 StaticSocketDataProvider second_data(
8905 data_reads, arraysize(data_reads), NULL, 0);
8906 session_deps_.socket_factory->AddSocketDataProvider(&second_data);
8908 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8910 base::WeakPtr<HttpServerProperties> http_server_properties =
8911 session->http_server_properties();
8912 const int kUnrestrictedAlternatePort = 1024;
8913 AlternativeService alternative_service(
8914 AlternateProtocolFromNextProto(GetParam()), "www.google.com",
8915 kUnrestrictedAlternatePort);
8916 http_server_properties->SetAlternativeService(
8917 HostPortPair::FromURL(restricted_port_request.url), alternative_service,
8918 1.0);
8920 scoped_ptr<HttpTransaction> trans(
8921 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8922 TestCompletionCallback callback;
8924 int rv = trans->Start(
8925 &restricted_port_request,
8926 callback.callback(), BoundNetLog());
8927 EXPECT_EQ(ERR_IO_PENDING, rv);
8928 // Invalid change to unrestricted port should fail.
8929 EXPECT_EQ(ERR_CONNECTION_REFUSED, callback.WaitForResult());
8932 TEST_P(HttpNetworkTransactionTest,
8933 AlternateProtocolPortRestrictedPermitted) {
8934 // Ensure that we're allowed to redirect traffic via an alternate
8935 // protocol to an unrestricted (port >= 1024) when the original traffic was
8936 // on a restricted port (port < 1024) if we set
8937 // enable_user_alternate_protocol_ports.
8939 session_deps_.use_alternate_protocols = true;
8940 session_deps_.enable_user_alternate_protocol_ports = true;
8942 HttpRequestInfo restricted_port_request;
8943 restricted_port_request.method = "GET";
8944 restricted_port_request.url = GURL("http://www.google.com:1023/");
8945 restricted_port_request.load_flags = 0;
8947 MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
8948 StaticSocketDataProvider first_data;
8949 first_data.set_connect_data(mock_connect);
8950 session_deps_.socket_factory->AddSocketDataProvider(&first_data);
8952 MockRead data_reads[] = {
8953 MockRead("HTTP/1.1 200 OK\r\n\r\n"),
8954 MockRead("hello world"),
8955 MockRead(ASYNC, OK),
8957 StaticSocketDataProvider second_data(
8958 data_reads, arraysize(data_reads), NULL, 0);
8959 session_deps_.socket_factory->AddSocketDataProvider(&second_data);
8961 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
8963 base::WeakPtr<HttpServerProperties> http_server_properties =
8964 session->http_server_properties();
8965 const int kUnrestrictedAlternatePort = 1024;
8966 AlternativeService alternative_service(
8967 AlternateProtocolFromNextProto(GetParam()), "www.google.com",
8968 kUnrestrictedAlternatePort);
8969 http_server_properties->SetAlternativeService(
8970 HostPortPair::FromURL(restricted_port_request.url), alternative_service,
8971 1.0);
8973 scoped_ptr<HttpTransaction> trans(
8974 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
8975 TestCompletionCallback callback;
8977 EXPECT_EQ(ERR_IO_PENDING, trans->Start(
8978 &restricted_port_request,
8979 callback.callback(), BoundNetLog()));
8980 // Change to unrestricted port should succeed.
8981 EXPECT_EQ(OK, callback.WaitForResult());
8984 TEST_P(HttpNetworkTransactionTest,
8985 AlternateProtocolPortRestrictedAllowed) {
8986 // Ensure that we're not allowed to redirect traffic via an alternate
8987 // protocol to an unrestricted (port >= 1024) when the original traffic was
8988 // on a restricted port (port < 1024). Ensure that we can redirect in all
8989 // other cases.
8990 session_deps_.use_alternate_protocols = true;
8992 HttpRequestInfo restricted_port_request;
8993 restricted_port_request.method = "GET";
8994 restricted_port_request.url = GURL("http://www.google.com:1023/");
8995 restricted_port_request.load_flags = 0;
8997 MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
8998 StaticSocketDataProvider first_data;
8999 first_data.set_connect_data(mock_connect);
9000 session_deps_.socket_factory->AddSocketDataProvider(&first_data);
9002 MockRead data_reads[] = {
9003 MockRead("HTTP/1.1 200 OK\r\n\r\n"),
9004 MockRead("hello world"),
9005 MockRead(ASYNC, OK),
9007 StaticSocketDataProvider second_data(
9008 data_reads, arraysize(data_reads), NULL, 0);
9009 session_deps_.socket_factory->AddSocketDataProvider(&second_data);
9011 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9013 base::WeakPtr<HttpServerProperties> http_server_properties =
9014 session->http_server_properties();
9015 const int kRestrictedAlternatePort = 80;
9016 AlternativeService alternative_service(
9017 AlternateProtocolFromNextProto(GetParam()), "www.google.com",
9018 kRestrictedAlternatePort);
9019 http_server_properties->SetAlternativeService(
9020 HostPortPair::FromURL(restricted_port_request.url), alternative_service,
9021 1.0);
9023 scoped_ptr<HttpTransaction> trans(
9024 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9025 TestCompletionCallback callback;
9027 int rv = trans->Start(
9028 &restricted_port_request,
9029 callback.callback(), BoundNetLog());
9030 EXPECT_EQ(ERR_IO_PENDING, rv);
9031 // Valid change to restricted port should pass.
9032 EXPECT_EQ(OK, callback.WaitForResult());
9035 TEST_P(HttpNetworkTransactionTest,
9036 AlternateProtocolPortUnrestrictedAllowed1) {
9037 // Ensure that we're not allowed to redirect traffic via an alternate
9038 // protocol to an unrestricted (port >= 1024) when the original traffic was
9039 // on a restricted port (port < 1024). Ensure that we can redirect in all
9040 // other cases.
9041 session_deps_.use_alternate_protocols = true;
9043 HttpRequestInfo unrestricted_port_request;
9044 unrestricted_port_request.method = "GET";
9045 unrestricted_port_request.url = GURL("http://www.google.com:1024/");
9046 unrestricted_port_request.load_flags = 0;
9048 MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
9049 StaticSocketDataProvider first_data;
9050 first_data.set_connect_data(mock_connect);
9051 session_deps_.socket_factory->AddSocketDataProvider(&first_data);
9053 MockRead data_reads[] = {
9054 MockRead("HTTP/1.1 200 OK\r\n\r\n"),
9055 MockRead("hello world"),
9056 MockRead(ASYNC, OK),
9058 StaticSocketDataProvider second_data(
9059 data_reads, arraysize(data_reads), NULL, 0);
9060 session_deps_.socket_factory->AddSocketDataProvider(&second_data);
9062 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9064 base::WeakPtr<HttpServerProperties> http_server_properties =
9065 session->http_server_properties();
9066 const int kRestrictedAlternatePort = 80;
9067 AlternativeService alternative_service(
9068 AlternateProtocolFromNextProto(GetParam()), "www.google.com",
9069 kRestrictedAlternatePort);
9070 http_server_properties->SetAlternativeService(
9071 HostPortPair::FromURL(unrestricted_port_request.url), alternative_service,
9072 1.0);
9074 scoped_ptr<HttpTransaction> trans(
9075 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9076 TestCompletionCallback callback;
9078 int rv = trans->Start(
9079 &unrestricted_port_request, callback.callback(), BoundNetLog());
9080 EXPECT_EQ(ERR_IO_PENDING, rv);
9081 // Valid change to restricted port should pass.
9082 EXPECT_EQ(OK, callback.WaitForResult());
9085 TEST_P(HttpNetworkTransactionTest,
9086 AlternateProtocolPortUnrestrictedAllowed2) {
9087 // Ensure that we're not allowed to redirect traffic via an alternate
9088 // protocol to an unrestricted (port >= 1024) when the original traffic was
9089 // on a restricted port (port < 1024). Ensure that we can redirect in all
9090 // other cases.
9091 session_deps_.use_alternate_protocols = true;
9093 HttpRequestInfo unrestricted_port_request;
9094 unrestricted_port_request.method = "GET";
9095 unrestricted_port_request.url = GURL("http://www.google.com:1024/");
9096 unrestricted_port_request.load_flags = 0;
9098 MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
9099 StaticSocketDataProvider first_data;
9100 first_data.set_connect_data(mock_connect);
9101 session_deps_.socket_factory->AddSocketDataProvider(&first_data);
9103 MockRead data_reads[] = {
9104 MockRead("HTTP/1.1 200 OK\r\n\r\n"),
9105 MockRead("hello world"),
9106 MockRead(ASYNC, OK),
9108 StaticSocketDataProvider second_data(
9109 data_reads, arraysize(data_reads), NULL, 0);
9110 session_deps_.socket_factory->AddSocketDataProvider(&second_data);
9112 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9114 base::WeakPtr<HttpServerProperties> http_server_properties =
9115 session->http_server_properties();
9116 const int kUnrestrictedAlternatePort = 1024;
9117 AlternativeService alternative_service(
9118 AlternateProtocolFromNextProto(GetParam()), "www.google.com",
9119 kUnrestrictedAlternatePort);
9120 http_server_properties->SetAlternativeService(
9121 HostPortPair::FromURL(unrestricted_port_request.url), alternative_service,
9122 1.0);
9124 scoped_ptr<HttpTransaction> trans(
9125 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9126 TestCompletionCallback callback;
9128 int rv = trans->Start(
9129 &unrestricted_port_request, callback.callback(), BoundNetLog());
9130 EXPECT_EQ(ERR_IO_PENDING, rv);
9131 // Valid change to an unrestricted port should pass.
9132 EXPECT_EQ(OK, callback.WaitForResult());
9135 TEST_P(HttpNetworkTransactionTest, AlternateProtocolUnsafeBlocked) {
9136 // Ensure that we're not allowed to redirect traffic via an alternate
9137 // protocol to an unsafe port, and that we resume the second
9138 // HttpStreamFactoryImpl::Job once the alternate protocol request fails.
9139 session_deps_.use_alternate_protocols = true;
9141 HttpRequestInfo request;
9142 request.method = "GET";
9143 request.url = GURL("http://www.google.com/");
9144 request.load_flags = 0;
9146 // The alternate protocol request will error out before we attempt to connect,
9147 // so only the standard HTTP request will try to connect.
9148 MockRead data_reads[] = {
9149 MockRead("HTTP/1.1 200 OK\r\n\r\n"),
9150 MockRead("hello world"),
9151 MockRead(ASYNC, OK),
9153 StaticSocketDataProvider data(
9154 data_reads, arraysize(data_reads), NULL, 0);
9155 session_deps_.socket_factory->AddSocketDataProvider(&data);
9157 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9159 base::WeakPtr<HttpServerProperties> http_server_properties =
9160 session->http_server_properties();
9161 const int kUnsafePort = 7;
9162 AlternativeService alternative_service(
9163 AlternateProtocolFromNextProto(GetParam()), "www.google.com",
9164 kUnsafePort);
9165 http_server_properties->SetAlternativeService(
9166 HostPortPair::FromURL(request.url), alternative_service, 1.0);
9168 scoped_ptr<HttpTransaction> trans(
9169 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9170 TestCompletionCallback callback;
9172 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
9173 EXPECT_EQ(ERR_IO_PENDING, rv);
9174 // The HTTP request should succeed.
9175 EXPECT_EQ(OK, callback.WaitForResult());
9177 // Disable alternate protocol before the asserts.
9178 // HttpStreamFactory::set_use_alternate_protocols(false);
9180 const HttpResponseInfo* response = trans->GetResponseInfo();
9181 ASSERT_TRUE(response != NULL);
9182 ASSERT_TRUE(response->headers.get() != NULL);
9183 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9185 std::string response_data;
9186 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9187 EXPECT_EQ("hello world", response_data);
9190 TEST_P(HttpNetworkTransactionTest, UseAlternateProtocolForNpnSpdy) {
9191 session_deps_.use_alternate_protocols = true;
9192 session_deps_.next_protos = SpdyNextProtos();
9194 HttpRequestInfo request;
9195 request.method = "GET";
9196 request.url = GURL("http://www.google.com/");
9197 request.load_flags = 0;
9199 std::string alternate_protocol_http_header =
9200 GetAlternateProtocolHttpHeader();
9202 MockRead data_reads[] = {
9203 MockRead("HTTP/1.1 200 OK\r\n"),
9204 MockRead(alternate_protocol_http_header.c_str()),
9205 MockRead("hello world"),
9206 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
9207 MockRead(ASYNC, OK)
9210 StaticSocketDataProvider first_transaction(
9211 data_reads, arraysize(data_reads), NULL, 0);
9212 session_deps_.socket_factory->AddSocketDataProvider(&first_transaction);
9214 SSLSocketDataProvider ssl(ASYNC, OK);
9215 ssl.SetNextProto(GetParam());
9216 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
9218 scoped_ptr<SpdyFrame> req(
9219 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, true));
9220 MockWrite spdy_writes[] = { CreateMockWrite(*req) };
9222 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
9223 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
9224 MockRead spdy_reads[] = {
9225 CreateMockRead(*resp),
9226 CreateMockRead(*data),
9227 MockRead(ASYNC, 0, 0),
9230 DelayedSocketData spdy_data(
9231 1, // wait for one write to finish before reading.
9232 spdy_reads, arraysize(spdy_reads),
9233 spdy_writes, arraysize(spdy_writes));
9234 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
9236 MockConnect never_finishing_connect(SYNCHRONOUS, ERR_IO_PENDING);
9237 StaticSocketDataProvider hanging_non_alternate_protocol_socket(
9238 NULL, 0, NULL, 0);
9239 hanging_non_alternate_protocol_socket.set_connect_data(
9240 never_finishing_connect);
9241 session_deps_.socket_factory->AddSocketDataProvider(
9242 &hanging_non_alternate_protocol_socket);
9244 TestCompletionCallback callback;
9246 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9247 scoped_ptr<HttpTransaction> trans(
9248 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9250 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
9251 EXPECT_EQ(ERR_IO_PENDING, rv);
9252 EXPECT_EQ(OK, callback.WaitForResult());
9254 const HttpResponseInfo* response = trans->GetResponseInfo();
9255 ASSERT_TRUE(response != NULL);
9256 ASSERT_TRUE(response->headers.get() != NULL);
9257 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9259 std::string response_data;
9260 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9261 EXPECT_EQ("hello world", response_data);
9263 trans.reset(new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9265 rv = trans->Start(&request, callback.callback(), BoundNetLog());
9266 EXPECT_EQ(ERR_IO_PENDING, rv);
9267 EXPECT_EQ(OK, callback.WaitForResult());
9269 response = trans->GetResponseInfo();
9270 ASSERT_TRUE(response != NULL);
9271 ASSERT_TRUE(response->headers.get() != NULL);
9272 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9273 EXPECT_TRUE(response->was_fetched_via_spdy);
9274 EXPECT_TRUE(response->was_npn_negotiated);
9276 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9277 EXPECT_EQ("hello!", response_data);
9280 TEST_P(HttpNetworkTransactionTest, AlternateProtocolWithSpdyLateBinding) {
9281 session_deps_.use_alternate_protocols = true;
9282 session_deps_.next_protos = SpdyNextProtos();
9284 HttpRequestInfo request;
9285 request.method = "GET";
9286 request.url = GURL("http://www.google.com/");
9287 request.load_flags = 0;
9289 std::string alternate_protocol_http_header =
9290 GetAlternateProtocolHttpHeader();
9292 MockRead data_reads[] = {
9293 MockRead("HTTP/1.1 200 OK\r\n"),
9294 MockRead(alternate_protocol_http_header.c_str()),
9295 MockRead("hello world"),
9296 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
9297 MockRead(ASYNC, OK),
9300 StaticSocketDataProvider first_transaction(
9301 data_reads, arraysize(data_reads), NULL, 0);
9302 // Socket 1 is the HTTP transaction with the Alternate-Protocol header.
9303 session_deps_.socket_factory->AddSocketDataProvider(&first_transaction);
9305 MockConnect never_finishing_connect(SYNCHRONOUS, ERR_IO_PENDING);
9306 StaticSocketDataProvider hanging_socket(
9307 NULL, 0, NULL, 0);
9308 hanging_socket.set_connect_data(never_finishing_connect);
9309 // Socket 2 and 3 are the hanging Alternate-Protocol and
9310 // non-Alternate-Protocol jobs from the 2nd transaction.
9311 session_deps_.socket_factory->AddSocketDataProvider(&hanging_socket);
9312 session_deps_.socket_factory->AddSocketDataProvider(&hanging_socket);
9314 SSLSocketDataProvider ssl(ASYNC, OK);
9315 ssl.SetNextProto(GetParam());
9316 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
9318 scoped_ptr<SpdyFrame> req1(
9319 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, true));
9320 scoped_ptr<SpdyFrame> req2(
9321 spdy_util_.ConstructSpdyGet(NULL, 0, false, 3, LOWEST, true));
9322 MockWrite spdy_writes[] = {
9323 CreateMockWrite(*req1),
9324 CreateMockWrite(*req2),
9326 scoped_ptr<SpdyFrame> resp1(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
9327 scoped_ptr<SpdyFrame> data1(spdy_util_.ConstructSpdyBodyFrame(1, true));
9328 scoped_ptr<SpdyFrame> resp2(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
9329 scoped_ptr<SpdyFrame> data2(spdy_util_.ConstructSpdyBodyFrame(3, true));
9330 MockRead spdy_reads[] = {
9331 CreateMockRead(*resp1),
9332 CreateMockRead(*data1),
9333 CreateMockRead(*resp2),
9334 CreateMockRead(*data2),
9335 MockRead(ASYNC, 0, 0),
9338 DelayedSocketData spdy_data(
9339 2, // wait for writes to finish before reading.
9340 spdy_reads, arraysize(spdy_reads),
9341 spdy_writes, arraysize(spdy_writes));
9342 // Socket 4 is the successful Alternate-Protocol for transaction 3.
9343 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
9345 // Socket 5 is the unsuccessful non-Alternate-Protocol for transaction 3.
9346 session_deps_.socket_factory->AddSocketDataProvider(&hanging_socket);
9348 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9349 TestCompletionCallback callback1;
9350 HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
9352 int rv = trans1.Start(&request, callback1.callback(), BoundNetLog());
9353 EXPECT_EQ(ERR_IO_PENDING, rv);
9354 EXPECT_EQ(OK, callback1.WaitForResult());
9356 const HttpResponseInfo* response = trans1.GetResponseInfo();
9357 ASSERT_TRUE(response != NULL);
9358 ASSERT_TRUE(response->headers.get() != NULL);
9359 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9361 std::string response_data;
9362 ASSERT_EQ(OK, ReadTransaction(&trans1, &response_data));
9363 EXPECT_EQ("hello world", response_data);
9365 TestCompletionCallback callback2;
9366 HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
9367 rv = trans2.Start(&request, callback2.callback(), BoundNetLog());
9368 EXPECT_EQ(ERR_IO_PENDING, rv);
9370 TestCompletionCallback callback3;
9371 HttpNetworkTransaction trans3(DEFAULT_PRIORITY, session.get());
9372 rv = trans3.Start(&request, callback3.callback(), BoundNetLog());
9373 EXPECT_EQ(ERR_IO_PENDING, rv);
9375 EXPECT_EQ(OK, callback2.WaitForResult());
9376 EXPECT_EQ(OK, callback3.WaitForResult());
9378 response = trans2.GetResponseInfo();
9379 ASSERT_TRUE(response != NULL);
9380 ASSERT_TRUE(response->headers.get() != NULL);
9381 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9382 EXPECT_TRUE(response->was_fetched_via_spdy);
9383 EXPECT_TRUE(response->was_npn_negotiated);
9384 ASSERT_EQ(OK, ReadTransaction(&trans2, &response_data));
9385 EXPECT_EQ("hello!", response_data);
9387 response = trans3.GetResponseInfo();
9388 ASSERT_TRUE(response != NULL);
9389 ASSERT_TRUE(response->headers.get() != NULL);
9390 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9391 EXPECT_TRUE(response->was_fetched_via_spdy);
9392 EXPECT_TRUE(response->was_npn_negotiated);
9393 ASSERT_EQ(OK, ReadTransaction(&trans3, &response_data));
9394 EXPECT_EQ("hello!", response_data);
9397 TEST_P(HttpNetworkTransactionTest, StallAlternateProtocolForNpnSpdy) {
9398 session_deps_.use_alternate_protocols = true;
9399 session_deps_.next_protos = SpdyNextProtos();
9401 HttpRequestInfo request;
9402 request.method = "GET";
9403 request.url = GURL("http://www.google.com/");
9404 request.load_flags = 0;
9406 std::string alternate_protocol_http_header =
9407 GetAlternateProtocolHttpHeader();
9409 MockRead data_reads[] = {
9410 MockRead("HTTP/1.1 200 OK\r\n"),
9411 MockRead(alternate_protocol_http_header.c_str()),
9412 MockRead("hello world"),
9413 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
9414 MockRead(ASYNC, OK),
9417 StaticSocketDataProvider first_transaction(
9418 data_reads, arraysize(data_reads), NULL, 0);
9419 session_deps_.socket_factory->AddSocketDataProvider(&first_transaction);
9421 SSLSocketDataProvider ssl(ASYNC, OK);
9422 ssl.SetNextProto(GetParam());
9423 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
9425 MockConnect never_finishing_connect(SYNCHRONOUS, ERR_IO_PENDING);
9426 StaticSocketDataProvider hanging_alternate_protocol_socket(
9427 NULL, 0, NULL, 0);
9428 hanging_alternate_protocol_socket.set_connect_data(
9429 never_finishing_connect);
9430 session_deps_.socket_factory->AddSocketDataProvider(
9431 &hanging_alternate_protocol_socket);
9433 // 2nd request is just a copy of the first one, over HTTP again.
9434 session_deps_.socket_factory->AddSocketDataProvider(&first_transaction);
9436 TestCompletionCallback callback;
9438 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9439 scoped_ptr<HttpTransaction> trans(
9440 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9442 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
9443 EXPECT_EQ(ERR_IO_PENDING, rv);
9444 EXPECT_EQ(OK, callback.WaitForResult());
9446 const HttpResponseInfo* response = trans->GetResponseInfo();
9447 ASSERT_TRUE(response != NULL);
9448 ASSERT_TRUE(response->headers.get() != NULL);
9449 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9451 std::string response_data;
9452 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9453 EXPECT_EQ("hello world", response_data);
9455 trans.reset(new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9457 rv = trans->Start(&request, callback.callback(), BoundNetLog());
9458 EXPECT_EQ(ERR_IO_PENDING, rv);
9459 EXPECT_EQ(OK, callback.WaitForResult());
9461 response = trans->GetResponseInfo();
9462 ASSERT_TRUE(response != NULL);
9463 ASSERT_TRUE(response->headers.get() != NULL);
9464 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9465 EXPECT_FALSE(response->was_fetched_via_spdy);
9466 EXPECT_FALSE(response->was_npn_negotiated);
9468 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9469 EXPECT_EQ("hello world", response_data);
9472 class CapturingProxyResolver : public ProxyResolver {
9473 public:
9474 CapturingProxyResolver() : ProxyResolver(false /* expects_pac_bytes */) {}
9475 ~CapturingProxyResolver() override {}
9477 int GetProxyForURL(const GURL& url,
9478 ProxyInfo* results,
9479 const CompletionCallback& callback,
9480 RequestHandle* request,
9481 const BoundNetLog& net_log) override {
9482 ProxyServer proxy_server(ProxyServer::SCHEME_HTTP,
9483 HostPortPair("myproxy", 80));
9484 results->UseProxyServer(proxy_server);
9485 resolved_.push_back(url);
9486 return OK;
9489 void CancelRequest(RequestHandle request) override { NOTREACHED(); }
9491 LoadState GetLoadState(RequestHandle request) const override {
9492 NOTREACHED();
9493 return LOAD_STATE_IDLE;
9496 void CancelSetPacScript() override { NOTREACHED(); }
9498 int SetPacScript(const scoped_refptr<ProxyResolverScriptData>&,
9499 const CompletionCallback& /*callback*/) override {
9500 return OK;
9503 const std::vector<GURL>& resolved() const { return resolved_; }
9505 private:
9506 std::vector<GURL> resolved_;
9508 DISALLOW_COPY_AND_ASSIGN(CapturingProxyResolver);
9511 TEST_P(HttpNetworkTransactionTest,
9512 UseAlternateProtocolForTunneledNpnSpdy) {
9513 session_deps_.use_alternate_protocols = true;
9514 session_deps_.next_protos = SpdyNextProtos();
9516 ProxyConfig proxy_config;
9517 proxy_config.set_auto_detect(true);
9518 proxy_config.set_pac_url(GURL("http://fooproxyurl"));
9520 CapturingProxyResolver* capturing_proxy_resolver =
9521 new CapturingProxyResolver();
9522 session_deps_.proxy_service.reset(new ProxyService(
9523 new ProxyConfigServiceFixed(proxy_config), capturing_proxy_resolver,
9524 NULL));
9525 CapturingNetLog net_log;
9526 session_deps_.net_log = &net_log;
9528 HttpRequestInfo request;
9529 request.method = "GET";
9530 request.url = GURL("http://www.google.com/");
9531 request.load_flags = 0;
9533 std::string alternate_protocol_http_header =
9534 GetAlternateProtocolHttpHeader();
9536 MockRead data_reads[] = {
9537 MockRead("HTTP/1.1 200 OK\r\n"),
9538 MockRead(alternate_protocol_http_header.c_str()),
9539 MockRead("hello world"),
9540 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
9541 MockRead(ASYNC, OK),
9544 StaticSocketDataProvider first_transaction(
9545 data_reads, arraysize(data_reads), NULL, 0);
9546 session_deps_.socket_factory->AddSocketDataProvider(&first_transaction);
9548 SSLSocketDataProvider ssl(ASYNC, OK);
9549 ssl.SetNextProto(GetParam());
9550 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
9552 scoped_ptr<SpdyFrame> req(
9553 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, true));
9554 MockWrite spdy_writes[] = {
9555 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
9556 "Host: www.google.com\r\n"
9557 "Proxy-Connection: keep-alive\r\n\r\n"), // 0
9558 CreateMockWrite(*req), // 3
9561 const char kCONNECTResponse[] = "HTTP/1.1 200 Connected\r\n\r\n";
9563 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
9564 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
9565 MockRead spdy_reads[] = {
9566 MockRead(ASYNC, kCONNECTResponse, arraysize(kCONNECTResponse) - 1, 1), // 1
9567 CreateMockRead(*resp.get(), 4), // 2, 4
9568 CreateMockRead(*data.get(), 4), // 5
9569 MockRead(ASYNC, 0, 0, 4), // 6
9572 OrderedSocketData spdy_data(
9573 spdy_reads, arraysize(spdy_reads),
9574 spdy_writes, arraysize(spdy_writes));
9575 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
9577 MockConnect never_finishing_connect(SYNCHRONOUS, ERR_IO_PENDING);
9578 StaticSocketDataProvider hanging_non_alternate_protocol_socket(
9579 NULL, 0, NULL, 0);
9580 hanging_non_alternate_protocol_socket.set_connect_data(
9581 never_finishing_connect);
9582 session_deps_.socket_factory->AddSocketDataProvider(
9583 &hanging_non_alternate_protocol_socket);
9585 TestCompletionCallback callback;
9587 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9588 scoped_ptr<HttpTransaction> trans(
9589 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9591 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
9592 EXPECT_EQ(ERR_IO_PENDING, rv);
9593 EXPECT_EQ(OK, callback.WaitForResult());
9595 const HttpResponseInfo* response = trans->GetResponseInfo();
9596 ASSERT_TRUE(response != NULL);
9597 ASSERT_TRUE(response->headers.get() != NULL);
9598 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9599 EXPECT_FALSE(response->was_fetched_via_spdy);
9600 EXPECT_FALSE(response->was_npn_negotiated);
9602 std::string response_data;
9603 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9604 EXPECT_EQ("hello world", response_data);
9606 trans.reset(new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9608 rv = trans->Start(&request, callback.callback(), BoundNetLog());
9609 EXPECT_EQ(ERR_IO_PENDING, rv);
9610 EXPECT_EQ(OK, callback.WaitForResult());
9612 response = trans->GetResponseInfo();
9613 ASSERT_TRUE(response != NULL);
9614 ASSERT_TRUE(response->headers.get() != NULL);
9615 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9616 EXPECT_TRUE(response->was_fetched_via_spdy);
9617 EXPECT_TRUE(response->was_npn_negotiated);
9619 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9620 EXPECT_EQ("hello!", response_data);
9621 ASSERT_EQ(3u, capturing_proxy_resolver->resolved().size());
9622 EXPECT_EQ("http://www.google.com/",
9623 capturing_proxy_resolver->resolved()[0].spec());
9624 EXPECT_EQ("https://www.google.com/",
9625 capturing_proxy_resolver->resolved()[1].spec());
9627 LoadTimingInfo load_timing_info;
9628 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
9629 TestLoadTimingNotReusedWithPac(load_timing_info,
9630 CONNECT_TIMING_HAS_SSL_TIMES);
9633 TEST_P(HttpNetworkTransactionTest,
9634 UseAlternateProtocolForNpnSpdyWithExistingSpdySession) {
9635 session_deps_.use_alternate_protocols = true;
9636 session_deps_.next_protos = SpdyNextProtos();
9638 HttpRequestInfo request;
9639 request.method = "GET";
9640 request.url = GURL("http://www.google.com/");
9641 request.load_flags = 0;
9643 std::string alternate_protocol_http_header =
9644 GetAlternateProtocolHttpHeader();
9646 MockRead data_reads[] = {
9647 MockRead("HTTP/1.1 200 OK\r\n"),
9648 MockRead(alternate_protocol_http_header.c_str()),
9649 MockRead("hello world"),
9650 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 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
9661 scoped_ptr<SpdyFrame> req(
9662 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, true));
9663 MockWrite spdy_writes[] = { CreateMockWrite(*req) };
9665 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
9666 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
9667 MockRead spdy_reads[] = {
9668 CreateMockRead(*resp),
9669 CreateMockRead(*data),
9670 MockRead(ASYNC, 0, 0),
9673 DelayedSocketData spdy_data(
9674 1, // wait for one write to finish before reading.
9675 spdy_reads, arraysize(spdy_reads),
9676 spdy_writes, arraysize(spdy_writes));
9677 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
9679 TestCompletionCallback callback;
9681 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
9683 scoped_ptr<HttpTransaction> trans(
9684 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9686 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
9687 EXPECT_EQ(ERR_IO_PENDING, rv);
9688 EXPECT_EQ(OK, callback.WaitForResult());
9690 const HttpResponseInfo* response = trans->GetResponseInfo();
9691 ASSERT_TRUE(response != NULL);
9692 ASSERT_TRUE(response->headers.get() != NULL);
9693 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9695 std::string response_data;
9696 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9697 EXPECT_EQ("hello world", response_data);
9699 // Set up an initial SpdySession in the pool to reuse.
9700 HostPortPair host_port_pair("www.google.com", 443);
9701 SpdySessionKey key(host_port_pair, ProxyServer::Direct(),
9702 PRIVACY_MODE_DISABLED);
9703 base::WeakPtr<SpdySession> spdy_session =
9704 CreateSecureSpdySession(session, key, BoundNetLog());
9706 trans.reset(new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
9708 rv = trans->Start(&request, callback.callback(), BoundNetLog());
9709 EXPECT_EQ(ERR_IO_PENDING, rv);
9710 EXPECT_EQ(OK, callback.WaitForResult());
9712 response = trans->GetResponseInfo();
9713 ASSERT_TRUE(response != NULL);
9714 ASSERT_TRUE(response->headers.get() != NULL);
9715 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
9716 EXPECT_TRUE(response->was_fetched_via_spdy);
9717 EXPECT_TRUE(response->was_npn_negotiated);
9719 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
9720 EXPECT_EQ("hello!", response_data);
9723 // GenerateAuthToken is a mighty big test.
9724 // It tests all permutation of GenerateAuthToken behavior:
9725 // - Synchronous and Asynchronous completion.
9726 // - OK or error on completion.
9727 // - Direct connection, non-authenticating proxy, and authenticating proxy.
9728 // - HTTP or HTTPS backend (to include proxy tunneling).
9729 // - Non-authenticating and authenticating backend.
9731 // In all, there are 44 reasonable permuations (for example, if there are
9732 // problems generating an auth token for an authenticating proxy, we don't
9733 // need to test all permutations of the backend server).
9735 // The test proceeds by going over each of the configuration cases, and
9736 // potentially running up to three rounds in each of the tests. The TestConfig
9737 // specifies both the configuration for the test as well as the expectations
9738 // for the results.
9739 TEST_P(HttpNetworkTransactionTest, GenerateAuthToken) {
9740 static const char kServer[] = "http://www.example.com";
9741 static const char kSecureServer[] = "https://www.example.com";
9742 static const char kProxy[] = "myproxy:70";
9743 const int kAuthErr = ERR_INVALID_AUTH_CREDENTIALS;
9745 enum AuthTiming {
9746 AUTH_NONE,
9747 AUTH_SYNC,
9748 AUTH_ASYNC,
9751 const MockWrite kGet(
9752 "GET / HTTP/1.1\r\n"
9753 "Host: www.example.com\r\n"
9754 "Connection: keep-alive\r\n\r\n");
9755 const MockWrite kGetProxy(
9756 "GET http://www.example.com/ HTTP/1.1\r\n"
9757 "Host: www.example.com\r\n"
9758 "Proxy-Connection: keep-alive\r\n\r\n");
9759 const MockWrite kGetAuth(
9760 "GET / HTTP/1.1\r\n"
9761 "Host: www.example.com\r\n"
9762 "Connection: keep-alive\r\n"
9763 "Authorization: auth_token\r\n\r\n");
9764 const MockWrite kGetProxyAuth(
9765 "GET http://www.example.com/ HTTP/1.1\r\n"
9766 "Host: www.example.com\r\n"
9767 "Proxy-Connection: keep-alive\r\n"
9768 "Proxy-Authorization: auth_token\r\n\r\n");
9769 const MockWrite kGetAuthThroughProxy(
9770 "GET http://www.example.com/ HTTP/1.1\r\n"
9771 "Host: www.example.com\r\n"
9772 "Proxy-Connection: keep-alive\r\n"
9773 "Authorization: auth_token\r\n\r\n");
9774 const MockWrite kGetAuthWithProxyAuth(
9775 "GET http://www.example.com/ HTTP/1.1\r\n"
9776 "Host: www.example.com\r\n"
9777 "Proxy-Connection: keep-alive\r\n"
9778 "Proxy-Authorization: auth_token\r\n"
9779 "Authorization: auth_token\r\n\r\n");
9780 const MockWrite kConnect(
9781 "CONNECT www.example.com:443 HTTP/1.1\r\n"
9782 "Host: www.example.com\r\n"
9783 "Proxy-Connection: keep-alive\r\n\r\n");
9784 const MockWrite kConnectProxyAuth(
9785 "CONNECT www.example.com:443 HTTP/1.1\r\n"
9786 "Host: www.example.com\r\n"
9787 "Proxy-Connection: keep-alive\r\n"
9788 "Proxy-Authorization: auth_token\r\n\r\n");
9790 const MockRead kSuccess(
9791 "HTTP/1.1 200 OK\r\n"
9792 "Content-Type: text/html; charset=iso-8859-1\r\n"
9793 "Content-Length: 3\r\n\r\n"
9794 "Yes");
9795 const MockRead kFailure(
9796 "Should not be called.");
9797 const MockRead kServerChallenge(
9798 "HTTP/1.1 401 Unauthorized\r\n"
9799 "WWW-Authenticate: Mock realm=server\r\n"
9800 "Content-Type: text/html; charset=iso-8859-1\r\n"
9801 "Content-Length: 14\r\n\r\n"
9802 "Unauthorized\r\n");
9803 const MockRead kProxyChallenge(
9804 "HTTP/1.1 407 Unauthorized\r\n"
9805 "Proxy-Authenticate: Mock realm=proxy\r\n"
9806 "Proxy-Connection: close\r\n"
9807 "Content-Type: text/html; charset=iso-8859-1\r\n"
9808 "Content-Length: 14\r\n\r\n"
9809 "Unauthorized\r\n");
9810 const MockRead kProxyConnected(
9811 "HTTP/1.1 200 Connection Established\r\n\r\n");
9813 // NOTE(cbentzel): I wanted TestReadWriteRound to be a simple struct with
9814 // no constructors, but the C++ compiler on Windows warns about
9815 // unspecified data in compound literals. So, moved to using constructors,
9816 // and TestRound's created with the default constructor should not be used.
9817 struct TestRound {
9818 TestRound()
9819 : expected_rv(ERR_UNEXPECTED),
9820 extra_write(NULL),
9821 extra_read(NULL) {
9823 TestRound(const MockWrite& write_arg, const MockRead& read_arg,
9824 int expected_rv_arg)
9825 : write(write_arg),
9826 read(read_arg),
9827 expected_rv(expected_rv_arg),
9828 extra_write(NULL),
9829 extra_read(NULL) {
9831 TestRound(const MockWrite& write_arg, const MockRead& read_arg,
9832 int expected_rv_arg, const MockWrite* extra_write_arg,
9833 const MockRead* extra_read_arg)
9834 : write(write_arg),
9835 read(read_arg),
9836 expected_rv(expected_rv_arg),
9837 extra_write(extra_write_arg),
9838 extra_read(extra_read_arg) {
9840 MockWrite write;
9841 MockRead read;
9842 int expected_rv;
9843 const MockWrite* extra_write;
9844 const MockRead* extra_read;
9847 static const int kNoSSL = 500;
9849 struct TestConfig {
9850 const char* const proxy_url;
9851 AuthTiming proxy_auth_timing;
9852 int proxy_auth_rv;
9853 const char* const server_url;
9854 AuthTiming server_auth_timing;
9855 int server_auth_rv;
9856 int num_auth_rounds;
9857 int first_ssl_round;
9858 TestRound rounds[3];
9859 } test_configs[] = {
9860 // Non-authenticating HTTP server with a direct connection.
9861 { NULL, AUTH_NONE, OK, kServer, AUTH_NONE, OK, 1, kNoSSL,
9862 { TestRound(kGet, kSuccess, OK)}},
9863 // Authenticating HTTP server with a direct connection.
9864 { NULL, AUTH_NONE, OK, kServer, AUTH_SYNC, OK, 2, kNoSSL,
9865 { TestRound(kGet, kServerChallenge, OK),
9866 TestRound(kGetAuth, kSuccess, OK)}},
9867 { NULL, AUTH_NONE, OK, kServer, AUTH_SYNC, kAuthErr, 2, kNoSSL,
9868 { TestRound(kGet, kServerChallenge, OK),
9869 TestRound(kGetAuth, kFailure, kAuthErr)}},
9870 { NULL, AUTH_NONE, OK, kServer, AUTH_ASYNC, OK, 2, kNoSSL,
9871 { TestRound(kGet, kServerChallenge, OK),
9872 TestRound(kGetAuth, kSuccess, OK)}},
9873 { NULL, AUTH_NONE, OK, kServer, AUTH_ASYNC, kAuthErr, 2, kNoSSL,
9874 { TestRound(kGet, kServerChallenge, OK),
9875 TestRound(kGetAuth, kFailure, kAuthErr)}},
9876 // Non-authenticating HTTP server through a non-authenticating proxy.
9877 { kProxy, AUTH_NONE, OK, kServer, AUTH_NONE, OK, 1, kNoSSL,
9878 { TestRound(kGetProxy, kSuccess, OK)}},
9879 // Authenticating HTTP server through a non-authenticating proxy.
9880 { kProxy, AUTH_NONE, OK, kServer, AUTH_SYNC, OK, 2, kNoSSL,
9881 { TestRound(kGetProxy, kServerChallenge, OK),
9882 TestRound(kGetAuthThroughProxy, kSuccess, OK)}},
9883 { kProxy, AUTH_NONE, OK, kServer, AUTH_SYNC, kAuthErr, 2, kNoSSL,
9884 { TestRound(kGetProxy, kServerChallenge, OK),
9885 TestRound(kGetAuthThroughProxy, kFailure, kAuthErr)}},
9886 { kProxy, AUTH_NONE, OK, kServer, AUTH_ASYNC, OK, 2, kNoSSL,
9887 { TestRound(kGetProxy, kServerChallenge, OK),
9888 TestRound(kGetAuthThroughProxy, kSuccess, OK)}},
9889 { kProxy, AUTH_NONE, OK, kServer, AUTH_ASYNC, kAuthErr, 2, kNoSSL,
9890 { TestRound(kGetProxy, kServerChallenge, OK),
9891 TestRound(kGetAuthThroughProxy, kFailure, kAuthErr)}},
9892 // Non-authenticating HTTP server through an authenticating proxy.
9893 { kProxy, AUTH_SYNC, OK, kServer, AUTH_NONE, OK, 2, kNoSSL,
9894 { TestRound(kGetProxy, kProxyChallenge, OK),
9895 TestRound(kGetProxyAuth, kSuccess, OK)}},
9896 { kProxy, AUTH_SYNC, kAuthErr, kServer, AUTH_NONE, OK, 2, kNoSSL,
9897 { TestRound(kGetProxy, kProxyChallenge, OK),
9898 TestRound(kGetProxyAuth, kFailure, kAuthErr)}},
9899 { kProxy, AUTH_ASYNC, OK, kServer, AUTH_NONE, OK, 2, kNoSSL,
9900 { TestRound(kGetProxy, kProxyChallenge, OK),
9901 TestRound(kGetProxyAuth, kSuccess, OK)}},
9902 { kProxy, AUTH_ASYNC, kAuthErr, kServer, AUTH_NONE, OK, 2, kNoSSL,
9903 { TestRound(kGetProxy, kProxyChallenge, OK),
9904 TestRound(kGetProxyAuth, kFailure, kAuthErr)}},
9905 // Authenticating HTTP server through an authenticating proxy.
9906 { kProxy, AUTH_SYNC, OK, kServer, AUTH_SYNC, OK, 3, kNoSSL,
9907 { TestRound(kGetProxy, kProxyChallenge, OK),
9908 TestRound(kGetProxyAuth, kServerChallenge, OK),
9909 TestRound(kGetAuthWithProxyAuth, kSuccess, OK)}},
9910 { kProxy, AUTH_SYNC, OK, kServer, AUTH_SYNC, kAuthErr, 3, kNoSSL,
9911 { TestRound(kGetProxy, kProxyChallenge, OK),
9912 TestRound(kGetProxyAuth, kServerChallenge, OK),
9913 TestRound(kGetAuthWithProxyAuth, kFailure, kAuthErr)}},
9914 { kProxy, AUTH_ASYNC, OK, kServer, AUTH_SYNC, OK, 3, kNoSSL,
9915 { TestRound(kGetProxy, kProxyChallenge, OK),
9916 TestRound(kGetProxyAuth, kServerChallenge, OK),
9917 TestRound(kGetAuthWithProxyAuth, kSuccess, OK)}},
9918 { kProxy, AUTH_ASYNC, OK, kServer, AUTH_SYNC, kAuthErr, 3, kNoSSL,
9919 { TestRound(kGetProxy, kProxyChallenge, OK),
9920 TestRound(kGetProxyAuth, kServerChallenge, OK),
9921 TestRound(kGetAuthWithProxyAuth, kFailure, kAuthErr)}},
9922 { kProxy, AUTH_SYNC, OK, kServer, AUTH_ASYNC, OK, 3, kNoSSL,
9923 { TestRound(kGetProxy, kProxyChallenge, OK),
9924 TestRound(kGetProxyAuth, kServerChallenge, OK),
9925 TestRound(kGetAuthWithProxyAuth, kSuccess, OK)}},
9926 { kProxy, AUTH_SYNC, OK, kServer, AUTH_ASYNC, kAuthErr, 3, kNoSSL,
9927 { TestRound(kGetProxy, kProxyChallenge, OK),
9928 TestRound(kGetProxyAuth, kServerChallenge, OK),
9929 TestRound(kGetAuthWithProxyAuth, kFailure, kAuthErr)}},
9930 { kProxy, AUTH_ASYNC, OK, kServer, AUTH_ASYNC, OK, 3, kNoSSL,
9931 { TestRound(kGetProxy, kProxyChallenge, OK),
9932 TestRound(kGetProxyAuth, kServerChallenge, OK),
9933 TestRound(kGetAuthWithProxyAuth, kSuccess, OK)}},
9934 { kProxy, AUTH_ASYNC, OK, kServer, AUTH_ASYNC, kAuthErr, 3, kNoSSL,
9935 { TestRound(kGetProxy, kProxyChallenge, OK),
9936 TestRound(kGetProxyAuth, kServerChallenge, OK),
9937 TestRound(kGetAuthWithProxyAuth, kFailure, kAuthErr)}},
9938 // Non-authenticating HTTPS server with a direct connection.
9939 { NULL, AUTH_NONE, OK, kSecureServer, AUTH_NONE, OK, 1, 0,
9940 { TestRound(kGet, kSuccess, OK)}},
9941 // Authenticating HTTPS server with a direct connection.
9942 { NULL, AUTH_NONE, OK, kSecureServer, AUTH_SYNC, OK, 2, 0,
9943 { TestRound(kGet, kServerChallenge, OK),
9944 TestRound(kGetAuth, kSuccess, OK)}},
9945 { NULL, AUTH_NONE, OK, kSecureServer, AUTH_SYNC, kAuthErr, 2, 0,
9946 { TestRound(kGet, kServerChallenge, OK),
9947 TestRound(kGetAuth, kFailure, kAuthErr)}},
9948 { NULL, AUTH_NONE, OK, kSecureServer, AUTH_ASYNC, OK, 2, 0,
9949 { TestRound(kGet, kServerChallenge, OK),
9950 TestRound(kGetAuth, kSuccess, OK)}},
9951 { NULL, AUTH_NONE, OK, kSecureServer, AUTH_ASYNC, kAuthErr, 2, 0,
9952 { TestRound(kGet, kServerChallenge, OK),
9953 TestRound(kGetAuth, kFailure, kAuthErr)}},
9954 // Non-authenticating HTTPS server with a non-authenticating proxy.
9955 { kProxy, AUTH_NONE, OK, kSecureServer, AUTH_NONE, OK, 1, 0,
9956 { TestRound(kConnect, kProxyConnected, OK, &kGet, &kSuccess)}},
9957 // Authenticating HTTPS server through a non-authenticating proxy.
9958 { kProxy, AUTH_NONE, OK, kSecureServer, AUTH_SYNC, OK, 2, 0,
9959 { TestRound(kConnect, kProxyConnected, OK, &kGet, &kServerChallenge),
9960 TestRound(kGetAuth, kSuccess, OK)}},
9961 { kProxy, AUTH_NONE, OK, kSecureServer, AUTH_SYNC, kAuthErr, 2, 0,
9962 { TestRound(kConnect, kProxyConnected, OK, &kGet, &kServerChallenge),
9963 TestRound(kGetAuth, kFailure, kAuthErr)}},
9964 { kProxy, AUTH_NONE, OK, kSecureServer, AUTH_ASYNC, OK, 2, 0,
9965 { TestRound(kConnect, kProxyConnected, OK, &kGet, &kServerChallenge),
9966 TestRound(kGetAuth, kSuccess, OK)}},
9967 { kProxy, AUTH_NONE, OK, kSecureServer, AUTH_ASYNC, kAuthErr, 2, 0,
9968 { TestRound(kConnect, kProxyConnected, OK, &kGet, &kServerChallenge),
9969 TestRound(kGetAuth, kFailure, kAuthErr)}},
9970 // Non-Authenticating HTTPS server through an authenticating proxy.
9971 { kProxy, AUTH_SYNC, OK, kSecureServer, AUTH_NONE, OK, 2, 1,
9972 { TestRound(kConnect, kProxyChallenge, OK),
9973 TestRound(kConnectProxyAuth, kProxyConnected, OK, &kGet, &kSuccess)}},
9974 { kProxy, AUTH_SYNC, kAuthErr, kSecureServer, AUTH_NONE, OK, 2, kNoSSL,
9975 { TestRound(kConnect, kProxyChallenge, OK),
9976 TestRound(kConnectProxyAuth, kFailure, kAuthErr)}},
9977 { kProxy, AUTH_ASYNC, OK, kSecureServer, AUTH_NONE, OK, 2, 1,
9978 { TestRound(kConnect, kProxyChallenge, OK),
9979 TestRound(kConnectProxyAuth, kProxyConnected, OK, &kGet, &kSuccess)}},
9980 { kProxy, AUTH_ASYNC, kAuthErr, kSecureServer, AUTH_NONE, OK, 2, kNoSSL,
9981 { TestRound(kConnect, kProxyChallenge, OK),
9982 TestRound(kConnectProxyAuth, kFailure, kAuthErr)}},
9983 // Authenticating HTTPS server through an authenticating proxy.
9984 { kProxy, AUTH_SYNC, OK, kSecureServer, AUTH_SYNC, OK, 3, 1,
9985 { TestRound(kConnect, kProxyChallenge, OK),
9986 TestRound(kConnectProxyAuth, kProxyConnected, OK,
9987 &kGet, &kServerChallenge),
9988 TestRound(kGetAuth, kSuccess, OK)}},
9989 { kProxy, AUTH_SYNC, OK, kSecureServer, AUTH_SYNC, kAuthErr, 3, 1,
9990 { TestRound(kConnect, kProxyChallenge, OK),
9991 TestRound(kConnectProxyAuth, kProxyConnected, OK,
9992 &kGet, &kServerChallenge),
9993 TestRound(kGetAuth, kFailure, kAuthErr)}},
9994 { kProxy, AUTH_ASYNC, OK, kSecureServer, AUTH_SYNC, OK, 3, 1,
9995 { TestRound(kConnect, kProxyChallenge, OK),
9996 TestRound(kConnectProxyAuth, kProxyConnected, OK,
9997 &kGet, &kServerChallenge),
9998 TestRound(kGetAuth, kSuccess, OK)}},
9999 { kProxy, AUTH_ASYNC, OK, kSecureServer, AUTH_SYNC, kAuthErr, 3, 1,
10000 { TestRound(kConnect, kProxyChallenge, OK),
10001 TestRound(kConnectProxyAuth, kProxyConnected, OK,
10002 &kGet, &kServerChallenge),
10003 TestRound(kGetAuth, kFailure, kAuthErr)}},
10004 { kProxy, AUTH_SYNC, OK, kSecureServer, AUTH_ASYNC, OK, 3, 1,
10005 { TestRound(kConnect, kProxyChallenge, OK),
10006 TestRound(kConnectProxyAuth, kProxyConnected, OK,
10007 &kGet, &kServerChallenge),
10008 TestRound(kGetAuth, kSuccess, OK)}},
10009 { kProxy, AUTH_SYNC, OK, kSecureServer, AUTH_ASYNC, kAuthErr, 3, 1,
10010 { TestRound(kConnect, kProxyChallenge, OK),
10011 TestRound(kConnectProxyAuth, kProxyConnected, OK,
10012 &kGet, &kServerChallenge),
10013 TestRound(kGetAuth, kFailure, kAuthErr)}},
10014 { kProxy, AUTH_ASYNC, OK, kSecureServer, AUTH_ASYNC, OK, 3, 1,
10015 { TestRound(kConnect, kProxyChallenge, OK),
10016 TestRound(kConnectProxyAuth, kProxyConnected, OK,
10017 &kGet, &kServerChallenge),
10018 TestRound(kGetAuth, kSuccess, OK)}},
10019 { kProxy, AUTH_ASYNC, OK, kSecureServer, AUTH_ASYNC, kAuthErr, 3, 1,
10020 { TestRound(kConnect, kProxyChallenge, OK),
10021 TestRound(kConnectProxyAuth, kProxyConnected, OK,
10022 &kGet, &kServerChallenge),
10023 TestRound(kGetAuth, kFailure, kAuthErr)}},
10026 for (size_t i = 0; i < arraysize(test_configs); ++i) {
10027 HttpAuthHandlerMock::Factory* auth_factory(
10028 new HttpAuthHandlerMock::Factory());
10029 session_deps_.http_auth_handler_factory.reset(auth_factory);
10030 const TestConfig& test_config = test_configs[i];
10032 // Set up authentication handlers as necessary.
10033 if (test_config.proxy_auth_timing != AUTH_NONE) {
10034 for (int n = 0; n < 2; n++) {
10035 HttpAuthHandlerMock* auth_handler(new HttpAuthHandlerMock());
10036 std::string auth_challenge = "Mock realm=proxy";
10037 GURL origin(test_config.proxy_url);
10038 HttpAuthChallengeTokenizer tokenizer(auth_challenge.begin(),
10039 auth_challenge.end());
10040 auth_handler->InitFromChallenge(&tokenizer, HttpAuth::AUTH_PROXY,
10041 origin, BoundNetLog());
10042 auth_handler->SetGenerateExpectation(
10043 test_config.proxy_auth_timing == AUTH_ASYNC,
10044 test_config.proxy_auth_rv);
10045 auth_factory->AddMockHandler(auth_handler, HttpAuth::AUTH_PROXY);
10048 if (test_config.server_auth_timing != AUTH_NONE) {
10049 HttpAuthHandlerMock* auth_handler(new HttpAuthHandlerMock());
10050 std::string auth_challenge = "Mock realm=server";
10051 GURL origin(test_config.server_url);
10052 HttpAuthChallengeTokenizer tokenizer(auth_challenge.begin(),
10053 auth_challenge.end());
10054 auth_handler->InitFromChallenge(&tokenizer, HttpAuth::AUTH_SERVER,
10055 origin, BoundNetLog());
10056 auth_handler->SetGenerateExpectation(
10057 test_config.server_auth_timing == AUTH_ASYNC,
10058 test_config.server_auth_rv);
10059 auth_factory->AddMockHandler(auth_handler, HttpAuth::AUTH_SERVER);
10061 if (test_config.proxy_url) {
10062 session_deps_.proxy_service.reset(
10063 ProxyService::CreateFixed(test_config.proxy_url));
10064 } else {
10065 session_deps_.proxy_service.reset(ProxyService::CreateDirect());
10068 HttpRequestInfo request;
10069 request.method = "GET";
10070 request.url = GURL(test_config.server_url);
10071 request.load_flags = 0;
10073 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10074 HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
10076 for (int round = 0; round < test_config.num_auth_rounds; ++round) {
10077 const TestRound& read_write_round = test_config.rounds[round];
10079 // Set up expected reads and writes.
10080 MockRead reads[2];
10081 reads[0] = read_write_round.read;
10082 size_t length_reads = 1;
10083 if (read_write_round.extra_read) {
10084 reads[1] = *read_write_round.extra_read;
10085 length_reads = 2;
10088 MockWrite writes[2];
10089 writes[0] = read_write_round.write;
10090 size_t length_writes = 1;
10091 if (read_write_round.extra_write) {
10092 writes[1] = *read_write_round.extra_write;
10093 length_writes = 2;
10095 StaticSocketDataProvider data_provider(
10096 reads, length_reads, writes, length_writes);
10097 session_deps_.socket_factory->AddSocketDataProvider(&data_provider);
10099 // Add an SSL sequence if necessary.
10100 SSLSocketDataProvider ssl_socket_data_provider(SYNCHRONOUS, OK);
10101 if (round >= test_config.first_ssl_round)
10102 session_deps_.socket_factory->AddSSLSocketDataProvider(
10103 &ssl_socket_data_provider);
10105 // Start or restart the transaction.
10106 TestCompletionCallback callback;
10107 int rv;
10108 if (round == 0) {
10109 rv = trans.Start(&request, callback.callback(), BoundNetLog());
10110 } else {
10111 rv = trans.RestartWithAuth(
10112 AuthCredentials(kFoo, kBar), callback.callback());
10114 if (rv == ERR_IO_PENDING)
10115 rv = callback.WaitForResult();
10117 // Compare results with expected data.
10118 EXPECT_EQ(read_write_round.expected_rv, rv);
10119 const HttpResponseInfo* response = trans.GetResponseInfo();
10120 if (read_write_round.expected_rv == OK) {
10121 ASSERT_TRUE(response != NULL);
10122 } else {
10123 EXPECT_TRUE(response == NULL);
10124 EXPECT_EQ(round + 1, test_config.num_auth_rounds);
10125 continue;
10127 if (round + 1 < test_config.num_auth_rounds) {
10128 EXPECT_FALSE(response->auth_challenge.get() == NULL);
10129 } else {
10130 EXPECT_TRUE(response->auth_challenge.get() == NULL);
10136 TEST_P(HttpNetworkTransactionTest, MultiRoundAuth) {
10137 // Do multi-round authentication and make sure it works correctly.
10138 HttpAuthHandlerMock::Factory* auth_factory(
10139 new HttpAuthHandlerMock::Factory());
10140 session_deps_.http_auth_handler_factory.reset(auth_factory);
10141 session_deps_.proxy_service.reset(ProxyService::CreateDirect());
10142 session_deps_.host_resolver->rules()->AddRule("www.example.com", "10.0.0.1");
10143 session_deps_.host_resolver->set_synchronous_mode(true);
10145 HttpAuthHandlerMock* auth_handler(new HttpAuthHandlerMock());
10146 auth_handler->set_connection_based(true);
10147 std::string auth_challenge = "Mock realm=server";
10148 GURL origin("http://www.example.com");
10149 HttpAuthChallengeTokenizer tokenizer(auth_challenge.begin(),
10150 auth_challenge.end());
10151 auth_handler->InitFromChallenge(&tokenizer, HttpAuth::AUTH_SERVER,
10152 origin, BoundNetLog());
10153 auth_factory->AddMockHandler(auth_handler, HttpAuth::AUTH_SERVER);
10155 int rv = OK;
10156 const HttpResponseInfo* response = NULL;
10157 HttpRequestInfo request;
10158 request.method = "GET";
10159 request.url = origin;
10160 request.load_flags = 0;
10162 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10164 // Use a TCP Socket Pool with only one connection per group. This is used
10165 // to validate that the TCP socket is not released to the pool between
10166 // each round of multi-round authentication.
10167 HttpNetworkSessionPeer session_peer(session);
10168 TransportClientSocketPool* transport_pool = new TransportClientSocketPool(
10169 50, // Max sockets for pool
10170 1, // Max sockets per group
10171 session_deps_.host_resolver.get(),
10172 session_deps_.socket_factory.get(),
10173 session_deps_.net_log);
10174 scoped_ptr<MockClientSocketPoolManager> mock_pool_manager(
10175 new MockClientSocketPoolManager);
10176 mock_pool_manager->SetTransportSocketPool(transport_pool);
10177 session_peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
10179 scoped_ptr<HttpTransaction> trans(
10180 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10181 TestCompletionCallback callback;
10183 const MockWrite kGet(
10184 "GET / HTTP/1.1\r\n"
10185 "Host: www.example.com\r\n"
10186 "Connection: keep-alive\r\n\r\n");
10187 const MockWrite kGetAuth(
10188 "GET / HTTP/1.1\r\n"
10189 "Host: www.example.com\r\n"
10190 "Connection: keep-alive\r\n"
10191 "Authorization: auth_token\r\n\r\n");
10193 const MockRead kServerChallenge(
10194 "HTTP/1.1 401 Unauthorized\r\n"
10195 "WWW-Authenticate: Mock realm=server\r\n"
10196 "Content-Type: text/html; charset=iso-8859-1\r\n"
10197 "Content-Length: 14\r\n\r\n"
10198 "Unauthorized\r\n");
10199 const MockRead kSuccess(
10200 "HTTP/1.1 200 OK\r\n"
10201 "Content-Type: text/html; charset=iso-8859-1\r\n"
10202 "Content-Length: 3\r\n\r\n"
10203 "Yes");
10205 MockWrite writes[] = {
10206 // First round
10207 kGet,
10208 // Second round
10209 kGetAuth,
10210 // Third round
10211 kGetAuth,
10212 // Fourth round
10213 kGetAuth,
10214 // Competing request
10215 kGet,
10217 MockRead reads[] = {
10218 // First round
10219 kServerChallenge,
10220 // Second round
10221 kServerChallenge,
10222 // Third round
10223 kServerChallenge,
10224 // Fourth round
10225 kSuccess,
10226 // Competing response
10227 kSuccess,
10229 StaticSocketDataProvider data_provider(reads, arraysize(reads),
10230 writes, arraysize(writes));
10231 session_deps_.socket_factory->AddSocketDataProvider(&data_provider);
10233 const char kSocketGroup[] = "www.example.com:80";
10235 // First round of authentication.
10236 auth_handler->SetGenerateExpectation(false, OK);
10237 rv = trans->Start(&request, callback.callback(), BoundNetLog());
10238 if (rv == ERR_IO_PENDING)
10239 rv = callback.WaitForResult();
10240 EXPECT_EQ(OK, rv);
10241 response = trans->GetResponseInfo();
10242 ASSERT_TRUE(response != NULL);
10243 EXPECT_FALSE(response->auth_challenge.get() == NULL);
10244 EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10246 // In between rounds, another request comes in for the same domain.
10247 // It should not be able to grab the TCP socket that trans has already
10248 // claimed.
10249 scoped_ptr<HttpTransaction> trans_compete(
10250 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10251 TestCompletionCallback callback_compete;
10252 rv = trans_compete->Start(
10253 &request, callback_compete.callback(), BoundNetLog());
10254 EXPECT_EQ(ERR_IO_PENDING, rv);
10255 // callback_compete.WaitForResult at this point would stall forever,
10256 // since the HttpNetworkTransaction does not release the request back to
10257 // the pool until after authentication completes.
10259 // Second round of authentication.
10260 auth_handler->SetGenerateExpectation(false, OK);
10261 rv = trans->RestartWithAuth(AuthCredentials(kFoo, kBar), callback.callback());
10262 if (rv == ERR_IO_PENDING)
10263 rv = callback.WaitForResult();
10264 EXPECT_EQ(OK, rv);
10265 response = trans->GetResponseInfo();
10266 ASSERT_TRUE(response != NULL);
10267 EXPECT_TRUE(response->auth_challenge.get() == NULL);
10268 EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10270 // Third round of authentication.
10271 auth_handler->SetGenerateExpectation(false, OK);
10272 rv = trans->RestartWithAuth(AuthCredentials(), callback.callback());
10273 if (rv == ERR_IO_PENDING)
10274 rv = callback.WaitForResult();
10275 EXPECT_EQ(OK, rv);
10276 response = trans->GetResponseInfo();
10277 ASSERT_TRUE(response != NULL);
10278 EXPECT_TRUE(response->auth_challenge.get() == NULL);
10279 EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10281 // Fourth round of authentication, which completes successfully.
10282 auth_handler->SetGenerateExpectation(false, OK);
10283 rv = trans->RestartWithAuth(AuthCredentials(), callback.callback());
10284 if (rv == ERR_IO_PENDING)
10285 rv = callback.WaitForResult();
10286 EXPECT_EQ(OK, rv);
10287 response = trans->GetResponseInfo();
10288 ASSERT_TRUE(response != NULL);
10289 EXPECT_TRUE(response->auth_challenge.get() == NULL);
10290 EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10292 // Read the body since the fourth round was successful. This will also
10293 // release the socket back to the pool.
10294 scoped_refptr<IOBufferWithSize> io_buf(new IOBufferWithSize(50));
10295 rv = trans->Read(io_buf.get(), io_buf->size(), callback.callback());
10296 if (rv == ERR_IO_PENDING)
10297 rv = callback.WaitForResult();
10298 EXPECT_EQ(3, rv);
10299 rv = trans->Read(io_buf.get(), io_buf->size(), callback.callback());
10300 EXPECT_EQ(0, rv);
10301 // There are still 0 idle sockets, since the trans_compete transaction
10302 // will be handed it immediately after trans releases it to the group.
10303 EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10305 // The competing request can now finish. Wait for the headers and then
10306 // read the body.
10307 rv = callback_compete.WaitForResult();
10308 EXPECT_EQ(OK, rv);
10309 rv = trans_compete->Read(io_buf.get(), io_buf->size(), callback.callback());
10310 if (rv == ERR_IO_PENDING)
10311 rv = callback.WaitForResult();
10312 EXPECT_EQ(3, rv);
10313 rv = trans_compete->Read(io_buf.get(), io_buf->size(), callback.callback());
10314 EXPECT_EQ(0, rv);
10316 // Finally, the socket is released to the group.
10317 EXPECT_EQ(1, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10320 // This tests the case that a request is issued via http instead of spdy after
10321 // npn is negotiated.
10322 TEST_P(HttpNetworkTransactionTest, NpnWithHttpOverSSL) {
10323 session_deps_.use_alternate_protocols = true;
10324 NextProtoVector next_protos;
10325 next_protos.push_back(kProtoHTTP11);
10326 session_deps_.next_protos = next_protos;
10328 HttpRequestInfo request;
10329 request.method = "GET";
10330 request.url = GURL("https://www.google.com/");
10331 request.load_flags = 0;
10333 MockWrite data_writes[] = {
10334 MockWrite("GET / HTTP/1.1\r\n"
10335 "Host: www.google.com\r\n"
10336 "Connection: keep-alive\r\n\r\n"),
10339 std::string alternate_protocol_http_header =
10340 GetAlternateProtocolHttpHeader();
10342 MockRead data_reads[] = {
10343 MockRead("HTTP/1.1 200 OK\r\n"),
10344 MockRead(alternate_protocol_http_header.c_str()),
10345 MockRead("hello world"),
10346 MockRead(SYNCHRONOUS, OK),
10349 SSLSocketDataProvider ssl(ASYNC, OK);
10350 ssl.next_proto_status = SSLClientSocket::kNextProtoNegotiated;
10351 ssl.next_proto = "http/1.1";
10352 ssl.protocol_negotiated = kProtoHTTP11;
10354 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
10356 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
10357 data_writes, arraysize(data_writes));
10358 session_deps_.socket_factory->AddSocketDataProvider(&data);
10360 TestCompletionCallback callback;
10362 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10363 scoped_ptr<HttpTransaction> trans(
10364 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10366 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
10368 EXPECT_EQ(ERR_IO_PENDING, rv);
10369 EXPECT_EQ(OK, callback.WaitForResult());
10371 const HttpResponseInfo* response = trans->GetResponseInfo();
10372 ASSERT_TRUE(response != NULL);
10373 ASSERT_TRUE(response->headers.get() != NULL);
10374 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
10376 std::string response_data;
10377 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
10378 EXPECT_EQ("hello world", response_data);
10380 EXPECT_FALSE(response->was_fetched_via_spdy);
10381 EXPECT_TRUE(response->was_npn_negotiated);
10384 TEST_P(HttpNetworkTransactionTest, SpdyPostNPNServerHangup) {
10385 // Simulate the SSL handshake completing with an NPN negotiation
10386 // followed by an immediate server closing of the socket.
10387 // Fix crash: http://crbug.com/46369
10388 session_deps_.use_alternate_protocols = true;
10389 session_deps_.next_protos = SpdyNextProtos();
10391 HttpRequestInfo request;
10392 request.method = "GET";
10393 request.url = GURL("https://www.google.com/");
10394 request.load_flags = 0;
10396 SSLSocketDataProvider ssl(ASYNC, OK);
10397 ssl.SetNextProto(GetParam());
10398 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
10400 scoped_ptr<SpdyFrame> req(
10401 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, true));
10402 MockWrite spdy_writes[] = { CreateMockWrite(*req) };
10404 MockRead spdy_reads[] = {
10405 MockRead(SYNCHRONOUS, 0, 0) // Not async - return 0 immediately.
10408 DelayedSocketData spdy_data(
10409 0, // don't wait in this case, immediate hangup.
10410 spdy_reads, arraysize(spdy_reads),
10411 spdy_writes, arraysize(spdy_writes));
10412 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
10414 TestCompletionCallback callback;
10416 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10417 scoped_ptr<HttpTransaction> trans(
10418 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10420 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
10421 EXPECT_EQ(ERR_IO_PENDING, rv);
10422 EXPECT_EQ(ERR_CONNECTION_CLOSED, callback.WaitForResult());
10425 // A subclass of HttpAuthHandlerMock that records the request URL when
10426 // it gets it. This is needed since the auth handler may get destroyed
10427 // before we get a chance to query it.
10428 class UrlRecordingHttpAuthHandlerMock : public HttpAuthHandlerMock {
10429 public:
10430 explicit UrlRecordingHttpAuthHandlerMock(GURL* url) : url_(url) {}
10432 ~UrlRecordingHttpAuthHandlerMock() override {}
10434 protected:
10435 int GenerateAuthTokenImpl(const AuthCredentials* credentials,
10436 const HttpRequestInfo* request,
10437 const CompletionCallback& callback,
10438 std::string* auth_token) override {
10439 *url_ = request->url;
10440 return HttpAuthHandlerMock::GenerateAuthTokenImpl(
10441 credentials, request, callback, auth_token);
10444 private:
10445 GURL* url_;
10448 TEST_P(HttpNetworkTransactionTest, SpdyAlternateProtocolThroughProxy) {
10449 // This test ensures that the URL passed into the proxy is upgraded
10450 // to https when doing an Alternate Protocol upgrade.
10451 session_deps_.use_alternate_protocols = true;
10452 session_deps_.next_protos = SpdyNextProtos();
10454 session_deps_.proxy_service.reset(
10455 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
10456 CapturingNetLog net_log;
10457 session_deps_.net_log = &net_log;
10458 GURL request_url;
10460 HttpAuthHandlerMock::Factory* auth_factory =
10461 new HttpAuthHandlerMock::Factory();
10462 UrlRecordingHttpAuthHandlerMock* auth_handler =
10463 new UrlRecordingHttpAuthHandlerMock(&request_url);
10464 auth_factory->AddMockHandler(auth_handler, HttpAuth::AUTH_PROXY);
10465 auth_factory->set_do_init_from_challenge(true);
10466 session_deps_.http_auth_handler_factory.reset(auth_factory);
10469 HttpRequestInfo request;
10470 request.method = "GET";
10471 request.url = GURL("http://www.google.com");
10472 request.load_flags = 0;
10474 // First round goes unauthenticated through the proxy.
10475 MockWrite data_writes_1[] = {
10476 MockWrite("GET http://www.google.com/ HTTP/1.1\r\n"
10477 "Host: www.google.com\r\n"
10478 "Proxy-Connection: keep-alive\r\n"
10479 "\r\n"),
10481 MockRead data_reads_1[] = {
10482 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
10483 MockRead("HTTP/1.1 200 OK\r\n"),
10484 MockRead("Alternate-Protocol: 443:"),
10485 MockRead(GetAlternateProtocolFromParam()),
10486 MockRead("\r\n"),
10487 MockRead("Proxy-Connection: close\r\n"),
10488 MockRead("\r\n"),
10490 StaticSocketDataProvider data_1(data_reads_1, arraysize(data_reads_1),
10491 data_writes_1, arraysize(data_writes_1));
10493 // Second round tries to tunnel to www.google.com due to the
10494 // Alternate-Protocol announcement in the first round. It fails due
10495 // to a proxy authentication challenge.
10496 // After the failure, a tunnel is established to www.google.com using
10497 // Proxy-Authorization headers. There is then a SPDY request round.
10499 // NOTE: Despite the "Proxy-Connection: Close", these are done on the
10500 // same MockTCPClientSocket since the underlying HttpNetworkClientSocket
10501 // does a Disconnect and Connect on the same socket, rather than trying
10502 // to obtain a new one.
10504 // NOTE: Originally, the proxy response to the second CONNECT request
10505 // simply returned another 407 so the unit test could skip the SSL connection
10506 // establishment and SPDY framing issues. Alas, the
10507 // retry-http-when-alternate-protocol fails logic kicks in, which was more
10508 // complicated to set up expectations for than the SPDY session.
10510 scoped_ptr<SpdyFrame> req(
10511 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, true));
10512 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
10513 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
10515 MockWrite data_writes_2[] = {
10516 // First connection attempt without Proxy-Authorization.
10517 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
10518 "Host: www.google.com\r\n"
10519 "Proxy-Connection: keep-alive\r\n"
10520 "\r\n"),
10522 // Second connection attempt with Proxy-Authorization.
10523 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
10524 "Host: www.google.com\r\n"
10525 "Proxy-Connection: keep-alive\r\n"
10526 "Proxy-Authorization: auth_token\r\n"
10527 "\r\n"),
10529 // SPDY request
10530 CreateMockWrite(*req),
10532 const char kRejectConnectResponse[] = ("HTTP/1.1 407 Unauthorized\r\n"
10533 "Proxy-Authenticate: Mock\r\n"
10534 "Proxy-Connection: close\r\n"
10535 "\r\n");
10536 const char kAcceptConnectResponse[] = "HTTP/1.1 200 Connected\r\n\r\n";
10537 MockRead data_reads_2[] = {
10538 // First connection attempt fails
10539 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ, 1),
10540 MockRead(ASYNC, kRejectConnectResponse,
10541 arraysize(kRejectConnectResponse) - 1, 1),
10543 // Second connection attempt passes
10544 MockRead(ASYNC, kAcceptConnectResponse,
10545 arraysize(kAcceptConnectResponse) -1, 4),
10547 // SPDY response
10548 CreateMockRead(*resp.get(), 6),
10549 CreateMockRead(*data.get(), 6),
10550 MockRead(ASYNC, 0, 0, 6),
10552 OrderedSocketData data_2(
10553 data_reads_2, arraysize(data_reads_2),
10554 data_writes_2, arraysize(data_writes_2));
10556 SSLSocketDataProvider ssl(ASYNC, OK);
10557 ssl.SetNextProto(GetParam());
10559 MockConnect never_finishing_connect(SYNCHRONOUS, ERR_IO_PENDING);
10560 StaticSocketDataProvider hanging_non_alternate_protocol_socket(
10561 NULL, 0, NULL, 0);
10562 hanging_non_alternate_protocol_socket.set_connect_data(
10563 never_finishing_connect);
10565 session_deps_.socket_factory->AddSocketDataProvider(&data_1);
10566 session_deps_.socket_factory->AddSocketDataProvider(&data_2);
10567 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
10568 session_deps_.socket_factory->AddSocketDataProvider(
10569 &hanging_non_alternate_protocol_socket);
10570 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10572 // First round should work and provide the Alternate-Protocol state.
10573 TestCompletionCallback callback_1;
10574 scoped_ptr<HttpTransaction> trans_1(
10575 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10576 int rv = trans_1->Start(&request, callback_1.callback(), BoundNetLog());
10577 EXPECT_EQ(ERR_IO_PENDING, rv);
10578 EXPECT_EQ(OK, callback_1.WaitForResult());
10580 // Second round should attempt a tunnel connect and get an auth challenge.
10581 TestCompletionCallback callback_2;
10582 scoped_ptr<HttpTransaction> trans_2(
10583 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10584 rv = trans_2->Start(&request, callback_2.callback(), BoundNetLog());
10585 EXPECT_EQ(ERR_IO_PENDING, rv);
10586 EXPECT_EQ(OK, callback_2.WaitForResult());
10587 const HttpResponseInfo* response = trans_2->GetResponseInfo();
10588 ASSERT_TRUE(response != NULL);
10589 ASSERT_FALSE(response->auth_challenge.get() == NULL);
10591 // Restart with auth. Tunnel should work and response received.
10592 TestCompletionCallback callback_3;
10593 rv = trans_2->RestartWithAuth(
10594 AuthCredentials(kFoo, kBar), callback_3.callback());
10595 EXPECT_EQ(ERR_IO_PENDING, rv);
10596 EXPECT_EQ(OK, callback_3.WaitForResult());
10598 // After all that work, these two lines (or actually, just the scheme) are
10599 // what this test is all about. Make sure it happens correctly.
10600 EXPECT_EQ("https", request_url.scheme());
10601 EXPECT_EQ("www.google.com", request_url.host());
10603 LoadTimingInfo load_timing_info;
10604 EXPECT_TRUE(trans_2->GetLoadTimingInfo(&load_timing_info));
10605 TestLoadTimingNotReusedWithPac(load_timing_info,
10606 CONNECT_TIMING_HAS_SSL_TIMES);
10609 // Test that if we cancel the transaction as the connection is completing, that
10610 // everything tears down correctly.
10611 TEST_P(HttpNetworkTransactionTest, SimpleCancel) {
10612 // Setup everything about the connection to complete synchronously, so that
10613 // after calling HttpNetworkTransaction::Start, the only thing we're waiting
10614 // for is the callback from the HttpStreamRequest.
10615 // Then cancel the transaction.
10616 // Verify that we don't crash.
10617 MockConnect mock_connect(SYNCHRONOUS, OK);
10618 MockRead data_reads[] = {
10619 MockRead(SYNCHRONOUS, "HTTP/1.0 200 OK\r\n\r\n"),
10620 MockRead(SYNCHRONOUS, "hello world"),
10621 MockRead(SYNCHRONOUS, OK),
10624 HttpRequestInfo request;
10625 request.method = "GET";
10626 request.url = GURL("http://www.google.com/");
10627 request.load_flags = 0;
10629 session_deps_.host_resolver->set_synchronous_mode(true);
10630 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10631 scoped_ptr<HttpTransaction> trans(
10632 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10634 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
10635 data.set_connect_data(mock_connect);
10636 session_deps_.socket_factory->AddSocketDataProvider(&data);
10638 TestCompletionCallback callback;
10640 CapturingBoundNetLog log;
10641 int rv = trans->Start(&request, callback.callback(), log.bound());
10642 EXPECT_EQ(ERR_IO_PENDING, rv);
10643 trans.reset(); // Cancel the transaction here.
10645 base::MessageLoop::current()->RunUntilIdle();
10648 // Test that if a transaction is cancelled after receiving the headers, the
10649 // stream is drained properly and added back to the socket pool. The main
10650 // purpose of this test is to make sure that an HttpStreamParser can be read
10651 // from after the HttpNetworkTransaction and the objects it owns have been
10652 // deleted.
10653 // See http://crbug.com/368418
10654 TEST_P(HttpNetworkTransactionTest, CancelAfterHeaders) {
10655 MockRead data_reads[] = {
10656 MockRead(ASYNC, "HTTP/1.1 200 OK\r\n"),
10657 MockRead(ASYNC, "Content-Length: 2\r\n"),
10658 MockRead(ASYNC, "Connection: Keep-Alive\r\n\r\n"),
10659 MockRead(ASYNC, "1"),
10660 // 2 async reads are necessary to trigger a ReadResponseBody call after the
10661 // HttpNetworkTransaction has been deleted.
10662 MockRead(ASYNC, "2"),
10663 MockRead(SYNCHRONOUS, ERR_IO_PENDING), // Should never read this.
10665 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
10666 session_deps_.socket_factory->AddSocketDataProvider(&data);
10668 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10671 HttpRequestInfo request;
10672 request.method = "GET";
10673 request.url = GURL("http://www.google.com/");
10674 request.load_flags = 0;
10676 HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
10677 TestCompletionCallback callback;
10679 int rv = trans.Start(&request, callback.callback(), BoundNetLog());
10680 EXPECT_EQ(ERR_IO_PENDING, rv);
10681 callback.WaitForResult();
10683 const HttpResponseInfo* response = trans.GetResponseInfo();
10684 ASSERT_TRUE(response != NULL);
10685 EXPECT_TRUE(response->headers.get() != NULL);
10686 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
10688 // The transaction and HttpRequestInfo are deleted.
10691 // Let the HttpResponseBodyDrainer drain the socket.
10692 base::MessageLoop::current()->RunUntilIdle();
10694 // Socket should now be idle, waiting to be reused.
10695 EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
10698 // Test a basic GET request through a proxy.
10699 TEST_P(HttpNetworkTransactionTest, ProxyGet) {
10700 session_deps_.proxy_service.reset(
10701 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
10702 CapturingBoundNetLog log;
10703 session_deps_.net_log = log.bound().net_log();
10704 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10706 HttpRequestInfo request;
10707 request.method = "GET";
10708 request.url = GURL("http://www.google.com/");
10710 MockWrite data_writes1[] = {
10711 MockWrite("GET http://www.google.com/ HTTP/1.1\r\n"
10712 "Host: www.google.com\r\n"
10713 "Proxy-Connection: keep-alive\r\n\r\n"),
10716 MockRead data_reads1[] = {
10717 MockRead("HTTP/1.1 200 OK\r\n"),
10718 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
10719 MockRead("Content-Length: 100\r\n\r\n"),
10720 MockRead(SYNCHRONOUS, OK),
10723 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
10724 data_writes1, arraysize(data_writes1));
10725 session_deps_.socket_factory->AddSocketDataProvider(&data1);
10727 TestCompletionCallback callback1;
10729 scoped_ptr<HttpTransaction> trans(
10730 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10731 BeforeProxyHeadersSentHandler proxy_headers_handler;
10732 trans->SetBeforeProxyHeadersSentCallback(
10733 base::Bind(&BeforeProxyHeadersSentHandler::OnBeforeProxyHeadersSent,
10734 base::Unretained(&proxy_headers_handler)));
10736 int rv = trans->Start(&request, callback1.callback(), log.bound());
10737 EXPECT_EQ(ERR_IO_PENDING, rv);
10739 rv = callback1.WaitForResult();
10740 EXPECT_EQ(OK, rv);
10742 const HttpResponseInfo* response = trans->GetResponseInfo();
10743 ASSERT_TRUE(response != NULL);
10745 EXPECT_TRUE(response->headers->IsKeepAlive());
10746 EXPECT_EQ(200, response->headers->response_code());
10747 EXPECT_EQ(100, response->headers->GetContentLength());
10748 EXPECT_TRUE(response->was_fetched_via_proxy);
10749 EXPECT_TRUE(
10750 response->proxy_server.Equals(HostPortPair::FromString("myproxy:70")));
10751 EXPECT_TRUE(proxy_headers_handler.observed_before_proxy_headers_sent());
10752 EXPECT_EQ("myproxy:70", proxy_headers_handler.observed_proxy_server_uri());
10753 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
10755 LoadTimingInfo load_timing_info;
10756 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
10757 TestLoadTimingNotReusedWithPac(load_timing_info,
10758 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
10761 // Test a basic HTTPS GET request through a proxy.
10762 TEST_P(HttpNetworkTransactionTest, ProxyTunnelGet) {
10763 session_deps_.proxy_service.reset(
10764 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
10765 CapturingBoundNetLog log;
10766 session_deps_.net_log = log.bound().net_log();
10767 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10769 HttpRequestInfo request;
10770 request.method = "GET";
10771 request.url = GURL("https://www.google.com/");
10773 // Since we have proxy, should try to establish tunnel.
10774 MockWrite data_writes1[] = {
10775 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
10776 "Host: www.google.com\r\n"
10777 "Proxy-Connection: keep-alive\r\n\r\n"),
10779 MockWrite("GET / HTTP/1.1\r\n"
10780 "Host: www.google.com\r\n"
10781 "Connection: keep-alive\r\n\r\n"),
10784 MockRead data_reads1[] = {
10785 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
10787 MockRead("HTTP/1.1 200 OK\r\n"),
10788 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
10789 MockRead("Content-Length: 100\r\n\r\n"),
10790 MockRead(SYNCHRONOUS, OK),
10793 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
10794 data_writes1, arraysize(data_writes1));
10795 session_deps_.socket_factory->AddSocketDataProvider(&data1);
10796 SSLSocketDataProvider ssl(ASYNC, OK);
10797 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
10799 TestCompletionCallback callback1;
10801 scoped_ptr<HttpTransaction> trans(
10802 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10804 int rv = trans->Start(&request, callback1.callback(), log.bound());
10805 EXPECT_EQ(ERR_IO_PENDING, rv);
10807 rv = callback1.WaitForResult();
10808 EXPECT_EQ(OK, rv);
10809 net::CapturingNetLog::CapturedEntryList entries;
10810 log.GetEntries(&entries);
10811 size_t pos = ExpectLogContainsSomewhere(
10812 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
10813 NetLog::PHASE_NONE);
10814 ExpectLogContainsSomewhere(
10815 entries, pos,
10816 NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
10817 NetLog::PHASE_NONE);
10819 const HttpResponseInfo* response = trans->GetResponseInfo();
10820 ASSERT_TRUE(response != NULL);
10822 EXPECT_TRUE(response->headers->IsKeepAlive());
10823 EXPECT_EQ(200, response->headers->response_code());
10824 EXPECT_EQ(100, response->headers->GetContentLength());
10825 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
10826 EXPECT_TRUE(response->was_fetched_via_proxy);
10827 EXPECT_TRUE(
10828 response->proxy_server.Equals(HostPortPair::FromString("myproxy:70")));
10830 LoadTimingInfo load_timing_info;
10831 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
10832 TestLoadTimingNotReusedWithPac(load_timing_info,
10833 CONNECT_TIMING_HAS_SSL_TIMES);
10836 // Test a basic HTTPS GET request through a proxy, but the server hangs up
10837 // while establishing the tunnel.
10838 TEST_P(HttpNetworkTransactionTest, ProxyTunnelGetHangup) {
10839 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
10840 CapturingBoundNetLog log;
10841 session_deps_.net_log = log.bound().net_log();
10842 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10844 HttpRequestInfo request;
10845 request.method = "GET";
10846 request.url = GURL("https://www.google.com/");
10848 // Since we have proxy, should try to establish tunnel.
10849 MockWrite data_writes1[] = {
10850 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
10851 "Host: www.google.com\r\n"
10852 "Proxy-Connection: keep-alive\r\n\r\n"),
10854 MockWrite("GET / HTTP/1.1\r\n"
10855 "Host: www.google.com\r\n"
10856 "Connection: keep-alive\r\n\r\n"),
10859 MockRead data_reads1[] = {
10860 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
10861 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
10862 MockRead(ASYNC, 0, 0), // EOF
10865 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
10866 data_writes1, arraysize(data_writes1));
10867 session_deps_.socket_factory->AddSocketDataProvider(&data1);
10868 SSLSocketDataProvider ssl(ASYNC, OK);
10869 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
10871 TestCompletionCallback callback1;
10873 scoped_ptr<HttpTransaction> trans(
10874 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10876 int rv = trans->Start(&request, callback1.callback(), log.bound());
10877 EXPECT_EQ(ERR_IO_PENDING, rv);
10879 rv = callback1.WaitForResult();
10880 EXPECT_EQ(ERR_EMPTY_RESPONSE, rv);
10881 net::CapturingNetLog::CapturedEntryList entries;
10882 log.GetEntries(&entries);
10883 size_t pos = ExpectLogContainsSomewhere(
10884 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
10885 NetLog::PHASE_NONE);
10886 ExpectLogContainsSomewhere(
10887 entries, pos,
10888 NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
10889 NetLog::PHASE_NONE);
10892 // Test for crbug.com/55424.
10893 TEST_P(HttpNetworkTransactionTest, PreconnectWithExistingSpdySession) {
10894 scoped_ptr<SpdyFrame> req(
10895 spdy_util_.ConstructSpdyGet("https://www.google.com", false, 1, LOWEST));
10896 MockWrite spdy_writes[] = { CreateMockWrite(*req) };
10898 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
10899 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
10900 MockRead spdy_reads[] = {
10901 CreateMockRead(*resp),
10902 CreateMockRead(*data),
10903 MockRead(ASYNC, 0, 0),
10906 DelayedSocketData spdy_data(
10907 1, // wait for one write to finish before reading.
10908 spdy_reads, arraysize(spdy_reads),
10909 spdy_writes, arraysize(spdy_writes));
10910 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
10912 SSLSocketDataProvider ssl(ASYNC, OK);
10913 ssl.SetNextProto(GetParam());
10914 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
10916 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10918 // Set up an initial SpdySession in the pool to reuse.
10919 HostPortPair host_port_pair("www.google.com", 443);
10920 SpdySessionKey key(host_port_pair, ProxyServer::Direct(),
10921 PRIVACY_MODE_DISABLED);
10922 base::WeakPtr<SpdySession> spdy_session =
10923 CreateInsecureSpdySession(session, key, BoundNetLog());
10925 HttpRequestInfo request;
10926 request.method = "GET";
10927 request.url = GURL("https://www.google.com/");
10928 request.load_flags = 0;
10930 // This is the important line that marks this as a preconnect.
10931 request.motivation = HttpRequestInfo::PRECONNECT_MOTIVATED;
10933 scoped_ptr<HttpTransaction> trans(
10934 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10936 TestCompletionCallback callback;
10937 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
10938 EXPECT_EQ(ERR_IO_PENDING, rv);
10939 EXPECT_EQ(OK, callback.WaitForResult());
10942 // Given a net error, cause that error to be returned from the first Write()
10943 // call and verify that the HttpTransaction fails with that error.
10944 void HttpNetworkTransactionTest::CheckErrorIsPassedBack(
10945 int error, IoMode mode) {
10946 net::HttpRequestInfo request_info;
10947 request_info.url = GURL("https://www.example.com/");
10948 request_info.method = "GET";
10949 request_info.load_flags = net::LOAD_NORMAL;
10951 SSLSocketDataProvider ssl_data(mode, OK);
10952 net::MockWrite data_writes[] = {
10953 net::MockWrite(mode, error),
10955 net::StaticSocketDataProvider data(NULL, 0,
10956 data_writes, arraysize(data_writes));
10957 session_deps_.socket_factory->AddSocketDataProvider(&data);
10958 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data);
10960 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10961 scoped_ptr<HttpTransaction> trans(
10962 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10964 TestCompletionCallback callback;
10965 int rv = trans->Start(&request_info, callback.callback(), net::BoundNetLog());
10966 if (rv == net::ERR_IO_PENDING)
10967 rv = callback.WaitForResult();
10968 ASSERT_EQ(error, rv);
10971 TEST_P(HttpNetworkTransactionTest, SSLWriteCertError) {
10972 // Just check a grab bag of cert errors.
10973 static const int kErrors[] = {
10974 ERR_CERT_COMMON_NAME_INVALID,
10975 ERR_CERT_AUTHORITY_INVALID,
10976 ERR_CERT_DATE_INVALID,
10978 for (size_t i = 0; i < arraysize(kErrors); i++) {
10979 CheckErrorIsPassedBack(kErrors[i], ASYNC);
10980 CheckErrorIsPassedBack(kErrors[i], SYNCHRONOUS);
10984 // Ensure that a client certificate is removed from the SSL client auth
10985 // cache when:
10986 // 1) No proxy is involved.
10987 // 2) TLS False Start is disabled.
10988 // 3) The initial TLS handshake requests a client certificate.
10989 // 4) The client supplies an invalid/unacceptable certificate.
10990 TEST_P(HttpNetworkTransactionTest,
10991 ClientAuthCertCache_Direct_NoFalseStart) {
10992 net::HttpRequestInfo request_info;
10993 request_info.url = GURL("https://www.example.com/");
10994 request_info.method = "GET";
10995 request_info.load_flags = net::LOAD_NORMAL;
10997 scoped_refptr<SSLCertRequestInfo> cert_request(new SSLCertRequestInfo());
10998 cert_request->host_and_port = HostPortPair("www.example.com", 443);
11000 // [ssl_]data1 contains the data for the first SSL handshake. When a
11001 // CertificateRequest is received for the first time, the handshake will
11002 // be aborted to allow the caller to provide a certificate.
11003 SSLSocketDataProvider ssl_data1(ASYNC, net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
11004 ssl_data1.cert_request_info = cert_request.get();
11005 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data1);
11006 net::StaticSocketDataProvider data1(NULL, 0, NULL, 0);
11007 session_deps_.socket_factory->AddSocketDataProvider(&data1);
11009 // [ssl_]data2 contains the data for the second SSL handshake. When TLS
11010 // False Start is not being used, the result of the SSL handshake will be
11011 // returned as part of the SSLClientSocket::Connect() call. This test
11012 // matches the result of a server sending a handshake_failure alert,
11013 // rather than a Finished message, because it requires a client
11014 // certificate and none was supplied.
11015 SSLSocketDataProvider ssl_data2(ASYNC, net::ERR_SSL_PROTOCOL_ERROR);
11016 ssl_data2.cert_request_info = cert_request.get();
11017 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data2);
11018 net::StaticSocketDataProvider data2(NULL, 0, NULL, 0);
11019 session_deps_.socket_factory->AddSocketDataProvider(&data2);
11021 // [ssl_]data3 contains the data for the third SSL handshake. When a
11022 // connection to a server fails during an SSL handshake,
11023 // HttpNetworkTransaction will attempt to fallback to TLSv1 if the previous
11024 // connection was attempted with TLSv1.1. This is transparent to the caller
11025 // of the HttpNetworkTransaction. Because this test failure is due to
11026 // requiring a client certificate, this fallback handshake should also
11027 // fail.
11028 SSLSocketDataProvider ssl_data3(ASYNC, net::ERR_SSL_PROTOCOL_ERROR);
11029 ssl_data3.cert_request_info = cert_request.get();
11030 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data3);
11031 net::StaticSocketDataProvider data3(NULL, 0, NULL, 0);
11032 session_deps_.socket_factory->AddSocketDataProvider(&data3);
11034 // [ssl_]data4 contains the data for the fourth SSL handshake. When a
11035 // connection to a server fails during an SSL handshake,
11036 // HttpNetworkTransaction will attempt to fallback to SSLv3 if the previous
11037 // connection was attempted with TLSv1. This is transparent to the caller
11038 // of the HttpNetworkTransaction. Because this test failure is due to
11039 // requiring a client certificate, this fallback handshake should also
11040 // fail.
11041 SSLSocketDataProvider ssl_data4(ASYNC, net::ERR_SSL_PROTOCOL_ERROR);
11042 ssl_data4.cert_request_info = cert_request.get();
11043 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data4);
11044 net::StaticSocketDataProvider data4(NULL, 0, NULL, 0);
11045 session_deps_.socket_factory->AddSocketDataProvider(&data4);
11047 // Need one more if TLSv1.2 is enabled.
11048 SSLSocketDataProvider ssl_data5(ASYNC, net::ERR_SSL_PROTOCOL_ERROR);
11049 ssl_data5.cert_request_info = cert_request.get();
11050 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data5);
11051 net::StaticSocketDataProvider data5(NULL, 0, NULL, 0);
11052 session_deps_.socket_factory->AddSocketDataProvider(&data5);
11054 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11055 scoped_ptr<HttpTransaction> trans(
11056 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
11058 // Begin the SSL handshake with the peer. This consumes ssl_data1.
11059 TestCompletionCallback callback;
11060 int rv = trans->Start(&request_info, callback.callback(), net::BoundNetLog());
11061 ASSERT_EQ(net::ERR_IO_PENDING, rv);
11063 // Complete the SSL handshake, which should abort due to requiring a
11064 // client certificate.
11065 rv = callback.WaitForResult();
11066 ASSERT_EQ(net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
11068 // Indicate that no certificate should be supplied. From the perspective
11069 // of SSLClientCertCache, NULL is just as meaningful as a real
11070 // certificate, so this is the same as supply a
11071 // legitimate-but-unacceptable certificate.
11072 rv = trans->RestartWithCertificate(NULL, callback.callback());
11073 ASSERT_EQ(net::ERR_IO_PENDING, rv);
11075 // Ensure the certificate was added to the client auth cache before
11076 // allowing the connection to continue restarting.
11077 scoped_refptr<X509Certificate> client_cert;
11078 ASSERT_TRUE(session->ssl_client_auth_cache()->Lookup(
11079 HostPortPair("www.example.com", 443), &client_cert));
11080 ASSERT_EQ(NULL, client_cert.get());
11082 // Restart the handshake. This will consume ssl_data2, which fails, and
11083 // then consume ssl_data3 and ssl_data4, both of which should also fail.
11084 // The result code is checked against what ssl_data4 should return.
11085 rv = callback.WaitForResult();
11086 ASSERT_EQ(net::ERR_SSL_PROTOCOL_ERROR, rv);
11088 // Ensure that the client certificate is removed from the cache on a
11089 // handshake failure.
11090 ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
11091 HostPortPair("www.example.com", 443), &client_cert));
11094 // Ensure that a client certificate is removed from the SSL client auth
11095 // cache when:
11096 // 1) No proxy is involved.
11097 // 2) TLS False Start is enabled.
11098 // 3) The initial TLS handshake requests a client certificate.
11099 // 4) The client supplies an invalid/unacceptable certificate.
11100 TEST_P(HttpNetworkTransactionTest,
11101 ClientAuthCertCache_Direct_FalseStart) {
11102 net::HttpRequestInfo request_info;
11103 request_info.url = GURL("https://www.example.com/");
11104 request_info.method = "GET";
11105 request_info.load_flags = net::LOAD_NORMAL;
11107 scoped_refptr<SSLCertRequestInfo> cert_request(new SSLCertRequestInfo());
11108 cert_request->host_and_port = HostPortPair("www.example.com", 443);
11110 // When TLS False Start is used, SSLClientSocket::Connect() calls will
11111 // return successfully after reading up to the peer's Certificate message.
11112 // This is to allow the caller to call SSLClientSocket::Write(), which can
11113 // enqueue application data to be sent in the same packet as the
11114 // ChangeCipherSpec and Finished messages.
11115 // The actual handshake will be finished when SSLClientSocket::Read() is
11116 // called, which expects to process the peer's ChangeCipherSpec and
11117 // Finished messages. If there was an error negotiating with the peer,
11118 // such as due to the peer requiring a client certificate when none was
11119 // supplied, the alert sent by the peer won't be processed until Read() is
11120 // called.
11122 // Like the non-False Start case, when a client certificate is requested by
11123 // the peer, the handshake is aborted during the Connect() call.
11124 // [ssl_]data1 represents the initial SSL handshake with the peer.
11125 SSLSocketDataProvider ssl_data1(ASYNC, net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
11126 ssl_data1.cert_request_info = cert_request.get();
11127 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data1);
11128 net::StaticSocketDataProvider data1(NULL, 0, NULL, 0);
11129 session_deps_.socket_factory->AddSocketDataProvider(&data1);
11131 // When a client certificate is supplied, Connect() will not be aborted
11132 // when the peer requests the certificate. Instead, the handshake will
11133 // artificially succeed, allowing the caller to write the HTTP request to
11134 // the socket. The handshake messages are not processed until Read() is
11135 // called, which then detects that the handshake was aborted, due to the
11136 // peer sending a handshake_failure because it requires a client
11137 // certificate.
11138 SSLSocketDataProvider ssl_data2(ASYNC, net::OK);
11139 ssl_data2.cert_request_info = cert_request.get();
11140 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data2);
11141 net::MockRead data2_reads[] = {
11142 net::MockRead(ASYNC /* async */, net::ERR_SSL_PROTOCOL_ERROR),
11144 net::StaticSocketDataProvider data2(
11145 data2_reads, arraysize(data2_reads), NULL, 0);
11146 session_deps_.socket_factory->AddSocketDataProvider(&data2);
11148 // As described in ClientAuthCertCache_Direct_NoFalseStart, [ssl_]data3 is
11149 // the data for the SSL handshake once the TLSv1.1 connection falls back to
11150 // TLSv1. It has the same behaviour as [ssl_]data2.
11151 SSLSocketDataProvider ssl_data3(ASYNC, net::OK);
11152 ssl_data3.cert_request_info = cert_request.get();
11153 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data3);
11154 net::StaticSocketDataProvider data3(
11155 data2_reads, arraysize(data2_reads), NULL, 0);
11156 session_deps_.socket_factory->AddSocketDataProvider(&data3);
11158 // [ssl_]data4 is the data for the SSL handshake once the TLSv1 connection
11159 // falls back to SSLv3. It has the same behaviour as [ssl_]data2.
11160 SSLSocketDataProvider ssl_data4(ASYNC, net::OK);
11161 ssl_data4.cert_request_info = cert_request.get();
11162 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data4);
11163 net::StaticSocketDataProvider data4(
11164 data2_reads, arraysize(data2_reads), NULL, 0);
11165 session_deps_.socket_factory->AddSocketDataProvider(&data4);
11167 // Need one more if TLSv1.2 is enabled.
11168 SSLSocketDataProvider ssl_data5(ASYNC, net::OK);
11169 ssl_data5.cert_request_info = cert_request.get();
11170 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data5);
11171 net::StaticSocketDataProvider data5(
11172 data2_reads, arraysize(data2_reads), NULL, 0);
11173 session_deps_.socket_factory->AddSocketDataProvider(&data5);
11175 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11176 scoped_ptr<HttpTransaction> trans(
11177 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
11179 // Begin the initial SSL handshake.
11180 TestCompletionCallback callback;
11181 int rv = trans->Start(&request_info, callback.callback(), net::BoundNetLog());
11182 ASSERT_EQ(net::ERR_IO_PENDING, rv);
11184 // Complete the SSL handshake, which should abort due to requiring a
11185 // client certificate.
11186 rv = callback.WaitForResult();
11187 ASSERT_EQ(net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
11189 // Indicate that no certificate should be supplied. From the perspective
11190 // of SSLClientCertCache, NULL is just as meaningful as a real
11191 // certificate, so this is the same as supply a
11192 // legitimate-but-unacceptable certificate.
11193 rv = trans->RestartWithCertificate(NULL, callback.callback());
11194 ASSERT_EQ(net::ERR_IO_PENDING, rv);
11196 // Ensure the certificate was added to the client auth cache before
11197 // allowing the connection to continue restarting.
11198 scoped_refptr<X509Certificate> client_cert;
11199 ASSERT_TRUE(session->ssl_client_auth_cache()->Lookup(
11200 HostPortPair("www.example.com", 443), &client_cert));
11201 ASSERT_EQ(NULL, client_cert.get());
11203 // Restart the handshake. This will consume ssl_data2, which fails, and
11204 // then consume ssl_data3 and ssl_data4, both of which should also fail.
11205 // The result code is checked against what ssl_data4 should return.
11206 rv = callback.WaitForResult();
11207 ASSERT_EQ(net::ERR_SSL_PROTOCOL_ERROR, rv);
11209 // Ensure that the client certificate is removed from the cache on a
11210 // handshake failure.
11211 ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
11212 HostPortPair("www.example.com", 443), &client_cert));
11215 // Ensure that a client certificate is removed from the SSL client auth
11216 // cache when:
11217 // 1) An HTTPS proxy is involved.
11218 // 3) The HTTPS proxy requests a client certificate.
11219 // 4) The client supplies an invalid/unacceptable certificate for the
11220 // proxy.
11221 // The test is repeated twice, first for connecting to an HTTPS endpoint,
11222 // then for connecting to an HTTP endpoint.
11223 TEST_P(HttpNetworkTransactionTest, ClientAuthCertCache_Proxy_Fail) {
11224 session_deps_.proxy_service.reset(
11225 ProxyService::CreateFixed("https://proxy:70"));
11226 CapturingBoundNetLog log;
11227 session_deps_.net_log = log.bound().net_log();
11229 scoped_refptr<SSLCertRequestInfo> cert_request(new SSLCertRequestInfo());
11230 cert_request->host_and_port = HostPortPair("proxy", 70);
11232 // See ClientAuthCertCache_Direct_NoFalseStart for the explanation of
11233 // [ssl_]data[1-3]. Rather than represending the endpoint
11234 // (www.example.com:443), they represent failures with the HTTPS proxy
11235 // (proxy:70).
11236 SSLSocketDataProvider ssl_data1(ASYNC, net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
11237 ssl_data1.cert_request_info = cert_request.get();
11238 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data1);
11239 net::StaticSocketDataProvider data1(NULL, 0, NULL, 0);
11240 session_deps_.socket_factory->AddSocketDataProvider(&data1);
11242 SSLSocketDataProvider ssl_data2(ASYNC, net::ERR_SSL_PROTOCOL_ERROR);
11243 ssl_data2.cert_request_info = cert_request.get();
11244 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data2);
11245 net::StaticSocketDataProvider data2(NULL, 0, NULL, 0);
11246 session_deps_.socket_factory->AddSocketDataProvider(&data2);
11248 // TODO(wtc): find out why this unit test doesn't need [ssl_]data3.
11249 #if 0
11250 SSLSocketDataProvider ssl_data3(ASYNC, net::ERR_SSL_PROTOCOL_ERROR);
11251 ssl_data3.cert_request_info = cert_request.get();
11252 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data3);
11253 net::StaticSocketDataProvider data3(NULL, 0, NULL, 0);
11254 session_deps_.socket_factory->AddSocketDataProvider(&data3);
11255 #endif
11257 net::HttpRequestInfo requests[2];
11258 requests[0].url = GURL("https://www.example.com/");
11259 requests[0].method = "GET";
11260 requests[0].load_flags = net::LOAD_NORMAL;
11262 requests[1].url = GURL("http://www.example.com/");
11263 requests[1].method = "GET";
11264 requests[1].load_flags = net::LOAD_NORMAL;
11266 for (size_t i = 0; i < arraysize(requests); ++i) {
11267 session_deps_.socket_factory->ResetNextMockIndexes();
11268 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11269 scoped_ptr<HttpNetworkTransaction> trans(
11270 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
11272 // Begin the SSL handshake with the proxy.
11273 TestCompletionCallback callback;
11274 int rv = trans->Start(
11275 &requests[i], callback.callback(), net::BoundNetLog());
11276 ASSERT_EQ(net::ERR_IO_PENDING, rv);
11278 // Complete the SSL handshake, which should abort due to requiring a
11279 // client certificate.
11280 rv = callback.WaitForResult();
11281 ASSERT_EQ(net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
11283 // Indicate that no certificate should be supplied. From the perspective
11284 // of SSLClientCertCache, NULL is just as meaningful as a real
11285 // certificate, so this is the same as supply a
11286 // legitimate-but-unacceptable certificate.
11287 rv = trans->RestartWithCertificate(NULL, callback.callback());
11288 ASSERT_EQ(net::ERR_IO_PENDING, rv);
11290 // Ensure the certificate was added to the client auth cache before
11291 // allowing the connection to continue restarting.
11292 scoped_refptr<X509Certificate> client_cert;
11293 ASSERT_TRUE(session->ssl_client_auth_cache()->Lookup(
11294 HostPortPair("proxy", 70), &client_cert));
11295 ASSERT_EQ(NULL, client_cert.get());
11296 // Ensure the certificate was NOT cached for the endpoint. This only
11297 // applies to HTTPS requests, but is fine to check for HTTP requests.
11298 ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
11299 HostPortPair("www.example.com", 443), &client_cert));
11301 // Restart the handshake. This will consume ssl_data2, which fails, and
11302 // then consume ssl_data3, which should also fail. The result code is
11303 // checked against what ssl_data3 should return.
11304 rv = callback.WaitForResult();
11305 ASSERT_EQ(net::ERR_PROXY_CONNECTION_FAILED, rv);
11307 // Now that the new handshake has failed, ensure that the client
11308 // certificate was removed from the client auth cache.
11309 ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
11310 HostPortPair("proxy", 70), &client_cert));
11311 ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
11312 HostPortPair("www.example.com", 443), &client_cert));
11316 // Unlike TEST/TEST_F, which are macros that expand to further macros,
11317 // TEST_P is a macro that expands directly to code that stringizes the
11318 // arguments. As a result, macros passed as parameters (such as prefix
11319 // or test_case_name) will not be expanded by the preprocessor. To
11320 // work around this, indirect the macro for TEST_P, so that the
11321 // pre-processor will expand macros such as MAYBE_test_name before
11322 // instantiating the test.
11323 #define WRAPPED_TEST_P(test_case_name, test_name) \
11324 TEST_P(test_case_name, test_name)
11326 // Times out on Win7 dbg(2) bot. http://crbug.com/124776
11327 #if defined(OS_WIN)
11328 #define MAYBE_UseIPConnectionPooling DISABLED_UseIPConnectionPooling
11329 #else
11330 #define MAYBE_UseIPConnectionPooling UseIPConnectionPooling
11331 #endif
11332 WRAPPED_TEST_P(HttpNetworkTransactionTest, MAYBE_UseIPConnectionPooling) {
11333 session_deps_.use_alternate_protocols = true;
11334 session_deps_.next_protos = SpdyNextProtos();
11336 // Set up a special HttpNetworkSession with a MockCachingHostResolver.
11337 session_deps_.host_resolver.reset(new MockCachingHostResolver());
11338 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11339 SpdySessionPoolPeer pool_peer(session->spdy_session_pool());
11340 pool_peer.DisableDomainAuthenticationVerification();
11342 SSLSocketDataProvider ssl(ASYNC, OK);
11343 ssl.SetNextProto(GetParam());
11344 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
11346 scoped_ptr<SpdyFrame> host1_req(
11347 spdy_util_.ConstructSpdyGet("https://www.google.com", false, 1, LOWEST));
11348 scoped_ptr<SpdyFrame> host2_req(
11349 spdy_util_.ConstructSpdyGet("https://www.gmail.com", false, 3, LOWEST));
11350 MockWrite spdy_writes[] = {
11351 CreateMockWrite(*host1_req, 1),
11352 CreateMockWrite(*host2_req, 4),
11354 scoped_ptr<SpdyFrame> host1_resp(
11355 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11356 scoped_ptr<SpdyFrame> host1_resp_body(
11357 spdy_util_.ConstructSpdyBodyFrame(1, true));
11358 scoped_ptr<SpdyFrame> host2_resp(
11359 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
11360 scoped_ptr<SpdyFrame> host2_resp_body(
11361 spdy_util_.ConstructSpdyBodyFrame(3, true));
11362 MockRead spdy_reads[] = {
11363 CreateMockRead(*host1_resp, 2),
11364 CreateMockRead(*host1_resp_body, 3),
11365 CreateMockRead(*host2_resp, 5),
11366 CreateMockRead(*host2_resp_body, 6),
11367 MockRead(ASYNC, 0, 7),
11370 IPAddressNumber ip;
11371 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &ip));
11372 IPEndPoint peer_addr = IPEndPoint(ip, 443);
11373 MockConnect connect(ASYNC, OK, peer_addr);
11374 OrderedSocketData spdy_data(
11375 connect,
11376 spdy_reads, arraysize(spdy_reads),
11377 spdy_writes, arraysize(spdy_writes));
11378 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
11380 TestCompletionCallback callback;
11381 HttpRequestInfo request1;
11382 request1.method = "GET";
11383 request1.url = GURL("https://www.google.com/");
11384 request1.load_flags = 0;
11385 HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
11387 int rv = trans1.Start(&request1, callback.callback(), BoundNetLog());
11388 EXPECT_EQ(ERR_IO_PENDING, rv);
11389 EXPECT_EQ(OK, callback.WaitForResult());
11391 const HttpResponseInfo* response = trans1.GetResponseInfo();
11392 ASSERT_TRUE(response != NULL);
11393 ASSERT_TRUE(response->headers.get() != NULL);
11394 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
11396 std::string response_data;
11397 ASSERT_EQ(OK, ReadTransaction(&trans1, &response_data));
11398 EXPECT_EQ("hello!", response_data);
11400 // Preload www.gmail.com into HostCache.
11401 HostPortPair host_port("www.gmail.com", 443);
11402 HostResolver::RequestInfo resolve_info(host_port);
11403 AddressList ignored;
11404 rv = session_deps_.host_resolver->Resolve(resolve_info,
11405 DEFAULT_PRIORITY,
11406 &ignored,
11407 callback.callback(),
11408 NULL,
11409 BoundNetLog());
11410 EXPECT_EQ(ERR_IO_PENDING, rv);
11411 rv = callback.WaitForResult();
11412 EXPECT_EQ(OK, rv);
11414 HttpRequestInfo request2;
11415 request2.method = "GET";
11416 request2.url = GURL("https://www.gmail.com/");
11417 request2.load_flags = 0;
11418 HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
11420 rv = trans2.Start(&request2, callback.callback(), BoundNetLog());
11421 EXPECT_EQ(ERR_IO_PENDING, rv);
11422 EXPECT_EQ(OK, callback.WaitForResult());
11424 response = trans2.GetResponseInfo();
11425 ASSERT_TRUE(response != NULL);
11426 ASSERT_TRUE(response->headers.get() != NULL);
11427 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
11428 EXPECT_TRUE(response->was_fetched_via_spdy);
11429 EXPECT_TRUE(response->was_npn_negotiated);
11430 ASSERT_EQ(OK, ReadTransaction(&trans2, &response_data));
11431 EXPECT_EQ("hello!", response_data);
11433 #undef MAYBE_UseIPConnectionPooling
11435 TEST_P(HttpNetworkTransactionTest, UseIPConnectionPoolingAfterResolution) {
11436 session_deps_.use_alternate_protocols = true;
11437 session_deps_.next_protos = SpdyNextProtos();
11439 // Set up a special HttpNetworkSession with a MockCachingHostResolver.
11440 session_deps_.host_resolver.reset(new MockCachingHostResolver());
11441 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11442 SpdySessionPoolPeer pool_peer(session->spdy_session_pool());
11443 pool_peer.DisableDomainAuthenticationVerification();
11445 SSLSocketDataProvider ssl(ASYNC, OK);
11446 ssl.SetNextProto(GetParam());
11447 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
11449 scoped_ptr<SpdyFrame> host1_req(
11450 spdy_util_.ConstructSpdyGet("https://www.google.com", false, 1, LOWEST));
11451 scoped_ptr<SpdyFrame> host2_req(
11452 spdy_util_.ConstructSpdyGet("https://www.gmail.com", false, 3, LOWEST));
11453 MockWrite spdy_writes[] = {
11454 CreateMockWrite(*host1_req, 1),
11455 CreateMockWrite(*host2_req, 4),
11457 scoped_ptr<SpdyFrame> host1_resp(
11458 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11459 scoped_ptr<SpdyFrame> host1_resp_body(
11460 spdy_util_.ConstructSpdyBodyFrame(1, true));
11461 scoped_ptr<SpdyFrame> host2_resp(
11462 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
11463 scoped_ptr<SpdyFrame> host2_resp_body(
11464 spdy_util_.ConstructSpdyBodyFrame(3, true));
11465 MockRead spdy_reads[] = {
11466 CreateMockRead(*host1_resp, 2),
11467 CreateMockRead(*host1_resp_body, 3),
11468 CreateMockRead(*host2_resp, 5),
11469 CreateMockRead(*host2_resp_body, 6),
11470 MockRead(ASYNC, 0, 7),
11473 IPAddressNumber ip;
11474 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &ip));
11475 IPEndPoint peer_addr = IPEndPoint(ip, 443);
11476 MockConnect connect(ASYNC, OK, peer_addr);
11477 OrderedSocketData spdy_data(
11478 connect,
11479 spdy_reads, arraysize(spdy_reads),
11480 spdy_writes, arraysize(spdy_writes));
11481 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
11483 TestCompletionCallback callback;
11484 HttpRequestInfo request1;
11485 request1.method = "GET";
11486 request1.url = GURL("https://www.google.com/");
11487 request1.load_flags = 0;
11488 HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
11490 int rv = trans1.Start(&request1, callback.callback(), BoundNetLog());
11491 EXPECT_EQ(ERR_IO_PENDING, rv);
11492 EXPECT_EQ(OK, callback.WaitForResult());
11494 const HttpResponseInfo* response = trans1.GetResponseInfo();
11495 ASSERT_TRUE(response != NULL);
11496 ASSERT_TRUE(response->headers.get() != NULL);
11497 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
11499 std::string response_data;
11500 ASSERT_EQ(OK, ReadTransaction(&trans1, &response_data));
11501 EXPECT_EQ("hello!", response_data);
11503 HttpRequestInfo request2;
11504 request2.method = "GET";
11505 request2.url = GURL("https://www.gmail.com/");
11506 request2.load_flags = 0;
11507 HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
11509 rv = trans2.Start(&request2, callback.callback(), BoundNetLog());
11510 EXPECT_EQ(ERR_IO_PENDING, rv);
11511 EXPECT_EQ(OK, callback.WaitForResult());
11513 response = trans2.GetResponseInfo();
11514 ASSERT_TRUE(response != NULL);
11515 ASSERT_TRUE(response->headers.get() != NULL);
11516 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
11517 EXPECT_TRUE(response->was_fetched_via_spdy);
11518 EXPECT_TRUE(response->was_npn_negotiated);
11519 ASSERT_EQ(OK, ReadTransaction(&trans2, &response_data));
11520 EXPECT_EQ("hello!", response_data);
11523 class OneTimeCachingHostResolver : public net::HostResolver {
11524 public:
11525 explicit OneTimeCachingHostResolver(const HostPortPair& host_port)
11526 : host_port_(host_port) {}
11527 ~OneTimeCachingHostResolver() override {}
11529 RuleBasedHostResolverProc* rules() { return host_resolver_.rules(); }
11531 // HostResolver methods:
11532 int Resolve(const RequestInfo& info,
11533 RequestPriority priority,
11534 AddressList* addresses,
11535 const CompletionCallback& callback,
11536 RequestHandle* out_req,
11537 const BoundNetLog& net_log) override {
11538 return host_resolver_.Resolve(
11539 info, priority, addresses, callback, out_req, net_log);
11542 int ResolveFromCache(const RequestInfo& info,
11543 AddressList* addresses,
11544 const BoundNetLog& net_log) override {
11545 int rv = host_resolver_.ResolveFromCache(info, addresses, net_log);
11546 if (rv == OK && info.host_port_pair().Equals(host_port_))
11547 host_resolver_.GetHostCache()->clear();
11548 return rv;
11551 void CancelRequest(RequestHandle req) override {
11552 host_resolver_.CancelRequest(req);
11555 MockCachingHostResolver* GetMockHostResolver() {
11556 return &host_resolver_;
11559 private:
11560 MockCachingHostResolver host_resolver_;
11561 const HostPortPair host_port_;
11564 // Times out on Win7 dbg(2) bot. http://crbug.com/124776
11565 #if defined(OS_WIN)
11566 #define MAYBE_UseIPConnectionPoolingWithHostCacheExpiration \
11567 DISABLED_UseIPConnectionPoolingWithHostCacheExpiration
11568 #else
11569 #define MAYBE_UseIPConnectionPoolingWithHostCacheExpiration \
11570 UseIPConnectionPoolingWithHostCacheExpiration
11571 #endif
11572 WRAPPED_TEST_P(HttpNetworkTransactionTest,
11573 MAYBE_UseIPConnectionPoolingWithHostCacheExpiration) {
11574 // Times out on Win7 dbg(2) bot. http://crbug.com/124776 . (MAYBE_
11575 // prefix doesn't work with parametrized tests).
11576 #if defined(OS_WIN)
11577 return;
11578 #else
11579 session_deps_.use_alternate_protocols = true;
11580 session_deps_.next_protos = SpdyNextProtos();
11582 // Set up a special HttpNetworkSession with a OneTimeCachingHostResolver.
11583 OneTimeCachingHostResolver host_resolver(HostPortPair("www.gmail.com", 443));
11584 HttpNetworkSession::Params params =
11585 SpdySessionDependencies::CreateSessionParams(&session_deps_);
11586 params.host_resolver = &host_resolver;
11587 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11588 SpdySessionPoolPeer pool_peer(session->spdy_session_pool());
11589 pool_peer.DisableDomainAuthenticationVerification();
11591 SSLSocketDataProvider ssl(ASYNC, OK);
11592 ssl.SetNextProto(GetParam());
11593 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
11595 scoped_ptr<SpdyFrame> host1_req(
11596 spdy_util_.ConstructSpdyGet("https://www.google.com", false, 1, LOWEST));
11597 scoped_ptr<SpdyFrame> host2_req(
11598 spdy_util_.ConstructSpdyGet("https://www.gmail.com", false, 3, LOWEST));
11599 MockWrite spdy_writes[] = {
11600 CreateMockWrite(*host1_req, 1),
11601 CreateMockWrite(*host2_req, 4),
11603 scoped_ptr<SpdyFrame> host1_resp(
11604 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11605 scoped_ptr<SpdyFrame> host1_resp_body(
11606 spdy_util_.ConstructSpdyBodyFrame(1, true));
11607 scoped_ptr<SpdyFrame> host2_resp(
11608 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
11609 scoped_ptr<SpdyFrame> host2_resp_body(
11610 spdy_util_.ConstructSpdyBodyFrame(3, true));
11611 MockRead spdy_reads[] = {
11612 CreateMockRead(*host1_resp, 2),
11613 CreateMockRead(*host1_resp_body, 3),
11614 CreateMockRead(*host2_resp, 5),
11615 CreateMockRead(*host2_resp_body, 6),
11616 MockRead(ASYNC, 0, 7),
11619 IPAddressNumber ip;
11620 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &ip));
11621 IPEndPoint peer_addr = IPEndPoint(ip, 443);
11622 MockConnect connect(ASYNC, OK, peer_addr);
11623 OrderedSocketData spdy_data(
11624 connect,
11625 spdy_reads, arraysize(spdy_reads),
11626 spdy_writes, arraysize(spdy_writes));
11627 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
11629 TestCompletionCallback callback;
11630 HttpRequestInfo request1;
11631 request1.method = "GET";
11632 request1.url = GURL("https://www.google.com/");
11633 request1.load_flags = 0;
11634 HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
11636 int rv = trans1.Start(&request1, callback.callback(), BoundNetLog());
11637 EXPECT_EQ(ERR_IO_PENDING, rv);
11638 EXPECT_EQ(OK, callback.WaitForResult());
11640 const HttpResponseInfo* response = trans1.GetResponseInfo();
11641 ASSERT_TRUE(response != NULL);
11642 ASSERT_TRUE(response->headers.get() != NULL);
11643 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
11645 std::string response_data;
11646 ASSERT_EQ(OK, ReadTransaction(&trans1, &response_data));
11647 EXPECT_EQ("hello!", response_data);
11649 // Preload cache entries into HostCache.
11650 HostResolver::RequestInfo resolve_info(HostPortPair("www.gmail.com", 443));
11651 AddressList ignored;
11652 rv = host_resolver.Resolve(resolve_info,
11653 DEFAULT_PRIORITY,
11654 &ignored,
11655 callback.callback(),
11656 NULL,
11657 BoundNetLog());
11658 EXPECT_EQ(ERR_IO_PENDING, rv);
11659 rv = callback.WaitForResult();
11660 EXPECT_EQ(OK, rv);
11662 HttpRequestInfo request2;
11663 request2.method = "GET";
11664 request2.url = GURL("https://www.gmail.com/");
11665 request2.load_flags = 0;
11666 HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
11668 rv = trans2.Start(&request2, callback.callback(), BoundNetLog());
11669 EXPECT_EQ(ERR_IO_PENDING, rv);
11670 EXPECT_EQ(OK, callback.WaitForResult());
11672 response = trans2.GetResponseInfo();
11673 ASSERT_TRUE(response != NULL);
11674 ASSERT_TRUE(response->headers.get() != NULL);
11675 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
11676 EXPECT_TRUE(response->was_fetched_via_spdy);
11677 EXPECT_TRUE(response->was_npn_negotiated);
11678 ASSERT_EQ(OK, ReadTransaction(&trans2, &response_data));
11679 EXPECT_EQ("hello!", response_data);
11680 #endif
11682 #undef MAYBE_UseIPConnectionPoolingWithHostCacheExpiration
11684 TEST_P(HttpNetworkTransactionTest, DoNotUseSpdySessionForHttp) {
11685 const std::string https_url = "https://www.google.com:8080/";
11686 const std::string http_url = "http://www.google.com:8080/";
11688 // SPDY GET for HTTPS URL
11689 scoped_ptr<SpdyFrame> req1(
11690 spdy_util_.ConstructSpdyGet(https_url.c_str(), false, 1, LOWEST));
11692 MockWrite writes1[] = {
11693 CreateMockWrite(*req1, 0),
11696 scoped_ptr<SpdyFrame> resp1(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11697 scoped_ptr<SpdyFrame> body1(spdy_util_.ConstructSpdyBodyFrame(1, true));
11698 MockRead reads1[] = {
11699 CreateMockRead(*resp1, 1),
11700 CreateMockRead(*body1, 2),
11701 MockRead(ASYNC, ERR_IO_PENDING, 3)
11704 DelayedSocketData data1(
11705 1, reads1, arraysize(reads1),
11706 writes1, arraysize(writes1));
11707 MockConnect connect_data1(ASYNC, OK);
11708 data1.set_connect_data(connect_data1);
11710 // HTTP GET for the HTTP URL
11711 MockWrite writes2[] = {
11712 MockWrite(ASYNC, 4,
11713 "GET / HTTP/1.1\r\n"
11714 "Host: www.google.com:8080\r\n"
11715 "Connection: keep-alive\r\n\r\n"),
11718 MockRead reads2[] = {
11719 MockRead(ASYNC, 5, "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
11720 MockRead(ASYNC, 6, "hello"),
11721 MockRead(ASYNC, 7, OK),
11724 DelayedSocketData data2(
11725 1, reads2, arraysize(reads2),
11726 writes2, arraysize(writes2));
11728 SSLSocketDataProvider ssl(ASYNC, OK);
11729 ssl.SetNextProto(GetParam());
11730 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
11731 session_deps_.socket_factory->AddSocketDataProvider(&data1);
11732 session_deps_.socket_factory->AddSocketDataProvider(&data2);
11734 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11736 // Start the first transaction to set up the SpdySession
11737 HttpRequestInfo request1;
11738 request1.method = "GET";
11739 request1.url = GURL(https_url);
11740 request1.load_flags = 0;
11741 HttpNetworkTransaction trans1(LOWEST, session.get());
11742 TestCompletionCallback callback1;
11743 EXPECT_EQ(ERR_IO_PENDING,
11744 trans1.Start(&request1, callback1.callback(), BoundNetLog()));
11745 base::MessageLoop::current()->RunUntilIdle();
11747 EXPECT_EQ(OK, callback1.WaitForResult());
11748 EXPECT_TRUE(trans1.GetResponseInfo()->was_fetched_via_spdy);
11750 // Now, start the HTTP request
11751 HttpRequestInfo request2;
11752 request2.method = "GET";
11753 request2.url = GURL(http_url);
11754 request2.load_flags = 0;
11755 HttpNetworkTransaction trans2(MEDIUM, session.get());
11756 TestCompletionCallback callback2;
11757 EXPECT_EQ(ERR_IO_PENDING,
11758 trans2.Start(&request2, callback2.callback(), BoundNetLog()));
11759 base::MessageLoop::current()->RunUntilIdle();
11761 EXPECT_EQ(OK, callback2.WaitForResult());
11762 EXPECT_FALSE(trans2.GetResponseInfo()->was_fetched_via_spdy);
11765 TEST_P(HttpNetworkTransactionTest, DoNotUseSpdySessionForHttpOverTunnel) {
11766 const std::string https_url = "https://www.google.com:8080/";
11767 const std::string http_url = "http://www.google.com:8080/";
11769 // SPDY GET for HTTPS URL (through CONNECT tunnel)
11770 const HostPortPair host_port_pair("www.google.com", 8080);
11771 scoped_ptr<SpdyFrame> connect(
11772 spdy_util_.ConstructSpdyConnect(NULL, 0, 1, LOWEST, host_port_pair));
11773 scoped_ptr<SpdyFrame> req1(
11774 spdy_util_.ConstructSpdyGet(https_url.c_str(), false, 1, LOWEST));
11775 scoped_ptr<SpdyFrame> wrapped_req1(
11776 spdy_util_.ConstructWrappedSpdyFrame(req1, 1));
11778 // SPDY GET for HTTP URL (through the proxy, but not the tunnel).
11779 SpdyHeaderBlock req2_block;
11780 req2_block[spdy_util_.GetMethodKey()] = "GET";
11781 req2_block[spdy_util_.GetPathKey()] = "/";
11782 req2_block[spdy_util_.GetHostKey()] = "www.google.com:8080";
11783 req2_block[spdy_util_.GetSchemeKey()] = "http";
11784 spdy_util_.MaybeAddVersionHeader(&req2_block);
11785 scoped_ptr<SpdyFrame> req2(
11786 spdy_util_.ConstructSpdySyn(3, req2_block, MEDIUM, false, true));
11788 MockWrite writes1[] = {
11789 CreateMockWrite(*connect, 0),
11790 CreateMockWrite(*wrapped_req1, 2),
11791 CreateMockWrite(*req2, 5),
11794 scoped_ptr<SpdyFrame> conn_resp(
11795 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11796 scoped_ptr<SpdyFrame> resp1(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11797 scoped_ptr<SpdyFrame> body1(spdy_util_.ConstructSpdyBodyFrame(1, true));
11798 scoped_ptr<SpdyFrame> wrapped_resp1(
11799 spdy_util_.ConstructWrappedSpdyFrame(resp1, 1));
11800 scoped_ptr<SpdyFrame> wrapped_body1(
11801 spdy_util_.ConstructWrappedSpdyFrame(body1, 1));
11802 scoped_ptr<SpdyFrame> resp2(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
11803 scoped_ptr<SpdyFrame> body2(spdy_util_.ConstructSpdyBodyFrame(3, true));
11804 MockRead reads1[] = {
11805 CreateMockRead(*conn_resp, 1),
11806 CreateMockRead(*wrapped_resp1, 3),
11807 CreateMockRead(*wrapped_body1, 4),
11808 CreateMockRead(*resp2, 6),
11809 CreateMockRead(*body2, 7),
11810 MockRead(ASYNC, ERR_IO_PENDING, 8)
11813 DeterministicSocketData data1(reads1, arraysize(reads1),
11814 writes1, arraysize(writes1));
11815 MockConnect connect_data1(ASYNC, OK);
11816 data1.set_connect_data(connect_data1);
11818 session_deps_.proxy_service.reset(
11819 ProxyService::CreateFixedFromPacResult("HTTPS proxy:70"));
11820 CapturingNetLog log;
11821 session_deps_.net_log = &log;
11822 SSLSocketDataProvider ssl1(ASYNC, OK); // to the proxy
11823 ssl1.SetNextProto(GetParam());
11824 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl1);
11825 SSLSocketDataProvider ssl2(ASYNC, OK); // to the server
11826 ssl2.SetNextProto(GetParam());
11827 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl2);
11828 session_deps_.deterministic_socket_factory->AddSocketDataProvider(&data1);
11830 scoped_refptr<HttpNetworkSession> session(
11831 SpdySessionDependencies::SpdyCreateSessionDeterministic(&session_deps_));
11833 // Start the first transaction to set up the SpdySession
11834 HttpRequestInfo request1;
11835 request1.method = "GET";
11836 request1.url = GURL(https_url);
11837 request1.load_flags = 0;
11838 HttpNetworkTransaction trans1(LOWEST, session.get());
11839 TestCompletionCallback callback1;
11840 EXPECT_EQ(ERR_IO_PENDING,
11841 trans1.Start(&request1, callback1.callback(), BoundNetLog()));
11842 base::MessageLoop::current()->RunUntilIdle();
11843 data1.RunFor(4);
11845 EXPECT_EQ(OK, callback1.WaitForResult());
11846 EXPECT_TRUE(trans1.GetResponseInfo()->was_fetched_via_spdy);
11848 LoadTimingInfo load_timing_info1;
11849 EXPECT_TRUE(trans1.GetLoadTimingInfo(&load_timing_info1));
11850 TestLoadTimingNotReusedWithPac(load_timing_info1,
11851 CONNECT_TIMING_HAS_SSL_TIMES);
11853 // Now, start the HTTP request
11854 HttpRequestInfo request2;
11855 request2.method = "GET";
11856 request2.url = GURL(http_url);
11857 request2.load_flags = 0;
11858 HttpNetworkTransaction trans2(MEDIUM, session.get());
11859 TestCompletionCallback callback2;
11860 EXPECT_EQ(ERR_IO_PENDING,
11861 trans2.Start(&request2, callback2.callback(), BoundNetLog()));
11862 base::MessageLoop::current()->RunUntilIdle();
11863 data1.RunFor(3);
11865 EXPECT_EQ(OK, callback2.WaitForResult());
11866 EXPECT_TRUE(trans2.GetResponseInfo()->was_fetched_via_spdy);
11868 LoadTimingInfo load_timing_info2;
11869 EXPECT_TRUE(trans2.GetLoadTimingInfo(&load_timing_info2));
11870 // The established SPDY sessions is considered reused by the HTTP request.
11871 TestLoadTimingReusedWithPac(load_timing_info2);
11872 // HTTP requests over a SPDY session should have a different connection
11873 // socket_log_id than requests over a tunnel.
11874 EXPECT_NE(load_timing_info1.socket_log_id, load_timing_info2.socket_log_id);
11877 TEST_P(HttpNetworkTransactionTest, UseSpdySessionForHttpWhenForced) {
11878 session_deps_.force_spdy_always = true;
11879 const std::string https_url = "https://www.google.com:8080/";
11880 const std::string http_url = "http://www.google.com:8080/";
11882 // SPDY GET for HTTPS URL
11883 scoped_ptr<SpdyFrame> req1(
11884 spdy_util_.ConstructSpdyGet(https_url.c_str(), false, 1, LOWEST));
11885 // SPDY GET for the HTTP URL
11886 scoped_ptr<SpdyFrame> req2(
11887 spdy_util_.ConstructSpdyGet(http_url.c_str(), false, 3, MEDIUM));
11889 MockWrite writes[] = {
11890 CreateMockWrite(*req1, 1),
11891 CreateMockWrite(*req2, 4),
11894 scoped_ptr<SpdyFrame> resp1(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11895 scoped_ptr<SpdyFrame> body1(spdy_util_.ConstructSpdyBodyFrame(1, true));
11896 scoped_ptr<SpdyFrame> resp2(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
11897 scoped_ptr<SpdyFrame> body2(spdy_util_.ConstructSpdyBodyFrame(3, true));
11898 MockRead reads[] = {
11899 CreateMockRead(*resp1, 2),
11900 CreateMockRead(*body1, 3),
11901 CreateMockRead(*resp2, 5),
11902 CreateMockRead(*body2, 6),
11903 MockRead(ASYNC, ERR_IO_PENDING, 7)
11906 OrderedSocketData data(reads, arraysize(reads),
11907 writes, arraysize(writes));
11909 SSLSocketDataProvider ssl(ASYNC, OK);
11910 ssl.SetNextProto(GetParam());
11911 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
11912 session_deps_.socket_factory->AddSocketDataProvider(&data);
11914 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11916 // Start the first transaction to set up the SpdySession
11917 HttpRequestInfo request1;
11918 request1.method = "GET";
11919 request1.url = GURL(https_url);
11920 request1.load_flags = 0;
11921 HttpNetworkTransaction trans1(LOWEST, session.get());
11922 TestCompletionCallback callback1;
11923 EXPECT_EQ(ERR_IO_PENDING,
11924 trans1.Start(&request1, callback1.callback(), BoundNetLog()));
11925 base::MessageLoop::current()->RunUntilIdle();
11927 EXPECT_EQ(OK, callback1.WaitForResult());
11928 EXPECT_TRUE(trans1.GetResponseInfo()->was_fetched_via_spdy);
11930 // Now, start the HTTP request
11931 HttpRequestInfo request2;
11932 request2.method = "GET";
11933 request2.url = GURL(http_url);
11934 request2.load_flags = 0;
11935 HttpNetworkTransaction trans2(MEDIUM, session.get());
11936 TestCompletionCallback callback2;
11937 EXPECT_EQ(ERR_IO_PENDING,
11938 trans2.Start(&request2, callback2.callback(), BoundNetLog()));
11939 base::MessageLoop::current()->RunUntilIdle();
11941 EXPECT_EQ(OK, callback2.WaitForResult());
11942 EXPECT_TRUE(trans2.GetResponseInfo()->was_fetched_via_spdy);
11945 // Test that in the case where we have a SPDY session to a SPDY proxy
11946 // that we do not pool other origins that resolve to the same IP when
11947 // the certificate does not match the new origin.
11948 // http://crbug.com/134690
11949 TEST_P(HttpNetworkTransactionTest, DoNotUseSpdySessionIfCertDoesNotMatch) {
11950 const std::string url1 = "http://www.google.com/";
11951 const std::string url2 = "https://mail.google.com/";
11952 const std::string ip_addr = "1.2.3.4";
11954 // SPDY GET for HTTP URL (through SPDY proxy)
11955 scoped_ptr<SpdyHeaderBlock> headers(
11956 spdy_util_.ConstructGetHeaderBlockForProxy("http://www.google.com/"));
11957 scoped_ptr<SpdyFrame> req1(
11958 spdy_util_.ConstructSpdySyn(1, *headers, LOWEST, false, true));
11960 MockWrite writes1[] = {
11961 CreateMockWrite(*req1, 0),
11964 scoped_ptr<SpdyFrame> resp1(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11965 scoped_ptr<SpdyFrame> body1(spdy_util_.ConstructSpdyBodyFrame(1, true));
11966 MockRead reads1[] = {
11967 CreateMockRead(*resp1, 1),
11968 CreateMockRead(*body1, 2),
11969 MockRead(ASYNC, OK, 3) // EOF
11972 scoped_ptr<DeterministicSocketData> data1(
11973 new DeterministicSocketData(reads1, arraysize(reads1),
11974 writes1, arraysize(writes1)));
11975 IPAddressNumber ip;
11976 ASSERT_TRUE(ParseIPLiteralToNumber(ip_addr, &ip));
11977 IPEndPoint peer_addr = IPEndPoint(ip, 443);
11978 MockConnect connect_data1(ASYNC, OK, peer_addr);
11979 data1->set_connect_data(connect_data1);
11981 // SPDY GET for HTTPS URL (direct)
11982 scoped_ptr<SpdyFrame> req2(
11983 spdy_util_.ConstructSpdyGet(url2.c_str(), false, 1, MEDIUM));
11985 MockWrite writes2[] = {
11986 CreateMockWrite(*req2, 0),
11989 scoped_ptr<SpdyFrame> resp2(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11990 scoped_ptr<SpdyFrame> body2(spdy_util_.ConstructSpdyBodyFrame(1, true));
11991 MockRead reads2[] = {
11992 CreateMockRead(*resp2, 1),
11993 CreateMockRead(*body2, 2),
11994 MockRead(ASYNC, OK, 3) // EOF
11997 scoped_ptr<DeterministicSocketData> data2(
11998 new DeterministicSocketData(reads2, arraysize(reads2),
11999 writes2, arraysize(writes2)));
12000 MockConnect connect_data2(ASYNC, OK);
12001 data2->set_connect_data(connect_data2);
12003 // Set up a proxy config that sends HTTP requests to a proxy, and
12004 // all others direct.
12005 ProxyConfig proxy_config;
12006 proxy_config.proxy_rules().ParseFromString("http=https://proxy:443");
12007 CapturingProxyResolver* capturing_proxy_resolver =
12008 new CapturingProxyResolver();
12009 session_deps_.proxy_service.reset(new ProxyService(
12010 new ProxyConfigServiceFixed(proxy_config), capturing_proxy_resolver,
12011 NULL));
12013 // Load a valid cert. Note, that this does not need to
12014 // be valid for proxy because the MockSSLClientSocket does
12015 // not actually verify it. But SpdySession will use this
12016 // to see if it is valid for the new origin
12017 base::FilePath certs_dir = GetTestCertsDirectory();
12018 scoped_refptr<X509Certificate> server_cert(
12019 ImportCertFromFile(certs_dir, "ok_cert.pem"));
12020 ASSERT_NE(static_cast<X509Certificate*>(NULL), server_cert.get());
12022 SSLSocketDataProvider ssl1(ASYNC, OK); // to the proxy
12023 ssl1.SetNextProto(GetParam());
12024 ssl1.cert = server_cert;
12025 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl1);
12026 session_deps_.deterministic_socket_factory->AddSocketDataProvider(
12027 data1.get());
12029 SSLSocketDataProvider ssl2(ASYNC, OK); // to the server
12030 ssl2.SetNextProto(GetParam());
12031 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl2);
12032 session_deps_.deterministic_socket_factory->AddSocketDataProvider(
12033 data2.get());
12035 session_deps_.host_resolver.reset(new MockCachingHostResolver());
12036 session_deps_.host_resolver->rules()->AddRule("mail.google.com", ip_addr);
12037 session_deps_.host_resolver->rules()->AddRule("proxy", ip_addr);
12039 scoped_refptr<HttpNetworkSession> session(
12040 SpdySessionDependencies::SpdyCreateSessionDeterministic(&session_deps_));
12042 // Start the first transaction to set up the SpdySession
12043 HttpRequestInfo request1;
12044 request1.method = "GET";
12045 request1.url = GURL(url1);
12046 request1.load_flags = 0;
12047 HttpNetworkTransaction trans1(LOWEST, session.get());
12048 TestCompletionCallback callback1;
12049 ASSERT_EQ(ERR_IO_PENDING,
12050 trans1.Start(&request1, callback1.callback(), BoundNetLog()));
12051 data1->RunFor(3);
12053 ASSERT_TRUE(callback1.have_result());
12054 EXPECT_EQ(OK, callback1.WaitForResult());
12055 EXPECT_TRUE(trans1.GetResponseInfo()->was_fetched_via_spdy);
12057 // Now, start the HTTP request
12058 HttpRequestInfo request2;
12059 request2.method = "GET";
12060 request2.url = GURL(url2);
12061 request2.load_flags = 0;
12062 HttpNetworkTransaction trans2(MEDIUM, session.get());
12063 TestCompletionCallback callback2;
12064 EXPECT_EQ(ERR_IO_PENDING,
12065 trans2.Start(&request2, callback2.callback(), BoundNetLog()));
12066 base::MessageLoop::current()->RunUntilIdle();
12067 data2->RunFor(3);
12069 ASSERT_TRUE(callback2.have_result());
12070 EXPECT_EQ(OK, callback2.WaitForResult());
12071 EXPECT_TRUE(trans2.GetResponseInfo()->was_fetched_via_spdy);
12074 // Test to verify that a failed socket read (due to an ERR_CONNECTION_CLOSED
12075 // error) in SPDY session, removes the socket from pool and closes the SPDY
12076 // session. Verify that new url's from the same HttpNetworkSession (and a new
12077 // SpdySession) do work. http://crbug.com/224701
12078 TEST_P(HttpNetworkTransactionTest, ErrorSocketNotConnected) {
12079 const std::string https_url = "https://www.google.com/";
12081 MockRead reads1[] = {
12082 MockRead(SYNCHRONOUS, ERR_CONNECTION_CLOSED, 0)
12085 scoped_ptr<DeterministicSocketData> data1(
12086 new DeterministicSocketData(reads1, arraysize(reads1), NULL, 0));
12087 data1->SetStop(1);
12089 scoped_ptr<SpdyFrame> req2(
12090 spdy_util_.ConstructSpdyGet(https_url.c_str(), false, 1, MEDIUM));
12091 MockWrite writes2[] = {
12092 CreateMockWrite(*req2, 0),
12095 scoped_ptr<SpdyFrame> resp2(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
12096 scoped_ptr<SpdyFrame> body2(spdy_util_.ConstructSpdyBodyFrame(1, true));
12097 MockRead reads2[] = {
12098 CreateMockRead(*resp2, 1),
12099 CreateMockRead(*body2, 2),
12100 MockRead(ASYNC, OK, 3) // EOF
12103 scoped_ptr<DeterministicSocketData> data2(
12104 new DeterministicSocketData(reads2, arraysize(reads2),
12105 writes2, arraysize(writes2)));
12107 SSLSocketDataProvider ssl1(ASYNC, OK);
12108 ssl1.SetNextProto(GetParam());
12109 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl1);
12110 session_deps_.deterministic_socket_factory->AddSocketDataProvider(
12111 data1.get());
12113 SSLSocketDataProvider ssl2(ASYNC, OK);
12114 ssl2.SetNextProto(GetParam());
12115 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl2);
12116 session_deps_.deterministic_socket_factory->AddSocketDataProvider(
12117 data2.get());
12119 scoped_refptr<HttpNetworkSession> session(
12120 SpdySessionDependencies::SpdyCreateSessionDeterministic(&session_deps_));
12122 // Start the first transaction to set up the SpdySession and verify that
12123 // connection was closed.
12124 HttpRequestInfo request1;
12125 request1.method = "GET";
12126 request1.url = GURL(https_url);
12127 request1.load_flags = 0;
12128 HttpNetworkTransaction trans1(MEDIUM, session.get());
12129 TestCompletionCallback callback1;
12130 EXPECT_EQ(ERR_IO_PENDING,
12131 trans1.Start(&request1, callback1.callback(), BoundNetLog()));
12132 base::MessageLoop::current()->RunUntilIdle();
12133 EXPECT_EQ(ERR_CONNECTION_CLOSED, callback1.WaitForResult());
12135 // Now, start the second request and make sure it succeeds.
12136 HttpRequestInfo request2;
12137 request2.method = "GET";
12138 request2.url = GURL(https_url);
12139 request2.load_flags = 0;
12140 HttpNetworkTransaction trans2(MEDIUM, session.get());
12141 TestCompletionCallback callback2;
12142 EXPECT_EQ(ERR_IO_PENDING,
12143 trans2.Start(&request2, callback2.callback(), BoundNetLog()));
12144 base::MessageLoop::current()->RunUntilIdle();
12145 data2->RunFor(3);
12147 ASSERT_TRUE(callback2.have_result());
12148 EXPECT_EQ(OK, callback2.WaitForResult());
12149 EXPECT_TRUE(trans2.GetResponseInfo()->was_fetched_via_spdy);
12152 TEST_P(HttpNetworkTransactionTest, CloseIdleSpdySessionToOpenNewOne) {
12153 session_deps_.next_protos = SpdyNextProtos();
12154 ClientSocketPoolManager::set_max_sockets_per_group(
12155 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
12156 ClientSocketPoolManager::set_max_sockets_per_pool(
12157 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
12159 // Use two different hosts with different IPs so they don't get pooled.
12160 session_deps_.host_resolver->rules()->AddRule("www.a.com", "10.0.0.1");
12161 session_deps_.host_resolver->rules()->AddRule("www.b.com", "10.0.0.2");
12162 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12164 SSLSocketDataProvider ssl1(ASYNC, OK);
12165 ssl1.SetNextProto(GetParam());
12166 SSLSocketDataProvider ssl2(ASYNC, OK);
12167 ssl2.SetNextProto(GetParam());
12168 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
12169 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
12171 scoped_ptr<SpdyFrame> host1_req(spdy_util_.ConstructSpdyGet(
12172 "https://www.a.com", false, 1, DEFAULT_PRIORITY));
12173 MockWrite spdy1_writes[] = {
12174 CreateMockWrite(*host1_req, 1),
12176 scoped_ptr<SpdyFrame> host1_resp(
12177 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
12178 scoped_ptr<SpdyFrame> host1_resp_body(
12179 spdy_util_.ConstructSpdyBodyFrame(1, true));
12180 MockRead spdy1_reads[] = {
12181 CreateMockRead(*host1_resp, 2),
12182 CreateMockRead(*host1_resp_body, 3),
12183 MockRead(ASYNC, ERR_IO_PENDING, 4),
12186 scoped_ptr<OrderedSocketData> spdy1_data(
12187 new OrderedSocketData(
12188 spdy1_reads, arraysize(spdy1_reads),
12189 spdy1_writes, arraysize(spdy1_writes)));
12190 session_deps_.socket_factory->AddSocketDataProvider(spdy1_data.get());
12192 scoped_ptr<SpdyFrame> host2_req(spdy_util_.ConstructSpdyGet(
12193 "https://www.b.com", false, 1, DEFAULT_PRIORITY));
12194 MockWrite spdy2_writes[] = {
12195 CreateMockWrite(*host2_req, 1),
12197 scoped_ptr<SpdyFrame> host2_resp(
12198 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
12199 scoped_ptr<SpdyFrame> host2_resp_body(
12200 spdy_util_.ConstructSpdyBodyFrame(1, true));
12201 MockRead spdy2_reads[] = {
12202 CreateMockRead(*host2_resp, 2),
12203 CreateMockRead(*host2_resp_body, 3),
12204 MockRead(ASYNC, ERR_IO_PENDING, 4),
12207 scoped_ptr<OrderedSocketData> spdy2_data(
12208 new OrderedSocketData(
12209 spdy2_reads, arraysize(spdy2_reads),
12210 spdy2_writes, arraysize(spdy2_writes)));
12211 session_deps_.socket_factory->AddSocketDataProvider(spdy2_data.get());
12213 MockWrite http_write[] = {
12214 MockWrite("GET / HTTP/1.1\r\n"
12215 "Host: www.a.com\r\n"
12216 "Connection: keep-alive\r\n\r\n"),
12219 MockRead http_read[] = {
12220 MockRead("HTTP/1.1 200 OK\r\n"),
12221 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
12222 MockRead("Content-Length: 6\r\n\r\n"),
12223 MockRead("hello!"),
12225 StaticSocketDataProvider http_data(http_read, arraysize(http_read),
12226 http_write, arraysize(http_write));
12227 session_deps_.socket_factory->AddSocketDataProvider(&http_data);
12229 HostPortPair host_port_pair_a("www.a.com", 443);
12230 SpdySessionKey spdy_session_key_a(
12231 host_port_pair_a, ProxyServer::Direct(), PRIVACY_MODE_DISABLED);
12232 EXPECT_FALSE(
12233 HasSpdySession(session->spdy_session_pool(), spdy_session_key_a));
12235 TestCompletionCallback callback;
12236 HttpRequestInfo request1;
12237 request1.method = "GET";
12238 request1.url = GURL("https://www.a.com/");
12239 request1.load_flags = 0;
12240 scoped_ptr<HttpNetworkTransaction> trans(
12241 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12243 int rv = trans->Start(&request1, callback.callback(), BoundNetLog());
12244 EXPECT_EQ(ERR_IO_PENDING, rv);
12245 EXPECT_EQ(OK, callback.WaitForResult());
12247 const HttpResponseInfo* response = trans->GetResponseInfo();
12248 ASSERT_TRUE(response != NULL);
12249 ASSERT_TRUE(response->headers.get() != NULL);
12250 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
12251 EXPECT_TRUE(response->was_fetched_via_spdy);
12252 EXPECT_TRUE(response->was_npn_negotiated);
12254 std::string response_data;
12255 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
12256 EXPECT_EQ("hello!", response_data);
12257 trans.reset();
12258 EXPECT_TRUE(
12259 HasSpdySession(session->spdy_session_pool(), spdy_session_key_a));
12261 HostPortPair host_port_pair_b("www.b.com", 443);
12262 SpdySessionKey spdy_session_key_b(
12263 host_port_pair_b, ProxyServer::Direct(), PRIVACY_MODE_DISABLED);
12264 EXPECT_FALSE(
12265 HasSpdySession(session->spdy_session_pool(), spdy_session_key_b));
12266 HttpRequestInfo request2;
12267 request2.method = "GET";
12268 request2.url = GURL("https://www.b.com/");
12269 request2.load_flags = 0;
12270 trans.reset(new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12272 rv = trans->Start(&request2, callback.callback(), BoundNetLog());
12273 EXPECT_EQ(ERR_IO_PENDING, rv);
12274 EXPECT_EQ(OK, callback.WaitForResult());
12276 response = trans->GetResponseInfo();
12277 ASSERT_TRUE(response != NULL);
12278 ASSERT_TRUE(response->headers.get() != NULL);
12279 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
12280 EXPECT_TRUE(response->was_fetched_via_spdy);
12281 EXPECT_TRUE(response->was_npn_negotiated);
12282 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
12283 EXPECT_EQ("hello!", response_data);
12284 EXPECT_FALSE(
12285 HasSpdySession(session->spdy_session_pool(), spdy_session_key_a));
12286 EXPECT_TRUE(
12287 HasSpdySession(session->spdy_session_pool(), spdy_session_key_b));
12289 HostPortPair host_port_pair_a1("www.a.com", 80);
12290 SpdySessionKey spdy_session_key_a1(
12291 host_port_pair_a1, ProxyServer::Direct(), PRIVACY_MODE_DISABLED);
12292 EXPECT_FALSE(
12293 HasSpdySession(session->spdy_session_pool(), spdy_session_key_a1));
12294 HttpRequestInfo request3;
12295 request3.method = "GET";
12296 request3.url = GURL("http://www.a.com/");
12297 request3.load_flags = 0;
12298 trans.reset(new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12300 rv = trans->Start(&request3, callback.callback(), BoundNetLog());
12301 EXPECT_EQ(ERR_IO_PENDING, rv);
12302 EXPECT_EQ(OK, callback.WaitForResult());
12304 response = trans->GetResponseInfo();
12305 ASSERT_TRUE(response != NULL);
12306 ASSERT_TRUE(response->headers.get() != NULL);
12307 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
12308 EXPECT_FALSE(response->was_fetched_via_spdy);
12309 EXPECT_FALSE(response->was_npn_negotiated);
12310 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
12311 EXPECT_EQ("hello!", response_data);
12312 EXPECT_FALSE(
12313 HasSpdySession(session->spdy_session_pool(), spdy_session_key_a));
12314 EXPECT_FALSE(
12315 HasSpdySession(session->spdy_session_pool(), spdy_session_key_b));
12318 TEST_P(HttpNetworkTransactionTest, HttpSyncConnectError) {
12319 HttpRequestInfo request;
12320 request.method = "GET";
12321 request.url = GURL("http://www.google.com/");
12322 request.load_flags = 0;
12324 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12325 scoped_ptr<HttpTransaction> trans(
12326 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12328 MockConnect mock_connect(SYNCHRONOUS, ERR_CONNECTION_REFUSED);
12329 StaticSocketDataProvider data;
12330 data.set_connect_data(mock_connect);
12331 session_deps_.socket_factory->AddSocketDataProvider(&data);
12333 TestCompletionCallback callback;
12335 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
12336 EXPECT_EQ(ERR_IO_PENDING, rv);
12338 rv = callback.WaitForResult();
12339 EXPECT_EQ(ERR_CONNECTION_REFUSED, rv);
12341 EXPECT_EQ(NULL, trans->GetResponseInfo());
12343 // We don't care whether this succeeds or fails, but it shouldn't crash.
12344 HttpRequestHeaders request_headers;
12345 trans->GetFullRequestHeaders(&request_headers);
12348 TEST_P(HttpNetworkTransactionTest, HttpAsyncConnectError) {
12349 HttpRequestInfo request;
12350 request.method = "GET";
12351 request.url = GURL("http://www.google.com/");
12352 request.load_flags = 0;
12354 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12355 scoped_ptr<HttpTransaction> trans(
12356 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12358 MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
12359 StaticSocketDataProvider data;
12360 data.set_connect_data(mock_connect);
12361 session_deps_.socket_factory->AddSocketDataProvider(&data);
12363 TestCompletionCallback callback;
12365 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
12366 EXPECT_EQ(ERR_IO_PENDING, rv);
12368 rv = callback.WaitForResult();
12369 EXPECT_EQ(ERR_CONNECTION_REFUSED, rv);
12371 EXPECT_EQ(NULL, trans->GetResponseInfo());
12373 // We don't care whether this succeeds or fails, but it shouldn't crash.
12374 HttpRequestHeaders request_headers;
12375 trans->GetFullRequestHeaders(&request_headers);
12378 TEST_P(HttpNetworkTransactionTest, HttpSyncWriteError) {
12379 HttpRequestInfo request;
12380 request.method = "GET";
12381 request.url = GURL("http://www.google.com/");
12382 request.load_flags = 0;
12384 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12385 scoped_ptr<HttpTransaction> trans(
12386 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12388 MockWrite data_writes[] = {
12389 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
12391 MockRead data_reads[] = {
12392 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
12395 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
12396 data_writes, arraysize(data_writes));
12397 session_deps_.socket_factory->AddSocketDataProvider(&data);
12399 TestCompletionCallback callback;
12401 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
12402 EXPECT_EQ(ERR_IO_PENDING, rv);
12404 rv = callback.WaitForResult();
12405 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
12407 EXPECT_EQ(NULL, trans->GetResponseInfo());
12409 HttpRequestHeaders request_headers;
12410 EXPECT_TRUE(trans->GetFullRequestHeaders(&request_headers));
12411 EXPECT_TRUE(request_headers.HasHeader("Host"));
12414 TEST_P(HttpNetworkTransactionTest, HttpAsyncWriteError) {
12415 HttpRequestInfo request;
12416 request.method = "GET";
12417 request.url = GURL("http://www.google.com/");
12418 request.load_flags = 0;
12420 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12421 scoped_ptr<HttpTransaction> trans(
12422 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12424 MockWrite data_writes[] = {
12425 MockWrite(ASYNC, ERR_CONNECTION_RESET),
12427 MockRead data_reads[] = {
12428 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
12431 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
12432 data_writes, arraysize(data_writes));
12433 session_deps_.socket_factory->AddSocketDataProvider(&data);
12435 TestCompletionCallback callback;
12437 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
12438 EXPECT_EQ(ERR_IO_PENDING, rv);
12440 rv = callback.WaitForResult();
12441 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
12443 EXPECT_EQ(NULL, trans->GetResponseInfo());
12445 HttpRequestHeaders request_headers;
12446 EXPECT_TRUE(trans->GetFullRequestHeaders(&request_headers));
12447 EXPECT_TRUE(request_headers.HasHeader("Host"));
12450 TEST_P(HttpNetworkTransactionTest, HttpSyncReadError) {
12451 HttpRequestInfo request;
12452 request.method = "GET";
12453 request.url = GURL("http://www.google.com/");
12454 request.load_flags = 0;
12456 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12457 scoped_ptr<HttpTransaction> trans(
12458 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12460 MockWrite data_writes[] = {
12461 MockWrite("GET / HTTP/1.1\r\n"
12462 "Host: www.google.com\r\n"
12463 "Connection: keep-alive\r\n\r\n"),
12465 MockRead data_reads[] = {
12466 MockRead(SYNCHRONOUS, ERR_CONNECTION_RESET),
12469 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
12470 data_writes, arraysize(data_writes));
12471 session_deps_.socket_factory->AddSocketDataProvider(&data);
12473 TestCompletionCallback callback;
12475 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
12476 EXPECT_EQ(ERR_IO_PENDING, rv);
12478 rv = callback.WaitForResult();
12479 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
12481 EXPECT_EQ(NULL, trans->GetResponseInfo());
12483 HttpRequestHeaders request_headers;
12484 EXPECT_TRUE(trans->GetFullRequestHeaders(&request_headers));
12485 EXPECT_TRUE(request_headers.HasHeader("Host"));
12488 TEST_P(HttpNetworkTransactionTest, HttpAsyncReadError) {
12489 HttpRequestInfo request;
12490 request.method = "GET";
12491 request.url = GURL("http://www.google.com/");
12492 request.load_flags = 0;
12494 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12495 scoped_ptr<HttpTransaction> trans(
12496 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12498 MockWrite data_writes[] = {
12499 MockWrite("GET / HTTP/1.1\r\n"
12500 "Host: www.google.com\r\n"
12501 "Connection: keep-alive\r\n\r\n"),
12503 MockRead data_reads[] = {
12504 MockRead(ASYNC, ERR_CONNECTION_RESET),
12507 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
12508 data_writes, arraysize(data_writes));
12509 session_deps_.socket_factory->AddSocketDataProvider(&data);
12511 TestCompletionCallback callback;
12513 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
12514 EXPECT_EQ(ERR_IO_PENDING, rv);
12516 rv = callback.WaitForResult();
12517 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
12519 EXPECT_EQ(NULL, trans->GetResponseInfo());
12521 HttpRequestHeaders request_headers;
12522 EXPECT_TRUE(trans->GetFullRequestHeaders(&request_headers));
12523 EXPECT_TRUE(request_headers.HasHeader("Host"));
12526 TEST_P(HttpNetworkTransactionTest, GetFullRequestHeadersIncludesExtraHeader) {
12527 HttpRequestInfo request;
12528 request.method = "GET";
12529 request.url = GURL("http://www.google.com/");
12530 request.load_flags = 0;
12531 request.extra_headers.SetHeader("X-Foo", "bar");
12533 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12534 scoped_ptr<HttpTransaction> trans(
12535 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12537 MockWrite data_writes[] = {
12538 MockWrite("GET / HTTP/1.1\r\n"
12539 "Host: www.google.com\r\n"
12540 "Connection: keep-alive\r\n"
12541 "X-Foo: bar\r\n\r\n"),
12543 MockRead data_reads[] = {
12544 MockRead("HTTP/1.1 200 OK\r\n"
12545 "Content-Length: 5\r\n\r\n"
12546 "hello"),
12547 MockRead(ASYNC, ERR_UNEXPECTED),
12550 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
12551 data_writes, arraysize(data_writes));
12552 session_deps_.socket_factory->AddSocketDataProvider(&data);
12554 TestCompletionCallback callback;
12556 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
12557 EXPECT_EQ(ERR_IO_PENDING, rv);
12559 rv = callback.WaitForResult();
12560 EXPECT_EQ(OK, rv);
12562 HttpRequestHeaders request_headers;
12563 EXPECT_TRUE(trans->GetFullRequestHeaders(&request_headers));
12564 std::string foo;
12565 EXPECT_TRUE(request_headers.GetHeader("X-Foo", &foo));
12566 EXPECT_EQ("bar", foo);
12569 namespace {
12571 // Fake HttpStream that simply records calls to SetPriority().
12572 class FakeStream : public HttpStream,
12573 public base::SupportsWeakPtr<FakeStream> {
12574 public:
12575 explicit FakeStream(RequestPriority priority) : priority_(priority) {}
12576 ~FakeStream() override {}
12578 RequestPriority priority() const { return priority_; }
12580 int InitializeStream(const HttpRequestInfo* request_info,
12581 RequestPriority priority,
12582 const BoundNetLog& net_log,
12583 const CompletionCallback& callback) override {
12584 return ERR_IO_PENDING;
12587 int SendRequest(const HttpRequestHeaders& request_headers,
12588 HttpResponseInfo* response,
12589 const CompletionCallback& callback) override {
12590 ADD_FAILURE();
12591 return ERR_UNEXPECTED;
12594 int ReadResponseHeaders(const CompletionCallback& callback) override {
12595 ADD_FAILURE();
12596 return ERR_UNEXPECTED;
12599 int ReadResponseBody(IOBuffer* buf,
12600 int buf_len,
12601 const CompletionCallback& callback) override {
12602 ADD_FAILURE();
12603 return ERR_UNEXPECTED;
12606 void Close(bool not_reusable) override {}
12608 bool IsResponseBodyComplete() const override {
12609 ADD_FAILURE();
12610 return false;
12613 bool CanFindEndOfResponse() const override { return false; }
12615 bool IsConnectionReused() const override {
12616 ADD_FAILURE();
12617 return false;
12620 void SetConnectionReused() override { ADD_FAILURE(); }
12622 bool IsConnectionReusable() const override {
12623 ADD_FAILURE();
12624 return false;
12627 int64 GetTotalReceivedBytes() const override {
12628 ADD_FAILURE();
12629 return 0;
12632 bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const override {
12633 ADD_FAILURE();
12634 return false;
12637 void GetSSLInfo(SSLInfo* ssl_info) override { ADD_FAILURE(); }
12639 void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override {
12640 ADD_FAILURE();
12643 bool IsSpdyHttpStream() const override {
12644 ADD_FAILURE();
12645 return false;
12648 void Drain(HttpNetworkSession* session) override { ADD_FAILURE(); }
12650 void SetPriority(RequestPriority priority) override { priority_ = priority; }
12652 UploadProgress GetUploadProgress() const override { return UploadProgress(); }
12654 HttpStream* RenewStreamForAuth() override { return NULL; }
12656 private:
12657 RequestPriority priority_;
12659 DISALLOW_COPY_AND_ASSIGN(FakeStream);
12662 // Fake HttpStreamRequest that simply records calls to SetPriority()
12663 // and vends FakeStreams with its current priority.
12664 class FakeStreamRequest : public HttpStreamRequest,
12665 public base::SupportsWeakPtr<FakeStreamRequest> {
12666 public:
12667 FakeStreamRequest(RequestPriority priority,
12668 HttpStreamRequest::Delegate* delegate)
12669 : priority_(priority),
12670 delegate_(delegate),
12671 websocket_stream_create_helper_(NULL) {}
12673 FakeStreamRequest(RequestPriority priority,
12674 HttpStreamRequest::Delegate* delegate,
12675 WebSocketHandshakeStreamBase::CreateHelper* create_helper)
12676 : priority_(priority),
12677 delegate_(delegate),
12678 websocket_stream_create_helper_(create_helper) {}
12680 ~FakeStreamRequest() override {}
12682 RequestPriority priority() const { return priority_; }
12684 const WebSocketHandshakeStreamBase::CreateHelper*
12685 websocket_stream_create_helper() const {
12686 return websocket_stream_create_helper_;
12689 // Create a new FakeStream and pass it to the request's
12690 // delegate. Returns a weak pointer to the FakeStream.
12691 base::WeakPtr<FakeStream> FinishStreamRequest() {
12692 FakeStream* fake_stream = new FakeStream(priority_);
12693 // Do this before calling OnStreamReady() as OnStreamReady() may
12694 // immediately delete |fake_stream|.
12695 base::WeakPtr<FakeStream> weak_stream = fake_stream->AsWeakPtr();
12696 delegate_->OnStreamReady(SSLConfig(), ProxyInfo(), fake_stream);
12697 return weak_stream;
12700 int RestartTunnelWithProxyAuth(const AuthCredentials& credentials) override {
12701 ADD_FAILURE();
12702 return ERR_UNEXPECTED;
12705 LoadState GetLoadState() const override {
12706 ADD_FAILURE();
12707 return LoadState();
12710 void SetPriority(RequestPriority priority) override { priority_ = priority; }
12712 bool was_npn_negotiated() const override { return false; }
12714 NextProto protocol_negotiated() const override { return kProtoUnknown; }
12716 bool using_spdy() const override { return false; }
12718 private:
12719 RequestPriority priority_;
12720 HttpStreamRequest::Delegate* const delegate_;
12721 WebSocketHandshakeStreamBase::CreateHelper* websocket_stream_create_helper_;
12723 DISALLOW_COPY_AND_ASSIGN(FakeStreamRequest);
12726 // Fake HttpStreamFactory that vends FakeStreamRequests.
12727 class FakeStreamFactory : public HttpStreamFactory {
12728 public:
12729 FakeStreamFactory() {}
12730 ~FakeStreamFactory() override {}
12732 // Returns a WeakPtr<> to the last HttpStreamRequest returned by
12733 // RequestStream() (which may be NULL if it was destroyed already).
12734 base::WeakPtr<FakeStreamRequest> last_stream_request() {
12735 return last_stream_request_;
12738 HttpStreamRequest* RequestStream(const HttpRequestInfo& info,
12739 RequestPriority priority,
12740 const SSLConfig& server_ssl_config,
12741 const SSLConfig& proxy_ssl_config,
12742 HttpStreamRequest::Delegate* delegate,
12743 const BoundNetLog& net_log) override {
12744 FakeStreamRequest* fake_request = new FakeStreamRequest(priority, delegate);
12745 last_stream_request_ = fake_request->AsWeakPtr();
12746 return fake_request;
12749 HttpStreamRequest* RequestWebSocketHandshakeStream(
12750 const HttpRequestInfo& info,
12751 RequestPriority priority,
12752 const SSLConfig& server_ssl_config,
12753 const SSLConfig& proxy_ssl_config,
12754 HttpStreamRequest::Delegate* delegate,
12755 WebSocketHandshakeStreamBase::CreateHelper* create_helper,
12756 const BoundNetLog& net_log) override {
12757 FakeStreamRequest* fake_request =
12758 new FakeStreamRequest(priority, delegate, create_helper);
12759 last_stream_request_ = fake_request->AsWeakPtr();
12760 return fake_request;
12763 void PreconnectStreams(int num_streams,
12764 const HttpRequestInfo& info,
12765 RequestPriority priority,
12766 const SSLConfig& server_ssl_config,
12767 const SSLConfig& proxy_ssl_config) override {
12768 ADD_FAILURE();
12771 const HostMappingRules* GetHostMappingRules() const override {
12772 ADD_FAILURE();
12773 return NULL;
12776 private:
12777 base::WeakPtr<FakeStreamRequest> last_stream_request_;
12779 DISALLOW_COPY_AND_ASSIGN(FakeStreamFactory);
12782 // TODO(ricea): Maybe unify this with the one in
12783 // url_request_http_job_unittest.cc ?
12784 class FakeWebSocketBasicHandshakeStream : public WebSocketHandshakeStreamBase {
12785 public:
12786 FakeWebSocketBasicHandshakeStream(scoped_ptr<ClientSocketHandle> connection,
12787 bool using_proxy)
12788 : state_(connection.release(), using_proxy) {}
12790 // Fake implementation of HttpStreamBase methods.
12791 // This ends up being quite "real" because this object has to really send data
12792 // on the mock socket. It might be easier to use the real implementation, but
12793 // the fact that the WebSocket code is not compiled on iOS makes that
12794 // difficult.
12795 int InitializeStream(const HttpRequestInfo* request_info,
12796 RequestPriority priority,
12797 const BoundNetLog& net_log,
12798 const CompletionCallback& callback) override {
12799 state_.Initialize(request_info, priority, net_log, callback);
12800 return OK;
12803 int SendRequest(const HttpRequestHeaders& request_headers,
12804 HttpResponseInfo* response,
12805 const CompletionCallback& callback) override {
12806 return parser()->SendRequest(state_.GenerateRequestLine(), request_headers,
12807 response, callback);
12810 int ReadResponseHeaders(const CompletionCallback& callback) override {
12811 return parser()->ReadResponseHeaders(callback);
12814 int ReadResponseBody(IOBuffer* buf,
12815 int buf_len,
12816 const CompletionCallback& callback) override {
12817 NOTREACHED();
12818 return ERR_IO_PENDING;
12821 void Close(bool not_reusable) override {
12822 if (parser())
12823 parser()->Close(true);
12826 bool IsResponseBodyComplete() const override {
12827 NOTREACHED();
12828 return false;
12831 bool CanFindEndOfResponse() const override {
12832 return parser()->CanFindEndOfResponse();
12835 bool IsConnectionReused() const override {
12836 NOTREACHED();
12837 return false;
12839 void SetConnectionReused() override { NOTREACHED(); }
12841 bool IsConnectionReusable() const override {
12842 NOTREACHED();
12843 return false;
12846 int64 GetTotalReceivedBytes() const override {
12847 NOTREACHED();
12848 return 0;
12851 bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const override {
12852 NOTREACHED();
12853 return false;
12856 void GetSSLInfo(SSLInfo* ssl_info) override {}
12858 void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override {
12859 NOTREACHED();
12862 bool IsSpdyHttpStream() const override {
12863 NOTREACHED();
12864 return false;
12867 void Drain(HttpNetworkSession* session) override { NOTREACHED(); }
12869 void SetPriority(RequestPriority priority) override { NOTREACHED(); }
12871 UploadProgress GetUploadProgress() const override {
12872 NOTREACHED();
12873 return UploadProgress();
12876 HttpStream* RenewStreamForAuth() override {
12877 NOTREACHED();
12878 return nullptr;
12881 // Fake implementation of WebSocketHandshakeStreamBase method(s)
12882 scoped_ptr<WebSocketStream> Upgrade() override {
12883 NOTREACHED();
12884 return scoped_ptr<WebSocketStream>();
12887 private:
12888 HttpStreamParser* parser() const { return state_.parser(); }
12889 HttpBasicState state_;
12891 DISALLOW_COPY_AND_ASSIGN(FakeWebSocketBasicHandshakeStream);
12894 // TODO(yhirano): Split this class out into a net/websockets file, if it is
12895 // worth doing.
12896 class FakeWebSocketStreamCreateHelper :
12897 public WebSocketHandshakeStreamBase::CreateHelper {
12898 public:
12899 WebSocketHandshakeStreamBase* CreateBasicStream(
12900 scoped_ptr<ClientSocketHandle> connection,
12901 bool using_proxy) override {
12902 return new FakeWebSocketBasicHandshakeStream(connection.Pass(),
12903 using_proxy);
12906 WebSocketHandshakeStreamBase* CreateSpdyStream(
12907 const base::WeakPtr<SpdySession>& session,
12908 bool use_relative_url) override {
12909 NOTREACHED();
12910 return NULL;
12913 ~FakeWebSocketStreamCreateHelper() override {}
12915 virtual scoped_ptr<WebSocketStream> Upgrade() {
12916 NOTREACHED();
12917 return scoped_ptr<WebSocketStream>();
12921 } // namespace
12923 // Make sure that HttpNetworkTransaction passes on its priority to its
12924 // stream request on start.
12925 TEST_P(HttpNetworkTransactionTest, SetStreamRequestPriorityOnStart) {
12926 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12927 HttpNetworkSessionPeer peer(session);
12928 FakeStreamFactory* fake_factory = new FakeStreamFactory();
12929 peer.SetHttpStreamFactory(scoped_ptr<HttpStreamFactory>(fake_factory));
12931 HttpNetworkTransaction trans(LOW, session.get());
12933 ASSERT_TRUE(fake_factory->last_stream_request() == NULL);
12935 HttpRequestInfo request;
12936 TestCompletionCallback callback;
12937 EXPECT_EQ(ERR_IO_PENDING,
12938 trans.Start(&request, callback.callback(), BoundNetLog()));
12940 base::WeakPtr<FakeStreamRequest> fake_request =
12941 fake_factory->last_stream_request();
12942 ASSERT_TRUE(fake_request != NULL);
12943 EXPECT_EQ(LOW, fake_request->priority());
12946 // Make sure that HttpNetworkTransaction passes on its priority
12947 // updates to its stream request.
12948 TEST_P(HttpNetworkTransactionTest, SetStreamRequestPriority) {
12949 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12950 HttpNetworkSessionPeer peer(session);
12951 FakeStreamFactory* fake_factory = new FakeStreamFactory();
12952 peer.SetHttpStreamFactory(scoped_ptr<HttpStreamFactory>(fake_factory));
12954 HttpNetworkTransaction trans(LOW, session.get());
12956 HttpRequestInfo request;
12957 TestCompletionCallback callback;
12958 EXPECT_EQ(ERR_IO_PENDING,
12959 trans.Start(&request, callback.callback(), BoundNetLog()));
12961 base::WeakPtr<FakeStreamRequest> fake_request =
12962 fake_factory->last_stream_request();
12963 ASSERT_TRUE(fake_request != NULL);
12964 EXPECT_EQ(LOW, fake_request->priority());
12966 trans.SetPriority(LOWEST);
12967 ASSERT_TRUE(fake_request != NULL);
12968 EXPECT_EQ(LOWEST, fake_request->priority());
12971 // Make sure that HttpNetworkTransaction passes on its priority
12972 // updates to its stream.
12973 TEST_P(HttpNetworkTransactionTest, SetStreamPriority) {
12974 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12975 HttpNetworkSessionPeer peer(session);
12976 FakeStreamFactory* fake_factory = new FakeStreamFactory();
12977 peer.SetHttpStreamFactory(scoped_ptr<HttpStreamFactory>(fake_factory));
12979 HttpNetworkTransaction trans(LOW, session.get());
12981 HttpRequestInfo request;
12982 TestCompletionCallback callback;
12983 EXPECT_EQ(ERR_IO_PENDING,
12984 trans.Start(&request, callback.callback(), BoundNetLog()));
12986 base::WeakPtr<FakeStreamRequest> fake_request =
12987 fake_factory->last_stream_request();
12988 ASSERT_TRUE(fake_request != NULL);
12989 base::WeakPtr<FakeStream> fake_stream = fake_request->FinishStreamRequest();
12990 ASSERT_TRUE(fake_stream != NULL);
12991 EXPECT_EQ(LOW, fake_stream->priority());
12993 trans.SetPriority(LOWEST);
12994 EXPECT_EQ(LOWEST, fake_stream->priority());
12997 TEST_P(HttpNetworkTransactionTest, CreateWebSocketHandshakeStream) {
12998 // The same logic needs to be tested for both ws: and wss: schemes, but this
12999 // test is already parameterised on NextProto, so it uses a loop to verify
13000 // that the different schemes work.
13001 std::string test_cases[] = {"ws://www.google.com/", "wss://www.google.com/"};
13002 for (size_t i = 0; i < arraysize(test_cases); ++i) {
13003 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13004 HttpNetworkSessionPeer peer(session);
13005 FakeStreamFactory* fake_factory = new FakeStreamFactory();
13006 FakeWebSocketStreamCreateHelper websocket_stream_create_helper;
13007 peer.SetHttpStreamFactoryForWebSocket(
13008 scoped_ptr<HttpStreamFactory>(fake_factory));
13010 HttpNetworkTransaction trans(LOW, session.get());
13011 trans.SetWebSocketHandshakeStreamCreateHelper(
13012 &websocket_stream_create_helper);
13014 HttpRequestInfo request;
13015 TestCompletionCallback callback;
13016 request.method = "GET";
13017 request.url = GURL(test_cases[i]);
13019 EXPECT_EQ(ERR_IO_PENDING,
13020 trans.Start(&request, callback.callback(), BoundNetLog()));
13022 base::WeakPtr<FakeStreamRequest> fake_request =
13023 fake_factory->last_stream_request();
13024 ASSERT_TRUE(fake_request != NULL);
13025 EXPECT_EQ(&websocket_stream_create_helper,
13026 fake_request->websocket_stream_create_helper());
13030 // Tests that when a used socket is returned to the SSL socket pool, it's closed
13031 // if the transport socket pool is stalled on the global socket limit.
13032 TEST_P(HttpNetworkTransactionTest, CloseSSLSocketOnIdleForHttpRequest) {
13033 ClientSocketPoolManager::set_max_sockets_per_group(
13034 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
13035 ClientSocketPoolManager::set_max_sockets_per_pool(
13036 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
13038 // Set up SSL request.
13040 HttpRequestInfo ssl_request;
13041 ssl_request.method = "GET";
13042 ssl_request.url = GURL("https://www.google.com/");
13044 MockWrite ssl_writes[] = {
13045 MockWrite("GET / HTTP/1.1\r\n"
13046 "Host: www.google.com\r\n"
13047 "Connection: keep-alive\r\n\r\n"),
13049 MockRead ssl_reads[] = {
13050 MockRead("HTTP/1.1 200 OK\r\n"),
13051 MockRead("Content-Length: 11\r\n\r\n"),
13052 MockRead("hello world"),
13053 MockRead(SYNCHRONOUS, OK),
13055 StaticSocketDataProvider ssl_data(ssl_reads, arraysize(ssl_reads),
13056 ssl_writes, arraysize(ssl_writes));
13057 session_deps_.socket_factory->AddSocketDataProvider(&ssl_data);
13059 SSLSocketDataProvider ssl(ASYNC, OK);
13060 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
13062 // Set up HTTP request.
13064 HttpRequestInfo http_request;
13065 http_request.method = "GET";
13066 http_request.url = GURL("http://www.google.com/");
13068 MockWrite http_writes[] = {
13069 MockWrite("GET / HTTP/1.1\r\n"
13070 "Host: www.google.com\r\n"
13071 "Connection: keep-alive\r\n\r\n"),
13073 MockRead http_reads[] = {
13074 MockRead("HTTP/1.1 200 OK\r\n"),
13075 MockRead("Content-Length: 7\r\n\r\n"),
13076 MockRead("falafel"),
13077 MockRead(SYNCHRONOUS, OK),
13079 StaticSocketDataProvider http_data(http_reads, arraysize(http_reads),
13080 http_writes, arraysize(http_writes));
13081 session_deps_.socket_factory->AddSocketDataProvider(&http_data);
13083 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13085 // Start the SSL request.
13086 TestCompletionCallback ssl_callback;
13087 scoped_ptr<HttpTransaction> ssl_trans(
13088 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13089 ASSERT_EQ(ERR_IO_PENDING,
13090 ssl_trans->Start(&ssl_request, ssl_callback.callback(),
13091 BoundNetLog()));
13093 // Start the HTTP request. Pool should stall.
13094 TestCompletionCallback http_callback;
13095 scoped_ptr<HttpTransaction> http_trans(
13096 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13097 ASSERT_EQ(ERR_IO_PENDING,
13098 http_trans->Start(&http_request, http_callback.callback(),
13099 BoundNetLog()));
13100 EXPECT_TRUE(IsTransportSocketPoolStalled(session.get()));
13102 // Wait for response from SSL request.
13103 ASSERT_EQ(OK, ssl_callback.WaitForResult());
13104 std::string response_data;
13105 ASSERT_EQ(OK, ReadTransaction(ssl_trans.get(), &response_data));
13106 EXPECT_EQ("hello world", response_data);
13108 // The SSL socket should automatically be closed, so the HTTP request can
13109 // start.
13110 EXPECT_EQ(0, GetIdleSocketCountInSSLSocketPool(session.get()));
13111 ASSERT_FALSE(IsTransportSocketPoolStalled(session.get()));
13113 // The HTTP request can now complete.
13114 ASSERT_EQ(OK, http_callback.WaitForResult());
13115 ASSERT_EQ(OK, ReadTransaction(http_trans.get(), &response_data));
13116 EXPECT_EQ("falafel", response_data);
13118 EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
13121 // Tests that when a SSL connection is established but there's no corresponding
13122 // request that needs it, the new socket is closed if the transport socket pool
13123 // is stalled on the global socket limit.
13124 TEST_P(HttpNetworkTransactionTest, CloseSSLSocketOnIdleForHttpRequest2) {
13125 ClientSocketPoolManager::set_max_sockets_per_group(
13126 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
13127 ClientSocketPoolManager::set_max_sockets_per_pool(
13128 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
13130 // Set up an ssl request.
13132 HttpRequestInfo ssl_request;
13133 ssl_request.method = "GET";
13134 ssl_request.url = GURL("https://www.foopy.com/");
13136 // No data will be sent on the SSL socket.
13137 StaticSocketDataProvider ssl_data;
13138 session_deps_.socket_factory->AddSocketDataProvider(&ssl_data);
13140 SSLSocketDataProvider ssl(ASYNC, OK);
13141 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
13143 // Set up HTTP request.
13145 HttpRequestInfo http_request;
13146 http_request.method = "GET";
13147 http_request.url = GURL("http://www.google.com/");
13149 MockWrite http_writes[] = {
13150 MockWrite("GET / HTTP/1.1\r\n"
13151 "Host: www.google.com\r\n"
13152 "Connection: keep-alive\r\n\r\n"),
13154 MockRead http_reads[] = {
13155 MockRead("HTTP/1.1 200 OK\r\n"),
13156 MockRead("Content-Length: 7\r\n\r\n"),
13157 MockRead("falafel"),
13158 MockRead(SYNCHRONOUS, OK),
13160 StaticSocketDataProvider http_data(http_reads, arraysize(http_reads),
13161 http_writes, arraysize(http_writes));
13162 session_deps_.socket_factory->AddSocketDataProvider(&http_data);
13164 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13166 // Preconnect an SSL socket. A preconnect is needed because connect jobs are
13167 // cancelled when a normal transaction is cancelled.
13168 net::HttpStreamFactory* http_stream_factory = session->http_stream_factory();
13169 net::SSLConfig ssl_config;
13170 session->ssl_config_service()->GetSSLConfig(&ssl_config);
13171 http_stream_factory->PreconnectStreams(1, ssl_request, DEFAULT_PRIORITY,
13172 ssl_config, ssl_config);
13173 EXPECT_EQ(0, GetIdleSocketCountInSSLSocketPool(session.get()));
13175 // Start the HTTP request. Pool should stall.
13176 TestCompletionCallback http_callback;
13177 scoped_ptr<HttpTransaction> http_trans(
13178 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13179 ASSERT_EQ(ERR_IO_PENDING,
13180 http_trans->Start(&http_request, http_callback.callback(),
13181 BoundNetLog()));
13182 EXPECT_TRUE(IsTransportSocketPoolStalled(session.get()));
13184 // The SSL connection will automatically be closed once the connection is
13185 // established, to let the HTTP request start.
13186 ASSERT_EQ(OK, http_callback.WaitForResult());
13187 std::string response_data;
13188 ASSERT_EQ(OK, ReadTransaction(http_trans.get(), &response_data));
13189 EXPECT_EQ("falafel", response_data);
13191 EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
13194 TEST_P(HttpNetworkTransactionTest, PostReadsErrorResponseAfterReset) {
13195 ScopedVector<UploadElementReader> element_readers;
13196 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13197 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
13199 HttpRequestInfo request;
13200 request.method = "POST";
13201 request.url = GURL("http://www.foo.com/");
13202 request.upload_data_stream = &upload_data_stream;
13203 request.load_flags = 0;
13205 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13206 scoped_ptr<HttpTransaction> trans(
13207 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13208 // Send headers successfully, but get an error while sending the body.
13209 MockWrite data_writes[] = {
13210 MockWrite("POST / HTTP/1.1\r\n"
13211 "Host: www.foo.com\r\n"
13212 "Connection: keep-alive\r\n"
13213 "Content-Length: 3\r\n\r\n"),
13214 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13217 MockRead data_reads[] = {
13218 MockRead("HTTP/1.0 400 Not OK\r\n\r\n"),
13219 MockRead("hello world"),
13220 MockRead(SYNCHRONOUS, OK),
13222 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13223 arraysize(data_writes));
13224 session_deps_.socket_factory->AddSocketDataProvider(&data);
13226 TestCompletionCallback callback;
13228 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13229 EXPECT_EQ(ERR_IO_PENDING, rv);
13231 rv = callback.WaitForResult();
13232 EXPECT_EQ(OK, rv);
13234 const HttpResponseInfo* response = trans->GetResponseInfo();
13235 ASSERT_TRUE(response != NULL);
13237 EXPECT_TRUE(response->headers.get() != NULL);
13238 EXPECT_EQ("HTTP/1.0 400 Not OK", response->headers->GetStatusLine());
13240 std::string response_data;
13241 rv = ReadTransaction(trans.get(), &response_data);
13242 EXPECT_EQ(OK, rv);
13243 EXPECT_EQ("hello world", response_data);
13246 // This test makes sure the retry logic doesn't trigger when reading an error
13247 // response from a server that rejected a POST with a CONNECTION_RESET.
13248 TEST_P(HttpNetworkTransactionTest,
13249 PostReadsErrorResponseAfterResetOnReusedSocket) {
13250 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13251 MockWrite data_writes[] = {
13252 MockWrite("GET / HTTP/1.1\r\n"
13253 "Host: www.foo.com\r\n"
13254 "Connection: keep-alive\r\n\r\n"),
13255 MockWrite("POST / HTTP/1.1\r\n"
13256 "Host: www.foo.com\r\n"
13257 "Connection: keep-alive\r\n"
13258 "Content-Length: 3\r\n\r\n"),
13259 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13262 MockRead data_reads[] = {
13263 MockRead("HTTP/1.1 200 Peachy\r\n"
13264 "Content-Length: 14\r\n\r\n"),
13265 MockRead("first response"),
13266 MockRead("HTTP/1.1 400 Not OK\r\n"
13267 "Content-Length: 15\r\n\r\n"),
13268 MockRead("second response"),
13269 MockRead(SYNCHRONOUS, OK),
13271 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13272 arraysize(data_writes));
13273 session_deps_.socket_factory->AddSocketDataProvider(&data);
13275 TestCompletionCallback callback;
13276 HttpRequestInfo request1;
13277 request1.method = "GET";
13278 request1.url = GURL("http://www.foo.com/");
13279 request1.load_flags = 0;
13281 scoped_ptr<HttpTransaction> trans1(
13282 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13283 int rv = trans1->Start(&request1, callback.callback(), BoundNetLog());
13284 EXPECT_EQ(ERR_IO_PENDING, rv);
13286 rv = callback.WaitForResult();
13287 EXPECT_EQ(OK, rv);
13289 const HttpResponseInfo* response1 = trans1->GetResponseInfo();
13290 ASSERT_TRUE(response1 != NULL);
13292 EXPECT_TRUE(response1->headers.get() != NULL);
13293 EXPECT_EQ("HTTP/1.1 200 Peachy", response1->headers->GetStatusLine());
13295 std::string response_data1;
13296 rv = ReadTransaction(trans1.get(), &response_data1);
13297 EXPECT_EQ(OK, rv);
13298 EXPECT_EQ("first response", response_data1);
13299 // Delete the transaction to release the socket back into the socket pool.
13300 trans1.reset();
13302 ScopedVector<UploadElementReader> element_readers;
13303 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13304 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
13306 HttpRequestInfo request2;
13307 request2.method = "POST";
13308 request2.url = GURL("http://www.foo.com/");
13309 request2.upload_data_stream = &upload_data_stream;
13310 request2.load_flags = 0;
13312 scoped_ptr<HttpTransaction> trans2(
13313 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13314 rv = trans2->Start(&request2, callback.callback(), BoundNetLog());
13315 EXPECT_EQ(ERR_IO_PENDING, rv);
13317 rv = callback.WaitForResult();
13318 EXPECT_EQ(OK, rv);
13320 const HttpResponseInfo* response2 = trans2->GetResponseInfo();
13321 ASSERT_TRUE(response2 != NULL);
13323 EXPECT_TRUE(response2->headers.get() != NULL);
13324 EXPECT_EQ("HTTP/1.1 400 Not OK", response2->headers->GetStatusLine());
13326 std::string response_data2;
13327 rv = ReadTransaction(trans2.get(), &response_data2);
13328 EXPECT_EQ(OK, rv);
13329 EXPECT_EQ("second response", response_data2);
13332 TEST_P(HttpNetworkTransactionTest,
13333 PostReadsErrorResponseAfterResetPartialBodySent) {
13334 ScopedVector<UploadElementReader> element_readers;
13335 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13336 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
13338 HttpRequestInfo request;
13339 request.method = "POST";
13340 request.url = GURL("http://www.foo.com/");
13341 request.upload_data_stream = &upload_data_stream;
13342 request.load_flags = 0;
13344 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13345 scoped_ptr<HttpTransaction> trans(
13346 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13347 // Send headers successfully, but get an error while sending the body.
13348 MockWrite data_writes[] = {
13349 MockWrite("POST / HTTP/1.1\r\n"
13350 "Host: www.foo.com\r\n"
13351 "Connection: keep-alive\r\n"
13352 "Content-Length: 3\r\n\r\n"
13353 "fo"),
13354 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13357 MockRead data_reads[] = {
13358 MockRead("HTTP/1.0 400 Not OK\r\n\r\n"),
13359 MockRead("hello world"),
13360 MockRead(SYNCHRONOUS, OK),
13362 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13363 arraysize(data_writes));
13364 session_deps_.socket_factory->AddSocketDataProvider(&data);
13366 TestCompletionCallback callback;
13368 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13369 EXPECT_EQ(ERR_IO_PENDING, rv);
13371 rv = callback.WaitForResult();
13372 EXPECT_EQ(OK, rv);
13374 const HttpResponseInfo* response = trans->GetResponseInfo();
13375 ASSERT_TRUE(response != NULL);
13377 EXPECT_TRUE(response->headers.get() != NULL);
13378 EXPECT_EQ("HTTP/1.0 400 Not OK", response->headers->GetStatusLine());
13380 std::string response_data;
13381 rv = ReadTransaction(trans.get(), &response_data);
13382 EXPECT_EQ(OK, rv);
13383 EXPECT_EQ("hello world", response_data);
13386 // This tests the more common case than the previous test, where headers and
13387 // body are not merged into a single request.
13388 TEST_P(HttpNetworkTransactionTest, ChunkedPostReadsErrorResponseAfterReset) {
13389 ScopedVector<UploadElementReader> element_readers;
13390 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13391 ChunkedUploadDataStream upload_data_stream(0);
13393 HttpRequestInfo request;
13394 request.method = "POST";
13395 request.url = GURL("http://www.foo.com/");
13396 request.upload_data_stream = &upload_data_stream;
13397 request.load_flags = 0;
13399 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13400 scoped_ptr<HttpTransaction> trans(
13401 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13402 // Send headers successfully, but get an error while sending the body.
13403 MockWrite data_writes[] = {
13404 MockWrite("POST / HTTP/1.1\r\n"
13405 "Host: www.foo.com\r\n"
13406 "Connection: keep-alive\r\n"
13407 "Transfer-Encoding: chunked\r\n\r\n"),
13408 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13411 MockRead data_reads[] = {
13412 MockRead("HTTP/1.0 400 Not OK\r\n\r\n"),
13413 MockRead("hello world"),
13414 MockRead(SYNCHRONOUS, OK),
13416 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13417 arraysize(data_writes));
13418 session_deps_.socket_factory->AddSocketDataProvider(&data);
13420 TestCompletionCallback callback;
13422 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13423 EXPECT_EQ(ERR_IO_PENDING, rv);
13424 // Make sure the headers are sent before adding a chunk. This ensures that
13425 // they can't be merged with the body in a single send. Not currently
13426 // necessary since a chunked body is never merged with headers, but this makes
13427 // the test more future proof.
13428 base::RunLoop().RunUntilIdle();
13430 upload_data_stream.AppendData("last chunk", 10, true);
13432 rv = callback.WaitForResult();
13433 EXPECT_EQ(OK, rv);
13435 const HttpResponseInfo* response = trans->GetResponseInfo();
13436 ASSERT_TRUE(response != NULL);
13438 EXPECT_TRUE(response->headers.get() != NULL);
13439 EXPECT_EQ("HTTP/1.0 400 Not OK", response->headers->GetStatusLine());
13441 std::string response_data;
13442 rv = ReadTransaction(trans.get(), &response_data);
13443 EXPECT_EQ(OK, rv);
13444 EXPECT_EQ("hello world", response_data);
13447 TEST_P(HttpNetworkTransactionTest, PostReadsErrorResponseAfterResetAnd100) {
13448 ScopedVector<UploadElementReader> element_readers;
13449 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13450 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
13452 HttpRequestInfo request;
13453 request.method = "POST";
13454 request.url = GURL("http://www.foo.com/");
13455 request.upload_data_stream = &upload_data_stream;
13456 request.load_flags = 0;
13458 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13459 scoped_ptr<HttpTransaction> trans(
13460 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13462 MockWrite data_writes[] = {
13463 MockWrite("POST / HTTP/1.1\r\n"
13464 "Host: www.foo.com\r\n"
13465 "Connection: keep-alive\r\n"
13466 "Content-Length: 3\r\n\r\n"),
13467 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13470 MockRead data_reads[] = {
13471 MockRead("HTTP/1.0 100 Continue\r\n\r\n"),
13472 MockRead("HTTP/1.0 400 Not OK\r\n\r\n"),
13473 MockRead("hello world"),
13474 MockRead(SYNCHRONOUS, OK),
13476 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13477 arraysize(data_writes));
13478 session_deps_.socket_factory->AddSocketDataProvider(&data);
13480 TestCompletionCallback callback;
13482 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13483 EXPECT_EQ(ERR_IO_PENDING, rv);
13485 rv = callback.WaitForResult();
13486 EXPECT_EQ(OK, rv);
13488 const HttpResponseInfo* response = trans->GetResponseInfo();
13489 ASSERT_TRUE(response != NULL);
13491 EXPECT_TRUE(response->headers.get() != NULL);
13492 EXPECT_EQ("HTTP/1.0 400 Not OK", response->headers->GetStatusLine());
13494 std::string response_data;
13495 rv = ReadTransaction(trans.get(), &response_data);
13496 EXPECT_EQ(OK, rv);
13497 EXPECT_EQ("hello world", response_data);
13500 TEST_P(HttpNetworkTransactionTest, PostIgnoresNonErrorResponseAfterReset) {
13501 ScopedVector<UploadElementReader> element_readers;
13502 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13503 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
13505 HttpRequestInfo request;
13506 request.method = "POST";
13507 request.url = GURL("http://www.foo.com/");
13508 request.upload_data_stream = &upload_data_stream;
13509 request.load_flags = 0;
13511 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13512 scoped_ptr<HttpTransaction> trans(
13513 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13514 // Send headers successfully, but get an error while sending the body.
13515 MockWrite data_writes[] = {
13516 MockWrite("POST / HTTP/1.1\r\n"
13517 "Host: www.foo.com\r\n"
13518 "Connection: keep-alive\r\n"
13519 "Content-Length: 3\r\n\r\n"),
13520 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13523 MockRead data_reads[] = {
13524 MockRead("HTTP/1.0 200 Just Dandy\r\n\r\n"),
13525 MockRead("hello world"),
13526 MockRead(SYNCHRONOUS, OK),
13528 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13529 arraysize(data_writes));
13530 session_deps_.socket_factory->AddSocketDataProvider(&data);
13532 TestCompletionCallback callback;
13534 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13535 EXPECT_EQ(ERR_IO_PENDING, rv);
13537 rv = callback.WaitForResult();
13538 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
13540 const HttpResponseInfo* response = trans->GetResponseInfo();
13541 EXPECT_TRUE(response == NULL);
13544 TEST_P(HttpNetworkTransactionTest,
13545 PostIgnoresNonErrorResponseAfterResetAnd100) {
13546 ScopedVector<UploadElementReader> element_readers;
13547 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13548 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
13550 HttpRequestInfo request;
13551 request.method = "POST";
13552 request.url = GURL("http://www.foo.com/");
13553 request.upload_data_stream = &upload_data_stream;
13554 request.load_flags = 0;
13556 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13557 scoped_ptr<HttpTransaction> trans(
13558 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13559 // Send headers successfully, but get an error while sending the body.
13560 MockWrite data_writes[] = {
13561 MockWrite("POST / HTTP/1.1\r\n"
13562 "Host: www.foo.com\r\n"
13563 "Connection: keep-alive\r\n"
13564 "Content-Length: 3\r\n\r\n"),
13565 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13568 MockRead data_reads[] = {
13569 MockRead("HTTP/1.0 100 Continue\r\n\r\n"),
13570 MockRead("HTTP/1.0 302 Redirect\r\n"),
13571 MockRead("Location: http://somewhere-else.com/\r\n"),
13572 MockRead("Content-Length: 0\r\n\r\n"),
13573 MockRead(SYNCHRONOUS, OK),
13575 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13576 arraysize(data_writes));
13577 session_deps_.socket_factory->AddSocketDataProvider(&data);
13579 TestCompletionCallback callback;
13581 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13582 EXPECT_EQ(ERR_IO_PENDING, rv);
13584 rv = callback.WaitForResult();
13585 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
13587 const HttpResponseInfo* response = trans->GetResponseInfo();
13588 EXPECT_TRUE(response == NULL);
13591 TEST_P(HttpNetworkTransactionTest, PostIgnoresHttp09ResponseAfterReset) {
13592 ScopedVector<UploadElementReader> element_readers;
13593 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13594 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
13596 HttpRequestInfo request;
13597 request.method = "POST";
13598 request.url = GURL("http://www.foo.com/");
13599 request.upload_data_stream = &upload_data_stream;
13600 request.load_flags = 0;
13602 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13603 scoped_ptr<HttpTransaction> trans(
13604 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13605 // Send headers successfully, but get an error while sending the body.
13606 MockWrite data_writes[] = {
13607 MockWrite("POST / HTTP/1.1\r\n"
13608 "Host: www.foo.com\r\n"
13609 "Connection: keep-alive\r\n"
13610 "Content-Length: 3\r\n\r\n"),
13611 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13614 MockRead data_reads[] = {
13615 MockRead("HTTP 0.9 rocks!"),
13616 MockRead(SYNCHRONOUS, OK),
13618 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13619 arraysize(data_writes));
13620 session_deps_.socket_factory->AddSocketDataProvider(&data);
13622 TestCompletionCallback callback;
13624 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13625 EXPECT_EQ(ERR_IO_PENDING, rv);
13627 rv = callback.WaitForResult();
13628 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
13630 const HttpResponseInfo* response = trans->GetResponseInfo();
13631 EXPECT_TRUE(response == NULL);
13634 TEST_P(HttpNetworkTransactionTest, PostIgnoresPartial400HeadersAfterReset) {
13635 ScopedVector<UploadElementReader> element_readers;
13636 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13637 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
13639 HttpRequestInfo request;
13640 request.method = "POST";
13641 request.url = GURL("http://www.foo.com/");
13642 request.upload_data_stream = &upload_data_stream;
13643 request.load_flags = 0;
13645 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13646 scoped_ptr<HttpTransaction> trans(
13647 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13648 // Send headers successfully, but get an error while sending the body.
13649 MockWrite data_writes[] = {
13650 MockWrite("POST / HTTP/1.1\r\n"
13651 "Host: www.foo.com\r\n"
13652 "Connection: keep-alive\r\n"
13653 "Content-Length: 3\r\n\r\n"),
13654 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13657 MockRead data_reads[] = {
13658 MockRead("HTTP/1.0 400 Not a Full Response\r\n"),
13659 MockRead(SYNCHRONOUS, OK),
13661 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13662 arraysize(data_writes));
13663 session_deps_.socket_factory->AddSocketDataProvider(&data);
13665 TestCompletionCallback callback;
13667 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13668 EXPECT_EQ(ERR_IO_PENDING, rv);
13670 rv = callback.WaitForResult();
13671 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
13673 const HttpResponseInfo* response = trans->GetResponseInfo();
13674 EXPECT_TRUE(response == NULL);
13677 // Verify that proxy headers are not sent to the destination server when
13678 // establishing a tunnel for a secure WebSocket connection.
13679 TEST_P(HttpNetworkTransactionTest, ProxyHeadersNotSentOverWssTunnel) {
13680 HttpRequestInfo request;
13681 request.method = "GET";
13682 request.url = GURL("wss://www.google.com/");
13683 AddWebSocketHeaders(&request.extra_headers);
13685 // Configure against proxy server "myproxy:70".
13686 session_deps_.proxy_service.reset(
13687 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
13689 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13691 // Since a proxy is configured, try to establish a tunnel.
13692 MockWrite data_writes[] = {
13693 MockWrite(
13694 "CONNECT www.google.com:443 HTTP/1.1\r\n"
13695 "Host: www.google.com\r\n"
13696 "Proxy-Connection: keep-alive\r\n\r\n"),
13698 // After calling trans->RestartWithAuth(), this is the request we should
13699 // be issuing -- the final header line contains the credentials.
13700 MockWrite(
13701 "CONNECT www.google.com:443 HTTP/1.1\r\n"
13702 "Host: www.google.com\r\n"
13703 "Proxy-Connection: keep-alive\r\n"
13704 "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
13706 MockWrite(
13707 "GET / HTTP/1.1\r\n"
13708 "Host: www.google.com\r\n"
13709 "Connection: Upgrade\r\n"
13710 "Upgrade: websocket\r\n"
13711 "Origin: http://www.google.com\r\n"
13712 "Sec-WebSocket-Version: 13\r\n"
13713 "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n"),
13716 // The proxy responds to the connect with a 407, using a persistent
13717 // connection.
13718 MockRead data_reads[] = {
13719 // No credentials.
13720 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
13721 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
13722 MockRead("Proxy-Connection: close\r\n\r\n"),
13724 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
13726 MockRead("HTTP/1.1 101 Switching Protocols\r\n"),
13727 MockRead("Upgrade: websocket\r\n"),
13728 MockRead("Connection: Upgrade\r\n"),
13729 MockRead("Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n"),
13732 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13733 arraysize(data_writes));
13734 session_deps_.socket_factory->AddSocketDataProvider(&data);
13735 SSLSocketDataProvider ssl(ASYNC, OK);
13736 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
13738 scoped_ptr<HttpTransaction> trans(
13739 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13740 FakeWebSocketStreamCreateHelper websocket_stream_create_helper;
13741 trans->SetWebSocketHandshakeStreamCreateHelper(
13742 &websocket_stream_create_helper);
13745 TestCompletionCallback callback;
13747 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13748 EXPECT_EQ(ERR_IO_PENDING, rv);
13750 rv = callback.WaitForResult();
13751 EXPECT_EQ(OK, rv);
13754 const HttpResponseInfo* response = trans->GetResponseInfo();
13755 ASSERT_TRUE(response);
13756 ASSERT_TRUE(response->headers.get());
13757 EXPECT_EQ(407, response->headers->response_code());
13760 TestCompletionCallback callback;
13762 int rv = trans->RestartWithAuth(AuthCredentials(kFoo, kBar),
13763 callback.callback());
13764 EXPECT_EQ(ERR_IO_PENDING, rv);
13766 rv = callback.WaitForResult();
13767 EXPECT_EQ(OK, rv);
13770 response = trans->GetResponseInfo();
13771 ASSERT_TRUE(response);
13772 ASSERT_TRUE(response->headers.get());
13774 EXPECT_EQ(101, response->headers->response_code());
13776 trans.reset();
13777 session->CloseAllConnections();
13780 // Verify that proxy headers are not sent to the destination server when
13781 // establishing a tunnel for an insecure WebSocket connection.
13782 // This requires the authentication info to be injected into the auth cache
13783 // due to crbug.com/395064
13784 // TODO(ricea): Change to use a 407 response once issue 395064 is fixed.
13785 TEST_P(HttpNetworkTransactionTest, ProxyHeadersNotSentOverWsTunnel) {
13786 HttpRequestInfo request;
13787 request.method = "GET";
13788 request.url = GURL("ws://www.google.com/");
13789 AddWebSocketHeaders(&request.extra_headers);
13791 // Configure against proxy server "myproxy:70".
13792 session_deps_.proxy_service.reset(
13793 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
13795 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13797 MockWrite data_writes[] = {
13798 // Try to establish a tunnel for the WebSocket connection, with
13799 // credentials. Because WebSockets have a separate set of socket pools,
13800 // they cannot and will not use the same TCP/IP connection as the
13801 // preflight HTTP request.
13802 MockWrite(
13803 "CONNECT www.google.com:80 HTTP/1.1\r\n"
13804 "Host: www.google.com\r\n"
13805 "Proxy-Connection: keep-alive\r\n"
13806 "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
13808 MockWrite(
13809 "GET / HTTP/1.1\r\n"
13810 "Host: www.google.com\r\n"
13811 "Connection: Upgrade\r\n"
13812 "Upgrade: websocket\r\n"
13813 "Origin: http://www.google.com\r\n"
13814 "Sec-WebSocket-Version: 13\r\n"
13815 "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n"),
13818 MockRead data_reads[] = {
13819 // HTTP CONNECT with credentials.
13820 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
13822 // WebSocket connection established inside tunnel.
13823 MockRead("HTTP/1.1 101 Switching Protocols\r\n"),
13824 MockRead("Upgrade: websocket\r\n"),
13825 MockRead("Connection: Upgrade\r\n"),
13826 MockRead("Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n"),
13829 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13830 arraysize(data_writes));
13831 session_deps_.socket_factory->AddSocketDataProvider(&data);
13833 session->http_auth_cache()->Add(
13834 GURL("http://myproxy:70/"), "MyRealm1", HttpAuth::AUTH_SCHEME_BASIC,
13835 "Basic realm=MyRealm1", AuthCredentials(kFoo, kBar), "/");
13837 scoped_ptr<HttpTransaction> trans(
13838 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13839 FakeWebSocketStreamCreateHelper websocket_stream_create_helper;
13840 trans->SetWebSocketHandshakeStreamCreateHelper(
13841 &websocket_stream_create_helper);
13843 TestCompletionCallback callback;
13845 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13846 EXPECT_EQ(ERR_IO_PENDING, rv);
13848 rv = callback.WaitForResult();
13849 EXPECT_EQ(OK, rv);
13851 const HttpResponseInfo* response = trans->GetResponseInfo();
13852 ASSERT_TRUE(response);
13853 ASSERT_TRUE(response->headers.get());
13855 EXPECT_EQ(101, response->headers->response_code());
13857 trans.reset();
13858 session->CloseAllConnections();
13861 } // namespace net