platform_util_linux.cc 13 KB

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