platform_util_linux.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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/run_loop.h"
  23. #include "base/strings/escape.h"
  24. #include "base/strings/string_util.h"
  25. #include "base/threading/thread_restrictions.h"
  26. #include "components/dbus/thread_linux/dbus_thread_linux.h"
  27. #include "content/public/browser/browser_thread.h"
  28. #include "dbus/bus.h"
  29. #include "dbus/message.h"
  30. #include "dbus/object_proxy.h"
  31. #include "shell/common/platform_util_internal.h"
  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. const bool focus_launched_process,
  224. platform_util::OpenCallback callback) {
  225. base::LaunchOptions options;
  226. if (focus_launched_process) {
  227. base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed);
  228. base::RepeatingClosure quit_loop = run_loop.QuitClosure();
  229. base::nix::CreateLaunchOptionsWithXdgActivation(base::BindOnce(
  230. [](base::RepeatingClosure quit_loop, base::LaunchOptions* options_out,
  231. base::LaunchOptions options) {
  232. *options_out = std::move(options);
  233. std::move(quit_loop).Run();
  234. },
  235. std::move(quit_loop), &options));
  236. run_loop.Run();
  237. }
  238. options.current_directory = working_directory;
  239. options.allow_new_privs = true;
  240. // xdg-open can fall back on mailcap which eventually might plumb through
  241. // to a command that needs a terminal. Set the environment variable telling
  242. // it that we definitely don't have a terminal available and that it should
  243. // bring up a new terminal if necessary. See "man mailcap".
  244. options.environment["MM_NOTTTY"] = "1";
  245. base::Process process = base::LaunchProcess(argv, options);
  246. if (!process.IsValid())
  247. return false;
  248. if (wait_for_exit) {
  249. base::ScopedAllowBaseSyncPrimitivesForTesting
  250. allow_sync; // required by WaitForExit
  251. int exit_code = -1;
  252. bool success = process.WaitForExit(&exit_code);
  253. if (!callback.is_null())
  254. std::move(callback).Run(GetErrorDescription(exit_code));
  255. return success ? (exit_code == 0) : false;
  256. }
  257. base::EnsureProcessGetsReaped(std::move(process));
  258. return true;
  259. }
  260. bool XDGOpen(const base::FilePath& working_directory,
  261. const std::string& path,
  262. const bool wait_for_exit,
  263. platform_util::OpenCallback callback) {
  264. return XDGUtil({"xdg-open", path}, working_directory, wait_for_exit,
  265. /*focus_launched_process=*/true, std::move(callback));
  266. }
  267. bool XDGEmail(const std::string& email, const bool wait_for_exit) {
  268. return XDGUtil({"xdg-email", email}, base::FilePath(), wait_for_exit,
  269. /*focus_launched_process=*/true,
  270. platform_util::OpenCallback());
  271. }
  272. } // namespace
  273. namespace platform_util {
  274. void ShowItemInFolder(const base::FilePath& full_path) {
  275. DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  276. ShowItemHelper::GetInstance().ShowItemInFolder(full_path);
  277. }
  278. void OpenPath(const base::FilePath& full_path, OpenCallback callback) {
  279. // This is async, so we don't care about the return value.
  280. XDGOpen(full_path.DirName(), full_path.value(), true, std::move(callback));
  281. }
  282. void OpenFolder(const base::FilePath& full_path) {
  283. if (!base::DirectoryExists(full_path))
  284. return;
  285. XDGOpen(full_path.DirName(), ".", false, platform_util::OpenCallback());
  286. }
  287. void OpenExternal(const GURL& url,
  288. const OpenExternalOptions& options,
  289. OpenCallback callback) {
  290. // Don't wait for exit, since we don't want to wait for the browser/email
  291. // client window to close before returning
  292. if (url.SchemeIs("mailto")) {
  293. bool success = XDGEmail(url.spec(), false);
  294. std::move(callback).Run(success ? "" : "Failed to open path");
  295. } else {
  296. bool success = XDGOpen(base::FilePath(), url.spec(), false,
  297. platform_util::OpenCallback());
  298. std::move(callback).Run(success ? "" : "Failed to open path");
  299. }
  300. }
  301. bool MoveItemToTrash(const base::FilePath& full_path, bool delete_on_fail) {
  302. auto env = base::Environment::Create();
  303. // find the trash method
  304. std::string trash;
  305. if (!env->GetVar(ELECTRON_TRASH, &trash)) {
  306. // Determine desktop environment and set accordingly.
  307. const auto desktop_env(base::nix::GetDesktopEnvironment(env.get()));
  308. if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE4 ||
  309. desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE5) {
  310. trash = "kioclient5";
  311. } else if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE3) {
  312. trash = "kioclient";
  313. }
  314. }
  315. // build the invocation
  316. std::vector<std::string> argv;
  317. const auto& filename = full_path.value();
  318. if (trash == "kioclient5" || trash == "kioclient") {
  319. argv = {trash, "move", filename, "trash:/"};
  320. } else if (trash == "trash-cli") {
  321. argv = {"trash-put", filename};
  322. } else if (trash == "gvfs-trash") {
  323. argv = {"gvfs-trash", filename}; // deprecated, but still exists
  324. } else {
  325. argv = {"gio", "trash", filename};
  326. }
  327. return XDGUtil(argv, base::FilePath(), true, /*focus_launched_process=*/false,
  328. platform_util::OpenCallback());
  329. }
  330. namespace internal {
  331. bool PlatformTrashItem(const base::FilePath& full_path, std::string* error) {
  332. if (!MoveItemToTrash(full_path, false)) {
  333. // TODO(nornagon): at least include the exit code?
  334. *error = "Failed to move item to trash";
  335. return false;
  336. }
  337. return true;
  338. }
  339. } // namespace internal
  340. void Beep() {
  341. // echo '\a' > /dev/console
  342. FILE* fp = fopen("/dev/console", "a");
  343. if (fp == nullptr) {
  344. fp = fopen("/dev/tty", "a");
  345. }
  346. if (fp != nullptr) {
  347. fprintf(fp, "\a");
  348. fclose(fp);
  349. }
  350. }
  351. bool GetDesktopName(std::string* setme) {
  352. return base::Environment::Create()->GetVar("CHROME_DESKTOP", setme);
  353. }
  354. std::string GetXdgAppId() {
  355. std::string desktop_file_name;
  356. if (GetDesktopName(&desktop_file_name)) {
  357. const std::string kDesktopExtension{".desktop"};
  358. if (base::EndsWith(desktop_file_name, kDesktopExtension,
  359. base::CompareCase::INSENSITIVE_ASCII)) {
  360. desktop_file_name.resize(desktop_file_name.size() -
  361. kDesktopExtension.size());
  362. }
  363. }
  364. return desktop_file_name;
  365. }
  366. } // namespace platform_util