Use content::Referrer to pass around referrers in the plugin code
[chromium-blink-merge.git] / content / child / resource_dispatcher.cc
blob0e8bd3647a071acdc13fae38d47e1b12765e9906
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/debug/dump_without_crashing.h"
14 #include "base/files/file_path.h"
15 #include "base/memory/shared_memory.h"
16 #include "base/message_loop/message_loop.h"
17 #include "base/metrics/histogram.h"
18 #include "base/strings/string_util.h"
19 #include "content/child/request_extra_data.h"
20 #include "content/child/request_info.h"
21 #include "content/child/resource_loader_bridge.h"
22 #include "content/child/site_isolation_policy.h"
23 #include "content/child/sync_load_response.h"
24 #include "content/child/threaded_data_provider.h"
25 #include "content/common/inter_process_time_ticks_converter.h"
26 #include "content/common/resource_messages.h"
27 #include "content/public/child/request_peer.h"
28 #include "content/public/child/resource_dispatcher_delegate.h"
29 #include "content/public/common/resource_response.h"
30 #include "content/public/common/resource_type.h"
31 #include "net/base/net_errors.h"
32 #include "net/base/net_util.h"
33 #include "net/base/request_priority.h"
34 #include "net/http/http_response_headers.h"
36 namespace content {
38 namespace {
40 // Converts |time| from a remote to local TimeTicks, overwriting the original
41 // value.
42 void RemoteToLocalTimeTicks(
43 const InterProcessTimeTicksConverter& converter,
44 base::TimeTicks* time) {
45 RemoteTimeTicks remote_time = RemoteTimeTicks::FromTimeTicks(*time);
46 *time = converter.ToLocalTimeTicks(remote_time).ToTimeTicks();
49 void CrashOnMapFailure() {
50 #if defined(OS_WIN)
51 DWORD last_err = GetLastError();
52 base::debug::Alias(&last_err);
53 #endif
54 CHECK(false);
57 // Each resource request is assigned an ID scoped to this process.
58 int MakeRequestID() {
59 // NOTE: The resource_dispatcher_host also needs probably unique
60 // request_ids, so they count down from -2 (-1 is a special we're
61 // screwed value), while the renderer process counts up.
62 static int next_request_id = 0;
63 return next_request_id++;
66 } // namespace
68 // ResourceLoaderBridge implementation ----------------------------------------
70 class IPCResourceLoaderBridge : public ResourceLoaderBridge {
71 public:
72 IPCResourceLoaderBridge(ResourceDispatcher* dispatcher,
73 const RequestInfo& request_info);
74 ~IPCResourceLoaderBridge() override;
76 // ResourceLoaderBridge
77 void SetRequestBody(ResourceRequestBody* request_body) override;
78 bool Start(RequestPeer* peer) override;
79 void Cancel() override;
80 void SetDefersLoading(bool value) override;
81 void DidChangePriority(net::RequestPriority new_priority,
82 int intra_priority_value) override;
83 bool AttachThreadedDataReceiver(
84 blink::WebThreadedDataReceiver* threaded_data_receiver) override;
85 void SyncLoad(SyncLoadResponse* response) override;
87 private:
88 // The resource dispatcher for this loader. The bridge doesn't own it, but
89 // it's guaranteed to outlive the bridge.
90 ResourceDispatcher* dispatcher_;
92 // The request to send, created on initialization for modification and
93 // appending data.
94 ResourceHostMsg_Request request_;
96 // ID for the request, valid once Start()ed, -1 if not valid yet.
97 int request_id_;
99 // The routing id used when sending IPC messages.
100 int routing_id_;
102 // The security origin of the frame that initiates this request.
103 GURL frame_origin_;
105 bool is_synchronous_request_;
108 IPCResourceLoaderBridge::IPCResourceLoaderBridge(
109 ResourceDispatcher* dispatcher,
110 const RequestInfo& request_info)
111 : dispatcher_(dispatcher),
112 request_id_(-1),
113 routing_id_(request_info.routing_id),
114 is_synchronous_request_(false) {
115 DCHECK(dispatcher_) << "no resource dispatcher";
116 request_.method = request_info.method;
117 request_.url = request_info.url;
118 request_.first_party_for_cookies = request_info.first_party_for_cookies;
119 request_.referrer = request_info.referrer.url;
120 request_.referrer_policy = request_info.referrer.policy;
121 request_.headers = request_info.headers;
122 request_.load_flags = request_info.load_flags;
123 request_.origin_pid = request_info.requestor_pid;
124 request_.resource_type = request_info.request_type;
125 request_.priority = request_info.priority;
126 request_.request_context = request_info.request_context;
127 request_.appcache_host_id = request_info.appcache_host_id;
128 request_.download_to_file = request_info.download_to_file;
129 request_.has_user_gesture = request_info.has_user_gesture;
130 request_.skip_service_worker = request_info.skip_service_worker;
131 request_.fetch_request_mode = request_info.fetch_request_mode;
132 request_.fetch_credentials_mode = request_info.fetch_credentials_mode;
133 request_.fetch_request_context_type = request_info.fetch_request_context_type;
134 request_.fetch_frame_type = request_info.fetch_frame_type;
135 request_.enable_load_timing = request_info.enable_load_timing;
136 request_.enable_upload_progress = request_info.enable_upload_progress;
138 if ((request_info.referrer.policy == blink::WebReferrerPolicyDefault ||
139 request_info.referrer.policy ==
140 blink::WebReferrerPolicyNoReferrerWhenDowngrade) &&
141 request_info.referrer.url.SchemeIsSecure() &&
142 !request_info.url.SchemeIsSecure()) {
143 // Debug code for crbug.com/422871
144 base::debug::DumpWithoutCrashing();
145 DLOG(FATAL) << "Trying to send secure referrer for insecure request "
146 << "without an appropriate referrer policy.\n"
147 << "URL = " << request_info.url << "\n"
148 << "Referrer = " << request_info.referrer.url;
151 const RequestExtraData kEmptyData;
152 const RequestExtraData* extra_data;
153 if (request_info.extra_data)
154 extra_data = static_cast<RequestExtraData*>(request_info.extra_data);
155 else
156 extra_data = &kEmptyData;
157 request_.visiblity_state = extra_data->visibility_state();
158 request_.render_frame_id = extra_data->render_frame_id();
159 request_.is_main_frame = extra_data->is_main_frame();
160 request_.parent_is_main_frame = extra_data->parent_is_main_frame();
161 request_.parent_render_frame_id = extra_data->parent_render_frame_id();
162 request_.allow_download = extra_data->allow_download();
163 request_.transition_type = extra_data->transition_type();
164 request_.should_replace_current_entry =
165 extra_data->should_replace_current_entry();
166 request_.transferred_request_child_id =
167 extra_data->transferred_request_child_id();
168 request_.transferred_request_request_id =
169 extra_data->transferred_request_request_id();
170 request_.service_worker_provider_id =
171 extra_data->service_worker_provider_id();
172 frame_origin_ = extra_data->frame_origin();
175 IPCResourceLoaderBridge::~IPCResourceLoaderBridge() {
176 // we remove our hook for the resource dispatcher only when going away, since
177 // it doesn't keep track of whether we've force terminated the request
178 if (request_id_ >= 0) {
179 // this operation may fail, as the dispatcher will have preemptively
180 // removed us when the renderer sends the ReceivedAllData message.
181 dispatcher_->RemovePendingRequest(request_id_);
185 void IPCResourceLoaderBridge::SetRequestBody(
186 ResourceRequestBody* request_body) {
187 DCHECK(request_id_ == -1) << "request already started";
188 request_.request_body = request_body;
191 // Writes a footer on the message and sends it
192 bool IPCResourceLoaderBridge::Start(RequestPeer* peer) {
193 if (request_id_ != -1) {
194 NOTREACHED() << "Starting a request twice";
195 return false;
198 // generate the request ID, and append it to the message
199 request_id_ = dispatcher_->AddPendingRequest(peer,
200 request_.resource_type,
201 request_.origin_pid,
202 frame_origin_,
203 request_.url,
204 request_.download_to_file);
206 return dispatcher_->message_sender()->Send(
207 new ResourceHostMsg_RequestResource(routing_id_, request_id_, request_));
210 void IPCResourceLoaderBridge::Cancel() {
211 if (request_id_ < 0) {
212 NOTREACHED() << "Trying to cancel an unstarted request";
213 return;
216 if (!is_synchronous_request_) {
217 // This also removes the the request from the dispatcher.
218 dispatcher_->CancelPendingRequest(request_id_);
222 void IPCResourceLoaderBridge::SetDefersLoading(bool value) {
223 if (request_id_ < 0) {
224 NOTREACHED() << "Trying to (un)defer an unstarted request";
225 return;
228 dispatcher_->SetDefersLoading(request_id_, value);
231 void IPCResourceLoaderBridge::DidChangePriority(
232 net::RequestPriority new_priority,
233 int intra_priority_value) {
234 if (request_id_ < 0) {
235 NOTREACHED() << "Trying to change priority of an unstarted request";
236 return;
239 dispatcher_->DidChangePriority(
240 request_id_, new_priority, intra_priority_value);
243 bool IPCResourceLoaderBridge::AttachThreadedDataReceiver(
244 blink::WebThreadedDataReceiver* threaded_data_receiver) {
245 if (request_id_ < 0) {
246 NOTREACHED() << "Trying to attach threaded receiver on unstarted request";
247 return false;
250 return dispatcher_->AttachThreadedDataReceiver(request_id_,
251 threaded_data_receiver);
254 void IPCResourceLoaderBridge::SyncLoad(SyncLoadResponse* response) {
255 if (request_id_ != -1) {
256 NOTREACHED() << "Starting a request twice";
257 response->error_code = net::ERR_FAILED;
258 return;
261 request_id_ = MakeRequestID();
262 is_synchronous_request_ = true;
264 SyncLoadResult result;
265 IPC::SyncMessage* msg = new ResourceHostMsg_SyncLoad(routing_id_, request_id_,
266 request_, &result);
267 // NOTE: This may pump events (see RenderThread::Send).
268 if (!dispatcher_->message_sender()->Send(msg)) {
269 response->error_code = net::ERR_FAILED;
270 return;
273 response->error_code = result.error_code;
274 response->url = result.final_url;
275 response->headers = result.headers;
276 response->mime_type = result.mime_type;
277 response->charset = result.charset;
278 response->request_time = result.request_time;
279 response->response_time = result.response_time;
280 response->encoded_data_length = result.encoded_data_length;
281 response->load_timing = result.load_timing;
282 response->devtools_info = result.devtools_info;
283 response->data.swap(result.data);
284 response->download_file_path = result.download_file_path;
287 // ResourceDispatcher ---------------------------------------------------------
289 ResourceDispatcher::ResourceDispatcher(IPC::Sender* sender)
290 : message_sender_(sender),
291 delegate_(NULL),
292 io_timestamp_(base::TimeTicks()),
293 weak_factory_(this) {
296 ResourceDispatcher::~ResourceDispatcher() {
299 // ResourceDispatcher implementation ------------------------------------------
301 bool ResourceDispatcher::OnMessageReceived(const IPC::Message& message) {
302 if (!IsResourceDispatcherMessage(message)) {
303 return false;
306 int request_id;
308 PickleIterator iter(message);
309 if (!message.ReadInt(&iter, &request_id)) {
310 NOTREACHED() << "malformed resource message";
311 return true;
314 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
315 if (!request_info) {
316 // Release resources in the message if it is a data message.
317 ReleaseResourcesInDataMessage(message);
318 return true;
321 if (request_info->is_deferred) {
322 request_info->deferred_message_queue.push_back(new IPC::Message(message));
323 return true;
325 // Make sure any deferred messages are dispatched before we dispatch more.
326 if (!request_info->deferred_message_queue.empty()) {
327 FlushDeferredMessages(request_id);
328 // The request could have been deferred now. If yes then the current
329 // message has to be queued up. The request_info instance should remain
330 // valid here as there are pending messages for it.
331 DCHECK(pending_requests_.find(request_id) != pending_requests_.end());
332 if (request_info->is_deferred) {
333 request_info->deferred_message_queue.push_back(new IPC::Message(message));
334 return true;
338 DispatchMessage(message);
339 return true;
342 ResourceDispatcher::PendingRequestInfo*
343 ResourceDispatcher::GetPendingRequestInfo(int request_id) {
344 PendingRequestList::iterator it = pending_requests_.find(request_id);
345 if (it == pending_requests_.end()) {
346 // This might happen for kill()ed requests on the webkit end.
347 return NULL;
349 return &(it->second);
352 void ResourceDispatcher::OnUploadProgress(int request_id, int64 position,
353 int64 size) {
354 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
355 if (!request_info)
356 return;
358 request_info->peer->OnUploadProgress(position, size);
360 // Acknowledge receipt
361 message_sender_->Send(new ResourceHostMsg_UploadProgress_ACK(request_id));
364 void ResourceDispatcher::OnReceivedResponse(
365 int request_id, const ResourceResponseHead& response_head) {
366 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedResponse");
367 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
368 if (!request_info)
369 return;
370 request_info->response_start = ConsumeIOTimestamp();
372 if (delegate_) {
373 RequestPeer* new_peer =
374 delegate_->OnReceivedResponse(
375 request_info->peer, response_head.mime_type, request_info->url);
376 if (new_peer)
377 request_info->peer = new_peer;
380 // Updates the response_url if the response was fetched by a ServiceWorker,
381 // and it was not generated inside the ServiceWorker.
382 if (response_head.was_fetched_via_service_worker &&
383 !response_head.original_url_via_service_worker.is_empty()) {
384 request_info->response_url = response_head.original_url_via_service_worker;
387 ResourceResponseInfo renderer_response_info;
388 ToResourceResponseInfo(*request_info, response_head, &renderer_response_info);
389 request_info->site_isolation_metadata =
390 SiteIsolationPolicy::OnReceivedResponse(request_info->frame_origin,
391 request_info->response_url,
392 request_info->resource_type,
393 request_info->origin_pid,
394 renderer_response_info);
395 request_info->peer->OnReceivedResponse(renderer_response_info);
398 void ResourceDispatcher::OnReceivedCachedMetadata(
399 int request_id, const std::vector<char>& data) {
400 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
401 if (!request_info)
402 return;
404 if (data.size())
405 request_info->peer->OnReceivedCachedMetadata(&data.front(), data.size());
408 void ResourceDispatcher::OnSetDataBuffer(int request_id,
409 base::SharedMemoryHandle shm_handle,
410 int shm_size,
411 base::ProcessId renderer_pid) {
412 TRACE_EVENT0("loader", "ResourceDispatcher::OnSetDataBuffer");
413 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
414 if (!request_info)
415 return;
417 bool shm_valid = base::SharedMemory::IsHandleValid(shm_handle);
418 CHECK((shm_valid && shm_size > 0) || (!shm_valid && !shm_size));
420 request_info->buffer.reset(
421 new base::SharedMemory(shm_handle, true)); // read only
423 bool ok = request_info->buffer->Map(shm_size);
424 if (!ok) {
425 // Added to help debug crbug/160401.
426 base::ProcessId renderer_pid_copy = renderer_pid;
427 base::debug::Alias(&renderer_pid_copy);
429 base::SharedMemoryHandle shm_handle_copy = shm_handle;
430 base::debug::Alias(&shm_handle_copy);
432 CrashOnMapFailure();
433 return;
436 request_info->buffer_size = shm_size;
439 void ResourceDispatcher::OnReceivedData(int request_id,
440 int data_offset,
441 int data_length,
442 int encoded_data_length) {
443 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedData");
444 DCHECK_GT(data_length, 0);
445 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
446 bool send_ack = true;
447 if (request_info && data_length > 0) {
448 CHECK(base::SharedMemory::IsHandleValid(request_info->buffer->handle()));
449 CHECK_GE(request_info->buffer_size, data_offset + data_length);
451 // Ensure that the SHM buffer remains valid for the duration of this scope.
452 // It is possible for CancelPendingRequest() to be called before we exit
453 // this scope.
454 linked_ptr<base::SharedMemory> retain_buffer(request_info->buffer);
456 base::TimeTicks time_start = base::TimeTicks::Now();
458 const char* data_start = static_cast<char*>(request_info->buffer->memory());
459 CHECK(data_start);
460 CHECK(data_start + data_offset);
461 const char* data_ptr = data_start + data_offset;
463 // Check whether this response data is compliant with our cross-site
464 // document blocking policy. We only do this for the first packet.
465 std::string alternative_data;
466 if (request_info->site_isolation_metadata.get()) {
467 request_info->blocked_response =
468 SiteIsolationPolicy::ShouldBlockResponse(
469 request_info->site_isolation_metadata, data_ptr, data_length,
470 &alternative_data);
471 request_info->site_isolation_metadata.reset();
473 // When the response is blocked we may have any alternative data to
474 // send to the renderer. When |alternative_data| is zero-sized, we do not
475 // call peer's callback.
476 if (request_info->blocked_response && !alternative_data.empty()) {
477 data_ptr = alternative_data.data();
478 data_length = alternative_data.size();
479 encoded_data_length = alternative_data.size();
483 if (!request_info->blocked_response || !alternative_data.empty()) {
484 if (request_info->threaded_data_provider) {
485 request_info->threaded_data_provider->OnReceivedDataOnForegroundThread(
486 data_ptr, data_length, encoded_data_length);
487 // A threaded data provider will take care of its own ACKing, as the
488 // data may be processed later on another thread.
489 send_ack = false;
490 } else {
491 request_info->peer->OnReceivedData(
492 data_ptr, data_length, encoded_data_length);
496 UMA_HISTOGRAM_TIMES("ResourceDispatcher.OnReceivedDataTime",
497 base::TimeTicks::Now() - time_start);
500 // Acknowledge the reception of this data.
501 if (send_ack)
502 message_sender_->Send(new ResourceHostMsg_DataReceived_ACK(request_id));
505 void ResourceDispatcher::OnDownloadedData(int request_id,
506 int data_len,
507 int encoded_data_length) {
508 // Acknowledge the reception of this message.
509 message_sender_->Send(new ResourceHostMsg_DataDownloaded_ACK(request_id));
511 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
512 if (!request_info)
513 return;
515 request_info->peer->OnDownloadedData(data_len, encoded_data_length);
518 void ResourceDispatcher::OnReceivedRedirect(
519 int request_id,
520 const net::RedirectInfo& redirect_info,
521 const ResourceResponseHead& response_head) {
522 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedRedirect");
523 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
524 if (!request_info)
525 return;
526 request_info->response_start = ConsumeIOTimestamp();
528 ResourceResponseInfo renderer_response_info;
529 ToResourceResponseInfo(*request_info, response_head, &renderer_response_info);
530 if (request_info->peer->OnReceivedRedirect(redirect_info,
531 renderer_response_info)) {
532 // Double-check if the request is still around. The call above could
533 // potentially remove it.
534 request_info = GetPendingRequestInfo(request_id);
535 if (!request_info)
536 return;
537 // We update the response_url here so that we can send it to
538 // SiteIsolationPolicy later when OnReceivedResponse is called.
539 request_info->response_url = redirect_info.new_url;
540 request_info->pending_redirect_message.reset(
541 new ResourceHostMsg_FollowRedirect(request_id));
542 if (!request_info->is_deferred) {
543 FollowPendingRedirect(request_id, *request_info);
545 } else {
546 CancelPendingRequest(request_id);
550 void ResourceDispatcher::FollowPendingRedirect(
551 int request_id,
552 PendingRequestInfo& request_info) {
553 IPC::Message* msg = request_info.pending_redirect_message.release();
554 if (msg)
555 message_sender_->Send(msg);
558 void ResourceDispatcher::OnRequestComplete(
559 int request_id,
560 const ResourceMsg_RequestCompleteData& request_complete_data) {
561 TRACE_EVENT0("loader", "ResourceDispatcher::OnRequestComplete");
563 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
564 if (!request_info)
565 return;
566 request_info->completion_time = ConsumeIOTimestamp();
567 request_info->buffer.reset();
568 request_info->buffer_size = 0;
570 RequestPeer* peer = request_info->peer;
572 if (delegate_) {
573 RequestPeer* new_peer =
574 delegate_->OnRequestComplete(
575 request_info->peer, request_info->resource_type,
576 request_complete_data.error_code);
577 if (new_peer)
578 request_info->peer = new_peer;
581 base::TimeTicks renderer_completion_time = ToRendererCompletionTime(
582 *request_info, request_complete_data.completion_time);
583 // The request ID will be removed from our pending list in the destructor.
584 // Normally, dispatching this message causes the reference-counted request to
585 // die immediately.
586 peer->OnCompletedRequest(request_complete_data.error_code,
587 request_complete_data.was_ignored_by_handler,
588 request_complete_data.exists_in_cache,
589 request_complete_data.security_info,
590 renderer_completion_time,
591 request_complete_data.encoded_data_length);
594 int ResourceDispatcher::AddPendingRequest(RequestPeer* callback,
595 ResourceType resource_type,
596 int origin_pid,
597 const GURL& frame_origin,
598 const GURL& request_url,
599 bool download_to_file) {
600 // Compute a unique request_id for this renderer process.
601 int id = MakeRequestID();
602 pending_requests_[id] = PendingRequestInfo(callback,
603 resource_type,
604 origin_pid,
605 frame_origin,
606 request_url,
607 download_to_file);
608 return id;
611 bool ResourceDispatcher::RemovePendingRequest(int request_id) {
612 PendingRequestList::iterator it = pending_requests_.find(request_id);
613 if (it == pending_requests_.end())
614 return false;
616 PendingRequestInfo& request_info = it->second;
618 bool release_downloaded_file = request_info.download_to_file;
620 ReleaseResourcesInMessageQueue(&request_info.deferred_message_queue);
621 pending_requests_.erase(it);
623 if (release_downloaded_file) {
624 message_sender_->Send(
625 new ResourceHostMsg_ReleaseDownloadedFile(request_id));
628 return true;
631 void ResourceDispatcher::CancelPendingRequest(int request_id) {
632 PendingRequestList::iterator it = pending_requests_.find(request_id);
633 if (it == pending_requests_.end()) {
634 DVLOG(1) << "unknown request";
635 return;
638 // Cancel the request, and clean it up so the bridge will receive no more
639 // messages.
640 message_sender_->Send(new ResourceHostMsg_CancelRequest(request_id));
641 RemovePendingRequest(request_id);
644 void ResourceDispatcher::SetDefersLoading(int request_id, bool value) {
645 PendingRequestList::iterator it = pending_requests_.find(request_id);
646 if (it == pending_requests_.end()) {
647 DLOG(ERROR) << "unknown request";
648 return;
650 PendingRequestInfo& request_info = it->second;
651 if (value) {
652 request_info.is_deferred = value;
653 } else if (request_info.is_deferred) {
654 request_info.is_deferred = false;
656 FollowPendingRedirect(request_id, request_info);
658 base::MessageLoop::current()->PostTask(
659 FROM_HERE,
660 base::Bind(&ResourceDispatcher::FlushDeferredMessages,
661 weak_factory_.GetWeakPtr(),
662 request_id));
666 void ResourceDispatcher::DidChangePriority(int request_id,
667 net::RequestPriority new_priority,
668 int intra_priority_value) {
669 DCHECK(ContainsKey(pending_requests_, request_id));
670 message_sender_->Send(new ResourceHostMsg_DidChangePriority(
671 request_id, new_priority, intra_priority_value));
674 bool ResourceDispatcher::AttachThreadedDataReceiver(
675 int request_id, blink::WebThreadedDataReceiver* threaded_data_receiver) {
676 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
677 DCHECK(request_info);
679 if (request_info->buffer != NULL) {
680 DCHECK(!request_info->threaded_data_provider);
681 request_info->threaded_data_provider = new ThreadedDataProvider(
682 request_id, threaded_data_receiver, request_info->buffer,
683 request_info->buffer_size);
684 return true;
687 return false;
690 ResourceDispatcher::PendingRequestInfo::PendingRequestInfo()
691 : peer(NULL),
692 threaded_data_provider(NULL),
693 resource_type(RESOURCE_TYPE_SUB_RESOURCE),
694 is_deferred(false),
695 download_to_file(false),
696 blocked_response(false),
697 buffer_size(0) {
700 ResourceDispatcher::PendingRequestInfo::PendingRequestInfo(
701 RequestPeer* peer,
702 ResourceType resource_type,
703 int origin_pid,
704 const GURL& frame_origin,
705 const GURL& request_url,
706 bool download_to_file)
707 : peer(peer),
708 threaded_data_provider(NULL),
709 resource_type(resource_type),
710 origin_pid(origin_pid),
711 is_deferred(false),
712 url(request_url),
713 frame_origin(frame_origin),
714 response_url(request_url),
715 download_to_file(download_to_file),
716 request_start(base::TimeTicks::Now()),
717 blocked_response(false) {}
719 ResourceDispatcher::PendingRequestInfo::~PendingRequestInfo() {
720 if (threaded_data_provider)
721 threaded_data_provider->Stop();
724 void ResourceDispatcher::DispatchMessage(const IPC::Message& message) {
725 IPC_BEGIN_MESSAGE_MAP(ResourceDispatcher, message)
726 IPC_MESSAGE_HANDLER(ResourceMsg_UploadProgress, OnUploadProgress)
727 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedResponse, OnReceivedResponse)
728 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedCachedMetadata,
729 OnReceivedCachedMetadata)
730 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedRedirect, OnReceivedRedirect)
731 IPC_MESSAGE_HANDLER(ResourceMsg_SetDataBuffer, OnSetDataBuffer)
732 IPC_MESSAGE_HANDLER(ResourceMsg_DataReceived, OnReceivedData)
733 IPC_MESSAGE_HANDLER(ResourceMsg_DataDownloaded, OnDownloadedData)
734 IPC_MESSAGE_HANDLER(ResourceMsg_RequestComplete, OnRequestComplete)
735 IPC_END_MESSAGE_MAP()
738 void ResourceDispatcher::FlushDeferredMessages(int request_id) {
739 PendingRequestList::iterator it = pending_requests_.find(request_id);
740 if (it == pending_requests_.end()) // The request could have become invalid.
741 return;
742 PendingRequestInfo& request_info = it->second;
743 if (request_info.is_deferred)
744 return;
745 // Because message handlers could result in request_info being destroyed,
746 // we need to work with a stack reference to the deferred queue.
747 MessageQueue q;
748 q.swap(request_info.deferred_message_queue);
749 while (!q.empty()) {
750 IPC::Message* m = q.front();
751 q.pop_front();
752 DispatchMessage(*m);
753 delete m;
754 // If this request is deferred in the context of the above message, then
755 // we should honor the same and stop dispatching further messages.
756 // We need to find the request again in the list as it may have completed
757 // by now and the request_info instance above may be invalid.
758 PendingRequestList::iterator index = pending_requests_.find(request_id);
759 if (index != pending_requests_.end()) {
760 PendingRequestInfo& pending_request = index->second;
761 if (pending_request.is_deferred) {
762 pending_request.deferred_message_queue.swap(q);
763 return;
769 ResourceLoaderBridge* ResourceDispatcher::CreateBridge(
770 const RequestInfo& request_info) {
771 return new IPCResourceLoaderBridge(this, request_info);
774 void ResourceDispatcher::ToResourceResponseInfo(
775 const PendingRequestInfo& request_info,
776 const ResourceResponseHead& browser_info,
777 ResourceResponseInfo* renderer_info) const {
778 *renderer_info = browser_info;
779 if (request_info.request_start.is_null() ||
780 request_info.response_start.is_null() ||
781 browser_info.request_start.is_null() ||
782 browser_info.response_start.is_null() ||
783 browser_info.load_timing.request_start.is_null()) {
784 return;
786 InterProcessTimeTicksConverter converter(
787 LocalTimeTicks::FromTimeTicks(request_info.request_start),
788 LocalTimeTicks::FromTimeTicks(request_info.response_start),
789 RemoteTimeTicks::FromTimeTicks(browser_info.request_start),
790 RemoteTimeTicks::FromTimeTicks(browser_info.response_start));
792 net::LoadTimingInfo* load_timing = &renderer_info->load_timing;
793 RemoteToLocalTimeTicks(converter, &load_timing->request_start);
794 RemoteToLocalTimeTicks(converter, &load_timing->proxy_resolve_start);
795 RemoteToLocalTimeTicks(converter, &load_timing->proxy_resolve_end);
796 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.dns_start);
797 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.dns_end);
798 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.connect_start);
799 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.connect_end);
800 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.ssl_start);
801 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.ssl_end);
802 RemoteToLocalTimeTicks(converter, &load_timing->send_start);
803 RemoteToLocalTimeTicks(converter, &load_timing->send_end);
804 RemoteToLocalTimeTicks(converter, &load_timing->receive_headers_end);
805 RemoteToLocalTimeTicks(converter,
806 &renderer_info->service_worker_fetch_start);
807 RemoteToLocalTimeTicks(converter,
808 &renderer_info->service_worker_fetch_ready);
809 RemoteToLocalTimeTicks(converter,
810 &renderer_info->service_worker_fetch_end);
812 // Collect UMA on the inter-process skew.
813 bool is_skew_additive = false;
814 if (converter.IsSkewAdditiveForMetrics()) {
815 is_skew_additive = true;
816 base::TimeDelta skew = converter.GetSkewForMetrics();
817 if (skew >= base::TimeDelta()) {
818 UMA_HISTOGRAM_TIMES(
819 "InterProcessTimeTicks.BrowserAhead_BrowserToRenderer", skew);
820 } else {
821 UMA_HISTOGRAM_TIMES(
822 "InterProcessTimeTicks.BrowserBehind_BrowserToRenderer", -skew);
825 UMA_HISTOGRAM_BOOLEAN(
826 "InterProcessTimeTicks.IsSkewAdditive_BrowserToRenderer",
827 is_skew_additive);
830 base::TimeTicks ResourceDispatcher::ToRendererCompletionTime(
831 const PendingRequestInfo& request_info,
832 const base::TimeTicks& browser_completion_time) const {
833 if (request_info.completion_time.is_null()) {
834 return browser_completion_time;
837 // TODO(simonjam): The optimal lower bound should be the most recent value of
838 // TimeTicks::Now() returned to WebKit. Is it worth trying to cache that?
839 // Until then, |response_start| is used as it is the most recent value
840 // returned for this request.
841 int64 result = std::max(browser_completion_time.ToInternalValue(),
842 request_info.response_start.ToInternalValue());
843 result = std::min(result, request_info.completion_time.ToInternalValue());
844 return base::TimeTicks::FromInternalValue(result);
847 base::TimeTicks ResourceDispatcher::ConsumeIOTimestamp() {
848 if (io_timestamp_ == base::TimeTicks())
849 return base::TimeTicks::Now();
850 base::TimeTicks result = io_timestamp_;
851 io_timestamp_ = base::TimeTicks();
852 return result;
855 // static
856 bool ResourceDispatcher::IsResourceDispatcherMessage(
857 const IPC::Message& message) {
858 switch (message.type()) {
859 case ResourceMsg_UploadProgress::ID:
860 case ResourceMsg_ReceivedResponse::ID:
861 case ResourceMsg_ReceivedCachedMetadata::ID:
862 case ResourceMsg_ReceivedRedirect::ID:
863 case ResourceMsg_SetDataBuffer::ID:
864 case ResourceMsg_DataReceived::ID:
865 case ResourceMsg_DataDownloaded::ID:
866 case ResourceMsg_RequestComplete::ID:
867 return true;
869 default:
870 break;
873 return false;
876 // static
877 void ResourceDispatcher::ReleaseResourcesInDataMessage(
878 const IPC::Message& message) {
879 PickleIterator iter(message);
880 int request_id;
881 if (!message.ReadInt(&iter, &request_id)) {
882 NOTREACHED() << "malformed resource message";
883 return;
886 // If the message contains a shared memory handle, we should close the handle
887 // or there will be a memory leak.
888 if (message.type() == ResourceMsg_SetDataBuffer::ID) {
889 base::SharedMemoryHandle shm_handle;
890 if (IPC::ParamTraits<base::SharedMemoryHandle>::Read(&message,
891 &iter,
892 &shm_handle)) {
893 if (base::SharedMemory::IsHandleValid(shm_handle))
894 base::SharedMemory::CloseHandle(shm_handle);
899 // static
900 void ResourceDispatcher::ReleaseResourcesInMessageQueue(MessageQueue* queue) {
901 while (!queue->empty()) {
902 IPC::Message* message = queue->front();
903 ReleaseResourcesInDataMessage(*message);
904 queue->pop_front();
905 delete message;
909 } // namespace content