ntmain.c 25 KB

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