platform_util_linux.cc 13 KB

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