Added await_shutdown() function.
[nssm.git] / service.cpp
index 873b8a8..028b035 100644 (file)
@@ -11,12 +11,21 @@ char exe[EXE_LENGTH];
 char flags[CMD_LENGTH];\r
 char dir[MAX_PATH];\r
 bool stopping;\r
+bool allow_restart;\r
 unsigned long throttle_delay;\r
 unsigned long stop_method;\r
+unsigned long kill_console_delay;\r
+unsigned long kill_window_delay;\r
+unsigned long kill_threads_delay;\r
+CRITICAL_SECTION throttle_section;\r
+CONDITION_VARIABLE throttle_condition;\r
 HANDLE throttle_timer;\r
 LARGE_INTEGER throttle_duetime;\r
+bool use_critical_section;\r
 FILETIME creation_time;\r
 \r
+extern imports_t imports;\r
+\r
 static enum { NSSM_EXIT_RESTART, NSSM_EXIT_IGNORE, NSSM_EXIT_REALLY, NSSM_EXIT_UNCLEAN } exit_actions;\r
 static const char *exit_action_strings[] = { "Restart", "Ignore", "Exit", "Suicide", 0 };\r
 \r
@@ -104,7 +113,7 @@ int install_service(char *name, char *exe, char *flags) {
     print_message(stderr, NSSM_MESSAGE_PATH_TOO_LONG, NSSM);\r
     return 3;\r
   }\r
-  if (_snprintf(command, sizeof(command), "\"%s\"", path) < 0) {\r
+  if (_snprintf_s(command, sizeof(command), _TRUNCATE, "\"%s\"", path) < 0) {\r
     print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY_FOR_IMAGEPATH);\r
     return 4;\r
   }\r
@@ -178,11 +187,15 @@ int remove_service(char *name) {
 \r
 /* Service initialisation */\r
 void WINAPI service_main(unsigned long argc, char **argv) {\r
-  if (_snprintf(service_name, sizeof(service_name), "%s", argv[0]) < 0) {\r
+  if (_snprintf_s(service_name, sizeof(service_name), _TRUNCATE, "%s", argv[0]) < 0) {\r
     log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, "service_name", "service_main()", 0);\r
     return;\r
   }\r
 \r
+  /* We can use a condition variable in a critical section on Vista or later. */\r
+  if (imports.SleepConditionVariableCS && imports.WakeConditionVariable) use_critical_section = true;\r
+  else use_critical_section = false;\r
+\r
   /* Initialise status */\r
   ZeroMemory(&service_status, sizeof(service_status));\r
   service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS;\r
@@ -217,9 +230,12 @@ void WINAPI service_main(unsigned long argc, char **argv) {
   }\r
 \r
   /* Used for signalling a resume if the service pauses when throttled. */\r
-  throttle_timer = CreateWaitableTimer(0, 1, 0);\r
-  if (! throttle_timer) {\r
-    log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_CREATEWAITABLETIMER_FAILED, service_name, error_string(GetLastError()), 0);\r
+  if (use_critical_section) InitializeCriticalSection(&throttle_section);\r
+  else {\r
+    throttle_timer = CreateWaitableTimer(0, 1, 0);\r
+    if (! throttle_timer) {\r
+      log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_CREATEWAITABLETIMER_FAILED, service_name, error_string(GetLastError()), 0);\r
+    }\r
   }\r
 \r
   monitor_service();\r
@@ -261,13 +277,13 @@ int monitor_service() {
   int ret = start_service();\r
   if (ret) {\r
     char code[16];\r
-    _snprintf(code, sizeof(code), "%d", ret);\r
+    _snprintf_s(code, sizeof(code), _TRUNCATE, "%d", ret);\r
     log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_START_SERVICE_FAILED, exe, service_name, ret, 0);\r
     return ret;\r
   }\r
   log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_STARTED_SERVICE, exe, flags, service_name, dir, 0);\r
 \r
-  /* Monitor service service */\r
+  /* Monitor service */\r
   if (! RegisterWaitForSingleObject(&wait_handle, process_handle, end_service, (void *) pid, INFINITE, WT_EXECUTEONLYONCE | WT_EXECUTELONGFUNCTION)) {\r
     log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_REGISTERWAITFORSINGLEOBJECT_FAILED, service_name, exe, error_string(GetLastError()), 0);\r
   }\r
