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/resource_loader_bridge.h"
21 #include "content/child/site_isolation_policy.h"
22 #include "content/child/sync_load_response.h"
23 #include "content/child/threaded_data_provider.h"
24 #include "content/common/inter_process_time_ticks_converter.h"
25 #include "content/common/resource_messages.h"
26 #include "content/public/child/request_peer.h"
27 #include "content/public/child/resource_dispatcher_delegate.h"
28 #include "content/public/common/resource_response.h"
29 #include "content/public/common/resource_type.h"
30 #include "net/base/net_errors.h"
31 #include "net/base/net_util.h"
32 #include "net/base/request_priority.h"
33 #include "net/http/http_response_headers.h"
39 // Converts |time| from a remote to local TimeTicks, overwriting the original
41 void RemoteToLocalTimeTicks(
42 const InterProcessTimeTicksConverter& converter,
43 base::TimeTicks* time) {
44 RemoteTimeTicks remote_time = RemoteTimeTicks::FromTimeTicks(*time);
45 *time = converter.ToLocalTimeTicks(remote_time).ToTimeTicks();
48 void CrashOnMapFailure() {
50 DWORD last_err = GetLastError();
51 base::debug::Alias(&last_err);
56 // Each resource request is assigned an ID scoped to this process.
58 // NOTE: The resource_dispatcher_host also needs probably unique
59 // request_ids, so they count down from -2 (-1 is a special we're
60 // screwed value), while the renderer process counts up.
61 static int next_request_id = 0;
62 return next_request_id++;
67 // ResourceLoaderBridge implementation ----------------------------------------
69 class IPCResourceLoaderBridge : public ResourceLoaderBridge {
71 IPCResourceLoaderBridge(ResourceDispatcher* dispatcher,
72 const RequestInfo& request_info);
73 ~IPCResourceLoaderBridge() override;
75 // ResourceLoaderBridge
76 void SetRequestBody(ResourceRequestBody* request_body) override;
77 bool Start(RequestPeer* peer) override;
78 void Cancel() override;
79 void SetDefersLoading(bool value) override;
80 void DidChangePriority(net::RequestPriority new_priority,
81 int intra_priority_value) override;
82 bool AttachThreadedDataReceiver(
83 blink::WebThreadedDataReceiver* threaded_data_receiver) override;
84 void SyncLoad(SyncLoadResponse* response) override;
87 // The resource dispatcher for this loader. The bridge doesn't own it, but
88 // it's guaranteed to outlive the bridge.
89 ResourceDispatcher* dispatcher_;
91 // The request to send, created on initialization for modification and
93 ResourceHostMsg_Request request_;
95 // ID for the request, valid once Start()ed, -1 if not valid yet.
98 // The routing id used when sending IPC messages.
101 // The security origin of the frame that initiates this request.
104 bool is_synchronous_request_;
107 IPCResourceLoaderBridge::IPCResourceLoaderBridge(
108 ResourceDispatcher* dispatcher,
109 const RequestInfo& request_info)
110 : dispatcher_(dispatcher),
112 routing_id_(request_info.routing_id),
113 is_synchronous_request_(false) {
114 DCHECK(dispatcher_) << "no resource dispatcher";
115 request_.method = request_info.method;
116 request_.url = request_info.url;
117 request_.first_party_for_cookies = request_info.first_party_for_cookies;
118 request_.referrer = request_info.referrer;
119 request_.referrer_policy = request_info.referrer_policy;
120 request_.headers = request_info.headers;
121 request_.load_flags = request_info.load_flags;
122 request_.origin_pid = request_info.requestor_pid;
123 request_.resource_type = request_info.request_type;
124 request_.priority = request_info.priority;
125 request_.request_context = request_info.request_context;
126 request_.appcache_host_id = request_info.appcache_host_id;
127 request_.download_to_file = request_info.download_to_file;
128 request_.has_user_gesture = request_info.has_user_gesture;
129 request_.skip_service_worker = request_info.skip_service_worker;
130 request_.fetch_request_mode = request_info.fetch_request_mode;
131 request_.fetch_credentials_mode = request_info.fetch_credentials_mode;
132 request_.fetch_request_context_type = request_info.fetch_request_context_type;
133 request_.fetch_frame_type = request_info.fetch_frame_type;
134 request_.enable_load_timing = request_info.enable_load_timing;
135 request_.enable_upload_progress = request_info.enable_upload_progress;
137 const RequestExtraData kEmptyData;
138 const RequestExtraData* extra_data;
139 if (request_info.extra_data)
140 extra_data = static_cast<RequestExtraData*>(request_info.extra_data);
142 extra_data = &kEmptyData;
143 request_.visiblity_state = extra_data->visibility_state();
144 request_.render_frame_id = extra_data->render_frame_id();
145 request_.is_main_frame = extra_data->is_main_frame();
146 request_.parent_is_main_frame = extra_data->parent_is_main_frame();
147 request_.parent_render_frame_id = extra_data->parent_render_frame_id();
148 request_.allow_download = extra_data->allow_download();
149 request_.transition_type = extra_data->transition_type();
150 request_.should_replace_current_entry =
151 extra_data->should_replace_current_entry();
152 request_.transferred_request_child_id =
153 extra_data->transferred_request_child_id();
154 request_.transferred_request_request_id =
155 extra_data->transferred_request_request_id();
156 request_.service_worker_provider_id =
157 extra_data->service_worker_provider_id();
158 frame_origin_ = extra_data->frame_origin();
161 IPCResourceLoaderBridge::~IPCResourceLoaderBridge() {
162 // we remove our hook for the resource dispatcher only when going away, since
163 // it doesn't keep track of whether we've force terminated the request
164 if (request_id_ >= 0) {
165 // this operation may fail, as the dispatcher will have preemptively
166 // removed us when the renderer sends the ReceivedAllData message.
167 dispatcher_->RemovePendingRequest(request_id_);
171 void IPCResourceLoaderBridge::SetRequestBody(
172 ResourceRequestBody* request_body) {
173 DCHECK(request_id_ == -1) << "request already started";
174 request_.request_body = request_body;
177 // Writes a footer on the message and sends it
178 bool IPCResourceLoaderBridge::Start(RequestPeer* peer) {
179 if (request_id_ != -1) {
180 NOTREACHED() << "Starting a request twice";
184 // generate the request ID, and append it to the message
185 request_id_ = dispatcher_->AddPendingRequest(peer,
186 request_.resource_type,
190 request_.download_to_file);
192 return dispatcher_->message_sender()->Send(
193 new ResourceHostMsg_RequestResource(routing_id_, request_id_, request_));
196 void IPCResourceLoaderBridge::Cancel() {
197 if (request_id_ < 0) {
198 NOTREACHED() << "Trying to cancel an unstarted request";
202 if (!is_synchronous_request_) {
203 // This also removes the the request from the dispatcher.
204 dispatcher_->CancelPendingRequest(request_id_);
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,
219 int intra_priority_value) {
220 if (request_id_ < 0) {
221 NOTREACHED() << "Trying to change priority of an unstarted request";
225 dispatcher_->DidChangePriority(
226 request_id_, new_priority, intra_priority_value);
229 bool IPCResourceLoaderBridge::AttachThreadedDataReceiver(
230 blink::WebThreadedDataReceiver* threaded_data_receiver) {
231 if (request_id_ < 0) {
232 NOTREACHED() << "Trying to attach threaded receiver on unstarted request";
236 return dispatcher_->AttachThreadedDataReceiver(request_id_,
237 threaded_data_receiver);
240 void IPCResourceLoaderBridge::SyncLoad(SyncLoadResponse* response) {
241 if (request_id_ != -1) {
242 NOTREACHED() << "Starting a request twice";
243 response->error_code = net::ERR_FAILED;
247 request_id_ = MakeRequestID();
248 is_synchronous_request_ = true;
250 SyncLoadResult result;
251 IPC::SyncMessage* msg = new ResourceHostMsg_SyncLoad(routing_id_, request_id_,
253 // NOTE: This may pump events (see RenderThread::Send).
254 if (!dispatcher_->message_sender()->Send(msg)) {
255 response->error_code = net::ERR_FAILED;
259 response->error_code = result.error_code;
260 response->url = result.final_url;
261 response->headers = result.headers;
262 response->mime_type = result.mime_type;
263 response->charset = result.charset;
264 response->request_time = result.request_time;
265 response->response_time = result.response_time;
266 response->encoded_data_length = result.encoded_data_length;
267 response->load_timing = result.load_timing;
268 response->devtools_info = result.devtools_info;
269 response->data.swap(result.data);
270 response->download_file_path = result.download_file_path;
273 // ResourceDispatcher ---------------------------------------------------------
275 ResourceDispatcher::ResourceDispatcher(IPC::Sender* sender)
276 : message_sender_(sender),
278 io_timestamp_(base::TimeTicks()),
279 weak_factory_(this) {
282 ResourceDispatcher::~ResourceDispatcher() {
285 // ResourceDispatcher implementation ------------------------------------------
287 bool ResourceDispatcher::OnMessageReceived(const IPC::Message& message) {
288 if (!IsResourceDispatcherMessage(message)) {
294 PickleIterator iter(message);
295 if (!message.ReadInt(&iter, &request_id)) {
296 NOTREACHED() << "malformed resource message";
300 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
302 // Release resources in the message if it is a data message.
303 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 // Updates the response_url if the response was fetched by a ServiceWorker,
367 // and it was not generated inside the ServiceWorker.
368 if (response_head.was_fetched_via_service_worker &&
369 !response_head.original_url_via_service_worker.is_empty()) {
370 request_info->response_url = response_head.original_url_via_service_worker;
373 ResourceResponseInfo renderer_response_info;
374 ToResourceResponseInfo(*request_info, response_head, &renderer_response_info);
375 request_info->site_isolation_metadata =
376 SiteIsolationPolicy::OnReceivedResponse(request_info->frame_origin,
377 request_info->response_url,
378 request_info->resource_type,
379 request_info->origin_pid,
380 renderer_response_info);
381 request_info->peer->OnReceivedResponse(renderer_response_info);
384 void ResourceDispatcher::OnReceivedCachedMetadata(
385 int request_id, const std::vector<char>& data) {
386 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
391 request_info->peer->OnReceivedCachedMetadata(&data.front(), data.size());
394 void ResourceDispatcher::OnSetDataBuffer(int request_id,
395 base::SharedMemoryHandle shm_handle,
397 base::ProcessId renderer_pid) {
398 TRACE_EVENT0("loader", "ResourceDispatcher::OnSetDataBuffer");
399 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
403 bool shm_valid = base::SharedMemory::IsHandleValid(shm_handle);
404 CHECK((shm_valid && shm_size > 0) || (!shm_valid && !shm_size));
406 request_info->buffer.reset(
407 new base::SharedMemory(shm_handle, true)); // read only
409 bool ok = request_info->buffer->Map(shm_size);
411 // Added to help debug crbug/160401.
412 base::ProcessId renderer_pid_copy = renderer_pid;
413 base::debug::Alias(&renderer_pid_copy);
415 base::SharedMemoryHandle shm_handle_copy = shm_handle;
416 base::debug::Alias(&shm_handle_copy);
422 request_info->buffer_size = shm_size;
425 void ResourceDispatcher::OnReceivedData(int request_id,
428 int encoded_data_length) {
429 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedData");
430 DCHECK_GT(data_length, 0);
431 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
432 bool send_ack = true;
433 if (request_info && data_length > 0) {
434 CHECK(base::SharedMemory::IsHandleValid(request_info->buffer->handle()));
435 CHECK_GE(request_info->buffer_size, data_offset + data_length);
437 // Ensure that the SHM buffer remains valid for the duration of this scope.
438 // It is possible for CancelPendingRequest() to be called before we exit
440 linked_ptr<base::SharedMemory> retain_buffer(request_info->buffer);
442 base::TimeTicks time_start = base::TimeTicks::Now();
444 const char* data_start = static_cast<char*>(request_info->buffer->memory());
446 CHECK(data_start + data_offset);
447 const char* data_ptr = data_start + data_offset;
449 // Check whether this response data is compliant with our cross-site
450 // document blocking policy. We only do this for the first packet.
451 std::string alternative_data;
452 if (request_info->site_isolation_metadata.get()) {
453 request_info->blocked_response =
454 SiteIsolationPolicy::ShouldBlockResponse(
455 request_info->site_isolation_metadata, data_ptr, data_length,
457 request_info->site_isolation_metadata.reset();
459 // When the response is blocked we may have any alternative data to
460 // send to the renderer. When |alternative_data| is zero-sized, we do not
461 // call peer's callback.
462 if (request_info->blocked_response && !alternative_data.empty()) {
463 data_ptr = alternative_data.data();
464 data_length = alternative_data.size();
465 encoded_data_length = alternative_data.size();
469 if (!request_info->blocked_response || !alternative_data.empty()) {
470 if (request_info->threaded_data_provider) {
471 request_info->threaded_data_provider->OnReceivedDataOnForegroundThread(
472 data_ptr, data_length, encoded_data_length);
473 // A threaded data provider will take care of its own ACKing, as the
474 // data may be processed later on another thread.
477 request_info->peer->OnReceivedData(
478 data_ptr, data_length, encoded_data_length);
482 UMA_HISTOGRAM_TIMES("ResourceDispatcher.OnReceivedDataTime",
483 base::TimeTicks::Now() - time_start);
486 // Acknowledge the reception of this data.
488 message_sender_->Send(new ResourceHostMsg_DataReceived_ACK(request_id));
491 void ResourceDispatcher::OnDownloadedData(int request_id,
493 int encoded_data_length) {
494 // Acknowledge the reception of this message.
495 message_sender_->Send(new ResourceHostMsg_DataDownloaded_ACK(request_id));
497 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
501 request_info->peer->OnDownloadedData(data_len, encoded_data_length);
504 void ResourceDispatcher::OnReceivedRedirect(
506 const net::RedirectInfo& redirect_info,
507 const ResourceResponseHead& response_head) {
508 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedRedirect");
509 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
512 request_info->response_start = ConsumeIOTimestamp();
514 ResourceResponseInfo renderer_response_info;
515 ToResourceResponseInfo(*request_info, response_head, &renderer_response_info);
516 if (request_info->peer->OnReceivedRedirect(redirect_info,
517 renderer_response_info)) {
518 // Double-check if the request is still around. The call above could
519 // potentially remove it.
520 request_info = GetPendingRequestInfo(request_id);
523 // We update the response_url here so that we can send it to
524 // SiteIsolationPolicy later when OnReceivedResponse is called.
525 request_info->response_url = redirect_info.new_url;
526 request_info->pending_redirect_message.reset(
527 new ResourceHostMsg_FollowRedirect(request_id));
528 if (!request_info->is_deferred) {
529 FollowPendingRedirect(request_id, *request_info);
532 CancelPendingRequest(request_id);
536 void ResourceDispatcher::FollowPendingRedirect(
538 PendingRequestInfo& request_info) {
539 IPC::Message* msg = request_info.pending_redirect_message.release();
541 message_sender_->Send(msg);
544 void ResourceDispatcher::OnRequestComplete(
546 const ResourceMsg_RequestCompleteData& request_complete_data) {
547 TRACE_EVENT0("loader", "ResourceDispatcher::OnRequestComplete");
549 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
552 request_info->completion_time = ConsumeIOTimestamp();
553 request_info->buffer.reset();
554 request_info->buffer_size = 0;
556 RequestPeer* peer = request_info->peer;
559 RequestPeer* new_peer =
560 delegate_->OnRequestComplete(
561 request_info->peer, request_info->resource_type,
562 request_complete_data.error_code);
564 request_info->peer = new_peer;
567 base::TimeTicks renderer_completion_time = ToRendererCompletionTime(
568 *request_info, request_complete_data.completion_time);
569 // The request ID will be removed from our pending list in the destructor.
570 // Normally, dispatching this message causes the reference-counted request to
572 peer->OnCompletedRequest(request_complete_data.error_code,
573 request_complete_data.was_ignored_by_handler,
574 request_complete_data.exists_in_cache,
575 request_complete_data.security_info,
576 renderer_completion_time,
577 request_complete_data.encoded_data_length);
580 int ResourceDispatcher::AddPendingRequest(RequestPeer* callback,
581 ResourceType resource_type,
583 const GURL& frame_origin,
584 const GURL& request_url,
585 bool download_to_file) {
586 // Compute a unique request_id for this renderer process.
587 int id = MakeRequestID();
588 pending_requests_[id] = PendingRequestInfo(callback,
597 bool ResourceDispatcher::RemovePendingRequest(int request_id) {
598 PendingRequestList::iterator it = pending_requests_.find(request_id);
599 if (it == pending_requests_.end())
602 PendingRequestInfo& request_info = it->second;
604 bool release_downloaded_file = request_info.download_to_file;
606 ReleaseResourcesInMessageQueue(&request_info.deferred_message_queue);
607 pending_requests_.erase(it);
609 if (release_downloaded_file) {
610 message_sender_->Send(
611 new ResourceHostMsg_ReleaseDownloadedFile(request_id));
617 void ResourceDispatcher::CancelPendingRequest(int request_id) {
618 PendingRequestList::iterator it = pending_requests_.find(request_id);
619 if (it == pending_requests_.end()) {
620 DVLOG(1) << "unknown request";
624 // Cancel the request, and clean it up so the bridge will receive no more
626 message_sender_->Send(new ResourceHostMsg_CancelRequest(request_id));
627 RemovePendingRequest(request_id);
630 void ResourceDispatcher::SetDefersLoading(int request_id, bool value) {
631 PendingRequestList::iterator it = pending_requests_.find(request_id);
632 if (it == pending_requests_.end()) {
633 DLOG(ERROR) << "unknown request";
636 PendingRequestInfo& request_info = it->second;
638 request_info.is_deferred = value;
639 } else if (request_info.is_deferred) {
640 request_info.is_deferred = false;
642 FollowPendingRedirect(request_id, request_info);
644 base::MessageLoop::current()->PostTask(
646 base::Bind(&ResourceDispatcher::FlushDeferredMessages,
647 weak_factory_.GetWeakPtr(),
652 void ResourceDispatcher::DidChangePriority(int request_id,
653 net::RequestPriority new_priority,
654 int intra_priority_value) {
655 DCHECK(ContainsKey(pending_requests_, request_id));
656 message_sender_->Send(new ResourceHostMsg_DidChangePriority(
657 request_id, new_priority, intra_priority_value));
660 bool ResourceDispatcher::AttachThreadedDataReceiver(
661 int request_id, blink::WebThreadedDataReceiver* threaded_data_receiver) {
662 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
663 DCHECK(request_info);
665 if (request_info->buffer != NULL) {
666 DCHECK(!request_info->threaded_data_provider);
667 request_info->threaded_data_provider = new ThreadedDataProvider(
668 request_id, threaded_data_receiver, request_info->buffer,
669 request_info->buffer_size);
676 ResourceDispatcher::PendingRequestInfo::PendingRequestInfo()
678 threaded_data_provider(NULL),
679 resource_type(RESOURCE_TYPE_SUB_RESOURCE),
681 download_to_file(false),
682 blocked_response(false),
686 ResourceDispatcher::PendingRequestInfo::PendingRequestInfo(
688 ResourceType resource_type,
690 const GURL& frame_origin,
691 const GURL& request_url,
692 bool download_to_file)
694 threaded_data_provider(NULL),
695 resource_type(resource_type),
696 origin_pid(origin_pid),
699 frame_origin(frame_origin),
700 response_url(request_url),
701 download_to_file(download_to_file),
702 request_start(base::TimeTicks::Now()),
703 blocked_response(false) {}
705 ResourceDispatcher::PendingRequestInfo::~PendingRequestInfo() {
706 if (threaded_data_provider)
707 threaded_data_provider->Stop();
710 void ResourceDispatcher::DispatchMessage(const IPC::Message& message) {
711 IPC_BEGIN_MESSAGE_MAP(ResourceDispatcher, message)
712 IPC_MESSAGE_HANDLER(ResourceMsg_UploadProgress, OnUploadProgress)
713 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedResponse, OnReceivedResponse)
714 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedCachedMetadata,
715 OnReceivedCachedMetadata)
716 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedRedirect, OnReceivedRedirect)
717 IPC_MESSAGE_HANDLER(ResourceMsg_SetDataBuffer, OnSetDataBuffer)
718 IPC_MESSAGE_HANDLER(ResourceMsg_DataReceived, OnReceivedData)
719 IPC_MESSAGE_HANDLER(ResourceMsg_DataDownloaded, OnDownloadedData)
720 IPC_MESSAGE_HANDLER(ResourceMsg_RequestComplete, OnRequestComplete)
721 IPC_END_MESSAGE_MAP()
724 void ResourceDispatcher::FlushDeferredMessages(int request_id) {
725 PendingRequestList::iterator it = pending_requests_.find(request_id);
726 if (it == pending_requests_.end()) // The request could have become invalid.
728 PendingRequestInfo& request_info = it->second;
729 if (request_info.is_deferred)
731 // Because message handlers could result in request_info being destroyed,
732 // we need to work with a stack reference to the deferred queue.
734 q.swap(request_info.deferred_message_queue);
736 IPC::Message* m = q.front();
740 // If this request is deferred in the context of the above message, then
741 // we should honor the same and stop dispatching further messages.
742 // We need to find the request again in the list as it may have completed
743 // by now and the request_info instance above may be invalid.
744 PendingRequestList::iterator index = pending_requests_.find(request_id);
745 if (index != pending_requests_.end()) {
746 PendingRequestInfo& pending_request = index->second;
747 if (pending_request.is_deferred) {
748 pending_request.deferred_message_queue.swap(q);
755 ResourceLoaderBridge* ResourceDispatcher::CreateBridge(
756 const RequestInfo& request_info) {
757 return new IPCResourceLoaderBridge(this, request_info);
760 void ResourceDispatcher::ToResourceResponseInfo(
761 const PendingRequestInfo& request_info,
762 const ResourceResponseHead& browser_info,
763 ResourceResponseInfo* renderer_info) const {
764 *renderer_info = browser_info;
765 if (request_info.request_start.is_null() ||
766 request_info.response_start.is_null() ||
767 browser_info.request_start.is_null() ||
768 browser_info.response_start.is_null() ||
769 browser_info.load_timing.request_start.is_null()) {
772 InterProcessTimeTicksConverter converter(
773 LocalTimeTicks::FromTimeTicks(request_info.request_start),
774 LocalTimeTicks::FromTimeTicks(request_info.response_start),
775 RemoteTimeTicks::FromTimeTicks(browser_info.request_start),
776 RemoteTimeTicks::FromTimeTicks(browser_info.response_start));
778 net::LoadTimingInfo* load_timing = &renderer_info->load_timing;
779 RemoteToLocalTimeTicks(converter, &load_timing->request_start);
780 RemoteToLocalTimeTicks(converter, &load_timing->proxy_resolve_start);
781 RemoteToLocalTimeTicks(converter, &load_timing->proxy_resolve_end);
782 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.dns_start);
783 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.dns_end);
784 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.connect_start);
785 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.connect_end);
786 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.ssl_start);
787 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.ssl_end);
788 RemoteToLocalTimeTicks(converter, &load_timing->send_start);
789 RemoteToLocalTimeTicks(converter, &load_timing->send_end);
790 RemoteToLocalTimeTicks(converter, &load_timing->receive_headers_end);
791 RemoteToLocalTimeTicks(converter,
792 &renderer_info->service_worker_fetch_start);
793 RemoteToLocalTimeTicks(converter,
794 &renderer_info->service_worker_fetch_ready);
795 RemoteToLocalTimeTicks(converter,
796 &renderer_info->service_worker_fetch_end);
798 // Collect UMA on the inter-process skew.
799 bool is_skew_additive = false;
800 if (converter.IsSkewAdditiveForMetrics()) {
801 is_skew_additive = true;
802 base::TimeDelta skew = converter.GetSkewForMetrics();
803 if (skew >= base::TimeDelta()) {
805 "InterProcessTimeTicks.BrowserAhead_BrowserToRenderer", skew);
808 "InterProcessTimeTicks.BrowserBehind_BrowserToRenderer", -skew);
811 UMA_HISTOGRAM_BOOLEAN(
812 "InterProcessTimeTicks.IsSkewAdditive_BrowserToRenderer",
816 base::TimeTicks ResourceDispatcher::ToRendererCompletionTime(
817 const PendingRequestInfo& request_info,
818 const base::TimeTicks& browser_completion_time) const {
819 if (request_info.completion_time.is_null()) {
820 return browser_completion_time;
823 // TODO(simonjam): The optimal lower bound should be the most recent value of
824 // TimeTicks::Now() returned to WebKit. Is it worth trying to cache that?
825 // Until then, |response_start| is used as it is the most recent value
826 // returned for this request.
827 int64 result = std::max(browser_completion_time.ToInternalValue(),
828 request_info.response_start.ToInternalValue());
829 result = std::min(result, request_info.completion_time.ToInternalValue());
830 return base::TimeTicks::FromInternalValue(result);
833 base::TimeTicks ResourceDispatcher::ConsumeIOTimestamp() {
834 if (io_timestamp_ == base::TimeTicks())
835 return base::TimeTicks::Now();
836 base::TimeTicks result = io_timestamp_;
837 io_timestamp_ = base::TimeTicks();
842 bool ResourceDispatcher::IsResourceDispatcherMessage(
843 const IPC::Message& message) {
844 switch (message.type()) {
845 case ResourceMsg_UploadProgress::ID:
846 case ResourceMsg_ReceivedResponse::ID:
847 case ResourceMsg_ReceivedCachedMetadata::ID:
848 case ResourceMsg_ReceivedRedirect::ID:
849 case ResourceMsg_SetDataBuffer::ID:
850 case ResourceMsg_DataReceived::ID:
851 case ResourceMsg_DataDownloaded::ID:
852 case ResourceMsg_RequestComplete::ID:
863 void ResourceDispatcher::ReleaseResourcesInDataMessage(
864 const IPC::Message& message) {
865 PickleIterator iter(message);
867 if (!message.ReadInt(&iter, &request_id)) {
868 NOTREACHED() << "malformed resource message";
872 // If the message contains a shared memory handle, we should close the handle
873 // or there will be a memory leak.
874 if (message.type() == ResourceMsg_SetDataBuffer::ID) {
875 base::SharedMemoryHandle shm_handle;
876 if (IPC::ParamTraits<base::SharedMemoryHandle>::Read(&message,
879 if (base::SharedMemory::IsHandleValid(shm_handle))
880 base::SharedMemory::CloseHandle(shm_handle);
886 void ResourceDispatcher::ReleaseResourcesInMessageQueue(MessageQueue* queue) {
887 while (!queue->empty()) {
888 IPC::Message* message = queue->front();
889 ReleaseResourcesInDataMessage(*message);
895 } // namespace content