ntmain.c 24 KB

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