ntmain.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2012, 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+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. #else
  431. strlcpy(tor_exe_ascii, tor_exe, sizeof(tor_exe_ascii));
  432. #endif
  433. /* Allocate a string for the NT service command line and */
  434. /* Format the service command */
  435. if (options) {
  436. tor_asprintf(&command, "\"%s\" --nt-service \"%s\"",
  437. tor_exe_ascii, options);
  438. } else { /* ! options */
  439. tor_asprintf(&command, "\"%s\" --nt-service", tor_exe_ascii);
  440. }
  441. tor_free(options);
  442. return command;
  443. }
  444. /** Creates a Tor NT service, set to start on boot. The service will be
  445. * started if installation succeeds. Returns 0 on success, or -1 on
  446. * failure. */
  447. static int
  448. nt_service_install(int argc, char **argv)
  449. {
  450. /* Notes about developing NT services:
  451. *
  452. * 1. Don't count on your CWD. If an absolute path is not given, the
  453. * fopen() function goes wrong.
  454. * 2. The parameters given to the nt_service_body() function differ
  455. * from those given to main() function.
  456. */
  457. SC_HANDLE hSCManager = NULL;
  458. SC_HANDLE hService = NULL;
  459. SERVICE_DESCRIPTIONA sdBuff;
  460. char *command;
  461. char *errmsg;
  462. const char *user_acct = NULL;
  463. const char *password = "";
  464. int i;
  465. OSVERSIONINFOEX info;
  466. SID_NAME_USE sidUse;
  467. DWORD sidLen = 0, domainLen = 0;
  468. int is_win2k_or_worse = 0;
  469. int using_default_torrc = 0;
  470. nt_service_loadlibrary();
  471. /* Open the service control manager so we can create a new service */
  472. if ((hSCManager = nt_service_open_scm()) == NULL)
  473. return -1;
  474. /* Build the command line used for the service */
  475. if ((command = nt_service_command_line(&using_default_torrc)) == NULL) {
  476. printf("Unable to build service command line.\n");
  477. service_fns.CloseServiceHandle_fn(hSCManager);
  478. return -1;
  479. }
  480. for (i=1; i < argc; ++i) {
  481. if (!strcmp(argv[i], "--user") && i+1<argc) {
  482. user_acct = argv[i+1];
  483. ++i;
  484. }
  485. if (!strcmp(argv[i], "--password") && i+1<argc) {
  486. password = argv[i+1];
  487. ++i;
  488. }
  489. }
  490. /* Compute our version and see whether we're running win2k or earlier. */
  491. memset(&info, 0, sizeof(info));
  492. info.dwOSVersionInfoSize = sizeof(info);
  493. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  494. printf("Call to GetVersionEx failed.\n");
  495. is_win2k_or_worse = 1;
  496. } else {
  497. if (info.dwMajorVersion < 5 ||
  498. (info.dwMajorVersion == 5 && info.dwMinorVersion == 0))
  499. is_win2k_or_worse = 1;
  500. }
  501. if (!user_acct) {
  502. if (is_win2k_or_worse) {
  503. /* On Win2k, there is no LocalService account, so we actually need to
  504. * fall back on NULL (the system account). */
  505. printf("Running on Win2K or earlier, so the LocalService account "
  506. "doesn't exist. Falling back to SYSTEM account.\n");
  507. } else {
  508. /* Genericity is apparently _so_ last year in Redmond, where some
  509. * accounts are accounts that you can look up, and some accounts
  510. * are magic and undetectable via the security subsystem. See
  511. * http://msdn2.microsoft.com/en-us/library/ms684188.aspx
  512. */
  513. printf("Running on a Post-Win2K OS, so we'll assume that the "
  514. "LocalService account exists.\n");
  515. user_acct = GENSRV_USERACCT;
  516. }
  517. } else if (0 && service_fns.LookupAccountNameA_fn(NULL, // On this system
  518. user_acct,
  519. NULL, &sidLen, // Don't care about the SID
  520. NULL, &domainLen, // Don't care about the domain
  521. &sidUse) == 0) {
  522. /* XXXX For some reason, the above test segfaults. Fix that. */
  523. printf("User \"%s\" doesn't seem to exist.\n", user_acct);
  524. return -1;
  525. } else {
  526. printf("Will try to install service as user \"%s\".\n", user_acct);
  527. }
  528. /* XXXX This warning could be better about explaining how to resolve the
  529. * situation. */
  530. if (using_default_torrc)
  531. printf("IMPORTANT NOTE:\n"
  532. " The Tor service will run under the account \"%s\". This means\n"
  533. " that Tor will look for its configuration file under that\n"
  534. " account's Application Data directory, which is probably not\n"
  535. " the same as yours.\n", user_acct?user_acct:"<local system>");
  536. /* Create the Tor service, set to auto-start on boot */
  537. if ((hService = service_fns.CreateServiceA_fn(hSCManager, GENSRV_SERVICENAME,
  538. GENSRV_DISPLAYNAME,
  539. SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
  540. SERVICE_AUTO_START, SERVICE_ERROR_IGNORE,
  541. command, NULL, NULL, NULL,
  542. user_acct, password)) == NULL) {
  543. errmsg = format_win32_error(GetLastError());
  544. printf("CreateService() failed : %s\n", errmsg);
  545. service_fns.CloseServiceHandle_fn(hSCManager);
  546. tor_free(errmsg);
  547. tor_free(command);
  548. return -1;
  549. }
  550. printf("Done with CreateService.\n");
  551. /* Set the service's description */
  552. sdBuff.lpDescription = (char*)GENSRV_DESCRIPTION;
  553. service_fns.ChangeServiceConfig2A_fn(hService, SERVICE_CONFIG_DESCRIPTION,
  554. &sdBuff);
  555. printf("Service installed successfully\n");
  556. /* Start the service initially */
  557. nt_service_start(hService);
  558. service_fns.CloseServiceHandle_fn(hService);
  559. service_fns.CloseServiceHandle_fn(hSCManager);
  560. tor_free(command);
  561. return 0;
  562. }
  563. /** Removes the Tor NT service. Returns 0 if the service was successfully
  564. * removed, or -1 on error. */
  565. static int
  566. nt_service_remove(void)
  567. {
  568. SC_HANDLE hSCManager = NULL;
  569. SC_HANDLE hService = NULL;
  570. char *errmsg;
  571. nt_service_loadlibrary();
  572. if ((hSCManager = nt_service_open_scm()) == NULL)
  573. return -1;
  574. if ((hService = nt_service_open(hSCManager)) == NULL) {
  575. service_fns.CloseServiceHandle_fn(hSCManager);
  576. return -1;
  577. }
  578. nt_service_stop(hService);
  579. if (service_fns.DeleteService_fn(hService) == FALSE) {
  580. errmsg = format_win32_error(GetLastError());
  581. printf("DeleteService() failed : %s\n", errmsg);
  582. tor_free(errmsg);
  583. service_fns.CloseServiceHandle_fn(hService);
  584. service_fns.CloseServiceHandle_fn(hSCManager);
  585. return -1;
  586. }
  587. service_fns.CloseServiceHandle_fn(hService);
  588. service_fns.CloseServiceHandle_fn(hSCManager);
  589. printf("Service removed successfully\n");
  590. return 0;
  591. }
  592. /** Starts the Tor service. Returns 0 on success, or -1 on error. */
  593. static int
  594. nt_service_cmd_start(void)
  595. {
  596. SC_HANDLE hSCManager;
  597. SC_HANDLE hService;
  598. int start;
  599. if ((hSCManager = nt_service_open_scm()) == NULL)
  600. return -1;
  601. if ((hService = nt_service_open(hSCManager)) == NULL) {
  602. service_fns.CloseServiceHandle_fn(hSCManager);
  603. return -1;
  604. }
  605. start = nt_service_start(hService);
  606. service_fns.CloseServiceHandle_fn(hService);
  607. service_fns.CloseServiceHandle_fn(hSCManager);
  608. return start;
  609. }
  610. /** Stops the Tor service. Returns 0 on success, or -1 on error. */
  611. static int
  612. nt_service_cmd_stop(void)
  613. {
  614. SC_HANDLE hSCManager;
  615. SC_HANDLE hService;
  616. int stop;
  617. if ((hSCManager = nt_service_open_scm()) == NULL)
  618. return -1;
  619. if ((hService = nt_service_open(hSCManager)) == NULL) {
  620. service_fns.CloseServiceHandle_fn(hSCManager);
  621. return -1;
  622. }
  623. stop = nt_service_stop(hService);
  624. service_fns.CloseServiceHandle_fn(hService);
  625. service_fns.CloseServiceHandle_fn(hSCManager);
  626. return stop;
  627. }
  628. int
  629. nt_service_parse_options(int argc, char **argv, int *should_exit)
  630. {
  631. backup_argv = argv;
  632. backup_argc = argc;
  633. *should_exit = 0;
  634. if ((argc >= 3) &&
  635. (!strcmp(argv[1], "-service") || !strcmp(argv[1], "--service"))) {
  636. nt_service_loadlibrary();
  637. *should_exit = 1;
  638. if (!strcmp(argv[2], "install"))
  639. return nt_service_install(argc, argv);
  640. if (!strcmp(argv[2], "remove"))
  641. return nt_service_remove();
  642. if (!strcmp(argv[2], "start"))
  643. return nt_service_cmd_start();
  644. if (!strcmp(argv[2], "stop"))
  645. return nt_service_cmd_stop();
  646. printf("Unrecognized service command '%s'\n", argv[2]);
  647. return 1;
  648. }
  649. if (argc >= 2) {
  650. if (!strcmp(argv[1], "-nt-service") || !strcmp(argv[1], "--nt-service")) {
  651. nt_service_loadlibrary();
  652. nt_service_main();
  653. *should_exit = 1;
  654. return 0;
  655. }
  656. // These values have been deprecated since 0.1.1.2-alpha; we've warned
  657. // about them since 0.1.2.7-alpha.
  658. if (!strcmp(argv[1], "-install") || !strcmp(argv[1], "--install")) {
  659. nt_service_loadlibrary();
  660. fprintf(stderr,
  661. "The %s option is deprecated; use \"--service install\" instead.",
  662. argv[1]);
  663. *should_exit = 1;
  664. return nt_service_install(argc, argv);
  665. }
  666. if (!strcmp(argv[1], "-remove") || !strcmp(argv[1], "--remove")) {
  667. nt_service_loadlibrary();
  668. fprintf(stderr,
  669. "The %s option is deprecated; use \"--service remove\" instead.",
  670. argv[1]);
  671. *should_exit = 1;
  672. return nt_service_remove();
  673. }
  674. }
  675. *should_exit = 0;
  676. return 0;
  677. }