start_host_main.cc 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. // Copyright (c) 2012 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_main.h"
  5. #include <stddef.h>
  6. #include <stdio.h>
  7. #include "base/at_exit.h"
  8. #include "base/bind.h"
  9. #include "base/command_line.h"
  10. #include "base/message_loop/message_pump_type.h"
  11. #include "base/run_loop.h"
  12. #include "base/task/single_thread_task_executor.h"
  13. #include "base/task/single_thread_task_runner.h"
  14. #include "base/task/thread_pool/thread_pool_instance.h"
  15. #include "base/threading/thread.h"
  16. #include "build/build_config.h"
  17. #include "mojo/core/embedder/embedder.h"
  18. #include "net/url_request/url_request_context_getter.h"
  19. #include "remoting/base/logging.h"
  20. #include "remoting/base/url_request_context_getter.h"
  21. #include "remoting/host/setup/host_starter.h"
  22. #include "remoting/host/setup/pin_validator.h"
  23. #include "services/network/public/cpp/shared_url_loader_factory.h"
  24. #include "services/network/transitional_url_loader_factory_owner.h"
  25. #if BUILDFLAG(IS_POSIX)
  26. #include <termios.h>
  27. #include <unistd.h>
  28. #endif // BUILDFLAG(IS_POSIX)
  29. #if BUILDFLAG(IS_LINUX)
  30. #include "remoting/host/setup/daemon_controller_delegate_linux.h"
  31. #include "remoting/host/setup/start_host_as_root.h"
  32. #endif // BUILDFLAG(IS_LINUX)
  33. #if BUILDFLAG(IS_WIN)
  34. #include "base/process/process_info.h"
  35. #include <windows.h>
  36. #endif // BUILDFLAG(IS_WIN)
  37. namespace remoting {
  38. namespace {
  39. // True if the host was started successfully.
  40. bool g_started = false;
  41. base::SingleThreadTaskExecutor* g_main_thread_task_executor = nullptr;
  42. // The active RunLoop.
  43. base::RunLoop* g_active_run_loop = nullptr;
  44. // Lets us hide the PIN that a user types.
  45. void SetEcho(bool echo) {
  46. #if BUILDFLAG(IS_WIN)
  47. DWORD mode;
  48. HANDLE console_handle = GetStdHandle(STD_INPUT_HANDLE);
  49. if (!GetConsoleMode(console_handle, &mode)) {
  50. LOG(ERROR) << "GetConsoleMode failed";
  51. return;
  52. }
  53. SetConsoleMode(console_handle,
  54. (mode & ~ENABLE_ECHO_INPUT) | (echo ? ENABLE_ECHO_INPUT : 0));
  55. #else
  56. termios term;
  57. tcgetattr(STDIN_FILENO, &term);
  58. if (echo) {
  59. term.c_lflag |= ECHO;
  60. } else {
  61. term.c_lflag &= ~ECHO;
  62. }
  63. tcsetattr(STDIN_FILENO, TCSANOW, &term);
  64. #endif // !BUILDFLAG(IS_WIN)
  65. }
  66. // Reads a newline-terminated string from stdin.
  67. std::string ReadString(bool no_echo) {
  68. if (no_echo)
  69. SetEcho(false);
  70. const int kMaxLen = 1024;
  71. std::string str(kMaxLen, 0);
  72. char* result = fgets(&str[0], kMaxLen, stdin);
  73. if (no_echo) {
  74. printf("\n");
  75. SetEcho(true);
  76. }
  77. if (!result)
  78. return std::string();
  79. size_t newline_index = str.find('\n');
  80. if (newline_index != std::string::npos)
  81. str[newline_index] = '\0';
  82. str.resize(strlen(&str[0]));
  83. return str;
  84. }
  85. // Called when the HostStarter has finished.
  86. void OnDone(HostStarter::Result result) {
  87. if (!g_main_thread_task_executor->task_runner()->BelongsToCurrentThread()) {
  88. g_main_thread_task_executor->task_runner()->PostTask(
  89. FROM_HERE, base::BindOnce(&OnDone, result));
  90. return;
  91. }
  92. switch (result) {
  93. case HostStarter::START_COMPLETE:
  94. g_started = true;
  95. break;
  96. case HostStarter::NETWORK_ERROR:
  97. fprintf(stderr, "Couldn't start host: network error.\n");
  98. break;
  99. case HostStarter::OAUTH_ERROR:
  100. fprintf(stderr, "Couldn't start host: OAuth error.\n");
  101. break;
  102. case HostStarter::START_ERROR:
  103. fprintf(stderr, "Couldn't start host.\n");
  104. break;
  105. }
  106. g_active_run_loop->Quit();
  107. }
  108. } // namespace
  109. int StartHostMain(int argc, char** argv) {
  110. #if BUILDFLAG(IS_LINUX)
  111. // Minimize the amount of code that runs as root on Posix systems.
  112. if (getuid() == 0) {
  113. return remoting::StartHostAsRoot(argc, argv);
  114. }
  115. #endif // BUILDFLAG(IS_LINUX)
  116. // google_apis::GetOAuth2ClientID/Secret need a static CommandLine.
  117. base::CommandLine::Init(argc, argv);
  118. const base::CommandLine* command_line =
  119. base::CommandLine::ForCurrentProcess();
  120. // This object instance is required by Chrome code (for example,
  121. // FilePath, LazyInstance, MessageLoop).
  122. base::AtExitManager exit_manager;
  123. logging::LoggingSettings settings;
  124. settings.logging_dest =
  125. logging::LOG_TO_SYSTEM_DEBUG_LOG | logging::LOG_TO_STDERR;
  126. logging::InitLogging(settings);
  127. base::ThreadPoolInstance::CreateAndStartWithDefaultParams(
  128. "RemotingHostSetup");
  129. mojo::core::Init();
  130. std::string host_name = command_line->GetSwitchValueASCII("name");
  131. std::string host_pin = command_line->GetSwitchValueASCII("pin");
  132. std::string auth_code = command_line->GetSwitchValueASCII("code");
  133. std::string redirect_url = command_line->GetSwitchValueASCII("redirect-url");
  134. std::string host_id = command_line->GetSwitchValueASCII("host-id");
  135. // Optional parameter used to verify that |code| was generated by the
  136. // |host_owner| account. If this value is not provided, we register the host
  137. // for the account which generated |code|.
  138. std::string host_owner = command_line->GetSwitchValueASCII("host-owner");
  139. #if BUILDFLAG(IS_LINUX)
  140. if (command_line->HasSwitch("no-start")) {
  141. // On Linux, registering the host with systemd and starting it is the only
  142. // reason start_host requires root. The --no-start options skips that final
  143. // step, allowing it to be run non-interactively if the parent process has
  144. // root and can do complete the setup itself. Since this functionality is
  145. // Linux-specific, it isn't plumbed through the platform-independent daemon
  146. // controller code, and must be configured on the Linux delegate explicitly.
  147. DaemonControllerDelegateLinux::set_start_host_after_setup(false);
  148. }
  149. #endif // BUILDFLAG(IS_LINUX)
  150. #if BUILDFLAG(IS_WIN)
  151. // The tool must be run elevated on Windows so the host has access to the
  152. // directories used to store the configuration JSON files.
  153. if (!base::IsCurrentProcessElevated()) {
  154. fprintf(stderr, "Error: %s must be run as an elevated process.", argv[0]);
  155. return 1;
  156. }
  157. #endif // BUILDFLAG(IS_WIN)
  158. if (command_line->HasSwitch("help") || command_line->HasSwitch("h") ||
  159. command_line->HasSwitch("?") || !command_line->GetArgs().empty()) {
  160. fprintf(stderr,
  161. "Usage: %s [--name=<hostname>] [--code=<auth-code>] [--pin=<PIN>] "
  162. "[--redirect-url=<redirectURL>]\n",
  163. argv[0]);
  164. return 1;
  165. }
  166. if (auth_code.empty() || redirect_url.empty()) {
  167. fprintf(stdout,
  168. "You need a web browser to use this command. Please visit\n");
  169. fprintf(stdout,
  170. "https://remotedesktop.google.com/headless for instructions.\n");
  171. return 1;
  172. }
  173. if (host_name.empty()) {
  174. fprintf(stdout, "Enter a name for this computer: ");
  175. fflush(stdout);
  176. host_name = ReadString(false);
  177. }
  178. if (host_pin.empty()) {
  179. while (true) {
  180. fprintf(stdout, "Enter a PIN of at least six digits: ");
  181. fflush(stdout);
  182. host_pin = ReadString(true);
  183. if (!remoting::IsPinValid(host_pin)) {
  184. fprintf(stdout,
  185. "Please use a PIN consisting of at least six digits.\n");
  186. fflush(stdout);
  187. continue;
  188. }
  189. std::string host_pin_confirm;
  190. fprintf(stdout, "Enter the same PIN again: ");
  191. fflush(stdout);
  192. host_pin_confirm = ReadString(true);
  193. if (host_pin != host_pin_confirm) {
  194. fprintf(stdout, "You entered different PINs.\n");
  195. fflush(stdout);
  196. continue;
  197. }
  198. break;
  199. }
  200. } else {
  201. if (!remoting::IsPinValid(host_pin)) {
  202. fprintf(stderr, "Please use a PIN consisting of at least six digits.\n");
  203. return 1;
  204. }
  205. }
  206. // Provide SingleThreadTaskExecutor and threads for the
  207. // URLRequestContextGetter.
  208. base::SingleThreadTaskExecutor main_thread_task_executor;
  209. g_main_thread_task_executor = &main_thread_task_executor;
  210. base::Thread::Options io_thread_options(base::MessagePumpType::IO, 0);
  211. base::Thread io_thread("IO thread");
  212. io_thread.StartWithOptions(std::move(io_thread_options));
  213. scoped_refptr<net::URLRequestContextGetter> url_request_context_getter(
  214. new remoting::URLRequestContextGetter(io_thread.task_runner()));
  215. network::TransitionalURLLoaderFactoryOwner url_loader_factory_owner(
  216. url_request_context_getter);
  217. // Start the host.
  218. std::unique_ptr<HostStarter> host_starter(HostStarter::Create(
  219. url_loader_factory_owner.GetURLLoaderFactory()));
  220. host_starter->StartHost(host_id, host_name, host_pin, host_owner,
  221. /*consent_to_data_collection=*/true, auth_code,
  222. redirect_url, base::BindOnce(&OnDone));
  223. // Run the task executor until the StartHost completion callback.
  224. base::RunLoop run_loop;
  225. g_active_run_loop = &run_loop;
  226. run_loop.Run();
  227. g_main_thread_task_executor = nullptr;
  228. g_active_run_loop = nullptr;
  229. // Destroy the HostStarter and URLRequestContextGetter before stopping the
  230. // IO thread.
  231. host_starter.reset();
  232. url_request_context_getter = nullptr;
  233. io_thread.Stop();
  234. return g_started ? 0 : 1;
  235. }
  236. } // namespace remoting