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