Update SplitString calls to new form
[chromium-blink-merge.git] / content / browser / loader / resource_dispatcher_host_unittest.cc
blob80d78c508282411331ebbcb5fe9db93c24250cc0
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.
5 #include <vector>
7 #include "base/basictypes.h"
8 #include "base/bind.h"
9 #include "base/command_line.h"
10 #include "base/files/file_path.h"
11 #include "base/files/file_util.h"
12 #include "base/location.h"
13 #include "base/memory/scoped_vector.h"
14 #include "base/memory/shared_memory.h"
15 #include "base/pickle.h"
16 #include "base/run_loop.h"
17 #include "base/single_thread_task_runner.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_split.h"
20 #include "base/thread_task_runner_handle.h"
21 #include "content/browser/browser_thread_impl.h"
22 #include "content/browser/child_process_security_policy_impl.h"
23 #include "content/browser/loader/cross_site_resource_handler.h"
24 #include "content/browser/loader/detachable_resource_handler.h"
25 #include "content/browser/loader/resource_dispatcher_host_impl.h"
26 #include "content/browser/loader/resource_loader.h"
27 #include "content/browser/loader/resource_message_filter.h"
28 #include "content/browser/loader/resource_request_info_impl.h"
29 #include "content/common/appcache_interfaces.h"
30 #include "content/common/child_process_host_impl.h"
31 #include "content/common/resource_messages.h"
32 #include "content/common/view_messages.h"
33 #include "content/public/browser/global_request_id.h"
34 #include "content/public/browser/render_process_host.h"
35 #include "content/public/browser/resource_context.h"
36 #include "content/public/browser/resource_dispatcher_host_delegate.h"
37 #include "content/public/browser/resource_request_info.h"
38 #include "content/public/browser/resource_throttle.h"
39 #include "content/public/browser/web_contents.h"
40 #include "content/public/browser/web_contents_observer.h"
41 #include "content/public/common/child_process_host.h"
42 #include "content/public/common/content_switches.h"
43 #include "content/public/common/process_type.h"
44 #include "content/public/common/resource_response.h"
45 #include "content/public/test/test_browser_context.h"
46 #include "content/public/test/test_browser_thread_bundle.h"
47 #include "content/public/test/test_renderer_host.h"
48 #include "content/test/test_content_browser_client.h"
49 #include "net/base/elements_upload_data_stream.h"
50 #include "net/base/net_errors.h"
51 #include "net/base/request_priority.h"
52 #include "net/base/upload_bytes_element_reader.h"
53 #include "net/http/http_util.h"
54 #include "net/url_request/url_request.h"
55 #include "net/url_request/url_request_context.h"
56 #include "net/url_request/url_request_job.h"
57 #include "net/url_request/url_request_job_factory.h"
58 #include "net/url_request/url_request_simple_job.h"
59 #include "net/url_request/url_request_test_job.h"
60 #include "net/url_request/url_request_test_util.h"
61 #include "storage/browser/blob/shareable_file_reference.h"
62 #include "testing/gtest/include/gtest/gtest.h"
64 // TODO(eroman): Write unit tests for SafeBrowsing that exercise
65 // SafeBrowsingResourceHandler.
67 using storage::ShareableFileReference;
69 namespace content {
71 namespace {
73 // Returns the resource response header structure for this request.
74 void GetResponseHead(const std::vector<IPC::Message>& messages,
75 ResourceResponseHead* response_head) {
76 ASSERT_GE(messages.size(), 2U);
78 // The first messages should be received response.
79 ASSERT_EQ(ResourceMsg_ReceivedResponse::ID, messages[0].type());
81 base::PickleIterator iter(messages[0]);
82 int request_id;
83 ASSERT_TRUE(IPC::ReadParam(&messages[0], &iter, &request_id));
84 ASSERT_TRUE(IPC::ReadParam(&messages[0], &iter, response_head));
87 void GenerateIPCMessage(
88 scoped_refptr<ResourceMessageFilter> filter,
89 scoped_ptr<IPC::Message> message) {
90 ResourceDispatcherHostImpl::Get()->OnMessageReceived(
91 *message, filter.get());
94 // On Windows, ResourceMsg_SetDataBuffer supplies a HANDLE which is not
95 // automatically released.
97 // See ResourceDispatcher::ReleaseResourcesInDataMessage.
99 // TODO(davidben): It would be nice if the behavior for base::SharedMemoryHandle
100 // were more like it is in POSIX where the received fds are tracked in a
101 // ref-counted core that closes them if not extracted.
102 void ReleaseHandlesInMessage(const IPC::Message& message) {
103 if (message.type() == ResourceMsg_SetDataBuffer::ID) {
104 base::PickleIterator iter(message);
105 int request_id;
106 CHECK(iter.ReadInt(&request_id));
107 base::SharedMemoryHandle shm_handle;
108 if (IPC::ParamTraits<base::SharedMemoryHandle>::Read(&message,
109 &iter,
110 &shm_handle)) {
111 if (base::SharedMemory::IsHandleValid(shm_handle))
112 base::SharedMemory::CloseHandle(shm_handle);
117 } // namespace
119 static int RequestIDForMessage(const IPC::Message& msg) {
120 int request_id = -1;
121 switch (msg.type()) {
122 case ResourceMsg_UploadProgress::ID:
123 case ResourceMsg_ReceivedResponse::ID:
124 case ResourceMsg_ReceivedRedirect::ID:
125 case ResourceMsg_SetDataBuffer::ID:
126 case ResourceMsg_DataReceived::ID:
127 case ResourceMsg_DataDownloaded::ID:
128 case ResourceMsg_RequestComplete::ID: {
129 bool result = base::PickleIterator(msg).ReadInt(&request_id);
130 DCHECK(result);
131 break;
134 return request_id;
137 static ResourceHostMsg_Request CreateResourceRequest(const char* method,
138 ResourceType type,
139 const GURL& url) {
140 ResourceHostMsg_Request request;
141 request.method = std::string(method);
142 request.url = url;
143 request.first_party_for_cookies = url; // bypass third-party cookie blocking
144 request.referrer_policy = blink::WebReferrerPolicyDefault;
145 request.load_flags = 0;
146 request.origin_pid = 0;
147 request.resource_type = type;
148 request.request_context = 0;
149 request.appcache_host_id = kAppCacheNoHostId;
150 request.download_to_file = false;
151 request.should_reset_appcache = false;
152 request.is_main_frame = true;
153 request.parent_is_main_frame = false;
154 request.parent_render_frame_id = -1;
155 request.transition_type = ui::PAGE_TRANSITION_LINK;
156 request.allow_download = true;
157 return request;
160 // Spin up the message loop to kick off the request.
161 static void KickOffRequest() {
162 base::MessageLoop::current()->RunUntilIdle();
165 // We may want to move this to a shared space if it is useful for something else
166 class ResourceIPCAccumulator {
167 public:
168 ~ResourceIPCAccumulator() {
169 for (size_t i = 0; i < messages_.size(); i++) {
170 ReleaseHandlesInMessage(messages_[i]);
174 // On Windows, takes ownership of SharedMemoryHandles in |msg|.
175 void AddMessage(const IPC::Message& msg) {
176 messages_.push_back(msg);
179 // This groups the messages by their request ID. The groups will be in order
180 // that the first message for each request ID was received, and the messages
181 // within the groups will be in the order that they appeared.
182 // Note that this clears messages_. The caller takes ownership of any
183 // SharedMemoryHandles in messages placed into |msgs|.
184 typedef std::vector< std::vector<IPC::Message> > ClassifiedMessages;
185 void GetClassifiedMessages(ClassifiedMessages* msgs);
187 private:
188 std::vector<IPC::Message> messages_;
191 // This is very inefficient as a result of repeatedly extracting the ID, use
192 // only for tests!
193 void ResourceIPCAccumulator::GetClassifiedMessages(ClassifiedMessages* msgs) {
194 while (!messages_.empty()) {
195 // Ignore unknown message types as it is valid for code to generated other
196 // IPCs as side-effects that we are not testing here.
197 int cur_id = RequestIDForMessage(messages_[0]);
198 if (cur_id != -1) {
199 std::vector<IPC::Message> cur_requests;
200 cur_requests.push_back(messages_[0]);
201 // find all other messages with this ID
202 for (int i = 1; i < static_cast<int>(messages_.size()); i++) {
203 int id = RequestIDForMessage(messages_[i]);
204 if (id == cur_id) {
205 cur_requests.push_back(messages_[i]);
206 messages_.erase(messages_.begin() + i);
207 i--;
210 msgs->push_back(cur_requests);
212 messages_.erase(messages_.begin());
216 // This is used to create a filter matching a specified child id.
217 class TestFilterSpecifyingChild : public ResourceMessageFilter {
218 public:
219 explicit TestFilterSpecifyingChild(ResourceContext* resource_context,
220 int process_id)
221 : ResourceMessageFilter(
222 process_id,
223 PROCESS_TYPE_RENDERER,
224 NULL,
225 NULL,
226 NULL,
227 NULL,
228 NULL,
229 base::Bind(&TestFilterSpecifyingChild::GetContexts,
230 base::Unretained(this))),
231 resource_context_(resource_context),
232 canceled_(false),
233 received_after_canceled_(0) {
234 set_peer_process_for_testing(base::Process::Current());
237 void set_canceled(bool canceled) { canceled_ = canceled; }
238 int received_after_canceled() const { return received_after_canceled_; }
240 // ResourceMessageFilter override
241 bool Send(IPC::Message* msg) override {
242 // No messages should be received when the process has been canceled.
243 if (canceled_)
244 received_after_canceled_++;
245 ReleaseHandlesInMessage(*msg);
246 delete msg;
247 return true;
250 ResourceContext* resource_context() { return resource_context_; }
252 protected:
253 ~TestFilterSpecifyingChild() override {}
255 private:
256 void GetContexts(const ResourceHostMsg_Request& request,
257 ResourceContext** resource_context,
258 net::URLRequestContext** request_context) {
259 *resource_context = resource_context_;
260 *request_context = resource_context_->GetRequestContext();
263 ResourceContext* resource_context_;
264 bool canceled_;
265 int received_after_canceled_;
267 DISALLOW_COPY_AND_ASSIGN(TestFilterSpecifyingChild);
270 class TestFilter : public TestFilterSpecifyingChild {
271 public:
272 explicit TestFilter(ResourceContext* resource_context)
273 : TestFilterSpecifyingChild(
274 resource_context,
275 ChildProcessHostImpl::GenerateChildProcessUniqueId()) {
276 ChildProcessSecurityPolicyImpl::GetInstance()->Add(child_id());
279 protected:
280 ~TestFilter() override {
281 ChildProcessSecurityPolicyImpl::GetInstance()->Remove(child_id());
285 // This class forwards the incoming messages to the ResourceDispatcherHostTest.
286 // For the test, we want all the incoming messages to go to the same place,
287 // which is why this forwards.
288 class ForwardingFilter : public TestFilter {
289 public:
290 explicit ForwardingFilter(IPC::Sender* dest,
291 ResourceContext* resource_context)
292 : TestFilter(resource_context),
293 dest_(dest) {
296 // TestFilter override
297 bool Send(IPC::Message* msg) override { return dest_->Send(msg); }
299 private:
300 ~ForwardingFilter() override {}
302 IPC::Sender* dest_;
304 DISALLOW_COPY_AND_ASSIGN(ForwardingFilter);
307 // This class is a variation on URLRequestTestJob that will call
308 // URLRequest::WillStartUsingNetwork before starting.
309 class URLRequestTestDelayedNetworkJob : public net::URLRequestTestJob {
310 public:
311 URLRequestTestDelayedNetworkJob(net::URLRequest* request,
312 net::NetworkDelegate* network_delegate)
313 : net::URLRequestTestJob(request, network_delegate) {}
315 // Only start if not deferred for network start.
316 void Start() override {
317 bool defer = false;
318 NotifyBeforeNetworkStart(&defer);
319 if (defer)
320 return;
321 net::URLRequestTestJob::Start();
324 void ResumeNetworkStart() override { net::URLRequestTestJob::StartAsync(); }
326 private:
327 ~URLRequestTestDelayedNetworkJob() override {}
329 DISALLOW_COPY_AND_ASSIGN(URLRequestTestDelayedNetworkJob);
332 // This class is a variation on URLRequestTestJob in that it does
333 // not complete start upon entry, only when specifically told to.
334 class URLRequestTestDelayedStartJob : public net::URLRequestTestJob {
335 public:
336 URLRequestTestDelayedStartJob(net::URLRequest* request,
337 net::NetworkDelegate* network_delegate)
338 : net::URLRequestTestJob(request, network_delegate) {
339 Init();
341 URLRequestTestDelayedStartJob(net::URLRequest* request,
342 net::NetworkDelegate* network_delegate,
343 bool auto_advance)
344 : net::URLRequestTestJob(request, network_delegate, auto_advance) {
345 Init();
347 URLRequestTestDelayedStartJob(net::URLRequest* request,
348 net::NetworkDelegate* network_delegate,
349 const std::string& response_headers,
350 const std::string& response_data,
351 bool auto_advance)
352 : net::URLRequestTestJob(request,
353 network_delegate,
354 response_headers,
355 response_data,
356 auto_advance) {
357 Init();
360 // Do nothing until you're told to.
361 void Start() override {}
363 // Finish starting a URL request whose job is an instance of
364 // URLRequestTestDelayedStartJob. It is illegal to call this routine
365 // with a URLRequest that does not use URLRequestTestDelayedStartJob.
366 static void CompleteStart(net::URLRequest* request) {
367 for (URLRequestTestDelayedStartJob* job = list_head_;
368 job;
369 job = job->next_) {
370 if (job->request() == request) {
371 job->net::URLRequestTestJob::Start();
372 return;
375 NOTREACHED();
378 static bool DelayedStartQueueEmpty() {
379 return !list_head_;
382 static void ClearQueue() {
383 if (list_head_) {
384 LOG(ERROR)
385 << "Unreleased entries on URLRequestTestDelayedStartJob delay queue"
386 << "; may result in leaks.";
387 list_head_ = NULL;
391 protected:
392 ~URLRequestTestDelayedStartJob() override {
393 for (URLRequestTestDelayedStartJob** job = &list_head_; *job;
394 job = &(*job)->next_) {
395 if (*job == this) {
396 *job = (*job)->next_;
397 return;
400 NOTREACHED();
403 private:
404 void Init() {
405 next_ = list_head_;
406 list_head_ = this;
409 static URLRequestTestDelayedStartJob* list_head_;
410 URLRequestTestDelayedStartJob* next_;
413 URLRequestTestDelayedStartJob*
414 URLRequestTestDelayedStartJob::list_head_ = NULL;
416 // This class is a variation on URLRequestTestJob in that it
417 // returns IO_pending errors before every read, not just the first one.
418 class URLRequestTestDelayedCompletionJob : public net::URLRequestTestJob {
419 public:
420 URLRequestTestDelayedCompletionJob(net::URLRequest* request,
421 net::NetworkDelegate* network_delegate)
422 : net::URLRequestTestJob(request, network_delegate) {}
423 URLRequestTestDelayedCompletionJob(net::URLRequest* request,
424 net::NetworkDelegate* network_delegate,
425 bool auto_advance)
426 : net::URLRequestTestJob(request, network_delegate, auto_advance) {}
427 URLRequestTestDelayedCompletionJob(net::URLRequest* request,
428 net::NetworkDelegate* network_delegate,
429 const std::string& response_headers,
430 const std::string& response_data,
431 bool auto_advance)
432 : net::URLRequestTestJob(request,
433 network_delegate,
434 response_headers,
435 response_data,
436 auto_advance) {}
438 protected:
439 ~URLRequestTestDelayedCompletionJob() override {}
441 private:
442 bool NextReadAsync() override { return true; }
445 class URLRequestBigJob : public net::URLRequestSimpleJob {
446 public:
447 URLRequestBigJob(net::URLRequest* request,
448 net::NetworkDelegate* network_delegate)
449 : net::URLRequestSimpleJob(request, network_delegate) {
452 // URLRequestSimpleJob implementation:
453 int GetData(std::string* mime_type,
454 std::string* charset,
455 std::string* data,
456 const net::CompletionCallback& callback) const override {
457 *mime_type = "text/plain";
458 *charset = "UTF-8";
460 std::string text;
461 int count;
462 if (!ParseURL(request_->url(), &text, &count))
463 return net::ERR_INVALID_URL;
465 data->reserve(text.size() * count);
466 for (int i = 0; i < count; ++i)
467 data->append(text);
469 return net::OK;
472 base::TaskRunner* GetTaskRunner() const override {
473 return base::ThreadTaskRunnerHandle::Get().get();
476 private:
477 ~URLRequestBigJob() override {}
479 // big-job:substring,N
480 static bool ParseURL(const GURL& url, std::string* text, int* count) {
481 std::vector<std::string> parts = base::SplitString(
482 url.path(), ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
484 if (parts.size() != 2)
485 return false;
487 *text = parts[0];
488 return base::StringToInt(parts[1], count);
492 // URLRequestJob used to test GetLoadInfoForAllRoutes. The LoadState and
493 // UploadProgress values are set for the jobs at the time of creation, and
494 // the jobs will never actually do anything.
495 class URLRequestLoadInfoJob : public net::URLRequestJob {
496 public:
497 URLRequestLoadInfoJob(net::URLRequest* request,
498 net::NetworkDelegate* network_delegate,
499 const net::LoadState& load_state,
500 const net::UploadProgress& upload_progress)
501 : net::URLRequestJob(request, network_delegate),
502 load_state_(load_state),
503 upload_progress_(upload_progress) {}
505 // net::URLRequestJob implementation:
506 void Start() override {}
507 net::LoadState GetLoadState() const override { return load_state_; }
508 net::UploadProgress GetUploadProgress() const override {
509 return upload_progress_;
512 private:
513 ~URLRequestLoadInfoJob() override {}
515 // big-job:substring,N
516 static bool ParseURL(const GURL& url, std::string* text, int* count) {
517 std::vector<std::string> parts = base::SplitString(
518 url.path(), ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
520 if (parts.size() != 2)
521 return false;
523 *text = parts[0];
524 return base::StringToInt(parts[1], count);
527 const net::LoadState load_state_;
528 const net::UploadProgress upload_progress_;
531 class ResourceDispatcherHostTest;
533 class TestURLRequestJobFactory : public net::URLRequestJobFactory {
534 public:
535 explicit TestURLRequestJobFactory(ResourceDispatcherHostTest* test_fixture)
536 : test_fixture_(test_fixture),
537 delay_start_(false),
538 delay_complete_(false),
539 network_start_notification_(false),
540 url_request_jobs_created_count_(0) {
543 void HandleScheme(const std::string& scheme) {
544 supported_schemes_.insert(scheme);
547 int url_request_jobs_created_count() const {
548 return url_request_jobs_created_count_;
551 void SetDelayedStartJobGeneration(bool delay_job_start) {
552 delay_start_ = delay_job_start;
555 void SetDelayedCompleteJobGeneration(bool delay_job_complete) {
556 delay_complete_ = delay_job_complete;
559 void SetNetworkStartNotificationJobGeneration(bool notification) {
560 network_start_notification_ = notification;
563 net::URLRequestJob* MaybeCreateJobWithProtocolHandler(
564 const std::string& scheme,
565 net::URLRequest* request,
566 net::NetworkDelegate* network_delegate) const override;
568 net::URLRequestJob* MaybeInterceptRedirect(
569 net::URLRequest* request,
570 net::NetworkDelegate* network_delegate,
571 const GURL& location) const override;
573 net::URLRequestJob* MaybeInterceptResponse(
574 net::URLRequest* request,
575 net::NetworkDelegate* network_delegate) const override;
577 bool IsHandledProtocol(const std::string& scheme) const override {
578 return supported_schemes_.count(scheme) > 0;
581 bool IsHandledURL(const GURL& url) const override {
582 return supported_schemes_.count(url.scheme()) > 0;
585 bool IsSafeRedirectTarget(const GURL& location) const override {
586 return false;
589 private:
590 ResourceDispatcherHostTest* test_fixture_;
591 bool delay_start_;
592 bool delay_complete_;
593 bool network_start_notification_;
594 mutable int url_request_jobs_created_count_;
595 std::set<std::string> supported_schemes_;
597 DISALLOW_COPY_AND_ASSIGN(TestURLRequestJobFactory);
600 // Associated with an URLRequest to determine if the URLRequest gets deleted.
601 class TestUserData : public base::SupportsUserData::Data {
602 public:
603 explicit TestUserData(bool* was_deleted)
604 : was_deleted_(was_deleted) {
607 ~TestUserData() override { *was_deleted_ = true; }
609 private:
610 bool* was_deleted_;
613 class TransfersAllNavigationsContentBrowserClient
614 : public TestContentBrowserClient {
615 public:
616 bool ShouldSwapProcessesForRedirect(ResourceContext* resource_context,
617 const GURL& current_url,
618 const GURL& new_url) override {
619 return true;
623 enum GenericResourceThrottleFlags {
624 NONE = 0,
625 DEFER_STARTING_REQUEST = 1 << 0,
626 DEFER_PROCESSING_RESPONSE = 1 << 1,
627 CANCEL_BEFORE_START = 1 << 2,
628 DEFER_NETWORK_START = 1 << 3
631 // Throttle that tracks the current throttle blocking a request. Only one
632 // can throttle any request at a time.
633 class GenericResourceThrottle : public ResourceThrottle {
634 public:
635 // The value is used to indicate that the throttle should not provide
636 // a error code when cancelling a request. net::OK is used, because this
637 // is not an error code.
638 static const int USE_DEFAULT_CANCEL_ERROR_CODE = net::OK;
640 GenericResourceThrottle(int flags, int code)
641 : flags_(flags),
642 error_code_for_cancellation_(code) {
645 ~GenericResourceThrottle() override {
646 if (active_throttle_ == this)
647 active_throttle_ = NULL;
650 // ResourceThrottle implementation:
651 void WillStartRequest(bool* defer) override {
652 ASSERT_EQ(NULL, active_throttle_);
653 if (flags_ & DEFER_STARTING_REQUEST) {
654 active_throttle_ = this;
655 *defer = true;
658 if (flags_ & CANCEL_BEFORE_START) {
659 if (error_code_for_cancellation_ == USE_DEFAULT_CANCEL_ERROR_CODE) {
660 controller()->Cancel();
661 } else {
662 controller()->CancelWithError(error_code_for_cancellation_);
667 void WillProcessResponse(bool* defer) override {
668 ASSERT_EQ(NULL, active_throttle_);
669 if (flags_ & DEFER_PROCESSING_RESPONSE) {
670 active_throttle_ = this;
671 *defer = true;
675 void WillStartUsingNetwork(bool* defer) override {
676 ASSERT_EQ(NULL, active_throttle_);
678 if (flags_ & DEFER_NETWORK_START) {
679 active_throttle_ = this;
680 *defer = true;
684 const char* GetNameForLogging() const override {
685 return "GenericResourceThrottle";
688 void Resume() {
689 ASSERT_TRUE(this == active_throttle_);
690 active_throttle_ = NULL;
691 controller()->Resume();
694 static GenericResourceThrottle* active_throttle() {
695 return active_throttle_;
698 private:
699 int flags_; // bit-wise union of GenericResourceThrottleFlags.
700 int error_code_for_cancellation_;
702 // The currently active throttle, if any.
703 static GenericResourceThrottle* active_throttle_;
705 // static
706 GenericResourceThrottle* GenericResourceThrottle::active_throttle_ = NULL;
708 class TestResourceDispatcherHostDelegate
709 : public ResourceDispatcherHostDelegate {
710 public:
711 TestResourceDispatcherHostDelegate()
712 : create_two_throttles_(false),
713 flags_(NONE),
714 error_code_for_cancellation_(
715 GenericResourceThrottle::USE_DEFAULT_CANCEL_ERROR_CODE) {
718 void set_url_request_user_data(base::SupportsUserData::Data* user_data) {
719 user_data_.reset(user_data);
722 void set_flags(int value) {
723 flags_ = value;
726 void set_error_code_for_cancellation(int code) {
727 error_code_for_cancellation_ = code;
730 void set_create_two_throttles(bool create_two_throttles) {
731 create_two_throttles_ = create_two_throttles;
734 // ResourceDispatcherHostDelegate implementation:
736 void RequestBeginning(net::URLRequest* request,
737 ResourceContext* resource_context,
738 AppCacheService* appcache_service,
739 ResourceType resource_type,
740 ScopedVector<ResourceThrottle>* throttles) override {
741 if (user_data_) {
742 const void* key = user_data_.get();
743 request->SetUserData(key, user_data_.release());
746 if (flags_ != NONE) {
747 throttles->push_back(new GenericResourceThrottle(
748 flags_, error_code_for_cancellation_));
749 if (create_two_throttles_)
750 throttles->push_back(new GenericResourceThrottle(
751 flags_, error_code_for_cancellation_));
755 private:
756 bool create_two_throttles_;
757 int flags_;
758 int error_code_for_cancellation_;
759 scoped_ptr<base::SupportsUserData::Data> user_data_;
762 // Waits for a ShareableFileReference to be released.
763 class ShareableFileReleaseWaiter {
764 public:
765 ShareableFileReleaseWaiter(const base::FilePath& path) {
766 scoped_refptr<ShareableFileReference> file =
767 ShareableFileReference::Get(path);
768 file->AddFinalReleaseCallback(
769 base::Bind(&ShareableFileReleaseWaiter::Released,
770 base::Unretained(this)));
773 void Wait() {
774 loop_.Run();
777 private:
778 void Released(const base::FilePath& path) {
779 loop_.Quit();
782 base::RunLoop loop_;
784 DISALLOW_COPY_AND_ASSIGN(ShareableFileReleaseWaiter);
787 // For verifying notifications sent to the WebContents by the
788 // ResourceDispatcherHostImpl.
789 class TestWebContentsObserver : public WebContentsObserver {
790 public:
791 TestWebContentsObserver(WebContents* web_contents)
792 : WebContentsObserver(web_contents),
793 resource_request_redirect_count_(0),
794 resource_response_start_count_(0) {}
796 void DidGetRedirectForResourceRequest(
797 RenderFrameHost* render_frame_host,
798 const ResourceRedirectDetails& details) override {
799 ++resource_request_redirect_count_;
802 void DidGetResourceResponseStart(
803 const ResourceRequestDetails& details) override {
804 ++resource_response_start_count_;
807 int resource_response_start_count() { return resource_response_start_count_; }
809 int resource_request_redirect_count() {
810 return resource_request_redirect_count_;
813 private:
814 int resource_request_redirect_count_;
815 int resource_response_start_count_;
818 // Information used to create resource requests that use URLRequestLoadInfoJobs.
819 // The child_id is just that of ResourceDispatcherHostTest::filter_.
820 struct LoadInfoTestRequestInfo {
821 int route_id;
822 GURL url;
823 net::LoadState load_state;
824 net::UploadProgress upload_progress;
827 class ResourceDispatcherHostTest : public testing::Test,
828 public IPC::Sender {
829 public:
830 typedef ResourceDispatcherHostImpl::LoadInfo LoadInfo;
831 typedef ResourceDispatcherHostImpl::LoadInfoMap LoadInfoMap;
833 ResourceDispatcherHostTest()
834 : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
835 old_factory_(NULL),
836 send_data_received_acks_(false) {
837 browser_context_.reset(new TestBrowserContext());
838 BrowserContext::EnsureResourceContextInitialized(browser_context_.get());
839 base::RunLoop().RunUntilIdle();
840 filter_ = MakeForwardingFilter();
841 // TODO(cbentzel): Better way to get URLRequestContext?
842 net::URLRequestContext* request_context =
843 browser_context_->GetResourceContext()->GetRequestContext();
844 job_factory_.reset(new TestURLRequestJobFactory(this));
845 request_context->set_job_factory(job_factory_.get());
846 request_context->set_network_delegate(&network_delegate_);
849 // IPC::Sender implementation
850 bool Send(IPC::Message* msg) override {
851 accum_.AddMessage(*msg);
853 if (send_data_received_acks_ &&
854 msg->type() == ResourceMsg_DataReceived::ID) {
855 GenerateDataReceivedACK(*msg);
858 if (wait_for_request_complete_loop_ &&
859 msg->type() == ResourceMsg_RequestComplete::ID) {
860 wait_for_request_complete_loop_->Quit();
863 // Do not release handles in it yet; the accumulator owns them now.
864 delete msg;
865 return true;
868 scoped_ptr<LoadInfoMap> RunLoadInfoTest(LoadInfoTestRequestInfo* request_info,
869 size_t num_requests) {
870 for (size_t i = 0; i < num_requests; ++i) {
871 loader_test_request_info_.reset(
872 new LoadInfoTestRequestInfo(request_info[i]));
873 wait_for_request_create_loop_.reset(new base::RunLoop());
874 MakeTestRequest(request_info[i].route_id, i + 1, request_info[i].url);
875 wait_for_request_create_loop_->Run();
876 wait_for_request_create_loop_.reset();
878 return ResourceDispatcherHostImpl::Get()->GetLoadInfoForAllRoutes();
881 protected:
882 friend class TestURLRequestJobFactory;
884 // testing::Test
885 void SetUp() override {
886 ChildProcessSecurityPolicyImpl::GetInstance()->Add(0);
887 HandleScheme("test");
888 scoped_refptr<SiteInstance> site_instance =
889 SiteInstance::Create(browser_context_.get());
890 web_contents_.reset(
891 WebContents::Create(WebContents::CreateParams(browser_context_.get())));
892 web_contents_observer_.reset(
893 new TestWebContentsObserver(web_contents_.get()));
894 web_contents_filter_ = new TestFilterSpecifyingChild(
895 browser_context_->GetResourceContext(),
896 web_contents_->GetRenderProcessHost()->GetID());
897 child_ids_.insert(web_contents_->GetRenderProcessHost()->GetID());
900 void TearDown() override {
901 web_contents_observer_.reset();
902 web_contents_.reset();
904 EXPECT_TRUE(URLRequestTestDelayedStartJob::DelayedStartQueueEmpty());
905 URLRequestTestDelayedStartJob::ClearQueue();
907 for (std::set<int>::iterator it = child_ids_.begin();
908 it != child_ids_.end(); ++it) {
909 host_.CancelRequestsForProcess(*it);
912 host_.Shutdown();
914 ChildProcessSecurityPolicyImpl::GetInstance()->Remove(0);
916 // Flush the message loop to make application verifiers happy.
917 if (ResourceDispatcherHostImpl::Get())
918 ResourceDispatcherHostImpl::Get()->CancelRequestsForContext(
919 browser_context_->GetResourceContext());
921 browser_context_.reset();
922 base::RunLoop().RunUntilIdle();
925 // Creates a new ForwardingFilter and registers it with |child_ids_| so as not
926 // to leak per-child state on test shutdown.
927 ForwardingFilter* MakeForwardingFilter() {
928 ForwardingFilter* filter =
929 new ForwardingFilter(this, browser_context_->GetResourceContext());
930 child_ids_.insert(filter->child_id());
931 return filter;
934 // Creates a request using the current test object as the filter and
935 // SubResource as the resource type.
936 void MakeTestRequest(int render_view_id,
937 int request_id,
938 const GURL& url);
940 // Generates a request using the given filter and resource type.
941 void MakeTestRequestWithResourceType(ResourceMessageFilter* filter,
942 int render_view_id,
943 int request_id,
944 const GURL& url,
945 ResourceType type);
947 void MakeWebContentsAssociatedTestRequest(int request_id, const GURL& url);
949 void CancelRequest(int request_id);
950 void RendererCancelRequest(int request_id) {
951 ResourceMessageFilter* old_filter = SetFilter(filter_.get());
952 host_.OnCancelRequest(request_id);
953 SetFilter(old_filter);
956 void CompleteStartRequest(int request_id);
957 void CompleteStartRequest(ResourceMessageFilter* filter, int request_id);
959 net::TestNetworkDelegate* network_delegate() { return &network_delegate_; }
961 void EnsureSchemeIsAllowed(const std::string& scheme) {
962 ChildProcessSecurityPolicyImpl* policy =
963 ChildProcessSecurityPolicyImpl::GetInstance();
964 if (!policy->IsWebSafeScheme(scheme))
965 policy->RegisterWebSafeScheme(scheme);
968 // Sets a particular response for any request from now on. To switch back to
969 // the default bahavior, pass an empty |headers|. |headers| should be raw-
970 // formatted (NULLs instead of EOLs).
971 void SetResponse(const std::string& headers, const std::string& data) {
972 response_headers_ = net::HttpUtil::AssembleRawHeaders(headers.data(),
973 headers.size());
974 response_data_ = data;
976 void SetResponse(const std::string& headers) {
977 SetResponse(headers, std::string());
980 void SendDataReceivedACKs(bool send_acks) {
981 send_data_received_acks_ = send_acks;
984 // Intercepts requests for the given protocol.
985 void HandleScheme(const std::string& scheme) {
986 job_factory_->HandleScheme(scheme);
987 EnsureSchemeIsAllowed(scheme);
990 void GenerateDataReceivedACK(const IPC::Message& msg) {
991 EXPECT_EQ(ResourceMsg_DataReceived::ID, msg.type());
993 int request_id = -1;
994 bool result = base::PickleIterator(msg).ReadInt(&request_id);
995 DCHECK(result);
996 scoped_ptr<IPC::Message> ack(
997 new ResourceHostMsg_DataReceived_ACK(request_id));
999 base::ThreadTaskRunnerHandle::Get()->PostTask(
1000 FROM_HERE,
1001 base::Bind(&GenerateIPCMessage, filter_, base::Passed(&ack)));
1004 // Setting filters for testing renderer messages.
1005 // Returns the previous filter.
1006 ResourceMessageFilter* SetFilter(ResourceMessageFilter* new_filter) {
1007 ResourceMessageFilter* old_filter = host_.filter_;
1008 host_.filter_ = new_filter;
1009 return old_filter;
1012 void WaitForRequestComplete() {
1013 DCHECK(!wait_for_request_complete_loop_);
1014 wait_for_request_complete_loop_.reset(new base::RunLoop);
1015 wait_for_request_complete_loop_->Run();
1016 wait_for_request_complete_loop_.reset();
1019 scoped_ptr<LoadInfoTestRequestInfo> loader_test_request_info_;
1020 scoped_ptr<base::RunLoop> wait_for_request_create_loop_;
1022 content::TestBrowserThreadBundle thread_bundle_;
1023 scoped_ptr<TestBrowserContext> browser_context_;
1024 scoped_ptr<TestURLRequestJobFactory> job_factory_;
1025 scoped_ptr<WebContents> web_contents_;
1026 scoped_ptr<TestWebContentsObserver> web_contents_observer_;
1027 scoped_refptr<ForwardingFilter> filter_;
1028 scoped_refptr<TestFilterSpecifyingChild> web_contents_filter_;
1029 net::TestNetworkDelegate network_delegate_;
1030 ResourceDispatcherHostImpl host_;
1031 ResourceIPCAccumulator accum_;
1032 std::string response_headers_;
1033 std::string response_data_;
1034 std::string scheme_;
1035 net::URLRequest::ProtocolFactory* old_factory_;
1036 bool send_data_received_acks_;
1037 std::set<int> child_ids_;
1038 scoped_ptr<base::RunLoop> wait_for_request_complete_loop_;
1039 RenderViewHostTestEnabler render_view_host_test_enabler_;
1042 void ResourceDispatcherHostTest::MakeTestRequest(int render_view_id,
1043 int request_id,
1044 const GURL& url) {
1045 MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
1046 url, RESOURCE_TYPE_SUB_RESOURCE);
1049 void ResourceDispatcherHostTest::MakeTestRequestWithResourceType(
1050 ResourceMessageFilter* filter,
1051 int render_view_id,
1052 int request_id,
1053 const GURL& url,
1054 ResourceType type) {
1055 ResourceHostMsg_Request request =
1056 CreateResourceRequest("GET", type, url);
1057 ResourceHostMsg_RequestResource msg(render_view_id, request_id, request);
1058 host_.OnMessageReceived(msg, filter);
1059 KickOffRequest();
1062 void ResourceDispatcherHostTest::MakeWebContentsAssociatedTestRequest(
1063 int request_id,
1064 const GURL& url) {
1065 ResourceHostMsg_Request request =
1066 CreateResourceRequest("GET", RESOURCE_TYPE_SUB_RESOURCE, url);
1067 request.origin_pid = web_contents_->GetRenderProcessHost()->GetID();
1068 request.render_frame_id = web_contents_->GetMainFrame()->GetRoutingID();
1069 ResourceHostMsg_RequestResource msg(web_contents_->GetRoutingID(), request_id,
1070 request);
1071 host_.OnMessageReceived(msg, web_contents_filter_.get());
1072 KickOffRequest();
1075 void ResourceDispatcherHostTest::CancelRequest(int request_id) {
1076 host_.CancelRequest(filter_->child_id(), request_id);
1079 void ResourceDispatcherHostTest::CompleteStartRequest(int request_id) {
1080 CompleteStartRequest(filter_.get(), request_id);
1083 void ResourceDispatcherHostTest::CompleteStartRequest(
1084 ResourceMessageFilter* filter,
1085 int request_id) {
1086 GlobalRequestID gid(filter->child_id(), request_id);
1087 net::URLRequest* req = host_.GetURLRequest(gid);
1088 EXPECT_TRUE(req);
1089 if (req)
1090 URLRequestTestDelayedStartJob::CompleteStart(req);
1093 void CheckRequestCompleteErrorCode(const IPC::Message& message,
1094 int expected_error_code) {
1095 // Verify the expected error code was received.
1096 int request_id;
1097 int error_code;
1099 ASSERT_EQ(ResourceMsg_RequestComplete::ID, message.type());
1101 base::PickleIterator iter(message);
1102 ASSERT_TRUE(IPC::ReadParam(&message, &iter, &request_id));
1103 ASSERT_TRUE(IPC::ReadParam(&message, &iter, &error_code));
1104 ASSERT_EQ(expected_error_code, error_code);
1107 testing::AssertionResult ExtractDataOffsetAndLength(const IPC::Message& message,
1108 int* data_offset,
1109 int* data_length) {
1110 base::PickleIterator iter(message);
1111 int request_id;
1112 if (!IPC::ReadParam(&message, &iter, &request_id))
1113 return testing::AssertionFailure() << "Could not read request_id";
1114 if (!IPC::ReadParam(&message, &iter, data_offset))
1115 return testing::AssertionFailure() << "Could not read data_offset";
1116 if (!IPC::ReadParam(&message, &iter, data_length))
1117 return testing::AssertionFailure() << "Could not read data_length";
1118 return testing::AssertionSuccess();
1121 void CheckSuccessfulRequestWithErrorCode(
1122 const std::vector<IPC::Message>& messages,
1123 const std::string& reference_data,
1124 int expected_error) {
1125 // A successful request will have received 4 messages:
1126 // ReceivedResponse (indicates headers received)
1127 // SetDataBuffer (contains shared memory handle)
1128 // DataReceived (data offset and length into shared memory)
1129 // RequestComplete (request is done)
1131 // This function verifies that we received 4 messages and that they are
1132 // appropriate. It allows for an error code other than net::OK if the request
1133 // should successfully receive data and then abort, e.g., on cancel.
1134 ASSERT_EQ(4U, messages.size());
1136 // The first messages should be received response
1137 ASSERT_EQ(ResourceMsg_ReceivedResponse::ID, messages[0].type());
1139 ASSERT_EQ(ResourceMsg_SetDataBuffer::ID, messages[1].type());
1141 base::PickleIterator iter(messages[1]);
1142 int request_id;
1143 ASSERT_TRUE(IPC::ReadParam(&messages[1], &iter, &request_id));
1144 base::SharedMemoryHandle shm_handle;
1145 ASSERT_TRUE(IPC::ReadParam(&messages[1], &iter, &shm_handle));
1146 int shm_size;
1147 ASSERT_TRUE(IPC::ReadParam(&messages[1], &iter, &shm_size));
1149 // Followed by the data, currently we only do the data in one chunk, but
1150 // should probably test multiple chunks later
1151 ASSERT_EQ(ResourceMsg_DataReceived::ID, messages[2].type());
1153 int data_offset;
1154 int data_length;
1155 ASSERT_TRUE(
1156 ExtractDataOffsetAndLength(messages[2], &data_offset, &data_length));
1158 ASSERT_EQ(reference_data.size(), static_cast<size_t>(data_length));
1159 ASSERT_GE(shm_size, data_length);
1161 base::SharedMemory shared_mem(shm_handle, true); // read only
1162 shared_mem.Map(data_length);
1163 const char* data = static_cast<char*>(shared_mem.memory()) + data_offset;
1164 ASSERT_EQ(0, memcmp(reference_data.c_str(), data, data_length));
1166 // The last message should be all data received.
1167 CheckRequestCompleteErrorCode(messages[3], expected_error);
1170 void CheckSuccessfulRequest(const std::vector<IPC::Message>& messages,
1171 const std::string& reference_data) {
1172 CheckSuccessfulRequestWithErrorCode(messages, reference_data, net::OK);
1175 void CheckSuccessfulRedirect(const std::vector<IPC::Message>& messages,
1176 const std::string& reference_data) {
1177 ASSERT_EQ(5U, messages.size());
1178 ASSERT_EQ(ResourceMsg_ReceivedRedirect::ID, messages[0].type());
1180 const std::vector<IPC::Message> second_req_msgs =
1181 std::vector<IPC::Message>(messages.begin() + 1, messages.end());
1182 CheckSuccessfulRequest(second_req_msgs, reference_data);
1185 void CheckFailedRequest(const std::vector<IPC::Message>& messages,
1186 const std::string& reference_data,
1187 int expected_error) {
1188 ASSERT_LT(0U, messages.size());
1189 ASSERT_GE(2U, messages.size());
1190 size_t failure_index = messages.size() - 1;
1192 if (messages.size() == 2) {
1193 EXPECT_EQ(ResourceMsg_ReceivedResponse::ID, messages[0].type());
1196 CheckRequestCompleteErrorCode(messages[failure_index], expected_error);
1199 // Tests whether many messages get dispatched properly.
1200 TEST_F(ResourceDispatcherHostTest, TestMany) {
1201 MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_1());
1202 MakeTestRequest(0, 2, net::URLRequestTestJob::test_url_2());
1203 MakeTestRequest(0, 3, net::URLRequestTestJob::test_url_3());
1204 MakeTestRequestWithResourceType(filter_.get(), 0, 4,
1205 net::URLRequestTestJob::test_url_4(),
1206 RESOURCE_TYPE_PREFETCH); // detachable type
1207 MakeTestRequest(0, 5, net::URLRequestTestJob::test_url_redirect_to_url_2());
1209 // Finish the redirection
1210 ResourceHostMsg_FollowRedirect redirect_msg(5);
1211 host_.OnMessageReceived(redirect_msg, filter_.get());
1212 base::MessageLoop::current()->RunUntilIdle();
1214 // flush all the pending requests
1215 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1217 // sorts out all the messages we saw by request
1218 ResourceIPCAccumulator::ClassifiedMessages msgs;
1219 accum_.GetClassifiedMessages(&msgs);
1221 // there are five requests, so we should have gotten them classified as such
1222 ASSERT_EQ(5U, msgs.size());
1224 CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_1());
1225 CheckSuccessfulRequest(msgs[1], net::URLRequestTestJob::test_data_2());
1226 CheckSuccessfulRequest(msgs[2], net::URLRequestTestJob::test_data_3());
1227 CheckSuccessfulRequest(msgs[3], net::URLRequestTestJob::test_data_4());
1228 CheckSuccessfulRedirect(msgs[4], net::URLRequestTestJob::test_data_2());
1231 // Tests whether messages get canceled properly. We issue four requests,
1232 // cancel two of them, and make sure that each sent the proper notifications.
1233 TEST_F(ResourceDispatcherHostTest, Cancel) {
1234 MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_1());
1235 MakeTestRequest(0, 2, net::URLRequestTestJob::test_url_2());
1236 MakeTestRequest(0, 3, net::URLRequestTestJob::test_url_3());
1238 MakeTestRequestWithResourceType(filter_.get(), 0, 4,
1239 net::URLRequestTestJob::test_url_4(),
1240 RESOURCE_TYPE_PREFETCH); // detachable type
1242 CancelRequest(2);
1244 // Cancel request must come from the renderer for a detachable resource to
1245 // delay.
1246 RendererCancelRequest(4);
1248 // The handler should have been detached now.
1249 GlobalRequestID global_request_id(filter_->child_id(), 4);
1250 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(
1251 host_.GetURLRequest(global_request_id));
1252 ASSERT_TRUE(info->detachable_handler()->is_detached());
1254 // flush all the pending requests
1255 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1256 base::MessageLoop::current()->RunUntilIdle();
1258 // Everything should be out now.
1259 EXPECT_EQ(0, host_.pending_requests());
1261 ResourceIPCAccumulator::ClassifiedMessages msgs;
1262 accum_.GetClassifiedMessages(&msgs);
1264 // there are four requests, so we should have gotten them classified as such
1265 ASSERT_EQ(4U, msgs.size());
1267 CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_1());
1268 CheckSuccessfulRequest(msgs[2], net::URLRequestTestJob::test_data_3());
1270 // Check that request 2 and 4 got canceled, as far as the renderer is
1271 // concerned. Request 2 will have been deleted.
1272 ASSERT_EQ(1U, msgs[1].size());
1273 ASSERT_EQ(ResourceMsg_ReceivedResponse::ID, msgs[1][0].type());
1275 ASSERT_EQ(2U, msgs[3].size());
1276 ASSERT_EQ(ResourceMsg_ReceivedResponse::ID, msgs[3][0].type());
1277 CheckRequestCompleteErrorCode(msgs[3][1], net::ERR_ABORTED);
1279 // However, request 4 should have actually gone to completion. (Only request 2
1280 // was canceled.)
1281 EXPECT_EQ(4, network_delegate()->completed_requests());
1282 EXPECT_EQ(1, network_delegate()->canceled_requests());
1283 EXPECT_EQ(0, network_delegate()->error_count());
1286 // Shows that detachable requests will timeout if the request takes too long to
1287 // complete.
1288 TEST_F(ResourceDispatcherHostTest, DetachedResourceTimesOut) {
1289 MakeTestRequestWithResourceType(filter_.get(), 0, 1,
1290 net::URLRequestTestJob::test_url_2(),
1291 RESOURCE_TYPE_PREFETCH); // detachable type
1292 GlobalRequestID global_request_id(filter_->child_id(), 1);
1293 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(
1294 host_.GetURLRequest(global_request_id));
1295 ASSERT_TRUE(info->detachable_handler());
1296 info->detachable_handler()->set_cancel_delay(
1297 base::TimeDelta::FromMilliseconds(200));
1298 base::MessageLoop::current()->RunUntilIdle();
1300 RendererCancelRequest(1);
1302 // From the renderer's perspective, the request was cancelled.
1303 ResourceIPCAccumulator::ClassifiedMessages msgs;
1304 accum_.GetClassifiedMessages(&msgs);
1305 ASSERT_EQ(1U, msgs.size());
1306 ASSERT_EQ(2U, msgs[0].size());
1307 ASSERT_EQ(ResourceMsg_ReceivedResponse::ID, msgs[0][0].type());
1308 CheckRequestCompleteErrorCode(msgs[0][1], net::ERR_ABORTED);
1310 // But it continues detached.
1311 EXPECT_EQ(1, host_.pending_requests());
1312 EXPECT_TRUE(info->detachable_handler()->is_detached());
1314 // Wait until after the delay timer times out before we start processing any
1315 // messages.
1316 base::OneShotTimer<base::MessageLoop> timer;
1317 timer.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(210),
1318 base::MessageLoop::current(), &base::MessageLoop::QuitWhenIdle);
1319 base::MessageLoop::current()->Run();
1321 // The prefetch should be cancelled by now.
1322 EXPECT_EQ(0, host_.pending_requests());
1323 EXPECT_EQ(1, network_delegate()->completed_requests());
1324 EXPECT_EQ(1, network_delegate()->canceled_requests());
1325 EXPECT_EQ(0, network_delegate()->error_count());
1328 // If the filter has disappeared then detachable resources should continue to
1329 // load.
1330 TEST_F(ResourceDispatcherHostTest, DeletedFilterDetached) {
1331 // test_url_1's data is available synchronously, so use 2 and 3.
1332 ResourceHostMsg_Request request_prefetch = CreateResourceRequest(
1333 "GET", RESOURCE_TYPE_PREFETCH, net::URLRequestTestJob::test_url_2());
1334 ResourceHostMsg_Request request_ping = CreateResourceRequest(
1335 "GET", RESOURCE_TYPE_PING, net::URLRequestTestJob::test_url_3());
1337 ResourceHostMsg_RequestResource msg_prefetch(0, 1, request_prefetch);
1338 host_.OnMessageReceived(msg_prefetch, filter_.get());
1339 ResourceHostMsg_RequestResource msg_ping(0, 2, request_ping);
1340 host_.OnMessageReceived(msg_ping, filter_.get());
1342 // Remove the filter before processing the requests by simulating channel
1343 // closure.
1344 ResourceRequestInfoImpl* info_prefetch = ResourceRequestInfoImpl::ForRequest(
1345 host_.GetURLRequest(GlobalRequestID(filter_->child_id(), 1)));
1346 ResourceRequestInfoImpl* info_ping = ResourceRequestInfoImpl::ForRequest(
1347 host_.GetURLRequest(GlobalRequestID(filter_->child_id(), 2)));
1348 DCHECK_EQ(filter_.get(), info_prefetch->filter());
1349 DCHECK_EQ(filter_.get(), info_ping->filter());
1350 filter_->OnChannelClosing();
1351 info_prefetch->filter_.reset();
1352 info_ping->filter_.reset();
1354 // From the renderer's perspective, the requests were cancelled.
1355 ResourceIPCAccumulator::ClassifiedMessages msgs;
1356 accum_.GetClassifiedMessages(&msgs);
1357 ASSERT_EQ(2U, msgs.size());
1358 CheckRequestCompleteErrorCode(msgs[0][0], net::ERR_ABORTED);
1359 CheckRequestCompleteErrorCode(msgs[1][0], net::ERR_ABORTED);
1361 // But it continues detached.
1362 EXPECT_EQ(2, host_.pending_requests());
1363 EXPECT_TRUE(info_prefetch->detachable_handler()->is_detached());
1364 EXPECT_TRUE(info_ping->detachable_handler()->is_detached());
1366 KickOffRequest();
1368 // Make sure the requests weren't canceled early.
1369 EXPECT_EQ(2, host_.pending_requests());
1371 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1372 base::MessageLoop::current()->RunUntilIdle();
1374 EXPECT_EQ(0, host_.pending_requests());
1375 EXPECT_EQ(2, network_delegate()->completed_requests());
1376 EXPECT_EQ(0, network_delegate()->canceled_requests());
1377 EXPECT_EQ(0, network_delegate()->error_count());
1380 // If the filter has disappeared (original process dies) then detachable
1381 // resources should continue to load, even when redirected.
1382 TEST_F(ResourceDispatcherHostTest, DeletedFilterDetachedRedirect) {
1383 ResourceHostMsg_Request request = CreateResourceRequest(
1384 "GET", RESOURCE_TYPE_PREFETCH,
1385 net::URLRequestTestJob::test_url_redirect_to_url_2());
1387 ResourceHostMsg_RequestResource msg(0, 1, request);
1388 host_.OnMessageReceived(msg, filter_.get());
1390 // Remove the filter before processing the request by simulating channel
1391 // closure.
1392 GlobalRequestID global_request_id(filter_->child_id(), 1);
1393 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(
1394 host_.GetURLRequest(global_request_id));
1395 info->filter_->OnChannelClosing();
1396 info->filter_.reset();
1398 // From the renderer's perspective, the request was cancelled.
1399 ResourceIPCAccumulator::ClassifiedMessages msgs;
1400 accum_.GetClassifiedMessages(&msgs);
1401 ASSERT_EQ(1U, msgs.size());
1402 CheckRequestCompleteErrorCode(msgs[0][0], net::ERR_ABORTED);
1404 // But it continues detached.
1405 EXPECT_EQ(1, host_.pending_requests());
1406 EXPECT_TRUE(info->detachable_handler()->is_detached());
1408 // Verify no redirects before resetting the filter.
1409 net::URLRequest* url_request = host_.GetURLRequest(global_request_id);
1410 EXPECT_EQ(1u, url_request->url_chain().size());
1411 KickOffRequest();
1413 // Verify that a redirect was followed.
1414 EXPECT_EQ(2u, url_request->url_chain().size());
1416 // Make sure the request wasn't canceled early.
1417 EXPECT_EQ(1, host_.pending_requests());
1419 // Finish up the request.
1420 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1421 base::MessageLoop::current()->RunUntilIdle();
1423 EXPECT_EQ(0, host_.pending_requests());
1424 EXPECT_EQ(1, network_delegate()->completed_requests());
1425 EXPECT_EQ(0, network_delegate()->canceled_requests());
1426 EXPECT_EQ(0, network_delegate()->error_count());
1429 TEST_F(ResourceDispatcherHostTest, CancelWhileStartIsDeferred) {
1430 bool was_deleted = false;
1432 // Arrange to have requests deferred before starting.
1433 TestResourceDispatcherHostDelegate delegate;
1434 delegate.set_flags(DEFER_STARTING_REQUEST);
1435 delegate.set_url_request_user_data(new TestUserData(&was_deleted));
1436 host_.SetDelegate(&delegate);
1438 MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_1());
1439 // We cancel from the renderer because all non-renderer cancels delete
1440 // the request synchronously.
1441 RendererCancelRequest(1);
1443 // Our TestResourceThrottle should not have been deleted yet. This is to
1444 // ensure that destruction of the URLRequest happens asynchronously to
1445 // calling CancelRequest.
1446 EXPECT_FALSE(was_deleted);
1448 base::MessageLoop::current()->RunUntilIdle();
1450 EXPECT_TRUE(was_deleted);
1453 TEST_F(ResourceDispatcherHostTest, DetachWhileStartIsDeferred) {
1454 bool was_deleted = false;
1456 // Arrange to have requests deferred before starting.
1457 TestResourceDispatcherHostDelegate delegate;
1458 delegate.set_flags(DEFER_STARTING_REQUEST);
1459 delegate.set_url_request_user_data(new TestUserData(&was_deleted));
1460 host_.SetDelegate(&delegate);
1462 MakeTestRequestWithResourceType(filter_.get(), 0, 1,
1463 net::URLRequestTestJob::test_url_1(),
1464 RESOURCE_TYPE_PREFETCH); // detachable type
1465 // Cancel request must come from the renderer for a detachable resource to
1466 // detach.
1467 RendererCancelRequest(1);
1469 // Even after driving the event loop, the request has not been deleted.
1470 EXPECT_FALSE(was_deleted);
1472 // However, it is still throttled because the defer happened above the
1473 // DetachableResourceHandler.
1474 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1475 base::MessageLoop::current()->RunUntilIdle();
1476 EXPECT_FALSE(was_deleted);
1478 // Resume the request.
1479 GenericResourceThrottle* throttle =
1480 GenericResourceThrottle::active_throttle();
1481 ASSERT_TRUE(throttle);
1482 throttle->Resume();
1484 // Now, the request completes.
1485 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1486 base::MessageLoop::current()->RunUntilIdle();
1487 EXPECT_TRUE(was_deleted);
1488 EXPECT_EQ(1, network_delegate()->completed_requests());
1489 EXPECT_EQ(0, network_delegate()->canceled_requests());
1490 EXPECT_EQ(0, network_delegate()->error_count());
1493 // Tests if cancel is called in ResourceThrottle::WillStartRequest, then the
1494 // URLRequest will not be started.
1495 TEST_F(ResourceDispatcherHostTest, CancelInResourceThrottleWillStartRequest) {
1496 TestResourceDispatcherHostDelegate delegate;
1497 delegate.set_flags(CANCEL_BEFORE_START);
1498 host_.SetDelegate(&delegate);
1500 MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_1());
1502 // flush all the pending requests
1503 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1504 base::MessageLoop::current()->RunUntilIdle();
1506 ResourceIPCAccumulator::ClassifiedMessages msgs;
1507 accum_.GetClassifiedMessages(&msgs);
1509 // Check that request got canceled.
1510 ASSERT_EQ(1U, msgs[0].size());
1511 CheckRequestCompleteErrorCode(msgs[0][0], net::ERR_ABORTED);
1513 // Make sure URLRequest is never started.
1514 EXPECT_EQ(0, job_factory_->url_request_jobs_created_count());
1517 TEST_F(ResourceDispatcherHostTest, PausedStartError) {
1518 // Arrange to have requests deferred before processing response headers.
1519 TestResourceDispatcherHostDelegate delegate;
1520 delegate.set_flags(DEFER_PROCESSING_RESPONSE);
1521 host_.SetDelegate(&delegate);
1523 job_factory_->SetDelayedStartJobGeneration(true);
1524 MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_error());
1525 CompleteStartRequest(1);
1527 // flush all the pending requests
1528 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1529 base::MessageLoop::current()->RunUntilIdle();
1531 EXPECT_EQ(0, host_.pending_requests());
1534 // Test the WillStartUsingNetwork throttle.
1535 TEST_F(ResourceDispatcherHostTest, ThrottleNetworkStart) {
1536 // Arrange to have requests deferred before processing response headers.
1537 TestResourceDispatcherHostDelegate delegate;
1538 delegate.set_flags(DEFER_NETWORK_START);
1539 host_.SetDelegate(&delegate);
1541 job_factory_->SetNetworkStartNotificationJobGeneration(true);
1542 MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_2());
1544 // Should have deferred for network start.
1545 GenericResourceThrottle* first_throttle =
1546 GenericResourceThrottle::active_throttle();
1547 ASSERT_TRUE(first_throttle);
1548 EXPECT_EQ(0, network_delegate()->completed_requests());
1549 EXPECT_EQ(1, host_.pending_requests());
1551 first_throttle->Resume();
1553 // Flush all the pending requests.
1554 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1555 base::MessageLoop::current()->RunUntilIdle();
1557 EXPECT_EQ(1, network_delegate()->completed_requests());
1558 EXPECT_EQ(0, host_.pending_requests());
1561 TEST_F(ResourceDispatcherHostTest, ThrottleAndResumeTwice) {
1562 // Arrange to have requests deferred before starting.
1563 TestResourceDispatcherHostDelegate delegate;
1564 delegate.set_flags(DEFER_STARTING_REQUEST);
1565 delegate.set_create_two_throttles(true);
1566 host_.SetDelegate(&delegate);
1568 // Make sure the first throttle blocked the request, and then resume.
1569 MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_1());
1570 GenericResourceThrottle* first_throttle =
1571 GenericResourceThrottle::active_throttle();
1572 ASSERT_TRUE(first_throttle);
1573 first_throttle->Resume();
1575 // Make sure the second throttle blocked the request, and then resume.
1576 ASSERT_TRUE(GenericResourceThrottle::active_throttle());
1577 ASSERT_NE(first_throttle, GenericResourceThrottle::active_throttle());
1578 GenericResourceThrottle::active_throttle()->Resume();
1580 ASSERT_FALSE(GenericResourceThrottle::active_throttle());
1582 // The request is started asynchronously.
1583 base::MessageLoop::current()->RunUntilIdle();
1585 // Flush all the pending requests.
1586 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1588 EXPECT_EQ(0, host_.pending_requests());
1590 // Make sure the request completed successfully.
1591 ResourceIPCAccumulator::ClassifiedMessages msgs;
1592 accum_.GetClassifiedMessages(&msgs);
1593 ASSERT_EQ(1U, msgs.size());
1594 CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_1());
1598 // Tests that the delegate can cancel a request and provide a error code.
1599 TEST_F(ResourceDispatcherHostTest, CancelInDelegate) {
1600 TestResourceDispatcherHostDelegate delegate;
1601 delegate.set_flags(CANCEL_BEFORE_START);
1602 delegate.set_error_code_for_cancellation(net::ERR_ACCESS_DENIED);
1603 host_.SetDelegate(&delegate);
1605 MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_1());
1606 // The request will get cancelled by the throttle.
1608 // flush all the pending requests
1609 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1610 base::MessageLoop::current()->RunUntilIdle();
1612 ResourceIPCAccumulator::ClassifiedMessages msgs;
1613 accum_.GetClassifiedMessages(&msgs);
1615 // Check the cancellation
1616 ASSERT_EQ(1U, msgs.size());
1617 ASSERT_EQ(1U, msgs[0].size());
1619 CheckRequestCompleteErrorCode(msgs[0][0], net::ERR_ACCESS_DENIED);
1622 // Tests CancelRequestsForProcess
1623 TEST_F(ResourceDispatcherHostTest, TestProcessCancel) {
1624 scoped_refptr<TestFilter> test_filter = new TestFilter(
1625 browser_context_->GetResourceContext());
1626 child_ids_.insert(test_filter->child_id());
1628 // request 1 goes to the test delegate
1629 ResourceHostMsg_Request request = CreateResourceRequest(
1630 "GET", RESOURCE_TYPE_SUB_RESOURCE, net::URLRequestTestJob::test_url_1());
1632 MakeTestRequestWithResourceType(test_filter.get(), 0, 1,
1633 net::URLRequestTestJob::test_url_1(),
1634 RESOURCE_TYPE_SUB_RESOURCE);
1636 // request 2 goes to us
1637 MakeTestRequest(0, 2, net::URLRequestTestJob::test_url_2());
1639 // request 3 goes to the test delegate
1640 MakeTestRequestWithResourceType(test_filter.get(), 0, 3,
1641 net::URLRequestTestJob::test_url_3(),
1642 RESOURCE_TYPE_SUB_RESOURCE);
1644 // request 4 goes to us
1645 MakeTestRequestWithResourceType(filter_.get(), 0, 4,
1646 net::URLRequestTestJob::test_url_4(),
1647 RESOURCE_TYPE_PREFETCH); // detachable type
1650 // Make sure all requests have finished stage one. test_url_1 will have
1651 // finished.
1652 base::MessageLoop::current()->RunUntilIdle();
1654 // TODO(mbelshe):
1655 // Now that the async IO path is in place, the IO always completes on the
1656 // initial call; so the requests have already completed. This basically
1657 // breaks the whole test.
1658 //EXPECT_EQ(3, host_.pending_requests());
1660 // Process test_url_2 and test_url_3 for one level so one callback is called.
1661 // We'll cancel test_url_4 (detachable) before processing it to verify that it
1662 // delays the cancel.
1663 for (int i = 0; i < 2; i++)
1664 EXPECT_TRUE(net::URLRequestTestJob::ProcessOnePendingMessage());
1666 // Cancel the requests to the test process.
1667 host_.CancelRequestsForProcess(filter_->child_id());
1668 test_filter->set_canceled(true);
1670 // The requests should all be cancelled, except request 4, which is detached.
1671 EXPECT_EQ(1, host_.pending_requests());
1672 GlobalRequestID global_request_id(filter_->child_id(), 4);
1673 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(
1674 host_.GetURLRequest(global_request_id));
1675 ASSERT_TRUE(info->detachable_handler()->is_detached());
1677 // Flush all the pending requests.
1678 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1680 EXPECT_EQ(0, host_.pending_requests());
1682 // The test delegate should not have gotten any messages after being canceled.
1683 ASSERT_EQ(0, test_filter->received_after_canceled());
1685 // There should be two results.
1686 ResourceIPCAccumulator::ClassifiedMessages msgs;
1687 accum_.GetClassifiedMessages(&msgs);
1688 ASSERT_EQ(2U, msgs.size());
1689 CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_2());
1690 // The detachable request was cancelled by the renderer before it
1691 // finished. From the perspective of the renderer, it should have cancelled.
1692 ASSERT_EQ(2U, msgs[1].size());
1693 ASSERT_EQ(ResourceMsg_ReceivedResponse::ID, msgs[1][0].type());
1694 CheckRequestCompleteErrorCode(msgs[1][1], net::ERR_ABORTED);
1695 // But it completed anyway. For the network stack, no requests were canceled.
1696 EXPECT_EQ(4, network_delegate()->completed_requests());
1697 EXPECT_EQ(0, network_delegate()->canceled_requests());
1698 EXPECT_EQ(0, network_delegate()->error_count());
1701 TEST_F(ResourceDispatcherHostTest, TestProcessCancelDetachedTimesOut) {
1702 MakeTestRequestWithResourceType(filter_.get(), 0, 1,
1703 net::URLRequestTestJob::test_url_4(),
1704 RESOURCE_TYPE_PREFETCH); // detachable type
1705 GlobalRequestID global_request_id(filter_->child_id(), 1);
1706 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(
1707 host_.GetURLRequest(global_request_id));
1708 ASSERT_TRUE(info->detachable_handler());
1709 info->detachable_handler()->set_cancel_delay(
1710 base::TimeDelta::FromMilliseconds(200));
1711 base::MessageLoop::current()->RunUntilIdle();
1713 // Cancel the requests to the test process.
1714 host_.CancelRequestsForProcess(filter_->child_id());
1715 EXPECT_EQ(1, host_.pending_requests());
1717 // Wait until after the delay timer times out before we start processing any
1718 // messages.
1719 base::OneShotTimer<base::MessageLoop> timer;
1720 timer.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(210),
1721 base::MessageLoop::current(), &base::MessageLoop::QuitWhenIdle);
1722 base::MessageLoop::current()->Run();
1724 // The prefetch should be cancelled by now.
1725 EXPECT_EQ(0, host_.pending_requests());
1727 // In case any messages are still to be processed.
1728 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1729 base::MessageLoop::current()->RunUntilIdle();
1731 ResourceIPCAccumulator::ClassifiedMessages msgs;
1732 accum_.GetClassifiedMessages(&msgs);
1734 ASSERT_EQ(1U, msgs.size());
1736 // The request should have cancelled.
1737 ASSERT_EQ(2U, msgs[0].size());
1738 ASSERT_EQ(ResourceMsg_ReceivedResponse::ID, msgs[0][0].type());
1739 CheckRequestCompleteErrorCode(msgs[0][1], net::ERR_ABORTED);
1740 // And not run to completion.
1741 EXPECT_EQ(1, network_delegate()->completed_requests());
1742 EXPECT_EQ(1, network_delegate()->canceled_requests());
1743 EXPECT_EQ(0, network_delegate()->error_count());
1746 // Tests blocking and resuming requests.
1747 TEST_F(ResourceDispatcherHostTest, TestBlockingResumingRequests) {
1748 host_.BlockRequestsForRoute(filter_->child_id(), 1);
1749 host_.BlockRequestsForRoute(filter_->child_id(), 2);
1750 host_.BlockRequestsForRoute(filter_->child_id(), 3);
1752 MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_1());
1753 MakeTestRequest(1, 2, net::URLRequestTestJob::test_url_2());
1754 MakeTestRequest(0, 3, net::URLRequestTestJob::test_url_3());
1755 MakeTestRequest(1, 4, net::URLRequestTestJob::test_url_1());
1756 MakeTestRequest(2, 5, net::URLRequestTestJob::test_url_2());
1757 MakeTestRequest(3, 6, net::URLRequestTestJob::test_url_3());
1759 // Flush all the pending requests
1760 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1762 // Sort out all the messages we saw by request
1763 ResourceIPCAccumulator::ClassifiedMessages msgs;
1764 accum_.GetClassifiedMessages(&msgs);
1766 // All requests but the 2 for the RVH 0 should have been blocked.
1767 ASSERT_EQ(2U, msgs.size());
1769 CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_1());
1770 CheckSuccessfulRequest(msgs[1], net::URLRequestTestJob::test_data_3());
1772 // Resume requests for RVH 1 and flush pending requests.
1773 host_.ResumeBlockedRequestsForRoute(filter_->child_id(), 1);
1774 KickOffRequest();
1775 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1777 msgs.clear();
1778 accum_.GetClassifiedMessages(&msgs);
1779 ASSERT_EQ(2U, msgs.size());
1780 CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_2());
1781 CheckSuccessfulRequest(msgs[1], net::URLRequestTestJob::test_data_1());
1783 // Test that new requests are not blocked for RVH 1.
1784 MakeTestRequest(1, 7, net::URLRequestTestJob::test_url_1());
1785 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1786 msgs.clear();
1787 accum_.GetClassifiedMessages(&msgs);
1788 ASSERT_EQ(1U, msgs.size());
1789 CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_1());
1791 // Now resumes requests for all RVH (2 and 3).
1792 host_.ResumeBlockedRequestsForRoute(filter_->child_id(), 2);
1793 host_.ResumeBlockedRequestsForRoute(filter_->child_id(), 3);
1794 KickOffRequest();
1795 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1797 msgs.clear();
1798 accum_.GetClassifiedMessages(&msgs);
1799 ASSERT_EQ(2U, msgs.size());
1800 CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_2());
1801 CheckSuccessfulRequest(msgs[1], net::URLRequestTestJob::test_data_3());
1804 // Tests blocking and canceling requests.
1805 TEST_F(ResourceDispatcherHostTest, TestBlockingCancelingRequests) {
1806 host_.BlockRequestsForRoute(filter_->child_id(), 1);
1808 MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_1());
1809 MakeTestRequest(1, 2, net::URLRequestTestJob::test_url_2());
1810 MakeTestRequest(0, 3, net::URLRequestTestJob::test_url_3());
1811 MakeTestRequest(1, 4, net::URLRequestTestJob::test_url_1());
1812 // Blocked detachable resources should not delay cancellation.
1813 MakeTestRequestWithResourceType(filter_.get(), 1, 5,
1814 net::URLRequestTestJob::test_url_4(),
1815 RESOURCE_TYPE_PREFETCH); // detachable type
1817 // Flush all the pending requests.
1818 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1820 // Sort out all the messages we saw by request.
1821 ResourceIPCAccumulator::ClassifiedMessages msgs;
1822 accum_.GetClassifiedMessages(&msgs);
1824 // The 2 requests for the RVH 0 should have been processed.
1825 ASSERT_EQ(2U, msgs.size());
1827 CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_1());
1828 CheckSuccessfulRequest(msgs[1], net::URLRequestTestJob::test_data_3());
1830 // Cancel requests for RVH 1.
1831 host_.CancelBlockedRequestsForRoute(filter_->child_id(), 1);
1832 KickOffRequest();
1833 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1835 msgs.clear();
1836 accum_.GetClassifiedMessages(&msgs);
1837 ASSERT_EQ(0U, msgs.size());
1840 // Tests that blocked requests are canceled if their associated process dies.
1841 TEST_F(ResourceDispatcherHostTest, TestBlockedRequestsProcessDies) {
1842 // This second filter is used to emulate a second process.
1843 scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
1845 host_.BlockRequestsForRoute(second_filter->child_id(), 0);
1847 MakeTestRequestWithResourceType(filter_.get(), 0, 1,
1848 net::URLRequestTestJob::test_url_1(),
1849 RESOURCE_TYPE_SUB_RESOURCE);
1850 MakeTestRequestWithResourceType(second_filter.get(), 0, 2,
1851 net::URLRequestTestJob::test_url_2(),
1852 RESOURCE_TYPE_SUB_RESOURCE);
1853 MakeTestRequestWithResourceType(filter_.get(), 0, 3,
1854 net::URLRequestTestJob::test_url_3(),
1855 RESOURCE_TYPE_SUB_RESOURCE);
1856 MakeTestRequestWithResourceType(second_filter.get(), 0, 4,
1857 net::URLRequestTestJob::test_url_1(),
1858 RESOURCE_TYPE_SUB_RESOURCE);
1859 MakeTestRequestWithResourceType(second_filter.get(), 0, 5,
1860 net::URLRequestTestJob::test_url_4(),
1861 RESOURCE_TYPE_PREFETCH); // detachable type
1863 // Simulate process death.
1864 host_.CancelRequestsForProcess(second_filter->child_id());
1866 // Flush all the pending requests.
1867 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1869 // Sort out all the messages we saw by request.
1870 ResourceIPCAccumulator::ClassifiedMessages msgs;
1871 accum_.GetClassifiedMessages(&msgs);
1873 // The 2 requests for the RVH 0 should have been processed. Note that
1874 // blocked detachable requests are canceled without delay.
1875 ASSERT_EQ(2U, msgs.size());
1877 CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_1());
1878 CheckSuccessfulRequest(msgs[1], net::URLRequestTestJob::test_data_3());
1880 EXPECT_TRUE(host_.blocked_loaders_map_.empty());
1883 // Tests that blocked requests don't leak when the ResourceDispatcherHost goes
1884 // away. Note that we rely on Purify for finding the leaks if any.
1885 // If this test turns the Purify bot red, check the ResourceDispatcherHost
1886 // destructor to make sure the blocked requests are deleted.
1887 TEST_F(ResourceDispatcherHostTest, TestBlockedRequestsDontLeak) {
1888 // This second filter is used to emulate a second process.
1889 scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
1891 host_.BlockRequestsForRoute(filter_->child_id(), 1);
1892 host_.BlockRequestsForRoute(filter_->child_id(), 2);
1893 host_.BlockRequestsForRoute(second_filter->child_id(), 1);
1895 MakeTestRequestWithResourceType(filter_.get(), 0, 1,
1896 net::URLRequestTestJob::test_url_1(),
1897 RESOURCE_TYPE_SUB_RESOURCE);
1898 MakeTestRequestWithResourceType(filter_.get(), 1, 2,
1899 net::URLRequestTestJob::test_url_2(),
1900 RESOURCE_TYPE_SUB_RESOURCE);
1901 MakeTestRequestWithResourceType(filter_.get(), 0, 3,
1902 net::URLRequestTestJob::test_url_3(),
1903 RESOURCE_TYPE_SUB_RESOURCE);
1904 MakeTestRequestWithResourceType(second_filter.get(), 1, 4,
1905 net::URLRequestTestJob::test_url_1(),
1906 RESOURCE_TYPE_SUB_RESOURCE);
1907 MakeTestRequestWithResourceType(filter_.get(), 2, 5,
1908 net::URLRequestTestJob::test_url_2(),
1909 RESOURCE_TYPE_SUB_RESOURCE);
1910 MakeTestRequestWithResourceType(filter_.get(), 2, 6,
1911 net::URLRequestTestJob::test_url_3(),
1912 RESOURCE_TYPE_SUB_RESOURCE);
1913 MakeTestRequestWithResourceType(filter_.get(), 0, 7,
1914 net::URLRequestTestJob::test_url_4(),
1915 RESOURCE_TYPE_PREFETCH); // detachable type
1916 MakeTestRequestWithResourceType(second_filter.get(), 1, 8,
1917 net::URLRequestTestJob::test_url_4(),
1918 RESOURCE_TYPE_PREFETCH); // detachable type
1920 host_.CancelRequestsForProcess(filter_->child_id());
1921 host_.CancelRequestsForProcess(second_filter->child_id());
1923 // Flush all the pending requests.
1924 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
1927 // Test the private helper method "CalculateApproximateMemoryCost()".
1928 TEST_F(ResourceDispatcherHostTest, CalculateApproximateMemoryCost) {
1929 net::URLRequestContext context;
1930 scoped_ptr<net::URLRequest> req(context.CreateRequest(
1931 GURL("http://www.google.com"), net::DEFAULT_PRIORITY, NULL));
1932 EXPECT_EQ(
1933 4427,
1934 ResourceDispatcherHostImpl::CalculateApproximateMemoryCost(req.get()));
1936 // Add 9 bytes of referrer.
1937 req->SetReferrer("123456789");
1938 EXPECT_EQ(
1939 4436,
1940 ResourceDispatcherHostImpl::CalculateApproximateMemoryCost(req.get()));
1942 // Add 33 bytes of upload content.
1943 std::string upload_content;
1944 upload_content.resize(33);
1945 std::fill(upload_content.begin(), upload_content.end(), 'x');
1946 scoped_ptr<net::UploadElementReader> reader(new net::UploadBytesElementReader(
1947 upload_content.data(), upload_content.size()));
1948 req->set_upload(
1949 net::ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0));
1951 // Since the upload throttling is disabled, this has no effect on the cost.
1952 EXPECT_EQ(
1953 4436,
1954 ResourceDispatcherHostImpl::CalculateApproximateMemoryCost(req.get()));
1957 // Test that too much memory for outstanding requests for a particular
1958 // render_process_host_id causes requests to fail.
1959 TEST_F(ResourceDispatcherHostTest, TooMuchOutstandingRequestsMemory) {
1960 // Expected cost of each request as measured by
1961 // ResourceDispatcherHost::CalculateApproximateMemoryCost().
1962 int kMemoryCostOfTest2Req =
1963 ResourceDispatcherHostImpl::kAvgBytesPerOutstandingRequest +
1964 std::string("GET").size() +
1965 net::URLRequestTestJob::test_url_2().spec().size();
1967 // Tighten the bound on the ResourceDispatcherHost, to speed things up.
1968 int kMaxCostPerProcess = 440000;
1969 host_.set_max_outstanding_requests_cost_per_process(kMaxCostPerProcess);
1971 // Determine how many instance of test_url_2() we can request before
1972 // throttling kicks in.
1973 size_t kMaxRequests = kMaxCostPerProcess / kMemoryCostOfTest2Req;
1975 // This second filter is used to emulate a second process.
1976 scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
1978 // Saturate the number of outstanding requests for our process.
1979 for (size_t i = 0; i < kMaxRequests; ++i) {
1980 MakeTestRequestWithResourceType(filter_.get(), 0, i + 1,
1981 net::URLRequestTestJob::test_url_2(),
1982 RESOURCE_TYPE_SUB_RESOURCE);
1985 // Issue two more requests for our process -- these should fail immediately.
1986 MakeTestRequestWithResourceType(filter_.get(), 0, kMaxRequests + 1,
1987 net::URLRequestTestJob::test_url_2(),
1988 RESOURCE_TYPE_SUB_RESOURCE);
1989 MakeTestRequestWithResourceType(filter_.get(), 0, kMaxRequests + 2,
1990 net::URLRequestTestJob::test_url_2(),
1991 RESOURCE_TYPE_SUB_RESOURCE);
1993 // Issue two requests for the second process -- these should succeed since
1994 // it is just process 0 that is saturated.
1995 MakeTestRequestWithResourceType(second_filter.get(), 0, kMaxRequests + 3,
1996 net::URLRequestTestJob::test_url_2(),
1997 RESOURCE_TYPE_SUB_RESOURCE);
1998 MakeTestRequestWithResourceType(second_filter.get(), 0, kMaxRequests + 4,
1999 net::URLRequestTestJob::test_url_2(),
2000 RESOURCE_TYPE_SUB_RESOURCE);
2002 // Flush all the pending requests.
2003 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
2004 base::MessageLoop::current()->RunUntilIdle();
2006 // Sorts out all the messages we saw by request.
2007 ResourceIPCAccumulator::ClassifiedMessages msgs;
2008 accum_.GetClassifiedMessages(&msgs);
2010 // We issued (kMaxRequests + 4) total requests.
2011 ASSERT_EQ(kMaxRequests + 4, msgs.size());
2013 // Check that the first kMaxRequests succeeded.
2014 for (size_t i = 0; i < kMaxRequests; ++i)
2015 CheckSuccessfulRequest(msgs[i], net::URLRequestTestJob::test_data_2());
2017 // Check that the subsequent two requests (kMaxRequests + 1) and
2018 // (kMaxRequests + 2) were failed, since the per-process bound was reached.
2019 for (int i = 0; i < 2; ++i) {
2020 // Should have sent a single RequestComplete message.
2021 int index = kMaxRequests + i;
2022 CheckFailedRequest(msgs[index], net::URLRequestTestJob::test_data_2(),
2023 net::ERR_INSUFFICIENT_RESOURCES);
2026 // The final 2 requests should have succeeded.
2027 CheckSuccessfulRequest(msgs[kMaxRequests + 2],
2028 net::URLRequestTestJob::test_data_2());
2029 CheckSuccessfulRequest(msgs[kMaxRequests + 3],
2030 net::URLRequestTestJob::test_data_2());
2033 // Test that when too many requests are outstanding for a particular
2034 // render_process_host_id, any subsequent request from it fails. Also verify
2035 // that the global limit is honored.
2036 TEST_F(ResourceDispatcherHostTest, TooManyOutstandingRequests) {
2037 // Tighten the bound on the ResourceDispatcherHost, to speed things up.
2038 const size_t kMaxRequestsPerProcess = 2;
2039 host_.set_max_num_in_flight_requests_per_process(kMaxRequestsPerProcess);
2040 const size_t kMaxRequests = 3;
2041 host_.set_max_num_in_flight_requests(kMaxRequests);
2043 // Needed to emulate additional processes.
2044 scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
2045 scoped_refptr<ForwardingFilter> third_filter = MakeForwardingFilter();
2047 // Saturate the number of outstanding requests for our process.
2048 for (size_t i = 0; i < kMaxRequestsPerProcess; ++i) {
2049 MakeTestRequestWithResourceType(filter_.get(), 0, i + 1,
2050 net::URLRequestTestJob::test_url_2(),
2051 RESOURCE_TYPE_SUB_RESOURCE);
2054 // Issue another request for our process -- this should fail immediately.
2055 MakeTestRequestWithResourceType(filter_.get(), 0, kMaxRequestsPerProcess + 1,
2056 net::URLRequestTestJob::test_url_2(),
2057 RESOURCE_TYPE_SUB_RESOURCE);
2059 // Issue a request for the second process -- this should succeed, because it
2060 // is just process 0 that is saturated.
2061 MakeTestRequestWithResourceType(
2062 second_filter.get(), 0, kMaxRequestsPerProcess + 2,
2063 net::URLRequestTestJob::test_url_2(), RESOURCE_TYPE_SUB_RESOURCE);
2065 // Issue a request for the third process -- this should fail, because the
2066 // global limit has been reached.
2067 MakeTestRequestWithResourceType(
2068 third_filter.get(), 0, kMaxRequestsPerProcess + 3,
2069 net::URLRequestTestJob::test_url_2(), RESOURCE_TYPE_SUB_RESOURCE);
2071 // Flush all the pending requests.
2072 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
2073 base::MessageLoop::current()->RunUntilIdle();
2075 // Sorts out all the messages we saw by request.
2076 ResourceIPCAccumulator::ClassifiedMessages msgs;
2077 accum_.GetClassifiedMessages(&msgs);
2079 // The processes issued the following requests:
2080 // #1 issued kMaxRequestsPerProcess that passed + 1 that failed
2081 // #2 issued 1 request that passed
2082 // #3 issued 1 request that failed
2083 ASSERT_EQ((kMaxRequestsPerProcess + 1) + 1 + 1, msgs.size());
2085 for (size_t i = 0; i < kMaxRequestsPerProcess; ++i)
2086 CheckSuccessfulRequest(msgs[i], net::URLRequestTestJob::test_data_2());
2088 CheckFailedRequest(msgs[kMaxRequestsPerProcess + 0],
2089 net::URLRequestTestJob::test_data_2(),
2090 net::ERR_INSUFFICIENT_RESOURCES);
2091 CheckSuccessfulRequest(msgs[kMaxRequestsPerProcess + 1],
2092 net::URLRequestTestJob::test_data_2());
2093 CheckFailedRequest(msgs[kMaxRequestsPerProcess + 2],
2094 net::URLRequestTestJob::test_data_2(),
2095 net::ERR_INSUFFICIENT_RESOURCES);
2098 // Tests that we sniff the mime type for a simple request.
2099 TEST_F(ResourceDispatcherHostTest, MimeSniffed) {
2100 std::string raw_headers("HTTP/1.1 200 OK\n\n");
2101 std::string response_data("<html><title>Test One</title></html>");
2102 SetResponse(raw_headers, response_data);
2104 HandleScheme("http");
2105 MakeTestRequest(0, 1, GURL("http:bla"));
2107 // Flush all pending requests.
2108 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
2110 // Sorts out all the messages we saw by request.
2111 ResourceIPCAccumulator::ClassifiedMessages msgs;
2112 accum_.GetClassifiedMessages(&msgs);
2113 ASSERT_EQ(1U, msgs.size());
2115 ResourceResponseHead response_head;
2116 GetResponseHead(msgs[0], &response_head);
2117 ASSERT_EQ("text/html", response_head.mime_type);
2120 // Tests that we don't sniff the mime type when the server provides one.
2121 TEST_F(ResourceDispatcherHostTest, MimeNotSniffed) {
2122 std::string raw_headers("HTTP/1.1 200 OK\n"
2123 "Content-type: image/jpeg\n\n");
2124 std::string response_data("<html><title>Test One</title></html>");
2125 SetResponse(raw_headers, response_data);
2127 HandleScheme("http");
2128 MakeTestRequest(0, 1, GURL("http:bla"));
2130 // Flush all pending requests.
2131 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
2133 // Sorts out all the messages we saw by request.
2134 ResourceIPCAccumulator::ClassifiedMessages msgs;
2135 accum_.GetClassifiedMessages(&msgs);
2136 ASSERT_EQ(1U, msgs.size());
2138 ResourceResponseHead response_head;
2139 GetResponseHead(msgs[0], &response_head);
2140 ASSERT_EQ("image/jpeg", response_head.mime_type);
2143 // Tests that we don't sniff the mime type when there is no message body.
2144 TEST_F(ResourceDispatcherHostTest, MimeNotSniffed2) {
2145 SetResponse("HTTP/1.1 304 Not Modified\n\n");
2147 HandleScheme("http");
2148 MakeTestRequest(0, 1, GURL("http:bla"));
2150 // Flush all pending requests.
2151 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
2153 // Sorts out all the messages we saw by request.
2154 ResourceIPCAccumulator::ClassifiedMessages msgs;
2155 accum_.GetClassifiedMessages(&msgs);
2156 ASSERT_EQ(1U, msgs.size());
2158 ResourceResponseHead response_head;
2159 GetResponseHead(msgs[0], &response_head);
2160 ASSERT_EQ("", response_head.mime_type);
2163 TEST_F(ResourceDispatcherHostTest, MimeSniff204) {
2164 SetResponse("HTTP/1.1 204 No Content\n\n");
2166 HandleScheme("http");
2167 MakeTestRequest(0, 1, GURL("http:bla"));
2169 // Flush all pending requests.
2170 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
2172 // Sorts out all the messages we saw by request.
2173 ResourceIPCAccumulator::ClassifiedMessages msgs;
2174 accum_.GetClassifiedMessages(&msgs);
2175 ASSERT_EQ(1U, msgs.size());
2177 ResourceResponseHead response_head;
2178 GetResponseHead(msgs[0], &response_head);
2179 ASSERT_EQ("text/plain", response_head.mime_type);
2182 TEST_F(ResourceDispatcherHostTest, MimeSniffEmpty) {
2183 SetResponse("HTTP/1.1 200 OK\n\n");
2185 HandleScheme("http");
2186 MakeTestRequest(0, 1, GURL("http:bla"));
2188 // Flush all pending requests.
2189 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
2191 // Sorts out all the messages we saw by request.
2192 ResourceIPCAccumulator::ClassifiedMessages msgs;
2193 accum_.GetClassifiedMessages(&msgs);
2194 ASSERT_EQ(1U, msgs.size());
2196 ResourceResponseHead response_head;
2197 GetResponseHead(msgs[0], &response_head);
2198 ASSERT_EQ("text/plain", response_head.mime_type);
2201 // Tests for crbug.com/31266 (Non-2xx + application/octet-stream).
2202 TEST_F(ResourceDispatcherHostTest, ForbiddenDownload) {
2203 std::string raw_headers("HTTP/1.1 403 Forbidden\n"
2204 "Content-disposition: attachment; filename=blah\n"
2205 "Content-type: application/octet-stream\n\n");
2206 std::string response_data("<html><title>Test One</title></html>");
2207 SetResponse(raw_headers, response_data);
2209 HandleScheme("http");
2211 // Only MAIN_FRAMEs can trigger a download.
2212 MakeTestRequestWithResourceType(filter_.get(), 0, 1, GURL("http:bla"),
2213 RESOURCE_TYPE_MAIN_FRAME);
2215 // Flush all pending requests.
2216 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
2217 base::MessageLoop::current()->RunUntilIdle();
2219 // Sorts out all the messages we saw by request.
2220 ResourceIPCAccumulator::ClassifiedMessages msgs;
2221 accum_.GetClassifiedMessages(&msgs);
2223 // We should have gotten one RequestComplete message.
2224 ASSERT_EQ(1U, msgs.size());
2225 ASSERT_EQ(1U, msgs[0].size());
2226 EXPECT_EQ(ResourceMsg_RequestComplete::ID, msgs[0][0].type());
2228 // The RequestComplete message should have had the error code of
2229 // ERR_INVALID_RESPONSE.
2230 CheckRequestCompleteErrorCode(msgs[0][0], net::ERR_INVALID_RESPONSE);
2233 // Test for http://crbug.com/76202 . We don't want to destroy a
2234 // download request prematurely when processing a cancellation from
2235 // the renderer.
2236 TEST_F(ResourceDispatcherHostTest, IgnoreCancelForDownloads) {
2237 EXPECT_EQ(0, host_.pending_requests());
2239 int render_view_id = 0;
2240 int request_id = 1;
2242 std::string raw_headers("HTTP\n"
2243 "Content-disposition: attachment; filename=foo\n\n");
2244 std::string response_data("01234567890123456789\x01foobar");
2246 // Get past sniffing metrics in the MimeTypeResourceHandler. Note that
2247 // if we don't get past the sniffing metrics, the result will be that
2248 // the MimeTypeResourceHandler won't have figured out that it's a download,
2249 // won't have constructed a DownloadResourceHandler, and and the request will
2250 // be successfully canceled below, failing the test.
2251 response_data.resize(1025, ' ');
2253 SetResponse(raw_headers, response_data);
2254 job_factory_->SetDelayedCompleteJobGeneration(true);
2255 HandleScheme("http");
2257 MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
2258 GURL("http://example.com/blah"),
2259 RESOURCE_TYPE_MAIN_FRAME);
2260 // Return some data so that the request is identified as a download
2261 // and the proper resource handlers are created.
2262 EXPECT_TRUE(net::URLRequestTestJob::ProcessOnePendingMessage());
2264 // And now simulate a cancellation coming from the renderer.
2265 ResourceHostMsg_CancelRequest msg(request_id);
2266 host_.OnMessageReceived(msg, filter_.get());
2268 // Since the request had already started processing as a download,
2269 // the cancellation above should have been ignored and the request
2270 // should still be alive.
2271 EXPECT_EQ(1, host_.pending_requests());
2273 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
2276 TEST_F(ResourceDispatcherHostTest, CancelRequestsForContext) {
2277 EXPECT_EQ(0, host_.pending_requests());
2279 int render_view_id = 0;
2280 int request_id = 1;
2282 std::string raw_headers("HTTP\n"
2283 "Content-disposition: attachment; filename=foo\n\n");
2284 std::string response_data("01234567890123456789\x01foobar");
2285 // Get past sniffing metrics.
2286 response_data.resize(1025, ' ');
2288 SetResponse(raw_headers, response_data);
2289 job_factory_->SetDelayedCompleteJobGeneration(true);
2290 HandleScheme("http");
2292 MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
2293 GURL("http://example.com/blah"),
2294 RESOURCE_TYPE_MAIN_FRAME);
2295 // Return some data so that the request is identified as a download
2296 // and the proper resource handlers are created.
2297 EXPECT_TRUE(net::URLRequestTestJob::ProcessOnePendingMessage());
2299 // And now simulate a cancellation coming from the renderer.
2300 ResourceHostMsg_CancelRequest msg(request_id);
2301 host_.OnMessageReceived(msg, filter_.get());
2303 // Since the request had already started processing as a download,
2304 // the cancellation above should have been ignored and the request
2305 // should still be alive.
2306 EXPECT_EQ(1, host_.pending_requests());
2308 // Cancelling by other methods shouldn't work either.
2309 host_.CancelRequestsForProcess(render_view_id);
2310 EXPECT_EQ(1, host_.pending_requests());
2312 // Cancelling by context should work.
2313 host_.CancelRequestsForContext(filter_->resource_context());
2314 EXPECT_EQ(0, host_.pending_requests());
2317 TEST_F(ResourceDispatcherHostTest, CancelRequestsForContextDetached) {
2318 EXPECT_EQ(0, host_.pending_requests());
2320 int render_view_id = 0;
2321 int request_id = 1;
2323 MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
2324 net::URLRequestTestJob::test_url_4(),
2325 RESOURCE_TYPE_PREFETCH); // detachable type
2327 // Simulate a cancel coming from the renderer.
2328 RendererCancelRequest(request_id);
2330 // Since the request had already started processing as detachable,
2331 // the cancellation above should have been ignored and the request
2332 // should have been detached.
2333 EXPECT_EQ(1, host_.pending_requests());
2335 // Cancelling by other methods should also leave it detached.
2336 host_.CancelRequestsForProcess(render_view_id);
2337 EXPECT_EQ(1, host_.pending_requests());
2339 // Cancelling by context should work.
2340 host_.CancelRequestsForContext(filter_->resource_context());
2341 EXPECT_EQ(0, host_.pending_requests());
2344 // Test the cancelling of requests that are being transferred to a new renderer
2345 // due to a redirection.
2346 TEST_F(ResourceDispatcherHostTest, CancelRequestsForContextTransferred) {
2347 EXPECT_EQ(0, host_.pending_requests());
2349 int render_view_id = 0;
2350 int request_id = 1;
2352 std::string raw_headers("HTTP/1.1 200 OK\n"
2353 "Content-Type: text/html; charset=utf-8\n\n");
2354 std::string response_data("<html>foobar</html>");
2356 SetResponse(raw_headers, response_data);
2357 HandleScheme("http");
2359 MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
2360 GURL("http://example.com/blah"),
2361 RESOURCE_TYPE_MAIN_FRAME);
2364 GlobalRequestID global_request_id(filter_->child_id(), request_id);
2365 host_.MarkAsTransferredNavigation(global_request_id);
2367 // And now simulate a cancellation coming from the renderer.
2368 ResourceHostMsg_CancelRequest msg(request_id);
2369 host_.OnMessageReceived(msg, filter_.get());
2371 // Since the request is marked as being transferred,
2372 // the cancellation above should have been ignored and the request
2373 // should still be alive.
2374 EXPECT_EQ(1, host_.pending_requests());
2376 // Cancelling by other methods shouldn't work either.
2377 host_.CancelRequestsForProcess(render_view_id);
2378 EXPECT_EQ(1, host_.pending_requests());
2380 // Cancelling by context should work.
2381 host_.CancelRequestsForContext(filter_->resource_context());
2382 EXPECT_EQ(0, host_.pending_requests());
2385 // Test transferred navigations with text/html, which doesn't trigger any
2386 // content sniffing.
2387 TEST_F(ResourceDispatcherHostTest, TransferNavigationHtml) {
2388 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2389 switches::kEnableBrowserSideNavigation)) {
2390 SUCCEED() << "Test is not applicable with browser side navigation enabled";
2391 return;
2393 // This test expects the cross site request to be leaked, so it can transfer
2394 // the request directly.
2395 CrossSiteResourceHandler::SetLeakRequestsForTesting(true);
2397 EXPECT_EQ(0, host_.pending_requests());
2399 int render_view_id = 0;
2400 int request_id = 1;
2402 // Configure initial request.
2403 SetResponse("HTTP/1.1 302 Found\n"
2404 "Location: http://other.com/blech\n\n");
2406 HandleScheme("http");
2408 // Temporarily replace ContentBrowserClient with one that will trigger the
2409 // transfer navigation code paths.
2410 TransfersAllNavigationsContentBrowserClient new_client;
2411 ContentBrowserClient* old_client = SetBrowserClientForTesting(&new_client);
2413 MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
2414 GURL("http://example.com/blah"),
2415 RESOURCE_TYPE_MAIN_FRAME);
2417 // Now that we're blocked on the redirect, update the response and unblock by
2418 // telling the AsyncResourceHandler to follow the redirect.
2419 const std::string kResponseBody = "hello world";
2420 SetResponse("HTTP/1.1 200 OK\n"
2421 "Content-Type: text/html\n\n",
2422 kResponseBody);
2423 ResourceHostMsg_FollowRedirect redirect_msg(request_id);
2424 host_.OnMessageReceived(redirect_msg, filter_.get());
2425 base::MessageLoop::current()->RunUntilIdle();
2427 // Flush all the pending requests to get the response through the
2428 // MimeTypeResourceHandler.
2429 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
2431 // Restore, now that we've set up a transfer.
2432 SetBrowserClientForTesting(old_client);
2434 // This second filter is used to emulate a second process.
2435 scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
2437 int new_render_view_id = 1;
2438 int new_request_id = 2;
2440 ResourceHostMsg_Request request =
2441 CreateResourceRequest("GET", RESOURCE_TYPE_MAIN_FRAME,
2442 GURL("http://other.com/blech"));
2443 request.transferred_request_child_id = filter_->child_id();
2444 request.transferred_request_request_id = request_id;
2446 ResourceHostMsg_RequestResource transfer_request_msg(
2447 new_render_view_id, new_request_id, request);
2448 host_.OnMessageReceived(transfer_request_msg, second_filter.get());
2449 base::MessageLoop::current()->RunUntilIdle();
2451 // Check generated messages.
2452 ResourceIPCAccumulator::ClassifiedMessages msgs;
2453 accum_.GetClassifiedMessages(&msgs);
2455 ASSERT_EQ(2U, msgs.size());
2456 EXPECT_EQ(ResourceMsg_ReceivedRedirect::ID, msgs[0][0].type());
2457 CheckSuccessfulRequest(msgs[1], kResponseBody);
2460 // Test transferring two navigations with text/html, to ensure the resource
2461 // accounting works.
2462 TEST_F(ResourceDispatcherHostTest, TransferTwoNavigationsHtml) {
2463 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2464 switches::kEnableBrowserSideNavigation)) {
2465 SUCCEED() << "Test is not applicable with browser side navigation enabled";
2466 return;
2468 // This test expects the cross site request to be leaked, so it can transfer
2469 // the request directly.
2470 CrossSiteResourceHandler::SetLeakRequestsForTesting(true);
2472 EXPECT_EQ(0, host_.pending_requests());
2474 int render_view_id = 0;
2475 int request_id = 1;
2477 // Configure initial request.
2478 const std::string kResponseBody = "hello world";
2479 SetResponse("HTTP/1.1 200 OK\n"
2480 "Content-Type: text/html\n\n",
2481 kResponseBody);
2483 HandleScheme("http");
2485 // Temporarily replace ContentBrowserClient with one that will trigger the
2486 // transfer navigation code paths.
2487 TransfersAllNavigationsContentBrowserClient new_client;
2488 ContentBrowserClient* old_client = SetBrowserClientForTesting(&new_client);
2490 // Make the first request.
2491 MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
2492 GURL("http://example.com/blah"),
2493 RESOURCE_TYPE_MAIN_FRAME);
2495 // Make a second request from the same process.
2496 int second_request_id = 2;
2497 MakeTestRequestWithResourceType(filter_.get(), render_view_id,
2498 second_request_id,
2499 GURL("http://example.com/foo"),
2500 RESOURCE_TYPE_MAIN_FRAME);
2502 // Flush all the pending requests to get the response through the
2503 // MimeTypeResourceHandler.
2504 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
2506 // Restore, now that we've set up a transfer.
2507 SetBrowserClientForTesting(old_client);
2509 // This second filter is used to emulate a second process.
2510 scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
2512 // Transfer the first request.
2513 int new_render_view_id = 1;
2514 int new_request_id = 5;
2515 ResourceHostMsg_Request request =
2516 CreateResourceRequest("GET", RESOURCE_TYPE_MAIN_FRAME,
2517 GURL("http://example.com/blah"));
2518 request.transferred_request_child_id = filter_->child_id();
2519 request.transferred_request_request_id = request_id;
2521 ResourceHostMsg_RequestResource transfer_request_msg(
2522 new_render_view_id, new_request_id, request);
2523 host_.OnMessageReceived(transfer_request_msg, second_filter.get());
2524 base::MessageLoop::current()->RunUntilIdle();
2526 // Transfer the second request.
2527 int new_second_request_id = 6;
2528 ResourceHostMsg_Request second_request =
2529 CreateResourceRequest("GET", RESOURCE_TYPE_MAIN_FRAME,
2530 GURL("http://example.com/foo"));
2531 request.transferred_request_child_id = filter_->child_id();
2532 request.transferred_request_request_id = second_request_id;
2534 ResourceHostMsg_RequestResource second_transfer_request_msg(
2535 new_render_view_id, new_second_request_id, second_request);
2536 host_.OnMessageReceived(second_transfer_request_msg, second_filter.get());
2537 base::MessageLoop::current()->RunUntilIdle();
2539 // Check generated messages.
2540 ResourceIPCAccumulator::ClassifiedMessages msgs;
2541 accum_.GetClassifiedMessages(&msgs);
2543 ASSERT_EQ(2U, msgs.size());
2544 CheckSuccessfulRequest(msgs[0], kResponseBody);
2547 // Test transferred navigations with text/plain, which causes
2548 // MimeTypeResourceHandler to buffer the response to sniff the content before
2549 // the transfer occurs.
2550 TEST_F(ResourceDispatcherHostTest, TransferNavigationText) {
2551 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2552 switches::kEnableBrowserSideNavigation)) {
2553 SUCCEED() << "Test is not applicable with browser side navigation enabled";
2554 return;
2556 // This test expects the cross site request to be leaked, so it can transfer
2557 // the request directly.
2558 CrossSiteResourceHandler::SetLeakRequestsForTesting(true);
2560 EXPECT_EQ(0, host_.pending_requests());
2562 int render_view_id = 0;
2563 int request_id = 1;
2565 // Configure initial request.
2566 SetResponse("HTTP/1.1 302 Found\n"
2567 "Location: http://other.com/blech\n\n");
2569 HandleScheme("http");
2571 // Temporarily replace ContentBrowserClient with one that will trigger the
2572 // transfer navigation code paths.
2573 TransfersAllNavigationsContentBrowserClient new_client;
2574 ContentBrowserClient* old_client = SetBrowserClientForTesting(&new_client);
2576 MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
2577 GURL("http://example.com/blah"),
2578 RESOURCE_TYPE_MAIN_FRAME);
2580 // Now that we're blocked on the redirect, update the response and unblock by
2581 // telling the AsyncResourceHandler to follow the redirect. Use a text/plain
2582 // MIME type, which causes MimeTypeResourceHandler to buffer it before the
2583 // transfer occurs.
2584 const std::string kResponseBody = "hello world";
2585 SetResponse("HTTP/1.1 200 OK\n"
2586 "Content-Type: text/plain\n\n",
2587 kResponseBody);
2588 ResourceHostMsg_FollowRedirect redirect_msg(request_id);
2589 host_.OnMessageReceived(redirect_msg, filter_.get());
2590 base::MessageLoop::current()->RunUntilIdle();
2592 // Flush all the pending requests to get the response through the
2593 // MimeTypeResourceHandler.
2594 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
2596 // Restore, now that we've set up a transfer.
2597 SetBrowserClientForTesting(old_client);
2599 // This second filter is used to emulate a second process.
2600 scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
2602 int new_render_view_id = 1;
2603 int new_request_id = 2;
2605 ResourceHostMsg_Request request =
2606 CreateResourceRequest("GET", RESOURCE_TYPE_MAIN_FRAME,
2607 GURL("http://other.com/blech"));
2608 request.transferred_request_child_id = filter_->child_id();
2609 request.transferred_request_request_id = request_id;
2611 ResourceHostMsg_RequestResource transfer_request_msg(
2612 new_render_view_id, new_request_id, request);
2613 host_.OnMessageReceived(transfer_request_msg, second_filter.get());
2614 base::MessageLoop::current()->RunUntilIdle();
2616 // Check generated messages.
2617 ResourceIPCAccumulator::ClassifiedMessages msgs;
2618 accum_.GetClassifiedMessages(&msgs);
2620 ASSERT_EQ(2U, msgs.size());
2621 EXPECT_EQ(ResourceMsg_ReceivedRedirect::ID, msgs[0][0].type());
2622 CheckSuccessfulRequest(msgs[1], kResponseBody);
2625 TEST_F(ResourceDispatcherHostTest, TransferNavigationWithProcessCrash) {
2626 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2627 switches::kEnableBrowserSideNavigation)) {
2628 SUCCEED() << "Test is not applicable with browser side navigation enabled";
2629 return;
2631 // This test expects the cross site request to be leaked, so it can transfer
2632 // the request directly.
2633 CrossSiteResourceHandler::SetLeakRequestsForTesting(true);
2635 EXPECT_EQ(0, host_.pending_requests());
2637 int render_view_id = 0;
2638 int request_id = 1;
2639 int first_child_id = -1;
2641 // Configure initial request.
2642 SetResponse("HTTP/1.1 302 Found\n"
2643 "Location: http://other.com/blech\n\n");
2644 const std::string kResponseBody = "hello world";
2646 HandleScheme("http");
2648 // Temporarily replace ContentBrowserClient with one that will trigger the
2649 // transfer navigation code paths.
2650 TransfersAllNavigationsContentBrowserClient new_client;
2651 ContentBrowserClient* old_client = SetBrowserClientForTesting(&new_client);
2653 // Create a first filter that can be deleted before the second one starts.
2655 scoped_refptr<ForwardingFilter> first_filter = MakeForwardingFilter();
2656 first_child_id = first_filter->child_id();
2658 ResourceHostMsg_Request first_request =
2659 CreateResourceRequest("GET", RESOURCE_TYPE_MAIN_FRAME,
2660 GURL("http://example.com/blah"));
2662 ResourceHostMsg_RequestResource first_request_msg(
2663 render_view_id, request_id, first_request);
2664 host_.OnMessageReceived(first_request_msg, first_filter.get());
2665 base::MessageLoop::current()->RunUntilIdle();
2667 // Now that we're blocked on the redirect, update the response and unblock
2668 // by telling the AsyncResourceHandler to follow the redirect.
2669 SetResponse("HTTP/1.1 200 OK\n"
2670 "Content-Type: text/html\n\n",
2671 kResponseBody);
2672 ResourceHostMsg_FollowRedirect redirect_msg(request_id);
2673 host_.OnMessageReceived(redirect_msg, first_filter.get());
2674 base::MessageLoop::current()->RunUntilIdle();
2676 // Flush all the pending requests to get the response through the
2677 // MimeTypeResourceHandler.
2678 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
2680 // The first filter is now deleted, as if the child process died.
2682 // Restore.
2683 SetBrowserClientForTesting(old_client);
2685 // Make sure we don't hold onto the ResourceMessageFilter after it is deleted.
2686 GlobalRequestID first_global_request_id(first_child_id, request_id);
2688 // This second filter is used to emulate a second process.
2689 scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
2691 int new_render_view_id = 1;
2692 int new_request_id = 2;
2694 ResourceHostMsg_Request request =
2695 CreateResourceRequest("GET", RESOURCE_TYPE_MAIN_FRAME,
2696 GURL("http://other.com/blech"));
2697 request.transferred_request_child_id = first_child_id;
2698 request.transferred_request_request_id = request_id;
2700 // For cleanup.
2701 child_ids_.insert(second_filter->child_id());
2702 ResourceHostMsg_RequestResource transfer_request_msg(
2703 new_render_view_id, new_request_id, request);
2704 host_.OnMessageReceived(transfer_request_msg, second_filter.get());
2705 base::MessageLoop::current()->RunUntilIdle();
2707 // Check generated messages.
2708 ResourceIPCAccumulator::ClassifiedMessages msgs;
2709 accum_.GetClassifiedMessages(&msgs);
2711 ASSERT_EQ(2U, msgs.size());
2712 EXPECT_EQ(ResourceMsg_ReceivedRedirect::ID, msgs[0][0].type());
2713 CheckSuccessfulRequest(msgs[1], kResponseBody);
2716 TEST_F(ResourceDispatcherHostTest, TransferNavigationWithTwoRedirects) {
2717 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2718 switches::kEnableBrowserSideNavigation)) {
2719 SUCCEED() << "Test is not applicable with browser side navigation enabled";
2720 return;
2722 // This test expects the cross site request to be leaked, so it can transfer
2723 // the request directly.
2724 CrossSiteResourceHandler::SetLeakRequestsForTesting(true);
2726 EXPECT_EQ(0, host_.pending_requests());
2728 int render_view_id = 0;
2729 int request_id = 1;
2731 // Configure initial request.
2732 SetResponse("HTTP/1.1 302 Found\n"
2733 "Location: http://other.com/blech\n\n");
2735 HandleScheme("http");
2737 // Temporarily replace ContentBrowserClient with one that will trigger the
2738 // transfer navigation code paths.
2739 TransfersAllNavigationsContentBrowserClient new_client;
2740 ContentBrowserClient* old_client = SetBrowserClientForTesting(&new_client);
2742 MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
2743 GURL("http://example.com/blah"),
2744 RESOURCE_TYPE_MAIN_FRAME);
2746 // Now that we're blocked on the redirect, simulate hitting another redirect.
2747 SetResponse("HTTP/1.1 302 Found\n"
2748 "Location: http://other.com/blerg\n\n");
2749 ResourceHostMsg_FollowRedirect redirect_msg(request_id);
2750 host_.OnMessageReceived(redirect_msg, filter_.get());
2751 base::MessageLoop::current()->RunUntilIdle();
2753 // Now that we're blocked on the second redirect, update the response and
2754 // unblock by telling the AsyncResourceHandler to follow the redirect.
2755 // Again, use text/plain to force MimeTypeResourceHandler to buffer before
2756 // the transfer.
2757 const std::string kResponseBody = "hello world";
2758 SetResponse("HTTP/1.1 200 OK\n"
2759 "Content-Type: text/plain\n\n",
2760 kResponseBody);
2761 ResourceHostMsg_FollowRedirect redirect_msg2(request_id);
2762 host_.OnMessageReceived(redirect_msg2, filter_.get());
2763 base::MessageLoop::current()->RunUntilIdle();
2765 // Flush all the pending requests to get the response through the
2766 // MimeTypeResourceHandler.
2767 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
2769 // Restore.
2770 SetBrowserClientForTesting(old_client);
2772 // This second filter is used to emulate a second process.
2773 scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
2775 int new_render_view_id = 1;
2776 int new_request_id = 2;
2778 ResourceHostMsg_Request request =
2779 CreateResourceRequest("GET", RESOURCE_TYPE_MAIN_FRAME,
2780 GURL("http://other.com/blech"));
2781 request.transferred_request_child_id = filter_->child_id();
2782 request.transferred_request_request_id = request_id;
2784 // For cleanup.
2785 child_ids_.insert(second_filter->child_id());
2786 ResourceHostMsg_RequestResource transfer_request_msg(
2787 new_render_view_id, new_request_id, request);
2788 host_.OnMessageReceived(transfer_request_msg, second_filter.get());
2790 // Verify that we update the ResourceRequestInfo.
2791 GlobalRequestID global_request_id(second_filter->child_id(), new_request_id);
2792 const ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(
2793 host_.GetURLRequest(global_request_id));
2794 EXPECT_EQ(second_filter->child_id(), info->GetChildID());
2795 EXPECT_EQ(new_render_view_id, info->GetRouteID());
2796 EXPECT_EQ(new_request_id, info->GetRequestID());
2797 EXPECT_EQ(second_filter.get(), info->filter());
2799 // Let request complete.
2800 base::MessageLoop::current()->RunUntilIdle();
2802 // Check generated messages.
2803 ResourceIPCAccumulator::ClassifiedMessages msgs;
2804 accum_.GetClassifiedMessages(&msgs);
2806 ASSERT_EQ(2U, msgs.size());
2807 EXPECT_EQ(ResourceMsg_ReceivedRedirect::ID, msgs[0][0].type());
2808 CheckSuccessfulRequest(msgs[1], kResponseBody);
2811 TEST_F(ResourceDispatcherHostTest, UnknownURLScheme) {
2812 EXPECT_EQ(0, host_.pending_requests());
2814 HandleScheme("http");
2816 MakeTestRequestWithResourceType(filter_.get(), 0, 1, GURL("foo://bar"),
2817 RESOURCE_TYPE_MAIN_FRAME);
2819 // Flush all pending requests.
2820 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
2822 // Sort all the messages we saw by request.
2823 ResourceIPCAccumulator::ClassifiedMessages msgs;
2824 accum_.GetClassifiedMessages(&msgs);
2826 // We should have gotten one RequestComplete message.
2827 ASSERT_EQ(1U, msgs[0].size());
2828 EXPECT_EQ(ResourceMsg_RequestComplete::ID, msgs[0][0].type());
2830 // The RequestComplete message should have the error code of
2831 // ERR_UNKNOWN_URL_SCHEME.
2832 CheckRequestCompleteErrorCode(msgs[0][0], net::ERR_UNKNOWN_URL_SCHEME);
2835 TEST_F(ResourceDispatcherHostTest, DataReceivedACKs) {
2836 EXPECT_EQ(0, host_.pending_requests());
2838 SendDataReceivedACKs(true);
2840 HandleScheme("big-job");
2841 MakeTestRequest(0, 1, GURL("big-job:0123456789,1000000"));
2843 base::RunLoop().RunUntilIdle();
2845 // Sort all the messages we saw by request.
2846 ResourceIPCAccumulator::ClassifiedMessages msgs;
2847 accum_.GetClassifiedMessages(&msgs);
2849 size_t size = msgs[0].size();
2851 EXPECT_EQ(ResourceMsg_ReceivedResponse::ID, msgs[0][0].type());
2852 EXPECT_EQ(ResourceMsg_SetDataBuffer::ID, msgs[0][1].type());
2853 for (size_t i = 2; i < size - 1; ++i)
2854 EXPECT_EQ(ResourceMsg_DataReceived::ID, msgs[0][i].type());
2855 EXPECT_EQ(ResourceMsg_RequestComplete::ID, msgs[0][size - 1].type());
2858 // Request a very large detachable resource and cancel part way. Some of the
2859 // data should have been sent to the renderer, but not all.
2860 TEST_F(ResourceDispatcherHostTest, DataSentBeforeDetach) {
2861 EXPECT_EQ(0, host_.pending_requests());
2863 int render_view_id = 0;
2864 int request_id = 1;
2866 std::string raw_headers("HTTP\n"
2867 "Content-type: image/jpeg\n\n");
2868 std::string response_data("01234567890123456789\x01foobar");
2870 // Create a response larger than kMaxAllocationSize (currently 32K). Note
2871 // that if this increase beyond 512K we'll need to make the response longer.
2872 const int kAllocSize = 1024*512;
2873 response_data.resize(kAllocSize, ' ');
2875 SetResponse(raw_headers, response_data);
2876 job_factory_->SetDelayedCompleteJobGeneration(true);
2877 HandleScheme("http");
2879 MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
2880 GURL("http://example.com/blah"),
2881 RESOURCE_TYPE_PREFETCH);
2883 // Get a bit of data before cancelling.
2884 EXPECT_TRUE(net::URLRequestTestJob::ProcessOnePendingMessage());
2886 // Simulate a cancellation coming from the renderer.
2887 ResourceHostMsg_CancelRequest msg(request_id);
2888 host_.OnMessageReceived(msg, filter_.get());
2890 EXPECT_EQ(1, host_.pending_requests());
2892 while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
2894 // Sort all the messages we saw by request.
2895 ResourceIPCAccumulator::ClassifiedMessages msgs;
2896 accum_.GetClassifiedMessages(&msgs);
2898 EXPECT_EQ(4U, msgs[0].size());
2900 // Figure out how many bytes were received by the renderer.
2901 int data_offset;
2902 int data_length;
2903 ASSERT_TRUE(
2904 ExtractDataOffsetAndLength(msgs[0][2], &data_offset, &data_length));
2905 EXPECT_LT(0, data_length);
2906 EXPECT_GT(kAllocSize, data_length);
2908 // Verify the data that was received before cancellation. The request should
2909 // have appeared to cancel, however.
2910 CheckSuccessfulRequestWithErrorCode(
2911 msgs[0],
2912 std::string(response_data.begin(), response_data.begin() + data_length),
2913 net::ERR_ABORTED);
2916 TEST_F(ResourceDispatcherHostTest, DelayedDataReceivedACKs) {
2917 EXPECT_EQ(0, host_.pending_requests());
2919 HandleScheme("big-job");
2920 MakeTestRequest(0, 1, GURL("big-job:0123456789,1000000"));
2922 base::RunLoop().RunUntilIdle();
2924 // Sort all the messages we saw by request.
2925 ResourceIPCAccumulator::ClassifiedMessages msgs;
2926 accum_.GetClassifiedMessages(&msgs);
2928 // We expect 1x ReceivedResponse, 1x SetDataBuffer, Nx ReceivedData messages.
2929 EXPECT_EQ(ResourceMsg_ReceivedResponse::ID, msgs[0][0].type());
2930 EXPECT_EQ(ResourceMsg_SetDataBuffer::ID, msgs[0][1].type());
2931 for (size_t i = 2; i < msgs[0].size(); ++i)
2932 EXPECT_EQ(ResourceMsg_DataReceived::ID, msgs[0][i].type());
2934 // NOTE: If we fail the above checks then it means that we probably didn't
2935 // load a big enough response to trigger the delay mechanism we are trying to
2936 // test!
2938 msgs[0].erase(msgs[0].begin());
2939 msgs[0].erase(msgs[0].begin());
2941 // ACK all DataReceived messages until we find a RequestComplete message.
2942 bool complete = false;
2943 while (!complete) {
2944 for (size_t i = 0; i < msgs[0].size(); ++i) {
2945 if (msgs[0][i].type() == ResourceMsg_RequestComplete::ID) {
2946 complete = true;
2947 break;
2950 EXPECT_EQ(ResourceMsg_DataReceived::ID, msgs[0][i].type());
2952 ResourceHostMsg_DataReceived_ACK msg(1);
2953 host_.OnMessageReceived(msg, filter_.get());
2956 base::MessageLoop::current()->RunUntilIdle();
2958 msgs.clear();
2959 accum_.GetClassifiedMessages(&msgs);
2963 // Flakyness of this test might indicate memory corruption issues with
2964 // for example the ResourceBuffer of AsyncResourceHandler.
2965 TEST_F(ResourceDispatcherHostTest, DataReceivedUnexpectedACKs) {
2966 EXPECT_EQ(0, host_.pending_requests());
2968 HandleScheme("big-job");
2969 MakeTestRequest(0, 1, GURL("big-job:0123456789,1000000"));
2971 base::RunLoop().RunUntilIdle();
2973 // Sort all the messages we saw by request.
2974 ResourceIPCAccumulator::ClassifiedMessages msgs;
2975 accum_.GetClassifiedMessages(&msgs);
2977 // We expect 1x ReceivedResponse, 1x SetDataBuffer, Nx ReceivedData messages.
2978 EXPECT_EQ(ResourceMsg_ReceivedResponse::ID, msgs[0][0].type());
2979 EXPECT_EQ(ResourceMsg_SetDataBuffer::ID, msgs[0][1].type());
2980 for (size_t i = 2; i < msgs[0].size(); ++i)
2981 EXPECT_EQ(ResourceMsg_DataReceived::ID, msgs[0][i].type());
2983 // NOTE: If we fail the above checks then it means that we probably didn't
2984 // load a big enough response to trigger the delay mechanism.
2986 // Send some unexpected ACKs.
2987 for (size_t i = 0; i < 128; ++i) {
2988 ResourceHostMsg_DataReceived_ACK msg(1);
2989 host_.OnMessageReceived(msg, filter_.get());
2992 msgs[0].erase(msgs[0].begin());
2993 msgs[0].erase(msgs[0].begin());
2995 // ACK all DataReceived messages until we find a RequestComplete message.
2996 bool complete = false;
2997 while (!complete) {
2998 for (size_t i = 0; i < msgs[0].size(); ++i) {
2999 if (msgs[0][i].type() == ResourceMsg_RequestComplete::ID) {
3000 complete = true;
3001 break;
3004 EXPECT_EQ(ResourceMsg_DataReceived::ID, msgs[0][i].type());
3006 ResourceHostMsg_DataReceived_ACK msg(1);
3007 host_.OnMessageReceived(msg, filter_.get());
3010 base::MessageLoop::current()->RunUntilIdle();
3012 msgs.clear();
3013 accum_.GetClassifiedMessages(&msgs);
3017 // Tests the dispatcher host's temporary file management.
3018 TEST_F(ResourceDispatcherHostTest, RegisterDownloadedTempFile) {
3019 const int kRequestID = 1;
3021 // Create a temporary file.
3022 base::FilePath file_path;
3023 ASSERT_TRUE(base::CreateTemporaryFile(&file_path));
3024 scoped_refptr<ShareableFileReference> deletable_file =
3025 ShareableFileReference::GetOrCreate(
3026 file_path,
3027 ShareableFileReference::DELETE_ON_FINAL_RELEASE,
3028 BrowserThread::GetMessageLoopProxyForThread(
3029 BrowserThread::FILE).get());
3031 // Not readable.
3032 EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
3033 filter_->child_id(), file_path));
3035 // Register it for a resource request.
3036 host_.RegisterDownloadedTempFile(filter_->child_id(), kRequestID, file_path);
3038 // Should be readable now.
3039 EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
3040 filter_->child_id(), file_path));
3042 // The child releases from the request.
3043 ResourceHostMsg_ReleaseDownloadedFile release_msg(kRequestID);
3044 host_.OnMessageReceived(release_msg, filter_.get());
3046 // Still readable because there is another reference to the file. (The child
3047 // may take additional blob references.)
3048 EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
3049 filter_->child_id(), file_path));
3051 // Release extra references and wait for the file to be deleted. (This relies
3052 // on the delete happening on the FILE thread which is mapped to main thread
3053 // in this test.)
3054 deletable_file = NULL;
3055 base::RunLoop().RunUntilIdle();
3057 // The file is no longer readable to the child and has been deleted.
3058 EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
3059 filter_->child_id(), file_path));
3060 EXPECT_FALSE(base::PathExists(file_path));
3063 // Tests that temporary files held on behalf of child processes are released
3064 // when the child process dies.
3065 TEST_F(ResourceDispatcherHostTest, ReleaseTemporiesOnProcessExit) {
3066 const int kRequestID = 1;
3068 // Create a temporary file.
3069 base::FilePath file_path;
3070 ASSERT_TRUE(base::CreateTemporaryFile(&file_path));
3071 scoped_refptr<ShareableFileReference> deletable_file =
3072 ShareableFileReference::GetOrCreate(
3073 file_path,
3074 ShareableFileReference::DELETE_ON_FINAL_RELEASE,
3075 BrowserThread::GetMessageLoopProxyForThread(
3076 BrowserThread::FILE).get());
3078 // Register it for a resource request.
3079 host_.RegisterDownloadedTempFile(filter_->child_id(), kRequestID, file_path);
3080 deletable_file = NULL;
3082 // Should be readable now.
3083 EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
3084 filter_->child_id(), file_path));
3086 // Let the process die.
3087 filter_->OnChannelClosing();
3088 base::RunLoop().RunUntilIdle();
3090 // The file is no longer readable to the child and has been deleted.
3091 EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
3092 filter_->child_id(), file_path));
3093 EXPECT_FALSE(base::PathExists(file_path));
3096 TEST_F(ResourceDispatcherHostTest, DownloadToFile) {
3097 // Make a request which downloads to file.
3098 ResourceHostMsg_Request request = CreateResourceRequest(
3099 "GET", RESOURCE_TYPE_SUB_RESOURCE, net::URLRequestTestJob::test_url_1());
3100 request.download_to_file = true;
3101 ResourceHostMsg_RequestResource request_msg(0, 1, request);
3102 host_.OnMessageReceived(request_msg, filter_.get());
3104 // Running the message loop until idle does not work because
3105 // RedirectToFileResourceHandler posts things to base::WorkerPool. Instead,
3106 // wait for the ResourceMsg_RequestComplete to go out. Then run the event loop
3107 // until idle so the loader is gone.
3108 WaitForRequestComplete();
3109 base::RunLoop().RunUntilIdle();
3110 EXPECT_EQ(0, host_.pending_requests());
3112 ResourceIPCAccumulator::ClassifiedMessages msgs;
3113 accum_.GetClassifiedMessages(&msgs);
3115 ASSERT_EQ(1U, msgs.size());
3116 const std::vector<IPC::Message>& messages = msgs[0];
3118 // The request should contain the following messages:
3119 // ReceivedResponse (indicates headers received and filename)
3120 // DataDownloaded* (bytes downloaded and total length)
3121 // RequestComplete (request is done)
3123 // ReceivedResponse
3124 ResourceResponseHead response_head;
3125 GetResponseHead(messages, &response_head);
3126 ASSERT_FALSE(response_head.download_file_path.empty());
3128 // DataDownloaded
3129 size_t total_len = 0;
3130 for (size_t i = 1; i < messages.size() - 1; i++) {
3131 ASSERT_EQ(ResourceMsg_DataDownloaded::ID, messages[i].type());
3132 base::PickleIterator iter(messages[i]);
3133 int request_id, data_len;
3134 ASSERT_TRUE(IPC::ReadParam(&messages[i], &iter, &request_id));
3135 ASSERT_TRUE(IPC::ReadParam(&messages[i], &iter, &data_len));
3136 total_len += data_len;
3138 EXPECT_EQ(net::URLRequestTestJob::test_data_1().size(), total_len);
3140 // RequestComplete
3141 CheckRequestCompleteErrorCode(messages.back(), net::OK);
3143 // Verify that the data ended up in the temporary file.
3144 std::string contents;
3145 ASSERT_TRUE(base::ReadFileToString(response_head.download_file_path,
3146 &contents));
3147 EXPECT_EQ(net::URLRequestTestJob::test_data_1(), contents);
3149 // The file should be readable by the child.
3150 EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
3151 filter_->child_id(), response_head.download_file_path));
3153 // When the renderer releases the file, it should be deleted. Again,
3154 // RunUntilIdle doesn't work because base::WorkerPool is involved.
3155 ShareableFileReleaseWaiter waiter(response_head.download_file_path);
3156 ResourceHostMsg_ReleaseDownloadedFile release_msg(1);
3157 host_.OnMessageReceived(release_msg, filter_.get());
3158 waiter.Wait();
3159 // The release callback runs before the delete is scheduled, so pump the
3160 // message loop for the delete itself. (This relies on the delete happening on
3161 // the FILE thread which is mapped to main thread in this test.)
3162 base::RunLoop().RunUntilIdle();
3164 EXPECT_FALSE(base::PathExists(response_head.download_file_path));
3165 EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
3166 filter_->child_id(), response_head.download_file_path));
3169 // Tests GetLoadInfoForAllRoutes when there are no pending requests.
3170 TEST_F(ResourceDispatcherHostTest, LoadInfoNoRequests) {
3171 scoped_ptr<LoadInfoMap> load_info_map = RunLoadInfoTest(nullptr, 0);
3172 EXPECT_EQ(0u, load_info_map->size());
3175 // Tests GetLoadInfoForAllRoutes when there are 3 requests from the same
3176 // RenderView. The second one is farthest along.
3177 TEST_F(ResourceDispatcherHostTest, LoadInfo) {
3178 const GlobalRoutingID kId(filter_->child_id(), 0);
3179 LoadInfoTestRequestInfo request_info[] = {
3180 {kId.route_id,
3181 GURL("test://1/"),
3182 net::LOAD_STATE_SENDING_REQUEST,
3183 net::UploadProgress(0, 0)},
3184 {kId.route_id,
3185 GURL("test://2/"),
3186 net::LOAD_STATE_READING_RESPONSE,
3187 net::UploadProgress(0, 0)},
3188 {kId.route_id,
3189 GURL("test://3/"),
3190 net::LOAD_STATE_SENDING_REQUEST,
3191 net::UploadProgress(0, 0)},
3193 scoped_ptr<LoadInfoMap> load_info_map =
3194 RunLoadInfoTest(request_info, arraysize(request_info));
3195 ASSERT_EQ(1u, load_info_map->size());
3196 ASSERT_TRUE(load_info_map->find(kId) != load_info_map->end());
3197 EXPECT_EQ(GURL("test://2/"), (*load_info_map)[kId].url);
3198 EXPECT_EQ(net::LOAD_STATE_READING_RESPONSE,
3199 (*load_info_map)[kId].load_state.state);
3200 EXPECT_EQ(0u, (*load_info_map)[kId].upload_position);
3201 EXPECT_EQ(0u, (*load_info_map)[kId].upload_size);
3204 // Tests GetLoadInfoForAllRoutes when there are 2 requests with the same
3205 // priority. The first one (Which will have the lowest ID) should be returned.
3206 TEST_F(ResourceDispatcherHostTest, LoadInfoSamePriority) {
3207 const GlobalRoutingID kId(filter_->child_id(), 0);
3208 LoadInfoTestRequestInfo request_info[] = {
3209 {kId.route_id,
3210 GURL("test://1/"),
3211 net::LOAD_STATE_IDLE,
3212 net::UploadProgress(0, 0)},
3213 {kId.route_id,
3214 GURL("test://2/"),
3215 net::LOAD_STATE_IDLE,
3216 net::UploadProgress(0, 0)},
3218 scoped_ptr<LoadInfoMap> load_info_map =
3219 RunLoadInfoTest(request_info, arraysize(request_info));
3220 ASSERT_EQ(1u, load_info_map->size());
3221 ASSERT_TRUE(load_info_map->find(kId) != load_info_map->end());
3222 EXPECT_EQ(GURL("test://1/"), (*load_info_map)[kId].url);
3223 EXPECT_EQ(net::LOAD_STATE_IDLE, (*load_info_map)[kId].load_state.state);
3224 EXPECT_EQ(0u, (*load_info_map)[kId].upload_position);
3225 EXPECT_EQ(0u, (*load_info_map)[kId].upload_size);
3228 // Tests GetLoadInfoForAllRoutes when a request is uploading a body.
3229 TEST_F(ResourceDispatcherHostTest, LoadInfoUploadProgress) {
3230 const GlobalRoutingID kId(filter_->child_id(), 0);
3231 LoadInfoTestRequestInfo request_info[] = {
3232 {kId.route_id,
3233 GURL("test://1/"),
3234 net::LOAD_STATE_READING_RESPONSE,
3235 net::UploadProgress(0, 0)},
3236 {kId.route_id,
3237 GURL("test://1/"),
3238 net::LOAD_STATE_READING_RESPONSE,
3239 net::UploadProgress(1000, 1000)},
3240 {kId.route_id,
3241 GURL("test://2/"),
3242 net::LOAD_STATE_SENDING_REQUEST,
3243 net::UploadProgress(50, 100)},
3244 {kId.route_id,
3245 GURL("test://1/"),
3246 net::LOAD_STATE_READING_RESPONSE,
3247 net::UploadProgress(1000, 1000)},
3248 {kId.route_id,
3249 GURL("test://3/"),
3250 net::LOAD_STATE_READING_RESPONSE,
3251 net::UploadProgress(0, 0)},
3253 scoped_ptr<LoadInfoMap> load_info_map =
3254 RunLoadInfoTest(request_info, arraysize(request_info));
3255 ASSERT_EQ(1u, load_info_map->size());
3256 ASSERT_TRUE(load_info_map->find(kId) != load_info_map->end());
3257 EXPECT_EQ(GURL("test://2/"), (*load_info_map)[kId].url);
3258 EXPECT_EQ(net::LOAD_STATE_SENDING_REQUEST,
3259 (*load_info_map)[kId].load_state.state);
3260 EXPECT_EQ(50u, (*load_info_map)[kId].upload_position);
3261 EXPECT_EQ(100u, (*load_info_map)[kId].upload_size);
3264 // Tests GetLoadInfoForAllRoutes when there are 4 requests from 2 different
3265 // RenderViews. Also tests the case where the first / last requests are the
3266 // most interesting ones.
3267 TEST_F(ResourceDispatcherHostTest, LoadInfoTwoRenderViews) {
3268 const GlobalRoutingID kId1(filter_->child_id(), 0);
3269 const GlobalRoutingID kId2(filter_->child_id(), 1);
3270 LoadInfoTestRequestInfo request_info[] = {
3271 {kId1.route_id,
3272 GURL("test://1/"),
3273 net::LOAD_STATE_CONNECTING,
3274 net::UploadProgress(0, 0)},
3275 {kId2.route_id,
3276 GURL("test://2/"),
3277 net::LOAD_STATE_IDLE,
3278 net::UploadProgress(0, 0)},
3279 {kId1.route_id,
3280 GURL("test://3/"),
3281 net::LOAD_STATE_IDLE,
3282 net::UploadProgress(0, 0)},
3283 {kId2.route_id,
3284 GURL("test://4/"),
3285 net::LOAD_STATE_CONNECTING,
3286 net::UploadProgress(0, 0)},
3288 scoped_ptr<LoadInfoMap> load_info_map =
3289 RunLoadInfoTest(request_info, arraysize(request_info));
3290 ASSERT_EQ(2u, load_info_map->size());
3292 ASSERT_TRUE(load_info_map->find(kId1) != load_info_map->end());
3293 EXPECT_EQ(GURL("test://1/"), (*load_info_map)[kId1].url);
3294 EXPECT_EQ(net::LOAD_STATE_CONNECTING,
3295 (*load_info_map)[kId1].load_state.state);
3296 EXPECT_EQ(0u, (*load_info_map)[kId1].upload_position);
3297 EXPECT_EQ(0u, (*load_info_map)[kId1].upload_size);
3299 ASSERT_TRUE(load_info_map->find(kId2) != load_info_map->end());
3300 EXPECT_EQ(GURL("test://4/"), (*load_info_map)[kId2].url);
3301 EXPECT_EQ(net::LOAD_STATE_CONNECTING,
3302 (*load_info_map)[kId2].load_state.state);
3303 EXPECT_EQ(0u, (*load_info_map)[kId2].upload_position);
3304 EXPECT_EQ(0u, (*load_info_map)[kId2].upload_size);
3307 // Confirm that resource response started notifications are correctly
3308 // transmitted to the WebContents.
3309 TEST_F(ResourceDispatcherHostTest, TransferResponseStarted) {
3310 int initial_count = web_contents_observer_->resource_response_start_count();
3312 MakeWebContentsAssociatedTestRequest(1, net::URLRequestTestJob::test_url_1());
3313 base::MessageLoop::current()->RunUntilIdle();
3315 EXPECT_EQ(initial_count + 1,
3316 web_contents_observer_->resource_response_start_count());
3319 // Confirm that request redirected notifications are correctly
3320 // transmitted to the WebContents.
3321 TEST_F(ResourceDispatcherHostTest, TransferRequestRedirected) {
3322 int initial_count = web_contents_observer_->resource_request_redirect_count();
3324 MakeWebContentsAssociatedTestRequest(
3325 1, net::URLRequestTestJob::test_url_redirect_to_url_2());
3326 base::MessageLoop::current()->RunUntilIdle();
3328 EXPECT_EQ(initial_count + 1,
3329 web_contents_observer_->resource_request_redirect_count());
3332 net::URLRequestJob* TestURLRequestJobFactory::MaybeCreateJobWithProtocolHandler(
3333 const std::string& scheme,
3334 net::URLRequest* request,
3335 net::NetworkDelegate* network_delegate) const {
3336 url_request_jobs_created_count_++;
3337 if (test_fixture_->wait_for_request_create_loop_)
3338 test_fixture_->wait_for_request_create_loop_->Quit();
3339 if (test_fixture_->loader_test_request_info_) {
3340 DCHECK_EQ(test_fixture_->loader_test_request_info_->url, request->url());
3341 scoped_ptr<LoadInfoTestRequestInfo> info =
3342 test_fixture_->loader_test_request_info_.Pass();
3343 return new URLRequestLoadInfoJob(request, network_delegate,
3344 info->load_state, info->upload_progress);
3346 if (test_fixture_->response_headers_.empty()) {
3347 if (delay_start_) {
3348 return new URLRequestTestDelayedStartJob(request, network_delegate);
3349 } else if (delay_complete_) {
3350 return new URLRequestTestDelayedCompletionJob(request,
3351 network_delegate);
3352 } else if (network_start_notification_) {
3353 return new URLRequestTestDelayedNetworkJob(request, network_delegate);
3354 } else if (scheme == "big-job") {
3355 return new URLRequestBigJob(request, network_delegate);
3356 } else {
3357 return new net::URLRequestTestJob(request, network_delegate);
3359 } else {
3360 if (delay_start_) {
3361 return new URLRequestTestDelayedStartJob(
3362 request, network_delegate,
3363 test_fixture_->response_headers_, test_fixture_->response_data_,
3364 false);
3365 } else if (delay_complete_) {
3366 return new URLRequestTestDelayedCompletionJob(
3367 request, network_delegate,
3368 test_fixture_->response_headers_, test_fixture_->response_data_,
3369 false);
3370 } else {
3371 return new net::URLRequestTestJob(
3372 request, network_delegate,
3373 test_fixture_->response_headers_, test_fixture_->response_data_,
3374 false);
3379 net::URLRequestJob* TestURLRequestJobFactory::MaybeInterceptRedirect(
3380 net::URLRequest* request,
3381 net::NetworkDelegate* network_delegate,
3382 const GURL& location) const {
3383 return nullptr;
3386 net::URLRequestJob* TestURLRequestJobFactory::MaybeInterceptResponse(
3387 net::URLRequest* request,
3388 net::NetworkDelegate* network_delegate) const {
3389 return nullptr;
3392 } // namespace content