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. #define MAIN_PRIVATE
  6. #include "or.h"
  7. #include "config.h"
  8. #include "main.h"
  9. #include "ntmain.h"
  10. #ifdef HAVE_EVENT2_EVENT_H
  11. #include <event2/event.h>
  12. #else
  13. #include <event.h>
  14. #endif
  15. #include <windows.h>
  16. #define GENSRV_SERVICENAME "tor"
  17. #define GENSRV_DISPLAYNAME "Tor Win32 Service"
  18. #define GENSRV_DESCRIPTION \
  19. "Provides an anonymous Internet communication system"
  20. #define GENSRV_USERACCT "NT AUTHORITY\\LocalService"
  21. // Cheating: using the pre-defined error codes, tricks Windows into displaying
  22. // a semi-related human-readable error message if startup fails as
  23. // opposed to simply scaring people with Error: 0xffffffff
  24. #define NT_SERVICE_ERROR_TORINIT_FAILED ERROR_EXCEPTION_IN_SERVICE
  25. static SERVICE_STATUS service_status;
  26. static SERVICE_STATUS_HANDLE hStatus;
  27. /* XXXX This 'backup argv' and 'backup argc' business is an ugly hack. This
  28. * is a job for arguments, not globals. Alas, some of the functions that
  29. * use them use them need to have fixed signatures, so they can be passed
  30. * to the NT service functions. */
  31. static char **backup_argv;
  32. static int backup_argc;
  33. static void nt_service_control(DWORD request);
  34. static void nt_service_body(int argc, char **argv);
  35. static void nt_service_main(void);
  36. static SC_HANDLE nt_service_open_scm(void);
  37. static SC_HANDLE nt_service_open(SC_HANDLE hSCManager);
  38. static int nt_service_start(SC_HANDLE hService);
  39. static int nt_service_stop(SC_HANDLE hService);
  40. static int nt_service_install(int argc, char **argv);
  41. static int nt_service_remove(void);
  42. static int nt_service_cmd_start(void);
  43. static int nt_service_cmd_stop(void);
  44. /** Struct to hold dynamically loaded NT-service related function pointers.
  45. */
  46. struct service_fns {
  47. int loaded;
  48. /** @{ */
  49. /** Function pointers for Windows API functions related to service
  50. * management. These are NULL, or they point to the . They're set by
  51. * calling the LOAD macro below. */
  52. BOOL (WINAPI *ChangeServiceConfig2A_fn)(
  53. SC_HANDLE hService,
  54. DWORD dwInfoLevel,
  55. LPVOID lpInfo);
  56. BOOL (WINAPI *CloseServiceHandle_fn)(
  57. SC_HANDLE hSCObject);
  58. BOOL (WINAPI *ControlService_fn)(
  59. SC_HANDLE hService,
  60. DWORD dwControl,
  61. LPSERVICE_STATUS lpServiceStatus);
  62. SC_HANDLE (WINAPI *CreateServiceA_fn)(
  63. SC_HANDLE hSCManager,
  64. LPCSTR lpServiceName,
  65. LPCSTR lpDisplayName,
  66. DWORD dwDesiredAccess,
  67. DWORD dwServiceType,
  68. DWORD dwStartType,
  69. DWORD dwErrorControl,
  70. LPCSTR lpBinaryPathName,
  71. LPCSTR lpLoadOrderGroup,
  72. LPDWORD lpdwTagId,
  73. LPCSTR lpDependencies,
  74. LPCSTR lpServiceStartName,
  75. LPCSTR lpPassword);
  76. BOOL (WINAPI *DeleteService_fn)(
  77. SC_HANDLE hService);
  78. SC_HANDLE (WINAPI *OpenSCManagerA_fn)(
  79. LPCSTR lpMachineName,
  80. LPCSTR lpDatabaseName,
  81. DWORD dwDesiredAccess);
  82. SC_HANDLE (WINAPI *OpenServiceA_fn)(
  83. SC_HANDLE hSCManager,
  84. LPCSTR lpServiceName,
  85. DWORD dwDesiredAccess);
  86. BOOL (WINAPI *QueryServiceStatus_fn)(
  87. SC_HANDLE hService,
  88. LPSERVICE_STATUS lpServiceStatus);
  89. SERVICE_STATUS_HANDLE (WINAPI *RegisterServiceCtrlHandlerA_fn)(
  90. LPCSTR lpServiceName,
  91. LPHANDLER_FUNCTION lpHandlerProc);
  92. BOOL (WINAPI *SetServiceStatus_fn)(SERVICE_STATUS_HANDLE,
  93. LPSERVICE_STATUS);
  94. BOOL (WINAPI *StartServiceCtrlDispatcherA_fn)(
  95. const SERVICE_TABLE_ENTRYA* lpServiceTable);
  96. BOOL (WINAPI *StartServiceA_fn)(
  97. SC_HANDLE hService,
  98. DWORD dwNumServiceArgs,
  99. LPCSTR* lpServiceArgVectors);
  100. BOOL (WINAPI *LookupAccountNameA_fn)(
  101. LPCSTR lpSystemName,
  102. LPCSTR lpAccountName,
  103. PSID Sid,
  104. LPDWORD cbSid,
  105. LPTSTR ReferencedDomainName,
  106. LPDWORD cchReferencedDomainName,
  107. PSID_NAME_USE peUse);
  108. /** @} */
  109. } service_fns = { 0,
  110. NULL, NULL, NULL, NULL, NULL, NULL,
  111. NULL, NULL, NULL, NULL, NULL, NULL,
  112. NULL};
  113. /** Loads functions used by NT services. Returns on success, or prints a
  114. * complaint to stdout and exits on error. */
  115. static void
  116. nt_service_loadlibrary(void)
  117. {
  118. HMODULE library = 0;
  119. void *fn;
  120. if (service_fns.loaded)
  121. return;
  122. if (!(library = load_windows_system_library(TEXT("advapi32.dll")))) {
  123. log_err(LD_GENERAL, "Couldn't open advapi32.dll. Are you trying to use "
  124. "NT services on Windows 98? That doesn't work.");
  125. goto err;
  126. }
  127. /* Helper macro: try to load a function named <b>f</b> from "library" into
  128. * service_functions.<b>f</b>_fn. On failure, log an error message, and goto
  129. * err.
  130. */
  131. #define LOAD(f) STMT_BEGIN \
  132. if (!(fn = GetProcAddress(library, #f))) { \
  133. log_err(LD_BUG, \
  134. "Couldn't find %s in advapi32.dll! We probably got the " \
  135. "name wrong.", #f); \
  136. goto err; \
  137. } else { \
  138. service_fns.f ## _fn = fn; \
  139. } \
  140. STMT_END
  141. LOAD(ChangeServiceConfig2A);
  142. LOAD(CloseServiceHandle);
  143. LOAD(ControlService);
  144. LOAD(CreateServiceA);
  145. LOAD(DeleteService);
  146. LOAD(OpenSCManagerA);
  147. LOAD(OpenServiceA);
  148. LOAD(QueryServiceStatus);
  149. LOAD(RegisterServiceCtrlHandlerA);
  150. LOAD(SetServiceStatus);
  151. LOAD(StartServiceCtrlDispatcherA);
  152. LOAD(StartServiceA);
  153. LOAD(LookupAccountNameA);
  154. service_fns.loaded = 1;
  155. return;
  156. err:
  157. printf("Unable to load library support for NT services: exiting.\n");
  158. exit(1);
  159. }
  160. /** If we're compiled to run as an NT service, and the service wants to
  161. * shut down, then change our current status and return 1. Else
  162. * return 0.
  163. */
  164. int
  165. nt_service_is_stopping(void)
  166. {
  167. /* If we haven't loaded the function pointers, we can't possibly be an NT
  168. * service trying to shut down. */
  169. if (!service_fns.loaded)
  170. return 0;
  171. if (service_status.dwCurrentState == SERVICE_STOP_PENDING) {
  172. service_status.dwWin32ExitCode = 0;
  173. service_status.dwCurrentState = SERVICE_STOPPED;
  174. service_fns.SetServiceStatus_fn(hStatus, &service_status);
  175. return 1;
  176. } else if (service_status.dwCurrentState == SERVICE_STOPPED) {
  177. return 1;
  178. }
  179. return 0;
  180. }
  181. /** Set the dwCurrentState field for our service to <b>state</b>. */
  182. void
  183. nt_service_set_state(DWORD state)
  184. {
  185. service_status.dwCurrentState = state;
  186. }
  187. /** Handles service control requests, such as stopping or starting the
  188. * Tor service. */
  189. static void
  190. nt_service_control(DWORD request)
  191. {
  192. static struct timeval exit_now;
  193. exit_now.tv_sec = 0;
  194. exit_now.tv_usec = 0;
  195. nt_service_loadlibrary();
  196. switch (request) {
  197. case SERVICE_CONTROL_STOP:
  198. case SERVICE_CONTROL_SHUTDOWN:
  199. log_notice(LD_GENERAL,
  200. "Got stop/shutdown request; shutting down cleanly.");
  201. service_status.dwCurrentState = SERVICE_STOP_PENDING;
  202. event_base_loopexit(tor_libevent_get_base(), &exit_now);
  203. return;
  204. }
  205. service_fns.SetServiceStatus_fn(hStatus, &service_status);
  206. }
  207. /** Called when the service is started via the system's service control
  208. * manager. This calls tor_init() and starts the main event loop. If
  209. * tor_init() fails, the service will be stopped and exit code set to
  210. * NT_SERVICE_ERROR_TORINIT_FAILED. */
  211. static void
  212. nt_service_body(int argc, char **argv)
  213. {
  214. int r;
  215. (void) argc; /* unused */
  216. (void) argv; /* unused */
  217. nt_service_loadlibrary();
  218. service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
  219. service_status.dwCurrentState = SERVICE_START_PENDING;
  220. service_status.dwControlsAccepted =
  221. SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  222. service_status.dwWin32ExitCode = 0;
  223. service_status.dwServiceSpecificExitCode = 0;
  224. service_status.dwCheckPoint = 0;
  225. service_status.dwWaitHint = 1000;
  226. hStatus = service_fns.RegisterServiceCtrlHandlerA_fn(GENSRV_SERVICENAME,
  227. (LPHANDLER_FUNCTION) nt_service_control);
  228. if (hStatus == 0) {
  229. /* Failed to register the service control handler function */
  230. return;
  231. }
  232. r = tor_init(backup_argc, backup_argv);
  233. if (r) {
  234. /* Failed to start the Tor service */
  235. r = NT_SERVICE_ERROR_TORINIT_FAILED;
  236. service_status.dwCurrentState = SERVICE_STOPPED;
  237. service_status.dwWin32ExitCode = r;
  238. service_status.dwServiceSpecificExitCode = r;
  239. service_fns.SetServiceStatus_fn(hStatus, &service_status);
  240. return;
  241. }
  242. /* Set the service's status to SERVICE_RUNNING and start the main
  243. * event loop */
  244. service_status.dwCurrentState = SERVICE_RUNNING;
  245. service_fns.SetServiceStatus_fn(hStatus, &service_status);
  246. do_main_loop();
  247. tor_cleanup();
  248. }
  249. /** Main service entry point. Starts the service control dispatcher and waits
  250. * until the service status is set to SERVICE_STOPPED. */
  251. static void
  252. nt_service_main(void)
  253. {
  254. SERVICE_TABLE_ENTRYA table[2];
  255. DWORD result = 0;
  256. char *errmsg;
  257. nt_service_loadlibrary();
  258. table[0].lpServiceName = (char*)GENSRV_SERVICENAME;
  259. table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTIONA)nt_service_body;
  260. table[1].lpServiceName = NULL;
  261. table[1].lpServiceProc = NULL;
  262. if (!service_fns.StartServiceCtrlDispatcherA_fn(table)) {
  263. result = GetLastError();
  264. errmsg = format_win32_error(result);
  265. printf("Service error %d : %s\n", (int) result, errmsg);
  266. tor_free(errmsg);
  267. if (result == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
  268. if (tor_init(backup_argc, backup_argv) < 0)
  269. return;
  270. switch (get_options()->command) {
  271. case CMD_RUN_TOR:
  272. do_main_loop();
  273. break;
  274. case CMD_LIST_FINGERPRINT:
  275. case CMD_HASH_PASSWORD:
  276. case CMD_VERIFY_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. }