Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / chrome / browser / chromeos / file_manager / file_browser_handlers.cc
blob846adbd94dd0a1e7063468e285834311d5ec0ae0
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.
5 #include "chrome/browser/chromeos/file_manager/file_browser_handlers.h"
7 #include <algorithm>
8 #include <set>
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/files/file_util.h"
13 #include "base/i18n/case_conversion.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "chrome/browser/chromeos/drive/file_system_util.h"
16 #include "chrome/browser/chromeos/file_manager/app_id.h"
17 #include "chrome/browser/chromeos/file_manager/fileapi_util.h"
18 #include "chrome/browser/chromeos/file_manager/open_with_browser.h"
19 #include "chrome/browser/chromeos/fileapi/file_system_backend.h"
20 #include "chrome/browser/extensions/extension_service.h"
21 #include "chrome/browser/extensions/extension_util.h"
22 #include "chrome/browser/profiles/profile.h"
23 #include "chrome/browser/ui/browser_finder.h"
24 #include "chrome/common/extensions/api/file_browser_handlers/file_browser_handler.h"
25 #include "chrome/common/extensions/api/file_manager_private.h"
26 #include "chromeos/chromeos_switches.h"
27 #include "content/public/browser/browser_thread.h"
28 #include "content/public/browser/child_process_security_policy.h"
29 #include "content/public/browser/render_process_host.h"
30 #include "content/public/browser/site_instance.h"
31 #include "content/public/browser/web_contents.h"
32 #include "extensions/browser/event_router.h"
33 #include "extensions/browser/extension_host.h"
34 #include "extensions/browser/extension_registry.h"
35 #include "extensions/browser/extension_util.h"
36 #include "extensions/browser/lazy_background_task_queue.h"
37 #include "extensions/common/extension_set.h"
38 #include "extensions/common/manifest_handlers/background_info.h"
39 #include "extensions/common/url_pattern.h"
40 #include "net/base/escape.h"
41 #include "storage/browser/fileapi/file_system_context.h"
42 #include "storage/browser/fileapi/file_system_url.h"
43 #include "storage/common/fileapi/file_system_info.h"
44 #include "storage/common/fileapi/file_system_util.h"
46 using content::BrowserThread;
47 using content::ChildProcessSecurityPolicy;
48 using content::SiteInstance;
49 using content::WebContents;
50 using extensions::Extension;
51 using storage::FileSystemURL;
52 using file_manager::util::EntryDefinition;
53 using file_manager::util::EntryDefinitionList;
54 using file_manager::util::FileDefinition;
55 using file_manager::util::FileDefinitionList;
57 namespace file_manager {
58 namespace file_browser_handlers {
59 namespace {
61 // Returns process id of the process the extension is running in.
62 int ExtractProcessFromExtensionId(Profile* profile,
63 const std::string& extension_id) {
64 GURL extension_url =
65 Extension::GetBaseURLFromExtensionId(extension_id);
66 extensions::ProcessManager* manager =
67 extensions::ProcessManager::Get(profile);
69 scoped_refptr<SiteInstance> site_instance =
70 manager->GetSiteInstanceForURL(extension_url);
71 if (!site_instance || !site_instance->HasProcess())
72 return -1;
73 content::RenderProcessHost* process = site_instance->GetProcess();
75 return process->GetID();
78 // Finds a file browser handler that matches |action_id|. Returns NULL if not
79 // found.
80 const FileBrowserHandler* FindFileBrowserHandlerForActionId(
81 const Extension* extension,
82 const std::string& action_id) {
83 FileBrowserHandler::List* handler_list =
84 FileBrowserHandler::GetHandlers(extension);
85 for (FileBrowserHandler::List::const_iterator handler_iter =
86 handler_list->begin();
87 handler_iter != handler_list->end();
88 ++handler_iter) {
89 if (handler_iter->get()->id() == action_id)
90 return handler_iter->get();
92 return NULL;
95 std::string EscapedUtf8ToLower(const std::string& str) {
96 base::string16 utf16 = base::UTF8ToUTF16(
97 net::UnescapeURLComponent(str, net::UnescapeRule::NORMAL));
98 return net::EscapeUrlEncodedData(
99 base::UTF16ToUTF8(base::i18n::ToLower(utf16)),
100 false /* do not replace space with plus */);
103 // Finds file browser handlers that can handle the |selected_file_url|.
104 FileBrowserHandlerList FindFileBrowserHandlersForURL(
105 Profile* profile,
106 const GURL& selected_file_url) {
107 extensions::ExtensionRegistry* registry =
108 extensions::ExtensionRegistry::Get(profile);
109 // In unit-tests, we may not have an ExtensionRegistry.
110 if (!registry)
111 return FileBrowserHandlerList();
113 // We need case-insensitive matching, and pattern in the handler is already
114 // in lower case.
115 const GURL lowercase_url(EscapedUtf8ToLower(selected_file_url.spec()));
117 FileBrowserHandlerList results;
118 for (const scoped_refptr<const Extension>& extension :
119 registry->enabled_extensions()) {
120 if (profile->IsOffTheRecord() &&
121 !extensions::util::IsIncognitoEnabled(extension->id(), profile))
122 continue;
123 if (extensions::util::IsEphemeralApp(extension->id(), profile))
124 continue;
126 FileBrowserHandler::List* handler_list =
127 FileBrowserHandler::GetHandlers(extension.get());
128 if (!handler_list)
129 continue;
130 for (FileBrowserHandler::List::const_iterator handler_iter =
131 handler_list->begin();
132 handler_iter != handler_list->end();
133 ++handler_iter) {
134 const FileBrowserHandler* handler = handler_iter->get();
135 if (!handler->MatchesURL(lowercase_url))
136 continue;
137 // Filter out Files app from handling ZIP files via a handler, as it's
138 // now handled by new ZIP unpacker extension based on File System Provider
139 // API.
140 const URLPattern zip_pattern(URLPattern::SCHEME_EXTENSION,
141 "chrome-extension://*/*.zip");
142 if (handler->extension_id() == kFileManagerAppId &&
143 zip_pattern.MatchesURL(selected_file_url) &&
144 !base::CommandLine::ForCurrentProcess()->HasSwitch(
145 chromeos::switches::kDisableNewZIPUnpacker)) {
146 continue;
148 results.push_back(handler);
151 return results;
154 // This class is used to execute a file browser handler task. Here's how this
155 // works:
157 // 1) Open the "external" file system
158 // 2) Set up permissions for the target files on the external file system.
159 // 3) Raise onExecute event with the action ID and entries of the target
160 // files. The event will launch the file browser handler if not active.
161 // 4) In the file browser handler, onExecute event is handled and executes the
162 // task in JavaScript.
164 // That said, the class itself does not execute a task. The task will be
165 // executed in JavaScript.
166 class FileBrowserHandlerExecutor {
167 public:
168 FileBrowserHandlerExecutor(Profile* profile,
169 const Extension* extension,
170 const std::string& action_id);
172 // Executes the task for each file. |done| will be run with the result.
173 void Execute(const std::vector<FileSystemURL>& file_urls,
174 const file_tasks::FileTaskFinishedCallback& done);
176 private:
177 // This object is responsible to delete itself.
178 virtual ~FileBrowserHandlerExecutor();
180 // Checks legitimacy of file url and grants file RO access permissions from
181 // handler (target) extension and its renderer process.
182 static scoped_ptr<FileDefinitionList> SetupFileAccessPermissions(
183 scoped_refptr<storage::FileSystemContext> file_system_context_handler,
184 const scoped_refptr<const Extension>& handler_extension,
185 const std::vector<FileSystemURL>& file_urls);
187 void ExecuteDoneOnUIThread(bool success);
188 void ExecuteAfterSetupFileAccess(scoped_ptr<FileDefinitionList> file_list);
189 void ExecuteFileActionsOnUIThread(
190 scoped_ptr<FileDefinitionList> file_definition_list,
191 scoped_ptr<EntryDefinitionList> entry_definition_list);
192 void SetupPermissionsAndDispatchEvent(
193 scoped_ptr<FileDefinitionList> file_definition_list,
194 scoped_ptr<EntryDefinitionList> entry_definition_list,
195 int handler_pid_in,
196 extensions::ExtensionHost* host);
198 // Registers file permissions from |handler_host_permissions_| with
199 // ChildProcessSecurityPolicy for process with id |handler_pid|.
200 void SetupHandlerHostFileAccessPermissions(
201 FileDefinitionList* file_definition_list,
202 const Extension* extension,
203 int handler_pid);
205 Profile* profile_;
206 scoped_refptr<const Extension> extension_;
207 const std::string action_id_;
208 file_tasks::FileTaskFinishedCallback done_;
209 base::WeakPtrFactory<FileBrowserHandlerExecutor> weak_ptr_factory_;
211 DISALLOW_COPY_AND_ASSIGN(FileBrowserHandlerExecutor);
214 // static
215 scoped_ptr<FileDefinitionList>
216 FileBrowserHandlerExecutor::SetupFileAccessPermissions(
217 scoped_refptr<storage::FileSystemContext> file_system_context_handler,
218 const scoped_refptr<const Extension>& handler_extension,
219 const std::vector<FileSystemURL>& file_urls) {
220 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
221 DCHECK(handler_extension.get());
223 storage::ExternalFileSystemBackend* backend =
224 file_system_context_handler->external_backend();
226 scoped_ptr<FileDefinitionList> file_definition_list(new FileDefinitionList);
227 for (size_t i = 0; i < file_urls.size(); ++i) {
228 const FileSystemURL& url = file_urls[i];
230 // Check if this file system entry exists first.
231 base::File::Info file_info;
233 base::FilePath local_path = url.path();
234 base::FilePath virtual_path = url.virtual_path();
236 const bool is_drive_file = url.type() == storage::kFileSystemTypeDrive;
237 DCHECK(!is_drive_file || drive::util::IsUnderDriveMountPoint(local_path));
239 const bool is_native_file =
240 url.type() == storage::kFileSystemTypeNativeLocal ||
241 url.type() == storage::kFileSystemTypeRestrictedNativeLocal;
243 // If the file is from a physical volume, actual file must be found.
244 if (is_native_file) {
245 if (!base::PathExists(local_path) ||
246 base::IsLink(local_path) ||
247 !base::GetFileInfo(local_path, &file_info)) {
248 continue;
252 // Grant access to this particular file to target extension. This will
253 // ensure that the target extension can access only this FS entry and
254 // prevent from traversing FS hierarchy upward.
255 backend->GrantFileAccessToExtension(handler_extension->id(), virtual_path);
257 // Output values.
258 FileDefinition file_definition;
259 file_definition.virtual_path = virtual_path;
260 file_definition.is_directory = file_info.is_directory;
261 file_definition.absolute_path = local_path;
262 file_definition_list->push_back(file_definition);
265 return file_definition_list.Pass();
268 FileBrowserHandlerExecutor::FileBrowserHandlerExecutor(
269 Profile* profile,
270 const Extension* extension,
271 const std::string& action_id)
272 : profile_(profile),
273 extension_(extension),
274 action_id_(action_id),
275 weak_ptr_factory_(this) {
278 FileBrowserHandlerExecutor::~FileBrowserHandlerExecutor() {}
280 void FileBrowserHandlerExecutor::Execute(
281 const std::vector<FileSystemURL>& file_urls,
282 const file_tasks::FileTaskFinishedCallback& done) {
283 done_ = done;
285 // Get file system context for the extension to which onExecute event will be
286 // sent. The file access permissions will be granted to the extension in the
287 // file system context for the files in |file_urls|.
288 scoped_refptr<storage::FileSystemContext> file_system_context(
289 util::GetFileSystemContextForExtensionId(profile_, extension_->id()));
291 BrowserThread::PostTaskAndReplyWithResult(
292 BrowserThread::FILE,
293 FROM_HERE,
294 base::Bind(&SetupFileAccessPermissions,
295 file_system_context,
296 extension_,
297 file_urls),
298 base::Bind(&FileBrowserHandlerExecutor::ExecuteAfterSetupFileAccess,
299 weak_ptr_factory_.GetWeakPtr()));
302 void FileBrowserHandlerExecutor::ExecuteAfterSetupFileAccess(
303 scoped_ptr<FileDefinitionList> file_definition_list) {
304 // Outlives the conversion process, since bound to the callback.
305 const FileDefinitionList& file_definition_list_ref =
306 *file_definition_list.get();
307 file_manager::util::ConvertFileDefinitionListToEntryDefinitionList(
308 profile_,
309 extension_->id(),
310 file_definition_list_ref,
311 base::Bind(&FileBrowserHandlerExecutor::ExecuteFileActionsOnUIThread,
312 weak_ptr_factory_.GetWeakPtr(),
313 base::Passed(&file_definition_list)));
316 void FileBrowserHandlerExecutor::ExecuteDoneOnUIThread(bool success) {
317 DCHECK_CURRENTLY_ON(BrowserThread::UI);
318 if (!done_.is_null())
319 done_.Run(
320 success
321 ? extensions::api::file_manager_private::TASK_RESULT_MESSAGE_SENT
322 : extensions::api::file_manager_private::TASK_RESULT_FAILED);
323 delete this;
326 void FileBrowserHandlerExecutor::ExecuteFileActionsOnUIThread(
327 scoped_ptr<FileDefinitionList> file_definition_list,
328 scoped_ptr<EntryDefinitionList> entry_definition_list) {
329 DCHECK_CURRENTLY_ON(BrowserThread::UI);
331 if (file_definition_list->empty() || entry_definition_list->empty()) {
332 ExecuteDoneOnUIThread(false);
333 return;
336 int handler_pid = ExtractProcessFromExtensionId(profile_, extension_->id());
337 if (handler_pid <= 0 &&
338 !extensions::BackgroundInfo::HasLazyBackgroundPage(extension_.get())) {
339 ExecuteDoneOnUIThread(false);
340 return;
343 if (handler_pid > 0) {
344 SetupPermissionsAndDispatchEvent(file_definition_list.Pass(),
345 entry_definition_list.Pass(),
346 handler_pid,
347 NULL);
348 } else {
349 // We have to wake the handler background page before we proceed.
350 extensions::LazyBackgroundTaskQueue* queue =
351 extensions::LazyBackgroundTaskQueue::Get(profile_);
352 if (!queue->ShouldEnqueueTask(profile_, extension_.get())) {
353 ExecuteDoneOnUIThread(false);
354 return;
356 queue->AddPendingTask(
357 profile_,
358 extension_->id(),
359 base::Bind(
360 &FileBrowserHandlerExecutor::SetupPermissionsAndDispatchEvent,
361 weak_ptr_factory_.GetWeakPtr(),
362 base::Passed(file_definition_list.Pass()),
363 base::Passed(entry_definition_list.Pass()),
364 handler_pid));
368 void FileBrowserHandlerExecutor::SetupPermissionsAndDispatchEvent(
369 scoped_ptr<FileDefinitionList> file_definition_list,
370 scoped_ptr<EntryDefinitionList> entry_definition_list,
371 int handler_pid_in,
372 extensions::ExtensionHost* host) {
373 int handler_pid = host ? host->render_process_host()->GetID() :
374 handler_pid_in;
376 if (handler_pid <= 0) {
377 ExecuteDoneOnUIThread(false);
378 return;
381 extensions::EventRouter* router = extensions::EventRouter::Get(profile_);
382 if (!router) {
383 ExecuteDoneOnUIThread(false);
384 return;
387 SetupHandlerHostFileAccessPermissions(
388 file_definition_list.get(), extension_.get(), handler_pid);
390 scoped_ptr<base::ListValue> event_args(new base::ListValue());
391 event_args->Append(new base::StringValue(action_id_));
392 base::DictionaryValue* details = new base::DictionaryValue();
393 event_args->Append(details);
394 // Get file definitions. These will be replaced with Entry instances by
395 // dispatchEvent() method from event_binding.js.
396 base::ListValue* file_entries = new base::ListValue();
397 details->Set("entries", file_entries);
399 for (EntryDefinitionList::const_iterator iter =
400 entry_definition_list->begin();
401 iter != entry_definition_list->end();
402 ++iter) {
403 base::DictionaryValue* file_def = new base::DictionaryValue();
404 file_entries->Append(file_def);
405 file_def->SetString("fileSystemName", iter->file_system_name);
406 file_def->SetString("fileSystemRoot", iter->file_system_root_url);
407 file_def->SetString("fileFullPath",
408 "/" + iter->full_path.AsUTF8Unsafe());
409 file_def->SetBoolean("fileIsDirectory", iter->is_directory);
412 scoped_ptr<extensions::Event> event(
413 new extensions::Event(extensions::events::FILE_BROWSER_HANDLER_ON_EXECUTE,
414 "fileBrowserHandler.onExecute", event_args.Pass()));
415 event->restrict_to_browser_context = profile_;
416 router->DispatchEventToExtension(extension_->id(), event.Pass());
418 ExecuteDoneOnUIThread(true);
421 void FileBrowserHandlerExecutor::SetupHandlerHostFileAccessPermissions(
422 FileDefinitionList* file_definition_list,
423 const Extension* extension,
424 int handler_pid) {
425 const FileBrowserHandler* action =
426 FindFileBrowserHandlerForActionId(extension_.get(), action_id_);
427 for (FileDefinitionList::const_iterator iter = file_definition_list->begin();
428 iter != file_definition_list->end();
429 ++iter) {
430 if (!action)
431 continue;
432 if (action->CanRead()) {
433 content::ChildProcessSecurityPolicy::GetInstance()->GrantReadFile(
434 handler_pid, iter->absolute_path);
436 if (action->CanWrite()) {
437 content::ChildProcessSecurityPolicy::GetInstance()->
438 GrantCreateReadWriteFile(handler_pid, iter->absolute_path);
443 // Returns true if |extension_id| and |action_id| indicate that the file
444 // currently being handled should be opened with the browser. This function
445 // is used to handle certain action IDs of the file manager.
446 bool ShouldBeOpenedWithBrowser(const std::string& extension_id,
447 const std::string& action_id) {
448 return (extension_id == kFileManagerAppId &&
449 (action_id == "view-pdf" ||
450 action_id == "view-swf" ||
451 action_id == "view-in-browser" ||
452 action_id == "open-hosted-generic" ||
453 action_id == "open-hosted-gdoc" ||
454 action_id == "open-hosted-gsheet" ||
455 action_id == "open-hosted-gslides"));
458 // Opens the files specified by |file_urls| with the browser for |profile|.
459 // Returns true on success. It's a failure if no files are opened.
460 bool OpenFilesWithBrowser(Profile* profile,
461 const std::vector<FileSystemURL>& file_urls) {
462 int num_opened = 0;
463 for (size_t i = 0; i < file_urls.size(); ++i) {
464 const FileSystemURL& file_url = file_urls[i];
465 if (chromeos::FileSystemBackend::CanHandleURL(file_url)) {
466 num_opened += util::OpenFileWithBrowser(profile, file_url) ? 1 : 0;
469 return num_opened > 0;
472 } // namespace
474 bool ExecuteFileBrowserHandler(
475 Profile* profile,
476 const Extension* extension,
477 const std::string& action_id,
478 const std::vector<FileSystemURL>& file_urls,
479 const file_tasks::FileTaskFinishedCallback& done) {
480 // Forbid calling undeclared handlers.
481 if (!FindFileBrowserHandlerForActionId(extension, action_id))
482 return false;
484 // Some action IDs of the file manager's file browser handlers require the
485 // files to be directly opened with the browser.
486 if (ShouldBeOpenedWithBrowser(extension->id(), action_id)) {
487 const bool result = OpenFilesWithBrowser(profile, file_urls);
488 if (result && !done.is_null())
489 done.Run(extensions::api::file_manager_private::TASK_RESULT_OPENED);
490 return result;
493 // The executor object will be self deleted on completion.
494 (new FileBrowserHandlerExecutor(
495 profile, extension, action_id))->Execute(file_urls, done);
496 return true;
499 FileBrowserHandlerList FindFileBrowserHandlers(
500 Profile* profile,
501 const std::vector<GURL>& file_list) {
502 FileBrowserHandlerList common_handlers;
503 for (std::vector<GURL>::const_iterator it = file_list.begin();
504 it != file_list.end(); ++it) {
505 FileBrowserHandlerList handlers =
506 FindFileBrowserHandlersForURL(profile, *it);
507 // If there is nothing to do for one file, the intersection of handlers
508 // for all files will be empty at the end, so no need to check further.
509 if (handlers.empty())
510 return FileBrowserHandlerList();
512 // For the very first file, just copy all the elements.
513 if (it == file_list.begin()) {
514 common_handlers = handlers;
515 } else {
516 // For all additional files, find intersection between the accumulated and
517 // file specific set.
518 FileBrowserHandlerList intersection;
519 std::set<const FileBrowserHandler*> common_handler_set(
520 common_handlers.begin(), common_handlers.end());
522 for (FileBrowserHandlerList::const_iterator itr = handlers.begin();
523 itr != handlers.end(); ++itr) {
524 if (ContainsKey(common_handler_set, *itr))
525 intersection.push_back(*itr);
528 std::swap(common_handlers, intersection);
529 if (common_handlers.empty())
530 return FileBrowserHandlerList();
534 return common_handlers;
537 } // namespace file_browser_handlers
538 } // namespace file_manager