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;
41 // Converts |time| from a remote to local TimeTicks, overwriting the original
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();
50 void CrashOnMapFailure() {
52 DWORD last_err = GetLastError();
53 base::debug::Alias(&last_err);
58 // Each resource request is assigned an ID scoped to this process.
60 // NOTE: The resource_dispatcher_host also needs probably unique
61 // request_ids, so they count down from -2 (-1 is a special we're
62 // screwed value), while the renderer process counts up.
63 static int next_request_id = 0;
64 return next_request_id++;
69 // ResourceLoaderBridge implementation ----------------------------------------
71 class IPCResourceLoaderBridge : public ResourceLoaderBridge {
73 IPCResourceLoaderBridge(ResourceDispatcher* dispatcher,
74 const RequestInfo& request_info);
75 virtual ~IPCResourceLoaderBridge();
77 // ResourceLoaderBridge
78 virtual void SetRequestBody(ResourceRequestBody* request_body) OVERRIDE;
79 virtual bool Start(RequestPeer* peer) OVERRIDE;
80 virtual void Cancel() OVERRIDE;
81 virtual void SetDefersLoading(bool value) OVERRIDE;
82 virtual void DidChangePriority(net::RequestPriority new_priority,
83 int intra_priority_value) OVERRIDE;
84 virtual void SyncLoad(SyncLoadResponse* response) OVERRIDE;
89 // The resource dispatcher for this loader. The bridge doesn't own it, but
90 // it's guaranteed to outlive the bridge.
91 ResourceDispatcher* dispatcher_;
93 // The request to send, created on initialization for modification and
95 ResourceHostMsg_Request request_;
97 // ID for the request, valid once Start()ed, -1 if not valid yet.
100 // The routing id used when sending IPC messages.
103 // The security origin of the frame that initiates this request.
106 bool is_synchronous_request_;
109 IPCResourceLoaderBridge::IPCResourceLoaderBridge(
110 ResourceDispatcher* dispatcher,
111 const RequestInfo& request_info)
113 dispatcher_(dispatcher),
115 routing_id_(request_info.routing_id),
116 is_synchronous_request_(false) {
117 DCHECK(dispatcher_) << "no resource dispatcher";
118 request_.method = request_info.method;
119 request_.url = request_info.url;
120 request_.first_party_for_cookies = request_info.first_party_for_cookies;
121 request_.referrer = request_info.referrer;
122 request_.referrer_policy = request_info.referrer_policy;
123 request_.headers = request_info.headers;
124 request_.load_flags = request_info.load_flags;
125 request_.origin_pid = request_info.requestor_pid;
126 request_.resource_type = request_info.request_type;
127 request_.priority = request_info.priority;
128 request_.request_context = request_info.request_context;
129 request_.appcache_host_id = request_info.appcache_host_id;
130 request_.download_to_file = request_info.download_to_file;
131 request_.has_user_gesture = request_info.has_user_gesture;
133 const RequestExtraData kEmptyData;
134 const RequestExtraData* extra_data;
135 if (request_info.extra_data)
136 extra_data = static_cast<RequestExtraData*>(request_info.extra_data);
138 extra_data = &kEmptyData;
139 request_.visiblity_state = extra_data->visibility_state();
140 request_.render_frame_id = extra_data->render_frame_id();
141 request_.is_main_frame = extra_data->is_main_frame();
142 request_.parent_is_main_frame = extra_data->parent_is_main_frame();
143 request_.parent_render_frame_id = extra_data->parent_render_frame_id();
144 request_.allow_download = extra_data->allow_download();
145 request_.transition_type = extra_data->transition_type();
146 request_.should_replace_current_entry =
147 extra_data->should_replace_current_entry();
148 request_.transferred_request_child_id =
149 extra_data->transferred_request_child_id();
150 request_.transferred_request_request_id =
151 extra_data->transferred_request_request_id();
152 request_.service_worker_provider_id =
153 extra_data->service_worker_provider_id();
154 frame_origin_ = extra_data->frame_origin();
157 IPCResourceLoaderBridge::~IPCResourceLoaderBridge() {
158 // we remove our hook for the resource dispatcher only when going away, since
159 // it doesn't keep track of whether we've force terminated the request
160 if (request_id_ >= 0) {
161 // this operation may fail, as the dispatcher will have preemptively
162 // removed us when the renderer sends the ReceivedAllData message.
163 dispatcher_->RemovePendingRequest(request_id_);
167 void IPCResourceLoaderBridge::SetRequestBody(
168 ResourceRequestBody* request_body) {
169 DCHECK(request_id_ == -1) << "request already started";
170 request_.request_body = request_body;
173 // Writes a footer on the message and sends it
174 bool IPCResourceLoaderBridge::Start(RequestPeer* peer) {
175 if (request_id_ != -1) {
176 NOTREACHED() << "Starting a request twice";
182 // generate the request ID, and append it to the message
183 request_id_ = dispatcher_->AddPendingRequest(peer_,
184 request_.resource_type,
188 request_.download_to_file);
190 return dispatcher_->message_sender()->Send(
191 new ResourceHostMsg_RequestResource(routing_id_, request_id_, request_));
194 void IPCResourceLoaderBridge::Cancel() {
195 if (request_id_ < 0) {
196 NOTREACHED() << "Trying to cancel an unstarted request";
200 if (!is_synchronous_request_)
201 dispatcher_->CancelPendingRequest(request_id_);
203 // We can't remove the request ID from the resource dispatcher because more
204 // data might be pending. Sending the cancel message may cause more data
205 // to be flushed, and will then cause a complete message to be sent.
208 void IPCResourceLoaderBridge::SetDefersLoading(bool value) {
209 if (request_id_ < 0) {
210 NOTREACHED() << "Trying to (un)defer an unstarted request";
214 dispatcher_->SetDefersLoading(request_id_, value);
217 void IPCResourceLoaderBridge::DidChangePriority(
218 net::RequestPriority new_priority, int intra_priority_value) {
219 if (request_id_ < 0) {
220 NOTREACHED() << "Trying to change priority of an unstarted request";
224 dispatcher_->DidChangePriority(routing_id_, request_id_, new_priority,
225 intra_priority_value);
228 void IPCResourceLoaderBridge::SyncLoad(SyncLoadResponse* response) {
229 if (request_id_ != -1) {
230 NOTREACHED() << "Starting a request twice";
231 response->error_code = net::ERR_FAILED;
235 request_id_ = MakeRequestID();
236 is_synchronous_request_ = true;
238 SyncLoadResult result;
239 IPC::SyncMessage* msg = new ResourceHostMsg_SyncLoad(routing_id_, request_id_,
241 // NOTE: This may pump events (see RenderThread::Send).
242 if (!dispatcher_->message_sender()->Send(msg)) {
243 response->error_code = net::ERR_FAILED;
247 response->error_code = result.error_code;
248 response->url = result.final_url;
249 response->headers = result.headers;
250 response->mime_type = result.mime_type;
251 response->charset = result.charset;
252 response->request_time = result.request_time;
253 response->response_time = result.response_time;
254 response->encoded_data_length = result.encoded_data_length;
255 response->load_timing = result.load_timing;
256 response->devtools_info = result.devtools_info;
257 response->data.swap(result.data);
258 response->download_file_path = result.download_file_path;
261 // ResourceDispatcher ---------------------------------------------------------
263 ResourceDispatcher::ResourceDispatcher(IPC::Sender* sender)
264 : message_sender_(sender),
267 io_timestamp_(base::TimeTicks()) {
270 ResourceDispatcher::~ResourceDispatcher() {
273 // ResourceDispatcher implementation ------------------------------------------
275 bool ResourceDispatcher::OnMessageReceived(const IPC::Message& message) {
276 if (!IsResourceDispatcherMessage(message)) {
282 PickleIterator iter(message);
283 if (!message.ReadInt(&iter, &request_id)) {
284 NOTREACHED() << "malformed resource message";
288 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
290 // Release resources in the message if it is a data message.
291 ReleaseResourcesInDataMessage(message);
295 // If the request has been canceled, only dispatch
296 // ResourceMsg_RequestComplete (otherwise resource leaks) and drop other
298 if (request_info->is_canceled) {
299 if (message.type() == ResourceMsg_RequestComplete::ID) {
300 DispatchMessage(message);
302 ReleaseResourcesInDataMessage(message);
307 if (request_info->is_deferred) {
308 request_info->deferred_message_queue.push_back(new IPC::Message(message));
311 // Make sure any deferred messages are dispatched before we dispatch more.
312 if (!request_info->deferred_message_queue.empty()) {
313 FlushDeferredMessages(request_id);
314 // The request could have been deferred now. If yes then the current
315 // message has to be queued up. The request_info instance should remain
316 // valid here as there are pending messages for it.
317 DCHECK(pending_requests_.find(request_id) != pending_requests_.end());
318 if (request_info->is_deferred) {
319 request_info->deferred_message_queue.push_back(new IPC::Message(message));
324 DispatchMessage(message);
328 ResourceDispatcher::PendingRequestInfo*
329 ResourceDispatcher::GetPendingRequestInfo(int request_id) {
330 PendingRequestList::iterator it = pending_requests_.find(request_id);
331 if (it == pending_requests_.end()) {
332 // This might happen for kill()ed requests on the webkit end.
335 return &(it->second);
338 void ResourceDispatcher::OnUploadProgress(int request_id, int64 position,
340 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
344 request_info->peer->OnUploadProgress(position, size);
346 // Acknowledge receipt
347 message_sender()->Send(new ResourceHostMsg_UploadProgress_ACK(request_id));
350 void ResourceDispatcher::OnReceivedResponse(
351 int request_id, const ResourceResponseHead& response_head) {
352 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedResponse");
353 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
356 request_info->response_start = ConsumeIOTimestamp();
359 RequestPeer* new_peer =
360 delegate_->OnReceivedResponse(
361 request_info->peer, response_head.mime_type, request_info->url);
363 request_info->peer = new_peer;
366 ResourceResponseInfo renderer_response_info;
367 ToResourceResponseInfo(*request_info, response_head, &renderer_response_info);
368 request_info->site_isolation_metadata =
369 SiteIsolationPolicy::OnReceivedResponse(request_info->frame_origin,
370 request_info->response_url,
371 request_info->resource_type,
372 request_info->origin_pid,
373 renderer_response_info);
374 request_info->peer->OnReceivedResponse(renderer_response_info);
377 void ResourceDispatcher::OnReceivedCachedMetadata(
378 int request_id, const std::vector<char>& data) {
379 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
384 request_info->peer->OnReceivedCachedMetadata(&data.front(), data.size());
387 void ResourceDispatcher::OnSetDataBuffer(int request_id,
388 base::SharedMemoryHandle shm_handle,
390 base::ProcessId renderer_pid) {
391 TRACE_EVENT0("loader", "ResourceDispatcher::OnSetDataBuffer");
392 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
396 bool shm_valid = base::SharedMemory::IsHandleValid(shm_handle);
397 CHECK((shm_valid && shm_size > 0) || (!shm_valid && !shm_size));
399 request_info->buffer.reset(
400 new base::SharedMemory(shm_handle, true)); // read only
402 bool ok = request_info->buffer->Map(shm_size);
404 // Added to help debug crbug/160401.
405 base::ProcessId renderer_pid_copy = renderer_pid;
406 base::debug::Alias(&renderer_pid_copy);
408 base::SharedMemoryHandle shm_handle_copy = shm_handle;
409 base::debug::Alias(&shm_handle_copy);
415 request_info->buffer_size = shm_size;
418 void ResourceDispatcher::OnReceivedData(int request_id,
421 int encoded_data_length) {
422 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedData");
423 DCHECK_GT(data_length, 0);
424 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
425 if (request_info && data_length > 0) {
426 CHECK(base::SharedMemory::IsHandleValid(request_info->buffer->handle()));
427 CHECK_GE(request_info->buffer_size, data_offset + data_length);
429 // Ensure that the SHM buffer remains valid for the duration of this scope.
430 // It is possible for CancelPendingRequest() to be called before we exit
432 linked_ptr<base::SharedMemory> retain_buffer(request_info->buffer);
434 base::TimeTicks time_start = base::TimeTicks::Now();
436 const char* data_ptr = static_cast<char*>(request_info->buffer->memory());
438 CHECK(data_ptr + data_offset);
440 // Check whether this response data is compliant with our cross-site
441 // document blocking policy. We only do this for the first packet.
442 std::string alternative_data;
443 if (request_info->site_isolation_metadata.get()) {
444 request_info->blocked_response =
445 SiteIsolationPolicy::ShouldBlockResponse(
446 request_info->site_isolation_metadata, data_ptr + data_offset,
447 data_length, &alternative_data);
448 request_info->site_isolation_metadata.reset();
451 // When the response is not blocked.
452 if (!request_info->blocked_response) {
453 request_info->peer->OnReceivedData(
454 data_ptr + data_offset, data_length, encoded_data_length);
455 } else if (alternative_data.size() > 0) {
456 // When the response is blocked, and when we have any alternative data to
457 // send to the renderer. When |alternative_data| is zero-sized, we do not
458 // call peer's callback.
459 request_info->peer->OnReceivedData(alternative_data.data(),
460 alternative_data.size(),
461 alternative_data.size());
464 UMA_HISTOGRAM_TIMES("ResourceDispatcher.OnReceivedDataTime",
465 base::TimeTicks::Now() - time_start);
468 // Acknowledge the reception of this data.
469 message_sender()->Send(new ResourceHostMsg_DataReceived_ACK(request_id));
472 void ResourceDispatcher::OnDownloadedData(int request_id,
474 int encoded_data_length) {
475 // Acknowledge the reception of this message.
476 message_sender()->Send(
477 new ResourceHostMsg_DataDownloaded_ACK(request_id));
479 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
483 request_info->peer->OnDownloadedData(data_len, encoded_data_length);
486 void ResourceDispatcher::OnReceivedRedirect(
489 const ResourceResponseHead& response_head) {
490 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedRedirect");
491 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
494 request_info->response_start = ConsumeIOTimestamp();
496 bool has_new_first_party_for_cookies = false;
497 GURL new_first_party_for_cookies;
498 ResourceResponseInfo renderer_response_info;
499 ToResourceResponseInfo(*request_info, response_head, &renderer_response_info);
500 if (request_info->peer->OnReceivedRedirect(new_url, renderer_response_info,
501 &has_new_first_party_for_cookies,
502 &new_first_party_for_cookies)) {
503 // Double-check if the request is still around. The call above could
504 // potentially remove it.
505 request_info = GetPendingRequestInfo(request_id);
508 // We update the response_url here so that we can send it to
509 // SiteIsolationPolicy later when OnReceivedResponse is called.
510 request_info->response_url = new_url;
511 request_info->pending_redirect_message.reset(
512 new ResourceHostMsg_FollowRedirect(request_id,
513 has_new_first_party_for_cookies,
514 new_first_party_for_cookies));
515 if (!request_info->is_deferred) {
516 FollowPendingRedirect(request_id, *request_info);
519 CancelPendingRequest(request_id);
523 void ResourceDispatcher::FollowPendingRedirect(
525 PendingRequestInfo& request_info) {
526 IPC::Message* msg = request_info.pending_redirect_message.release();
528 message_sender()->Send(msg);
531 void ResourceDispatcher::OnRequestComplete(
533 const ResourceMsg_RequestCompleteData& request_complete_data) {
534 TRACE_EVENT0("loader", "ResourceDispatcher::OnRequestComplete");
536 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
539 request_info->completion_time = ConsumeIOTimestamp();
540 request_info->buffer.reset();
541 request_info->buffer_size = 0;
543 RequestPeer* peer = request_info->peer;
546 RequestPeer* new_peer =
547 delegate_->OnRequestComplete(
548 request_info->peer, request_info->resource_type,
549 request_complete_data.error_code);
551 request_info->peer = new_peer;
554 base::TimeTicks renderer_completion_time = ToRendererCompletionTime(
555 *request_info, request_complete_data.completion_time);
556 // The request ID will be removed from our pending list in the destructor.
557 // Normally, dispatching this message causes the reference-counted request to
559 peer->OnCompletedRequest(request_complete_data.error_code,
560 request_complete_data.was_ignored_by_handler,
561 request_complete_data.exists_in_cache,
562 request_complete_data.security_info,
563 renderer_completion_time,
564 request_complete_data.encoded_data_length);
567 int ResourceDispatcher::AddPendingRequest(RequestPeer* callback,
568 ResourceType::Type resource_type,
570 const GURL& frame_origin,
571 const GURL& request_url,
572 bool download_to_file) {
573 // Compute a unique request_id for this renderer process.
574 int id = MakeRequestID();
575 pending_requests_[id] = PendingRequestInfo(callback,
584 bool ResourceDispatcher::RemovePendingRequest(int request_id) {
585 PendingRequestList::iterator it = pending_requests_.find(request_id);
586 if (it == pending_requests_.end())
589 PendingRequestInfo& request_info = it->second;
591 bool release_downloaded_file = request_info.download_to_file;
593 ReleaseResourcesInMessageQueue(&request_info.deferred_message_queue);
594 pending_requests_.erase(it);
596 if (release_downloaded_file) {
597 message_sender_->Send(
598 new ResourceHostMsg_ReleaseDownloadedFile(request_id));
604 void ResourceDispatcher::CancelPendingRequest(int request_id) {
605 PendingRequestList::iterator it = pending_requests_.find(request_id);
606 if (it == pending_requests_.end()) {
607 DVLOG(1) << "unknown request";
611 PendingRequestInfo& request_info = it->second;
612 request_info.is_canceled = true;
614 // Because message handlers could result in request_info being destroyed,
615 // we need to work with a stack reference to the deferred queue.
617 queue.swap(request_info.deferred_message_queue);
618 // Removes pending requests. If ResourceMsg_RequestComplete was queued,
620 bool first_message = true;
621 while (!queue.empty()) {
622 IPC::Message* message = queue.front();
623 if (message->type() == ResourceMsg_RequestComplete::ID) {
626 DispatchMessage(*message);
628 // If we skip some ResourceMsg_DataReceived and then dispatched the
629 // original ResourceMsg_RequestComplete(status=success), chrome will
630 // crash because it entered an unexpected state. So replace
631 // ResourceMsg_RequestComplete with failure status.
632 ResourceMsg_RequestCompleteData request_complete_data;
633 request_complete_data.error_code = net::ERR_ABORTED;
634 request_complete_data.was_ignored_by_handler = false;
635 request_complete_data.exists_in_cache = false;
636 request_complete_data.completion_time = base::TimeTicks();
637 request_complete_data.encoded_data_length = 0;
639 ResourceMsg_RequestComplete error_message(request_id,
640 request_complete_data);
641 DispatchMessage(error_message);
644 ReleaseResourcesInDataMessage(*message);
646 first_message = false;
651 // |request_id| will be removed from |pending_requests_| when
652 // OnRequestComplete returns with ERR_ABORTED.
653 message_sender()->Send(new ResourceHostMsg_CancelRequest(request_id));
656 void ResourceDispatcher::SetDefersLoading(int request_id, bool value) {
657 PendingRequestList::iterator it = pending_requests_.find(request_id);
658 if (it == pending_requests_.end()) {
659 DLOG(ERROR) << "unknown request";
662 PendingRequestInfo& request_info = it->second;
664 request_info.is_deferred = value;
665 } else if (request_info.is_deferred) {
666 request_info.is_deferred = false;
668 FollowPendingRedirect(request_id, request_info);
670 base::MessageLoop::current()->PostTask(
672 base::Bind(&ResourceDispatcher::FlushDeferredMessages,
673 weak_factory_.GetWeakPtr(),
678 void ResourceDispatcher::DidChangePriority(int routing_id,
680 net::RequestPriority new_priority,
681 int intra_priority_value) {
682 DCHECK(ContainsKey(pending_requests_, request_id));
683 message_sender()->Send(new ResourceHostMsg_DidChangePriority(
684 request_id, new_priority, intra_priority_value));
687 ResourceDispatcher::PendingRequestInfo::PendingRequestInfo()
689 resource_type(ResourceType::SUB_RESOURCE),
692 download_to_file(false),
693 blocked_response(false),
697 ResourceDispatcher::PendingRequestInfo::PendingRequestInfo(
699 ResourceType::Type resource_type,
701 const GURL& frame_origin,
702 const GURL& request_url,
703 bool download_to_file)
705 resource_type(resource_type),
706 origin_pid(origin_pid),
710 frame_origin(frame_origin),
711 response_url(request_url),
712 download_to_file(download_to_file),
713 request_start(base::TimeTicks::Now()),
714 blocked_response(false) {}
716 ResourceDispatcher::PendingRequestInfo::~PendingRequestInfo() {}
718 void ResourceDispatcher::DispatchMessage(const IPC::Message& message) {
719 IPC_BEGIN_MESSAGE_MAP(ResourceDispatcher, message)
720 IPC_MESSAGE_HANDLER(ResourceMsg_UploadProgress, OnUploadProgress)
721 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedResponse, OnReceivedResponse)
722 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedCachedMetadata,
723 OnReceivedCachedMetadata)
724 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedRedirect, OnReceivedRedirect)
725 IPC_MESSAGE_HANDLER(ResourceMsg_SetDataBuffer, OnSetDataBuffer)
726 IPC_MESSAGE_HANDLER(ResourceMsg_DataReceived, OnReceivedData)
727 IPC_MESSAGE_HANDLER(ResourceMsg_DataDownloaded, OnDownloadedData)
728 IPC_MESSAGE_HANDLER(ResourceMsg_RequestComplete, OnRequestComplete)
729 IPC_END_MESSAGE_MAP()
732 void ResourceDispatcher::FlushDeferredMessages(int request_id) {
733 PendingRequestList::iterator it = pending_requests_.find(request_id);
734 if (it == pending_requests_.end()) // The request could have become invalid.
736 PendingRequestInfo& request_info = it->second;
737 if (request_info.is_deferred)
739 // Because message handlers could result in request_info being destroyed,
740 // we need to work with a stack reference to the deferred queue.
742 q.swap(request_info.deferred_message_queue);
744 IPC::Message* m = q.front();
748 // If this request is deferred in the context of the above message, then
749 // we should honor the same and stop dispatching further messages.
750 // We need to find the request again in the list as it may have completed
751 // by now and the request_info instance above may be invalid.
752 PendingRequestList::iterator index = pending_requests_.find(request_id);
753 if (index != pending_requests_.end()) {
754 PendingRequestInfo& pending_request = index->second;
755 if (pending_request.is_deferred) {
756 pending_request.deferred_message_queue.swap(q);
763 ResourceLoaderBridge* ResourceDispatcher::CreateBridge(
764 const RequestInfo& request_info) {
765 return new IPCResourceLoaderBridge(this, request_info);
768 void ResourceDispatcher::ToResourceResponseInfo(
769 const PendingRequestInfo& request_info,
770 const ResourceResponseHead& browser_info,
771 ResourceResponseInfo* renderer_info) const {
772 *renderer_info = browser_info;
773 if (request_info.request_start.is_null() ||
774 request_info.response_start.is_null() ||
775 browser_info.request_start.is_null() ||
776 browser_info.response_start.is_null() ||
777 browser_info.load_timing.request_start.is_null()) {
780 InterProcessTimeTicksConverter converter(
781 LocalTimeTicks::FromTimeTicks(request_info.request_start),
782 LocalTimeTicks::FromTimeTicks(request_info.response_start),
783 RemoteTimeTicks::FromTimeTicks(browser_info.request_start),
784 RemoteTimeTicks::FromTimeTicks(browser_info.response_start));
786 net::LoadTimingInfo* load_timing = &renderer_info->load_timing;
787 RemoteToLocalTimeTicks(converter, &load_timing->request_start);
788 RemoteToLocalTimeTicks(converter, &load_timing->proxy_resolve_start);
789 RemoteToLocalTimeTicks(converter, &load_timing->proxy_resolve_end);
790 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.dns_start);
791 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.dns_end);
792 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.connect_start);
793 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.connect_end);
794 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.ssl_start);
795 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.ssl_end);
796 RemoteToLocalTimeTicks(converter, &load_timing->send_start);
797 RemoteToLocalTimeTicks(converter, &load_timing->send_end);
798 RemoteToLocalTimeTicks(converter, &load_timing->receive_headers_end);
801 base::TimeTicks ResourceDispatcher::ToRendererCompletionTime(
802 const PendingRequestInfo& request_info,
803 const base::TimeTicks& browser_completion_time) const {
804 if (request_info.completion_time.is_null()) {
805 return browser_completion_time;
808 // TODO(simonjam): The optimal lower bound should be the most recent value of
809 // TimeTicks::Now() returned to WebKit. Is it worth trying to cache that?
810 // Until then, |response_start| is used as it is the most recent value
811 // returned for this request.
812 int64 result = std::max(browser_completion_time.ToInternalValue(),
813 request_info.response_start.ToInternalValue());
814 result = std::min(result, request_info.completion_time.ToInternalValue());
815 return base::TimeTicks::FromInternalValue(result);
818 base::TimeTicks ResourceDispatcher::ConsumeIOTimestamp() {
819 if (io_timestamp_ == base::TimeTicks())
820 return base::TimeTicks::Now();
821 base::TimeTicks result = io_timestamp_;
822 io_timestamp_ = base::TimeTicks();
827 bool ResourceDispatcher::IsResourceDispatcherMessage(
828 const IPC::Message& message) {
829 switch (message.type()) {
830 case ResourceMsg_UploadProgress::ID:
831 case ResourceMsg_ReceivedResponse::ID:
832 case ResourceMsg_ReceivedCachedMetadata::ID:
833 case ResourceMsg_ReceivedRedirect::ID:
834 case ResourceMsg_SetDataBuffer::ID:
835 case ResourceMsg_DataReceived::ID:
836 case ResourceMsg_DataDownloaded::ID:
837 case ResourceMsg_RequestComplete::ID:
848 void ResourceDispatcher::ReleaseResourcesInDataMessage(
849 const IPC::Message& message) {
850 PickleIterator iter(message);
852 if (!message.ReadInt(&iter, &request_id)) {
853 NOTREACHED() << "malformed resource message";
857 // If the message contains a shared memory handle, we should close the handle
858 // or there will be a memory leak.
859 if (message.type() == ResourceMsg_SetDataBuffer::ID) {
860 base::SharedMemoryHandle shm_handle;
861 if (IPC::ParamTraits<base::SharedMemoryHandle>::Read(&message,
864 if (base::SharedMemory::IsHandleValid(shm_handle))
865 base::SharedMemory::CloseHandle(shm_handle);
871 void ResourceDispatcher::ReleaseResourcesInMessageQueue(MessageQueue* queue) {
872 while (!queue->empty()) {
873 IPC::Message* message = queue->front();
874 ReleaseResourcesInDataMessage(*message);
880 } // namespace content