1 // Copyright 2013 The Chromium Authors
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"
11 #include "base/bind.h"
12 #include "base/command_line.h"
13 #include "base/files/file_path.h"
14 #include "base/files/file_util.h"
15 #include "base/logging.h"
16 #include "base/memory/raw_ptr.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/notreached.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/task/task_traits.h"
22 #include "base/task/thread_pool.h"
23 #include "build/build_config.h"
24 #include "build/chromeos_buildflags.h"
25 #include "components/services/app_service/public/cpp/file_handler_info.h"
26 #include "content/public/browser/browser_context.h"
27 #include "content/public/browser/browser_task_traits.h"
28 #include "content/public/browser/browser_thread.h"
29 #include "content/public/browser/render_process_host.h"
30 #include "content/public/browser/web_contents.h"
31 #include "content/public/common/content_switches.h"
32 #include "content/public/common/url_constants.h"
33 #include "extensions/browser/api/app_runtime/app_runtime_api.h"
34 #include "extensions/browser/api/file_handlers/app_file_handler_util.h"
35 #include "extensions/browser/api/file_handlers/directory_util.h"
36 #include "extensions/browser/api/file_handlers/mime_util.h"
37 #include "extensions/browser/entry_info.h"
38 #include "extensions/browser/event_router.h"
39 #include "extensions/browser/extension_host.h"
40 #include "extensions/browser/extension_prefs.h"
41 #include "extensions/browser/extension_registry.h"
42 #include "extensions/browser/granted_file_entry.h"
43 #include "extensions/browser/lazy_context_id.h"
44 #include "extensions/browser/lazy_context_task_queue.h"
45 #include "extensions/browser/process_manager.h"
46 #include "extensions/common/api/app_runtime.h"
47 #include "extensions/common/extension.h"
48 #include "extensions/common/manifest_handlers/kiosk_mode_info.h"
49 #include "extensions/common/permissions/api_permission.h"
50 #include "extensions/common/permissions/permissions_data.h"
51 #include "net/base/filename_util.h"
54 #if BUILDFLAG(IS_CHROMEOS_ASH)
55 #include "components/app_restore/app_launch_info.h"
56 #include "components/app_restore/full_restore_utils.h"
57 #include "components/user_manager/user_manager.h"
60 namespace app_runtime = extensions::api::app_runtime;
62 using content::BrowserThread;
63 using extensions::AppRuntimeEventRouter;
64 using extensions::EventRouter;
65 using extensions::Extension;
66 using extensions::ExtensionHost;
67 using extensions::GrantedFileEntry;
68 using extensions::app_file_handler_util::CreateEntryInfos;
69 using extensions::app_file_handler_util::CreateFileEntry;
70 using extensions::app_file_handler_util::FileHandlerCanHandleEntry;
71 using extensions::app_file_handler_util::FileHandlerForId;
72 using extensions::app_file_handler_util::HasFileSystemWritePermission;
73 using extensions::app_file_handler_util::PrepareFilesForWritableApp;
79 bool DoMakePathAbsolute(const base::FilePath& current_directory,
80 base::FilePath* file_path) {
82 if (file_path->IsAbsolute())
85 if (current_directory.empty()) {
86 base::FilePath absolute_path = base::MakeAbsoluteFilePath(*file_path);
87 if (absolute_path.empty())
89 *file_path = absolute_path;
93 if (!current_directory.IsAbsolute())
96 *file_path = current_directory.Append(*file_path);
100 // Class to handle launching of platform apps to open specific paths.
101 // An instance of this class is created for each launch. The lifetime of these
102 // instances is managed by reference counted pointers. As long as an instance
103 // has outstanding tasks on a message queue it will be retained; once all
104 // outstanding tasks are completed it will be deleted.
105 class PlatformAppPathLauncher
106 : public base::RefCountedThreadSafe<PlatformAppPathLauncher> {
108 PlatformAppPathLauncher(content::BrowserContext* context,
109 const Extension* app,
110 const std::vector<base::FilePath>& entry_paths)
112 extension_id(app->id()),
113 entry_paths_(entry_paths),
114 mime_type_collector_(context),
115 is_directory_collector_(context) {}
117 PlatformAppPathLauncher(content::BrowserContext* context,
118 const Extension* app,
119 const base::FilePath& file_path)
121 extension_id(app->id()),
122 mime_type_collector_(context),
123 is_directory_collector_(context) {
124 if (!file_path.empty())
125 entry_paths_.push_back(file_path);
127 PlatformAppPathLauncher(const PlatformAppPathLauncher&) = delete;
128 PlatformAppPathLauncher& operator=(const PlatformAppPathLauncher&) = delete;
130 void set_action_data(absl::optional<app_runtime::ActionData> action_data) {
131 action_data_ = std::move(action_data);
134 void set_launch_source(extensions::AppLaunchSource launch_source) {
135 launch_source_ = launch_source;
139 DCHECK_CURRENTLY_ON(BrowserThread::UI);
141 const Extension* app = GetExtension();
145 if (entry_paths_.empty()) {
146 LaunchWithBasicData();
150 for (size_t i = 0; i < entry_paths_.size(); ++i) {
151 DCHECK(entry_paths_[i].IsAbsolute());
154 is_directory_collector_.CollectForEntriesPaths(
156 base::BindOnce(&PlatformAppPathLauncher::OnAreDirectoriesCollected,
157 this, HasFileSystemWritePermission(app)));
160 void LaunchWithHandler(const std::string& handler_id) {
161 handler_id_ = handler_id;
165 void LaunchWithRelativePath(const base::FilePath& current_directory) {
166 base::ThreadPool::PostTask(
168 {base::TaskPriority::USER_VISIBLE, base::MayBlock(),
169 base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
170 base::BindOnce(&PlatformAppPathLauncher::MakePathAbsolute, this,
175 friend class base::RefCountedThreadSafe<PlatformAppPathLauncher>;
177 virtual ~PlatformAppPathLauncher() = default;
179 void MakePathAbsolute(const base::FilePath& current_directory) {
180 for (std::vector<base::FilePath>::iterator it = entry_paths_.begin();
181 it != entry_paths_.end(); ++it) {
182 if (!DoMakePathAbsolute(current_directory, &*it)) {
183 LOG(WARNING) << "Cannot make absolute path from " << it->value();
184 content::GetUIThreadTaskRunner({})->PostTask(
186 base::BindOnce(&PlatformAppPathLauncher::LaunchWithBasicData,
192 content::GetUIThreadTaskRunner({})->PostTask(
193 FROM_HERE, base::BindOnce(&PlatformAppPathLauncher::Launch, this));
196 void OnFilesValid(std::unique_ptr<std::set<base::FilePath>> directory_paths) {
197 mime_type_collector_.CollectForLocalPaths(
200 &PlatformAppPathLauncher::OnAreDirectoriesAndMimeTypesCollected,
201 this, std::move(directory_paths)));
204 void OnFilesInvalid(const base::FilePath& /* error_path */) {
205 LaunchWithBasicData();
208 void LaunchWithBasicData() {
209 // This method is required as an entry point on the UI thread.
210 DCHECK_CURRENTLY_ON(BrowserThread::UI);
212 const Extension* app = GetExtension();
216 app_runtime::LaunchData launch_data;
218 // TODO(crbug.com/1354063): This conditional block is being added here
219 // temporarily, and should be removed once the underlying type of
220 // |launch_data.action_data| is wrapped with absl::optional<T>.
222 launch_data.action_data = std::move(*action_data_);
223 action_data_.reset();
225 if (!handler_id_.empty())
226 launch_data.id = handler_id_;
228 AppRuntimeEventRouter::DispatchOnLaunchedEvent(
229 context_, app, launch_source_, std::move(launch_data));
232 void OnAreDirectoriesCollected(
233 bool has_file_system_write_permission,
234 std::unique_ptr<std::set<base::FilePath>> directory_paths) {
235 if (has_file_system_write_permission) {
236 std::set<base::FilePath>* const directory_paths_ptr =
237 directory_paths.get();
238 PrepareFilesForWritableApp(
239 entry_paths_, context_, *directory_paths_ptr,
240 base::BindOnce(&PlatformAppPathLauncher::OnFilesValid, this,
241 std::move(directory_paths)),
242 base::BindOnce(&PlatformAppPathLauncher::OnFilesInvalid, this));
246 OnFilesValid(std::move(directory_paths));
249 void OnAreDirectoriesAndMimeTypesCollected(
250 std::unique_ptr<std::set<base::FilePath>> directory_paths,
251 std::unique_ptr<std::vector<std::string>> mime_types) {
252 // If mime type fetch fails then the following provides a fallback.
253 entries_ = CreateEntryInfos(entry_paths_, *mime_types, *directory_paths);
255 const Extension* app = GetExtension();
259 // Find file handler from the platform app for the file being opened.
260 const FileHandlerInfo* handler = nullptr;
261 if (!handler_id_.empty()) {
262 handler = FileHandlerForId(*app, handler_id_);
264 for (size_t i = 0; i < entry_paths_.size(); ++i) {
265 if (!FileHandlerCanHandleEntry(*handler, entries_[i])) {
267 << "Extension does not provide a valid file handler for "
268 << entry_paths_[i].value();
275 const std::vector<extensions::FileHandlerMatch> handlers =
276 extensions::app_file_handler_util::FindFileHandlerMatchesForEntries(
278 if (!handlers.empty())
279 handler = handlers[0].handler;
282 // If this app doesn't have a file handler that supports the file, launch
283 // with no launch data.
285 LOG(WARNING) << "Extension does not provide a valid file handler.";
286 LaunchWithBasicData();
290 if (handler_id_.empty())
291 handler_id_ = handler->id;
293 // Access needs to be granted to the file for the process associated with
294 // the extension. To do this the ExtensionHost is needed. This might not be
295 // available, or it might be in the process of being unloaded, in which case
296 // the lazy background task queue is used to load the extension and then
298 const extensions::LazyContextId context_id(context_, extension_id);
299 extensions::LazyContextTaskQueue* const queue = context_id.GetTaskQueue();
300 if (queue->ShouldEnqueueTask(context_, app)) {
301 queue->AddPendingTask(
303 base::BindOnce(&PlatformAppPathLauncher::GrantAccessToFilesAndLaunch,
308 extensions::ProcessManager* const process_manager =
309 extensions::ProcessManager::Get(context_);
310 ExtensionHost* const host =
311 process_manager->GetBackgroundHostForExtension(extension_id);
313 GrantAccessToFilesAndLaunch(
314 std::make_unique<extensions::LazyContextTaskQueue::ContextInfo>(host));
317 void GrantAccessToFilesAndLaunch(
318 std::unique_ptr<extensions::LazyContextTaskQueue::ContextInfo>
320 const Extension* app = GetExtension();
324 // If there was an error loading the app page, |context_info| will be NULL.
326 LOG(ERROR) << "Could not load app page for " << extension_id;
330 std::vector<GrantedFileEntry> granted_entries;
331 for (size_t i = 0; i < entry_paths_.size(); ++i) {
332 granted_entries.push_back(CreateFileEntry(
333 context_, app, context_info->render_process_host->GetID(),
334 entries_[i].path, entries_[i].is_directory));
337 AppRuntimeEventRouter::DispatchOnLaunchedEventWithFileEntries(
338 context_, app, launch_source_, handler_id_, entries_, granted_entries,
339 std::move(action_data_));
342 const Extension* GetExtension() const {
343 return extensions::ExtensionRegistry::Get(context_)->GetExtensionById(
344 extension_id, extensions::ExtensionRegistry::EVERYTHING);
347 // The browser context the app should be run in.
348 raw_ptr<content::BrowserContext> context_;
349 // The id of the extension providing the app. A pointer to the extension is
350 // not kept as the extension may be unloaded and deleted during the course of
352 const std::string extension_id;
353 extensions::AppLaunchSource launch_source_ =
354 extensions::AppLaunchSource::kSourceFileHandler;
355 absl::optional<app_runtime::ActionData> action_data_;
356 // A list of files and directories to be passed through to the app.
357 std::vector<base::FilePath> entry_paths_;
358 // A corresponding list with EntryInfo for every base::FilePath in
360 std::vector<extensions::EntryInfo> entries_;
361 // The ID of the file handler used to launch the app.
362 std::string handler_id_;
363 extensions::app_file_handler_util::MimeTypeCollector mime_type_collector_;
364 extensions::app_file_handler_util::IsDirectoryCollector
365 is_directory_collector_;
370 void LaunchPlatformAppWithCommandLine(content::BrowserContext* context,
371 const extensions::Extension* app,
372 const base::CommandLine& command_line,
373 const base::FilePath& current_directory,
374 extensions::AppLaunchSource source) {
375 LaunchPlatformAppWithCommandLineAndLaunchId(context, app, "", command_line,
376 current_directory, source);
379 void LaunchPlatformAppWithCommandLineAndLaunchId(
380 content::BrowserContext* context,
381 const extensions::Extension* app,
382 const std::string& launch_id,
383 const base::CommandLine& command_line,
384 const base::FilePath& current_directory,
385 extensions::AppLaunchSource source) {
386 // An app with "kiosk_only" should not be installed and launched
387 // outside of ChromeOS kiosk mode in the first place. This is a defensive
388 // check in case this scenario does occur.
389 if (extensions::KioskModeInfo::IsKioskOnly(app)) {
390 bool in_kiosk_mode = false;
391 #if BUILDFLAG(IS_CHROMEOS_ASH)
392 user_manager::UserManager* user_manager = user_manager::UserManager::Get();
393 in_kiosk_mode = user_manager && user_manager->IsLoggedInAsKioskApp();
395 if (!in_kiosk_mode) {
396 LOG(ERROR) << "App with 'kiosk_only' attribute must be run in "
397 << " ChromeOS kiosk mode.";
403 #if BUILDFLAG(IS_WIN)
404 base::CommandLine::StringType about_blank_url(
405 base::ASCIIToWide(url::kAboutBlankURL));
407 base::CommandLine::StringType about_blank_url(url::kAboutBlankURL);
409 base::CommandLine::StringVector args = command_line.GetArgs();
410 // Browser tests will add about:blank to the command line. This should
411 // never be interpreted as a file to open, as doing so with an app that
412 // has write access will result in a file 'about' being created, which
413 // causes problems on the bots.
414 if (args.empty() || (command_line.HasSwitch(switches::kTestType) &&
415 args[0] == about_blank_url)) {
416 app_runtime::LaunchData launch_data;
417 if (!launch_id.empty())
418 launch_data.id = launch_id;
419 AppRuntimeEventRouter::DispatchOnLaunchedEvent(context, app, source,
420 std::move(launch_data));
424 base::FilePath file_path(command_line.GetArgs()[0]);
425 scoped_refptr<PlatformAppPathLauncher> launcher =
426 new PlatformAppPathLauncher(context, app, file_path);
427 launcher->LaunchWithRelativePath(current_directory);
430 void LaunchPlatformAppWithPath(content::BrowserContext* context,
431 const Extension* app,
432 const base::FilePath& file_path) {
434 base::MakeRefCounted<PlatformAppPathLauncher>(context, app, file_path);
438 void LaunchPlatformAppWithFilePaths(
439 content::BrowserContext* context,
440 const extensions::Extension* app,
441 const std::vector<base::FilePath>& file_paths) {
443 base::MakeRefCounted<PlatformAppPathLauncher>(context, app, file_paths);
447 void LaunchPlatformAppWithAction(content::BrowserContext* context,
448 const extensions::Extension* app,
449 app_runtime::ActionData action_data) {
450 CHECK(!action_data.is_lock_screen_action ||
451 !*action_data.is_lock_screen_action ||
452 app->permissions_data()->HasAPIPermission(
453 extensions::mojom::APIPermissionID::kLockScreen))
454 << "Launching lock screen action handler requires lockScreen permission.";
456 scoped_refptr<PlatformAppPathLauncher> launcher =
457 new PlatformAppPathLauncher(context, app, base::FilePath());
458 launcher->set_action_data(std::move(action_data));
459 launcher->set_launch_source(extensions::AppLaunchSource::kSourceUntracked);
463 void LaunchPlatformApp(content::BrowserContext* context,
464 const Extension* app,
465 extensions::AppLaunchSource source) {
466 LaunchPlatformAppWithCommandLine(
467 context, app, base::CommandLine(base::CommandLine::NO_PROGRAM),
468 base::FilePath(), source);
471 void LaunchPlatformAppWithFileHandler(
472 content::BrowserContext* context,
473 const Extension* app,
474 const std::string& handler_id,
475 const std::vector<base::FilePath>& entry_paths) {
476 #if BUILDFLAG(IS_CHROMEOS_ASH)
477 auto launch_info = std::make_unique<app_restore::AppLaunchInfo>(
478 app->id(), handler_id, entry_paths);
479 full_restore::SaveAppLaunchInfo(context->GetPath(), std::move(launch_info));
482 scoped_refptr<PlatformAppPathLauncher> launcher =
483 new PlatformAppPathLauncher(context, app, entry_paths);
484 launcher->LaunchWithHandler(handler_id);
487 void RestartPlatformApp(content::BrowserContext* context,
488 const Extension* app) {
489 EventRouter* event_router = EventRouter::Get(context);
490 bool listening_to_restart = event_router->ExtensionHasEventListener(
491 app->id(), app_runtime::OnRestarted::kEventName);
493 if (listening_to_restart) {
494 AppRuntimeEventRouter::DispatchOnRestartedEvent(context, app);
498 extensions::ExtensionPrefs* extension_prefs =
499 extensions::ExtensionPrefs::Get(context);
500 bool had_windows = extension_prefs->IsActive(app->id());
501 extension_prefs->SetIsActive(app->id(), false);
502 bool listening_to_launch = event_router->ExtensionHasEventListener(
503 app->id(), app_runtime::OnLaunched::kEventName);
505 if (listening_to_launch && had_windows) {
506 AppRuntimeEventRouter::DispatchOnLaunchedEvent(
507 context, app, extensions::AppLaunchSource::kSourceRestart,
512 void LaunchPlatformAppWithUrl(content::BrowserContext* context,
513 const Extension* app,
514 const std::string& handler_id,
516 const GURL& referrer_url) {
517 AppRuntimeEventRouter::DispatchOnLaunchedEventWithUrl(
518 context, app, handler_id, url, referrer_url);