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