platform_util_linux.cc 13 KB

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