Switch from using codec ids to codec name hashes.
[chromium-blink-merge.git] / content / child / resource_dispatcher.cc
blobaeb1cbebc66081a825d767c136866c04d3bbe4fd
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 if (!IsResourceDispatcherMessage(message)) {
84 return false;
87 int request_id;
89 base::PickleIterator iter(message);
90 if (!iter.ReadInt(&request_id)) {
91 NOTREACHED() << "malformed resource message";
92 return true;
95 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
96 if (!request_info) {
97 // Release resources in the message if it is a data message.
98 ReleaseResourcesInDataMessage(message);
99 return true;
102 if (request_info->is_deferred) {
103 request_info->deferred_message_queue.push_back(new IPC::Message(message));
104 return true;
106 // Make sure any deferred messages are dispatched before we dispatch more.
107 if (!request_info->deferred_message_queue.empty()) {
108 FlushDeferredMessages(request_id);
109 request_info = GetPendingRequestInfo(request_id);
110 DCHECK(request_info);
111 if (request_info->is_deferred) {
112 request_info->deferred_message_queue.push_back(new IPC::Message(message));
113 return true;
117 DispatchMessage(message);
118 return true;
121 ResourceDispatcher::PendingRequestInfo*
122 ResourceDispatcher::GetPendingRequestInfo(int request_id) {
123 PendingRequestList::iterator it = pending_requests_.find(request_id);
124 if (it == pending_requests_.end()) {
125 // This might happen for kill()ed requests on the webkit end.
126 return NULL;
128 return &(it->second);
131 void ResourceDispatcher::OnUploadProgress(int request_id, int64 position,
132 int64 size) {
133 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
134 if (!request_info)
135 return;
137 request_info->peer->OnUploadProgress(position, size);
139 // Acknowledge receipt
140 message_sender_->Send(new ResourceHostMsg_UploadProgress_ACK(request_id));
143 void ResourceDispatcher::OnReceivedResponse(
144 int request_id, const ResourceResponseHead& response_head) {
145 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedResponse");
146 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
147 if (!request_info)
148 return;
149 request_info->response_start = ConsumeIOTimestamp();
151 if (delegate_) {
152 RequestPeer* new_peer =
153 delegate_->OnReceivedResponse(
154 request_info->peer, response_head.mime_type, request_info->url);
155 if (new_peer)
156 request_info->peer = new_peer;
159 ResourceResponseInfo renderer_response_info;
160 ToResourceResponseInfo(*request_info, response_head, &renderer_response_info);
161 request_info->site_isolation_metadata =
162 SiteIsolationStatsGatherer::OnReceivedResponse(
163 request_info->frame_origin, request_info->response_url,
164 request_info->resource_type, request_info->origin_pid,
165 renderer_response_info);
166 request_info->peer->OnReceivedResponse(renderer_response_info);
169 void ResourceDispatcher::OnReceivedCachedMetadata(
170 int request_id, const std::vector<char>& data) {
171 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
172 if (!request_info)
173 return;
175 if (data.size())
176 request_info->peer->OnReceivedCachedMetadata(&data.front(), data.size());
179 void ResourceDispatcher::OnSetDataBuffer(int request_id,
180 base::SharedMemoryHandle shm_handle,
181 int shm_size,
182 base::ProcessId renderer_pid) {
183 TRACE_EVENT0("loader", "ResourceDispatcher::OnSetDataBuffer");
184 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
185 if (!request_info)
186 return;
188 bool shm_valid = base::SharedMemory::IsHandleValid(shm_handle);
189 CHECK((shm_valid && shm_size > 0) || (!shm_valid && !shm_size));
191 request_info->buffer.reset(
192 new base::SharedMemory(shm_handle, true)); // read only
193 request_info->received_data_factory =
194 make_scoped_refptr(new SharedMemoryReceivedDataFactory(
195 message_sender_, request_id, request_info->buffer));
197 bool ok = request_info->buffer->Map(shm_size);
198 if (!ok) {
199 // Added to help debug crbug/160401.
200 base::ProcessId renderer_pid_copy = renderer_pid;
201 base::debug::Alias(&renderer_pid_copy);
203 base::SharedMemoryHandle shm_handle_copy = shm_handle;
204 base::debug::Alias(&shm_handle_copy);
206 CrashOnMapFailure();
207 return;
210 request_info->buffer_size = shm_size;
213 void ResourceDispatcher::OnReceivedData(int request_id,
214 int data_offset,
215 int data_length,
216 int encoded_data_length) {
217 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedData");
218 DCHECK_GT(data_length, 0);
219 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
220 bool send_ack = true;
221 if (request_info && data_length > 0) {
222 CHECK(base::SharedMemory::IsHandleValid(request_info->buffer->handle()));
223 CHECK_GE(request_info->buffer_size, data_offset + data_length);
225 // Ensure that the SHM buffer remains valid for the duration of this scope.
226 // It is possible for Cancel() to be called before we exit this scope.
227 // SharedMemoryReceivedDataFactory stores the SHM buffer inside it.
228 scoped_refptr<SharedMemoryReceivedDataFactory> factory(
229 request_info->received_data_factory);
231 base::TimeTicks time_start = base::TimeTicks::Now();
233 const char* data_start = static_cast<char*>(request_info->buffer->memory());
234 CHECK(data_start);
235 CHECK(data_start + data_offset);
236 const char* data_ptr = data_start + data_offset;
238 // Check whether this response data is compliant with our cross-site
239 // document blocking policy. We only do this for the first chunk of data.
240 if (request_info->site_isolation_metadata.get()) {
241 SiteIsolationStatsGatherer::OnReceivedFirstChunk(
242 request_info->site_isolation_metadata, data_ptr, data_length);
243 request_info->site_isolation_metadata.reset();
246 if (request_info->threaded_data_provider) {
247 // A threaded data provider will take care of its own ACKing, as the data
248 // may be processed later on another thread.
249 send_ack = false;
250 request_info->threaded_data_provider->OnReceivedDataOnForegroundThread(
251 data_ptr, data_length, encoded_data_length);
252 } else {
253 scoped_ptr<RequestPeer::ReceivedData> data =
254 factory->Create(data_offset, data_length, encoded_data_length);
255 // |data| takes care of ACKing.
256 send_ack = false;
257 request_info->peer->OnReceivedData(data.Pass());
260 UMA_HISTOGRAM_TIMES("ResourceDispatcher.OnReceivedDataTime",
261 base::TimeTicks::Now() - time_start);
264 // Acknowledge the reception of this data.
265 if (send_ack)
266 message_sender_->Send(new ResourceHostMsg_DataReceived_ACK(request_id));
269 void ResourceDispatcher::OnDownloadedData(int request_id,
270 int data_len,
271 int encoded_data_length) {
272 // Acknowledge the reception of this message.
273 message_sender_->Send(new ResourceHostMsg_DataDownloaded_ACK(request_id));
275 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
276 if (!request_info)
277 return;
279 request_info->peer->OnDownloadedData(data_len, encoded_data_length);
282 void ResourceDispatcher::OnReceivedRedirect(
283 int request_id,
284 const net::RedirectInfo& redirect_info,
285 const ResourceResponseHead& response_head) {
286 TRACE_EVENT0("loader", "ResourceDispatcher::OnReceivedRedirect");
287 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
288 if (!request_info)
289 return;
290 request_info->response_start = ConsumeIOTimestamp();
292 ResourceResponseInfo renderer_response_info;
293 ToResourceResponseInfo(*request_info, response_head, &renderer_response_info);
294 if (request_info->peer->OnReceivedRedirect(redirect_info,
295 renderer_response_info)) {
296 // Double-check if the request is still around. The call above could
297 // potentially remove it.
298 request_info = GetPendingRequestInfo(request_id);
299 if (!request_info)
300 return;
301 // We update the response_url here so that we can send it to
302 // SiteIsolationStatsGatherer later when OnReceivedResponse is called.
303 request_info->response_url = redirect_info.new_url;
304 request_info->pending_redirect_message.reset(
305 new ResourceHostMsg_FollowRedirect(request_id));
306 if (!request_info->is_deferred) {
307 FollowPendingRedirect(request_id, *request_info);
309 } else {
310 Cancel(request_id);
314 void ResourceDispatcher::FollowPendingRedirect(
315 int request_id,
316 PendingRequestInfo& request_info) {
317 IPC::Message* msg = request_info.pending_redirect_message.release();
318 if (msg)
319 message_sender_->Send(msg);
322 void ResourceDispatcher::OnRequestComplete(
323 int request_id,
324 const ResourceMsg_RequestCompleteData& request_complete_data) {
325 TRACE_EVENT0("loader", "ResourceDispatcher::OnRequestComplete");
327 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
328 if (!request_info)
329 return;
330 request_info->completion_time = ConsumeIOTimestamp();
331 request_info->buffer.reset();
332 if (request_info->received_data_factory)
333 request_info->received_data_factory->Stop();
334 request_info->received_data_factory = nullptr;
335 request_info->buffer_size = 0;
337 RequestPeer* peer = request_info->peer;
339 if (delegate_) {
340 RequestPeer* new_peer =
341 delegate_->OnRequestComplete(
342 request_info->peer, request_info->resource_type,
343 request_complete_data.error_code);
344 if (new_peer)
345 request_info->peer = new_peer;
348 base::TimeTicks renderer_completion_time = ToRendererCompletionTime(
349 *request_info, request_complete_data.completion_time);
351 // If we have a threaded data provider, this message needs to bounce off the
352 // background thread before it's returned to this thread and handled,
353 // to make sure it's processed after all incoming data.
354 if (request_info->threaded_data_provider) {
355 request_info->threaded_data_provider->OnRequestCompleteForegroundThread(
356 weak_factory_.GetWeakPtr(), request_complete_data,
357 renderer_completion_time);
358 return;
361 // The request ID will be removed from our pending list in the destructor.
362 // Normally, dispatching this message causes the reference-counted request to
363 // die immediately.
364 peer->OnCompletedRequest(request_complete_data.error_code,
365 request_complete_data.was_ignored_by_handler,
366 request_complete_data.exists_in_cache,
367 request_complete_data.security_info,
368 renderer_completion_time,
369 request_complete_data.encoded_data_length);
372 void ResourceDispatcher::CompletedRequestAfterBackgroundThreadFlush(
373 int request_id,
374 const ResourceMsg_RequestCompleteData& request_complete_data,
375 const base::TimeTicks& renderer_completion_time) {
376 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
377 if (!request_info)
378 return;
380 RequestPeer* peer = request_info->peer;
381 peer->OnCompletedRequest(request_complete_data.error_code,
382 request_complete_data.was_ignored_by_handler,
383 request_complete_data.exists_in_cache,
384 request_complete_data.security_info,
385 renderer_completion_time,
386 request_complete_data.encoded_data_length);
389 bool ResourceDispatcher::RemovePendingRequest(int request_id) {
390 PendingRequestList::iterator it = pending_requests_.find(request_id);
391 if (it == pending_requests_.end())
392 return false;
394 PendingRequestInfo& request_info = it->second;
396 bool release_downloaded_file = request_info.download_to_file;
398 ReleaseResourcesInMessageQueue(&request_info.deferred_message_queue);
399 pending_requests_.erase(it);
401 if (release_downloaded_file) {
402 message_sender_->Send(
403 new ResourceHostMsg_ReleaseDownloadedFile(request_id));
406 return true;
409 void ResourceDispatcher::Cancel(int request_id) {
410 PendingRequestList::iterator it = pending_requests_.find(request_id);
411 if (it == pending_requests_.end()) {
412 DVLOG(1) << "unknown request";
413 return;
416 // Cancel the request, and clean it up so the bridge will receive no more
417 // messages.
418 message_sender_->Send(new ResourceHostMsg_CancelRequest(request_id));
419 RemovePendingRequest(request_id);
422 void ResourceDispatcher::SetDefersLoading(int request_id, bool value) {
423 PendingRequestList::iterator it = pending_requests_.find(request_id);
424 if (it == pending_requests_.end()) {
425 DLOG(ERROR) << "unknown request";
426 return;
428 PendingRequestInfo& request_info = it->second;
429 if (value) {
430 request_info.is_deferred = value;
431 } else if (request_info.is_deferred) {
432 request_info.is_deferred = false;
434 FollowPendingRedirect(request_id, request_info);
436 main_thread_task_runner_->PostTask(
437 FROM_HERE, base::Bind(&ResourceDispatcher::FlushDeferredMessages,
438 weak_factory_.GetWeakPtr(), request_id));
442 void ResourceDispatcher::DidChangePriority(int request_id,
443 net::RequestPriority new_priority,
444 int intra_priority_value) {
445 DCHECK(ContainsKey(pending_requests_, request_id));
446 message_sender_->Send(new ResourceHostMsg_DidChangePriority(
447 request_id, new_priority, intra_priority_value));
450 bool ResourceDispatcher::AttachThreadedDataReceiver(
451 int request_id, blink::WebThreadedDataReceiver* threaded_data_receiver) {
452 PendingRequestInfo* request_info = GetPendingRequestInfo(request_id);
453 DCHECK(request_info);
455 if (request_info->buffer != NULL) {
456 DCHECK(!request_info->threaded_data_provider);
457 request_info->threaded_data_provider = new ThreadedDataProvider(
458 request_id, threaded_data_receiver, request_info->buffer,
459 request_info->buffer_size, main_thread_task_runner_);
460 return true;
463 return false;
466 ResourceDispatcher::PendingRequestInfo::PendingRequestInfo()
467 : peer(NULL),
468 threaded_data_provider(NULL),
469 resource_type(RESOURCE_TYPE_SUB_RESOURCE),
470 is_deferred(false),
471 download_to_file(false),
472 buffer_size(0) {
475 ResourceDispatcher::PendingRequestInfo::PendingRequestInfo(
476 RequestPeer* peer,
477 ResourceType resource_type,
478 int origin_pid,
479 const GURL& frame_origin,
480 const GURL& request_url,
481 bool download_to_file)
482 : peer(peer),
483 threaded_data_provider(NULL),
484 resource_type(resource_type),
485 origin_pid(origin_pid),
486 is_deferred(false),
487 url(request_url),
488 frame_origin(frame_origin),
489 response_url(request_url),
490 download_to_file(download_to_file),
491 request_start(base::TimeTicks::Now()) {
494 ResourceDispatcher::PendingRequestInfo::~PendingRequestInfo() {
495 if (threaded_data_provider)
496 threaded_data_provider->Stop();
499 void ResourceDispatcher::DispatchMessage(const IPC::Message& message) {
500 IPC_BEGIN_MESSAGE_MAP(ResourceDispatcher, message)
501 IPC_MESSAGE_HANDLER(ResourceMsg_UploadProgress, OnUploadProgress)
502 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedResponse, OnReceivedResponse)
503 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedCachedMetadata,
504 OnReceivedCachedMetadata)
505 IPC_MESSAGE_HANDLER(ResourceMsg_ReceivedRedirect, OnReceivedRedirect)
506 IPC_MESSAGE_HANDLER(ResourceMsg_SetDataBuffer, OnSetDataBuffer)
507 IPC_MESSAGE_HANDLER(ResourceMsg_DataReceived, OnReceivedData)
508 IPC_MESSAGE_HANDLER(ResourceMsg_DataDownloaded, OnDownloadedData)
509 IPC_MESSAGE_HANDLER(ResourceMsg_RequestComplete, OnRequestComplete)
510 IPC_END_MESSAGE_MAP()
513 void ResourceDispatcher::FlushDeferredMessages(int request_id) {
514 PendingRequestList::iterator it = pending_requests_.find(request_id);
515 if (it == pending_requests_.end()) // The request could have become invalid.
516 return;
517 PendingRequestInfo& request_info = it->second;
518 if (request_info.is_deferred)
519 return;
520 // Because message handlers could result in request_info being destroyed,
521 // we need to work with a stack reference to the deferred queue.
522 MessageQueue q;
523 q.swap(request_info.deferred_message_queue);
524 while (!q.empty()) {
525 IPC::Message* m = q.front();
526 q.pop_front();
527 DispatchMessage(*m);
528 delete m;
529 // If this request is deferred in the context of the above message, then
530 // we should honor the same and stop dispatching further messages.
531 // We need to find the request again in the list as it may have completed
532 // by now and the request_info instance above may be invalid.
533 PendingRequestList::iterator index = pending_requests_.find(request_id);
534 if (index != pending_requests_.end()) {
535 PendingRequestInfo& pending_request = index->second;
536 if (pending_request.is_deferred) {
537 pending_request.deferred_message_queue.swap(q);
538 return;
544 void ResourceDispatcher::StartSync(const RequestInfo& request_info,
545 ResourceRequestBody* request_body,
546 SyncLoadResponse* response) {
547 scoped_ptr<ResourceHostMsg_Request> request =
548 CreateRequest(request_info, request_body, NULL);
550 SyncLoadResult result;
551 IPC::SyncMessage* msg = new ResourceHostMsg_SyncLoad(
552 request_info.routing_id, MakeRequestID(), *request, &result);
554 // NOTE: This may pump events (see RenderThread::Send).
555 if (!message_sender_->Send(msg)) {
556 response->error_code = net::ERR_FAILED;
557 return;
560 response->error_code = result.error_code;
561 response->url = result.final_url;
562 response->headers = result.headers;
563 response->mime_type = result.mime_type;
564 response->charset = result.charset;
565 response->request_time = result.request_time;
566 response->response_time = result.response_time;
567 response->encoded_data_length = result.encoded_data_length;
568 response->load_timing = result.load_timing;
569 response->devtools_info = result.devtools_info;
570 response->data.swap(result.data);
571 response->download_file_path = result.download_file_path;
574 int ResourceDispatcher::StartAsync(const RequestInfo& request_info,
575 ResourceRequestBody* request_body,
576 RequestPeer* peer) {
577 GURL frame_origin;
578 scoped_ptr<ResourceHostMsg_Request> request =
579 CreateRequest(request_info, request_body, &frame_origin);
581 // Compute a unique request_id for this renderer process.
582 int request_id = MakeRequestID();
583 pending_requests_[request_id] =
584 PendingRequestInfo(peer,
585 request->resource_type,
586 request->origin_pid,
587 frame_origin,
588 request->url,
589 request_info.download_to_file);
591 message_sender_->Send(new ResourceHostMsg_RequestResource(
592 request_info.routing_id, request_id, *request));
594 return request_id;
597 void ResourceDispatcher::ToResourceResponseInfo(
598 const PendingRequestInfo& request_info,
599 const ResourceResponseHead& browser_info,
600 ResourceResponseInfo* renderer_info) const {
601 *renderer_info = browser_info;
602 if (request_info.request_start.is_null() ||
603 request_info.response_start.is_null() ||
604 browser_info.request_start.is_null() ||
605 browser_info.response_start.is_null() ||
606 browser_info.load_timing.request_start.is_null()) {
607 return;
609 InterProcessTimeTicksConverter converter(
610 LocalTimeTicks::FromTimeTicks(request_info.request_start),
611 LocalTimeTicks::FromTimeTicks(request_info.response_start),
612 RemoteTimeTicks::FromTimeTicks(browser_info.request_start),
613 RemoteTimeTicks::FromTimeTicks(browser_info.response_start));
615 net::LoadTimingInfo* load_timing = &renderer_info->load_timing;
616 RemoteToLocalTimeTicks(converter, &load_timing->request_start);
617 RemoteToLocalTimeTicks(converter, &load_timing->proxy_resolve_start);
618 RemoteToLocalTimeTicks(converter, &load_timing->proxy_resolve_end);
619 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.dns_start);
620 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.dns_end);
621 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.connect_start);
622 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.connect_end);
623 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.ssl_start);
624 RemoteToLocalTimeTicks(converter, &load_timing->connect_timing.ssl_end);
625 RemoteToLocalTimeTicks(converter, &load_timing->send_start);
626 RemoteToLocalTimeTicks(converter, &load_timing->send_end);
627 RemoteToLocalTimeTicks(converter, &load_timing->receive_headers_end);
628 RemoteToLocalTimeTicks(converter, &renderer_info->service_worker_start_time);
629 RemoteToLocalTimeTicks(converter, &renderer_info->service_worker_ready_time);
631 // Collect UMA on the inter-process skew.
632 bool is_skew_additive = false;
633 if (converter.IsSkewAdditiveForMetrics()) {
634 is_skew_additive = true;
635 base::TimeDelta skew = converter.GetSkewForMetrics();
636 if (skew >= base::TimeDelta()) {
637 UMA_HISTOGRAM_TIMES(
638 "InterProcessTimeTicks.BrowserAhead_BrowserToRenderer", skew);
639 } else {
640 UMA_HISTOGRAM_TIMES(
641 "InterProcessTimeTicks.BrowserBehind_BrowserToRenderer", -skew);
644 UMA_HISTOGRAM_BOOLEAN(
645 "InterProcessTimeTicks.IsSkewAdditive_BrowserToRenderer",
646 is_skew_additive);
649 base::TimeTicks ResourceDispatcher::ToRendererCompletionTime(
650 const PendingRequestInfo& request_info,
651 const base::TimeTicks& browser_completion_time) const {
652 if (request_info.completion_time.is_null()) {
653 return browser_completion_time;
656 // TODO(simonjam): The optimal lower bound should be the most recent value of
657 // TimeTicks::Now() returned to WebKit. Is it worth trying to cache that?
658 // Until then, |response_start| is used as it is the most recent value
659 // returned for this request.
660 int64 result = std::max(browser_completion_time.ToInternalValue(),
661 request_info.response_start.ToInternalValue());
662 result = std::min(result, request_info.completion_time.ToInternalValue());
663 return base::TimeTicks::FromInternalValue(result);
666 base::TimeTicks ResourceDispatcher::ConsumeIOTimestamp() {
667 if (io_timestamp_ == base::TimeTicks())
668 return base::TimeTicks::Now();
669 base::TimeTicks result = io_timestamp_;
670 io_timestamp_ = base::TimeTicks();
671 return result;
674 // static
675 bool ResourceDispatcher::IsResourceDispatcherMessage(
676 const IPC::Message& message) {
677 switch (message.type()) {
678 case ResourceMsg_UploadProgress::ID:
679 case ResourceMsg_ReceivedResponse::ID:
680 case ResourceMsg_ReceivedCachedMetadata::ID:
681 case ResourceMsg_ReceivedRedirect::ID:
682 case ResourceMsg_SetDataBuffer::ID:
683 case ResourceMsg_DataReceived::ID:
684 case ResourceMsg_DataDownloaded::ID:
685 case ResourceMsg_RequestComplete::ID:
686 return true;
688 default:
689 break;
692 return false;
695 // static
696 void ResourceDispatcher::ReleaseResourcesInDataMessage(
697 const IPC::Message& message) {
698 base::PickleIterator iter(message);
699 int request_id;
700 if (!iter.ReadInt(&request_id)) {
701 NOTREACHED() << "malformed resource message";
702 return;
705 // If the message contains a shared memory handle, we should close the handle
706 // or there will be a memory leak.
707 if (message.type() == ResourceMsg_SetDataBuffer::ID) {
708 base::SharedMemoryHandle shm_handle;
709 if (IPC::ParamTraits<base::SharedMemoryHandle>::Read(&message,
710 &iter,
711 &shm_handle)) {
712 if (base::SharedMemory::IsHandleValid(shm_handle))
713 base::SharedMemory::CloseHandle(shm_handle);
718 // static
719 void ResourceDispatcher::ReleaseResourcesInMessageQueue(MessageQueue* queue) {
720 while (!queue->empty()) {
721 IPC::Message* message = queue->front();
722 ReleaseResourcesInDataMessage(*message);
723 queue->pop_front();
724 delete message;
728 scoped_ptr<ResourceHostMsg_Request> ResourceDispatcher::CreateRequest(
729 const RequestInfo& request_info,
730 ResourceRequestBody* request_body,
731 GURL* frame_origin) {
732 scoped_ptr<ResourceHostMsg_Request> request(new ResourceHostMsg_Request);
733 request->method = request_info.method;
734 request->url = request_info.url;
735 request->first_party_for_cookies = request_info.first_party_for_cookies;
736 request->referrer = request_info.referrer.url;
737 request->referrer_policy = request_info.referrer.policy;
738 request->headers = request_info.headers;
739 request->load_flags = request_info.load_flags;
740 request->origin_pid = request_info.requestor_pid;
741 request->resource_type = request_info.request_type;
742 request->priority = request_info.priority;
743 request->request_context = request_info.request_context;
744 request->appcache_host_id = request_info.appcache_host_id;
745 request->download_to_file = request_info.download_to_file;
746 request->has_user_gesture = request_info.has_user_gesture;
747 request->skip_service_worker = request_info.skip_service_worker;
748 request->should_reset_appcache = request_info.should_reset_appcache;
749 request->fetch_request_mode = request_info.fetch_request_mode;
750 request->fetch_credentials_mode = request_info.fetch_credentials_mode;
751 request->fetch_redirect_mode = request_info.fetch_redirect_mode;
752 request->fetch_request_context_type = request_info.fetch_request_context_type;
753 request->fetch_frame_type = request_info.fetch_frame_type;
754 request->enable_load_timing = request_info.enable_load_timing;
755 request->enable_upload_progress = request_info.enable_upload_progress;
756 request->do_not_prompt_for_login = request_info.do_not_prompt_for_login;
757 request->report_raw_headers = request_info.report_raw_headers;
759 if ((request_info.referrer.policy == blink::WebReferrerPolicyDefault ||
760 request_info.referrer.policy ==
761 blink::WebReferrerPolicyNoReferrerWhenDowngrade) &&
762 request_info.referrer.url.SchemeIsCryptographic() &&
763 !request_info.url.SchemeIsCryptographic()) {
764 LOG(FATAL) << "Trying to send secure referrer for insecure request "
765 << "without an appropriate referrer policy.\n"
766 << "URL = " << request_info.url << "\n"
767 << "Referrer = " << request_info.referrer.url;
770 const RequestExtraData kEmptyData;
771 const RequestExtraData* extra_data;
772 if (request_info.extra_data)
773 extra_data = static_cast<RequestExtraData*>(request_info.extra_data);
774 else
775 extra_data = &kEmptyData;
776 request->visiblity_state = extra_data->visibility_state();
777 request->render_frame_id = extra_data->render_frame_id();
778 request->is_main_frame = extra_data->is_main_frame();
779 request->parent_is_main_frame = extra_data->parent_is_main_frame();
780 request->parent_render_frame_id = extra_data->parent_render_frame_id();
781 request->allow_download = extra_data->allow_download();
782 request->transition_type = extra_data->transition_type();
783 request->should_replace_current_entry =
784 extra_data->should_replace_current_entry();
785 request->transferred_request_child_id =
786 extra_data->transferred_request_child_id();
787 request->transferred_request_request_id =
788 extra_data->transferred_request_request_id();
789 request->service_worker_provider_id =
790 extra_data->service_worker_provider_id();
791 request->request_body = request_body;
792 if (frame_origin)
793 *frame_origin = extra_data->frame_origin();
794 return request.Pass();
797 } // namespace content