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