[safe_browsing] Remove unused ContainsBrowseUrl() parameter.
[chromium-blink-merge.git] / content / child / resource_dispatcher.cc
blobb6a877fa65d5f8b9b91658ac2d14d5e01bb74680
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 // See http://dev.chromium.org/developers/design-documents/multi-process-resource-loading
7 #include "content/child/resource_dispatcher.h"
9 #include "base/basictypes.h"
10 #include "base/bind.h"
11 #include "base/compiler_specific.h"
12 #include "base/debug/alias.h"
13 #include "base/files/file_path.h"
14 #include "base/memory/shared_memory.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/metrics/histogram.h"
17 #include "base/strings/string_util.h"
18 #include "content/child/request_extra_data.h"
19 #include "content/child/request_info.h"
20 #include "content/child/site_isolation_policy.h"
21 #include "content/child/sync_load_response.h"
22 #include "content/common/inter_process_time_ticks_converter.h"
23 #include "content/common/resource_messages.h"
24 #include "content/public/child/request_peer.h"
25 #include "content/public/child/resource_dispatcher_delegate.h"
26 #include "content/public/common/resource_response.h"
27 #include "net/base/net_errors.h"
28 #include "net/base/net_util.h"
29 #include "net/base/request_priority.h"
30 #include "net/http/http_response_headers.h"
31 #include "webkit/child/resource_loader_bridge.h"
32 #include "webkit/common/resource_type.h"
34 using webkit_glue::ResourceLoaderBridge;
35 using webkit_glue::ResourceResponseInfo;
37 namespace content {
39 namespace {
41 // Converts |time| from a remote to local TimeTicks, overwriting the original
42 // value.
43 void RemoteToLocalTimeTicks(
44 const InterProcessTimeTicksConverter& converter,
45 base::TimeTicks* time) {
46 RemoteTimeTicks remote_time = RemoteTimeTicks::FromTimeTicks(*time);
47 *time = converter.ToLocalTimeTicks(remote_time).ToTimeTicks();
51 } // namespace
53 static void CrashOnMapFailure() {
54 #if defined(OS_WIN)
55 DWORD last_err = GetLastError();
56 base::debug::Alias(&last_err);
57 #endif
58 CHECK(false);
61 // Each resource request is assigned an ID scoped to this process.
62 static int MakeRequestID() {
63 // NOTE: The resource_dispatcher_host also needs probably unique
64 // request_ids, so they count down from -2 (-1 is a special we're
65 // screwed value), while the renderer process counts up.
66 static int next_request_id = 0;
67 return next_request_id++;
70 // ResourceLoaderBridge implementation ----------------------------------------
72 class IPCResourceLoaderBridge : public ResourceLoaderBridge {
73 public:
74 IPCResourceLoaderBridge(ResourceDispatcher* dispatcher,
75 const RequestInfo& request_info);
76 virtual ~IPCResourceLoaderBridge();
78 // ResourceLoaderBridge
79 virtual void SetRequestBody(ResourceRequestBody* request_body) OVERRIDE;
80 virtual bool Start(RequestPeer* peer) OVERRIDE;
81 virtual void Cancel() OVERRIDE;
82 virtual void SetDefersLoading(bool value) OVERRIDE;
83 virtual void DidChangePriority(net::RequestPriority new_priority,
84 int intra_priority_value) OVERRIDE;
85 virtual void SyncLoad(SyncLoadResponse* response) OVERRIDE;
87 private:
88 RequestPeer* peer_;
90 // The resource dispatcher for this loader. The bridge doesn't own it, but
91 // it's guaranteed to outlive the bridge.
92 ResourceDispatcher* dispatcher_;
94 // The request to send, created on initialization for modification and
95 // appending data.
96 ResourceHostMsg_Request request_;
98 // ID for the request, valid once Start()ed, -1 if not valid yet.
99 int request_id_;
101 // The routing id used when sending IPC messages.
102 int routing_id_;
104 // The security origin of the frame that initiates this request.
105 GURL frame_origin_;
107 bool is_synchronous_request_;
110 IPCResourceLoaderBridge::IPCResourceLoaderBridge(
111 ResourceDispatcher* dispatcher,
112 const RequestInfo& request_info)
113 : peer_(NULL),
114 dispatcher_(dispatcher),
115 request_id_(-1),
116 routing_id_(request_info.routing_id),
117 is_synchronous_request_(false) {
118 DCHECK(dispatcher_) << "no resource dispatcher";
119 request_.method = request_info.method;
120 request_.url = request_info.url;
121 request_.first_party_for_cookies = request_info.first_party_for_cookies;
122 request_.referrer = request_info.referrer;
123 request_.referrer_policy = request_info.referrer_policy;
124 request_.headers = request_info.headers;
125 request_.load_flags = request_info.load_flags;
126 request_.origin_pid = request_info.requestor_pid;
127 request_.resource_type = request_info.request_type;
128 request_.priority = request_info.priority;
129 request_.request_context = request_info.request_context;
130 request_.appcache_host_id = request_info.appcache_host_id;
131 request_.download_to_file = request_info.download_to_file;
132 request_.has_user_gesture = request_info.has_user_gesture;
134 const RequestExtraData kEmptyData;
135 const RequestExtraData* extra_data;
136 if (request_info.extra_data)
137 extra_data = static_cast<RequestExtraData*>(request_info.extra_data);
138 else
139 extra_data = &kEmptyData;
140 request_.visiblity_state = extra_data->visibility_state();
141 request_.render_frame_id = extra_data->render_frame_id();
142 request_.is_main_frame = extra_data->is_main_frame();
143 request_.parent_is_main_frame = extra_data->parent_is_main_frame();
144 request_.parent_render_frame_id = extra_data->parent_render_frame_id();
145 request_.allow_download = extra_data->allow_download();
146 request_.transition_type = extra_data->transition_type();
147 request_.should_replace_current_entry =
148 extra_data->should_replace_current_entry();
149 request_.transferred_request_child_id =
150 extra_data->transferred_request_child_id();
151 request_.transferred_request_request_id =
152 extra_data->transferred_request_request_id();
153 request_.service_worker_provider_id =
154 extra_data->service_worker_provider_id();
155 frame_origin_ = extra_data->frame_origin();
158 IPCResourceLoaderBridge::~IPCResourceLoaderBridge() {
159 // we remove our hook for the resource dispatcher only when going away, since
160 // it doesn't keep track of whether we've force terminated the request
161 if (request_id_ >= 0) {
162 // this operation may fail, as the dispatcher will have preemptively
163 // removed us when the renderer sends the ReceivedAllData message.
164 dispatcher_->RemovePendingRequest(request_id_);
166 if (request_.download_to_file) {
167 dispatcher_->message_sender()->Send(
168 new ResourceHostMsg_ReleaseDownloadedFile(request_id_));
173 void IPCResourceLoaderBridge::SetRequestBody(
174 ResourceRequestBody* request_body) {
175 DCHECK(request_id_ == -1) << "request already started";
176 request_.request_body = request_body;
179 // Writes a footer on the message and sends it
180 bool IPCResourceLoaderBridge::Start(RequestPeer* peer) {
181 if (request_id_ != -1) {
182 NOTREACHED() << "Starting a request twice";
183 return false;
186 peer_ = peer;
188 // generate the request ID, and append it to the message
189 request_id_ = dispatcher_->AddPendingRequest(peer_,
190 request_.resource_type,
191 request_.origin_pid,
192 frame_origin_,
193 request_.url);
195 return dispatcher_->message_sender()->Send(
196 new ResourceHostMsg_RequestResource(routing_id_, request_id_, request_));
199 void IPCResourceLoaderBridge::Cancel() {
200 if (request_id_ < 0) {
201 NOTREACHED() << "Trying to cancel an unstarted request";
202 return;
205 if (!is_synchronous_request_)
206 dispatcher_->CancelPendingRequest(request_id_);
208 // We can't remove the request ID from the resource dispatcher because more
209 // data might be pending. Sending the cancel message may cause more data
210 // to be flushed, and will then cause a complete message to be sent.
213 void IPCResourceLoaderBridge::SetDefersLoading(bool value) {
214 if (request_id_ < 0) {
215 NOTREACHED() << "Trying to (un)defer an unstarted request";
216 return;
219 dispatcher_->SetDefersLoading(request_id_, value);
222 void IPCResourceLoaderBridge::DidChangePriority(
223 net::RequestPriority new_priority, int intra_priority_value) {
224 if (request_id_ < 0) {
225 NOTREACHED() << "Trying to change priority of an unstarted request";
226 return;
229 dispatcher_->DidChangePriority(routing_id_, request_id_, new_priority,
230 intra_priority_value);
233 void IPCResourceLoaderBridge::SyncLoad(SyncLoadResponse* response) {
234 if (request_id_ != -1) {
235 NOTREACHED() << "Starting a request twice";
236 response->error_code = net::ERR_FAILED;
237 return;
240 request_id_ = MakeRequestID();
241 is_synchronous_request_ = true;
243 SyncLoadResult result;
244 IPC::SyncMessage* msg = new ResourceHostMsg_SyncLoad(routing_id_, request_id_,
245 request_, &result);
246 // NOTE: This may pump events (see RenderThread::Send).
247 if (!dispatcher_->message_sender()->Send(msg)) {
248 response->error_code = net::ERR_FAILED;
249 return;
252 response->error_code = result.error_code;
253 response->url = result.final_url;
254 response->headers = result.headers;
255 response->mime_type = result.mime_type;
256 response->charset = result.charset;
257 response->request_time = result.request_time;
258 response->response_time = result.response_time;
259 response->encoded_data_length = result.encoded_data_length;
260 response->load_timing = result.load_timing;
261 response->devtools_info = result.devtools_info;
262 response->data.swap(result.data);
263 response->download_file_path = result.download_file_path;
266 // ResourceDispatcher ---------------------------------------------------------
268 ResourceDispatcher::ResourceDispatcher(IPC::Sender* sender)
269 : message_sender_(sender),
270 weak_factory_(this),
271 delegate_(NULL),
272 io_timestamp_(base::TimeTicks()) {
275 ResourceDispatcher::~ResourceDispatcher() {
278 // ResourceDispatcher implementation ------------------------------------------
280 bool ResourceDispatcher::OnMessageReceived(const IPC::Message& message) {
281 if (!IsResourceDispatcherMessage(message)) {
282 return false;
285 int request_id;
287 PickleIterator iter(message);
288 if (!message.ReadInt(&iter, &request_id)) {
289 NOTREACHED() << "malformed resource message";
290 return true;
293 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
294 if (!request_info) {
295 // Release resources in the message if it is a data message.
296 ReleaseResourcesInDataMessage(message);
297 return true;
300 if (request_info->is_deferred) {
301 request_info->deferred_message_queue.push_back(new IPC::Message(message));
302 return true;
304 // Make sure any deferred messages are dispatched before we dispatch more.
305 if (!request_info->deferred_message_queue.empty()) {
306 FlushDeferredMessages(request_id);
307 // The request could have been deferred now. If yes then the current
308 // message has to be queued up. The request_info instance should remain
309 // valid here as there are pending messages for it.
310 DCHECK(pending_requests_.find(request_id) != pending_requests_.end());
311 if (request_info->is_deferred) {
312 request_info->deferred_message_queue.push_back(new IPC::Message(message));
313 return true;
317 DispatchMessage(message);
318 return true;
321 ResourceDispatcher::PendingRequestInfo*
322 ResourceDispatcher::GetPendingRequestInfo(int request_id) {
323 PendingRequestList::iterator it = pending_requests_.find(request_id);
324 if (it == pending_requests_.end()) {
325 // This might happen for kill()ed requests on the webkit end.
326 return NULL;
328 return &(it->second);
331 void ResourceDispatcher::OnUploadProgress(int request_id, int64 position,
332 int64 size) {
333 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
334 if (!request_info)
335 return;
337 request_info->peer->OnUploadProgress(position, size);
339 // Acknowledge receipt
340 message_sender()->Send(new ResourceHostMsg_UploadProgress_ACK(request_id));
343 void ResourceDispatcher::OnReceivedResponse(
344 int request_id, const ResourceResponseHead& response_head) {
345 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedResponse");
346 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
347 if (!request_info)
348 return;
349 request_info->response_start = ConsumeIOTimestamp();
351 if (delegate_) {
352 RequestPeer* new_peer =
353 delegate_->OnReceivedResponse(
354 request_info->peer, response_head.mime_type, request_info->url);
355 if (new_peer)
356 request_info->peer = new_peer;
359 ResourceResponseInfo renderer_response_info;
360 ToResourceResponseInfo(*request_info, response_head, &renderer_response_info);
361 request_info->site_isolation_metadata =
362 SiteIsolationPolicy::OnReceivedResponse(request_info->frame_origin,
363 request_info->response_url,
364 request_info->resource_type,
365 request_info->origin_pid,
366 renderer_response_info);
367 request_info->peer->OnReceivedResponse(renderer_response_info);
370 void ResourceDispatcher::OnReceivedCachedMetadata(
371 int request_id, const std::vector<char>& data) {
372 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
373 if (!request_info)
374 return;
376 if (data.size())
377 request_info->peer->OnReceivedCachedMetadata(&data.front(), data.size());
380 void ResourceDispatcher::OnSetDataBuffer(int request_id,
381 base::SharedMemoryHandle shm_handle,
382 int shm_size,
383 base::ProcessId renderer_pid) {
384 TRACE_EVENT0("loader", "ResourceDispatcher::OnSetDataBuffer");
385 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
386 if (!request_info)
387 return;
389 bool shm_valid = base::SharedMemory::IsHandleValid(shm_handle);
390 CHECK((shm_valid && shm_size > 0) || (!shm_valid && !shm_size));
392 request_info->buffer.reset(
393 new base::SharedMemory(shm_handle, true)); // read only
395 bool ok = request_info->buffer->Map(shm_size);
396 if (!ok) {
397 // Added to help debug crbug/160401.
398 base::ProcessId renderer_pid_copy = renderer_pid;
399 base::debug::Alias(&renderer_pid_copy);
401 base::SharedMemoryHandle shm_handle_copy = shm_handle;
402 base::debug::Alias(&shm_handle_copy);
404 CrashOnMapFailure();
405 return;
408 request_info->buffer_size = shm_size;
411 void ResourceDispatcher::OnReceivedData(int request_id,
412 int data_offset,
413 int data_length,
414 int encoded_data_length) {
415 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedData");
416 DCHECK_GT(data_length, 0);
417 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
418 if (request_info && data_length > 0) {
419 CHECK(base::SharedMemory::IsHandleValid(request_info->buffer->handle()));
420 CHECK_GE(request_info->buffer_size, data_offset + data_length);
422 // Ensure that the SHM buffer remains valid for the duration of this scope.
423 // It is possible for CancelPendingRequest() to be called before we exit
424 // this scope.
425 linked_ptr<base::SharedMemory> retain_buffer(request_info->buffer);
427 base::TimeTicks time_start = base::TimeTicks::Now();
429 const char* data_ptr = static_cast<char*>(request_info->buffer->memory());
430 CHECK(data_ptr);
431 CHECK(data_ptr + data_offset);
433 // Check whether this response data is compliant with our cross-site
434 // document blocking policy. We only do this for the first packet.
435 std::string alternative_data;
436 if (request_info->site_isolation_metadata.get()) {
437 request_info->blocked_response =
438 SiteIsolationPolicy::ShouldBlockResponse(
439 request_info->site_isolation_metadata, data_ptr + data_offset,
440 data_length, &alternative_data);
441 request_info->site_isolation_metadata.reset();
444 // When the response is not blocked.
445 if (!request_info->blocked_response) {
446 request_info->peer->OnReceivedData(
447 data_ptr + data_offset, data_length, encoded_data_length);
448 } else if (alternative_data.size() > 0) {
449 // When the response is blocked, and when we have any alternative data to
450 // send to the renderer. When |alternative_data| is zero-sized, we do not
451 // call peer's callback.
452 request_info->peer->OnReceivedData(alternative_data.data(),
453 alternative_data.size(),
454 alternative_data.size());
457 UMA_HISTOGRAM_TIMES("ResourceDispatcher.OnReceivedDataTime",
458 base::TimeTicks::Now() - time_start);
461 // Acknowledge the reception of this data.
462 message_sender()->Send(new ResourceHostMsg_DataReceived_ACK(request_id));
465 void ResourceDispatcher::OnDownloadedData(int request_id,
466 int data_len,
467 int encoded_data_length) {
468 // Acknowledge the reception of this message.
469 message_sender()->Send(
470 new ResourceHostMsg_DataDownloaded_ACK(request_id));
472 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
473 if (!request_info)
474 return;
476 request_info->peer->OnDownloadedData(data_len, encoded_data_length);
479 void ResourceDispatcher::OnReceivedRedirect(
480 int request_id,
481 const GURL& new_url,
482 const ResourceResponseHead& response_head) {
483 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedRedirect");
484 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
485 if (!request_info)
486 return;
487 request_info->response_start = ConsumeIOTimestamp();
489 bool has_new_first_party_for_cookies = false;
490 GURL new_first_party_for_cookies;
491 ResourceResponseInfo renderer_response_info;
492 ToResourceResponseInfo(*request_info, response_head, &renderer_response_info);
493 if (request_info->peer->OnReceivedRedirect(new_url, renderer_response_info,
494 &has_new_first_party_for_cookies,
495 &new_first_party_for_cookies)) {
496 // Double-check if the request is still around. The call above could
497 // potentially remove it.
498 request_info = GetPendingRequestInfo(request_id);
499 if (!request_info)
500 return;
501 // We update the response_url here so that we can send it to
502 // SiteIsolationPolicy later when OnReceivedResponse is called.
503 request_info->response_url = new_url;
504 request_info->pending_redirect_message.reset(
505 new ResourceHostMsg_FollowRedirect(request_id,
506 has_new_first_party_for_cookies,
507 new_first_party_for_cookies));
508 if (!request_info->is_deferred) {
509 FollowPendingRedirect(request_id, *request_info);
511 } else {
512 CancelPendingRequest(request_id);
516 void ResourceDispatcher::FollowPendingRedirect(
517 int request_id,
518 PendingRequestInfo& request_info) {
519 IPC::Message* msg = request_info.pending_redirect_message.release();
520 if (msg)
521 message_sender()->Send(msg);
524 void ResourceDispatcher::OnRequestComplete(
525 int request_id,
526 const ResourceMsg_RequestCompleteData& request_complete_data) {
527 TRACE_EVENT0("loader", "ResourceDispatcher::OnRequestComplete");
529 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
530 if (!request_info)
531 return;
532 request_info->completion_time = ConsumeIOTimestamp();
533 request_info->buffer.reset();
534 request_info->buffer_size = 0;
536 RequestPeer* peer = request_info->peer;
538 if (delegate_) {
539 RequestPeer* new_peer =
540 delegate_->OnRequestComplete(
541 request_info->peer, request_info->resource_type,
542 request_complete_data.error_code);
543 if (new_peer)
544 request_info->peer = new_peer;
547 base::TimeTicks renderer_completion_time = ToRendererCompletionTime(
548 *request_info, request_complete_data.completion_time);
549 // The request ID will be removed from our pending list in the destructor.
550 // Normally, dispatching this message causes the reference-counted request to
551 // die immediately.
552 peer->OnCompletedRequest(request_complete_data.error_code,
553 request_complete_data.was_ignored_by_handler,
554 request_complete_data.exists_in_cache,
555 request_complete_data.security_info,
556 renderer_completion_time,
557 request_complete_data.encoded_data_length);
560 int ResourceDispatcher::AddPendingRequest(RequestPeer* callback,
561 ResourceType::Type resource_type,
562 int origin_pid,
563 const GURL& frame_origin,
564 const GURL& request_url) {
565 // Compute a unique request_id for this renderer process.
566 int id = MakeRequestID();
567 pending_requests_[id] = PendingRequestInfo(
568 callback, resource_type, origin_pid, frame_origin, request_url);
569 return id;
572 bool ResourceDispatcher::RemovePendingRequest(int request_id) {
573 PendingRequestList::iterator it = pending_requests_.find(request_id);
574 if (it == pending_requests_.end())
575 return false;
577 PendingRequestInfo& request_info = it->second;
578 ReleaseResourcesInMessageQueue(&request_info.deferred_message_queue);
579 pending_requests_.erase(it);
581 return true;
584 void ResourceDispatcher::CancelPendingRequest(int request_id) {
585 PendingRequestList::iterator it = pending_requests_.find(request_id);
586 if (it == pending_requests_.end()) {
587 DVLOG(1) << "unknown request";
588 return;
591 // |request_id| will be removed from |pending_requests_| when
592 // OnRequestComplete returns with ERR_ABORTED.
593 message_sender()->Send(new ResourceHostMsg_CancelRequest(request_id));
596 void ResourceDispatcher::SetDefersLoading(int request_id, bool value) {
597 PendingRequestList::iterator it = pending_requests_.find(request_id);
598 if (it == pending_requests_.end()) {
599 DLOG(ERROR) << "unknown request";
600 return;
602 PendingRequestInfo& request_info = it->second;
603 if (value) {
604 request_info.is_deferred = value;
605 } else if (request_info.is_deferred) {
606 request_info.is_deferred = false;
608 FollowPendingRedirect(request_id, request_info);
610 base::MessageLoop::current()->PostTask(
611 FROM_HERE,
612 base::Bind(&ResourceDispatcher::FlushDeferredMessages,
613 weak_factory_.GetWeakPtr(),
614 request_id));
618 void ResourceDispatcher::DidChangePriority(
619 int routing_id, int request_id, net::RequestPriority new_priority,
620 int intra_priority_value) {
621 DCHECK(ContainsKey(pending_requests_, request_id));
622 message_sender()->Send(new ResourceHostMsg_DidChangePriority(
623 request_id, new_priority, intra_priority_value));
626 ResourceDispatcher::PendingRequestInfo::PendingRequestInfo()
627 : peer(NULL),
628 resource_type(ResourceType::SUB_RESOURCE),
629 is_deferred(false),
630 blocked_response(false),
631 buffer_size(0) {
634 ResourceDispatcher::PendingRequestInfo::PendingRequestInfo(
635 RequestPeer* peer,
636 ResourceType::Type resource_type,
637 int origin_pid,
638 const GURL& frame_origin,
639 const GURL& request_url)
640 : peer(peer),
641 resource_type(resource_type),
642 origin_pid(origin_pid),
643 is_deferred(false),
644 url(request_url),
645 frame_origin(frame_origin),
646 response_url(request_url),
647 request_start(base::TimeTicks::Now()),
648 blocked_response(false) {}
650 ResourceDispatcher::PendingRequestInfo::~PendingRequestInfo() {}
652 void ResourceDispatcher::DispatchMessage(const IPC::Message& message) {
653 IPC_BEGIN_MESSAGE_MAP(ResourceDispatcher, message)
654 IPC_MESSAGE_HANDLER(ResourceMsg_UploadProgress, OnUploadProgress)
655 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedResponse, OnReceivedResponse)
656 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedCachedMetadata,
657 OnReceivedCachedMetadata)
658 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedRedirect, OnReceivedRedirect)
659 IPC_MESSAGE_HANDLER(ResourceMsg_SetDataBuffer, OnSetDataBuffer)
660 IPC_MESSAGE_HANDLER(ResourceMsg_DataReceived, OnReceivedData)
661 IPC_MESSAGE_HANDLER(ResourceMsg_DataDownloaded, OnDownloadedData)
662 IPC_MESSAGE_HANDLER(ResourceMsg_RequestComplete, OnRequestComplete)
663 IPC_END_MESSAGE_MAP()
666 void ResourceDispatcher::FlushDeferredMessages(int request_id) {
667 PendingRequestList::iterator it = pending_requests_.find(request_id);
668 if (it == pending_requests_.end()) // The request could have become invalid.
669 return;
670 PendingRequestInfo& request_info = it->second;
671 if (request_info.is_deferred)
672 return;
673 // Because message handlers could result in request_info being destroyed,
674 // we need to work with a stack reference to the deferred queue.
675 MessageQueue q;
676 q.swap(request_info.deferred_message_queue);
677 while (!q.empty()) {
678 IPC::Message* m = q.front();
679 q.pop_front();
680 DispatchMessage(*m);
681 delete m;
682 // If this request is deferred in the context of the above message, then
683 // we should honor the same and stop dispatching further messages.
684 // We need to find the request again in the list as it may have completed
685 // by now and the request_info instance above may be invalid.
686 PendingRequestList::iterator index = pending_requests_.find(request_id);
687 if (index != pending_requests_.end()) {
688 PendingRequestInfo& pending_request = index->second;
689 if (pending_request.is_deferred) {
690 pending_request.deferred_message_queue.swap(q);
691 return;
697 ResourceLoaderBridge* ResourceDispatcher::CreateBridge(
698 const RequestInfo& request_info) {
699 return new IPCResourceLoaderBridge(this, request_info);
702 void ResourceDispatcher::ToResourceResponseInfo(
703 const PendingRequestInfo& request_info,
704 const ResourceResponseHead& browser_info,
705 ResourceResponseInfo* renderer_info) const {
706 *renderer_info = browser_info;
707 if (request_info.request_start.is_null() ||
708 request_info.response_start.is_null() ||
709 browser_info.request_start.is_null() ||
710 browser_info.response_start.is_null() ||
711 browser_info.load_timing.request_start.is_null()) {
712 return;
714 InterProcessTimeTicksConverter converter(
715 LocalTimeTicks::FromTimeTicks(request_info.request_start),
716 LocalTimeTicks::FromTimeTicks(request_info.response_start),
717 RemoteTimeTicks::FromTimeTicks(browser_info.request_start),
718 RemoteTimeTicks::FromTimeTicks(browser_info.response_start));
720 net::LoadTimingInfo* load_timing = &renderer_info->load_timing;
721 RemoteToLocalTimeTicks(converter, &load_timing->request_start);
722 RemoteToLocalTimeTicks(converter, &load_timing->proxy_resolve_start);
723 RemoteToLocalTimeTicks(converter, &load_timing->proxy_resolve_end);
724 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.dns_start);
725 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.dns_end);
726 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.connect_start);
727 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.connect_end);
728 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.ssl_start);
729 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.ssl_end);
730 RemoteToLocalTimeTicks(converter, &load_timing->send_start);
731 RemoteToLocalTimeTicks(converter, &load_timing->send_end);
732 RemoteToLocalTimeTicks(converter, &load_timing->receive_headers_end);
735 base::TimeTicks ResourceDispatcher::ToRendererCompletionTime(
736 const PendingRequestInfo& request_info,
737 const base::TimeTicks& browser_completion_time) const {
738 if (request_info.completion_time.is_null()) {
739 return browser_completion_time;
742 // TODO(simonjam): The optimal lower bound should be the most recent value of
743 // TimeTicks::Now() returned to WebKit. Is it worth trying to cache that?
744 // Until then, |response_start| is used as it is the most recent value
745 // returned for this request.
746 int64 result = std::max(browser_completion_time.ToInternalValue(),
747 request_info.response_start.ToInternalValue());
748 result = std::min(result, request_info.completion_time.ToInternalValue());
749 return base::TimeTicks::FromInternalValue(result);
752 base::TimeTicks ResourceDispatcher::ConsumeIOTimestamp() {
753 if (io_timestamp_ == base::TimeTicks())
754 return base::TimeTicks::Now();
755 base::TimeTicks result = io_timestamp_;
756 io_timestamp_ = base::TimeTicks();
757 return result;
760 // static
761 bool ResourceDispatcher::IsResourceDispatcherMessage(
762 const IPC::Message& message) {
763 switch (message.type()) {
764 case ResourceMsg_UploadProgress::ID:
765 case ResourceMsg_ReceivedResponse::ID:
766 case ResourceMsg_ReceivedCachedMetadata::ID:
767 case ResourceMsg_ReceivedRedirect::ID:
768 case ResourceMsg_SetDataBuffer::ID:
769 case ResourceMsg_DataReceived::ID:
770 case ResourceMsg_DataDownloaded::ID:
771 case ResourceMsg_RequestComplete::ID:
772 return true;
774 default:
775 break;
778 return false;
781 // static
782 void ResourceDispatcher::ReleaseResourcesInDataMessage(
783 const IPC::Message& message) {
784 PickleIterator iter(message);
785 int request_id;
786 if (!message.ReadInt(&iter, &request_id)) {
787 NOTREACHED() << "malformed resource message";
788 return;
791 // If the message contains a shared memory handle, we should close the handle
792 // or there will be a memory leak.
793 if (message.type() == ResourceMsg_SetDataBuffer::ID) {
794 base::SharedMemoryHandle shm_handle;
795 if (IPC::ParamTraits<base::SharedMemoryHandle>::Read(&message,
796 &iter,
797 &shm_handle)) {
798 if (base::SharedMemory::IsHandleValid(shm_handle))
799 base::SharedMemory::CloseHandle(shm_handle);
804 // static
805 void ResourceDispatcher::ReleaseResourcesInMessageQueue(MessageQueue* queue) {
806 while (!queue->empty()) {
807 IPC::Message* message = queue->front();
808 ReleaseResourcesInDataMessage(*message);
809 queue->pop_front();
810 delete message;
814 } // namespace content