fixup! Fix for Geolocation webTCT failures
[platform/framework/web/chromium-efl.git] / apps / launcher.cc
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.
4
5 #include "apps/launcher.h"
6
7 #include <memory>
8 #include <set>
9 #include <utility>
10
11 #include "base/command_line.h"
12 #include "base/files/file_path.h"
13 #include "base/files/file_util.h"
14 #include "base/functional/bind.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"
52 #include "url/gurl.h"
53
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"
58 #endif
59
60 namespace app_runtime = extensions::api::app_runtime;
61
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;
74
75 namespace apps {
76
77 namespace {
78
79 bool DoMakePathAbsolute(const base::FilePath& current_directory,
80                         base::FilePath* file_path) {
81   DCHECK(file_path);
82   if (file_path->IsAbsolute())
83     return true;
84
85   if (current_directory.empty()) {
86     base::FilePath absolute_path = base::MakeAbsoluteFilePath(*file_path);
87     if (absolute_path.empty())
88       return false;
89     *file_path = absolute_path;
90     return true;
91   }
92
93   if (!current_directory.IsAbsolute())
94     return false;
95
96   *file_path = current_directory.Append(*file_path);
97   return true;
98 }
99
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> {
107  public:
108   PlatformAppPathLauncher(content::BrowserContext* context,
109                           const Extension* app,
110                           const std::vector<base::FilePath>& entry_paths)
111       : context_(context),
112         extension_id(app->id()),
113         entry_paths_(entry_paths),
114         mime_type_collector_(context),
115         is_directory_collector_(context) {}
116
117   PlatformAppPathLauncher(content::BrowserContext* context,
118                           const Extension* app,
119                           const base::FilePath& file_path)
120       : context_(context),
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);
126   }
127   PlatformAppPathLauncher(const PlatformAppPathLauncher&) = delete;
128   PlatformAppPathLauncher& operator=(const PlatformAppPathLauncher&) = delete;
129
130   void set_action_data(absl::optional<app_runtime::ActionData> action_data) {
131     action_data_ = std::move(action_data);
132   }
133
134   void set_launch_source(extensions::AppLaunchSource launch_source) {
135     launch_source_ = launch_source;
136   }
137
138   void Launch() {
139     DCHECK_CURRENTLY_ON(BrowserThread::UI);
140
141     const Extension* app = GetExtension();
142     if (!app)
143       return;
144
145     if (entry_paths_.empty()) {
146       LaunchWithBasicData();
147       return;
148     }
149
150     for (size_t i = 0; i < entry_paths_.size(); ++i) {
151       DCHECK(entry_paths_[i].IsAbsolute());
152     }
153
154     is_directory_collector_.CollectForEntriesPaths(
155         entry_paths_,
156         base::BindOnce(&PlatformAppPathLauncher::OnAreDirectoriesCollected,
157                        this, HasFileSystemWritePermission(app)));
158   }
159
160   void LaunchWithHandler(const std::string& handler_id) {
161     handler_id_ = handler_id;
162     Launch();
163   }
164
165   void LaunchWithRelativePath(const base::FilePath& current_directory) {
166     base::ThreadPool::PostTask(
167         FROM_HERE,
168         {base::TaskPriority::USER_VISIBLE, base::MayBlock(),
169          base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
170         base::BindOnce(&PlatformAppPathLauncher::MakePathAbsolute, this,
171                        current_directory));
172   }
173
174  private:
175   friend class base::RefCountedThreadSafe<PlatformAppPathLauncher>;
176
177   virtual ~PlatformAppPathLauncher() = default;
178
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(
185             FROM_HERE,
186             base::BindOnce(&PlatformAppPathLauncher::LaunchWithBasicData,
187                            this));
188         return;
189       }
190     }
191
192     content::GetUIThreadTaskRunner({})->PostTask(
193         FROM_HERE, base::BindOnce(&PlatformAppPathLauncher::Launch, this));
194   }
195
196   void OnFilesValid(std::unique_ptr<std::set<base::FilePath>> directory_paths) {
197     mime_type_collector_.CollectForLocalPaths(
198         entry_paths_,
199         base::BindOnce(
200             &PlatformAppPathLauncher::OnAreDirectoriesAndMimeTypesCollected,
201             this, std::move(directory_paths)));
202   }
203
204   void OnFilesInvalid(const base::FilePath& /* error_path */) {
205     LaunchWithBasicData();
206   }
207
208   void LaunchWithBasicData() {
209     // This method is required as an entry point on the UI thread.
210     DCHECK_CURRENTLY_ON(BrowserThread::UI);
211
212     const Extension* app = GetExtension();
213     if (!app)
214       return;
215
216     app_runtime::LaunchData launch_data;
217
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>.
221     if (action_data_) {
222       launch_data.action_data = std::move(*action_data_);
223       action_data_.reset();
224     }
225     if (!handler_id_.empty())
226       launch_data.id = handler_id_;
227
228     AppRuntimeEventRouter::DispatchOnLaunchedEvent(
229         context_, app, launch_source_, std::move(launch_data));
230   }
231
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));
243       return;
244     }
245
246     OnFilesValid(std::move(directory_paths));
247   }
248
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);
254
255     const Extension* app = GetExtension();
256     if (!app)
257       return;
258
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_);
263       if (handler) {
264         for (size_t i = 0; i < entry_paths_.size(); ++i) {
265           if (!FileHandlerCanHandleEntry(*handler, entries_[i])) {
266             LOG(WARNING)
267                 << "Extension does not provide a valid file handler for "
268                 << entry_paths_[i].value();
269             handler = nullptr;
270             break;
271           }
272         }
273       }
274     } else {
275       const std::vector<extensions::FileHandlerMatch> handlers =
276           extensions::app_file_handler_util::FindFileHandlerMatchesForEntries(
277               *app, entries_);
278       if (!handlers.empty())
279         handler = handlers[0].handler;
280     }
281
282     // If this app doesn't have a file handler that supports the file, launch
283     // with no launch data.
284     if (!handler) {
285       LOG(WARNING) << "Extension does not provide a valid file handler.";
286       LaunchWithBasicData();
287       return;
288     }
289
290     if (handler_id_.empty())
291       handler_id_ = handler->id;
292
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
297     // call back to us.
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(
302           context_id,
303           base::BindOnce(&PlatformAppPathLauncher::GrantAccessToFilesAndLaunch,
304                          this));
305       return;
306     }
307
308     extensions::ProcessManager* const process_manager =
309         extensions::ProcessManager::Get(context_);
310     ExtensionHost* const host =
311         process_manager->GetBackgroundHostForExtension(extension_id);
312     DCHECK(host);
313     GrantAccessToFilesAndLaunch(
314         std::make_unique<extensions::LazyContextTaskQueue::ContextInfo>(host));
315   }
316
317   void GrantAccessToFilesAndLaunch(
318       std::unique_ptr<extensions::LazyContextTaskQueue::ContextInfo>
319           context_info) {
320     const Extension* app = GetExtension();
321     if (!app)
322       return;
323
324     // If there was an error loading the app page, |context_info| will be NULL.
325     if (!context_info) {
326       LOG(ERROR) << "Could not load app page for " << extension_id;
327       return;
328     }
329
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));
335     }
336
337     AppRuntimeEventRouter::DispatchOnLaunchedEventWithFileEntries(
338         context_, app, launch_source_, handler_id_, entries_, granted_entries,
339         std::move(action_data_));
340   }
341
342   const Extension* GetExtension() const {
343     return extensions::ExtensionRegistry::Get(context_)->GetExtensionById(
344         extension_id, extensions::ExtensionRegistry::EVERYTHING);
345   }
346
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
351   // the launch.
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
359   // entry_paths_.
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_;
366 };
367
368 }  // namespace
369
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);
377 }
378
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();
394 #endif
395     if (!in_kiosk_mode) {
396       LOG(ERROR) << "App with 'kiosk_only' attribute must be run in "
397                  << " ChromeOS kiosk mode.";
398       NOTREACHED();
399       return;
400     }
401   }
402
403 #if BUILDFLAG(IS_WIN)
404   base::CommandLine::StringType about_blank_url(
405       base::ASCIIToWide(url::kAboutBlankURL));
406 #else
407   base::CommandLine::StringType about_blank_url(url::kAboutBlankURL);
408 #endif
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));
421     return;
422   }
423
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);
428 }
429
430 void LaunchPlatformAppWithPath(content::BrowserContext* context,
431                                const Extension* app,
432                                const base::FilePath& file_path) {
433   auto launcher =
434       base::MakeRefCounted<PlatformAppPathLauncher>(context, app, file_path);
435   launcher->Launch();
436 }
437
438 void LaunchPlatformAppWithFilePaths(
439     content::BrowserContext* context,
440     const extensions::Extension* app,
441     const std::vector<base::FilePath>& file_paths) {
442   auto launcher =
443       base::MakeRefCounted<PlatformAppPathLauncher>(context, app, file_paths);
444   launcher->Launch();
445 }
446
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.";
455
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);
460   launcher->Launch();
461 }
462
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);
469 }
470
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));
480 #endif
481
482   scoped_refptr<PlatformAppPathLauncher> launcher =
483       new PlatformAppPathLauncher(context, app, entry_paths);
484   launcher->LaunchWithHandler(handler_id);
485 }
486
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);
492
493   if (listening_to_restart) {
494     AppRuntimeEventRouter::DispatchOnRestartedEvent(context, app);
495     return;
496   }
497
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);
504
505   if (listening_to_launch && had_windows) {
506     AppRuntimeEventRouter::DispatchOnLaunchedEvent(
507         context, app, extensions::AppLaunchSource::kSourceRestart,
508         absl::nullopt);
509   }
510 }
511
512 void LaunchPlatformAppWithUrl(content::BrowserContext* context,
513                               const Extension* app,
514                               const std::string& handler_id,
515                               const GURL& url,
516                               const GURL& referrer_url) {
517   AppRuntimeEventRouter::DispatchOnLaunchedEventWithUrl(
518       context, app, handler_id, url, referrer_url);
519 }
520
521 }  // namespace apps