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