start_host_as_root.cc 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2021 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "remoting/host/setup/start_host_as_root.h"
  5. #include <pwd.h>
  6. #include <sys/wait.h>
  7. #include <unistd.h>
  8. #include "base/check.h"
  9. #include "base/command_line.h"
  10. #include "base/process/launch.h"
  11. namespace remoting {
  12. int StartHostAsRoot(int argc, char** argv) {
  13. DCHECK(getuid() == 0);
  14. base::CommandLine command_line(argc, argv);
  15. std::string user_name = command_line.GetSwitchValueASCII("user-name");
  16. if (user_name.empty()) {
  17. fprintf(stderr,
  18. "Must specify the --user-name option when running as root.\n");
  19. return 1;
  20. }
  21. int return_value = 1;
  22. command_line.RemoveSwitch("user-name");
  23. command_line.AppendSwitch("no-start");
  24. std::vector<std::string> create_config_command_line{
  25. "/usr/bin/sudo",
  26. "-u",
  27. user_name.c_str(),
  28. };
  29. create_config_command_line.insert(create_config_command_line.end(),
  30. command_line.argv().begin(),
  31. command_line.argv().end());
  32. // LaunchProcess redirects stdin to /dev/null, but start_host prompts for a
  33. // PIN if one isn't specified on the command-line, so dup and remap it.
  34. base::LaunchOptions options;
  35. int stdin_dup = dup(STDIN_FILENO);
  36. options.fds_to_remap.emplace_back(stdin_dup, STDIN_FILENO);
  37. auto create_config_process =
  38. base::LaunchProcess(create_config_command_line, options);
  39. close(stdin_dup);
  40. if (!create_config_process.WaitForExit(&return_value) || return_value != 0) {
  41. fprintf(stderr, "Failed to set new config.\n");
  42. return return_value;
  43. }
  44. return_value = 1;
  45. std::vector<std::string> systemctl_command_line{
  46. "systemctl", "enable", "--now",
  47. std::string("chrome-remote-desktop@") + user_name};
  48. auto systemctl_process =
  49. base::LaunchProcess(systemctl_command_line, base::LaunchOptions());
  50. if (!systemctl_process.WaitForExit(&return_value) || return_value != 0) {
  51. fprintf(stderr, "Failed to enable host service.\n");
  52. return return_value;
  53. }
  54. return 0;
  55. }
  56. } // namespace remoting