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