platform_util_linux.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. // Copyright (c) 2013 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "shell/common/platform_util.h"
  5. #include <fcntl.h>
  6. #include <stdio.h>
  7. #include <optional>
  8. #include <string>
  9. #include <vector>
  10. #include <gdk/gdk.h>
  11. #include "base/cancelable_callback.h"
  12. #include "base/containers/contains.h"
  13. #include "base/environment.h"
  14. #include "base/files/file_util.h"
  15. #include "base/files/scoped_file.h"
  16. #include "base/logging.h"
  17. #include "base/memory/raw_ptr.h"
  18. #include "base/nix/xdg_util.h"
  19. #include "base/no_destructor.h"
  20. #include "base/posix/eintr_wrapper.h"
  21. #include "base/process/kill.h"
  22. #include "base/process/launch.h"
  23. #include "base/run_loop.h"
  24. #include "base/strings/escape.h"
  25. #include "base/strings/string_util.h"
  26. #include "base/threading/thread_restrictions.h"
  27. #include "components/dbus/thread_linux/dbus_thread_linux.h"
  28. #include "content/public/browser/browser_thread.h"
  29. #include "dbus/bus.h"
  30. #include "dbus/message.h"
  31. #include "dbus/object_proxy.h"
  32. #include "shell/common/platform_util_internal.h"
  33. #include "url/gurl.h"
  34. #define ELECTRON_TRASH "ELECTRON_TRASH"
  35. namespace platform_util {
  36. void OpenFolder(const base::FilePath& full_path);
  37. }
  38. namespace {
  39. const char kMethodListActivatableNames[] = "ListActivatableNames";
  40. const char kMethodNameHasOwner[] = "NameHasOwner";
  41. const char kFreedesktopFileManagerName[] = "org.freedesktop.FileManager1";
  42. const char kFreedesktopFileManagerPath[] = "/org/freedesktop/FileManager1";
  43. const char kMethodShowItems[] = "ShowItems";
  44. const char kFreedesktopPortalName[] = "org.freedesktop.portal.Desktop";
  45. const char kFreedesktopPortalPath[] = "/org/freedesktop/portal/desktop";
  46. const char kFreedesktopPortalOpenURI[] = "org.freedesktop.portal.OpenURI";
  47. const char kMethodOpenDirectory[] = "OpenDirectory";
  48. class ShowItemHelper {
  49. public:
  50. static ShowItemHelper& GetInstance() {
  51. static base::NoDestructor<ShowItemHelper> instance;
  52. return *instance;
  53. }
  54. ShowItemHelper() = default;
  55. ShowItemHelper(const ShowItemHelper&) = delete;
  56. ShowItemHelper& operator=(const ShowItemHelper&) = delete;
  57. void ShowItemInFolder(const base::FilePath& full_path) {
  58. if (!bus_) {
  59. // Sets up the D-Bus connection.
  60. dbus::Bus::Options bus_options;
  61. bus_options.bus_type = dbus::Bus::SESSION;
  62. bus_options.connection_type = dbus::Bus::PRIVATE;
  63. bus_options.dbus_task_runner = dbus_thread_linux::GetTaskRunner();
  64. bus_ = base::MakeRefCounted<dbus::Bus>(bus_options);
  65. }
  66. if (!dbus_proxy_) {
  67. dbus_proxy_ = bus_->GetObjectProxy(DBUS_SERVICE_DBUS,
  68. dbus::ObjectPath(DBUS_PATH_DBUS));
  69. }
  70. if (prefer_filemanager_interface_.has_value()) {
  71. if (prefer_filemanager_interface_.value()) {
  72. ShowItemUsingFileManager(full_path);
  73. } else {
  74. ShowItemUsingFreedesktopPortal(full_path);
  75. }
  76. } else {
  77. CheckFileManagerRunning(full_path);
  78. }
  79. }
  80. private:
  81. void CheckFileManagerRunning(const base::FilePath& full_path) {
  82. dbus::MethodCall method_call(DBUS_INTERFACE_DBUS, kMethodNameHasOwner);
  83. dbus::MessageWriter writer(&method_call);
  84. writer.AppendString(kFreedesktopFileManagerName);
  85. dbus_proxy_->CallMethod(
  86. &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
  87. base::BindOnce(&ShowItemHelper::CheckFileManagerRunningResponse,
  88. base::Unretained(this), full_path));
  89. }
  90. void CheckFileManagerRunningResponse(const base::FilePath& full_path,
  91. dbus::Response* response) {
  92. if (prefer_filemanager_interface_.has_value()) {
  93. ShowItemInFolder(full_path);
  94. return;
  95. }
  96. bool is_running = false;
  97. if (!response) {
  98. LOG(ERROR) << "Failed to call " << kMethodNameHasOwner;
  99. } else {
  100. dbus::MessageReader reader(response);
  101. bool owned = false;
  102. if (!reader.PopBool(&owned)) {
  103. LOG(ERROR) << "Failed to read " << kMethodNameHasOwner << " response";
  104. } else if (owned) {
  105. is_running = true;
  106. }
  107. }
  108. if (is_running) {
  109. prefer_filemanager_interface_ = true;
  110. ShowItemInFolder(full_path);
  111. } else {
  112. CheckFileManagerActivatable(full_path);
  113. }
  114. }
  115. void CheckFileManagerActivatable(const base::FilePath& full_path) {
  116. dbus::MethodCall method_call(DBUS_INTERFACE_DBUS,
  117. kMethodListActivatableNames);
  118. dbus_proxy_->CallMethod(
  119. &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
  120. base::BindOnce(&ShowItemHelper::CheckFileManagerActivatableResponse,
  121. base::Unretained(this), full_path));
  122. }
  123. void CheckFileManagerActivatableResponse(const base::FilePath& full_path,
  124. dbus::Response* response) {
  125. if (prefer_filemanager_interface_.has_value()) {
  126. ShowItemInFolder(full_path);
  127. return;
  128. }
  129. bool is_activatable = false;
  130. if (!response) {
  131. LOG(ERROR) << "Failed to call " << kMethodListActivatableNames;
  132. } else {
  133. dbus::MessageReader reader(response);
  134. std::vector<std::string> names;
  135. if (!reader.PopArrayOfStrings(&names)) {
  136. LOG(ERROR) << "Failed to read " << kMethodListActivatableNames
  137. << " response";
  138. } else if (base::Contains(names, kFreedesktopFileManagerName)) {
  139. is_activatable = true;
  140. }
  141. }
  142. prefer_filemanager_interface_ = is_activatable;
  143. ShowItemInFolder(full_path);
  144. }
  145. void ShowItemUsingFreedesktopPortal(const base::FilePath& full_path) {
  146. if (!object_proxy_) {
  147. object_proxy_ = bus_->GetObjectProxy(
  148. kFreedesktopPortalName, dbus::ObjectPath(kFreedesktopPortalPath));
  149. }
  150. base::ScopedFD fd(
  151. HANDLE_EINTR(open(full_path.value().c_str(), O_RDONLY | O_CLOEXEC)));
  152. if (!fd.is_valid()) {
  153. LOG(ERROR) << "Failed to open " << full_path << " for URI portal";
  154. // If the call fails, at least open the parent folder.
  155. platform_util::OpenFolder(full_path.DirName());
  156. return;
  157. }
  158. dbus::MethodCall open_directory_call(kFreedesktopPortalOpenURI,
  159. kMethodOpenDirectory);
  160. dbus::MessageWriter writer(&open_directory_call);
  161. writer.AppendString("");
  162. // Note that AppendFileDescriptor() duplicates the fd, so we shouldn't
  163. // release ownership of it here.
  164. writer.AppendFileDescriptor(fd.get());
  165. dbus::MessageWriter options_writer(nullptr);
  166. writer.OpenArray("{sv}", &options_writer);
  167. writer.CloseContainer(&options_writer);
  168. ShowItemUsingBusCall(&open_directory_call, full_path);
  169. }
  170. void ShowItemUsingFileManager(const base::FilePath& full_path) {
  171. if (!object_proxy_) {
  172. object_proxy_ =
  173. bus_->GetObjectProxy(kFreedesktopFileManagerName,
  174. dbus::ObjectPath(kFreedesktopFileManagerPath));
  175. }
  176. dbus::MethodCall show_items_call(kFreedesktopFileManagerName,
  177. kMethodShowItems);
  178. dbus::MessageWriter writer(&show_items_call);
  179. writer.AppendArrayOfStrings(
  180. {"file://" + base::EscapePath(
  181. full_path.value())}); // List of file(s) to highlight.
  182. writer.AppendString({}); // startup-id
  183. ShowItemUsingBusCall(&show_items_call, full_path);
  184. }
  185. void ShowItemUsingBusCall(dbus::MethodCall* call,
  186. const base::FilePath& full_path) {
  187. object_proxy_->CallMethod(
  188. call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
  189. base::BindOnce(&ShowItemHelper::ShowItemInFolderResponse,
  190. base::Unretained(this), full_path, call->GetMember()));
  191. }
  192. void ShowItemInFolderResponse(const base::FilePath& full_path,
  193. const std::string& method,
  194. dbus::Response* response) {
  195. if (response)
  196. return;
  197. LOG(ERROR) << "Error calling " << method;
  198. // If the bus call fails, at least open the parent folder.
  199. platform_util::OpenFolder(full_path.DirName());
  200. }
  201. scoped_refptr<dbus::Bus> bus_;
  202. raw_ptr<dbus::ObjectProxy> dbus_proxy_ = nullptr;
  203. raw_ptr<dbus::ObjectProxy> object_proxy_ = nullptr;
  204. std::optional<bool> prefer_filemanager_interface_;
  205. };
  206. // Descriptions pulled from https://linux.die.net/man/1/xdg-open
  207. std::string GetErrorDescription(int error_code) {
  208. switch (error_code) {
  209. case 1:
  210. return "Error in command line syntax";
  211. case 2:
  212. return "The item does not exist";
  213. case 3:
  214. return "A required tool could not be found";
  215. case 4:
  216. return "The action failed";
  217. default:
  218. return "";
  219. }
  220. }
  221. bool XDGUtil(const std::vector<std::string>& argv,
  222. const base::FilePath& working_directory,
  223. const bool wait_for_exit,
  224. const bool focus_launched_process,
  225. platform_util::OpenCallback callback) {
  226. base::LaunchOptions options;
  227. if (focus_launched_process) {
  228. base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed);
  229. base::RepeatingClosure quit_loop = run_loop.QuitClosure();
  230. base::nix::CreateLaunchOptionsWithXdgActivation(base::BindOnce(
  231. [](base::RepeatingClosure quit_loop, base::LaunchOptions* options_out,
  232. base::LaunchOptions options) {
  233. *options_out = std::move(options);
  234. std::move(quit_loop).Run();
  235. },
  236. std::move(quit_loop), &options));
  237. run_loop.Run();
  238. }
  239. options.current_directory = working_directory;
  240. options.allow_new_privs = true;
  241. // xdg-open can fall back on mailcap which eventually might plumb through
  242. // to a command that needs a terminal. Set the environment variable telling
  243. // it that we definitely don't have a terminal available and that it should
  244. // bring up a new terminal if necessary. See "man mailcap".
  245. options.environment["MM_NOTTTY"] = "1";
  246. base::Process process = base::LaunchProcess(argv, options);
  247. if (!process.IsValid())
  248. return false;
  249. if (wait_for_exit) {
  250. base::ScopedAllowBaseSyncPrimitivesForTesting
  251. allow_sync; // required by WaitForExit
  252. int exit_code = -1;
  253. bool success = process.WaitForExit(&exit_code);
  254. if (!callback.is_null())
  255. std::move(callback).Run(GetErrorDescription(exit_code));
  256. return success ? (exit_code == 0) : false;
  257. }
  258. base::EnsureProcessGetsReaped(std::move(process));
  259. return true;
  260. }
  261. bool XDGOpen(const base::FilePath& working_directory,
  262. const std::string& path,
  263. const bool wait_for_exit,
  264. platform_util::OpenCallback callback) {
  265. return XDGUtil({"xdg-open", path}, working_directory, wait_for_exit,
  266. /*focus_launched_process=*/true, std::move(callback));
  267. }
  268. bool XDGEmail(const std::string& email, const bool wait_for_exit) {
  269. return XDGUtil({"xdg-email", email}, base::FilePath(), wait_for_exit,
  270. /*focus_launched_process=*/true,
  271. platform_util::OpenCallback());
  272. }
  273. } // namespace
  274. namespace platform_util {
  275. void ShowItemInFolder(const base::FilePath& full_path) {
  276. DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  277. ShowItemHelper::GetInstance().ShowItemInFolder(full_path);
  278. }
  279. void OpenPath(const base::FilePath& full_path, OpenCallback callback) {
  280. // This is async, so we don't care about the return value.
  281. XDGOpen(full_path.DirName(), full_path.value(), true, std::move(callback));
  282. }
  283. void OpenFolder(const base::FilePath& full_path) {
  284. if (!base::DirectoryExists(full_path))
  285. return;
  286. XDGOpen(full_path.DirName(), ".", false, platform_util::OpenCallback());
  287. }
  288. void OpenExternal(const GURL& url,
  289. const OpenExternalOptions& options,
  290. OpenCallback callback) {
  291. // Don't wait for exit, since we don't want to wait for the browser/email
  292. // client window to close before returning
  293. if (url.SchemeIs("mailto")) {
  294. bool success = XDGEmail(url.spec(), false);
  295. std::move(callback).Run(success ? "" : "Failed to open path");
  296. } else {
  297. bool success = XDGOpen(base::FilePath(), url.spec(), false,
  298. platform_util::OpenCallback());
  299. std::move(callback).Run(success ? "" : "Failed to open path");
  300. }
  301. }
  302. bool MoveItemToTrash(const base::FilePath& full_path, bool delete_on_fail) {
  303. auto env = base::Environment::Create();
  304. // find the trash method
  305. std::string trash;
  306. if (!env->GetVar(ELECTRON_TRASH, &trash)) {
  307. // Determine desktop environment and set accordingly.
  308. const auto desktop_env(base::nix::GetDesktopEnvironment(env.get()));
  309. if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE4 ||
  310. desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE5) {
  311. trash = "kioclient5";
  312. } else if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE3) {
  313. trash = "kioclient";
  314. }
  315. }
  316. // build the invocation
  317. std::vector<std::string> argv;
  318. const auto& filename = full_path.value();
  319. if (trash == "kioclient5" || trash == "kioclient") {
  320. argv = {trash, "move", filename, "trash:/"};
  321. } else if (trash == "trash-cli") {
  322. argv = {"trash-put", filename};
  323. } else if (trash == "gvfs-trash") {
  324. argv = {"gvfs-trash", filename}; // deprecated, but still exists
  325. } else {
  326. argv = {"gio", "trash", filename};
  327. }
  328. return XDGUtil(argv, base::FilePath(), true, /*focus_launched_process=*/false,
  329. platform_util::OpenCallback());
  330. }
  331. namespace internal {
  332. bool PlatformTrashItem(const base::FilePath& full_path, std::string* error) {
  333. if (!MoveItemToTrash(full_path, false)) {
  334. // TODO(nornagon): at least include the exit code?
  335. *error = "Failed to move item to trash";
  336. return false;
  337. }
  338. return true;
  339. }
  340. } // namespace internal
  341. void Beep() {
  342. auto* display = gdk_display_get_default();
  343. gdk_display_beep(display);
  344. }
  345. bool GetDesktopName(std::string* setme) {
  346. return base::Environment::Create()->GetVar("CHROME_DESKTOP", setme);
  347. }
  348. std::string GetXdgAppId() {
  349. std::string desktop_file_name;
  350. if (GetDesktopName(&desktop_file_name)) {
  351. const std::string kDesktopExtension{".desktop"};
  352. if (base::EndsWith(desktop_file_name, kDesktopExtension,
  353. base::CompareCase::INSENSITIVE_ASCII)) {
  354. desktop_file_name.resize(desktop_file_name.size() -
  355. kDesktopExtension.size());
  356. }
  357. }
  358. return desktop_file_name;
  359. }
  360. } // namespace platform_util