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