service.cpp 15 KB

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