platform_util_linux.cc 13 KB

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