service.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. monitor_service();
  181. }
  182. /* Make sure service recovery actions are taken where necessary */
  183. void set_service_recovery(char *service_name) {
  184. SC_HANDLE services = open_service_manager();
  185. if (! services) return;
  186. SC_HANDLE service = OpenService(services, service_name, SC_MANAGER_ALL_ACCESS);
  187. if (! service) return;
  188. return;
  189. SERVICE_FAILURE_ACTIONS_FLAG flag;
  190. ZeroMemory(&flag, sizeof(flag));
  191. flag.fFailureActionsOnNonCrashFailures = true;
  192. /* This functionality was added in Vista so the call may fail */
  193. ChangeServiceConfig2(service, SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, &flag);
  194. }
  195. int monitor_service() {
  196. /* Set service status to started */
  197. int ret = start_service();
  198. if (ret) {
  199. char code[16];
  200. _snprintf(code, sizeof(code), "%d", ret);
  201. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_START_SERVICE_FAILED, exe, service_name, ret, 0);
  202. return ret;
  203. }
  204. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_STARTED_SERVICE, exe, flags, service_name, dir, 0);
  205. /* Monitor service service */
  206. if (! RegisterWaitForSingleObject(&wait_handle, process_handle, end_service, (void *) pid, INFINITE, WT_EXECUTEONLYONCE | WT_EXECUTELONGFUNCTION)) {
  207. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_REGISTERWAITFORSINGLEOBJECT_FAILED, service_name, exe, error_string(GetLastError()), 0);
  208. }
  209. return 0;
  210. }
  211. /* Service control handler */
  212. unsigned long WINAPI service_control_handler(unsigned long control, unsigned long event, void *data, void *context) {
  213. switch (control) {
  214. case SERVICE_CONTROL_SHUTDOWN:
  215. case SERVICE_CONTROL_STOP:
  216. stop_service(0, true, true);
  217. return NO_ERROR;
  218. case SERVICE_CONTROL_CONTINUE:
  219. throttle = 0;
  220. ZeroMemory(&throttle_duetime, sizeof(throttle_duetime));
  221. SetWaitableTimer(throttle_timer, &throttle_duetime, 0, 0, 0, 0);
  222. service_status.dwCurrentState = SERVICE_CONTINUE_PENDING;
  223. service_status.dwWaitHint = throttle_milliseconds() + NSSM_WAITHINT_MARGIN;
  224. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_RESET_THROTTLE, service_name, 0);
  225. SetServiceStatus(service_handle, &service_status);
  226. return NO_ERROR;
  227. case SERVICE_CONTROL_PAUSE:
  228. /*
  229. We don't accept pause messages but it isn't possible to register
  230. only for continue messages so we have to handle this case.
  231. */
  232. return ERROR_CALL_NOT_IMPLEMENTED;
  233. }
  234. /* Unknown control */
  235. return ERROR_CALL_NOT_IMPLEMENTED;
  236. }
  237. /* Start the service */
  238. int start_service() {
  239. stopping = false;
  240. if (process_handle) return 0;
  241. /* Allocate a STARTUPINFO structure for a new process */
  242. STARTUPINFO si;
  243. ZeroMemory(&si, sizeof(si));
  244. si.cb = sizeof(si);
  245. /* Allocate a PROCESSINFO structure for the process */
  246. PROCESS_INFORMATION pi;
  247. ZeroMemory(&pi, sizeof(pi));
  248. /* Get startup parameters */
  249. int ret = get_parameters(service_name, exe, sizeof(exe), flags, sizeof(flags), dir, sizeof(dir), &throttle_delay);
  250. if (ret) {
  251. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GET_PARAMETERS_FAILED, service_name, 0);
  252. return stop_service(2, true, true);
  253. }
  254. /* Launch executable with arguments */
  255. char cmd[CMD_LENGTH];
  256. if (_snprintf(cmd, sizeof(cmd), "%s %s", exe, flags) < 0) {
  257. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, "command line", "start_service", 0);
  258. return stop_service(2, true, true);
  259. }
  260. throttle_restart();
  261. if (! CreateProcess(0, cmd, 0, 0, false, 0, 0, dir, &si, &pi)) {
  262. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEPROCESS_FAILED, service_name, exe, error_string(GetLastError()), 0);
  263. return stop_service(3, true, true);
  264. }
  265. process_handle = pi.hProcess;
  266. pid = pi.dwProcessId;
  267. /* Signal successful start */
  268. service_status.dwCurrentState = SERVICE_RUNNING;
  269. SetServiceStatus(service_handle, &service_status);
  270. /* Wait for a clean startup. */
  271. if (WaitForSingleObject(process_handle, throttle_delay) == WAIT_TIMEOUT) throttle = 0;
  272. return 0;
  273. }
  274. /* Stop the service */
  275. int stop_service(unsigned long exitcode, bool graceful, bool default_action) {
  276. if (default_action && ! exitcode && ! graceful) {
  277. 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);
  278. graceful = true;
  279. }
  280. /* Signal we are stopping */
  281. if (graceful) {
  282. service_status.dwCurrentState = SERVICE_STOP_PENDING;
  283. service_status.dwWaitHint = NSSM_KILL_WINDOW_GRACE_PERIOD + NSSM_KILL_THREADS_GRACE_PERIOD + NSSM_WAITHINT_MARGIN;
  284. SetServiceStatus(service_handle, &service_status);
  285. }
  286. /* Nothing to do if server isn't running */
  287. if (pid) {
  288. /* Shut down server */
  289. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_TERMINATEPROCESS, service_name, exe, 0);
  290. kill_process(service_name, process_handle, pid, 0);
  291. process_handle = 0;
  292. }
  293. else log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_PROCESS_ALREADY_STOPPED, service_name, exe, 0);
  294. end_service((void *) pid, true);
  295. /* Signal we stopped */
  296. if (graceful) {
  297. service_status.dwCurrentState = SERVICE_STOPPED;
  298. if (exitcode) {
  299. service_status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
  300. service_status.dwServiceSpecificExitCode = exitcode;
  301. }
  302. else {
  303. service_status.dwWin32ExitCode = NO_ERROR;
  304. service_status.dwServiceSpecificExitCode = 0;
  305. }
  306. SetServiceStatus(service_handle, &service_status);
  307. }
  308. return exitcode;
  309. }
  310. /* Callback function triggered when the server exits */
  311. void CALLBACK end_service(void *arg, unsigned char why) {
  312. if (stopping) return;
  313. stopping = true;
  314. pid = (unsigned long) arg;
  315. /* Check exit code */
  316. unsigned long exitcode = 0;
  317. GetExitCodeProcess(process_handle, &exitcode);
  318. /* Clean up. */
  319. kill_process_tree(service_name, pid, exitcode, pid);
  320. /*
  321. The why argument is true if our wait timed out or false otherwise.
  322. Our wait is infinite so why will never be true when called by the system.
  323. If it is indeed true, assume we were called from stop_service() because
  324. this is a controlled shutdown, and don't take any restart action.
  325. */
  326. if (why) return;
  327. char code[16];
  328. _snprintf(code, sizeof(code), "%d", exitcode);
  329. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_ENDED_SERVICE, exe, service_name, code, 0);
  330. /* What action should we take? */
  331. int action = NSSM_EXIT_RESTART;
  332. unsigned char action_string[ACTION_LEN];
  333. bool default_action;
  334. if (! get_exit_action(service_name, &exitcode, action_string, &default_action)) {
  335. for (int i = 0; exit_action_strings[i]; i++) {
  336. if (! _strnicmp((const char *) action_string, exit_action_strings[i], ACTION_LEN)) {
  337. action = i;
  338. break;
  339. }
  340. }
  341. }
  342. process_handle = 0;
  343. pid = 0;
  344. switch (action) {
  345. /* Try to restart the service or return failure code to service manager */
  346. case NSSM_EXIT_RESTART:
  347. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_RESTART, service_name, code, exit_action_strings[action], exe, 0);
  348. while (monitor_service()) {
  349. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_RESTART_SERVICE_FAILED, exe, service_name, 0);
  350. Sleep(30000);
  351. }
  352. break;
  353. /* Do nothing, just like srvany would */
  354. case NSSM_EXIT_IGNORE:
  355. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_IGNORE, service_name, code, exit_action_strings[action], exe, 0);
  356. Sleep(INFINITE);
  357. break;
  358. /* Tell the service manager we are finished */
  359. case NSSM_EXIT_REALLY:
  360. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_REALLY, service_name, code, exit_action_strings[action], 0);
  361. stop_service(exitcode, true, default_action);
  362. break;
  363. /* Fake a crash so pre-Vista service managers will run recovery actions. */
  364. case NSSM_EXIT_UNCLEAN:
  365. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_UNCLEAN, service_name, code, exit_action_strings[action], 0);
  366. exit(stop_service(exitcode, false, default_action));
  367. break;
  368. }
  369. }
  370. void throttle_restart() {
  371. /* This can't be a restart if the service is already running. */
  372. if (! throttle++) return;
  373. int ms = throttle_milliseconds();
  374. if (throttle > 7) throttle = 8;
  375. char threshold[8], milliseconds[8];
  376. _snprintf(threshold, sizeof(threshold), "%d", throttle_delay);
  377. _snprintf(milliseconds, sizeof(milliseconds), "%d", ms);
  378. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_THROTTLED, service_name, threshold, milliseconds, 0);
  379. ZeroMemory(&throttle_duetime, sizeof(throttle_duetime));
  380. throttle_duetime.QuadPart = 0 - (ms * 10000);
  381. SetWaitableTimer(throttle_timer, &throttle_duetime, 0, 0, 0, 0);
  382. service_status.dwCurrentState = SERVICE_PAUSED;
  383. SetServiceStatus(service_handle, &service_status);
  384. WaitForSingleObject(throttle_timer, INFINITE);
  385. }