cc: Make picture pile base thread safe.
[chromium-blink-merge.git] / content / child / resource_dispatcher.cc
blobfe71a50fc8255ad1d6adec87df798a2aad7a2c76
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"
35 namespace content {
37 namespace {
39 // Converts |time| from a remote to local TimeTicks, overwriting the original
40 // value.
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() {
49 #if defined(OS_WIN)
50 DWORD last_err = GetLastError();
51 base::debug::Alias(&last_err);
52 #endif
53 CHECK(false);
56 // Each resource request is assigned an ID scoped to this process.
57 int MakeRequestID() {
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++;
65 } // namespace
67 // ResourceLoaderBridge implementation ----------------------------------------
69 class IPCResourceLoaderBridge : public ResourceLoaderBridge {
70 public:
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;
86 private:
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
92 // appending data.
93 ResourceHostMsg_Request request_;
95 // ID for the request, valid once Start()ed, -1 if not valid yet.
96 int request_id_;
98 // The routing id used when sending IPC messages.
99 int routing_id_;
101 // The security origin of the frame that initiates this request.
102 GURL frame_origin_;
104 bool is_synchronous_request_;
107 IPCResourceLoaderBridge::IPCResourceLoaderBridge(
108 ResourceDispatcher* dispatcher,
109 const RequestInfo& request_info)
110 : dispatcher_(dispatcher),
111 request_id_(-1),
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;
136 const RequestExtraData kEmptyData;
137 const RequestExtraData* extra_data;
138 if (request_info.extra_data)
139 extra_data = static_cast<RequestExtraData*>(request_info.extra_data);
140 else
141 extra_data = &kEmptyData;
142 request_.visiblity_state = extra_data->visibility_state();
143 request_.render_frame_id = extra_data->render_frame_id();
144 request_.is_main_frame = extra_data->is_main_frame();
145 request_.parent_is_main_frame = extra_data->parent_is_main_frame();
146 request_.parent_render_frame_id = extra_data->parent_render_frame_id();
147 request_.allow_download = extra_data->allow_download();
148 request_.transition_type = extra_data->transition_type();
149 request_.should_replace_current_entry =
150 extra_data->should_replace_current_entry();
151 request_.transferred_request_child_id =
152 extra_data->transferred_request_child_id();
153 request_.transferred_request_request_id =
154 extra_data->transferred_request_request_id();
155 request_.service_worker_provider_id =
156 extra_data->service_worker_provider_id();
157 frame_origin_ = extra_data->frame_origin();
160 IPCResourceLoaderBridge::~IPCResourceLoaderBridge() {
161 // we remove our hook for the resource dispatcher only when going away, since
162 // it doesn't keep track of whether we've force terminated the request
163 if (request_id_ >= 0) {
164 // this operation may fail, as the dispatcher will have preemptively
165 // removed us when the renderer sends the ReceivedAllData message.
166 dispatcher_->RemovePendingRequest(request_id_);
170 void IPCResourceLoaderBridge::SetRequestBody(
171 ResourceRequestBody* request_body) {
172 DCHECK(request_id_ == -1) << "request already started";
173 request_.request_body = request_body;
176 // Writes a footer on the message and sends it
177 bool IPCResourceLoaderBridge::Start(RequestPeer* peer) {
178 if (request_id_ != -1) {
179 NOTREACHED() << "Starting a request twice";
180 return false;
183 // generate the request ID, and append it to the message
184 request_id_ = dispatcher_->AddPendingRequest(peer,
185 request_.resource_type,
186 request_.origin_pid,
187 frame_origin_,
188 request_.url,
189 request_.download_to_file);
191 return dispatcher_->message_sender()->Send(
192 new ResourceHostMsg_RequestResource(routing_id_, request_id_, request_));
195 void IPCResourceLoaderBridge::Cancel() {
196 if (request_id_ < 0) {
197 NOTREACHED() << "Trying to cancel an unstarted request";
198 return;
201 if (!is_synchronous_request_) {
202 // This also removes the the request from the dispatcher.
203 dispatcher_->CancelPendingRequest(request_id_);
207 void IPCResourceLoaderBridge::SetDefersLoading(bool value) {
208 if (request_id_ < 0) {
209 NOTREACHED() << "Trying to (un)defer an unstarted request";
210 return;
213 dispatcher_->SetDefersLoading(request_id_, value);
216 void IPCResourceLoaderBridge::DidChangePriority(
217 net::RequestPriority new_priority,
218 int intra_priority_value) {
219 if (request_id_ < 0) {
220 NOTREACHED() << "Trying to change priority of an unstarted request";
221 return;
224 dispatcher_->DidChangePriority(
225 request_id_, new_priority, intra_priority_value);
228 bool IPCResourceLoaderBridge::AttachThreadedDataReceiver(
229 blink::WebThreadedDataReceiver* threaded_data_receiver) {
230 if (request_id_ < 0) {
231 NOTREACHED() << "Trying to attach threaded receiver on unstarted request";
232 return false;
235 return dispatcher_->AttachThreadedDataReceiver(request_id_,
236 threaded_data_receiver);
239 void IPCResourceLoaderBridge::SyncLoad(SyncLoadResponse* response) {
240 if (request_id_ != -1) {
241 NOTREACHED() << "Starting a request twice";
242 response->error_code = net::ERR_FAILED;
243 return;
246 request_id_ = MakeRequestID();
247 is_synchronous_request_ = true;
249 SyncLoadResult result;
250 IPC::SyncMessage* msg = new ResourceHostMsg_SyncLoad(routing_id_, request_id_,
251 request_, &result);
252 // NOTE: This may pump events (see RenderThread::Send).
253 if (!dispatcher_->message_sender()->Send(msg)) {
254 response->error_code = net::ERR_FAILED;
255 return;
258 response->error_code = result.error_code;
259 response->url = result.final_url;
260 response->headers = result.headers;
261 response->mime_type = result.mime_type;
262 response->charset = result.charset;
263 response->request_time = result.request_time;
264 response->response_time = result.response_time;
265 response->encoded_data_length = result.encoded_data_length;
266 response->load_timing = result.load_timing;
267 response->devtools_info = result.devtools_info;
268 response->data.swap(result.data);
269 response->download_file_path = result.download_file_path;
272 // ResourceDispatcher ---------------------------------------------------------
274 ResourceDispatcher::ResourceDispatcher(IPC::Sender* sender)
275 : message_sender_(sender),
276 delegate_(NULL),
277 io_timestamp_(base::TimeTicks()),
278 weak_factory_(this) {
281 ResourceDispatcher::~ResourceDispatcher() {
284 // ResourceDispatcher implementation ------------------------------------------
286 bool ResourceDispatcher::OnMessageReceived(const IPC::Message& message) {
287 if (!IsResourceDispatcherMessage(message)) {
288 return false;
291 int request_id;
293 PickleIterator iter(message);
294 if (!message.ReadInt(&iter, &request_id)) {
295 NOTREACHED() << "malformed resource message";
296 return true;
299 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
300 if (!request_info) {
301 // Release resources in the message if it is a data message.
302 ReleaseResourcesInDataMessage(message);
303 return true;
306 if (request_info->is_deferred) {
307 request_info->deferred_message_queue.push_back(new IPC::Message(message));
308 return true;
310 // Make sure any deferred messages are dispatched before we dispatch more.
311 if (!request_info->deferred_message_queue.empty()) {
312 FlushDeferredMessages(request_id);
313 // The request could have been deferred now. If yes then the current
314 // message has to be queued up. The request_info instance should remain
315 // valid here as there are pending messages for it.
316 DCHECK(pending_requests_.find(request_id) != pending_requests_.end());
317 if (request_info->is_deferred) {
318 request_info->deferred_message_queue.push_back(new IPC::Message(message));
319 return true;
323 DispatchMessage(message);
324 return true;
327 ResourceDispatcher::PendingRequestInfo*
328 ResourceDispatcher::GetPendingRequestInfo(int request_id) {
329 PendingRequestList::iterator it = pending_requests_.find(request_id);
330 if (it == pending_requests_.end()) {
331 // This might happen for kill()ed requests on the webkit end.
332 return NULL;
334 return &(it->second);
337 void ResourceDispatcher::OnUploadProgress(int request_id, int64 position,
338 int64 size) {
339 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
340 if (!request_info)
341 return;
343 request_info->peer->OnUploadProgress(position, size);
345 // Acknowledge receipt
346 message_sender_->Send(new ResourceHostMsg_UploadProgress_ACK(request_id));
349 void ResourceDispatcher::OnReceivedResponse(
350 int request_id, const ResourceResponseHead& response_head) {
351 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedResponse");
352 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
353 if (!request_info)
354 return;
355 request_info->response_start = ConsumeIOTimestamp();
357 if (delegate_) {
358 RequestPeer* new_peer =
359 delegate_->OnReceivedResponse(
360 request_info->peer, response_head.mime_type, request_info->url);
361 if (new_peer)
362 request_info->peer = new_peer;
365 // Updates the response_url if the response was fetched by a ServiceWorker,
366 // and it was not generated inside the ServiceWorker.
367 if (response_head.was_fetched_via_service_worker &&
368 !response_head.original_url_via_service_worker.is_empty()) {
369 request_info->response_url = response_head.original_url_via_service_worker;
372 ResourceResponseInfo renderer_response_info;
373 ToResourceResponseInfo(*request_info, response_head, &renderer_response_info);
374 request_info->site_isolation_metadata =
375 SiteIsolationPolicy::OnReceivedResponse(request_info->frame_origin,
376 request_info->response_url,
377 request_info->resource_type,
378 request_info->origin_pid,
379 renderer_response_info);
380 request_info->peer->OnReceivedResponse(renderer_response_info);
383 void ResourceDispatcher::OnReceivedCachedMetadata(
384 int request_id, const std::vector<char>& data) {
385 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
386 if (!request_info)
387 return;
389 if (data.size())
390 request_info->peer->OnReceivedCachedMetadata(&data.front(), data.size());
393 void ResourceDispatcher::OnSetDataBuffer(int request_id,
394 base::SharedMemoryHandle shm_handle,
395 int shm_size,
396 base::ProcessId renderer_pid) {
397 TRACE_EVENT0("loader", "ResourceDispatcher::OnSetDataBuffer");
398 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
399 if (!request_info)
400 return;
402 bool shm_valid = base::SharedMemory::IsHandleValid(shm_handle);
403 CHECK((shm_valid && shm_size > 0) || (!shm_valid && !shm_size));
405 request_info->buffer.reset(
406 new base::SharedMemory(shm_handle, true)); // read only
408 bool ok = request_info->buffer->Map(shm_size);
409 if (!ok) {
410 // Added to help debug crbug/160401.
411 base::ProcessId renderer_pid_copy = renderer_pid;
412 base::debug::Alias(&renderer_pid_copy);
414 base::SharedMemoryHandle shm_handle_copy = shm_handle;
415 base::debug::Alias(&shm_handle_copy);
417 CrashOnMapFailure();
418 return;
421 request_info->buffer_size = shm_size;
424 void ResourceDispatcher::OnReceivedData(int request_id,
425 int data_offset,
426 int data_length,
427 int encoded_data_length) {
428 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedData");
429 DCHECK_GT(data_length, 0);
430 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
431 bool send_ack = true;
432 if (request_info && data_length > 0) {
433 CHECK(base::SharedMemory::IsHandleValid(request_info->buffer->handle()));
434 CHECK_GE(request_info->buffer_size, data_offset + data_length);
436 // Ensure that the SHM buffer remains valid for the duration of this scope.
437 // It is possible for CancelPendingRequest() to be called before we exit
438 // this scope.
439 linked_ptr<base::SharedMemory> retain_buffer(request_info->buffer);
441 base::TimeTicks time_start = base::TimeTicks::Now();
443 const char* data_start = static_cast<char*>(request_info->buffer->memory());
444 CHECK(data_start);
445 CHECK(data_start + data_offset);
446 const char* data_ptr = data_start + data_offset;
448 // Check whether this response data is compliant with our cross-site
449 // document blocking policy. We only do this for the first packet.
450 std::string alternative_data;
451 if (request_info->site_isolation_metadata.get()) {
452 request_info->blocked_response =
453 SiteIsolationPolicy::ShouldBlockResponse(
454 request_info->site_isolation_metadata, data_ptr, data_length,
455 &alternative_data);
456 request_info->site_isolation_metadata.reset();
458 // When the response is blocked we may have any alternative data to
459 // send to the renderer. When |alternative_data| is zero-sized, we do not
460 // call peer's callback.
461 if (request_info->blocked_response && !alternative_data.empty()) {
462 data_ptr = alternative_data.data();
463 data_length = alternative_data.size();
464 encoded_data_length = alternative_data.size();
468 if (!request_info->blocked_response || !alternative_data.empty()) {
469 if (request_info->threaded_data_provider) {
470 request_info->threaded_data_provider->OnReceivedDataOnForegroundThread(
471 data_ptr, data_length, encoded_data_length);
472 // A threaded data provider will take care of its own ACKing, as the
473 // data may be processed later on another thread.
474 send_ack = false;
475 } else {
476 request_info->peer->OnReceivedData(
477 data_ptr, data_length, encoded_data_length);
481 UMA_HISTOGRAM_TIMES("ResourceDispatcher.OnReceivedDataTime",
482 base::TimeTicks::Now() - time_start);
485 // Acknowledge the reception of this data.
486 if (send_ack)
487 message_sender_->Send(new ResourceHostMsg_DataReceived_ACK(request_id));
490 void ResourceDispatcher::OnDownloadedData(int request_id,
491 int data_len,
492 int encoded_data_length) {
493 // Acknowledge the reception of this message.
494 message_sender_->Send(new ResourceHostMsg_DataDownloaded_ACK(request_id));
496 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
497 if (!request_info)
498 return;
500 request_info->peer->OnDownloadedData(data_len, encoded_data_length);
503 void ResourceDispatcher::OnReceivedRedirect(
504 int request_id,
505 const net::RedirectInfo& redirect_info,
506 const ResourceResponseHead& response_head) {
507 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedRedirect");
508 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
509 if (!request_info)
510 return;
511 request_info->response_start = ConsumeIOTimestamp();
513 ResourceResponseInfo renderer_response_info;
514 ToResourceResponseInfo(*request_info, response_head, &renderer_response_info);
515 if (request_info->peer->OnReceivedRedirect(redirect_info,
516 renderer_response_info)) {
517 // Double-check if the request is still around. The call above could
518 // potentially remove it.
519 request_info = GetPendingRequestInfo(request_id);
520 if (!request_info)
521 return;
522 // We update the response_url here so that we can send it to
523 // SiteIsolationPolicy later when OnReceivedResponse is called.
524 request_info->response_url = redirect_info.new_url;
525 request_info->pending_redirect_message.reset(
526 new ResourceHostMsg_FollowRedirect(request_id));
527 if (!request_info->is_deferred) {
528 FollowPendingRedirect(request_id, *request_info);
530 } else {
531 CancelPendingRequest(request_id);
535 void ResourceDispatcher::FollowPendingRedirect(
536 int request_id,
537 PendingRequestInfo& request_info) {
538 IPC::Message* msg = request_info.pending_redirect_message.release();
539 if (msg)
540 message_sender_->Send(msg);
543 void ResourceDispatcher::OnRequestComplete(
544 int request_id,
545 const ResourceMsg_RequestCompleteData& request_complete_data) {
546 TRACE_EVENT0("loader", "ResourceDispatcher::OnRequestComplete");
548 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
549 if (!request_info)
550 return;
551 request_info->completion_time = ConsumeIOTimestamp();
552 request_info->buffer.reset();
553 request_info->buffer_size = 0;
555 RequestPeer* peer = request_info->peer;
557 if (delegate_) {
558 RequestPeer* new_peer =
559 delegate_->OnRequestComplete(
560 request_info->peer, request_info->resource_type,
561 request_complete_data.error_code);
562 if (new_peer)
563 request_info->peer = new_peer;
566 base::TimeTicks renderer_completion_time = ToRendererCompletionTime(
567 *request_info, request_complete_data.completion_time);
568 // The request ID will be removed from our pending list in the destructor.
569 // Normally, dispatching this message causes the reference-counted request to
570 // die immediately.
571 peer->OnCompletedRequest(request_complete_data.error_code,
572 request_complete_data.was_ignored_by_handler,
573 request_complete_data.exists_in_cache,
574 request_complete_data.security_info,
575 renderer_completion_time,
576 request_complete_data.encoded_data_length);
579 int ResourceDispatcher::AddPendingRequest(RequestPeer* callback,
580 ResourceType resource_type,
581 int origin_pid,
582 const GURL& frame_origin,
583 const GURL& request_url,
584 bool download_to_file) {
585 // Compute a unique request_id for this renderer process.
586 int id = MakeRequestID();
587 pending_requests_[id] = PendingRequestInfo(callback,
588 resource_type,
589 origin_pid,
590 frame_origin,
591 request_url,
592 download_to_file);
593 return id;
596 bool ResourceDispatcher::RemovePendingRequest(int request_id) {
597 PendingRequestList::iterator it = pending_requests_.find(request_id);
598 if (it == pending_requests_.end())
599 return false;
601 PendingRequestInfo& request_info = it->second;
603 bool release_downloaded_file = request_info.download_to_file;
605 ReleaseResourcesInMessageQueue(&request_info.deferred_message_queue);
606 pending_requests_.erase(it);
608 if (release_downloaded_file) {
609 message_sender_->Send(
610 new ResourceHostMsg_ReleaseDownloadedFile(request_id));
613 return true;
616 void ResourceDispatcher::CancelPendingRequest(int request_id) {
617 PendingRequestList::iterator it = pending_requests_.find(request_id);
618 if (it == pending_requests_.end()) {
619 DVLOG(1) << "unknown request";
620 return;
623 // Cancel the request, and clean it up so the bridge will receive no more
624 // messages.
625 message_sender_->Send(new ResourceHostMsg_CancelRequest(request_id));
626 RemovePendingRequest(request_id);
629 void ResourceDispatcher::SetDefersLoading(int request_id, bool value) {
630 PendingRequestList::iterator it = pending_requests_.find(request_id);
631 if (it == pending_requests_.end()) {
632 DLOG(ERROR) << "unknown request";
633 return;
635 PendingRequestInfo& request_info = it->second;
636 if (value) {
637 request_info.is_deferred = value;
638 } else if (request_info.is_deferred) {
639 request_info.is_deferred = false;
641 FollowPendingRedirect(request_id, request_info);
643 base::MessageLoop::current()->PostTask(
644 FROM_HERE,
645 base::Bind(&ResourceDispatcher::FlushDeferredMessages,
646 weak_factory_.GetWeakPtr(),
647 request_id));
651 void ResourceDispatcher::DidChangePriority(int request_id,
652 net::RequestPriority new_priority,
653 int intra_priority_value) {
654 DCHECK(ContainsKey(pending_requests_, request_id));
655 message_sender_->Send(new ResourceHostMsg_DidChangePriority(
656 request_id, new_priority, intra_priority_value));
659 bool ResourceDispatcher::AttachThreadedDataReceiver(
660 int request_id, blink::WebThreadedDataReceiver* threaded_data_receiver) {
661 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
662 DCHECK(request_info);
664 if (request_info->buffer != NULL) {
665 DCHECK(!request_info->threaded_data_provider);
666 request_info->threaded_data_provider = new ThreadedDataProvider(
667 request_id, threaded_data_receiver, request_info->buffer,
668 request_info->buffer_size);
669 return true;
672 return false;
675 ResourceDispatcher::PendingRequestInfo::PendingRequestInfo()
676 : peer(NULL),
677 threaded_data_provider(NULL),
678 resource_type(RESOURCE_TYPE_SUB_RESOURCE),
679 is_deferred(false),
680 download_to_file(false),
681 blocked_response(false),
682 buffer_size(0) {
685 ResourceDispatcher::PendingRequestInfo::PendingRequestInfo(
686 RequestPeer* peer,
687 ResourceType resource_type,
688 int origin_pid,
689 const GURL& frame_origin,
690 const GURL& request_url,
691 bool download_to_file)
692 : peer(peer),
693 threaded_data_provider(NULL),
694 resource_type(resource_type),
695 origin_pid(origin_pid),
696 is_deferred(false),
697 url(request_url),
698 frame_origin(frame_origin),
699 response_url(request_url),
700 download_to_file(download_to_file),
701 request_start(base::TimeTicks::Now()),
702 blocked_response(false) {}
704 ResourceDispatcher::PendingRequestInfo::~PendingRequestInfo() {
705 if (threaded_data_provider)
706 threaded_data_provider->Stop();
709 void ResourceDispatcher::DispatchMessage(const IPC::Message& message) {
710 IPC_BEGIN_MESSAGE_MAP(ResourceDispatcher, message)
711 IPC_MESSAGE_HANDLER(ResourceMsg_UploadProgress, OnUploadProgress)
712 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedResponse, OnReceivedResponse)
713 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedCachedMetadata,
714 OnReceivedCachedMetadata)
715 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedRedirect, OnReceivedRedirect)
716 IPC_MESSAGE_HANDLER(ResourceMsg_SetDataBuffer, OnSetDataBuffer)
717 IPC_MESSAGE_HANDLER(ResourceMsg_DataReceived, OnReceivedData)
718 IPC_MESSAGE_HANDLER(ResourceMsg_DataDownloaded, OnDownloadedData)
719 IPC_MESSAGE_HANDLER(ResourceMsg_RequestComplete, OnRequestComplete)
720 IPC_END_MESSAGE_MAP()
723 void ResourceDispatcher::FlushDeferredMessages(int request_id) {
724 PendingRequestList::iterator it = pending_requests_.find(request_id);
725 if (it == pending_requests_.end()) // The request could have become invalid.
726 return;
727 PendingRequestInfo& request_info = it->second;
728 if (request_info.is_deferred)
729 return;
730 // Because message handlers could result in request_info being destroyed,
731 // we need to work with a stack reference to the deferred queue.
732 MessageQueue q;
733 q.swap(request_info.deferred_message_queue);
734 while (!q.empty()) {
735 IPC::Message* m = q.front();
736 q.pop_front();
737 DispatchMessage(*m);
738 delete m;
739 // If this request is deferred in the context of the above message, then
740 // we should honor the same and stop dispatching further messages.
741 // We need to find the request again in the list as it may have completed
742 // by now and the request_info instance above may be invalid.
743 PendingRequestList::iterator index = pending_requests_.find(request_id);
744 if (index != pending_requests_.end()) {
745 PendingRequestInfo& pending_request = index->second;
746 if (pending_request.is_deferred) {
747 pending_request.deferred_message_queue.swap(q);
748 return;
754 ResourceLoaderBridge* ResourceDispatcher::CreateBridge(
755 const RequestInfo& request_info) {
756 return new IPCResourceLoaderBridge(this, request_info);
759 void ResourceDispatcher::ToResourceResponseInfo(
760 const PendingRequestInfo& request_info,
761 const ResourceResponseHead& browser_info,
762 ResourceResponseInfo* renderer_info) const {
763 *renderer_info = browser_info;
764 if (request_info.request_start.is_null() ||
765 request_info.response_start.is_null() ||
766 browser_info.request_start.is_null() ||
767 browser_info.response_start.is_null() ||
768 browser_info.load_timing.request_start.is_null()) {
769 return;
771 InterProcessTimeTicksConverter converter(
772 LocalTimeTicks::FromTimeTicks(request_info.request_start),
773 LocalTimeTicks::FromTimeTicks(request_info.response_start),
774 RemoteTimeTicks::FromTimeTicks(browser_info.request_start),
775 RemoteTimeTicks::FromTimeTicks(browser_info.response_start));
777 net::LoadTimingInfo* load_timing = &renderer_info->load_timing;
778 RemoteToLocalTimeTicks(converter, &load_timing->request_start);
779 RemoteToLocalTimeTicks(converter, &load_timing->proxy_resolve_start);
780 RemoteToLocalTimeTicks(converter, &load_timing->proxy_resolve_end);
781 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.dns_start);
782 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.dns_end);
783 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.connect_start);
784 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.connect_end);
785 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.ssl_start);
786 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.ssl_end);
787 RemoteToLocalTimeTicks(converter, &load_timing->send_start);
788 RemoteToLocalTimeTicks(converter, &load_timing->send_end);
789 RemoteToLocalTimeTicks(converter, &load_timing->receive_headers_end);
790 RemoteToLocalTimeTicks(converter,
791 &renderer_info->service_worker_fetch_start);
792 RemoteToLocalTimeTicks(converter,
793 &renderer_info->service_worker_fetch_ready);
794 RemoteToLocalTimeTicks(converter,
795 &renderer_info->service_worker_fetch_end);
797 // Collect UMA on the inter-process skew.
798 bool is_skew_additive = false;
799 if (converter.IsSkewAdditiveForMetrics()) {
800 is_skew_additive = true;
801 base::TimeDelta skew = converter.GetSkewForMetrics();
802 if (skew >= base::TimeDelta()) {
803 UMA_HISTOGRAM_TIMES(
804 "InterProcessTimeTicks.BrowserAhead_BrowserToRenderer", skew);
805 } else {
806 UMA_HISTOGRAM_TIMES(
807 "InterProcessTimeTicks.BrowserBehind_BrowserToRenderer", -skew);
810 UMA_HISTOGRAM_BOOLEAN(
811 "InterProcessTimeTicks.IsSkewAdditive_BrowserToRenderer",
812 is_skew_additive);
815 base::TimeTicks ResourceDispatcher::ToRendererCompletionTime(
816 const PendingRequestInfo& request_info,
817 const base::TimeTicks& browser_completion_time) const {
818 if (request_info.completion_time.is_null()) {
819 return browser_completion_time;
822 // TODO(simonjam): The optimal lower bound should be the most recent value of
823 // TimeTicks::Now() returned to WebKit. Is it worth trying to cache that?
824 // Until then, |response_start| is used as it is the most recent value
825 // returned for this request.
826 int64 result = std::max(browser_completion_time.ToInternalValue(),
827 request_info.response_start.ToInternalValue());
828 result = std::min(result, request_info.completion_time.ToInternalValue());
829 return base::TimeTicks::FromInternalValue(result);
832 base::TimeTicks ResourceDispatcher::ConsumeIOTimestamp() {
833 if (io_timestamp_ == base::TimeTicks())
834 return base::TimeTicks::Now();
835 base::TimeTicks result = io_timestamp_;
836 io_timestamp_ = base::TimeTicks();
837 return result;
840 // static
841 bool ResourceDispatcher::IsResourceDispatcherMessage(
842 const IPC::Message& message) {
843 switch (message.type()) {
844 case ResourceMsg_UploadProgress::ID:
845 case ResourceMsg_ReceivedResponse::ID:
846 case ResourceMsg_ReceivedCachedMetadata::ID:
847 case ResourceMsg_ReceivedRedirect::ID:
848 case ResourceMsg_SetDataBuffer::ID:
849 case ResourceMsg_DataReceived::ID:
850 case ResourceMsg_DataDownloaded::ID:
851 case ResourceMsg_RequestComplete::ID:
852 return true;
854 default:
855 break;
858 return false;
861 // static
862 void ResourceDispatcher::ReleaseResourcesInDataMessage(
863 const IPC::Message& message) {
864 PickleIterator iter(message);
865 int request_id;
866 if (!message.ReadInt(&iter, &request_id)) {
867 NOTREACHED() << "malformed resource message";
868 return;
871 // If the message contains a shared memory handle, we should close the handle
872 // or there will be a memory leak.
873 if (message.type() == ResourceMsg_SetDataBuffer::ID) {
874 base::SharedMemoryHandle shm_handle;
875 if (IPC::ParamTraits<base::SharedMemoryHandle>::Read(&message,
876 &iter,
877 &shm_handle)) {
878 if (base::SharedMemory::IsHandleValid(shm_handle))
879 base::SharedMemory::CloseHandle(shm_handle);
884 // static
885 void ResourceDispatcher::ReleaseResourcesInMessageQueue(MessageQueue* queue) {
886 while (!queue->empty()) {
887 IPC::Message* message = queue->front();
888 ReleaseResourcesInDataMessage(*message);
889 queue->pop_front();
890 delete message;
894 } // namespace content