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