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