ntmain.c 25 KB

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