X-Git-Url: http://git.iain.cx/?a=blobdiff_plain;f=service.cpp;h=d0141a1125eab68a3f57b97fd02a17877c481c84;hb=143238dfe314c16bc90a6807ab0f00220efd34a2;hp=8440038c148a57a4eca25c1891a7feecf4cd3616;hpb=9cf66b86846f97f0bd2efdfe2b8bd36ea0b00499;p=nssm.git diff --git a/service.cpp b/service.cpp index 8440038..d0141a1 100644 --- a/service.cpp +++ b/service.cpp @@ -11,10 +11,160 @@ extern settings_t settings[]; const TCHAR *exit_action_strings[] = { _T("Restart"), _T("Ignore"), _T("Exit"), _T("Suicide"), 0 }; const TCHAR *startup_strings[] = { _T("SERVICE_AUTO_START"), _T("SERVICE_DELAYED_AUTO_START"), _T("SERVICE_DEMAND_START"), _T("SERVICE_DISABLED"), 0 }; +const TCHAR *priority_strings[] = { _T("REALTIME_PRIORITY_CLASS"), _T("HIGH_PRIORITY_CLASS"), _T("ABOVE_NORMAL_PRIORITY_CLASS"), _T("NORMAL_PRIORITY_CLASS"), _T("BELOW_NORMAL_PRIORITY_CLASS"), _T("IDLE_PRIORITY_CLASS"), 0 }; -static inline int throttle_milliseconds(unsigned long throttle) { +typedef struct { + int first; + int last; +} list_t; + +int affinity_mask_to_string(__int64 mask, TCHAR **string) { + if (! string) return 1; + if (! mask) { + *string = 0; + return 0; + } + + __int64 i, n; + + /* SetProcessAffinityMask() accepts a mask of up to 64 processors. */ + list_t set[64]; + for (n = 0; n < _countof(set); n++) set[n].first = set[n].last = -1; + + for (i = 0, n = 0; i < _countof(set); i++) { + if (mask & (1LL << i)) { + if (set[n].first == -1) set[n].first = set[n].last = (int) i; + else if (set[n].last == (int) i - 1) set[n].last = (int) i; + else { + n++; + set[n].first = set[n].last = (int) i; + } + } + } + + /* Worst case is 2x2 characters for first and last CPU plus - and/or , */ + size_t len = (size_t) (n + 1) * 6; + *string = (TCHAR *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len * sizeof(TCHAR)); + if (! string) return 2; + + size_t s = 0; + int ret; + for (i = 0; i <= n; i++) { + if (i) (*string)[s++] = _T(','); + ret = _sntprintf_s(*string + s, 3, _TRUNCATE, _T("%u"), set[i].first); + if (ret < 0) { + HeapFree(GetProcessHeap(), 0, *string); + *string = 0; + return 3; + } + else s += ret; + if (set[i].last != set[i].first) { + ret =_sntprintf_s(*string + s, 4, _TRUNCATE, _T("%c%u"), (set[i].last == set[i].first + 1) ? _T(',') : _T('-'), set[i].last); + if (ret < 0) { + HeapFree(GetProcessHeap(), 0, *string); + *string = 0; + return 4; + } + else s += ret; + } + } + + return 0; +} + +int affinity_string_to_mask(TCHAR *string, __int64 *mask) { + if (! mask) return 1; + + *mask = 0LL; + if (! string) return 0; + + list_t set[64]; + + TCHAR *s = string; + TCHAR *end; + int ret; + int i; + int n = 0; + unsigned long number; + + for (n = 0; n < _countof(set); n++) set[n].first = set[n].last = -1; + n = 0; + + while (*s) { + ret = str_number(s, &number, &end); + s = end; + if (ret == 0 || ret == 2) { + if (number >= _countof(set)) return 2; + set[n].first = set[n].last = (int) number; + + switch (*s) { + case 0: + break; + + case _T(','): + n++; + s++; + break; + + case _T('-'): + if (! *(++s)) return 3; + ret = str_number(s, &number, &end); + if (ret == 0 || ret == 2) { + s = end; + if (! *s || *s == _T(',')) { + set[n].last = (int) number; + if (! *s) break; + n++; + s++; + } + else return 3; + } + else return 3; + break; + + default: + return 3; + } + } + else return 4; + } + + for (i = 0; i <= n; i++) { + for (int j = set[i].first; j <= set[i].last; j++) (__int64) *mask |= (1LL << (__int64) j); + } + + return 0; +} + +inline unsigned long priority_mask() { + return REALTIME_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | ABOVE_NORMAL_PRIORITY_CLASS | NORMAL_PRIORITY_CLASS | BELOW_NORMAL_PRIORITY_CLASS | IDLE_PRIORITY_CLASS; +} + +int priority_constant_to_index(unsigned long constant) { + switch (constant & priority_mask()) { + case REALTIME_PRIORITY_CLASS: return NSSM_REALTIME_PRIORITY; + case HIGH_PRIORITY_CLASS: return NSSM_HIGH_PRIORITY; + case ABOVE_NORMAL_PRIORITY_CLASS: return NSSM_ABOVE_NORMAL_PRIORITY; + case BELOW_NORMAL_PRIORITY_CLASS: return NSSM_BELOW_NORMAL_PRIORITY; + case IDLE_PRIORITY_CLASS: return NSSM_IDLE_PRIORITY; + } + return NSSM_NORMAL_PRIORITY; +} + +unsigned long priority_index_to_constant(int index) { + switch (index) { + case NSSM_REALTIME_PRIORITY: return REALTIME_PRIORITY_CLASS; + case NSSM_HIGH_PRIORITY: return HIGH_PRIORITY_CLASS; + case NSSM_ABOVE_NORMAL_PRIORITY: return ABOVE_NORMAL_PRIORITY_CLASS; + case NSSM_BELOW_NORMAL_PRIORITY: return BELOW_NORMAL_PRIORITY_CLASS; + case NSSM_IDLE_PRIORITY: return IDLE_PRIORITY_CLASS; + } + return NORMAL_PRIORITY_CLASS; +} + +static inline unsigned long throttle_milliseconds(unsigned long throttle) { /* pow() operates on doubles. */ - int ret = 1; for (unsigned long i = 1; i < throttle; i++) ret *= 2; + unsigned long ret = 1; for (unsigned long i = 1; i < throttle; i++) ret *= 2; return ret * 1000; } @@ -37,6 +187,85 @@ SC_HANDLE open_service_manager() { return ret; } +/* Open a service by name or display name. */ +SC_HANDLE open_service(SC_HANDLE services, TCHAR *service_name, TCHAR *canonical_name, unsigned long canonical_namelen) { + SC_HANDLE service_handle = OpenService(services, service_name, SERVICE_ALL_ACCESS); + if (service_handle) { + if (canonical_name && canonical_name != service_name) { + if (_sntprintf_s(canonical_name, canonical_namelen, _TRUNCATE, _T("%s"), service_name) < 0) { + print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("canonical_name"), _T("open_service()")); + return 0; + } + } + return service_handle; + } + + unsigned long error = GetLastError(); + if (error != ERROR_SERVICE_DOES_NOT_EXIST) { + print_message(stderr, NSSM_MESSAGE_OPENSERVICE_FAILED, error_string(GetLastError())); + return 0; + } + + /* We can't look for a display name because there's no buffer to store it. */ + if (! canonical_name) { + print_message(stderr, NSSM_MESSAGE_OPENSERVICE_FAILED, error_string(GetLastError())); + return 0; + } + + unsigned long bufsize, required, count, i; + unsigned long resume = 0; + EnumServicesStatus(services, SERVICE_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_KERNEL_DRIVER | SERVICE_WIN32, SERVICE_STATE_ALL, 0, 0, &required, &count, &resume); + error = GetLastError(); + if (error != ERROR_MORE_DATA) { + print_message(stderr, NSSM_MESSAGE_ENUMSERVICESSTATUS_FAILED, error_string(GetLastError())); + return 0; + } + + ENUM_SERVICE_STATUS *status = (ENUM_SERVICE_STATUS *) HeapAlloc(GetProcessHeap(), 0, required); + if (! status) { + print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("ENUM_SERVICE_STATUS"), _T("open_service()")); + return 0; + } + + bufsize = required; + while (true) { + /* + EnumServicesStatus() returns: + 1 when it retrieved data and there's no more data to come. + 0 and sets last error to ERROR_MORE_DATA when it retrieved data and + there's more data to come. + 0 and sets last error to something else on error. + */ + int ret = EnumServicesStatus(services, SERVICE_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_KERNEL_DRIVER | SERVICE_WIN32, SERVICE_STATE_ALL, status, bufsize, &required, &count, &resume); + if (! ret) { + error = GetLastError(); + if (error != ERROR_MORE_DATA) { + HeapFree(GetProcessHeap(), 0, status); + print_message(stderr, NSSM_MESSAGE_ENUMSERVICESSTATUS_FAILED, error_string(GetLastError())); + return 0; + } + } + + for (i = 0; i < count; i++) { + if (str_equiv(status[i].lpDisplayName, service_name)) { + if (_sntprintf_s(canonical_name, canonical_namelen, _TRUNCATE, _T("%s"), status[i].lpServiceName) < 0) { + HeapFree(GetProcessHeap(), 0, status); + print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("canonical_name"), _T("open_service()")); + return 0; + } + + HeapFree(GetProcessHeap(), 0, status); + return open_service(services, canonical_name, 0, 0); + } + } + + if (ret) break; + } + + /* Recurse so we can get an error message. */ + return open_service(services, service_name, 0, 0); +} + QUERY_SERVICE_CONFIG *query_service_config(const TCHAR *service_name, SC_HANDLE service_handle) { QUERY_SERVICE_CONFIG *qsc; unsigned long bufsize; @@ -183,6 +412,7 @@ int get_service_username(const TCHAR *service_name, const QUERY_SERVICE_CONFIG * } int grant_logon_as_service(const TCHAR *username) { + if (! username) return 0; if (str_equiv(username, NSSM_LOCALSYSTEM_ACCOUNT)) return 0; /* Open Policy object. */ @@ -206,7 +436,7 @@ int grant_logon_as_service(const TCHAR *username) { #else size_t buflen; mbstowcs_s(&buflen, NULL, 0, username, _TRUNCATE); - lsa_username.MaximumLength = buflen * sizeof(wchar_t); + lsa_username.MaximumLength = (unsigned short) buflen * sizeof(wchar_t); lsa_username.Length = lsa_username.MaximumLength - sizeof(wchar_t); lsa_username.Buffer = (wchar_t *) HeapAlloc(GetProcessHeap(), 0, lsa_username.MaximumLength); if (lsa_username.Buffer) mbstowcs_s(&buflen, lsa_username.Buffer, lsa_username.MaximumLength, username, _TRUNCATE); @@ -333,6 +563,7 @@ void set_nssm_service_defaults(nssm_service_t *service) { if (! service) return; service->type = SERVICE_WIN32_OWN_PROCESS; + service->priority = NORMAL_PRIORITY_CLASS; service->stdin_sharing = NSSM_STDIN_SHARING; service->stdin_disposition = NSSM_STDIN_DISPOSITION; service->stdin_flags = NSSM_STDIN_FLAGS; @@ -491,10 +722,9 @@ int pre_edit_service(int argc, TCHAR **argv) { } /* Try to open the service */ - service->handle = OpenService(services, service->name, SC_MANAGER_ALL_ACCESS); + service->handle = open_service(services, service->name, service->name, _countof(service->name)); if (! service->handle) { CloseServiceHandle(services); - print_message(stderr, NSSM_MESSAGE_OPENSERVICE_FAILED); return 3; } @@ -703,9 +933,9 @@ int install_service(nssm_service_t *service) { GetModuleFileName(0, service->image, _countof(service->image)); /* Create the service - settings will be changed in edit_service() */ - service->handle = CreateService(services, service->name, service->name, SC_MANAGER_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, service->image, 0, 0, 0, 0, 0); + service->handle = CreateService(services, service->name, service->name, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, service->image, 0, 0, 0, 0, 0); if (! service->handle) { - print_message(stderr, NSSM_MESSAGE_CREATESERVICE_FAILED); + print_message(stderr, NSSM_MESSAGE_CREATESERVICE_FAILED, error_string(GetLastError())); CloseServiceHandle(services); return 5; } @@ -806,6 +1036,7 @@ int edit_service(nssm_service_t *service, bool editing) { int control_service(unsigned long control, int argc, TCHAR **argv) { if (argc < 1) return usage(1); TCHAR *service_name = argv[0]; + TCHAR canonical_name[SERVICE_NAME_LENGTH]; SC_HANDLE services = open_service_manager(); if (! services) { @@ -813,9 +1044,8 @@ int control_service(unsigned long control, int argc, TCHAR **argv) { return 2; } - SC_HANDLE service_handle = OpenService(services, service_name, SC_MANAGER_ALL_ACCESS); + SC_HANDLE service_handle = open_service(services, service_name, canonical_name, _countof(canonical_name)); if (! service_handle) { - print_message(stderr, NSSM_MESSAGE_OPENSERVICE_FAILED); CloseServiceHandle(services); return 3; } @@ -829,6 +1059,21 @@ int control_service(unsigned long control, int argc, TCHAR **argv) { CloseHandle(service_handle); CloseServiceHandle(services); + if (error == ERROR_IO_PENDING) { + /* + Older versions of Windows return immediately with ERROR_IO_PENDING + indicate that the operation is still in progress. Newer versions + will return it if there really is a delay. As far as we're + concerned the operation is a success. We don't claim to offer a + fully-feature service control method; it's just a quick 'n' dirty + interface. + + In the future we may identify and handle this situation properly. + */ + ret = 1; + error = ERROR_SUCCESS; + } + if (ret) { _tprintf(_T("%s: %s"), canonical_name, error_string(error)); return 0; @@ -861,7 +1106,7 @@ int control_service(unsigned long control, int argc, TCHAR **argv) { return 0; } else { - _ftprintf(stderr, _T("%s: %s\n"), service_name, error_string(error)); + _ftprintf(stderr, _T("%s: %s\n"), canonical_name, error_string(error)); return 1; } } @@ -871,6 +1116,11 @@ int control_service(unsigned long control, int argc, TCHAR **argv) { CloseHandle(service_handle); CloseServiceHandle(services); + if (error == ERROR_IO_PENDING) { + ret = 1; + error = ERROR_SUCCESS; + } + if (ret) { _tprintf(_T("%s: %s"), canonical_name, error_string(error)); return 0; @@ -894,9 +1144,8 @@ int remove_service(nssm_service_t *service) { } /* Try to open the service */ - service->handle = OpenService(services, service->name, SC_MANAGER_ALL_ACCESS); + service->handle = open_service(services, service->name, service->name, _countof(service->name)); if (! service->handle) { - print_message(stderr, NSSM_MESSAGE_OPENSERVICE_FAILED); CloseServiceHandle(services); return 3; } @@ -1161,7 +1410,8 @@ int start_service(nssm_service_t *service) { bool inherit_handles = false; if (si.dwFlags & STARTF_USESTDHANDLES) inherit_handles = true; - unsigned long flags = 0; + unsigned long flags = service->priority & priority_mask(); + if (service->affinity) flags |= CREATE_SUSPENDED; #ifdef UNICODE flags |= CREATE_UNICODE_ENVIRONMENT; #endif @@ -1181,7 +1431,36 @@ int start_service(nssm_service_t *service) { if (get_process_creation_time(service->process_handle, &service->creation_time)) ZeroMemory(&service->creation_time, sizeof(service->creation_time)); - close_output_handles(&si); + close_output_handles(&si, ! service->rotate_stdout_online, ! service->rotate_stderr_online); + + if (service->affinity) { + /* + We are explicitly storing service->affinity as a 64-bit unsigned integer + so that we can parse it regardless of whether we're running in 32-bit + or 64-bit mode. The arguments to SetProcessAffinityMask(), however, are + defined as type DWORD_PTR and hence limited to 32 bits on a 32-bit system + (or when running the 32-bit NSSM). + + The result is a lot of seemingly-unnecessary casting throughout the code + and potentially confusion when we actually try to start the service. + Having said that, however, it's unlikely that we're actually going to + run in 32-bit mode on a system which has more than 32 CPUs so the + likelihood of seeing a confusing situation is somewhat diminished. + */ + DWORD_PTR affinity, system_affinity; + + if (GetProcessAffinityMask(service->process_handle, &affinity, &system_affinity)) affinity = service->affinity & system_affinity; + else { + affinity = (DWORD_PTR) service->affinity; + log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GETPROCESSAFFINITYMASK_FAILED, service->name, error_string(GetLastError()), 0); + } + + if (! SetProcessAffinityMask(service->process_handle, affinity)) { + log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_SETPROCESSAFFINITYMASK_FAILED, service->name, error_string(GetLastError()), 0); + } + + ResumeThread(pi.hThread); + } /* Wait for a clean startup before changing the service status to RUNNING @@ -1211,6 +1490,9 @@ int start_service(nssm_service_t *service) { else service->throttle = 0; } + /* Ensure the restart delay is always applied. */ + if (service->restart_delay && ! service->throttle) service->throttle++; + return 0; } @@ -1353,14 +1635,22 @@ void throttle_restart(nssm_service_t *service) { /* This can't be a restart if the service is already running. */ if (! service->throttle++) return; - int ms = throttle_milliseconds(service->throttle); + unsigned long ms; + unsigned long throttle_ms = throttle_milliseconds(service->throttle); + TCHAR threshold[8], milliseconds[8]; + + if (service->restart_delay > throttle_ms) ms = service->restart_delay; + else ms = throttle_ms; if (service->throttle > 7) service->throttle = 8; - TCHAR threshold[8], milliseconds[8]; - _sntprintf_s(threshold, _countof(threshold), _TRUNCATE, _T("%lu"), service->throttle_delay); _sntprintf_s(milliseconds, _countof(milliseconds), _TRUNCATE, _T("%lu"), ms); - log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_THROTTLED, service->name, threshold, milliseconds, 0); + + if (service->throttle == 1 && service->restart_delay > throttle_ms) log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_RESTART_DELAY, service->name, milliseconds, 0); + else { + _sntprintf_s(threshold, _countof(threshold), _TRUNCATE, _T("%lu"), service->throttle_delay); + log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_THROTTLED, service->name, threshold, milliseconds, 0); + } if (use_critical_section) EnterCriticalSection(&service->throttle_section); else if (service->throttle_timer) {