platform_util_linux.cc 13 KB

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