Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / net / url_request / url_request_unittest.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "build/build_config.h"
6
7 #if defined(OS_WIN)
8 #include <windows.h>
9 #include <shlobj.h>
10 #endif
11
12 #include <algorithm>
13 #include <string>
14
15 #include "base/basictypes.h"
16 #include "base/bind.h"
17 #include "base/compiler_specific.h"
18 #include "base/files/file_util.h"
19 #include "base/files/scoped_temp_dir.h"
20 #include "base/format_macros.h"
21 #include "base/memory/scoped_ptr.h"
22 #include "base/memory/weak_ptr.h"
23 #include "base/message_loop/message_loop.h"
24 #include "base/message_loop/message_loop_proxy.h"
25 #include "base/path_service.h"
26 #include "base/run_loop.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/string_piece.h"
29 #include "base/strings/string_split.h"
30 #include "base/strings/string_util.h"
31 #include "base/strings/stringprintf.h"
32 #include "base/strings/utf_string_conversions.h"
33 #include "net/base/capturing_net_log.h"
34 #include "net/base/chunked_upload_data_stream.h"
35 #include "net/base/elements_upload_data_stream.h"
36 #include "net/base/load_flags.h"
37 #include "net/base/load_timing_info.h"
38 #include "net/base/load_timing_info_test_util.h"
39 #include "net/base/net_errors.h"
40 #include "net/base/net_log.h"
41 #include "net/base/net_log_unittest.h"
42 #include "net/base/net_module.h"
43 #include "net/base/net_util.h"
44 #include "net/base/request_priority.h"
45 #include "net/base/test_data_directory.h"
46 #include "net/base/upload_bytes_element_reader.h"
47 #include "net/base/upload_data_stream.h"
48 #include "net/base/upload_file_element_reader.h"
49 #include "net/cert/ev_root_ca_metadata.h"
50 #include "net/cert/mock_cert_verifier.h"
51 #include "net/cert/test_root_certs.h"
52 #include "net/cookies/cookie_monster.h"
53 #include "net/cookies/cookie_store_test_helpers.h"
54 #include "net/disk_cache/disk_cache.h"
55 #include "net/dns/mock_host_resolver.h"
56 #include "net/ftp/ftp_network_layer.h"
57 #include "net/http/http_byte_range.h"
58 #include "net/http/http_cache.h"
59 #include "net/http/http_network_layer.h"
60 #include "net/http/http_network_session.h"
61 #include "net/http/http_request_headers.h"
62 #include "net/http/http_response_headers.h"
63 #include "net/http/http_util.h"
64 #include "net/ocsp/nss_ocsp.h"
65 #include "net/proxy/proxy_service.h"
66 #include "net/socket/ssl_client_socket.h"
67 #include "net/ssl/ssl_cipher_suite_names.h"
68 #include "net/ssl/ssl_connection_status_flags.h"
69 #include "net/test/cert_test_util.h"
70 #include "net/test/spawned_test_server/spawned_test_server.h"
71 #include "net/url_request/data_protocol_handler.h"
72 #include "net/url_request/static_http_user_agent_settings.h"
73 #include "net/url_request/url_request.h"
74 #include "net/url_request/url_request_http_job.h"
75 #include "net/url_request/url_request_intercepting_job_factory.h"
76 #include "net/url_request/url_request_interceptor.h"
77 #include "net/url_request/url_request_job_factory_impl.h"
78 #include "net/url_request/url_request_redirect_job.h"
79 #include "net/url_request/url_request_test_job.h"
80 #include "net/url_request/url_request_test_util.h"
81 #include "testing/gtest/include/gtest/gtest.h"
82 #include "testing/platform_test.h"
83
84 #if !defined(DISABLE_FILE_SUPPORT)
85 #include "net/base/filename_util.h"
86 #include "net/url_request/file_protocol_handler.h"
87 #include "net/url_request/url_request_file_dir_job.h"
88 #endif
89
90 #if !defined(DISABLE_FTP_SUPPORT)
91 #include "net/url_request/ftp_protocol_handler.h"
92 #endif
93
94 #if defined(OS_WIN)
95 #include "base/win/scoped_com_initializer.h"
96 #include "base/win/scoped_comptr.h"
97 #include "base/win/windows_version.h"
98 #endif
99
100 using base::ASCIIToUTF16;
101 using base::Time;
102
103 namespace net {
104
105 namespace {
106
107 const base::string16 kChrome(ASCIIToUTF16("chrome"));
108 const base::string16 kSecret(ASCIIToUTF16("secret"));
109 const base::string16 kUser(ASCIIToUTF16("user"));
110
111 // Tests load timing information in the case a fresh connection was used, with
112 // no proxy.
113 void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
114                              int connect_timing_flags) {
115   EXPECT_FALSE(load_timing_info.socket_reused);
116   EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
117
118   EXPECT_FALSE(load_timing_info.request_start_time.is_null());
119   EXPECT_FALSE(load_timing_info.request_start.is_null());
120
121   EXPECT_LE(load_timing_info.request_start,
122             load_timing_info.connect_timing.connect_start);
123   ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
124                               connect_timing_flags);
125   EXPECT_LE(load_timing_info.connect_timing.connect_end,
126             load_timing_info.send_start);
127   EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
128   EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
129
130   EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
131   EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
132 }
133
134 // Same as above, but with proxy times.
135 void TestLoadTimingNotReusedWithProxy(
136     const LoadTimingInfo& load_timing_info,
137     int connect_timing_flags) {
138   EXPECT_FALSE(load_timing_info.socket_reused);
139   EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
140
141   EXPECT_FALSE(load_timing_info.request_start_time.is_null());
142   EXPECT_FALSE(load_timing_info.request_start.is_null());
143
144   EXPECT_LE(load_timing_info.request_start,
145             load_timing_info.proxy_resolve_start);
146   EXPECT_LE(load_timing_info.proxy_resolve_start,
147             load_timing_info.proxy_resolve_end);
148   EXPECT_LE(load_timing_info.proxy_resolve_end,
149             load_timing_info.connect_timing.connect_start);
150   ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
151                               connect_timing_flags);
152   EXPECT_LE(load_timing_info.connect_timing.connect_end,
153             load_timing_info.send_start);
154   EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
155   EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
156 }
157
158 // Same as above, but with a reused socket and proxy times.
159 void TestLoadTimingReusedWithProxy(
160     const LoadTimingInfo& load_timing_info) {
161   EXPECT_TRUE(load_timing_info.socket_reused);
162   EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
163
164   EXPECT_FALSE(load_timing_info.request_start_time.is_null());
165   EXPECT_FALSE(load_timing_info.request_start.is_null());
166
167   ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
168
169   EXPECT_LE(load_timing_info.request_start,
170             load_timing_info.proxy_resolve_start);
171   EXPECT_LE(load_timing_info.proxy_resolve_start,
172             load_timing_info.proxy_resolve_end);
173   EXPECT_LE(load_timing_info.proxy_resolve_end,
174             load_timing_info.send_start);
175   EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
176   EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
177 }
178
179 // Tests load timing information in the case of a cache hit, when no cache
180 // validation request was sent over the wire.
181 base::StringPiece TestNetResourceProvider(int key) {
182   return "header";
183 }
184
185 void FillBuffer(char* buffer, size_t len) {
186   static bool called = false;
187   if (!called) {
188     called = true;
189     int seed = static_cast<int>(Time::Now().ToInternalValue());
190     srand(seed);
191   }
192
193   for (size_t i = 0; i < len; i++) {
194     buffer[i] = static_cast<char>(rand());
195     if (!buffer[i])
196       buffer[i] = 'g';
197   }
198 }
199
200 #if !defined(OS_IOS)
201 void TestLoadTimingCacheHitNoNetwork(
202     const LoadTimingInfo& load_timing_info) {
203   EXPECT_FALSE(load_timing_info.socket_reused);
204   EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
205
206   EXPECT_FALSE(load_timing_info.request_start_time.is_null());
207   EXPECT_FALSE(load_timing_info.request_start.is_null());
208
209   ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
210   EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
211   EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
212   EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
213
214   EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
215   EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
216 }
217
218 // Tests load timing in the case that there is no HTTP response.  This can be
219 // used to test in the case of errors or non-HTTP requests.
220 void TestLoadTimingNoHttpResponse(
221     const LoadTimingInfo& load_timing_info) {
222   EXPECT_FALSE(load_timing_info.socket_reused);
223   EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
224
225   // Only the request times should be non-null.
226   EXPECT_FALSE(load_timing_info.request_start_time.is_null());
227   EXPECT_FALSE(load_timing_info.request_start.is_null());
228
229   ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
230
231   EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
232   EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
233   EXPECT_TRUE(load_timing_info.send_start.is_null());
234   EXPECT_TRUE(load_timing_info.send_end.is_null());
235   EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
236 }
237
238 // Do a case-insensitive search through |haystack| for |needle|.
239 bool ContainsString(const std::string& haystack, const char* needle) {
240   std::string::const_iterator it =
241       std::search(haystack.begin(),
242                   haystack.end(),
243                   needle,
244                   needle + strlen(needle),
245                   base::CaseInsensitiveCompare<char>());
246   return it != haystack.end();
247 }
248
249 scoped_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
250   scoped_ptr<UploadElementReader> reader(
251       new UploadBytesElementReader(data, strlen(data)));
252   return ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0);
253 }
254
255 // Verify that the SSLInfo of a successful SSL connection has valid values.
256 void CheckSSLInfo(const SSLInfo& ssl_info) {
257   // -1 means unknown.  0 means no encryption.
258   EXPECT_GT(ssl_info.security_bits, 0);
259
260   // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
261   int cipher_suite = SSLConnectionStatusToCipherSuite(
262       ssl_info.connection_status);
263   EXPECT_NE(0, cipher_suite);
264 }
265
266 void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
267                              const GURL& host_url) {
268   std::string sent_value;
269
270   EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
271   EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
272
273   EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
274   EXPECT_EQ("keep-alive", sent_value);
275 }
276
277 bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
278   size_t size = a.size();
279
280   if (size != b.size())
281     return false;
282
283   for (size_t i = 0; i < size; ++i) {
284     if (!a[i].Equals(b[i]))
285       return false;
286   }
287
288   return true;
289 }
290 #endif  // !defined(OS_IOS)
291
292 // A network delegate that allows the user to choose a subset of request stages
293 // to block in. When blocking, the delegate can do one of the following:
294 //  * synchronously return a pre-specified error code, or
295 //  * asynchronously return that value via an automatically called callback,
296 //    or
297 //  * block and wait for the user to do a callback.
298 // Additionally, the user may also specify a redirect URL -- then each request
299 // with the current URL different from the redirect target will be redirected
300 // to that target, in the on-before-URL-request stage, independent of whether
301 // the delegate blocks in ON_BEFORE_URL_REQUEST or not.
302 class BlockingNetworkDelegate : public TestNetworkDelegate {
303  public:
304   // Stages in which the delegate can block.
305   enum Stage {
306     NOT_BLOCKED = 0,
307     ON_BEFORE_URL_REQUEST = 1 << 0,
308     ON_BEFORE_SEND_HEADERS = 1 << 1,
309     ON_HEADERS_RECEIVED = 1 << 2,
310     ON_AUTH_REQUIRED = 1 << 3
311   };
312
313   // Behavior during blocked stages.  During other stages, just
314   // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
315   enum BlockMode {
316     SYNCHRONOUS,    // No callback, returns specified return values.
317     AUTO_CALLBACK,  // |this| posts a task to run the callback using the
318                     // specified return codes.
319     USER_CALLBACK,  // User takes care of doing a callback.  |retval_| and
320                     // |auth_retval_| are ignored. In every blocking stage the
321                     // message loop is quit.
322   };
323
324   // Creates a delegate which does not block at all.
325   explicit BlockingNetworkDelegate(BlockMode block_mode);
326
327   // For users to trigger a callback returning |response|.
328   // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
329   // Only call if |block_mode_| == USER_CALLBACK.
330   void DoCallback(int response);
331   void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
332
333   // Setters.
334   void set_retval(int retval) {
335     ASSERT_NE(USER_CALLBACK, block_mode_);
336     ASSERT_NE(ERR_IO_PENDING, retval);
337     ASSERT_NE(OK, retval);
338     retval_ = retval;
339   }
340
341   // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
342   // |auth_credentials_| will be passed with the response.
343   void set_auth_retval(AuthRequiredResponse auth_retval) {
344     ASSERT_NE(USER_CALLBACK, block_mode_);
345     ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
346     auth_retval_ = auth_retval;
347   }
348   void set_auth_credentials(const AuthCredentials& auth_credentials) {
349     auth_credentials_ = auth_credentials;
350   }
351
352   void set_redirect_url(const GURL& url) {
353     redirect_url_ = url;
354   }
355
356   void set_block_on(int block_on) {
357     block_on_ = block_on;
358   }
359
360   // Allows the user to check in which state did we block.
361   Stage stage_blocked_for_callback() const {
362     EXPECT_EQ(USER_CALLBACK, block_mode_);
363     return stage_blocked_for_callback_;
364   }
365
366  private:
367   void RunCallback(int response, const CompletionCallback& callback);
368   void RunAuthCallback(AuthRequiredResponse response,
369                        const AuthCallback& callback);
370
371   // TestNetworkDelegate implementation.
372   int OnBeforeURLRequest(URLRequest* request,
373                          const CompletionCallback& callback,
374                          GURL* new_url) override;
375
376   int OnBeforeSendHeaders(URLRequest* request,
377                           const CompletionCallback& callback,
378                           HttpRequestHeaders* headers) override;
379
380   int OnHeadersReceived(
381       URLRequest* request,
382       const CompletionCallback& callback,
383       const HttpResponseHeaders* original_response_headers,
384       scoped_refptr<HttpResponseHeaders>* override_response_headers,
385       GURL* allowed_unsafe_redirect_url) override;
386
387   NetworkDelegate::AuthRequiredResponse OnAuthRequired(
388       URLRequest* request,
389       const AuthChallengeInfo& auth_info,
390       const AuthCallback& callback,
391       AuthCredentials* credentials) override;
392
393   // Resets the callbacks and |stage_blocked_for_callback_|.
394   void Reset();
395
396   // Checks whether we should block in |stage|. If yes, returns an error code
397   // and optionally sets up callback based on |block_mode_|. If no, returns OK.
398   int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
399
400   // Configuration parameters, can be adjusted by public methods:
401   const BlockMode block_mode_;
402
403   // Values returned on blocking stages when mode is SYNCHRONOUS or
404   // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
405   int retval_;  // To be returned in non-auth stages.
406   AuthRequiredResponse auth_retval_;
407
408   GURL redirect_url_;  // Used if non-empty during OnBeforeURLRequest.
409   int block_on_;  // Bit mask: in which stages to block.
410
411   // |auth_credentials_| will be copied to |*target_auth_credential_| on
412   // callback.
413   AuthCredentials auth_credentials_;
414   AuthCredentials* target_auth_credentials_;
415
416   // Internal variables, not set by not the user:
417   // Last blocked stage waiting for user callback (unused if |block_mode_| !=
418   // USER_CALLBACK).
419   Stage stage_blocked_for_callback_;
420
421   // Callback objects stored during blocking stages.
422   CompletionCallback callback_;
423   AuthCallback auth_callback_;
424
425   base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
426
427   DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
428 };
429
430 BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
431     : block_mode_(block_mode),
432       retval_(OK),
433       auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
434       block_on_(0),
435       target_auth_credentials_(NULL),
436       stage_blocked_for_callback_(NOT_BLOCKED),
437       weak_factory_(this) {
438 }
439
440 void BlockingNetworkDelegate::DoCallback(int response) {
441   ASSERT_EQ(USER_CALLBACK, block_mode_);
442   ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
443   ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
444   CompletionCallback callback = callback_;
445   Reset();
446   RunCallback(response, callback);
447 }
448
449 void BlockingNetworkDelegate::DoAuthCallback(
450     NetworkDelegate::AuthRequiredResponse response) {
451   ASSERT_EQ(USER_CALLBACK, block_mode_);
452   ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
453   AuthCallback auth_callback = auth_callback_;
454   Reset();
455   RunAuthCallback(response, auth_callback);
456 }
457
458 void BlockingNetworkDelegate::RunCallback(int response,
459                                           const CompletionCallback& callback) {
460   callback.Run(response);
461 }
462
463 void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
464                                               const AuthCallback& callback) {
465   if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
466     ASSERT_TRUE(target_auth_credentials_ != NULL);
467     *target_auth_credentials_ = auth_credentials_;
468   }
469   callback.Run(response);
470 }
471
472 int BlockingNetworkDelegate::OnBeforeURLRequest(
473     URLRequest* request,
474     const CompletionCallback& callback,
475     GURL* new_url) {
476   if (redirect_url_ == request->url())
477     return OK;  // We've already seen this request and redirected elsewhere.
478
479   TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
480
481   if (!redirect_url_.is_empty())
482     *new_url = redirect_url_;
483
484   return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
485 }
486
487 int BlockingNetworkDelegate::OnBeforeSendHeaders(
488     URLRequest* request,
489     const CompletionCallback& callback,
490     HttpRequestHeaders* headers) {
491   TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
492
493   return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
494 }
495
496 int BlockingNetworkDelegate::OnHeadersReceived(
497     URLRequest* request,
498     const CompletionCallback& callback,
499     const HttpResponseHeaders* original_response_headers,
500     scoped_refptr<HttpResponseHeaders>* override_response_headers,
501     GURL* allowed_unsafe_redirect_url) {
502   TestNetworkDelegate::OnHeadersReceived(request,
503                                          callback,
504                                          original_response_headers,
505                                          override_response_headers,
506                                          allowed_unsafe_redirect_url);
507
508   return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
509 }
510
511 NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
512     URLRequest* request,
513     const AuthChallengeInfo& auth_info,
514     const AuthCallback& callback,
515     AuthCredentials* credentials) {
516   TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
517                                       credentials);
518   // Check that the user has provided callback for the previous blocked stage.
519   EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
520
521   if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
522     return AUTH_REQUIRED_RESPONSE_NO_ACTION;
523   }
524
525   target_auth_credentials_ = credentials;
526
527   switch (block_mode_) {
528     case SYNCHRONOUS:
529       if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
530         *target_auth_credentials_ = auth_credentials_;
531       return auth_retval_;
532
533     case AUTO_CALLBACK:
534       base::MessageLoop::current()->PostTask(
535           FROM_HERE,
536           base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
537                      weak_factory_.GetWeakPtr(), auth_retval_, callback));
538       return AUTH_REQUIRED_RESPONSE_IO_PENDING;
539
540     case USER_CALLBACK:
541       auth_callback_ = callback;
542       stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
543       base::MessageLoop::current()->PostTask(FROM_HERE,
544                                              base::MessageLoop::QuitClosure());
545       return AUTH_REQUIRED_RESPONSE_IO_PENDING;
546   }
547   NOTREACHED();
548   return AUTH_REQUIRED_RESPONSE_NO_ACTION;  // Dummy value.
549 }
550
551 void BlockingNetworkDelegate::Reset() {
552   EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
553   stage_blocked_for_callback_ = NOT_BLOCKED;
554   callback_.Reset();
555   auth_callback_.Reset();
556 }
557
558 int BlockingNetworkDelegate::MaybeBlockStage(
559     BlockingNetworkDelegate::Stage stage,
560     const CompletionCallback& callback) {
561   // Check that the user has provided callback for the previous blocked stage.
562   EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
563
564   if ((block_on_ & stage) == 0) {
565     return OK;
566   }
567
568   switch (block_mode_) {
569     case SYNCHRONOUS:
570       EXPECT_NE(OK, retval_);
571       return retval_;
572
573     case AUTO_CALLBACK:
574       base::MessageLoop::current()->PostTask(
575           FROM_HERE,
576           base::Bind(&BlockingNetworkDelegate::RunCallback,
577                      weak_factory_.GetWeakPtr(), retval_, callback));
578       return ERR_IO_PENDING;
579
580     case USER_CALLBACK:
581       callback_ = callback;
582       stage_blocked_for_callback_ = stage;
583       base::MessageLoop::current()->PostTask(FROM_HERE,
584                                              base::MessageLoop::QuitClosure());
585       return ERR_IO_PENDING;
586   }
587   NOTREACHED();
588   return 0;
589 }
590
591 class TestURLRequestContextWithProxy : public TestURLRequestContext {
592  public:
593   // Does not own |delegate|.
594   TestURLRequestContextWithProxy(const std::string& proxy,
595                                  NetworkDelegate* delegate)
596       : TestURLRequestContext(true) {
597     context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
598     set_network_delegate(delegate);
599     Init();
600   }
601   ~TestURLRequestContextWithProxy() override {}
602 };
603
604 }  // namespace
605
606 // Inherit PlatformTest since we require the autorelease pool on Mac OS X.
607 class URLRequestTest : public PlatformTest {
608  public:
609   URLRequestTest() : default_context_(true) {
610     default_context_.set_network_delegate(&default_network_delegate_);
611     default_context_.set_net_log(&net_log_);
612     job_factory_impl_ = new URLRequestJobFactoryImpl();
613     job_factory_.reset(job_factory_impl_);
614   }
615
616   ~URLRequestTest() override {
617     // URLRequestJobs may post clean-up tasks on destruction.
618     base::RunLoop().RunUntilIdle();
619   }
620
621   virtual void SetUp() {
622     SetUpFactory();
623     default_context_.set_job_factory(job_factory_.get());
624     default_context_.Init();
625     PlatformTest::SetUp();
626   }
627
628   virtual void SetUpFactory() {
629     job_factory_impl_->SetProtocolHandler("data", new DataProtocolHandler);
630 #if !defined(DISABLE_FILE_SUPPORT)
631     job_factory_impl_->SetProtocolHandler(
632         "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
633 #endif
634   }
635
636   TestNetworkDelegate* default_network_delegate() {
637     return &default_network_delegate_;
638   }
639
640   const TestURLRequestContext& default_context() const {
641     return default_context_;
642   }
643
644
645   // Adds the TestJobInterceptor to the default context.
646   TestJobInterceptor* AddTestInterceptor() {
647     TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
648     job_factory_impl_->SetProtocolHandler("http", NULL);
649     job_factory_impl_->SetProtocolHandler("http", protocol_handler_);
650     return protocol_handler_;
651   }
652
653  protected:
654   CapturingNetLog net_log_;
655   TestNetworkDelegate default_network_delegate_;  // Must outlive URLRequest.
656   URLRequestJobFactoryImpl* job_factory_impl_;
657   scoped_ptr<URLRequestJobFactory> job_factory_;
658   TestURLRequestContext default_context_;
659 };
660
661 TEST_F(URLRequestTest, AboutBlankTest) {
662   TestDelegate d;
663   {
664     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
665         GURL("about:blank"), DEFAULT_PRIORITY, &d, NULL));
666
667     r->Start();
668     EXPECT_TRUE(r->is_pending());
669
670     base::RunLoop().Run();
671
672     EXPECT_TRUE(!r->is_pending());
673     EXPECT_FALSE(d.received_data_before_response());
674     EXPECT_EQ(d.bytes_received(), 0);
675     EXPECT_EQ("", r->GetSocketAddress().host());
676     EXPECT_EQ(0, r->GetSocketAddress().port());
677
678     HttpRequestHeaders headers;
679     EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
680   }
681 }
682
683 TEST_F(URLRequestTest, DataURLImageTest) {
684   TestDelegate d;
685   {
686     // Use our nice little Chrome logo.
687     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
688         GURL(
689         "data:image/png;base64,"
690         "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUBBjG3"
691         "w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQxIEVxitD"
692         "5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI5MpCVdW0gO7t"
693         "vNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKzMx1+fg9bAgK6zHq9"
694         "cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7CkIMDxQpF7r/MWq12UctI1"
695         "dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0WYUqt57yWf2McHTObYPbVD+Z"
696         "wbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2HQQcm43XwmtoYM6vVKleh0uoWvnzW"
697         "3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nkDFHF9ZS+uYVjRUasMeHUmyLYtcklTvzW"
698         "GFZnNOXczThvpKIzjcahSqIzkvDLayDq6D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTb"
699         "xXX1T5xsV9tm9r4TQwHLiZw/pdDZJea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5"
700         "MrVvMzNaI3+ERHfrFzPKQukrQGI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gV"
701         "Md6q5c8GdosynKmSeRuGzpjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq"
702         "/uxxZKzNiZFGD0wRC3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7F"
703         "Ux1qLnV7MGF40smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufB"
704         "JbsysjjW4kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJM"
705         "nlm2O34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfm"
706         "moRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV5En"
707         "hORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
708         DEFAULT_PRIORITY, &d, NULL));
709
710     r->Start();
711     EXPECT_TRUE(r->is_pending());
712
713     base::RunLoop().Run();
714
715     EXPECT_TRUE(!r->is_pending());
716     EXPECT_FALSE(d.received_data_before_response());
717     EXPECT_EQ(d.bytes_received(), 911);
718     EXPECT_EQ("", r->GetSocketAddress().host());
719     EXPECT_EQ(0, r->GetSocketAddress().port());
720
721     HttpRequestHeaders headers;
722     EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
723   }
724 }
725
726 #if !defined(DISABLE_FILE_SUPPORT)
727 TEST_F(URLRequestTest, FileTest) {
728   base::FilePath app_path;
729   PathService::Get(base::FILE_EXE, &app_path);
730   GURL app_url = FilePathToFileURL(app_path);
731
732   TestDelegate d;
733   {
734     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
735         app_url, DEFAULT_PRIORITY, &d, NULL));
736
737     r->Start();
738     EXPECT_TRUE(r->is_pending());
739
740     base::RunLoop().Run();
741
742     int64 file_size = -1;
743     EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
744
745     EXPECT_TRUE(!r->is_pending());
746     EXPECT_EQ(1, d.response_started_count());
747     EXPECT_FALSE(d.received_data_before_response());
748     EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
749     EXPECT_EQ("", r->GetSocketAddress().host());
750     EXPECT_EQ(0, r->GetSocketAddress().port());
751
752     HttpRequestHeaders headers;
753     EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
754   }
755 }
756
757 TEST_F(URLRequestTest, FileTestCancel) {
758   base::FilePath app_path;
759   PathService::Get(base::FILE_EXE, &app_path);
760   GURL app_url = FilePathToFileURL(app_path);
761
762   TestDelegate d;
763   {
764     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
765         app_url, DEFAULT_PRIORITY, &d, NULL));
766
767     r->Start();
768     EXPECT_TRUE(r->is_pending());
769     r->Cancel();
770   }
771   // Async cancellation should be safe even when URLRequest has been already
772   // destroyed.
773   base::RunLoop().RunUntilIdle();
774 }
775
776 TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
777   const size_t buffer_size = 4000;
778   scoped_ptr<char[]> buffer(new char[buffer_size]);
779   FillBuffer(buffer.get(), buffer_size);
780
781   base::FilePath temp_path;
782   EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
783   GURL temp_url = FilePathToFileURL(temp_path);
784   EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
785
786   int64 file_size;
787   EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
788
789   const size_t first_byte_position = 500;
790   const size_t last_byte_position = buffer_size - first_byte_position;
791   const size_t content_length = last_byte_position - first_byte_position + 1;
792   std::string partial_buffer_string(buffer.get() + first_byte_position,
793                                     buffer.get() + last_byte_position + 1);
794
795   TestDelegate d;
796   {
797     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
798         temp_url, DEFAULT_PRIORITY, &d, NULL));
799
800     HttpRequestHeaders headers;
801     headers.SetHeader(
802         HttpRequestHeaders::kRange,
803         HttpByteRange::Bounded(
804             first_byte_position, last_byte_position).GetHeaderValue());
805     r->SetExtraRequestHeaders(headers);
806     r->Start();
807     EXPECT_TRUE(r->is_pending());
808
809     base::RunLoop().Run();
810     EXPECT_TRUE(!r->is_pending());
811     EXPECT_EQ(1, d.response_started_count());
812     EXPECT_FALSE(d.received_data_before_response());
813     EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
814     // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
815     EXPECT_TRUE(partial_buffer_string == d.data_received());
816   }
817
818   EXPECT_TRUE(base::DeleteFile(temp_path, false));
819 }
820
821 TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
822   const size_t buffer_size = 4000;
823   scoped_ptr<char[]> buffer(new char[buffer_size]);
824   FillBuffer(buffer.get(), buffer_size);
825
826   base::FilePath temp_path;
827   EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
828   GURL temp_url = FilePathToFileURL(temp_path);
829   EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
830
831   int64 file_size;
832   EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
833
834   const size_t first_byte_position = 500;
835   const size_t last_byte_position = buffer_size - 1;
836   const size_t content_length = last_byte_position - first_byte_position + 1;
837   std::string partial_buffer_string(buffer.get() + first_byte_position,
838                                     buffer.get() + last_byte_position + 1);
839
840   TestDelegate d;
841   {
842     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
843         temp_url, DEFAULT_PRIORITY, &d, NULL));
844
845     HttpRequestHeaders headers;
846     headers.SetHeader(HttpRequestHeaders::kRange,
847                       HttpByteRange::RightUnbounded(
848                           first_byte_position).GetHeaderValue());
849     r->SetExtraRequestHeaders(headers);
850     r->Start();
851     EXPECT_TRUE(r->is_pending());
852
853     base::RunLoop().Run();
854     EXPECT_TRUE(!r->is_pending());
855     EXPECT_EQ(1, d.response_started_count());
856     EXPECT_FALSE(d.received_data_before_response());
857     EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
858     // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
859     EXPECT_TRUE(partial_buffer_string == d.data_received());
860   }
861
862   EXPECT_TRUE(base::DeleteFile(temp_path, false));
863 }
864
865 TEST_F(URLRequestTest, FileTestMultipleRanges) {
866   const size_t buffer_size = 400000;
867   scoped_ptr<char[]> buffer(new char[buffer_size]);
868   FillBuffer(buffer.get(), buffer_size);
869
870   base::FilePath temp_path;
871   EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
872   GURL temp_url = FilePathToFileURL(temp_path);
873   EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
874
875   int64 file_size;
876   EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
877
878   TestDelegate d;
879   {
880     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
881         temp_url, DEFAULT_PRIORITY, &d, NULL));
882
883     HttpRequestHeaders headers;
884     headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
885     r->SetExtraRequestHeaders(headers);
886     r->Start();
887     EXPECT_TRUE(r->is_pending());
888
889     base::RunLoop().Run();
890     EXPECT_TRUE(d.request_failed());
891   }
892
893   EXPECT_TRUE(base::DeleteFile(temp_path, false));
894 }
895
896 TEST_F(URLRequestTest, AllowFileURLs) {
897   base::ScopedTempDir temp_dir;
898   ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
899   base::FilePath test_file;
900   ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
901   std::string test_data("monkey");
902   base::WriteFile(test_file, test_data.data(), test_data.size());
903   GURL test_file_url = FilePathToFileURL(test_file);
904
905   {
906     TestDelegate d;
907     TestNetworkDelegate network_delegate;
908     network_delegate.set_can_access_files(true);
909     default_context_.set_network_delegate(&network_delegate);
910     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
911         test_file_url, DEFAULT_PRIORITY, &d, NULL));
912     r->Start();
913     base::RunLoop().Run();
914     EXPECT_FALSE(d.request_failed());
915     EXPECT_EQ(test_data, d.data_received());
916   }
917
918   {
919     TestDelegate d;
920     TestNetworkDelegate network_delegate;
921     network_delegate.set_can_access_files(false);
922     default_context_.set_network_delegate(&network_delegate);
923     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
924         test_file_url, DEFAULT_PRIORITY, &d, NULL));
925     r->Start();
926     base::RunLoop().Run();
927     EXPECT_TRUE(d.request_failed());
928     EXPECT_EQ("", d.data_received());
929   }
930 }
931
932
933 TEST_F(URLRequestTest, FileDirCancelTest) {
934   // Put in mock resource provider.
935   NetModule::SetResourceProvider(TestNetResourceProvider);
936
937   TestDelegate d;
938   {
939     base::FilePath file_path;
940     PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
941     file_path = file_path.Append(FILE_PATH_LITERAL("net"));
942     file_path = file_path.Append(FILE_PATH_LITERAL("data"));
943
944     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
945         FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d, NULL));
946     req->Start();
947     EXPECT_TRUE(req->is_pending());
948
949     d.set_cancel_in_received_data_pending(true);
950
951     base::RunLoop().Run();
952   }
953
954   // Take out mock resource provider.
955   NetModule::SetResourceProvider(NULL);
956 }
957
958 TEST_F(URLRequestTest, FileDirOutputSanity) {
959   // Verify the general sanity of the the output of the file:
960   // directory lister by checking for the output of a known existing
961   // file.
962   const char sentinel_name[] = "filedir-sentinel";
963
964   base::FilePath path;
965   PathService::Get(base::DIR_SOURCE_ROOT, &path);
966   path = path.Append(FILE_PATH_LITERAL("net"));
967   path = path.Append(FILE_PATH_LITERAL("data"));
968   path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
969
970   TestDelegate d;
971   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
972       FilePathToFileURL(path), DEFAULT_PRIORITY, &d, NULL));
973   req->Start();
974   base::RunLoop().Run();
975
976   // Generate entry for the sentinel file.
977   base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
978   base::File::Info info;
979   EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
980   EXPECT_GT(info.size, 0);
981   std::string sentinel_output = GetDirectoryListingEntry(
982       base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
983       std::string(sentinel_name),
984       false /* is_dir */,
985       info.size,
986       info.last_modified);
987
988   ASSERT_LT(0, d.bytes_received());
989   ASSERT_FALSE(d.request_failed());
990   ASSERT_TRUE(req->status().is_success());
991   // Check for the entry generated for the "sentinel" file.
992   const std::string& data = d.data_received();
993   ASSERT_NE(data.find(sentinel_output), std::string::npos);
994 }
995
996 TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
997   // There is an implicit redirect when loading a file path that matches a
998   // directory and does not end with a slash.  Ensure that following such
999   // redirects does not crash.  See http://crbug.com/18686.
1000
1001   base::FilePath path;
1002   PathService::Get(base::DIR_SOURCE_ROOT, &path);
1003   path = path.Append(FILE_PATH_LITERAL("net"));
1004   path = path.Append(FILE_PATH_LITERAL("data"));
1005   path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
1006
1007   TestDelegate d;
1008   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1009       FilePathToFileURL(path), DEFAULT_PRIORITY, &d, NULL));
1010   req->Start();
1011   base::RunLoop().Run();
1012
1013   ASSERT_EQ(1, d.received_redirect_count());
1014   ASSERT_LT(0, d.bytes_received());
1015   ASSERT_FALSE(d.request_failed());
1016   ASSERT_TRUE(req->status().is_success());
1017 }
1018
1019 #if defined(OS_WIN)
1020 // Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1021 TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1022   TestDelegate d;
1023   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1024       GURL("file:///"), DEFAULT_PRIORITY, &d, NULL));
1025   req->Start();
1026   base::RunLoop().Run();
1027
1028   ASSERT_EQ(1, d.received_redirect_count());
1029   ASSERT_FALSE(req->status().is_success());
1030 }
1031 #endif  // defined(OS_WIN)
1032
1033 #endif  // !defined(DISABLE_FILE_SUPPORT)
1034
1035 TEST_F(URLRequestTest, InvalidUrlTest) {
1036   TestDelegate d;
1037   {
1038     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
1039         GURL("invalid url"), DEFAULT_PRIORITY, &d, NULL));
1040
1041     r->Start();
1042     EXPECT_TRUE(r->is_pending());
1043
1044     base::RunLoop().Run();
1045     EXPECT_TRUE(d.request_failed());
1046   }
1047 }
1048
1049 TEST_F(URLRequestTest, InvalidReferrerTest) {
1050   TestURLRequestContext context;
1051   TestNetworkDelegate network_delegate;
1052   network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1053   context.set_network_delegate(&network_delegate);
1054   TestDelegate d;
1055   scoped_ptr<URLRequest> req(context.CreateRequest(
1056       GURL("http://localhost/"), DEFAULT_PRIORITY, &d, NULL));
1057   req->SetReferrer("https://somewhere.com/");
1058
1059   req->Start();
1060   base::RunLoop().Run();
1061   EXPECT_TRUE(d.request_failed());
1062 }
1063
1064 #if defined(OS_WIN)
1065 TEST_F(URLRequestTest, ResolveShortcutTest) {
1066   base::FilePath app_path;
1067   PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
1068   app_path = app_path.AppendASCII("net");
1069   app_path = app_path.AppendASCII("data");
1070   app_path = app_path.AppendASCII("url_request_unittest");
1071   app_path = app_path.AppendASCII("with-headers.html");
1072
1073   std::wstring lnk_path = app_path.value() + L".lnk";
1074
1075   base::win::ScopedCOMInitializer com_initializer;
1076
1077   // Temporarily create a shortcut for test
1078   {
1079     base::win::ScopedComPtr<IShellLink> shell;
1080     ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1081                                                CLSCTX_INPROC_SERVER)));
1082     base::win::ScopedComPtr<IPersistFile> persist;
1083     ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1084     EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1085     EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1086     EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1087   }
1088
1089   TestDelegate d;
1090   {
1091     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
1092         FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1093         NULL));
1094
1095     r->Start();
1096     EXPECT_TRUE(r->is_pending());
1097
1098     base::RunLoop().Run();
1099
1100     WIN32_FILE_ATTRIBUTE_DATA data;
1101     GetFileAttributesEx(app_path.value().c_str(),
1102                         GetFileExInfoStandard, &data);
1103     HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1104                              FILE_SHARE_READ, NULL, OPEN_EXISTING,
1105                              FILE_ATTRIBUTE_NORMAL, NULL);
1106     EXPECT_NE(INVALID_HANDLE_VALUE, file);
1107     scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1108     DWORD read_size;
1109     BOOL result;
1110     result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1111                       &read_size, NULL);
1112     std::string content(buffer.get(), read_size);
1113     CloseHandle(file);
1114
1115     EXPECT_TRUE(!r->is_pending());
1116     EXPECT_EQ(1, d.received_redirect_count());
1117     EXPECT_EQ(content, d.data_received());
1118   }
1119
1120   // Clean the shortcut
1121   DeleteFile(lnk_path.c_str());
1122 }
1123 #endif  // defined(OS_WIN)
1124
1125 // Custom URLRequestJobs for use with interceptor tests
1126 class RestartTestJob : public URLRequestTestJob {
1127  public:
1128   RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1129     : URLRequestTestJob(request, network_delegate, true) {}
1130  protected:
1131   void StartAsync() override { this->NotifyRestartRequired(); }
1132  private:
1133   ~RestartTestJob() override {}
1134 };
1135
1136 class CancelTestJob : public URLRequestTestJob {
1137  public:
1138   explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1139     : URLRequestTestJob(request, network_delegate, true) {}
1140  protected:
1141   void StartAsync() override { request_->Cancel(); }
1142  private:
1143   ~CancelTestJob() override {}
1144 };
1145
1146 class CancelThenRestartTestJob : public URLRequestTestJob {
1147  public:
1148   explicit CancelThenRestartTestJob(URLRequest* request,
1149                                     NetworkDelegate* network_delegate)
1150       : URLRequestTestJob(request, network_delegate, true) {
1151   }
1152  protected:
1153   void StartAsync() override {
1154     request_->Cancel();
1155     this->NotifyRestartRequired();
1156   }
1157  private:
1158   ~CancelThenRestartTestJob() override {}
1159 };
1160
1161 // An Interceptor for use with interceptor tests
1162 class TestInterceptor : URLRequest::Interceptor {
1163  public:
1164   TestInterceptor()
1165       : intercept_main_request_(false), restart_main_request_(false),
1166         cancel_main_request_(false), cancel_then_restart_main_request_(false),
1167         simulate_main_network_error_(false),
1168         intercept_redirect_(false), cancel_redirect_request_(false),
1169         intercept_final_response_(false), cancel_final_request_(false),
1170         did_intercept_main_(false), did_restart_main_(false),
1171         did_cancel_main_(false), did_cancel_then_restart_main_(false),
1172         did_simulate_error_main_(false),
1173         did_intercept_redirect_(false), did_cancel_redirect_(false),
1174         did_intercept_final_(false), did_cancel_final_(false) {
1175     URLRequest::Deprecated::RegisterRequestInterceptor(this);
1176   }
1177
1178   ~TestInterceptor() override {
1179     URLRequest::Deprecated::UnregisterRequestInterceptor(this);
1180   }
1181
1182   URLRequestJob* MaybeIntercept(URLRequest* request,
1183                                 NetworkDelegate* network_delegate) override {
1184     if (restart_main_request_) {
1185       restart_main_request_ = false;
1186       did_restart_main_ = true;
1187       return new RestartTestJob(request, network_delegate);
1188     }
1189     if (cancel_main_request_) {
1190       cancel_main_request_ = false;
1191       did_cancel_main_ = true;
1192       return new CancelTestJob(request, network_delegate);
1193     }
1194     if (cancel_then_restart_main_request_) {
1195       cancel_then_restart_main_request_ = false;
1196       did_cancel_then_restart_main_ = true;
1197       return new CancelThenRestartTestJob(request, network_delegate);
1198     }
1199     if (simulate_main_network_error_) {
1200       simulate_main_network_error_ = false;
1201       did_simulate_error_main_ = true;
1202       // will error since the requeted url is not one of its canned urls
1203       return new URLRequestTestJob(request, network_delegate, true);
1204     }
1205     if (!intercept_main_request_)
1206       return NULL;
1207     intercept_main_request_ = false;
1208     did_intercept_main_ = true;
1209     URLRequestTestJob* job =  new URLRequestTestJob(request,
1210                                                     network_delegate,
1211                                                     main_headers_,
1212                                                     main_data_,
1213                                                     true);
1214     job->set_load_timing_info(main_request_load_timing_info_);
1215     return job;
1216   }
1217
1218   URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1219                                         NetworkDelegate* network_delegate,
1220                                         const GURL& location) override {
1221     if (cancel_redirect_request_) {
1222       cancel_redirect_request_ = false;
1223       did_cancel_redirect_ = true;
1224       return new CancelTestJob(request, network_delegate);
1225     }
1226     if (!intercept_redirect_)
1227       return NULL;
1228     intercept_redirect_ = false;
1229     did_intercept_redirect_ = true;
1230     return new URLRequestTestJob(request,
1231                                  network_delegate,
1232                                  redirect_headers_,
1233                                  redirect_data_,
1234                                  true);
1235   }
1236
1237   URLRequestJob* MaybeInterceptResponse(
1238       URLRequest* request,
1239       NetworkDelegate* network_delegate) override {
1240     if (cancel_final_request_) {
1241       cancel_final_request_ = false;
1242       did_cancel_final_ = true;
1243       return new CancelTestJob(request, network_delegate);
1244     }
1245     if (!intercept_final_response_)
1246       return NULL;
1247     intercept_final_response_ = false;
1248     did_intercept_final_ = true;
1249     return new URLRequestTestJob(request,
1250                                  network_delegate,
1251                                  final_headers_,
1252                                  final_data_,
1253                                  true);
1254   }
1255
1256   // Whether to intercept the main request, and if so the response to return and
1257   // the LoadTimingInfo to use.
1258   bool intercept_main_request_;
1259   std::string main_headers_;
1260   std::string main_data_;
1261   LoadTimingInfo main_request_load_timing_info_;
1262
1263   // Other actions we take at MaybeIntercept time
1264   bool restart_main_request_;
1265   bool cancel_main_request_;
1266   bool cancel_then_restart_main_request_;
1267   bool simulate_main_network_error_;
1268
1269   // Whether to intercept redirects, and if so the response to return.
1270   bool intercept_redirect_;
1271   std::string redirect_headers_;
1272   std::string redirect_data_;
1273
1274   // Other actions we can take at MaybeInterceptRedirect time
1275   bool cancel_redirect_request_;
1276
1277   // Whether to intercept final response, and if so the response to return.
1278   bool intercept_final_response_;
1279   std::string final_headers_;
1280   std::string final_data_;
1281
1282   // Other actions we can take at MaybeInterceptResponse time
1283   bool cancel_final_request_;
1284
1285   // If we did something or not
1286   bool did_intercept_main_;
1287   bool did_restart_main_;
1288   bool did_cancel_main_;
1289   bool did_cancel_then_restart_main_;
1290   bool did_simulate_error_main_;
1291   bool did_intercept_redirect_;
1292   bool did_cancel_redirect_;
1293   bool did_intercept_final_;
1294   bool did_cancel_final_;
1295
1296   // Static getters for canned response header and data strings
1297
1298   static std::string ok_data() {
1299     return URLRequestTestJob::test_data_1();
1300   }
1301
1302   static std::string ok_headers() {
1303     return URLRequestTestJob::test_headers();
1304   }
1305
1306   static std::string redirect_data() {
1307     return std::string();
1308   }
1309
1310   static std::string redirect_headers() {
1311     return URLRequestTestJob::test_redirect_headers();
1312   }
1313
1314   static std::string error_data() {
1315     return std::string("ohhh nooooo mr. bill!");
1316   }
1317
1318   static std::string error_headers() {
1319     return URLRequestTestJob::test_error_headers();
1320   }
1321 };
1322
1323 TEST_F(URLRequestTest, Intercept) {
1324   TestInterceptor interceptor;
1325
1326   // intercept the main request and respond with a simple response
1327   interceptor.intercept_main_request_ = true;
1328   interceptor.main_headers_ = TestInterceptor::ok_headers();
1329   interceptor.main_data_ = TestInterceptor::ok_data();
1330
1331   TestDelegate d;
1332   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1333       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1334   base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1335   base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1336   base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1337   req->SetUserData(NULL, user_data0);
1338   req->SetUserData(&user_data1, user_data1);
1339   req->SetUserData(&user_data2, user_data2);
1340   req->set_method("GET");
1341   req->Start();
1342   base::RunLoop().Run();
1343
1344   // Make sure we can retrieve our specific user data
1345   EXPECT_EQ(user_data0, req->GetUserData(NULL));
1346   EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1347   EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
1348
1349   // Check the interceptor got called as expected
1350   EXPECT_TRUE(interceptor.did_intercept_main_);
1351
1352   // Check we got one good response
1353   EXPECT_TRUE(req->status().is_success());
1354   EXPECT_EQ(200, req->response_headers()->response_code());
1355   EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1356   EXPECT_EQ(1, d.response_started_count());
1357   EXPECT_EQ(0, d.received_redirect_count());
1358 }
1359
1360 TEST_F(URLRequestTest, InterceptRedirect) {
1361   TestInterceptor interceptor;
1362
1363   // intercept the main request and respond with a redirect
1364   interceptor.intercept_main_request_ = true;
1365   interceptor.main_headers_ = TestInterceptor::redirect_headers();
1366   interceptor.main_data_ = TestInterceptor::redirect_data();
1367
1368   // intercept that redirect and respond a final OK response
1369   interceptor.intercept_redirect_ = true;
1370   interceptor.redirect_headers_ =  TestInterceptor::ok_headers();
1371   interceptor.redirect_data_ = TestInterceptor::ok_data();
1372
1373   TestDelegate d;
1374   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1375       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1376   req->set_method("GET");
1377   req->Start();
1378   base::RunLoop().Run();
1379
1380   // Check the interceptor got called as expected
1381   EXPECT_TRUE(interceptor.did_intercept_main_);
1382   EXPECT_TRUE(interceptor.did_intercept_redirect_);
1383
1384   // Check we got one good response
1385   EXPECT_TRUE(req->status().is_success());
1386   if (req->status().is_success()) {
1387     EXPECT_EQ(200, req->response_headers()->response_code());
1388   }
1389   EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1390   EXPECT_EQ(1, d.response_started_count());
1391   EXPECT_EQ(0, d.received_redirect_count());
1392 }
1393
1394 TEST_F(URLRequestTest, InterceptServerError) {
1395   TestInterceptor interceptor;
1396
1397   // intercept the main request to generate a server error response
1398   interceptor.intercept_main_request_ = true;
1399   interceptor.main_headers_ = TestInterceptor::error_headers();
1400   interceptor.main_data_ = TestInterceptor::error_data();
1401
1402   // intercept that error and respond with an OK response
1403   interceptor.intercept_final_response_ = true;
1404   interceptor.final_headers_ = TestInterceptor::ok_headers();
1405   interceptor.final_data_ = TestInterceptor::ok_data();
1406
1407   TestDelegate d;
1408   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1409       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1410   req->set_method("GET");
1411   req->Start();
1412   base::RunLoop().Run();
1413
1414   // Check the interceptor got called as expected
1415   EXPECT_TRUE(interceptor.did_intercept_main_);
1416   EXPECT_TRUE(interceptor.did_intercept_final_);
1417
1418   // Check we got one good response
1419   EXPECT_TRUE(req->status().is_success());
1420   EXPECT_EQ(200, req->response_headers()->response_code());
1421   EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1422   EXPECT_EQ(1, d.response_started_count());
1423   EXPECT_EQ(0, d.received_redirect_count());
1424 }
1425
1426 TEST_F(URLRequestTest, InterceptNetworkError) {
1427   TestInterceptor interceptor;
1428
1429   // intercept the main request to simulate a network error
1430   interceptor.simulate_main_network_error_ = true;
1431
1432   // intercept that error and respond with an OK response
1433   interceptor.intercept_final_response_ = true;
1434   interceptor.final_headers_ = TestInterceptor::ok_headers();
1435   interceptor.final_data_ = TestInterceptor::ok_data();
1436
1437   TestDelegate d;
1438   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1439       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1440   req->set_method("GET");
1441   req->Start();
1442   base::RunLoop().Run();
1443
1444   // Check the interceptor got called as expected
1445   EXPECT_TRUE(interceptor.did_simulate_error_main_);
1446   EXPECT_TRUE(interceptor.did_intercept_final_);
1447
1448   // Check we received one good response
1449   EXPECT_TRUE(req->status().is_success());
1450   EXPECT_EQ(200, req->response_headers()->response_code());
1451   EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1452   EXPECT_EQ(1, d.response_started_count());
1453   EXPECT_EQ(0, d.received_redirect_count());
1454 }
1455
1456 TEST_F(URLRequestTest, InterceptRestartRequired) {
1457   TestInterceptor interceptor;
1458
1459   // restart the main request
1460   interceptor.restart_main_request_ = true;
1461
1462   // then intercept the new main request and respond with an OK response
1463   interceptor.intercept_main_request_ = true;
1464   interceptor.main_headers_ = TestInterceptor::ok_headers();
1465   interceptor.main_data_ = TestInterceptor::ok_data();
1466
1467   TestDelegate d;
1468   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1469       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1470   req->set_method("GET");
1471   req->Start();
1472   base::RunLoop().Run();
1473
1474   // Check the interceptor got called as expected
1475   EXPECT_TRUE(interceptor.did_restart_main_);
1476   EXPECT_TRUE(interceptor.did_intercept_main_);
1477
1478   // Check we received one good response
1479   EXPECT_TRUE(req->status().is_success());
1480   if (req->status().is_success()) {
1481     EXPECT_EQ(200, req->response_headers()->response_code());
1482   }
1483   EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1484   EXPECT_EQ(1, d.response_started_count());
1485   EXPECT_EQ(0, d.received_redirect_count());
1486 }
1487
1488 TEST_F(URLRequestTest, InterceptRespectsCancelMain) {
1489   TestInterceptor interceptor;
1490
1491   // intercept the main request and cancel from within the restarted job
1492   interceptor.cancel_main_request_ = true;
1493
1494   // setup to intercept final response and override it with an OK response
1495   interceptor.intercept_final_response_ = true;
1496   interceptor.final_headers_ = TestInterceptor::ok_headers();
1497   interceptor.final_data_ = TestInterceptor::ok_data();
1498
1499   TestDelegate d;
1500   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1501       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1502   req->set_method("GET");
1503   req->Start();
1504   base::RunLoop().Run();
1505
1506   // Check the interceptor got called as expected
1507   EXPECT_TRUE(interceptor.did_cancel_main_);
1508   EXPECT_FALSE(interceptor.did_intercept_final_);
1509
1510   // Check we see a canceled request
1511   EXPECT_FALSE(req->status().is_success());
1512   EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1513 }
1514
1515 TEST_F(URLRequestTest, InterceptRespectsCancelRedirect) {
1516   TestInterceptor interceptor;
1517
1518   // intercept the main request and respond with a redirect
1519   interceptor.intercept_main_request_ = true;
1520   interceptor.main_headers_ = TestInterceptor::redirect_headers();
1521   interceptor.main_data_ = TestInterceptor::redirect_data();
1522
1523   // intercept the redirect and cancel from within that job
1524   interceptor.cancel_redirect_request_ = true;
1525
1526   // setup to intercept final response and override it with an OK response
1527   interceptor.intercept_final_response_ = true;
1528   interceptor.final_headers_ = TestInterceptor::ok_headers();
1529   interceptor.final_data_ = TestInterceptor::ok_data();
1530
1531   TestDelegate d;
1532   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1533       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1534   req->set_method("GET");
1535   req->Start();
1536   base::RunLoop().Run();
1537
1538   // Check the interceptor got called as expected
1539   EXPECT_TRUE(interceptor.did_intercept_main_);
1540   EXPECT_TRUE(interceptor.did_cancel_redirect_);
1541   EXPECT_FALSE(interceptor.did_intercept_final_);
1542
1543   // Check we see a canceled request
1544   EXPECT_FALSE(req->status().is_success());
1545   EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1546 }
1547
1548 TEST_F(URLRequestTest, InterceptRespectsCancelFinal) {
1549   TestInterceptor interceptor;
1550
1551   // intercept the main request to simulate a network error
1552   interceptor.simulate_main_network_error_ = true;
1553
1554   // setup to intercept final response and cancel from within that job
1555   interceptor.cancel_final_request_ = true;
1556
1557   TestDelegate d;
1558   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1559       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1560   req->set_method("GET");
1561   req->Start();
1562   base::RunLoop().Run();
1563
1564   // Check the interceptor got called as expected
1565   EXPECT_TRUE(interceptor.did_simulate_error_main_);
1566   EXPECT_TRUE(interceptor.did_cancel_final_);
1567
1568   // Check we see a canceled request
1569   EXPECT_FALSE(req->status().is_success());
1570   EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1571 }
1572
1573 TEST_F(URLRequestTest, InterceptRespectsCancelInRestart) {
1574   TestInterceptor interceptor;
1575
1576   // intercept the main request and cancel then restart from within that job
1577   interceptor.cancel_then_restart_main_request_ = true;
1578
1579   // setup to intercept final response and override it with an OK response
1580   interceptor.intercept_final_response_ = true;
1581   interceptor.final_headers_ = TestInterceptor::ok_headers();
1582   interceptor.final_data_ = TestInterceptor::ok_data();
1583
1584   TestDelegate d;
1585   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1586       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1587   req->set_method("GET");
1588   req->Start();
1589   base::RunLoop().Run();
1590
1591   // Check the interceptor got called as expected
1592   EXPECT_TRUE(interceptor.did_cancel_then_restart_main_);
1593   EXPECT_FALSE(interceptor.did_intercept_final_);
1594
1595   // Check we see a canceled request
1596   EXPECT_FALSE(req->status().is_success());
1597   EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1598 }
1599
1600 // An Interceptor for use with interceptor tests.
1601 class MockURLRequestInterceptor : public URLRequestInterceptor {
1602  public:
1603   // Static getters for canned response header and data strings.
1604   static std::string ok_data() {
1605     return URLRequestTestJob::test_data_1();
1606   }
1607
1608   static std::string ok_headers() {
1609     return URLRequestTestJob::test_headers();
1610   }
1611
1612   static std::string redirect_data() {
1613     return std::string();
1614   }
1615
1616   static std::string redirect_headers() {
1617     return URLRequestTestJob::test_redirect_headers();
1618   }
1619
1620   static std::string error_data() {
1621     return std::string("ohhh nooooo mr. bill!");
1622   }
1623
1624   static std::string error_headers() {
1625     return URLRequestTestJob::test_error_headers();
1626   }
1627
1628   MockURLRequestInterceptor()
1629       : intercept_main_request_(false), restart_main_request_(false),
1630         cancel_main_request_(false), cancel_then_restart_main_request_(false),
1631         simulate_main_network_error_(false),
1632         intercept_redirect_(false), cancel_redirect_request_(false),
1633         intercept_final_response_(false), cancel_final_request_(false),
1634         use_url_request_http_job_(false),
1635         did_intercept_main_(false), did_restart_main_(false),
1636         did_cancel_main_(false), did_cancel_then_restart_main_(false),
1637         did_simulate_error_main_(false),
1638         did_intercept_redirect_(false), did_cancel_redirect_(false),
1639         did_intercept_final_(false), did_cancel_final_(false) {
1640   }
1641
1642   ~MockURLRequestInterceptor() override {
1643   }
1644
1645   // URLRequestInterceptor implementation:
1646   URLRequestJob* MaybeInterceptRequest(
1647       URLRequest* request,
1648       NetworkDelegate* network_delegate) const override {
1649     if (restart_main_request_) {
1650       restart_main_request_ = false;
1651       did_restart_main_ = true;
1652       return new RestartTestJob(request, network_delegate);
1653     }
1654     if (cancel_main_request_) {
1655       cancel_main_request_ = false;
1656       did_cancel_main_ = true;
1657       return new CancelTestJob(request, network_delegate);
1658     }
1659     if (cancel_then_restart_main_request_) {
1660       cancel_then_restart_main_request_ = false;
1661       did_cancel_then_restart_main_ = true;
1662       return new CancelThenRestartTestJob(request, network_delegate);
1663     }
1664     if (simulate_main_network_error_) {
1665       simulate_main_network_error_ = false;
1666       did_simulate_error_main_ = true;
1667       if (use_url_request_http_job_) {
1668         return URLRequestHttpJob::Factory(request, network_delegate, "http");
1669       }
1670       // This job will result in error since the requested URL is not one of the
1671       // URLs supported by these tests.
1672       return new URLRequestTestJob(request, network_delegate, true);
1673     }
1674     if (!intercept_main_request_)
1675       return nullptr;
1676     intercept_main_request_ = false;
1677     did_intercept_main_ = true;
1678     URLRequestTestJob* job =  new URLRequestTestJob(request,
1679                                                     network_delegate,
1680                                                     main_headers_,
1681                                                     main_data_,
1682                                                     true);
1683     job->set_load_timing_info(main_request_load_timing_info_);
1684     return job;
1685   }
1686
1687   URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1688                                         NetworkDelegate* network_delegate,
1689                                         const GURL& location) const override {
1690     if (cancel_redirect_request_) {
1691       cancel_redirect_request_ = false;
1692       did_cancel_redirect_ = true;
1693       return new CancelTestJob(request, network_delegate);
1694     }
1695     if (!intercept_redirect_)
1696       return nullptr;
1697     intercept_redirect_ = false;
1698     did_intercept_redirect_ = true;
1699     if (use_url_request_http_job_) {
1700       return URLRequestHttpJob::Factory(request, network_delegate, "http");
1701     }
1702     return new URLRequestTestJob(request,
1703                                  network_delegate,
1704                                  redirect_headers_,
1705                                  redirect_data_,
1706                                  true);
1707   }
1708
1709   URLRequestJob* MaybeInterceptResponse(
1710       URLRequest* request,
1711       NetworkDelegate* network_delegate) const override {
1712     if (cancel_final_request_) {
1713       cancel_final_request_ = false;
1714       did_cancel_final_ = true;
1715       return new CancelTestJob(request, network_delegate);
1716     }
1717     if (!intercept_final_response_)
1718       return nullptr;
1719     intercept_final_response_ = false;
1720     did_intercept_final_ = true;
1721     if (use_url_request_http_job_) {
1722       return URLRequestHttpJob::Factory(request, network_delegate, "http");
1723     }
1724     return new URLRequestTestJob(request,
1725                                  network_delegate,
1726                                  final_headers_,
1727                                  final_data_,
1728                                  true);
1729   }
1730
1731   void set_intercept_main_request(bool intercept_main_request) {
1732     intercept_main_request_ = intercept_main_request;
1733   }
1734
1735   void set_main_headers(const std::string& main_headers) {
1736     main_headers_ = main_headers;
1737   }
1738
1739   void set_main_data(const std::string& main_data) {
1740     main_data_ = main_data;
1741   }
1742
1743   void set_main_request_load_timing_info(
1744       const LoadTimingInfo& main_request_load_timing_info) {
1745     main_request_load_timing_info_ = main_request_load_timing_info;
1746   }
1747
1748   void set_restart_main_request(bool restart_main_request) {
1749     restart_main_request_ = restart_main_request;
1750   }
1751
1752   void set_cancel_main_request(bool cancel_main_request) {
1753     cancel_main_request_ = cancel_main_request;
1754   }
1755
1756   void set_cancel_then_restart_main_request(
1757       bool cancel_then_restart_main_request) {
1758     cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1759   }
1760
1761   void set_simulate_main_network_error(bool simulate_main_network_error) {
1762     simulate_main_network_error_ = simulate_main_network_error;
1763   }
1764
1765   void set_intercept_redirect(bool intercept_redirect) {
1766     intercept_redirect_ = intercept_redirect;
1767   }
1768
1769   void set_redirect_headers(const std::string& redirect_headers) {
1770     redirect_headers_ = redirect_headers;
1771   }
1772
1773   void set_redirect_data(const std::string& redirect_data) {
1774     redirect_data_ = redirect_data;
1775   }
1776
1777   void set_cancel_redirect_request(bool cancel_redirect_request) {
1778     cancel_redirect_request_ = cancel_redirect_request;
1779   }
1780
1781   void set_intercept_final_response(bool intercept_final_response) {
1782     intercept_final_response_ = intercept_final_response;
1783   }
1784
1785   void set_final_headers(const std::string& final_headers) {
1786     final_headers_ = final_headers;
1787   }
1788
1789   void set_final_data(const std::string& final_data) {
1790     final_data_ = final_data;
1791   }
1792
1793   void set_cancel_final_request(bool cancel_final_request) {
1794     cancel_final_request_ = cancel_final_request;
1795   }
1796
1797   void set_use_url_request_http_job(bool use_url_request_http_job) {
1798     use_url_request_http_job_ = use_url_request_http_job;
1799   }
1800
1801   bool did_intercept_main() const {
1802     return did_intercept_main_;
1803   }
1804
1805   bool did_restart_main() const {
1806     return did_restart_main_;
1807   }
1808
1809   bool did_cancel_main() const {
1810     return did_cancel_main_;
1811   }
1812
1813   bool did_cancel_then_restart_main() const {
1814     return did_cancel_then_restart_main_;
1815   }
1816
1817   bool did_simulate_error_main() const {
1818     return did_simulate_error_main_;
1819   }
1820
1821   bool did_intercept_redirect() const {
1822     return did_intercept_redirect_;
1823   }
1824
1825   bool did_cancel_redirect() const {
1826     return did_cancel_redirect_;
1827   }
1828
1829   bool did_intercept_final() const {
1830     return did_intercept_final_;
1831   }
1832
1833   bool did_cancel_final() const {
1834     return did_cancel_final_;
1835   }
1836
1837  private:
1838   // Indicate whether to intercept the main request, and if so specify the
1839   // response to return and the LoadTimingInfo to use.
1840   mutable bool intercept_main_request_;
1841   mutable std::string main_headers_;
1842   mutable std::string main_data_;
1843   mutable LoadTimingInfo main_request_load_timing_info_;
1844
1845   // These indicate actions that can be taken within MaybeInterceptRequest.
1846   mutable bool restart_main_request_;
1847   mutable bool cancel_main_request_;
1848   mutable bool cancel_then_restart_main_request_;
1849   mutable bool simulate_main_network_error_;
1850
1851   // Indicate whether to intercept redirects, and if so specify the response to
1852   // return.
1853   mutable bool intercept_redirect_;
1854   mutable std::string redirect_headers_;
1855   mutable std::string redirect_data_;
1856
1857   // Cancel the request within MaybeInterceptRedirect.
1858   mutable bool cancel_redirect_request_;
1859
1860   // Indicate whether to intercept the final response, and if so specify the
1861   // response to return.
1862   mutable bool intercept_final_response_;
1863   mutable std::string final_headers_;
1864   mutable std::string final_data_;
1865
1866   // Cancel the final request within MaybeInterceptResponse.
1867   mutable bool cancel_final_request_;
1868
1869   // Instruct the interceptor to use a real URLRequestHTTPJob.
1870   mutable bool use_url_request_http_job_;
1871
1872   // These indicate if the interceptor did something or not.
1873   mutable bool did_intercept_main_;
1874   mutable bool did_restart_main_;
1875   mutable bool did_cancel_main_;
1876   mutable bool did_cancel_then_restart_main_;
1877   mutable bool did_simulate_error_main_;
1878   mutable bool did_intercept_redirect_;
1879   mutable bool did_cancel_redirect_;
1880   mutable bool did_intercept_final_;
1881   mutable bool did_cancel_final_;
1882 };
1883
1884 // Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1885 class URLRequestInterceptorTest : public URLRequestTest {
1886  public:
1887   URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1888   }
1889
1890   ~URLRequestInterceptorTest() override {
1891     // URLRequestJobs may post clean-up tasks on destruction.
1892     base::RunLoop().RunUntilIdle();
1893   }
1894
1895   void SetUpFactory() override {
1896     interceptor_ = new MockURLRequestInterceptor();
1897     job_factory_.reset(new URLRequestInterceptingJobFactory(
1898         job_factory_.Pass(), make_scoped_ptr(interceptor_)));
1899   }
1900
1901   MockURLRequestInterceptor* interceptor() const {
1902     return interceptor_;
1903   }
1904
1905  private:
1906   MockURLRequestInterceptor* interceptor_;
1907 };
1908
1909 TEST_F(URLRequestInterceptorTest, Intercept) {
1910   // Intercept the main request and respond with a simple response.
1911   interceptor()->set_intercept_main_request(true);
1912   interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1913   interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1914   TestDelegate d;
1915   scoped_ptr<URLRequest> req(default_context().CreateRequest(
1916       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1917   base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1918   base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1919   base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1920   req->SetUserData(nullptr, user_data0);
1921   req->SetUserData(&user_data1, user_data1);
1922   req->SetUserData(&user_data2, user_data2);
1923   req->set_method("GET");
1924   req->Start();
1925   base::RunLoop().Run();
1926
1927   // Make sure we can retrieve our specific user data.
1928   EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1929   EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1930   EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
1931
1932   // Check that we got one good response.
1933   EXPECT_TRUE(req->status().is_success());
1934   EXPECT_EQ(200, req->response_headers()->response_code());
1935   EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1936   EXPECT_EQ(1, d.response_started_count());
1937   EXPECT_EQ(0, d.received_redirect_count());
1938 }
1939
1940 TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1941   // Intercept the main request and respond with a redirect.
1942   interceptor()->set_intercept_main_request(true);
1943   interceptor()->set_main_headers(
1944       MockURLRequestInterceptor::redirect_headers());
1945   interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1946
1947   // Intercept that redirect and respond with a final OK response.
1948   interceptor()->set_intercept_redirect(true);
1949   interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1950   interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1951
1952   TestDelegate d;
1953   scoped_ptr<URLRequest> req(default_context().CreateRequest(
1954       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1955   req->set_method("GET");
1956   req->Start();
1957   base::RunLoop().Run();
1958
1959   // Check that the interceptor got called as expected.
1960   EXPECT_TRUE(interceptor()->did_intercept_main());
1961   EXPECT_TRUE(interceptor()->did_intercept_redirect());
1962
1963   // Check that we got one good response.
1964   EXPECT_TRUE(req->status().is_success());
1965   if (req->status().is_success())
1966     EXPECT_EQ(200, req->response_headers()->response_code());
1967
1968   EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1969   EXPECT_EQ(1, d.response_started_count());
1970   EXPECT_EQ(0, d.received_redirect_count());
1971 }
1972
1973 TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1974   // Intercept the main request to generate a server error response.
1975   interceptor()->set_intercept_main_request(true);
1976   interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1977   interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1978
1979   // Intercept that error and respond with an OK response.
1980   interceptor()->set_intercept_final_response(true);
1981   interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1982   interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1983
1984   TestDelegate d;
1985   scoped_ptr<URLRequest> req(default_context().CreateRequest(
1986       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1987   req->set_method("GET");
1988   req->Start();
1989   base::RunLoop().Run();
1990
1991   // Check that the interceptor got called as expected.
1992   EXPECT_TRUE(interceptor()->did_intercept_main());
1993   EXPECT_TRUE(interceptor()->did_intercept_final());
1994
1995   // Check that we got one good response.
1996   EXPECT_TRUE(req->status().is_success());
1997   EXPECT_EQ(200, req->response_headers()->response_code());
1998   EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1999   EXPECT_EQ(1, d.response_started_count());
2000   EXPECT_EQ(0, d.received_redirect_count());
2001 }
2002
2003 TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
2004   // Intercept the main request to simulate a network error.
2005   interceptor()->set_simulate_main_network_error(true);
2006
2007   // Intercept that error and respond with an OK response.
2008   interceptor()->set_intercept_final_response(true);
2009   interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2010   interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2011
2012   TestDelegate d;
2013   scoped_ptr<URLRequest> req(default_context().CreateRequest(
2014       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2015   req->set_method("GET");
2016   req->Start();
2017   base::RunLoop().Run();
2018
2019   // Check that the interceptor got called as expected.
2020   EXPECT_TRUE(interceptor()->did_simulate_error_main());
2021   EXPECT_TRUE(interceptor()->did_intercept_final());
2022
2023   // Check that we received one good response.
2024   EXPECT_TRUE(req->status().is_success());
2025   EXPECT_EQ(200, req->response_headers()->response_code());
2026   EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
2027   EXPECT_EQ(1, d.response_started_count());
2028   EXPECT_EQ(0, d.received_redirect_count());
2029 }
2030
2031 TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
2032   // Restart the main request.
2033   interceptor()->set_restart_main_request(true);
2034
2035   // then intercept the new main request and respond with an OK response
2036   interceptor()->set_intercept_main_request(true);
2037   interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
2038   interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
2039
2040   TestDelegate d;
2041   scoped_ptr<URLRequest> req(default_context().CreateRequest(
2042       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2043   req->set_method("GET");
2044   req->Start();
2045   base::RunLoop().Run();
2046
2047   // Check that the interceptor got called as expected.
2048   EXPECT_TRUE(interceptor()->did_restart_main());
2049   EXPECT_TRUE(interceptor()->did_intercept_main());
2050
2051   // Check that we received one good response.
2052   EXPECT_TRUE(req->status().is_success());
2053   if (req->status().is_success())
2054     EXPECT_EQ(200, req->response_headers()->response_code());
2055
2056   EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
2057   EXPECT_EQ(1, d.response_started_count());
2058   EXPECT_EQ(0, d.received_redirect_count());
2059 }
2060
2061 TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
2062   // Intercept the main request and cancel from within the restarted job.
2063   interceptor()->set_cancel_main_request(true);
2064
2065   // Set up to intercept the final response and override it with an OK response.
2066   interceptor()->set_intercept_final_response(true);
2067   interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2068   interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2069
2070   TestDelegate d;
2071   scoped_ptr<URLRequest> req(default_context().CreateRequest(
2072       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2073   req->set_method("GET");
2074   req->Start();
2075   base::RunLoop().Run();
2076
2077   // Check that the interceptor got called as expected.
2078   EXPECT_TRUE(interceptor()->did_cancel_main());
2079   EXPECT_FALSE(interceptor()->did_intercept_final());
2080
2081   // Check that we see a canceled request.
2082   EXPECT_FALSE(req->status().is_success());
2083   EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
2084 }
2085
2086 TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
2087   // Intercept the main request and respond with a redirect.
2088   interceptor()->set_intercept_main_request(true);
2089   interceptor()->set_main_headers(
2090       MockURLRequestInterceptor::redirect_headers());
2091   interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
2092
2093   // Intercept the redirect and cancel from within that job.
2094   interceptor()->set_cancel_redirect_request(true);
2095
2096   // Set up to intercept the final response and override it with an OK response.
2097   interceptor()->set_intercept_final_response(true);
2098   interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2099   interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2100
2101   TestDelegate d;
2102   scoped_ptr<URLRequest> req(default_context().CreateRequest(
2103       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2104   req->set_method("GET");
2105   req->Start();
2106   base::RunLoop().Run();
2107
2108   // Check that the interceptor got called as expected.
2109   EXPECT_TRUE(interceptor()->did_intercept_main());
2110   EXPECT_TRUE(interceptor()->did_cancel_redirect());
2111   EXPECT_FALSE(interceptor()->did_intercept_final());
2112
2113   // Check that we see a canceled request.
2114   EXPECT_FALSE(req->status().is_success());
2115   EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
2116 }
2117
2118 TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
2119   // Intercept the main request to simulate a network error.
2120   interceptor()->set_simulate_main_network_error(true);
2121
2122   // Set up to intercept final the response and cancel from within that job.
2123   interceptor()->set_cancel_final_request(true);
2124
2125   TestDelegate d;
2126   scoped_ptr<URLRequest> req(default_context().CreateRequest(
2127       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2128   req->set_method("GET");
2129   req->Start();
2130   base::RunLoop().Run();
2131
2132   // Check that the interceptor got called as expected.
2133   EXPECT_TRUE(interceptor()->did_simulate_error_main());
2134   EXPECT_TRUE(interceptor()->did_cancel_final());
2135
2136   // Check that we see a canceled request.
2137   EXPECT_FALSE(req->status().is_success());
2138   EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
2139 }
2140
2141 TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
2142   // Intercept the main request and cancel then restart from within that job.
2143   interceptor()->set_cancel_then_restart_main_request(true);
2144
2145   // Set up to intercept the final response and override it with an OK response.
2146   interceptor()->set_intercept_final_response(true);
2147   interceptor()->set_final_headers(TestInterceptor::ok_headers());
2148   interceptor()->set_final_data(TestInterceptor::ok_data());
2149
2150   TestDelegate d;
2151   scoped_ptr<URLRequest> req(default_context().CreateRequest(
2152       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2153   req->set_method("GET");
2154   req->Start();
2155   base::RunLoop().Run();
2156
2157   // Check that the interceptor got called as expected.
2158   EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
2159   EXPECT_FALSE(interceptor()->did_intercept_final());
2160
2161   // Check that we see a canceled request.
2162   EXPECT_FALSE(req->status().is_success());
2163   EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
2164 }
2165
2166 // "Normal" LoadTimingInfo as returned by a job.  Everything is in order, not
2167 // reused.  |connect_time_flags| is used to indicate if there should be dns
2168 // or SSL times, and |used_proxy| is used for proxy times.
2169 LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
2170                                     int connect_time_flags,
2171                                     bool used_proxy) {
2172   LoadTimingInfo load_timing;
2173   load_timing.socket_log_id = 1;
2174
2175   if (used_proxy) {
2176     load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2177     load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2178   }
2179
2180   LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
2181   if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
2182     connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
2183     connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
2184   }
2185   connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
2186   if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
2187     connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
2188     connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
2189   }
2190   connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
2191
2192   load_timing.send_start = now + base::TimeDelta::FromDays(9);
2193   load_timing.send_end = now + base::TimeDelta::FromDays(10);
2194   load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2195   return load_timing;
2196 }
2197
2198 // Same as above, but in the case of a reused socket.
2199 LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
2200                                           bool used_proxy) {
2201   LoadTimingInfo load_timing;
2202   load_timing.socket_log_id = 1;
2203   load_timing.socket_reused = true;
2204
2205   if (used_proxy) {
2206     load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2207     load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2208   }
2209
2210   load_timing.send_start = now + base::TimeDelta::FromDays(9);
2211   load_timing.send_end = now + base::TimeDelta::FromDays(10);
2212   load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2213   return load_timing;
2214 }
2215
2216 LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
2217     const LoadTimingInfo& job_load_timing,
2218     const URLRequestContext& context,
2219     MockURLRequestInterceptor* interceptor) {
2220   interceptor->set_intercept_main_request(true);
2221   interceptor->set_main_request_load_timing_info(job_load_timing);
2222   TestDelegate d;
2223   scoped_ptr<URLRequest> req(context.CreateRequest(
2224       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2225   req->Start();
2226   base::RunLoop().Run();
2227
2228   LoadTimingInfo resulting_load_timing;
2229   req->GetLoadTimingInfo(&resulting_load_timing);
2230
2231   // None of these should be modified by the URLRequest.
2232   EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
2233   EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
2234   EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
2235   EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
2236   EXPECT_EQ(job_load_timing.receive_headers_end,
2237             resulting_load_timing.receive_headers_end);
2238
2239   return resulting_load_timing;
2240 }
2241
2242 // Basic test that the intercept + load timing tests work.
2243 TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
2244   base::TimeTicks now = base::TimeTicks::Now();
2245   LoadTimingInfo job_load_timing =
2246       NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
2247
2248   LoadTimingInfo load_timing_result =
2249       RunURLRequestInterceptorLoadTimingTest(
2250           job_load_timing, default_context(), interceptor());
2251
2252   // Nothing should have been changed by the URLRequest.
2253   EXPECT_EQ(job_load_timing.proxy_resolve_start,
2254             load_timing_result.proxy_resolve_start);
2255   EXPECT_EQ(job_load_timing.proxy_resolve_end,
2256             load_timing_result.proxy_resolve_end);
2257   EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2258             load_timing_result.connect_timing.dns_start);
2259   EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2260             load_timing_result.connect_timing.dns_end);
2261   EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2262             load_timing_result.connect_timing.connect_start);
2263   EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2264             load_timing_result.connect_timing.connect_end);
2265   EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2266             load_timing_result.connect_timing.ssl_start);
2267   EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2268             load_timing_result.connect_timing.ssl_end);
2269
2270   // Redundant sanity check.
2271   TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
2272 }
2273
2274 // Another basic test, with proxy and SSL times, but no DNS times.
2275 TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
2276   base::TimeTicks now = base::TimeTicks::Now();
2277   LoadTimingInfo job_load_timing =
2278       NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
2279
2280   LoadTimingInfo load_timing_result =
2281       RunURLRequestInterceptorLoadTimingTest(
2282           job_load_timing, default_context(), interceptor());
2283
2284   // Nothing should have been changed by the URLRequest.
2285   EXPECT_EQ(job_load_timing.proxy_resolve_start,
2286             load_timing_result.proxy_resolve_start);
2287   EXPECT_EQ(job_load_timing.proxy_resolve_end,
2288             load_timing_result.proxy_resolve_end);
2289   EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2290             load_timing_result.connect_timing.dns_start);
2291   EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2292             load_timing_result.connect_timing.dns_end);
2293   EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2294             load_timing_result.connect_timing.connect_start);
2295   EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2296             load_timing_result.connect_timing.connect_end);
2297   EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2298             load_timing_result.connect_timing.ssl_start);
2299   EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2300             load_timing_result.connect_timing.ssl_end);
2301
2302   // Redundant sanity check.
2303   TestLoadTimingNotReusedWithProxy(load_timing_result,
2304                                    CONNECT_TIMING_HAS_SSL_TIMES);
2305 }
2306
2307 // Make sure that URLRequest correctly adjusts proxy times when they're before
2308 // |request_start|, due to already having a connected socket.  This happens in
2309 // the case of reusing a SPDY session.  The connected socket is not considered
2310 // reused in this test (May be a preconnect).
2311 //
2312 // To mix things up from the test above, assumes DNS times but no SSL times.
2313 TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
2314   base::TimeTicks now = base::TimeTicks::Now();
2315   LoadTimingInfo job_load_timing =
2316       NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2317   job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2318   job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2319   job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2320   job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2321   job_load_timing.connect_timing.connect_start =
2322       now - base::TimeDelta::FromDays(2);
2323   job_load_timing.connect_timing.connect_end =
2324       now - base::TimeDelta::FromDays(1);
2325
2326   LoadTimingInfo load_timing_result =
2327       RunURLRequestInterceptorLoadTimingTest(
2328           job_load_timing, default_context(), interceptor());
2329
2330   // Proxy times, connect times, and DNS times should all be replaced with
2331   // request_start.
2332   EXPECT_EQ(load_timing_result.request_start,
2333             load_timing_result.proxy_resolve_start);
2334   EXPECT_EQ(load_timing_result.request_start,
2335             load_timing_result.proxy_resolve_end);
2336   EXPECT_EQ(load_timing_result.request_start,
2337             load_timing_result.connect_timing.dns_start);
2338   EXPECT_EQ(load_timing_result.request_start,
2339             load_timing_result.connect_timing.dns_end);
2340   EXPECT_EQ(load_timing_result.request_start,
2341             load_timing_result.connect_timing.connect_start);
2342   EXPECT_EQ(load_timing_result.request_start,
2343             load_timing_result.connect_timing.connect_end);
2344
2345   // Other times should have been left null.
2346   TestLoadTimingNotReusedWithProxy(load_timing_result,
2347                                    CONNECT_TIMING_HAS_DNS_TIMES);
2348 }
2349
2350 // Same as above, but in the reused case.
2351 TEST_F(URLRequestInterceptorTest,
2352        InterceptLoadTimingEarlyProxyResolutionReused) {
2353   base::TimeTicks now = base::TimeTicks::Now();
2354   LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2355   job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2356   job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2357
2358   LoadTimingInfo load_timing_result =
2359       RunURLRequestInterceptorLoadTimingTest(
2360           job_load_timing, default_context(), interceptor());
2361
2362   // Proxy times and connect times should all be replaced with request_start.
2363   EXPECT_EQ(load_timing_result.request_start,
2364             load_timing_result.proxy_resolve_start);
2365   EXPECT_EQ(load_timing_result.request_start,
2366             load_timing_result.proxy_resolve_end);
2367
2368   // Other times should have been left null.
2369   TestLoadTimingReusedWithProxy(load_timing_result);
2370 }
2371
2372 // Make sure that URLRequest correctly adjusts connect times when they're before
2373 // |request_start|, due to reusing a connected socket.  The connected socket is
2374 // not considered reused in this test (May be a preconnect).
2375 //
2376 // To mix things up, the request has SSL times, but no DNS times.
2377 TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
2378   base::TimeTicks now = base::TimeTicks::Now();
2379   LoadTimingInfo job_load_timing =
2380       NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2381   job_load_timing.connect_timing.connect_start =
2382       now - base::TimeDelta::FromDays(1);
2383   job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2384   job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2385   job_load_timing.connect_timing.connect_end =
2386       now - base::TimeDelta::FromDays(4);
2387
2388   LoadTimingInfo load_timing_result =
2389       RunURLRequestInterceptorLoadTimingTest(
2390           job_load_timing, default_context(), interceptor());
2391
2392   // Connect times, and SSL times should be replaced with request_start.
2393   EXPECT_EQ(load_timing_result.request_start,
2394             load_timing_result.connect_timing.connect_start);
2395   EXPECT_EQ(load_timing_result.request_start,
2396             load_timing_result.connect_timing.ssl_start);
2397   EXPECT_EQ(load_timing_result.request_start,
2398             load_timing_result.connect_timing.ssl_end);
2399   EXPECT_EQ(load_timing_result.request_start,
2400             load_timing_result.connect_timing.connect_end);
2401
2402   // Other times should have been left null.
2403   TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2404 }
2405
2406 // Make sure that URLRequest correctly adjusts connect times when they're before
2407 // |request_start|, due to reusing a connected socket in the case that there
2408 // are also proxy times.  The connected socket is not considered reused in this
2409 // test (May be a preconnect).
2410 //
2411 // In this test, there are no SSL or DNS times.
2412 TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
2413   base::TimeTicks now = base::TimeTicks::Now();
2414   LoadTimingInfo job_load_timing =
2415       NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2416   job_load_timing.connect_timing.connect_start =
2417       now - base::TimeDelta::FromDays(1);
2418   job_load_timing.connect_timing.connect_end =
2419       now - base::TimeDelta::FromDays(2);
2420
2421   LoadTimingInfo load_timing_result =
2422       RunURLRequestInterceptorLoadTimingTest(
2423           job_load_timing, default_context(), interceptor());
2424
2425   // Connect times should be replaced with proxy_resolve_end.
2426   EXPECT_EQ(load_timing_result.proxy_resolve_end,
2427             load_timing_result.connect_timing.connect_start);
2428   EXPECT_EQ(load_timing_result.proxy_resolve_end,
2429             load_timing_result.connect_timing.connect_end);
2430
2431   // Other times should have been left null.
2432   TestLoadTimingNotReusedWithProxy(load_timing_result,
2433                                    CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2434 }
2435
2436 // Check that two different URL requests have different identifiers.
2437 TEST_F(URLRequestTest, Identifiers) {
2438   TestDelegate d;
2439   TestURLRequestContext context;
2440   scoped_ptr<URLRequest> req(context.CreateRequest(
2441       GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
2442   scoped_ptr<URLRequest> other_req(context.CreateRequest(
2443       GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
2444
2445   ASSERT_NE(req->identifier(), other_req->identifier());
2446 }
2447
2448 // Check that a failure to connect to the proxy is reported to the network
2449 // delegate.
2450 TEST_F(URLRequestTest, NetworkDelegateProxyError) {
2451   MockHostResolver host_resolver;
2452   host_resolver.rules()->AddSimulatedFailure("*");
2453
2454   TestNetworkDelegate network_delegate;  // Must outlive URLRequests.
2455   TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2456
2457   TestDelegate d;
2458   scoped_ptr<URLRequest> req(context.CreateRequest(
2459       GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
2460   req->set_method("GET");
2461
2462   req->Start();
2463   base::RunLoop().Run();
2464
2465   // Check we see a failed request.
2466   EXPECT_FALSE(req->status().is_success());
2467   // The proxy server is not set before failure.
2468   EXPECT_TRUE(req->proxy_server().IsEmpty());
2469   EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2470   EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
2471
2472   EXPECT_EQ(1, network_delegate.error_count());
2473   EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
2474   EXPECT_EQ(1, network_delegate.completed_requests());
2475 }
2476
2477 // Make sure that NetworkDelegate::NotifyCompleted is called if
2478 // content is empty.
2479 TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2480   TestDelegate d;
2481   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2482       GURL("data:,"), DEFAULT_PRIORITY, &d, NULL));
2483   req->Start();
2484   base::RunLoop().Run();
2485   EXPECT_EQ("", d.data_received());
2486   EXPECT_EQ(1, default_network_delegate_.completed_requests());
2487 }
2488
2489 // Make sure that SetPriority actually sets the URLRequest's priority
2490 // correctly, both before and after start.
2491 TEST_F(URLRequestTest, SetPriorityBasic) {
2492   TestDelegate d;
2493   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2494       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
2495   EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
2496
2497   req->SetPriority(LOW);
2498   EXPECT_EQ(LOW, req->priority());
2499
2500   req->Start();
2501   EXPECT_EQ(LOW, req->priority());
2502
2503   req->SetPriority(MEDIUM);
2504   EXPECT_EQ(MEDIUM, req->priority());
2505 }
2506
2507 // Make sure that URLRequest calls SetPriority on a job before calling
2508 // Start on it.
2509 TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2510   TestDelegate d;
2511   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2512       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
2513   EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
2514
2515   scoped_refptr<URLRequestTestJob> job =
2516       new URLRequestTestJob(req.get(), &default_network_delegate_);
2517   AddTestInterceptor()->set_main_intercept_job(job.get());
2518   EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
2519
2520   req->SetPriority(LOW);
2521
2522   req->Start();
2523   EXPECT_EQ(LOW, job->priority());
2524 }
2525
2526 // Make sure that URLRequest passes on its priority updates to its
2527 // job.
2528 TEST_F(URLRequestTest, SetJobPriority) {
2529   TestDelegate d;
2530   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2531       GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
2532
2533   scoped_refptr<URLRequestTestJob> job =
2534       new URLRequestTestJob(req.get(), &default_network_delegate_);
2535   AddTestInterceptor()->set_main_intercept_job(job.get());
2536
2537   req->SetPriority(LOW);
2538   req->Start();
2539   EXPECT_EQ(LOW, job->priority());
2540
2541   req->SetPriority(MEDIUM);
2542   EXPECT_EQ(MEDIUM, req->priority());
2543   EXPECT_EQ(MEDIUM, job->priority());
2544 }
2545
2546 // Setting the IGNORE_LIMITS load flag should be okay if the priority
2547 // is MAXIMUM_PRIORITY.
2548 TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2549   TestDelegate d;
2550   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2551       GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d, NULL));
2552   EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
2553
2554   scoped_refptr<URLRequestTestJob> job =
2555       new URLRequestTestJob(req.get(), &default_network_delegate_);
2556   AddTestInterceptor()->set_main_intercept_job(job.get());
2557
2558   req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2559   EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
2560
2561   req->SetPriority(MAXIMUM_PRIORITY);
2562   EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
2563
2564   req->Start();
2565   EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
2566   EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
2567 }
2568
2569 // TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
2570 #if !defined(OS_IOS)
2571 // A subclass of SpawnedTestServer that uses a statically-configured hostname.
2572 // This is to work around mysterious failures in chrome_frame_net_tests. See:
2573 // http://crbug.com/114369
2574 // TODO(erikwright): remove or update as needed; see http://crbug.com/334634.
2575 class LocalHttpTestServer : public SpawnedTestServer {
2576  public:
2577   explicit LocalHttpTestServer(const base::FilePath& document_root)
2578       : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
2579                           ScopedCustomUrlRequestTestHttpHost::value(),
2580                           document_root) {}
2581   LocalHttpTestServer()
2582       : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
2583                           ScopedCustomUrlRequestTestHttpHost::value(),
2584                           base::FilePath()) {}
2585 };
2586
2587 TEST_F(URLRequestTest, DelayedCookieCallback) {
2588   LocalHttpTestServer test_server;
2589   ASSERT_TRUE(test_server.Start());
2590
2591   TestURLRequestContext context;
2592   scoped_refptr<DelayedCookieMonster> delayed_cm =
2593       new DelayedCookieMonster();
2594   scoped_refptr<CookieStore> cookie_store = delayed_cm;
2595   context.set_cookie_store(delayed_cm.get());
2596
2597   // Set up a cookie.
2598   {
2599     TestNetworkDelegate network_delegate;
2600     context.set_network_delegate(&network_delegate);
2601     TestDelegate d;
2602     scoped_ptr<URLRequest> req(context.CreateRequest(
2603         test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2604         &d, NULL));
2605     req->Start();
2606     base::RunLoop().Run();
2607     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2608     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2609     EXPECT_EQ(1, network_delegate.set_cookie_count());
2610   }
2611
2612   // Verify that the cookie is set.
2613   {
2614     TestNetworkDelegate network_delegate;
2615     context.set_network_delegate(&network_delegate);
2616     TestDelegate d;
2617     scoped_ptr<URLRequest> req(context.CreateRequest(
2618         test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2619     req->Start();
2620     base::RunLoop().Run();
2621
2622     EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2623                 != std::string::npos);
2624     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2625     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2626   }
2627 }
2628
2629 TEST_F(URLRequestTest, DoNotSendCookies) {
2630   LocalHttpTestServer test_server;
2631   ASSERT_TRUE(test_server.Start());
2632
2633   // Set up a cookie.
2634   {
2635     TestNetworkDelegate network_delegate;
2636     default_context_.set_network_delegate(&network_delegate);
2637     TestDelegate d;
2638     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2639         test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2640         &d, NULL));
2641     req->Start();
2642     base::RunLoop().Run();
2643     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2644     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2645   }
2646
2647   // Verify that the cookie is set.
2648   {
2649     TestNetworkDelegate network_delegate;
2650     default_context_.set_network_delegate(&network_delegate);
2651     TestDelegate d;
2652     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2653         test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2654     req->Start();
2655     base::RunLoop().Run();
2656
2657     EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2658                 != std::string::npos);
2659     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2660     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2661   }
2662
2663   // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2664   {
2665     TestNetworkDelegate network_delegate;
2666     default_context_.set_network_delegate(&network_delegate);
2667     TestDelegate d;
2668     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2669         test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2670     req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2671     req->Start();
2672     base::RunLoop().Run();
2673
2674     EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2675                 == std::string::npos);
2676
2677     // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2678     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2679     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2680   }
2681 }
2682
2683 TEST_F(URLRequestTest, DoNotSaveCookies) {
2684   LocalHttpTestServer test_server;
2685   ASSERT_TRUE(test_server.Start());
2686
2687   // Set up a cookie.
2688   {
2689     TestNetworkDelegate network_delegate;
2690     default_context_.set_network_delegate(&network_delegate);
2691     TestDelegate d;
2692     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2693         test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2694         &d, NULL));
2695     req->Start();
2696     base::RunLoop().Run();
2697
2698     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2699     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2700     EXPECT_EQ(1, network_delegate.set_cookie_count());
2701   }
2702
2703   // Try to set-up another cookie and update the previous cookie.
2704   {
2705     TestNetworkDelegate network_delegate;
2706     default_context_.set_network_delegate(&network_delegate);
2707     TestDelegate d;
2708     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2709         test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2710         DEFAULT_PRIORITY, &d, NULL));
2711     req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2712     req->Start();
2713
2714     base::RunLoop().Run();
2715
2716     // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2717     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2718     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2719     EXPECT_EQ(0, network_delegate.set_cookie_count());
2720   }
2721
2722   // Verify the cookies weren't saved or updated.
2723   {
2724     TestNetworkDelegate network_delegate;
2725     default_context_.set_network_delegate(&network_delegate);
2726     TestDelegate d;
2727     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2728         test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2729     req->Start();
2730     base::RunLoop().Run();
2731
2732     EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2733                 == std::string::npos);
2734     EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2735                 != std::string::npos);
2736
2737     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2738     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2739     EXPECT_EQ(0, network_delegate.set_cookie_count());
2740   }
2741 }
2742
2743 TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2744   LocalHttpTestServer test_server;
2745   ASSERT_TRUE(test_server.Start());
2746
2747   // Set up a cookie.
2748   {
2749     TestNetworkDelegate network_delegate;
2750     default_context_.set_network_delegate(&network_delegate);
2751     TestDelegate d;
2752     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2753         test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2754         &d, NULL));
2755     req->Start();
2756     base::RunLoop().Run();
2757
2758     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2759     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2760   }
2761
2762   // Verify that the cookie is set.
2763   {
2764     TestNetworkDelegate network_delegate;
2765     default_context_.set_network_delegate(&network_delegate);
2766     TestDelegate d;
2767     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2768         test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2769     req->Start();
2770     base::RunLoop().Run();
2771
2772     EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2773                 != std::string::npos);
2774
2775     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2776     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2777   }
2778
2779   // Verify that the cookie isn't sent.
2780   {
2781     TestNetworkDelegate network_delegate;
2782     default_context_.set_network_delegate(&network_delegate);
2783     TestDelegate d;
2784     network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2785     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2786         test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2787     req->Start();
2788     base::RunLoop().Run();
2789
2790     EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2791                 == std::string::npos);
2792
2793     EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2794     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2795   }
2796 }
2797
2798 TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2799   LocalHttpTestServer test_server;
2800   ASSERT_TRUE(test_server.Start());
2801
2802   // Set up a cookie.
2803   {
2804     TestNetworkDelegate network_delegate;
2805     default_context_.set_network_delegate(&network_delegate);
2806     TestDelegate d;
2807     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2808         test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2809         &d, NULL));
2810     req->Start();
2811     base::RunLoop().Run();
2812
2813     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2814     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2815   }
2816
2817   // Try to set-up another cookie and update the previous cookie.
2818   {
2819     TestNetworkDelegate network_delegate;
2820     default_context_.set_network_delegate(&network_delegate);
2821     TestDelegate d;
2822     network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2823     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2824         test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2825         DEFAULT_PRIORITY, &d, NULL));
2826     req->Start();
2827
2828     base::RunLoop().Run();
2829
2830     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2831     EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2832   }
2833
2834   // Verify the cookies weren't saved or updated.
2835   {
2836     TestNetworkDelegate network_delegate;
2837     default_context_.set_network_delegate(&network_delegate);
2838     TestDelegate d;
2839     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2840         test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2841     req->Start();
2842     base::RunLoop().Run();
2843
2844     EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2845                 == std::string::npos);
2846     EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2847                 != std::string::npos);
2848
2849     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2850     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2851   }
2852 }
2853
2854 TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2855   LocalHttpTestServer test_server;
2856   ASSERT_TRUE(test_server.Start());
2857
2858   // Set up an empty cookie.
2859   {
2860     TestNetworkDelegate network_delegate;
2861     default_context_.set_network_delegate(&network_delegate);
2862     TestDelegate d;
2863     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2864         test_server.GetURL("set-cookie"), DEFAULT_PRIORITY, &d, NULL));
2865     req->Start();
2866     base::RunLoop().Run();
2867
2868     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2869     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2870     EXPECT_EQ(0, network_delegate.set_cookie_count());
2871   }
2872 }
2873
2874 TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2875   LocalHttpTestServer test_server;
2876   ASSERT_TRUE(test_server.Start());
2877
2878   // Set up a cookie.
2879   {
2880     TestNetworkDelegate network_delegate;
2881     default_context_.set_network_delegate(&network_delegate);
2882     TestDelegate d;
2883     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2884         test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2885         &d, NULL));
2886     req->Start();
2887     base::RunLoop().Run();
2888
2889     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2890     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2891   }
2892
2893   // Verify that the cookie is set.
2894   {
2895     TestNetworkDelegate network_delegate;
2896     default_context_.set_network_delegate(&network_delegate);
2897     TestDelegate d;
2898     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2899         test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2900     req->Start();
2901     base::RunLoop().Run();
2902
2903     EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2904                 != std::string::npos);
2905
2906     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2907     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2908   }
2909
2910   // Verify that the cookie isn't sent.
2911   {
2912     TestNetworkDelegate network_delegate;
2913     default_context_.set_network_delegate(&network_delegate);
2914     TestDelegate d;
2915     network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2916     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2917         test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2918     req->Start();
2919     base::RunLoop().Run();
2920
2921     EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2922                 == std::string::npos);
2923
2924     EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2925     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2926   }
2927 }
2928
2929 TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2930   LocalHttpTestServer test_server;
2931   ASSERT_TRUE(test_server.Start());
2932
2933   // Set up a cookie.
2934   {
2935     TestNetworkDelegate network_delegate;
2936     default_context_.set_network_delegate(&network_delegate);
2937     TestDelegate d;
2938     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2939         test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2940         &d, NULL));
2941     req->Start();
2942     base::RunLoop().Run();
2943
2944     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2945     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2946   }
2947
2948   // Try to set-up another cookie and update the previous cookie.
2949   {
2950     TestNetworkDelegate network_delegate;
2951     default_context_.set_network_delegate(&network_delegate);
2952     TestDelegate d;
2953     network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2954     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2955         test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2956         DEFAULT_PRIORITY, &d, NULL));
2957     req->Start();
2958
2959     base::RunLoop().Run();
2960
2961     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2962     EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2963   }
2964
2965   // Verify the cookies weren't saved or updated.
2966   {
2967     TestNetworkDelegate network_delegate;
2968     default_context_.set_network_delegate(&network_delegate);
2969     TestDelegate d;
2970     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2971         test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2972     req->Start();
2973     base::RunLoop().Run();
2974
2975     EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2976                 == std::string::npos);
2977     EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2978                 != std::string::npos);
2979
2980     EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2981     EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2982   }
2983 }
2984
2985 // FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2986 // value for the |fixed_date| argument given to the constructor.
2987 class FixedDateNetworkDelegate : public TestNetworkDelegate {
2988  public:
2989   explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2990       : fixed_date_(fixed_date) {}
2991   ~FixedDateNetworkDelegate() override {}
2992
2993   // NetworkDelegate implementation
2994   int OnHeadersReceived(
2995       URLRequest* request,
2996       const CompletionCallback& callback,
2997       const HttpResponseHeaders* original_response_headers,
2998       scoped_refptr<HttpResponseHeaders>* override_response_headers,
2999       GURL* allowed_unsafe_redirect_url) override;
3000
3001  private:
3002   std::string fixed_date_;
3003
3004   DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3005 };
3006
3007 int FixedDateNetworkDelegate::OnHeadersReceived(
3008     URLRequest* request,
3009     const CompletionCallback& callback,
3010     const HttpResponseHeaders* original_response_headers,
3011     scoped_refptr<HttpResponseHeaders>* override_response_headers,
3012     GURL* allowed_unsafe_redirect_url) {
3013   HttpResponseHeaders* new_response_headers =
3014       new HttpResponseHeaders(original_response_headers->raw_headers());
3015
3016   new_response_headers->RemoveHeader("Date");
3017   new_response_headers->AddHeader("Date: " + fixed_date_);
3018
3019   *override_response_headers = new_response_headers;
3020   return TestNetworkDelegate::OnHeadersReceived(request,
3021                                                 callback,
3022                                                 original_response_headers,
3023                                                 override_response_headers,
3024                                                 allowed_unsafe_redirect_url);
3025 }
3026
3027 // Test that cookie expiration times are adjusted for server/client clock
3028 // skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3029 // headers by defaulting to GMT. (crbug.com/135131)
3030 TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
3031   LocalHttpTestServer test_server;
3032   ASSERT_TRUE(test_server.Start());
3033
3034   // Set up an expired cookie.
3035   {
3036     TestNetworkDelegate network_delegate;
3037     default_context_.set_network_delegate(&network_delegate);
3038     TestDelegate d;
3039     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3040         test_server.GetURL(
3041             "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
3042         DEFAULT_PRIORITY, &d, NULL));
3043     req->Start();
3044     base::RunLoop().Run();
3045   }
3046   // Verify that the cookie is not set.
3047   {
3048     TestNetworkDelegate network_delegate;
3049     default_context_.set_network_delegate(&network_delegate);
3050     TestDelegate d;
3051     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3052         test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
3053     req->Start();
3054     base::RunLoop().Run();
3055
3056     EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3057   }
3058   // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3059   {
3060     FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3061     default_context_.set_network_delegate(&network_delegate);
3062     TestDelegate d;
3063     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3064         test_server.GetURL(
3065             "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
3066         DEFAULT_PRIORITY, &d, NULL));
3067     req->Start();
3068     base::RunLoop().Run();
3069   }
3070   // Verify that the cookie is set.
3071   {
3072     TestNetworkDelegate network_delegate;
3073     default_context_.set_network_delegate(&network_delegate);
3074     TestDelegate d;
3075     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3076         test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
3077     req->Start();
3078     base::RunLoop().Run();
3079
3080     EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3081   }
3082 }
3083
3084
3085 // Check that it is impossible to change the referrer in the extra headers of
3086 // an URLRequest.
3087 TEST_F(URLRequestTest, DoNotOverrideReferrer) {
3088   LocalHttpTestServer test_server;
3089   ASSERT_TRUE(test_server.Start());
3090
3091   // If extra headers contain referer and the request contains a referer,
3092   // only the latter shall be respected.
3093   {
3094     TestDelegate d;
3095     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3096         test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
3097     req->SetReferrer("http://foo.com/");
3098
3099     HttpRequestHeaders headers;
3100     headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
3101     req->SetExtraRequestHeaders(headers);
3102
3103     req->Start();
3104     base::RunLoop().Run();
3105
3106     EXPECT_EQ("http://foo.com/", d.data_received());
3107   }
3108
3109   // If extra headers contain a referer but the request does not, no referer
3110   // shall be sent in the header.
3111   {
3112     TestDelegate d;
3113     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3114         test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
3115
3116     HttpRequestHeaders headers;
3117     headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
3118     req->SetExtraRequestHeaders(headers);
3119     req->SetLoadFlags(LOAD_VALIDATE_CACHE);
3120
3121     req->Start();
3122     base::RunLoop().Run();
3123
3124     EXPECT_EQ("None", d.data_received());
3125   }
3126 }
3127
3128 class URLRequestTestHTTP : public URLRequestTest {
3129  public:
3130   URLRequestTestHTTP()
3131       : test_server_(base::FilePath(FILE_PATH_LITERAL(
3132                                   "net/data/url_request_unittest"))) {
3133   }
3134
3135  protected:
3136   // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3137   // |request_method| is the method to use for the initial request.
3138   // |redirect_method| is the method that is expected to be used for the second
3139   // request, after redirection.
3140   // If |include_data| is true, data is uploaded with the request.  The
3141   // response body is expected to match it exactly, if and only if
3142   // |request_method| == |redirect_method|.
3143   void HTTPRedirectMethodTest(const GURL& redirect_url,
3144                               const std::string& request_method,
3145                               const std::string& redirect_method,
3146                               bool include_data) {
3147     static const char kData[] = "hello world";
3148     TestDelegate d;
3149     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3150         redirect_url, DEFAULT_PRIORITY, &d, NULL));
3151     req->set_method(request_method);
3152     if (include_data) {
3153       req->set_upload(CreateSimpleUploadData(kData));
3154       HttpRequestHeaders headers;
3155       headers.SetHeader(HttpRequestHeaders::kContentLength,
3156                         base::UintToString(arraysize(kData) - 1));
3157       req->SetExtraRequestHeaders(headers);
3158     }
3159     req->Start();
3160     base::RunLoop().Run();
3161     EXPECT_EQ(redirect_method, req->method());
3162     EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
3163     EXPECT_EQ(OK, req->status().error());
3164     if (include_data) {
3165       if (request_method == redirect_method) {
3166         EXPECT_EQ(kData, d.data_received());
3167       } else {
3168         EXPECT_NE(kData, d.data_received());
3169       }
3170     }
3171     if (HasFailure())
3172       LOG(WARNING) << "Request method was: " << request_method;
3173   }
3174
3175   void HTTPUploadDataOperationTest(const std::string& method) {
3176     const int kMsgSize = 20000;  // multiple of 10
3177     const int kIterations = 50;
3178     char* uploadBytes = new char[kMsgSize+1];
3179     char* ptr = uploadBytes;
3180     char marker = 'a';
3181     for (int idx = 0; idx < kMsgSize/10; idx++) {
3182       memcpy(ptr, "----------", 10);
3183       ptr += 10;
3184       if (idx % 100 == 0) {
3185         ptr--;
3186         *ptr++ = marker;
3187         if (++marker > 'z')
3188           marker = 'a';
3189       }
3190     }
3191     uploadBytes[kMsgSize] = '\0';
3192
3193     for (int i = 0; i < kIterations; ++i) {
3194       TestDelegate d;
3195       scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3196           test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
3197       r->set_method(method.c_str());
3198
3199       r->set_upload(CreateSimpleUploadData(uploadBytes));
3200
3201       r->Start();
3202       EXPECT_TRUE(r->is_pending());
3203
3204       base::RunLoop().Run();
3205
3206       ASSERT_EQ(1, d.response_started_count())
3207           << "request failed: " << r->status().status()
3208           << ", os error: " << r->status().error();
3209
3210       EXPECT_FALSE(d.received_data_before_response());
3211       EXPECT_EQ(uploadBytes, d.data_received());
3212     }
3213     delete[] uploadBytes;
3214   }
3215
3216   void AddChunksToUpload(URLRequest* r) {
3217     r->AppendChunkToUpload("a", 1, false);
3218     r->AppendChunkToUpload("bcd", 3, false);
3219     r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
3220     r->AppendChunkToUpload("\r\n\r\n", 4, false);
3221     r->AppendChunkToUpload("0", 1, false);
3222     r->AppendChunkToUpload("2323", 4, true);
3223   }
3224
3225   void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
3226     // This should match the chunks sent by AddChunksToUpload().
3227     const std::string expected_data =
3228         "abcdthis is a longer chunk than before.\r\n\r\n02323";
3229
3230     ASSERT_EQ(1, d->response_started_count())
3231         << "request failed: " << r->status().status()
3232         << ", os error: " << r->status().error();
3233
3234     EXPECT_FALSE(d->received_data_before_response());
3235
3236     EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
3237     EXPECT_EQ(expected_data, d->data_received());
3238   }
3239
3240   bool DoManyCookiesRequest(int num_cookies) {
3241     TestDelegate d;
3242     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3243         test_server_.GetURL("set-many-cookies?" +
3244                                 base::IntToString(num_cookies)),
3245         DEFAULT_PRIORITY, &d, NULL));
3246
3247     r->Start();
3248     EXPECT_TRUE(r->is_pending());
3249
3250     base::RunLoop().Run();
3251
3252     bool is_success = r->status().is_success();
3253
3254     if (!is_success) {
3255       EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
3256       // The test server appears to be unable to handle subsequent requests
3257       // after this error is triggered. Force it to restart.
3258       EXPECT_TRUE(test_server_.Stop());
3259       EXPECT_TRUE(test_server_.Start());
3260     }
3261
3262     return is_success;
3263   }
3264
3265   LocalHttpTestServer* test_server() {
3266     return &test_server_;
3267   }
3268
3269  protected:
3270   LocalHttpTestServer test_server_;
3271 };
3272
3273 // In this unit test, we're using the HTTPTestServer as a proxy server and
3274 // issuing a CONNECT request with the magic host name "www.redirect.com".
3275 // The HTTPTestServer will return a 302 response, which we should not
3276 // follow.
3277 TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
3278   ASSERT_TRUE(test_server_.Start());
3279
3280   TestNetworkDelegate network_delegate;  // Must outlive URLRequest.
3281   TestURLRequestContextWithProxy context(
3282       test_server_.host_port_pair().ToString(), &network_delegate);
3283
3284   TestDelegate d;
3285   {
3286     scoped_ptr<URLRequest> r(context.CreateRequest(
3287         GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, NULL));
3288     r->Start();
3289     EXPECT_TRUE(r->is_pending());
3290
3291     base::RunLoop().Run();
3292
3293     EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3294     // The proxy server is not set before failure.
3295     EXPECT_TRUE(r->proxy_server().IsEmpty());
3296     EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
3297     EXPECT_EQ(1, d.response_started_count());
3298     // We should not have followed the redirect.
3299     EXPECT_EQ(0, d.received_redirect_count());
3300   }
3301 }
3302
3303 // This is the same as the previous test, but checks that the network delegate
3304 // registers the error.
3305 TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
3306   ASSERT_TRUE(test_server_.Start());
3307
3308   TestNetworkDelegate network_delegate;  // Must outlive URLRequest.
3309   TestURLRequestContextWithProxy context(
3310       test_server_.host_port_pair().ToString(), &network_delegate);
3311
3312   TestDelegate d;
3313   {
3314     scoped_ptr<URLRequest> r(context.CreateRequest(
3315         GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, NULL));
3316     r->Start();
3317     EXPECT_TRUE(r->is_pending());
3318
3319     base::RunLoop().Run();
3320
3321     EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3322     // The proxy server is not set before failure.
3323     EXPECT_TRUE(r->proxy_server().IsEmpty());
3324     EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
3325     EXPECT_EQ(1, d.response_started_count());
3326     // We should not have followed the redirect.
3327     EXPECT_EQ(0, d.received_redirect_count());
3328
3329     EXPECT_EQ(1, network_delegate.error_count());
3330     EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
3331   }
3332 }
3333
3334 // Tests that we can block and asynchronously return OK in various stages.
3335 TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3336   static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3337     BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3338     BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3339     BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3340   };
3341   static const size_t blocking_stages_length = arraysize(blocking_stages);
3342
3343   ASSERT_TRUE(test_server_.Start());
3344
3345   TestDelegate d;
3346   BlockingNetworkDelegate network_delegate(
3347       BlockingNetworkDelegate::USER_CALLBACK);
3348   network_delegate.set_block_on(
3349       BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3350       BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3351       BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3352
3353   TestURLRequestContext context(true);
3354   context.set_network_delegate(&network_delegate);
3355   context.Init();
3356
3357   {
3358     scoped_ptr<URLRequest> r(context.CreateRequest(
3359         test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
3360
3361     r->Start();
3362     for (size_t i = 0; i < blocking_stages_length; ++i) {
3363       base::RunLoop().Run();
3364       EXPECT_EQ(blocking_stages[i],
3365                 network_delegate.stage_blocked_for_callback());
3366       network_delegate.DoCallback(OK);
3367     }
3368     base::RunLoop().Run();
3369     EXPECT_EQ(200, r->GetResponseCode());
3370     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3371     EXPECT_EQ(1, network_delegate.created_requests());
3372     EXPECT_EQ(0, network_delegate.destroyed_requests());
3373   }
3374   EXPECT_EQ(1, network_delegate.destroyed_requests());
3375 }
3376
3377 // Tests that the network delegate can block and cancel a request.
3378 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
3379   ASSERT_TRUE(test_server_.Start());
3380
3381   TestDelegate d;
3382   BlockingNetworkDelegate network_delegate(
3383       BlockingNetworkDelegate::AUTO_CALLBACK);
3384   network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3385   network_delegate.set_retval(ERR_EMPTY_RESPONSE);
3386
3387   TestURLRequestContextWithProxy context(
3388       test_server_.host_port_pair().ToString(), &network_delegate);
3389
3390   {
3391     scoped_ptr<URLRequest> r(context.CreateRequest(
3392         test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
3393
3394     r->Start();
3395     base::RunLoop().Run();
3396
3397     EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3398     // The proxy server is not set before cancellation.
3399     EXPECT_TRUE(r->proxy_server().IsEmpty());
3400     EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
3401     EXPECT_EQ(1, network_delegate.created_requests());
3402     EXPECT_EQ(0, network_delegate.destroyed_requests());
3403   }
3404   EXPECT_EQ(1, network_delegate.destroyed_requests());
3405 }
3406
3407 // Helper function for NetworkDelegateCancelRequestAsynchronously and
3408 // NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3409 // delegate operating in |block_mode| and a request for |url|. It blocks the
3410 // request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3411 void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3412                                   BlockingNetworkDelegate::Stage stage,
3413                                   const GURL& url) {
3414   TestDelegate d;
3415   BlockingNetworkDelegate network_delegate(block_mode);
3416   network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3417   network_delegate.set_block_on(stage);
3418
3419   TestURLRequestContext context(true);
3420   context.set_network_delegate(&network_delegate);
3421   context.Init();
3422
3423   {
3424     scoped_ptr<URLRequest> r(context.CreateRequest(
3425         url, DEFAULT_PRIORITY, &d, NULL));
3426
3427     r->Start();
3428     base::RunLoop().Run();
3429
3430     EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3431     // The proxy server is not set before cancellation.
3432     EXPECT_TRUE(r->proxy_server().IsEmpty());
3433     EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
3434     EXPECT_EQ(1, network_delegate.created_requests());
3435     EXPECT_EQ(0, network_delegate.destroyed_requests());
3436   }
3437   EXPECT_EQ(1, network_delegate.destroyed_requests());
3438 }
3439
3440 // The following 3 tests check that the network delegate can cancel a request
3441 // synchronously in various stages of the request.
3442 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
3443   ASSERT_TRUE(test_server_.Start());
3444   NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3445                                BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3446                                test_server_.GetURL(std::string()));
3447 }
3448
3449 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
3450   ASSERT_TRUE(test_server_.Start());
3451   NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3452                                BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3453                                test_server_.GetURL(std::string()));
3454 }
3455
3456 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
3457   ASSERT_TRUE(test_server_.Start());
3458   NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3459                                BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3460                                test_server_.GetURL(std::string()));
3461 }
3462
3463 // The following 3 tests check that the network delegate can cancel a request
3464 // asynchronously in various stages of the request.
3465 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
3466   ASSERT_TRUE(test_server_.Start());
3467   NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3468                                BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3469                                test_server_.GetURL(std::string()));
3470 }
3471
3472 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
3473   ASSERT_TRUE(test_server_.Start());
3474   NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3475                                BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3476                                test_server_.GetURL(std::string()));
3477 }
3478
3479 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
3480   ASSERT_TRUE(test_server_.Start());
3481   NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3482                                BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3483                                test_server_.GetURL(std::string()));
3484 }
3485
3486 // Tests that the network delegate can block and redirect a request to a new
3487 // URL.
3488 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
3489   ASSERT_TRUE(test_server_.Start());
3490
3491   TestDelegate d;
3492   BlockingNetworkDelegate network_delegate(
3493       BlockingNetworkDelegate::AUTO_CALLBACK);
3494   network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3495   GURL redirect_url(test_server_.GetURL("simple.html"));
3496   network_delegate.set_redirect_url(redirect_url);
3497
3498   TestURLRequestContextWithProxy context(
3499       test_server_.host_port_pair().ToString(), &network_delegate);
3500
3501   {
3502     GURL original_url(test_server_.GetURL("empty.html"));
3503     scoped_ptr<URLRequest> r(context.CreateRequest(
3504         original_url, DEFAULT_PRIORITY, &d, NULL));
3505
3506     // Quit after hitting the redirect, so can check the headers.
3507     d.set_quit_on_redirect(true);
3508     r->Start();
3509     base::RunLoop().Run();
3510
3511     // Check headers from URLRequestJob.
3512     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3513     EXPECT_EQ(307, r->GetResponseCode());
3514     EXPECT_EQ(307, r->response_headers()->response_code());
3515     std::string location;
3516     ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3517                                                        &location));
3518     EXPECT_EQ(redirect_url, GURL(location));
3519
3520     // Let the request finish.
3521     r->FollowDeferredRedirect();
3522     base::RunLoop().Run();
3523     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3524     EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
3525     EXPECT_EQ(
3526         1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3527     EXPECT_TRUE(
3528         network_delegate.last_observed_proxy().Equals(
3529             test_server_.host_port_pair()));
3530
3531     EXPECT_EQ(0, r->status().error());
3532     EXPECT_EQ(redirect_url, r->url());
3533     EXPECT_EQ(original_url, r->original_url());
3534     EXPECT_EQ(2U, r->url_chain().size());
3535     EXPECT_EQ(1, network_delegate.created_requests());
3536     EXPECT_EQ(0, network_delegate.destroyed_requests());
3537   }
3538   EXPECT_EQ(1, network_delegate.destroyed_requests());
3539 }
3540
3541 // Tests that the network delegate can block and redirect a request to a new
3542 // URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3543 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
3544   ASSERT_TRUE(test_server_.Start());
3545
3546   TestDelegate d;
3547   BlockingNetworkDelegate network_delegate(
3548       BlockingNetworkDelegate::SYNCHRONOUS);
3549   GURL redirect_url(test_server_.GetURL("simple.html"));
3550   network_delegate.set_redirect_url(redirect_url);
3551
3552   TestURLRequestContextWithProxy context(
3553       test_server_.host_port_pair().ToString(), &network_delegate);
3554
3555   {
3556     GURL original_url(test_server_.GetURL("empty.html"));
3557     scoped_ptr<URLRequest> r(context.CreateRequest(
3558         original_url, DEFAULT_PRIORITY, &d, NULL));
3559
3560     // Quit after hitting the redirect, so can check the headers.
3561     d.set_quit_on_redirect(true);
3562     r->Start();
3563     base::RunLoop().Run();
3564
3565     // Check headers from URLRequestJob.
3566     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3567     EXPECT_EQ(307, r->GetResponseCode());
3568     EXPECT_EQ(307, r->response_headers()->response_code());
3569     std::string location;
3570     ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3571                                                        &location));
3572     EXPECT_EQ(redirect_url, GURL(location));
3573
3574     // Let the request finish.
3575     r->FollowDeferredRedirect();
3576     base::RunLoop().Run();
3577
3578     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3579     EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
3580     EXPECT_EQ(
3581         1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3582     EXPECT_TRUE(
3583         network_delegate.last_observed_proxy().Equals(
3584             test_server_.host_port_pair()));
3585     EXPECT_EQ(0, r->status().error());
3586     EXPECT_EQ(redirect_url, r->url());
3587     EXPECT_EQ(original_url, r->original_url());
3588     EXPECT_EQ(2U, r->url_chain().size());
3589     EXPECT_EQ(1, network_delegate.created_requests());
3590     EXPECT_EQ(0, network_delegate.destroyed_requests());
3591   }
3592   EXPECT_EQ(1, network_delegate.destroyed_requests());
3593 }
3594
3595 // Tests that redirects caused by the network delegate preserve POST data.
3596 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
3597   ASSERT_TRUE(test_server_.Start());
3598
3599   const char kData[] = "hello world";
3600
3601   TestDelegate d;
3602   BlockingNetworkDelegate network_delegate(
3603       BlockingNetworkDelegate::AUTO_CALLBACK);
3604   network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3605   GURL redirect_url(test_server_.GetURL("echo"));
3606   network_delegate.set_redirect_url(redirect_url);
3607
3608   TestURLRequestContext context(true);
3609   context.set_network_delegate(&network_delegate);
3610   context.Init();
3611
3612   {
3613     GURL original_url(test_server_.GetURL("empty.html"));
3614     scoped_ptr<URLRequest> r(context.CreateRequest(
3615         original_url, DEFAULT_PRIORITY, &d, NULL));
3616     r->set_method("POST");
3617     r->set_upload(CreateSimpleUploadData(kData));
3618     HttpRequestHeaders headers;
3619     headers.SetHeader(HttpRequestHeaders::kContentLength,
3620                       base::UintToString(arraysize(kData) - 1));
3621     r->SetExtraRequestHeaders(headers);
3622
3623     // Quit after hitting the redirect, so can check the headers.
3624     d.set_quit_on_redirect(true);
3625     r->Start();
3626     base::RunLoop().Run();
3627
3628     // Check headers from URLRequestJob.
3629     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3630     EXPECT_EQ(307, r->GetResponseCode());
3631     EXPECT_EQ(307, r->response_headers()->response_code());
3632     std::string location;
3633     ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3634                                                        &location));
3635     EXPECT_EQ(redirect_url, GURL(location));
3636
3637     // Let the request finish.
3638     r->FollowDeferredRedirect();
3639     base::RunLoop().Run();
3640
3641     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3642     EXPECT_EQ(0, r->status().error());
3643     EXPECT_EQ(redirect_url, r->url());
3644     EXPECT_EQ(original_url, r->original_url());
3645     EXPECT_EQ(2U, r->url_chain().size());
3646     EXPECT_EQ(1, network_delegate.created_requests());
3647     EXPECT_EQ(0, network_delegate.destroyed_requests());
3648     EXPECT_EQ("POST", r->method());
3649     EXPECT_EQ(kData, d.data_received());
3650   }
3651   EXPECT_EQ(1, network_delegate.destroyed_requests());
3652 }
3653
3654 // Tests that the network delegate can block and redirect a request to a new
3655 // URL during OnHeadersReceived.
3656 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3657   ASSERT_TRUE(test_server_.Start());
3658
3659   TestDelegate d;
3660   BlockingNetworkDelegate network_delegate(
3661       BlockingNetworkDelegate::AUTO_CALLBACK);
3662   network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3663   GURL redirect_url(test_server_.GetURL("simple.html"));
3664   network_delegate.set_redirect_on_headers_received_url(redirect_url);
3665
3666   TestURLRequestContextWithProxy context(
3667       test_server_.host_port_pair().ToString(), &network_delegate);
3668
3669   {
3670     GURL original_url(test_server_.GetURL("empty.html"));
3671     scoped_ptr<URLRequest> r(context.CreateRequest(
3672         original_url, DEFAULT_PRIORITY, &d, NULL));
3673
3674     r->Start();
3675     base::RunLoop().Run();
3676
3677     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3678     EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
3679     EXPECT_EQ(
3680         2, network_delegate.observed_before_proxy_headers_sent_callbacks());
3681     EXPECT_TRUE(
3682         network_delegate.last_observed_proxy().Equals(
3683             test_server_.host_port_pair()));
3684
3685     EXPECT_EQ(OK, r->status().error());
3686     EXPECT_EQ(redirect_url, r->url());
3687     EXPECT_EQ(original_url, r->original_url());
3688     EXPECT_EQ(2U, r->url_chain().size());
3689     EXPECT_EQ(2, network_delegate.created_requests());
3690     EXPECT_EQ(0, network_delegate.destroyed_requests());
3691   }
3692   EXPECT_EQ(1, network_delegate.destroyed_requests());
3693 }
3694
3695 // Tests that the network delegate can synchronously complete OnAuthRequired
3696 // by taking no action. This indicates that the NetworkDelegate does not want to
3697 // handle the challenge, and is passing the buck along to the
3698 // URLRequest::Delegate.
3699 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3700   ASSERT_TRUE(test_server_.Start());
3701
3702   TestDelegate d;
3703   BlockingNetworkDelegate network_delegate(
3704       BlockingNetworkDelegate::SYNCHRONOUS);
3705
3706   TestURLRequestContext context(true);
3707   context.set_network_delegate(&network_delegate);
3708   context.Init();
3709
3710   d.set_credentials(AuthCredentials(kUser, kSecret));
3711
3712   {
3713     GURL url(test_server_.GetURL("auth-basic"));
3714     scoped_ptr<URLRequest> r(context.CreateRequest(
3715         url, DEFAULT_PRIORITY, &d, NULL));
3716     r->Start();
3717
3718     base::RunLoop().Run();
3719
3720     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3721     EXPECT_EQ(0, r->status().error());
3722     EXPECT_EQ(200, r->GetResponseCode());
3723     EXPECT_TRUE(d.auth_required_called());
3724     EXPECT_EQ(1, network_delegate.created_requests());
3725     EXPECT_EQ(0, network_delegate.destroyed_requests());
3726   }
3727   EXPECT_EQ(1, network_delegate.destroyed_requests());
3728 }
3729
3730 TEST_F(URLRequestTestHTTP,
3731     NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3732   ASSERT_TRUE(test_server_.Start());
3733
3734   TestDelegate d;
3735   BlockingNetworkDelegate network_delegate(
3736       BlockingNetworkDelegate::SYNCHRONOUS);
3737
3738   TestURLRequestContext context(true);
3739   context.set_network_delegate(&network_delegate);
3740   context.Init();
3741
3742   d.set_credentials(AuthCredentials(kUser, kSecret));
3743
3744   {
3745     GURL url(test_server_.GetURL("auth-basic"));
3746     scoped_ptr<URLRequest> r(context.CreateRequest(
3747         url, DEFAULT_PRIORITY, &d, NULL));
3748     r->Start();
3749
3750     {
3751       HttpRequestHeaders headers;
3752       EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3753       EXPECT_FALSE(headers.HasHeader("Authorization"));
3754     }
3755
3756     base::RunLoop().Run();
3757
3758     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3759     EXPECT_EQ(0, r->status().error());
3760     EXPECT_EQ(200, r->GetResponseCode());
3761     EXPECT_TRUE(d.auth_required_called());
3762     EXPECT_EQ(1, network_delegate.created_requests());
3763     EXPECT_EQ(0, network_delegate.destroyed_requests());
3764   }
3765   EXPECT_EQ(1, network_delegate.destroyed_requests());
3766 }
3767
3768 // Tests that the network delegate can synchronously complete OnAuthRequired
3769 // by setting credentials.
3770 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3771   ASSERT_TRUE(test_server_.Start());
3772
3773   TestDelegate d;
3774   BlockingNetworkDelegate network_delegate(
3775       BlockingNetworkDelegate::SYNCHRONOUS);
3776   network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3777   network_delegate.set_auth_retval(
3778       NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3779
3780   network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3781
3782   TestURLRequestContext context(true);
3783   context.set_network_delegate(&network_delegate);
3784   context.Init();
3785
3786   {
3787     GURL url(test_server_.GetURL("auth-basic"));
3788     scoped_ptr<URLRequest> r(context.CreateRequest(
3789         url, DEFAULT_PRIORITY, &d, NULL));
3790     r->Start();
3791     base::RunLoop().Run();
3792
3793     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3794     EXPECT_EQ(0, r->status().error());
3795     EXPECT_EQ(200, r->GetResponseCode());
3796     EXPECT_FALSE(d.auth_required_called());
3797     EXPECT_EQ(1, network_delegate.created_requests());
3798     EXPECT_EQ(0, network_delegate.destroyed_requests());
3799   }
3800   EXPECT_EQ(1, network_delegate.destroyed_requests());
3801 }
3802
3803 // Same as above, but also tests that GetFullRequestHeaders returns the proper
3804 // headers (for the first or second request) when called at the proper times.
3805 TEST_F(URLRequestTestHTTP,
3806     NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3807   ASSERT_TRUE(test_server_.Start());
3808
3809   TestDelegate d;
3810   BlockingNetworkDelegate network_delegate(
3811       BlockingNetworkDelegate::SYNCHRONOUS);
3812   network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3813   network_delegate.set_auth_retval(
3814       NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3815
3816   network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3817
3818   TestURLRequestContext context(true);
3819   context.set_network_delegate(&network_delegate);
3820   context.Init();
3821
3822   {
3823     GURL url(test_server_.GetURL("auth-basic"));
3824     scoped_ptr<URLRequest> r(context.CreateRequest(
3825         url, DEFAULT_PRIORITY, &d, NULL));
3826     r->Start();
3827     base::RunLoop().Run();
3828
3829     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3830     EXPECT_EQ(0, r->status().error());
3831     EXPECT_EQ(200, r->GetResponseCode());
3832     EXPECT_FALSE(d.auth_required_called());
3833     EXPECT_EQ(1, network_delegate.created_requests());
3834     EXPECT_EQ(0, network_delegate.destroyed_requests());
3835
3836     {
3837       HttpRequestHeaders headers;
3838       EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3839       EXPECT_TRUE(headers.HasHeader("Authorization"));
3840     }
3841   }
3842   EXPECT_EQ(1, network_delegate.destroyed_requests());
3843 }
3844
3845 // Tests that the network delegate can synchronously complete OnAuthRequired
3846 // by cancelling authentication.
3847 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3848   ASSERT_TRUE(test_server_.Start());
3849
3850   TestDelegate d;
3851   BlockingNetworkDelegate network_delegate(
3852       BlockingNetworkDelegate::SYNCHRONOUS);
3853   network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3854   network_delegate.set_auth_retval(
3855       NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3856
3857   TestURLRequestContext context(true);
3858   context.set_network_delegate(&network_delegate);
3859   context.Init();
3860
3861   {
3862     GURL url(test_server_.GetURL("auth-basic"));
3863     scoped_ptr<URLRequest> r(context.CreateRequest(
3864         url, DEFAULT_PRIORITY, &d, NULL));
3865     r->Start();
3866     base::RunLoop().Run();
3867
3868     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3869     EXPECT_EQ(OK, r->status().error());
3870     EXPECT_EQ(401, r->GetResponseCode());
3871     EXPECT_FALSE(d.auth_required_called());
3872     EXPECT_EQ(1, network_delegate.created_requests());
3873     EXPECT_EQ(0, network_delegate.destroyed_requests());
3874   }
3875   EXPECT_EQ(1, network_delegate.destroyed_requests());
3876 }
3877
3878 // Tests that the network delegate can asynchronously complete OnAuthRequired
3879 // by taking no action. This indicates that the NetworkDelegate does not want
3880 // to handle the challenge, and is passing the buck along to the
3881 // URLRequest::Delegate.
3882 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3883   ASSERT_TRUE(test_server_.Start());
3884
3885   TestDelegate d;
3886   BlockingNetworkDelegate network_delegate(
3887       BlockingNetworkDelegate::AUTO_CALLBACK);
3888   network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3889
3890   TestURLRequestContext context(true);
3891   context.set_network_delegate(&network_delegate);
3892   context.Init();
3893
3894   d.set_credentials(AuthCredentials(kUser, kSecret));
3895
3896   {
3897     GURL url(test_server_.GetURL("auth-basic"));
3898     scoped_ptr<URLRequest> r(context.CreateRequest(
3899         url, DEFAULT_PRIORITY, &d, NULL));
3900     r->Start();
3901     base::RunLoop().Run();
3902
3903     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3904     EXPECT_EQ(0, r->status().error());
3905     EXPECT_EQ(200, r->GetResponseCode());
3906     EXPECT_TRUE(d.auth_required_called());
3907     EXPECT_EQ(1, network_delegate.created_requests());
3908     EXPECT_EQ(0, network_delegate.destroyed_requests());
3909   }
3910   EXPECT_EQ(1, network_delegate.destroyed_requests());
3911 }
3912
3913 // Tests that the network delegate can asynchronously complete OnAuthRequired
3914 // by setting credentials.
3915 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3916   ASSERT_TRUE(test_server_.Start());
3917
3918   TestDelegate d;
3919   BlockingNetworkDelegate network_delegate(
3920       BlockingNetworkDelegate::AUTO_CALLBACK);
3921   network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3922   network_delegate.set_auth_retval(
3923       NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3924
3925   AuthCredentials auth_credentials(kUser, kSecret);
3926   network_delegate.set_auth_credentials(auth_credentials);
3927
3928   TestURLRequestContext context(true);
3929   context.set_network_delegate(&network_delegate);
3930   context.Init();
3931
3932   {
3933     GURL url(test_server_.GetURL("auth-basic"));
3934     scoped_ptr<URLRequest> r(context.CreateRequest(
3935         url, DEFAULT_PRIORITY, &d, NULL));
3936     r->Start();
3937     base::RunLoop().Run();
3938
3939     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3940     EXPECT_EQ(0, r->status().error());
3941
3942     EXPECT_EQ(200, r->GetResponseCode());
3943     EXPECT_FALSE(d.auth_required_called());
3944     EXPECT_EQ(1, network_delegate.created_requests());
3945     EXPECT_EQ(0, network_delegate.destroyed_requests());
3946   }
3947   EXPECT_EQ(1, network_delegate.destroyed_requests());
3948 }
3949
3950 // Tests that the network delegate can asynchronously complete OnAuthRequired
3951 // by cancelling authentication.
3952 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3953   ASSERT_TRUE(test_server_.Start());
3954
3955   TestDelegate d;
3956   BlockingNetworkDelegate network_delegate(
3957       BlockingNetworkDelegate::AUTO_CALLBACK);
3958   network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3959   network_delegate.set_auth_retval(
3960       NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3961
3962   TestURLRequestContext context(true);
3963   context.set_network_delegate(&network_delegate);
3964   context.Init();
3965
3966   {
3967     GURL url(test_server_.GetURL("auth-basic"));
3968     scoped_ptr<URLRequest> r(context.CreateRequest(
3969         url, DEFAULT_PRIORITY, &d, NULL));
3970     r->Start();
3971     base::RunLoop().Run();
3972
3973     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3974     EXPECT_EQ(OK, r->status().error());
3975     EXPECT_EQ(401, r->GetResponseCode());
3976     EXPECT_FALSE(d.auth_required_called());
3977     EXPECT_EQ(1, network_delegate.created_requests());
3978     EXPECT_EQ(0, network_delegate.destroyed_requests());
3979   }
3980   EXPECT_EQ(1, network_delegate.destroyed_requests());
3981 }
3982
3983 // Tests that we can handle when a network request was canceled while we were
3984 // waiting for the network delegate.
3985 // Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3986 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3987   ASSERT_TRUE(test_server_.Start());
3988
3989   TestDelegate d;
3990   BlockingNetworkDelegate network_delegate(
3991       BlockingNetworkDelegate::USER_CALLBACK);
3992   network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3993
3994   TestURLRequestContext context(true);
3995   context.set_network_delegate(&network_delegate);
3996   context.Init();
3997
3998   {
3999     scoped_ptr<URLRequest> r(context.CreateRequest(
4000         test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4001
4002     r->Start();
4003     base::RunLoop().Run();
4004     EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4005               network_delegate.stage_blocked_for_callback());
4006     EXPECT_EQ(0, network_delegate.completed_requests());
4007     // Cancel before callback.
4008     r->Cancel();
4009     // Ensure that network delegate is notified.
4010     EXPECT_EQ(1, network_delegate.completed_requests());
4011     EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4012     EXPECT_EQ(ERR_ABORTED, r->status().error());
4013     EXPECT_EQ(1, network_delegate.created_requests());
4014     EXPECT_EQ(0, network_delegate.destroyed_requests());
4015   }
4016   EXPECT_EQ(1, network_delegate.destroyed_requests());
4017 }
4018
4019 // Tests that we can handle when a network request was canceled while we were
4020 // waiting for the network delegate.
4021 // Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
4022 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
4023   ASSERT_TRUE(test_server_.Start());
4024
4025   TestDelegate d;
4026   BlockingNetworkDelegate network_delegate(
4027       BlockingNetworkDelegate::USER_CALLBACK);
4028   network_delegate.set_block_on(
4029       BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
4030
4031   TestURLRequestContext context(true);
4032   context.set_network_delegate(&network_delegate);
4033   context.Init();
4034
4035   {
4036     scoped_ptr<URLRequest> r(context.CreateRequest(
4037         test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4038
4039     r->Start();
4040     base::RunLoop().Run();
4041     EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4042               network_delegate.stage_blocked_for_callback());
4043     EXPECT_EQ(0, network_delegate.completed_requests());
4044     // Cancel before callback.
4045     r->Cancel();
4046     // Ensure that network delegate is notified.
4047     EXPECT_EQ(1, network_delegate.completed_requests());
4048     EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4049     EXPECT_EQ(ERR_ABORTED, r->status().error());
4050     EXPECT_EQ(1, network_delegate.created_requests());
4051     EXPECT_EQ(0, network_delegate.destroyed_requests());
4052   }
4053   EXPECT_EQ(1, network_delegate.destroyed_requests());
4054 }
4055
4056 // Tests that we can handle when a network request was canceled while we were
4057 // waiting for the network delegate.
4058 // Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4059 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
4060   ASSERT_TRUE(test_server_.Start());
4061
4062   TestDelegate d;
4063   BlockingNetworkDelegate network_delegate(
4064       BlockingNetworkDelegate::USER_CALLBACK);
4065   network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
4066
4067   TestURLRequestContext context(true);
4068   context.set_network_delegate(&network_delegate);
4069   context.Init();
4070
4071   {
4072     scoped_ptr<URLRequest> r(context.CreateRequest(
4073         test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4074
4075     r->Start();
4076     base::RunLoop().Run();
4077     EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4078               network_delegate.stage_blocked_for_callback());
4079     EXPECT_EQ(0, network_delegate.completed_requests());
4080     // Cancel before callback.
4081     r->Cancel();
4082     // Ensure that network delegate is notified.
4083     EXPECT_EQ(1, network_delegate.completed_requests());
4084     EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4085     EXPECT_EQ(ERR_ABORTED, r->status().error());
4086     EXPECT_EQ(1, network_delegate.created_requests());
4087     EXPECT_EQ(0, network_delegate.destroyed_requests());
4088   }
4089   EXPECT_EQ(1, network_delegate.destroyed_requests());
4090 }
4091
4092 // Tests that we can handle when a network request was canceled while we were
4093 // waiting for the network delegate.
4094 // Part 4: Request is cancelled while waiting for OnAuthRequired callback.
4095 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
4096   ASSERT_TRUE(test_server_.Start());
4097
4098   TestDelegate d;
4099   BlockingNetworkDelegate network_delegate(
4100       BlockingNetworkDelegate::USER_CALLBACK);
4101   network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4102
4103   TestURLRequestContext context(true);
4104   context.set_network_delegate(&network_delegate);
4105   context.Init();
4106
4107   {
4108     scoped_ptr<URLRequest> r(context.CreateRequest(
4109         test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
4110
4111     r->Start();
4112     base::RunLoop().Run();
4113     EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4114               network_delegate.stage_blocked_for_callback());
4115     EXPECT_EQ(0, network_delegate.completed_requests());
4116     // Cancel before callback.
4117     r->Cancel();
4118     // Ensure that network delegate is notified.
4119     EXPECT_EQ(1, network_delegate.completed_requests());
4120     EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4121     EXPECT_EQ(ERR_ABORTED, r->status().error());
4122     EXPECT_EQ(1, network_delegate.created_requests());
4123     EXPECT_EQ(0, network_delegate.destroyed_requests());
4124   }
4125   EXPECT_EQ(1, network_delegate.destroyed_requests());
4126 }
4127
4128 // In this unit test, we're using the HTTPTestServer as a proxy server and
4129 // issuing a CONNECT request with the magic host name "www.server-auth.com".
4130 // The HTTPTestServer will return a 401 response, which we should balk at.
4131 TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
4132   ASSERT_TRUE(test_server_.Start());
4133
4134   TestNetworkDelegate network_delegate;  // Must outlive URLRequest.
4135   TestURLRequestContextWithProxy context(
4136       test_server_.host_port_pair().ToString(), &network_delegate);
4137
4138   TestDelegate d;
4139   {
4140     scoped_ptr<URLRequest> r(context.CreateRequest(
4141         GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d, NULL));
4142
4143     r->Start();
4144     EXPECT_TRUE(r->is_pending());
4145
4146     base::RunLoop().Run();
4147
4148     EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4149     // The proxy server is not set before failure.
4150     EXPECT_TRUE(r->proxy_server().IsEmpty());
4151     EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
4152   }
4153 }
4154
4155 TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
4156   ASSERT_TRUE(test_server_.Start());
4157
4158   TestDelegate d;
4159   {
4160     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4161         test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4162
4163     r->Start();
4164     EXPECT_TRUE(r->is_pending());
4165
4166     base::RunLoop().Run();
4167
4168     EXPECT_EQ(1, d.response_started_count());
4169     EXPECT_FALSE(d.received_data_before_response());
4170     EXPECT_NE(0, d.bytes_received());
4171     EXPECT_EQ(test_server_.host_port_pair().host(),
4172               r->GetSocketAddress().host());
4173     EXPECT_EQ(test_server_.host_port_pair().port(),
4174               r->GetSocketAddress().port());
4175
4176     // TODO(eroman): Add back the NetLog tests...
4177   }
4178 }
4179
4180 // This test has the server send a large number of cookies to the client.
4181 // To ensure that no number of cookies causes a crash, a galloping binary
4182 // search is used to estimate that maximum number of cookies that are accepted
4183 // by the browser. Beyond the maximum number, the request will fail with
4184 // ERR_RESPONSE_HEADERS_TOO_BIG.
4185 #if defined(OS_WIN)
4186 // http://crbug.com/177916
4187 #define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4188 #else
4189 #define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4190 #endif  // defined(OS_WIN)
4191 TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
4192   ASSERT_TRUE(test_server_.Start());
4193
4194   int lower_bound = 0;
4195   int upper_bound = 1;
4196
4197   // Double the number of cookies until the response header limits are
4198   // exceeded.
4199   while (DoManyCookiesRequest(upper_bound)) {
4200     lower_bound = upper_bound;
4201     upper_bound *= 2;
4202     ASSERT_LT(upper_bound, 1000000);
4203   }
4204
4205   int tolerance = upper_bound * 0.005;
4206   if (tolerance < 2)
4207     tolerance = 2;
4208
4209   // Perform a binary search to find the highest possible number of cookies,
4210   // within the desired tolerance.
4211   while (upper_bound - lower_bound >= tolerance) {
4212     int num_cookies = (lower_bound + upper_bound) / 2;
4213
4214     if (DoManyCookiesRequest(num_cookies))
4215       lower_bound = num_cookies;
4216     else
4217       upper_bound = num_cookies;
4218   }
4219   // Success: the test did not crash.
4220 }
4221
4222 TEST_F(URLRequestTestHTTP, GetTest) {
4223   ASSERT_TRUE(test_server_.Start());
4224
4225   TestDelegate d;
4226   {
4227     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4228         test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4229
4230     r->Start();
4231     EXPECT_TRUE(r->is_pending());
4232
4233     base::RunLoop().Run();
4234
4235     EXPECT_EQ(1, d.response_started_count());
4236     EXPECT_FALSE(d.received_data_before_response());
4237     EXPECT_NE(0, d.bytes_received());
4238     EXPECT_EQ(test_server_.host_port_pair().host(),
4239               r->GetSocketAddress().host());
4240     EXPECT_EQ(test_server_.host_port_pair().port(),
4241               r->GetSocketAddress().port());
4242   }
4243 }
4244
4245 TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
4246   ASSERT_TRUE(test_server_.Start());
4247
4248   TestDelegate d;
4249   {
4250     GURL test_url(test_server_.GetURL(std::string()));
4251     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4252         test_url, DEFAULT_PRIORITY, &d, NULL));
4253
4254     HttpRequestHeaders headers;
4255     EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
4256
4257     r->Start();
4258     EXPECT_TRUE(r->is_pending());
4259
4260     base::RunLoop().Run();
4261
4262     EXPECT_EQ(1, d.response_started_count());
4263     EXPECT_FALSE(d.received_data_before_response());
4264     EXPECT_NE(0, d.bytes_received());
4265     EXPECT_EQ(test_server_.host_port_pair().host(),
4266               r->GetSocketAddress().host());
4267     EXPECT_EQ(test_server_.host_port_pair().port(),
4268               r->GetSocketAddress().port());
4269
4270     EXPECT_TRUE(d.have_full_request_headers());
4271     CheckFullRequestHeaders(d.full_request_headers(), test_url);
4272   }
4273 }
4274
4275 TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
4276   ASSERT_TRUE(test_server_.Start());
4277
4278   TestDelegate d;
4279   {
4280     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4281         test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4282
4283     r->Start();
4284     EXPECT_TRUE(r->is_pending());
4285
4286     base::RunLoop().Run();
4287
4288     LoadTimingInfo load_timing_info;
4289     r->GetLoadTimingInfo(&load_timing_info);
4290     TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4291
4292     EXPECT_EQ(1, d.response_started_count());
4293     EXPECT_FALSE(d.received_data_before_response());
4294     EXPECT_NE(0, d.bytes_received());
4295     EXPECT_EQ(test_server_.host_port_pair().host(),
4296               r->GetSocketAddress().host());
4297     EXPECT_EQ(test_server_.host_port_pair().port(),
4298               r->GetSocketAddress().port());
4299   }
4300 }
4301
4302 TEST_F(URLRequestTestHTTP, GetZippedTest) {
4303   ASSERT_TRUE(test_server_.Start());
4304
4305   // Parameter that specifies the Content-Length field in the response:
4306   // C - Compressed length.
4307   // U - Uncompressed length.
4308   // L - Large length (larger than both C & U).
4309   // M - Medium length (between C & U).
4310   // S - Small length (smaller than both C & U).
4311   const char test_parameters[] = "CULMS";
4312   const int num_tests = arraysize(test_parameters)- 1;  // Skip NULL.
4313   // C & U should be OK.
4314   // L & M are larger than the data sent, and show an error.
4315   // S has too little data, but we seem to accept it.
4316   const bool test_expect_success[num_tests] =
4317       { true, true, false, false, true };
4318
4319   for (int i = 0; i < num_tests ; i++) {
4320     TestDelegate d;
4321     {
4322       std::string test_file =
4323           base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
4324                              test_parameters[i]);
4325
4326       TestNetworkDelegate network_delegate;  // Must outlive URLRequest.
4327       TestURLRequestContext context(true);
4328       context.set_network_delegate(&network_delegate);
4329       context.Init();
4330
4331       scoped_ptr<URLRequest> r(context.CreateRequest(
4332           test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d, NULL));
4333       r->Start();
4334       EXPECT_TRUE(r->is_pending());
4335
4336       base::RunLoop().Run();
4337
4338       EXPECT_EQ(1, d.response_started_count());
4339       EXPECT_FALSE(d.received_data_before_response());
4340       VLOG(1) << " Received " << d.bytes_received() << " bytes"
4341               << " status = " << r->status().status()
4342               << " error = " << r->status().error();
4343       if (test_expect_success[i]) {
4344         EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
4345             << " Parameter = \"" << test_file << "\"";
4346       } else {
4347         EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4348         EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
4349             << " Parameter = \"" << test_file << "\"";
4350       }
4351     }
4352   }
4353 }
4354
4355 TEST_F(URLRequestTestHTTP, HTTPSToHTTPRedirectNoRefererTest) {
4356   ASSERT_TRUE(test_server_.Start());
4357
4358   SpawnedTestServer https_test_server(
4359       SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
4360       base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
4361   ASSERT_TRUE(https_test_server.Start());
4362
4363   // An https server is sent a request with an https referer,
4364   // and responds with a redirect to an http url. The http
4365   // server should not be sent the referer.
4366   GURL http_destination = test_server_.GetURL(std::string());
4367   TestDelegate d;
4368   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
4369       https_test_server.GetURL("server-redirect?" + http_destination.spec()),
4370       DEFAULT_PRIORITY, &d, NULL));
4371   req->SetReferrer("https://www.referrer.com/");
4372   req->Start();
4373   base::RunLoop().Run();
4374
4375   EXPECT_EQ(1, d.response_started_count());
4376   EXPECT_EQ(1, d.received_redirect_count());
4377   EXPECT_EQ(http_destination, req->url());
4378   EXPECT_EQ(std::string(), req->referrer());
4379 }
4380
4381 TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
4382   ASSERT_TRUE(test_server_.Start());
4383
4384   GURL destination_url = test_server_.GetURL(std::string());
4385   GURL original_url =
4386       test_server_.GetURL("server-redirect?" + destination_url.spec());
4387   TestDelegate d;
4388   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
4389       original_url, DEFAULT_PRIORITY, &d, NULL));
4390   req->Start();
4391   base::RunLoop().Run();
4392
4393   EXPECT_EQ(1, d.response_started_count());
4394   EXPECT_EQ(1, d.received_redirect_count());
4395   EXPECT_EQ(destination_url, req->url());
4396   EXPECT_EQ(original_url, req->original_url());
4397   ASSERT_EQ(2U, req->url_chain().size());
4398   EXPECT_EQ(original_url, req->url_chain()[0]);
4399   EXPECT_EQ(destination_url, req->url_chain()[1]);
4400
4401   LoadTimingInfo load_timing_info_before_redirect;
4402   EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4403       &load_timing_info_before_redirect));
4404   TestLoadTimingNotReused(load_timing_info_before_redirect,
4405                           CONNECT_TIMING_HAS_DNS_TIMES);
4406
4407   LoadTimingInfo load_timing_info;
4408   req->GetLoadTimingInfo(&load_timing_info);
4409   TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4410
4411   // Check that a new socket was used on redirect, since the server does not
4412   // supposed keep-alive sockets, and that the times before the redirect are
4413   // before the ones recorded for the second request.
4414   EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4415             load_timing_info.socket_log_id);
4416   EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4417             load_timing_info.connect_timing.connect_start);
4418 }
4419
4420 TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
4421   ASSERT_TRUE(test_server_.Start());
4422
4423   GURL destination_url = test_server_.GetURL(std::string());
4424   GURL middle_redirect_url =
4425       test_server_.GetURL("server-redirect?" + destination_url.spec());
4426   GURL original_url = test_server_.GetURL(
4427       "server-redirect?" + middle_redirect_url.spec());
4428   TestDelegate d;
4429   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
4430       original_url, DEFAULT_PRIORITY, &d, NULL));
4431   req->Start();
4432   base::RunLoop().Run();
4433
4434   EXPECT_EQ(1, d.response_started_count());
4435   EXPECT_EQ(2, d.received_redirect_count());
4436   EXPECT_EQ(destination_url, req->url());
4437   EXPECT_EQ(original_url, req->original_url());
4438   ASSERT_EQ(3U, req->url_chain().size());
4439   EXPECT_EQ(original_url, req->url_chain()[0]);
4440   EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4441   EXPECT_EQ(destination_url, req->url_chain()[2]);
4442 }
4443
4444 // First and second pieces of information logged by delegates to URLRequests.
4445 const char kFirstDelegateInfo[] = "Wonderful delegate";
4446 const char kSecondDelegateInfo[] = "Exciting delegate";
4447
4448 // Logs delegate information to a URLRequest.  The first string is logged
4449 // synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY.  The second is
4450 // logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER.  Then
4451 // another asynchronous call is used to clear the delegate information
4452 // before calling a callback.  The object then deletes itself.
4453 class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4454  public:
4455   typedef base::Callback<void()> Callback;
4456
4457   // Each time delegate information is added to the URLRequest, the resulting
4458   // load state is checked.  The expected load state after each request is
4459   // passed in as an argument.
4460   static void Run(URLRequest* url_request,
4461                   LoadState expected_first_load_state,
4462                   LoadState expected_second_load_state,
4463                   LoadState expected_third_load_state,
4464                   const Callback& callback) {
4465     AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4466         url_request,
4467         expected_first_load_state,
4468         expected_second_load_state,
4469         expected_third_load_state,
4470         callback);
4471     logger->Start();
4472   }
4473
4474   // Checks that the log entries, starting with log_position, contain the
4475   // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4476   // recorded.  Returns the index of entry after the expected number of
4477   // events this logged, or entries.size() if there aren't enough entries.
4478   static size_t CheckDelegateInfo(
4479       const CapturingNetLog::CapturedEntryList& entries, size_t log_position) {
4480     // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4481     if (log_position + 3 >= entries.size()) {
4482       ADD_FAILURE() << "Not enough log entries";
4483       return entries.size();
4484     }
4485     std::string delegate_info;
4486     EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4487     EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4488     EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4489                                                      &delegate_info));
4490     EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4491
4492     ++log_position;
4493     EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4494     EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4495
4496     ++log_position;
4497     EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4498     EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4499     EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4500                                                      &delegate_info));
4501     EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4502
4503     ++log_position;
4504     EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4505     EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4506
4507     return log_position + 1;
4508   }
4509
4510   // Find delegate request begin and end messages for OnBeforeNetworkStart.
4511   // Returns the position of the end message.
4512   static size_t ExpectBeforeNetworkEvents(
4513       const CapturingNetLog::CapturedEntryList& entries,
4514       size_t log_position) {
4515     log_position =
4516         ExpectLogContainsSomewhereAfter(entries,
4517                                         log_position,
4518                                         NetLog::TYPE_URL_REQUEST_DELEGATE,
4519                                         NetLog::PHASE_BEGIN);
4520     EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4521               entries[log_position + 1].type);
4522     EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4523     return log_position + 1;
4524   }
4525
4526  private:
4527   friend class base::RefCounted<AsyncDelegateLogger>;
4528
4529   AsyncDelegateLogger(URLRequest* url_request,
4530                       LoadState expected_first_load_state,
4531                       LoadState expected_second_load_state,
4532                       LoadState expected_third_load_state,
4533                       const Callback& callback)
4534       : url_request_(url_request),
4535         expected_first_load_state_(expected_first_load_state),
4536         expected_second_load_state_(expected_second_load_state),
4537         expected_third_load_state_(expected_third_load_state),
4538         callback_(callback) {
4539   }
4540
4541   ~AsyncDelegateLogger() {}
4542
4543   void Start() {
4544     url_request_->LogBlockedBy(kFirstDelegateInfo);
4545     LoadStateWithParam load_state = url_request_->GetLoadState();
4546     EXPECT_EQ(expected_first_load_state_, load_state.state);
4547     EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
4548     base::MessageLoop::current()->PostTask(
4549         FROM_HERE,
4550         base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
4551   }
4552
4553   void LogSecondDelegate() {
4554     url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
4555     LoadStateWithParam load_state = url_request_->GetLoadState();
4556     EXPECT_EQ(expected_second_load_state_, load_state.state);
4557     if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4558       EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4559     } else {
4560       EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4561     }
4562     base::MessageLoop::current()->PostTask(
4563         FROM_HERE,
4564         base::Bind(&AsyncDelegateLogger::LogComplete, this));
4565   }
4566
4567   void LogComplete() {
4568     url_request_->LogUnblocked();
4569     LoadStateWithParam load_state = url_request_->GetLoadState();
4570     EXPECT_EQ(expected_third_load_state_, load_state.state);
4571     if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
4572       EXPECT_EQ(base::string16(), load_state.param);
4573     callback_.Run();
4574   }
4575
4576   URLRequest* url_request_;
4577   const int expected_first_load_state_;
4578   const int expected_second_load_state_;
4579   const int expected_third_load_state_;
4580   const Callback callback_;
4581
4582   DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4583 };
4584
4585 // NetworkDelegate that logs delegate information before a request is started,
4586 // before headers are sent, when headers are read, and when auth information
4587 // is requested.  Uses AsyncDelegateLogger.
4588 class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4589  public:
4590   AsyncLoggingNetworkDelegate() {}
4591   ~AsyncLoggingNetworkDelegate() override {}
4592
4593   // NetworkDelegate implementation.
4594   int OnBeforeURLRequest(URLRequest* request,
4595                          const CompletionCallback& callback,
4596                          GURL* new_url) override {
4597     TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4598     return RunCallbackAsynchronously(request, callback);
4599   }
4600
4601   int OnBeforeSendHeaders(URLRequest* request,
4602                           const CompletionCallback& callback,
4603                           HttpRequestHeaders* headers) override {
4604     TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4605     return RunCallbackAsynchronously(request, callback);
4606   }
4607
4608   int OnHeadersReceived(
4609       URLRequest* request,
4610       const CompletionCallback& callback,
4611       const HttpResponseHeaders* original_response_headers,
4612       scoped_refptr<HttpResponseHeaders>* override_response_headers,
4613       GURL* allowed_unsafe_redirect_url) override {
4614     TestNetworkDelegate::OnHeadersReceived(request,
4615                                            callback,
4616                                            original_response_headers,
4617                                            override_response_headers,
4618                                            allowed_unsafe_redirect_url);
4619     return RunCallbackAsynchronously(request, callback);
4620   }
4621
4622   NetworkDelegate::AuthRequiredResponse OnAuthRequired(
4623       URLRequest* request,
4624       const AuthChallengeInfo& auth_info,
4625       const AuthCallback& callback,
4626       AuthCredentials* credentials) override {
4627     AsyncDelegateLogger::Run(
4628         request,
4629         LOAD_STATE_WAITING_FOR_DELEGATE,
4630         LOAD_STATE_WAITING_FOR_DELEGATE,
4631         LOAD_STATE_WAITING_FOR_DELEGATE,
4632         base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4633                    callback, credentials));
4634     return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4635   }
4636
4637  private:
4638   static int RunCallbackAsynchronously(
4639       URLRequest* request,
4640       const CompletionCallback& callback) {
4641     AsyncDelegateLogger::Run(
4642         request,
4643         LOAD_STATE_WAITING_FOR_DELEGATE,
4644         LOAD_STATE_WAITING_FOR_DELEGATE,
4645         LOAD_STATE_WAITING_FOR_DELEGATE,
4646         base::Bind(callback, OK));
4647     return ERR_IO_PENDING;
4648   }
4649
4650   static void SetAuthAndResume(const AuthCallback& callback,
4651                                AuthCredentials* credentials) {
4652     *credentials = AuthCredentials(kUser, kSecret);
4653     callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4654   }
4655
4656   DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4657 };
4658
4659 // URLRequest::Delegate that logs delegate information when the headers
4660 // are received, when each read completes, and during redirects.  Uses
4661 // AsyncDelegateLogger.  Can optionally cancel a request in any phase.
4662 //
4663 // Inherits from TestDelegate to reuse the TestDelegate code to handle
4664 // advancing to the next step in most cases, as well as cancellation.
4665 class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4666  public:
4667   enum CancelStage {
4668     NO_CANCEL = 0,
4669     CANCEL_ON_RECEIVED_REDIRECT,
4670     CANCEL_ON_RESPONSE_STARTED,
4671     CANCEL_ON_READ_COMPLETED
4672   };
4673
4674   explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4675       : cancel_stage_(cancel_stage) {
4676     if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4677       set_cancel_in_received_redirect(true);
4678     else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4679       set_cancel_in_response_started(true);
4680     else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4681       set_cancel_in_received_data(true);
4682   }
4683   ~AsyncLoggingUrlRequestDelegate() override {}
4684
4685   // URLRequest::Delegate implementation:
4686   void OnReceivedRedirect(URLRequest* request,
4687                           const RedirectInfo& redirect_info,
4688                           bool* defer_redirect) override {
4689     *defer_redirect = true;
4690     AsyncDelegateLogger::Run(
4691         request,
4692         LOAD_STATE_WAITING_FOR_DELEGATE,
4693         LOAD_STATE_WAITING_FOR_DELEGATE,
4694         LOAD_STATE_WAITING_FOR_DELEGATE,
4695         base::Bind(
4696             &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
4697             base::Unretained(this), request, redirect_info));
4698   }
4699
4700   void OnResponseStarted(URLRequest* request) override {
4701     AsyncDelegateLogger::Run(
4702       request,
4703       LOAD_STATE_WAITING_FOR_DELEGATE,
4704       LOAD_STATE_WAITING_FOR_DELEGATE,
4705       LOAD_STATE_WAITING_FOR_DELEGATE,
4706       base::Bind(
4707           &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4708           base::Unretained(this), request));
4709   }
4710
4711   void OnReadCompleted(URLRequest* request, int bytes_read) override {
4712     AsyncDelegateLogger::Run(
4713         request,
4714         LOAD_STATE_IDLE,
4715         LOAD_STATE_IDLE,
4716         LOAD_STATE_IDLE,
4717         base::Bind(
4718             &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4719             base::Unretained(this), request, bytes_read));
4720   }
4721
4722  private:
4723   void OnReceivedRedirectLoggingComplete(URLRequest* request,
4724                                          const RedirectInfo& redirect_info) {
4725     bool defer_redirect = false;
4726     TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
4727     // FollowDeferredRedirect should not be called after cancellation.
4728     if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4729       return;
4730     if (!defer_redirect)
4731       request->FollowDeferredRedirect();
4732   }
4733
4734   void OnResponseStartedLoggingComplete(URLRequest* request) {
4735     // The parent class continues the request.
4736     TestDelegate::OnResponseStarted(request);
4737   }
4738
4739   void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4740     // The parent class continues the request.
4741     TestDelegate::OnReadCompleted(request, bytes_read);
4742   }
4743
4744   const CancelStage cancel_stage_;
4745
4746   DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4747 };
4748
4749 // Tests handling of delegate info before a request starts.
4750 TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4751   ASSERT_TRUE(test_server_.Start());
4752
4753   TestDelegate request_delegate;
4754   TestURLRequestContext context(true);
4755   context.set_network_delegate(NULL);
4756   context.set_net_log(&net_log_);
4757   context.Init();
4758
4759   {
4760     scoped_ptr<URLRequest> r(context.CreateRequest(
4761         test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &request_delegate,
4762         NULL));
4763     LoadStateWithParam load_state = r->GetLoadState();
4764     EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4765     EXPECT_EQ(base::string16(), load_state.param);
4766
4767     AsyncDelegateLogger::Run(
4768         r.get(),
4769         LOAD_STATE_WAITING_FOR_DELEGATE,
4770         LOAD_STATE_WAITING_FOR_DELEGATE,
4771         LOAD_STATE_IDLE,
4772         base::Bind(&URLRequest::Start, base::Unretained(r.get())));
4773
4774     base::RunLoop().Run();
4775
4776     EXPECT_EQ(200, r->GetResponseCode());
4777     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4778   }
4779
4780   CapturingNetLog::CapturedEntryList entries;
4781   net_log_.GetEntries(&entries);
4782   size_t log_position = ExpectLogContainsSomewhereAfter(
4783       entries,
4784       0,
4785       NetLog::TYPE_DELEGATE_INFO,
4786       NetLog::PHASE_BEGIN);
4787
4788   log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4789
4790   // Nothing else should add any delegate info to the request.
4791   EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4792       entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4793 }
4794
4795 // Tests handling of delegate info from a network delegate.
4796 TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4797   ASSERT_TRUE(test_server_.Start());
4798
4799   TestDelegate request_delegate;
4800   AsyncLoggingNetworkDelegate network_delegate;
4801   TestURLRequestContext context(true);
4802   context.set_network_delegate(&network_delegate);
4803   context.set_net_log(&net_log_);
4804   context.Init();
4805
4806   {
4807     scoped_ptr<URLRequest> r(context.CreateRequest(
4808         test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &request_delegate,
4809         NULL));
4810     LoadStateWithParam load_state = r->GetLoadState();
4811     EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4812     EXPECT_EQ(base::string16(), load_state.param);
4813
4814     r->Start();
4815     base::RunLoop().Run();
4816
4817     EXPECT_EQ(200, r->GetResponseCode());
4818     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4819     EXPECT_EQ(1, network_delegate.created_requests());
4820     EXPECT_EQ(0, network_delegate.destroyed_requests());
4821   }
4822   EXPECT_EQ(1, network_delegate.destroyed_requests());
4823
4824   size_t log_position = 0;
4825   CapturingNetLog::CapturedEntryList entries;
4826   net_log_.GetEntries(&entries);
4827   for (size_t i = 0; i < 3; ++i) {
4828     log_position = ExpectLogContainsSomewhereAfter(
4829         entries,
4830         log_position + 1,
4831         NetLog::TYPE_URL_REQUEST_DELEGATE,
4832         NetLog::PHASE_BEGIN);
4833
4834     log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4835                                                           log_position + 1);
4836
4837     ASSERT_LT(log_position, entries.size());
4838     EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4839     EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4840
4841     if (i == 1) {
4842       log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4843           entries, log_position + 1);
4844     }
4845   }
4846
4847   EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4848       entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4849 }
4850
4851 // Tests handling of delegate info from a network delegate in the case of an
4852 // HTTP redirect.
4853 TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4854   ASSERT_TRUE(test_server_.Start());
4855
4856   TestDelegate request_delegate;
4857   AsyncLoggingNetworkDelegate network_delegate;
4858   TestURLRequestContext context(true);
4859   context.set_network_delegate(&network_delegate);
4860   context.set_net_log(&net_log_);
4861   context.Init();
4862
4863   {
4864     scoped_ptr<URLRequest> r(context.CreateRequest(
4865         test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
4866         &request_delegate, NULL));
4867     LoadStateWithParam load_state = r->GetLoadState();
4868     EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4869     EXPECT_EQ(base::string16(), load_state.param);
4870
4871     r->Start();
4872     base::RunLoop().Run();
4873
4874     EXPECT_EQ(200, r->GetResponseCode());
4875     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4876     EXPECT_EQ(2, network_delegate.created_requests());
4877     EXPECT_EQ(0, network_delegate.destroyed_requests());
4878   }
4879   EXPECT_EQ(1, network_delegate.destroyed_requests());
4880
4881   size_t log_position = 0;
4882   CapturingNetLog::CapturedEntryList entries;
4883   net_log_.GetEntries(&entries);
4884   // The NetworkDelegate logged information in OnBeforeURLRequest,
4885   // OnBeforeSendHeaders, and OnHeadersReceived.
4886   for (size_t i = 0; i < 3; ++i) {
4887     log_position = ExpectLogContainsSomewhereAfter(
4888         entries,
4889         log_position + 1,
4890         NetLog::TYPE_URL_REQUEST_DELEGATE,
4891         NetLog::PHASE_BEGIN);
4892
4893     log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4894                                                           log_position + 1);
4895
4896     ASSERT_LT(log_position, entries.size());
4897     EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4898     EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4899
4900     if (i == 1) {
4901       log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4902           entries, log_position + 1);
4903     }
4904   }
4905
4906   // The URLRequest::Delegate then gets informed about the redirect.
4907   log_position = ExpectLogContainsSomewhereAfter(
4908       entries,
4909       log_position + 1,
4910       NetLog::TYPE_URL_REQUEST_DELEGATE,
4911       NetLog::PHASE_BEGIN);
4912
4913   // The NetworkDelegate logged information in the same three events as before.
4914   for (size_t i = 0; i < 3; ++i) {
4915     log_position = ExpectLogContainsSomewhereAfter(
4916         entries,
4917         log_position + 1,
4918         NetLog::TYPE_URL_REQUEST_DELEGATE,
4919         NetLog::PHASE_BEGIN);
4920
4921     log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4922                                                           log_position + 1);
4923
4924     ASSERT_LT(log_position, entries.size());
4925     EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4926     EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4927   }
4928
4929   EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4930       entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4931 }
4932
4933 // Tests handling of delegate info from a network delegate in the case of HTTP
4934 // AUTH.
4935 TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4936   ASSERT_TRUE(test_server_.Start());
4937
4938   TestDelegate request_delegate;
4939   AsyncLoggingNetworkDelegate network_delegate;
4940   TestURLRequestContext context(true);
4941   context.set_network_delegate(&network_delegate);
4942   context.set_net_log(&net_log_);
4943   context.Init();
4944
4945   {
4946     scoped_ptr<URLRequest> r(context.CreateRequest(
4947         test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &request_delegate,
4948         NULL));
4949     LoadStateWithParam load_state = r->GetLoadState();
4950     EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4951     EXPECT_EQ(base::string16(), load_state.param);
4952
4953     r->Start();
4954     base::RunLoop().Run();
4955
4956     EXPECT_EQ(200, r->GetResponseCode());
4957     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4958     EXPECT_EQ(1, network_delegate.created_requests());
4959     EXPECT_EQ(0, network_delegate.destroyed_requests());
4960   }
4961   EXPECT_EQ(1, network_delegate.destroyed_requests());
4962
4963   size_t log_position = 0;
4964   CapturingNetLog::CapturedEntryList entries;
4965   net_log_.GetEntries(&entries);
4966   // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4967   // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4968   // OnBeforeURLRequest and OnBeforeSendHeaders.
4969   for (size_t i = 0; i < 6; ++i) {
4970     log_position = ExpectLogContainsSomewhereAfter(
4971         entries,
4972         log_position + 1,
4973         NetLog::TYPE_URL_REQUEST_DELEGATE,
4974         NetLog::PHASE_BEGIN);
4975
4976     log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4977                                                           log_position + 1);
4978
4979     ASSERT_LT(log_position, entries.size());
4980     EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4981     EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4982
4983     if (i == 1) {
4984       log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4985           entries, log_position + 1);
4986     }
4987   }
4988
4989   EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4990       entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4991 }
4992
4993 // Tests handling of delegate info from a URLRequest::Delegate.
4994 TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4995   ASSERT_TRUE(test_server_.Start());
4996
4997   AsyncLoggingUrlRequestDelegate request_delegate(
4998       AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4999   TestURLRequestContext context(true);
5000   context.set_network_delegate(NULL);
5001   context.set_net_log(&net_log_);
5002   context.Init();
5003
5004   {
5005     // A chunked response with delays between chunks is used to make sure that
5006     // attempts by the URLRequest delegate to log information while reading the
5007     // body are ignored.  Since they are ignored, this test is robust against
5008     // the possibility of multiple reads being combined in the unlikely event
5009     // that it occurs.
5010     scoped_ptr<URLRequest> r(context.CreateRequest(
5011         test_server_.GetURL("chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
5012         &request_delegate, NULL));
5013     LoadStateWithParam load_state = r->GetLoadState();
5014     r->Start();
5015     base::RunLoop().Run();
5016
5017     EXPECT_EQ(200, r->GetResponseCode());
5018     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5019   }
5020
5021   CapturingNetLog::CapturedEntryList entries;
5022   net_log_.GetEntries(&entries);
5023
5024   size_t log_position = 0;
5025
5026   log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5027       entries, log_position);
5028
5029   // The delegate info should only have been logged on header complete.  Other
5030   // times it should silently be ignored.
5031   log_position =
5032       ExpectLogContainsSomewhereAfter(entries,
5033                                       log_position + 1,
5034                                       NetLog::TYPE_URL_REQUEST_DELEGATE,
5035                                       NetLog::PHASE_BEGIN);
5036
5037   log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5038                                                         log_position + 1);
5039
5040   ASSERT_LT(log_position, entries.size());
5041   EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5042   EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5043
5044   EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5045       entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5046   EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5047       entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5048 }
5049
5050 // Tests handling of delegate info from a URLRequest::Delegate in the case of
5051 // an HTTP redirect.
5052 TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
5053   ASSERT_TRUE(test_server_.Start());
5054
5055   AsyncLoggingUrlRequestDelegate request_delegate(
5056       AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5057   TestURLRequestContext context(true);
5058   context.set_network_delegate(NULL);
5059   context.set_net_log(&net_log_);
5060   context.Init();
5061
5062   {
5063     scoped_ptr<URLRequest> r(context.CreateRequest(
5064         test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
5065         &request_delegate, NULL));
5066     LoadStateWithParam load_state = r->GetLoadState();
5067     r->Start();
5068     base::RunLoop().Run();
5069
5070     EXPECT_EQ(200, r->GetResponseCode());
5071     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5072   }
5073
5074   CapturingNetLog::CapturedEntryList entries;
5075   net_log_.GetEntries(&entries);
5076
5077   // Delegate info should only have been logged in OnReceivedRedirect and
5078   // OnResponseStarted.
5079   size_t log_position = 0;
5080   for (int i = 0; i < 2; ++i) {
5081     if (i == 0) {
5082       log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5083                          entries, log_position) + 1;
5084     }
5085
5086     log_position = ExpectLogContainsSomewhereAfter(
5087             entries,
5088             log_position,
5089             NetLog::TYPE_URL_REQUEST_DELEGATE,
5090             NetLog::PHASE_BEGIN);
5091
5092     log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5093                                                           log_position + 1);
5094
5095     ASSERT_LT(log_position, entries.size());
5096     EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5097     EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5098   }
5099
5100   EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5101       entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5102   EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5103       entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5104 }
5105
5106 // Tests handling of delegate info from a URLRequest::Delegate in the case of
5107 // an HTTP redirect, with cancellation at various points.
5108 TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
5109   ASSERT_TRUE(test_server_.Start());
5110
5111   const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5112     AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5113     AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5114     AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5115   };
5116
5117   for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5118        ++test_case) {
5119     AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
5120     TestURLRequestContext context(true);
5121     CapturingNetLog net_log;
5122     context.set_network_delegate(NULL);
5123     context.set_net_log(&net_log);
5124     context.Init();
5125
5126     {
5127       scoped_ptr<URLRequest> r(context.CreateRequest(
5128           test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
5129           &request_delegate, NULL));
5130       LoadStateWithParam load_state = r->GetLoadState();
5131       r->Start();
5132       base::RunLoop().Run();
5133       EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
5134     }
5135
5136     CapturingNetLog::CapturedEntryList entries;
5137     net_log.GetEntries(&entries);
5138
5139     // Delegate info is always logged in both OnReceivedRedirect and
5140     // OnResponseStarted.  In the CANCEL_ON_RECEIVED_REDIRECT, the
5141     // OnResponseStarted delegate call is after cancellation, but logging is
5142     // still currently supported in that call.
5143     size_t log_position = 0;
5144     for (int i = 0; i < 2; ++i) {
5145       if (i == 0) {
5146         log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5147                            entries, log_position) + 1;
5148       }
5149
5150       log_position = ExpectLogContainsSomewhereAfter(
5151               entries,
5152               log_position,
5153               NetLog::TYPE_URL_REQUEST_DELEGATE,
5154               NetLog::PHASE_BEGIN);
5155
5156       log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5157                                                             log_position + 1);
5158
5159       ASSERT_LT(log_position, entries.size());
5160       EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5161       EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5162     }
5163
5164     EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5165         entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5166     EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5167         entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5168   }
5169 }
5170
5171 namespace {
5172
5173 const char kExtraHeader[] = "Allow-Snafu";
5174 const char kExtraValue[] = "fubar";
5175
5176 class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
5177   void OnReceivedRedirect(URLRequest* request,
5178                           const RedirectInfo& redirect_info,
5179                           bool* defer_redirect) override {
5180     TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
5181     request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5182   }
5183 };
5184
5185 }  // namespace
5186
5187 TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
5188   ASSERT_TRUE(test_server_.Start());
5189
5190   GURL destination_url = test_server_.GetURL(
5191       "echoheader?" + std::string(kExtraHeader));
5192   GURL original_url = test_server_.GetURL(
5193       "server-redirect?" + destination_url.spec());
5194   RedirectWithAdditionalHeadersDelegate d;
5195   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5196       original_url, DEFAULT_PRIORITY, &d, NULL));
5197   req->Start();
5198   base::RunLoop().Run();
5199
5200   std::string value;
5201   const HttpRequestHeaders& headers = req->extra_request_headers();
5202   EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5203   EXPECT_EQ(kExtraValue, value);
5204   EXPECT_FALSE(req->is_pending());
5205   EXPECT_FALSE(req->is_redirecting());
5206   EXPECT_EQ(kExtraValue, d.data_received());
5207 }
5208
5209 namespace {
5210
5211 const char kExtraHeaderToRemove[] = "To-Be-Removed";
5212
5213 class RedirectWithHeaderRemovalDelegate : public TestDelegate {
5214   void OnReceivedRedirect(URLRequest* request,
5215                           const RedirectInfo& redirect_info,
5216                           bool* defer_redirect) override {
5217     TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
5218     request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5219   }
5220 };
5221
5222 }  // namespace
5223
5224 TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
5225   ASSERT_TRUE(test_server_.Start());
5226
5227   GURL destination_url = test_server_.GetURL(
5228       "echoheader?" + std::string(kExtraHeaderToRemove));
5229   GURL original_url = test_server_.GetURL(
5230       "server-redirect?" + destination_url.spec());
5231   RedirectWithHeaderRemovalDelegate d;
5232   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5233       original_url, DEFAULT_PRIORITY, &d, NULL));
5234   req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5235   req->Start();
5236   base::RunLoop().Run();
5237
5238   std::string value;
5239   const HttpRequestHeaders& headers = req->extra_request_headers();
5240   EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
5241   EXPECT_FALSE(req->is_pending());
5242   EXPECT_FALSE(req->is_redirecting());
5243   EXPECT_EQ("None", d.data_received());
5244 }
5245
5246 TEST_F(URLRequestTestHTTP, CancelTest) {
5247   TestDelegate d;
5248   {
5249     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5250         GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d, NULL));
5251
5252     r->Start();
5253     EXPECT_TRUE(r->is_pending());
5254
5255     r->Cancel();
5256
5257     base::RunLoop().Run();
5258
5259     // We expect to receive OnResponseStarted even though the request has been
5260     // cancelled.
5261     EXPECT_EQ(1, d.response_started_count());
5262     EXPECT_EQ(0, d.bytes_received());
5263     EXPECT_FALSE(d.received_data_before_response());
5264   }
5265 }
5266
5267 TEST_F(URLRequestTestHTTP, CancelTest2) {
5268   ASSERT_TRUE(test_server_.Start());
5269
5270   TestDelegate d;
5271   {
5272     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5273         test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
5274
5275     d.set_cancel_in_response_started(true);
5276
5277     r->Start();
5278     EXPECT_TRUE(r->is_pending());
5279
5280     base::RunLoop().Run();
5281
5282     EXPECT_EQ(1, d.response_started_count());
5283     EXPECT_EQ(0, d.bytes_received());
5284     EXPECT_FALSE(d.received_data_before_response());
5285     EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
5286   }
5287 }
5288
5289 TEST_F(URLRequestTestHTTP, CancelTest3) {
5290   ASSERT_TRUE(test_server_.Start());
5291
5292   TestDelegate d;
5293   {
5294     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5295         test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
5296
5297     d.set_cancel_in_received_data(true);
5298
5299     r->Start();
5300     EXPECT_TRUE(r->is_pending());
5301
5302     base::RunLoop().Run();
5303
5304     EXPECT_EQ(1, d.response_started_count());
5305     // There is no guarantee about how much data was received
5306     // before the cancel was issued.  It could have been 0 bytes,
5307     // or it could have been all the bytes.
5308     // EXPECT_EQ(0, d.bytes_received());
5309     EXPECT_FALSE(d.received_data_before_response());
5310     EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
5311   }
5312 }
5313
5314 TEST_F(URLRequestTestHTTP, CancelTest4) {
5315   ASSERT_TRUE(test_server_.Start());
5316
5317   TestDelegate d;
5318   {
5319     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5320         test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
5321
5322     r->Start();
5323     EXPECT_TRUE(r->is_pending());
5324
5325     // The request will be implicitly canceled when it is destroyed. The
5326     // test delegate must not post a quit message when this happens because
5327     // this test doesn't actually have a message loop. The quit message would
5328     // get put on this thread's message queue and the next test would exit
5329     // early, causing problems.
5330     d.set_quit_on_complete(false);
5331   }
5332   // expect things to just cleanup properly.
5333
5334   // we won't actually get a received reponse here because we've never run the
5335   // message loop
5336   EXPECT_FALSE(d.received_data_before_response());
5337   EXPECT_EQ(0, d.bytes_received());
5338 }
5339
5340 TEST_F(URLRequestTestHTTP, CancelTest5) {
5341   ASSERT_TRUE(test_server_.Start());
5342
5343   // populate cache
5344   {
5345     TestDelegate d;
5346     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5347         test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d, NULL));
5348     r->Start();
5349     base::RunLoop().Run();
5350     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5351   }
5352
5353   // cancel read from cache (see bug 990242)
5354   {
5355     TestDelegate d;
5356     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5357         test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d, NULL));
5358     r->Start();
5359     r->Cancel();
5360     base::RunLoop().Run();
5361
5362     EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
5363     EXPECT_EQ(1, d.response_started_count());
5364     EXPECT_EQ(0, d.bytes_received());
5365     EXPECT_FALSE(d.received_data_before_response());
5366   }
5367 }
5368
5369 TEST_F(URLRequestTestHTTP, PostTest) {
5370   ASSERT_TRUE(test_server_.Start());
5371   HTTPUploadDataOperationTest("POST");
5372 }
5373
5374 TEST_F(URLRequestTestHTTP, PutTest) {
5375   ASSERT_TRUE(test_server_.Start());
5376   HTTPUploadDataOperationTest("PUT");
5377 }
5378
5379 TEST_F(URLRequestTestHTTP, PostEmptyTest) {
5380   ASSERT_TRUE(test_server_.Start());
5381
5382   TestDelegate d;
5383   {
5384     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5385         test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5386     r->set_method("POST");
5387
5388     r->Start();
5389     EXPECT_TRUE(r->is_pending());
5390
5391     base::RunLoop().Run();
5392
5393     ASSERT_EQ(1, d.response_started_count())
5394         << "request failed: " << r->status().status()
5395         << ", error: " << r->status().error();
5396
5397     EXPECT_FALSE(d.received_data_before_response());
5398     EXPECT_TRUE(d.data_received().empty());
5399   }
5400 }
5401
5402 TEST_F(URLRequestTestHTTP, PostFileTest) {
5403   ASSERT_TRUE(test_server_.Start());
5404
5405   TestDelegate d;
5406   {
5407     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5408         test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5409     r->set_method("POST");
5410
5411     base::FilePath dir;
5412     PathService::Get(base::DIR_EXE, &dir);
5413     base::SetCurrentDirectory(dir);
5414
5415     ScopedVector<UploadElementReader> element_readers;
5416
5417     base::FilePath path;
5418     PathService::Get(base::DIR_SOURCE_ROOT, &path);
5419     path = path.Append(FILE_PATH_LITERAL("net"));
5420     path = path.Append(FILE_PATH_LITERAL("data"));
5421     path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5422     path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5423     element_readers.push_back(
5424         new UploadFileElementReader(base::MessageLoopProxy::current().get(),
5425                                     path,
5426                                     0,
5427                                     kuint64max,
5428                                     base::Time()));
5429     r->set_upload(make_scoped_ptr<UploadDataStream>(
5430         new ElementsUploadDataStream(element_readers.Pass(), 0)));
5431
5432     r->Start();
5433     EXPECT_TRUE(r->is_pending());
5434
5435     base::RunLoop().Run();
5436
5437     int64 size = 0;
5438     ASSERT_EQ(true, base::GetFileSize(path, &size));
5439     scoped_ptr<char[]> buf(new char[size]);
5440
5441     ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
5442
5443     ASSERT_EQ(1, d.response_started_count())
5444         << "request failed: " << r->status().status()
5445         << ", error: " << r->status().error();
5446
5447     EXPECT_FALSE(d.received_data_before_response());
5448
5449     EXPECT_EQ(size, d.bytes_received());
5450     EXPECT_EQ(std::string(&buf[0], size), d.data_received());
5451   }
5452 }
5453
5454 TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
5455   ASSERT_TRUE(test_server_.Start());
5456
5457   TestDelegate d;
5458   {
5459     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5460         test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5461     r->set_method("POST");
5462
5463     ScopedVector<UploadElementReader> element_readers;
5464
5465     element_readers.push_back(new UploadFileElementReader(
5466         base::MessageLoopProxy::current().get(),
5467         base::FilePath(FILE_PATH_LITERAL(
5468             "c:\\path\\to\\non\\existant\\file.randomness.12345")),
5469         0,
5470         kuint64max,
5471         base::Time()));
5472     r->set_upload(make_scoped_ptr<UploadDataStream>(
5473         new ElementsUploadDataStream(element_readers.Pass(), 0)));
5474
5475     r->Start();
5476     EXPECT_TRUE(r->is_pending());
5477
5478     base::RunLoop().Run();
5479
5480     EXPECT_TRUE(d.request_failed());
5481     EXPECT_FALSE(d.received_data_before_response());
5482     EXPECT_EQ(0, d.bytes_received());
5483     EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5484     EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
5485   }
5486 }
5487
5488 TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
5489   ASSERT_TRUE(test_server_.Start());
5490
5491   TestDelegate d;
5492   {
5493     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5494         test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5495     r->EnableChunkedUpload();
5496     r->set_method("POST");
5497     AddChunksToUpload(r.get());
5498     r->Start();
5499     EXPECT_TRUE(r->is_pending());
5500
5501     base::RunLoop().Run();
5502
5503     VerifyReceivedDataMatchesChunks(r.get(), &d);
5504   }
5505 }
5506
5507 TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
5508   ASSERT_TRUE(test_server_.Start());
5509
5510   TestDelegate d;
5511   {
5512     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5513         test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5514     r->EnableChunkedUpload();
5515     r->set_method("POST");
5516     r->Start();
5517     EXPECT_TRUE(r->is_pending());
5518     AddChunksToUpload(r.get());
5519     base::RunLoop().Run();
5520
5521     VerifyReceivedDataMatchesChunks(r.get(), &d);
5522   }
5523 }
5524
5525 TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
5526   ASSERT_TRUE(test_server_.Start());
5527
5528   TestDelegate d;
5529   {
5530     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5531         test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5532     r->EnableChunkedUpload();
5533     r->set_method("POST");
5534     r->Start();
5535     EXPECT_TRUE(r->is_pending());
5536
5537     base::RunLoop().RunUntilIdle();
5538     AddChunksToUpload(r.get());
5539     base::RunLoop().Run();
5540
5541     VerifyReceivedDataMatchesChunks(r.get(), &d);
5542   }
5543 }
5544
5545 TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
5546   ASSERT_TRUE(test_server_.Start());
5547
5548   TestDelegate d;
5549   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5550       test_server_.GetURL("files/with-headers.html"), DEFAULT_PRIORITY, &d,
5551       NULL));
5552   req->Start();
5553   base::RunLoop().Run();
5554
5555   const HttpResponseHeaders* headers = req->response_headers();
5556
5557   // Simple sanity check that response_info() accesses the same data.
5558   EXPECT_EQ(headers, req->response_info().headers.get());
5559
5560   std::string header;
5561   EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5562   EXPECT_EQ("private", header);
5563
5564   header.clear();
5565   EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5566   EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5567
5568   // The response has two "X-Multiple-Entries" headers.
5569   // This verfies our output has them concatenated together.
5570   header.clear();
5571   EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5572   EXPECT_EQ("a, b", header);
5573 }
5574
5575 TEST_F(URLRequestTestHTTP, ProcessSTS) {
5576   SpawnedTestServer::SSLOptions ssl_options;
5577   SpawnedTestServer https_test_server(
5578       SpawnedTestServer::TYPE_HTTPS,
5579       ssl_options,
5580       base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5581   ASSERT_TRUE(https_test_server.Start());
5582
5583   TestDelegate d;
5584   scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5585       https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY, &d,
5586       NULL));
5587   request->Start();
5588   base::RunLoop().Run();
5589
5590   TransportSecurityState* security_state =
5591       default_context_.transport_security_state();
5592   TransportSecurityState::DomainState domain_state;
5593   EXPECT_TRUE(security_state->GetDynamicDomainState(
5594       SpawnedTestServer::kLocalhost, &domain_state));
5595   EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5596             domain_state.sts.upgrade_mode);
5597   EXPECT_TRUE(domain_state.sts.include_subdomains);
5598   EXPECT_FALSE(domain_state.pkp.include_subdomains);
5599 #if defined(OS_ANDROID)
5600   // Android's CertVerifyProc does not (yet) handle pins.
5601 #else
5602   EXPECT_FALSE(domain_state.HasPublicKeyPins());
5603 #endif
5604 }
5605
5606 // Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5607 // reject HPKP headers, and a test setting only HPKP headers will fail (no
5608 // DomainState present because header rejected).
5609 #if defined(OS_ANDROID)
5610 #define MAYBE_ProcessPKP DISABLED_ProcessPKP
5611 #else
5612 #define MAYBE_ProcessPKP ProcessPKP
5613 #endif
5614
5615 // Tests that enabling HPKP on a domain does not affect the HSTS
5616 // validity/expiration.
5617 TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
5618   SpawnedTestServer::SSLOptions ssl_options;
5619   SpawnedTestServer https_test_server(
5620       SpawnedTestServer::TYPE_HTTPS,
5621       ssl_options,
5622       base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5623   ASSERT_TRUE(https_test_server.Start());
5624
5625   TestDelegate d;
5626   scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5627       https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
5628       NULL));
5629   request->Start();
5630   base::RunLoop().Run();
5631
5632   TransportSecurityState* security_state =
5633       default_context_.transport_security_state();
5634   TransportSecurityState::DomainState domain_state;
5635   EXPECT_TRUE(security_state->GetDynamicDomainState(
5636       SpawnedTestServer::kLocalhost, &domain_state));
5637   EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
5638             domain_state.sts.upgrade_mode);
5639   EXPECT_FALSE(domain_state.sts.include_subdomains);
5640   EXPECT_FALSE(domain_state.pkp.include_subdomains);
5641   EXPECT_TRUE(domain_state.HasPublicKeyPins());
5642   EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5643 }
5644
5645 TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
5646   SpawnedTestServer::SSLOptions ssl_options;
5647   SpawnedTestServer https_test_server(
5648       SpawnedTestServer::TYPE_HTTPS,
5649       ssl_options,
5650       base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5651   ASSERT_TRUE(https_test_server.Start());
5652
5653   TestDelegate d;
5654   scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5655       https_test_server.GetURL("files/hsts-multiple-headers.html"),
5656       DEFAULT_PRIORITY, &d, NULL));
5657   request->Start();
5658   base::RunLoop().Run();
5659
5660   // We should have set parameters from the first header, not the second.
5661   TransportSecurityState* security_state =
5662       default_context_.transport_security_state();
5663   TransportSecurityState::DomainState domain_state;
5664   EXPECT_TRUE(security_state->GetDynamicDomainState(
5665       SpawnedTestServer::kLocalhost, &domain_state));
5666   EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5667             domain_state.sts.upgrade_mode);
5668   EXPECT_FALSE(domain_state.sts.include_subdomains);
5669   EXPECT_FALSE(domain_state.pkp.include_subdomains);
5670 }
5671
5672 TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
5673   SpawnedTestServer::SSLOptions ssl_options;
5674   SpawnedTestServer https_test_server(
5675       SpawnedTestServer::TYPE_HTTPS,
5676       ssl_options,
5677       base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5678   ASSERT_TRUE(https_test_server.Start());
5679
5680   TestDelegate d;
5681   scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5682       https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
5683       DEFAULT_PRIORITY, &d, NULL));
5684   request->Start();
5685   base::RunLoop().Run();
5686
5687   // We should have set parameters from the first header, not the second.
5688   TransportSecurityState* security_state =
5689       default_context_.transport_security_state();
5690   TransportSecurityState::DomainState domain_state;
5691   EXPECT_TRUE(security_state->GetDynamicDomainState(
5692       SpawnedTestServer::kLocalhost, &domain_state));
5693   EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5694             domain_state.sts.upgrade_mode);
5695 #if defined(OS_ANDROID)
5696   // Android's CertVerifyProc does not (yet) handle pins.
5697 #else
5698   EXPECT_TRUE(domain_state.HasPublicKeyPins());
5699 #endif
5700   EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5701
5702   // Even though there is an HSTS header asserting includeSubdomains, it is
5703   // the *second* such header, and we MUST process only the first.
5704   EXPECT_FALSE(domain_state.sts.include_subdomains);
5705   // includeSubdomains does not occur in the test HPKP header.
5706   EXPECT_FALSE(domain_state.pkp.include_subdomains);
5707 }
5708
5709 // Tests that when multiple HPKP headers are present, asserting different
5710 // policies, that only the first such policy is processed.
5711 TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
5712   SpawnedTestServer::SSLOptions ssl_options;
5713   SpawnedTestServer https_test_server(
5714       SpawnedTestServer::TYPE_HTTPS,
5715       ssl_options,
5716       base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5717   ASSERT_TRUE(https_test_server.Start());
5718
5719   TestDelegate d;
5720   scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5721       https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
5722       DEFAULT_PRIORITY, &d, NULL));
5723   request->Start();
5724   base::RunLoop().Run();
5725
5726   TransportSecurityState* security_state =
5727       default_context_.transport_security_state();
5728   TransportSecurityState::DomainState domain_state;
5729   EXPECT_TRUE(security_state->GetDynamicDomainState(
5730       SpawnedTestServer::kLocalhost, &domain_state));
5731   EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5732             domain_state.sts.upgrade_mode);
5733 #if defined(OS_ANDROID)
5734   // Android's CertVerifyProc does not (yet) handle pins.
5735 #else
5736   EXPECT_TRUE(domain_state.HasPublicKeyPins());
5737 #endif
5738   EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5739
5740   EXPECT_TRUE(domain_state.sts.include_subdomains);
5741   EXPECT_FALSE(domain_state.pkp.include_subdomains);
5742 }
5743
5744 TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5745   ASSERT_TRUE(test_server_.Start());
5746
5747   TestDelegate d;
5748   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5749       test_server_.GetURL("files/content-type-normalization.html"),
5750       DEFAULT_PRIORITY, &d, NULL));
5751   req->Start();
5752   base::RunLoop().Run();
5753
5754   std::string mime_type;
5755   req->GetMimeType(&mime_type);
5756   EXPECT_EQ("text/html", mime_type);
5757
5758   std::string charset;
5759   req->GetCharset(&charset);
5760   EXPECT_EQ("utf-8", charset);
5761   req->Cancel();
5762 }
5763
5764 TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
5765   // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5766   GURL data_url("data:,foo");
5767   DataProtocolHandler data_protocol_handler;
5768   EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
5769
5770   // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5771   EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
5772 }
5773
5774 #if !defined(DISABLE_FILE_SUPPORT)
5775 TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
5776   // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5777   GURL file_url("file:///foo.txt");
5778   FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
5779   EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5780
5781   // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5782   EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
5783 }
5784
5785 TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
5786   ASSERT_TRUE(test_server_.Start());
5787
5788   TestDelegate d;
5789   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5790       test_server_.GetURL("files/redirect-to-file.html"), DEFAULT_PRIORITY, &d,
5791       NULL));
5792   req->Start();
5793   base::RunLoop().Run();
5794
5795   EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5796   EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
5797 }
5798 #endif  // !defined(DISABLE_FILE_SUPPORT)
5799
5800 TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5801   ASSERT_TRUE(test_server_.Start());
5802
5803   TestDelegate d;
5804   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5805       test_server_.GetURL("files/redirect-to-data.html"), DEFAULT_PRIORITY, &d,
5806       NULL));
5807   req->Start();
5808   base::MessageLoop::current()->Run();
5809
5810   EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5811   EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
5812 }
5813
5814 TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5815   ASSERT_TRUE(test_server_.Start());
5816
5817   TestDelegate d;
5818   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5819       test_server_.GetURL("files/redirect-to-invalid-url.html"),
5820       DEFAULT_PRIORITY, &d, NULL));
5821   req->Start();
5822   base::RunLoop().Run();
5823
5824   EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5825   EXPECT_EQ(ERR_INVALID_URL, req->status().error());
5826 }
5827
5828 // Make sure redirects are cached, despite not reading their bodies.
5829 TEST_F(URLRequestTestHTTP, CacheRedirect) {
5830   ASSERT_TRUE(test_server_.Start());
5831   GURL redirect_url =
5832       test_server_.GetURL("files/redirect302-to-echo-cacheable");
5833
5834   {
5835     TestDelegate d;
5836     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5837         redirect_url, DEFAULT_PRIORITY, &d, NULL));
5838     req->Start();
5839     base::RunLoop().Run();
5840     EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5841     EXPECT_EQ(1, d.received_redirect_count());
5842     EXPECT_EQ(test_server_.GetURL("echo"), req->url());
5843   }
5844
5845   {
5846     TestDelegate d;
5847     d.set_quit_on_redirect(true);
5848     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5849         redirect_url, DEFAULT_PRIORITY, &d, NULL));
5850     req->Start();
5851     base::RunLoop().Run();
5852
5853     EXPECT_EQ(1, d.received_redirect_count());
5854     EXPECT_EQ(0, d.response_started_count());
5855     EXPECT_TRUE(req->was_cached());
5856
5857     req->FollowDeferredRedirect();
5858     base::RunLoop().Run();
5859     EXPECT_EQ(1, d.received_redirect_count());
5860     EXPECT_EQ(1, d.response_started_count());
5861     EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5862     EXPECT_EQ(test_server_.GetURL("echo"), req->url());
5863   }
5864 }
5865
5866 // Make sure a request isn't cached when a NetworkDelegate forces a redirect
5867 // when the headers are read, since the body won't have been read.
5868 TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5869   ASSERT_TRUE(test_server_.Start());
5870   // URL that is normally cached.
5871   GURL initial_url = test_server_.GetURL("cachetime");
5872
5873   {
5874     // Set up the TestNetworkDelegate tp force a redirect.
5875     GURL redirect_to_url = test_server_.GetURL("echo");
5876     default_network_delegate_.set_redirect_on_headers_received_url(
5877         redirect_to_url);
5878
5879     TestDelegate d;
5880     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5881         initial_url, DEFAULT_PRIORITY, &d, NULL));
5882     req->Start();
5883     base::RunLoop().Run();
5884     EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5885     EXPECT_EQ(1, d.received_redirect_count());
5886     EXPECT_EQ(redirect_to_url, req->url());
5887   }
5888
5889   {
5890     TestDelegate d;
5891     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5892         initial_url, DEFAULT_PRIORITY, &d, NULL));
5893     req->Start();
5894     base::RunLoop().Run();
5895
5896     EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5897     EXPECT_FALSE(req->was_cached());
5898     EXPECT_EQ(0, d.received_redirect_count());
5899     EXPECT_EQ(initial_url, req->url());
5900   }
5901 }
5902
5903 // Tests that redirection to an unsafe URL is allowed when it has been marked as
5904 // safe.
5905 TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5906   ASSERT_TRUE(test_server_.Start());
5907
5908   GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5909   default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5910   default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5911
5912   TestDelegate d;
5913   {
5914     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5915         test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d, NULL));
5916
5917     r->Start();
5918     base::RunLoop().Run();
5919
5920     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5921
5922     EXPECT_EQ(2U, r->url_chain().size());
5923     EXPECT_EQ(OK, r->status().error());
5924     EXPECT_EQ(unsafe_url, r->url());
5925     EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
5926   }
5927 }
5928
5929 // Tests that a redirect to a different unsafe URL is blocked, even after adding
5930 // some other URL to the whitelist.
5931 TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
5932   ASSERT_TRUE(test_server_.Start());
5933
5934   GURL unsafe_url("data:text/html,something");
5935   GURL different_unsafe_url("data:text/html,something-else");
5936   default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5937   default_network_delegate_.set_allowed_unsafe_redirect_url(
5938       different_unsafe_url);
5939
5940   TestDelegate d;
5941   {
5942     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5943         test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d, NULL));
5944
5945     r->Start();
5946     base::RunLoop().Run();
5947
5948     EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5949     EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
5950   }
5951 }
5952
5953 // Redirects from an URL with fragment to an unsafe URL with fragment should
5954 // be allowed, and the reference fragment of the target URL should be preserved.
5955 TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
5956   ASSERT_TRUE(test_server_.Start());
5957
5958   GURL original_url(test_server_.GetURL("original#fragment1"));
5959   GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5960   GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5961
5962   default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5963   default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5964
5965   TestDelegate d;
5966   {
5967     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5968         original_url, DEFAULT_PRIORITY, &d, NULL));
5969
5970     r->Start();
5971     base::RunLoop().Run();
5972
5973     EXPECT_EQ(2U, r->url_chain().size());
5974     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5975     EXPECT_EQ(OK, r->status().error());
5976     EXPECT_EQ(original_url, r->original_url());
5977     EXPECT_EQ(expected_url, r->url());
5978   }
5979 }
5980
5981 // When a delegate has specified a safe redirect URL, but it does not match the
5982 // redirect target, then do not prevent the reference fragment from being added.
5983 TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
5984   ASSERT_TRUE(test_server_.Start());
5985
5986   GURL original_url(test_server_.GetURL("original#expected-fragment"));
5987   GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5988   GURL redirect_url(test_server_.GetURL("target"));
5989   GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
5990
5991   default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5992   default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5993
5994   TestDelegate d;
5995   {
5996     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5997         original_url, DEFAULT_PRIORITY, &d, NULL));
5998
5999     r->Start();
6000     base::RunLoop().Run();
6001
6002     EXPECT_EQ(2U, r->url_chain().size());
6003     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6004     EXPECT_EQ(OK, r->status().error());
6005     EXPECT_EQ(original_url, r->original_url());
6006     EXPECT_EQ(expected_redirect_url, r->url());
6007   }
6008 }
6009
6010 // When a delegate has specified a safe redirect URL, assume that the redirect
6011 // URL should not be changed. In particular, the reference fragment should not
6012 // be modified.
6013 TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
6014   ASSERT_TRUE(test_server_.Start());
6015
6016   GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
6017   GURL redirect_url("data:text/html,expect-no-reference-fragment");
6018
6019   default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6020   default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
6021
6022   TestDelegate d;
6023   {
6024     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6025         original_url, DEFAULT_PRIORITY, &d, NULL));
6026
6027     r->Start();
6028     base::RunLoop().Run();
6029
6030     EXPECT_EQ(2U, r->url_chain().size());
6031     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6032     EXPECT_EQ(OK, r->status().error());
6033     EXPECT_EQ(original_url, r->original_url());
6034     EXPECT_EQ(redirect_url, r->url());
6035   }
6036 }
6037
6038 // When a URLRequestRedirectJob is created, the redirection must be followed and
6039 // the reference fragment of the target URL must not be modified.
6040 TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
6041   ASSERT_TRUE(test_server_.Start());
6042
6043   GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
6044   GURL redirect_url(test_server_.GetURL("echo"));
6045
6046   TestDelegate d;
6047   scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6048       original_url, DEFAULT_PRIORITY, &d, NULL));
6049
6050   URLRequestRedirectJob* job = new URLRequestRedirectJob(
6051       r.get(), &default_network_delegate_, redirect_url,
6052       URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6053   AddTestInterceptor()->set_main_intercept_job(job);
6054
6055   r->Start();
6056   base::RunLoop().Run();
6057
6058   EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6059   EXPECT_EQ(OK, r->status().error());
6060   EXPECT_EQ(original_url, r->original_url());
6061   EXPECT_EQ(redirect_url, r->url());
6062 }
6063
6064 TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
6065   ASSERT_TRUE(test_server_.Start());
6066
6067   TestDelegate d;
6068   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6069       test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
6070   req->SetReferrer("http://user:pass@foo.com/");
6071   req->Start();
6072   base::RunLoop().Run();
6073
6074   EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
6075 }
6076
6077 TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
6078   ASSERT_TRUE(test_server_.Start());
6079
6080   TestDelegate d;
6081   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6082       test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
6083   req->SetReferrer("http://foo.com/test#fragment");
6084   req->Start();
6085   base::RunLoop().Run();
6086
6087   EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
6088 }
6089
6090 TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
6091   ASSERT_TRUE(test_server_.Start());
6092
6093   TestDelegate d;
6094   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6095       test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
6096   req->SetReferrer("http://foo.com/test#fragment");
6097   req->SetReferrer("");
6098   req->Start();
6099   base::RunLoop().Run();
6100
6101   EXPECT_EQ(std::string("None"), d.data_received());
6102 }
6103
6104 // Defer network start and then resume, checking that the request was a success
6105 // and bytes were received.
6106 TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
6107   ASSERT_TRUE(test_server_.Start());
6108
6109   TestDelegate d;
6110   {
6111     d.set_quit_on_network_start(true);
6112     GURL test_url(test_server_.GetURL("echo"));
6113     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6114         test_url, DEFAULT_PRIORITY, &d, NULL));
6115
6116     req->Start();
6117     base::RunLoop().Run();
6118
6119     EXPECT_EQ(1, d.received_before_network_start_count());
6120     EXPECT_EQ(0, d.response_started_count());
6121
6122     req->ResumeNetworkStart();
6123     base::RunLoop().Run();
6124
6125     EXPECT_EQ(1, d.response_started_count());
6126     EXPECT_NE(0, d.bytes_received());
6127     EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6128   }
6129 }
6130
6131 // Check that OnBeforeNetworkStart is only called once even if there is a
6132 // redirect.
6133 TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
6134   ASSERT_TRUE(test_server_.Start());
6135
6136   TestDelegate d;
6137   {
6138     d.set_quit_on_redirect(true);
6139     d.set_quit_on_network_start(true);
6140     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6141         test_server_.GetURL("server-redirect?echo"), DEFAULT_PRIORITY, &d,
6142         NULL));
6143
6144     req->Start();
6145     base::RunLoop().Run();
6146
6147     EXPECT_EQ(1, d.received_before_network_start_count());
6148     EXPECT_EQ(0, d.response_started_count());
6149     EXPECT_EQ(0, d.received_redirect_count());
6150
6151     req->ResumeNetworkStart();
6152     base::RunLoop().Run();
6153
6154     EXPECT_EQ(1, d.received_redirect_count());
6155     req->FollowDeferredRedirect();
6156     base::RunLoop().Run();
6157
6158     // Check that the redirect's new network transaction does not get propagated
6159     // to a second OnBeforeNetworkStart() notification.
6160     EXPECT_EQ(1, d.received_before_network_start_count());
6161
6162     EXPECT_EQ(1, d.response_started_count());
6163     EXPECT_NE(0, d.bytes_received());
6164     EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6165   }
6166 }
6167
6168 // Cancel the request after learning that the request would use the network.
6169 TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
6170   ASSERT_TRUE(test_server_.Start());
6171
6172   TestDelegate d;
6173   {
6174     d.set_quit_on_network_start(true);
6175     GURL test_url(test_server_.GetURL("echo"));
6176     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6177         test_url, DEFAULT_PRIORITY, &d, NULL));
6178
6179     req->Start();
6180     base::RunLoop().Run();
6181
6182     EXPECT_EQ(1, d.received_before_network_start_count());
6183     EXPECT_EQ(0, d.response_started_count());
6184
6185     req->Cancel();
6186     base::RunLoop().Run();
6187
6188     EXPECT_EQ(1, d.response_started_count());
6189     EXPECT_EQ(0, d.bytes_received());
6190     EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
6191   }
6192 }
6193
6194 TEST_F(URLRequestTestHTTP, CancelRedirect) {
6195   ASSERT_TRUE(test_server_.Start());
6196
6197   TestDelegate d;
6198   {
6199     d.set_cancel_in_received_redirect(true);
6200     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6201         test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d,
6202         NULL));
6203     req->Start();
6204     base::RunLoop().Run();
6205
6206     EXPECT_EQ(1, d.response_started_count());
6207     EXPECT_EQ(0, d.bytes_received());
6208     EXPECT_FALSE(d.received_data_before_response());
6209     EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
6210   }
6211 }
6212
6213 TEST_F(URLRequestTestHTTP, DeferredRedirect) {
6214   ASSERT_TRUE(test_server_.Start());
6215
6216   TestDelegate d;
6217   {
6218     d.set_quit_on_redirect(true);
6219     GURL test_url(test_server_.GetURL("files/redirect-test.html"));
6220     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6221         test_url, DEFAULT_PRIORITY, &d, NULL));
6222
6223     req->Start();
6224     base::RunLoop().Run();
6225
6226     EXPECT_EQ(1, d.received_redirect_count());
6227
6228     req->FollowDeferredRedirect();
6229     base::RunLoop().Run();
6230
6231     EXPECT_EQ(1, d.response_started_count());
6232     EXPECT_FALSE(d.received_data_before_response());
6233     EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6234
6235     base::FilePath path;
6236     PathService::Get(base::DIR_SOURCE_ROOT, &path);
6237     path = path.Append(FILE_PATH_LITERAL("net"));
6238     path = path.Append(FILE_PATH_LITERAL("data"));
6239     path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
6240     path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6241
6242     std::string contents;
6243     EXPECT_TRUE(base::ReadFileToString(path, &contents));
6244     EXPECT_EQ(contents, d.data_received());
6245   }
6246 }
6247
6248 TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
6249   ASSERT_TRUE(test_server_.Start());
6250
6251   TestDelegate d;
6252   {
6253     d.set_quit_on_redirect(true);
6254     GURL test_url(test_server_.GetURL("files/redirect-test.html"));
6255     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6256         test_url, DEFAULT_PRIORITY, &d, NULL));
6257
6258     EXPECT_FALSE(d.have_full_request_headers());
6259
6260     req->Start();
6261     base::RunLoop().Run();
6262
6263     EXPECT_EQ(1, d.received_redirect_count());
6264     EXPECT_TRUE(d.have_full_request_headers());
6265     CheckFullRequestHeaders(d.full_request_headers(), test_url);
6266     d.ClearFullRequestHeaders();
6267
6268     req->FollowDeferredRedirect();
6269     base::RunLoop().Run();
6270
6271     GURL target_url(test_server_.GetURL("files/with-headers.html"));
6272     EXPECT_EQ(1, d.response_started_count());
6273     EXPECT_TRUE(d.have_full_request_headers());
6274     CheckFullRequestHeaders(d.full_request_headers(), target_url);
6275     EXPECT_FALSE(d.received_data_before_response());
6276     EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6277
6278     base::FilePath path;
6279     PathService::Get(base::DIR_SOURCE_ROOT, &path);
6280     path = path.Append(FILE_PATH_LITERAL("net"));
6281     path = path.Append(FILE_PATH_LITERAL("data"));
6282     path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
6283     path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6284
6285     std::string contents;
6286     EXPECT_TRUE(base::ReadFileToString(path, &contents));
6287     EXPECT_EQ(contents, d.data_received());
6288   }
6289 }
6290
6291 TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
6292   ASSERT_TRUE(test_server_.Start());
6293
6294   TestDelegate d;
6295   {
6296     d.set_quit_on_redirect(true);
6297     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6298         test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d,
6299         NULL));
6300     req->Start();
6301     base::RunLoop().Run();
6302
6303     EXPECT_EQ(1, d.received_redirect_count());
6304
6305     req->Cancel();
6306     base::RunLoop().Run();
6307
6308     EXPECT_EQ(1, d.response_started_count());
6309     EXPECT_EQ(0, d.bytes_received());
6310     EXPECT_FALSE(d.received_data_before_response());
6311     EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
6312   }
6313 }
6314
6315 TEST_F(URLRequestTestHTTP, VaryHeader) {
6316   ASSERT_TRUE(test_server_.Start());
6317
6318   // Populate the cache.
6319   {
6320     TestDelegate d;
6321     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6322         test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d,
6323         NULL));
6324     HttpRequestHeaders headers;
6325     headers.SetHeader("foo", "1");
6326     req->SetExtraRequestHeaders(headers);
6327     req->Start();
6328     base::RunLoop().Run();
6329
6330     LoadTimingInfo load_timing_info;
6331     req->GetLoadTimingInfo(&load_timing_info);
6332     TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6333   }
6334
6335   // Expect a cache hit.
6336   {
6337     TestDelegate d;
6338     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6339         test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d,
6340         NULL));
6341     HttpRequestHeaders headers;
6342     headers.SetHeader("foo", "1");
6343     req->SetExtraRequestHeaders(headers);
6344     req->Start();
6345     base::RunLoop().Run();
6346
6347     EXPECT_TRUE(req->was_cached());
6348
6349     LoadTimingInfo load_timing_info;
6350     req->GetLoadTimingInfo(&load_timing_info);
6351     TestLoadTimingCacheHitNoNetwork(load_timing_info);
6352   }
6353
6354   // Expect a cache miss.
6355   {
6356     TestDelegate d;
6357     scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6358         test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d,
6359         NULL));
6360     HttpRequestHeaders headers;
6361     headers.SetHeader("foo", "2");
6362     req->SetExtraRequestHeaders(headers);
6363     req->Start();
6364     base::RunLoop().Run();
6365
6366     EXPECT_FALSE(req->was_cached());
6367
6368     LoadTimingInfo load_timing_info;
6369     req->GetLoadTimingInfo(&load_timing_info);
6370     TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6371   }
6372 }
6373
6374 TEST_F(URLRequestTestHTTP, BasicAuth) {
6375   ASSERT_TRUE(test_server_.Start());
6376
6377   // populate the cache
6378   {
6379     TestDelegate d;
6380     d.set_credentials(AuthCredentials(kUser, kSecret));
6381
6382     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6383         test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
6384     r->Start();
6385
6386     base::RunLoop().Run();
6387
6388     EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6389   }
6390
6391   // repeat request with end-to-end validation.  since auth-basic results in a
6392   // cachable page, we expect this test to result in a 304.  in which case, the
6393   // response should be fetched from the cache.
6394   {
6395     TestDelegate d;
6396     d.set_credentials(AuthCredentials(kUser, kSecret));
6397
6398     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6399         test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
6400     r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6401     r->Start();
6402
6403     base::RunLoop().Run();
6404
6405     EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6406
6407     // Should be the same cached document.
6408     EXPECT_TRUE(r->was_cached());
6409   }
6410 }
6411
6412 // Check that Set-Cookie headers in 401 responses are respected.
6413 // http://crbug.com/6450
6414 TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
6415   ASSERT_TRUE(test_server_.Start());
6416
6417   GURL url_requiring_auth =
6418       test_server_.GetURL("auth-basic?set-cookie-if-challenged");
6419
6420   // Request a page that will give a 401 containing a Set-Cookie header.
6421   // Verify that when the transaction is restarted, it includes the new cookie.
6422   {
6423     TestNetworkDelegate network_delegate;  // Must outlive URLRequest.
6424     TestURLRequestContext context(true);
6425     context.set_network_delegate(&network_delegate);
6426     context.Init();
6427
6428     TestDelegate d;
6429     d.set_credentials(AuthCredentials(kUser, kSecret));
6430
6431     scoped_ptr<URLRequest> r(context.CreateRequest(
6432         url_requiring_auth, DEFAULT_PRIORITY, &d, NULL));
6433     r->Start();
6434
6435     base::RunLoop().Run();
6436
6437     EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6438
6439     // Make sure we sent the cookie in the restarted transaction.
6440     EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6441         != std::string::npos);
6442   }
6443
6444   // Same test as above, except this time the restart is initiated earlier
6445   // (without user intervention since identity is embedded in the URL).
6446   {
6447     TestNetworkDelegate network_delegate;  // Must outlive URLRequest.
6448     TestURLRequestContext context(true);
6449     context.set_network_delegate(&network_delegate);
6450     context.Init();
6451
6452     TestDelegate d;
6453
6454     GURL::Replacements replacements;
6455     std::string username("user2");
6456     std::string password("secret");
6457     replacements.SetUsernameStr(username);
6458     replacements.SetPasswordStr(password);
6459     GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
6460
6461     scoped_ptr<URLRequest> r(context.CreateRequest(
6462         url_with_identity, DEFAULT_PRIORITY, &d, NULL));
6463     r->Start();
6464
6465     base::RunLoop().Run();
6466
6467     EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6468
6469     // Make sure we sent the cookie in the restarted transaction.
6470     EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6471         != std::string::npos);
6472   }
6473 }
6474
6475 // Tests that load timing works as expected with auth and the cache.
6476 TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
6477   ASSERT_TRUE(test_server_.Start());
6478
6479   // populate the cache
6480   {
6481     TestDelegate d;
6482     d.set_credentials(AuthCredentials(kUser, kSecret));
6483
6484     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6485         test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
6486     r->Start();
6487
6488     base::RunLoop().Run();
6489
6490     EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6491
6492     LoadTimingInfo load_timing_info_before_auth;
6493     EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
6494         &load_timing_info_before_auth));
6495     TestLoadTimingNotReused(load_timing_info_before_auth,
6496                             CONNECT_TIMING_HAS_DNS_TIMES);
6497
6498     LoadTimingInfo load_timing_info;
6499     r->GetLoadTimingInfo(&load_timing_info);
6500     // The test server does not support keep alive sockets, so the second
6501     // request with auth should use a new socket.
6502     TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6503     EXPECT_NE(load_timing_info_before_auth.socket_log_id,
6504               load_timing_info.socket_log_id);
6505     EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
6506               load_timing_info.connect_timing.connect_start);
6507   }
6508
6509   // Repeat request with end-to-end validation.  Since auth-basic results in a
6510   // cachable page, we expect this test to result in a 304.  In which case, the
6511   // response should be fetched from the cache.
6512   {
6513     TestDelegate d;
6514     d.set_credentials(AuthCredentials(kUser, kSecret));
6515
6516     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6517         test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
6518     r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6519     r->Start();
6520
6521     base::RunLoop().Run();
6522
6523     EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6524
6525     // Should be the same cached document.
6526     EXPECT_TRUE(r->was_cached());
6527
6528     // Since there was a request that went over the wire, the load timing
6529     // information should include connection times.
6530     LoadTimingInfo load_timing_info;
6531     r->GetLoadTimingInfo(&load_timing_info);
6532     TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6533   }
6534 }
6535
6536 // In this test, we do a POST which the server will 302 redirect.
6537 // The subsequent transaction should use GET, and should not send the
6538 // Content-Type header.
6539 // http://code.google.com/p/chromium/issues/detail?id=843
6540 TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
6541   ASSERT_TRUE(test_server_.Start());
6542
6543   const char kData[] = "hello world";
6544
6545   TestDelegate d;
6546   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6547       test_server_.GetURL("files/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
6548       NULL));
6549   req->set_method("POST");
6550   req->set_upload(CreateSimpleUploadData(kData));
6551
6552   // Set headers (some of which are specific to the POST).
6553   HttpRequestHeaders headers;
6554   headers.AddHeadersFromString(
6555     "Content-Type: multipart/form-data; "
6556     "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
6557     "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
6558     "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
6559     "Accept-Language: en-US,en\r\n"
6560     "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
6561     "Content-Length: 11\r\n"
6562     "Origin: http://localhost:1337/");
6563   req->SetExtraRequestHeaders(headers);
6564   req->Start();
6565   base::RunLoop().Run();
6566
6567   std::string mime_type;
6568   req->GetMimeType(&mime_type);
6569   EXPECT_EQ("text/html", mime_type);
6570
6571   const std::string& data = d.data_received();
6572
6573   // Check that the post-specific headers were stripped:
6574   EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6575   EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6576   EXPECT_FALSE(ContainsString(data, "Origin:"));
6577
6578   // These extra request headers should not have been stripped.
6579   EXPECT_TRUE(ContainsString(data, "Accept:"));
6580   EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6581   EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6582 }
6583
6584 // The following tests check that we handle mutating the request method for
6585 // HTTP redirects as expected.
6586 // See http://crbug.com/56373 and http://crbug.com/102130.
6587
6588 TEST_F(URLRequestTestHTTP, Redirect301Tests) {
6589   ASSERT_TRUE(test_server_.Start());
6590
6591   const GURL url = test_server_.GetURL("files/redirect301-to-echo");
6592
6593   HTTPRedirectMethodTest(url, "POST", "GET", true);
6594   HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6595   HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6596 }
6597
6598 TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6599   ASSERT_TRUE(test_server_.Start());
6600
6601   const GURL url = test_server_.GetURL("files/redirect302-to-echo");
6602
6603   HTTPRedirectMethodTest(url, "POST", "GET", true);
6604   HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6605   HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6606 }
6607
6608 TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6609   ASSERT_TRUE(test_server_.Start());
6610
6611   const GURL url = test_server_.GetURL("files/redirect303-to-echo");
6612
6613   HTTPRedirectMethodTest(url, "POST", "GET", true);
6614   HTTPRedirectMethodTest(url, "PUT", "GET", true);
6615   HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6616 }
6617
6618 TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6619   ASSERT_TRUE(test_server_.Start());
6620
6621   const GURL url = test_server_.GetURL("files/redirect307-to-echo");
6622
6623   HTTPRedirectMethodTest(url, "POST", "POST", true);
6624   HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6625   HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6626 }
6627
6628 TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6629   ASSERT_TRUE(test_server_.Start());
6630
6631   const GURL url = test_server_.GetURL("files/redirect308-to-echo");
6632
6633   HTTPRedirectMethodTest(url, "POST", "POST", true);
6634   HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6635   HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6636 }
6637
6638 // Make sure that 308 responses without bodies are not treated as redirects.
6639 // Certain legacy apis that pre-date the response code expect this behavior
6640 // (Like Google Drive).
6641 TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6642   ASSERT_TRUE(test_server_.Start());
6643
6644   TestDelegate d;
6645   const GURL url = test_server_.GetURL("files/308-without-location-header");
6646
6647   scoped_ptr<URLRequest> request(default_context_.CreateRequest(
6648       url, DEFAULT_PRIORITY, &d, NULL));
6649
6650   request->Start();
6651   base::RunLoop().Run();
6652   EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
6653   EXPECT_EQ(OK, request->status().error());
6654   EXPECT_EQ(0, d.received_redirect_count());
6655   EXPECT_EQ(308, request->response_headers()->response_code());
6656   EXPECT_EQ("This is not a redirect.", d.data_received());
6657 }
6658
6659 TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6660   ASSERT_TRUE(test_server_.Start());
6661
6662   GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6663   GURL expected_url(test_server_.GetURL("echo#fragment"));
6664
6665   TestDelegate d;
6666   {
6667     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6668         original_url, DEFAULT_PRIORITY, &d, NULL));
6669
6670     r->Start();
6671     base::RunLoop().Run();
6672
6673     EXPECT_EQ(2U, r->url_chain().size());
6674     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6675     EXPECT_EQ(OK, r->status().error());
6676     EXPECT_EQ(original_url, r->original_url());
6677     EXPECT_EQ(expected_url, r->url());
6678   }
6679 }
6680
6681 TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
6682   ASSERT_TRUE(test_server_.Start());
6683
6684   GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6685   GURL first_party_url("http://example.com");
6686
6687   TestDelegate d;
6688   {
6689     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6690         url, DEFAULT_PRIORITY, &d, NULL));
6691     r->set_first_party_for_cookies(first_party_url);
6692
6693     r->Start();
6694     base::RunLoop().Run();
6695
6696     EXPECT_EQ(2U, r->url_chain().size());
6697     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6698     EXPECT_EQ(OK, r->status().error());
6699     EXPECT_EQ(first_party_url, r->first_party_for_cookies());
6700   }
6701 }
6702
6703 TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
6704   ASSERT_TRUE(test_server_.Start());
6705
6706   GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6707   GURL original_first_party_url("http://example.com");
6708   GURL expected_first_party_url(test_server_.GetURL("echo"));
6709
6710   TestDelegate d;
6711   {
6712     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6713         url, DEFAULT_PRIORITY, &d, NULL));
6714     r->set_first_party_for_cookies(original_first_party_url);
6715     r->set_first_party_url_policy(
6716         URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
6717
6718     r->Start();
6719     base::RunLoop().Run();
6720
6721     EXPECT_EQ(2U, r->url_chain().size());
6722     EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6723     EXPECT_EQ(OK, r->status().error());
6724     EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
6725   }
6726 }
6727
6728 TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6729   ASSERT_TRUE(test_server_.Start());
6730
6731   const char kData[] = "hello world";
6732
6733   TestDelegate d;
6734   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6735       test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
6736   req->set_method("POST");
6737   req->set_upload(CreateSimpleUploadData(kData));
6738   HttpRequestHeaders headers;
6739   headers.SetHeader(HttpRequestHeaders::kContentLength,
6740                     base::UintToString(arraysize(kData) - 1));
6741   req->SetExtraRequestHeaders(headers);
6742
6743   URLRequestRedirectJob* job = new URLRequestRedirectJob(
6744       req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
6745       URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6746   AddTestInterceptor()->set_main_intercept_job(job);
6747
6748   req->Start();
6749   base::RunLoop().Run();
6750   EXPECT_EQ("GET", req->method());
6751 }
6752
6753 TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6754   ASSERT_TRUE(test_server_.Start());
6755
6756   const char kData[] = "hello world";
6757
6758   TestDelegate d;
6759   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6760       test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
6761   req->set_method("POST");
6762   req->set_upload(CreateSimpleUploadData(kData));
6763   HttpRequestHeaders headers;
6764   headers.SetHeader(HttpRequestHeaders::kContentLength,
6765                     base::UintToString(arraysize(kData) - 1));
6766   req->SetExtraRequestHeaders(headers);
6767
6768   URLRequestRedirectJob* job = new URLRequestRedirectJob(
6769       req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
6770       URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6771       "Very Good Reason");
6772   AddTestInterceptor()->set_main_intercept_job(job);
6773
6774   req->Start();
6775   base::RunLoop().Run();
6776   EXPECT_EQ("POST", req->method());
6777   EXPECT_EQ(kData, d.data_received());
6778 }
6779
6780 // Check that default A-L header is sent.
6781 TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6782   ASSERT_TRUE(test_server_.Start());
6783
6784   StaticHttpUserAgentSettings settings("en", std::string());
6785   TestNetworkDelegate network_delegate;  // Must outlive URLRequests.
6786   TestURLRequestContext context(true);
6787   context.set_network_delegate(&network_delegate);
6788   context.set_http_user_agent_settings(&settings);
6789   context.Init();
6790
6791   TestDelegate d;
6792   scoped_ptr<URLRequest> req(context.CreateRequest(
6793       test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d,
6794       NULL));
6795   req->Start();
6796   base::RunLoop().Run();
6797   EXPECT_EQ("en", d.data_received());
6798 }
6799
6800 // Check that an empty A-L header is not sent. http://crbug.com/77365.
6801 TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6802   ASSERT_TRUE(test_server_.Start());
6803
6804   std::string empty_string;  // Avoid most vexing parse on line below.
6805   StaticHttpUserAgentSettings settings(empty_string, empty_string);
6806   TestNetworkDelegate network_delegate;  // Must outlive URLRequests.
6807   TestURLRequestContext context(true);
6808   context.set_network_delegate(&network_delegate);
6809   context.Init();
6810   // We override the language after initialization because empty entries
6811   // get overridden by Init().
6812   context.set_http_user_agent_settings(&settings);
6813
6814   TestDelegate d;
6815   scoped_ptr<URLRequest> req(context.CreateRequest(
6816       test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d,
6817       NULL));
6818   req->Start();
6819   base::RunLoop().Run();
6820   EXPECT_EQ("None", d.data_received());
6821 }
6822
6823 // Check that if request overrides the A-L header, the default is not appended.
6824 // See http://crbug.com/20894
6825 TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6826   ASSERT_TRUE(test_server_.Start());
6827
6828   TestDelegate d;
6829   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6830       test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d,
6831       NULL));
6832   HttpRequestHeaders headers;
6833   headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
6834   req->SetExtraRequestHeaders(headers);
6835   req->Start();
6836   base::RunLoop().Run();
6837   EXPECT_EQ(std::string("ru"), d.data_received());
6838 }
6839
6840 // Check that default A-E header is sent.
6841 TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6842   ASSERT_TRUE(test_server_.Start());
6843
6844   TestDelegate d;
6845   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6846       test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d,
6847       NULL));
6848   HttpRequestHeaders headers;
6849   req->SetExtraRequestHeaders(headers);
6850   req->Start();
6851   base::RunLoop().Run();
6852   EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6853 }
6854
6855 // Check that if request overrides the A-E header, the default is not appended.
6856 // See http://crbug.com/47381
6857 TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6858   ASSERT_TRUE(test_server_.Start());
6859
6860   TestDelegate d;
6861   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6862       test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d,
6863       NULL));
6864   HttpRequestHeaders headers;
6865   headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
6866   req->SetExtraRequestHeaders(headers);
6867   req->Start();
6868   base::RunLoop().Run();
6869   EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6870   EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6871 }
6872
6873 // Check that setting the A-C header sends the proper header.
6874 TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
6875   ASSERT_TRUE(test_server_.Start());
6876
6877   TestDelegate d;
6878   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6879       test_server_.GetURL("echoheader?Accept-Charset"), DEFAULT_PRIORITY, &d,
6880       NULL));
6881   HttpRequestHeaders headers;
6882   headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
6883   req->SetExtraRequestHeaders(headers);
6884   req->Start();
6885   base::RunLoop().Run();
6886   EXPECT_EQ(std::string("koi-8r"), d.data_received());
6887 }
6888
6889 // Check that default User-Agent header is sent.
6890 TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6891   ASSERT_TRUE(test_server_.Start());
6892
6893   TestDelegate d;
6894   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6895       test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d,
6896       NULL));
6897   req->Start();
6898   base::RunLoop().Run();
6899   EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
6900             d.data_received());
6901 }
6902
6903 // Check that if request overrides the User-Agent header,
6904 // the default is not appended.
6905 TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
6906   ASSERT_TRUE(test_server_.Start());
6907
6908   TestDelegate d;
6909   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6910       test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d,
6911       NULL));
6912   HttpRequestHeaders headers;
6913   headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
6914   req->SetExtraRequestHeaders(headers);
6915   req->Start();
6916   base::RunLoop().Run();
6917   EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
6918 }
6919
6920 // Check that a NULL HttpUserAgentSettings causes the corresponding empty
6921 // User-Agent header to be sent but does not send the Accept-Language and
6922 // Accept-Charset headers.
6923 TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
6924   ASSERT_TRUE(test_server_.Start());
6925
6926   TestNetworkDelegate network_delegate;  // Must outlive URLRequests.
6927   TestURLRequestContext context(true);
6928   context.set_network_delegate(&network_delegate);
6929   context.Init();
6930   // We override the HttpUserAgentSettings after initialization because empty
6931   // entries get overridden by Init().
6932   context.set_http_user_agent_settings(NULL);
6933
6934   struct {
6935     const char* request;
6936     const char* expected_response;
6937   } tests[] = { { "echoheader?Accept-Language", "None" },
6938                 { "echoheader?Accept-Charset", "None" },
6939                 { "echoheader?User-Agent", "" } };
6940
6941   for (size_t i = 0; i < arraysize(tests); i++) {
6942     TestDelegate d;
6943     scoped_ptr<URLRequest> req(context.CreateRequest(
6944         test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d, NULL));
6945     req->Start();
6946     base::RunLoop().Run();
6947     EXPECT_EQ(tests[i].expected_response, d.data_received())
6948         << " Request = \"" << tests[i].request << "\"";
6949   }
6950 }
6951
6952 // Make sure that URLRequest passes on its priority updates to
6953 // newly-created jobs after the first one.
6954 TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
6955   ASSERT_TRUE(test_server_.Start());
6956
6957   TestDelegate d;
6958   scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6959       test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
6960   EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
6961
6962   scoped_refptr<URLRequestRedirectJob> redirect_job =
6963       new URLRequestRedirectJob(
6964           req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
6965           URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6966   AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
6967
6968   req->SetPriority(LOW);
6969   req->Start();
6970   EXPECT_TRUE(req->is_pending());
6971
6972   scoped_refptr<URLRequestTestJob> job =
6973       new URLRequestTestJob(req.get(), &default_network_delegate_);
6974   AddTestInterceptor()->set_main_intercept_job(job.get());
6975
6976   // Should trigger |job| to be started.
6977   base::RunLoop().Run();
6978   EXPECT_EQ(LOW, job->priority());
6979 }
6980
6981 // Check that creating a network request while entering/exiting suspend mode
6982 // fails as it should.  This is the only case where an HttpTransactionFactory
6983 // does not return an HttpTransaction.
6984 TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6985   // Create a new HttpNetworkLayer that thinks it's suspended.
6986   HttpNetworkSession::Params params;
6987   params.host_resolver = default_context_.host_resolver();
6988   params.cert_verifier = default_context_.cert_verifier();
6989   params.transport_security_state = default_context_.transport_security_state();
6990   params.proxy_service = default_context_.proxy_service();
6991   params.ssl_config_service = default_context_.ssl_config_service();
6992   params.http_auth_handler_factory =
6993       default_context_.http_auth_handler_factory();
6994   params.network_delegate = &default_network_delegate_;
6995   params.http_server_properties = default_context_.http_server_properties();
6996   scoped_ptr<HttpNetworkLayer> network_layer(
6997       new HttpNetworkLayer(new HttpNetworkSession(params)));
6998   network_layer->OnSuspend();
6999
7000   HttpCache http_cache(network_layer.release(), default_context_.net_log(),
7001                        HttpCache::DefaultBackend::InMemory(0));
7002
7003   TestURLRequestContext context(true);
7004   context.set_http_transaction_factory(&http_cache);
7005   context.Init();
7006
7007   TestDelegate d;
7008   scoped_ptr<URLRequest> req(context.CreateRequest(
7009       GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d, NULL));
7010   req->Start();
7011   base::RunLoop().Run();
7012
7013   EXPECT_TRUE(d.request_failed());
7014   EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7015   EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
7016 }
7017
7018 // Check that creating a network request while entering/exiting suspend mode
7019 // fails as it should in the case there is no cache.  This is the only case
7020 // where an HttpTransactionFactory does not return an HttpTransaction.
7021 TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
7022   // Create a new HttpNetworkLayer that thinks it's suspended.
7023   HttpNetworkSession::Params params;
7024   params.host_resolver = default_context_.host_resolver();
7025   params.cert_verifier = default_context_.cert_verifier();
7026   params.transport_security_state = default_context_.transport_security_state();
7027   params.proxy_service = default_context_.proxy_service();
7028   params.ssl_config_service = default_context_.ssl_config_service();
7029   params.http_auth_handler_factory =
7030       default_context_.http_auth_handler_factory();
7031   params.network_delegate = &default_network_delegate_;
7032   params.http_server_properties = default_context_.http_server_properties();
7033   HttpNetworkLayer network_layer(new HttpNetworkSession(params));
7034   network_layer.OnSuspend();
7035
7036   TestURLRequestContext context(true);
7037   context.set_http_transaction_factory(&network_layer);
7038   context.Init();
7039
7040   TestDelegate d;
7041   scoped_ptr<URLRequest> req(context.CreateRequest(
7042       GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d, NULL));
7043   req->Start();
7044   base::RunLoop().Run();
7045
7046   EXPECT_TRUE(d.request_failed());
7047   EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7048   EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
7049 }
7050
7051 class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
7052  public:
7053   // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
7054   // ideally remove the dependency on URLRequestTestJob, and maybe move these
7055   // tests into the factory tests.
7056   URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
7057   }
7058
7059   void SetUpFactory() override {
7060     interceptor_ = new MockURLRequestInterceptor();
7061     job_factory_.reset(new URLRequestInterceptingJobFactory(
7062         job_factory_.Pass(), make_scoped_ptr(interceptor_)));
7063   }
7064
7065   MockURLRequestInterceptor* interceptor() const {
7066     return interceptor_;
7067   }
7068
7069  private:
7070   MockURLRequestInterceptor* interceptor_;
7071 };
7072
7073 TEST_F(URLRequestInterceptorTestHTTP,
7074        NetworkDelegateNotificationOnRedirectIntercept) {
7075   interceptor()->set_intercept_redirect(true);
7076   interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
7077   interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
7078
7079   ASSERT_TRUE(test_server()->Start());
7080
7081   TestDelegate d;
7082   scoped_ptr<URLRequest> req(default_context().CreateRequest(
7083       test_server()->GetURL("files/redirect-test.html"), DEFAULT_PRIORITY,
7084       &d, nullptr));
7085   req->Start();
7086   base::RunLoop().Run();
7087
7088   EXPECT_TRUE(interceptor()->did_intercept_redirect());
7089   // Check we got one good response
7090   EXPECT_TRUE(req->status().is_success());
7091   if (req->status().is_success())
7092     EXPECT_EQ(200, req->response_headers()->response_code());
7093
7094   EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7095   EXPECT_EQ(1, d.response_started_count());
7096   EXPECT_EQ(0, d.received_redirect_count());
7097
7098   EXPECT_EQ(1, default_network_delegate()->created_requests());
7099   EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7100   EXPECT_EQ(1, default_network_delegate()->headers_received_count());
7101 }
7102
7103 TEST_F(URLRequestInterceptorTestHTTP,
7104        NetworkDelegateNotificationOnErrorIntercept) {
7105   // Intercept that error and respond with an OK response.
7106   interceptor()->set_intercept_final_response(true);
7107   interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
7108   interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
7109   default_network_delegate()->set_can_be_intercepted_on_error(true);
7110
7111   ASSERT_TRUE(test_server()->Start());
7112
7113   TestDelegate d;
7114   scoped_ptr<URLRequest> req(default_context().CreateRequest(
7115       test_server()->GetURL("files/two-content-lengths.html"), DEFAULT_PRIORITY,
7116       &d, nullptr));
7117   req->set_method("GET");
7118   req->Start();
7119   base::RunLoop().Run();
7120
7121   EXPECT_TRUE(interceptor()->did_intercept_final());
7122
7123   // Check we received one good response.
7124   EXPECT_TRUE(req->status().is_success());
7125   if (req->status().is_success())
7126     EXPECT_EQ(200, req->response_headers()->response_code());
7127   EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7128   EXPECT_EQ(1, d.response_started_count());
7129   EXPECT_EQ(0, d.received_redirect_count());
7130
7131   EXPECT_EQ(1, default_network_delegate()->created_requests());
7132   EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7133   EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7134 }
7135
7136 TEST_F(URLRequestInterceptorTestHTTP,
7137        NetworkDelegateNotificationOnResponseIntercept) {
7138   // Intercept that error and respond with an OK response.
7139   interceptor()->set_intercept_final_response(true);
7140
7141   // Intercept with a real URLRequestHttpJob.
7142   interceptor()->set_use_url_request_http_job(true);
7143
7144   ASSERT_TRUE(test_server()->Start());
7145
7146   TestDelegate d;
7147   scoped_ptr<URLRequest> req(default_context().CreateRequest(
7148       test_server()->GetURL("files/simple.html"), DEFAULT_PRIORITY,
7149       &d, nullptr));
7150   req->set_method("GET");
7151   req->Start();
7152   base::RunLoop().Run();
7153
7154   EXPECT_TRUE(interceptor()->did_intercept_final());
7155
7156   // Check we received one good response.
7157   EXPECT_TRUE(req->status().is_success());
7158   if (req->status().is_success())
7159     EXPECT_EQ(200, req->response_headers()->response_code());
7160   EXPECT_EQ("hello", d.data_received());
7161   EXPECT_EQ(1, d.response_started_count());
7162   EXPECT_EQ(0, d.received_redirect_count());
7163
7164   EXPECT_EQ(1, default_network_delegate()->created_requests());
7165   EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
7166   EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7167 }
7168
7169 class HTTPSRequestTest : public testing::Test {
7170  public:
7171   HTTPSRequestTest() : default_context_(true) {
7172     default_context_.set_network_delegate(&default_network_delegate_);
7173     default_context_.Init();
7174   }
7175   ~HTTPSRequestTest() override {}
7176
7177  protected:
7178   TestNetworkDelegate default_network_delegate_;  // Must outlive URLRequest.
7179   TestURLRequestContext default_context_;
7180 };
7181
7182 TEST_F(HTTPSRequestTest, HTTPSGetTest) {
7183   SpawnedTestServer test_server(
7184       SpawnedTestServer::TYPE_HTTPS,
7185       SpawnedTestServer::kLocalhost,
7186       base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7187   ASSERT_TRUE(test_server.Start());
7188
7189   TestDelegate d;
7190   {
7191     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7192         test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
7193     r->Start();
7194     EXPECT_TRUE(r->is_pending());
7195
7196     base::RunLoop().Run();
7197
7198     EXPECT_EQ(1, d.response_started_count());
7199     EXPECT_FALSE(d.received_data_before_response());
7200     EXPECT_NE(0, d.bytes_received());
7201     CheckSSLInfo(r->ssl_info());
7202     EXPECT_EQ(test_server.host_port_pair().host(),
7203               r->GetSocketAddress().host());
7204     EXPECT_EQ(test_server.host_port_pair().port(),
7205               r->GetSocketAddress().port());
7206   }
7207 }
7208
7209 TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
7210   SpawnedTestServer::SSLOptions ssl_options(
7211       SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7212   SpawnedTestServer test_server(
7213       SpawnedTestServer::TYPE_HTTPS,
7214       ssl_options,
7215       base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7216   ASSERT_TRUE(test_server.Start());
7217
7218   bool err_allowed = true;
7219   for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7220     TestDelegate d;
7221     {
7222       d.set_allow_certificate_errors(err_allowed);
7223       scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7224           test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
7225
7226       r->Start();
7227       EXPECT_TRUE(r->is_pending());
7228
7229       base::RunLoop().Run();
7230
7231       EXPECT_EQ(1, d.response_started_count());
7232       EXPECT_FALSE(d.received_data_before_response());
7233       EXPECT_TRUE(d.have_certificate_errors());
7234       if (err_allowed) {
7235         EXPECT_NE(0, d.bytes_received());
7236         CheckSSLInfo(r->ssl_info());
7237       } else {
7238         EXPECT_EQ(0, d.bytes_received());
7239       }
7240     }
7241   }
7242 }
7243
7244 TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
7245   SpawnedTestServer::SSLOptions ssl_options(
7246       SpawnedTestServer::SSLOptions::CERT_EXPIRED);
7247   SpawnedTestServer test_server(
7248       SpawnedTestServer::TYPE_HTTPS,
7249       ssl_options,
7250       base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7251   ASSERT_TRUE(test_server.Start());
7252
7253   // Iterate from false to true, just so that we do the opposite of the
7254   // previous test in order to increase test coverage.
7255   bool err_allowed = false;
7256   for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7257     TestDelegate d;
7258     {
7259       d.set_allow_certificate_errors(err_allowed);
7260       scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7261           test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
7262
7263       r->Start();
7264       EXPECT_TRUE(r->is_pending());
7265
7266       base::RunLoop().Run();
7267
7268       EXPECT_EQ(1, d.response_started_count());
7269       EXPECT_FALSE(d.received_data_before_response());
7270       EXPECT_TRUE(d.have_certificate_errors());
7271       if (err_allowed) {
7272         EXPECT_NE(0, d.bytes_received());
7273         CheckSSLInfo(r->ssl_info());
7274       } else {
7275         EXPECT_EQ(0, d.bytes_received());
7276       }
7277     }
7278   }
7279 }
7280
7281 // This tests that a load of www.google.com with a certificate error sets
7282 // the |certificate_errors_are_fatal| flag correctly. This flag will cause
7283 // the interstitial to be fatal.
7284 TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
7285   SpawnedTestServer::SSLOptions ssl_options(
7286       SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7287   SpawnedTestServer test_server(
7288       SpawnedTestServer::TYPE_HTTPS,
7289       ssl_options,
7290       base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7291   ASSERT_TRUE(test_server.Start());
7292
7293   // We require that the URL be www.google.com in order to pick up the
7294   // preloaded HSTS entries in the TransportSecurityState. This means that we
7295   // have to use a MockHostResolver in order to direct www.google.com to the
7296   // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
7297
7298   MockHostResolver host_resolver;
7299   TestNetworkDelegate network_delegate;  // Must outlive URLRequest.
7300   TestURLRequestContext context(true);
7301   context.set_network_delegate(&network_delegate);
7302   context.set_host_resolver(&host_resolver);
7303   TransportSecurityState transport_security_state;
7304   context.set_transport_security_state(&transport_security_state);
7305   context.Init();
7306
7307   TestDelegate d;
7308   scoped_ptr<URLRequest> r(context.CreateRequest(
7309       GURL(base::StringPrintf("https://www.google.com:%d",
7310                                   test_server.host_port_pair().port())),
7311       DEFAULT_PRIORITY, &d, NULL));
7312
7313   r->Start();
7314   EXPECT_TRUE(r->is_pending());
7315
7316   base::RunLoop().Run();
7317
7318   EXPECT_EQ(1, d.response_started_count());
7319   EXPECT_FALSE(d.received_data_before_response());
7320   EXPECT_TRUE(d.have_certificate_errors());
7321   EXPECT_TRUE(d.certificate_errors_are_fatal());
7322 }
7323
7324 // This tests that cached HTTPS page loads do not cause any updates to the
7325 // TransportSecurityState.
7326 TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
7327   // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
7328   // matter. It just has to be any error.
7329   SpawnedTestServer::SSLOptions ssl_options(
7330       SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7331   SpawnedTestServer test_server(
7332       SpawnedTestServer::TYPE_HTTPS,
7333       ssl_options,
7334       base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7335   ASSERT_TRUE(test_server.Start());
7336
7337   // We require that the URL be www.google.com in order to pick up the static
7338   // and dynamic STS and PKP entries in the TransportSecurityState. This means
7339   // that we have to use a MockHostResolver in order to direct www.google.com to
7340   // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
7341
7342   MockHostResolver host_resolver;
7343   TestNetworkDelegate network_delegate;  // Must outlive URLRequest.
7344   TestURLRequestContext context(true);
7345   context.set_network_delegate(&network_delegate);
7346   context.set_host_resolver(&host_resolver);
7347   TransportSecurityState transport_security_state;
7348
7349   TransportSecurityState::DomainState static_domain_state;
7350   EXPECT_TRUE(transport_security_state.GetStaticDomainState(
7351       "www.google.com", &static_domain_state));
7352   context.set_transport_security_state(&transport_security_state);
7353   context.Init();
7354
7355   TransportSecurityState::DomainState dynamic_domain_state;
7356   EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7357       "www.google.com", &dynamic_domain_state));
7358
7359   TestDelegate d;
7360   scoped_ptr<URLRequest> r(context.CreateRequest(
7361       GURL(base::StringPrintf("https://www.google.com:%d",
7362                                   test_server.host_port_pair().port())),
7363       DEFAULT_PRIORITY, &d, NULL));
7364
7365   r->Start();
7366   EXPECT_TRUE(r->is_pending());
7367
7368   base::RunLoop().Run();
7369
7370   EXPECT_EQ(1, d.response_started_count());
7371   EXPECT_FALSE(d.received_data_before_response());
7372   EXPECT_TRUE(d.have_certificate_errors());
7373   EXPECT_TRUE(d.certificate_errors_are_fatal());
7374
7375   // Get a fresh copy of the states, and check that they haven't changed.
7376   TransportSecurityState::DomainState new_static_domain_state;
7377   EXPECT_TRUE(transport_security_state.GetStaticDomainState(
7378       "www.google.com", &new_static_domain_state));
7379   TransportSecurityState::DomainState new_dynamic_domain_state;
7380   EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7381       "www.google.com", &new_dynamic_domain_state));
7382
7383   EXPECT_EQ(new_static_domain_state.sts.upgrade_mode,
7384             static_domain_state.sts.upgrade_mode);
7385   EXPECT_EQ(new_static_domain_state.sts.include_subdomains,
7386             static_domain_state.sts.include_subdomains);
7387   EXPECT_EQ(new_static_domain_state.pkp.include_subdomains,
7388             static_domain_state.pkp.include_subdomains);
7389   EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.spki_hashes,
7390                                 static_domain_state.pkp.spki_hashes));
7391   EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.bad_spki_hashes,
7392                                 static_domain_state.pkp.bad_spki_hashes));
7393 }
7394
7395 // Make sure HSTS preserves a POST request's method and body.
7396 TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
7397   static const char kData[] = "hello world";
7398
7399   SpawnedTestServer::SSLOptions ssl_options(
7400       SpawnedTestServer::SSLOptions::CERT_OK);
7401   SpawnedTestServer test_server(
7402       SpawnedTestServer::TYPE_HTTPS,
7403       ssl_options,
7404       base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7405   ASSERT_TRUE(test_server.Start());
7406
7407
7408   // Per spec, TransportSecurityState expects a domain name, rather than an IP
7409   // address, so a MockHostResolver is needed to redirect www.somewhere.com to
7410   // the SpawnedTestServer.  By default, MockHostResolver maps all hosts
7411   // to 127.0.0.1.
7412   MockHostResolver host_resolver;
7413
7414   // Force https for www.somewhere.com.
7415   TransportSecurityState transport_security_state;
7416   base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
7417   bool include_subdomains = false;
7418   transport_security_state.AddHSTS("www.somewhere.com", expiry,
7419                                    include_subdomains);
7420
7421   TestNetworkDelegate network_delegate;  // Must outlive URLRequest.
7422
7423   TestURLRequestContext context(true);
7424   context.set_host_resolver(&host_resolver);
7425   context.set_transport_security_state(&transport_security_state);
7426   context.set_network_delegate(&network_delegate);
7427   context.Init();
7428
7429   TestDelegate d;
7430   // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
7431   // cause a certificate error.  Ignore the error.
7432   d.set_allow_certificate_errors(true);
7433
7434   scoped_ptr<URLRequest> req(context.CreateRequest(
7435       GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
7436                                   test_server.host_port_pair().port())),
7437       DEFAULT_PRIORITY, &d, NULL));
7438   req->set_method("POST");
7439   req->set_upload(CreateSimpleUploadData(kData));
7440
7441   req->Start();
7442   base::RunLoop().Run();
7443
7444   EXPECT_EQ("https", req->url().scheme());
7445   EXPECT_EQ("POST", req->method());
7446   EXPECT_EQ(kData, d.data_received());
7447
7448   LoadTimingInfo load_timing_info;
7449   network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
7450   // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
7451   TestLoadTimingCacheHitNoNetwork(load_timing_info);
7452 }
7453
7454 // Make sure that the CORS headers are added to cross-origin HSTS redirects.
7455 TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
7456   static const char kOriginHeaderValue[] = "http://www.example.com";
7457
7458   SpawnedTestServer::SSLOptions ssl_options(
7459       SpawnedTestServer::SSLOptions::CERT_OK);
7460   SpawnedTestServer test_server(
7461       SpawnedTestServer::TYPE_HTTPS,
7462       ssl_options,
7463       base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7464   ASSERT_TRUE(test_server.Start());
7465
7466   // Per spec, TransportSecurityState expects a domain name, rather than an IP
7467   // address, so a MockHostResolver is needed to redirect example.net to the
7468   // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
7469   MockHostResolver host_resolver;
7470
7471   TransportSecurityState transport_security_state;
7472   base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7473   bool include_subdomains = false;
7474   transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7475
7476   TestNetworkDelegate network_delegate;  // Must outlive URLRequest.
7477
7478   MockCertVerifier cert_verifier;
7479   cert_verifier.set_default_result(OK);
7480
7481   TestURLRequestContext context(true);
7482   context.set_host_resolver(&host_resolver);
7483   context.set_transport_security_state(&transport_security_state);
7484   context.set_network_delegate(&network_delegate);
7485   context.set_cert_verifier(&cert_verifier);
7486   context.Init();
7487
7488   GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
7489                                         test_server.host_port_pair().port()));
7490   url::Replacements<char> replacements;
7491   const char kNewScheme[] = "https";
7492   replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
7493   GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
7494
7495   TestDelegate d;
7496   // Quit on redirect to allow response header inspection upon redirect.
7497   d.set_quit_on_redirect(true);
7498
7499   scoped_ptr<URLRequest> req(context.CreateRequest(hsts_http_url,
7500                                                    DEFAULT_PRIORITY, &d, NULL));
7501   // Set Origin header to simulate a cross-origin request.
7502   HttpRequestHeaders request_headers;
7503   request_headers.SetHeader("Origin", kOriginHeaderValue);
7504   req->SetExtraRequestHeaders(request_headers);
7505
7506   req->Start();
7507   base::RunLoop().Run();
7508
7509   EXPECT_EQ(1, d.received_redirect_count());
7510
7511   const HttpResponseHeaders* headers = req->response_headers();
7512   std::string redirect_location;
7513   EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
7514   EXPECT_EQ(hsts_https_url.spec(), redirect_location);
7515
7516   std::string received_cors_header;
7517   EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
7518                                        &received_cors_header));
7519   EXPECT_EQ(kOriginHeaderValue, received_cors_header);
7520 }
7521
7522 namespace {
7523
7524 class SSLClientAuthTestDelegate : public TestDelegate {
7525  public:
7526   SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
7527   }
7528   void OnCertificateRequested(URLRequest* request,
7529                               SSLCertRequestInfo* cert_request_info) override {
7530     on_certificate_requested_count_++;
7531     base::MessageLoop::current()->Quit();
7532   }
7533   int on_certificate_requested_count() {
7534     return on_certificate_requested_count_;
7535   }
7536  private:
7537   int on_certificate_requested_count_;
7538 };
7539
7540 }  // namespace
7541
7542 // TODO(davidben): Test the rest of the code. Specifically,
7543 // - Filtering which certificates to select.
7544 // - Sending a certificate back.
7545 // - Getting a certificate request in an SSL renegotiation sending the
7546 //   HTTP request.
7547 TEST_F(HTTPSRequestTest, ClientAuthTest) {
7548   SpawnedTestServer::SSLOptions ssl_options;
7549   ssl_options.request_client_certificate = true;
7550   SpawnedTestServer test_server(
7551       SpawnedTestServer::TYPE_HTTPS,
7552       ssl_options,
7553       base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7554   ASSERT_TRUE(test_server.Start());
7555
7556   SSLClientAuthTestDelegate d;
7557   {
7558     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7559         test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
7560
7561     r->Start();
7562     EXPECT_TRUE(r->is_pending());
7563
7564     base::RunLoop().Run();
7565
7566     EXPECT_EQ(1, d.on_certificate_requested_count());
7567     EXPECT_FALSE(d.received_data_before_response());
7568     EXPECT_EQ(0, d.bytes_received());
7569
7570     // Send no certificate.
7571     // TODO(davidben): Get temporary client cert import (with keys) working on
7572     // all platforms so we can test sending a cert as well.
7573     r->ContinueWithCertificate(NULL);
7574
7575     base::RunLoop().Run();
7576
7577     EXPECT_EQ(1, d.response_started_count());
7578     EXPECT_FALSE(d.received_data_before_response());
7579     EXPECT_NE(0, d.bytes_received());
7580   }
7581 }
7582
7583 TEST_F(HTTPSRequestTest, ResumeTest) {
7584   // Test that we attempt a session resume when making two connections to the
7585   // same host.
7586   SpawnedTestServer::SSLOptions ssl_options;
7587   ssl_options.record_resume = true;
7588   SpawnedTestServer test_server(
7589       SpawnedTestServer::TYPE_HTTPS,
7590       ssl_options,
7591       base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7592   ASSERT_TRUE(test_server.Start());
7593
7594   SSLClientSocket::ClearSessionCache();
7595
7596   {
7597     TestDelegate d;
7598     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7599         test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
7600
7601     r->Start();
7602     EXPECT_TRUE(r->is_pending());
7603
7604     base::RunLoop().Run();
7605
7606     EXPECT_EQ(1, d.response_started_count());
7607   }
7608
7609   reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7610     CloseAllConnections();
7611
7612   {
7613     TestDelegate d;
7614     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7615         test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
7616
7617     r->Start();
7618     EXPECT_TRUE(r->is_pending());
7619
7620     base::RunLoop().Run();
7621
7622     // The response will look like;
7623     //   insert abc
7624     //   lookup abc
7625     //   insert xyz
7626     //
7627     // With a newline at the end which makes the split think that there are
7628     // four lines.
7629
7630     EXPECT_EQ(1, d.response_started_count());
7631     std::vector<std::string> lines;
7632     base::SplitString(d.data_received(), '\n', &lines);
7633     ASSERT_EQ(4u, lines.size()) << d.data_received();
7634
7635     std::string session_id;
7636
7637     for (size_t i = 0; i < 2; i++) {
7638       std::vector<std::string> parts;
7639       base::SplitString(lines[i], '\t', &parts);
7640       ASSERT_EQ(2u, parts.size());
7641       if (i == 0) {
7642         EXPECT_EQ("insert", parts[0]);
7643         session_id = parts[1];
7644       } else {
7645         EXPECT_EQ("lookup", parts[0]);
7646         EXPECT_EQ(session_id, parts[1]);
7647       }
7648     }
7649   }
7650 }
7651
7652 // AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
7653 // the result of fetching "ssl-session-cache" from the test server, indicates
7654 // that exactly two different sessions were inserted, with no lookups etc.
7655 static void AssertTwoDistinctSessionsInserted(const string& session_info) {
7656   std::vector<std::string> lines;
7657   base::SplitString(session_info, '\n', &lines);
7658   ASSERT_EQ(3u, lines.size()) << session_info;
7659
7660   std::string session_id;
7661   for (size_t i = 0; i < 2; i++) {
7662     std::vector<std::string> parts;
7663     base::SplitString(lines[i], '\t', &parts);
7664     ASSERT_EQ(2u, parts.size());
7665     EXPECT_EQ("insert", parts[0]);
7666     if (i == 0) {
7667       session_id = parts[1];
7668     } else {
7669       EXPECT_NE(session_id, parts[1]);
7670     }
7671   }
7672 }
7673
7674 TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
7675   // Test that sessions aren't resumed when the value of ssl_session_cache_shard
7676   // differs.
7677   SpawnedTestServer::SSLOptions ssl_options;
7678   ssl_options.record_resume = true;
7679   SpawnedTestServer test_server(
7680       SpawnedTestServer::TYPE_HTTPS,
7681       ssl_options,
7682       base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7683   ASSERT_TRUE(test_server.Start());
7684
7685   SSLClientSocket::ClearSessionCache();
7686
7687   {
7688     TestDelegate d;
7689     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7690         test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
7691
7692     r->Start();
7693     EXPECT_TRUE(r->is_pending());
7694
7695     base::RunLoop().Run();
7696
7697     EXPECT_EQ(1, d.response_started_count());
7698   }
7699
7700   // Now create a new HttpCache with a different ssl_session_cache_shard value.
7701   HttpNetworkSession::Params params;
7702   params.host_resolver = default_context_.host_resolver();
7703   params.cert_verifier = default_context_.cert_verifier();
7704   params.transport_security_state = default_context_.transport_security_state();
7705   params.proxy_service = default_context_.proxy_service();
7706   params.ssl_config_service = default_context_.ssl_config_service();
7707   params.http_auth_handler_factory =
7708       default_context_.http_auth_handler_factory();
7709   params.network_delegate = &default_network_delegate_;
7710   params.http_server_properties = default_context_.http_server_properties();
7711   params.ssl_session_cache_shard = "alternate";
7712
7713   scoped_ptr<HttpCache> cache(new HttpCache(
7714       new HttpNetworkSession(params),
7715       HttpCache::DefaultBackend::InMemory(0)));
7716
7717   default_context_.set_http_transaction_factory(cache.get());
7718
7719   {
7720     TestDelegate d;
7721     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7722         test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
7723
7724     r->Start();
7725     EXPECT_TRUE(r->is_pending());
7726
7727     base::RunLoop().Run();
7728
7729     // The response will look like;
7730     //   insert abc
7731     //   insert xyz
7732     //
7733     // With a newline at the end which makes the split think that there are
7734     // three lines.
7735
7736     EXPECT_EQ(1, d.response_started_count());
7737     AssertTwoDistinctSessionsInserted(d.data_received());
7738   }
7739 }
7740
7741 #if defined(OS_WIN)
7742
7743 namespace {
7744
7745 bool IsECDSACipherSuite(uint16_t cipher_suite) {
7746   const char* key_exchange;
7747   const char* cipher;
7748   const char* mac;
7749   bool is_aead;
7750   SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
7751   return std::string(key_exchange).find("ECDSA") != std::string::npos;
7752 }
7753
7754 }  // namespace
7755
7756 // Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
7757 // verified.
7758 TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
7759   if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
7760     LOG(INFO) << "Skipping test on this version.";
7761     return;
7762   }
7763
7764   SpawnedTestServer test_server(
7765       SpawnedTestServer::TYPE_HTTPS,
7766       SpawnedTestServer::kLocalhost,
7767       base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7768   ASSERT_TRUE(test_server.Start());
7769
7770   TestDelegate d;
7771   scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7772       test_server.GetURL("client-cipher-list"), DEFAULT_PRIORITY, &d, NULL));
7773   r->Start();
7774   EXPECT_TRUE(r->is_pending());
7775
7776   base::RunLoop().Run();
7777
7778   EXPECT_EQ(1, d.response_started_count());
7779   std::vector<std::string> lines;
7780   base::SplitString(d.data_received(), '\n', &lines);
7781
7782   for (size_t i = 0; i < lines.size(); i++) {
7783     int cipher_suite;
7784     ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
7785     EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
7786         << "ClientHello advertised " << cipher_suite;
7787   }
7788 }
7789
7790 #endif  // OS_WIN
7791
7792 class TestSSLConfigService : public SSLConfigService {
7793  public:
7794   TestSSLConfigService(bool ev_enabled,
7795                        bool online_rev_checking,
7796                        bool rev_checking_required_local_anchors)
7797       : ev_enabled_(ev_enabled),
7798         online_rev_checking_(online_rev_checking),
7799         rev_checking_required_local_anchors_(
7800             rev_checking_required_local_anchors),
7801         min_version_(kDefaultSSLVersionMin),
7802         fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
7803
7804   void set_min_version(uint16 version) {
7805     min_version_ = version;
7806   }
7807
7808   void set_fallback_min_version(uint16 version) {
7809     fallback_min_version_ = version;
7810   }
7811
7812   // SSLConfigService:
7813   void GetSSLConfig(SSLConfig* config) override {
7814     *config = SSLConfig();
7815     config->rev_checking_enabled = online_rev_checking_;
7816     config->verify_ev_cert = ev_enabled_;
7817     config->rev_checking_required_local_anchors =
7818         rev_checking_required_local_anchors_;
7819     if (fallback_min_version_) {
7820       config->version_fallback_min = fallback_min_version_;
7821     }
7822     if (min_version_) {
7823       config->version_min = min_version_;
7824     }
7825   }
7826
7827  protected:
7828   ~TestSSLConfigService() override {}
7829
7830  private:
7831   const bool ev_enabled_;
7832   const bool online_rev_checking_;
7833   const bool rev_checking_required_local_anchors_;
7834   uint16 min_version_;
7835   uint16 fallback_min_version_;
7836 };
7837
7838 class FallbackTestURLRequestContext : public TestURLRequestContext {
7839  public:
7840   explicit FallbackTestURLRequestContext(bool delay_initialization)
7841       : TestURLRequestContext(delay_initialization) {}
7842
7843   void set_fallback_min_version(uint16 version) {
7844     TestSSLConfigService *ssl_config_service =
7845         new TestSSLConfigService(true /* check for EV */,
7846                                  false /* online revocation checking */,
7847                                  false /* require rev. checking for local
7848                                           anchors */);
7849     ssl_config_service->set_min_version(SSL_PROTOCOL_VERSION_SSL3);
7850     ssl_config_service->set_fallback_min_version(version);
7851     set_ssl_config_service(ssl_config_service);
7852   }
7853 };
7854
7855 class HTTPSFallbackTest : public testing::Test {
7856  public:
7857   HTTPSFallbackTest() : context_(true) {}
7858   ~HTTPSFallbackTest() override {}
7859
7860  protected:
7861   void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
7862     DCHECK(!request_);
7863     context_.Init();
7864     delegate_.set_allow_certificate_errors(true);
7865
7866     SpawnedTestServer test_server(
7867         SpawnedTestServer::TYPE_HTTPS,
7868         ssl_options,
7869         base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7870     ASSERT_TRUE(test_server.Start());
7871
7872     request_ = context_.CreateRequest(
7873         test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate_, NULL);
7874     request_->Start();
7875
7876     base::RunLoop().Run();
7877   }
7878
7879   void set_fallback_min_version(uint16 version) {
7880     context_.set_fallback_min_version(version);
7881   }
7882
7883   void ExpectConnection(int version) {
7884     EXPECT_EQ(1, delegate_.response_started_count());
7885     EXPECT_NE(0, delegate_.bytes_received());
7886     EXPECT_EQ(version, SSLConnectionStatusToVersion(
7887         request_->ssl_info().connection_status));
7888     EXPECT_TRUE(request_->ssl_info().connection_status &
7889                 SSL_CONNECTION_VERSION_FALLBACK);
7890   }
7891
7892   void ExpectFailure(int error) {
7893     EXPECT_EQ(1, delegate_.response_started_count());
7894     EXPECT_FALSE(request_->status().is_success());
7895     EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
7896     EXPECT_EQ(error, request_->status().error());
7897   }
7898
7899  private:
7900   TestDelegate delegate_;
7901   FallbackTestURLRequestContext context_;
7902   scoped_ptr<URLRequest> request_;
7903 };
7904
7905 // Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
7906 // than necessary.
7907 TEST_F(HTTPSFallbackTest, TLSv1Fallback) {
7908   SpawnedTestServer::SSLOptions ssl_options(
7909       SpawnedTestServer::SSLOptions::CERT_OK);
7910   ssl_options.tls_intolerant =
7911       SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7912
7913   ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7914   ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7915 }
7916
7917 // This test is disabled on Android because the remote test server doesn't cause
7918 // a TCP reset.
7919 #if !defined(OS_ANDROID)
7920 // Tests fallback to TLS 1.0 on connection reset.
7921 TEST_F(HTTPSFallbackTest, TLSv1FallbackReset) {
7922   SpawnedTestServer::SSLOptions ssl_options(
7923       SpawnedTestServer::SSLOptions::CERT_OK);
7924   ssl_options.tls_intolerant =
7925       SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7926   ssl_options.tls_intolerance_type =
7927       SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
7928
7929   ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7930   ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7931 }
7932 #endif  // !OS_ANDROID
7933
7934 // Tests that we don't fallback on handshake failure with servers that implement
7935 // TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
7936 TEST_F(HTTPSFallbackTest, FallbackSCSV) {
7937   SpawnedTestServer::SSLOptions ssl_options(
7938       SpawnedTestServer::SSLOptions::CERT_OK);
7939   // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
7940   // a version fallback.
7941   ssl_options.tls_intolerant =
7942       SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7943   // Have the server process TLS_FALLBACK_SCSV so that version fallback
7944   // connections are rejected.
7945   ssl_options.fallback_scsv_enabled = true;
7946
7947   ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7948
7949   // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
7950   // intolerance. If the fallback SCSV is processed when the original error
7951   // that caused the fallback should be returned, which should be
7952   // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
7953   ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
7954 }
7955
7956 // Tests that we don't fallback on connection closed with servers that implement
7957 // TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
7958 TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
7959   SpawnedTestServer::SSLOptions ssl_options(
7960       SpawnedTestServer::SSLOptions::CERT_OK);
7961   // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
7962   // a version fallback.
7963   ssl_options.tls_intolerant =
7964       SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7965   ssl_options.tls_intolerance_type =
7966       SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
7967   // Have the server process TLS_FALLBACK_SCSV so that version fallback
7968   // connections are rejected.
7969   ssl_options.fallback_scsv_enabled = true;
7970
7971   ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7972
7973   // The original error should be replayed on rejected fallback.
7974   ExpectFailure(ERR_CONNECTION_CLOSED);
7975 }
7976
7977 // Tests that the SSLv3 fallback doesn't happen by default.
7978 TEST_F(HTTPSFallbackTest, SSLv3Fallback) {
7979   SpawnedTestServer::SSLOptions ssl_options(
7980       SpawnedTestServer::SSLOptions::CERT_OK);
7981   ssl_options.tls_intolerant =
7982       SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7983
7984   ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7985   ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
7986 }
7987
7988 // Tests that the SSLv3 fallback works when explicitly enabled.
7989 TEST_F(HTTPSFallbackTest, SSLv3FallbackEnabled) {
7990   SpawnedTestServer::SSLOptions ssl_options(
7991       SpawnedTestServer::SSLOptions::CERT_OK);
7992   ssl_options.tls_intolerant =
7993       SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7994   set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
7995
7996   ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7997   ExpectConnection(SSL_CONNECTION_VERSION_SSL3);
7998 }
7999
8000 // Tests that the SSLv3 fallback triggers on closed connections when explicitly
8001 // enabled.
8002 TEST_F(HTTPSFallbackTest, SSLv3FallbackClosed) {
8003   SpawnedTestServer::SSLOptions ssl_options(
8004       SpawnedTestServer::SSLOptions::CERT_OK);
8005   ssl_options.tls_intolerant =
8006       SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
8007   ssl_options.tls_intolerance_type =
8008       SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8009   set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
8010
8011   ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8012   ExpectConnection(SSL_CONNECTION_VERSION_SSL3);
8013 }
8014
8015 // Test that SSLv3 fallback probe connections don't cause sessions to be cached.
8016 TEST_F(HTTPSRequestTest, SSLv3FallbackNoCache) {
8017   SpawnedTestServer::SSLOptions ssl_options(
8018       SpawnedTestServer::SSLOptions::CERT_OK);
8019   ssl_options.tls_intolerant =
8020       SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
8021   ssl_options.tls_intolerance_type =
8022       SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8023   ssl_options.record_resume = true;
8024
8025   SpawnedTestServer test_server(
8026       SpawnedTestServer::TYPE_HTTPS,
8027       ssl_options,
8028       base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8029   ASSERT_TRUE(test_server.Start());
8030
8031   SSLClientSocket::ClearSessionCache();
8032
8033   // Make a connection that does a probe fallback to SSLv3 but fails because
8034   // SSLv3 fallback is disabled. We don't wish a session for this connection to
8035   // be inserted locally.
8036   {
8037     TestDelegate delegate;
8038     FallbackTestURLRequestContext context(true);
8039
8040     context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
8041     context.Init();
8042     scoped_ptr<URLRequest> request(context.CreateRequest(
8043         test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate, NULL));
8044     request->Start();
8045
8046     base::RunLoop().Run();
8047
8048     EXPECT_EQ(1, delegate.response_started_count());
8049     EXPECT_FALSE(request->status().is_success());
8050     EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8051     EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8052               request->status().error());
8053   }
8054
8055   // Now allow SSLv3 connections and request the session cache log.
8056   {
8057     TestDelegate delegate;
8058     FallbackTestURLRequestContext context(true);
8059     context.set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
8060
8061     context.Init();
8062     scoped_ptr<URLRequest> request(
8063         context.CreateRequest(test_server.GetURL("ssl-session-cache"),
8064                                DEFAULT_PRIORITY,
8065                                &delegate,
8066                                NULL));
8067     request->Start();
8068
8069     base::RunLoop().Run();
8070
8071     EXPECT_EQ(1, delegate.response_started_count());
8072     EXPECT_NE(0, delegate.bytes_received());
8073     EXPECT_EQ(SSL_CONNECTION_VERSION_SSL3, SSLConnectionStatusToVersion(
8074         request->ssl_info().connection_status));
8075     EXPECT_TRUE(request->ssl_info().connection_status &
8076                 SSL_CONNECTION_VERSION_FALLBACK);
8077
8078     std::vector<std::string> lines;
8079     // If no sessions were cached then the server should have seen two sessions
8080     // inserted with no lookups.
8081     AssertTwoDistinctSessionsInserted(delegate.data_received());
8082   }
8083 }
8084
8085 // This test is disabled on Android because the remote test server doesn't cause
8086 // a TCP reset.
8087 #if !defined(OS_ANDROID)
8088 // Tests that a reset connection does not fallback down to SSL3.
8089 TEST_F(HTTPSFallbackTest, SSLv3NoFallbackReset) {
8090   SpawnedTestServer::SSLOptions ssl_options(
8091       SpawnedTestServer::SSLOptions::CERT_OK);
8092   ssl_options.tls_intolerant =
8093       SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
8094   ssl_options.tls_intolerance_type =
8095       SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
8096
8097   ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8098   ExpectFailure(ERR_CONNECTION_RESET);
8099 }
8100 #endif  // !OS_ANDROID
8101
8102 class HTTPSSessionTest : public testing::Test {
8103  public:
8104   HTTPSSessionTest() : default_context_(true) {
8105     cert_verifier_.set_default_result(OK);
8106
8107     default_context_.set_network_delegate(&default_network_delegate_);
8108     default_context_.set_cert_verifier(&cert_verifier_);
8109     default_context_.Init();
8110   }
8111   ~HTTPSSessionTest() override {}
8112
8113  protected:
8114   MockCertVerifier cert_verifier_;
8115   TestNetworkDelegate default_network_delegate_;  // Must outlive URLRequest.
8116   TestURLRequestContext default_context_;
8117 };
8118
8119 // Tests that session resumption is not attempted if an invalid certificate
8120 // is presented.
8121 TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8122   SpawnedTestServer::SSLOptions ssl_options;
8123   ssl_options.record_resume = true;
8124   SpawnedTestServer test_server(
8125       SpawnedTestServer::TYPE_HTTPS,
8126       ssl_options,
8127       base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8128   ASSERT_TRUE(test_server.Start());
8129
8130   SSLClientSocket::ClearSessionCache();
8131
8132   // Simulate the certificate being expired and attempt a connection.
8133   cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
8134   {
8135     TestDelegate d;
8136     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8137         test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
8138
8139     r->Start();
8140     EXPECT_TRUE(r->is_pending());
8141
8142     base::RunLoop().Run();
8143
8144     EXPECT_EQ(1, d.response_started_count());
8145   }
8146
8147   reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8148     CloseAllConnections();
8149
8150   // Now change the certificate to be acceptable (so that the response is
8151   // loaded), and ensure that no session id is presented to the peer.
8152   cert_verifier_.set_default_result(OK);
8153   {
8154     TestDelegate d;
8155     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8156         test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
8157
8158     r->Start();
8159     EXPECT_TRUE(r->is_pending());
8160
8161     base::RunLoop().Run();
8162
8163     // The response will look like;
8164     //   insert abc
8165     //   insert xyz
8166     //
8167     // With a newline at the end which makes the split think that there are
8168     // three lines.
8169     //
8170     // If a session was presented (eg: a bug), then the response would look
8171     // like;
8172     //   insert abc
8173     //   lookup abc
8174     //   insert xyz
8175
8176     EXPECT_EQ(1, d.response_started_count());
8177     AssertTwoDistinctSessionsInserted(d.data_received());
8178   }
8179 }
8180
8181 // This the fingerprint of the "Testing CA" certificate used by the testserver.
8182 // See net/data/ssl/certificates/ocsp-test-root.pem.
8183 static const SHA1HashValue kOCSPTestCertFingerprint =
8184   { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8185       0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8186
8187 // This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8188 // testserver.
8189 static const SHA256HashValue kOCSPTestCertSPKI = { {
8190   0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8191   0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8192   0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8193   0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8194 } };
8195
8196 // This is the policy OID contained in the certificates that testserver
8197 // generates.
8198 static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8199
8200 class HTTPSOCSPTest : public HTTPSRequestTest {
8201  public:
8202   HTTPSOCSPTest()
8203       : context_(true),
8204         ev_test_policy_(
8205             new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8206                                    kOCSPTestCertFingerprint,
8207                                    kOCSPTestCertPolicy)) {
8208   }
8209
8210   void SetUp() override {
8211     SetupContext(&context_);
8212     context_.Init();
8213
8214     scoped_refptr<X509Certificate> root_cert =
8215         ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
8216     CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
8217     test_root_.reset(new ScopedTestRoot(root_cert.get()));
8218
8219 #if defined(USE_NSS) || defined(OS_IOS)
8220     SetURLRequestContextForNSSHttpIO(&context_);
8221     EnsureNSSHttpIOInit();
8222 #endif
8223   }
8224
8225   void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
8226                     CertStatus* out_cert_status) {
8227     // We always overwrite out_cert_status.
8228     *out_cert_status = 0;
8229     SpawnedTestServer test_server(
8230         SpawnedTestServer::TYPE_HTTPS,
8231         ssl_options,
8232         base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8233     ASSERT_TRUE(test_server.Start());
8234
8235     TestDelegate d;
8236     d.set_allow_certificate_errors(true);
8237     scoped_ptr<URLRequest> r(context_.CreateRequest(
8238         test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
8239     r->Start();
8240
8241     base::RunLoop().Run();
8242
8243     EXPECT_EQ(1, d.response_started_count());
8244     *out_cert_status = r->ssl_info().cert_status;
8245   }
8246
8247   ~HTTPSOCSPTest() override {
8248 #if defined(USE_NSS) || defined(OS_IOS)
8249     ShutdownNSSHttpIO();
8250 #endif
8251   }
8252
8253  protected:
8254   // SetupContext configures the URLRequestContext that will be used for making
8255   // connetions to testserver. This can be overridden in test subclasses for
8256   // different behaviour.
8257   virtual void SetupContext(URLRequestContext* context) {
8258     context->set_ssl_config_service(
8259         new TestSSLConfigService(true /* check for EV */,
8260                                  true /* online revocation checking */,
8261                                  false /* require rev. checking for local
8262                                           anchors */));
8263   }
8264
8265   scoped_ptr<ScopedTestRoot> test_root_;
8266   TestURLRequestContext context_;
8267   scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
8268 };
8269
8270 static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
8271 #if defined(OS_WIN)
8272   // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8273   // have that ability on other platforms.
8274   return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8275 #else
8276   return 0;
8277 #endif
8278 }
8279
8280 // SystemSupportsHardFailRevocationChecking returns true iff the current
8281 // operating system supports revocation checking and can distinguish between
8282 // situations where a given certificate lacks any revocation information (eg:
8283 // no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8284 // revocation information cannot be obtained (eg: the CRL was unreachable).
8285 // If it does not, then tests which rely on 'hard fail' behaviour should be
8286 // skipped.
8287 static bool SystemSupportsHardFailRevocationChecking() {
8288 #if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
8289   return true;
8290 #else
8291   return false;
8292 #endif
8293 }
8294
8295 // SystemUsesChromiumEVMetadata returns true iff the current operating system
8296 // uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8297 // several tests are effected because our testing EV certificate won't be
8298 // recognised as EV.
8299 static bool SystemUsesChromiumEVMetadata() {
8300 #if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
8301   // http://crbug.com/117478 - OpenSSL does not support EV validation.
8302   return false;
8303 #elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8304   // On OS X and Android, we use the system to tell us whether a certificate is
8305   // EV or not and the system won't recognise our testing root.
8306   return false;
8307 #else
8308   return true;
8309 #endif
8310 }
8311
8312 static bool SystemSupportsOCSP() {
8313 #if defined(USE_OPENSSL)
8314   // http://crbug.com/117478 - OpenSSL does not support OCSP.
8315   return false;
8316 #elif defined(OS_WIN)
8317   return base::win::GetVersion() >= base::win::VERSION_VISTA;
8318 #elif defined(OS_ANDROID)
8319   // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8320   return false;
8321 #else
8322   return true;
8323 #endif
8324 }
8325
8326 TEST_F(HTTPSOCSPTest, Valid) {
8327   if (!SystemSupportsOCSP()) {
8328     LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8329     return;
8330   }
8331
8332   SpawnedTestServer::SSLOptions ssl_options(
8333       SpawnedTestServer::SSLOptions::CERT_AUTO);
8334   ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8335
8336   CertStatus cert_status;
8337   DoConnection(ssl_options, &cert_status);
8338
8339   EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8340
8341   EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8342             static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8343
8344   EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8345 }
8346
8347 TEST_F(HTTPSOCSPTest, Revoked) {
8348   if (!SystemSupportsOCSP()) {
8349     LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8350     return;
8351   }
8352
8353   SpawnedTestServer::SSLOptions ssl_options(
8354       SpawnedTestServer::SSLOptions::CERT_AUTO);
8355   ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8356
8357   CertStatus cert_status;
8358   DoConnection(ssl_options, &cert_status);
8359
8360 #if !(defined(OS_MACOSX) && !defined(OS_IOS))
8361   // Doesn't pass on OS X yet for reasons that need to be investigated.
8362   EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8363 #endif
8364   EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8365   EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8366 }
8367
8368 TEST_F(HTTPSOCSPTest, Invalid) {
8369   if (!SystemSupportsOCSP()) {
8370     LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8371     return;
8372   }
8373
8374   SpawnedTestServer::SSLOptions ssl_options(
8375       SpawnedTestServer::SSLOptions::CERT_AUTO);
8376   ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8377
8378   CertStatus cert_status;
8379   DoConnection(ssl_options, &cert_status);
8380
8381   EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8382             cert_status & CERT_STATUS_ALL_ERRORS);
8383
8384   // Without a positive OCSP response, we shouldn't show the EV status.
8385   EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8386   EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8387 }
8388
8389 class HTTPSHardFailTest : public HTTPSOCSPTest {
8390  protected:
8391   void SetupContext(URLRequestContext* context) override {
8392     context->set_ssl_config_service(
8393         new TestSSLConfigService(false /* check for EV */,
8394                                  false /* online revocation checking */,
8395                                  true /* require rev. checking for local
8396                                          anchors */));
8397   }
8398 };
8399
8400
8401 TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
8402   if (!SystemSupportsOCSP()) {
8403     LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8404     return;
8405   }
8406
8407   if (!SystemSupportsHardFailRevocationChecking()) {
8408     LOG(WARNING) << "Skipping test because system doesn't support hard fail "
8409                  << "revocation checking";
8410     return;
8411   }
8412
8413   SpawnedTestServer::SSLOptions ssl_options(
8414       SpawnedTestServer::SSLOptions::CERT_AUTO);
8415   ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8416
8417   CertStatus cert_status;
8418   DoConnection(ssl_options, &cert_status);
8419
8420   EXPECT_EQ(CERT_STATUS_REVOKED,
8421             cert_status & CERT_STATUS_REVOKED);
8422
8423   // Without a positive OCSP response, we shouldn't show the EV status.
8424   EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8425 }
8426
8427 class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
8428  protected:
8429   void SetupContext(URLRequestContext* context) override {
8430     context->set_ssl_config_service(
8431         new TestSSLConfigService(true /* check for EV */,
8432                                  false /* online revocation checking */,
8433                                  false /* require rev. checking for local
8434                                           anchors */));
8435   }
8436 };
8437
8438 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
8439   if (!SystemSupportsOCSP()) {
8440     LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8441     return;
8442   }
8443
8444   SpawnedTestServer::SSLOptions ssl_options(
8445       SpawnedTestServer::SSLOptions::CERT_AUTO);
8446   ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8447   SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8448
8449   CertStatus cert_status;
8450   DoConnection(ssl_options, &cert_status);
8451
8452   EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8453             cert_status & CERT_STATUS_ALL_ERRORS);
8454
8455   EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8456   EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8457             static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8458 }
8459
8460 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
8461   if (!SystemSupportsOCSP()) {
8462     LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8463     return;
8464   }
8465
8466   SpawnedTestServer::SSLOptions ssl_options(
8467       SpawnedTestServer::SSLOptions::CERT_AUTO);
8468   ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8469   SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8470
8471   CertStatus cert_status;
8472   DoConnection(ssl_options, &cert_status);
8473
8474   // Currently only works for Windows. When using NSS or OS X, it's not
8475   // possible to determine whether the check failed because of actual
8476   // revocation or because there was an OCSP failure.
8477 #if defined(OS_WIN)
8478   EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8479 #else
8480   EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8481 #endif
8482
8483   EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8484   EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8485             static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8486 }
8487
8488 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
8489   if (!SystemSupportsOCSP()) {
8490     LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8491     return;
8492   }
8493
8494   SpawnedTestServer::SSLOptions ssl_options(
8495       SpawnedTestServer::SSLOptions::CERT_AUTO);
8496   ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8497   SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8498
8499   CertStatus cert_status;
8500   DoConnection(ssl_options, &cert_status);
8501
8502   EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8503
8504   EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8505             static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8506   EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8507             static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8508 }
8509
8510 TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
8511   if (!SystemSupportsOCSP()) {
8512     LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8513     return;
8514   }
8515
8516   SpawnedTestServer::SSLOptions ssl_options(
8517       SpawnedTestServer::SSLOptions::CERT_AUTO);
8518   ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8519   SSLConfigService::SetCRLSet(
8520       scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8521
8522   CertStatus cert_status;
8523   DoConnection(ssl_options, &cert_status);
8524
8525   EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8526             cert_status & CERT_STATUS_ALL_ERRORS);
8527
8528   EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8529   EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8530             static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8531 }
8532
8533 TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
8534   if (!SystemSupportsOCSP()) {
8535     LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8536     return;
8537   }
8538
8539   SpawnedTestServer::SSLOptions ssl_options(
8540       SpawnedTestServer::SSLOptions::CERT_AUTO);
8541   ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8542   SSLConfigService::SetCRLSet(
8543       scoped_refptr<CRLSet>(CRLSet::ForTesting(
8544           false, &kOCSPTestCertSPKI, "")));
8545
8546   CertStatus cert_status;
8547   DoConnection(ssl_options, &cert_status);
8548
8549   // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
8550   // revocation check for EV.
8551   EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8552   EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8553             static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8554   EXPECT_FALSE(
8555       static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8556 }
8557
8558 TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
8559   if (!SystemSupportsOCSP()) {
8560     LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8561     return;
8562   }
8563
8564   SpawnedTestServer::SSLOptions ssl_options(
8565       SpawnedTestServer::SSLOptions::CERT_AUTO);
8566   ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8567   SSLConfigService::SetCRLSet(
8568       scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
8569
8570   CertStatus cert_status = 0;
8571   DoConnection(ssl_options, &cert_status);
8572
8573   // Even with a fresh CRLSet, we should still do online revocation checks when
8574   // the certificate chain isn't covered by the CRLSet, which it isn't in this
8575   // test.
8576   EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8577             cert_status & CERT_STATUS_ALL_ERRORS);
8578
8579   EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8580   EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8581             static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8582 }
8583
8584 TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
8585   // Test that when EV verification is requested, but online revocation
8586   // checking is disabled, and the leaf certificate is not in fact EV, that
8587   // no revocation checking actually happens.
8588   if (!SystemSupportsOCSP()) {
8589     LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8590     return;
8591   }
8592
8593   // Unmark the certificate's OID as EV, which should disable revocation
8594   // checking (as per the user preference)
8595   ev_test_policy_.reset();
8596
8597   SpawnedTestServer::SSLOptions ssl_options(
8598       SpawnedTestServer::SSLOptions::CERT_AUTO);
8599   ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8600   SSLConfigService::SetCRLSet(
8601       scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8602
8603   CertStatus cert_status;
8604   DoConnection(ssl_options, &cert_status);
8605
8606   EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8607
8608   EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8609   EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8610 }
8611
8612 class HTTPSCRLSetTest : public HTTPSOCSPTest {
8613  protected:
8614   void SetupContext(URLRequestContext* context) override {
8615     context->set_ssl_config_service(
8616         new TestSSLConfigService(false /* check for EV */,
8617                                  false /* online revocation checking */,
8618                                  false /* require rev. checking for local
8619                                           anchors */));
8620   }
8621 };
8622
8623 TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
8624   SpawnedTestServer::SSLOptions ssl_options(
8625       SpawnedTestServer::SSLOptions::CERT_AUTO);
8626   ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8627   SSLConfigService::SetCRLSet(
8628       scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8629
8630   CertStatus cert_status;
8631   DoConnection(ssl_options, &cert_status);
8632
8633   // If we're not trying EV verification then, even if the CRLSet has expired,
8634   // we don't fall back to online revocation checks.
8635   EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8636   EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8637   EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8638 }
8639
8640 TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
8641 #if defined(OS_ANDROID)
8642   LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
8643   return;
8644 #endif
8645
8646   SpawnedTestServer::SSLOptions ssl_options(
8647       SpawnedTestServer::SSLOptions::CERT_AUTO);
8648   ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8649   ssl_options.cert_serial = 10;
8650   SSLConfigService::SetCRLSet(
8651       scoped_refptr<CRLSet>(CRLSet::ForTesting(
8652           false, &kOCSPTestCertSPKI, "\x0a")));
8653
8654   CertStatus cert_status = 0;
8655   DoConnection(ssl_options, &cert_status);
8656
8657   // If the certificate is recorded as revoked in the CRLSet, that should be
8658   // reflected without online revocation checking.
8659   EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8660   EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8661   EXPECT_FALSE(
8662       static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8663 }
8664 #endif  // !defined(OS_IOS)
8665
8666 #if !defined(DISABLE_FTP_SUPPORT)
8667 class URLRequestTestFTP : public URLRequestTest {
8668  public:
8669   URLRequestTestFTP()
8670       : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
8671                      base::FilePath()) {
8672   }
8673
8674  protected:
8675   SpawnedTestServer test_server_;
8676 };
8677
8678 // Make sure an FTP request using an unsafe ports fails.
8679 TEST_F(URLRequestTestFTP, UnsafePort) {
8680   ASSERT_TRUE(test_server_.Start());
8681
8682   URLRequestJobFactoryImpl job_factory;
8683   FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
8684
8685   GURL url("ftp://127.0.0.1:7");
8686   job_factory.SetProtocolHandler(
8687       "ftp",
8688       new FtpProtocolHandler(&ftp_transaction_factory));
8689   default_context_.set_job_factory(&job_factory);
8690
8691   TestDelegate d;
8692   {
8693     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8694         url, DEFAULT_PRIORITY, &d, NULL));
8695     r->Start();
8696     EXPECT_TRUE(r->is_pending());
8697
8698     base::RunLoop().Run();
8699
8700     EXPECT_FALSE(r->is_pending());
8701     EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
8702     EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
8703   }
8704 }
8705
8706 // Flaky, see http://crbug.com/25045.
8707 TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
8708   ASSERT_TRUE(test_server_.Start());
8709
8710   TestDelegate d;
8711   {
8712     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8713         test_server_.GetURL("/"), DEFAULT_PRIORITY, &d, NULL));
8714     r->Start();
8715     EXPECT_TRUE(r->is_pending());
8716
8717     base::RunLoop().Run();
8718
8719     EXPECT_FALSE(r->is_pending());
8720     EXPECT_EQ(1, d.response_started_count());
8721     EXPECT_FALSE(d.received_data_before_response());
8722     EXPECT_LT(0, d.bytes_received());
8723     EXPECT_EQ(test_server_.host_port_pair().host(),
8724               r->GetSocketAddress().host());
8725     EXPECT_EQ(test_server_.host_port_pair().port(),
8726               r->GetSocketAddress().port());
8727   }
8728 }
8729
8730 // Flaky, see http://crbug.com/25045.
8731 TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
8732   ASSERT_TRUE(test_server_.Start());
8733
8734   base::FilePath app_path;
8735   PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8736   app_path = app_path.AppendASCII("LICENSE");
8737   TestDelegate d;
8738   {
8739     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8740         test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, &d, NULL));
8741     r->Start();
8742     EXPECT_TRUE(r->is_pending());
8743
8744     base::RunLoop().Run();
8745
8746     int64 file_size = 0;
8747     base::GetFileSize(app_path, &file_size);
8748
8749     EXPECT_FALSE(r->is_pending());
8750     EXPECT_EQ(1, d.response_started_count());
8751     EXPECT_FALSE(d.received_data_before_response());
8752     EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8753     EXPECT_EQ(test_server_.host_port_pair().host(),
8754               r->GetSocketAddress().host());
8755     EXPECT_EQ(test_server_.host_port_pair().port(),
8756               r->GetSocketAddress().port());
8757   }
8758 }
8759
8760 // Flaky, see http://crbug.com/25045.
8761 TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
8762   ASSERT_TRUE(test_server_.Start());
8763
8764   base::FilePath app_path;
8765   PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8766   app_path = app_path.AppendASCII("LICENSE");
8767   TestDelegate d;
8768   {
8769     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8770         test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
8771         DEFAULT_PRIORITY, &d, NULL));
8772     r->Start();
8773     EXPECT_TRUE(r->is_pending());
8774
8775     base::RunLoop().Run();
8776
8777     int64 file_size = 0;
8778     base::GetFileSize(app_path, &file_size);
8779
8780     EXPECT_FALSE(r->is_pending());
8781     EXPECT_EQ(test_server_.host_port_pair().host(),
8782               r->GetSocketAddress().host());
8783     EXPECT_EQ(test_server_.host_port_pair().port(),
8784               r->GetSocketAddress().port());
8785     EXPECT_EQ(1, d.response_started_count());
8786     EXPECT_FALSE(d.received_data_before_response());
8787     EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8788
8789     LoadTimingInfo load_timing_info;
8790     r->GetLoadTimingInfo(&load_timing_info);
8791     TestLoadTimingNoHttpResponse(load_timing_info);
8792   }
8793 }
8794
8795 // Flaky, see http://crbug.com/25045.
8796 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
8797   ASSERT_TRUE(test_server_.Start());
8798
8799   base::FilePath app_path;
8800   PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8801   app_path = app_path.AppendASCII("LICENSE");
8802   TestDelegate d;
8803   {
8804     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8805         test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8806                                                "wrong_password"),
8807         DEFAULT_PRIORITY, &d, NULL));
8808     r->Start();
8809     EXPECT_TRUE(r->is_pending());
8810
8811     base::RunLoop().Run();
8812
8813     int64 file_size = 0;
8814     base::GetFileSize(app_path, &file_size);
8815
8816     EXPECT_FALSE(r->is_pending());
8817     EXPECT_EQ(1, d.response_started_count());
8818     EXPECT_FALSE(d.received_data_before_response());
8819     EXPECT_EQ(d.bytes_received(), 0);
8820   }
8821 }
8822
8823 // Flaky, see http://crbug.com/25045.
8824 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
8825   ASSERT_TRUE(test_server_.Start());
8826
8827   base::FilePath app_path;
8828   PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8829   app_path = app_path.AppendASCII("LICENSE");
8830   TestDelegate d;
8831   // Set correct login credentials. The delegate will be asked for them when
8832   // the initial login with wrong credentials will fail.
8833   d.set_credentials(AuthCredentials(kChrome, kChrome));
8834   {
8835     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8836         test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8837                                                "wrong_password"),
8838         DEFAULT_PRIORITY, &d, NULL));
8839     r->Start();
8840     EXPECT_TRUE(r->is_pending());
8841
8842     base::RunLoop().Run();
8843
8844     int64 file_size = 0;
8845     base::GetFileSize(app_path, &file_size);
8846
8847     EXPECT_FALSE(r->is_pending());
8848     EXPECT_EQ(1, d.response_started_count());
8849     EXPECT_FALSE(d.received_data_before_response());
8850     EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8851   }
8852 }
8853
8854 // Flaky, see http://crbug.com/25045.
8855 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
8856   ASSERT_TRUE(test_server_.Start());
8857
8858   base::FilePath app_path;
8859   PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8860   app_path = app_path.AppendASCII("LICENSE");
8861   TestDelegate d;
8862   {
8863     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8864         test_server_.GetURLWithUserAndPassword("/LICENSE", "wrong_user",
8865                                                "chrome"),
8866         DEFAULT_PRIORITY, &d, NULL));
8867     r->Start();
8868     EXPECT_TRUE(r->is_pending());
8869
8870     base::RunLoop().Run();
8871
8872     int64 file_size = 0;
8873     base::GetFileSize(app_path, &file_size);
8874
8875     EXPECT_FALSE(r->is_pending());
8876     EXPECT_EQ(1, d.response_started_count());
8877     EXPECT_FALSE(d.received_data_before_response());
8878     EXPECT_EQ(d.bytes_received(), 0);
8879   }
8880 }
8881
8882 // Flaky, see http://crbug.com/25045.
8883 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
8884   ASSERT_TRUE(test_server_.Start());
8885
8886   base::FilePath app_path;
8887   PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8888   app_path = app_path.AppendASCII("LICENSE");
8889   TestDelegate d;
8890   // Set correct login credentials. The delegate will be asked for them when
8891   // the initial login with wrong credentials will fail.
8892   d.set_credentials(AuthCredentials(kChrome, kChrome));
8893   {
8894     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8895         test_server_.GetURLWithUserAndPassword("/LICENSE", "wrong_user",
8896                                                "chrome"),
8897         DEFAULT_PRIORITY, &d, NULL));
8898     r->Start();
8899     EXPECT_TRUE(r->is_pending());
8900
8901     base::RunLoop().Run();
8902
8903     int64 file_size = 0;
8904     base::GetFileSize(app_path, &file_size);
8905
8906     EXPECT_FALSE(r->is_pending());
8907     EXPECT_EQ(1, d.response_started_count());
8908     EXPECT_FALSE(d.received_data_before_response());
8909     EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8910   }
8911 }
8912
8913 // Flaky, see http://crbug.com/25045.
8914 TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
8915   ASSERT_TRUE(test_server_.Start());
8916
8917   base::FilePath app_path;
8918   PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8919   app_path = app_path.AppendASCII("LICENSE");
8920
8921   scoped_ptr<TestDelegate> d(new TestDelegate);
8922   {
8923     // Pass correct login identity in the URL.
8924     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8925         test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
8926         DEFAULT_PRIORITY, d.get(), NULL));
8927     r->Start();
8928     EXPECT_TRUE(r->is_pending());
8929
8930     base::RunLoop().Run();
8931
8932     int64 file_size = 0;
8933     base::GetFileSize(app_path, &file_size);
8934
8935     EXPECT_FALSE(r->is_pending());
8936     EXPECT_EQ(1, d->response_started_count());
8937     EXPECT_FALSE(d->received_data_before_response());
8938     EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8939   }
8940
8941   d.reset(new TestDelegate);
8942   {
8943     // This request should use cached identity from previous request.
8944     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8945         test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get(), NULL));
8946     r->Start();
8947     EXPECT_TRUE(r->is_pending());
8948
8949     base::RunLoop().Run();
8950
8951     int64 file_size = 0;
8952     base::GetFileSize(app_path, &file_size);
8953
8954     EXPECT_FALSE(r->is_pending());
8955     EXPECT_EQ(1, d->response_started_count());
8956     EXPECT_FALSE(d->received_data_before_response());
8957     EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8958   }
8959 }
8960
8961 // Flaky, see http://crbug.com/25045.
8962 TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
8963   ASSERT_TRUE(test_server_.Start());
8964
8965   base::FilePath app_path;
8966   PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8967   app_path = app_path.AppendASCII("LICENSE");
8968
8969   scoped_ptr<TestDelegate> d(new TestDelegate);
8970   // Set correct login credentials. The delegate will be asked for them when
8971   // the initial login with wrong credentials will fail.
8972   d->set_credentials(AuthCredentials(kChrome, kChrome));
8973   {
8974     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8975         test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8976                                                "wrong_password"),
8977         DEFAULT_PRIORITY, d.get(), NULL));
8978     r->Start();
8979     EXPECT_TRUE(r->is_pending());
8980
8981     base::RunLoop().Run();
8982
8983     int64 file_size = 0;
8984     base::GetFileSize(app_path, &file_size);
8985
8986     EXPECT_FALSE(r->is_pending());
8987     EXPECT_EQ(1, d->response_started_count());
8988     EXPECT_FALSE(d->received_data_before_response());
8989     EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8990   }
8991
8992   // Use a new delegate without explicit credentials. The cached ones should be
8993   // used.
8994   d.reset(new TestDelegate);
8995   {
8996     // Don't pass wrong credentials in the URL, they would override valid cached
8997     // ones.
8998     scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8999         test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get(), NULL));
9000     r->Start();
9001     EXPECT_TRUE(r->is_pending());
9002
9003     base::RunLoop().Run();
9004
9005     int64 file_size = 0;
9006     base::GetFileSize(app_path, &file_size);
9007
9008     EXPECT_FALSE(r->is_pending());
9009     EXPECT_EQ(1, d->response_started_count());
9010     EXPECT_FALSE(d->received_data_before_response());
9011     EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
9012   }
9013 }
9014 #endif  // !defined(DISABLE_FTP_SUPPORT)
9015
9016 }  // namespace net