Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / renderer_host / chrome_resource_dispatcher_host_delegate.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 #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h"
6
7 #include <string>
8 #include <vector>
9
10 #include "base/base64.h"
11 #include "base/guid.h"
12 #include "base/logging.h"
13 #include "chrome/browser/browser_process.h"
14 #include "chrome/browser/chrome_notification_types.h"
15 #include "chrome/browser/component_updater/component_updater_resource_throttle.h"
16 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
17 #include "chrome/browser/content_settings/host_content_settings_map.h"
18 #include "chrome/browser/download/download_request_limiter.h"
19 #include "chrome/browser/download/download_resource_throttle.h"
20 #include "chrome/browser/prefetch/prefetch.h"
21 #include "chrome/browser/prerender/prerender_manager.h"
22 #include "chrome/browser/prerender/prerender_manager_factory.h"
23 #include "chrome/browser/prerender/prerender_pending_swap_throttle.h"
24 #include "chrome/browser/prerender/prerender_resource_throttle.h"
25 #include "chrome/browser/prerender/prerender_tracker.h"
26 #include "chrome/browser/prerender/prerender_util.h"
27 #include "chrome/browser/profiles/profile.h"
28 #include "chrome/browser/profiles/profile_io_data.h"
29 #include "chrome/browser/renderer_host/safe_browsing_resource_throttle_factory.h"
30 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
31 #include "chrome/browser/signin/signin_header_helper.h"
32 #include "chrome/browser/tab_contents/tab_util.h"
33 #include "chrome/browser/ui/login/login_prompt.h"
34 #include "chrome/browser/ui/sync/one_click_signin_helper.h"
35 #include "chrome/common/extensions/extension_constants.h"
36 #include "chrome/common/render_messages.h"
37 #include "chrome/common/url_constants.h"
38 #include "components/google/core/browser/google_util.h"
39 #include "components/variations/variations_http_header_provider.h"
40 #include "content/public/browser/browser_thread.h"
41 #include "content/public/browser/notification_service.h"
42 #include "content/public/browser/render_process_host.h"
43 #include "content/public/browser/render_view_host.h"
44 #include "content/public/browser/resource_context.h"
45 #include "content/public/browser/resource_dispatcher_host.h"
46 #include "content/public/browser/resource_request_info.h"
47 #include "content/public/browser/stream_handle.h"
48 #include "content/public/browser/web_contents.h"
49 #include "content/public/common/resource_response.h"
50 #include "net/base/load_flags.h"
51 #include "net/base/load_timing_info.h"
52 #include "net/base/request_priority.h"
53 #include "net/http/http_response_headers.h"
54 #include "net/url_request/url_request.h"
55
56 #if defined(ENABLE_CONFIGURATION_POLICY)
57 #include "components/policy/core/common/cloud/policy_header_io_helper.h"
58 #endif
59
60 #if defined(ENABLE_EXTENSIONS)
61 #include "chrome/browser/apps/app_url_redirector.h"
62 #include "chrome/browser/apps/ephemeral_app_throttle.h"
63 #include "chrome/browser/extensions/api/streams_private/streams_private_api.h"
64 #include "chrome/browser/extensions/user_script_listener.h"
65 #include "chrome/browser/guest_view/web_view/web_view_renderer_state.h"
66 #include "chrome/common/extensions/manifest_handlers/mime_types_handler.h"
67 #include "extensions/browser/info_map.h"
68 #include "extensions/common/constants.h"
69 #include "extensions/common/user_script.h"
70 #endif
71
72 #if defined(ENABLE_MANAGED_USERS)
73 #include "chrome/browser/supervised_user/supervised_user_resource_throttle.h"
74 #endif
75
76 #if defined(USE_SYSTEM_PROTOBUF)
77 #include <google/protobuf/repeated_field.h>
78 #else
79 #include "third_party/protobuf/src/google/protobuf/repeated_field.h"
80 #endif
81
82 #if defined(OS_ANDROID)
83 #include "chrome/browser/android/intercept_download_resource_throttle.h"
84 #include "chrome/browser/ui/android/infobars/auto_login_prompter.h"
85 #include "components/navigation_interception/intercept_navigation_delegate.h"
86 #endif
87
88 #if defined(OS_CHROMEOS)
89 #include "chrome/browser/chromeos/login/signin/merge_session_throttle.h"
90 // TODO(oshima): Enable this for other platforms.
91 #include "chrome/browser/renderer_host/offline_resource_throttle.h"
92 #endif
93
94 using content::BrowserThread;
95 using content::RenderViewHost;
96 using content::ResourceDispatcherHostLoginDelegate;
97 using content::ResourceRequestInfo;
98 using content::ResourceType;
99
100 #if defined(ENABLE_EXTENSIONS)
101 using extensions::Extension;
102 using extensions::StreamsPrivateAPI;
103 #endif
104
105 #if defined(OS_ANDROID)
106 using navigation_interception::InterceptNavigationDelegate;
107 #endif
108
109 namespace {
110
111 ExternalProtocolHandler::Delegate* g_external_protocol_handler_delegate = NULL;
112
113 void NotifyDownloadInitiatedOnUI(int render_process_id, int render_view_id) {
114   RenderViewHost* rvh = RenderViewHost::FromID(render_process_id,
115                                                render_view_id);
116   if (!rvh)
117     return;
118
119   content::NotificationService::current()->Notify(
120       chrome::NOTIFICATION_DOWNLOAD_INITIATED,
121       content::Source<RenderViewHost>(rvh),
122       content::NotificationService::NoDetails());
123 }
124
125 prerender::PrerenderManager* GetPrerenderManager(int render_process_id,
126                                                  int render_view_id) {
127   DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
128
129   content::WebContents* web_contents =
130       tab_util::GetWebContentsByID(render_process_id, render_view_id);
131   if (!web_contents)
132     return NULL;
133
134   content::BrowserContext* browser_context = web_contents->GetBrowserContext();
135   if (!browser_context)
136     return NULL;
137
138   Profile* profile = Profile::FromBrowserContext(browser_context);
139   if (!profile)
140     return NULL;
141
142   return prerender::PrerenderManagerFactory::GetForProfile(profile);
143 }
144
145 void UpdatePrerenderNetworkBytesCallback(int render_process_id,
146                                          int render_view_id,
147                                          int64 bytes) {
148   DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
149
150   content::WebContents* web_contents =
151       tab_util::GetWebContentsByID(render_process_id, render_view_id);
152   // PrerenderContents::FromWebContents handles the NULL case.
153   prerender::PrerenderContents* prerender_contents =
154       prerender::PrerenderContents::FromWebContents(web_contents);
155
156   if (prerender_contents)
157     prerender_contents->AddNetworkBytes(bytes);
158
159   prerender::PrerenderManager* prerender_manager =
160       GetPrerenderManager(render_process_id, render_view_id);
161   if (prerender_manager)
162     prerender_manager->AddProfileNetworkBytesIfEnabled(bytes);
163 }
164
165 #if defined(ENABLE_EXTENSIONS)
166 void SendExecuteMimeTypeHandlerEvent(scoped_ptr<content::StreamHandle> stream,
167                                      int64 expected_content_size,
168                                      int render_process_id,
169                                      int render_view_id,
170                                      const std::string& extension_id,
171                                      const std::string& view_id) {
172   DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
173
174   content::WebContents* web_contents =
175       tab_util::GetWebContentsByID(render_process_id, render_view_id);
176   if (!web_contents)
177     return;
178
179   // If the request was for a prerender, abort the prerender and do not
180   // continue.
181   prerender::PrerenderContents* prerender_contents =
182       prerender::PrerenderContents::FromWebContents(web_contents);
183   if (prerender_contents) {
184     prerender_contents->Destroy(prerender::FINAL_STATUS_DOWNLOAD);
185     return;
186   }
187
188   Profile* profile =
189       Profile::FromBrowserContext(web_contents->GetBrowserContext());
190
191   StreamsPrivateAPI* streams_private = StreamsPrivateAPI::Get(profile);
192   if (!streams_private)
193     return;
194   streams_private->ExecuteMimeTypeHandler(
195       extension_id, web_contents, stream.Pass(), view_id,
196       expected_content_size);
197 }
198 #endif  // !defined(ENABLE_EXTENSIONS)
199
200 #if !defined(OS_ANDROID)
201 void LaunchURL(const GURL& url, int render_process_id, int render_view_id) {
202   // If there is no longer a WebContents, the request may have raced with tab
203   // closing. Don't fire the external request. (It may have been a prerender.)
204   content::WebContents* web_contents =
205       tab_util::GetWebContentsByID(render_process_id, render_view_id);
206   if (!web_contents)
207     return;
208
209   // Do not launch external requests attached to unswapped prerenders.
210   prerender::PrerenderContents* prerender_contents =
211       prerender::PrerenderContents::FromWebContents(web_contents);
212   if (prerender_contents) {
213     prerender_contents->Destroy(prerender::FINAL_STATUS_UNSUPPORTED_SCHEME);
214     prerender::ReportPrerenderExternalURL();
215     return;
216   }
217
218   ExternalProtocolHandler::LaunchUrlWithDelegate(
219       url,
220       render_process_id,
221       render_view_id,
222       g_external_protocol_handler_delegate);
223 }
224 #endif  // !defined(OS_ANDROID)
225
226 void AppendComponentUpdaterThrottles(
227     net::URLRequest* request,
228     content::ResourceContext* resource_context,
229     ResourceType resource_type,
230     ScopedVector<content::ResourceThrottle>* throttles) {
231   const char* crx_id = NULL;
232   component_updater::ComponentUpdateService* cus =
233       g_browser_process->component_updater();
234   if (!cus)
235     return;
236   // Check for PNaCl pexe request.
237   if (resource_type == content::RESOURCE_TYPE_OBJECT) {
238     const net::HttpRequestHeaders& headers = request->extra_request_headers();
239     std::string accept_headers;
240     if (headers.GetHeader("Accept", &accept_headers)) {
241       if (accept_headers.find("application/x-pnacl") != std::string::npos &&
242           pnacl::NeedsOnDemandUpdate())
243         crx_id = "hnimpnehoodheedghdeeijklkeaacbdc";
244     }
245   }
246
247   if (crx_id) {
248     // We got a component we need to install, so throttle the resource
249     // until the component is installed.
250     throttles->push_back(
251         component_updater::GetOnDemandResourceThrottle(cus, crx_id));
252   }
253 }
254
255 }  // end namespace
256
257 ChromeResourceDispatcherHostDelegate::ChromeResourceDispatcherHostDelegate(
258     prerender::PrerenderTracker* prerender_tracker)
259     : download_request_limiter_(g_browser_process->download_request_limiter()),
260       safe_browsing_(g_browser_process->safe_browsing_service()),
261 #if defined(ENABLE_EXTENSIONS)
262       user_script_listener_(new extensions::UserScriptListener()),
263 #endif
264       prerender_tracker_(prerender_tracker) {
265 }
266
267 ChromeResourceDispatcherHostDelegate::~ChromeResourceDispatcherHostDelegate() {
268 #if defined(ENABLE_EXTENSIONS)
269   CHECK(stream_target_info_.empty());
270 #endif
271 }
272
273 bool ChromeResourceDispatcherHostDelegate::ShouldBeginRequest(
274     int child_id,
275     int route_id,
276     const std::string& method,
277     const GURL& url,
278     ResourceType resource_type,
279     content::ResourceContext* resource_context) {
280   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
281
282   // Handle a PREFETCH resource type. If prefetch is disabled, squelch the
283   // request.  Otherwise, do a normal request to warm the cache.
284   if (resource_type == content::RESOURCE_TYPE_PREFETCH) {
285     // All PREFETCH requests should be GETs, but be defensive about it.
286     if (method != "GET")
287       return false;
288
289     // If prefetch is disabled, kill the request.
290     if (!prefetch::IsPrefetchEnabled(resource_context))
291       return false;
292   }
293
294   return true;
295 }
296
297 void ChromeResourceDispatcherHostDelegate::RequestBeginning(
298     net::URLRequest* request,
299     content::ResourceContext* resource_context,
300     content::AppCacheService* appcache_service,
301     ResourceType resource_type,
302     int child_id,
303     int route_id,
304     ScopedVector<content::ResourceThrottle>* throttles) {
305   const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
306   bool is_prerendering =
307       info->GetVisibilityState() == blink::WebPageVisibilityStatePrerender;
308   if (is_prerendering) {
309     // Requests with the IGNORE_LIMITS flag set (i.e., sync XHRs)
310     // should remain at MAXIMUM_PRIORITY.
311     if (request->load_flags() & net::LOAD_IGNORE_LIMITS) {
312       DCHECK_EQ(request->priority(), net::MAXIMUM_PRIORITY);
313     } else {
314       request->SetPriority(net::IDLE);
315     }
316   }
317
318   ProfileIOData* io_data = ProfileIOData::FromResourceContext(
319       resource_context);
320
321 #if defined(OS_ANDROID)
322   // TODO(davidben): This is insufficient to integrate with prerender properly.
323   // https://crbug.com/370595
324   if (resource_type == content::RESOURCE_TYPE_MAIN_FRAME && !is_prerendering) {
325     throttles->push_back(
326         InterceptNavigationDelegate::CreateThrottleFor(request));
327   }
328 #else
329   if (resource_type == content::RESOURCE_TYPE_MAIN_FRAME) {
330     // Redirect some navigations to apps that have registered matching URL
331     // handlers ('url_handlers' in the manifest).
332     content::ResourceThrottle* url_to_app_throttle =
333         AppUrlRedirector::MaybeCreateThrottleFor(request, io_data);
334     if (url_to_app_throttle)
335       throttles->push_back(url_to_app_throttle);
336
337     if (!is_prerendering) {
338       // Experimental: Launch ephemeral apps from search results.
339       content::ResourceThrottle* ephemeral_app_throttle =
340           EphemeralAppThrottle::MaybeCreateThrottleForLaunch(
341               request, io_data);
342       if (ephemeral_app_throttle)
343         throttles->push_back(ephemeral_app_throttle);
344     }
345   }
346 #endif
347
348 #if defined(OS_CHROMEOS)
349   // Check if we need to add offline throttle. This should be done only
350   // for main frames.
351   if (resource_type == content::RESOURCE_TYPE_MAIN_FRAME) {
352     // We check offline first, then check safe browsing so that we still can
353     // block unsafe site after we remove offline page.
354     throttles->push_back(new OfflineResourceThrottle(request,
355                                                      appcache_service));
356   }
357
358   // Check if we need to add merge session throttle. This throttle will postpone
359   // loading of main frames and XHR request.
360   if (resource_type == content::RESOURCE_TYPE_MAIN_FRAME ||
361       resource_type == content::RESOURCE_TYPE_XHR) {
362     // Add interstitial page while merge session process (cookie
363     // reconstruction from OAuth2 refresh token in ChromeOS login) is still in
364     // progress while we are attempting to load a google property.
365     if (!MergeSessionThrottle::AreAllSessionMergedAlready() &&
366         request->url().SchemeIsHTTPOrHTTPS()) {
367       throttles->push_back(new MergeSessionThrottle(request, resource_type));
368     }
369   }
370 #endif
371
372   // Don't attempt to append headers to requests that have already started.
373   // TODO(stevet): Remove this once the request ordering issues are resolved
374   // in crbug.com/128048.
375   if (!request->is_pending()) {
376     net::HttpRequestHeaders headers;
377     headers.CopyFrom(request->extra_request_headers());
378     bool is_off_the_record = io_data->IsOffTheRecord();
379     variations::VariationsHttpHeaderProvider::GetInstance()->
380         AppendHeaders(request->url(),
381                       is_off_the_record,
382                       !is_off_the_record &&
383                           io_data->GetMetricsEnabledStateOnIOThread(),
384                       &headers);
385     request->SetExtraRequestHeaders(headers);
386   }
387
388 #if defined(ENABLE_ONE_CLICK_SIGNIN)
389   AppendChromeSyncGaiaHeader(request, resource_context);
390 #endif
391
392 #if defined(ENABLE_CONFIGURATION_POLICY)
393   if (io_data->policy_header_helper())
394     io_data->policy_header_helper()->AddPolicyHeaders(request->url(), request);
395 #endif
396
397   signin::AppendMirrorRequestHeaderIfPossible(
398       request, GURL() /* redirect_url */,
399       io_data, info->GetChildID(), info->GetRouteID());
400
401   AppendStandardResourceThrottles(request,
402                                   resource_context,
403                                   resource_type,
404                                   throttles);
405   if (!is_prerendering) {
406     AppendComponentUpdaterThrottles(request,
407                                     resource_context,
408                                     resource_type,
409                                     throttles);
410   }
411 }
412
413 void ChromeResourceDispatcherHostDelegate::DownloadStarting(
414     net::URLRequest* request,
415     content::ResourceContext* resource_context,
416     int child_id,
417     int route_id,
418     int request_id,
419     bool is_content_initiated,
420     bool must_download,
421     ScopedVector<content::ResourceThrottle>* throttles) {
422   BrowserThread::PostTask(
423       BrowserThread::UI, FROM_HERE,
424       base::Bind(&NotifyDownloadInitiatedOnUI, child_id, route_id));
425
426   // If it's from the web, we don't trust it, so we push the throttle on.
427   if (is_content_initiated) {
428     throttles->push_back(
429         new DownloadResourceThrottle(download_request_limiter_.get(),
430                                      child_id,
431                                      route_id,
432                                      request->url(),
433                                      request->method()));
434 #if defined(OS_ANDROID)
435     throttles->push_back(
436         new chrome::InterceptDownloadResourceThrottle(
437             request, child_id, route_id, request_id));
438 #endif
439   }
440
441   // If this isn't a new request, we've seen this before and added the standard
442   //  resource throttles already so no need to add it again.
443   if (!request->is_pending()) {
444     AppendStandardResourceThrottles(request,
445                                     resource_context,
446                                     content::RESOURCE_TYPE_MAIN_FRAME,
447                                     throttles);
448   }
449 }
450
451 ResourceDispatcherHostLoginDelegate*
452     ChromeResourceDispatcherHostDelegate::CreateLoginDelegate(
453         net::AuthChallengeInfo* auth_info, net::URLRequest* request) {
454   return CreateLoginPrompt(auth_info, request);
455 }
456
457 bool ChromeResourceDispatcherHostDelegate::HandleExternalProtocol(
458     const GURL& url,
459     int child_id,
460     int route_id) {
461 #if defined(OS_ANDROID)
462   // Android use a resource throttle to handle external as well as internal
463   // protocols.
464   return false;
465 #else
466
467 #if defined(ENABLE_EXTENSIONS)
468   if (extensions::WebViewRendererState::GetInstance()->IsGuest(child_id))
469     return false;
470
471 #endif  // defined(ENABLE_EXTENSIONS)
472
473   BrowserThread::PostTask(BrowserThread::UI,
474                           FROM_HERE,
475                           base::Bind(&LaunchURL, url, child_id, route_id));
476   return true;
477 #endif
478 }
479
480 void ChromeResourceDispatcherHostDelegate::AppendStandardResourceThrottles(
481     net::URLRequest* request,
482     content::ResourceContext* resource_context,
483     ResourceType resource_type,
484     ScopedVector<content::ResourceThrottle>* throttles) {
485   ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
486 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
487   // Insert safe browsing at the front of the list, so it gets to decide on
488   // policies first.
489   if (io_data->safe_browsing_enabled()->GetValue()
490 #if defined(OS_ANDROID)
491       || io_data->IsDataReductionProxyEnabled()
492 #endif
493   ) {
494     bool is_subresource_request =
495         resource_type != content::RESOURCE_TYPE_MAIN_FRAME;
496     content::ResourceThrottle* throttle =
497         SafeBrowsingResourceThrottleFactory::Create(request,
498                                                     resource_context,
499                                                     is_subresource_request,
500                                                     safe_browsing_.get());
501     if (throttle)
502       throttles->push_back(throttle);
503   }
504 #endif
505
506 #if defined(ENABLE_MANAGED_USERS)
507   bool is_subresource_request =
508       resource_type != content::RESOURCE_TYPE_MAIN_FRAME;
509   throttles->push_back(new SupervisedUserResourceThrottle(
510         request, !is_subresource_request,
511         io_data->supervised_user_url_filter()));
512 #endif
513
514 #if defined(ENABLE_EXTENSIONS)
515   content::ResourceThrottle* throttle =
516       user_script_listener_->CreateResourceThrottle(request->url(),
517                                                     resource_type);
518   if (throttle)
519     throttles->push_back(throttle);
520 #endif
521
522   const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
523   if (info->GetVisibilityState() == blink::WebPageVisibilityStatePrerender) {
524     throttles->push_back(new prerender::PrerenderResourceThrottle(request));
525   }
526   if (prerender_tracker_->IsPendingSwapRequestOnIOThread(
527           info->GetChildID(), info->GetRenderFrameID(), request->url())) {
528     throttles->push_back(new prerender::PrerenderPendingSwapThrottle(
529         request, prerender_tracker_));
530   }
531 }
532
533 #if defined(ENABLE_ONE_CLICK_SIGNIN)
534 void ChromeResourceDispatcherHostDelegate::AppendChromeSyncGaiaHeader(
535     net::URLRequest* request,
536     content::ResourceContext* resource_context) {
537   static const char kAllowChromeSignIn[] = "Allow-Chrome-SignIn";
538
539   ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
540   OneClickSigninHelper::Offer offer =
541       OneClickSigninHelper::CanOfferOnIOThread(request, io_data);
542   switch (offer) {
543     case OneClickSigninHelper::CAN_OFFER:
544       request->SetExtraRequestHeaderByName(kAllowChromeSignIn, "1", false);
545       break;
546     case OneClickSigninHelper::DONT_OFFER:
547       request->RemoveRequestHeaderByName(kAllowChromeSignIn);
548       break;
549     case OneClickSigninHelper::IGNORE_REQUEST:
550       break;
551   }
552 }
553 #endif
554
555 bool ChromeResourceDispatcherHostDelegate::ShouldForceDownloadResource(
556     const GURL& url, const std::string& mime_type) {
557 #if defined(ENABLE_EXTENSIONS)
558   // Special-case user scripts to get downloaded instead of viewed.
559   return extensions::UserScript::IsURLUserScript(url, mime_type);
560 #else
561   return false;
562 #endif
563 }
564
565 bool ChromeResourceDispatcherHostDelegate::ShouldInterceptResourceAsStream(
566     net::URLRequest* request,
567     const std::string& mime_type,
568     GURL* origin,
569     std::string* payload) {
570 #if defined(ENABLE_EXTENSIONS)
571   const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
572   ProfileIOData* io_data =
573       ProfileIOData::FromResourceContext(info->GetContext());
574   bool profile_is_off_the_record = io_data->IsOffTheRecord();
575   const scoped_refptr<const extensions::InfoMap> extension_info_map(
576       io_data->GetExtensionInfoMap());
577   std::vector<std::string> whitelist = MimeTypesHandler::GetMIMETypeWhitelist();
578   // Go through the white-listed extensions and try to use them to intercept
579   // the URL request.
580   for (size_t i = 0; i < whitelist.size(); ++i) {
581     const char* extension_id = whitelist[i].c_str();
582     const Extension* extension =
583         extension_info_map->extensions().GetByID(extension_id);
584     // The white-listed extension may not be installed, so we have to NULL check
585     // |extension|.
586     if (!extension ||
587         (profile_is_off_the_record &&
588          !extension_info_map->IsIncognitoEnabled(extension_id))) {
589       continue;
590     }
591
592     MimeTypesHandler* handler = MimeTypesHandler::GetHandler(extension);
593     if (handler && handler->CanHandleMIMEType(mime_type)) {
594       StreamTargetInfo target_info;
595       *origin = Extension::GetBaseURLFromExtensionId(extension_id);
596       target_info.extension_id = extension_id;
597       if (!handler->handler_url().empty()) {
598         target_info.view_id = base::GenerateGUID();
599         *payload = origin->spec() + handler->handler_url() +
600             "?id=" + target_info.view_id;
601       }
602       stream_target_info_[request] = target_info;
603       return true;
604     }
605   }
606 #endif
607   return false;
608 }
609
610 void ChromeResourceDispatcherHostDelegate::OnStreamCreated(
611     net::URLRequest* request,
612     scoped_ptr<content::StreamHandle> stream) {
613 #if defined(ENABLE_EXTENSIONS)
614   const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
615   std::map<net::URLRequest*, StreamTargetInfo>::iterator ix =
616       stream_target_info_.find(request);
617   CHECK(ix != stream_target_info_.end());
618   content::BrowserThread::PostTask(
619       content::BrowserThread::UI, FROM_HERE,
620       base::Bind(&SendExecuteMimeTypeHandlerEvent, base::Passed(&stream),
621                  request->GetExpectedContentSize(),
622                  info->GetChildID(), info->GetRouteID(),
623                  ix->second.extension_id, ix->second.view_id));
624   stream_target_info_.erase(request);
625 #endif
626 }
627
628 void ChromeResourceDispatcherHostDelegate::OnResponseStarted(
629     net::URLRequest* request,
630     content::ResourceContext* resource_context,
631     content::ResourceResponse* response,
632     IPC::Sender* sender) {
633   const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
634
635 #if defined(OS_ANDROID)
636   // See if the response contains the X-Auto-Login header.  If so, this was
637   // a request for a login page, and the server is allowing the browser to
638   // suggest auto-login, if available.
639   AutoLoginPrompter::ShowInfoBarIfPossible(request, info->GetChildID(),
640                                            info->GetRouteID());
641 #endif
642
643   ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
644
645 #if defined(ENABLE_ONE_CLICK_SIGNIN)
646   // See if the response contains the Google-Accounts-SignIn header.  If so,
647   // then the user has just finished signing in, and the server is allowing the
648   // browser to suggest connecting the user's profile to the account.
649   OneClickSigninHelper::ShowInfoBarIfPossible(request, io_data,
650                                               info->GetChildID(),
651                                               info->GetRouteID());
652 #endif
653
654   // See if the response contains the X-Chrome-Manage-Accounts header. If so
655   // show the profile avatar bubble so that user can complete signin/out action
656   // the native UI.
657   signin::ProcessMirrorResponseHeaderIfExists(request, io_data,
658                                               info->GetChildID(),
659                                               info->GetRouteID());
660
661   // Build in additional protection for the chrome web store origin.
662   GURL webstore_url(extension_urls::GetWebstoreLaunchURL());
663   if (request->url().DomainIs(webstore_url.host().c_str())) {
664     net::HttpResponseHeaders* response_headers = request->response_headers();
665     if (!response_headers->HasHeaderValue("x-frame-options", "deny") &&
666         !response_headers->HasHeaderValue("x-frame-options", "sameorigin")) {
667       response_headers->RemoveHeader("x-frame-options");
668       response_headers->AddHeader("x-frame-options: sameorigin");
669     }
670   }
671
672   // Ignores x-frame-options for the chrome signin UI.
673   const std::string request_spec(
674       request->first_party_for_cookies().GetOrigin().spec());
675 #if defined(OS_CHROMEOS)
676   if (request_spec == chrome::kChromeUIOobeURL ||
677       request_spec == chrome::kChromeUIChromeSigninURL) {
678 #else
679   if (request_spec == chrome::kChromeUIChromeSigninURL) {
680 #endif
681     net::HttpResponseHeaders* response_headers = request->response_headers();
682     if (response_headers && response_headers->HasHeader("x-frame-options"))
683       response_headers->RemoveHeader("x-frame-options");
684   }
685
686   prerender::URLRequestResponseStarted(request);
687 }
688
689 void ChromeResourceDispatcherHostDelegate::OnRequestRedirected(
690     const GURL& redirect_url,
691     net::URLRequest* request,
692     content::ResourceContext* resource_context,
693     content::ResourceResponse* response) {
694   ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
695   const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
696
697 #if defined(ENABLE_ONE_CLICK_SIGNIN)
698   // See if the response contains the Google-Accounts-SignIn header.  If so,
699   // then the user has just finished signing in, and the server is allowing the
700   // browser to suggest connecting the user's profile to the account.
701   OneClickSigninHelper::ShowInfoBarIfPossible(request, io_data,
702                                               info->GetChildID(),
703                                               info->GetRouteID());
704   AppendChromeSyncGaiaHeader(request, resource_context);
705 #endif
706
707   // In the Mirror world, Chrome should append a X-Chrome-Connected header to
708   // all Gaia requests from a connected profile so Gaia could return a 204
709   // response and let Chrome handle the action with native UI. The only
710   // exception is requests from gaia webview, since the native profile
711   // management UI is built on top of it.
712   signin::AppendMirrorRequestHeaderIfPossible(request, redirect_url, io_data,
713       info->GetChildID(), info->GetRouteID());
714
715 #if defined(ENABLE_CONFIGURATION_POLICY)
716   if (io_data->policy_header_helper())
717     io_data->policy_header_helper()->AddPolicyHeaders(redirect_url, request);
718 #endif
719 }
720
721 // Notification that a request has completed.
722 void ChromeResourceDispatcherHostDelegate::RequestComplete(
723     net::URLRequest* url_request) {
724   // Jump on the UI thread and inform the prerender about the bytes.
725   const ResourceRequestInfo* info =
726       ResourceRequestInfo::ForRequest(url_request);
727   if (url_request && !url_request->was_cached()) {
728     BrowserThread::PostTask(BrowserThread::UI,
729                             FROM_HERE,
730                             base::Bind(&UpdatePrerenderNetworkBytesCallback,
731                                        info->GetChildID(),
732                                        info->GetRouteID(),
733                                        url_request->GetTotalReceivedBytes()));
734   }
735 }
736
737 // static
738 void ChromeResourceDispatcherHostDelegate::
739     SetExternalProtocolHandlerDelegateForTesting(
740     ExternalProtocolHandler::Delegate* delegate) {
741   g_external_protocol_handler_delegate = delegate;
742 }