ntmain.c 25 KB

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