@@ -296,11 +312,11 @@ void log_service_control(char *service_name, unsigned long control, bool handled
     /* "0x" + 8 x hex + NULL */\r
     text = (char *) HeapAlloc(GetProcessHeap(), 0, 11);\r
     if (! text) {\r
-      log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, "control code", "log_service_control", 0);\r
+      log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, "control code", "log_service_control()", 0);\r
       return;\r
     }\r
-    if (_snprintf(text, 11, "0x%08x", control) < 0) {\r
-      log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, "control code", "log_service_control", 0);\r
+    if (_snprintf_s(text, 11, _TRUNCATE, "0x%08x", control) < 0) {\r
+      log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, "control code", "log_service_control()", 0);\r
       HeapFree(GetProcessHeap(), 0, text);\r
       return;\r
     }\r
@@ -332,10 +348,13 @@ unsigned long WINAPI service_control_handler(unsigned long control, unsigned lon
 \r
     case SERVICE_CONTROL_CONTINUE:\r
       log_service_control(service_name, control, true);\r
-      if (! throttle_timer) return ERROR_CALL_NOT_IMPLEMENTED;\r
       throttle = 0;\r
-      ZeroMemory(&throttle_duetime, sizeof(throttle_duetime));\r
-      SetWaitableTimer(throttle_timer, &throttle_duetime, 0, 0, 0, 0);\r
+      if (use_critical_section) imports.WakeConditionVariable(&throttle_condition);\r
+      else {\r
+        if (! throttle_timer) return ERROR_CALL_NOT_IMPLEMENTED;\r
+        ZeroMemory(&throttle_duetime, sizeof(throttle_duetime));\r
+        SetWaitableTimer(throttle_timer, &throttle_duetime, 0, 0, 0, 0);\r
+      }\r
       service_status.dwCurrentState = SERVICE_CONTINUE_PENDING;\r
       service_status.dwWaitHint = throttle_milliseconds() + NSSM_WAITHINT_MARGIN;\r
       log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_RESET_THROTTLE, service_name, 0);\r
