ntmain.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2016, 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. set_main_thread();
  256. do_main_loop();
  257. tor_cleanup();
  258. }
  259. /** Main service entry point. Starts the service control dispatcher and waits
  260. * until the service status is set to SERVICE_STOPPED. */
  261. static void
  262. nt_service_main(void)
  263. {
  264. SERVICE_TABLE_ENTRYA table[2];
  265. DWORD result = 0;
  266. char *errmsg;
  267. nt_service_loadlibrary();
  268. table[0].lpServiceName = (char*)GENSRV_SERVICENAME;
  269. table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTIONA)nt_service_body;
  270. table[1].lpServiceName = NULL;
  271. table[1].lpServiceProc = NULL;
  272. if (!service_fns.StartServiceCtrlDispatcherA_fn(table)) {
  273. result = GetLastError();
  274. errmsg = format_win32_error(result);
  275. printf("Service error %d : %s\n", (int) result, errmsg);
  276. tor_free(errmsg);
  277. if (result == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
  278. if (tor_init(backup_argc, backup_argv) < 0)
  279. return;
  280. switch (get_options()->command) {
  281. case CMD_RUN_TOR:
  282. do_main_loop();
  283. break;
  284. case CMD_LIST_FINGERPRINT:
  285. case CMD_HASH_PASSWORD:
  286. case CMD_VERIFY_CONFIG:
  287. case CMD_DUMP_CONFIG:
  288. case CMD_KEYGEN:
  289. log_err(LD_CONFIG, "Unsupported command (--list-fingerprint, "
  290. "--hash-password, --keygen, --dump-config, or --verify-config) "
  291. "in NT service.");
  292. break;
  293. case CMD_RUN_UNITTESTS:
  294. default:
  295. log_err(LD_CONFIG, "Illegal command number %d: internal error.",
  296. get_options()->command);
  297. }
  298. tor_cleanup();
  299. }
  300. }
  301. }
  302. /** Return a handle to the service control manager on success, or NULL on
  303. * failure. */
  304. static SC_HANDLE
  305. nt_service_open_scm(void)
  306. {
  307. SC_HANDLE hSCManager;
  308. char *errmsg = NULL;
  309. nt_service_loadlibrary();
  310. if ((hSCManager = service_fns.OpenSCManagerA_fn(
  311. NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) {
  312. errmsg = format_win32_error(GetLastError());
  313. printf("OpenSCManager() failed : %s\n", errmsg);
  314. tor_free(errmsg);
  315. }
  316. return hSCManager;
  317. }
  318. /** Open a handle to the Tor service using <b>hSCManager</b>. Return NULL
  319. * on failure. */
  320. static SC_HANDLE
  321. nt_service_open(SC_HANDLE hSCManager)
  322. {
  323. SC_HANDLE hService;
  324. char *errmsg = NULL;
  325. nt_service_loadlibrary();
  326. if ((hService = service_fns.OpenServiceA_fn(hSCManager, GENSRV_SERVICENAME,
  327. SERVICE_ALL_ACCESS)) == NULL) {
  328. errmsg = format_win32_error(GetLastError());
  329. printf("OpenService() failed : %s\n", errmsg);
  330. tor_free(errmsg);
  331. }
  332. return hService;
  333. }
  334. /** Start the Tor service. Return 0 if the service is started or was
  335. * previously running. Return -1 on error. */
  336. static int
  337. nt_service_start(SC_HANDLE hService)
  338. {
  339. char *errmsg = NULL;
  340. nt_service_loadlibrary();
  341. service_fns.QueryServiceStatus_fn(hService, &service_status);
  342. if (service_status.dwCurrentState == SERVICE_RUNNING) {
  343. printf("Service is already running\n");
  344. return 0;
  345. }
  346. if (service_fns.StartServiceA_fn(hService, 0, NULL)) {
  347. /* Loop until the service has finished attempting to start */
  348. while (service_fns.QueryServiceStatus_fn(hService, &service_status) &&
  349. (service_status.dwCurrentState == SERVICE_START_PENDING)) {
  350. Sleep(500);
  351. }
  352. /* Check if it started successfully or not */
  353. if (service_status.dwCurrentState == SERVICE_RUNNING) {
  354. printf("Service started successfully\n");
  355. return 0;
  356. } else {
  357. errmsg = format_win32_error(service_status.dwWin32ExitCode);
  358. printf("Service failed to start : %s\n", errmsg);
  359. tor_free(errmsg);
  360. }
  361. } else {
  362. errmsg = format_win32_error(GetLastError());
  363. printf("StartService() failed : %s\n", errmsg);
  364. tor_free(errmsg);
  365. }
  366. return -1;
  367. }
  368. /** Stop the Tor service. Return 0 if the service is stopped or was not
  369. * previously running. Return -1 on error. */
  370. static int
  371. nt_service_stop(SC_HANDLE hService)
  372. {
  373. /** Wait at most 10 seconds for the service to stop. */
  374. #define MAX_SERVICE_WAIT_TIME 10
  375. int wait_time;
  376. char *errmsg = NULL;
  377. nt_service_loadlibrary();
  378. service_fns.QueryServiceStatus_fn(hService, &service_status);
  379. if (service_status.dwCurrentState == SERVICE_STOPPED) {
  380. printf("Service is already stopped\n");
  381. return 0;
  382. }
  383. if (service_fns.ControlService_fn(hService, SERVICE_CONTROL_STOP,
  384. &service_status)) {
  385. wait_time = 0;
  386. while (service_fns.QueryServiceStatus_fn(hService, &service_status) &&
  387. (service_status.dwCurrentState != SERVICE_STOPPED) &&
  388. (wait_time < MAX_SERVICE_WAIT_TIME)) {
  389. Sleep(1000);
  390. wait_time++;
  391. }
  392. if (service_status.dwCurrentState == SERVICE_STOPPED) {
  393. printf("Service stopped successfully\n");
  394. return 0;
  395. } else if (wait_time == MAX_SERVICE_WAIT_TIME) {
  396. printf("Service did not stop within %d seconds.\n", wait_time);
  397. } else {
  398. errmsg = format_win32_error(GetLastError());
  399. printf("QueryServiceStatus() failed : %s\n",errmsg);
  400. tor_free(errmsg);
  401. }
  402. } else {
  403. errmsg = format_win32_error(GetLastError());
  404. printf("ControlService() failed : %s\n", errmsg);
  405. tor_free(errmsg);
  406. }
  407. return -1;
  408. }
  409. /** Build a formatted command line used for the NT service. Return a
  410. * pointer to the formatted string on success, or NULL on failure. Set
  411. * *<b>using_default_torrc</b> to true if we're going to use the default
  412. * location to torrc, or 1 if an option was specified on the command line.
  413. */
  414. static char *
  415. nt_service_command_line(int *using_default_torrc)
  416. {
  417. TCHAR tor_exe[MAX_PATH+1];
  418. char tor_exe_ascii[MAX_PATH*2+1];
  419. char *command=NULL, *options=NULL;
  420. smartlist_t *sl;
  421. int i;
  422. *using_default_torrc = 1;
  423. /* Get the location of tor.exe */
  424. if (0 == GetModuleFileName(NULL, tor_exe, MAX_PATH))
  425. return NULL;
  426. /* Get the service arguments */
  427. sl = smartlist_new();
  428. for (i = 1; i < backup_argc; ++i) {
  429. if (!strcmp(backup_argv[i], "--options") ||
  430. !strcmp(backup_argv[i], "-options")) {
  431. while (++i < backup_argc) {
  432. if (!strcmp(backup_argv[i], "-f"))
  433. *using_default_torrc = 0;
  434. smartlist_add(sl, backup_argv[i]);
  435. }
  436. }
  437. }
  438. if (smartlist_len(sl))
  439. options = smartlist_join_strings(sl,"\" \"",0,NULL);
  440. smartlist_free(sl);
  441. #ifdef UNICODE
  442. wcstombs(tor_exe_ascii, tor_exe, sizeof(tor_exe_ascii));
  443. tor_exe_ascii[sizeof(tor_exe_ascii)-1] = '\0';
  444. #else
  445. strlcpy(tor_exe_ascii, tor_exe, sizeof(tor_exe_ascii));
  446. #endif
  447. /* Allocate a string for the NT service command line and */
  448. /* Format the service command */
  449. if (options) {
  450. tor_asprintf(&command, "\"%s\" --nt-service \"%s\"",
  451. tor_exe_ascii, options);
  452. } else { /* ! options */
  453. tor_asprintf(&command, "\"%s\" --nt-service", tor_exe_ascii);
  454. }
  455. tor_free(options);
  456. return command;
  457. }
  458. /** Creates a Tor NT service, set to start on boot. The service will be
  459. * started if installation succeeds. Returns 0 on success, or -1 on
  460. * failure. */
  461. static int
  462. nt_service_install(int argc, char **argv)
  463. {
  464. /* Notes about developing NT services:
  465. *
  466. * 1. Don't count on your CWD. If an absolute path is not given, the
  467. * fopen() function goes wrong.
  468. * 2. The parameters given to the nt_service_body() function differ
  469. * from those given to main() function.
  470. */
  471. SC_HANDLE hSCManager = NULL;
  472. SC_HANDLE hService = NULL;
  473. SERVICE_DESCRIPTIONA sdBuff;
  474. char *command;
  475. char *errmsg;
  476. const char *user_acct = NULL;
  477. const char *password = "";
  478. int i;
  479. OSVERSIONINFOEX info;
  480. SID_NAME_USE sidUse;
  481. DWORD sidLen = 0, domainLen = 0;
  482. int is_win2k_or_worse = 0;
  483. int using_default_torrc = 0;
  484. nt_service_loadlibrary();
  485. /* Open the service control manager so we can create a new service */
  486. if ((hSCManager = nt_service_open_scm()) == NULL)
  487. return -1;
  488. /* Build the command line used for the service */
  489. if ((command = nt_service_command_line(&using_default_torrc)) == NULL) {
  490. printf("Unable to build service command line.\n");
  491. service_fns.CloseServiceHandle_fn(hSCManager);
  492. return -1;
  493. }
  494. for (i=1; i < argc; ++i) {
  495. if (!strcmp(argv[i], "--user") && i+1<argc) {
  496. user_acct = argv[i+1];
  497. ++i;
  498. }
  499. if (!strcmp(argv[i], "--password") && i+1<argc) {
  500. password = argv[i+1];
  501. ++i;
  502. }
  503. }
  504. /* Compute our version and see whether we're running win2k or earlier. */
  505. memset(&info, 0, sizeof(info));
  506. info.dwOSVersionInfoSize = sizeof(info);
  507. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  508. printf("Call to GetVersionEx failed.\n");
  509. is_win2k_or_worse = 1;
  510. } else {
  511. if (info.dwMajorVersion < 5 ||
  512. (info.dwMajorVersion == 5 && info.dwMinorVersion == 0))
  513. is_win2k_or_worse = 1;
  514. }
  515. if (!user_acct) {
  516. if (is_win2k_or_worse) {
  517. /* On Win2k, there is no LocalService account, so we actually need to
  518. * fall back on NULL (the system account). */
  519. printf("Running on Win2K or earlier, so the LocalService account "
  520. "doesn't exist. Falling back to SYSTEM account.\n");
  521. } else {
  522. /* Genericity is apparently _so_ last year in Redmond, where some
  523. * accounts are accounts that you can look up, and some accounts
  524. * are magic and undetectable via the security subsystem. See
  525. * http://msdn2.microsoft.com/en-us/library/ms684188.aspx
  526. */
  527. printf("Running on a Post-Win2K OS, so we'll assume that the "
  528. "LocalService account exists.\n");
  529. user_acct = GENSRV_USERACCT;
  530. }
  531. } else if (0 && service_fns.LookupAccountNameA_fn(NULL, // On this system
  532. user_acct,
  533. NULL, &sidLen, // Don't care about the SID
  534. NULL, &domainLen, // Don't care about the domain
  535. &sidUse) == 0) {
  536. /* XXXX For some reason, the above test segfaults. Fix that. */
  537. printf("User \"%s\" doesn't seem to exist.\n", user_acct);
  538. return -1;
  539. } else {
  540. printf("Will try to install service as user \"%s\".\n", user_acct);
  541. }
  542. /* XXXX This warning could be better about explaining how to resolve the
  543. * situation. */
  544. if (using_default_torrc)
  545. printf("IMPORTANT NOTE:\n"
  546. " The Tor service will run under the account \"%s\". This means\n"
  547. " that Tor will look for its configuration file under that\n"
  548. " account's Application Data directory, which is probably not\n"
  549. " the same as yours.\n", user_acct?user_acct:"<local system>");
  550. /* Create the Tor service, set to auto-start on boot */
  551. if ((hService = service_fns.CreateServiceA_fn(hSCManager, GENSRV_SERVICENAME,
  552. GENSRV_DISPLAYNAME,
  553. SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
  554. SERVICE_AUTO_START, SERVICE_ERROR_IGNORE,
  555. command, NULL, NULL, NULL,
  556. user_acct, password)) == NULL) {
  557. errmsg = format_win32_error(GetLastError());
  558. printf("CreateService() failed : %s\n", errmsg);
  559. service_fns.CloseServiceHandle_fn(hSCManager);
  560. tor_free(errmsg);
  561. tor_free(command);
  562. return -1;
  563. }
  564. printf("Done with CreateService.\n");
  565. /* Set the service's description */
  566. sdBuff.lpDescription = (char*)GENSRV_DESCRIPTION;
  567. service_fns.ChangeServiceConfig2A_fn(hService, SERVICE_CONFIG_DESCRIPTION,
  568. &sdBuff);
  569. printf("Service installed successfully\n");
  570. /* Start the service initially */
  571. nt_service_start(hService);
  572. service_fns.CloseServiceHandle_fn(hService);
  573. service_fns.CloseServiceHandle_fn(hSCManager);
  574. tor_free(command);
  575. return 0;
  576. }
  577. /** Removes the Tor NT service. Returns 0 if the service was successfully
  578. * removed, or -1 on error. */
  579. static int
  580. nt_service_remove(void)
  581. {
  582. SC_HANDLE hSCManager = NULL;
  583. SC_HANDLE hService = NULL;
  584. char *errmsg;
  585. nt_service_loadlibrary();
  586. if ((hSCManager = nt_service_open_scm()) == NULL)
  587. return -1;
  588. if ((hService = nt_service_open(hSCManager)) == NULL) {
  589. service_fns.CloseServiceHandle_fn(hSCManager);
  590. return -1;
  591. }
  592. nt_service_stop(hService);
  593. if (service_fns.DeleteService_fn(hService) == FALSE) {
  594. errmsg = format_win32_error(GetLastError());
  595. printf("DeleteService() failed : %s\n", errmsg);
  596. tor_free(errmsg);
  597. service_fns.CloseServiceHandle_fn(hService);
  598. service_fns.CloseServiceHandle_fn(hSCManager);
  599. return -1;
  600. }
  601. service_fns.CloseServiceHandle_fn(hService);
  602. service_fns.CloseServiceHandle_fn(hSCManager);
  603. printf("Service removed successfully\n");
  604. return 0;
  605. }
  606. /** Starts the Tor service. Returns 0 on success, or -1 on error. */
  607. static int
  608. nt_service_cmd_start(void)
  609. {
  610. SC_HANDLE hSCManager;
  611. SC_HANDLE hService;
  612. int start;
  613. if ((hSCManager = nt_service_open_scm()) == NULL)
  614. return -1;
  615. if ((hService = nt_service_open(hSCManager)) == NULL) {
  616. service_fns.CloseServiceHandle_fn(hSCManager);
  617. return -1;
  618. }
  619. start = nt_service_start(hService);
  620. service_fns.CloseServiceHandle_fn(hService);
  621. service_fns.CloseServiceHandle_fn(hSCManager);
  622. return start;
  623. }
  624. /** Stops the Tor service. Returns 0 on success, or -1 on error. */
  625. static int
  626. nt_service_cmd_stop(void)
  627. {
  628. SC_HANDLE hSCManager;
  629. SC_HANDLE hService;
  630. int stop;
  631. if ((hSCManager = nt_service_open_scm()) == NULL)
  632. return -1;
  633. if ((hService = nt_service_open(hSCManager)) == NULL) {
  634. service_fns.CloseServiceHandle_fn(hSCManager);
  635. return -1;
  636. }
  637. stop = nt_service_stop(hService);
  638. service_fns.CloseServiceHandle_fn(hService);
  639. service_fns.CloseServiceHandle_fn(hSCManager);
  640. return stop;
  641. }
  642. int
  643. nt_service_parse_options(int argc, char **argv, int *should_exit)
  644. {
  645. backup_argv = argv;
  646. backup_argc = argc;
  647. *should_exit = 0;
  648. if ((argc >= 3) &&
  649. (!strcmp(argv[1], "-service") || !strcmp(argv[1], "--service"))) {
  650. nt_service_loadlibrary();
  651. *should_exit = 1;
  652. if (!strcmp(argv[2], "install"))
  653. return nt_service_install(argc, argv);
  654. if (!strcmp(argv[2], "remove"))
  655. return nt_service_remove();
  656. if (!strcmp(argv[2], "start"))
  657. return nt_service_cmd_start();
  658. if (!strcmp(argv[2], "stop"))
  659. return nt_service_cmd_stop();
  660. printf("Unrecognized service command '%s'\n", argv[2]);
  661. return 1;
  662. }
  663. if (argc >= 2) {
  664. if (!strcmp(argv[1], "-nt-service") || !strcmp(argv[1], "--nt-service")) {
  665. nt_service_loadlibrary();
  666. nt_service_main();
  667. *should_exit = 1;
  668. return 0;
  669. }
  670. // These values have been deprecated since 0.1.1.2-alpha; we've warned
  671. // about them since 0.1.2.7-alpha.
  672. if (!strcmp(argv[1], "-install") || !strcmp(argv[1], "--install")) {
  673. nt_service_loadlibrary();
  674. fprintf(stderr,
  675. "The %s option is deprecated; use \"--service install\" instead.",
  676. argv[1]);
  677. *should_exit = 1;
  678. return nt_service_install(argc, argv);
  679. }
  680. if (!strcmp(argv[1], "-remove") || !strcmp(argv[1], "--remove")) {
  681. nt_service_loadlibrary();
  682. fprintf(stderr,
  683. "The %s option is deprecated; use \"--service remove\" instead.",
  684. argv[1]);
  685. *should_exit = 1;
  686. return nt_service_remove();
  687. }
  688. }
  689. *should_exit = 0;
  690. return 0;
  691. }
  692. #endif