ntmain.c 25 KB

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