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