• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 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/extensions/url_request_util.h"
6 
7 #include <string>
8 
9 #include "base/files/file_path.h"
10 #include "base/memory/weak_ptr.h"
11 #include "base/path_service.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/task_runner_util.h"
16 #include "chrome/browser/extensions/extension_renderer_state.h"
17 #include "chrome/common/chrome_paths.h"
18 #include "chrome/common/extensions/manifest_url_handler.h"
19 #include "content/public/browser/browser_thread.h"
20 #include "content/public/browser/resource_request_info.h"
21 #include "extensions/browser/component_extension_resource_manager.h"
22 #include "extensions/browser/extension_protocols.h"
23 #include "extensions/browser/extensions_browser_client.h"
24 #include "extensions/browser/info_map.h"
25 #include "extensions/common/file_util.h"
26 #include "extensions/common/manifest_handlers/icons_handler.h"
27 #include "extensions/common/manifest_handlers/web_accessible_resources_info.h"
28 #include "extensions/common/manifest_handlers/webview_info.h"
29 #include "net/base/mime_util.h"
30 #include "net/base/net_errors.h"
31 #include "net/http/http_request_headers.h"
32 #include "net/http/http_response_headers.h"
33 #include "net/http/http_response_info.h"
34 #include "net/url_request/url_request.h"
35 #include "net/url_request/url_request_simple_job.h"
36 #include "ui/base/resource/resource_bundle.h"
37 
38 using content::BrowserThread;
39 using extensions::ExtensionsBrowserClient;
40 
41 namespace {
42 
43 // A request for an extension resource in a Chrome .pak file. These are used
44 // by component extensions.
45 class URLRequestResourceBundleJob : public net::URLRequestSimpleJob {
46  public:
URLRequestResourceBundleJob(net::URLRequest * request,net::NetworkDelegate * network_delegate,const base::FilePath & filename,int resource_id,const std::string & content_security_policy,bool send_cors_header)47   URLRequestResourceBundleJob(net::URLRequest* request,
48                               net::NetworkDelegate* network_delegate,
49                               const base::FilePath& filename,
50                               int resource_id,
51                               const std::string& content_security_policy,
52                               bool send_cors_header)
53       : net::URLRequestSimpleJob(request, network_delegate),
54         filename_(filename),
55         resource_id_(resource_id),
56         weak_factory_(this) {
57     // Leave cache headers out of resource bundle requests.
58     response_info_.headers = extensions::BuildHttpHeaders(
59         content_security_policy, send_cors_header, base::Time());
60   }
61 
62   // Overridden from URLRequestSimpleJob:
GetData(std::string * mime_type,std::string * charset,std::string * data,const net::CompletionCallback & callback) const63   virtual int GetData(std::string* mime_type,
64                       std::string* charset,
65                       std::string* data,
66                       const net::CompletionCallback& callback) const OVERRIDE {
67     const ResourceBundle& rb = ResourceBundle::GetSharedInstance();
68     *data = rb.GetRawDataResource(resource_id_).as_string();
69 
70     // Add the Content-Length header now that we know the resource length.
71     response_info_.headers->AddHeader(
72         base::StringPrintf("%s: %s",
73                            net::HttpRequestHeaders::kContentLength,
74                            base::UintToString(data->size()).c_str()));
75 
76     std::string* read_mime_type = new std::string;
77     bool posted = base::PostTaskAndReplyWithResult(
78         BrowserThread::GetBlockingPool(),
79         FROM_HERE,
80         base::Bind(&net::GetMimeTypeFromFile,
81                    filename_,
82                    base::Unretained(read_mime_type)),
83         base::Bind(&URLRequestResourceBundleJob::OnMimeTypeRead,
84                    weak_factory_.GetWeakPtr(),
85                    mime_type,
86                    charset,
87                    data,
88                    base::Owned(read_mime_type),
89                    callback));
90     DCHECK(posted);
91 
92     return net::ERR_IO_PENDING;
93   }
94 
GetResponseInfo(net::HttpResponseInfo * info)95   virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE {
96     *info = response_info_;
97   }
98 
99  private:
~URLRequestResourceBundleJob()100   virtual ~URLRequestResourceBundleJob() {}
101 
OnMimeTypeRead(std::string * out_mime_type,std::string * charset,std::string * data,std::string * read_mime_type,const net::CompletionCallback & callback,bool read_result)102   void OnMimeTypeRead(std::string* out_mime_type,
103                       std::string* charset,
104                       std::string* data,
105                       std::string* read_mime_type,
106                       const net::CompletionCallback& callback,
107                       bool read_result) {
108     *out_mime_type = *read_mime_type;
109     if (StartsWithASCII(*read_mime_type, "text/", false)) {
110       // All of our HTML files should be UTF-8 and for other resource types
111       // (like images), charset doesn't matter.
112       DCHECK(base::IsStringUTF8(*data));
113       *charset = "utf-8";
114     }
115     int result = read_result ? net::OK : net::ERR_INVALID_URL;
116     callback.Run(result);
117   }
118 
119   // We need the filename of the resource to determine the mime type.
120   base::FilePath filename_;
121 
122   // The resource bundle id to load.
123   int resource_id_;
124 
125   net::HttpResponseInfo response_info_;
126 
127   mutable base::WeakPtrFactory<URLRequestResourceBundleJob> weak_factory_;
128 };
129 
130 }  // namespace
131 
132 namespace extensions {
133 namespace url_request_util {
134 
AllowCrossRendererResourceLoad(net::URLRequest * request,bool is_incognito,const Extension * extension,InfoMap * extension_info_map)135 bool AllowCrossRendererResourceLoad(net::URLRequest* request,
136                                     bool is_incognito,
137                                     const Extension* extension,
138                                     InfoMap* extension_info_map) {
139   const content::ResourceRequestInfo* info =
140       content::ResourceRequestInfo::ForRequest(request);
141 
142   // Check workers so that importScripts works from extension workers.
143   if (extension_info_map->worker_process_map().Contains(request->url().host(),
144                                                         info->GetChildID())) {
145     return true;
146   }
147 
148   // Extensions with webview: allow loading certain resources by guest renderers
149   // with privileged partition IDs as specified in the manifest file.
150   ExtensionRendererState* renderer_state =
151       ExtensionRendererState::GetInstance();
152   std::string partition_id;
153   bool is_guest =
154       renderer_state->GetWebViewPartitionID(info->GetChildID(), &partition_id);
155   std::string resource_path = request->url().path();
156   if (is_guest && WebviewInfo::IsResourceWebviewAccessible(
157                       extension, partition_id, resource_path)) {
158     return true;
159   }
160 
161   // If the request is for navigations outside of webviews, then it should be
162   // allowed. The navigation logic in CrossSiteResourceHandler will properly
163   // transfer the navigation to a privileged process before it commits.
164   if (ResourceType::IsFrame(info->GetResourceType()) && !is_guest)
165     return true;
166 
167   if (!content::PageTransitionIsWebTriggerable(info->GetPageTransition()))
168     return false;
169 
170   // The following checks require that we have an actual extension object. If we
171   // don't have it, allow the request handling to continue with the rest of the
172   // checks.
173   if (!extension)
174     return true;
175 
176   // Disallow loading of packaged resources for hosted apps. We don't allow
177   // hybrid hosted/packaged apps. The one exception is access to icons, since
178   // some extensions want to be able to do things like create their own
179   // launchers.
180   std::string resource_root_relative_path =
181       request->url().path().empty() ? std::string()
182                                     : request->url().path().substr(1);
183   if (extension->is_hosted_app() &&
184       !IconsInfo::GetIcons(extension)
185            .ContainsPath(resource_root_relative_path)) {
186     LOG(ERROR) << "Denying load of " << request->url().spec() << " from "
187                << "hosted app.";
188     return false;
189   }
190 
191   // Extensions with web_accessible_resources: allow loading by regular
192   // renderers. Since not all subresources are required to be listed in a v2
193   // manifest, we must allow all loads if there are any web accessible
194   // resources. See http://crbug.com/179127.
195   if (extension->manifest_version() < 2 ||
196       WebAccessibleResourcesInfo::HasWebAccessibleResources(extension)) {
197     return true;
198   }
199 
200   // If there aren't any explicitly marked web accessible resources, the
201   // load should be allowed only if it is by DevTools. A close approximation is
202   // checking if the extension contains a DevTools page.
203   if (!ManifestURL::GetDevToolsPage(extension).is_empty())
204     return true;
205 
206   // No special exception. Block the load.
207   return false;
208 }
209 
MaybeCreateURLRequestResourceBundleJob(net::URLRequest * request,net::NetworkDelegate * network_delegate,const base::FilePath & directory_path,const std::string & content_security_policy,bool send_cors_header)210 net::URLRequestJob* MaybeCreateURLRequestResourceBundleJob(
211     net::URLRequest* request,
212     net::NetworkDelegate* network_delegate,
213     const base::FilePath& directory_path,
214     const std::string& content_security_policy,
215     bool send_cors_header) {
216   base::FilePath resources_path;
217   base::FilePath relative_path;
218   // Try to load extension resources from chrome resource file if
219   // directory_path is a descendant of resources_path. resources_path
220   // corresponds to src/chrome/browser/resources in source tree.
221   if (PathService::Get(chrome::DIR_RESOURCES, &resources_path) &&
222       // Since component extension resources are included in
223       // component_extension_resources.pak file in resources_path, calculate
224       // extension relative path against resources_path.
225       resources_path.AppendRelativePath(directory_path, &relative_path)) {
226     base::FilePath request_path =
227         extensions::file_util::ExtensionURLToRelativeFilePath(request->url());
228     int resource_id = 0;
229     if (ExtensionsBrowserClient::Get()->GetComponentExtensionResourceManager()->
230         IsComponentExtensionResource(
231             directory_path, request_path, &resource_id)) {
232       relative_path = relative_path.Append(request_path);
233       relative_path = relative_path.NormalizePathSeparators();
234       return new URLRequestResourceBundleJob(request,
235                                              network_delegate,
236                                              relative_path,
237                                              resource_id,
238                                              content_security_policy,
239                                              send_cors_header);
240     }
241   }
242   return NULL;
243 }
244 
IsWebViewRequest(net::URLRequest * request)245 bool IsWebViewRequest(net::URLRequest* request) {
246   const content::ResourceRequestInfo* info =
247       content::ResourceRequestInfo::ForRequest(request);
248   // |info| can be NULL sometimes: http://crbug.com/370070.
249   if (!info)
250     return false;
251   ExtensionRendererState* renderer_state =
252       ExtensionRendererState::GetInstance();
253   ExtensionRendererState::WebViewInfo webview_info;
254   return renderer_state->GetWebViewInfo(
255       info->GetChildID(), info->GetRouteID(), &webview_info);
256 }
257 
258 }  // namespace url_request_util
259 }  // namespace extensions
260