Implemented UriBeacon decoder.
[chromium-blink-merge.git] / net / http / http_network_transaction_unittest.cc
bloba3a96c44b0ad6123adc544ebd0f40bcca4de9832
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, NULL, host_resolver, NULL, NULL) {}
579 template <>
580 CaptureGroupNameHttpProxySocketPool::CaptureGroupNameSocketPool(
581 HostResolver* /* host_resolver */,
582 CertVerifier* /* cert_verifier */)
583 : HttpProxyClientSocketPool(0, 0, NULL, NULL, NULL, NULL) {
586 template <>
587 CaptureGroupNameSSLSocketPool::CaptureGroupNameSocketPool(
588 HostResolver* /* host_resolver */,
589 CertVerifier* cert_verifier)
590 : SSLClientSocketPool(0,
592 NULL,
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), "alternative.host", 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 ClientSocketPoolHistograms transport_pool_histograms("SmallTCP");
10169 TransportClientSocketPool* transport_pool = new TransportClientSocketPool(
10170 50, // Max sockets for pool
10171 1, // Max sockets per group
10172 &transport_pool_histograms,
10173 session_deps_.host_resolver.get(),
10174 session_deps_.socket_factory.get(),
10175 session_deps_.net_log);
10176 scoped_ptr<MockClientSocketPoolManager> mock_pool_manager(
10177 new MockClientSocketPoolManager);
10178 mock_pool_manager->SetTransportSocketPool(transport_pool);
10179 session_peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
10181 scoped_ptr<HttpTransaction> trans(
10182 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10183 TestCompletionCallback callback;
10185 const MockWrite kGet(
10186 "GET / HTTP/1.1\r\n"
10187 "Host: www.example.com\r\n"
10188 "Connection: keep-alive\r\n\r\n");
10189 const MockWrite kGetAuth(
10190 "GET / HTTP/1.1\r\n"
10191 "Host: www.example.com\r\n"
10192 "Connection: keep-alive\r\n"
10193 "Authorization: auth_token\r\n\r\n");
10195 const MockRead kServerChallenge(
10196 "HTTP/1.1 401 Unauthorized\r\n"
10197 "WWW-Authenticate: Mock realm=server\r\n"
10198 "Content-Type: text/html; charset=iso-8859-1\r\n"
10199 "Content-Length: 14\r\n\r\n"
10200 "Unauthorized\r\n");
10201 const MockRead kSuccess(
10202 "HTTP/1.1 200 OK\r\n"
10203 "Content-Type: text/html; charset=iso-8859-1\r\n"
10204 "Content-Length: 3\r\n\r\n"
10205 "Yes");
10207 MockWrite writes[] = {
10208 // First round
10209 kGet,
10210 // Second round
10211 kGetAuth,
10212 // Third round
10213 kGetAuth,
10214 // Fourth round
10215 kGetAuth,
10216 // Competing request
10217 kGet,
10219 MockRead reads[] = {
10220 // First round
10221 kServerChallenge,
10222 // Second round
10223 kServerChallenge,
10224 // Third round
10225 kServerChallenge,
10226 // Fourth round
10227 kSuccess,
10228 // Competing response
10229 kSuccess,
10231 StaticSocketDataProvider data_provider(reads, arraysize(reads),
10232 writes, arraysize(writes));
10233 session_deps_.socket_factory->AddSocketDataProvider(&data_provider);
10235 const char kSocketGroup[] = "www.example.com:80";
10237 // First round of authentication.
10238 auth_handler->SetGenerateExpectation(false, OK);
10239 rv = trans->Start(&request, callback.callback(), BoundNetLog());
10240 if (rv == ERR_IO_PENDING)
10241 rv = callback.WaitForResult();
10242 EXPECT_EQ(OK, rv);
10243 response = trans->GetResponseInfo();
10244 ASSERT_TRUE(response != NULL);
10245 EXPECT_FALSE(response->auth_challenge.get() == NULL);
10246 EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10248 // In between rounds, another request comes in for the same domain.
10249 // It should not be able to grab the TCP socket that trans has already
10250 // claimed.
10251 scoped_ptr<HttpTransaction> trans_compete(
10252 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10253 TestCompletionCallback callback_compete;
10254 rv = trans_compete->Start(
10255 &request, callback_compete.callback(), BoundNetLog());
10256 EXPECT_EQ(ERR_IO_PENDING, rv);
10257 // callback_compete.WaitForResult at this point would stall forever,
10258 // since the HttpNetworkTransaction does not release the request back to
10259 // the pool until after authentication completes.
10261 // Second round of authentication.
10262 auth_handler->SetGenerateExpectation(false, OK);
10263 rv = trans->RestartWithAuth(AuthCredentials(kFoo, kBar), callback.callback());
10264 if (rv == ERR_IO_PENDING)
10265 rv = callback.WaitForResult();
10266 EXPECT_EQ(OK, rv);
10267 response = trans->GetResponseInfo();
10268 ASSERT_TRUE(response != NULL);
10269 EXPECT_TRUE(response->auth_challenge.get() == NULL);
10270 EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10272 // Third round of authentication.
10273 auth_handler->SetGenerateExpectation(false, OK);
10274 rv = trans->RestartWithAuth(AuthCredentials(), callback.callback());
10275 if (rv == ERR_IO_PENDING)
10276 rv = callback.WaitForResult();
10277 EXPECT_EQ(OK, rv);
10278 response = trans->GetResponseInfo();
10279 ASSERT_TRUE(response != NULL);
10280 EXPECT_TRUE(response->auth_challenge.get() == NULL);
10281 EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10283 // Fourth round of authentication, which completes successfully.
10284 auth_handler->SetGenerateExpectation(false, OK);
10285 rv = trans->RestartWithAuth(AuthCredentials(), callback.callback());
10286 if (rv == ERR_IO_PENDING)
10287 rv = callback.WaitForResult();
10288 EXPECT_EQ(OK, rv);
10289 response = trans->GetResponseInfo();
10290 ASSERT_TRUE(response != NULL);
10291 EXPECT_TRUE(response->auth_challenge.get() == NULL);
10292 EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10294 // Read the body since the fourth round was successful. This will also
10295 // release the socket back to the pool.
10296 scoped_refptr<IOBufferWithSize> io_buf(new IOBufferWithSize(50));
10297 rv = trans->Read(io_buf.get(), io_buf->size(), callback.callback());
10298 if (rv == ERR_IO_PENDING)
10299 rv = callback.WaitForResult();
10300 EXPECT_EQ(3, rv);
10301 rv = trans->Read(io_buf.get(), io_buf->size(), callback.callback());
10302 EXPECT_EQ(0, rv);
10303 // There are still 0 idle sockets, since the trans_compete transaction
10304 // will be handed it immediately after trans releases it to the group.
10305 EXPECT_EQ(0, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10307 // The competing request can now finish. Wait for the headers and then
10308 // read the body.
10309 rv = callback_compete.WaitForResult();
10310 EXPECT_EQ(OK, rv);
10311 rv = trans_compete->Read(io_buf.get(), io_buf->size(), callback.callback());
10312 if (rv == ERR_IO_PENDING)
10313 rv = callback.WaitForResult();
10314 EXPECT_EQ(3, rv);
10315 rv = trans_compete->Read(io_buf.get(), io_buf->size(), callback.callback());
10316 EXPECT_EQ(0, rv);
10318 // Finally, the socket is released to the group.
10319 EXPECT_EQ(1, transport_pool->IdleSocketCountInGroup(kSocketGroup));
10322 // This tests the case that a request is issued via http instead of spdy after
10323 // npn is negotiated.
10324 TEST_P(HttpNetworkTransactionTest, NpnWithHttpOverSSL) {
10325 session_deps_.use_alternate_protocols = true;
10326 NextProtoVector next_protos;
10327 next_protos.push_back(kProtoHTTP11);
10328 session_deps_.next_protos = next_protos;
10330 HttpRequestInfo request;
10331 request.method = "GET";
10332 request.url = GURL("https://www.google.com/");
10333 request.load_flags = 0;
10335 MockWrite data_writes[] = {
10336 MockWrite("GET / HTTP/1.1\r\n"
10337 "Host: www.google.com\r\n"
10338 "Connection: keep-alive\r\n\r\n"),
10341 std::string alternate_protocol_http_header =
10342 GetAlternateProtocolHttpHeader();
10344 MockRead data_reads[] = {
10345 MockRead("HTTP/1.1 200 OK\r\n"),
10346 MockRead(alternate_protocol_http_header.c_str()),
10347 MockRead("hello world"),
10348 MockRead(SYNCHRONOUS, OK),
10351 SSLSocketDataProvider ssl(ASYNC, OK);
10352 ssl.next_proto_status = SSLClientSocket::kNextProtoNegotiated;
10353 ssl.next_proto = "http/1.1";
10354 ssl.protocol_negotiated = kProtoHTTP11;
10356 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
10358 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
10359 data_writes, arraysize(data_writes));
10360 session_deps_.socket_factory->AddSocketDataProvider(&data);
10362 TestCompletionCallback callback;
10364 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10365 scoped_ptr<HttpTransaction> trans(
10366 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10368 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
10370 EXPECT_EQ(ERR_IO_PENDING, rv);
10371 EXPECT_EQ(OK, callback.WaitForResult());
10373 const HttpResponseInfo* response = trans->GetResponseInfo();
10374 ASSERT_TRUE(response != NULL);
10375 ASSERT_TRUE(response->headers.get() != NULL);
10376 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
10378 std::string response_data;
10379 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
10380 EXPECT_EQ("hello world", response_data);
10382 EXPECT_FALSE(response->was_fetched_via_spdy);
10383 EXPECT_TRUE(response->was_npn_negotiated);
10386 TEST_P(HttpNetworkTransactionTest, SpdyPostNPNServerHangup) {
10387 // Simulate the SSL handshake completing with an NPN negotiation
10388 // followed by an immediate server closing of the socket.
10389 // Fix crash: http://crbug.com/46369
10390 session_deps_.use_alternate_protocols = true;
10391 session_deps_.next_protos = SpdyNextProtos();
10393 HttpRequestInfo request;
10394 request.method = "GET";
10395 request.url = GURL("https://www.google.com/");
10396 request.load_flags = 0;
10398 SSLSocketDataProvider ssl(ASYNC, OK);
10399 ssl.SetNextProto(GetParam());
10400 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
10402 scoped_ptr<SpdyFrame> req(
10403 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, true));
10404 MockWrite spdy_writes[] = { CreateMockWrite(*req) };
10406 MockRead spdy_reads[] = {
10407 MockRead(SYNCHRONOUS, 0, 0) // Not async - return 0 immediately.
10410 DelayedSocketData spdy_data(
10411 0, // don't wait in this case, immediate hangup.
10412 spdy_reads, arraysize(spdy_reads),
10413 spdy_writes, arraysize(spdy_writes));
10414 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
10416 TestCompletionCallback callback;
10418 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10419 scoped_ptr<HttpTransaction> trans(
10420 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10422 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
10423 EXPECT_EQ(ERR_IO_PENDING, rv);
10424 EXPECT_EQ(ERR_CONNECTION_CLOSED, callback.WaitForResult());
10427 // A subclass of HttpAuthHandlerMock that records the request URL when
10428 // it gets it. This is needed since the auth handler may get destroyed
10429 // before we get a chance to query it.
10430 class UrlRecordingHttpAuthHandlerMock : public HttpAuthHandlerMock {
10431 public:
10432 explicit UrlRecordingHttpAuthHandlerMock(GURL* url) : url_(url) {}
10434 ~UrlRecordingHttpAuthHandlerMock() override {}
10436 protected:
10437 int GenerateAuthTokenImpl(const AuthCredentials* credentials,
10438 const HttpRequestInfo* request,
10439 const CompletionCallback& callback,
10440 std::string* auth_token) override {
10441 *url_ = request->url;
10442 return HttpAuthHandlerMock::GenerateAuthTokenImpl(
10443 credentials, request, callback, auth_token);
10446 private:
10447 GURL* url_;
10450 TEST_P(HttpNetworkTransactionTest, SpdyAlternateProtocolThroughProxy) {
10451 // This test ensures that the URL passed into the proxy is upgraded
10452 // to https when doing an Alternate Protocol upgrade.
10453 session_deps_.use_alternate_protocols = true;
10454 session_deps_.next_protos = SpdyNextProtos();
10456 session_deps_.proxy_service.reset(
10457 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
10458 CapturingNetLog net_log;
10459 session_deps_.net_log = &net_log;
10460 GURL request_url;
10462 HttpAuthHandlerMock::Factory* auth_factory =
10463 new HttpAuthHandlerMock::Factory();
10464 UrlRecordingHttpAuthHandlerMock* auth_handler =
10465 new UrlRecordingHttpAuthHandlerMock(&request_url);
10466 auth_factory->AddMockHandler(auth_handler, HttpAuth::AUTH_PROXY);
10467 auth_factory->set_do_init_from_challenge(true);
10468 session_deps_.http_auth_handler_factory.reset(auth_factory);
10471 HttpRequestInfo request;
10472 request.method = "GET";
10473 request.url = GURL("http://www.google.com");
10474 request.load_flags = 0;
10476 // First round goes unauthenticated through the proxy.
10477 MockWrite data_writes_1[] = {
10478 MockWrite("GET http://www.google.com/ HTTP/1.1\r\n"
10479 "Host: www.google.com\r\n"
10480 "Proxy-Connection: keep-alive\r\n"
10481 "\r\n"),
10483 MockRead data_reads_1[] = {
10484 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
10485 MockRead("HTTP/1.1 200 OK\r\n"),
10486 MockRead("Alternate-Protocol: 443:"),
10487 MockRead(GetAlternateProtocolFromParam()),
10488 MockRead("\r\n"),
10489 MockRead("Proxy-Connection: close\r\n"),
10490 MockRead("\r\n"),
10492 StaticSocketDataProvider data_1(data_reads_1, arraysize(data_reads_1),
10493 data_writes_1, arraysize(data_writes_1));
10495 // Second round tries to tunnel to www.google.com due to the
10496 // Alternate-Protocol announcement in the first round. It fails due
10497 // to a proxy authentication challenge.
10498 // After the failure, a tunnel is established to www.google.com using
10499 // Proxy-Authorization headers. There is then a SPDY request round.
10501 // NOTE: Despite the "Proxy-Connection: Close", these are done on the
10502 // same MockTCPClientSocket since the underlying HttpNetworkClientSocket
10503 // does a Disconnect and Connect on the same socket, rather than trying
10504 // to obtain a new one.
10506 // NOTE: Originally, the proxy response to the second CONNECT request
10507 // simply returned another 407 so the unit test could skip the SSL connection
10508 // establishment and SPDY framing issues. Alas, the
10509 // retry-http-when-alternate-protocol fails logic kicks in, which was more
10510 // complicated to set up expectations for than the SPDY session.
10512 scoped_ptr<SpdyFrame> req(
10513 spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, true));
10514 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
10515 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
10517 MockWrite data_writes_2[] = {
10518 // First connection attempt without Proxy-Authorization.
10519 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
10520 "Host: www.google.com\r\n"
10521 "Proxy-Connection: keep-alive\r\n"
10522 "\r\n"),
10524 // Second connection attempt with Proxy-Authorization.
10525 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
10526 "Host: www.google.com\r\n"
10527 "Proxy-Connection: keep-alive\r\n"
10528 "Proxy-Authorization: auth_token\r\n"
10529 "\r\n"),
10531 // SPDY request
10532 CreateMockWrite(*req),
10534 const char kRejectConnectResponse[] = ("HTTP/1.1 407 Unauthorized\r\n"
10535 "Proxy-Authenticate: Mock\r\n"
10536 "Proxy-Connection: close\r\n"
10537 "\r\n");
10538 const char kAcceptConnectResponse[] = "HTTP/1.1 200 Connected\r\n\r\n";
10539 MockRead data_reads_2[] = {
10540 // First connection attempt fails
10541 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ, 1),
10542 MockRead(ASYNC, kRejectConnectResponse,
10543 arraysize(kRejectConnectResponse) - 1, 1),
10545 // Second connection attempt passes
10546 MockRead(ASYNC, kAcceptConnectResponse,
10547 arraysize(kAcceptConnectResponse) -1, 4),
10549 // SPDY response
10550 CreateMockRead(*resp.get(), 6),
10551 CreateMockRead(*data.get(), 6),
10552 MockRead(ASYNC, 0, 0, 6),
10554 OrderedSocketData data_2(
10555 data_reads_2, arraysize(data_reads_2),
10556 data_writes_2, arraysize(data_writes_2));
10558 SSLSocketDataProvider ssl(ASYNC, OK);
10559 ssl.SetNextProto(GetParam());
10561 MockConnect never_finishing_connect(SYNCHRONOUS, ERR_IO_PENDING);
10562 StaticSocketDataProvider hanging_non_alternate_protocol_socket(
10563 NULL, 0, NULL, 0);
10564 hanging_non_alternate_protocol_socket.set_connect_data(
10565 never_finishing_connect);
10567 session_deps_.socket_factory->AddSocketDataProvider(&data_1);
10568 session_deps_.socket_factory->AddSocketDataProvider(&data_2);
10569 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
10570 session_deps_.socket_factory->AddSocketDataProvider(
10571 &hanging_non_alternate_protocol_socket);
10572 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10574 // First round should work and provide the Alternate-Protocol state.
10575 TestCompletionCallback callback_1;
10576 scoped_ptr<HttpTransaction> trans_1(
10577 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10578 int rv = trans_1->Start(&request, callback_1.callback(), BoundNetLog());
10579 EXPECT_EQ(ERR_IO_PENDING, rv);
10580 EXPECT_EQ(OK, callback_1.WaitForResult());
10582 // Second round should attempt a tunnel connect and get an auth challenge.
10583 TestCompletionCallback callback_2;
10584 scoped_ptr<HttpTransaction> trans_2(
10585 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10586 rv = trans_2->Start(&request, callback_2.callback(), BoundNetLog());
10587 EXPECT_EQ(ERR_IO_PENDING, rv);
10588 EXPECT_EQ(OK, callback_2.WaitForResult());
10589 const HttpResponseInfo* response = trans_2->GetResponseInfo();
10590 ASSERT_TRUE(response != NULL);
10591 ASSERT_FALSE(response->auth_challenge.get() == NULL);
10593 // Restart with auth. Tunnel should work and response received.
10594 TestCompletionCallback callback_3;
10595 rv = trans_2->RestartWithAuth(
10596 AuthCredentials(kFoo, kBar), callback_3.callback());
10597 EXPECT_EQ(ERR_IO_PENDING, rv);
10598 EXPECT_EQ(OK, callback_3.WaitForResult());
10600 // After all that work, these two lines (or actually, just the scheme) are
10601 // what this test is all about. Make sure it happens correctly.
10602 EXPECT_EQ("https", request_url.scheme());
10603 EXPECT_EQ("www.google.com", request_url.host());
10605 LoadTimingInfo load_timing_info;
10606 EXPECT_TRUE(trans_2->GetLoadTimingInfo(&load_timing_info));
10607 TestLoadTimingNotReusedWithPac(load_timing_info,
10608 CONNECT_TIMING_HAS_SSL_TIMES);
10611 // Test that if we cancel the transaction as the connection is completing, that
10612 // everything tears down correctly.
10613 TEST_P(HttpNetworkTransactionTest, SimpleCancel) {
10614 // Setup everything about the connection to complete synchronously, so that
10615 // after calling HttpNetworkTransaction::Start, the only thing we're waiting
10616 // for is the callback from the HttpStreamRequest.
10617 // Then cancel the transaction.
10618 // Verify that we don't crash.
10619 MockConnect mock_connect(SYNCHRONOUS, OK);
10620 MockRead data_reads[] = {
10621 MockRead(SYNCHRONOUS, "HTTP/1.0 200 OK\r\n\r\n"),
10622 MockRead(SYNCHRONOUS, "hello world"),
10623 MockRead(SYNCHRONOUS, OK),
10626 HttpRequestInfo request;
10627 request.method = "GET";
10628 request.url = GURL("http://www.google.com/");
10629 request.load_flags = 0;
10631 session_deps_.host_resolver->set_synchronous_mode(true);
10632 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10633 scoped_ptr<HttpTransaction> trans(
10634 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10636 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
10637 data.set_connect_data(mock_connect);
10638 session_deps_.socket_factory->AddSocketDataProvider(&data);
10640 TestCompletionCallback callback;
10642 CapturingBoundNetLog log;
10643 int rv = trans->Start(&request, callback.callback(), log.bound());
10644 EXPECT_EQ(ERR_IO_PENDING, rv);
10645 trans.reset(); // Cancel the transaction here.
10647 base::MessageLoop::current()->RunUntilIdle();
10650 // Test that if a transaction is cancelled after receiving the headers, the
10651 // stream is drained properly and added back to the socket pool. The main
10652 // purpose of this test is to make sure that an HttpStreamParser can be read
10653 // from after the HttpNetworkTransaction and the objects it owns have been
10654 // deleted.
10655 // See http://crbug.com/368418
10656 TEST_P(HttpNetworkTransactionTest, CancelAfterHeaders) {
10657 MockRead data_reads[] = {
10658 MockRead(ASYNC, "HTTP/1.1 200 OK\r\n"),
10659 MockRead(ASYNC, "Content-Length: 2\r\n"),
10660 MockRead(ASYNC, "Connection: Keep-Alive\r\n\r\n"),
10661 MockRead(ASYNC, "1"),
10662 // 2 async reads are necessary to trigger a ReadResponseBody call after the
10663 // HttpNetworkTransaction has been deleted.
10664 MockRead(ASYNC, "2"),
10665 MockRead(SYNCHRONOUS, ERR_IO_PENDING), // Should never read this.
10667 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
10668 session_deps_.socket_factory->AddSocketDataProvider(&data);
10670 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10673 HttpRequestInfo request;
10674 request.method = "GET";
10675 request.url = GURL("http://www.google.com/");
10676 request.load_flags = 0;
10678 HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
10679 TestCompletionCallback callback;
10681 int rv = trans.Start(&request, callback.callback(), BoundNetLog());
10682 EXPECT_EQ(ERR_IO_PENDING, rv);
10683 callback.WaitForResult();
10685 const HttpResponseInfo* response = trans.GetResponseInfo();
10686 ASSERT_TRUE(response != NULL);
10687 EXPECT_TRUE(response->headers.get() != NULL);
10688 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
10690 // The transaction and HttpRequestInfo are deleted.
10693 // Let the HttpResponseBodyDrainer drain the socket.
10694 base::MessageLoop::current()->RunUntilIdle();
10696 // Socket should now be idle, waiting to be reused.
10697 EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
10700 // Test a basic GET request through a proxy.
10701 TEST_P(HttpNetworkTransactionTest, ProxyGet) {
10702 session_deps_.proxy_service.reset(
10703 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
10704 CapturingBoundNetLog log;
10705 session_deps_.net_log = log.bound().net_log();
10706 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10708 HttpRequestInfo request;
10709 request.method = "GET";
10710 request.url = GURL("http://www.google.com/");
10712 MockWrite data_writes1[] = {
10713 MockWrite("GET http://www.google.com/ HTTP/1.1\r\n"
10714 "Host: www.google.com\r\n"
10715 "Proxy-Connection: keep-alive\r\n\r\n"),
10718 MockRead data_reads1[] = {
10719 MockRead("HTTP/1.1 200 OK\r\n"),
10720 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
10721 MockRead("Content-Length: 100\r\n\r\n"),
10722 MockRead(SYNCHRONOUS, OK),
10725 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
10726 data_writes1, arraysize(data_writes1));
10727 session_deps_.socket_factory->AddSocketDataProvider(&data1);
10729 TestCompletionCallback callback1;
10731 scoped_ptr<HttpTransaction> trans(
10732 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10733 BeforeProxyHeadersSentHandler proxy_headers_handler;
10734 trans->SetBeforeProxyHeadersSentCallback(
10735 base::Bind(&BeforeProxyHeadersSentHandler::OnBeforeProxyHeadersSent,
10736 base::Unretained(&proxy_headers_handler)));
10738 int rv = trans->Start(&request, callback1.callback(), log.bound());
10739 EXPECT_EQ(ERR_IO_PENDING, rv);
10741 rv = callback1.WaitForResult();
10742 EXPECT_EQ(OK, rv);
10744 const HttpResponseInfo* response = trans->GetResponseInfo();
10745 ASSERT_TRUE(response != NULL);
10747 EXPECT_TRUE(response->headers->IsKeepAlive());
10748 EXPECT_EQ(200, response->headers->response_code());
10749 EXPECT_EQ(100, response->headers->GetContentLength());
10750 EXPECT_TRUE(response->was_fetched_via_proxy);
10751 EXPECT_TRUE(
10752 response->proxy_server.Equals(HostPortPair::FromString("myproxy:70")));
10753 EXPECT_TRUE(proxy_headers_handler.observed_before_proxy_headers_sent());
10754 EXPECT_EQ("myproxy:70", proxy_headers_handler.observed_proxy_server_uri());
10755 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
10757 LoadTimingInfo load_timing_info;
10758 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
10759 TestLoadTimingNotReusedWithPac(load_timing_info,
10760 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
10763 // Test a basic HTTPS GET request through a proxy.
10764 TEST_P(HttpNetworkTransactionTest, ProxyTunnelGet) {
10765 session_deps_.proxy_service.reset(
10766 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
10767 CapturingBoundNetLog log;
10768 session_deps_.net_log = log.bound().net_log();
10769 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10771 HttpRequestInfo request;
10772 request.method = "GET";
10773 request.url = GURL("https://www.google.com/");
10775 // Since we have proxy, should try to establish tunnel.
10776 MockWrite data_writes1[] = {
10777 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
10778 "Host: www.google.com\r\n"
10779 "Proxy-Connection: keep-alive\r\n\r\n"),
10781 MockWrite("GET / HTTP/1.1\r\n"
10782 "Host: www.google.com\r\n"
10783 "Connection: keep-alive\r\n\r\n"),
10786 MockRead data_reads1[] = {
10787 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
10789 MockRead("HTTP/1.1 200 OK\r\n"),
10790 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
10791 MockRead("Content-Length: 100\r\n\r\n"),
10792 MockRead(SYNCHRONOUS, OK),
10795 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
10796 data_writes1, arraysize(data_writes1));
10797 session_deps_.socket_factory->AddSocketDataProvider(&data1);
10798 SSLSocketDataProvider ssl(ASYNC, OK);
10799 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
10801 TestCompletionCallback callback1;
10803 scoped_ptr<HttpTransaction> trans(
10804 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10806 int rv = trans->Start(&request, callback1.callback(), log.bound());
10807 EXPECT_EQ(ERR_IO_PENDING, rv);
10809 rv = callback1.WaitForResult();
10810 EXPECT_EQ(OK, rv);
10811 net::CapturingNetLog::CapturedEntryList entries;
10812 log.GetEntries(&entries);
10813 size_t pos = ExpectLogContainsSomewhere(
10814 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
10815 NetLog::PHASE_NONE);
10816 ExpectLogContainsSomewhere(
10817 entries, pos,
10818 NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
10819 NetLog::PHASE_NONE);
10821 const HttpResponseInfo* response = trans->GetResponseInfo();
10822 ASSERT_TRUE(response != NULL);
10824 EXPECT_TRUE(response->headers->IsKeepAlive());
10825 EXPECT_EQ(200, response->headers->response_code());
10826 EXPECT_EQ(100, response->headers->GetContentLength());
10827 EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
10828 EXPECT_TRUE(response->was_fetched_via_proxy);
10829 EXPECT_TRUE(
10830 response->proxy_server.Equals(HostPortPair::FromString("myproxy:70")));
10832 LoadTimingInfo load_timing_info;
10833 EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
10834 TestLoadTimingNotReusedWithPac(load_timing_info,
10835 CONNECT_TIMING_HAS_SSL_TIMES);
10838 // Test a basic HTTPS GET request through a proxy, but the server hangs up
10839 // while establishing the tunnel.
10840 TEST_P(HttpNetworkTransactionTest, ProxyTunnelGetHangup) {
10841 session_deps_.proxy_service.reset(ProxyService::CreateFixed("myproxy:70"));
10842 CapturingBoundNetLog log;
10843 session_deps_.net_log = log.bound().net_log();
10844 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10846 HttpRequestInfo request;
10847 request.method = "GET";
10848 request.url = GURL("https://www.google.com/");
10850 // Since we have proxy, should try to establish tunnel.
10851 MockWrite data_writes1[] = {
10852 MockWrite("CONNECT www.google.com:443 HTTP/1.1\r\n"
10853 "Host: www.google.com\r\n"
10854 "Proxy-Connection: keep-alive\r\n\r\n"),
10856 MockWrite("GET / HTTP/1.1\r\n"
10857 "Host: www.google.com\r\n"
10858 "Connection: keep-alive\r\n\r\n"),
10861 MockRead data_reads1[] = {
10862 MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
10863 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
10864 MockRead(ASYNC, 0, 0), // EOF
10867 StaticSocketDataProvider data1(data_reads1, arraysize(data_reads1),
10868 data_writes1, arraysize(data_writes1));
10869 session_deps_.socket_factory->AddSocketDataProvider(&data1);
10870 SSLSocketDataProvider ssl(ASYNC, OK);
10871 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
10873 TestCompletionCallback callback1;
10875 scoped_ptr<HttpTransaction> trans(
10876 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10878 int rv = trans->Start(&request, callback1.callback(), log.bound());
10879 EXPECT_EQ(ERR_IO_PENDING, rv);
10881 rv = callback1.WaitForResult();
10882 EXPECT_EQ(ERR_EMPTY_RESPONSE, rv);
10883 net::CapturingNetLog::CapturedEntryList entries;
10884 log.GetEntries(&entries);
10885 size_t pos = ExpectLogContainsSomewhere(
10886 entries, 0, NetLog::TYPE_HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
10887 NetLog::PHASE_NONE);
10888 ExpectLogContainsSomewhere(
10889 entries, pos,
10890 NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
10891 NetLog::PHASE_NONE);
10894 // Test for crbug.com/55424.
10895 TEST_P(HttpNetworkTransactionTest, PreconnectWithExistingSpdySession) {
10896 scoped_ptr<SpdyFrame> req(
10897 spdy_util_.ConstructSpdyGet("https://www.google.com", false, 1, LOWEST));
10898 MockWrite spdy_writes[] = { CreateMockWrite(*req) };
10900 scoped_ptr<SpdyFrame> resp(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
10901 scoped_ptr<SpdyFrame> data(spdy_util_.ConstructSpdyBodyFrame(1, true));
10902 MockRead spdy_reads[] = {
10903 CreateMockRead(*resp),
10904 CreateMockRead(*data),
10905 MockRead(ASYNC, 0, 0),
10908 DelayedSocketData spdy_data(
10909 1, // wait for one write to finish before reading.
10910 spdy_reads, arraysize(spdy_reads),
10911 spdy_writes, arraysize(spdy_writes));
10912 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
10914 SSLSocketDataProvider ssl(ASYNC, OK);
10915 ssl.SetNextProto(GetParam());
10916 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
10918 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10920 // Set up an initial SpdySession in the pool to reuse.
10921 HostPortPair host_port_pair("www.google.com", 443);
10922 SpdySessionKey key(host_port_pair, ProxyServer::Direct(),
10923 PRIVACY_MODE_DISABLED);
10924 base::WeakPtr<SpdySession> spdy_session =
10925 CreateInsecureSpdySession(session, key, BoundNetLog());
10927 HttpRequestInfo request;
10928 request.method = "GET";
10929 request.url = GURL("https://www.google.com/");
10930 request.load_flags = 0;
10932 // This is the important line that marks this as a preconnect.
10933 request.motivation = HttpRequestInfo::PRECONNECT_MOTIVATED;
10935 scoped_ptr<HttpTransaction> trans(
10936 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10938 TestCompletionCallback callback;
10939 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
10940 EXPECT_EQ(ERR_IO_PENDING, rv);
10941 EXPECT_EQ(OK, callback.WaitForResult());
10944 // Given a net error, cause that error to be returned from the first Write()
10945 // call and verify that the HttpTransaction fails with that error.
10946 void HttpNetworkTransactionTest::CheckErrorIsPassedBack(
10947 int error, IoMode mode) {
10948 net::HttpRequestInfo request_info;
10949 request_info.url = GURL("https://www.example.com/");
10950 request_info.method = "GET";
10951 request_info.load_flags = net::LOAD_NORMAL;
10953 SSLSocketDataProvider ssl_data(mode, OK);
10954 net::MockWrite data_writes[] = {
10955 net::MockWrite(mode, error),
10957 net::StaticSocketDataProvider data(NULL, 0,
10958 data_writes, arraysize(data_writes));
10959 session_deps_.socket_factory->AddSocketDataProvider(&data);
10960 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data);
10962 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
10963 scoped_ptr<HttpTransaction> trans(
10964 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
10966 TestCompletionCallback callback;
10967 int rv = trans->Start(&request_info, callback.callback(), net::BoundNetLog());
10968 if (rv == net::ERR_IO_PENDING)
10969 rv = callback.WaitForResult();
10970 ASSERT_EQ(error, rv);
10973 TEST_P(HttpNetworkTransactionTest, SSLWriteCertError) {
10974 // Just check a grab bag of cert errors.
10975 static const int kErrors[] = {
10976 ERR_CERT_COMMON_NAME_INVALID,
10977 ERR_CERT_AUTHORITY_INVALID,
10978 ERR_CERT_DATE_INVALID,
10980 for (size_t i = 0; i < arraysize(kErrors); i++) {
10981 CheckErrorIsPassedBack(kErrors[i], ASYNC);
10982 CheckErrorIsPassedBack(kErrors[i], SYNCHRONOUS);
10986 // Ensure that a client certificate is removed from the SSL client auth
10987 // cache when:
10988 // 1) No proxy is involved.
10989 // 2) TLS False Start is disabled.
10990 // 3) The initial TLS handshake requests a client certificate.
10991 // 4) The client supplies an invalid/unacceptable certificate.
10992 TEST_P(HttpNetworkTransactionTest,
10993 ClientAuthCertCache_Direct_NoFalseStart) {
10994 net::HttpRequestInfo request_info;
10995 request_info.url = GURL("https://www.example.com/");
10996 request_info.method = "GET";
10997 request_info.load_flags = net::LOAD_NORMAL;
10999 scoped_refptr<SSLCertRequestInfo> cert_request(new SSLCertRequestInfo());
11000 cert_request->host_and_port = HostPortPair("www.example.com", 443);
11002 // [ssl_]data1 contains the data for the first SSL handshake. When a
11003 // CertificateRequest is received for the first time, the handshake will
11004 // be aborted to allow the caller to provide a certificate.
11005 SSLSocketDataProvider ssl_data1(ASYNC, net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
11006 ssl_data1.cert_request_info = cert_request.get();
11007 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data1);
11008 net::StaticSocketDataProvider data1(NULL, 0, NULL, 0);
11009 session_deps_.socket_factory->AddSocketDataProvider(&data1);
11011 // [ssl_]data2 contains the data for the second SSL handshake. When TLS
11012 // False Start is not being used, the result of the SSL handshake will be
11013 // returned as part of the SSLClientSocket::Connect() call. This test
11014 // matches the result of a server sending a handshake_failure alert,
11015 // rather than a Finished message, because it requires a client
11016 // certificate and none was supplied.
11017 SSLSocketDataProvider ssl_data2(ASYNC, net::ERR_SSL_PROTOCOL_ERROR);
11018 ssl_data2.cert_request_info = cert_request.get();
11019 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data2);
11020 net::StaticSocketDataProvider data2(NULL, 0, NULL, 0);
11021 session_deps_.socket_factory->AddSocketDataProvider(&data2);
11023 // [ssl_]data3 contains the data for the third SSL handshake. When a
11024 // connection to a server fails during an SSL handshake,
11025 // HttpNetworkTransaction will attempt to fallback to TLSv1 if the previous
11026 // connection was attempted with TLSv1.1. This is transparent to the caller
11027 // of the HttpNetworkTransaction. Because this test failure is due to
11028 // requiring a client certificate, this fallback handshake should also
11029 // fail.
11030 SSLSocketDataProvider ssl_data3(ASYNC, net::ERR_SSL_PROTOCOL_ERROR);
11031 ssl_data3.cert_request_info = cert_request.get();
11032 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data3);
11033 net::StaticSocketDataProvider data3(NULL, 0, NULL, 0);
11034 session_deps_.socket_factory->AddSocketDataProvider(&data3);
11036 // [ssl_]data4 contains the data for the fourth SSL handshake. When a
11037 // connection to a server fails during an SSL handshake,
11038 // HttpNetworkTransaction will attempt to fallback to SSLv3 if the previous
11039 // connection was attempted with TLSv1. This is transparent to the caller
11040 // of the HttpNetworkTransaction. Because this test failure is due to
11041 // requiring a client certificate, this fallback handshake should also
11042 // fail.
11043 SSLSocketDataProvider ssl_data4(ASYNC, net::ERR_SSL_PROTOCOL_ERROR);
11044 ssl_data4.cert_request_info = cert_request.get();
11045 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data4);
11046 net::StaticSocketDataProvider data4(NULL, 0, NULL, 0);
11047 session_deps_.socket_factory->AddSocketDataProvider(&data4);
11049 // Need one more if TLSv1.2 is enabled.
11050 SSLSocketDataProvider ssl_data5(ASYNC, net::ERR_SSL_PROTOCOL_ERROR);
11051 ssl_data5.cert_request_info = cert_request.get();
11052 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data5);
11053 net::StaticSocketDataProvider data5(NULL, 0, NULL, 0);
11054 session_deps_.socket_factory->AddSocketDataProvider(&data5);
11056 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11057 scoped_ptr<HttpTransaction> trans(
11058 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
11060 // Begin the SSL handshake with the peer. This consumes ssl_data1.
11061 TestCompletionCallback callback;
11062 int rv = trans->Start(&request_info, callback.callback(), net::BoundNetLog());
11063 ASSERT_EQ(net::ERR_IO_PENDING, rv);
11065 // Complete the SSL handshake, which should abort due to requiring a
11066 // client certificate.
11067 rv = callback.WaitForResult();
11068 ASSERT_EQ(net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
11070 // Indicate that no certificate should be supplied. From the perspective
11071 // of SSLClientCertCache, NULL is just as meaningful as a real
11072 // certificate, so this is the same as supply a
11073 // legitimate-but-unacceptable certificate.
11074 rv = trans->RestartWithCertificate(NULL, callback.callback());
11075 ASSERT_EQ(net::ERR_IO_PENDING, rv);
11077 // Ensure the certificate was added to the client auth cache before
11078 // allowing the connection to continue restarting.
11079 scoped_refptr<X509Certificate> client_cert;
11080 ASSERT_TRUE(session->ssl_client_auth_cache()->Lookup(
11081 HostPortPair("www.example.com", 443), &client_cert));
11082 ASSERT_EQ(NULL, client_cert.get());
11084 // Restart the handshake. This will consume ssl_data2, which fails, and
11085 // then consume ssl_data3 and ssl_data4, both of which should also fail.
11086 // The result code is checked against what ssl_data4 should return.
11087 rv = callback.WaitForResult();
11088 ASSERT_EQ(net::ERR_SSL_PROTOCOL_ERROR, rv);
11090 // Ensure that the client certificate is removed from the cache on a
11091 // handshake failure.
11092 ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
11093 HostPortPair("www.example.com", 443), &client_cert));
11096 // Ensure that a client certificate is removed from the SSL client auth
11097 // cache when:
11098 // 1) No proxy is involved.
11099 // 2) TLS False Start is enabled.
11100 // 3) The initial TLS handshake requests a client certificate.
11101 // 4) The client supplies an invalid/unacceptable certificate.
11102 TEST_P(HttpNetworkTransactionTest,
11103 ClientAuthCertCache_Direct_FalseStart) {
11104 net::HttpRequestInfo request_info;
11105 request_info.url = GURL("https://www.example.com/");
11106 request_info.method = "GET";
11107 request_info.load_flags = net::LOAD_NORMAL;
11109 scoped_refptr<SSLCertRequestInfo> cert_request(new SSLCertRequestInfo());
11110 cert_request->host_and_port = HostPortPair("www.example.com", 443);
11112 // When TLS False Start is used, SSLClientSocket::Connect() calls will
11113 // return successfully after reading up to the peer's Certificate message.
11114 // This is to allow the caller to call SSLClientSocket::Write(), which can
11115 // enqueue application data to be sent in the same packet as the
11116 // ChangeCipherSpec and Finished messages.
11117 // The actual handshake will be finished when SSLClientSocket::Read() is
11118 // called, which expects to process the peer's ChangeCipherSpec and
11119 // Finished messages. If there was an error negotiating with the peer,
11120 // such as due to the peer requiring a client certificate when none was
11121 // supplied, the alert sent by the peer won't be processed until Read() is
11122 // called.
11124 // Like the non-False Start case, when a client certificate is requested by
11125 // the peer, the handshake is aborted during the Connect() call.
11126 // [ssl_]data1 represents the initial SSL handshake with the peer.
11127 SSLSocketDataProvider ssl_data1(ASYNC, net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
11128 ssl_data1.cert_request_info = cert_request.get();
11129 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data1);
11130 net::StaticSocketDataProvider data1(NULL, 0, NULL, 0);
11131 session_deps_.socket_factory->AddSocketDataProvider(&data1);
11133 // When a client certificate is supplied, Connect() will not be aborted
11134 // when the peer requests the certificate. Instead, the handshake will
11135 // artificially succeed, allowing the caller to write the HTTP request to
11136 // the socket. The handshake messages are not processed until Read() is
11137 // called, which then detects that the handshake was aborted, due to the
11138 // peer sending a handshake_failure because it requires a client
11139 // certificate.
11140 SSLSocketDataProvider ssl_data2(ASYNC, net::OK);
11141 ssl_data2.cert_request_info = cert_request.get();
11142 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data2);
11143 net::MockRead data2_reads[] = {
11144 net::MockRead(ASYNC /* async */, net::ERR_SSL_PROTOCOL_ERROR),
11146 net::StaticSocketDataProvider data2(
11147 data2_reads, arraysize(data2_reads), NULL, 0);
11148 session_deps_.socket_factory->AddSocketDataProvider(&data2);
11150 // As described in ClientAuthCertCache_Direct_NoFalseStart, [ssl_]data3 is
11151 // the data for the SSL handshake once the TLSv1.1 connection falls back to
11152 // TLSv1. It has the same behaviour as [ssl_]data2.
11153 SSLSocketDataProvider ssl_data3(ASYNC, net::OK);
11154 ssl_data3.cert_request_info = cert_request.get();
11155 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data3);
11156 net::StaticSocketDataProvider data3(
11157 data2_reads, arraysize(data2_reads), NULL, 0);
11158 session_deps_.socket_factory->AddSocketDataProvider(&data3);
11160 // [ssl_]data4 is the data for the SSL handshake once the TLSv1 connection
11161 // falls back to SSLv3. It has the same behaviour as [ssl_]data2.
11162 SSLSocketDataProvider ssl_data4(ASYNC, net::OK);
11163 ssl_data4.cert_request_info = cert_request.get();
11164 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data4);
11165 net::StaticSocketDataProvider data4(
11166 data2_reads, arraysize(data2_reads), NULL, 0);
11167 session_deps_.socket_factory->AddSocketDataProvider(&data4);
11169 // Need one more if TLSv1.2 is enabled.
11170 SSLSocketDataProvider ssl_data5(ASYNC, net::OK);
11171 ssl_data5.cert_request_info = cert_request.get();
11172 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data5);
11173 net::StaticSocketDataProvider data5(
11174 data2_reads, arraysize(data2_reads), NULL, 0);
11175 session_deps_.socket_factory->AddSocketDataProvider(&data5);
11177 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11178 scoped_ptr<HttpTransaction> trans(
11179 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
11181 // Begin the initial SSL handshake.
11182 TestCompletionCallback callback;
11183 int rv = trans->Start(&request_info, callback.callback(), net::BoundNetLog());
11184 ASSERT_EQ(net::ERR_IO_PENDING, rv);
11186 // Complete the SSL handshake, which should abort due to requiring a
11187 // client certificate.
11188 rv = callback.WaitForResult();
11189 ASSERT_EQ(net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
11191 // Indicate that no certificate should be supplied. From the perspective
11192 // of SSLClientCertCache, NULL is just as meaningful as a real
11193 // certificate, so this is the same as supply a
11194 // legitimate-but-unacceptable certificate.
11195 rv = trans->RestartWithCertificate(NULL, callback.callback());
11196 ASSERT_EQ(net::ERR_IO_PENDING, rv);
11198 // Ensure the certificate was added to the client auth cache before
11199 // allowing the connection to continue restarting.
11200 scoped_refptr<X509Certificate> client_cert;
11201 ASSERT_TRUE(session->ssl_client_auth_cache()->Lookup(
11202 HostPortPair("www.example.com", 443), &client_cert));
11203 ASSERT_EQ(NULL, client_cert.get());
11205 // Restart the handshake. This will consume ssl_data2, which fails, and
11206 // then consume ssl_data3 and ssl_data4, both of which should also fail.
11207 // The result code is checked against what ssl_data4 should return.
11208 rv = callback.WaitForResult();
11209 ASSERT_EQ(net::ERR_SSL_PROTOCOL_ERROR, rv);
11211 // Ensure that the client certificate is removed from the cache on a
11212 // handshake failure.
11213 ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
11214 HostPortPair("www.example.com", 443), &client_cert));
11217 // Ensure that a client certificate is removed from the SSL client auth
11218 // cache when:
11219 // 1) An HTTPS proxy is involved.
11220 // 3) The HTTPS proxy requests a client certificate.
11221 // 4) The client supplies an invalid/unacceptable certificate for the
11222 // proxy.
11223 // The test is repeated twice, first for connecting to an HTTPS endpoint,
11224 // then for connecting to an HTTP endpoint.
11225 TEST_P(HttpNetworkTransactionTest, ClientAuthCertCache_Proxy_Fail) {
11226 session_deps_.proxy_service.reset(
11227 ProxyService::CreateFixed("https://proxy:70"));
11228 CapturingBoundNetLog log;
11229 session_deps_.net_log = log.bound().net_log();
11231 scoped_refptr<SSLCertRequestInfo> cert_request(new SSLCertRequestInfo());
11232 cert_request->host_and_port = HostPortPair("proxy", 70);
11234 // See ClientAuthCertCache_Direct_NoFalseStart for the explanation of
11235 // [ssl_]data[1-3]. Rather than represending the endpoint
11236 // (www.example.com:443), they represent failures with the HTTPS proxy
11237 // (proxy:70).
11238 SSLSocketDataProvider ssl_data1(ASYNC, net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
11239 ssl_data1.cert_request_info = cert_request.get();
11240 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data1);
11241 net::StaticSocketDataProvider data1(NULL, 0, NULL, 0);
11242 session_deps_.socket_factory->AddSocketDataProvider(&data1);
11244 SSLSocketDataProvider ssl_data2(ASYNC, net::ERR_SSL_PROTOCOL_ERROR);
11245 ssl_data2.cert_request_info = cert_request.get();
11246 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data2);
11247 net::StaticSocketDataProvider data2(NULL, 0, NULL, 0);
11248 session_deps_.socket_factory->AddSocketDataProvider(&data2);
11250 // TODO(wtc): find out why this unit test doesn't need [ssl_]data3.
11251 #if 0
11252 SSLSocketDataProvider ssl_data3(ASYNC, net::ERR_SSL_PROTOCOL_ERROR);
11253 ssl_data3.cert_request_info = cert_request.get();
11254 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data3);
11255 net::StaticSocketDataProvider data3(NULL, 0, NULL, 0);
11256 session_deps_.socket_factory->AddSocketDataProvider(&data3);
11257 #endif
11259 net::HttpRequestInfo requests[2];
11260 requests[0].url = GURL("https://www.example.com/");
11261 requests[0].method = "GET";
11262 requests[0].load_flags = net::LOAD_NORMAL;
11264 requests[1].url = GURL("http://www.example.com/");
11265 requests[1].method = "GET";
11266 requests[1].load_flags = net::LOAD_NORMAL;
11268 for (size_t i = 0; i < arraysize(requests); ++i) {
11269 session_deps_.socket_factory->ResetNextMockIndexes();
11270 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11271 scoped_ptr<HttpNetworkTransaction> trans(
11272 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
11274 // Begin the SSL handshake with the proxy.
11275 TestCompletionCallback callback;
11276 int rv = trans->Start(
11277 &requests[i], callback.callback(), net::BoundNetLog());
11278 ASSERT_EQ(net::ERR_IO_PENDING, rv);
11280 // Complete the SSL handshake, which should abort due to requiring a
11281 // client certificate.
11282 rv = callback.WaitForResult();
11283 ASSERT_EQ(net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
11285 // Indicate that no certificate should be supplied. From the perspective
11286 // of SSLClientCertCache, NULL is just as meaningful as a real
11287 // certificate, so this is the same as supply a
11288 // legitimate-but-unacceptable certificate.
11289 rv = trans->RestartWithCertificate(NULL, callback.callback());
11290 ASSERT_EQ(net::ERR_IO_PENDING, rv);
11292 // Ensure the certificate was added to the client auth cache before
11293 // allowing the connection to continue restarting.
11294 scoped_refptr<X509Certificate> client_cert;
11295 ASSERT_TRUE(session->ssl_client_auth_cache()->Lookup(
11296 HostPortPair("proxy", 70), &client_cert));
11297 ASSERT_EQ(NULL, client_cert.get());
11298 // Ensure the certificate was NOT cached for the endpoint. This only
11299 // applies to HTTPS requests, but is fine to check for HTTP requests.
11300 ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
11301 HostPortPair("www.example.com", 443), &client_cert));
11303 // Restart the handshake. This will consume ssl_data2, which fails, and
11304 // then consume ssl_data3, which should also fail. The result code is
11305 // checked against what ssl_data3 should return.
11306 rv = callback.WaitForResult();
11307 ASSERT_EQ(net::ERR_PROXY_CONNECTION_FAILED, rv);
11309 // Now that the new handshake has failed, ensure that the client
11310 // certificate was removed from the client auth cache.
11311 ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
11312 HostPortPair("proxy", 70), &client_cert));
11313 ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
11314 HostPortPair("www.example.com", 443), &client_cert));
11318 // Unlike TEST/TEST_F, which are macros that expand to further macros,
11319 // TEST_P is a macro that expands directly to code that stringizes the
11320 // arguments. As a result, macros passed as parameters (such as prefix
11321 // or test_case_name) will not be expanded by the preprocessor. To
11322 // work around this, indirect the macro for TEST_P, so that the
11323 // pre-processor will expand macros such as MAYBE_test_name before
11324 // instantiating the test.
11325 #define WRAPPED_TEST_P(test_case_name, test_name) \
11326 TEST_P(test_case_name, test_name)
11328 // Times out on Win7 dbg(2) bot. http://crbug.com/124776
11329 #if defined(OS_WIN)
11330 #define MAYBE_UseIPConnectionPooling DISABLED_UseIPConnectionPooling
11331 #else
11332 #define MAYBE_UseIPConnectionPooling UseIPConnectionPooling
11333 #endif
11334 WRAPPED_TEST_P(HttpNetworkTransactionTest, MAYBE_UseIPConnectionPooling) {
11335 session_deps_.use_alternate_protocols = true;
11336 session_deps_.next_protos = SpdyNextProtos();
11338 // Set up a special HttpNetworkSession with a MockCachingHostResolver.
11339 session_deps_.host_resolver.reset(new MockCachingHostResolver());
11340 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11341 SpdySessionPoolPeer pool_peer(session->spdy_session_pool());
11342 pool_peer.DisableDomainAuthenticationVerification();
11344 SSLSocketDataProvider ssl(ASYNC, OK);
11345 ssl.SetNextProto(GetParam());
11346 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
11348 scoped_ptr<SpdyFrame> host1_req(
11349 spdy_util_.ConstructSpdyGet("https://www.google.com", false, 1, LOWEST));
11350 scoped_ptr<SpdyFrame> host2_req(
11351 spdy_util_.ConstructSpdyGet("https://www.gmail.com", false, 3, LOWEST));
11352 MockWrite spdy_writes[] = {
11353 CreateMockWrite(*host1_req, 1),
11354 CreateMockWrite(*host2_req, 4),
11356 scoped_ptr<SpdyFrame> host1_resp(
11357 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11358 scoped_ptr<SpdyFrame> host1_resp_body(
11359 spdy_util_.ConstructSpdyBodyFrame(1, true));
11360 scoped_ptr<SpdyFrame> host2_resp(
11361 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
11362 scoped_ptr<SpdyFrame> host2_resp_body(
11363 spdy_util_.ConstructSpdyBodyFrame(3, true));
11364 MockRead spdy_reads[] = {
11365 CreateMockRead(*host1_resp, 2),
11366 CreateMockRead(*host1_resp_body, 3),
11367 CreateMockRead(*host2_resp, 5),
11368 CreateMockRead(*host2_resp_body, 6),
11369 MockRead(ASYNC, 0, 7),
11372 IPAddressNumber ip;
11373 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &ip));
11374 IPEndPoint peer_addr = IPEndPoint(ip, 443);
11375 MockConnect connect(ASYNC, OK, peer_addr);
11376 OrderedSocketData spdy_data(
11377 connect,
11378 spdy_reads, arraysize(spdy_reads),
11379 spdy_writes, arraysize(spdy_writes));
11380 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
11382 TestCompletionCallback callback;
11383 HttpRequestInfo request1;
11384 request1.method = "GET";
11385 request1.url = GURL("https://www.google.com/");
11386 request1.load_flags = 0;
11387 HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
11389 int rv = trans1.Start(&request1, callback.callback(), BoundNetLog());
11390 EXPECT_EQ(ERR_IO_PENDING, rv);
11391 EXPECT_EQ(OK, callback.WaitForResult());
11393 const HttpResponseInfo* response = trans1.GetResponseInfo();
11394 ASSERT_TRUE(response != NULL);
11395 ASSERT_TRUE(response->headers.get() != NULL);
11396 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
11398 std::string response_data;
11399 ASSERT_EQ(OK, ReadTransaction(&trans1, &response_data));
11400 EXPECT_EQ("hello!", response_data);
11402 // Preload www.gmail.com into HostCache.
11403 HostPortPair host_port("www.gmail.com", 443);
11404 HostResolver::RequestInfo resolve_info(host_port);
11405 AddressList ignored;
11406 rv = session_deps_.host_resolver->Resolve(resolve_info,
11407 DEFAULT_PRIORITY,
11408 &ignored,
11409 callback.callback(),
11410 NULL,
11411 BoundNetLog());
11412 EXPECT_EQ(ERR_IO_PENDING, rv);
11413 rv = callback.WaitForResult();
11414 EXPECT_EQ(OK, rv);
11416 HttpRequestInfo request2;
11417 request2.method = "GET";
11418 request2.url = GURL("https://www.gmail.com/");
11419 request2.load_flags = 0;
11420 HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
11422 rv = trans2.Start(&request2, callback.callback(), BoundNetLog());
11423 EXPECT_EQ(ERR_IO_PENDING, rv);
11424 EXPECT_EQ(OK, callback.WaitForResult());
11426 response = trans2.GetResponseInfo();
11427 ASSERT_TRUE(response != NULL);
11428 ASSERT_TRUE(response->headers.get() != NULL);
11429 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
11430 EXPECT_TRUE(response->was_fetched_via_spdy);
11431 EXPECT_TRUE(response->was_npn_negotiated);
11432 ASSERT_EQ(OK, ReadTransaction(&trans2, &response_data));
11433 EXPECT_EQ("hello!", response_data);
11435 #undef MAYBE_UseIPConnectionPooling
11437 TEST_P(HttpNetworkTransactionTest, UseIPConnectionPoolingAfterResolution) {
11438 session_deps_.use_alternate_protocols = true;
11439 session_deps_.next_protos = SpdyNextProtos();
11441 // Set up a special HttpNetworkSession with a MockCachingHostResolver.
11442 session_deps_.host_resolver.reset(new MockCachingHostResolver());
11443 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11444 SpdySessionPoolPeer pool_peer(session->spdy_session_pool());
11445 pool_peer.DisableDomainAuthenticationVerification();
11447 SSLSocketDataProvider ssl(ASYNC, OK);
11448 ssl.SetNextProto(GetParam());
11449 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
11451 scoped_ptr<SpdyFrame> host1_req(
11452 spdy_util_.ConstructSpdyGet("https://www.google.com", false, 1, LOWEST));
11453 scoped_ptr<SpdyFrame> host2_req(
11454 spdy_util_.ConstructSpdyGet("https://www.gmail.com", false, 3, LOWEST));
11455 MockWrite spdy_writes[] = {
11456 CreateMockWrite(*host1_req, 1),
11457 CreateMockWrite(*host2_req, 4),
11459 scoped_ptr<SpdyFrame> host1_resp(
11460 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11461 scoped_ptr<SpdyFrame> host1_resp_body(
11462 spdy_util_.ConstructSpdyBodyFrame(1, true));
11463 scoped_ptr<SpdyFrame> host2_resp(
11464 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
11465 scoped_ptr<SpdyFrame> host2_resp_body(
11466 spdy_util_.ConstructSpdyBodyFrame(3, true));
11467 MockRead spdy_reads[] = {
11468 CreateMockRead(*host1_resp, 2),
11469 CreateMockRead(*host1_resp_body, 3),
11470 CreateMockRead(*host2_resp, 5),
11471 CreateMockRead(*host2_resp_body, 6),
11472 MockRead(ASYNC, 0, 7),
11475 IPAddressNumber ip;
11476 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &ip));
11477 IPEndPoint peer_addr = IPEndPoint(ip, 443);
11478 MockConnect connect(ASYNC, OK, peer_addr);
11479 OrderedSocketData spdy_data(
11480 connect,
11481 spdy_reads, arraysize(spdy_reads),
11482 spdy_writes, arraysize(spdy_writes));
11483 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
11485 TestCompletionCallback callback;
11486 HttpRequestInfo request1;
11487 request1.method = "GET";
11488 request1.url = GURL("https://www.google.com/");
11489 request1.load_flags = 0;
11490 HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
11492 int rv = trans1.Start(&request1, callback.callback(), BoundNetLog());
11493 EXPECT_EQ(ERR_IO_PENDING, rv);
11494 EXPECT_EQ(OK, callback.WaitForResult());
11496 const HttpResponseInfo* response = trans1.GetResponseInfo();
11497 ASSERT_TRUE(response != NULL);
11498 ASSERT_TRUE(response->headers.get() != NULL);
11499 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
11501 std::string response_data;
11502 ASSERT_EQ(OK, ReadTransaction(&trans1, &response_data));
11503 EXPECT_EQ("hello!", response_data);
11505 HttpRequestInfo request2;
11506 request2.method = "GET";
11507 request2.url = GURL("https://www.gmail.com/");
11508 request2.load_flags = 0;
11509 HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
11511 rv = trans2.Start(&request2, callback.callback(), BoundNetLog());
11512 EXPECT_EQ(ERR_IO_PENDING, rv);
11513 EXPECT_EQ(OK, callback.WaitForResult());
11515 response = trans2.GetResponseInfo();
11516 ASSERT_TRUE(response != NULL);
11517 ASSERT_TRUE(response->headers.get() != NULL);
11518 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
11519 EXPECT_TRUE(response->was_fetched_via_spdy);
11520 EXPECT_TRUE(response->was_npn_negotiated);
11521 ASSERT_EQ(OK, ReadTransaction(&trans2, &response_data));
11522 EXPECT_EQ("hello!", response_data);
11525 class OneTimeCachingHostResolver : public net::HostResolver {
11526 public:
11527 explicit OneTimeCachingHostResolver(const HostPortPair& host_port)
11528 : host_port_(host_port) {}
11529 ~OneTimeCachingHostResolver() override {}
11531 RuleBasedHostResolverProc* rules() { return host_resolver_.rules(); }
11533 // HostResolver methods:
11534 int Resolve(const RequestInfo& info,
11535 RequestPriority priority,
11536 AddressList* addresses,
11537 const CompletionCallback& callback,
11538 RequestHandle* out_req,
11539 const BoundNetLog& net_log) override {
11540 return host_resolver_.Resolve(
11541 info, priority, addresses, callback, out_req, net_log);
11544 int ResolveFromCache(const RequestInfo& info,
11545 AddressList* addresses,
11546 const BoundNetLog& net_log) override {
11547 int rv = host_resolver_.ResolveFromCache(info, addresses, net_log);
11548 if (rv == OK && info.host_port_pair().Equals(host_port_))
11549 host_resolver_.GetHostCache()->clear();
11550 return rv;
11553 void CancelRequest(RequestHandle req) override {
11554 host_resolver_.CancelRequest(req);
11557 MockCachingHostResolver* GetMockHostResolver() {
11558 return &host_resolver_;
11561 private:
11562 MockCachingHostResolver host_resolver_;
11563 const HostPortPair host_port_;
11566 // Times out on Win7 dbg(2) bot. http://crbug.com/124776
11567 #if defined(OS_WIN)
11568 #define MAYBE_UseIPConnectionPoolingWithHostCacheExpiration \
11569 DISABLED_UseIPConnectionPoolingWithHostCacheExpiration
11570 #else
11571 #define MAYBE_UseIPConnectionPoolingWithHostCacheExpiration \
11572 UseIPConnectionPoolingWithHostCacheExpiration
11573 #endif
11574 WRAPPED_TEST_P(HttpNetworkTransactionTest,
11575 MAYBE_UseIPConnectionPoolingWithHostCacheExpiration) {
11576 // Times out on Win7 dbg(2) bot. http://crbug.com/124776 . (MAYBE_
11577 // prefix doesn't work with parametrized tests).
11578 #if defined(OS_WIN)
11579 return;
11580 #else
11581 session_deps_.use_alternate_protocols = true;
11582 session_deps_.next_protos = SpdyNextProtos();
11584 // Set up a special HttpNetworkSession with a OneTimeCachingHostResolver.
11585 OneTimeCachingHostResolver host_resolver(HostPortPair("www.gmail.com", 443));
11586 HttpNetworkSession::Params params =
11587 SpdySessionDependencies::CreateSessionParams(&session_deps_);
11588 params.host_resolver = &host_resolver;
11589 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11590 SpdySessionPoolPeer pool_peer(session->spdy_session_pool());
11591 pool_peer.DisableDomainAuthenticationVerification();
11593 SSLSocketDataProvider ssl(ASYNC, OK);
11594 ssl.SetNextProto(GetParam());
11595 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
11597 scoped_ptr<SpdyFrame> host1_req(
11598 spdy_util_.ConstructSpdyGet("https://www.google.com", false, 1, LOWEST));
11599 scoped_ptr<SpdyFrame> host2_req(
11600 spdy_util_.ConstructSpdyGet("https://www.gmail.com", false, 3, LOWEST));
11601 MockWrite spdy_writes[] = {
11602 CreateMockWrite(*host1_req, 1),
11603 CreateMockWrite(*host2_req, 4),
11605 scoped_ptr<SpdyFrame> host1_resp(
11606 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11607 scoped_ptr<SpdyFrame> host1_resp_body(
11608 spdy_util_.ConstructSpdyBodyFrame(1, true));
11609 scoped_ptr<SpdyFrame> host2_resp(
11610 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
11611 scoped_ptr<SpdyFrame> host2_resp_body(
11612 spdy_util_.ConstructSpdyBodyFrame(3, true));
11613 MockRead spdy_reads[] = {
11614 CreateMockRead(*host1_resp, 2),
11615 CreateMockRead(*host1_resp_body, 3),
11616 CreateMockRead(*host2_resp, 5),
11617 CreateMockRead(*host2_resp_body, 6),
11618 MockRead(ASYNC, 0, 7),
11621 IPAddressNumber ip;
11622 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &ip));
11623 IPEndPoint peer_addr = IPEndPoint(ip, 443);
11624 MockConnect connect(ASYNC, OK, peer_addr);
11625 OrderedSocketData spdy_data(
11626 connect,
11627 spdy_reads, arraysize(spdy_reads),
11628 spdy_writes, arraysize(spdy_writes));
11629 session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
11631 TestCompletionCallback callback;
11632 HttpRequestInfo request1;
11633 request1.method = "GET";
11634 request1.url = GURL("https://www.google.com/");
11635 request1.load_flags = 0;
11636 HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
11638 int rv = trans1.Start(&request1, callback.callback(), BoundNetLog());
11639 EXPECT_EQ(ERR_IO_PENDING, rv);
11640 EXPECT_EQ(OK, callback.WaitForResult());
11642 const HttpResponseInfo* response = trans1.GetResponseInfo();
11643 ASSERT_TRUE(response != NULL);
11644 ASSERT_TRUE(response->headers.get() != NULL);
11645 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
11647 std::string response_data;
11648 ASSERT_EQ(OK, ReadTransaction(&trans1, &response_data));
11649 EXPECT_EQ("hello!", response_data);
11651 // Preload cache entries into HostCache.
11652 HostResolver::RequestInfo resolve_info(HostPortPair("www.gmail.com", 443));
11653 AddressList ignored;
11654 rv = host_resolver.Resolve(resolve_info,
11655 DEFAULT_PRIORITY,
11656 &ignored,
11657 callback.callback(),
11658 NULL,
11659 BoundNetLog());
11660 EXPECT_EQ(ERR_IO_PENDING, rv);
11661 rv = callback.WaitForResult();
11662 EXPECT_EQ(OK, rv);
11664 HttpRequestInfo request2;
11665 request2.method = "GET";
11666 request2.url = GURL("https://www.gmail.com/");
11667 request2.load_flags = 0;
11668 HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
11670 rv = trans2.Start(&request2, callback.callback(), BoundNetLog());
11671 EXPECT_EQ(ERR_IO_PENDING, rv);
11672 EXPECT_EQ(OK, callback.WaitForResult());
11674 response = trans2.GetResponseInfo();
11675 ASSERT_TRUE(response != NULL);
11676 ASSERT_TRUE(response->headers.get() != NULL);
11677 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
11678 EXPECT_TRUE(response->was_fetched_via_spdy);
11679 EXPECT_TRUE(response->was_npn_negotiated);
11680 ASSERT_EQ(OK, ReadTransaction(&trans2, &response_data));
11681 EXPECT_EQ("hello!", response_data);
11682 #endif
11684 #undef MAYBE_UseIPConnectionPoolingWithHostCacheExpiration
11686 TEST_P(HttpNetworkTransactionTest, DoNotUseSpdySessionForHttp) {
11687 const std::string https_url = "https://www.google.com:8080/";
11688 const std::string http_url = "http://www.google.com:8080/";
11690 // SPDY GET for HTTPS URL
11691 scoped_ptr<SpdyFrame> req1(
11692 spdy_util_.ConstructSpdyGet(https_url.c_str(), false, 1, LOWEST));
11694 MockWrite writes1[] = {
11695 CreateMockWrite(*req1, 0),
11698 scoped_ptr<SpdyFrame> resp1(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11699 scoped_ptr<SpdyFrame> body1(spdy_util_.ConstructSpdyBodyFrame(1, true));
11700 MockRead reads1[] = {
11701 CreateMockRead(*resp1, 1),
11702 CreateMockRead(*body1, 2),
11703 MockRead(ASYNC, ERR_IO_PENDING, 3)
11706 DelayedSocketData data1(
11707 1, reads1, arraysize(reads1),
11708 writes1, arraysize(writes1));
11709 MockConnect connect_data1(ASYNC, OK);
11710 data1.set_connect_data(connect_data1);
11712 // HTTP GET for the HTTP URL
11713 MockWrite writes2[] = {
11714 MockWrite(ASYNC, 4,
11715 "GET / HTTP/1.1\r\n"
11716 "Host: www.google.com:8080\r\n"
11717 "Connection: keep-alive\r\n\r\n"),
11720 MockRead reads2[] = {
11721 MockRead(ASYNC, 5, "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
11722 MockRead(ASYNC, 6, "hello"),
11723 MockRead(ASYNC, 7, OK),
11726 DelayedSocketData data2(
11727 1, reads2, arraysize(reads2),
11728 writes2, arraysize(writes2));
11730 SSLSocketDataProvider ssl(ASYNC, OK);
11731 ssl.SetNextProto(GetParam());
11732 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
11733 session_deps_.socket_factory->AddSocketDataProvider(&data1);
11734 session_deps_.socket_factory->AddSocketDataProvider(&data2);
11736 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11738 // Start the first transaction to set up the SpdySession
11739 HttpRequestInfo request1;
11740 request1.method = "GET";
11741 request1.url = GURL(https_url);
11742 request1.load_flags = 0;
11743 HttpNetworkTransaction trans1(LOWEST, session.get());
11744 TestCompletionCallback callback1;
11745 EXPECT_EQ(ERR_IO_PENDING,
11746 trans1.Start(&request1, callback1.callback(), BoundNetLog()));
11747 base::MessageLoop::current()->RunUntilIdle();
11749 EXPECT_EQ(OK, callback1.WaitForResult());
11750 EXPECT_TRUE(trans1.GetResponseInfo()->was_fetched_via_spdy);
11752 // Now, start the HTTP request
11753 HttpRequestInfo request2;
11754 request2.method = "GET";
11755 request2.url = GURL(http_url);
11756 request2.load_flags = 0;
11757 HttpNetworkTransaction trans2(MEDIUM, session.get());
11758 TestCompletionCallback callback2;
11759 EXPECT_EQ(ERR_IO_PENDING,
11760 trans2.Start(&request2, callback2.callback(), BoundNetLog()));
11761 base::MessageLoop::current()->RunUntilIdle();
11763 EXPECT_EQ(OK, callback2.WaitForResult());
11764 EXPECT_FALSE(trans2.GetResponseInfo()->was_fetched_via_spdy);
11767 TEST_P(HttpNetworkTransactionTest, DoNotUseSpdySessionForHttpOverTunnel) {
11768 const std::string https_url = "https://www.google.com:8080/";
11769 const std::string http_url = "http://www.google.com:8080/";
11771 // SPDY GET for HTTPS URL (through CONNECT tunnel)
11772 const HostPortPair host_port_pair("www.google.com", 8080);
11773 scoped_ptr<SpdyFrame> connect(
11774 spdy_util_.ConstructSpdyConnect(NULL, 0, 1, LOWEST, host_port_pair));
11775 scoped_ptr<SpdyFrame> req1(
11776 spdy_util_.ConstructSpdyGet(https_url.c_str(), false, 1, LOWEST));
11777 scoped_ptr<SpdyFrame> wrapped_req1(
11778 spdy_util_.ConstructWrappedSpdyFrame(req1, 1));
11780 // SPDY GET for HTTP URL (through the proxy, but not the tunnel).
11781 SpdyHeaderBlock req2_block;
11782 req2_block[spdy_util_.GetMethodKey()] = "GET";
11783 req2_block[spdy_util_.GetPathKey()] = "/";
11784 req2_block[spdy_util_.GetHostKey()] = "www.google.com:8080";
11785 req2_block[spdy_util_.GetSchemeKey()] = "http";
11786 spdy_util_.MaybeAddVersionHeader(&req2_block);
11787 scoped_ptr<SpdyFrame> req2(
11788 spdy_util_.ConstructSpdySyn(3, req2_block, MEDIUM, false, true));
11790 MockWrite writes1[] = {
11791 CreateMockWrite(*connect, 0),
11792 CreateMockWrite(*wrapped_req1, 2),
11793 CreateMockWrite(*req2, 5),
11796 scoped_ptr<SpdyFrame> conn_resp(
11797 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11798 scoped_ptr<SpdyFrame> resp1(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11799 scoped_ptr<SpdyFrame> body1(spdy_util_.ConstructSpdyBodyFrame(1, true));
11800 scoped_ptr<SpdyFrame> wrapped_resp1(
11801 spdy_util_.ConstructWrappedSpdyFrame(resp1, 1));
11802 scoped_ptr<SpdyFrame> wrapped_body1(
11803 spdy_util_.ConstructWrappedSpdyFrame(body1, 1));
11804 scoped_ptr<SpdyFrame> resp2(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
11805 scoped_ptr<SpdyFrame> body2(spdy_util_.ConstructSpdyBodyFrame(3, true));
11806 MockRead reads1[] = {
11807 CreateMockRead(*conn_resp, 1),
11808 CreateMockRead(*wrapped_resp1, 3),
11809 CreateMockRead(*wrapped_body1, 4),
11810 CreateMockRead(*resp2, 6),
11811 CreateMockRead(*body2, 7),
11812 MockRead(ASYNC, ERR_IO_PENDING, 8)
11815 DeterministicSocketData data1(reads1, arraysize(reads1),
11816 writes1, arraysize(writes1));
11817 MockConnect connect_data1(ASYNC, OK);
11818 data1.set_connect_data(connect_data1);
11820 session_deps_.proxy_service.reset(
11821 ProxyService::CreateFixedFromPacResult("HTTPS proxy:70"));
11822 CapturingNetLog log;
11823 session_deps_.net_log = &log;
11824 SSLSocketDataProvider ssl1(ASYNC, OK); // to the proxy
11825 ssl1.SetNextProto(GetParam());
11826 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl1);
11827 SSLSocketDataProvider ssl2(ASYNC, OK); // to the server
11828 ssl2.SetNextProto(GetParam());
11829 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl2);
11830 session_deps_.deterministic_socket_factory->AddSocketDataProvider(&data1);
11832 scoped_refptr<HttpNetworkSession> session(
11833 SpdySessionDependencies::SpdyCreateSessionDeterministic(&session_deps_));
11835 // Start the first transaction to set up the SpdySession
11836 HttpRequestInfo request1;
11837 request1.method = "GET";
11838 request1.url = GURL(https_url);
11839 request1.load_flags = 0;
11840 HttpNetworkTransaction trans1(LOWEST, session.get());
11841 TestCompletionCallback callback1;
11842 EXPECT_EQ(ERR_IO_PENDING,
11843 trans1.Start(&request1, callback1.callback(), BoundNetLog()));
11844 base::MessageLoop::current()->RunUntilIdle();
11845 data1.RunFor(4);
11847 EXPECT_EQ(OK, callback1.WaitForResult());
11848 EXPECT_TRUE(trans1.GetResponseInfo()->was_fetched_via_spdy);
11850 LoadTimingInfo load_timing_info1;
11851 EXPECT_TRUE(trans1.GetLoadTimingInfo(&load_timing_info1));
11852 TestLoadTimingNotReusedWithPac(load_timing_info1,
11853 CONNECT_TIMING_HAS_SSL_TIMES);
11855 // Now, start the HTTP request
11856 HttpRequestInfo request2;
11857 request2.method = "GET";
11858 request2.url = GURL(http_url);
11859 request2.load_flags = 0;
11860 HttpNetworkTransaction trans2(MEDIUM, session.get());
11861 TestCompletionCallback callback2;
11862 EXPECT_EQ(ERR_IO_PENDING,
11863 trans2.Start(&request2, callback2.callback(), BoundNetLog()));
11864 base::MessageLoop::current()->RunUntilIdle();
11865 data1.RunFor(3);
11867 EXPECT_EQ(OK, callback2.WaitForResult());
11868 EXPECT_TRUE(trans2.GetResponseInfo()->was_fetched_via_spdy);
11870 LoadTimingInfo load_timing_info2;
11871 EXPECT_TRUE(trans2.GetLoadTimingInfo(&load_timing_info2));
11872 // The established SPDY sessions is considered reused by the HTTP request.
11873 TestLoadTimingReusedWithPac(load_timing_info2);
11874 // HTTP requests over a SPDY session should have a different connection
11875 // socket_log_id than requests over a tunnel.
11876 EXPECT_NE(load_timing_info1.socket_log_id, load_timing_info2.socket_log_id);
11879 TEST_P(HttpNetworkTransactionTest, UseSpdySessionForHttpWhenForced) {
11880 session_deps_.force_spdy_always = true;
11881 const std::string https_url = "https://www.google.com:8080/";
11882 const std::string http_url = "http://www.google.com:8080/";
11884 // SPDY GET for HTTPS URL
11885 scoped_ptr<SpdyFrame> req1(
11886 spdy_util_.ConstructSpdyGet(https_url.c_str(), false, 1, LOWEST));
11887 // SPDY GET for the HTTP URL
11888 scoped_ptr<SpdyFrame> req2(
11889 spdy_util_.ConstructSpdyGet(http_url.c_str(), false, 3, MEDIUM));
11891 MockWrite writes[] = {
11892 CreateMockWrite(*req1, 1),
11893 CreateMockWrite(*req2, 4),
11896 scoped_ptr<SpdyFrame> resp1(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11897 scoped_ptr<SpdyFrame> body1(spdy_util_.ConstructSpdyBodyFrame(1, true));
11898 scoped_ptr<SpdyFrame> resp2(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 3));
11899 scoped_ptr<SpdyFrame> body2(spdy_util_.ConstructSpdyBodyFrame(3, true));
11900 MockRead reads[] = {
11901 CreateMockRead(*resp1, 2),
11902 CreateMockRead(*body1, 3),
11903 CreateMockRead(*resp2, 5),
11904 CreateMockRead(*body2, 6),
11905 MockRead(ASYNC, ERR_IO_PENDING, 7)
11908 OrderedSocketData data(reads, arraysize(reads),
11909 writes, arraysize(writes));
11911 SSLSocketDataProvider ssl(ASYNC, OK);
11912 ssl.SetNextProto(GetParam());
11913 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
11914 session_deps_.socket_factory->AddSocketDataProvider(&data);
11916 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
11918 // Start the first transaction to set up the SpdySession
11919 HttpRequestInfo request1;
11920 request1.method = "GET";
11921 request1.url = GURL(https_url);
11922 request1.load_flags = 0;
11923 HttpNetworkTransaction trans1(LOWEST, session.get());
11924 TestCompletionCallback callback1;
11925 EXPECT_EQ(ERR_IO_PENDING,
11926 trans1.Start(&request1, callback1.callback(), BoundNetLog()));
11927 base::MessageLoop::current()->RunUntilIdle();
11929 EXPECT_EQ(OK, callback1.WaitForResult());
11930 EXPECT_TRUE(trans1.GetResponseInfo()->was_fetched_via_spdy);
11932 // Now, start the HTTP request
11933 HttpRequestInfo request2;
11934 request2.method = "GET";
11935 request2.url = GURL(http_url);
11936 request2.load_flags = 0;
11937 HttpNetworkTransaction trans2(MEDIUM, session.get());
11938 TestCompletionCallback callback2;
11939 EXPECT_EQ(ERR_IO_PENDING,
11940 trans2.Start(&request2, callback2.callback(), BoundNetLog()));
11941 base::MessageLoop::current()->RunUntilIdle();
11943 EXPECT_EQ(OK, callback2.WaitForResult());
11944 EXPECT_TRUE(trans2.GetResponseInfo()->was_fetched_via_spdy);
11947 // Test that in the case where we have a SPDY session to a SPDY proxy
11948 // that we do not pool other origins that resolve to the same IP when
11949 // the certificate does not match the new origin.
11950 // http://crbug.com/134690
11951 TEST_P(HttpNetworkTransactionTest, DoNotUseSpdySessionIfCertDoesNotMatch) {
11952 const std::string url1 = "http://www.google.com/";
11953 const std::string url2 = "https://mail.google.com/";
11954 const std::string ip_addr = "1.2.3.4";
11956 // SPDY GET for HTTP URL (through SPDY proxy)
11957 scoped_ptr<SpdyHeaderBlock> headers(
11958 spdy_util_.ConstructGetHeaderBlockForProxy("http://www.google.com/"));
11959 scoped_ptr<SpdyFrame> req1(
11960 spdy_util_.ConstructSpdySyn(1, *headers, LOWEST, false, true));
11962 MockWrite writes1[] = {
11963 CreateMockWrite(*req1, 0),
11966 scoped_ptr<SpdyFrame> resp1(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11967 scoped_ptr<SpdyFrame> body1(spdy_util_.ConstructSpdyBodyFrame(1, true));
11968 MockRead reads1[] = {
11969 CreateMockRead(*resp1, 1),
11970 CreateMockRead(*body1, 2),
11971 MockRead(ASYNC, OK, 3) // EOF
11974 scoped_ptr<DeterministicSocketData> data1(
11975 new DeterministicSocketData(reads1, arraysize(reads1),
11976 writes1, arraysize(writes1)));
11977 IPAddressNumber ip;
11978 ASSERT_TRUE(ParseIPLiteralToNumber(ip_addr, &ip));
11979 IPEndPoint peer_addr = IPEndPoint(ip, 443);
11980 MockConnect connect_data1(ASYNC, OK, peer_addr);
11981 data1->set_connect_data(connect_data1);
11983 // SPDY GET for HTTPS URL (direct)
11984 scoped_ptr<SpdyFrame> req2(
11985 spdy_util_.ConstructSpdyGet(url2.c_str(), false, 1, MEDIUM));
11987 MockWrite writes2[] = {
11988 CreateMockWrite(*req2, 0),
11991 scoped_ptr<SpdyFrame> resp2(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
11992 scoped_ptr<SpdyFrame> body2(spdy_util_.ConstructSpdyBodyFrame(1, true));
11993 MockRead reads2[] = {
11994 CreateMockRead(*resp2, 1),
11995 CreateMockRead(*body2, 2),
11996 MockRead(ASYNC, OK, 3) // EOF
11999 scoped_ptr<DeterministicSocketData> data2(
12000 new DeterministicSocketData(reads2, arraysize(reads2),
12001 writes2, arraysize(writes2)));
12002 MockConnect connect_data2(ASYNC, OK);
12003 data2->set_connect_data(connect_data2);
12005 // Set up a proxy config that sends HTTP requests to a proxy, and
12006 // all others direct.
12007 ProxyConfig proxy_config;
12008 proxy_config.proxy_rules().ParseFromString("http=https://proxy:443");
12009 CapturingProxyResolver* capturing_proxy_resolver =
12010 new CapturingProxyResolver();
12011 session_deps_.proxy_service.reset(new ProxyService(
12012 new ProxyConfigServiceFixed(proxy_config), capturing_proxy_resolver,
12013 NULL));
12015 // Load a valid cert. Note, that this does not need to
12016 // be valid for proxy because the MockSSLClientSocket does
12017 // not actually verify it. But SpdySession will use this
12018 // to see if it is valid for the new origin
12019 base::FilePath certs_dir = GetTestCertsDirectory();
12020 scoped_refptr<X509Certificate> server_cert(
12021 ImportCertFromFile(certs_dir, "ok_cert.pem"));
12022 ASSERT_NE(static_cast<X509Certificate*>(NULL), server_cert.get());
12024 SSLSocketDataProvider ssl1(ASYNC, OK); // to the proxy
12025 ssl1.SetNextProto(GetParam());
12026 ssl1.cert = server_cert;
12027 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl1);
12028 session_deps_.deterministic_socket_factory->AddSocketDataProvider(
12029 data1.get());
12031 SSLSocketDataProvider ssl2(ASYNC, OK); // to the server
12032 ssl2.SetNextProto(GetParam());
12033 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl2);
12034 session_deps_.deterministic_socket_factory->AddSocketDataProvider(
12035 data2.get());
12037 session_deps_.host_resolver.reset(new MockCachingHostResolver());
12038 session_deps_.host_resolver->rules()->AddRule("mail.google.com", ip_addr);
12039 session_deps_.host_resolver->rules()->AddRule("proxy", ip_addr);
12041 scoped_refptr<HttpNetworkSession> session(
12042 SpdySessionDependencies::SpdyCreateSessionDeterministic(&session_deps_));
12044 // Start the first transaction to set up the SpdySession
12045 HttpRequestInfo request1;
12046 request1.method = "GET";
12047 request1.url = GURL(url1);
12048 request1.load_flags = 0;
12049 HttpNetworkTransaction trans1(LOWEST, session.get());
12050 TestCompletionCallback callback1;
12051 ASSERT_EQ(ERR_IO_PENDING,
12052 trans1.Start(&request1, callback1.callback(), BoundNetLog()));
12053 data1->RunFor(3);
12055 ASSERT_TRUE(callback1.have_result());
12056 EXPECT_EQ(OK, callback1.WaitForResult());
12057 EXPECT_TRUE(trans1.GetResponseInfo()->was_fetched_via_spdy);
12059 // Now, start the HTTP request
12060 HttpRequestInfo request2;
12061 request2.method = "GET";
12062 request2.url = GURL(url2);
12063 request2.load_flags = 0;
12064 HttpNetworkTransaction trans2(MEDIUM, session.get());
12065 TestCompletionCallback callback2;
12066 EXPECT_EQ(ERR_IO_PENDING,
12067 trans2.Start(&request2, callback2.callback(), BoundNetLog()));
12068 base::MessageLoop::current()->RunUntilIdle();
12069 data2->RunFor(3);
12071 ASSERT_TRUE(callback2.have_result());
12072 EXPECT_EQ(OK, callback2.WaitForResult());
12073 EXPECT_TRUE(trans2.GetResponseInfo()->was_fetched_via_spdy);
12076 // Test to verify that a failed socket read (due to an ERR_CONNECTION_CLOSED
12077 // error) in SPDY session, removes the socket from pool and closes the SPDY
12078 // session. Verify that new url's from the same HttpNetworkSession (and a new
12079 // SpdySession) do work. http://crbug.com/224701
12080 TEST_P(HttpNetworkTransactionTest, ErrorSocketNotConnected) {
12081 const std::string https_url = "https://www.google.com/";
12083 MockRead reads1[] = {
12084 MockRead(SYNCHRONOUS, ERR_CONNECTION_CLOSED, 0)
12087 scoped_ptr<DeterministicSocketData> data1(
12088 new DeterministicSocketData(reads1, arraysize(reads1), NULL, 0));
12089 data1->SetStop(1);
12091 scoped_ptr<SpdyFrame> req2(
12092 spdy_util_.ConstructSpdyGet(https_url.c_str(), false, 1, MEDIUM));
12093 MockWrite writes2[] = {
12094 CreateMockWrite(*req2, 0),
12097 scoped_ptr<SpdyFrame> resp2(spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
12098 scoped_ptr<SpdyFrame> body2(spdy_util_.ConstructSpdyBodyFrame(1, true));
12099 MockRead reads2[] = {
12100 CreateMockRead(*resp2, 1),
12101 CreateMockRead(*body2, 2),
12102 MockRead(ASYNC, OK, 3) // EOF
12105 scoped_ptr<DeterministicSocketData> data2(
12106 new DeterministicSocketData(reads2, arraysize(reads2),
12107 writes2, arraysize(writes2)));
12109 SSLSocketDataProvider ssl1(ASYNC, OK);
12110 ssl1.SetNextProto(GetParam());
12111 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl1);
12112 session_deps_.deterministic_socket_factory->AddSocketDataProvider(
12113 data1.get());
12115 SSLSocketDataProvider ssl2(ASYNC, OK);
12116 ssl2.SetNextProto(GetParam());
12117 session_deps_.deterministic_socket_factory->AddSSLSocketDataProvider(&ssl2);
12118 session_deps_.deterministic_socket_factory->AddSocketDataProvider(
12119 data2.get());
12121 scoped_refptr<HttpNetworkSession> session(
12122 SpdySessionDependencies::SpdyCreateSessionDeterministic(&session_deps_));
12124 // Start the first transaction to set up the SpdySession and verify that
12125 // connection was closed.
12126 HttpRequestInfo request1;
12127 request1.method = "GET";
12128 request1.url = GURL(https_url);
12129 request1.load_flags = 0;
12130 HttpNetworkTransaction trans1(MEDIUM, session.get());
12131 TestCompletionCallback callback1;
12132 EXPECT_EQ(ERR_IO_PENDING,
12133 trans1.Start(&request1, callback1.callback(), BoundNetLog()));
12134 base::MessageLoop::current()->RunUntilIdle();
12135 EXPECT_EQ(ERR_CONNECTION_CLOSED, callback1.WaitForResult());
12137 // Now, start the second request and make sure it succeeds.
12138 HttpRequestInfo request2;
12139 request2.method = "GET";
12140 request2.url = GURL(https_url);
12141 request2.load_flags = 0;
12142 HttpNetworkTransaction trans2(MEDIUM, session.get());
12143 TestCompletionCallback callback2;
12144 EXPECT_EQ(ERR_IO_PENDING,
12145 trans2.Start(&request2, callback2.callback(), BoundNetLog()));
12146 base::MessageLoop::current()->RunUntilIdle();
12147 data2->RunFor(3);
12149 ASSERT_TRUE(callback2.have_result());
12150 EXPECT_EQ(OK, callback2.WaitForResult());
12151 EXPECT_TRUE(trans2.GetResponseInfo()->was_fetched_via_spdy);
12154 TEST_P(HttpNetworkTransactionTest, CloseIdleSpdySessionToOpenNewOne) {
12155 session_deps_.next_protos = SpdyNextProtos();
12156 ClientSocketPoolManager::set_max_sockets_per_group(
12157 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
12158 ClientSocketPoolManager::set_max_sockets_per_pool(
12159 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
12161 // Use two different hosts with different IPs so they don't get pooled.
12162 session_deps_.host_resolver->rules()->AddRule("www.a.com", "10.0.0.1");
12163 session_deps_.host_resolver->rules()->AddRule("www.b.com", "10.0.0.2");
12164 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12166 SSLSocketDataProvider ssl1(ASYNC, OK);
12167 ssl1.SetNextProto(GetParam());
12168 SSLSocketDataProvider ssl2(ASYNC, OK);
12169 ssl2.SetNextProto(GetParam());
12170 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
12171 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
12173 scoped_ptr<SpdyFrame> host1_req(spdy_util_.ConstructSpdyGet(
12174 "https://www.a.com", false, 1, DEFAULT_PRIORITY));
12175 MockWrite spdy1_writes[] = {
12176 CreateMockWrite(*host1_req, 1),
12178 scoped_ptr<SpdyFrame> host1_resp(
12179 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
12180 scoped_ptr<SpdyFrame> host1_resp_body(
12181 spdy_util_.ConstructSpdyBodyFrame(1, true));
12182 MockRead spdy1_reads[] = {
12183 CreateMockRead(*host1_resp, 2),
12184 CreateMockRead(*host1_resp_body, 3),
12185 MockRead(ASYNC, ERR_IO_PENDING, 4),
12188 scoped_ptr<OrderedSocketData> spdy1_data(
12189 new OrderedSocketData(
12190 spdy1_reads, arraysize(spdy1_reads),
12191 spdy1_writes, arraysize(spdy1_writes)));
12192 session_deps_.socket_factory->AddSocketDataProvider(spdy1_data.get());
12194 scoped_ptr<SpdyFrame> host2_req(spdy_util_.ConstructSpdyGet(
12195 "https://www.b.com", false, 1, DEFAULT_PRIORITY));
12196 MockWrite spdy2_writes[] = {
12197 CreateMockWrite(*host2_req, 1),
12199 scoped_ptr<SpdyFrame> host2_resp(
12200 spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1));
12201 scoped_ptr<SpdyFrame> host2_resp_body(
12202 spdy_util_.ConstructSpdyBodyFrame(1, true));
12203 MockRead spdy2_reads[] = {
12204 CreateMockRead(*host2_resp, 2),
12205 CreateMockRead(*host2_resp_body, 3),
12206 MockRead(ASYNC, ERR_IO_PENDING, 4),
12209 scoped_ptr<OrderedSocketData> spdy2_data(
12210 new OrderedSocketData(
12211 spdy2_reads, arraysize(spdy2_reads),
12212 spdy2_writes, arraysize(spdy2_writes)));
12213 session_deps_.socket_factory->AddSocketDataProvider(spdy2_data.get());
12215 MockWrite http_write[] = {
12216 MockWrite("GET / HTTP/1.1\r\n"
12217 "Host: www.a.com\r\n"
12218 "Connection: keep-alive\r\n\r\n"),
12221 MockRead http_read[] = {
12222 MockRead("HTTP/1.1 200 OK\r\n"),
12223 MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
12224 MockRead("Content-Length: 6\r\n\r\n"),
12225 MockRead("hello!"),
12227 StaticSocketDataProvider http_data(http_read, arraysize(http_read),
12228 http_write, arraysize(http_write));
12229 session_deps_.socket_factory->AddSocketDataProvider(&http_data);
12231 HostPortPair host_port_pair_a("www.a.com", 443);
12232 SpdySessionKey spdy_session_key_a(
12233 host_port_pair_a, ProxyServer::Direct(), PRIVACY_MODE_DISABLED);
12234 EXPECT_FALSE(
12235 HasSpdySession(session->spdy_session_pool(), spdy_session_key_a));
12237 TestCompletionCallback callback;
12238 HttpRequestInfo request1;
12239 request1.method = "GET";
12240 request1.url = GURL("https://www.a.com/");
12241 request1.load_flags = 0;
12242 scoped_ptr<HttpNetworkTransaction> trans(
12243 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12245 int rv = trans->Start(&request1, callback.callback(), BoundNetLog());
12246 EXPECT_EQ(ERR_IO_PENDING, rv);
12247 EXPECT_EQ(OK, callback.WaitForResult());
12249 const HttpResponseInfo* response = trans->GetResponseInfo();
12250 ASSERT_TRUE(response != NULL);
12251 ASSERT_TRUE(response->headers.get() != NULL);
12252 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
12253 EXPECT_TRUE(response->was_fetched_via_spdy);
12254 EXPECT_TRUE(response->was_npn_negotiated);
12256 std::string response_data;
12257 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
12258 EXPECT_EQ("hello!", response_data);
12259 trans.reset();
12260 EXPECT_TRUE(
12261 HasSpdySession(session->spdy_session_pool(), spdy_session_key_a));
12263 HostPortPair host_port_pair_b("www.b.com", 443);
12264 SpdySessionKey spdy_session_key_b(
12265 host_port_pair_b, ProxyServer::Direct(), PRIVACY_MODE_DISABLED);
12266 EXPECT_FALSE(
12267 HasSpdySession(session->spdy_session_pool(), spdy_session_key_b));
12268 HttpRequestInfo request2;
12269 request2.method = "GET";
12270 request2.url = GURL("https://www.b.com/");
12271 request2.load_flags = 0;
12272 trans.reset(new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12274 rv = trans->Start(&request2, callback.callback(), BoundNetLog());
12275 EXPECT_EQ(ERR_IO_PENDING, rv);
12276 EXPECT_EQ(OK, callback.WaitForResult());
12278 response = trans->GetResponseInfo();
12279 ASSERT_TRUE(response != NULL);
12280 ASSERT_TRUE(response->headers.get() != NULL);
12281 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
12282 EXPECT_TRUE(response->was_fetched_via_spdy);
12283 EXPECT_TRUE(response->was_npn_negotiated);
12284 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
12285 EXPECT_EQ("hello!", response_data);
12286 EXPECT_FALSE(
12287 HasSpdySession(session->spdy_session_pool(), spdy_session_key_a));
12288 EXPECT_TRUE(
12289 HasSpdySession(session->spdy_session_pool(), spdy_session_key_b));
12291 HostPortPair host_port_pair_a1("www.a.com", 80);
12292 SpdySessionKey spdy_session_key_a1(
12293 host_port_pair_a1, ProxyServer::Direct(), PRIVACY_MODE_DISABLED);
12294 EXPECT_FALSE(
12295 HasSpdySession(session->spdy_session_pool(), spdy_session_key_a1));
12296 HttpRequestInfo request3;
12297 request3.method = "GET";
12298 request3.url = GURL("http://www.a.com/");
12299 request3.load_flags = 0;
12300 trans.reset(new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12302 rv = trans->Start(&request3, callback.callback(), BoundNetLog());
12303 EXPECT_EQ(ERR_IO_PENDING, rv);
12304 EXPECT_EQ(OK, callback.WaitForResult());
12306 response = trans->GetResponseInfo();
12307 ASSERT_TRUE(response != NULL);
12308 ASSERT_TRUE(response->headers.get() != NULL);
12309 EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
12310 EXPECT_FALSE(response->was_fetched_via_spdy);
12311 EXPECT_FALSE(response->was_npn_negotiated);
12312 ASSERT_EQ(OK, ReadTransaction(trans.get(), &response_data));
12313 EXPECT_EQ("hello!", response_data);
12314 EXPECT_FALSE(
12315 HasSpdySession(session->spdy_session_pool(), spdy_session_key_a));
12316 EXPECT_FALSE(
12317 HasSpdySession(session->spdy_session_pool(), spdy_session_key_b));
12320 TEST_P(HttpNetworkTransactionTest, HttpSyncConnectError) {
12321 HttpRequestInfo request;
12322 request.method = "GET";
12323 request.url = GURL("http://www.google.com/");
12324 request.load_flags = 0;
12326 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12327 scoped_ptr<HttpTransaction> trans(
12328 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12330 MockConnect mock_connect(SYNCHRONOUS, ERR_CONNECTION_REFUSED);
12331 StaticSocketDataProvider data;
12332 data.set_connect_data(mock_connect);
12333 session_deps_.socket_factory->AddSocketDataProvider(&data);
12335 TestCompletionCallback callback;
12337 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
12338 EXPECT_EQ(ERR_IO_PENDING, rv);
12340 rv = callback.WaitForResult();
12341 EXPECT_EQ(ERR_CONNECTION_REFUSED, rv);
12343 EXPECT_EQ(NULL, trans->GetResponseInfo());
12345 // We don't care whether this succeeds or fails, but it shouldn't crash.
12346 HttpRequestHeaders request_headers;
12347 trans->GetFullRequestHeaders(&request_headers);
12350 TEST_P(HttpNetworkTransactionTest, HttpAsyncConnectError) {
12351 HttpRequestInfo request;
12352 request.method = "GET";
12353 request.url = GURL("http://www.google.com/");
12354 request.load_flags = 0;
12356 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12357 scoped_ptr<HttpTransaction> trans(
12358 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12360 MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
12361 StaticSocketDataProvider data;
12362 data.set_connect_data(mock_connect);
12363 session_deps_.socket_factory->AddSocketDataProvider(&data);
12365 TestCompletionCallback callback;
12367 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
12368 EXPECT_EQ(ERR_IO_PENDING, rv);
12370 rv = callback.WaitForResult();
12371 EXPECT_EQ(ERR_CONNECTION_REFUSED, rv);
12373 EXPECT_EQ(NULL, trans->GetResponseInfo());
12375 // We don't care whether this succeeds or fails, but it shouldn't crash.
12376 HttpRequestHeaders request_headers;
12377 trans->GetFullRequestHeaders(&request_headers);
12380 TEST_P(HttpNetworkTransactionTest, HttpSyncWriteError) {
12381 HttpRequestInfo request;
12382 request.method = "GET";
12383 request.url = GURL("http://www.google.com/");
12384 request.load_flags = 0;
12386 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12387 scoped_ptr<HttpTransaction> trans(
12388 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12390 MockWrite data_writes[] = {
12391 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
12393 MockRead data_reads[] = {
12394 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
12397 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
12398 data_writes, arraysize(data_writes));
12399 session_deps_.socket_factory->AddSocketDataProvider(&data);
12401 TestCompletionCallback callback;
12403 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
12404 EXPECT_EQ(ERR_IO_PENDING, rv);
12406 rv = callback.WaitForResult();
12407 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
12409 EXPECT_EQ(NULL, trans->GetResponseInfo());
12411 HttpRequestHeaders request_headers;
12412 EXPECT_TRUE(trans->GetFullRequestHeaders(&request_headers));
12413 EXPECT_TRUE(request_headers.HasHeader("Host"));
12416 TEST_P(HttpNetworkTransactionTest, HttpAsyncWriteError) {
12417 HttpRequestInfo request;
12418 request.method = "GET";
12419 request.url = GURL("http://www.google.com/");
12420 request.load_flags = 0;
12422 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12423 scoped_ptr<HttpTransaction> trans(
12424 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12426 MockWrite data_writes[] = {
12427 MockWrite(ASYNC, ERR_CONNECTION_RESET),
12429 MockRead data_reads[] = {
12430 MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
12433 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
12434 data_writes, arraysize(data_writes));
12435 session_deps_.socket_factory->AddSocketDataProvider(&data);
12437 TestCompletionCallback callback;
12439 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
12440 EXPECT_EQ(ERR_IO_PENDING, rv);
12442 rv = callback.WaitForResult();
12443 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
12445 EXPECT_EQ(NULL, trans->GetResponseInfo());
12447 HttpRequestHeaders request_headers;
12448 EXPECT_TRUE(trans->GetFullRequestHeaders(&request_headers));
12449 EXPECT_TRUE(request_headers.HasHeader("Host"));
12452 TEST_P(HttpNetworkTransactionTest, HttpSyncReadError) {
12453 HttpRequestInfo request;
12454 request.method = "GET";
12455 request.url = GURL("http://www.google.com/");
12456 request.load_flags = 0;
12458 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12459 scoped_ptr<HttpTransaction> trans(
12460 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12462 MockWrite data_writes[] = {
12463 MockWrite("GET / HTTP/1.1\r\n"
12464 "Host: www.google.com\r\n"
12465 "Connection: keep-alive\r\n\r\n"),
12467 MockRead data_reads[] = {
12468 MockRead(SYNCHRONOUS, ERR_CONNECTION_RESET),
12471 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
12472 data_writes, arraysize(data_writes));
12473 session_deps_.socket_factory->AddSocketDataProvider(&data);
12475 TestCompletionCallback callback;
12477 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
12478 EXPECT_EQ(ERR_IO_PENDING, rv);
12480 rv = callback.WaitForResult();
12481 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
12483 EXPECT_EQ(NULL, trans->GetResponseInfo());
12485 HttpRequestHeaders request_headers;
12486 EXPECT_TRUE(trans->GetFullRequestHeaders(&request_headers));
12487 EXPECT_TRUE(request_headers.HasHeader("Host"));
12490 TEST_P(HttpNetworkTransactionTest, HttpAsyncReadError) {
12491 HttpRequestInfo request;
12492 request.method = "GET";
12493 request.url = GURL("http://www.google.com/");
12494 request.load_flags = 0;
12496 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12497 scoped_ptr<HttpTransaction> trans(
12498 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12500 MockWrite data_writes[] = {
12501 MockWrite("GET / HTTP/1.1\r\n"
12502 "Host: www.google.com\r\n"
12503 "Connection: keep-alive\r\n\r\n"),
12505 MockRead data_reads[] = {
12506 MockRead(ASYNC, ERR_CONNECTION_RESET),
12509 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
12510 data_writes, arraysize(data_writes));
12511 session_deps_.socket_factory->AddSocketDataProvider(&data);
12513 TestCompletionCallback callback;
12515 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
12516 EXPECT_EQ(ERR_IO_PENDING, rv);
12518 rv = callback.WaitForResult();
12519 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
12521 EXPECT_EQ(NULL, trans->GetResponseInfo());
12523 HttpRequestHeaders request_headers;
12524 EXPECT_TRUE(trans->GetFullRequestHeaders(&request_headers));
12525 EXPECT_TRUE(request_headers.HasHeader("Host"));
12528 TEST_P(HttpNetworkTransactionTest, GetFullRequestHeadersIncludesExtraHeader) {
12529 HttpRequestInfo request;
12530 request.method = "GET";
12531 request.url = GURL("http://www.google.com/");
12532 request.load_flags = 0;
12533 request.extra_headers.SetHeader("X-Foo", "bar");
12535 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12536 scoped_ptr<HttpTransaction> trans(
12537 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
12539 MockWrite data_writes[] = {
12540 MockWrite("GET / HTTP/1.1\r\n"
12541 "Host: www.google.com\r\n"
12542 "Connection: keep-alive\r\n"
12543 "X-Foo: bar\r\n\r\n"),
12545 MockRead data_reads[] = {
12546 MockRead("HTTP/1.1 200 OK\r\n"
12547 "Content-Length: 5\r\n\r\n"
12548 "hello"),
12549 MockRead(ASYNC, ERR_UNEXPECTED),
12552 StaticSocketDataProvider data(data_reads, arraysize(data_reads),
12553 data_writes, arraysize(data_writes));
12554 session_deps_.socket_factory->AddSocketDataProvider(&data);
12556 TestCompletionCallback callback;
12558 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
12559 EXPECT_EQ(ERR_IO_PENDING, rv);
12561 rv = callback.WaitForResult();
12562 EXPECT_EQ(OK, rv);
12564 HttpRequestHeaders request_headers;
12565 EXPECT_TRUE(trans->GetFullRequestHeaders(&request_headers));
12566 std::string foo;
12567 EXPECT_TRUE(request_headers.GetHeader("X-Foo", &foo));
12568 EXPECT_EQ("bar", foo);
12571 namespace {
12573 // Fake HttpStream that simply records calls to SetPriority().
12574 class FakeStream : public HttpStream,
12575 public base::SupportsWeakPtr<FakeStream> {
12576 public:
12577 explicit FakeStream(RequestPriority priority) : priority_(priority) {}
12578 ~FakeStream() override {}
12580 RequestPriority priority() const { return priority_; }
12582 int InitializeStream(const HttpRequestInfo* request_info,
12583 RequestPriority priority,
12584 const BoundNetLog& net_log,
12585 const CompletionCallback& callback) override {
12586 return ERR_IO_PENDING;
12589 int SendRequest(const HttpRequestHeaders& request_headers,
12590 HttpResponseInfo* response,
12591 const CompletionCallback& callback) override {
12592 ADD_FAILURE();
12593 return ERR_UNEXPECTED;
12596 int ReadResponseHeaders(const CompletionCallback& callback) override {
12597 ADD_FAILURE();
12598 return ERR_UNEXPECTED;
12601 int ReadResponseBody(IOBuffer* buf,
12602 int buf_len,
12603 const CompletionCallback& callback) override {
12604 ADD_FAILURE();
12605 return ERR_UNEXPECTED;
12608 void Close(bool not_reusable) override {}
12610 bool IsResponseBodyComplete() const override {
12611 ADD_FAILURE();
12612 return false;
12615 bool CanFindEndOfResponse() const override { return false; }
12617 bool IsConnectionReused() const override {
12618 ADD_FAILURE();
12619 return false;
12622 void SetConnectionReused() override { ADD_FAILURE(); }
12624 bool IsConnectionReusable() const override {
12625 ADD_FAILURE();
12626 return false;
12629 int64 GetTotalReceivedBytes() const override {
12630 ADD_FAILURE();
12631 return 0;
12634 bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const override {
12635 ADD_FAILURE();
12636 return false;
12639 void GetSSLInfo(SSLInfo* ssl_info) override { ADD_FAILURE(); }
12641 void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override {
12642 ADD_FAILURE();
12645 bool IsSpdyHttpStream() const override {
12646 ADD_FAILURE();
12647 return false;
12650 void Drain(HttpNetworkSession* session) override { ADD_FAILURE(); }
12652 void SetPriority(RequestPriority priority) override { priority_ = priority; }
12654 UploadProgress GetUploadProgress() const override { return UploadProgress(); }
12656 HttpStream* RenewStreamForAuth() override { return NULL; }
12658 private:
12659 RequestPriority priority_;
12661 DISALLOW_COPY_AND_ASSIGN(FakeStream);
12664 // Fake HttpStreamRequest that simply records calls to SetPriority()
12665 // and vends FakeStreams with its current priority.
12666 class FakeStreamRequest : public HttpStreamRequest,
12667 public base::SupportsWeakPtr<FakeStreamRequest> {
12668 public:
12669 FakeStreamRequest(RequestPriority priority,
12670 HttpStreamRequest::Delegate* delegate)
12671 : priority_(priority),
12672 delegate_(delegate),
12673 websocket_stream_create_helper_(NULL) {}
12675 FakeStreamRequest(RequestPriority priority,
12676 HttpStreamRequest::Delegate* delegate,
12677 WebSocketHandshakeStreamBase::CreateHelper* create_helper)
12678 : priority_(priority),
12679 delegate_(delegate),
12680 websocket_stream_create_helper_(create_helper) {}
12682 ~FakeStreamRequest() override {}
12684 RequestPriority priority() const { return priority_; }
12686 const WebSocketHandshakeStreamBase::CreateHelper*
12687 websocket_stream_create_helper() const {
12688 return websocket_stream_create_helper_;
12691 // Create a new FakeStream and pass it to the request's
12692 // delegate. Returns a weak pointer to the FakeStream.
12693 base::WeakPtr<FakeStream> FinishStreamRequest() {
12694 FakeStream* fake_stream = new FakeStream(priority_);
12695 // Do this before calling OnStreamReady() as OnStreamReady() may
12696 // immediately delete |fake_stream|.
12697 base::WeakPtr<FakeStream> weak_stream = fake_stream->AsWeakPtr();
12698 delegate_->OnStreamReady(SSLConfig(), ProxyInfo(), fake_stream);
12699 return weak_stream;
12702 int RestartTunnelWithProxyAuth(const AuthCredentials& credentials) override {
12703 ADD_FAILURE();
12704 return ERR_UNEXPECTED;
12707 LoadState GetLoadState() const override {
12708 ADD_FAILURE();
12709 return LoadState();
12712 void SetPriority(RequestPriority priority) override { priority_ = priority; }
12714 bool was_npn_negotiated() const override { return false; }
12716 NextProto protocol_negotiated() const override { return kProtoUnknown; }
12718 bool using_spdy() const override { return false; }
12720 private:
12721 RequestPriority priority_;
12722 HttpStreamRequest::Delegate* const delegate_;
12723 WebSocketHandshakeStreamBase::CreateHelper* websocket_stream_create_helper_;
12725 DISALLOW_COPY_AND_ASSIGN(FakeStreamRequest);
12728 // Fake HttpStreamFactory that vends FakeStreamRequests.
12729 class FakeStreamFactory : public HttpStreamFactory {
12730 public:
12731 FakeStreamFactory() {}
12732 ~FakeStreamFactory() override {}
12734 // Returns a WeakPtr<> to the last HttpStreamRequest returned by
12735 // RequestStream() (which may be NULL if it was destroyed already).
12736 base::WeakPtr<FakeStreamRequest> last_stream_request() {
12737 return last_stream_request_;
12740 HttpStreamRequest* RequestStream(const HttpRequestInfo& info,
12741 RequestPriority priority,
12742 const SSLConfig& server_ssl_config,
12743 const SSLConfig& proxy_ssl_config,
12744 HttpStreamRequest::Delegate* delegate,
12745 const BoundNetLog& net_log) override {
12746 FakeStreamRequest* fake_request = new FakeStreamRequest(priority, delegate);
12747 last_stream_request_ = fake_request->AsWeakPtr();
12748 return fake_request;
12751 HttpStreamRequest* RequestWebSocketHandshakeStream(
12752 const HttpRequestInfo& info,
12753 RequestPriority priority,
12754 const SSLConfig& server_ssl_config,
12755 const SSLConfig& proxy_ssl_config,
12756 HttpStreamRequest::Delegate* delegate,
12757 WebSocketHandshakeStreamBase::CreateHelper* create_helper,
12758 const BoundNetLog& net_log) override {
12759 FakeStreamRequest* fake_request =
12760 new FakeStreamRequest(priority, delegate, create_helper);
12761 last_stream_request_ = fake_request->AsWeakPtr();
12762 return fake_request;
12765 void PreconnectStreams(int num_streams,
12766 const HttpRequestInfo& info,
12767 RequestPriority priority,
12768 const SSLConfig& server_ssl_config,
12769 const SSLConfig& proxy_ssl_config) override {
12770 ADD_FAILURE();
12773 const HostMappingRules* GetHostMappingRules() const override {
12774 ADD_FAILURE();
12775 return NULL;
12778 private:
12779 base::WeakPtr<FakeStreamRequest> last_stream_request_;
12781 DISALLOW_COPY_AND_ASSIGN(FakeStreamFactory);
12784 // TODO(ricea): Maybe unify this with the one in
12785 // url_request_http_job_unittest.cc ?
12786 class FakeWebSocketBasicHandshakeStream : public WebSocketHandshakeStreamBase {
12787 public:
12788 FakeWebSocketBasicHandshakeStream(scoped_ptr<ClientSocketHandle> connection,
12789 bool using_proxy)
12790 : state_(connection.release(), using_proxy) {}
12792 // Fake implementation of HttpStreamBase methods.
12793 // This ends up being quite "real" because this object has to really send data
12794 // on the mock socket. It might be easier to use the real implementation, but
12795 // the fact that the WebSocket code is not compiled on iOS makes that
12796 // difficult.
12797 int InitializeStream(const HttpRequestInfo* request_info,
12798 RequestPriority priority,
12799 const BoundNetLog& net_log,
12800 const CompletionCallback& callback) override {
12801 state_.Initialize(request_info, priority, net_log, callback);
12802 return OK;
12805 int SendRequest(const HttpRequestHeaders& request_headers,
12806 HttpResponseInfo* response,
12807 const CompletionCallback& callback) override {
12808 return parser()->SendRequest(state_.GenerateRequestLine(), request_headers,
12809 response, callback);
12812 int ReadResponseHeaders(const CompletionCallback& callback) override {
12813 return parser()->ReadResponseHeaders(callback);
12816 int ReadResponseBody(IOBuffer* buf,
12817 int buf_len,
12818 const CompletionCallback& callback) override {
12819 NOTREACHED();
12820 return ERR_IO_PENDING;
12823 void Close(bool not_reusable) override {
12824 if (parser())
12825 parser()->Close(true);
12828 bool IsResponseBodyComplete() const override {
12829 NOTREACHED();
12830 return false;
12833 bool CanFindEndOfResponse() const override {
12834 return parser()->CanFindEndOfResponse();
12837 bool IsConnectionReused() const override {
12838 NOTREACHED();
12839 return false;
12841 void SetConnectionReused() override { NOTREACHED(); }
12843 bool IsConnectionReusable() const override {
12844 NOTREACHED();
12845 return false;
12848 int64 GetTotalReceivedBytes() const override {
12849 NOTREACHED();
12850 return 0;
12853 bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const override {
12854 NOTREACHED();
12855 return false;
12858 void GetSSLInfo(SSLInfo* ssl_info) override {}
12860 void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override {
12861 NOTREACHED();
12864 bool IsSpdyHttpStream() const override {
12865 NOTREACHED();
12866 return false;
12869 void Drain(HttpNetworkSession* session) override { NOTREACHED(); }
12871 void SetPriority(RequestPriority priority) override { NOTREACHED(); }
12873 UploadProgress GetUploadProgress() const override {
12874 NOTREACHED();
12875 return UploadProgress();
12878 HttpStream* RenewStreamForAuth() override {
12879 NOTREACHED();
12880 return nullptr;
12883 // Fake implementation of WebSocketHandshakeStreamBase method(s)
12884 scoped_ptr<WebSocketStream> Upgrade() override {
12885 NOTREACHED();
12886 return scoped_ptr<WebSocketStream>();
12889 private:
12890 HttpStreamParser* parser() const { return state_.parser(); }
12891 HttpBasicState state_;
12893 DISALLOW_COPY_AND_ASSIGN(FakeWebSocketBasicHandshakeStream);
12896 // TODO(yhirano): Split this class out into a net/websockets file, if it is
12897 // worth doing.
12898 class FakeWebSocketStreamCreateHelper :
12899 public WebSocketHandshakeStreamBase::CreateHelper {
12900 public:
12901 WebSocketHandshakeStreamBase* CreateBasicStream(
12902 scoped_ptr<ClientSocketHandle> connection,
12903 bool using_proxy) override {
12904 return new FakeWebSocketBasicHandshakeStream(connection.Pass(),
12905 using_proxy);
12908 WebSocketHandshakeStreamBase* CreateSpdyStream(
12909 const base::WeakPtr<SpdySession>& session,
12910 bool use_relative_url) override {
12911 NOTREACHED();
12912 return NULL;
12915 ~FakeWebSocketStreamCreateHelper() override {}
12917 virtual scoped_ptr<WebSocketStream> Upgrade() {
12918 NOTREACHED();
12919 return scoped_ptr<WebSocketStream>();
12923 } // namespace
12925 // Make sure that HttpNetworkTransaction passes on its priority to its
12926 // stream request on start.
12927 TEST_P(HttpNetworkTransactionTest, SetStreamRequestPriorityOnStart) {
12928 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12929 HttpNetworkSessionPeer peer(session);
12930 FakeStreamFactory* fake_factory = new FakeStreamFactory();
12931 peer.SetHttpStreamFactory(scoped_ptr<HttpStreamFactory>(fake_factory));
12933 HttpNetworkTransaction trans(LOW, session.get());
12935 ASSERT_TRUE(fake_factory->last_stream_request() == NULL);
12937 HttpRequestInfo request;
12938 TestCompletionCallback callback;
12939 EXPECT_EQ(ERR_IO_PENDING,
12940 trans.Start(&request, callback.callback(), BoundNetLog()));
12942 base::WeakPtr<FakeStreamRequest> fake_request =
12943 fake_factory->last_stream_request();
12944 ASSERT_TRUE(fake_request != NULL);
12945 EXPECT_EQ(LOW, fake_request->priority());
12948 // Make sure that HttpNetworkTransaction passes on its priority
12949 // updates to its stream request.
12950 TEST_P(HttpNetworkTransactionTest, SetStreamRequestPriority) {
12951 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12952 HttpNetworkSessionPeer peer(session);
12953 FakeStreamFactory* fake_factory = new FakeStreamFactory();
12954 peer.SetHttpStreamFactory(scoped_ptr<HttpStreamFactory>(fake_factory));
12956 HttpNetworkTransaction trans(LOW, session.get());
12958 HttpRequestInfo request;
12959 TestCompletionCallback callback;
12960 EXPECT_EQ(ERR_IO_PENDING,
12961 trans.Start(&request, callback.callback(), BoundNetLog()));
12963 base::WeakPtr<FakeStreamRequest> fake_request =
12964 fake_factory->last_stream_request();
12965 ASSERT_TRUE(fake_request != NULL);
12966 EXPECT_EQ(LOW, fake_request->priority());
12968 trans.SetPriority(LOWEST);
12969 ASSERT_TRUE(fake_request != NULL);
12970 EXPECT_EQ(LOWEST, fake_request->priority());
12973 // Make sure that HttpNetworkTransaction passes on its priority
12974 // updates to its stream.
12975 TEST_P(HttpNetworkTransactionTest, SetStreamPriority) {
12976 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
12977 HttpNetworkSessionPeer peer(session);
12978 FakeStreamFactory* fake_factory = new FakeStreamFactory();
12979 peer.SetHttpStreamFactory(scoped_ptr<HttpStreamFactory>(fake_factory));
12981 HttpNetworkTransaction trans(LOW, session.get());
12983 HttpRequestInfo request;
12984 TestCompletionCallback callback;
12985 EXPECT_EQ(ERR_IO_PENDING,
12986 trans.Start(&request, callback.callback(), BoundNetLog()));
12988 base::WeakPtr<FakeStreamRequest> fake_request =
12989 fake_factory->last_stream_request();
12990 ASSERT_TRUE(fake_request != NULL);
12991 base::WeakPtr<FakeStream> fake_stream = fake_request->FinishStreamRequest();
12992 ASSERT_TRUE(fake_stream != NULL);
12993 EXPECT_EQ(LOW, fake_stream->priority());
12995 trans.SetPriority(LOWEST);
12996 EXPECT_EQ(LOWEST, fake_stream->priority());
12999 TEST_P(HttpNetworkTransactionTest, CreateWebSocketHandshakeStream) {
13000 // The same logic needs to be tested for both ws: and wss: schemes, but this
13001 // test is already parameterised on NextProto, so it uses a loop to verify
13002 // that the different schemes work.
13003 std::string test_cases[] = {"ws://www.google.com/", "wss://www.google.com/"};
13004 for (size_t i = 0; i < arraysize(test_cases); ++i) {
13005 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13006 HttpNetworkSessionPeer peer(session);
13007 FakeStreamFactory* fake_factory = new FakeStreamFactory();
13008 FakeWebSocketStreamCreateHelper websocket_stream_create_helper;
13009 peer.SetHttpStreamFactoryForWebSocket(
13010 scoped_ptr<HttpStreamFactory>(fake_factory));
13012 HttpNetworkTransaction trans(LOW, session.get());
13013 trans.SetWebSocketHandshakeStreamCreateHelper(
13014 &websocket_stream_create_helper);
13016 HttpRequestInfo request;
13017 TestCompletionCallback callback;
13018 request.method = "GET";
13019 request.url = GURL(test_cases[i]);
13021 EXPECT_EQ(ERR_IO_PENDING,
13022 trans.Start(&request, callback.callback(), BoundNetLog()));
13024 base::WeakPtr<FakeStreamRequest> fake_request =
13025 fake_factory->last_stream_request();
13026 ASSERT_TRUE(fake_request != NULL);
13027 EXPECT_EQ(&websocket_stream_create_helper,
13028 fake_request->websocket_stream_create_helper());
13032 // Tests that when a used socket is returned to the SSL socket pool, it's closed
13033 // if the transport socket pool is stalled on the global socket limit.
13034 TEST_P(HttpNetworkTransactionTest, CloseSSLSocketOnIdleForHttpRequest) {
13035 ClientSocketPoolManager::set_max_sockets_per_group(
13036 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
13037 ClientSocketPoolManager::set_max_sockets_per_pool(
13038 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
13040 // Set up SSL request.
13042 HttpRequestInfo ssl_request;
13043 ssl_request.method = "GET";
13044 ssl_request.url = GURL("https://www.google.com/");
13046 MockWrite ssl_writes[] = {
13047 MockWrite("GET / HTTP/1.1\r\n"
13048 "Host: www.google.com\r\n"
13049 "Connection: keep-alive\r\n\r\n"),
13051 MockRead ssl_reads[] = {
13052 MockRead("HTTP/1.1 200 OK\r\n"),
13053 MockRead("Content-Length: 11\r\n\r\n"),
13054 MockRead("hello world"),
13055 MockRead(SYNCHRONOUS, OK),
13057 StaticSocketDataProvider ssl_data(ssl_reads, arraysize(ssl_reads),
13058 ssl_writes, arraysize(ssl_writes));
13059 session_deps_.socket_factory->AddSocketDataProvider(&ssl_data);
13061 SSLSocketDataProvider ssl(ASYNC, OK);
13062 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
13064 // Set up HTTP request.
13066 HttpRequestInfo http_request;
13067 http_request.method = "GET";
13068 http_request.url = GURL("http://www.google.com/");
13070 MockWrite http_writes[] = {
13071 MockWrite("GET / HTTP/1.1\r\n"
13072 "Host: www.google.com\r\n"
13073 "Connection: keep-alive\r\n\r\n"),
13075 MockRead http_reads[] = {
13076 MockRead("HTTP/1.1 200 OK\r\n"),
13077 MockRead("Content-Length: 7\r\n\r\n"),
13078 MockRead("falafel"),
13079 MockRead(SYNCHRONOUS, OK),
13081 StaticSocketDataProvider http_data(http_reads, arraysize(http_reads),
13082 http_writes, arraysize(http_writes));
13083 session_deps_.socket_factory->AddSocketDataProvider(&http_data);
13085 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13087 // Start the SSL request.
13088 TestCompletionCallback ssl_callback;
13089 scoped_ptr<HttpTransaction> ssl_trans(
13090 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13091 ASSERT_EQ(ERR_IO_PENDING,
13092 ssl_trans->Start(&ssl_request, ssl_callback.callback(),
13093 BoundNetLog()));
13095 // Start the HTTP request. Pool should stall.
13096 TestCompletionCallback http_callback;
13097 scoped_ptr<HttpTransaction> http_trans(
13098 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13099 ASSERT_EQ(ERR_IO_PENDING,
13100 http_trans->Start(&http_request, http_callback.callback(),
13101 BoundNetLog()));
13102 EXPECT_TRUE(IsTransportSocketPoolStalled(session.get()));
13104 // Wait for response from SSL request.
13105 ASSERT_EQ(OK, ssl_callback.WaitForResult());
13106 std::string response_data;
13107 ASSERT_EQ(OK, ReadTransaction(ssl_trans.get(), &response_data));
13108 EXPECT_EQ("hello world", response_data);
13110 // The SSL socket should automatically be closed, so the HTTP request can
13111 // start.
13112 EXPECT_EQ(0, GetIdleSocketCountInSSLSocketPool(session.get()));
13113 ASSERT_FALSE(IsTransportSocketPoolStalled(session.get()));
13115 // The HTTP request can now complete.
13116 ASSERT_EQ(OK, http_callback.WaitForResult());
13117 ASSERT_EQ(OK, ReadTransaction(http_trans.get(), &response_data));
13118 EXPECT_EQ("falafel", response_data);
13120 EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
13123 // Tests that when a SSL connection is established but there's no corresponding
13124 // request that needs it, the new socket is closed if the transport socket pool
13125 // is stalled on the global socket limit.
13126 TEST_P(HttpNetworkTransactionTest, CloseSSLSocketOnIdleForHttpRequest2) {
13127 ClientSocketPoolManager::set_max_sockets_per_group(
13128 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
13129 ClientSocketPoolManager::set_max_sockets_per_pool(
13130 HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
13132 // Set up an ssl request.
13134 HttpRequestInfo ssl_request;
13135 ssl_request.method = "GET";
13136 ssl_request.url = GURL("https://www.foopy.com/");
13138 // No data will be sent on the SSL socket.
13139 StaticSocketDataProvider ssl_data;
13140 session_deps_.socket_factory->AddSocketDataProvider(&ssl_data);
13142 SSLSocketDataProvider ssl(ASYNC, OK);
13143 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
13145 // Set up HTTP request.
13147 HttpRequestInfo http_request;
13148 http_request.method = "GET";
13149 http_request.url = GURL("http://www.google.com/");
13151 MockWrite http_writes[] = {
13152 MockWrite("GET / HTTP/1.1\r\n"
13153 "Host: www.google.com\r\n"
13154 "Connection: keep-alive\r\n\r\n"),
13156 MockRead http_reads[] = {
13157 MockRead("HTTP/1.1 200 OK\r\n"),
13158 MockRead("Content-Length: 7\r\n\r\n"),
13159 MockRead("falafel"),
13160 MockRead(SYNCHRONOUS, OK),
13162 StaticSocketDataProvider http_data(http_reads, arraysize(http_reads),
13163 http_writes, arraysize(http_writes));
13164 session_deps_.socket_factory->AddSocketDataProvider(&http_data);
13166 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13168 // Preconnect an SSL socket. A preconnect is needed because connect jobs are
13169 // cancelled when a normal transaction is cancelled.
13170 net::HttpStreamFactory* http_stream_factory = session->http_stream_factory();
13171 net::SSLConfig ssl_config;
13172 session->ssl_config_service()->GetSSLConfig(&ssl_config);
13173 http_stream_factory->PreconnectStreams(1, ssl_request, DEFAULT_PRIORITY,
13174 ssl_config, ssl_config);
13175 EXPECT_EQ(0, GetIdleSocketCountInSSLSocketPool(session.get()));
13177 // Start the HTTP request. Pool should stall.
13178 TestCompletionCallback http_callback;
13179 scoped_ptr<HttpTransaction> http_trans(
13180 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13181 ASSERT_EQ(ERR_IO_PENDING,
13182 http_trans->Start(&http_request, http_callback.callback(),
13183 BoundNetLog()));
13184 EXPECT_TRUE(IsTransportSocketPoolStalled(session.get()));
13186 // The SSL connection will automatically be closed once the connection is
13187 // established, to let the HTTP request start.
13188 ASSERT_EQ(OK, http_callback.WaitForResult());
13189 std::string response_data;
13190 ASSERT_EQ(OK, ReadTransaction(http_trans.get(), &response_data));
13191 EXPECT_EQ("falafel", response_data);
13193 EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
13196 TEST_P(HttpNetworkTransactionTest, PostReadsErrorResponseAfterReset) {
13197 ScopedVector<UploadElementReader> element_readers;
13198 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13199 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
13201 HttpRequestInfo request;
13202 request.method = "POST";
13203 request.url = GURL("http://www.foo.com/");
13204 request.upload_data_stream = &upload_data_stream;
13205 request.load_flags = 0;
13207 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13208 scoped_ptr<HttpTransaction> trans(
13209 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13210 // Send headers successfully, but get an error while sending the body.
13211 MockWrite data_writes[] = {
13212 MockWrite("POST / HTTP/1.1\r\n"
13213 "Host: www.foo.com\r\n"
13214 "Connection: keep-alive\r\n"
13215 "Content-Length: 3\r\n\r\n"),
13216 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13219 MockRead data_reads[] = {
13220 MockRead("HTTP/1.0 400 Not OK\r\n\r\n"),
13221 MockRead("hello world"),
13222 MockRead(SYNCHRONOUS, OK),
13224 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13225 arraysize(data_writes));
13226 session_deps_.socket_factory->AddSocketDataProvider(&data);
13228 TestCompletionCallback callback;
13230 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13231 EXPECT_EQ(ERR_IO_PENDING, rv);
13233 rv = callback.WaitForResult();
13234 EXPECT_EQ(OK, rv);
13236 const HttpResponseInfo* response = trans->GetResponseInfo();
13237 ASSERT_TRUE(response != NULL);
13239 EXPECT_TRUE(response->headers.get() != NULL);
13240 EXPECT_EQ("HTTP/1.0 400 Not OK", response->headers->GetStatusLine());
13242 std::string response_data;
13243 rv = ReadTransaction(trans.get(), &response_data);
13244 EXPECT_EQ(OK, rv);
13245 EXPECT_EQ("hello world", response_data);
13248 // This test makes sure the retry logic doesn't trigger when reading an error
13249 // response from a server that rejected a POST with a CONNECTION_RESET.
13250 TEST_P(HttpNetworkTransactionTest,
13251 PostReadsErrorResponseAfterResetOnReusedSocket) {
13252 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13253 MockWrite data_writes[] = {
13254 MockWrite("GET / HTTP/1.1\r\n"
13255 "Host: www.foo.com\r\n"
13256 "Connection: keep-alive\r\n\r\n"),
13257 MockWrite("POST / HTTP/1.1\r\n"
13258 "Host: www.foo.com\r\n"
13259 "Connection: keep-alive\r\n"
13260 "Content-Length: 3\r\n\r\n"),
13261 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13264 MockRead data_reads[] = {
13265 MockRead("HTTP/1.1 200 Peachy\r\n"
13266 "Content-Length: 14\r\n\r\n"),
13267 MockRead("first response"),
13268 MockRead("HTTP/1.1 400 Not OK\r\n"
13269 "Content-Length: 15\r\n\r\n"),
13270 MockRead("second response"),
13271 MockRead(SYNCHRONOUS, OK),
13273 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13274 arraysize(data_writes));
13275 session_deps_.socket_factory->AddSocketDataProvider(&data);
13277 TestCompletionCallback callback;
13278 HttpRequestInfo request1;
13279 request1.method = "GET";
13280 request1.url = GURL("http://www.foo.com/");
13281 request1.load_flags = 0;
13283 scoped_ptr<HttpTransaction> trans1(
13284 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13285 int rv = trans1->Start(&request1, callback.callback(), BoundNetLog());
13286 EXPECT_EQ(ERR_IO_PENDING, rv);
13288 rv = callback.WaitForResult();
13289 EXPECT_EQ(OK, rv);
13291 const HttpResponseInfo* response1 = trans1->GetResponseInfo();
13292 ASSERT_TRUE(response1 != NULL);
13294 EXPECT_TRUE(response1->headers.get() != NULL);
13295 EXPECT_EQ("HTTP/1.1 200 Peachy", response1->headers->GetStatusLine());
13297 std::string response_data1;
13298 rv = ReadTransaction(trans1.get(), &response_data1);
13299 EXPECT_EQ(OK, rv);
13300 EXPECT_EQ("first response", response_data1);
13301 // Delete the transaction to release the socket back into the socket pool.
13302 trans1.reset();
13304 ScopedVector<UploadElementReader> element_readers;
13305 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13306 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
13308 HttpRequestInfo request2;
13309 request2.method = "POST";
13310 request2.url = GURL("http://www.foo.com/");
13311 request2.upload_data_stream = &upload_data_stream;
13312 request2.load_flags = 0;
13314 scoped_ptr<HttpTransaction> trans2(
13315 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13316 rv = trans2->Start(&request2, callback.callback(), BoundNetLog());
13317 EXPECT_EQ(ERR_IO_PENDING, rv);
13319 rv = callback.WaitForResult();
13320 EXPECT_EQ(OK, rv);
13322 const HttpResponseInfo* response2 = trans2->GetResponseInfo();
13323 ASSERT_TRUE(response2 != NULL);
13325 EXPECT_TRUE(response2->headers.get() != NULL);
13326 EXPECT_EQ("HTTP/1.1 400 Not OK", response2->headers->GetStatusLine());
13328 std::string response_data2;
13329 rv = ReadTransaction(trans2.get(), &response_data2);
13330 EXPECT_EQ(OK, rv);
13331 EXPECT_EQ("second response", response_data2);
13334 TEST_P(HttpNetworkTransactionTest,
13335 PostReadsErrorResponseAfterResetPartialBodySent) {
13336 ScopedVector<UploadElementReader> element_readers;
13337 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13338 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
13340 HttpRequestInfo request;
13341 request.method = "POST";
13342 request.url = GURL("http://www.foo.com/");
13343 request.upload_data_stream = &upload_data_stream;
13344 request.load_flags = 0;
13346 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13347 scoped_ptr<HttpTransaction> trans(
13348 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13349 // Send headers successfully, but get an error while sending the body.
13350 MockWrite data_writes[] = {
13351 MockWrite("POST / HTTP/1.1\r\n"
13352 "Host: www.foo.com\r\n"
13353 "Connection: keep-alive\r\n"
13354 "Content-Length: 3\r\n\r\n"
13355 "fo"),
13356 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13359 MockRead data_reads[] = {
13360 MockRead("HTTP/1.0 400 Not OK\r\n\r\n"),
13361 MockRead("hello world"),
13362 MockRead(SYNCHRONOUS, OK),
13364 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13365 arraysize(data_writes));
13366 session_deps_.socket_factory->AddSocketDataProvider(&data);
13368 TestCompletionCallback callback;
13370 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13371 EXPECT_EQ(ERR_IO_PENDING, rv);
13373 rv = callback.WaitForResult();
13374 EXPECT_EQ(OK, rv);
13376 const HttpResponseInfo* response = trans->GetResponseInfo();
13377 ASSERT_TRUE(response != NULL);
13379 EXPECT_TRUE(response->headers.get() != NULL);
13380 EXPECT_EQ("HTTP/1.0 400 Not OK", response->headers->GetStatusLine());
13382 std::string response_data;
13383 rv = ReadTransaction(trans.get(), &response_data);
13384 EXPECT_EQ(OK, rv);
13385 EXPECT_EQ("hello world", response_data);
13388 // This tests the more common case than the previous test, where headers and
13389 // body are not merged into a single request.
13390 TEST_P(HttpNetworkTransactionTest, ChunkedPostReadsErrorResponseAfterReset) {
13391 ScopedVector<UploadElementReader> element_readers;
13392 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13393 ChunkedUploadDataStream upload_data_stream(0);
13395 HttpRequestInfo request;
13396 request.method = "POST";
13397 request.url = GURL("http://www.foo.com/");
13398 request.upload_data_stream = &upload_data_stream;
13399 request.load_flags = 0;
13401 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13402 scoped_ptr<HttpTransaction> trans(
13403 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13404 // Send headers successfully, but get an error while sending the body.
13405 MockWrite data_writes[] = {
13406 MockWrite("POST / HTTP/1.1\r\n"
13407 "Host: www.foo.com\r\n"
13408 "Connection: keep-alive\r\n"
13409 "Transfer-Encoding: chunked\r\n\r\n"),
13410 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13413 MockRead data_reads[] = {
13414 MockRead("HTTP/1.0 400 Not OK\r\n\r\n"),
13415 MockRead("hello world"),
13416 MockRead(SYNCHRONOUS, OK),
13418 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13419 arraysize(data_writes));
13420 session_deps_.socket_factory->AddSocketDataProvider(&data);
13422 TestCompletionCallback callback;
13424 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13425 EXPECT_EQ(ERR_IO_PENDING, rv);
13426 // Make sure the headers are sent before adding a chunk. This ensures that
13427 // they can't be merged with the body in a single send. Not currently
13428 // necessary since a chunked body is never merged with headers, but this makes
13429 // the test more future proof.
13430 base::RunLoop().RunUntilIdle();
13432 upload_data_stream.AppendData("last chunk", 10, true);
13434 rv = callback.WaitForResult();
13435 EXPECT_EQ(OK, rv);
13437 const HttpResponseInfo* response = trans->GetResponseInfo();
13438 ASSERT_TRUE(response != NULL);
13440 EXPECT_TRUE(response->headers.get() != NULL);
13441 EXPECT_EQ("HTTP/1.0 400 Not OK", response->headers->GetStatusLine());
13443 std::string response_data;
13444 rv = ReadTransaction(trans.get(), &response_data);
13445 EXPECT_EQ(OK, rv);
13446 EXPECT_EQ("hello world", response_data);
13449 TEST_P(HttpNetworkTransactionTest, PostReadsErrorResponseAfterResetAnd100) {
13450 ScopedVector<UploadElementReader> element_readers;
13451 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13452 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
13454 HttpRequestInfo request;
13455 request.method = "POST";
13456 request.url = GURL("http://www.foo.com/");
13457 request.upload_data_stream = &upload_data_stream;
13458 request.load_flags = 0;
13460 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13461 scoped_ptr<HttpTransaction> trans(
13462 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13464 MockWrite data_writes[] = {
13465 MockWrite("POST / HTTP/1.1\r\n"
13466 "Host: www.foo.com\r\n"
13467 "Connection: keep-alive\r\n"
13468 "Content-Length: 3\r\n\r\n"),
13469 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13472 MockRead data_reads[] = {
13473 MockRead("HTTP/1.0 100 Continue\r\n\r\n"),
13474 MockRead("HTTP/1.0 400 Not OK\r\n\r\n"),
13475 MockRead("hello world"),
13476 MockRead(SYNCHRONOUS, OK),
13478 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13479 arraysize(data_writes));
13480 session_deps_.socket_factory->AddSocketDataProvider(&data);
13482 TestCompletionCallback callback;
13484 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13485 EXPECT_EQ(ERR_IO_PENDING, rv);
13487 rv = callback.WaitForResult();
13488 EXPECT_EQ(OK, rv);
13490 const HttpResponseInfo* response = trans->GetResponseInfo();
13491 ASSERT_TRUE(response != NULL);
13493 EXPECT_TRUE(response->headers.get() != NULL);
13494 EXPECT_EQ("HTTP/1.0 400 Not OK", response->headers->GetStatusLine());
13496 std::string response_data;
13497 rv = ReadTransaction(trans.get(), &response_data);
13498 EXPECT_EQ(OK, rv);
13499 EXPECT_EQ("hello world", response_data);
13502 TEST_P(HttpNetworkTransactionTest, PostIgnoresNonErrorResponseAfterReset) {
13503 ScopedVector<UploadElementReader> element_readers;
13504 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13505 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
13507 HttpRequestInfo request;
13508 request.method = "POST";
13509 request.url = GURL("http://www.foo.com/");
13510 request.upload_data_stream = &upload_data_stream;
13511 request.load_flags = 0;
13513 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13514 scoped_ptr<HttpTransaction> trans(
13515 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13516 // Send headers successfully, but get an error while sending the body.
13517 MockWrite data_writes[] = {
13518 MockWrite("POST / HTTP/1.1\r\n"
13519 "Host: www.foo.com\r\n"
13520 "Connection: keep-alive\r\n"
13521 "Content-Length: 3\r\n\r\n"),
13522 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13525 MockRead data_reads[] = {
13526 MockRead("HTTP/1.0 200 Just Dandy\r\n\r\n"),
13527 MockRead("hello world"),
13528 MockRead(SYNCHRONOUS, OK),
13530 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13531 arraysize(data_writes));
13532 session_deps_.socket_factory->AddSocketDataProvider(&data);
13534 TestCompletionCallback callback;
13536 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13537 EXPECT_EQ(ERR_IO_PENDING, rv);
13539 rv = callback.WaitForResult();
13540 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
13542 const HttpResponseInfo* response = trans->GetResponseInfo();
13543 EXPECT_TRUE(response == NULL);
13546 TEST_P(HttpNetworkTransactionTest,
13547 PostIgnoresNonErrorResponseAfterResetAnd100) {
13548 ScopedVector<UploadElementReader> element_readers;
13549 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13550 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
13552 HttpRequestInfo request;
13553 request.method = "POST";
13554 request.url = GURL("http://www.foo.com/");
13555 request.upload_data_stream = &upload_data_stream;
13556 request.load_flags = 0;
13558 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13559 scoped_ptr<HttpTransaction> trans(
13560 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13561 // Send headers successfully, but get an error while sending the body.
13562 MockWrite data_writes[] = {
13563 MockWrite("POST / HTTP/1.1\r\n"
13564 "Host: www.foo.com\r\n"
13565 "Connection: keep-alive\r\n"
13566 "Content-Length: 3\r\n\r\n"),
13567 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13570 MockRead data_reads[] = {
13571 MockRead("HTTP/1.0 100 Continue\r\n\r\n"),
13572 MockRead("HTTP/1.0 302 Redirect\r\n"),
13573 MockRead("Location: http://somewhere-else.com/\r\n"),
13574 MockRead("Content-Length: 0\r\n\r\n"),
13575 MockRead(SYNCHRONOUS, OK),
13577 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13578 arraysize(data_writes));
13579 session_deps_.socket_factory->AddSocketDataProvider(&data);
13581 TestCompletionCallback callback;
13583 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13584 EXPECT_EQ(ERR_IO_PENDING, rv);
13586 rv = callback.WaitForResult();
13587 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
13589 const HttpResponseInfo* response = trans->GetResponseInfo();
13590 EXPECT_TRUE(response == NULL);
13593 TEST_P(HttpNetworkTransactionTest, PostIgnoresHttp09ResponseAfterReset) {
13594 ScopedVector<UploadElementReader> element_readers;
13595 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13596 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
13598 HttpRequestInfo request;
13599 request.method = "POST";
13600 request.url = GURL("http://www.foo.com/");
13601 request.upload_data_stream = &upload_data_stream;
13602 request.load_flags = 0;
13604 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13605 scoped_ptr<HttpTransaction> trans(
13606 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13607 // Send headers successfully, but get an error while sending the body.
13608 MockWrite data_writes[] = {
13609 MockWrite("POST / HTTP/1.1\r\n"
13610 "Host: www.foo.com\r\n"
13611 "Connection: keep-alive\r\n"
13612 "Content-Length: 3\r\n\r\n"),
13613 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13616 MockRead data_reads[] = {
13617 MockRead("HTTP 0.9 rocks!"),
13618 MockRead(SYNCHRONOUS, OK),
13620 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13621 arraysize(data_writes));
13622 session_deps_.socket_factory->AddSocketDataProvider(&data);
13624 TestCompletionCallback callback;
13626 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13627 EXPECT_EQ(ERR_IO_PENDING, rv);
13629 rv = callback.WaitForResult();
13630 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
13632 const HttpResponseInfo* response = trans->GetResponseInfo();
13633 EXPECT_TRUE(response == NULL);
13636 TEST_P(HttpNetworkTransactionTest, PostIgnoresPartial400HeadersAfterReset) {
13637 ScopedVector<UploadElementReader> element_readers;
13638 element_readers.push_back(new UploadBytesElementReader("foo", 3));
13639 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
13641 HttpRequestInfo request;
13642 request.method = "POST";
13643 request.url = GURL("http://www.foo.com/");
13644 request.upload_data_stream = &upload_data_stream;
13645 request.load_flags = 0;
13647 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13648 scoped_ptr<HttpTransaction> trans(
13649 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13650 // Send headers successfully, but get an error while sending the body.
13651 MockWrite data_writes[] = {
13652 MockWrite("POST / HTTP/1.1\r\n"
13653 "Host: www.foo.com\r\n"
13654 "Connection: keep-alive\r\n"
13655 "Content-Length: 3\r\n\r\n"),
13656 MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
13659 MockRead data_reads[] = {
13660 MockRead("HTTP/1.0 400 Not a Full Response\r\n"),
13661 MockRead(SYNCHRONOUS, OK),
13663 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13664 arraysize(data_writes));
13665 session_deps_.socket_factory->AddSocketDataProvider(&data);
13667 TestCompletionCallback callback;
13669 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13670 EXPECT_EQ(ERR_IO_PENDING, rv);
13672 rv = callback.WaitForResult();
13673 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
13675 const HttpResponseInfo* response = trans->GetResponseInfo();
13676 EXPECT_TRUE(response == NULL);
13679 // Verify that proxy headers are not sent to the destination server when
13680 // establishing a tunnel for a secure WebSocket connection.
13681 TEST_P(HttpNetworkTransactionTest, ProxyHeadersNotSentOverWssTunnel) {
13682 HttpRequestInfo request;
13683 request.method = "GET";
13684 request.url = GURL("wss://www.google.com/");
13685 AddWebSocketHeaders(&request.extra_headers);
13687 // Configure against proxy server "myproxy:70".
13688 session_deps_.proxy_service.reset(
13689 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
13691 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13693 // Since a proxy is configured, try to establish a tunnel.
13694 MockWrite data_writes[] = {
13695 MockWrite(
13696 "CONNECT www.google.com:443 HTTP/1.1\r\n"
13697 "Host: www.google.com\r\n"
13698 "Proxy-Connection: keep-alive\r\n\r\n"),
13700 // After calling trans->RestartWithAuth(), this is the request we should
13701 // be issuing -- the final header line contains the credentials.
13702 MockWrite(
13703 "CONNECT www.google.com:443 HTTP/1.1\r\n"
13704 "Host: www.google.com\r\n"
13705 "Proxy-Connection: keep-alive\r\n"
13706 "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
13708 MockWrite(
13709 "GET / HTTP/1.1\r\n"
13710 "Host: www.google.com\r\n"
13711 "Connection: Upgrade\r\n"
13712 "Upgrade: websocket\r\n"
13713 "Origin: http://www.google.com\r\n"
13714 "Sec-WebSocket-Version: 13\r\n"
13715 "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n"),
13718 // The proxy responds to the connect with a 407, using a persistent
13719 // connection.
13720 MockRead data_reads[] = {
13721 // No credentials.
13722 MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
13723 MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
13724 MockRead("Proxy-Connection: close\r\n\r\n"),
13726 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
13728 MockRead("HTTP/1.1 101 Switching Protocols\r\n"),
13729 MockRead("Upgrade: websocket\r\n"),
13730 MockRead("Connection: Upgrade\r\n"),
13731 MockRead("Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n"),
13734 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13735 arraysize(data_writes));
13736 session_deps_.socket_factory->AddSocketDataProvider(&data);
13737 SSLSocketDataProvider ssl(ASYNC, OK);
13738 session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
13740 scoped_ptr<HttpTransaction> trans(
13741 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13742 FakeWebSocketStreamCreateHelper websocket_stream_create_helper;
13743 trans->SetWebSocketHandshakeStreamCreateHelper(
13744 &websocket_stream_create_helper);
13747 TestCompletionCallback callback;
13749 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13750 EXPECT_EQ(ERR_IO_PENDING, rv);
13752 rv = callback.WaitForResult();
13753 EXPECT_EQ(OK, rv);
13756 const HttpResponseInfo* response = trans->GetResponseInfo();
13757 ASSERT_TRUE(response);
13758 ASSERT_TRUE(response->headers.get());
13759 EXPECT_EQ(407, response->headers->response_code());
13762 TestCompletionCallback callback;
13764 int rv = trans->RestartWithAuth(AuthCredentials(kFoo, kBar),
13765 callback.callback());
13766 EXPECT_EQ(ERR_IO_PENDING, rv);
13768 rv = callback.WaitForResult();
13769 EXPECT_EQ(OK, rv);
13772 response = trans->GetResponseInfo();
13773 ASSERT_TRUE(response);
13774 ASSERT_TRUE(response->headers.get());
13776 EXPECT_EQ(101, response->headers->response_code());
13778 trans.reset();
13779 session->CloseAllConnections();
13782 // Verify that proxy headers are not sent to the destination server when
13783 // establishing a tunnel for an insecure WebSocket connection.
13784 // This requires the authentication info to be injected into the auth cache
13785 // due to crbug.com/395064
13786 // TODO(ricea): Change to use a 407 response once issue 395064 is fixed.
13787 TEST_P(HttpNetworkTransactionTest, ProxyHeadersNotSentOverWsTunnel) {
13788 HttpRequestInfo request;
13789 request.method = "GET";
13790 request.url = GURL("ws://www.google.com/");
13791 AddWebSocketHeaders(&request.extra_headers);
13793 // Configure against proxy server "myproxy:70".
13794 session_deps_.proxy_service.reset(
13795 ProxyService::CreateFixedFromPacResult("PROXY myproxy:70"));
13797 scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_));
13799 MockWrite data_writes[] = {
13800 // Try to establish a tunnel for the WebSocket connection, with
13801 // credentials. Because WebSockets have a separate set of socket pools,
13802 // they cannot and will not use the same TCP/IP connection as the
13803 // preflight HTTP request.
13804 MockWrite(
13805 "CONNECT www.google.com:80 HTTP/1.1\r\n"
13806 "Host: www.google.com\r\n"
13807 "Proxy-Connection: keep-alive\r\n"
13808 "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
13810 MockWrite(
13811 "GET / HTTP/1.1\r\n"
13812 "Host: www.google.com\r\n"
13813 "Connection: Upgrade\r\n"
13814 "Upgrade: websocket\r\n"
13815 "Origin: http://www.google.com\r\n"
13816 "Sec-WebSocket-Version: 13\r\n"
13817 "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n"),
13820 MockRead data_reads[] = {
13821 // HTTP CONNECT with credentials.
13822 MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
13824 // WebSocket connection established inside tunnel.
13825 MockRead("HTTP/1.1 101 Switching Protocols\r\n"),
13826 MockRead("Upgrade: websocket\r\n"),
13827 MockRead("Connection: Upgrade\r\n"),
13828 MockRead("Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n"),
13831 StaticSocketDataProvider data(data_reads, arraysize(data_reads), data_writes,
13832 arraysize(data_writes));
13833 session_deps_.socket_factory->AddSocketDataProvider(&data);
13835 session->http_auth_cache()->Add(
13836 GURL("http://myproxy:70/"), "MyRealm1", HttpAuth::AUTH_SCHEME_BASIC,
13837 "Basic realm=MyRealm1", AuthCredentials(kFoo, kBar), "/");
13839 scoped_ptr<HttpTransaction> trans(
13840 new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
13841 FakeWebSocketStreamCreateHelper websocket_stream_create_helper;
13842 trans->SetWebSocketHandshakeStreamCreateHelper(
13843 &websocket_stream_create_helper);
13845 TestCompletionCallback callback;
13847 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
13848 EXPECT_EQ(ERR_IO_PENDING, rv);
13850 rv = callback.WaitForResult();
13851 EXPECT_EQ(OK, rv);
13853 const HttpResponseInfo* response = trans->GetResponseInfo();
13854 ASSERT_TRUE(response);
13855 ASSERT_TRUE(response->headers.get());
13857 EXPECT_EQ(101, response->headers->response_code());
13859 trans.reset();
13860 session->CloseAllConnections();
13863 } // namespace net