1 // Copyright 2013 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 "apps/launcher.h"
7 #include "apps/browser/api/app_runtime/app_runtime_api.h"
8 #include "apps/browser/file_handler_util.h"
9 #include "apps/common/api/app_runtime.h"
10 #include "base/command_line.h"
11 #include "base/file_util.h"
12 #include "base/files/file_path.h"
13 #include "base/logging.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "chrome/browser/extensions/api/file_handlers/app_file_handler_util.h"
18 #include "chrome/browser/extensions/api/file_system/file_system_api.h"
19 #include "chrome/browser/profiles/profile.h"
20 #include "content/public/browser/browser_thread.h"
21 #include "content/public/browser/render_process_host.h"
22 #include "content/public/browser/web_contents.h"
23 #include "extensions/browser/event_router.h"
24 #include "extensions/browser/extension_host.h"
25 #include "extensions/browser/extension_prefs.h"
26 #include "extensions/browser/extension_system.h"
27 #include "extensions/browser/lazy_background_task_queue.h"
28 #include "extensions/browser/process_manager.h"
29 #include "extensions/common/extension.h"
30 #include "extensions/common/extension_messages.h"
31 #include "extensions/common/manifest_handlers/kiosk_mode_info.h"
32 #include "net/base/filename_util.h"
33 #include "net/base/mime_sniffer.h"
34 #include "net/base/mime_util.h"
35 #include "net/base/net_util.h"
38 #if defined(OS_CHROMEOS)
39 #include "chrome/browser/chromeos/drive/file_errors.h"
40 #include "chrome/browser/chromeos/drive/file_system_interface.h"
41 #include "chrome/browser/chromeos/drive/file_system_util.h"
42 #include "chrome/browser/chromeos/login/user_manager.h"
45 namespace app_runtime
= apps::api::app_runtime
;
47 using apps::file_handler_util::GrantedFileEntry
;
48 using content::BrowserThread
;
49 using extensions::app_file_handler_util::CheckWritableFiles
;
50 using extensions::app_file_handler_util::FileHandlerForId
;
51 using extensions::app_file_handler_util::FileHandlerCanHandleFile
;
52 using extensions::app_file_handler_util::FirstFileHandlerForFile
;
53 using extensions::app_file_handler_util::CreateFileEntry
;
54 using extensions::app_file_handler_util::HasFileSystemWritePermission
;
55 using extensions::EventRouter
;
56 using extensions::Extension
;
57 using extensions::ExtensionHost
;
58 using extensions::ExtensionSystem
;
64 const char kFallbackMimeType
[] = "application/octet-stream";
66 bool MakePathAbsolute(const base::FilePath
& current_directory
,
67 base::FilePath
* file_path
) {
69 if (file_path
->IsAbsolute())
72 if (current_directory
.empty()) {
73 *file_path
= base::MakeAbsoluteFilePath(*file_path
);
74 return !file_path
->empty();
77 if (!current_directory
.IsAbsolute())
80 *file_path
= current_directory
.Append(*file_path
);
84 bool GetAbsolutePathFromCommandLine(const CommandLine
& command_line
,
85 const base::FilePath
& current_directory
,
86 base::FilePath
* path
) {
87 if (!command_line
.GetArgs().size())
90 base::FilePath
relative_path(command_line
.GetArgs()[0]);
91 base::FilePath
absolute_path(relative_path
);
92 if (!MakePathAbsolute(current_directory
, &absolute_path
)) {
93 LOG(WARNING
) << "Cannot make absolute path from " << relative_path
.value();
96 *path
= absolute_path
;
100 // Helper method to launch the platform app |extension| with no data. This
101 // should be called in the fallback case, where it has been impossible to
102 // load or obtain file launch data.
103 void LaunchPlatformAppWithNoData(Profile
* profile
, const Extension
* extension
) {
104 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
105 AppEventRouter::DispatchOnLaunchedEvent(profile
, extension
);
108 // Class to handle launching of platform apps to open a specific path.
109 // An instance of this class is created for each launch. The lifetime of these
110 // instances is managed by reference counted pointers. As long as an instance
111 // has outstanding tasks on a message queue it will be retained; once all
112 // outstanding tasks are completed it will be deleted.
113 class PlatformAppPathLauncher
114 : public base::RefCountedThreadSafe
<PlatformAppPathLauncher
> {
116 PlatformAppPathLauncher(Profile
* profile
,
117 const Extension
* extension
,
118 const base::FilePath
& file_path
)
119 : profile_(profile
), extension_(extension
), file_path_(file_path
) {}
122 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
123 if (file_path_
.empty()) {
124 LaunchPlatformAppWithNoData(profile_
, extension_
);
128 DCHECK(file_path_
.IsAbsolute());
130 if (HasFileSystemWritePermission(extension_
)) {
131 std::vector
<base::FilePath
> paths
;
132 paths
.push_back(file_path_
);
137 base::Bind(&PlatformAppPathLauncher::OnFileValid
, this),
138 base::Bind(&PlatformAppPathLauncher::OnFileInvalid
, this));
145 void LaunchWithHandler(const std::string
& handler_id
) {
146 handler_id_
= handler_id
;
151 friend class base::RefCountedThreadSafe
<PlatformAppPathLauncher
>;
153 virtual ~PlatformAppPathLauncher() {}
156 #if defined(OS_CHROMEOS)
157 if (drive::util::IsUnderDriveMountPoint(file_path_
)) {
158 PlatformAppPathLauncher::GetMimeTypeAndLaunchForDriveFile();
163 BrowserThread::PostTask(
166 base::Bind(&PlatformAppPathLauncher::GetMimeTypeAndLaunch
, this));
169 void OnFileInvalid(const base::FilePath
& /* error_path */) {
170 LaunchWithNoLaunchData();
173 void GetMimeTypeAndLaunch() {
174 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
176 // If the file doesn't exist, or is a directory, launch with no launch data.
177 if (!base::PathExists(file_path_
) ||
178 base::DirectoryExists(file_path_
)) {
179 LOG(WARNING
) << "No file exists with path " << file_path_
.value();
180 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
, base::Bind(
181 &PlatformAppPathLauncher::LaunchWithNoLaunchData
, this));
185 std::string mime_type
;
186 if (!net::GetMimeTypeFromFile(file_path_
, &mime_type
)) {
187 // If MIME type of the file can't be determined by its path,
188 // try to sniff it by its content.
189 std::vector
<char> content(net::kMaxBytesToSniff
);
190 int bytes_read
= base::ReadFile(file_path_
, &content
[0], content
.size());
191 if (bytes_read
>= 0) {
192 net::SniffMimeType(&content
[0],
194 net::FilePathToFileURL(file_path_
),
195 std::string(), // type_hint (passes no hint)
198 if (mime_type
.empty())
199 mime_type
= kFallbackMimeType
;
202 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
, base::Bind(
203 &PlatformAppPathLauncher::LaunchWithMimeType
, this, mime_type
));
206 #if defined(OS_CHROMEOS)
207 void GetMimeTypeAndLaunchForDriveFile() {
208 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
210 drive::FileSystemInterface
* file_system
=
211 drive::util::GetFileSystemByProfile(profile_
);
213 LaunchWithNoLaunchData();
217 file_system
->GetFile(
218 drive::util::ExtractDrivePath(file_path_
),
219 base::Bind(&PlatformAppPathLauncher::OnGotDriveFile
, this));
222 void OnGotDriveFile(drive::FileError error
,
223 const base::FilePath
& file_path
,
224 scoped_ptr
<drive::ResourceEntry
> entry
) {
225 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
227 if (error
!= drive::FILE_ERROR_OK
||
228 !entry
|| entry
->file_specific_info().is_hosted_document()) {
229 LaunchWithNoLaunchData();
233 const std::string
& mime_type
=
234 entry
->file_specific_info().content_mime_type();
235 LaunchWithMimeType(mime_type
.empty() ? kFallbackMimeType
: mime_type
);
237 #endif // defined(OS_CHROMEOS)
239 void LaunchWithNoLaunchData() {
240 // This method is required as an entry point on the UI thread.
241 LaunchPlatformAppWithNoData(profile_
, extension_
);
244 void LaunchWithMimeType(const std::string
& mime_type
) {
245 // Find file handler from the platform app for the file being opened.
246 const extensions::FileHandlerInfo
* handler
= NULL
;
247 if (!handler_id_
.empty())
248 handler
= FileHandlerForId(*extension_
, handler_id_
);
250 handler
= FirstFileHandlerForFile(*extension_
, mime_type
, file_path_
);
251 if (handler
&& !FileHandlerCanHandleFile(*handler
, mime_type
, file_path_
)) {
252 LOG(WARNING
) << "Extension does not provide a valid file handler for "
253 << file_path_
.value();
254 LaunchWithNoLaunchData();
258 // If this app doesn't have a file handler that supports the file, launch
259 // with no launch data.
261 LOG(WARNING
) << "Extension does not provide a valid file handler for "
262 << file_path_
.value();
263 LaunchWithNoLaunchData();
267 if (handler_id_
.empty())
268 handler_id_
= handler
->id
;
270 // Access needs to be granted to the file for the process associated with
271 // the extension. To do this the ExtensionHost is needed. This might not be
272 // available, or it might be in the process of being unloaded, in which case
273 // the lazy background task queue is used to load the extension and then
275 extensions::LazyBackgroundTaskQueue
* queue
=
276 ExtensionSystem::Get(profile_
)->lazy_background_task_queue();
277 if (queue
->ShouldEnqueueTask(profile_
, extension_
)) {
278 queue
->AddPendingTask(profile_
, extension_
->id(), base::Bind(
279 &PlatformAppPathLauncher::GrantAccessToFileAndLaunch
,
284 extensions::ProcessManager
* process_manager
=
285 ExtensionSystem::Get(profile_
)->process_manager();
286 ExtensionHost
* host
=
287 process_manager
->GetBackgroundHostForExtension(extension_
->id());
289 GrantAccessToFileAndLaunch(mime_type
, host
);
292 void GrantAccessToFileAndLaunch(const std::string
& mime_type
,
293 ExtensionHost
* host
) {
294 // If there was an error loading the app page, |host| will be NULL.
296 LOG(ERROR
) << "Could not load app page for " << extension_
->id();
300 GrantedFileEntry file_entry
=
301 CreateFileEntry(profile_
,
303 host
->render_process_host()->GetID(),
306 AppEventRouter::DispatchOnLaunchedEventWithFileEntry(
307 profile_
, extension_
, handler_id_
, mime_type
, file_entry
);
310 // The profile the app should be run in.
312 // The extension providing the app.
313 const Extension
* extension_
;
314 // The path to be passed through to the app.
315 const base::FilePath file_path_
;
316 // The ID of the file handler used to launch the app.
317 std::string handler_id_
;
319 DISALLOW_COPY_AND_ASSIGN(PlatformAppPathLauncher
);
324 void LaunchPlatformAppWithCommandLine(Profile
* profile
,
325 const Extension
* extension
,
326 const CommandLine
& command_line
,
327 const base::FilePath
& current_directory
) {
328 // An app with "kiosk_only" should not be installed and launched
329 // outside of ChromeOS kiosk mode in the first place. This is a defensive
330 // check in case this scenario does occur.
331 if (extensions::KioskModeInfo::IsKioskOnly(extension
)) {
332 bool in_kiosk_mode
= false;
333 #if defined(OS_CHROMEOS)
334 chromeos::UserManager
* user_manager
= chromeos::UserManager::Get();
335 in_kiosk_mode
= user_manager
&& user_manager
->IsLoggedInAsKioskApp();
337 if (!in_kiosk_mode
) {
338 LOG(ERROR
) << "App with 'kiosk_only' attribute must be run in "
339 << " ChromeOS kiosk mode.";
346 if (!GetAbsolutePathFromCommandLine(command_line
, current_directory
, &path
)) {
347 LaunchPlatformAppWithNoData(profile
, extension
);
351 // TODO(benwells): add a command-line argument to provide a handler ID.
352 LaunchPlatformAppWithPath(profile
, extension
, path
);
355 void LaunchPlatformAppWithPath(Profile
* profile
,
356 const Extension
* extension
,
357 const base::FilePath
& file_path
) {
358 // launcher will be freed when nothing has a reference to it. The message
359 // queue will retain a reference for any outstanding task, so when the
360 // launcher has finished it will be freed.
361 scoped_refptr
<PlatformAppPathLauncher
> launcher
=
362 new PlatformAppPathLauncher(profile
, extension
, file_path
);
366 void LaunchPlatformApp(Profile
* profile
, const Extension
* extension
) {
367 LaunchPlatformAppWithCommandLine(profile
,
369 CommandLine(CommandLine::NO_PROGRAM
),
373 void LaunchPlatformAppWithFileHandler(Profile
* profile
,
374 const Extension
* extension
,
375 const std::string
& handler_id
,
376 const base::FilePath
& file_path
) {
377 scoped_refptr
<PlatformAppPathLauncher
> launcher
=
378 new PlatformAppPathLauncher(profile
, extension
, file_path
);
379 launcher
->LaunchWithHandler(handler_id
);
382 void RestartPlatformApp(Profile
* profile
, const Extension
* extension
) {
383 EventRouter
* event_router
= EventRouter::Get(profile
);
384 bool listening_to_restart
= event_router
->
385 ExtensionHasEventListener(extension
->id(),
386 app_runtime::OnRestarted::kEventName
);
388 if (listening_to_restart
) {
389 AppEventRouter::DispatchOnRestartedEvent(profile
, extension
);
393 extensions::ExtensionPrefs
* extension_prefs
=
394 extensions::ExtensionPrefs::Get(profile
);
395 bool had_windows
= extension_prefs
->IsActive(extension
->id());
396 extension_prefs
->SetIsActive(extension
->id(), false);
397 bool listening_to_launch
= event_router
->
398 ExtensionHasEventListener(extension
->id(),
399 app_runtime::OnLaunched::kEventName
);
401 if (listening_to_launch
&& had_windows
)
402 LaunchPlatformAppWithNoData(profile
, extension
);
405 void LaunchPlatformAppWithUrl(Profile
* profile
,
406 const Extension
* extension
,
407 const std::string
& handler_id
,
409 const GURL
& referrer_url
) {
410 AppEventRouter::DispatchOnLaunchedEventWithUrl(
411 profile
, extension
, handler_id
, url
, referrer_url
);