Roll src/third_party/WebKit 27253e2:e5fc8b6 (svn 202580:202581)
[chromium-blink-merge.git] / content / child / resource_dispatcher.cc
blobc9858a970434c76b9f1625336f2c194e4cc6a42f
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/shared_memory_received_data_factory.h"
22 #include "content/child/site_isolation_stats_gatherer.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/fixed_received_data.h"
28 #include "content/public/child/request_peer.h"
29 #include "content/public/child/resource_dispatcher_delegate.h"
30 #include "content/public/common/resource_response.h"
31 #include "content/public/common/resource_type.h"
32 #include "net/base/net_errors.h"
33 #include "net/base/net_util.h"
34 #include "net/base/request_priority.h"
35 #include "net/http/http_response_headers.h"
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 ResourceDispatcher::ResourceDispatcher(
70 IPC::Sender* sender,
71 scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner)
72 : message_sender_(sender),
73 delegate_(NULL),
74 io_timestamp_(base::TimeTicks()),
75 main_thread_task_runner_(main_thread_task_runner),
76 weak_factory_(this) {
79 ResourceDispatcher::~ResourceDispatcher() {
82 bool ResourceDispatcher::OnMessageReceived(const IPC::Message& message) {
83 // TODO(erikchen): Temporary code to help track http://crbug.com/527588.
84 content::CheckContentsOfDataReceivedMessage(&message);
86 if (!IsResourceDispatcherMessage(message)) {
87 return false;
90 int request_id;
92 base::PickleIterator iter(message);
93 if (!iter.ReadInt(&request_id)) {
94 NOTREACHED() << "malformed resource message";
95 return true;
98 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
99 if (!request_info) {
100 // Release resources in the message if it is a data message.
101 ReleaseResourcesInDataMessage(message);
102 return true;
105 if (request_info->is_deferred) {
106 request_info->deferred_message_queue.push_back(new IPC::Message(message));
107 return true;
109 // Make sure any deferred messages are dispatched before we dispatch more.
110 if (!request_info->deferred_message_queue.empty()) {
111 FlushDeferredMessages(request_id);
112 request_info = GetPendingRequestInfo(request_id);
113 DCHECK(request_info);
114 if (request_info->is_deferred) {
115 request_info->deferred_message_queue.push_back(new IPC::Message(message));
116 return true;
120 DispatchMessage(message);
121 return true;
124 ResourceDispatcher::PendingRequestInfo*
125 ResourceDispatcher::GetPendingRequestInfo(int request_id) {
126 PendingRequestList::iterator it = pending_requests_.find(request_id);
127 if (it == pending_requests_.end()) {
128 // This might happen for kill()ed requests on the webkit end.
129 return NULL;
131 return &(it->second);
134 void ResourceDispatcher::OnUploadProgress(int request_id, int64 position,
135 int64 size) {
136 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
137 if (!request_info)
138 return;
140 request_info->peer->OnUploadProgress(position, size);
142 // Acknowledge receipt
143 message_sender_->Send(new ResourceHostMsg_UploadProgress_ACK(request_id));
146 void ResourceDispatcher::OnReceivedResponse(
147 int request_id, const ResourceResponseHead& response_head) {
148 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedResponse");
149 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
150 if (!request_info)
151 return;
152 request_info->response_start = ConsumeIOTimestamp();
154 if (delegate_) {
155 RequestPeer* new_peer =
156 delegate_->OnReceivedResponse(
157 request_info->peer, response_head.mime_type, request_info->url);
158 if (new_peer)
159 request_info->peer = new_peer;
162 ResourceResponseInfo renderer_response_info;
163 ToResourceResponseInfo(*request_info, response_head, &renderer_response_info);
164 request_info->site_isolation_metadata =
165 SiteIsolationStatsGatherer::OnReceivedResponse(
166 request_info->frame_origin, request_info->response_url,
167 request_info->resource_type, request_info->origin_pid,
168 renderer_response_info);
169 request_info->peer->OnReceivedResponse(renderer_response_info);
172 void ResourceDispatcher::OnReceivedCachedMetadata(
173 int request_id, const std::vector<char>& data) {
174 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
175 if (!request_info)
176 return;
178 if (data.size())
179 request_info->peer->OnReceivedCachedMetadata(&data.front(), data.size());
182 void ResourceDispatcher::OnSetDataBuffer(int request_id,
183 base::SharedMemoryHandle shm_handle,
184 int shm_size,
185 base::ProcessId renderer_pid) {
186 TRACE_EVENT0("loader", "ResourceDispatcher::OnSetDataBuffer");
187 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
188 if (!request_info)
189 return;
191 bool shm_valid = base::SharedMemory::IsHandleValid(shm_handle);
192 CHECK((shm_valid && shm_size > 0) || (!shm_valid && !shm_size));
194 request_info->buffer.reset(
195 new base::SharedMemory(shm_handle, true)); // read only
196 request_info->received_data_factory =
197 make_scoped_refptr(new SharedMemoryReceivedDataFactory(
198 message_sender_, request_id, request_info->buffer));
200 bool ok = request_info->buffer->Map(shm_size);
201 if (!ok) {
202 // Added to help debug crbug/160401.
203 base::ProcessId renderer_pid_copy = renderer_pid;
204 base::debug::Alias(&renderer_pid_copy);
206 base::SharedMemoryHandle shm_handle_copy = shm_handle;
207 base::debug::Alias(&shm_handle_copy);
209 CrashOnMapFailure();
210 return;
213 request_info->buffer_size = shm_size;
216 void ResourceDispatcher::OnReceivedData(int request_id,
217 int data_offset,
218 int data_length,
219 int encoded_data_length) {
220 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedData");
221 DCHECK_GT(data_length, 0);
222 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
223 bool send_ack = true;
224 if (request_info && data_length > 0) {
225 // TODO(erikchen): Temporary code to help track http://crbug.com/527588.
226 int buffer_size = request_info->buffer_size;
228 CHECK(base::SharedMemory::IsHandleValid(request_info->buffer->handle()));
229 CHECK_GE(request_info->buffer_size, data_offset + data_length);
231 // TODO(erikchen): Temporary code to help track http://crbug.com/527588.
232 base::debug::Alias(request_info);
233 base::debug::Alias(&buffer_size);
235 // Ensure that the SHM buffer remains valid for the duration of this scope.
236 // It is possible for Cancel() to be called before we exit this scope.
237 // SharedMemoryReceivedDataFactory stores the SHM buffer inside it.
238 scoped_refptr<SharedMemoryReceivedDataFactory> factory(
239 request_info->received_data_factory);
241 base::TimeTicks time_start = base::TimeTicks::Now();
243 const char* data_start = static_cast<char*>(request_info->buffer->memory());
244 CHECK(data_start);
245 CHECK(data_start + data_offset);
246 const char* data_ptr = data_start + data_offset;
248 // Check whether this response data is compliant with our cross-site
249 // document blocking policy. We only do this for the first chunk of data.
250 if (request_info->site_isolation_metadata.get()) {
251 SiteIsolationStatsGatherer::OnReceivedFirstChunk(
252 request_info->site_isolation_metadata, data_ptr, data_length);
253 request_info->site_isolation_metadata.reset();
256 if (request_info->threaded_data_provider) {
257 // A threaded data provider will take care of its own ACKing, as the data
258 // may be processed later on another thread.
259 send_ack = false;
260 request_info->threaded_data_provider->OnReceivedDataOnForegroundThread(
261 data_ptr, data_length, encoded_data_length);
262 } else {
263 scoped_ptr<RequestPeer::ReceivedData> data =
264 factory->Create(data_offset, data_length, encoded_data_length);
265 // |data| takes care of ACKing.
266 send_ack = false;
267 request_info->peer->OnReceivedData(data.Pass());
270 UMA_HISTOGRAM_TIMES("ResourceDispatcher.OnReceivedDataTime",
271 base::TimeTicks::Now() - time_start);
274 // Acknowledge the reception of this data.
275 if (send_ack)
276 message_sender_->Send(new ResourceHostMsg_DataReceived_ACK(request_id));
279 void ResourceDispatcher::OnDownloadedData(int request_id,
280 int data_len,
281 int encoded_data_length) {
282 // Acknowledge the reception of this message.
283 message_sender_->Send(new ResourceHostMsg_DataDownloaded_ACK(request_id));
285 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
286 if (!request_info)
287 return;
289 request_info->peer->OnDownloadedData(data_len, encoded_data_length);
292 void ResourceDispatcher::OnReceivedRedirect(
293 int request_id,
294 const net::RedirectInfo& redirect_info,
295 const ResourceResponseHead& response_head) {
296 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedRedirect");
297 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
298 if (!request_info)
299 return;
300 request_info->response_start = ConsumeIOTimestamp();
302 ResourceResponseInfo renderer_response_info;
303 ToResourceResponseInfo(*request_info, response_head, &renderer_response_info);
304 if (request_info->peer->OnReceivedRedirect(redirect_info,
305 renderer_response_info)) {
306 // Double-check if the request is still around. The call above could
307 // potentially remove it.
308 request_info = GetPendingRequestInfo(request_id);
309 if (!request_info)
310 return;
311 // We update the response_url here so that we can send it to
312 // SiteIsolationStatsGatherer later when OnReceivedResponse is called.
313 request_info->response_url = redirect_info.new_url;
314 request_info->pending_redirect_message.reset(
315 new ResourceHostMsg_FollowRedirect(request_id));
316 if (!request_info->is_deferred) {
317 FollowPendingRedirect(request_id, *request_info);
319 } else {
320 Cancel(request_id);
324 void ResourceDispatcher::FollowPendingRedirect(
325 int request_id,
326 PendingRequestInfo& request_info) {
327 IPC::Message* msg = request_info.pending_redirect_message.release();
328 if (msg)
329 message_sender_->Send(msg);
332 void ResourceDispatcher::OnRequestComplete(
333 int request_id,
334 const ResourceMsg_RequestCompleteData& request_complete_data) {
335 TRACE_EVENT0("loader", "ResourceDispatcher::OnRequestComplete");
337 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
338 if (!request_info)
339 return;
340 request_info->completion_time = ConsumeIOTimestamp();
341 request_info->buffer.reset();
342 if (request_info->received_data_factory)
343 request_info->received_data_factory->Stop();
344 request_info->received_data_factory = nullptr;
345 request_info->buffer_size = 0;
347 RequestPeer* peer = request_info->peer;
349 if (delegate_) {
350 RequestPeer* new_peer =
351 delegate_->OnRequestComplete(
352 request_info->peer, request_info->resource_type,
353 request_complete_data.error_code);
354 if (new_peer)
355 request_info->peer = new_peer;
358 base::TimeTicks renderer_completion_time = ToRendererCompletionTime(
359 *request_info, request_complete_data.completion_time);
361 // If we have a threaded data provider, this message needs to bounce off the
362 // background thread before it's returned to this thread and handled,
363 // to make sure it's processed after all incoming data.
364 if (request_info->threaded_data_provider) {
365 request_info->threaded_data_provider->OnRequestCompleteForegroundThread(
366 weak_factory_.GetWeakPtr(), request_complete_data,
367 renderer_completion_time);
368 return;
371 // The request ID will be removed from our pending list in the destructor.
372 // Normally, dispatching this message causes the reference-counted request to
373 // die immediately.
374 peer->OnCompletedRequest(request_complete_data.error_code,
375 request_complete_data.was_ignored_by_handler,
376 request_complete_data.exists_in_cache,
377 request_complete_data.security_info,
378 renderer_completion_time,
379 request_complete_data.encoded_data_length);
382 void ResourceDispatcher::CompletedRequestAfterBackgroundThreadFlush(
383 int request_id,
384 const ResourceMsg_RequestCompleteData& request_complete_data,
385 const base::TimeTicks& renderer_completion_time) {
386 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
387 if (!request_info)
388 return;
390 RequestPeer* peer = request_info->peer;
391 peer->OnCompletedRequest(request_complete_data.error_code,
392 request_complete_data.was_ignored_by_handler,
393 request_complete_data.exists_in_cache,
394 request_complete_data.security_info,
395 renderer_completion_time,
396 request_complete_data.encoded_data_length);
399 bool ResourceDispatcher::RemovePendingRequest(int request_id) {
400 PendingRequestList::iterator it = pending_requests_.find(request_id);
401 if (it == pending_requests_.end())
402 return false;
404 PendingRequestInfo& request_info = it->second;
406 bool release_downloaded_file = request_info.download_to_file;
408 ReleaseResourcesInMessageQueue(&request_info.deferred_message_queue);
409 pending_requests_.erase(it);
411 if (release_downloaded_file) {
412 message_sender_->Send(
413 new ResourceHostMsg_ReleaseDownloadedFile(request_id));
416 return true;
419 void ResourceDispatcher::Cancel(int request_id) {
420 PendingRequestList::iterator it = pending_requests_.find(request_id);
421 if (it == pending_requests_.end()) {
422 DVLOG(1) << "unknown request";
423 return;
426 // Cancel the request, and clean it up so the bridge will receive no more
427 // messages.
428 message_sender_->Send(new ResourceHostMsg_CancelRequest(request_id));
429 RemovePendingRequest(request_id);
432 void ResourceDispatcher::SetDefersLoading(int request_id, bool value) {
433 PendingRequestList::iterator it = pending_requests_.find(request_id);
434 if (it == pending_requests_.end()) {
435 DLOG(ERROR) << "unknown request";
436 return;
438 PendingRequestInfo& request_info = it->second;
439 if (value) {
440 request_info.is_deferred = value;
441 } else if (request_info.is_deferred) {
442 request_info.is_deferred = false;
444 FollowPendingRedirect(request_id, request_info);
446 main_thread_task_runner_->PostTask(
447 FROM_HERE, base::Bind(&ResourceDispatcher::FlushDeferredMessages,
448 weak_factory_.GetWeakPtr(), request_id));
452 void ResourceDispatcher::DidChangePriority(int request_id,
453 net::RequestPriority new_priority,
454 int intra_priority_value) {
455 DCHECK(ContainsKey(pending_requests_, request_id));
456 message_sender_->Send(new ResourceHostMsg_DidChangePriority(
457 request_id, new_priority, intra_priority_value));
460 bool ResourceDispatcher::AttachThreadedDataReceiver(
461 int request_id, blink::WebThreadedDataReceiver* threaded_data_receiver) {
462 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
463 DCHECK(request_info);
465 if (request_info->buffer != NULL) {
466 DCHECK(!request_info->threaded_data_provider);
467 request_info->threaded_data_provider = new ThreadedDataProvider(
468 request_id, threaded_data_receiver, request_info->buffer,
469 request_info->buffer_size, main_thread_task_runner_);
470 return true;
473 return false;
476 ResourceDispatcher::PendingRequestInfo::PendingRequestInfo()
477 : peer(NULL),
478 threaded_data_provider(NULL),
479 resource_type(RESOURCE_TYPE_SUB_RESOURCE),
480 is_deferred(false),
481 download_to_file(false),
482 buffer_size(0) {
485 ResourceDispatcher::PendingRequestInfo::PendingRequestInfo(
486 RequestPeer* peer,
487 ResourceType resource_type,
488 int origin_pid,
489 const GURL& frame_origin,
490 const GURL& request_url,
491 bool download_to_file)
492 : peer(peer),
493 threaded_data_provider(NULL),
494 resource_type(resource_type),
495 origin_pid(origin_pid),
496 is_deferred(false),
497 url(request_url),
498 frame_origin(frame_origin),
499 response_url(request_url),
500 download_to_file(download_to_file),
501 request_start(base::TimeTicks::Now()) {
504 ResourceDispatcher::PendingRequestInfo::~PendingRequestInfo() {
505 if (threaded_data_provider)
506 threaded_data_provider->Stop();
509 void ResourceDispatcher::DispatchMessage(const IPC::Message& message) {
510 IPC_BEGIN_MESSAGE_MAP(ResourceDispatcher, message)
511 IPC_MESSAGE_HANDLER(ResourceMsg_UploadProgress, OnUploadProgress)
512 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedResponse, OnReceivedResponse)
513 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedCachedMetadata,
514 OnReceivedCachedMetadata)
515 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedRedirect, OnReceivedRedirect)
516 IPC_MESSAGE_HANDLER(ResourceMsg_SetDataBuffer, OnSetDataBuffer)
517 IPC_MESSAGE_HANDLER(ResourceMsg_DataReceived, OnReceivedData)
518 IPC_MESSAGE_HANDLER(ResourceMsg_DataDownloaded, OnDownloadedData)
519 IPC_MESSAGE_HANDLER(ResourceMsg_RequestComplete, OnRequestComplete)
520 IPC_END_MESSAGE_MAP()
523 void ResourceDispatcher::FlushDeferredMessages(int request_id) {
524 PendingRequestList::iterator it = pending_requests_.find(request_id);
525 if (it == pending_requests_.end()) // The request could have become invalid.
526 return;
527 PendingRequestInfo& request_info = it->second;
528 if (request_info.is_deferred)
529 return;
530 // Because message handlers could result in request_info being destroyed,
531 // we need to work with a stack reference to the deferred queue.
532 MessageQueue q;
533 q.swap(request_info.deferred_message_queue);
534 while (!q.empty()) {
535 IPC::Message* m = q.front();
536 q.pop_front();
537 DispatchMessage(*m);
538 delete m;
539 // If this request is deferred in the context of the above message, then
540 // we should honor the same and stop dispatching further messages.
541 // We need to find the request again in the list as it may have completed
542 // by now and the request_info instance above may be invalid.
543 PendingRequestList::iterator index = pending_requests_.find(request_id);
544 if (index != pending_requests_.end()) {
545 PendingRequestInfo& pending_request = index->second;
546 if (pending_request.is_deferred) {
547 pending_request.deferred_message_queue.swap(q);
548 return;
554 void ResourceDispatcher::StartSync(const RequestInfo& request_info,
555 ResourceRequestBody* request_body,
556 SyncLoadResponse* response) {
557 scoped_ptr<ResourceHostMsg_Request> request =
558 CreateRequest(request_info, request_body, NULL);
560 SyncLoadResult result;
561 IPC::SyncMessage* msg = new ResourceHostMsg_SyncLoad(
562 request_info.routing_id, MakeRequestID(), *request, &result);
564 // NOTE: This may pump events (see RenderThread::Send).
565 if (!message_sender_->Send(msg)) {
566 response->error_code = net::ERR_FAILED;
567 return;
570 response->error_code = result.error_code;
571 response->url = result.final_url;
572 response->headers = result.headers;
573 response->mime_type = result.mime_type;
574 response->charset = result.charset;
575 response->request_time = result.request_time;
576 response->response_time = result.response_time;
577 response->encoded_data_length = result.encoded_data_length;
578 response->load_timing = result.load_timing;
579 response->devtools_info = result.devtools_info;
580 response->data.swap(result.data);
581 response->download_file_path = result.download_file_path;
584 int ResourceDispatcher::StartAsync(const RequestInfo& request_info,
585 ResourceRequestBody* request_body,
586 RequestPeer* peer) {
587 GURL frame_origin;
588 scoped_ptr<ResourceHostMsg_Request> request =
589 CreateRequest(request_info, request_body, &frame_origin);
591 // Compute a unique request_id for this renderer process.
592 int request_id = MakeRequestID();
593 pending_requests_[request_id] =
594 PendingRequestInfo(peer,
595 request->resource_type,
596 request->origin_pid,
597 frame_origin,
598 request->url,
599 request_info.download_to_file);
601 message_sender_->Send(new ResourceHostMsg_RequestResource(
602 request_info.routing_id, request_id, *request));
604 return request_id;
607 void ResourceDispatcher::ToResourceResponseInfo(
608 const PendingRequestInfo& request_info,
609 const ResourceResponseHead& browser_info,
610 ResourceResponseInfo* renderer_info) const {
611 *renderer_info = browser_info;
612 if (request_info.request_start.is_null() ||
613 request_info.response_start.is_null() ||
614 browser_info.request_start.is_null() ||
615 browser_info.response_start.is_null() ||
616 browser_info.load_timing.request_start.is_null()) {
617 return;
619 InterProcessTimeTicksConverter converter(
620 LocalTimeTicks::FromTimeTicks(request_info.request_start),
621 LocalTimeTicks::FromTimeTicks(request_info.response_start),
622 RemoteTimeTicks::FromTimeTicks(browser_info.request_start),
623 RemoteTimeTicks::FromTimeTicks(browser_info.response_start));
625 net::LoadTimingInfo* load_timing = &renderer_info->load_timing;
626 RemoteToLocalTimeTicks(converter, &load_timing->request_start);
627 RemoteToLocalTimeTicks(converter, &load_timing->proxy_resolve_start);
628 RemoteToLocalTimeTicks(converter, &load_timing->proxy_resolve_end);
629 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.dns_start);
630 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.dns_end);
631 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.connect_start);
632 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.connect_end);
633 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.ssl_start);
634 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.ssl_end);
635 RemoteToLocalTimeTicks(converter, &load_timing->send_start);
636 RemoteToLocalTimeTicks(converter, &load_timing->send_end);
637 RemoteToLocalTimeTicks(converter, &load_timing->receive_headers_end);
638 RemoteToLocalTimeTicks(converter, &renderer_info->service_worker_start_time);
639 RemoteToLocalTimeTicks(converter, &renderer_info->service_worker_ready_time);
641 // Collect UMA on the inter-process skew.
642 bool is_skew_additive = false;
643 if (converter.IsSkewAdditiveForMetrics()) {
644 is_skew_additive = true;
645 base::TimeDelta skew = converter.GetSkewForMetrics();
646 if (skew >= base::TimeDelta()) {
647 UMA_HISTOGRAM_TIMES(
648 "InterProcessTimeTicks.BrowserAhead_BrowserToRenderer", skew);
649 } else {
650 UMA_HISTOGRAM_TIMES(
651 "InterProcessTimeTicks.BrowserBehind_BrowserToRenderer", -skew);
654 UMA_HISTOGRAM_BOOLEAN(
655 "InterProcessTimeTicks.IsSkewAdditive_BrowserToRenderer",
656 is_skew_additive);
659 base::TimeTicks ResourceDispatcher::ToRendererCompletionTime(
660 const PendingRequestInfo& request_info,
661 const base::TimeTicks& browser_completion_time) const {
662 if (request_info.completion_time.is_null()) {
663 return browser_completion_time;
666 // TODO(simonjam): The optimal lower bound should be the most recent value of
667 // TimeTicks::Now() returned to WebKit. Is it worth trying to cache that?
668 // Until then, |response_start| is used as it is the most recent value
669 // returned for this request.
670 int64 result = std::max(browser_completion_time.ToInternalValue(),
671 request_info.response_start.ToInternalValue());
672 result = std::min(result, request_info.completion_time.ToInternalValue());
673 return base::TimeTicks::FromInternalValue(result);
676 base::TimeTicks ResourceDispatcher::ConsumeIOTimestamp() {
677 if (io_timestamp_ == base::TimeTicks())
678 return base::TimeTicks::Now();
679 base::TimeTicks result = io_timestamp_;
680 io_timestamp_ = base::TimeTicks();
681 return result;
684 // static
685 bool ResourceDispatcher::IsResourceDispatcherMessage(
686 const IPC::Message& message) {
687 switch (message.type()) {
688 case ResourceMsg_UploadProgress::ID:
689 case ResourceMsg_ReceivedResponse::ID:
690 case ResourceMsg_ReceivedCachedMetadata::ID:
691 case ResourceMsg_ReceivedRedirect::ID:
692 case ResourceMsg_SetDataBuffer::ID:
693 case ResourceMsg_DataReceived::ID:
694 case ResourceMsg_DataDownloaded::ID:
695 case ResourceMsg_RequestComplete::ID:
696 return true;
698 default:
699 break;
702 return false;
705 // static
706 void ResourceDispatcher::ReleaseResourcesInDataMessage(
707 const IPC::Message& message) {
708 base::PickleIterator iter(message);
709 int request_id;
710 if (!iter.ReadInt(&request_id)) {
711 NOTREACHED() << "malformed resource message";
712 return;
715 // If the message contains a shared memory handle, we should close the handle
716 // or there will be a memory leak.
717 if (message.type() == ResourceMsg_SetDataBuffer::ID) {
718 base::SharedMemoryHandle shm_handle;
719 if (IPC::ParamTraits<base::SharedMemoryHandle>::Read(&message,
720 &iter,
721 &shm_handle)) {
722 if (base::SharedMemory::IsHandleValid(shm_handle))
723 base::SharedMemory::CloseHandle(shm_handle);
728 // static
729 void ResourceDispatcher::ReleaseResourcesInMessageQueue(MessageQueue* queue) {
730 while (!queue->empty()) {
731 IPC::Message* message = queue->front();
732 ReleaseResourcesInDataMessage(*message);
733 queue->pop_front();
734 delete message;
738 scoped_ptr<ResourceHostMsg_Request> ResourceDispatcher::CreateRequest(
739 const RequestInfo& request_info,
740 ResourceRequestBody* request_body,
741 GURL* frame_origin) {
742 scoped_ptr<ResourceHostMsg_Request> request(new ResourceHostMsg_Request);
743 request->method = request_info.method;
744 request->url = request_info.url;
745 request->first_party_for_cookies = request_info.first_party_for_cookies;
746 request->referrer = request_info.referrer.url;
747 request->referrer_policy = request_info.referrer.policy;
748 request->headers = request_info.headers;
749 request->load_flags = request_info.load_flags;
750 request->origin_pid = request_info.requestor_pid;
751 request->resource_type = request_info.request_type;
752 request->priority = request_info.priority;
753 request->request_context = request_info.request_context;
754 request->appcache_host_id = request_info.appcache_host_id;
755 request->download_to_file = request_info.download_to_file;
756 request->has_user_gesture = request_info.has_user_gesture;
757 request->skip_service_worker = request_info.skip_service_worker;
758 request->should_reset_appcache = request_info.should_reset_appcache;
759 request->fetch_request_mode = request_info.fetch_request_mode;
760 request->fetch_credentials_mode = request_info.fetch_credentials_mode;
761 request->fetch_redirect_mode = request_info.fetch_redirect_mode;
762 request->fetch_request_context_type = request_info.fetch_request_context_type;
763 request->fetch_frame_type = request_info.fetch_frame_type;
764 request->enable_load_timing = request_info.enable_load_timing;
765 request->enable_upload_progress = request_info.enable_upload_progress;
766 request->do_not_prompt_for_login = request_info.do_not_prompt_for_login;
767 request->report_raw_headers = request_info.report_raw_headers;
769 if ((request_info.referrer.policy == blink::WebReferrerPolicyDefault ||
770 request_info.referrer.policy ==
771 blink::WebReferrerPolicyNoReferrerWhenDowngrade) &&
772 request_info.referrer.url.SchemeIsCryptographic() &&
773 !request_info.url.SchemeIsCryptographic()) {
774 LOG(FATAL) << "Trying to send secure referrer for insecure request "
775 << "without an appropriate referrer policy.\n"
776 << "URL = " << request_info.url << "\n"
777 << "Referrer = " << request_info.referrer.url;
780 const RequestExtraData kEmptyData;
781 const RequestExtraData* extra_data;
782 if (request_info.extra_data)
783 extra_data = static_cast<RequestExtraData*>(request_info.extra_data);
784 else
785 extra_data = &kEmptyData;
786 request->visiblity_state = extra_data->visibility_state();
787 request->render_frame_id = extra_data->render_frame_id();
788 request->is_main_frame = extra_data->is_main_frame();
789 request->parent_is_main_frame = extra_data->parent_is_main_frame();
790 request->parent_render_frame_id = extra_data->parent_render_frame_id();
791 request->allow_download = extra_data->allow_download();
792 request->transition_type = extra_data->transition_type();
793 request->should_replace_current_entry =
794 extra_data->should_replace_current_entry();
795 request->transferred_request_child_id =
796 extra_data->transferred_request_child_id();
797 request->transferred_request_request_id =
798 extra_data->transferred_request_request_id();
799 request->service_worker_provider_id =
800 extra_data->service_worker_provider_id();
801 request->request_body = request_body;
802 if (frame_origin)
803 *frame_origin = extra_data->frame_origin();
804 return request.Pass();
807 } // namespace content