1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "build/build_config.h"
6
7#if defined(OS_WIN)
8#include <windows.h>
9#include <shlobj.h>
10#endif
11
12#include <algorithm>
13#include <string>
14
15#include "base/basictypes.h"
16#include "base/bind.h"
17#include "base/compiler_specific.h"
18#include "base/files/file_util.h"
19#include "base/files/scoped_temp_dir.h"
20#include "base/format_macros.h"
21#include "base/memory/scoped_ptr.h"
22#include "base/memory/weak_ptr.h"
23#include "base/message_loop/message_loop.h"
24#include "base/message_loop/message_loop_proxy.h"
25#include "base/path_service.h"
26#include "base/run_loop.h"
27#include "base/strings/string_number_conversions.h"
28#include "base/strings/string_piece.h"
29#include "base/strings/string_split.h"
30#include "base/strings/string_util.h"
31#include "base/strings/stringprintf.h"
32#include "base/strings/utf_string_conversions.h"
33#include "net/base/capturing_net_log.h"
34#include "net/base/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_cipher_suite_names.h"
66#include "net/ssl/ssl_connection_status_flags.h"
67#include "net/test/cert_test_util.h"
68#include "net/test/spawned_test_server/spawned_test_server.h"
69#include "net/url_request/data_protocol_handler.h"
70#include "net/url_request/static_http_user_agent_settings.h"
71#include "net/url_request/url_request.h"
72#include "net/url_request/url_request_http_job.h"
73#include "net/url_request/url_request_job_factory_impl.h"
74#include "net/url_request/url_request_redirect_job.h"
75#include "net/url_request/url_request_test_job.h"
76#include "net/url_request/url_request_test_util.h"
77#include "testing/gtest/include/gtest/gtest.h"
78#include "testing/platform_test.h"
79
80#if !defined(DISABLE_FILE_SUPPORT)
81#include "net/base/filename_util.h"
82#include "net/url_request/file_protocol_handler.h"
83#include "net/url_request/url_request_file_dir_job.h"
84#endif
85
86#if !defined(DISABLE_FTP_SUPPORT)
87#include "net/url_request/ftp_protocol_handler.h"
88#endif
89
90#if defined(OS_WIN)
91#include "base/win/scoped_com_initializer.h"
92#include "base/win/scoped_comptr.h"
93#include "base/win/windows_version.h"
94#endif
95
96using base::ASCIIToUTF16;
97using base::Time;
98
99namespace net {
100
101namespace {
102
103const base::string16 kChrome(ASCIIToUTF16("chrome"));
104const base::string16 kSecret(ASCIIToUTF16("secret"));
105const base::string16 kUser(ASCIIToUTF16("user"));
106
107// Tests load timing information in the case a fresh connection was used, with
108// no proxy.
109void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
110                             int connect_timing_flags) {
111  EXPECT_FALSE(load_timing_info.socket_reused);
112  EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
113
114  EXPECT_FALSE(load_timing_info.request_start_time.is_null());
115  EXPECT_FALSE(load_timing_info.request_start.is_null());
116
117  EXPECT_LE(load_timing_info.request_start,
118            load_timing_info.connect_timing.connect_start);
119  ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
120                              connect_timing_flags);
121  EXPECT_LE(load_timing_info.connect_timing.connect_end,
122            load_timing_info.send_start);
123  EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
124  EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
125
126  EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
127  EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
128}
129
130// Same as above, but with proxy times.
131void TestLoadTimingNotReusedWithProxy(
132    const LoadTimingInfo& load_timing_info,
133    int connect_timing_flags) {
134  EXPECT_FALSE(load_timing_info.socket_reused);
135  EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
136
137  EXPECT_FALSE(load_timing_info.request_start_time.is_null());
138  EXPECT_FALSE(load_timing_info.request_start.is_null());
139
140  EXPECT_LE(load_timing_info.request_start,
141            load_timing_info.proxy_resolve_start);
142  EXPECT_LE(load_timing_info.proxy_resolve_start,
143            load_timing_info.proxy_resolve_end);
144  EXPECT_LE(load_timing_info.proxy_resolve_end,
145            load_timing_info.connect_timing.connect_start);
146  ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
147                              connect_timing_flags);
148  EXPECT_LE(load_timing_info.connect_timing.connect_end,
149            load_timing_info.send_start);
150  EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
151  EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
152}
153
154// Same as above, but with a reused socket and proxy times.
155void TestLoadTimingReusedWithProxy(
156    const LoadTimingInfo& load_timing_info) {
157  EXPECT_TRUE(load_timing_info.socket_reused);
158  EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
159
160  EXPECT_FALSE(load_timing_info.request_start_time.is_null());
161  EXPECT_FALSE(load_timing_info.request_start.is_null());
162
163  ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
164
165  EXPECT_LE(load_timing_info.request_start,
166            load_timing_info.proxy_resolve_start);
167  EXPECT_LE(load_timing_info.proxy_resolve_start,
168            load_timing_info.proxy_resolve_end);
169  EXPECT_LE(load_timing_info.proxy_resolve_end,
170            load_timing_info.send_start);
171  EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
172  EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
173}
174
175// Tests load timing information in the case of a cache hit, when no cache
176// validation request was sent over the wire.
177base::StringPiece TestNetResourceProvider(int key) {
178  return "header";
179}
180
181void FillBuffer(char* buffer, size_t len) {
182  static bool called = false;
183  if (!called) {
184    called = true;
185    int seed = static_cast<int>(Time::Now().ToInternalValue());
186    srand(seed);
187  }
188
189  for (size_t i = 0; i < len; i++) {
190    buffer[i] = static_cast<char>(rand());
191    if (!buffer[i])
192      buffer[i] = 'g';
193  }
194}
195
196#if !defined(OS_IOS)
197void TestLoadTimingCacheHitNoNetwork(
198    const LoadTimingInfo& load_timing_info) {
199  EXPECT_FALSE(load_timing_info.socket_reused);
200  EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
201
202  EXPECT_FALSE(load_timing_info.request_start_time.is_null());
203  EXPECT_FALSE(load_timing_info.request_start.is_null());
204
205  ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
206  EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
207  EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
208  EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
209
210  EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
211  EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
212}
213
214// Tests load timing in the case that there is no HTTP response.  This can be
215// used to test in the case of errors or non-HTTP requests.
216void TestLoadTimingNoHttpResponse(
217    const LoadTimingInfo& load_timing_info) {
218  EXPECT_FALSE(load_timing_info.socket_reused);
219  EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
220
221  // Only the request times should be non-null.
222  EXPECT_FALSE(load_timing_info.request_start_time.is_null());
223  EXPECT_FALSE(load_timing_info.request_start.is_null());
224
225  ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
226
227  EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
228  EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
229  EXPECT_TRUE(load_timing_info.send_start.is_null());
230  EXPECT_TRUE(load_timing_info.send_end.is_null());
231  EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
232}
233
234// Do a case-insensitive search through |haystack| for |needle|.
235bool ContainsString(const std::string& haystack, const char* needle) {
236  std::string::const_iterator it =
237      std::search(haystack.begin(),
238                  haystack.end(),
239                  needle,
240                  needle + strlen(needle),
241                  base::CaseInsensitiveCompare<char>());
242  return it != haystack.end();
243}
244
245UploadDataStream* CreateSimpleUploadData(const char* data) {
246  scoped_ptr<UploadElementReader> reader(
247      new UploadBytesElementReader(data, strlen(data)));
248  return UploadDataStream::CreateWithReader(reader.Pass(), 0);
249}
250
251// Verify that the SSLInfo of a successful SSL connection has valid values.
252void CheckSSLInfo(const SSLInfo& ssl_info) {
253  // -1 means unknown.  0 means no encryption.
254  EXPECT_GT(ssl_info.security_bits, 0);
255
256  // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
257  int cipher_suite = SSLConnectionStatusToCipherSuite(
258      ssl_info.connection_status);
259  EXPECT_NE(0, cipher_suite);
260}
261
262void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
263                             const GURL& host_url) {
264  std::string sent_value;
265
266  EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
267  EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
268
269  EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
270  EXPECT_EQ("keep-alive", sent_value);
271}
272
273bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
274  size_t size = a.size();
275
276  if (size != b.size())
277    return false;
278
279  for (size_t i = 0; i < size; ++i) {
280    if (!a[i].Equals(b[i]))
281      return false;
282  }
283
284  return true;
285}
286#endif  // !defined(OS_IOS)
287
288// A network delegate that allows the user to choose a subset of request stages
289// to block in. When blocking, the delegate can do one of the following:
290//  * synchronously return a pre-specified error code, or
291//  * asynchronously return that value via an automatically called callback,
292//    or
293//  * block and wait for the user to do a callback.
294// Additionally, the user may also specify a redirect URL -- then each request
295// with the current URL different from the redirect target will be redirected
296// to that target, in the on-before-URL-request stage, independent of whether
297// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
298class BlockingNetworkDelegate : public TestNetworkDelegate {
299 public:
300  // Stages in which the delegate can block.
301  enum Stage {
302    NOT_BLOCKED = 0,
303    ON_BEFORE_URL_REQUEST = 1 << 0,
304    ON_BEFORE_SEND_HEADERS = 1 << 1,
305    ON_HEADERS_RECEIVED = 1 << 2,
306    ON_AUTH_REQUIRED = 1 << 3
307  };
308
309  // Behavior during blocked stages.  During other stages, just
310  // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
311  enum BlockMode {
312    SYNCHRONOUS,    // No callback, returns specified return values.
313    AUTO_CALLBACK,  // |this| posts a task to run the callback using the
314                    // specified return codes.
315    USER_CALLBACK,  // User takes care of doing a callback.  |retval_| and
316                    // |auth_retval_| are ignored. In every blocking stage the
317                    // message loop is quit.
318  };
319
320  // Creates a delegate which does not block at all.
321  explicit BlockingNetworkDelegate(BlockMode block_mode);
322
323  // For users to trigger a callback returning |response|.
324  // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
325  // Only call if |block_mode_| == USER_CALLBACK.
326  void DoCallback(int response);
327  void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
328
329  // Setters.
330  void set_retval(int retval) {
331    ASSERT_NE(USER_CALLBACK, block_mode_);
332    ASSERT_NE(ERR_IO_PENDING, retval);
333    ASSERT_NE(OK, retval);
334    retval_ = retval;
335  }
336
337  // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
338  // |auth_credentials_| will be passed with the response.
339  void set_auth_retval(AuthRequiredResponse auth_retval) {
340    ASSERT_NE(USER_CALLBACK, block_mode_);
341    ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
342    auth_retval_ = auth_retval;
343  }
344  void set_auth_credentials(const AuthCredentials& auth_credentials) {
345    auth_credentials_ = auth_credentials;
346  }
347
348  void set_redirect_url(const GURL& url) {
349    redirect_url_ = url;
350  }
351
352  void set_block_on(int block_on) {
353    block_on_ = block_on;
354  }
355
356  // Allows the user to check in which state did we block.
357  Stage stage_blocked_for_callback() const {
358    EXPECT_EQ(USER_CALLBACK, block_mode_);
359    return stage_blocked_for_callback_;
360  }
361
362 private:
363  void RunCallback(int response, const CompletionCallback& callback);
364  void RunAuthCallback(AuthRequiredResponse response,
365                       const AuthCallback& callback);
366
367  // TestNetworkDelegate implementation.
368  virtual int OnBeforeURLRequest(URLRequest* request,
369                                 const CompletionCallback& callback,
370                                 GURL* new_url) OVERRIDE;
371
372  virtual int OnBeforeSendHeaders(URLRequest* request,
373                                  const CompletionCallback& callback,
374                                  HttpRequestHeaders* headers) OVERRIDE;
375
376  virtual int OnHeadersReceived(
377      URLRequest* request,
378      const CompletionCallback& callback,
379      const HttpResponseHeaders* original_response_headers,
380      scoped_refptr<HttpResponseHeaders>* override_response_headers,
381      GURL* allowed_unsafe_redirect_url) OVERRIDE;
382
383  virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
384      URLRequest* request,
385      const AuthChallengeInfo& auth_info,
386      const AuthCallback& callback,
387      AuthCredentials* credentials) OVERRIDE;
388
389  // Resets the callbacks and |stage_blocked_for_callback_|.
390  void Reset();
391
392  // Checks whether we should block in |stage|. If yes, returns an error code
393  // and optionally sets up callback based on |block_mode_|. If no, returns OK.
394  int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
395
396  // Configuration parameters, can be adjusted by public methods:
397  const BlockMode block_mode_;
398
399  // Values returned on blocking stages when mode is SYNCHRONOUS or
400  // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
401  int retval_;  // To be returned in non-auth stages.
402  AuthRequiredResponse auth_retval_;
403
404  GURL redirect_url_;  // Used if non-empty during OnBeforeURLRequest.
405  int block_on_;  // Bit mask: in which stages to block.
406
407  // |auth_credentials_| will be copied to |*target_auth_credential_| on
408  // callback.
409  AuthCredentials auth_credentials_;
410  AuthCredentials* target_auth_credentials_;
411
412  // Internal variables, not set by not the user:
413  // Last blocked stage waiting for user callback (unused if |block_mode_| !=
414  // USER_CALLBACK).
415  Stage stage_blocked_for_callback_;
416
417  // Callback objects stored during blocking stages.
418  CompletionCallback callback_;
419  AuthCallback auth_callback_;
420
421  base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
422
423  DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
424};
425
426BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
427    : block_mode_(block_mode),
428      retval_(OK),
429      auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
430      block_on_(0),
431      target_auth_credentials_(NULL),
432      stage_blocked_for_callback_(NOT_BLOCKED),
433      weak_factory_(this) {
434}
435
436void BlockingNetworkDelegate::DoCallback(int response) {
437  ASSERT_EQ(USER_CALLBACK, block_mode_);
438  ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
439  ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
440  CompletionCallback callback = callback_;
441  Reset();
442  RunCallback(response, callback);
443}
444
445void BlockingNetworkDelegate::DoAuthCallback(
446    NetworkDelegate::AuthRequiredResponse response) {
447  ASSERT_EQ(USER_CALLBACK, block_mode_);
448  ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
449  AuthCallback auth_callback = auth_callback_;
450  Reset();
451  RunAuthCallback(response, auth_callback);
452}
453
454void BlockingNetworkDelegate::RunCallback(int response,
455                                          const CompletionCallback& callback) {
456  callback.Run(response);
457}
458
459void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
460                                              const AuthCallback& callback) {
461  if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
462    ASSERT_TRUE(target_auth_credentials_ != NULL);
463    *target_auth_credentials_ = auth_credentials_;
464  }
465  callback.Run(response);
466}
467
468int BlockingNetworkDelegate::OnBeforeURLRequest(
469    URLRequest* request,
470    const CompletionCallback& callback,
471    GURL* new_url) {
472  if (redirect_url_ == request->url())
473    return OK;  // We've already seen this request and redirected elsewhere.
474
475  TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
476
477  if (!redirect_url_.is_empty())
478    *new_url = redirect_url_;
479
480  return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
481}
482
483int BlockingNetworkDelegate::OnBeforeSendHeaders(
484    URLRequest* request,
485    const CompletionCallback& callback,
486    HttpRequestHeaders* headers) {
487  TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
488
489  return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
490}
491
492int BlockingNetworkDelegate::OnHeadersReceived(
493    URLRequest* request,
494    const CompletionCallback& callback,
495    const HttpResponseHeaders* original_response_headers,
496    scoped_refptr<HttpResponseHeaders>* override_response_headers,
497    GURL* allowed_unsafe_redirect_url) {
498  TestNetworkDelegate::OnHeadersReceived(request,
499                                         callback,
500                                         original_response_headers,
501                                         override_response_headers,
502                                         allowed_unsafe_redirect_url);
503
504  return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
505}
506
507NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
508    URLRequest* request,
509    const AuthChallengeInfo& auth_info,
510    const AuthCallback& callback,
511    AuthCredentials* credentials) {
512  TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
513                                      credentials);
514  // Check that the user has provided callback for the previous blocked stage.
515  EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
516
517  if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
518    return AUTH_REQUIRED_RESPONSE_NO_ACTION;
519  }
520
521  target_auth_credentials_ = credentials;
522
523  switch (block_mode_) {
524    case SYNCHRONOUS:
525      if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
526        *target_auth_credentials_ = auth_credentials_;
527      return auth_retval_;
528
529    case AUTO_CALLBACK:
530      base::MessageLoop::current()->PostTask(
531          FROM_HERE,
532          base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
533                     weak_factory_.GetWeakPtr(), auth_retval_, callback));
534      return AUTH_REQUIRED_RESPONSE_IO_PENDING;
535
536    case USER_CALLBACK:
537      auth_callback_ = callback;
538      stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
539      base::MessageLoop::current()->PostTask(FROM_HERE,
540                                             base::MessageLoop::QuitClosure());
541      return AUTH_REQUIRED_RESPONSE_IO_PENDING;
542  }
543  NOTREACHED();
544  return AUTH_REQUIRED_RESPONSE_NO_ACTION;  // Dummy value.
545}
546
547void BlockingNetworkDelegate::Reset() {
548  EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
549  stage_blocked_for_callback_ = NOT_BLOCKED;
550  callback_.Reset();
551  auth_callback_.Reset();
552}
553
554int BlockingNetworkDelegate::MaybeBlockStage(
555    BlockingNetworkDelegate::Stage stage,
556    const CompletionCallback& callback) {
557  // Check that the user has provided callback for the previous blocked stage.
558  EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
559
560  if ((block_on_ & stage) == 0) {
561    return OK;
562  }
563
564  switch (block_mode_) {
565    case SYNCHRONOUS:
566      EXPECT_NE(OK, retval_);
567      return retval_;
568
569    case AUTO_CALLBACK:
570      base::MessageLoop::current()->PostTask(
571          FROM_HERE,
572          base::Bind(&BlockingNetworkDelegate::RunCallback,
573                     weak_factory_.GetWeakPtr(), retval_, callback));
574      return ERR_IO_PENDING;
575
576    case USER_CALLBACK:
577      callback_ = callback;
578      stage_blocked_for_callback_ = stage;
579      base::MessageLoop::current()->PostTask(FROM_HERE,
580                                             base::MessageLoop::QuitClosure());
581      return ERR_IO_PENDING;
582  }
583  NOTREACHED();
584  return 0;
585}
586
587class TestURLRequestContextWithProxy : public TestURLRequestContext {
588 public:
589  // Does not own |delegate|.
590  TestURLRequestContextWithProxy(const std::string& proxy,
591                                 NetworkDelegate* delegate)
592      : TestURLRequestContext(true) {
593    context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
594    set_network_delegate(delegate);
595    Init();
596  }
597  virtual ~TestURLRequestContextWithProxy() {}
598};
599
600}  // namespace
601
602// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
603class URLRequestTest : public PlatformTest {
604 public:
605  URLRequestTest() : default_context_(true) {
606    default_context_.set_network_delegate(&default_network_delegate_);
607    default_context_.set_net_log(&net_log_);
608    job_factory_.SetProtocolHandler("data", new DataProtocolHandler);
609#if !defined(DISABLE_FILE_SUPPORT)
610    job_factory_.SetProtocolHandler(
611        "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
612#endif
613    default_context_.set_job_factory(&job_factory_);
614    default_context_.Init();
615  }
616  virtual ~URLRequestTest() {
617    // URLRequestJobs may post clean-up tasks on destruction.
618    base::RunLoop().RunUntilIdle();
619  }
620
621  // Adds the TestJobInterceptor to the default context.
622  TestJobInterceptor* AddTestInterceptor() {
623    TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
624    job_factory_.SetProtocolHandler("http", NULL);
625    job_factory_.SetProtocolHandler("http", protocol_handler_);
626    return protocol_handler_;
627  }
628
629 protected:
630  CapturingNetLog net_log_;
631  TestNetworkDelegate default_network_delegate_;  // Must outlive URLRequest.
632  URLRequestJobFactoryImpl job_factory_;
633  TestURLRequestContext default_context_;
634};
635
636TEST_F(URLRequestTest, AboutBlankTest) {
637  TestDelegate d;
638  {
639    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
640        GURL("about:blank"), DEFAULT_PRIORITY, &d, NULL));
641
642    r->Start();
643    EXPECT_TRUE(r->is_pending());
644
645    base::RunLoop().Run();
646
647    EXPECT_TRUE(!r->is_pending());
648    EXPECT_FALSE(d.received_data_before_response());
649    EXPECT_EQ(d.bytes_received(), 0);
650    EXPECT_EQ("", r->GetSocketAddress().host());
651    EXPECT_EQ(0, r->GetSocketAddress().port());
652
653    HttpRequestHeaders headers;
654    EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
655  }
656}
657
658TEST_F(URLRequestTest, DataURLImageTest) {
659  TestDelegate d;
660  {
661    // Use our nice little Chrome logo.
662    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
663        GURL(
664        "data:image/png;base64,"
665        "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUBBjG3"
666        "w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQxIEVxitD"
667        "5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI5MpCVdW0gO7t"
668        "vNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKzMx1+fg9bAgK6zHq9"
669        "cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7CkIMDxQpF7r/MWq12UctI1"
670        "dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0WYUqt57yWf2McHTObYPbVD+Z"
671        "wbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2HQQcm43XwmtoYM6vVKleh0uoWvnzW"
672        "3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nkDFHF9ZS+uYVjRUasMeHUmyLYtcklTvzW"
673        "GFZnNOXczThvpKIzjcahSqIzkvDLayDq6D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTb"
674        "xXX1T5xsV9tm9r4TQwHLiZw/pdDZJea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5"
675        "MrVvMzNaI3+ERHfrFzPKQukrQGI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gV"
676        "Md6q5c8GdosynKmSeRuGzpjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq"
677        "/uxxZKzNiZFGD0wRC3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7F"
678        "Ux1qLnV7MGF40smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufB"
679        "JbsysjjW4kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJM"
680        "nlm2O34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfm"
681        "moRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV5En"
682        "hORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
683        DEFAULT_PRIORITY, &d, NULL));
684
685    r->Start();
686    EXPECT_TRUE(r->is_pending());
687
688    base::RunLoop().Run();
689
690    EXPECT_TRUE(!r->is_pending());
691    EXPECT_FALSE(d.received_data_before_response());
692    EXPECT_EQ(d.bytes_received(), 911);
693    EXPECT_EQ("", r->GetSocketAddress().host());
694    EXPECT_EQ(0, r->GetSocketAddress().port());
695
696    HttpRequestHeaders headers;
697    EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
698  }
699}
700
701#if !defined(DISABLE_FILE_SUPPORT)
702TEST_F(URLRequestTest, FileTest) {
703  base::FilePath app_path;
704  PathService::Get(base::FILE_EXE, &app_path);
705  GURL app_url = FilePathToFileURL(app_path);
706
707  TestDelegate d;
708  {
709    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
710        app_url, DEFAULT_PRIORITY, &d, NULL));
711
712    r->Start();
713    EXPECT_TRUE(r->is_pending());
714
715    base::RunLoop().Run();
716
717    int64 file_size = -1;
718    EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
719
720    EXPECT_TRUE(!r->is_pending());
721    EXPECT_EQ(1, d.response_started_count());
722    EXPECT_FALSE(d.received_data_before_response());
723    EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
724    EXPECT_EQ("", r->GetSocketAddress().host());
725    EXPECT_EQ(0, r->GetSocketAddress().port());
726
727    HttpRequestHeaders headers;
728    EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
729  }
730}
731
732TEST_F(URLRequestTest, FileTestCancel) {
733  base::FilePath app_path;
734  PathService::Get(base::FILE_EXE, &app_path);
735  GURL app_url = FilePathToFileURL(app_path);
736
737  TestDelegate d;
738  {
739    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
740        app_url, DEFAULT_PRIORITY, &d, NULL));
741
742    r->Start();
743    EXPECT_TRUE(r->is_pending());
744    r->Cancel();
745  }
746  // Async cancellation should be safe even when URLRequest has been already
747  // destroyed.
748  base::RunLoop().RunUntilIdle();
749}
750
751TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
752  const size_t buffer_size = 4000;
753  scoped_ptr<char[]> buffer(new char[buffer_size]);
754  FillBuffer(buffer.get(), buffer_size);
755
756  base::FilePath temp_path;
757  EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
758  GURL temp_url = FilePathToFileURL(temp_path);
759  EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
760
761  int64 file_size;
762  EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
763
764  const size_t first_byte_position = 500;
765  const size_t last_byte_position = buffer_size - first_byte_position;
766  const size_t content_length = last_byte_position - first_byte_position + 1;
767  std::string partial_buffer_string(buffer.get() + first_byte_position,
768                                    buffer.get() + last_byte_position + 1);
769
770  TestDelegate d;
771  {
772    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
773        temp_url, DEFAULT_PRIORITY, &d, NULL));
774
775    HttpRequestHeaders headers;
776    headers.SetHeader(
777        HttpRequestHeaders::kRange,
778        HttpByteRange::Bounded(
779            first_byte_position, last_byte_position).GetHeaderValue());
780    r->SetExtraRequestHeaders(headers);
781    r->Start();
782    EXPECT_TRUE(r->is_pending());
783
784    base::RunLoop().Run();
785    EXPECT_TRUE(!r->is_pending());
786    EXPECT_EQ(1, d.response_started_count());
787    EXPECT_FALSE(d.received_data_before_response());
788    EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
789    // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
790    EXPECT_TRUE(partial_buffer_string == d.data_received());
791  }
792
793  EXPECT_TRUE(base::DeleteFile(temp_path, false));
794}
795
796TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
797  const size_t buffer_size = 4000;
798  scoped_ptr<char[]> buffer(new char[buffer_size]);
799  FillBuffer(buffer.get(), buffer_size);
800
801  base::FilePath temp_path;
802  EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
803  GURL temp_url = FilePathToFileURL(temp_path);
804  EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
805
806  int64 file_size;
807  EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
808
809  const size_t first_byte_position = 500;
810  const size_t last_byte_position = buffer_size - 1;
811  const size_t content_length = last_byte_position - first_byte_position + 1;
812  std::string partial_buffer_string(buffer.get() + first_byte_position,
813                                    buffer.get() + last_byte_position + 1);
814
815  TestDelegate d;
816  {
817    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
818        temp_url, DEFAULT_PRIORITY, &d, NULL));
819
820    HttpRequestHeaders headers;
821    headers.SetHeader(HttpRequestHeaders::kRange,
822                      HttpByteRange::RightUnbounded(
823                          first_byte_position).GetHeaderValue());
824    r->SetExtraRequestHeaders(headers);
825    r->Start();
826    EXPECT_TRUE(r->is_pending());
827
828    base::RunLoop().Run();
829    EXPECT_TRUE(!r->is_pending());
830    EXPECT_EQ(1, d.response_started_count());
831    EXPECT_FALSE(d.received_data_before_response());
832    EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
833    // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
834    EXPECT_TRUE(partial_buffer_string == d.data_received());
835  }
836
837  EXPECT_TRUE(base::DeleteFile(temp_path, false));
838}
839
840TEST_F(URLRequestTest, FileTestMultipleRanges) {
841  const size_t buffer_size = 400000;
842  scoped_ptr<char[]> buffer(new char[buffer_size]);
843  FillBuffer(buffer.get(), buffer_size);
844
845  base::FilePath temp_path;
846  EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
847  GURL temp_url = FilePathToFileURL(temp_path);
848  EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
849
850  int64 file_size;
851  EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
852
853  TestDelegate d;
854  {
855    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
856        temp_url, DEFAULT_PRIORITY, &d, NULL));
857
858    HttpRequestHeaders headers;
859    headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
860    r->SetExtraRequestHeaders(headers);
861    r->Start();
862    EXPECT_TRUE(r->is_pending());
863
864    base::RunLoop().Run();
865    EXPECT_TRUE(d.request_failed());
866  }
867
868  EXPECT_TRUE(base::DeleteFile(temp_path, false));
869}
870
871TEST_F(URLRequestTest, AllowFileURLs) {
872  base::ScopedTempDir temp_dir;
873  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
874  base::FilePath test_file;
875  ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
876  std::string test_data("monkey");
877  base::WriteFile(test_file, test_data.data(), test_data.size());
878  GURL test_file_url = FilePathToFileURL(test_file);
879
880  {
881    TestDelegate d;
882    TestNetworkDelegate network_delegate;
883    network_delegate.set_can_access_files(true);
884    default_context_.set_network_delegate(&network_delegate);
885    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
886        test_file_url, DEFAULT_PRIORITY, &d, NULL));
887    r->Start();
888    base::RunLoop().Run();
889    EXPECT_FALSE(d.request_failed());
890    EXPECT_EQ(test_data, d.data_received());
891  }
892
893  {
894    TestDelegate d;
895    TestNetworkDelegate network_delegate;
896    network_delegate.set_can_access_files(false);
897    default_context_.set_network_delegate(&network_delegate);
898    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
899        test_file_url, DEFAULT_PRIORITY, &d, NULL));
900    r->Start();
901    base::RunLoop().Run();
902    EXPECT_TRUE(d.request_failed());
903    EXPECT_EQ("", d.data_received());
904  }
905}
906
907
908TEST_F(URLRequestTest, FileDirCancelTest) {
909  // Put in mock resource provider.
910  NetModule::SetResourceProvider(TestNetResourceProvider);
911
912  TestDelegate d;
913  {
914    base::FilePath file_path;
915    PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
916    file_path = file_path.Append(FILE_PATH_LITERAL("net"));
917    file_path = file_path.Append(FILE_PATH_LITERAL("data"));
918
919    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
920        FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d, NULL));
921    req->Start();
922    EXPECT_TRUE(req->is_pending());
923
924    d.set_cancel_in_received_data_pending(true);
925
926    base::RunLoop().Run();
927  }
928
929  // Take out mock resource provider.
930  NetModule::SetResourceProvider(NULL);
931}
932
933TEST_F(URLRequestTest, FileDirOutputSanity) {
934  // Verify the general sanity of the the output of the file:
935  // directory lister by checking for the output of a known existing
936  // file.
937  const char sentinel_name[] = "filedir-sentinel";
938
939  base::FilePath path;
940  PathService::Get(base::DIR_SOURCE_ROOT, &path);
941  path = path.Append(FILE_PATH_LITERAL("net"));
942  path = path.Append(FILE_PATH_LITERAL("data"));
943  path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
944
945  TestDelegate d;
946  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
947      FilePathToFileURL(path), DEFAULT_PRIORITY, &d, NULL));
948  req->Start();
949  base::RunLoop().Run();
950
951  // Generate entry for the sentinel file.
952  base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
953  base::File::Info info;
954  EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
955  EXPECT_GT(info.size, 0);
956  std::string sentinel_output = GetDirectoryListingEntry(
957      base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
958      std::string(sentinel_name),
959      false /* is_dir */,
960      info.size,
961      info.last_modified);
962
963  ASSERT_LT(0, d.bytes_received());
964  ASSERT_FALSE(d.request_failed());
965  ASSERT_TRUE(req->status().is_success());
966  // Check for the entry generated for the "sentinel" file.
967  const std::string& data = d.data_received();
968  ASSERT_NE(data.find(sentinel_output), std::string::npos);
969}
970
971TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
972  // There is an implicit redirect when loading a file path that matches a
973  // directory and does not end with a slash.  Ensure that following such
974  // redirects does not crash.  See http://crbug.com/18686.
975
976  base::FilePath path;
977  PathService::Get(base::DIR_SOURCE_ROOT, &path);
978  path = path.Append(FILE_PATH_LITERAL("net"));
979  path = path.Append(FILE_PATH_LITERAL("data"));
980  path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
981
982  TestDelegate d;
983  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
984      FilePathToFileURL(path), DEFAULT_PRIORITY, &d, NULL));
985  req->Start();
986  base::RunLoop().Run();
987
988  ASSERT_EQ(1, d.received_redirect_count());
989  ASSERT_LT(0, d.bytes_received());
990  ASSERT_FALSE(d.request_failed());
991  ASSERT_TRUE(req->status().is_success());
992}
993
994#if defined(OS_WIN)
995// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
996TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
997  TestDelegate d;
998  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
999      GURL("file:///"), DEFAULT_PRIORITY, &d, NULL));
1000  req->Start();
1001  base::RunLoop().Run();
1002
1003  ASSERT_EQ(1, d.received_redirect_count());
1004  ASSERT_FALSE(req->status().is_success());
1005}
1006#endif  // defined(OS_WIN)
1007
1008#endif  // !defined(DISABLE_FILE_SUPPORT)
1009
1010TEST_F(URLRequestTest, InvalidUrlTest) {
1011  TestDelegate d;
1012  {
1013    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
1014        GURL("invalid url"), DEFAULT_PRIORITY, &d, NULL));
1015
1016    r->Start();
1017    EXPECT_TRUE(r->is_pending());
1018
1019    base::RunLoop().Run();
1020    EXPECT_TRUE(d.request_failed());
1021  }
1022}
1023
1024TEST_F(URLRequestTest, InvalidReferrerTest) {
1025  TestURLRequestContext context;
1026  TestNetworkDelegate network_delegate;
1027  network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1028  context.set_network_delegate(&network_delegate);
1029  TestDelegate d;
1030  scoped_ptr<URLRequest> req(context.CreateRequest(
1031      GURL("http://localhost/"), DEFAULT_PRIORITY, &d, NULL));
1032  req->SetReferrer("https://somewhere.com/");
1033
1034  req->Start();
1035  base::RunLoop().Run();
1036  EXPECT_TRUE(d.request_failed());
1037}
1038
1039#if defined(OS_WIN)
1040TEST_F(URLRequestTest, ResolveShortcutTest) {
1041  base::FilePath app_path;
1042  PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
1043  app_path = app_path.AppendASCII("net");
1044  app_path = app_path.AppendASCII("data");
1045  app_path = app_path.AppendASCII("url_request_unittest");
1046  app_path = app_path.AppendASCII("with-headers.html");
1047
1048  std::wstring lnk_path = app_path.value() + L".lnk";
1049
1050  base::win::ScopedCOMInitializer com_initializer;
1051
1052  // Temporarily create a shortcut for test
1053  {
1054    base::win::ScopedComPtr<IShellLink> shell;
1055    ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1056                                               CLSCTX_INPROC_SERVER)));
1057    base::win::ScopedComPtr<IPersistFile> persist;
1058    ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1059    EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1060    EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1061    EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1062  }
1063
1064  TestDelegate d;
1065  {
1066    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
1067        FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1068        NULL));
1069
1070    r->Start();
1071    EXPECT_TRUE(r->is_pending());
1072
1073    base::RunLoop().Run();
1074
1075    WIN32_FILE_ATTRIBUTE_DATA data;
1076    GetFileAttributesEx(app_path.value().c_str(),
1077                        GetFileExInfoStandard, &data);
1078    HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1079                             FILE_SHARE_READ, NULL, OPEN_EXISTING,
1080                             FILE_ATTRIBUTE_NORMAL, NULL);
1081    EXPECT_NE(INVALID_HANDLE_VALUE, file);
1082    scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1083    DWORD read_size;
1084    BOOL result;
1085    result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1086                      &read_size, NULL);
1087    std::string content(buffer.get(), read_size);
1088    CloseHandle(file);
1089
1090    EXPECT_TRUE(!r->is_pending());
1091    EXPECT_EQ(1, d.received_redirect_count());
1092    EXPECT_EQ(content, d.data_received());
1093  }
1094
1095  // Clean the shortcut
1096  DeleteFile(lnk_path.c_str());
1097}
1098#endif  // defined(OS_WIN)
1099
1100// Custom URLRequestJobs for use with interceptor tests
1101class RestartTestJob : public URLRequestTestJob {
1102 public:
1103  RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1104    : URLRequestTestJob(request, network_delegate, true) {}
1105 protected:
1106  virtual void StartAsync() OVERRIDE {
1107    this->NotifyRestartRequired();
1108  }
1109 private:
1110  virtual ~RestartTestJob() {}
1111};
1112
1113class CancelTestJob : public URLRequestTestJob {
1114 public:
1115  explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1116    : URLRequestTestJob(request, network_delegate, true) {}
1117 protected:
1118  virtual void StartAsync() OVERRIDE {
1119    request_->Cancel();
1120  }
1121 private:
1122  virtual ~CancelTestJob() {}
1123};
1124
1125class CancelThenRestartTestJob : public URLRequestTestJob {
1126 public:
1127  explicit CancelThenRestartTestJob(URLRequest* request,
1128                                    NetworkDelegate* network_delegate)
1129      : URLRequestTestJob(request, network_delegate, true) {
1130  }
1131 protected:
1132  virtual void StartAsync() OVERRIDE {
1133    request_->Cancel();
1134    this->NotifyRestartRequired();
1135  }
1136 private:
1137  virtual ~CancelThenRestartTestJob() {}
1138};
1139
1140// An Interceptor for use with interceptor tests
1141class TestInterceptor : URLRequest::Interceptor {
1142 public:
1143  TestInterceptor()
1144      : intercept_main_request_(false), restart_main_request_(false),
1145        cancel_main_request_(false), cancel_then_restart_main_request_(false),
1146        simulate_main_network_error_(false),
1147        intercept_redirect_(false), cancel_redirect_request_(false),
1148        intercept_final_response_(false), cancel_final_request_(false),
1149        did_intercept_main_(false), did_restart_main_(false),
1150        did_cancel_main_(false), did_cancel_then_restart_main_(false),
1151        did_simulate_error_main_(false),
1152        did_intercept_redirect_(false), did_cancel_redirect_(false),
1153        did_intercept_final_(false), did_cancel_final_(false) {
1154    URLRequest::Deprecated::RegisterRequestInterceptor(this);
1155  }
1156
1157  virtual ~TestInterceptor() {
1158    URLRequest::Deprecated::UnregisterRequestInterceptor(this);
1159  }
1160
1161  virtual URLRequestJob* MaybeIntercept(
1162      URLRequest* request,
1163      NetworkDelegate* network_delegate) OVERRIDE {
1164    if (restart_main_request_) {
1165      restart_main_request_ = false;
1166      did_restart_main_ = true;
1167      return new RestartTestJob(request, network_delegate);
1168    }
1169    if (cancel_main_request_) {
1170      cancel_main_request_ = false;
1171      did_cancel_main_ = true;
1172      return new CancelTestJob(request, network_delegate);
1173    }
1174    if (cancel_then_restart_main_request_) {
1175      cancel_then_restart_main_request_ = false;
1176      did_cancel_then_restart_main_ = true;
1177      return new CancelThenRestartTestJob(request, network_delegate);
1178    }
1179    if (simulate_main_network_error_) {
1180      simulate_main_network_error_ = false;
1181      did_simulate_error_main_ = true;
1182      // will error since the requeted url is not one of its canned urls
1183      return new URLRequestTestJob(request, network_delegate, true);
1184    }
1185    if (!intercept_main_request_)
1186      return NULL;
1187    intercept_main_request_ = false;
1188    did_intercept_main_ = true;
1189    URLRequestTestJob* job =  new URLRequestTestJob(request,
1190                                                    network_delegate,
1191                                                    main_headers_,
1192                                                    main_data_,
1193                                                    true);
1194    job->set_load_timing_info(main_request_load_timing_info_);
1195    return job;
1196  }
1197
1198  virtual URLRequestJob* MaybeInterceptRedirect(
1199      URLRequest* request,
1200      NetworkDelegate* network_delegate,
1201      const GURL& location) OVERRIDE {
1202    if (cancel_redirect_request_) {
1203      cancel_redirect_request_ = false;
1204      did_cancel_redirect_ = true;
1205      return new CancelTestJob(request, network_delegate);
1206    }
1207    if (!intercept_redirect_)
1208      return NULL;
1209    intercept_redirect_ = false;
1210    did_intercept_redirect_ = true;
1211    return new URLRequestTestJob(request,
1212                                 network_delegate,
1213                                 redirect_headers_,
1214                                 redirect_data_,
1215                                 true);
1216  }
1217
1218  virtual URLRequestJob* MaybeInterceptResponse(
1219      URLRequest* request, NetworkDelegate* network_delegate) OVERRIDE {
1220    if (cancel_final_request_) {
1221      cancel_final_request_ = false;
1222      did_cancel_final_ = true;
1223      return new CancelTestJob(request, network_delegate);
1224    }
1225    if (!intercept_final_response_)
1226      return NULL;
1227    intercept_final_response_ = false;
1228    did_intercept_final_ = true;
1229    return new URLRequestTestJob(request,
1230                                 network_delegate,
1231                                 final_headers_,
1232                                 final_data_,
1233                                 true);
1234  }
1235
1236  // Whether to intercept the main request, and if so the response to return and
1237  // the LoadTimingInfo to use.
1238  bool intercept_main_request_;
1239  std::string main_headers_;
1240  std::string main_data_;
1241  LoadTimingInfo main_request_load_timing_info_;
1242
1243  // Other actions we take at MaybeIntercept time
1244  bool restart_main_request_;
1245  bool cancel_main_request_;
1246  bool cancel_then_restart_main_request_;
1247  bool simulate_main_network_error_;
1248
1249  // Whether to intercept redirects, and if so the response to return.
1250  bool intercept_redirect_;
1251  std::string redirect_headers_;
1252  std::string redirect_data_;
1253
1254  // Other actions we can take at MaybeInterceptRedirect time
1255  bool cancel_redirect_request_;
1256
1257  // Whether to intercept final response, and if so the response to return.
1258  bool intercept_final_response_;
1259  std::string final_headers_;
1260  std::string final_data_;
1261
1262  // Other actions we can take at MaybeInterceptResponse time
1263  bool cancel_final_request_;
1264
1265  // If we did something or not
1266  bool did_intercept_main_;
1267  bool did_restart_main_;
1268  bool did_cancel_main_;
1269  bool did_cancel_then_restart_main_;
1270  bool did_simulate_error_main_;
1271  bool did_intercept_redirect_;
1272  bool did_cancel_redirect_;
1273  bool did_intercept_final_;
1274  bool did_cancel_final_;
1275
1276  // Static getters for canned response header and data strings
1277
1278  static std::string ok_data() {
1279    return URLRequestTestJob::test_data_1();
1280  }
1281
1282  static std::string ok_headers() {
1283    return URLRequestTestJob::test_headers();
1284  }
1285
1286  static std::string redirect_data() {
1287    return std::string();
1288  }
1289
1290  static std::string redirect_headers() {
1291    return URLRequestTestJob::test_redirect_headers();
1292  }
1293
1294  static std::string error_data() {
1295    return std::string("ohhh nooooo mr. bill!");
1296  }
1297
1298  static std::string error_headers() {
1299    return URLRequestTestJob::test_error_headers();
1300  }
1301};
1302
1303TEST_F(URLRequestTest, Intercept) {
1304  TestInterceptor interceptor;
1305
1306  // intercept the main request and respond with a simple response
1307  interceptor.intercept_main_request_ = true;
1308  interceptor.main_headers_ = TestInterceptor::ok_headers();
1309  interceptor.main_data_ = TestInterceptor::ok_data();
1310
1311  TestDelegate d;
1312  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1313      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1314  base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1315  base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1316  base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1317  req->SetUserData(NULL, user_data0);
1318  req->SetUserData(&user_data1, user_data1);
1319  req->SetUserData(&user_data2, user_data2);
1320  req->set_method("GET");
1321  req->Start();
1322  base::RunLoop().Run();
1323
1324  // Make sure we can retrieve our specific user data
1325  EXPECT_EQ(user_data0, req->GetUserData(NULL));
1326  EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1327  EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
1328
1329  // Check the interceptor got called as expected
1330  EXPECT_TRUE(interceptor.did_intercept_main_);
1331
1332  // Check we got one good response
1333  EXPECT_TRUE(req->status().is_success());
1334  EXPECT_EQ(200, req->response_headers()->response_code());
1335  EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1336  EXPECT_EQ(1, d.response_started_count());
1337  EXPECT_EQ(0, d.received_redirect_count());
1338}
1339
1340TEST_F(URLRequestTest, InterceptRedirect) {
1341  TestInterceptor interceptor;
1342
1343  // intercept the main request and respond with a redirect
1344  interceptor.intercept_main_request_ = true;
1345  interceptor.main_headers_ = TestInterceptor::redirect_headers();
1346  interceptor.main_data_ = TestInterceptor::redirect_data();
1347
1348  // intercept that redirect and respond a final OK response
1349  interceptor.intercept_redirect_ = true;
1350  interceptor.redirect_headers_ =  TestInterceptor::ok_headers();
1351  interceptor.redirect_data_ = TestInterceptor::ok_data();
1352
1353  TestDelegate d;
1354  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1355      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1356  req->set_method("GET");
1357  req->Start();
1358  base::RunLoop().Run();
1359
1360  // Check the interceptor got called as expected
1361  EXPECT_TRUE(interceptor.did_intercept_main_);
1362  EXPECT_TRUE(interceptor.did_intercept_redirect_);
1363
1364  // Check we got one good response
1365  EXPECT_TRUE(req->status().is_success());
1366  if (req->status().is_success()) {
1367    EXPECT_EQ(200, req->response_headers()->response_code());
1368  }
1369  EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1370  EXPECT_EQ(1, d.response_started_count());
1371  EXPECT_EQ(0, d.received_redirect_count());
1372}
1373
1374TEST_F(URLRequestTest, InterceptServerError) {
1375  TestInterceptor interceptor;
1376
1377  // intercept the main request to generate a server error response
1378  interceptor.intercept_main_request_ = true;
1379  interceptor.main_headers_ = TestInterceptor::error_headers();
1380  interceptor.main_data_ = TestInterceptor::error_data();
1381
1382  // intercept that error and respond with an OK response
1383  interceptor.intercept_final_response_ = true;
1384  interceptor.final_headers_ = TestInterceptor::ok_headers();
1385  interceptor.final_data_ = TestInterceptor::ok_data();
1386
1387  TestDelegate d;
1388  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1389      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1390  req->set_method("GET");
1391  req->Start();
1392  base::RunLoop().Run();
1393
1394  // Check the interceptor got called as expected
1395  EXPECT_TRUE(interceptor.did_intercept_main_);
1396  EXPECT_TRUE(interceptor.did_intercept_final_);
1397
1398  // Check we got one good response
1399  EXPECT_TRUE(req->status().is_success());
1400  EXPECT_EQ(200, req->response_headers()->response_code());
1401  EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1402  EXPECT_EQ(1, d.response_started_count());
1403  EXPECT_EQ(0, d.received_redirect_count());
1404}
1405
1406TEST_F(URLRequestTest, InterceptNetworkError) {
1407  TestInterceptor interceptor;
1408
1409  // intercept the main request to simulate a network error
1410  interceptor.simulate_main_network_error_ = true;
1411
1412  // intercept that error and respond with an OK response
1413  interceptor.intercept_final_response_ = true;
1414  interceptor.final_headers_ = TestInterceptor::ok_headers();
1415  interceptor.final_data_ = TestInterceptor::ok_data();
1416
1417  TestDelegate d;
1418  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1419      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1420  req->set_method("GET");
1421  req->Start();
1422  base::RunLoop().Run();
1423
1424  // Check the interceptor got called as expected
1425  EXPECT_TRUE(interceptor.did_simulate_error_main_);
1426  EXPECT_TRUE(interceptor.did_intercept_final_);
1427
1428  // Check we received one good response
1429  EXPECT_TRUE(req->status().is_success());
1430  EXPECT_EQ(200, req->response_headers()->response_code());
1431  EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1432  EXPECT_EQ(1, d.response_started_count());
1433  EXPECT_EQ(0, d.received_redirect_count());
1434}
1435
1436TEST_F(URLRequestTest, InterceptRestartRequired) {
1437  TestInterceptor interceptor;
1438
1439  // restart the main request
1440  interceptor.restart_main_request_ = true;
1441
1442  // then intercept the new main request and respond with an OK response
1443  interceptor.intercept_main_request_ = true;
1444  interceptor.main_headers_ = TestInterceptor::ok_headers();
1445  interceptor.main_data_ = TestInterceptor::ok_data();
1446
1447  TestDelegate d;
1448  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1449      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1450  req->set_method("GET");
1451  req->Start();
1452  base::RunLoop().Run();
1453
1454  // Check the interceptor got called as expected
1455  EXPECT_TRUE(interceptor.did_restart_main_);
1456  EXPECT_TRUE(interceptor.did_intercept_main_);
1457
1458  // Check we received one good response
1459  EXPECT_TRUE(req->status().is_success());
1460  if (req->status().is_success()) {
1461    EXPECT_EQ(200, req->response_headers()->response_code());
1462  }
1463  EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1464  EXPECT_EQ(1, d.response_started_count());
1465  EXPECT_EQ(0, d.received_redirect_count());
1466}
1467
1468TEST_F(URLRequestTest, InterceptRespectsCancelMain) {
1469  TestInterceptor interceptor;
1470
1471  // intercept the main request and cancel from within the restarted job
1472  interceptor.cancel_main_request_ = true;
1473
1474  // setup to intercept final response and override it with an OK response
1475  interceptor.intercept_final_response_ = true;
1476  interceptor.final_headers_ = TestInterceptor::ok_headers();
1477  interceptor.final_data_ = TestInterceptor::ok_data();
1478
1479  TestDelegate d;
1480  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1481      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1482  req->set_method("GET");
1483  req->Start();
1484  base::RunLoop().Run();
1485
1486  // Check the interceptor got called as expected
1487  EXPECT_TRUE(interceptor.did_cancel_main_);
1488  EXPECT_FALSE(interceptor.did_intercept_final_);
1489
1490  // Check we see a canceled request
1491  EXPECT_FALSE(req->status().is_success());
1492  EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1493}
1494
1495TEST_F(URLRequestTest, InterceptRespectsCancelRedirect) {
1496  TestInterceptor interceptor;
1497
1498  // intercept the main request and respond with a redirect
1499  interceptor.intercept_main_request_ = true;
1500  interceptor.main_headers_ = TestInterceptor::redirect_headers();
1501  interceptor.main_data_ = TestInterceptor::redirect_data();
1502
1503  // intercept the redirect and cancel from within that job
1504  interceptor.cancel_redirect_request_ = true;
1505
1506  // setup to intercept final response and override it with an OK response
1507  interceptor.intercept_final_response_ = true;
1508  interceptor.final_headers_ = TestInterceptor::ok_headers();
1509  interceptor.final_data_ = TestInterceptor::ok_data();
1510
1511  TestDelegate d;
1512  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1513      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1514  req->set_method("GET");
1515  req->Start();
1516  base::RunLoop().Run();
1517
1518  // Check the interceptor got called as expected
1519  EXPECT_TRUE(interceptor.did_intercept_main_);
1520  EXPECT_TRUE(interceptor.did_cancel_redirect_);
1521  EXPECT_FALSE(interceptor.did_intercept_final_);
1522
1523  // Check we see a canceled request
1524  EXPECT_FALSE(req->status().is_success());
1525  EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1526}
1527
1528TEST_F(URLRequestTest, InterceptRespectsCancelFinal) {
1529  TestInterceptor interceptor;
1530
1531  // intercept the main request to simulate a network error
1532  interceptor.simulate_main_network_error_ = true;
1533
1534  // setup to intercept final response and cancel from within that job
1535  interceptor.cancel_final_request_ = true;
1536
1537  TestDelegate d;
1538  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1539      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1540  req->set_method("GET");
1541  req->Start();
1542  base::RunLoop().Run();
1543
1544  // Check the interceptor got called as expected
1545  EXPECT_TRUE(interceptor.did_simulate_error_main_);
1546  EXPECT_TRUE(interceptor.did_cancel_final_);
1547
1548  // Check we see a canceled request
1549  EXPECT_FALSE(req->status().is_success());
1550  EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1551}
1552
1553TEST_F(URLRequestTest, InterceptRespectsCancelInRestart) {
1554  TestInterceptor interceptor;
1555
1556  // intercept the main request and cancel then restart from within that job
1557  interceptor.cancel_then_restart_main_request_ = true;
1558
1559  // setup to intercept final response and override it with an OK response
1560  interceptor.intercept_final_response_ = true;
1561  interceptor.final_headers_ = TestInterceptor::ok_headers();
1562  interceptor.final_data_ = TestInterceptor::ok_data();
1563
1564  TestDelegate d;
1565  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1566      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1567  req->set_method("GET");
1568  req->Start();
1569  base::RunLoop().Run();
1570
1571  // Check the interceptor got called as expected
1572  EXPECT_TRUE(interceptor.did_cancel_then_restart_main_);
1573  EXPECT_FALSE(interceptor.did_intercept_final_);
1574
1575  // Check we see a canceled request
1576  EXPECT_FALSE(req->status().is_success());
1577  EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1578}
1579
1580LoadTimingInfo RunLoadTimingTest(const LoadTimingInfo& job_load_timing,
1581                                 URLRequestContext* context) {
1582  TestInterceptor interceptor;
1583  interceptor.intercept_main_request_ = true;
1584  interceptor.main_request_load_timing_info_ = job_load_timing;
1585  TestDelegate d;
1586  scoped_ptr<URLRequest> req(context->CreateRequest(
1587      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1588  req->Start();
1589  base::RunLoop().Run();
1590
1591  LoadTimingInfo resulting_load_timing;
1592  req->GetLoadTimingInfo(&resulting_load_timing);
1593
1594  // None of these should be modified by the URLRequest.
1595  EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1596  EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1597  EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1598  EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1599  EXPECT_EQ(job_load_timing.receive_headers_end,
1600            resulting_load_timing.receive_headers_end);
1601
1602  return resulting_load_timing;
1603}
1604
1605// "Normal" LoadTimingInfo as returned by a job.  Everything is in order, not
1606// reused.  |connect_time_flags| is used to indicate if there should be dns
1607// or SSL times, and |used_proxy| is used for proxy times.
1608LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1609                                    int connect_time_flags,
1610                                    bool used_proxy) {
1611  LoadTimingInfo load_timing;
1612  load_timing.socket_log_id = 1;
1613
1614  if (used_proxy) {
1615    load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1616    load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1617  }
1618
1619  LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1620  if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1621    connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1622    connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1623  }
1624  connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1625  if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1626    connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1627    connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1628  }
1629  connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1630
1631  load_timing.send_start = now + base::TimeDelta::FromDays(9);
1632  load_timing.send_end = now + base::TimeDelta::FromDays(10);
1633  load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1634  return load_timing;
1635}
1636
1637// Same as above, but in the case of a reused socket.
1638LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1639                                          bool used_proxy) {
1640  LoadTimingInfo load_timing;
1641  load_timing.socket_log_id = 1;
1642  load_timing.socket_reused = true;
1643
1644  if (used_proxy) {
1645    load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1646    load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1647  }
1648
1649  load_timing.send_start = now + base::TimeDelta::FromDays(9);
1650  load_timing.send_end = now + base::TimeDelta::FromDays(10);
1651  load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1652  return load_timing;
1653}
1654
1655// Basic test that the intercept + load timing tests work.
1656TEST_F(URLRequestTest, InterceptLoadTiming) {
1657  base::TimeTicks now = base::TimeTicks::Now();
1658  LoadTimingInfo job_load_timing =
1659      NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1660
1661  LoadTimingInfo load_timing_result =
1662      RunLoadTimingTest(job_load_timing, &default_context_);
1663
1664  // Nothing should have been changed by the URLRequest.
1665  EXPECT_EQ(job_load_timing.proxy_resolve_start,
1666            load_timing_result.proxy_resolve_start);
1667  EXPECT_EQ(job_load_timing.proxy_resolve_end,
1668            load_timing_result.proxy_resolve_end);
1669  EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1670            load_timing_result.connect_timing.dns_start);
1671  EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1672            load_timing_result.connect_timing.dns_end);
1673  EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1674            load_timing_result.connect_timing.connect_start);
1675  EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1676            load_timing_result.connect_timing.connect_end);
1677  EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1678            load_timing_result.connect_timing.ssl_start);
1679  EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1680            load_timing_result.connect_timing.ssl_end);
1681
1682  // Redundant sanity check.
1683  TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1684}
1685
1686// Another basic test, with proxy and SSL times, but no DNS times.
1687TEST_F(URLRequestTest, InterceptLoadTimingProxy) {
1688  base::TimeTicks now = base::TimeTicks::Now();
1689  LoadTimingInfo job_load_timing =
1690      NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1691
1692  LoadTimingInfo load_timing_result =
1693      RunLoadTimingTest(job_load_timing, &default_context_);
1694
1695  // Nothing should have been changed by the URLRequest.
1696  EXPECT_EQ(job_load_timing.proxy_resolve_start,
1697            load_timing_result.proxy_resolve_start);
1698  EXPECT_EQ(job_load_timing.proxy_resolve_end,
1699            load_timing_result.proxy_resolve_end);
1700  EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1701            load_timing_result.connect_timing.dns_start);
1702  EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1703            load_timing_result.connect_timing.dns_end);
1704  EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1705            load_timing_result.connect_timing.connect_start);
1706  EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1707            load_timing_result.connect_timing.connect_end);
1708  EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1709            load_timing_result.connect_timing.ssl_start);
1710  EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1711            load_timing_result.connect_timing.ssl_end);
1712
1713  // Redundant sanity check.
1714  TestLoadTimingNotReusedWithProxy(load_timing_result,
1715                                   CONNECT_TIMING_HAS_SSL_TIMES);
1716}
1717
1718// Make sure that URLRequest correctly adjusts proxy times when they're before
1719// |request_start|, due to already having a connected socket.  This happens in
1720// the case of reusing a SPDY session.  The connected socket is not considered
1721// reused in this test (May be a preconnect).
1722//
1723// To mix things up from the test above, assumes DNS times but no SSL times.
1724TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolution) {
1725  base::TimeTicks now = base::TimeTicks::Now();
1726  LoadTimingInfo job_load_timing =
1727      NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1728  job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1729  job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1730  job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1731  job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1732  job_load_timing.connect_timing.connect_start =
1733      now - base::TimeDelta::FromDays(2);
1734  job_load_timing.connect_timing.connect_end =
1735      now - base::TimeDelta::FromDays(1);
1736
1737  LoadTimingInfo load_timing_result =
1738      RunLoadTimingTest(job_load_timing, &default_context_);
1739
1740  // Proxy times, connect times, and DNS times should all be replaced with
1741  // request_start.
1742  EXPECT_EQ(load_timing_result.request_start,
1743            load_timing_result.proxy_resolve_start);
1744  EXPECT_EQ(load_timing_result.request_start,
1745            load_timing_result.proxy_resolve_end);
1746  EXPECT_EQ(load_timing_result.request_start,
1747            load_timing_result.connect_timing.dns_start);
1748  EXPECT_EQ(load_timing_result.request_start,
1749            load_timing_result.connect_timing.dns_end);
1750  EXPECT_EQ(load_timing_result.request_start,
1751            load_timing_result.connect_timing.connect_start);
1752  EXPECT_EQ(load_timing_result.request_start,
1753            load_timing_result.connect_timing.connect_end);
1754
1755  // Other times should have been left null.
1756  TestLoadTimingNotReusedWithProxy(load_timing_result,
1757                                   CONNECT_TIMING_HAS_DNS_TIMES);
1758}
1759
1760// Same as above, but in the reused case.
1761TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolutionReused) {
1762  base::TimeTicks now = base::TimeTicks::Now();
1763  LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1764  job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1765  job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1766
1767  LoadTimingInfo load_timing_result =
1768      RunLoadTimingTest(job_load_timing, &default_context_);
1769
1770  // Proxy times and connect times should all be replaced with request_start.
1771  EXPECT_EQ(load_timing_result.request_start,
1772            load_timing_result.proxy_resolve_start);
1773  EXPECT_EQ(load_timing_result.request_start,
1774            load_timing_result.proxy_resolve_end);
1775
1776  // Other times should have been left null.
1777  TestLoadTimingReusedWithProxy(load_timing_result);
1778}
1779
1780// Make sure that URLRequest correctly adjusts connect times when they're before
1781// |request_start|, due to reusing a connected socket.  The connected socket is
1782// not considered reused in this test (May be a preconnect).
1783//
1784// To mix things up, the request has SSL times, but no DNS times.
1785TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnect) {
1786  base::TimeTicks now = base::TimeTicks::Now();
1787  LoadTimingInfo job_load_timing =
1788      NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1789  job_load_timing.connect_timing.connect_start =
1790      now - base::TimeDelta::FromDays(1);
1791  job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1792  job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1793  job_load_timing.connect_timing.connect_end =
1794      now - base::TimeDelta::FromDays(4);
1795
1796  LoadTimingInfo load_timing_result =
1797      RunLoadTimingTest(job_load_timing, &default_context_);
1798
1799  // Connect times, and SSL times should be replaced with request_start.
1800  EXPECT_EQ(load_timing_result.request_start,
1801            load_timing_result.connect_timing.connect_start);
1802  EXPECT_EQ(load_timing_result.request_start,
1803            load_timing_result.connect_timing.ssl_start);
1804  EXPECT_EQ(load_timing_result.request_start,
1805            load_timing_result.connect_timing.ssl_end);
1806  EXPECT_EQ(load_timing_result.request_start,
1807            load_timing_result.connect_timing.connect_end);
1808
1809  // Other times should have been left null.
1810  TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1811}
1812
1813// Make sure that URLRequest correctly adjusts connect times when they're before
1814// |request_start|, due to reusing a connected socket in the case that there
1815// are also proxy times.  The connected socket is not considered reused in this
1816// test (May be a preconnect).
1817//
1818// In this test, there are no SSL or DNS times.
1819TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnectWithProxy) {
1820  base::TimeTicks now = base::TimeTicks::Now();
1821  LoadTimingInfo job_load_timing =
1822      NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1823  job_load_timing.connect_timing.connect_start =
1824      now - base::TimeDelta::FromDays(1);
1825  job_load_timing.connect_timing.connect_end =
1826      now - base::TimeDelta::FromDays(2);
1827
1828  LoadTimingInfo load_timing_result =
1829      RunLoadTimingTest(job_load_timing, &default_context_);
1830
1831  // Connect times should be replaced with proxy_resolve_end.
1832  EXPECT_EQ(load_timing_result.proxy_resolve_end,
1833            load_timing_result.connect_timing.connect_start);
1834  EXPECT_EQ(load_timing_result.proxy_resolve_end,
1835            load_timing_result.connect_timing.connect_end);
1836
1837  // Other times should have been left null.
1838  TestLoadTimingNotReusedWithProxy(load_timing_result,
1839                                   CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
1840}
1841
1842// Check that two different URL requests have different identifiers.
1843TEST_F(URLRequestTest, Identifiers) {
1844  TestDelegate d;
1845  TestURLRequestContext context;
1846  scoped_ptr<URLRequest> req(context.CreateRequest(
1847      GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
1848  scoped_ptr<URLRequest> other_req(context.CreateRequest(
1849      GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
1850
1851  ASSERT_NE(req->identifier(), other_req->identifier());
1852}
1853
1854// Check that a failure to connect to the proxy is reported to the network
1855// delegate.
1856TEST_F(URLRequestTest, NetworkDelegateProxyError) {
1857  MockHostResolver host_resolver;
1858  host_resolver.rules()->AddSimulatedFailure("*");
1859
1860  TestNetworkDelegate network_delegate;  // Must outlive URLRequests.
1861  TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
1862
1863  TestDelegate d;
1864  scoped_ptr<URLRequest> req(context.CreateRequest(
1865      GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
1866  req->set_method("GET");
1867
1868  req->Start();
1869  base::RunLoop().Run();
1870
1871  // Check we see a failed request.
1872  EXPECT_FALSE(req->status().is_success());
1873  // The proxy server is not set before failure.
1874  EXPECT_TRUE(req->proxy_server().IsEmpty());
1875  EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
1876  EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
1877
1878  EXPECT_EQ(1, network_delegate.error_count());
1879  EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
1880  EXPECT_EQ(1, network_delegate.completed_requests());
1881}
1882
1883// Make sure that NetworkDelegate::NotifyCompleted is called if
1884// content is empty.
1885TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
1886  TestDelegate d;
1887  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1888      GURL("data:,"), DEFAULT_PRIORITY, &d, NULL));
1889  req->Start();
1890  base::RunLoop().Run();
1891  EXPECT_EQ("", d.data_received());
1892  EXPECT_EQ(1, default_network_delegate_.completed_requests());
1893}
1894
1895// Make sure that SetPriority actually sets the URLRequest's priority
1896// correctly, both before and after start.
1897TEST_F(URLRequestTest, SetPriorityBasic) {
1898  TestDelegate d;
1899  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1900      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1901  EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
1902
1903  req->SetPriority(LOW);
1904  EXPECT_EQ(LOW, req->priority());
1905
1906  req->Start();
1907  EXPECT_EQ(LOW, req->priority());
1908
1909  req->SetPriority(MEDIUM);
1910  EXPECT_EQ(MEDIUM, req->priority());
1911}
1912
1913// Make sure that URLRequest calls SetPriority on a job before calling
1914// Start on it.
1915TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
1916  TestDelegate d;
1917  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1918      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1919  EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
1920
1921  scoped_refptr<URLRequestTestJob> job =
1922      new URLRequestTestJob(req.get(), &default_network_delegate_);
1923  AddTestInterceptor()->set_main_intercept_job(job.get());
1924  EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
1925
1926  req->SetPriority(LOW);
1927
1928  req->Start();
1929  EXPECT_EQ(LOW, job->priority());
1930}
1931
1932// Make sure that URLRequest passes on its priority updates to its
1933// job.
1934TEST_F(URLRequestTest, SetJobPriority) {
1935  TestDelegate d;
1936  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1937      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1938
1939  scoped_refptr<URLRequestTestJob> job =
1940      new URLRequestTestJob(req.get(), &default_network_delegate_);
1941  AddTestInterceptor()->set_main_intercept_job(job.get());
1942
1943  req->SetPriority(LOW);
1944  req->Start();
1945  EXPECT_EQ(LOW, job->priority());
1946
1947  req->SetPriority(MEDIUM);
1948  EXPECT_EQ(MEDIUM, req->priority());
1949  EXPECT_EQ(MEDIUM, job->priority());
1950}
1951
1952// Setting the IGNORE_LIMITS load flag should be okay if the priority
1953// is MAXIMUM_PRIORITY.
1954TEST_F(URLRequestTest, PriorityIgnoreLimits) {
1955  TestDelegate d;
1956  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1957      GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d, NULL));
1958  EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
1959
1960  scoped_refptr<URLRequestTestJob> job =
1961      new URLRequestTestJob(req.get(), &default_network_delegate_);
1962  AddTestInterceptor()->set_main_intercept_job(job.get());
1963
1964  req->SetLoadFlags(LOAD_IGNORE_LIMITS);
1965  EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
1966
1967  req->SetPriority(MAXIMUM_PRIORITY);
1968  EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
1969
1970  req->Start();
1971  EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
1972  EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
1973}
1974
1975// TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
1976#if !defined(OS_IOS)
1977// A subclass of SpawnedTestServer that uses a statically-configured hostname.
1978// This is to work around mysterious failures in chrome_frame_net_tests. See:
1979// http://crbug.com/114369
1980// TODO(erikwright): remove or update as needed; see http://crbug.com/334634.
1981class LocalHttpTestServer : public SpawnedTestServer {
1982 public:
1983  explicit LocalHttpTestServer(const base::FilePath& document_root)
1984      : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1985                          ScopedCustomUrlRequestTestHttpHost::value(),
1986                          document_root) {}
1987  LocalHttpTestServer()
1988      : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1989                          ScopedCustomUrlRequestTestHttpHost::value(),
1990                          base::FilePath()) {}
1991};
1992
1993TEST_F(URLRequestTest, DelayedCookieCallback) {
1994  LocalHttpTestServer test_server;
1995  ASSERT_TRUE(test_server.Start());
1996
1997  TestURLRequestContext context;
1998  scoped_refptr<DelayedCookieMonster> delayed_cm =
1999      new DelayedCookieMonster();
2000  scoped_refptr<CookieStore> cookie_store = delayed_cm;
2001  context.set_cookie_store(delayed_cm.get());
2002
2003  // Set up a cookie.
2004  {
2005    TestNetworkDelegate network_delegate;
2006    context.set_network_delegate(&network_delegate);
2007    TestDelegate d;
2008    scoped_ptr<URLRequest> req(context.CreateRequest(
2009        test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2010        &d, NULL));
2011    req->Start();
2012    base::RunLoop().Run();
2013    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2014    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2015    EXPECT_EQ(1, network_delegate.set_cookie_count());
2016  }
2017
2018  // Verify that the cookie is set.
2019  {
2020    TestNetworkDelegate network_delegate;
2021    context.set_network_delegate(&network_delegate);
2022    TestDelegate d;
2023    scoped_ptr<URLRequest> req(context.CreateRequest(
2024        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2025    req->Start();
2026    base::RunLoop().Run();
2027
2028    EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2029                != std::string::npos);
2030    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2031    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2032  }
2033}
2034
2035TEST_F(URLRequestTest, DoNotSendCookies) {
2036  LocalHttpTestServer test_server;
2037  ASSERT_TRUE(test_server.Start());
2038
2039  // Set up a cookie.
2040  {
2041    TestNetworkDelegate network_delegate;
2042    default_context_.set_network_delegate(&network_delegate);
2043    TestDelegate d;
2044    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2045        test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2046        &d, NULL));
2047    req->Start();
2048    base::RunLoop().Run();
2049    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2050    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2051  }
2052
2053  // Verify that the cookie is set.
2054  {
2055    TestNetworkDelegate network_delegate;
2056    default_context_.set_network_delegate(&network_delegate);
2057    TestDelegate d;
2058    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2059        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
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    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2075        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2076    req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2077    req->Start();
2078    base::RunLoop().Run();
2079
2080    EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2081                == std::string::npos);
2082
2083    // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2084    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2085    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2086  }
2087}
2088
2089TEST_F(URLRequestTest, DoNotSaveCookies) {
2090  LocalHttpTestServer test_server;
2091  ASSERT_TRUE(test_server.Start());
2092
2093  // Set up a cookie.
2094  {
2095    TestNetworkDelegate network_delegate;
2096    default_context_.set_network_delegate(&network_delegate);
2097    TestDelegate d;
2098    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2099        test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2100        &d, NULL));
2101    req->Start();
2102    base::RunLoop().Run();
2103
2104    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2105    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2106    EXPECT_EQ(1, network_delegate.set_cookie_count());
2107  }
2108
2109  // Try to set-up another cookie and update the previous cookie.
2110  {
2111    TestNetworkDelegate network_delegate;
2112    default_context_.set_network_delegate(&network_delegate);
2113    TestDelegate d;
2114    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2115        test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2116        DEFAULT_PRIORITY, &d, NULL));
2117    req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2118    req->Start();
2119
2120    base::RunLoop().Run();
2121
2122    // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2123    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2124    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2125    EXPECT_EQ(0, network_delegate.set_cookie_count());
2126  }
2127
2128  // Verify the cookies weren't saved or updated.
2129  {
2130    TestNetworkDelegate network_delegate;
2131    default_context_.set_network_delegate(&network_delegate);
2132    TestDelegate d;
2133    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2134        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2135    req->Start();
2136    base::RunLoop().Run();
2137
2138    EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2139                == std::string::npos);
2140    EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2141                != std::string::npos);
2142
2143    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2144    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2145    EXPECT_EQ(0, network_delegate.set_cookie_count());
2146  }
2147}
2148
2149TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2150  LocalHttpTestServer test_server;
2151  ASSERT_TRUE(test_server.Start());
2152
2153  // Set up a cookie.
2154  {
2155    TestNetworkDelegate network_delegate;
2156    default_context_.set_network_delegate(&network_delegate);
2157    TestDelegate d;
2158    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2159        test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2160        &d, NULL));
2161    req->Start();
2162    base::RunLoop().Run();
2163
2164    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2165    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2166  }
2167
2168  // Verify that the cookie is set.
2169  {
2170    TestNetworkDelegate network_delegate;
2171    default_context_.set_network_delegate(&network_delegate);
2172    TestDelegate d;
2173    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2174        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2175    req->Start();
2176    base::RunLoop().Run();
2177
2178    EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2179                != std::string::npos);
2180
2181    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2182    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2183  }
2184
2185  // Verify that the cookie isn't sent.
2186  {
2187    TestNetworkDelegate network_delegate;
2188    default_context_.set_network_delegate(&network_delegate);
2189    TestDelegate d;
2190    network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2191    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2192        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2193    req->Start();
2194    base::RunLoop().Run();
2195
2196    EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2197                == std::string::npos);
2198
2199    EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2200    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2201  }
2202}
2203
2204TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2205  LocalHttpTestServer test_server;
2206  ASSERT_TRUE(test_server.Start());
2207
2208  // Set up a cookie.
2209  {
2210    TestNetworkDelegate network_delegate;
2211    default_context_.set_network_delegate(&network_delegate);
2212    TestDelegate d;
2213    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2214        test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2215        &d, NULL));
2216    req->Start();
2217    base::RunLoop().Run();
2218
2219    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2220    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2221  }
2222
2223  // Try to set-up another cookie and update the previous cookie.
2224  {
2225    TestNetworkDelegate network_delegate;
2226    default_context_.set_network_delegate(&network_delegate);
2227    TestDelegate d;
2228    network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2229    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2230        test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2231        DEFAULT_PRIORITY, &d, NULL));
2232    req->Start();
2233
2234    base::RunLoop().Run();
2235
2236    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2237    EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2238  }
2239
2240  // Verify the cookies weren't saved or updated.
2241  {
2242    TestNetworkDelegate network_delegate;
2243    default_context_.set_network_delegate(&network_delegate);
2244    TestDelegate d;
2245    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2246        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2247    req->Start();
2248    base::RunLoop().Run();
2249
2250    EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2251                == std::string::npos);
2252    EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2253                != std::string::npos);
2254
2255    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2256    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2257  }
2258}
2259
2260TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2261  LocalHttpTestServer test_server;
2262  ASSERT_TRUE(test_server.Start());
2263
2264  // Set up an empty cookie.
2265  {
2266    TestNetworkDelegate network_delegate;
2267    default_context_.set_network_delegate(&network_delegate);
2268    TestDelegate d;
2269    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2270        test_server.GetURL("set-cookie"), DEFAULT_PRIORITY, &d, NULL));
2271    req->Start();
2272    base::RunLoop().Run();
2273
2274    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2275    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2276    EXPECT_EQ(0, network_delegate.set_cookie_count());
2277  }
2278}
2279
2280TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2281  LocalHttpTestServer test_server;
2282  ASSERT_TRUE(test_server.Start());
2283
2284  // Set up a cookie.
2285  {
2286    TestNetworkDelegate network_delegate;
2287    default_context_.set_network_delegate(&network_delegate);
2288    TestDelegate d;
2289    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2290        test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2291        &d, NULL));
2292    req->Start();
2293    base::RunLoop().Run();
2294
2295    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2296    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2297  }
2298
2299  // Verify that the cookie is set.
2300  {
2301    TestNetworkDelegate network_delegate;
2302    default_context_.set_network_delegate(&network_delegate);
2303    TestDelegate d;
2304    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2305        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2306    req->Start();
2307    base::RunLoop().Run();
2308
2309    EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2310                != std::string::npos);
2311
2312    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2313    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2314  }
2315
2316  // Verify that the cookie isn't sent.
2317  {
2318    TestNetworkDelegate network_delegate;
2319    default_context_.set_network_delegate(&network_delegate);
2320    TestDelegate d;
2321    network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2322    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2323        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2324    req->Start();
2325    base::RunLoop().Run();
2326
2327    EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2328                == std::string::npos);
2329
2330    EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2331    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2332  }
2333}
2334
2335TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2336  LocalHttpTestServer test_server;
2337  ASSERT_TRUE(test_server.Start());
2338
2339  // Set up a cookie.
2340  {
2341    TestNetworkDelegate network_delegate;
2342    default_context_.set_network_delegate(&network_delegate);
2343    TestDelegate d;
2344    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2345        test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2346        &d, NULL));
2347    req->Start();
2348    base::RunLoop().Run();
2349
2350    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2351    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2352  }
2353
2354  // Try to set-up another cookie and update the previous cookie.
2355  {
2356    TestNetworkDelegate network_delegate;
2357    default_context_.set_network_delegate(&network_delegate);
2358    TestDelegate d;
2359    network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2360    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2361        test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2362        DEFAULT_PRIORITY, &d, NULL));
2363    req->Start();
2364
2365    base::RunLoop().Run();
2366
2367    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2368    EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2369  }
2370
2371  // Verify the cookies weren't saved or updated.
2372  {
2373    TestNetworkDelegate network_delegate;
2374    default_context_.set_network_delegate(&network_delegate);
2375    TestDelegate d;
2376    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2377        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2378    req->Start();
2379    base::RunLoop().Run();
2380
2381    EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2382                == std::string::npos);
2383    EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2384                != std::string::npos);
2385
2386    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2387    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2388  }
2389}
2390
2391// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2392// value for the |fixed_date| argument given to the constructor.
2393class FixedDateNetworkDelegate : public TestNetworkDelegate {
2394 public:
2395  explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2396      : fixed_date_(fixed_date) {}
2397  virtual ~FixedDateNetworkDelegate() {}
2398
2399  // NetworkDelegate implementation
2400  virtual int OnHeadersReceived(
2401      URLRequest* request,
2402      const CompletionCallback& callback,
2403      const HttpResponseHeaders* original_response_headers,
2404      scoped_refptr<HttpResponseHeaders>* override_response_headers,
2405      GURL* allowed_unsafe_redirect_url) OVERRIDE;
2406
2407 private:
2408  std::string fixed_date_;
2409
2410  DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2411};
2412
2413int FixedDateNetworkDelegate::OnHeadersReceived(
2414    URLRequest* request,
2415    const CompletionCallback& callback,
2416    const HttpResponseHeaders* original_response_headers,
2417    scoped_refptr<HttpResponseHeaders>* override_response_headers,
2418    GURL* allowed_unsafe_redirect_url) {
2419  HttpResponseHeaders* new_response_headers =
2420      new HttpResponseHeaders(original_response_headers->raw_headers());
2421
2422  new_response_headers->RemoveHeader("Date");
2423  new_response_headers->AddHeader("Date: " + fixed_date_);
2424
2425  *override_response_headers = new_response_headers;
2426  return TestNetworkDelegate::OnHeadersReceived(request,
2427                                                callback,
2428                                                original_response_headers,
2429                                                override_response_headers,
2430                                                allowed_unsafe_redirect_url);
2431}
2432
2433// Test that cookie expiration times are adjusted for server/client clock
2434// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2435// headers by defaulting to GMT. (crbug.com/135131)
2436TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2437  LocalHttpTestServer test_server;
2438  ASSERT_TRUE(test_server.Start());
2439
2440  // Set up an expired cookie.
2441  {
2442    TestNetworkDelegate network_delegate;
2443    default_context_.set_network_delegate(&network_delegate);
2444    TestDelegate d;
2445    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2446        test_server.GetURL(
2447            "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2448        DEFAULT_PRIORITY, &d, NULL));
2449    req->Start();
2450    base::RunLoop().Run();
2451  }
2452  // Verify that the cookie is not set.
2453  {
2454    TestNetworkDelegate network_delegate;
2455    default_context_.set_network_delegate(&network_delegate);
2456    TestDelegate d;
2457    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2458        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2459    req->Start();
2460    base::RunLoop().Run();
2461
2462    EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2463  }
2464  // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2465  {
2466    FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2467    default_context_.set_network_delegate(&network_delegate);
2468    TestDelegate d;
2469    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2470        test_server.GetURL(
2471            "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2472        DEFAULT_PRIORITY, &d, NULL));
2473    req->Start();
2474    base::RunLoop().Run();
2475  }
2476  // Verify that the cookie is set.
2477  {
2478    TestNetworkDelegate network_delegate;
2479    default_context_.set_network_delegate(&network_delegate);
2480    TestDelegate d;
2481    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2482        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2483    req->Start();
2484    base::RunLoop().Run();
2485
2486    EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2487  }
2488}
2489
2490
2491// Check that it is impossible to change the referrer in the extra headers of
2492// an URLRequest.
2493TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2494  LocalHttpTestServer test_server;
2495  ASSERT_TRUE(test_server.Start());
2496
2497  // If extra headers contain referer and the request contains a referer,
2498  // only the latter shall be respected.
2499  {
2500    TestDelegate d;
2501    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2502        test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
2503    req->SetReferrer("http://foo.com/");
2504
2505    HttpRequestHeaders headers;
2506    headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2507    req->SetExtraRequestHeaders(headers);
2508
2509    req->Start();
2510    base::RunLoop().Run();
2511
2512    EXPECT_EQ("http://foo.com/", d.data_received());
2513  }
2514
2515  // If extra headers contain a referer but the request does not, no referer
2516  // shall be sent in the header.
2517  {
2518    TestDelegate d;
2519    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2520        test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
2521
2522    HttpRequestHeaders headers;
2523    headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2524    req->SetExtraRequestHeaders(headers);
2525    req->SetLoadFlags(LOAD_VALIDATE_CACHE);
2526
2527    req->Start();
2528    base::RunLoop().Run();
2529
2530    EXPECT_EQ("None", d.data_received());
2531  }
2532}
2533
2534class URLRequestTestHTTP : public URLRequestTest {
2535 public:
2536  URLRequestTestHTTP()
2537      : test_server_(base::FilePath(FILE_PATH_LITERAL(
2538                                  "net/data/url_request_unittest"))) {
2539  }
2540
2541 protected:
2542  // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2543  // |request_method| is the method to use for the initial request.
2544  // |redirect_method| is the method that is expected to be used for the second
2545  // request, after redirection.
2546  // If |include_data| is true, data is uploaded with the request.  The
2547  // response body is expected to match it exactly, if and only if
2548  // |request_method| == |redirect_method|.
2549  void HTTPRedirectMethodTest(const GURL& redirect_url,
2550                              const std::string& request_method,
2551                              const std::string& redirect_method,
2552                              bool include_data) {
2553    static const char kData[] = "hello world";
2554    TestDelegate d;
2555    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2556        redirect_url, DEFAULT_PRIORITY, &d, NULL));
2557    req->set_method(request_method);
2558    if (include_data) {
2559      req->set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
2560      HttpRequestHeaders headers;
2561      headers.SetHeader(HttpRequestHeaders::kContentLength,
2562                        base::UintToString(arraysize(kData) - 1));
2563      req->SetExtraRequestHeaders(headers);
2564    }
2565    req->Start();
2566    base::RunLoop().Run();
2567    EXPECT_EQ(redirect_method, req->method());
2568    EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
2569    EXPECT_EQ(OK, req->status().error());
2570    if (include_data) {
2571      if (request_method == redirect_method) {
2572        EXPECT_EQ(kData, d.data_received());
2573      } else {
2574        EXPECT_NE(kData, d.data_received());
2575      }
2576    }
2577    if (HasFailure())
2578      LOG(WARNING) << "Request method was: " << request_method;
2579  }
2580
2581  void HTTPUploadDataOperationTest(const std::string& method) {
2582    const int kMsgSize = 20000;  // multiple of 10
2583    const int kIterations = 50;
2584    char* uploadBytes = new char[kMsgSize+1];
2585    char* ptr = uploadBytes;
2586    char marker = 'a';
2587    for (int idx = 0; idx < kMsgSize/10; idx++) {
2588      memcpy(ptr, "----------", 10);
2589      ptr += 10;
2590      if (idx % 100 == 0) {
2591        ptr--;
2592        *ptr++ = marker;
2593        if (++marker > 'z')
2594          marker = 'a';
2595      }
2596    }
2597    uploadBytes[kMsgSize] = '\0';
2598
2599    for (int i = 0; i < kIterations; ++i) {
2600      TestDelegate d;
2601      scoped_ptr<URLRequest> r(default_context_.CreateRequest(
2602          test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
2603      r->set_method(method.c_str());
2604
2605      r->set_upload(make_scoped_ptr(CreateSimpleUploadData(uploadBytes)));
2606
2607      r->Start();
2608      EXPECT_TRUE(r->is_pending());
2609
2610      base::RunLoop().Run();
2611
2612      ASSERT_EQ(1, d.response_started_count())
2613          << "request failed: " << r->status().status()
2614          << ", os error: " << r->status().error();
2615
2616      EXPECT_FALSE(d.received_data_before_response());
2617      EXPECT_EQ(uploadBytes, d.data_received());
2618    }
2619    delete[] uploadBytes;
2620  }
2621
2622  void AddChunksToUpload(URLRequest* r) {
2623    r->AppendChunkToUpload("a", 1, false);
2624    r->AppendChunkToUpload("bcd", 3, false);
2625    r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2626    r->AppendChunkToUpload("\r\n\r\n", 4, false);
2627    r->AppendChunkToUpload("0", 1, false);
2628    r->AppendChunkToUpload("2323", 4, true);
2629  }
2630
2631  void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
2632    // This should match the chunks sent by AddChunksToUpload().
2633    const std::string expected_data =
2634        "abcdthis is a longer chunk than before.\r\n\r\n02323";
2635
2636    ASSERT_EQ(1, d->response_started_count())
2637        << "request failed: " << r->status().status()
2638        << ", os error: " << r->status().error();
2639
2640    EXPECT_FALSE(d->received_data_before_response());
2641
2642    EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2643    EXPECT_EQ(expected_data, d->data_received());
2644  }
2645
2646  bool DoManyCookiesRequest(int num_cookies) {
2647    TestDelegate d;
2648    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
2649        test_server_.GetURL("set-many-cookies?" +
2650                                base::IntToString(num_cookies)),
2651        DEFAULT_PRIORITY, &d, NULL));
2652
2653    r->Start();
2654    EXPECT_TRUE(r->is_pending());
2655
2656    base::RunLoop().Run();
2657
2658    bool is_success = r->status().is_success();
2659
2660    if (!is_success) {
2661      EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
2662      // The test server appears to be unable to handle subsequent requests
2663      // after this error is triggered. Force it to restart.
2664      EXPECT_TRUE(test_server_.Stop());
2665      EXPECT_TRUE(test_server_.Start());
2666    }
2667
2668    return is_success;
2669  }
2670
2671  LocalHttpTestServer test_server_;
2672};
2673
2674// In this unit test, we're using the HTTPTestServer as a proxy server and
2675// issuing a CONNECT request with the magic host name "www.redirect.com".
2676// The HTTPTestServer will return a 302 response, which we should not
2677// follow.
2678TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
2679  ASSERT_TRUE(test_server_.Start());
2680
2681  TestNetworkDelegate network_delegate;  // Must outlive URLRequest.
2682  TestURLRequestContextWithProxy context(
2683      test_server_.host_port_pair().ToString(), &network_delegate);
2684
2685  TestDelegate d;
2686  {
2687    scoped_ptr<URLRequest> r(context.CreateRequest(
2688        GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, NULL));
2689    r->Start();
2690    EXPECT_TRUE(r->is_pending());
2691
2692    base::RunLoop().Run();
2693
2694    EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
2695    // The proxy server is not set before failure.
2696    EXPECT_TRUE(r->proxy_server().IsEmpty());
2697    EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
2698    EXPECT_EQ(1, d.response_started_count());
2699    // We should not have followed the redirect.
2700    EXPECT_EQ(0, d.received_redirect_count());
2701  }
2702}
2703
2704// This is the same as the previous test, but checks that the network delegate
2705// registers the error.
2706TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
2707  ASSERT_TRUE(test_server_.Start());
2708
2709  TestNetworkDelegate network_delegate;  // Must outlive URLRequest.
2710  TestURLRequestContextWithProxy context(
2711      test_server_.host_port_pair().ToString(), &network_delegate);
2712
2713  TestDelegate d;
2714  {
2715    scoped_ptr<URLRequest> r(context.CreateRequest(
2716        GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, NULL));
2717    r->Start();
2718    EXPECT_TRUE(r->is_pending());
2719
2720    base::RunLoop().Run();
2721
2722    EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
2723    // The proxy server is not set before failure.
2724    EXPECT_TRUE(r->proxy_server().IsEmpty());
2725    EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
2726    EXPECT_EQ(1, d.response_started_count());
2727    // We should not have followed the redirect.
2728    EXPECT_EQ(0, d.received_redirect_count());
2729
2730    EXPECT_EQ(1, network_delegate.error_count());
2731    EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
2732  }
2733}
2734
2735// Tests that we can block and asynchronously return OK in various stages.
2736TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
2737  static const BlockingNetworkDelegate::Stage blocking_stages[] = {
2738    BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2739    BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2740    BlockingNetworkDelegate::ON_HEADERS_RECEIVED
2741  };
2742  static const size_t blocking_stages_length = arraysize(blocking_stages);
2743
2744  ASSERT_TRUE(test_server_.Start());
2745
2746  TestDelegate d;
2747  BlockingNetworkDelegate network_delegate(
2748      BlockingNetworkDelegate::USER_CALLBACK);
2749  network_delegate.set_block_on(
2750      BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
2751      BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
2752      BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
2753
2754  TestURLRequestContext context(true);
2755  context.set_network_delegate(&network_delegate);
2756  context.Init();
2757
2758  {
2759    scoped_ptr<URLRequest> r(context.CreateRequest(
2760        test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
2761
2762    r->Start();
2763    for (size_t i = 0; i < blocking_stages_length; ++i) {
2764      base::RunLoop().Run();
2765      EXPECT_EQ(blocking_stages[i],
2766                network_delegate.stage_blocked_for_callback());
2767      network_delegate.DoCallback(OK);
2768    }
2769    base::RunLoop().Run();
2770    EXPECT_EQ(200, r->GetResponseCode());
2771    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
2772    EXPECT_EQ(1, network_delegate.created_requests());
2773    EXPECT_EQ(0, network_delegate.destroyed_requests());
2774  }
2775  EXPECT_EQ(1, network_delegate.destroyed_requests());
2776}
2777
2778// Tests that the network delegate can block and cancel a request.
2779TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
2780  ASSERT_TRUE(test_server_.Start());
2781
2782  TestDelegate d;
2783  BlockingNetworkDelegate network_delegate(
2784      BlockingNetworkDelegate::AUTO_CALLBACK);
2785  network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2786  network_delegate.set_retval(ERR_EMPTY_RESPONSE);
2787
2788  TestURLRequestContextWithProxy context(
2789      test_server_.host_port_pair().ToString(), &network_delegate);
2790
2791  {
2792    scoped_ptr<URLRequest> r(context.CreateRequest(
2793        test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
2794
2795    r->Start();
2796    base::RunLoop().Run();
2797
2798    EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
2799    // The proxy server is not set before cancellation.
2800    EXPECT_TRUE(r->proxy_server().IsEmpty());
2801    EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
2802    EXPECT_EQ(1, network_delegate.created_requests());
2803    EXPECT_EQ(0, network_delegate.destroyed_requests());
2804  }
2805  EXPECT_EQ(1, network_delegate.destroyed_requests());
2806}
2807
2808// Helper function for NetworkDelegateCancelRequestAsynchronously and
2809// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
2810// delegate operating in |block_mode| and a request for |url|. It blocks the
2811// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
2812void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
2813                                  BlockingNetworkDelegate::Stage stage,
2814                                  const GURL& url) {
2815  TestDelegate d;
2816  BlockingNetworkDelegate network_delegate(block_mode);
2817  network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
2818  network_delegate.set_block_on(stage);
2819
2820  TestURLRequestContext context(true);
2821  context.set_network_delegate(&network_delegate);
2822  context.Init();
2823
2824  {
2825    scoped_ptr<URLRequest> r(context.CreateRequest(
2826        url, DEFAULT_PRIORITY, &d, NULL));
2827
2828    r->Start();
2829    base::RunLoop().Run();
2830
2831    EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
2832    // The proxy server is not set before cancellation.
2833    EXPECT_TRUE(r->proxy_server().IsEmpty());
2834    EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
2835    EXPECT_EQ(1, network_delegate.created_requests());
2836    EXPECT_EQ(0, network_delegate.destroyed_requests());
2837  }
2838  EXPECT_EQ(1, network_delegate.destroyed_requests());
2839}
2840
2841// The following 3 tests check that the network delegate can cancel a request
2842// synchronously in various stages of the request.
2843TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
2844  ASSERT_TRUE(test_server_.Start());
2845  NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2846                               BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2847                               test_server_.GetURL(std::string()));
2848}
2849
2850TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
2851  ASSERT_TRUE(test_server_.Start());
2852  NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2853                               BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2854                               test_server_.GetURL(std::string()));
2855}
2856
2857TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
2858  ASSERT_TRUE(test_server_.Start());
2859  NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2860                               BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
2861                               test_server_.GetURL(std::string()));
2862}
2863
2864// The following 3 tests check that the network delegate can cancel a request
2865// asynchronously in various stages of the request.
2866TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
2867  ASSERT_TRUE(test_server_.Start());
2868  NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2869                               BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2870                               test_server_.GetURL(std::string()));
2871}
2872
2873TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
2874  ASSERT_TRUE(test_server_.Start());
2875  NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2876                               BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2877                               test_server_.GetURL(std::string()));
2878}
2879
2880TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
2881  ASSERT_TRUE(test_server_.Start());
2882  NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2883                               BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
2884                               test_server_.GetURL(std::string()));
2885}
2886
2887// Tests that the network delegate can block and redirect a request to a new
2888// URL.
2889TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
2890  ASSERT_TRUE(test_server_.Start());
2891
2892  TestDelegate d;
2893  BlockingNetworkDelegate network_delegate(
2894      BlockingNetworkDelegate::AUTO_CALLBACK);
2895  network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2896  GURL redirect_url(test_server_.GetURL("simple.html"));
2897  network_delegate.set_redirect_url(redirect_url);
2898
2899  TestURLRequestContextWithProxy context(
2900      test_server_.host_port_pair().ToString(), &network_delegate);
2901
2902  {
2903    GURL original_url(test_server_.GetURL("empty.html"));
2904    scoped_ptr<URLRequest> r(context.CreateRequest(
2905        original_url, DEFAULT_PRIORITY, &d, NULL));
2906
2907    // Quit after hitting the redirect, so can check the headers.
2908    d.set_quit_on_redirect(true);
2909    r->Start();
2910    base::RunLoop().Run();
2911
2912    // Check headers from URLRequestJob.
2913    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
2914    EXPECT_EQ(307, r->GetResponseCode());
2915    EXPECT_EQ(307, r->response_headers()->response_code());
2916    std::string location;
2917    ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
2918                                                       &location));
2919    EXPECT_EQ(redirect_url, GURL(location));
2920
2921    // Let the request finish.
2922    r->FollowDeferredRedirect();
2923    base::RunLoop().Run();
2924    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
2925    EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
2926    EXPECT_EQ(
2927        1, network_delegate.observed_before_proxy_headers_sent_callbacks());
2928    EXPECT_TRUE(
2929        network_delegate.last_observed_proxy().Equals(
2930            test_server_.host_port_pair()));
2931
2932    EXPECT_EQ(0, r->status().error());
2933    EXPECT_EQ(redirect_url, r->url());
2934    EXPECT_EQ(original_url, r->original_url());
2935    EXPECT_EQ(2U, r->url_chain().size());
2936    EXPECT_EQ(1, network_delegate.created_requests());
2937    EXPECT_EQ(0, network_delegate.destroyed_requests());
2938  }
2939  EXPECT_EQ(1, network_delegate.destroyed_requests());
2940}
2941
2942// Tests that the network delegate can block and redirect a request to a new
2943// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
2944TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
2945  ASSERT_TRUE(test_server_.Start());
2946
2947  TestDelegate d;
2948  BlockingNetworkDelegate network_delegate(
2949      BlockingNetworkDelegate::SYNCHRONOUS);
2950  GURL redirect_url(test_server_.GetURL("simple.html"));
2951  network_delegate.set_redirect_url(redirect_url);
2952
2953  TestURLRequestContextWithProxy context(
2954      test_server_.host_port_pair().ToString(), &network_delegate);
2955
2956  {
2957    GURL original_url(test_server_.GetURL("empty.html"));
2958    scoped_ptr<URLRequest> r(context.CreateRequest(
2959        original_url, DEFAULT_PRIORITY, &d, NULL));
2960
2961    // Quit after hitting the redirect, so can check the headers.
2962    d.set_quit_on_redirect(true);
2963    r->Start();
2964    base::RunLoop().Run();
2965
2966    // Check headers from URLRequestJob.
2967    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
2968    EXPECT_EQ(307, r->GetResponseCode());
2969    EXPECT_EQ(307, r->response_headers()->response_code());
2970    std::string location;
2971    ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
2972                                                       &location));
2973    EXPECT_EQ(redirect_url, GURL(location));
2974
2975    // Let the request finish.
2976    r->FollowDeferredRedirect();
2977    base::RunLoop().Run();
2978
2979    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
2980    EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
2981    EXPECT_EQ(
2982        1, network_delegate.observed_before_proxy_headers_sent_callbacks());
2983    EXPECT_TRUE(
2984        network_delegate.last_observed_proxy().Equals(
2985            test_server_.host_port_pair()));
2986    EXPECT_EQ(0, r->status().error());
2987    EXPECT_EQ(redirect_url, r->url());
2988    EXPECT_EQ(original_url, r->original_url());
2989    EXPECT_EQ(2U, r->url_chain().size());
2990    EXPECT_EQ(1, network_delegate.created_requests());
2991    EXPECT_EQ(0, network_delegate.destroyed_requests());
2992  }
2993  EXPECT_EQ(1, network_delegate.destroyed_requests());
2994}
2995
2996// Tests that redirects caused by the network delegate preserve POST data.
2997TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
2998  ASSERT_TRUE(test_server_.Start());
2999
3000  const char kData[] = "hello world";
3001
3002  TestDelegate d;
3003  BlockingNetworkDelegate network_delegate(
3004      BlockingNetworkDelegate::AUTO_CALLBACK);
3005  network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3006  GURL redirect_url(test_server_.GetURL("echo"));
3007  network_delegate.set_redirect_url(redirect_url);
3008
3009  TestURLRequestContext context(true);
3010  context.set_network_delegate(&network_delegate);
3011  context.Init();
3012
3013  {
3014    GURL original_url(test_server_.GetURL("empty.html"));
3015    scoped_ptr<URLRequest> r(context.CreateRequest(
3016        original_url, DEFAULT_PRIORITY, &d, NULL));
3017    r->set_method("POST");
3018    r->set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
3019    HttpRequestHeaders headers;
3020    headers.SetHeader(HttpRequestHeaders::kContentLength,
3021                      base::UintToString(arraysize(kData) - 1));
3022    r->SetExtraRequestHeaders(headers);
3023
3024    // Quit after hitting the redirect, so can check the headers.
3025    d.set_quit_on_redirect(true);
3026    r->Start();
3027    base::RunLoop().Run();
3028
3029    // Check headers from URLRequestJob.
3030    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3031    EXPECT_EQ(307, r->GetResponseCode());
3032    EXPECT_EQ(307, r->response_headers()->response_code());
3033    std::string location;
3034    ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3035                                                       &location));
3036    EXPECT_EQ(redirect_url, GURL(location));
3037
3038    // Let the request finish.
3039    r->FollowDeferredRedirect();
3040    base::RunLoop().Run();
3041
3042    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3043    EXPECT_EQ(0, r->status().error());
3044    EXPECT_EQ(redirect_url, r->url());
3045    EXPECT_EQ(original_url, r->original_url());
3046    EXPECT_EQ(2U, r->url_chain().size());
3047    EXPECT_EQ(1, network_delegate.created_requests());
3048    EXPECT_EQ(0, network_delegate.destroyed_requests());
3049    EXPECT_EQ("POST", r->method());
3050    EXPECT_EQ(kData, d.data_received());
3051  }
3052  EXPECT_EQ(1, network_delegate.destroyed_requests());
3053}
3054
3055// Tests that the network delegate can block and redirect a request to a new
3056// URL during OnHeadersReceived.
3057TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3058  ASSERT_TRUE(test_server_.Start());
3059
3060  TestDelegate d;
3061  BlockingNetworkDelegate network_delegate(
3062      BlockingNetworkDelegate::AUTO_CALLBACK);
3063  network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3064  GURL redirect_url(test_server_.GetURL("simple.html"));
3065  network_delegate.set_redirect_on_headers_received_url(redirect_url);
3066
3067  TestURLRequestContextWithProxy context(
3068      test_server_.host_port_pair().ToString(), &network_delegate);
3069
3070  {
3071    GURL original_url(test_server_.GetURL("empty.html"));
3072    scoped_ptr<URLRequest> r(context.CreateRequest(
3073        original_url, DEFAULT_PRIORITY, &d, NULL));
3074
3075    r->Start();
3076    base::RunLoop().Run();
3077
3078    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3079    EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
3080    EXPECT_EQ(
3081        2, network_delegate.observed_before_proxy_headers_sent_callbacks());
3082    EXPECT_TRUE(
3083        network_delegate.last_observed_proxy().Equals(
3084            test_server_.host_port_pair()));
3085
3086    EXPECT_EQ(OK, r->status().error());
3087    EXPECT_EQ(redirect_url, r->url());
3088    EXPECT_EQ(original_url, r->original_url());
3089    EXPECT_EQ(2U, r->url_chain().size());
3090    EXPECT_EQ(2, network_delegate.created_requests());
3091    EXPECT_EQ(0, network_delegate.destroyed_requests());
3092  }
3093  EXPECT_EQ(1, network_delegate.destroyed_requests());
3094}
3095
3096// Tests that the network delegate can synchronously complete OnAuthRequired
3097// by taking no action. This indicates that the NetworkDelegate does not want to
3098// handle the challenge, and is passing the buck along to the
3099// URLRequest::Delegate.
3100TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3101  ASSERT_TRUE(test_server_.Start());
3102
3103  TestDelegate d;
3104  BlockingNetworkDelegate network_delegate(
3105      BlockingNetworkDelegate::SYNCHRONOUS);
3106
3107  TestURLRequestContext context(true);
3108  context.set_network_delegate(&network_delegate);
3109  context.Init();
3110
3111  d.set_credentials(AuthCredentials(kUser, kSecret));
3112
3113  {
3114    GURL url(test_server_.GetURL("auth-basic"));
3115    scoped_ptr<URLRequest> r(context.CreateRequest(
3116        url, DEFAULT_PRIORITY, &d, NULL));
3117    r->Start();
3118
3119    base::RunLoop().Run();
3120
3121    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3122    EXPECT_EQ(0, r->status().error());
3123    EXPECT_EQ(200, r->GetResponseCode());
3124    EXPECT_TRUE(d.auth_required_called());
3125    EXPECT_EQ(1, network_delegate.created_requests());
3126    EXPECT_EQ(0, network_delegate.destroyed_requests());
3127  }
3128  EXPECT_EQ(1, network_delegate.destroyed_requests());
3129}
3130
3131TEST_F(URLRequestTestHTTP,
3132    NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3133  ASSERT_TRUE(test_server_.Start());
3134
3135  TestDelegate d;
3136  BlockingNetworkDelegate network_delegate(
3137      BlockingNetworkDelegate::SYNCHRONOUS);
3138
3139  TestURLRequestContext context(true);
3140  context.set_network_delegate(&network_delegate);
3141  context.Init();
3142
3143  d.set_credentials(AuthCredentials(kUser, kSecret));
3144
3145  {
3146    GURL url(test_server_.GetURL("auth-basic"));
3147    scoped_ptr<URLRequest> r(context.CreateRequest(
3148        url, DEFAULT_PRIORITY, &d, NULL));
3149    r->Start();
3150
3151    {
3152      HttpRequestHeaders headers;
3153      EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3154      EXPECT_FALSE(headers.HasHeader("Authorization"));
3155    }
3156
3157    base::RunLoop().Run();
3158
3159    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3160    EXPECT_EQ(0, r->status().error());
3161    EXPECT_EQ(200, r->GetResponseCode());
3162    EXPECT_TRUE(d.auth_required_called());
3163    EXPECT_EQ(1, network_delegate.created_requests());
3164    EXPECT_EQ(0, network_delegate.destroyed_requests());
3165  }
3166  EXPECT_EQ(1, network_delegate.destroyed_requests());
3167}
3168
3169// Tests that the network delegate can synchronously complete OnAuthRequired
3170// by setting credentials.
3171TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3172  ASSERT_TRUE(test_server_.Start());
3173
3174  TestDelegate d;
3175  BlockingNetworkDelegate network_delegate(
3176      BlockingNetworkDelegate::SYNCHRONOUS);
3177  network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3178  network_delegate.set_auth_retval(
3179      NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3180
3181  network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3182
3183  TestURLRequestContext context(true);
3184  context.set_network_delegate(&network_delegate);
3185  context.Init();
3186
3187  {
3188    GURL url(test_server_.GetURL("auth-basic"));
3189    scoped_ptr<URLRequest> r(context.CreateRequest(
3190        url, DEFAULT_PRIORITY, &d, NULL));
3191    r->Start();
3192    base::RunLoop().Run();
3193
3194    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3195    EXPECT_EQ(0, r->status().error());
3196    EXPECT_EQ(200, r->GetResponseCode());
3197    EXPECT_FALSE(d.auth_required_called());
3198    EXPECT_EQ(1, network_delegate.created_requests());
3199    EXPECT_EQ(0, network_delegate.destroyed_requests());
3200  }
3201  EXPECT_EQ(1, network_delegate.destroyed_requests());
3202}
3203
3204// Same as above, but also tests that GetFullRequestHeaders returns the proper
3205// headers (for the first or second request) when called at the proper times.
3206TEST_F(URLRequestTestHTTP,
3207    NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
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_SET_AUTH);
3216
3217  network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3218
3219  TestURLRequestContext context(true);
3220  context.set_network_delegate(&network_delegate);
3221  context.Init();
3222
3223  {
3224    GURL url(test_server_.GetURL("auth-basic"));
3225    scoped_ptr<URLRequest> r(context.CreateRequest(
3226        url, DEFAULT_PRIORITY, &d, NULL));
3227    r->Start();
3228    base::RunLoop().Run();
3229
3230    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3231    EXPECT_EQ(0, r->status().error());
3232    EXPECT_EQ(200, r->GetResponseCode());
3233    EXPECT_FALSE(d.auth_required_called());
3234    EXPECT_EQ(1, network_delegate.created_requests());
3235    EXPECT_EQ(0, network_delegate.destroyed_requests());
3236
3237    {
3238      HttpRequestHeaders headers;
3239      EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3240      EXPECT_TRUE(headers.HasHeader("Authorization"));
3241    }
3242  }
3243  EXPECT_EQ(1, network_delegate.destroyed_requests());
3244}
3245
3246// Tests that the network delegate can synchronously complete OnAuthRequired
3247// by cancelling authentication.
3248TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3249  ASSERT_TRUE(test_server_.Start());
3250
3251  TestDelegate d;
3252  BlockingNetworkDelegate network_delegate(
3253      BlockingNetworkDelegate::SYNCHRONOUS);
3254  network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3255  network_delegate.set_auth_retval(
3256      NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3257
3258  TestURLRequestContext context(true);
3259  context.set_network_delegate(&network_delegate);
3260  context.Init();
3261
3262  {
3263    GURL url(test_server_.GetURL("auth-basic"));
3264    scoped_ptr<URLRequest> r(context.CreateRequest(
3265        url, DEFAULT_PRIORITY, &d, NULL));
3266    r->Start();
3267    base::RunLoop().Run();
3268
3269    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3270    EXPECT_EQ(OK, r->status().error());
3271    EXPECT_EQ(401, r->GetResponseCode());
3272    EXPECT_FALSE(d.auth_required_called());
3273    EXPECT_EQ(1, network_delegate.created_requests());
3274    EXPECT_EQ(0, network_delegate.destroyed_requests());
3275  }
3276  EXPECT_EQ(1, network_delegate.destroyed_requests());
3277}
3278
3279// Tests that the network delegate can asynchronously complete OnAuthRequired
3280// by taking no action. This indicates that the NetworkDelegate does not want
3281// to handle the challenge, and is passing the buck along to the
3282// URLRequest::Delegate.
3283TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3284  ASSERT_TRUE(test_server_.Start());
3285
3286  TestDelegate d;
3287  BlockingNetworkDelegate network_delegate(
3288      BlockingNetworkDelegate::AUTO_CALLBACK);
3289  network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3290
3291  TestURLRequestContext context(true);
3292  context.set_network_delegate(&network_delegate);
3293  context.Init();
3294
3295  d.set_credentials(AuthCredentials(kUser, kSecret));
3296
3297  {
3298    GURL url(test_server_.GetURL("auth-basic"));
3299    scoped_ptr<URLRequest> r(context.CreateRequest(
3300        url, DEFAULT_PRIORITY, &d, NULL));
3301    r->Start();
3302    base::RunLoop().Run();
3303
3304    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3305    EXPECT_EQ(0, r->status().error());
3306    EXPECT_EQ(200, r->GetResponseCode());
3307    EXPECT_TRUE(d.auth_required_called());
3308    EXPECT_EQ(1, network_delegate.created_requests());
3309    EXPECT_EQ(0, network_delegate.destroyed_requests());
3310  }
3311  EXPECT_EQ(1, network_delegate.destroyed_requests());
3312}
3313
3314// Tests that the network delegate can asynchronously complete OnAuthRequired
3315// by setting credentials.
3316TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3317  ASSERT_TRUE(test_server_.Start());
3318
3319  TestDelegate d;
3320  BlockingNetworkDelegate network_delegate(
3321      BlockingNetworkDelegate::AUTO_CALLBACK);
3322  network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3323  network_delegate.set_auth_retval(
3324      NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3325
3326  AuthCredentials auth_credentials(kUser, kSecret);
3327  network_delegate.set_auth_credentials(auth_credentials);
3328
3329  TestURLRequestContext context(true);
3330  context.set_network_delegate(&network_delegate);
3331  context.Init();
3332
3333  {
3334    GURL url(test_server_.GetURL("auth-basic"));
3335    scoped_ptr<URLRequest> r(context.CreateRequest(
3336        url, DEFAULT_PRIORITY, &d, NULL));
3337    r->Start();
3338    base::RunLoop().Run();
3339
3340    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3341    EXPECT_EQ(0, r->status().error());
3342
3343    EXPECT_EQ(200, r->GetResponseCode());
3344    EXPECT_FALSE(d.auth_required_called());
3345    EXPECT_EQ(1, network_delegate.created_requests());
3346    EXPECT_EQ(0, network_delegate.destroyed_requests());
3347  }
3348  EXPECT_EQ(1, network_delegate.destroyed_requests());
3349}
3350
3351// Tests that the network delegate can asynchronously complete OnAuthRequired
3352// by cancelling authentication.
3353TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3354  ASSERT_TRUE(test_server_.Start());
3355
3356  TestDelegate d;
3357  BlockingNetworkDelegate network_delegate(
3358      BlockingNetworkDelegate::AUTO_CALLBACK);
3359  network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3360  network_delegate.set_auth_retval(
3361      NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3362
3363  TestURLRequestContext context(true);
3364  context.set_network_delegate(&network_delegate);
3365  context.Init();
3366
3367  {
3368    GURL url(test_server_.GetURL("auth-basic"));
3369    scoped_ptr<URLRequest> r(context.CreateRequest(
3370        url, DEFAULT_PRIORITY, &d, NULL));
3371    r->Start();
3372    base::RunLoop().Run();
3373
3374    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3375    EXPECT_EQ(OK, r->status().error());
3376    EXPECT_EQ(401, r->GetResponseCode());
3377    EXPECT_FALSE(d.auth_required_called());
3378    EXPECT_EQ(1, network_delegate.created_requests());
3379    EXPECT_EQ(0, network_delegate.destroyed_requests());
3380  }
3381  EXPECT_EQ(1, network_delegate.destroyed_requests());
3382}
3383
3384// Tests that we can handle when a network request was canceled while we were
3385// waiting for the network delegate.
3386// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3387TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3388  ASSERT_TRUE(test_server_.Start());
3389
3390  TestDelegate d;
3391  BlockingNetworkDelegate network_delegate(
3392      BlockingNetworkDelegate::USER_CALLBACK);
3393  network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3394
3395  TestURLRequestContext context(true);
3396  context.set_network_delegate(&network_delegate);
3397  context.Init();
3398
3399  {
3400    scoped_ptr<URLRequest> r(context.CreateRequest(
3401        test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
3402
3403    r->Start();
3404    base::RunLoop().Run();
3405    EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3406              network_delegate.stage_blocked_for_callback());
3407    EXPECT_EQ(0, network_delegate.completed_requests());
3408    // Cancel before callback.
3409    r->Cancel();
3410    // Ensure that network delegate is notified.
3411    EXPECT_EQ(1, network_delegate.completed_requests());
3412    EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3413    EXPECT_EQ(ERR_ABORTED, r->status().error());
3414    EXPECT_EQ(1, network_delegate.created_requests());
3415    EXPECT_EQ(0, network_delegate.destroyed_requests());
3416  }
3417  EXPECT_EQ(1, network_delegate.destroyed_requests());
3418}
3419
3420// Tests that we can handle when a network request was canceled while we were
3421// waiting for the network delegate.
3422// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3423TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3424  ASSERT_TRUE(test_server_.Start());
3425
3426  TestDelegate d;
3427  BlockingNetworkDelegate network_delegate(
3428      BlockingNetworkDelegate::USER_CALLBACK);
3429  network_delegate.set_block_on(
3430      BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
3431
3432  TestURLRequestContext context(true);
3433  context.set_network_delegate(&network_delegate);
3434  context.Init();
3435
3436  {
3437    scoped_ptr<URLRequest> r(context.CreateRequest(
3438        test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
3439
3440    r->Start();
3441    base::RunLoop().Run();
3442    EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3443              network_delegate.stage_blocked_for_callback());
3444    EXPECT_EQ(0, network_delegate.completed_requests());
3445    // Cancel before callback.
3446    r->Cancel();
3447    // Ensure that network delegate is notified.
3448    EXPECT_EQ(1, network_delegate.completed_requests());
3449    EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3450    EXPECT_EQ(ERR_ABORTED, r->status().error());
3451    EXPECT_EQ(1, network_delegate.created_requests());
3452    EXPECT_EQ(0, network_delegate.destroyed_requests());
3453  }
3454  EXPECT_EQ(1, network_delegate.destroyed_requests());
3455}
3456
3457// Tests that we can handle when a network request was canceled while we were
3458// waiting for the network delegate.
3459// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3460TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3461  ASSERT_TRUE(test_server_.Start());
3462
3463  TestDelegate d;
3464  BlockingNetworkDelegate network_delegate(
3465      BlockingNetworkDelegate::USER_CALLBACK);
3466  network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3467
3468  TestURLRequestContext context(true);
3469  context.set_network_delegate(&network_delegate);
3470  context.Init();
3471
3472  {
3473    scoped_ptr<URLRequest> r(context.CreateRequest(
3474        test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
3475
3476    r->Start();
3477    base::RunLoop().Run();
3478    EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3479              network_delegate.stage_blocked_for_callback());
3480    EXPECT_EQ(0, network_delegate.completed_requests());
3481    // Cancel before callback.
3482    r->Cancel();
3483    // Ensure that network delegate is notified.
3484    EXPECT_EQ(1, network_delegate.completed_requests());
3485    EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3486    EXPECT_EQ(ERR_ABORTED, r->status().error());
3487    EXPECT_EQ(1, network_delegate.created_requests());
3488    EXPECT_EQ(0, network_delegate.destroyed_requests());
3489  }
3490  EXPECT_EQ(1, network_delegate.destroyed_requests());
3491}
3492
3493// Tests that we can handle when a network request was canceled while we were
3494// waiting for the network delegate.
3495// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
3496TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
3497  ASSERT_TRUE(test_server_.Start());
3498
3499  TestDelegate d;
3500  BlockingNetworkDelegate network_delegate(
3501      BlockingNetworkDelegate::USER_CALLBACK);
3502  network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3503
3504  TestURLRequestContext context(true);
3505  context.set_network_delegate(&network_delegate);
3506  context.Init();
3507
3508  {
3509    scoped_ptr<URLRequest> r(context.CreateRequest(
3510        test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
3511
3512    r->Start();
3513    base::RunLoop().Run();
3514    EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3515              network_delegate.stage_blocked_for_callback());
3516    EXPECT_EQ(0, network_delegate.completed_requests());
3517    // Cancel before callback.
3518    r->Cancel();
3519    // Ensure that network delegate is notified.
3520    EXPECT_EQ(1, network_delegate.completed_requests());
3521    EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3522    EXPECT_EQ(ERR_ABORTED, r->status().error());
3523    EXPECT_EQ(1, network_delegate.created_requests());
3524    EXPECT_EQ(0, network_delegate.destroyed_requests());
3525  }
3526  EXPECT_EQ(1, network_delegate.destroyed_requests());
3527}
3528
3529// In this unit test, we're using the HTTPTestServer as a proxy server and
3530// issuing a CONNECT request with the magic host name "www.server-auth.com".
3531// The HTTPTestServer will return a 401 response, which we should balk at.
3532TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
3533  ASSERT_TRUE(test_server_.Start());
3534
3535  TestNetworkDelegate network_delegate;  // Must outlive URLRequest.
3536  TestURLRequestContextWithProxy context(
3537      test_server_.host_port_pair().ToString(), &network_delegate);
3538
3539  TestDelegate d;
3540  {
3541    scoped_ptr<URLRequest> r(context.CreateRequest(
3542        GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d, NULL));
3543
3544    r->Start();
3545    EXPECT_TRUE(r->is_pending());
3546
3547    base::RunLoop().Run();
3548
3549    EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3550    // The proxy server is not set before failure.
3551    EXPECT_TRUE(r->proxy_server().IsEmpty());
3552    EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
3553  }
3554}
3555
3556TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
3557  ASSERT_TRUE(test_server_.Start());
3558
3559  TestDelegate d;
3560  {
3561    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3562        test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
3563
3564    r->Start();
3565    EXPECT_TRUE(r->is_pending());
3566
3567    base::RunLoop().Run();
3568
3569    EXPECT_EQ(1, d.response_started_count());
3570    EXPECT_FALSE(d.received_data_before_response());
3571    EXPECT_NE(0, d.bytes_received());
3572    EXPECT_EQ(test_server_.host_port_pair().host(),
3573              r->GetSocketAddress().host());
3574    EXPECT_EQ(test_server_.host_port_pair().port(),
3575              r->GetSocketAddress().port());
3576
3577    // TODO(eroman): Add back the NetLog tests...
3578  }
3579}
3580
3581// This test has the server send a large number of cookies to the client.
3582// To ensure that no number of cookies causes a crash, a galloping binary
3583// search is used to estimate that maximum number of cookies that are accepted
3584// by the browser. Beyond the maximum number, the request will fail with
3585// ERR_RESPONSE_HEADERS_TOO_BIG.
3586#if defined(OS_WIN)
3587// http://crbug.com/177916
3588#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3589#else
3590#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3591#endif  // defined(OS_WIN)
3592TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
3593  ASSERT_TRUE(test_server_.Start());
3594
3595  int lower_bound = 0;
3596  int upper_bound = 1;
3597
3598  // Double the number of cookies until the response header limits are
3599  // exceeded.
3600  while (DoManyCookiesRequest(upper_bound)) {
3601    lower_bound = upper_bound;
3602    upper_bound *= 2;
3603    ASSERT_LT(upper_bound, 1000000);
3604  }
3605
3606  int tolerance = upper_bound * 0.005;
3607  if (tolerance < 2)
3608    tolerance = 2;
3609
3610  // Perform a binary search to find the highest possible number of cookies,
3611  // within the desired tolerance.
3612  while (upper_bound - lower_bound >= tolerance) {
3613    int num_cookies = (lower_bound + upper_bound) / 2;
3614
3615    if (DoManyCookiesRequest(num_cookies))
3616      lower_bound = num_cookies;
3617    else
3618      upper_bound = num_cookies;
3619  }
3620  // Success: the test did not crash.
3621}
3622
3623TEST_F(URLRequestTestHTTP, GetTest) {
3624  ASSERT_TRUE(test_server_.Start());
3625
3626  TestDelegate d;
3627  {
3628    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3629        test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
3630
3631    r->Start();
3632    EXPECT_TRUE(r->is_pending());
3633
3634    base::RunLoop().Run();
3635
3636    EXPECT_EQ(1, d.response_started_count());
3637    EXPECT_FALSE(d.received_data_before_response());
3638    EXPECT_NE(0, d.bytes_received());
3639    EXPECT_EQ(test_server_.host_port_pair().host(),
3640              r->GetSocketAddress().host());
3641    EXPECT_EQ(test_server_.host_port_pair().port(),
3642              r->GetSocketAddress().port());
3643  }
3644}
3645
3646TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
3647  ASSERT_TRUE(test_server_.Start());
3648
3649  TestDelegate d;
3650  {
3651    GURL test_url(test_server_.GetURL(std::string()));
3652    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3653        test_url, DEFAULT_PRIORITY, &d, NULL));
3654
3655    HttpRequestHeaders headers;
3656    EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
3657
3658    r->Start();
3659    EXPECT_TRUE(r->is_pending());
3660
3661    base::RunLoop().Run();
3662
3663    EXPECT_EQ(1, d.response_started_count());
3664    EXPECT_FALSE(d.received_data_before_response());
3665    EXPECT_NE(0, d.bytes_received());
3666    EXPECT_EQ(test_server_.host_port_pair().host(),
3667              r->GetSocketAddress().host());
3668    EXPECT_EQ(test_server_.host_port_pair().port(),
3669              r->GetSocketAddress().port());
3670
3671    EXPECT_TRUE(d.have_full_request_headers());
3672    CheckFullRequestHeaders(d.full_request_headers(), test_url);
3673  }
3674}
3675
3676TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
3677  ASSERT_TRUE(test_server_.Start());
3678
3679  TestDelegate d;
3680  {
3681    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3682        test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
3683
3684    r->Start();
3685    EXPECT_TRUE(r->is_pending());
3686
3687    base::RunLoop().Run();
3688
3689    LoadTimingInfo load_timing_info;
3690    r->GetLoadTimingInfo(&load_timing_info);
3691    TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3692
3693    EXPECT_EQ(1, d.response_started_count());
3694    EXPECT_FALSE(d.received_data_before_response());
3695    EXPECT_NE(0, d.bytes_received());
3696    EXPECT_EQ(test_server_.host_port_pair().host(),
3697              r->GetSocketAddress().host());
3698    EXPECT_EQ(test_server_.host_port_pair().port(),
3699              r->GetSocketAddress().port());
3700  }
3701}
3702
3703TEST_F(URLRequestTestHTTP, GetZippedTest) {
3704  ASSERT_TRUE(test_server_.Start());
3705
3706  // Parameter that specifies the Content-Length field in the response:
3707  // C - Compressed length.
3708  // U - Uncompressed length.
3709  // L - Large length (larger than both C & U).
3710  // M - Medium length (between C & U).
3711  // S - Small length (smaller than both C & U).
3712  const char test_parameters[] = "CULMS";
3713  const int num_tests = arraysize(test_parameters)- 1;  // Skip NULL.
3714  // C & U should be OK.
3715  // L & M are larger than the data sent, and show an error.
3716  // S has too little data, but we seem to accept it.
3717  const bool test_expect_success[num_tests] =
3718      { true, true, false, false, true };
3719
3720  for (int i = 0; i < num_tests ; i++) {
3721    TestDelegate d;
3722    {
3723      std::string test_file =
3724          base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
3725                             test_parameters[i]);
3726
3727      TestNetworkDelegate network_delegate;  // Must outlive URLRequest.
3728      TestURLRequestContext context(true);
3729      context.set_network_delegate(&network_delegate);
3730      context.Init();
3731
3732      scoped_ptr<URLRequest> r(context.CreateRequest(
3733          test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d, NULL));
3734      r->Start();
3735      EXPECT_TRUE(r->is_pending());
3736
3737      base::RunLoop().Run();
3738
3739      EXPECT_EQ(1, d.response_started_count());
3740      EXPECT_FALSE(d.received_data_before_response());
3741      VLOG(1) << " Received " << d.bytes_received() << " bytes"
3742              << " status = " << r->status().status()
3743              << " error = " << r->status().error();
3744      if (test_expect_success[i]) {
3745        EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
3746            << " Parameter = \"" << test_file << "\"";
3747      } else {
3748        EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3749        EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
3750            << " Parameter = \"" << test_file << "\"";
3751      }
3752    }
3753  }
3754}
3755
3756TEST_F(URLRequestTestHTTP, HTTPSToHTTPRedirectNoRefererTest) {
3757  ASSERT_TRUE(test_server_.Start());
3758
3759  SpawnedTestServer https_test_server(
3760      SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
3761      base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3762  ASSERT_TRUE(https_test_server.Start());
3763
3764  // An https server is sent a request with an https referer,
3765  // and responds with a redirect to an http url. The http
3766  // server should not be sent the referer.
3767  GURL http_destination = test_server_.GetURL(std::string());
3768  TestDelegate d;
3769  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3770      https_test_server.GetURL("server-redirect?" + http_destination.spec()),
3771      DEFAULT_PRIORITY, &d, NULL));
3772  req->SetReferrer("https://www.referrer.com/");
3773  req->Start();
3774  base::RunLoop().Run();
3775
3776  EXPECT_EQ(1, d.response_started_count());
3777  EXPECT_EQ(1, d.received_redirect_count());
3778  EXPECT_EQ(http_destination, req->url());
3779  EXPECT_EQ(std::string(), req->referrer());
3780}
3781
3782TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
3783  ASSERT_TRUE(test_server_.Start());
3784
3785  GURL destination_url = test_server_.GetURL(std::string());
3786  GURL original_url =
3787      test_server_.GetURL("server-redirect?" + destination_url.spec());
3788  TestDelegate d;
3789  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3790      original_url, DEFAULT_PRIORITY, &d, NULL));
3791  req->Start();
3792  base::RunLoop().Run();
3793
3794  EXPECT_EQ(1, d.response_started_count());
3795  EXPECT_EQ(1, d.received_redirect_count());
3796  EXPECT_EQ(destination_url, req->url());
3797  EXPECT_EQ(original_url, req->original_url());
3798  ASSERT_EQ(2U, req->url_chain().size());
3799  EXPECT_EQ(original_url, req->url_chain()[0]);
3800  EXPECT_EQ(destination_url, req->url_chain()[1]);
3801
3802  LoadTimingInfo load_timing_info_before_redirect;
3803  EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
3804      &load_timing_info_before_redirect));
3805  TestLoadTimingNotReused(load_timing_info_before_redirect,
3806                          CONNECT_TIMING_HAS_DNS_TIMES);
3807
3808  LoadTimingInfo load_timing_info;
3809  req->GetLoadTimingInfo(&load_timing_info);
3810  TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3811
3812  // Check that a new socket was used on redirect, since the server does not
3813  // supposed keep-alive sockets, and that the times before the redirect are
3814  // before the ones recorded for the second request.
3815  EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
3816            load_timing_info.socket_log_id);
3817  EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
3818            load_timing_info.connect_timing.connect_start);
3819}
3820
3821TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
3822  ASSERT_TRUE(test_server_.Start());
3823
3824  GURL destination_url = test_server_.GetURL(std::string());
3825  GURL middle_redirect_url =
3826      test_server_.GetURL("server-redirect?" + destination_url.spec());
3827  GURL original_url = test_server_.GetURL(
3828      "server-redirect?" + middle_redirect_url.spec());
3829  TestDelegate d;
3830  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3831      original_url, DEFAULT_PRIORITY, &d, NULL));
3832  req->Start();
3833  base::RunLoop().Run();
3834
3835  EXPECT_EQ(1, d.response_started_count());
3836  EXPECT_EQ(2, d.received_redirect_count());
3837  EXPECT_EQ(destination_url, req->url());
3838  EXPECT_EQ(original_url, req->original_url());
3839  ASSERT_EQ(3U, req->url_chain().size());
3840  EXPECT_EQ(original_url, req->url_chain()[0]);
3841  EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
3842  EXPECT_EQ(destination_url, req->url_chain()[2]);
3843}
3844
3845// First and second pieces of information logged by delegates to URLRequests.
3846const char kFirstDelegateInfo[] = "Wonderful delegate";
3847const char kSecondDelegateInfo[] = "Exciting delegate";
3848
3849// Logs delegate information to a URLRequest.  The first string is logged
3850// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY.  The second is
3851// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER.  Then
3852// another asynchronous call is used to clear the delegate information
3853// before calling a callback.  The object then deletes itself.
3854class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
3855 public:
3856  typedef base::Callback<void()> Callback;
3857
3858  // Each time delegate information is added to the URLRequest, the resulting
3859  // load state is checked.  The expected load state after each request is
3860  // passed in as an argument.
3861  static void Run(URLRequest* url_request,
3862                  LoadState expected_first_load_state,
3863                  LoadState expected_second_load_state,
3864                  LoadState expected_third_load_state,
3865                  const Callback& callback) {
3866    AsyncDelegateLogger* logger = new AsyncDelegateLogger(
3867        url_request,
3868        expected_first_load_state,
3869        expected_second_load_state,
3870        expected_third_load_state,
3871        callback);
3872    logger->Start();
3873  }
3874
3875  // Checks that the log entries, starting with log_position, contain the
3876  // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
3877  // recorded.  Returns the index of entry after the expected number of
3878  // events this logged, or entries.size() if there aren't enough entries.
3879  static size_t CheckDelegateInfo(
3880      const CapturingNetLog::CapturedEntryList& entries, size_t log_position) {
3881    // There should be 4 DELEGATE_INFO events: Two begins and two ends.
3882    if (log_position + 3 >= entries.size()) {
3883      ADD_FAILURE() << "Not enough log entries";
3884      return entries.size();
3885    }
3886    std::string delegate_info;
3887    EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3888    EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3889    EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3890                                                     &delegate_info));
3891    EXPECT_EQ(kFirstDelegateInfo, delegate_info);
3892
3893    ++log_position;
3894    EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3895    EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3896
3897    ++log_position;
3898    EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3899    EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3900    EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3901                                                     &delegate_info));
3902    EXPECT_EQ(kSecondDelegateInfo, delegate_info);
3903
3904    ++log_position;
3905    EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3906    EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3907
3908    return log_position + 1;
3909  }
3910
3911  // Find delegate request begin and end messages for OnBeforeNetworkStart.
3912  // Returns the position of the end message.
3913  static size_t ExpectBeforeNetworkEvents(
3914      const CapturingNetLog::CapturedEntryList& entries,
3915      size_t log_position) {
3916    log_position =
3917        ExpectLogContainsSomewhereAfter(entries,
3918                                        log_position,
3919                                        NetLog::TYPE_URL_REQUEST_DELEGATE,
3920                                        NetLog::PHASE_BEGIN);
3921    EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
3922              entries[log_position + 1].type);
3923    EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
3924    return log_position + 1;
3925  }
3926
3927 private:
3928  friend class base::RefCounted<AsyncDelegateLogger>;
3929
3930  AsyncDelegateLogger(URLRequest* url_request,
3931                      LoadState expected_first_load_state,
3932                      LoadState expected_second_load_state,
3933                      LoadState expected_third_load_state,
3934                      const Callback& callback)
3935      : url_request_(url_request),
3936        expected_first_load_state_(expected_first_load_state),
3937        expected_second_load_state_(expected_second_load_state),
3938        expected_third_load_state_(expected_third_load_state),
3939        callback_(callback) {
3940  }
3941
3942  ~AsyncDelegateLogger() {}
3943
3944  void Start() {
3945    url_request_->LogBlockedBy(kFirstDelegateInfo);
3946    LoadStateWithParam load_state = url_request_->GetLoadState();
3947    EXPECT_EQ(expected_first_load_state_, load_state.state);
3948    EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
3949    base::MessageLoop::current()->PostTask(
3950        FROM_HERE,
3951        base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
3952  }
3953
3954  void LogSecondDelegate() {
3955    url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
3956    LoadStateWithParam load_state = url_request_->GetLoadState();
3957    EXPECT_EQ(expected_second_load_state_, load_state.state);
3958    if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
3959      EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3960    } else {
3961      EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3962    }
3963    base::MessageLoop::current()->PostTask(
3964        FROM_HERE,
3965        base::Bind(&AsyncDelegateLogger::LogComplete, this));
3966  }
3967
3968  void LogComplete() {
3969    url_request_->LogUnblocked();
3970    LoadStateWithParam load_state = url_request_->GetLoadState();
3971    EXPECT_EQ(expected_third_load_state_, load_state.state);
3972    if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
3973      EXPECT_EQ(base::string16(), load_state.param);
3974    callback_.Run();
3975  }
3976
3977  URLRequest* url_request_;
3978  const int expected_first_load_state_;
3979  const int expected_second_load_state_;
3980  const int expected_third_load_state_;
3981  const Callback callback_;
3982
3983  DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
3984};
3985
3986// NetworkDelegate that logs delegate information before a request is started,
3987// before headers are sent, when headers are read, and when auth information
3988// is requested.  Uses AsyncDelegateLogger.
3989class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
3990 public:
3991  AsyncLoggingNetworkDelegate() {}
3992  virtual ~AsyncLoggingNetworkDelegate() {}
3993
3994  // NetworkDelegate implementation.
3995  virtual int OnBeforeURLRequest(URLRequest* request,
3996                                 const CompletionCallback& callback,
3997                                 GURL* new_url) OVERRIDE {
3998    TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
3999    return RunCallbackAsynchronously(request, callback);
4000  }
4001
4002  virtual int OnBeforeSendHeaders(URLRequest* request,
4003                                  const CompletionCallback& callback,
4004                                  HttpRequestHeaders* headers) OVERRIDE {
4005    TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4006    return RunCallbackAsynchronously(request, callback);
4007  }
4008
4009  virtual int OnHeadersReceived(
4010      URLRequest* request,
4011      const CompletionCallback& callback,
4012      const HttpResponseHeaders* original_response_headers,
4013      scoped_refptr<HttpResponseHeaders>* override_response_headers,
4014      GURL* allowed_unsafe_redirect_url) OVERRIDE {
4015    TestNetworkDelegate::OnHeadersReceived(request,
4016                                           callback,
4017                                           original_response_headers,
4018                                           override_response_headers,
4019                                           allowed_unsafe_redirect_url);
4020    return RunCallbackAsynchronously(request, callback);
4021  }
4022
4023  virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
4024      URLRequest* request,
4025      const AuthChallengeInfo& auth_info,
4026      const AuthCallback& callback,
4027      AuthCredentials* credentials) OVERRIDE {
4028    AsyncDelegateLogger::Run(
4029        request,
4030        LOAD_STATE_WAITING_FOR_DELEGATE,
4031        LOAD_STATE_WAITING_FOR_DELEGATE,
4032        LOAD_STATE_WAITING_FOR_DELEGATE,
4033        base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4034                   callback, credentials));
4035    return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4036  }
4037
4038 private:
4039  static int RunCallbackAsynchronously(
4040      URLRequest* request,
4041      const CompletionCallback& callback) {
4042    AsyncDelegateLogger::Run(
4043        request,
4044        LOAD_STATE_WAITING_FOR_DELEGATE,
4045        LOAD_STATE_WAITING_FOR_DELEGATE,
4046        LOAD_STATE_WAITING_FOR_DELEGATE,
4047        base::Bind(callback, OK));
4048    return ERR_IO_PENDING;
4049  }
4050
4051  static void SetAuthAndResume(const AuthCallback& callback,
4052                               AuthCredentials* credentials) {
4053    *credentials = AuthCredentials(kUser, kSecret);
4054    callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4055  }
4056
4057  DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4058};
4059
4060// URLRequest::Delegate that logs delegate information when the headers
4061// are received, when each read completes, and during redirects.  Uses
4062// AsyncDelegateLogger.  Can optionally cancel a request in any phase.
4063//
4064// Inherits from TestDelegate to reuse the TestDelegate code to handle
4065// advancing to the next step in most cases, as well as cancellation.
4066class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4067 public:
4068  enum CancelStage {
4069    NO_CANCEL = 0,
4070    CANCEL_ON_RECEIVED_REDIRECT,
4071    CANCEL_ON_RESPONSE_STARTED,
4072    CANCEL_ON_READ_COMPLETED
4073  };
4074
4075  explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4076      : cancel_stage_(cancel_stage) {
4077    if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4078      set_cancel_in_received_redirect(true);
4079    else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4080      set_cancel_in_response_started(true);
4081    else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4082      set_cancel_in_received_data(true);
4083  }
4084  virtual ~AsyncLoggingUrlRequestDelegate() {}
4085
4086  // URLRequest::Delegate implementation:
4087  void virtual OnReceivedRedirect(URLRequest* request,
4088                                  const RedirectInfo& redirect_info,
4089                                  bool* defer_redirect) OVERRIDE {
4090    *defer_redirect = true;
4091    AsyncDelegateLogger::Run(
4092        request,
4093        LOAD_STATE_WAITING_FOR_DELEGATE,
4094        LOAD_STATE_WAITING_FOR_DELEGATE,
4095        LOAD_STATE_WAITING_FOR_DELEGATE,
4096        base::Bind(
4097            &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
4098            base::Unretained(this), request, redirect_info));
4099  }
4100
4101  virtual void OnResponseStarted(URLRequest* request) OVERRIDE {
4102    AsyncDelegateLogger::Run(
4103      request,
4104      LOAD_STATE_WAITING_FOR_DELEGATE,
4105      LOAD_STATE_WAITING_FOR_DELEGATE,
4106      LOAD_STATE_WAITING_FOR_DELEGATE,
4107      base::Bind(
4108          &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4109          base::Unretained(this), request));
4110  }
4111
4112  virtual void OnReadCompleted(URLRequest* request,
4113                               int bytes_read) OVERRIDE {
4114    AsyncDelegateLogger::Run(
4115        request,
4116        LOAD_STATE_IDLE,
4117        LOAD_STATE_IDLE,
4118        LOAD_STATE_IDLE,
4119        base::Bind(
4120            &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4121            base::Unretained(this), request, bytes_read));
4122  }
4123
4124 private:
4125  void OnReceivedRedirectLoggingComplete(URLRequest* request,
4126                                         const RedirectInfo& redirect_info) {
4127    bool defer_redirect = false;
4128    TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
4129    // FollowDeferredRedirect should not be called after cancellation.
4130    if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4131      return;
4132    if (!defer_redirect)
4133      request->FollowDeferredRedirect();
4134  }
4135
4136  void OnResponseStartedLoggingComplete(URLRequest* request) {
4137    // The parent class continues the request.
4138    TestDelegate::OnResponseStarted(request);
4139  }
4140
4141  void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4142    // The parent class continues the request.
4143    TestDelegate::OnReadCompleted(request, bytes_read);
4144  }
4145
4146  const CancelStage cancel_stage_;
4147
4148  DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4149};
4150
4151// Tests handling of delegate info before a request starts.
4152TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4153  ASSERT_TRUE(test_server_.Start());
4154
4155  TestDelegate request_delegate;
4156  TestURLRequestContext context(true);
4157  context.set_network_delegate(NULL);
4158  context.set_net_log(&net_log_);
4159  context.Init();
4160
4161  {
4162    scoped_ptr<URLRequest> r(context.CreateRequest(
4163        test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &request_delegate,
4164        NULL));
4165    LoadStateWithParam load_state = r->GetLoadState();
4166    EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4167    EXPECT_EQ(base::string16(), load_state.param);
4168
4169    AsyncDelegateLogger::Run(
4170        r.get(),
4171        LOAD_STATE_WAITING_FOR_DELEGATE,
4172        LOAD_STATE_WAITING_FOR_DELEGATE,
4173        LOAD_STATE_IDLE,
4174        base::Bind(&URLRequest::Start, base::Unretained(r.get())));
4175
4176    base::RunLoop().Run();
4177
4178    EXPECT_EQ(200, r->GetResponseCode());
4179    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4180  }
4181
4182  CapturingNetLog::CapturedEntryList entries;
4183  net_log_.GetEntries(&entries);
4184  size_t log_position = ExpectLogContainsSomewhereAfter(
4185      entries,
4186      0,
4187      NetLog::TYPE_DELEGATE_INFO,
4188      NetLog::PHASE_BEGIN);
4189
4190  log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4191
4192  // Nothing else should add any delegate info to the request.
4193  EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4194      entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4195}
4196
4197// Tests handling of delegate info from a network delegate.
4198TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4199  ASSERT_TRUE(test_server_.Start());
4200
4201  TestDelegate request_delegate;
4202  AsyncLoggingNetworkDelegate network_delegate;
4203  TestURLRequestContext context(true);
4204  context.set_network_delegate(&network_delegate);
4205  context.set_net_log(&net_log_);
4206  context.Init();
4207
4208  {
4209    scoped_ptr<URLRequest> r(context.CreateRequest(
4210        test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &request_delegate,
4211        NULL));
4212    LoadStateWithParam load_state = r->GetLoadState();
4213    EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4214    EXPECT_EQ(base::string16(), load_state.param);
4215
4216    r->Start();
4217    base::RunLoop().Run();
4218
4219    EXPECT_EQ(200, r->GetResponseCode());
4220    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4221    EXPECT_EQ(1, network_delegate.created_requests());
4222    EXPECT_EQ(0, network_delegate.destroyed_requests());
4223  }
4224  EXPECT_EQ(1, network_delegate.destroyed_requests());
4225
4226  size_t log_position = 0;
4227  CapturingNetLog::CapturedEntryList entries;
4228  net_log_.GetEntries(&entries);
4229  for (size_t i = 0; i < 3; ++i) {
4230    log_position = ExpectLogContainsSomewhereAfter(
4231        entries,
4232        log_position + 1,
4233        NetLog::TYPE_URL_REQUEST_DELEGATE,
4234        NetLog::PHASE_BEGIN);
4235
4236    log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4237                                                          log_position + 1);
4238
4239    ASSERT_LT(log_position, entries.size());
4240    EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4241    EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4242
4243    if (i == 1) {
4244      log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4245          entries, log_position + 1);
4246    }
4247  }
4248
4249  EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4250      entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4251}
4252
4253// Tests handling of delegate info from a network delegate in the case of an
4254// HTTP redirect.
4255TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4256  ASSERT_TRUE(test_server_.Start());
4257
4258  TestDelegate request_delegate;
4259  AsyncLoggingNetworkDelegate network_delegate;
4260  TestURLRequestContext context(true);
4261  context.set_network_delegate(&network_delegate);
4262  context.set_net_log(&net_log_);
4263  context.Init();
4264
4265  {
4266    scoped_ptr<URLRequest> r(context.CreateRequest(
4267        test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
4268        &request_delegate, NULL));
4269    LoadStateWithParam load_state = r->GetLoadState();
4270    EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4271    EXPECT_EQ(base::string16(), load_state.param);
4272
4273    r->Start();
4274    base::RunLoop().Run();
4275
4276    EXPECT_EQ(200, r->GetResponseCode());
4277    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4278    EXPECT_EQ(2, network_delegate.created_requests());
4279    EXPECT_EQ(0, network_delegate.destroyed_requests());
4280  }
4281  EXPECT_EQ(1, network_delegate.destroyed_requests());
4282
4283  size_t log_position = 0;
4284  CapturingNetLog::CapturedEntryList entries;
4285  net_log_.GetEntries(&entries);
4286  // The NetworkDelegate logged information in OnBeforeURLRequest,
4287  // OnBeforeSendHeaders, and OnHeadersReceived.
4288  for (size_t i = 0; i < 3; ++i) {
4289    log_position = ExpectLogContainsSomewhereAfter(
4290        entries,
4291        log_position + 1,
4292        NetLog::TYPE_URL_REQUEST_DELEGATE,
4293        NetLog::PHASE_BEGIN);
4294
4295    log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4296                                                          log_position + 1);
4297
4298    ASSERT_LT(log_position, entries.size());
4299    EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4300    EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4301
4302    if (i == 1) {
4303      log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4304          entries, log_position + 1);
4305    }
4306  }
4307
4308  // The URLRequest::Delegate then gets informed about the redirect.
4309  log_position = ExpectLogContainsSomewhereAfter(
4310      entries,
4311      log_position + 1,
4312      NetLog::TYPE_URL_REQUEST_DELEGATE,
4313      NetLog::PHASE_BEGIN);
4314
4315  // The NetworkDelegate logged information in the same three events as before.
4316  for (size_t i = 0; i < 3; ++i) {
4317    log_position = ExpectLogContainsSomewhereAfter(
4318        entries,
4319        log_position + 1,
4320        NetLog::TYPE_URL_REQUEST_DELEGATE,
4321        NetLog::PHASE_BEGIN);
4322
4323    log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4324                                                          log_position + 1);
4325
4326    ASSERT_LT(log_position, entries.size());
4327    EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4328    EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4329  }
4330
4331  EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4332      entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4333}
4334
4335// Tests handling of delegate info from a network delegate in the case of HTTP
4336// AUTH.
4337TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4338  ASSERT_TRUE(test_server_.Start());
4339
4340  TestDelegate request_delegate;
4341  AsyncLoggingNetworkDelegate network_delegate;
4342  TestURLRequestContext context(true);
4343  context.set_network_delegate(&network_delegate);
4344  context.set_net_log(&net_log_);
4345  context.Init();
4346
4347  {
4348    scoped_ptr<URLRequest> r(context.CreateRequest(
4349        test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &request_delegate,
4350        NULL));
4351    LoadStateWithParam load_state = r->GetLoadState();
4352    EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4353    EXPECT_EQ(base::string16(), load_state.param);
4354
4355    r->Start();
4356    base::RunLoop().Run();
4357
4358    EXPECT_EQ(200, r->GetResponseCode());
4359    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4360    EXPECT_EQ(1, network_delegate.created_requests());
4361    EXPECT_EQ(0, network_delegate.destroyed_requests());
4362  }
4363  EXPECT_EQ(1, network_delegate.destroyed_requests());
4364
4365  size_t log_position = 0;
4366  CapturingNetLog::CapturedEntryList entries;
4367  net_log_.GetEntries(&entries);
4368  // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4369  // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4370  // OnBeforeURLRequest and OnBeforeSendHeaders.
4371  for (size_t i = 0; i < 6; ++i) {
4372    log_position = ExpectLogContainsSomewhereAfter(
4373        entries,
4374        log_position + 1,
4375        NetLog::TYPE_URL_REQUEST_DELEGATE,
4376        NetLog::PHASE_BEGIN);
4377
4378    log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4379                                                          log_position + 1);
4380
4381    ASSERT_LT(log_position, entries.size());
4382    EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4383    EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4384
4385    if (i == 1) {
4386      log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4387          entries, log_position + 1);
4388    }
4389  }
4390
4391  EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4392      entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4393}
4394
4395// Tests handling of delegate info from a URLRequest::Delegate.
4396TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4397  ASSERT_TRUE(test_server_.Start());
4398
4399  AsyncLoggingUrlRequestDelegate request_delegate(
4400      AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4401  TestURLRequestContext context(true);
4402  context.set_network_delegate(NULL);
4403  context.set_net_log(&net_log_);
4404  context.Init();
4405
4406  {
4407    // A chunked response with delays between chunks is used to make sure that
4408    // attempts by the URLRequest delegate to log information while reading the
4409    // body are ignored.  Since they are ignored, this test is robust against
4410    // the possibility of multiple reads being combined in the unlikely event
4411    // that it occurs.
4412    scoped_ptr<URLRequest> r(context.CreateRequest(
4413        test_server_.GetURL("chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
4414        &request_delegate, NULL));
4415    LoadStateWithParam load_state = r->GetLoadState();
4416    r->Start();
4417    base::RunLoop().Run();
4418
4419    EXPECT_EQ(200, r->GetResponseCode());
4420    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4421  }
4422
4423  CapturingNetLog::CapturedEntryList entries;
4424  net_log_.GetEntries(&entries);
4425
4426  size_t log_position = 0;
4427
4428  log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4429      entries, log_position);
4430
4431  // The delegate info should only have been logged on header complete.  Other
4432  // times it should silently be ignored.
4433  log_position =
4434      ExpectLogContainsSomewhereAfter(entries,
4435                                      log_position + 1,
4436                                      NetLog::TYPE_URL_REQUEST_DELEGATE,
4437                                      NetLog::PHASE_BEGIN);
4438
4439  log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4440                                                        log_position + 1);
4441
4442  ASSERT_LT(log_position, entries.size());
4443  EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4444  EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4445
4446  EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4447      entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4448  EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4449      entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4450}
4451
4452// Tests handling of delegate info from a URLRequest::Delegate in the case of
4453// an HTTP redirect.
4454TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4455  ASSERT_TRUE(test_server_.Start());
4456
4457  AsyncLoggingUrlRequestDelegate request_delegate(
4458      AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4459  TestURLRequestContext context(true);
4460  context.set_network_delegate(NULL);
4461  context.set_net_log(&net_log_);
4462  context.Init();
4463
4464  {
4465    scoped_ptr<URLRequest> r(context.CreateRequest(
4466        test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
4467        &request_delegate, NULL));
4468    LoadStateWithParam load_state = r->GetLoadState();
4469    r->Start();
4470    base::RunLoop().Run();
4471
4472    EXPECT_EQ(200, r->GetResponseCode());
4473    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4474  }
4475
4476  CapturingNetLog::CapturedEntryList entries;
4477  net_log_.GetEntries(&entries);
4478
4479  // Delegate info should only have been logged in OnReceivedRedirect and
4480  // OnResponseStarted.
4481  size_t log_position = 0;
4482  for (int i = 0; i < 2; ++i) {
4483    if (i == 0) {
4484      log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4485                         entries, log_position) + 1;
4486    }
4487
4488    log_position = ExpectLogContainsSomewhereAfter(
4489            entries,
4490            log_position,
4491            NetLog::TYPE_URL_REQUEST_DELEGATE,
4492            NetLog::PHASE_BEGIN);
4493
4494    log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4495                                                          log_position + 1);
4496
4497    ASSERT_LT(log_position, entries.size());
4498    EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4499    EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4500  }
4501
4502  EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4503      entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4504  EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4505      entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4506}
4507
4508// Tests handling of delegate info from a URLRequest::Delegate in the case of
4509// an HTTP redirect, with cancellation at various points.
4510TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4511  ASSERT_TRUE(test_server_.Start());
4512
4513  const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4514    AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4515    AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4516    AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4517  };
4518
4519  for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4520       ++test_case) {
4521    AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4522    TestURLRequestContext context(true);
4523    CapturingNetLog net_log;
4524    context.set_network_delegate(NULL);
4525    context.set_net_log(&net_log);
4526    context.Init();
4527
4528    {
4529      scoped_ptr<URLRequest> r(context.CreateRequest(
4530          test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
4531          &request_delegate, NULL));
4532      LoadStateWithParam load_state = r->GetLoadState();
4533      r->Start();
4534      base::RunLoop().Run();
4535      EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4536    }
4537
4538    CapturingNetLog::CapturedEntryList entries;
4539    net_log.GetEntries(&entries);
4540
4541    // Delegate info is always logged in both OnReceivedRedirect and
4542    // OnResponseStarted.  In the CANCEL_ON_RECEIVED_REDIRECT, the
4543    // OnResponseStarted delegate call is after cancellation, but logging is
4544    // still currently supported in that call.
4545    size_t log_position = 0;
4546    for (int i = 0; i < 2; ++i) {
4547      if (i == 0) {
4548        log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4549                           entries, log_position) + 1;
4550      }
4551
4552      log_position = ExpectLogContainsSomewhereAfter(
4553              entries,
4554              log_position,
4555              NetLog::TYPE_URL_REQUEST_DELEGATE,
4556              NetLog::PHASE_BEGIN);
4557
4558      log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4559                                                            log_position + 1);
4560
4561      ASSERT_LT(log_position, entries.size());
4562      EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4563      EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4564    }
4565
4566    EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4567        entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4568    EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4569        entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4570  }
4571}
4572
4573namespace {
4574
4575const char kExtraHeader[] = "Allow-Snafu";
4576const char kExtraValue[] = "fubar";
4577
4578class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
4579  virtual void OnReceivedRedirect(URLRequest* request,
4580                                  const RedirectInfo& redirect_info,
4581                                  bool* defer_redirect) OVERRIDE {
4582    TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
4583    request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
4584  }
4585};
4586
4587}  // namespace
4588
4589TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
4590  ASSERT_TRUE(test_server_.Start());
4591
4592  GURL destination_url = test_server_.GetURL(
4593      "echoheader?" + std::string(kExtraHeader));
4594  GURL original_url = test_server_.GetURL(
4595      "server-redirect?" + destination_url.spec());
4596  RedirectWithAdditionalHeadersDelegate d;
4597  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
4598      original_url, DEFAULT_PRIORITY, &d, NULL));
4599  req->Start();
4600  base::RunLoop().Run();
4601
4602  std::string value;
4603  const HttpRequestHeaders& headers = req->extra_request_headers();
4604  EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
4605  EXPECT_EQ(kExtraValue, value);
4606  EXPECT_FALSE(req->is_pending());
4607  EXPECT_FALSE(req->is_redirecting());
4608  EXPECT_EQ(kExtraValue, d.data_received());
4609}
4610
4611namespace {
4612
4613const char kExtraHeaderToRemove[] = "To-Be-Removed";
4614
4615class RedirectWithHeaderRemovalDelegate : public TestDelegate {
4616  virtual void OnReceivedRedirect(URLRequest* request,
4617                                  const RedirectInfo& redirect_info,
4618                                  bool* defer_redirect) OVERRIDE {
4619    TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
4620    request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
4621  }
4622};
4623
4624}  // namespace
4625
4626TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
4627  ASSERT_TRUE(test_server_.Start());
4628
4629  GURL destination_url = test_server_.GetURL(
4630      "echoheader?" + std::string(kExtraHeaderToRemove));
4631  GURL original_url = test_server_.GetURL(
4632      "server-redirect?" + destination_url.spec());
4633  RedirectWithHeaderRemovalDelegate d;
4634  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
4635      original_url, DEFAULT_PRIORITY, &d, NULL));
4636  req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
4637  req->Start();
4638  base::RunLoop().Run();
4639
4640  std::string value;
4641  const HttpRequestHeaders& headers = req->extra_request_headers();
4642  EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
4643  EXPECT_FALSE(req->is_pending());
4644  EXPECT_FALSE(req->is_redirecting());
4645  EXPECT_EQ("None", d.data_received());
4646}
4647
4648TEST_F(URLRequestTestHTTP, CancelTest) {
4649  TestDelegate d;
4650  {
4651    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4652        GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d, NULL));
4653
4654    r->Start();
4655    EXPECT_TRUE(r->is_pending());
4656
4657    r->Cancel();
4658
4659    base::RunLoop().Run();
4660
4661    // We expect to receive OnResponseStarted even though the request has been
4662    // cancelled.
4663    EXPECT_EQ(1, d.response_started_count());
4664    EXPECT_EQ(0, d.bytes_received());
4665    EXPECT_FALSE(d.received_data_before_response());
4666  }
4667}
4668
4669TEST_F(URLRequestTestHTTP, CancelTest2) {
4670  ASSERT_TRUE(test_server_.Start());
4671
4672  TestDelegate d;
4673  {
4674    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4675        test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4676
4677    d.set_cancel_in_response_started(true);
4678
4679    r->Start();
4680    EXPECT_TRUE(r->is_pending());
4681
4682    base::RunLoop().Run();
4683
4684    EXPECT_EQ(1, d.response_started_count());
4685    EXPECT_EQ(0, d.bytes_received());
4686    EXPECT_FALSE(d.received_data_before_response());
4687    EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4688  }
4689}
4690
4691TEST_F(URLRequestTestHTTP, CancelTest3) {
4692  ASSERT_TRUE(test_server_.Start());
4693
4694  TestDelegate d;
4695  {
4696    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4697        test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4698
4699    d.set_cancel_in_received_data(true);
4700
4701    r->Start();
4702    EXPECT_TRUE(r->is_pending());
4703
4704    base::RunLoop().Run();
4705
4706    EXPECT_EQ(1, d.response_started_count());
4707    // There is no guarantee about how much data was received
4708    // before the cancel was issued.  It could have been 0 bytes,
4709    // or it could have been all the bytes.
4710    // EXPECT_EQ(0, d.bytes_received());
4711    EXPECT_FALSE(d.received_data_before_response());
4712    EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4713  }
4714}
4715
4716TEST_F(URLRequestTestHTTP, CancelTest4) {
4717  ASSERT_TRUE(test_server_.Start());
4718
4719  TestDelegate d;
4720  {
4721    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4722        test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4723
4724    r->Start();
4725    EXPECT_TRUE(r->is_pending());
4726
4727    // The request will be implicitly canceled when it is destroyed. The
4728    // test delegate must not post a quit message when this happens because
4729    // this test doesn't actually have a message loop. The quit message would
4730    // get put on this thread's message queue and the next test would exit
4731    // early, causing problems.
4732    d.set_quit_on_complete(false);
4733  }
4734  // expect things to just cleanup properly.
4735
4736  // we won't actually get a received reponse here because we've never run the
4737  // message loop
4738  EXPECT_FALSE(d.received_data_before_response());
4739  EXPECT_EQ(0, d.bytes_received());
4740}
4741
4742TEST_F(URLRequestTestHTTP, CancelTest5) {
4743  ASSERT_TRUE(test_server_.Start());
4744
4745  // populate cache
4746  {
4747    TestDelegate d;
4748    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4749        test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d, NULL));
4750    r->Start();
4751    base::RunLoop().Run();
4752    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4753  }
4754
4755  // cancel read from cache (see bug 990242)
4756  {
4757    TestDelegate d;
4758    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4759        test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d, NULL));
4760    r->Start();
4761    r->Cancel();
4762    base::RunLoop().Run();
4763
4764    EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4765    EXPECT_EQ(1, d.response_started_count());
4766    EXPECT_EQ(0, d.bytes_received());
4767    EXPECT_FALSE(d.received_data_before_response());
4768  }
4769}
4770
4771TEST_F(URLRequestTestHTTP, PostTest) {
4772  ASSERT_TRUE(test_server_.Start());
4773  HTTPUploadDataOperationTest("POST");
4774}
4775
4776TEST_F(URLRequestTestHTTP, PutTest) {
4777  ASSERT_TRUE(test_server_.Start());
4778  HTTPUploadDataOperationTest("PUT");
4779}
4780
4781TEST_F(URLRequestTestHTTP, PostEmptyTest) {
4782  ASSERT_TRUE(test_server_.Start());
4783
4784  TestDelegate d;
4785  {
4786    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4787        test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
4788    r->set_method("POST");
4789
4790    r->Start();
4791    EXPECT_TRUE(r->is_pending());
4792
4793    base::RunLoop().Run();
4794
4795    ASSERT_EQ(1, d.response_started_count())
4796        << "request failed: " << r->status().status()
4797        << ", error: " << r->status().error();
4798
4799    EXPECT_FALSE(d.received_data_before_response());
4800    EXPECT_TRUE(d.data_received().empty());
4801  }
4802}
4803
4804TEST_F(URLRequestTestHTTP, PostFileTest) {
4805  ASSERT_TRUE(test_server_.Start());
4806
4807  TestDelegate d;
4808  {
4809    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4810        test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
4811    r->set_method("POST");
4812
4813    base::FilePath dir;
4814    PathService::Get(base::DIR_EXE, &dir);
4815    base::SetCurrentDirectory(dir);
4816
4817    ScopedVector<UploadElementReader> element_readers;
4818
4819    base::FilePath path;
4820    PathService::Get(base::DIR_SOURCE_ROOT, &path);
4821    path = path.Append(FILE_PATH_LITERAL("net"));
4822    path = path.Append(FILE_PATH_LITERAL("data"));
4823    path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
4824    path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
4825    element_readers.push_back(
4826        new UploadFileElementReader(base::MessageLoopProxy::current().get(),
4827                                    path,
4828                                    0,
4829                                    kuint64max,
4830                                    base::Time()));
4831    r->set_upload(make_scoped_ptr(
4832        new UploadDataStream(element_readers.Pass(), 0)));
4833
4834    r->Start();
4835    EXPECT_TRUE(r->is_pending());
4836
4837    base::RunLoop().Run();
4838
4839    int64 size = 0;
4840    ASSERT_EQ(true, base::GetFileSize(path, &size));
4841    scoped_ptr<char[]> buf(new char[size]);
4842
4843    ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
4844
4845    ASSERT_EQ(1, d.response_started_count())
4846        << "request failed: " << r->status().status()
4847        << ", error: " << r->status().error();
4848
4849    EXPECT_FALSE(d.received_data_before_response());
4850
4851    EXPECT_EQ(size, d.bytes_received());
4852    EXPECT_EQ(std::string(&buf[0], size), d.data_received());
4853  }
4854}
4855
4856TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
4857  ASSERT_TRUE(test_server_.Start());
4858
4859  TestDelegate d;
4860  {
4861    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4862        test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
4863    r->set_method("POST");
4864
4865    ScopedVector<UploadElementReader> element_readers;
4866
4867    element_readers.push_back(new UploadFileElementReader(
4868        base::MessageLoopProxy::current().get(),
4869        base::FilePath(FILE_PATH_LITERAL(
4870            "c:\\path\\to\\non\\existant\\file.randomness.12345")),
4871        0,
4872        kuint64max,
4873        base::Time()));
4874    r->set_upload(make_scoped_ptr(
4875        new UploadDataStream(element_readers.Pass(), 0)));
4876
4877    r->Start();
4878    EXPECT_TRUE(r->is_pending());
4879
4880    base::RunLoop().Run();
4881
4882    EXPECT_TRUE(d.request_failed());
4883    EXPECT_FALSE(d.received_data_before_response());
4884    EXPECT_EQ(0, d.bytes_received());
4885    EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4886    EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
4887  }
4888}
4889
4890TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
4891  ASSERT_TRUE(test_server_.Start());
4892
4893  TestDelegate d;
4894  {
4895    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4896        test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
4897    r->EnableChunkedUpload();
4898    r->set_method("POST");
4899    AddChunksToUpload(r.get());
4900    r->Start();
4901    EXPECT_TRUE(r->is_pending());
4902
4903    base::RunLoop().Run();
4904
4905    VerifyReceivedDataMatchesChunks(r.get(), &d);
4906  }
4907}
4908
4909TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
4910  ASSERT_TRUE(test_server_.Start());
4911
4912  TestDelegate d;
4913  {
4914    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4915        test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
4916    r->EnableChunkedUpload();
4917    r->set_method("POST");
4918    r->Start();
4919    EXPECT_TRUE(r->is_pending());
4920    AddChunksToUpload(r.get());
4921    base::RunLoop().Run();
4922
4923    VerifyReceivedDataMatchesChunks(r.get(), &d);
4924  }
4925}
4926
4927TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
4928  ASSERT_TRUE(test_server_.Start());
4929
4930  TestDelegate d;
4931  {
4932    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4933        test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
4934    r->EnableChunkedUpload();
4935    r->set_method("POST");
4936    r->Start();
4937    EXPECT_TRUE(r->is_pending());
4938
4939    base::RunLoop().RunUntilIdle();
4940    AddChunksToUpload(r.get());
4941    base::RunLoop().Run();
4942
4943    VerifyReceivedDataMatchesChunks(r.get(), &d);
4944  }
4945}
4946
4947TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
4948  ASSERT_TRUE(test_server_.Start());
4949
4950  TestDelegate d;
4951  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
4952      test_server_.GetURL("files/with-headers.html"), DEFAULT_PRIORITY, &d,
4953      NULL));
4954  req->Start();
4955  base::RunLoop().Run();
4956
4957  const HttpResponseHeaders* headers = req->response_headers();
4958
4959  // Simple sanity check that response_info() accesses the same data.
4960  EXPECT_EQ(headers, req->response_info().headers.get());
4961
4962  std::string header;
4963  EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
4964  EXPECT_EQ("private", header);
4965
4966  header.clear();
4967  EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
4968  EXPECT_EQ("text/html; charset=ISO-8859-1", header);
4969
4970  // The response has two "X-Multiple-Entries" headers.
4971  // This verfies our output has them concatenated together.
4972  header.clear();
4973  EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
4974  EXPECT_EQ("a, b", header);
4975}
4976
4977TEST_F(URLRequestTestHTTP, ProcessSTS) {
4978  SpawnedTestServer::SSLOptions ssl_options;
4979  SpawnedTestServer https_test_server(
4980      SpawnedTestServer::TYPE_HTTPS,
4981      ssl_options,
4982      base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4983  ASSERT_TRUE(https_test_server.Start());
4984
4985  TestDelegate d;
4986  scoped_ptr<URLRequest> request(default_context_.CreateRequest(
4987      https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY, &d,
4988      NULL));
4989  request->Start();
4990  base::RunLoop().Run();
4991
4992  TransportSecurityState* security_state =
4993      default_context_.transport_security_state();
4994  TransportSecurityState::DomainState domain_state;
4995  EXPECT_TRUE(security_state->GetDynamicDomainState(
4996      SpawnedTestServer::kLocalhost, &domain_state));
4997  EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
4998            domain_state.sts.upgrade_mode);
4999  EXPECT_TRUE(domain_state.sts.include_subdomains);
5000  EXPECT_FALSE(domain_state.pkp.include_subdomains);
5001#if defined(OS_ANDROID)
5002  // Android's CertVerifyProc does not (yet) handle pins.
5003#else
5004  EXPECT_FALSE(domain_state.HasPublicKeyPins());
5005#endif
5006}
5007
5008// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5009// reject HPKP headers, and a test setting only HPKP headers will fail (no
5010// DomainState present because header rejected).
5011#if defined(OS_ANDROID)
5012#define MAYBE_ProcessPKP DISABLED_ProcessPKP
5013#else
5014#define MAYBE_ProcessPKP ProcessPKP
5015#endif
5016
5017// Tests that enabling HPKP on a domain does not affect the HSTS
5018// validity/expiration.
5019TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
5020  SpawnedTestServer::SSLOptions ssl_options;
5021  SpawnedTestServer https_test_server(
5022      SpawnedTestServer::TYPE_HTTPS,
5023      ssl_options,
5024      base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5025  ASSERT_TRUE(https_test_server.Start());
5026
5027  TestDelegate d;
5028  scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5029      https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
5030      NULL));
5031  request->Start();
5032  base::RunLoop().Run();
5033
5034  TransportSecurityState* security_state =
5035      default_context_.transport_security_state();
5036  TransportSecurityState::DomainState domain_state;
5037  EXPECT_TRUE(security_state->GetDynamicDomainState(
5038      SpawnedTestServer::kLocalhost, &domain_state));
5039  EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
5040            domain_state.sts.upgrade_mode);
5041  EXPECT_FALSE(domain_state.sts.include_subdomains);
5042  EXPECT_FALSE(domain_state.pkp.include_subdomains);
5043  EXPECT_TRUE(domain_state.HasPublicKeyPins());
5044  EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5045}
5046
5047TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
5048  SpawnedTestServer::SSLOptions ssl_options;
5049  SpawnedTestServer https_test_server(
5050      SpawnedTestServer::TYPE_HTTPS,
5051      ssl_options,
5052      base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5053  ASSERT_TRUE(https_test_server.Start());
5054
5055  TestDelegate d;
5056  scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5057      https_test_server.GetURL("files/hsts-multiple-headers.html"),
5058      DEFAULT_PRIORITY, &d, NULL));
5059  request->Start();
5060  base::RunLoop().Run();
5061
5062  // We should have set parameters from the first header, not the second.
5063  TransportSecurityState* security_state =
5064      default_context_.transport_security_state();
5065  TransportSecurityState::DomainState domain_state;
5066  EXPECT_TRUE(security_state->GetDynamicDomainState(
5067      SpawnedTestServer::kLocalhost, &domain_state));
5068  EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5069            domain_state.sts.upgrade_mode);
5070  EXPECT_FALSE(domain_state.sts.include_subdomains);
5071  EXPECT_FALSE(domain_state.pkp.include_subdomains);
5072}
5073
5074TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
5075  SpawnedTestServer::SSLOptions ssl_options;
5076  SpawnedTestServer https_test_server(
5077      SpawnedTestServer::TYPE_HTTPS,
5078      ssl_options,
5079      base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5080  ASSERT_TRUE(https_test_server.Start());
5081
5082  TestDelegate d;
5083  scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5084      https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
5085      DEFAULT_PRIORITY, &d, NULL));
5086  request->Start();
5087  base::RunLoop().Run();
5088
5089  // We should have set parameters from the first header, not the second.
5090  TransportSecurityState* security_state =
5091      default_context_.transport_security_state();
5092  TransportSecurityState::DomainState domain_state;
5093  EXPECT_TRUE(security_state->GetDynamicDomainState(
5094      SpawnedTestServer::kLocalhost, &domain_state));
5095  EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5096            domain_state.sts.upgrade_mode);
5097#if defined(OS_ANDROID)
5098  // Android's CertVerifyProc does not (yet) handle pins.
5099#else
5100  EXPECT_TRUE(domain_state.HasPublicKeyPins());
5101#endif
5102  EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5103
5104  // Even though there is an HSTS header asserting includeSubdomains, it is
5105  // the *second* such header, and we MUST process only the first.
5106  EXPECT_FALSE(domain_state.sts.include_subdomains);
5107  // includeSubdomains does not occur in the test HPKP header.
5108  EXPECT_FALSE(domain_state.pkp.include_subdomains);
5109}
5110
5111// Tests that when multiple HPKP headers are present, asserting different
5112// policies, that only the first such policy is processed.
5113TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
5114  SpawnedTestServer::SSLOptions ssl_options;
5115  SpawnedTestServer https_test_server(
5116      SpawnedTestServer::TYPE_HTTPS,
5117      ssl_options,
5118      base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5119  ASSERT_TRUE(https_test_server.