@@ -359,6 +378,7 @@ unsigned long WINAPI service_control_handler(unsigned long control, unsigned lon
 /* Start the service */\r
 int start_service() {\r
   stopping = false;\r
+  allow_restart = true;\r
 \r
   if (process_handle) return 0;\r
 \r
@@ -373,7 +393,7 @@ int start_service() {
 \r
   /* Get startup parameters */\r
   char *env = 0;\r
-  int ret = get_parameters(service_name, exe, sizeof(exe), flags, sizeof(flags), dir, sizeof(dir), &env, &throttle_delay, &stop_method, &si);\r
+  int ret = get_parameters(service_name, exe, sizeof(exe), flags, sizeof(flags), dir, sizeof(dir), &env, &throttle_delay, &stop_method, &kill_console_delay, &kill_window_delay, &kill_threads_delay, &si);\r
   if (ret) {\r
     log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GET_PARAMETERS_FAILED, service_name, 0);\r
     return stop_service(2, true, true);\r
@@ -381,7 +401,7 @@ int start_service() {
 \r
   /* Launch executable with arguments */\r
   char cmd[CMD_LENGTH];\r
-  if (_snprintf(cmd, sizeof(cmd), "\"%s\" %s", exe, flags) < 0) {\r
+  if (_snprintf_s(cmd, sizeof(cmd), _TRUNCATE, "\"%s\" %s", exe, flags) < 0) {\r
     log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, "command line", "start_service", 0);\r
     close_output_handles(&si);\r
     return stop_service(2, true, true);\r
@@ -389,7 +409,8 @@ int start_service() {
 \r
   throttle_restart();\r
 \r
-  bool inherit_handles = (si.dwFlags & STARTF_USESTDHANDLES);\r
+  bool inherit_handles = false;\r
+  if (si.dwFlags & STARTF_USESTDHANDLES) inherit_handles = true;\r
   if (! CreateProcess(0, cmd, 0, 0, inherit_handles, 0, env, dir, &si, &pi)) {\r
     unsigned long error = GetLastError();\r
     if (error == ERROR_INVALID_PARAMETER && env) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEPROCESS_FAILED_INVALID_ENVIRONMENT, service_name, exe, NSSM_REG_ENV, 0);\r
@@ -404,18 +425,21 @@ int start_service() {
 \r
   close_output_handles(&si);\r
 \r
+  /* Wait for a clean startup. */\r
+  if (WaitForSingleObject(process_handle, throttle_delay) == WAIT_TIMEOUT) throttle = 0;\r
+\r
   /* Signal successful start */\r
   service_status.dwCurrentState = SERVICE_RUNNING;\r
   SetServiceStatus(service_handle, &service_status);\r
 \r
-  /* Wait for a clean startup. */\r
-  if (WaitForSingleObject(process_handle, throttle_delay) == WAIT_TIMEOUT) throttle = 0;\r
-\r
   return 0;\r
 }\r
 \r
 /* Stop the service */\r
 int stop_service(unsigned long exitcode, bool graceful, bool default_action) {\r
+  allow_restart = false;\r
+  if (wait_handle) UnregisterWait(wait_handle);\r
+\r
   if (default_action && ! exitcode && ! graceful) {\r
     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);\r
     graceful = true;\r
@@ -424,7 +448,10 @@ int stop_service(unsigned long exitcode, bool graceful, bool default_action) {
   /* Signal we are stopping */\r
   if (graceful) {\r
     service_status.dwCurrentState = SERVICE_STOP_PENDING;\r
-    service_status.dwWaitHint = NSSM_KILL_WINDOW_GRACE_PERIOD + NSSM_KILL_THREADS_GRACE_PERIOD + NSSM_WAITHINT_MARGIN;\r
+    service_status.dwWaitHint = NSSM_WAITHINT_MARGIN;\r
+    if (stop_method & NSSM_STOP_METHOD_CONSOLE && imports.AttachConsole) service_status.dwWaitHint += kill_console_delay;\r
+    if (stop_method & NSSM_STOP_METHOD_WINDOW) service_status.dwWaitHint += kill_window_delay;\r
+    if (stop_method & NSSM_STOP_METHOD_THREADS) service_status.dwWaitHint += kill_threads_delay;\r
     SetServiceStatus(service_handle, &service_status);\r
   }\r
 \r
@@ -476,11 +503,12 @@ void CALLBACK end_service(void *arg, unsigned char why) {
     tree.  See below for the possible values of the why argument.\r
   */\r
   if (! why) {\r
-    _snprintf(code, sizeof(code), "%d", exitcode);\r
+    _snprintf_s(code, sizeof(code), _TRUNCATE, "%lu", exitcode);\r
     log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_ENDED_SERVICE, exe, service_name, code, 0);\r
   }\r
 \r
   /* Clean up. */\r
+  if (exitcode == STILL_ACTIVE) exitcode = 0;\r
   kill_process_tree(service_name, stop_method, pid, exitcode, pid, &creation_time, &exit_time);\r
 \r
   /*\r
@@ -490,6 +518,7 @@ void CALLBACK end_service(void *arg, unsigned char why) {
     this is a controlled shutdown, and don't take any restart action.\r
   */\r
   if (why) return;\r
+  if (! allow_restart) return;\r
 \r
   /* What action should we take? */\r
   int action = NSSM_EXIT_RESTART;\r
@@ -531,7 +560,9 @@ void CALLBACK end_service(void *arg, unsigned char why) {
     /* Fake a crash so pre-Vista service managers will run recovery actions. */\r
     case NSSM_EXIT_UNCLEAN:\r
       log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_UNCLEAN, service_name, code, exit_action_strings[action], 0);\r
-      exit(stop_service(exitcode, false, default_action));\r
+      stop_service(exitcode, false, default_action);\r
+      free_imports();\r
+      exit(exitcode);\r
     break;\r
   }\r
 }\r
@@ -545,11 +576,12 @@ void throttle_restart() {
   if (throttle > 7) throttle = 8;\r
 \r
   char threshold[8], milliseconds[8];\r
-  _snprintf(threshold, sizeof(threshold), "%d", throttle_delay);\r
-  _snprintf(milliseconds, sizeof(milliseconds), "%d", ms);\r
+  _snprintf_s(threshold, sizeof(threshold), _TRUNCATE, "%lu", throttle_delay);\r
+  _snprintf_s(milliseconds, sizeof(milliseconds), _TRUNCATE, "%lu", ms);\r
   log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_THROTTLED, service_name, threshold, milliseconds, 0);\r
 \r
-  if (throttle_timer) {\r
+  if (use_critical_section) EnterCriticalSection(&throttle_section);\r
+  else if (throttle_timer) {\r
     ZeroMemory(&throttle_duetime, sizeof(throttle_duetime));\r
     throttle_duetime.QuadPart = 0 - (ms * 10000LL);\r
     SetWaitableTimer(throttle_timer, &throttle_duetime, 0, 0, 0, 0);\r
@@ -558,6 +590,98 @@ void throttle_restart() {
   service_status.dwCurrentState = SERVICE_PAUSED;\r
   SetServiceStatus(service_handle, &service_status);\r
 \r
-  if (throttle_timer) WaitForSingleObject(throttle_timer, INFINITE);\r
-  else Sleep(ms);\r
+  if (use_critical_section) {\r
+    imports.SleepConditionVariableCS(&throttle_condition, &throttle_section, ms);\r
+    LeaveCriticalSection(&throttle_section);\r
+  }\r
+  else {\r
+    if (throttle_timer) WaitForSingleObject(throttle_timer, INFINITE);\r
+    else Sleep(ms);\r
+  }\r
+}\r
+\r
+/*\r
+  When responding to a stop (or any other) request we need to set dwWaitHint to\r
+  the number of milliseconds we expect the operation to take, and optionally\r
+  increase dwCheckPoint.  If dwWaitHint milliseconds elapses without the\r
+  operation completing or dwCheckPoint increasing, the system will consider the\r
+  service to be hung.\r
+\r
+  However the system will consider the service to be hung after 30000\r
+  milliseconds regardless of the value of dwWaitHint if dwCheckPoint has not\r
+  changed.  Therefore if we want to wait longer than that we must periodically\r
+  increase dwCheckPoint.\r
+\r
+  Furthermore, it will consider the service to be hung after 60000 milliseconds\r
+  regardless of the value of dwCheckPoint unless dwWaitHint is increased every\r
+  time dwCheckPoint is also increased.\r
+\r
+  Our strategy then is to retrieve the initial dwWaitHint and wait for\r
+  NSSM_SHUTDOWN_CHECKPOINT milliseconds.  If the process is still running and\r
+  we haven't finished waiting we increment dwCheckPoint and add whichever is\r
+  smaller of NSSM_SHUTDOWN_CHECKPOINT or the remaining timeout to dwWaitHint.\r
+\r
+  Only doing both these things will prevent the system from killing the service.\r
+\r
+  Returns: 1 if the wait timed out.\r
+           0 if the wait completed.\r
+          -1 on error.\r
+*/\r
+int await_shutdown(char *function_name, char *service_name, SERVICE_STATUS_HANDLE service_handle, SERVICE_STATUS *service_status, HANDLE process_handle, unsigned long timeout) {\r
+  unsigned long interval;\r
+  unsigned long waithint;\r
+  unsigned long ret;\r
+  unsigned long waited;\r
+  char interval_milliseconds[16];\r
+  char timeout_milliseconds[16];\r
+  char waited_milliseconds[16];\r
+  char *function = function_name;\r
+\r
+  /* Add brackets to function name. */\r
+  size_t funclen = strlen(function_name) + 3;\r
+  char *func = (char *) HeapAlloc(GetProcessHeap(), 0, funclen);\r
+  if (func) {\r
+    if (_snprintf_s(func, funclen, _TRUNCATE, "%s()", function_name) > -1) function = func;\r
+  }\r
+\r
+  _snprintf_s(timeout_milliseconds, sizeof(timeout_milliseconds), _TRUNCATE, "%lu", timeout);\r
+\r
+  waithint = service_status->dwWaitHint;\r
+  waited = 0;\r
+  while (waited < timeout) {\r
+    interval = timeout - waited;\r
+    if (interval > NSSM_SHUTDOWN_CHECKPOINT) interval = NSSM_SHUTDOWN_CHECKPOINT;\r
+\r
+    service_status->dwCurrentState = SERVICE_STOP_PENDING;\r
+    service_status->dwWaitHint += interval;\r
+    service_status->dwCheckPoint++;\r
+    SetServiceStatus(service_handle, service_status);\r
+\r
+    if (waited) {\r
+      _snprintf_s(waited_milliseconds, sizeof(waited_milliseconds), _TRUNCATE, "%lu", waited);\r
+      _snprintf_s(interval_milliseconds, sizeof(interval_milliseconds), _TRUNCATE, "%lu", interval);\r
+      log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_AWAITING_SHUTDOWN, function, service_name, waited_milliseconds, interval_milliseconds, timeout_milliseconds, 0);\r
+    }\r
+\r
+    switch (WaitForSingleObject(process_handle, interval)) {\r
+      case WAIT_OBJECT_0:\r
+        ret = 0;\r
+        goto awaited;\r
+\r
+      case WAIT_TIMEOUT:\r
+        ret = 1;\r
+      break;\r
+\r
+      default:\r
+        ret = -1;\r
+        goto awaited;\r
+    }\r
+\r
+    waited += interval;\r
+  }\r
+\r
+awaited:\r
+  if (func) HeapFree(GetProcessHeap(), 0, func);\r
+\r
+  return ret;\r
 }\r