service.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. #include "nssm.h"
  2. bool is_admin;
  3. bool use_critical_section;
  4. extern imports_t imports;
  5. const TCHAR *exit_action_strings[] = { _T("Restart"), _T("Ignore"), _T("Exit"), _T("Suicide"), 0 };
  6. static inline int throttle_milliseconds(unsigned long throttle) {
  7. /* pow() operates on doubles. */
  8. int ret = 1; for (unsigned long i = 1; i < throttle; i++) ret *= 2;
  9. return ret * 1000;
  10. }
  11. /*
  12. Wrapper to be called in a new thread so that we can acknowledge a STOP
  13. control immediately.
  14. */
  15. static unsigned long WINAPI shutdown_service(void *arg) {
  16. return stop_service((nssm_service_t *) arg, 0, true, true);
  17. }
  18. /* Connect to the service manager */
  19. SC_HANDLE open_service_manager() {
  20. SC_HANDLE ret = OpenSCManager(0, SERVICES_ACTIVE_DATABASE, SC_MANAGER_ALL_ACCESS);
  21. if (! ret) {
  22. if (is_admin) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OPENSCMANAGER_FAILED, 0);
  23. return 0;
  24. }
  25. return ret;
  26. }
  27. /* Set default values which aren't zero. */
  28. void set_nssm_service_defaults(nssm_service_t *service) {
  29. if (! service) return;
  30. service->stdin_sharing = NSSM_STDIN_SHARING;
  31. service->stdin_disposition = NSSM_STDIN_DISPOSITION;
  32. service->stdin_flags = NSSM_STDIN_FLAGS;
  33. service->stdout_sharing = NSSM_STDOUT_SHARING;
  34. service->stdout_disposition = NSSM_STDOUT_DISPOSITION;
  35. service->stdout_flags = NSSM_STDOUT_FLAGS;
  36. service->stderr_sharing = NSSM_STDERR_SHARING;
  37. service->stderr_disposition = NSSM_STDERR_DISPOSITION;
  38. service->stderr_flags = NSSM_STDERR_FLAGS;
  39. service->throttle_delay = NSSM_RESET_THROTTLE_RESTART;
  40. service->stop_method = ~0;
  41. service->kill_console_delay = NSSM_KILL_CONSOLE_GRACE_PERIOD;
  42. service->kill_window_delay = NSSM_KILL_WINDOW_GRACE_PERIOD;
  43. service->kill_threads_delay = NSSM_KILL_THREADS_GRACE_PERIOD;
  44. }
  45. /* Allocate and zero memory for a service. */
  46. nssm_service_t *alloc_nssm_service() {
  47. nssm_service_t *service = (nssm_service_t *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(nssm_service_t));
  48. if (! service) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("service"), _T("alloc_nssm_service()"), 0);
  49. return service;
  50. }
  51. /* Free memory for a service. */
  52. void cleanup_nssm_service(nssm_service_t *service) {
  53. if (! service) return;
  54. if (service->env) HeapFree(GetProcessHeap(), 0, service->env);
  55. if (service->env_extra) HeapFree(GetProcessHeap(), 0, service->env_extra);
  56. if (service->handle) CloseServiceHandle(service->handle);
  57. if (service->process_handle) CloseHandle(service->process_handle);
  58. if (service->wait_handle) UnregisterWait(service->process_handle);
  59. if (service->throttle_section_initialised) DeleteCriticalSection(&service->throttle_section);
  60. if (service->throttle_timer) CloseHandle(service->throttle_timer);
  61. HeapFree(GetProcessHeap(), 0, service);
  62. }
  63. /* About to install the service */
  64. int pre_install_service(int argc, TCHAR **argv) {
  65. /* Show the dialogue box if we didn't give the service name and path */
  66. if (argc < 2) return nssm_gui(IDD_INSTALL, argv[0]);
  67. nssm_service_t *service = alloc_nssm_service();
  68. if (! service) {
  69. print_message(stderr, NSSM_EVENT_OUT_OF_MEMORY, _T("service"), _T("pre_install_service()"));
  70. return 1;
  71. }
  72. set_nssm_service_defaults(service);
  73. _sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), argv[0]);
  74. _sntprintf_s(service->exe, _countof(service->exe), _TRUNCATE, _T("%s"), argv[1]);
  75. /* Arguments are optional */
  76. size_t flagslen = 0;
  77. size_t s = 0;
  78. int i;
  79. for (i = 2; i < argc; i++) flagslen += _tcslen(argv[i]) + 1;
  80. if (! flagslen) flagslen = 1;
  81. if (flagslen > _countof(service->flags)) {
  82. print_message(stderr, NSSM_MESSAGE_FLAGS_TOO_LONG);
  83. return 2;
  84. }
  85. for (i = 2; i < argc; i++) {
  86. size_t len = _tcslen(argv[i]);
  87. memmove(service->flags + s, argv[i], len * sizeof(TCHAR));
  88. s += len;
  89. if (i < argc - 1) service->flags[s++] = _T(' ');
  90. }
  91. /* Work out directory name */
  92. _sntprintf_s(service->dir, _countof(service->dir), _TRUNCATE, _T("%s"), service->exe);
  93. strip_basename(service->dir);
  94. int ret = install_service(service);
  95. cleanup_nssm_service(service);
  96. return ret;
  97. }
  98. /* About to remove the service */
  99. int pre_remove_service(int argc, TCHAR **argv) {
  100. /* Show dialogue box if we didn't pass service name and "confirm" */
  101. if (argc < 2) return nssm_gui(IDD_REMOVE, argv[0]);
  102. if (str_equiv(argv[1], _T("confirm"))) {
  103. nssm_service_t *service = alloc_nssm_service();
  104. _sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), argv[0]);
  105. int ret = remove_service(service);
  106. cleanup_nssm_service(service);
  107. return ret;
  108. }
  109. print_message(stderr, NSSM_MESSAGE_PRE_REMOVE_SERVICE);
  110. return 100;
  111. }
  112. /* Install the service */
  113. int install_service(nssm_service_t *service) {
  114. if (! service) return 1;
  115. /* Open service manager */
  116. SC_HANDLE services = open_service_manager();
  117. if (! services) {
  118. print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
  119. cleanup_nssm_service(service);
  120. return 2;
  121. }
  122. /* Get path of this program */
  123. TCHAR command[MAX_PATH];
  124. GetModuleFileName(0, command, _countof(command));
  125. /* Startup type. */
  126. unsigned long startup;
  127. switch (service->startup) {
  128. case NSSM_STARTUP_MANUAL: startup = SERVICE_DEMAND_START; break;
  129. case NSSM_STARTUP_DISABLED: startup = SERVICE_DISABLED; break;
  130. default: startup = SERVICE_AUTO_START;
  131. }
  132. /* Display name. */
  133. if (! service->displayname[0]) _sntprintf_s(service->displayname, _countof(service->displayname), _TRUNCATE, _T("%s"), service->name);
  134. /* Create the service */
  135. service->handle = CreateService(services, service->name, service->displayname, SC_MANAGER_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, startup, SERVICE_ERROR_NORMAL, command, 0, 0, 0, 0, 0);
  136. if (! service->handle) {
  137. print_message(stderr, NSSM_MESSAGE_CREATESERVICE_FAILED);
  138. CloseServiceHandle(services);
  139. return 5;
  140. }
  141. if (service->description[0]) {
  142. SERVICE_DESCRIPTION description;
  143. ZeroMemory(&description, sizeof(description));
  144. description.lpDescription = service->description;
  145. if (! ChangeServiceConfig2(service->handle, SERVICE_CONFIG_DESCRIPTION, &description)) {
  146. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SERVICE_CONFIG_DESCRIPTION_FAILED, service->name, error_string(GetLastError()), 0);
  147. }
  148. }
  149. if (service->startup == NSSM_STARTUP_DELAYED) {
  150. SERVICE_DELAYED_AUTO_START_INFO delayed;
  151. ZeroMemory(&delayed, sizeof(delayed));
  152. delayed.fDelayedAutostart = 1;
  153. /* Delayed startup isn't supported until Vista. */
  154. if (! ChangeServiceConfig2(service->handle, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, &delayed)) {
  155. unsigned long error = GetLastError();
  156. /* Pre-Vista we expect to fail with ERROR_INVALID_LEVEL */
  157. if (error != ERROR_INVALID_LEVEL) {
  158. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SERVICE_CONFIG_DELAYED_AUTO_START_INFO_FAILED, service->name, error_string(error), 0);
  159. }
  160. }
  161. }
  162. /* Now we need to put the parameters into the registry */
  163. if (create_parameters(service)) {
  164. print_message(stderr, NSSM_MESSAGE_CREATE_PARAMETERS_FAILED);
  165. DeleteService(service->handle);
  166. CloseServiceHandle(services);
  167. return 6;
  168. }
  169. set_service_recovery(service);
  170. print_message(stdout, NSSM_MESSAGE_SERVICE_INSTALLED, service->name);
  171. /* Cleanup */
  172. CloseServiceHandle(services);
  173. return 0;
  174. }
  175. /* Remove the service */
  176. int remove_service(nssm_service_t *service) {
  177. if (! service) return 1;
  178. /* Open service manager */
  179. SC_HANDLE services = open_service_manager();
  180. if (! services) {
  181. print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
  182. return 2;
  183. }
  184. /* Try to open the service */
  185. service->handle = OpenService(services, service->name, SC_MANAGER_ALL_ACCESS);
  186. if (! service->handle) {
  187. print_message(stderr, NSSM_MESSAGE_OPENSERVICE_FAILED);
  188. CloseServiceHandle(services);
  189. return 3;
  190. }
  191. /* Try to delete the service */
  192. if (! DeleteService(service->handle)) {
  193. print_message(stderr, NSSM_MESSAGE_DELETESERVICE_FAILED);
  194. CloseServiceHandle(services);
  195. return 4;
  196. }
  197. /* Cleanup */
  198. CloseServiceHandle(services);
  199. print_message(stdout, NSSM_MESSAGE_SERVICE_REMOVED, service->name);
  200. return 0;
  201. }
  202. /* Service initialisation */
  203. void WINAPI service_main(unsigned long argc, TCHAR **argv) {
  204. nssm_service_t *service = alloc_nssm_service();
  205. if (! service) return;
  206. if (_sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), argv[0]) < 0) {
  207. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("service->name"), _T("service_main()"), 0);
  208. return;
  209. }
  210. /* We can use a condition variable in a critical section on Vista or later. */
  211. if (imports.SleepConditionVariableCS && imports.WakeConditionVariable) use_critical_section = true;
  212. else use_critical_section = false;
  213. /* Initialise status */
  214. ZeroMemory(&service->status, sizeof(service->status));
  215. service->status.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS;
  216. service->status.dwControlsAccepted = SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE;
  217. service->status.dwWin32ExitCode = NO_ERROR;
  218. service->status.dwServiceSpecificExitCode = 0;
  219. service->status.dwCheckPoint = 0;
  220. service->status.dwWaitHint = NSSM_WAITHINT_MARGIN;
  221. /* Signal we AREN'T running the server */
  222. service->process_handle = 0;
  223. service->pid = 0;
  224. /* Register control handler */
  225. service->status_handle = RegisterServiceCtrlHandlerEx(NSSM, service_control_handler, (void *) service);
  226. if (! service->status_handle) {
  227. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_REGISTERSERVICECTRLHANDER_FAILED, error_string(GetLastError()), 0);
  228. return;
  229. }
  230. log_service_control(service->name, 0, true);
  231. service->status.dwCurrentState = SERVICE_START_PENDING;
  232. service->status.dwWaitHint = service->throttle_delay + NSSM_WAITHINT_MARGIN;
  233. SetServiceStatus(service->status_handle, &service->status);
  234. if (is_admin) {
  235. /* Try to create the exit action parameters; we don't care if it fails */
  236. create_exit_action(service->name, exit_action_strings[0]);
  237. SC_HANDLE services = open_service_manager();
  238. if (services) {
  239. service->handle = OpenService(services, service->name, SC_MANAGER_ALL_ACCESS);
  240. set_service_recovery(service);
  241. CloseServiceHandle(services);
  242. }
  243. }
  244. /* Used for signalling a resume if the service pauses when throttled. */
  245. if (use_critical_section) {
  246. InitializeCriticalSection(&service->throttle_section);
  247. service->throttle_section_initialised = true;
  248. }
  249. else {
  250. service->throttle_timer = CreateWaitableTimer(0, 1, 0);
  251. if (! service->throttle_timer) {
  252. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_CREATEWAITABLETIMER_FAILED, service->name, error_string(GetLastError()), 0);
  253. }
  254. }
  255. monitor_service(service);
  256. }
  257. /* Make sure service recovery actions are taken where necessary */
  258. void set_service_recovery(nssm_service_t *service) {
  259. SERVICE_FAILURE_ACTIONS_FLAG flag;
  260. ZeroMemory(&flag, sizeof(flag));
  261. flag.fFailureActionsOnNonCrashFailures = true;
  262. /* This functionality was added in Vista so the call may fail */
  263. if (! ChangeServiceConfig2(service->handle, SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, &flag)) {
  264. unsigned long error = GetLastError();
  265. /* Pre-Vista we expect to fail with ERROR_INVALID_LEVEL */
  266. if (error != ERROR_INVALID_LEVEL) {
  267. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SERVICE_CONFIG_FAILURE_ACTIONS_FAILED, service->name, error_string(error), 0);
  268. }
  269. }
  270. }
  271. int monitor_service(nssm_service_t *service) {
  272. /* Set service status to started */
  273. int ret = start_service(service);
  274. if (ret) {
  275. TCHAR code[16];
  276. _sntprintf_s(code, _countof(code), _TRUNCATE, _T("%d"), ret);
  277. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_START_SERVICE_FAILED, service->exe, service->name, ret, 0);
  278. return ret;
  279. }
  280. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_STARTED_SERVICE, service->exe, service->flags, service->name, service->dir, 0);
  281. /* Monitor service */
  282. if (! RegisterWaitForSingleObject(&service->wait_handle, service->process_handle, end_service, (void *) service, INFINITE, WT_EXECUTEONLYONCE | WT_EXECUTELONGFUNCTION)) {
  283. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_REGISTERWAITFORSINGLEOBJECT_FAILED, service->name, service->exe, error_string(GetLastError()), 0);
  284. }
  285. return 0;
  286. }
  287. TCHAR *service_control_text(unsigned long control) {
  288. switch (control) {
  289. /* HACK: there is no SERVICE_CONTROL_START constant */
  290. case 0: return _T("START");
  291. case SERVICE_CONTROL_STOP: return _T("STOP");
  292. case SERVICE_CONTROL_SHUTDOWN: return _T("SHUTDOWN");
  293. case SERVICE_CONTROL_PAUSE: return _T("PAUSE");
  294. case SERVICE_CONTROL_CONTINUE: return _T("CONTINUE");
  295. case SERVICE_CONTROL_INTERROGATE: return _T("INTERROGATE");
  296. default: return 0;
  297. }
  298. }
  299. void log_service_control(TCHAR *service_name, unsigned long control, bool handled) {
  300. TCHAR *text = service_control_text(control);
  301. unsigned long event;
  302. if (! text) {
  303. /* "0x" + 8 x hex + NULL */
  304. text = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, 11 * sizeof(TCHAR));
  305. if (! text) {
  306. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("control code"), _T("log_service_control()"), 0);
  307. return;
  308. }
  309. if (_sntprintf_s(text, 11, _TRUNCATE, _T("0x%08x"), control) < 0) {
  310. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("control code"), _T("log_service_control()"), 0);
  311. HeapFree(GetProcessHeap(), 0, text);
  312. return;
  313. }
  314. event = NSSM_EVENT_SERVICE_CONTROL_UNKNOWN;
  315. }
  316. else if (handled) event = NSSM_EVENT_SERVICE_CONTROL_HANDLED;
  317. else event = NSSM_EVENT_SERVICE_CONTROL_NOT_HANDLED;
  318. log_event(EVENTLOG_INFORMATION_TYPE, event, service_name, text, 0);
  319. if (event == NSSM_EVENT_SERVICE_CONTROL_UNKNOWN) {
  320. HeapFree(GetProcessHeap(), 0, text);
  321. }
  322. }
  323. /* Service control handler */
  324. unsigned long WINAPI service_control_handler(unsigned long control, unsigned long event, void *data, void *context) {
  325. nssm_service_t *service = (nssm_service_t *) context;
  326. switch (control) {
  327. case SERVICE_CONTROL_INTERROGATE:
  328. /* We always keep the service status up-to-date so this is a no-op. */
  329. return NO_ERROR;
  330. case SERVICE_CONTROL_SHUTDOWN:
  331. case SERVICE_CONTROL_STOP:
  332. log_service_control(service->name, control, true);
  333. /*
  334. We MUST acknowledge the stop request promptly but we're committed to
  335. waiting for the application to exit. Spawn a new thread to wait
  336. while we acknowledge the request.
  337. */
  338. if (! CreateThread(NULL, 0, shutdown_service, context, 0, NULL)) {
  339. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATETHREAD_FAILED, error_string(GetLastError()), 0);
  340. /*
  341. We couldn't create a thread to tidy up so we'll have to force the tidyup
  342. to complete in time in this thread.
  343. */
  344. service->kill_console_delay = NSSM_KILL_CONSOLE_GRACE_PERIOD;
  345. service->kill_window_delay = NSSM_KILL_WINDOW_GRACE_PERIOD;
  346. service->kill_threads_delay = NSSM_KILL_THREADS_GRACE_PERIOD;
  347. stop_service(service, 0, true, true);
  348. }
  349. return NO_ERROR;
  350. case SERVICE_CONTROL_CONTINUE:
  351. log_service_control(service->name, control, true);
  352. service->throttle = 0;
  353. if (use_critical_section) imports.WakeConditionVariable(&service->throttle_condition);
  354. else {
  355. if (! service->throttle_timer) return ERROR_CALL_NOT_IMPLEMENTED;
  356. ZeroMemory(&service->throttle_duetime, sizeof(service->throttle_duetime));
  357. SetWaitableTimer(service->throttle_timer, &service->throttle_duetime, 0, 0, 0, 0);
  358. }
  359. service->status.dwCurrentState = SERVICE_CONTINUE_PENDING;
  360. service->status.dwWaitHint = throttle_milliseconds(service->throttle) + NSSM_WAITHINT_MARGIN;
  361. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_RESET_THROTTLE, service->name, 0);
  362. SetServiceStatus(service->status_handle, &service->status);
  363. return NO_ERROR;
  364. case SERVICE_CONTROL_PAUSE:
  365. /*
  366. We don't accept pause messages but it isn't possible to register
  367. only for continue messages so we have to handle this case.
  368. */
  369. log_service_control(service->name, control, false);
  370. return ERROR_CALL_NOT_IMPLEMENTED;
  371. }
  372. /* Unknown control */
  373. log_service_control(service->name, control, false);
  374. return ERROR_CALL_NOT_IMPLEMENTED;
  375. }
  376. /* Start the service */
  377. int start_service(nssm_service_t *service) {
  378. service->stopping = false;
  379. service->allow_restart = true;
  380. if (service->process_handle) return 0;
  381. /* Allocate a STARTUPINFO structure for a new process */
  382. STARTUPINFO si;
  383. ZeroMemory(&si, sizeof(si));
  384. si.cb = sizeof(si);
  385. /* Allocate a PROCESSINFO structure for the process */
  386. PROCESS_INFORMATION pi;
  387. ZeroMemory(&pi, sizeof(pi));
  388. /* Get startup parameters */
  389. int ret = get_parameters(service, &si);
  390. if (ret) {
  391. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GET_PARAMETERS_FAILED, service->name, 0);
  392. return stop_service(service, 2, true, true);
  393. }
  394. /* Launch executable with arguments */
  395. TCHAR cmd[CMD_LENGTH];
  396. if (_sntprintf_s(cmd, _countof(cmd), _TRUNCATE, _T("\"%s\" %s"), service->exe, service->flags) < 0) {
  397. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("command line"), _T("start_service"), 0);
  398. close_output_handles(&si);
  399. return stop_service(service, 2, true, true);
  400. }
  401. throttle_restart(service);
  402. bool inherit_handles = false;
  403. if (si.dwFlags & STARTF_USESTDHANDLES) inherit_handles = true;
  404. unsigned long flags = 0;
  405. #ifdef UNICODE
  406. flags |= CREATE_UNICODE_ENVIRONMENT;
  407. #endif
  408. if (! CreateProcess(0, cmd, 0, 0, inherit_handles, flags, service->env, service->dir, &si, &pi)) {
  409. unsigned long exitcode = 3;
  410. unsigned long error = GetLastError();
  411. if (error == ERROR_INVALID_PARAMETER && service->env) {
  412. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEPROCESS_FAILED_INVALID_ENVIRONMENT, service->name, service->exe, NSSM_REG_ENV, 0);
  413. if (test_environment(service->env)) exitcode = 4;
  414. }
  415. else log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEPROCESS_FAILED, service->name, service->exe, error_string(error), 0);
  416. close_output_handles(&si);
  417. return stop_service(service, exitcode, true, true);
  418. }
  419. service->process_handle = pi.hProcess;
  420. service->pid = pi.dwProcessId;
  421. if (get_process_creation_time(service->process_handle, &service->creation_time)) ZeroMemory(&service->creation_time, sizeof(service->creation_time));
  422. close_output_handles(&si);
  423. /*
  424. Wait for a clean startup before changing the service status to RUNNING
  425. but be mindful of the fact that we are blocking the service control manager
  426. so abandon the wait before too much time has elapsed.
  427. */
  428. unsigned long delay = service->throttle_delay;
  429. if (delay > NSSM_SERVICE_STATUS_DEADLINE) {
  430. TCHAR delay_milliseconds[16];
  431. _sntprintf_s(delay_milliseconds, _countof(delay_milliseconds), _TRUNCATE, _T("%lu"), delay);
  432. TCHAR deadline_milliseconds[16];
  433. _sntprintf_s(deadline_milliseconds, _countof(deadline_milliseconds), _TRUNCATE, _T("%lu"), NSSM_SERVICE_STATUS_DEADLINE);
  434. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_STARTUP_DELAY_TOO_LONG, service->name, delay_milliseconds, NSSM, deadline_milliseconds, 0);
  435. delay = NSSM_SERVICE_STATUS_DEADLINE;
  436. }
  437. unsigned long deadline = WaitForSingleObject(service->process_handle, delay);
  438. /* Signal successful start */
  439. service->status.dwCurrentState = SERVICE_RUNNING;
  440. SetServiceStatus(service->status_handle, &service->status);
  441. /* Continue waiting for a clean startup. */
  442. if (deadline == WAIT_TIMEOUT) {
  443. if (service->throttle_delay > delay) {
  444. if (WaitForSingleObject(service->process_handle, service->throttle_delay - delay) == WAIT_TIMEOUT) service->throttle = 0;
  445. }
  446. else service->throttle = 0;
  447. }
  448. return 0;
  449. }
  450. /* Stop the service */
  451. int stop_service(nssm_service_t *service, unsigned long exitcode, bool graceful, bool default_action) {
  452. service->allow_restart = false;
  453. if (service->wait_handle) {
  454. UnregisterWait(service->wait_handle);
  455. service->wait_handle = 0;
  456. }
  457. if (default_action && ! exitcode && ! graceful) {
  458. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_GRACEFUL_SUICIDE, service->name, service->exe, exit_action_strings[NSSM_EXIT_UNCLEAN], exit_action_strings[NSSM_EXIT_UNCLEAN], exit_action_strings[NSSM_EXIT_UNCLEAN], exit_action_strings[NSSM_EXIT_REALLY], 0);
  459. graceful = true;
  460. }
  461. /* Signal we are stopping */
  462. if (graceful) {
  463. service->status.dwCurrentState = SERVICE_STOP_PENDING;
  464. service->status.dwWaitHint = NSSM_WAITHINT_MARGIN;
  465. SetServiceStatus(service->status_handle, &service->status);
  466. }
  467. /* Nothing to do if service isn't running */
  468. if (service->pid) {
  469. /* Shut down service */
  470. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_TERMINATEPROCESS, service->name, service->exe, 0);
  471. kill_process(service, service->process_handle, service->pid, 0);
  472. }
  473. else log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_PROCESS_ALREADY_STOPPED, service->name, service->exe, 0);
  474. end_service((void *) service, true);
  475. /* Signal we stopped */
  476. if (graceful) {
  477. service->status.dwCurrentState = SERVICE_STOPPED;
  478. if (exitcode) {
  479. service->status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
  480. service->status.dwServiceSpecificExitCode = exitcode;
  481. }
  482. else {
  483. service->status.dwWin32ExitCode = NO_ERROR;
  484. service->status.dwServiceSpecificExitCode = 0;
  485. }
  486. SetServiceStatus(service->status_handle, &service->status);
  487. }
  488. return exitcode;
  489. }
  490. /* Callback function triggered when the server exits */
  491. void CALLBACK end_service(void *arg, unsigned char why) {
  492. nssm_service_t *service = (nssm_service_t *) arg;
  493. if (service->stopping) return;
  494. service->stopping = true;
  495. /* Check exit code */
  496. unsigned long exitcode = 0;
  497. TCHAR code[16];
  498. if (service->process_handle) {
  499. GetExitCodeProcess(service->process_handle, &exitcode);
  500. if (exitcode == STILL_ACTIVE || get_process_exit_time(service->process_handle, &service->exit_time)) GetSystemTimeAsFileTime(&service->exit_time);
  501. CloseHandle(service->process_handle);
  502. }
  503. else GetSystemTimeAsFileTime(&service->exit_time);
  504. service->process_handle = 0;
  505. /*
  506. Log that the service ended BEFORE logging about killing the process
  507. tree. See below for the possible values of the why argument.
  508. */
  509. if (! why) {
  510. _sntprintf_s(code, _countof(code), _TRUNCATE, _T("%lu"), exitcode);
  511. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_ENDED_SERVICE, service->exe, service->name, code, 0);
  512. }
  513. /* Clean up. */
  514. if (exitcode == STILL_ACTIVE) exitcode = 0;
  515. if (service->pid) kill_process_tree(service, service->pid, exitcode, service->pid);
  516. service->pid = 0;
  517. /*
  518. The why argument is true if our wait timed out or false otherwise.
  519. Our wait is infinite so why will never be true when called by the system.
  520. If it is indeed true, assume we were called from stop_service() because
  521. this is a controlled shutdown, and don't take any restart action.
  522. */
  523. if (why) return;
  524. if (! service->allow_restart) return;
  525. /* What action should we take? */
  526. int action = NSSM_EXIT_RESTART;
  527. TCHAR action_string[ACTION_LEN];
  528. bool default_action;
  529. if (! get_exit_action(service->name, &exitcode, action_string, &default_action)) {
  530. for (int i = 0; exit_action_strings[i]; i++) {
  531. if (! _tcsnicmp((const TCHAR *) action_string, exit_action_strings[i], ACTION_LEN)) {
  532. action = i;
  533. break;
  534. }
  535. }
  536. }
  537. switch (action) {
  538. /* Try to restart the service or return failure code to service manager */
  539. case NSSM_EXIT_RESTART:
  540. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_RESTART, service->name, code, exit_action_strings[action], service->exe, 0);
  541. while (monitor_service(service)) {
  542. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_RESTART_SERVICE_FAILED, service->exe, service->name, 0);
  543. Sleep(30000);
  544. }
  545. break;
  546. /* Do nothing, just like srvany would */
  547. case NSSM_EXIT_IGNORE:
  548. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_IGNORE, service->name, code, exit_action_strings[action], service->exe, 0);
  549. Sleep(INFINITE);
  550. break;
  551. /* Tell the service manager we are finished */
  552. case NSSM_EXIT_REALLY:
  553. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_REALLY, service->name, code, exit_action_strings[action], 0);
  554. stop_service(service, exitcode, true, default_action);
  555. break;
  556. /* Fake a crash so pre-Vista service managers will run recovery actions. */
  557. case NSSM_EXIT_UNCLEAN:
  558. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_UNCLEAN, service->name, code, exit_action_strings[action], 0);
  559. stop_service(service, exitcode, false, default_action);
  560. free_imports();
  561. exit(exitcode);
  562. break;
  563. }
  564. }
  565. void throttle_restart(nssm_service_t *service) {
  566. /* This can't be a restart if the service is already running. */
  567. if (! service->throttle++) return;
  568. int ms = throttle_milliseconds(service->throttle);
  569. if (service->throttle > 7) service->throttle = 8;
  570. TCHAR threshold[8], milliseconds[8];
  571. _sntprintf_s(threshold, _countof(threshold), _TRUNCATE, _T("%lu"), service->throttle_delay);
  572. _sntprintf_s(milliseconds, _countof(milliseconds), _TRUNCATE, _T("%lu"), ms);
  573. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_THROTTLED, service->name, threshold, milliseconds, 0);
  574. if (use_critical_section) EnterCriticalSection(&service->throttle_section);
  575. else if (service->throttle_timer) {
  576. ZeroMemory(&service->throttle_duetime, sizeof(service->throttle_duetime));
  577. service->throttle_duetime.QuadPart = 0 - (ms * 10000LL);
  578. SetWaitableTimer(service->throttle_timer, &service->throttle_duetime, 0, 0, 0, 0);
  579. }
  580. service->status.dwCurrentState = SERVICE_PAUSED;
  581. SetServiceStatus(service->status_handle, &service->status);
  582. if (use_critical_section) {
  583. imports.SleepConditionVariableCS(&service->throttle_condition, &service->throttle_section, ms);
  584. LeaveCriticalSection(&service->throttle_section);
  585. }
  586. else {
  587. if (service->throttle_timer) WaitForSingleObject(service->throttle_timer, INFINITE);
  588. else Sleep(ms);
  589. }
  590. }
  591. /*
  592. When responding to a stop (or any other) request we need to set dwWaitHint to
  593. the number of milliseconds we expect the operation to take, and optionally
  594. increase dwCheckPoint. If dwWaitHint milliseconds elapses without the
  595. operation completing or dwCheckPoint increasing, the system will consider the
  596. service to be hung.
  597. However the system will consider the service to be hung after 30000
  598. milliseconds regardless of the value of dwWaitHint if dwCheckPoint has not
  599. changed. Therefore if we want to wait longer than that we must periodically
  600. increase dwCheckPoint.
  601. Furthermore, it will consider the service to be hung after 60000 milliseconds
  602. regardless of the value of dwCheckPoint unless dwWaitHint is increased every
  603. time dwCheckPoint is also increased.
  604. Our strategy then is to retrieve the initial dwWaitHint and wait for
  605. NSSM_SERVICE_STATUS_DEADLINE milliseconds. If the process is still running
  606. and we haven't finished waiting we increment dwCheckPoint and add whichever is
  607. smaller of NSSM_SERVICE_STATUS_DEADLINE or the remaining timeout to
  608. dwWaitHint.
  609. Only doing both these things will prevent the system from killing the service.
  610. Returns: 1 if the wait timed out.
  611. 0 if the wait completed.
  612. -1 on error.
  613. */
  614. int await_shutdown(nssm_service_t *service, TCHAR *function_name, unsigned long timeout) {
  615. unsigned long interval;
  616. unsigned long waithint;
  617. unsigned long ret;
  618. unsigned long waited;
  619. TCHAR interval_milliseconds[16];
  620. TCHAR timeout_milliseconds[16];
  621. TCHAR waited_milliseconds[16];
  622. TCHAR *function = function_name;
  623. /* Add brackets to function name. */
  624. size_t funclen = _tcslen(function_name) + 3;
  625. TCHAR *func = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, funclen * sizeof(TCHAR));
  626. if (func) {
  627. if (_sntprintf_s(func, funclen, _TRUNCATE, _T("%s()"), function_name) > -1) function = func;
  628. }
  629. _sntprintf_s(timeout_milliseconds, _countof(timeout_milliseconds), _TRUNCATE, _T("%lu"), timeout);
  630. waithint = service->status.dwWaitHint;
  631. waited = 0;
  632. while (waited < timeout) {
  633. interval = timeout - waited;
  634. if (interval > NSSM_SERVICE_STATUS_DEADLINE) interval = NSSM_SERVICE_STATUS_DEADLINE;
  635. service->status.dwCurrentState = SERVICE_STOP_PENDING;
  636. service->status.dwWaitHint += interval;
  637. service->status.dwCheckPoint++;
  638. SetServiceStatus(service->status_handle, &service->status);
  639. if (waited) {
  640. _sntprintf_s(waited_milliseconds, _countof(waited_milliseconds), _TRUNCATE, _T("%lu"), waited);
  641. _sntprintf_s(interval_milliseconds, _countof(interval_milliseconds), _TRUNCATE, _T("%lu"), interval);
  642. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_AWAITING_SHUTDOWN, function, service->name, waited_milliseconds, interval_milliseconds, timeout_milliseconds, 0);
  643. }
  644. switch (WaitForSingleObject(service->process_handle, interval)) {
  645. case WAIT_OBJECT_0:
  646. ret = 0;
  647. goto awaited;
  648. case WAIT_TIMEOUT:
  649. ret = 1;
  650. break;
  651. default:
  652. ret = -1;
  653. goto awaited;
  654. }
  655. waited += interval;
  656. }
  657. awaited:
  658. if (func) HeapFree(GetProcessHeap(), 0, func);
  659. return ret;
  660. }