ntmain.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file ntmain.c
  7. *
  8. * \brief Entry points for running/configuring Tor as a Windows Service.
  9. *
  10. * Windows Services expect to be registered with the operating system, and to
  11. * have entry points for starting, stopping, and monitoring them. This module
  12. * implements those entry points so that a tor relay or client or hidden
  13. * service can run as a Windows service. Therefore, this module
  14. * is only compiled when building for Windows.
  15. *
  16. * Warning: this module is not very well tested or very well maintained.
  17. */
  18. #ifdef _WIN32
  19. #include "core/or/or.h"
  20. #include "app/config/config.h"
  21. #include "app/main/main.h"
  22. #include "app/main/ntmain.h"
  23. #include "core/mainloop/mainloop.h"
  24. #include "lib/evloop/compat_libevent.h"
  25. #include "lib/fs/winlib.h"
  26. #include "lib/log/win32err.h"
  27. #include <windows.h>
  28. #define GENSRV_SERVICENAME "tor"
  29. #define GENSRV_DISPLAYNAME "Tor Win32 Service"
  30. #define GENSRV_DESCRIPTION \
  31. "Provides an anonymous Internet communication system"
  32. #define GENSRV_USERACCT "NT AUTHORITY\\LocalService"
  33. // Cheating: using the pre-defined error codes, tricks Windows into displaying
  34. // a semi-related human-readable error message if startup fails as
  35. // opposed to simply scaring people with Error: 0xffffffff
  36. #define NT_SERVICE_ERROR_TORINIT_FAILED ERROR_EXCEPTION_IN_SERVICE
  37. static SERVICE_STATUS service_status;
  38. static SERVICE_STATUS_HANDLE hStatus;
  39. /* XXXX This 'backup argv' and 'backup argc' business is an ugly hack. This
  40. * is a job for arguments, not globals. Alas, some of the functions that
  41. * use them use them need to have fixed signatures, so they can be passed
  42. * to the NT service functions. */
  43. static char **backup_argv;
  44. static int backup_argc;
  45. static void nt_service_control(DWORD request);
  46. static void nt_service_body(int argc, char **argv);
  47. static void nt_service_main(void);
  48. static SC_HANDLE nt_service_open_scm(void);
  49. static SC_HANDLE nt_service_open(SC_HANDLE hSCManager);
  50. static int nt_service_start(SC_HANDLE hService);
  51. static int nt_service_stop(SC_HANDLE hService);
  52. static int nt_service_install(int argc, char **argv);
  53. static int nt_service_remove(void);
  54. static int nt_service_cmd_start(void);
  55. static int nt_service_cmd_stop(void);
  56. /** Struct to hold dynamically loaded NT-service related function pointers.
  57. */
  58. struct service_fns {
  59. int loaded;
  60. /** @{ */
  61. /** Function pointers for Windows API functions related to service
  62. * management. These are NULL, or they point to the . They're set by
  63. * calling the LOAD macro below. */
  64. BOOL (WINAPI *ChangeServiceConfig2A_fn)(
  65. SC_HANDLE hService,
  66. DWORD dwInfoLevel,
  67. LPVOID lpInfo);
  68. BOOL (WINAPI *CloseServiceHandle_fn)(
  69. SC_HANDLE hSCObject);
  70. BOOL (WINAPI *ControlService_fn)(
  71. SC_HANDLE hService,
  72. DWORD dwControl,
  73. LPSERVICE_STATUS lpServiceStatus);
  74. SC_HANDLE (WINAPI *CreateServiceA_fn)(
  75. SC_HANDLE hSCManager,
  76. LPCSTR lpServiceName,
  77. LPCSTR lpDisplayName,
  78. DWORD dwDesiredAccess,
  79. DWORD dwServiceType,
  80. DWORD dwStartType,
  81. DWORD dwErrorControl,
  82. LPCSTR lpBinaryPathName,
  83. LPCSTR lpLoadOrderGroup,
  84. LPDWORD lpdwTagId,
  85. LPCSTR lpDependencies,
  86. LPCSTR lpServiceStartName,
  87. LPCSTR lpPassword);
  88. BOOL (WINAPI *DeleteService_fn)(
  89. SC_HANDLE hService);
  90. SC_HANDLE (WINAPI *OpenSCManagerA_fn)(
  91. LPCSTR lpMachineName,
  92. LPCSTR lpDatabaseName,
  93. DWORD dwDesiredAccess);
  94. SC_HANDLE (WINAPI *OpenServiceA_fn)(
  95. SC_HANDLE hSCManager,
  96. LPCSTR lpServiceName,
  97. DWORD dwDesiredAccess);
  98. BOOL (WINAPI *QueryServiceStatus_fn)(
  99. SC_HANDLE hService,
  100. LPSERVICE_STATUS lpServiceStatus);
  101. SERVICE_STATUS_HANDLE (WINAPI *RegisterServiceCtrlHandlerA_fn)(
  102. LPCSTR lpServiceName,
  103. LPHANDLER_FUNCTION lpHandlerProc);
  104. BOOL (WINAPI *SetServiceStatus_fn)(SERVICE_STATUS_HANDLE,
  105. LPSERVICE_STATUS);
  106. BOOL (WINAPI *StartServiceCtrlDispatcherA_fn)(
  107. const SERVICE_TABLE_ENTRYA* lpServiceTable);
  108. BOOL (WINAPI *StartServiceA_fn)(
  109. SC_HANDLE hService,
  110. DWORD dwNumServiceArgs,
  111. LPCSTR* lpServiceArgVectors);
  112. BOOL (WINAPI *LookupAccountNameA_fn)(
  113. LPCSTR lpSystemName,
  114. LPCSTR lpAccountName,
  115. PSID Sid,
  116. LPDWORD cbSid,
  117. LPTSTR ReferencedDomainName,
  118. LPDWORD cchReferencedDomainName,
  119. PSID_NAME_USE peUse);
  120. /** @} */
  121. } service_fns = { 0,
  122. NULL, NULL, NULL, NULL, NULL, NULL,
  123. NULL, NULL, NULL, NULL, NULL, NULL,
  124. NULL};
  125. /** Loads functions used by NT services. Returns on success, or prints a
  126. * complaint to stdout and exits on error. */
  127. static void
  128. nt_service_loadlibrary(void)
  129. {
  130. HMODULE library = 0;
  131. void *fn;
  132. if (service_fns.loaded)
  133. return;
  134. if (!(library = load_windows_system_library(TEXT("advapi32.dll")))) {
  135. log_err(LD_GENERAL, "Couldn't open advapi32.dll. Are you trying to use "
  136. "NT services on Windows 98? That doesn't work.");
  137. goto err;
  138. }
  139. /* Helper macro: try to load a function named <b>f</b> from "library" into
  140. * service_functions.<b>f</b>_fn. On failure, log an error message, and goto
  141. * err.
  142. */
  143. #define LOAD(f) STMT_BEGIN \
  144. if (!(fn = GetProcAddress(library, #f))) { \
  145. log_err(LD_BUG, \
  146. "Couldn't find %s in advapi32.dll! We probably got the " \
  147. "name wrong.", #f); \
  148. goto err; \
  149. } else { \
  150. service_fns.f ## _fn = fn; \
  151. } \
  152. STMT_END
  153. LOAD(ChangeServiceConfig2A);
  154. LOAD(CloseServiceHandle);
  155. LOAD(ControlService);
  156. LOAD(CreateServiceA);
  157. LOAD(DeleteService);
  158. LOAD(OpenSCManagerA);
  159. LOAD(OpenServiceA);
  160. LOAD(QueryServiceStatus);
  161. LOAD(RegisterServiceCtrlHandlerA);
  162. LOAD(SetServiceStatus);
  163. LOAD(StartServiceCtrlDispatcherA);
  164. LOAD(StartServiceA);
  165. LOAD(LookupAccountNameA);
  166. service_fns.loaded = 1;
  167. return;
  168. err:
  169. printf("Unable to load library support for NT services: exiting.\n");
  170. exit(1); // exit ok: ntmain can't read libraries
  171. }
  172. /** If we're compiled to run as an NT service, and the service wants to
  173. * shut down, then change our current status and return 1. Else
  174. * return 0.
  175. */
  176. int
  177. nt_service_is_stopping(void)
  178. {
  179. /* If we haven't loaded the function pointers, we can't possibly be an NT
  180. * service trying to shut down. */
  181. if (!service_fns.loaded)
  182. return 0;
  183. if (service_status.dwCurrentState == SERVICE_STOP_PENDING) {
  184. service_status.dwWin32ExitCode = 0;
  185. service_status.dwCurrentState = SERVICE_STOPPED;
  186. service_fns.SetServiceStatus_fn(hStatus, &service_status);
  187. return 1;
  188. } else if (service_status.dwCurrentState == SERVICE_STOPPED) {
  189. return 1;
  190. }
  191. return 0;
  192. }
  193. /** Set the dwCurrentState field for our service to <b>state</b>. */
  194. void
  195. nt_service_set_state(DWORD state)
  196. {
  197. service_status.dwCurrentState = state;
  198. }
  199. /** Handles service control requests, such as stopping or starting the
  200. * Tor service. */
  201. static void
  202. nt_service_control(DWORD request)
  203. {
  204. static struct timeval exit_now;
  205. exit_now.tv_sec = 0;
  206. exit_now.tv_usec = 0;
  207. nt_service_loadlibrary();
  208. switch (request) {
  209. case SERVICE_CONTROL_STOP:
  210. case SERVICE_CONTROL_SHUTDOWN:
  211. log_notice(LD_GENERAL,
  212. "Got stop/shutdown request; shutting down cleanly.");
  213. service_status.dwCurrentState = SERVICE_STOP_PENDING;
  214. tor_libevent_exit_loop_after_delay(tor_libevent_get_base(),
  215. &exit_now);
  216. return;
  217. }
  218. service_fns.SetServiceStatus_fn(hStatus, &service_status);
  219. }
  220. /** Called when the service is started via the system's service control
  221. * manager. This calls tor_init() and starts the main event loop. If
  222. * tor_init() fails, the service will be stopped and exit code set to
  223. * NT_SERVICE_ERROR_TORINIT_FAILED. */
  224. static void
  225. nt_service_body(int argc, char **argv)
  226. {
  227. int r;
  228. (void) argc; /* unused */
  229. (void) argv; /* unused */
  230. nt_service_loadlibrary();
  231. service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
  232. service_status.dwCurrentState = SERVICE_START_PENDING;
  233. service_status.dwControlsAccepted =
  234. SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  235. service_status.dwWin32ExitCode = 0;
  236. service_status.dwServiceSpecificExitCode = 0;
  237. service_status.dwCheckPoint = 0;
  238. service_status.dwWaitHint = 1000;
  239. hStatus = service_fns.RegisterServiceCtrlHandlerA_fn(GENSRV_SERVICENAME,
  240. (LPHANDLER_FUNCTION) nt_service_control);
  241. if (hStatus == 0) {
  242. /* Failed to register the service control handler function */
  243. return;
  244. }
  245. r = tor_init(backup_argc, backup_argv);
  246. if (r) {
  247. /* Failed to start the Tor service */
  248. r = NT_SERVICE_ERROR_TORINIT_FAILED;
  249. service_status.dwCurrentState = SERVICE_STOPPED;
  250. service_status.dwWin32ExitCode = r;
  251. service_status.dwServiceSpecificExitCode = r;
  252. service_fns.SetServiceStatus_fn(hStatus, &service_status);
  253. return;
  254. }
  255. /* Set the service's status to SERVICE_RUNNING and start the main
  256. * event loop */
  257. service_status.dwCurrentState = SERVICE_RUNNING;
  258. service_fns.SetServiceStatus_fn(hStatus, &service_status);
  259. set_main_thread();
  260. run_tor_main_loop();
  261. tor_cleanup();
  262. }
  263. /** Main service entry point. Starts the service control dispatcher and waits
  264. * until the service status is set to SERVICE_STOPPED. */
  265. static void
  266. nt_service_main(void)
  267. {
  268. SERVICE_TABLE_ENTRYA table[2];
  269. DWORD result = 0;
  270. char *errmsg;
  271. nt_service_loadlibrary();
  272. table[0].lpServiceName = (char*)GENSRV_SERVICENAME;
  273. table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTIONA)nt_service_body;
  274. table[1].lpServiceName = NULL;
  275. table[1].lpServiceProc = NULL;
  276. if (!service_fns.StartServiceCtrlDispatcherA_fn(table)) {
  277. result = GetLastError();
  278. errmsg = format_win32_error(result);
  279. printf("Service error %d : %s\n", (int) result, errmsg);
  280. tor_free(errmsg);
  281. if (result == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
  282. if (tor_init(backup_argc, backup_argv))
  283. return;
  284. switch (get_options()->command) {
  285. case CMD_RUN_TOR:
  286. run_tor_main_loop();
  287. break;
  288. case CMD_LIST_FINGERPRINT:
  289. case CMD_HASH_PASSWORD:
  290. case CMD_VERIFY_CONFIG:
  291. case CMD_DUMP_CONFIG:
  292. case CMD_KEYGEN:
  293. case CMD_KEY_EXPIRATION:
  294. log_err(LD_CONFIG, "Unsupported command (--list-fingerprint, "
  295. "--hash-password, --keygen, --dump-config, --verify-config, "
  296. "or --key-expiration) in NT service.");
  297. break;
  298. case CMD_RUN_UNITTESTS:
  299. default:
  300. log_err(LD_CONFIG, "Illegal command number %d: internal error.",
  301. get_options()->command);
  302. }
  303. tor_cleanup();
  304. }
  305. }
  306. }
  307. /** Return a handle to the service control manager on success, or NULL on
  308. * failure. */
  309. static SC_HANDLE
  310. nt_service_open_scm(void)
  311. {
  312. SC_HANDLE hSCManager;
  313. char *errmsg = NULL;
  314. nt_service_loadlibrary();
  315. if ((hSCManager = service_fns.OpenSCManagerA_fn(
  316. NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) {
  317. errmsg = format_win32_error(GetLastError());
  318. printf("OpenSCManager() failed : %s\n", errmsg);
  319. tor_free(errmsg);
  320. }
  321. return hSCManager;
  322. }
  323. /** Open a handle to the Tor service using <b>hSCManager</b>. Return NULL
  324. * on failure. */
  325. static SC_HANDLE
  326. nt_service_open(SC_HANDLE hSCManager)
  327. {
  328. SC_HANDLE hService;
  329. char *errmsg = NULL;
  330. nt_service_loadlibrary();
  331. if ((hService = service_fns.OpenServiceA_fn(hSCManager, GENSRV_SERVICENAME,
  332. SERVICE_ALL_ACCESS)) == NULL) {
  333. errmsg = format_win32_error(GetLastError());
  334. printf("OpenService() failed : %s\n", errmsg);
  335. tor_free(errmsg);
  336. }
  337. return hService;
  338. }
  339. /** Start the Tor service. Return 0 if the service is started or was
  340. * previously running. Return -1 on error. */
  341. static int
  342. nt_service_start(SC_HANDLE hService)
  343. {
  344. char *errmsg = NULL;
  345. nt_service_loadlibrary();
  346. service_fns.QueryServiceStatus_fn(hService, &service_status);
  347. if (service_status.dwCurrentState == SERVICE_RUNNING) {
  348. printf("Service is already running\n");
  349. return 0;
  350. }
  351. if (service_fns.StartServiceA_fn(hService, 0, NULL)) {
  352. /* Loop until the service has finished attempting to start */
  353. while (service_fns.QueryServiceStatus_fn(hService, &service_status) &&
  354. (service_status.dwCurrentState == SERVICE_START_PENDING)) {
  355. Sleep(500);
  356. }
  357. /* Check if it started successfully or not */
  358. if (service_status.dwCurrentState == SERVICE_RUNNING) {
  359. printf("Service started successfully\n");
  360. return 0;
  361. } else {
  362. errmsg = format_win32_error(service_status.dwWin32ExitCode);
  363. printf("Service failed to start : %s\n", errmsg);
  364. tor_free(errmsg);
  365. }
  366. } else {
  367. errmsg = format_win32_error(GetLastError());
  368. printf("StartService() failed : %s\n", errmsg);
  369. tor_free(errmsg);
  370. }
  371. return -1;
  372. }
  373. /** Stop the Tor service. Return 0 if the service is stopped or was not
  374. * previously running. Return -1 on error. */
  375. static int
  376. nt_service_stop(SC_HANDLE hService)
  377. {
  378. /** Wait at most 10 seconds for the service to stop. */
  379. #define MAX_SERVICE_WAIT_TIME 10
  380. int wait_time;
  381. char *errmsg = NULL;
  382. nt_service_loadlibrary();
  383. service_fns.QueryServiceStatus_fn(hService, &service_status);
  384. if (service_status.dwCurrentState == SERVICE_STOPPED) {
  385. printf("Service is already stopped\n");
  386. return 0;
  387. }
  388. if (service_fns.ControlService_fn(hService, SERVICE_CONTROL_STOP,
  389. &service_status)) {
  390. wait_time = 0;
  391. while (service_fns.QueryServiceStatus_fn(hService, &service_status) &&
  392. (service_status.dwCurrentState != SERVICE_STOPPED) &&
  393. (wait_time < MAX_SERVICE_WAIT_TIME)) {
  394. Sleep(1000);
  395. wait_time++;
  396. }
  397. if (service_status.dwCurrentState == SERVICE_STOPPED) {
  398. printf("Service stopped successfully\n");
  399. return 0;
  400. } else if (wait_time == MAX_SERVICE_WAIT_TIME) {
  401. printf("Service did not stop within %d seconds.\n", wait_time);
  402. } else {
  403. errmsg = format_win32_error(GetLastError());
  404. printf("QueryServiceStatus() failed : %s\n",errmsg);
  405. tor_free(errmsg);
  406. }
  407. } else {
  408. errmsg = format_win32_error(GetLastError());
  409. printf("ControlService() failed : %s\n", errmsg);
  410. tor_free(errmsg);
  411. }
  412. return -1;
  413. }
  414. /** Build a formatted command line used for the NT service. Return a
  415. * pointer to the formatted string on success, or NULL on failure. Set
  416. * *<b>using_default_torrc</b> to true if we're going to use the default
  417. * location to torrc, or 1 if an option was specified on the command line.
  418. */
  419. static char *
  420. nt_service_command_line(int *using_default_torrc)
  421. {
  422. TCHAR tor_exe[MAX_PATH+1];
  423. char tor_exe_ascii[MAX_PATH*2+1];
  424. char *command=NULL, *options=NULL;
  425. smartlist_t *sl;
  426. int i;
  427. *using_default_torrc = 1;
  428. /* Get the location of tor.exe */
  429. if (0 == GetModuleFileName(NULL, tor_exe, MAX_PATH))
  430. return NULL;
  431. /* Get the service arguments */
  432. sl = smartlist_new();
  433. for (i = 1; i < backup_argc; ++i) {
  434. if (!strcmp(backup_argv[i], "--options") ||
  435. !strcmp(backup_argv[i], "-options")) {
  436. while (++i < backup_argc) {
  437. if (!strcmp(backup_argv[i], "-f"))
  438. *using_default_torrc = 0;
  439. smartlist_add(sl, backup_argv[i]);
  440. }
  441. }
  442. }
  443. if (smartlist_len(sl))
  444. options = smartlist_join_strings(sl,"\" \"",0,NULL);
  445. smartlist_free(sl);
  446. #ifdef UNICODE
  447. wcstombs(tor_exe_ascii, tor_exe, sizeof(tor_exe_ascii));
  448. tor_exe_ascii[sizeof(tor_exe_ascii)-1] = '\0';
  449. #else
  450. strlcpy(tor_exe_ascii, tor_exe, sizeof(tor_exe_ascii));
  451. #endif /* defined(UNICODE) */
  452. /* Allocate a string for the NT service command line and */
  453. /* Format the service command */
  454. if (options) {
  455. tor_asprintf(&command, "\"%s\" --nt-service \"%s\"",
  456. tor_exe_ascii, options);
  457. } else { /* ! options */
  458. tor_asprintf(&command, "\"%s\" --nt-service", tor_exe_ascii);
  459. }
  460. tor_free(options);
  461. return command;
  462. }
  463. /** Creates a Tor NT service, set to start on boot. The service will be
  464. * started if installation succeeds. Returns 0 on success, or -1 on
  465. * failure. */
  466. static int
  467. nt_service_install(int argc, char **argv)
  468. {
  469. /* Notes about developing NT services:
  470. *
  471. * 1. Don't count on your CWD. If an absolute path is not given, the
  472. * fopen() function goes wrong.
  473. * 2. The parameters given to the nt_service_body() function differ
  474. * from those given to main() function.
  475. */
  476. SC_HANDLE hSCManager = NULL;
  477. SC_HANDLE hService = NULL;
  478. SERVICE_DESCRIPTIONA sdBuff;
  479. char *command;
  480. char *errmsg;
  481. const char *user_acct = NULL;
  482. const char *password = "";
  483. int i;
  484. OSVERSIONINFOEX info;
  485. SID_NAME_USE sidUse;
  486. DWORD sidLen = 0, domainLen = 0;
  487. int is_win2k_or_worse = 0;
  488. int using_default_torrc = 0;
  489. nt_service_loadlibrary();
  490. /* Open the service control manager so we can create a new service */
  491. if ((hSCManager = nt_service_open_scm()) == NULL)
  492. return -1;
  493. /* Build the command line used for the service */
  494. if ((command = nt_service_command_line(&using_default_torrc)) == NULL) {
  495. printf("Unable to build service command line.\n");
  496. service_fns.CloseServiceHandle_fn(hSCManager);
  497. return -1;
  498. }
  499. for (i=1; i < argc; ++i) {
  500. if (!strcmp(argv[i], "--user") && i+1<argc) {
  501. user_acct = argv[i+1];
  502. ++i;
  503. }
  504. if (!strcmp(argv[i], "--password") && i+1<argc) {
  505. password = argv[i+1];
  506. ++i;
  507. }
  508. }
  509. /* Compute our version and see whether we're running win2k or earlier. */
  510. memset(&info, 0, sizeof(info));
  511. info.dwOSVersionInfoSize = sizeof(info);
  512. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  513. printf("Call to GetVersionEx failed.\n");
  514. is_win2k_or_worse = 1;
  515. } else {
  516. if (info.dwMajorVersion < 5 ||
  517. (info.dwMajorVersion == 5 && info.dwMinorVersion == 0))
  518. is_win2k_or_worse = 1;
  519. }
  520. if (!user_acct) {
  521. if (is_win2k_or_worse) {
  522. /* On Win2k, there is no LocalService account, so we actually need to
  523. * fall back on NULL (the system account). */
  524. printf("Running on Win2K or earlier, so the LocalService account "
  525. "doesn't exist. Falling back to SYSTEM account.\n");
  526. } else {
  527. /* Genericity is apparently _so_ last year in Redmond, where some
  528. * accounts are accounts that you can look up, and some accounts
  529. * are magic and undetectable via the security subsystem. See
  530. * http://msdn2.microsoft.com/en-us/library/ms684188.aspx
  531. */
  532. printf("Running on a Post-Win2K OS, so we'll assume that the "
  533. "LocalService account exists.\n");
  534. user_acct = GENSRV_USERACCT;
  535. }
  536. } else if (0 && service_fns.LookupAccountNameA_fn(NULL, // On this system
  537. user_acct,
  538. NULL, &sidLen, // Don't care about the SID
  539. NULL, &domainLen, // Don't care about the domain
  540. &sidUse) == 0) {
  541. /* XXXX For some reason, the above test segfaults. Fix that. */
  542. printf("User \"%s\" doesn't seem to exist.\n", user_acct);
  543. return -1;
  544. } else {
  545. printf("Will try to install service as user \"%s\".\n", user_acct);
  546. }
  547. /* XXXX This warning could be better about explaining how to resolve the
  548. * situation. */
  549. if (using_default_torrc)
  550. printf("IMPORTANT NOTE:\n"
  551. " The Tor service will run under the account \"%s\". This means\n"
  552. " that Tor will look for its configuration file under that\n"
  553. " account's Application Data directory, which is probably not\n"
  554. " the same as yours.\n", user_acct?user_acct:"<local system>");
  555. /* Create the Tor service, set to auto-start on boot */
  556. if ((hService = service_fns.CreateServiceA_fn(hSCManager, GENSRV_SERVICENAME,
  557. GENSRV_DISPLAYNAME,
  558. SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
  559. SERVICE_AUTO_START, SERVICE_ERROR_IGNORE,
  560. command, NULL, NULL, NULL,
  561. user_acct, password)) == NULL) {
  562. errmsg = format_win32_error(GetLastError());
  563. printf("CreateService() failed : %s\n", errmsg);
  564. service_fns.CloseServiceHandle_fn(hSCManager);
  565. tor_free(errmsg);
  566. tor_free(command);
  567. return -1;
  568. }
  569. printf("Done with CreateService.\n");
  570. /* Set the service's description */
  571. sdBuff.lpDescription = (char*)GENSRV_DESCRIPTION;
  572. service_fns.ChangeServiceConfig2A_fn(hService, SERVICE_CONFIG_DESCRIPTION,
  573. &sdBuff);
  574. printf("Service installed successfully\n");
  575. /* Start the service initially */
  576. nt_service_start(hService);
  577. service_fns.CloseServiceHandle_fn(hService);
  578. service_fns.CloseServiceHandle_fn(hSCManager);
  579. tor_free(command);
  580. return 0;
  581. }
  582. /** Removes the Tor NT service. Returns 0 if the service was successfully
  583. * removed, or -1 on error. */
  584. static int
  585. nt_service_remove(void)
  586. {
  587. SC_HANDLE hSCManager = NULL;
  588. SC_HANDLE hService = NULL;
  589. char *errmsg;
  590. nt_service_loadlibrary();
  591. if ((hSCManager = nt_service_open_scm()) == NULL)
  592. return -1;
  593. if ((hService = nt_service_open(hSCManager)) == NULL) {
  594. service_fns.CloseServiceHandle_fn(hSCManager);
  595. return -1;
  596. }
  597. nt_service_stop(hService);
  598. if (service_fns.DeleteService_fn(hService) == FALSE) {
  599. errmsg = format_win32_error(GetLastError());
  600. printf("DeleteService() failed : %s\n", errmsg);
  601. tor_free(errmsg);
  602. service_fns.CloseServiceHandle_fn(hService);
  603. service_fns.CloseServiceHandle_fn(hSCManager);
  604. return -1;
  605. }
  606. service_fns.CloseServiceHandle_fn(hService);
  607. service_fns.CloseServiceHandle_fn(hSCManager);
  608. printf("Service removed successfully\n");
  609. return 0;
  610. }
  611. /** Starts the Tor service. Returns 0 on success, or -1 on error. */
  612. static int
  613. nt_service_cmd_start(void)
  614. {
  615. SC_HANDLE hSCManager;
  616. SC_HANDLE hService;
  617. int start;
  618. if ((hSCManager = nt_service_open_scm()) == NULL)
  619. return -1;
  620. if ((hService = nt_service_open(hSCManager)) == NULL) {
  621. service_fns.CloseServiceHandle_fn(hSCManager);
  622. return -1;
  623. }
  624. start = nt_service_start(hService);
  625. service_fns.CloseServiceHandle_fn(hService);
  626. service_fns.CloseServiceHandle_fn(hSCManager);
  627. return start;
  628. }
  629. /** Stops the Tor service. Returns 0 on success, or -1 on error. */
  630. static int
  631. nt_service_cmd_stop(void)
  632. {
  633. SC_HANDLE hSCManager;
  634. SC_HANDLE hService;
  635. int stop;
  636. if ((hSCManager = nt_service_open_scm()) == NULL)
  637. return -1;
  638. if ((hService = nt_service_open(hSCManager)) == NULL) {
  639. service_fns.CloseServiceHandle_fn(hSCManager);
  640. return -1;
  641. }
  642. stop = nt_service_stop(hService);
  643. service_fns.CloseServiceHandle_fn(hService);
  644. service_fns.CloseServiceHandle_fn(hSCManager);
  645. return stop;
  646. }
  647. int
  648. nt_service_parse_options(int argc, char **argv, int *should_exit)
  649. {
  650. backup_argv = argv;
  651. backup_argc = argc;
  652. *should_exit = 0;
  653. if ((argc >= 3) &&
  654. (!strcmp(argv[1], "-service") || !strcmp(argv[1], "--service"))) {
  655. nt_service_loadlibrary();
  656. *should_exit = 1;
  657. if (!strcmp(argv[2], "install"))
  658. return nt_service_install(argc, argv);
  659. if (!strcmp(argv[2], "remove"))
  660. return nt_service_remove();
  661. if (!strcmp(argv[2], "start"))
  662. return nt_service_cmd_start();
  663. if (!strcmp(argv[2], "stop"))
  664. return nt_service_cmd_stop();
  665. printf("Unrecognized service command '%s'\n", argv[2]);
  666. return 1;
  667. }
  668. if (argc >= 2) {
  669. if (!strcmp(argv[1], "-nt-service") || !strcmp(argv[1], "--nt-service")) {
  670. nt_service_loadlibrary();
  671. nt_service_main();
  672. *should_exit = 1;
  673. return 0;
  674. }
  675. // These values have been deprecated since 0.1.1.2-alpha; we've warned
  676. // about them since 0.1.2.7-alpha.
  677. if (!strcmp(argv[1], "-install") || !strcmp(argv[1], "--install")) {
  678. nt_service_loadlibrary();
  679. fprintf(stderr,
  680. "The %s option is deprecated; use \"--service install\" instead.",
  681. argv[1]);
  682. *should_exit = 1;
  683. return nt_service_install(argc, argv);
  684. }
  685. if (!strcmp(argv[1], "-remove") || !strcmp(argv[1], "--remove")) {
  686. nt_service_loadlibrary();
  687. fprintf(stderr,
  688. "The %s option is deprecated; use \"--service remove\" instead.",
  689. argv[1]);
  690. *should_exit = 1;
  691. return nt_service_remove();
  692. }
  693. }
  694. *should_exit = 0;
  695. return 0;
  696. }
  697. #endif /* defined(_WIN32) */