service.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. #include "nssm.h"
  2. SERVICE_STATUS service_status;
  3. SERVICE_STATUS_HANDLE service_handle;
  4. HANDLE process_handle;
  5. HANDLE wait_handle;
  6. unsigned long pid;
  7. static char service_name[SERVICE_NAME_LENGTH];
  8. char exe[EXE_LENGTH];
  9. char flags[CMD_LENGTH];
  10. char dir[MAX_PATH];
  11. bool stopping;
  12. unsigned long throttle_delay;
  13. HANDLE throttle_timer;
  14. LARGE_INTEGER throttle_duetime;
  15. static enum { NSSM_EXIT_RESTART, NSSM_EXIT_IGNORE, NSSM_EXIT_REALLY, NSSM_EXIT_UNCLEAN } exit_actions;
  16. static const char *exit_action_strings[] = { "Restart", "Ignore", "Exit", "Suicide", 0 };
  17. static unsigned long throttle;
  18. static inline int throttle_milliseconds() {
  19. /* pow() operates on doubles. */
  20. int ret = 1; for (unsigned long i = 1; i < throttle; i++) ret *= 2;
  21. return ret * 1000;
  22. }
  23. /* Connect to the service manager */
  24. SC_HANDLE open_service_manager() {
  25. SC_HANDLE ret = OpenSCManager(0, SERVICES_ACTIVE_DATABASE, SC_MANAGER_ALL_ACCESS);
  26. if (! ret) {
  27. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OPENSCMANAGER_FAILED, 0);
  28. return 0;
  29. }
  30. return ret;
  31. }
  32. /* About to install the service */
  33. int pre_install_service(int argc, char **argv) {
  34. /* Show the dialogue box if we didn't give the */
  35. if (argc < 2) return nssm_gui(IDD_INSTALL, argv[0]);
  36. /* Arguments are optional */
  37. char *flags;
  38. size_t flagslen = 0;
  39. size_t s = 0;
  40. int i;
  41. for (i = 2; i < argc; i++) flagslen += strlen(argv[i]) + 1;
  42. if (! flagslen) flagslen = 1;
  43. flags = (char *) HeapAlloc(GetProcessHeap(), 0, flagslen);
  44. if (! flags) {
  45. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, "flags", "pre_install_service()", 0);
  46. return 2;
  47. }
  48. ZeroMemory(flags, flagslen);
  49. /*
  50. This probably isn't UTF8-safe and should use std::string or something
  51. but it's been broken for the best part of a decade and due for a rewrite
  52. anyway so it'll do as a quick-'n'-dirty fix. Note that we don't free
  53. the flags buffer but as the program exits that isn't a big problem.
  54. */
  55. for (i = 2; i < argc; i++) {
  56. size_t len = strlen(argv[i]);
  57. memmove(flags + s, argv[i], len);
  58. s += len;
  59. if (i < argc - 1) flags[s++] = ' ';
  60. }
  61. return install_service(argv[0], argv[1], flags);
  62. }
  63. /* About to remove the service */
  64. int pre_remove_service(int argc, char **argv) {
  65. /* Show dialogue box if we didn't pass service name and "confirm" */
  66. if (argc < 2) return nssm_gui(IDD_REMOVE, argv[0]);
  67. if (str_equiv(argv[1], "confirm")) return remove_service(argv[0]);
  68. fprintf(stderr, "To remove a service without confirmation: nssm remove <servicename> confirm\n");
  69. return 100;
  70. }
  71. /* Install the service */
  72. int install_service(char *name, char *exe, char *flags) {
  73. /* Open service manager */
  74. SC_HANDLE services = open_service_manager();
  75. if (! services) {
  76. fprintf(stderr, "Error opening service manager!\n");
  77. return 2;
  78. }
  79. /* Get path of this program */
  80. char path[MAX_PATH];
  81. GetModuleFileName(0, path, MAX_PATH);
  82. /* Construct command */
  83. char command[CMD_LENGTH];
  84. size_t runlen = strlen(NSSM_RUN);
  85. size_t pathlen = strlen(path);
  86. if (pathlen + runlen + 2 >= VALUE_LENGTH) {
  87. fprintf(stderr, "The full path to " NSSM " is too long!\n");
  88. return 3;
  89. }
  90. if (_snprintf(command, sizeof(command), "\"%s\" %s", path, NSSM_RUN) < 0) {
  91. fprintf(stderr, "Out of memory for ImagePath!\n");
  92. return 4;
  93. }
  94. /* Work out directory name */
  95. size_t len = strlen(exe);
  96. size_t i;
  97. for (i = len; i && exe[i] != '\\' && exe[i] != '/'; i--);
  98. char dir[MAX_PATH];
  99. memmove(dir, exe, i);
  100. dir[i] = '\0';
  101. /* Create the service */
  102. SC_HANDLE service = CreateService(services, name, name, SC_MANAGER_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, command, 0, 0, 0, 0, 0);
  103. if (! service) {
  104. fprintf(stderr, "Error creating service!\n");
  105. CloseServiceHandle(services);
  106. return 5;
  107. }
  108. /* Now we need to put the parameters into the registry */
  109. if (create_parameters(name, exe, flags, dir)) {
  110. fprintf(stderr, "Error setting startup parameters for the service!\n");
  111. DeleteService(service);
  112. CloseServiceHandle(services);
  113. return 6;
  114. }
  115. /* Cleanup */
  116. CloseServiceHandle(service);
  117. CloseServiceHandle(services);
  118. printf("Service \"%s\" installed successfully!\n", name);
  119. return 0;
  120. }
  121. /* Remove the service */
  122. int remove_service(char *name) {
  123. /* Open service manager */
  124. SC_HANDLE services = open_service_manager();
  125. if (! services) {
  126. fprintf(stderr, "Error opening service manager!\n");
  127. return 2;
  128. }
  129. /* Try to open the service */
  130. SC_HANDLE service = OpenService(services, name, SC_MANAGER_ALL_ACCESS);
  131. if (! service) {
  132. fprintf(stderr, "Can't open service!");
  133. CloseServiceHandle(services);
  134. return 3;
  135. }
  136. /* Try to delete the service */
  137. if (! DeleteService(service)) {
  138. fprintf(stderr, "Error deleting service!\n");
  139. CloseServiceHandle(service);
  140. CloseServiceHandle(services);
  141. return 4;
  142. }
  143. /* Cleanup */
  144. CloseServiceHandle(service);
  145. CloseServiceHandle(services);
  146. printf("Service \"%s\" removed successfully!\n", name);
  147. return 0;
  148. }
  149. /* Service initialisation */
  150. void WINAPI service_main(unsigned long argc, char **argv) {
  151. if (_snprintf(service_name, sizeof(service_name), "%s", argv[0]) < 0) {
  152. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, "service_name", "service_main()", 0);
  153. return;
  154. }
  155. /* Initialise status */
  156. ZeroMemory(&service_status, sizeof(service_status));
  157. service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS;
  158. service_status.dwControlsAccepted = SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE;
  159. service_status.dwWin32ExitCode = NO_ERROR;
  160. service_status.dwServiceSpecificExitCode = 0;
  161. service_status.dwCheckPoint = 0;
  162. service_status.dwWaitHint = NSSM_WAITHINT_MARGIN;
  163. /* Signal we AREN'T running the server */
  164. process_handle = 0;
  165. pid = 0;
  166. /* Register control handler */
  167. service_handle = RegisterServiceCtrlHandlerEx(NSSM, service_control_handler, 0);
  168. if (! service_handle) {
  169. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_REGISTERSERVICECTRLHANDER_FAILED, error_string(GetLastError()), 0);
  170. return;
  171. }
  172. service_status.dwCurrentState = SERVICE_START_PENDING;
  173. service_status.dwWaitHint = throttle_delay + NSSM_WAITHINT_MARGIN;
  174. SetServiceStatus(service_handle, &service_status);
  175. /* Try to create the exit action parameters; we don't care if it fails */
  176. create_exit_action(argv[0], exit_action_strings[0]);
  177. set_service_recovery(service_name);
  178. /* Used for signalling a resume if the service pauses when throttled. */
  179. throttle_timer = CreateWaitableTimer(0, 1, 0);
  180. if (! throttle_timer) {
  181. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_CREATEWAITABLETIMER_FAILED, service_name, error_string(GetLastError()), 0);
  182. }
  183. monitor_service();
  184. }
  185. /* Make sure service recovery actions are taken where necessary */
  186. void set_service_recovery(char *service_name) {
  187. SC_HANDLE services = open_service_manager();
  188. if (! services) return;
  189. SC_HANDLE service = OpenService(services, service_name, SC_MANAGER_ALL_ACCESS);
  190. if (! service) return;
  191. return;
  192. SERVICE_FAILURE_ACTIONS_FLAG flag;
  193. ZeroMemory(&flag, sizeof(flag));
  194. flag.fFailureActionsOnNonCrashFailures = true;
  195. /* This functionality was added in Vista so the call may fail */
  196. ChangeServiceConfig2(service, SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, &flag);
  197. }
  198. int monitor_service() {
  199. /* Set service status to started */
  200. int ret = start_service();
  201. if (ret) {
  202. char code[16];
  203. _snprintf(code, sizeof(code), "%d", ret);
  204. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_START_SERVICE_FAILED, exe, service_name, ret, 0);
  205. return ret;
  206. }
  207. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_STARTED_SERVICE, exe, flags, service_name, dir, 0);
  208. /* Monitor service service */
  209. if (! RegisterWaitForSingleObject(&wait_handle, process_handle, end_service, (void *) pid, INFINITE, WT_EXECUTEONLYONCE | WT_EXECUTELONGFUNCTION)) {
  210. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_REGISTERWAITFORSINGLEOBJECT_FAILED, service_name, exe, error_string(GetLastError()), 0);
  211. }
  212. return 0;
  213. }
  214. /* Service control handler */
  215. unsigned long WINAPI service_control_handler(unsigned long control, unsigned long event, void *data, void *context) {
  216. switch (control) {
  217. case SERVICE_CONTROL_SHUTDOWN:
  218. case SERVICE_CONTROL_STOP:
  219. stop_service(0, true, true);
  220. return NO_ERROR;
  221. case SERVICE_CONTROL_CONTINUE:
  222. if (! throttle_timer) return ERROR_CALL_NOT_IMPLEMENTED;
  223. throttle = 0;
  224. ZeroMemory(&throttle_duetime, sizeof(throttle_duetime));
  225. SetWaitableTimer(throttle_timer, &throttle_duetime, 0, 0, 0, 0);
  226. service_status.dwCurrentState = SERVICE_CONTINUE_PENDING;
  227. service_status.dwWaitHint = throttle_milliseconds() + NSSM_WAITHINT_MARGIN;
  228. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_RESET_THROTTLE, service_name, 0);
  229. SetServiceStatus(service_handle, &service_status);
  230. return NO_ERROR;
  231. case SERVICE_CONTROL_PAUSE:
  232. /*
  233. We don't accept pause messages but it isn't possible to register
  234. only for continue messages so we have to handle this case.
  235. */
  236. return ERROR_CALL_NOT_IMPLEMENTED;
  237. }
  238. /* Unknown control */
  239. return ERROR_CALL_NOT_IMPLEMENTED;
  240. }
  241. /* Start the service */
  242. int start_service() {
  243. stopping = false;
  244. if (process_handle) return 0;
  245. /* Allocate a STARTUPINFO structure for a new process */
  246. STARTUPINFO si;
  247. ZeroMemory(&si, sizeof(si));
  248. si.cb = sizeof(si);
  249. /* Allocate a PROCESSINFO structure for the process */
  250. PROCESS_INFORMATION pi;
  251. ZeroMemory(&pi, sizeof(pi));
  252. /* Get startup parameters */
  253. int ret = get_parameters(service_name, exe, sizeof(exe), flags, sizeof(flags), dir, sizeof(dir), &throttle_delay);
  254. if (ret) {
  255. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GET_PARAMETERS_FAILED, service_name, 0);
  256. return stop_service(2, true, true);
  257. }
  258. /* Launch executable with arguments */
  259. char cmd[CMD_LENGTH];
  260. if (_snprintf(cmd, sizeof(cmd), "%s %s", exe, flags) < 0) {
  261. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, "command line", "start_service", 0);
  262. return stop_service(2, true, true);
  263. }
  264. throttle_restart();
  265. if (! CreateProcess(0, cmd, 0, 0, false, 0, 0, dir, &si, &pi)) {
  266. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEPROCESS_FAILED, service_name, exe, error_string(GetLastError()), 0);
  267. return stop_service(3, true, true);
  268. }
  269. process_handle = pi.hProcess;
  270. pid = pi.dwProcessId;
  271. /* Signal successful start */
  272. service_status.dwCurrentState = SERVICE_RUNNING;
  273. SetServiceStatus(service_handle, &service_status);
  274. /* Wait for a clean startup. */
  275. if (WaitForSingleObject(process_handle, throttle_delay) == WAIT_TIMEOUT) throttle = 0;
  276. return 0;
  277. }
  278. /* Stop the service */
  279. int stop_service(unsigned long exitcode, bool graceful, bool default_action) {
  280. if (default_action && ! exitcode && ! graceful) {
  281. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_GRACEFUL_SUICIDE, service_name, 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);
  282. graceful = true;
  283. }
  284. /* Signal we are stopping */
  285. if (graceful) {
  286. service_status.dwCurrentState = SERVICE_STOP_PENDING;
  287. service_status.dwWaitHint = NSSM_KILL_WINDOW_GRACE_PERIOD + NSSM_KILL_THREADS_GRACE_PERIOD + NSSM_WAITHINT_MARGIN;
  288. SetServiceStatus(service_handle, &service_status);
  289. }
  290. /* Nothing to do if server isn't running */
  291. if (pid) {
  292. /* Shut down server */
  293. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_TERMINATEPROCESS, service_name, exe, 0);
  294. kill_process(service_name, process_handle, pid, 0);
  295. process_handle = 0;
  296. }
  297. else log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_PROCESS_ALREADY_STOPPED, service_name, exe, 0);
  298. end_service((void *) pid, true);
  299. /* Signal we stopped */
  300. if (graceful) {
  301. service_status.dwCurrentState = SERVICE_STOPPED;
  302. if (exitcode) {
  303. service_status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
  304. service_status.dwServiceSpecificExitCode = exitcode;
  305. }
  306. else {
  307. service_status.dwWin32ExitCode = NO_ERROR;
  308. service_status.dwServiceSpecificExitCode = 0;
  309. }
  310. SetServiceStatus(service_handle, &service_status);
  311. }
  312. return exitcode;
  313. }
  314. /* Callback function triggered when the server exits */
  315. void CALLBACK end_service(void *arg, unsigned char why) {
  316. if (stopping) return;
  317. stopping = true;
  318. pid = (unsigned long) arg;
  319. /* Check exit code */
  320. unsigned long exitcode = 0;
  321. GetExitCodeProcess(process_handle, &exitcode);
  322. /* Clean up. */
  323. kill_process_tree(service_name, pid, exitcode, pid);
  324. /*
  325. The why argument is true if our wait timed out or false otherwise.
  326. Our wait is infinite so why will never be true when called by the system.
  327. If it is indeed true, assume we were called from stop_service() because
  328. this is a controlled shutdown, and don't take any restart action.
  329. */
  330. if (why) return;
  331. char code[16];
  332. _snprintf(code, sizeof(code), "%d", exitcode);
  333. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_ENDED_SERVICE, exe, service_name, code, 0);
  334. /* What action should we take? */
  335. int action = NSSM_EXIT_RESTART;
  336. unsigned char action_string[ACTION_LEN];
  337. bool default_action;
  338. if (! get_exit_action(service_name, &exitcode, action_string, &default_action)) {
  339. for (int i = 0; exit_action_strings[i]; i++) {
  340. if (! _strnicmp((const char *) action_string, exit_action_strings[i], ACTION_LEN)) {
  341. action = i;
  342. break;
  343. }
  344. }
  345. }
  346. process_handle = 0;
  347. pid = 0;
  348. switch (action) {
  349. /* Try to restart the service or return failure code to service manager */
  350. case NSSM_EXIT_RESTART:
  351. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_RESTART, service_name, code, exit_action_strings[action], exe, 0);
  352. while (monitor_service()) {
  353. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_RESTART_SERVICE_FAILED, exe, service_name, 0);
  354. Sleep(30000);
  355. }
  356. break;
  357. /* Do nothing, just like srvany would */
  358. case NSSM_EXIT_IGNORE:
  359. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_IGNORE, service_name, code, exit_action_strings[action], exe, 0);
  360. Sleep(INFINITE);
  361. break;
  362. /* Tell the service manager we are finished */
  363. case NSSM_EXIT_REALLY:
  364. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_REALLY, service_name, code, exit_action_strings[action], 0);
  365. stop_service(exitcode, true, default_action);
  366. break;
  367. /* Fake a crash so pre-Vista service managers will run recovery actions. */
  368. case NSSM_EXIT_UNCLEAN:
  369. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_UNCLEAN, service_name, code, exit_action_strings[action], 0);
  370. exit(stop_service(exitcode, false, default_action));
  371. break;
  372. }
  373. }
  374. void throttle_restart() {
  375. /* This can't be a restart if the service is already running. */
  376. if (! throttle++) return;
  377. int ms = throttle_milliseconds();
  378. if (throttle > 7) throttle = 8;
  379. char threshold[8], milliseconds[8];
  380. _snprintf(threshold, sizeof(threshold), "%d", throttle_delay);
  381. _snprintf(milliseconds, sizeof(milliseconds), "%d", ms);
  382. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_THROTTLED, service_name, threshold, milliseconds, 0);
  383. if (throttle_timer) {
  384. ZeroMemory(&throttle_duetime, sizeof(throttle_duetime));
  385. throttle_duetime.QuadPart = 0 - (ms * 10000LL);
  386. SetWaitableTimer(throttle_timer, &throttle_duetime, 0, 0, 0, 0);
  387. }
  388. service_status.dwCurrentState = SERVICE_PAUSED;
  389. SetServiceStatus(service_handle, &service_status);
  390. if (throttle_timer) WaitForSingleObject(throttle_timer, INFINITE);
  391. else Sleep(ms);
  392. }