Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / content / child / resource_dispatcher.cc
blob6c23fb85265a0b2dc345cc6ac9d12b383144f828
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/child/threaded_data_provider.h"
23 #include "content/common/inter_process_time_ticks_converter.h"
24 #include "content/common/resource_messages.h"
25 #include "content/public/child/request_peer.h"
26 #include "content/public/child/resource_dispatcher_delegate.h"
27 #include "content/public/common/resource_response.h"
28 #include "content/public/common/resource_type.h"
29 #include "net/base/net_errors.h"
30 #include "net/base/net_util.h"
31 #include "net/base/request_priority.h"
32 #include "net/http/http_response_headers.h"
33 #include "webkit/child/resource_loader_bridge.h"
35 using webkit_glue::ResourceLoaderBridge;
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();
50 void CrashOnMapFailure() {
51 #if defined(OS_WIN)
52 DWORD last_err = GetLastError();
53 base::debug::Alias(&last_err);
54 #endif
55 CHECK(false);
58 // Each resource request is assigned an ID scoped to this process.
59 int MakeRequestID() {
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++;
67 } // namespace
69 // ResourceLoaderBridge implementation ----------------------------------------
71 class IPCResourceLoaderBridge : public ResourceLoaderBridge {
72 public:
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 bool AttachThreadedDataReceiver(
85 blink::WebThreadedDataReceiver* threaded_data_receiver) OVERRIDE;
86 virtual void SyncLoad(SyncLoadResponse* response) OVERRIDE;
88 private:
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
94 // appending data.
95 ResourceHostMsg_Request request_;
97 // ID for the request, valid once Start()ed, -1 if not valid yet.
98 int request_id_;
100 // The routing id used when sending IPC messages.
101 int routing_id_;
103 // The security origin of the frame that initiates this request.
104 GURL frame_origin_;
106 bool is_synchronous_request_;
109 IPCResourceLoaderBridge::IPCResourceLoaderBridge(
110 ResourceDispatcher* dispatcher,
111 const RequestInfo& request_info)
112 : dispatcher_(dispatcher),
113 request_id_(-1),
114 routing_id_(request_info.routing_id),
115 is_synchronous_request_(false) {
116 DCHECK(dispatcher_) << "no resource dispatcher";
117 request_.method = request_info.method;
118 request_.url = request_info.url;
119 request_.first_party_for_cookies = request_info.first_party_for_cookies;
120 request_.referrer = request_info.referrer;
121 request_.referrer_policy = request_info.referrer_policy;
122 request_.headers = request_info.headers;
123 request_.load_flags = request_info.load_flags;
124 request_.origin_pid = request_info.requestor_pid;
125 request_.resource_type = request_info.request_type;
126 request_.priority = request_info.priority;
127 request_.request_context = request_info.request_context;
128 request_.appcache_host_id = request_info.appcache_host_id;
129 request_.download_to_file = request_info.download_to_file;
130 request_.has_user_gesture = request_info.has_user_gesture;
131 request_.enable_load_timing = request_info.enable_load_timing;
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);
137 else
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";
177 return false;
180 // generate the request ID, and append it to the message
181 request_id_ = dispatcher_->AddPendingRequest(peer,
182 request_.resource_type,
183 request_.origin_pid,
184 frame_origin_,
185 request_.url,
186 request_.download_to_file);
188 return dispatcher_->message_sender()->Send(
189 new ResourceHostMsg_RequestResource(routing_id_, request_id_, request_));
192 void IPCResourceLoaderBridge::Cancel() {
193 if (request_id_ < 0) {
194 NOTREACHED() << "Trying to cancel an unstarted request";
195 return;
198 if (!is_synchronous_request_) {
199 // This also removes the the request from the dispatcher.
200 dispatcher_->CancelPendingRequest(request_id_);
204 void IPCResourceLoaderBridge::SetDefersLoading(bool value) {
205 if (request_id_ < 0) {
206 NOTREACHED() << "Trying to (un)defer an unstarted request";
207 return;
210 dispatcher_->SetDefersLoading(request_id_, value);
213 void IPCResourceLoaderBridge::DidChangePriority(
214 net::RequestPriority new_priority,
215 int intra_priority_value) {
216 if (request_id_ < 0) {
217 NOTREACHED() << "Trying to change priority of an unstarted request";
218 return;
221 dispatcher_->DidChangePriority(
222 request_id_, new_priority, intra_priority_value);
225 bool IPCResourceLoaderBridge::AttachThreadedDataReceiver(
226 blink::WebThreadedDataReceiver* threaded_data_receiver) {
227 if (request_id_ < 0) {
228 NOTREACHED() << "Trying to attach threaded receiver on unstarted request";
229 return false;
232 return dispatcher_->AttachThreadedDataReceiver(request_id_,
233 threaded_data_receiver);
236 void IPCResourceLoaderBridge::SyncLoad(SyncLoadResponse* response) {
237 if (request_id_ != -1) {
238 NOTREACHED() << "Starting a request twice";
239 response->error_code = net::ERR_FAILED;
240 return;
243 request_id_ = MakeRequestID();
244 is_synchronous_request_ = true;
246 SyncLoadResult result;
247 IPC::SyncMessage* msg = new ResourceHostMsg_SyncLoad(routing_id_, request_id_,
248 request_, &result);
249 // NOTE: This may pump events (see RenderThread::Send).
250 if (!dispatcher_->message_sender()->Send(msg)) {
251 response->error_code = net::ERR_FAILED;
252 return;
255 response->error_code = result.error_code;
256 response->url = result.final_url;
257 response->headers = result.headers;
258 response->mime_type = result.mime_type;
259 response->charset = result.charset;
260 response->request_time = result.request_time;
261 response->response_time = result.response_time;
262 response->encoded_data_length = result.encoded_data_length;
263 response->load_timing = result.load_timing;
264 response->devtools_info = result.devtools_info;
265 response->data.swap(result.data);
266 response->download_file_path = result.download_file_path;
269 // ResourceDispatcher ---------------------------------------------------------
271 ResourceDispatcher::ResourceDispatcher(IPC::Sender* sender)
272 : message_sender_(sender),
273 weak_factory_(this),
274 delegate_(NULL),
275 io_timestamp_(base::TimeTicks()) {
278 ResourceDispatcher::~ResourceDispatcher() {
281 // ResourceDispatcher implementation ------------------------------------------
283 bool ResourceDispatcher::OnMessageReceived(const IPC::Message& message) {
284 if (!IsResourceDispatcherMessage(message)) {
285 return false;
288 int request_id;
290 PickleIterator iter(message);
291 if (!message.ReadInt(&iter, &request_id)) {
292 NOTREACHED() << "malformed resource message";
293 return true;
296 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
297 if (!request_info) {
298 // Release resources in the message if it is a data message.
299 ReleaseResourcesInDataMessage(message);
300 return true;
303 if (request_info->is_deferred) {
304 request_info->deferred_message_queue.push_back(new IPC::Message(message));
305 return true;
307 // Make sure any deferred messages are dispatched before we dispatch more.
308 if (!request_info->deferred_message_queue.empty()) {
309 FlushDeferredMessages(request_id);
310 // The request could have been deferred now. If yes then the current
311 // message has to be queued up. The request_info instance should remain
312 // valid here as there are pending messages for it.
313 DCHECK(pending_requests_.find(request_id) != pending_requests_.end());
314 if (request_info->is_deferred) {
315 request_info->deferred_message_queue.push_back(new IPC::Message(message));
316 return true;
320 DispatchMessage(message);
321 return true;
324 ResourceDispatcher::PendingRequestInfo*
325 ResourceDispatcher::GetPendingRequestInfo(int request_id) {
326 PendingRequestList::iterator it = pending_requests_.find(request_id);
327 if (it == pending_requests_.end()) {
328 // This might happen for kill()ed requests on the webkit end.
329 return NULL;
331 return &(it->second);
334 void ResourceDispatcher::OnUploadProgress(int request_id, int64 position,
335 int64 size) {
336 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
337 if (!request_info)
338 return;
340 request_info->peer->OnUploadProgress(position, size);
342 // Acknowledge receipt
343 message_sender_->Send(new ResourceHostMsg_UploadProgress_ACK(request_id));
346 void ResourceDispatcher::OnReceivedResponse(
347 int request_id, const ResourceResponseHead& response_head) {
348 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedResponse");
349 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
350 if (!request_info)
351 return;
352 request_info->response_start = ConsumeIOTimestamp();
354 if (delegate_) {
355 RequestPeer* new_peer =
356 delegate_->OnReceivedResponse(
357 request_info->peer, response_head.mime_type, request_info->url);
358 if (new_peer)
359 request_info->peer = new_peer;
362 // Updates the response_url if the response was fetched by a ServiceWorker,
363 // and it was not generated inside the ServiceWorker.
364 if (response_head.was_fetched_via_service_worker &&
365 !response_head.original_url_via_service_worker.is_empty()) {
366 request_info->response_url = response_head.original_url_via_service_worker;
369 ResourceResponseInfo renderer_response_info;
370 ToResourceResponseInfo(*request_info, response_head, &renderer_response_info);
371 request_info->site_isolation_metadata =
372 SiteIsolationPolicy::OnReceivedResponse(request_info->frame_origin,
373 request_info->response_url,
374 request_info->resource_type,
375 request_info->origin_pid,
376 renderer_response_info);
377 request_info->peer->OnReceivedResponse(renderer_response_info);
380 void ResourceDispatcher::OnReceivedCachedMetadata(
381 int request_id, const std::vector<char>& data) {
382 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
383 if (!request_info)
384 return;
386 if (data.size())
387 request_info->peer->OnReceivedCachedMetadata(&data.front(), data.size());
390 void ResourceDispatcher::OnSetDataBuffer(int request_id,
391 base::SharedMemoryHandle shm_handle,
392 int shm_size,
393 base::ProcessId renderer_pid) {
394 TRACE_EVENT0("loader", "ResourceDispatcher::OnSetDataBuffer");
395 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
396 if (!request_info)
397 return;
399 bool shm_valid = base::SharedMemory::IsHandleValid(shm_handle);
400 CHECK((shm_valid && shm_size > 0) || (!shm_valid && !shm_size));
402 request_info->buffer.reset(
403 new base::SharedMemory(shm_handle, true)); // read only
405 bool ok = request_info->buffer->Map(shm_size);
406 if (!ok) {
407 // Added to help debug crbug/160401.
408 base::ProcessId renderer_pid_copy = renderer_pid;
409 base::debug::Alias(&renderer_pid_copy);
411 base::SharedMemoryHandle shm_handle_copy = shm_handle;
412 base::debug::Alias(&shm_handle_copy);
414 CrashOnMapFailure();
415 return;
418 request_info->buffer_size = shm_size;
421 void ResourceDispatcher::OnReceivedData(int request_id,
422 int data_offset,
423 int data_length,
424 int encoded_data_length) {
425 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedData");
426 DCHECK_GT(data_length, 0);
427 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
428 bool send_ack = true;
429 if (request_info && data_length > 0) {
430 CHECK(base::SharedMemory::IsHandleValid(request_info->buffer->handle()));
431 CHECK_GE(request_info->buffer_size, data_offset + data_length);
433 // Ensure that the SHM buffer remains valid for the duration of this scope.
434 // It is possible for CancelPendingRequest() to be called before we exit
435 // this scope.
436 linked_ptr<base::SharedMemory> retain_buffer(request_info->buffer);
438 base::TimeTicks time_start = base::TimeTicks::Now();
440 const char* data_start = static_cast<char*>(request_info->buffer->memory());
441 CHECK(data_start);
442 CHECK(data_start + data_offset);
443 const char* data_ptr = data_start + data_offset;
445 // Check whether this response data is compliant with our cross-site
446 // document blocking policy. We only do this for the first packet.
447 std::string alternative_data;
448 if (request_info->site_isolation_metadata.get()) {
449 request_info->blocked_response =
450 SiteIsolationPolicy::ShouldBlockResponse(
451 request_info->site_isolation_metadata, data_ptr, data_length,
452 &alternative_data);
453 request_info->site_isolation_metadata.reset();
455 // When the response is blocked we may have any alternative data to
456 // send to the renderer. When |alternative_data| is zero-sized, we do not
457 // call peer's callback.
458 if (request_info->blocked_response && !alternative_data.empty()) {
459 data_ptr = alternative_data.data();
460 data_length = alternative_data.size();
461 encoded_data_length = alternative_data.size();
465 if (!request_info->blocked_response || !alternative_data.empty()) {
466 if (request_info->threaded_data_provider) {
467 request_info->threaded_data_provider->OnReceivedDataOnForegroundThread(
468 data_ptr, data_length, encoded_data_length);
469 // A threaded data provider will take care of its own ACKing, as the
470 // data may be processed later on another thread.
471 send_ack = false;
472 } else {
473 request_info->peer->OnReceivedData(
474 data_ptr, data_length, encoded_data_length);
478 UMA_HISTOGRAM_TIMES("ResourceDispatcher.OnReceivedDataTime",
479 base::TimeTicks::Now() - time_start);
482 // Acknowledge the reception of this data.
483 if (send_ack)
484 message_sender_->Send(new ResourceHostMsg_DataReceived_ACK(request_id));
487 void ResourceDispatcher::OnDownloadedData(int request_id,
488 int data_len,
489 int encoded_data_length) {
490 // Acknowledge the reception of this message.
491 message_sender_->Send(new ResourceHostMsg_DataDownloaded_ACK(request_id));
493 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
494 if (!request_info)
495 return;
497 request_info->peer->OnDownloadedData(data_len, encoded_data_length);
500 void ResourceDispatcher::OnReceivedRedirect(
501 int request_id,
502 const net::RedirectInfo& redirect_info,
503 const ResourceResponseHead& response_head) {
504 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedRedirect");
505 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
506 if (!request_info)
507 return;
508 request_info->response_start = ConsumeIOTimestamp();
510 ResourceResponseInfo renderer_response_info;
511 ToResourceResponseInfo(*request_info, response_head, &renderer_response_info);
512 if (request_info->peer->OnReceivedRedirect(redirect_info,
513 renderer_response_info)) {
514 // Double-check if the request is still around. The call above could
515 // potentially remove it.
516 request_info = GetPendingRequestInfo(request_id);
517 if (!request_info)
518 return;
519 // We update the response_url here so that we can send it to
520 // SiteIsolationPolicy later when OnReceivedResponse is called.
521 request_info->response_url = redirect_info.new_url;
522 request_info->pending_redirect_message.reset(
523 new ResourceHostMsg_FollowRedirect(request_id));
524 if (!request_info->is_deferred) {
525 FollowPendingRedirect(request_id, *request_info);
527 } else {
528 CancelPendingRequest(request_id);
532 void ResourceDispatcher::FollowPendingRedirect(
533 int request_id,
534 PendingRequestInfo& request_info) {
535 IPC::Message* msg = request_info.pending_redirect_message.release();
536 if (msg)
537 message_sender_->Send(msg);
540 void ResourceDispatcher::OnRequestComplete(
541 int request_id,
542 const ResourceMsg_RequestCompleteData& request_complete_data) {
543 TRACE_EVENT0("loader", "ResourceDispatcher::OnRequestComplete");
545 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
546 if (!request_info)
547 return;
548 request_info->completion_time = ConsumeIOTimestamp();
549 request_info->buffer.reset();
550 request_info->buffer_size = 0;
552 RequestPeer* peer = request_info->peer;
554 if (delegate_) {
555 RequestPeer* new_peer =
556 delegate_->OnRequestComplete(
557 request_info->peer, request_info->resource_type,
558 request_complete_data.error_code);
559 if (new_peer)
560 request_info->peer = new_peer;
563 base::TimeTicks renderer_completion_time = ToRendererCompletionTime(
564 *request_info, request_complete_data.completion_time);
565 // The request ID will be removed from our pending list in the destructor.
566 // Normally, dispatching this message causes the reference-counted request to
567 // die immediately.
568 peer->OnCompletedRequest(request_complete_data.error_code,
569 request_complete_data.was_ignored_by_handler,
570 request_complete_data.exists_in_cache,
571 request_complete_data.security_info,
572 renderer_completion_time,
573 request_complete_data.encoded_data_length);
576 int ResourceDispatcher::AddPendingRequest(RequestPeer* callback,
577 ResourceType resource_type,
578 int origin_pid,
579 const GURL& frame_origin,
580 const GURL& request_url,
581 bool download_to_file) {
582 // Compute a unique request_id for this renderer process.
583 int id = MakeRequestID();
584 pending_requests_[id] = PendingRequestInfo(callback,
585 resource_type,
586 origin_pid,
587 frame_origin,
588 request_url,
589 download_to_file);
590 return id;
593 bool ResourceDispatcher::RemovePendingRequest(int request_id) {
594 PendingRequestList::iterator it = pending_requests_.find(request_id);
595 if (it == pending_requests_.end())
596 return false;
598 PendingRequestInfo& request_info = it->second;
600 bool release_downloaded_file = request_info.download_to_file;
602 ReleaseResourcesInMessageQueue(&request_info.deferred_message_queue);
603 pending_requests_.erase(it);
605 if (release_downloaded_file) {
606 message_sender_->Send(
607 new ResourceHostMsg_ReleaseDownloadedFile(request_id));
610 return true;
613 void ResourceDispatcher::CancelPendingRequest(int request_id) {
614 PendingRequestList::iterator it = pending_requests_.find(request_id);
615 if (it == pending_requests_.end()) {
616 DVLOG(1) << "unknown request";
617 return;
620 // Cancel the request, and clean it up so the bridge will receive no more
621 // messages.
622 message_sender_->Send(new ResourceHostMsg_CancelRequest(request_id));
623 RemovePendingRequest(request_id);
626 void ResourceDispatcher::SetDefersLoading(int request_id, bool value) {
627 PendingRequestList::iterator it = pending_requests_.find(request_id);
628 if (it == pending_requests_.end()) {
629 DLOG(ERROR) << "unknown request";
630 return;
632 PendingRequestInfo& request_info = it->second;
633 if (value) {
634 request_info.is_deferred = value;
635 } else if (request_info.is_deferred) {
636 request_info.is_deferred = false;
638 FollowPendingRedirect(request_id, request_info);
640 base::MessageLoop::current()->PostTask(
641 FROM_HERE,
642 base::Bind(&ResourceDispatcher::FlushDeferredMessages,
643 weak_factory_.GetWeakPtr(),
644 request_id));
648 void ResourceDispatcher::DidChangePriority(int request_id,
649 net::RequestPriority new_priority,
650 int intra_priority_value) {
651 DCHECK(ContainsKey(pending_requests_, request_id));
652 message_sender_->Send(new ResourceHostMsg_DidChangePriority(
653 request_id, new_priority, intra_priority_value));
656 bool ResourceDispatcher::AttachThreadedDataReceiver(
657 int request_id, blink::WebThreadedDataReceiver* threaded_data_receiver) {
658 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
659 DCHECK(request_info);
661 if (request_info->buffer != NULL) {
662 DCHECK(!request_info->threaded_data_provider);
663 request_info->threaded_data_provider = new ThreadedDataProvider(
664 request_id, threaded_data_receiver, request_info->buffer,
665 request_info->buffer_size);
666 return true;
669 return false;
672 ResourceDispatcher::PendingRequestInfo::PendingRequestInfo()
673 : peer(NULL),
674 threaded_data_provider(NULL),
675 resource_type(RESOURCE_TYPE_SUB_RESOURCE),
676 is_deferred(false),
677 download_to_file(false),
678 blocked_response(false),
679 buffer_size(0) {
682 ResourceDispatcher::PendingRequestInfo::PendingRequestInfo(
683 RequestPeer* peer,
684 ResourceType resource_type,
685 int origin_pid,
686 const GURL& frame_origin,
687 const GURL& request_url,
688 bool download_to_file)
689 : peer(peer),
690 threaded_data_provider(NULL),
691 resource_type(resource_type),
692 origin_pid(origin_pid),
693 is_deferred(false),
694 url(request_url),
695 frame_origin(frame_origin),
696 response_url(request_url),
697 download_to_file(download_to_file),
698 request_start(base::TimeTicks::Now()),
699 blocked_response(false) {}
701 ResourceDispatcher::PendingRequestInfo::~PendingRequestInfo() {
702 if (threaded_data_provider)
703 threaded_data_provider->Stop();
706 void ResourceDispatcher::DispatchMessage(const IPC::Message& message) {
707 IPC_BEGIN_MESSAGE_MAP(ResourceDispatcher, message)
708 IPC_MESSAGE_HANDLER(ResourceMsg_UploadProgress, OnUploadProgress)
709 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedResponse, OnReceivedResponse)
710 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedCachedMetadata,
711 OnReceivedCachedMetadata)
712 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedRedirect, OnReceivedRedirect)
713 IPC_MESSAGE_HANDLER(ResourceMsg_SetDataBuffer, OnSetDataBuffer)
714 IPC_MESSAGE_HANDLER(ResourceMsg_DataReceived, OnReceivedData)
715 IPC_MESSAGE_HANDLER(ResourceMsg_DataDownloaded, OnDownloadedData)
716 IPC_MESSAGE_HANDLER(ResourceMsg_RequestComplete, OnRequestComplete)
717 IPC_END_MESSAGE_MAP()
720 void ResourceDispatcher::FlushDeferredMessages(int request_id) {
721 PendingRequestList::iterator it = pending_requests_.find(request_id);
722 if (it == pending_requests_.end()) // The request could have become invalid.
723 return;
724 PendingRequestInfo& request_info = it->second;
725 if (request_info.is_deferred)
726 return;
727 // Because message handlers could result in request_info being destroyed,
728 // we need to work with a stack reference to the deferred queue.
729 MessageQueue q;
730 q.swap(request_info.deferred_message_queue);
731 while (!q.empty()) {
732 IPC::Message* m = q.front();
733 q.pop_front();
734 DispatchMessage(*m);
735 delete m;
736 // If this request is deferred in the context of the above message, then
737 // we should honor the same and stop dispatching further messages.
738 // We need to find the request again in the list as it may have completed
739 // by now and the request_info instance above may be invalid.
740 PendingRequestList::iterator index = pending_requests_.find(request_id);
741 if (index != pending_requests_.end()) {
742 PendingRequestInfo& pending_request = index->second;
743 if (pending_request.is_deferred) {
744 pending_request.deferred_message_queue.swap(q);
745 return;
751 ResourceLoaderBridge* ResourceDispatcher::CreateBridge(
752 const RequestInfo& request_info) {
753 return new IPCResourceLoaderBridge(this, request_info);
756 void ResourceDispatcher::ToResourceResponseInfo(
757 const PendingRequestInfo& request_info,
758 const ResourceResponseHead& browser_info,
759 ResourceResponseInfo* renderer_info) const {
760 *renderer_info = browser_info;
761 if (request_info.request_start.is_null() ||
762 request_info.response_start.is_null() ||
763 browser_info.request_start.is_null() ||
764 browser_info.response_start.is_null() ||
765 browser_info.load_timing.request_start.is_null()) {
766 return;
768 InterProcessTimeTicksConverter converter(
769 LocalTimeTicks::FromTimeTicks(request_info.request_start),
770 LocalTimeTicks::FromTimeTicks(request_info.response_start),
771 RemoteTimeTicks::FromTimeTicks(browser_info.request_start),
772 RemoteTimeTicks::FromTimeTicks(browser_info.response_start));
774 net::LoadTimingInfo* load_timing = &renderer_info->load_timing;
775 RemoteToLocalTimeTicks(converter, &load_timing->request_start);
776 RemoteToLocalTimeTicks(converter, &load_timing->proxy_resolve_start);
777 RemoteToLocalTimeTicks(converter, &load_timing->proxy_resolve_end);
778 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.dns_start);
779 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.dns_end);
780 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.connect_start);
781 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.connect_end);
782 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.ssl_start);
783 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.ssl_end);
784 RemoteToLocalTimeTicks(converter, &load_timing->send_start);
785 RemoteToLocalTimeTicks(converter, &load_timing->send_end);
786 RemoteToLocalTimeTicks(converter, &load_timing->receive_headers_end);
788 // Collect UMA on the inter-process skew.
789 bool is_skew_additive = false;
790 if (converter.IsSkewAdditiveForMetrics()) {
791 is_skew_additive = true;
792 base::TimeDelta skew = converter.GetSkewForMetrics();
793 if (skew >= base::TimeDelta()) {
794 UMA_HISTOGRAM_TIMES(
795 "InterProcessTimeTicks.BrowserAhead_BrowserToRenderer", skew);
796 } else {
797 UMA_HISTOGRAM_TIMES(
798 "InterProcessTimeTicks.BrowserBehind_BrowserToRenderer", -skew);
801 UMA_HISTOGRAM_BOOLEAN(
802 "InterProcessTimeTicks.IsSkewAdditive_BrowserToRenderer",
803 is_skew_additive);
806 base::TimeTicks ResourceDispatcher::ToRendererCompletionTime(
807 const PendingRequestInfo& request_info,
808 const base::TimeTicks& browser_completion_time) const {
809 if (request_info.completion_time.is_null()) {
810 return browser_completion_time;
813 // TODO(simonjam): The optimal lower bound should be the most recent value of
814 // TimeTicks::Now() returned to WebKit. Is it worth trying to cache that?
815 // Until then, |response_start| is used as it is the most recent value
816 // returned for this request.
817 int64 result = std::max(browser_completion_time.ToInternalValue(),
818 request_info.response_start.ToInternalValue());
819 result = std::min(result, request_info.completion_time.ToInternalValue());
820 return base::TimeTicks::FromInternalValue(result);
823 base::TimeTicks ResourceDispatcher::ConsumeIOTimestamp() {
824 if (io_timestamp_ == base::TimeTicks())
825 return base::TimeTicks::Now();
826 base::TimeTicks result = io_timestamp_;
827 io_timestamp_ = base::TimeTicks();
828 return result;
831 // static
832 bool ResourceDispatcher::IsResourceDispatcherMessage(
833 const IPC::Message& message) {
834 switch (message.type()) {
835 case ResourceMsg_UploadProgress::ID:
836 case ResourceMsg_ReceivedResponse::ID:
837 case ResourceMsg_ReceivedCachedMetadata::ID:
838 case ResourceMsg_ReceivedRedirect::ID:
839 case ResourceMsg_SetDataBuffer::ID:
840 case ResourceMsg_DataReceived::ID:
841 case ResourceMsg_DataDownloaded::ID:
842 case ResourceMsg_RequestComplete::ID:
843 return true;
845 default:
846 break;
849 return false;
852 // static
853 void ResourceDispatcher::ReleaseResourcesInDataMessage(
854 const IPC::Message& message) {
855 PickleIterator iter(message);
856 int request_id;
857 if (!message.ReadInt(&iter, &request_id)) {
858 NOTREACHED() << "malformed resource message";
859 return;
862 // If the message contains a shared memory handle, we should close the handle
863 // or there will be a memory leak.
864 if (message.type() == ResourceMsg_SetDataBuffer::ID) {
865 base::SharedMemoryHandle shm_handle;
866 if (IPC::ParamTraits<base::SharedMemoryHandle>::Read(&message,
867 &iter,
868 &shm_handle)) {
869 if (base::SharedMemory::IsHandleValid(shm_handle))
870 base::SharedMemory::CloseHandle(shm_handle);
875 // static
876 void ResourceDispatcher::ReleaseResourcesInMessageQueue(MessageQueue* queue) {
877 while (!queue->empty()) {
878 IPC::Message* message = queue->front();
879 ReleaseResourcesInDataMessage(*message);
880 queue->pop_front();
881 delete message;
885 } // namespace content