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