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