123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749 |
- #include "nssm.h"
- /* This is explicitly a wide string. */
- #define NSSM_LOGON_AS_SERVICE_RIGHT L"SeServiceLogonRight"
- bool is_admin;
- bool use_critical_section;
- extern imports_t imports;
- 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 };
- 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 int throttle_milliseconds(unsigned long throttle) {
- /* pow() operates on doubles. */
- int ret = 1; for (unsigned long i = 1; i < throttle; i++) ret *= 2;
- return ret * 1000;
- }
- /*
- Wrapper to be called in a new thread so that we can acknowledge a STOP
- control immediately.
- */
- static unsigned long WINAPI shutdown_service(void *arg) {
- return stop_service((nssm_service_t *) arg, 0, true, true);
- }
- /* Connect to the service manager */
- SC_HANDLE open_service_manager() {
- SC_HANDLE ret = OpenSCManager(0, SERVICES_ACTIVE_DATABASE, SC_MANAGER_ALL_ACCESS);
- if (! ret) {
- if (is_admin) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OPENSCMANAGER_FAILED, 0);
- return 0;
- }
- 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;
- unsigned long error;
- QueryServiceConfig(service_handle, 0, 0, &bufsize);
- error = GetLastError();
- if (error == ERROR_INSUFFICIENT_BUFFER) {
- qsc = (QUERY_SERVICE_CONFIG *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bufsize);
- if (! qsc) {
- print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("QUERY_SERVICE_CONFIG"), _T("query_service_config()"), 0);
- return 0;
- }
- }
- else {
- print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG_FAILED, service_name, error_string(error), 0);
- return 0;
- }
- if (! QueryServiceConfig(service_handle, qsc, bufsize, &bufsize)) {
- HeapFree(GetProcessHeap(), 0, qsc);
- print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG_FAILED, service_name, error_string(GetLastError()), 0);
- return 0;
- }
- return qsc;
- }
- int set_service_description(const TCHAR *service_name, SC_HANDLE service_handle, TCHAR *buffer) {
- SERVICE_DESCRIPTION description;
- ZeroMemory(&description, sizeof(description));
- /*
- lpDescription must be NULL if we aren't changing, the new description
- or "".
- */
- if (buffer && buffer[0]) description.lpDescription = buffer;
- else description.lpDescription = _T("");
- if (ChangeServiceConfig2(service_handle, SERVICE_CONFIG_DESCRIPTION, &description)) return 0;
- log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SERVICE_CONFIG_DESCRIPTION_FAILED, service_name, error_string(GetLastError()), 0);
- return 1;
- }
- int get_service_description(const TCHAR *service_name, SC_HANDLE service_handle, unsigned long len, TCHAR *buffer) {
- if (! buffer) return 1;
- unsigned long bufsize;
- QueryServiceConfig2(service_handle, SERVICE_CONFIG_DESCRIPTION, 0, 0, &bufsize);
- unsigned long error = GetLastError();
- if (error == ERROR_INSUFFICIENT_BUFFER) {
- SERVICE_DESCRIPTION *description = (SERVICE_DESCRIPTION *) HeapAlloc(GetProcessHeap(), 0, bufsize);
- if (! description) {
- print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("SERVICE_CONFIG_DESCRIPTION"), _T("get_service_description()"));
- return 2;
- }
- if (QueryServiceConfig2(service_handle, SERVICE_CONFIG_DESCRIPTION, (unsigned char *) description, bufsize, &bufsize)) {
- if (description->lpDescription) _sntprintf_s(buffer, len, _TRUNCATE, _T("%s"), description->lpDescription);
- else ZeroMemory(buffer, len * sizeof(TCHAR));
- HeapFree(GetProcessHeap(), 0, description);
- return 0;
- }
- else {
- HeapFree(GetProcessHeap(), 0, description);
- print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG2_FAILED, service_name, _T("SERVICE_CONFIG_DESCRIPTION"), error_string(error));
- return 3;
- }
- }
- else {
- print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG2_FAILED, service_name, _T("SERVICE_CONFIG_DESCRIPTION"), error_string(error));
- return 4;
- }
- return 0;
- }
- int get_service_startup(const TCHAR *service_name, SC_HANDLE service_handle, const QUERY_SERVICE_CONFIG *qsc, unsigned long *startup) {
- if (! qsc) return 1;
- switch (qsc->dwStartType) {
- case SERVICE_DEMAND_START: *startup = NSSM_STARTUP_MANUAL; break;
- case SERVICE_DISABLED: *startup = NSSM_STARTUP_DISABLED; break;
- default: *startup = NSSM_STARTUP_AUTOMATIC;
- }
- if (*startup != NSSM_STARTUP_AUTOMATIC) return 0;
- /* Check for delayed start. */
- unsigned long bufsize;
- unsigned long error;
- QueryServiceConfig2(service_handle, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, 0, 0, &bufsize);
- error = GetLastError();
- if (error == ERROR_INSUFFICIENT_BUFFER) {
- SERVICE_DELAYED_AUTO_START_INFO *info = (SERVICE_DELAYED_AUTO_START_INFO *) HeapAlloc(GetProcessHeap(), 0, bufsize);
- if (! info) {
- print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("SERVICE_DELAYED_AUTO_START_INFO"), _T("get_service_startup()"));
- return 2;
- }
- if (QueryServiceConfig2(service_handle, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, (unsigned char *) info, bufsize, &bufsize)) {
- if (info->fDelayedAutostart) *startup = NSSM_STARTUP_DELAYED;
- HeapFree(GetProcessHeap(), 0, info);
- return 0;
- }
- else {
- error = GetLastError();
- if (error != ERROR_INVALID_LEVEL) {
- print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG2_FAILED, service_name, _T("SERVICE_CONFIG_DELAYED_AUTO_START_INFO"), error_string(error));
- return 3;
- }
- }
- }
- else if (error != ERROR_INVALID_LEVEL) {
- print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG2_FAILED, service_name, _T("SERVICE_DELAYED_AUTO_START_INFO"), error_string(error));
- return 3;
- }
- return 0;
- }
- int get_service_username(const TCHAR *service_name, const QUERY_SERVICE_CONFIG *qsc, TCHAR **username, size_t *usernamelen) {
- if (! username) return 1;
- if (! usernamelen) return 1;
- *username = 0;
- *usernamelen = 0;
- if (! qsc) return 1;
- if (str_equiv(qsc->lpServiceStartName, NSSM_LOCALSYSTEM_ACCOUNT)) return 0;
- size_t len = _tcslen(qsc->lpServiceStartName);
- *username = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(TCHAR));
- if (! *username) {
- print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("username"), _T("get_service_username()"));
- return 2;
- }
- memmove(*username, qsc->lpServiceStartName, (len + 1) * sizeof(TCHAR));
- *usernamelen = len;
- return 0;
- }
- int grant_logon_as_service(const TCHAR *username) {
- if (! username) return 0;
- if (str_equiv(username, NSSM_LOCALSYSTEM_ACCOUNT)) return 0;
- /* Open Policy object. */
- LSA_OBJECT_ATTRIBUTES attributes;
- ZeroMemory(&attributes, sizeof(attributes));
- LSA_HANDLE policy;
- NTSTATUS status = LsaOpenPolicy(0, &attributes, POLICY_ALL_ACCESS, &policy);
- if (status) {
- print_message(stderr, NSSM_MESSAGE_LSAOPENPOLICY_FAILED, error_string(LsaNtStatusToWinError(status)));
- return 1;
- }
- /* Look up SID for the account. */
- LSA_UNICODE_STRING lsa_username;
- #ifdef UNICODE
- lsa_username.Buffer = (wchar_t *) username;
- lsa_username.Length = (unsigned short) _tcslen(username) * sizeof(TCHAR);
- lsa_username.MaximumLength = lsa_username.Length + sizeof(TCHAR);
- #else
- size_t buflen;
- mbstowcs_s(&buflen, NULL, 0, username, _TRUNCATE);
- 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);
- else {
- LsaClose(policy);
- print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("LSA_UNICODE_STRING"), _T("grant_logon_as_service()"));
- return 2;
- }
- #endif
- LSA_REFERENCED_DOMAIN_LIST *translated_domains;
- LSA_TRANSLATED_SID *translated_sid;
- status = LsaLookupNames(policy, 1, &lsa_username, &translated_domains, &translated_sid);
- #ifndef UNICODE
- HeapFree(GetProcessHeap(), 0, lsa_username.Buffer);
- #endif
- if (status) {
- LsaFreeMemory(translated_domains);
- LsaFreeMemory(translated_sid);
- LsaClose(policy);
- print_message(stderr, NSSM_MESSAGE_LSALOOKUPNAMES_FAILED, username, error_string(LsaNtStatusToWinError(status)));
- return 3;
- }
- if (translated_sid->Use != SidTypeUser) {
- LsaFreeMemory(translated_domains);
- LsaFreeMemory(translated_sid);
- LsaClose(policy);
- print_message(stderr, NSSM_GUI_INVALID_USERNAME, username);
- return 4;
- }
- LSA_TRUST_INFORMATION *trust = &translated_domains->Domains[translated_sid->DomainIndex];
- if (! trust || ! IsValidSid(trust->Sid)) {
- LsaFreeMemory(translated_domains);
- LsaFreeMemory(translated_sid);
- LsaClose(policy);
- print_message(stderr, NSSM_GUI_INVALID_USERNAME, username);
- return 4;
- }
- /* GetSidSubAuthority*() return pointers! */
- unsigned char *n = GetSidSubAuthorityCount(trust->Sid);
- /* Convert translated SID to SID. */
- SID *sid = (SID *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, GetSidLengthRequired(*n + 1));
- if (! sid) {
- LsaFreeMemory(translated_domains);
- LsaFreeMemory(translated_sid);
- LsaClose(policy);
- print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("SID"), _T("grant_logon_as_service"));
- return 4;
- }
- unsigned long error;
- if (! InitializeSid(sid, GetSidIdentifierAuthority(trust->Sid), *n + 1)) {
- error = GetLastError();
- HeapFree(GetProcessHeap(), 0, sid);
- LsaFreeMemory(translated_domains);
- LsaFreeMemory(translated_sid);
- LsaClose(policy);
- print_message(stderr, NSSM_MESSAGE_INITIALIZESID_FAILED, username, error_string(error));
- return 5;
- }
- for (unsigned char i = 0; i <= *n; i++) {
- unsigned long *sub = GetSidSubAuthority(sid, i);
- if (i < *n) *sub = *GetSidSubAuthority(trust->Sid, i);
- else *sub = translated_sid->RelativeId;
- }
- LsaFreeMemory(translated_domains);
- LsaFreeMemory(translated_sid);
- /* Check if the SID has the "Log on as a service" right. */
- LSA_UNICODE_STRING lsa_right;
- lsa_right.Buffer = NSSM_LOGON_AS_SERVICE_RIGHT;
- lsa_right.Length = (unsigned short) wcslen(lsa_right.Buffer) * sizeof(wchar_t);
- lsa_right.MaximumLength = lsa_right.Length + sizeof(wchar_t);
- LSA_UNICODE_STRING *rights;
- unsigned long count = ~0;
- status = LsaEnumerateAccountRights(policy, sid, &rights, &count);
- if (status) {
- /*
- If the account has no rights set LsaEnumerateAccountRights() will return
- STATUS_OBJECT_NAME_NOT_FOUND and set count to 0.
- */
- error = LsaNtStatusToWinError(status);
- if (error != ERROR_FILE_NOT_FOUND) {
- HeapFree(GetProcessHeap(), 0, sid);
- LsaClose(policy);
- print_message(stderr, NSSM_MESSAGE_LSAENUMERATEACCOUNTRIGHTS_FAILED, username, error_string(error));
- return 4;
- }
- }
- for (unsigned long i = 0; i < count; i++) {
- if (rights[i].Length != lsa_right.Length) continue;
- if (_wcsnicmp(rights[i].Buffer, lsa_right.Buffer, lsa_right.MaximumLength)) continue;
- /* The SID has the right. */
- HeapFree(GetProcessHeap(), 0, sid);
- LsaFreeMemory(rights);
- LsaClose(policy);
- return 0;
- }
- LsaFreeMemory(rights);
- /* Add the right. */
- status = LsaAddAccountRights(policy, sid, &lsa_right, 1);
- HeapFree(GetProcessHeap(), 0, sid);
- LsaClose(policy);
- if (status) {
- print_message(stderr, NSSM_MESSAGE_LSAADDACCOUNTRIGHTS_FAILED, error_string(LsaNtStatusToWinError(status)));
- return 5;
- }
- print_message(stdout, NSSM_MESSAGE_GRANTED_LOGON_AS_SERVICE, username);
- return 0;
- }
- /* Set default values which aren't zero. */
- 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;
- service->stdout_sharing = NSSM_STDOUT_SHARING;
- service->stdout_disposition = NSSM_STDOUT_DISPOSITION;
- service->stdout_flags = NSSM_STDOUT_FLAGS;
- service->stderr_sharing = NSSM_STDERR_SHARING;
- service->stderr_disposition = NSSM_STDERR_DISPOSITION;
- service->stderr_flags = NSSM_STDERR_FLAGS;
- service->throttle_delay = NSSM_RESET_THROTTLE_RESTART;
- service->stop_method = ~0;
- service->kill_console_delay = NSSM_KILL_CONSOLE_GRACE_PERIOD;
- service->kill_window_delay = NSSM_KILL_WINDOW_GRACE_PERIOD;
- service->kill_threads_delay = NSSM_KILL_THREADS_GRACE_PERIOD;
- }
- /* Allocate and zero memory for a service. */
- nssm_service_t *alloc_nssm_service() {
- nssm_service_t *service = (nssm_service_t *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(nssm_service_t));
- if (! service) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("service"), _T("alloc_nssm_service()"), 0);
- return service;
- }
- /* Free memory for a service. */
- void cleanup_nssm_service(nssm_service_t *service) {
- if (! service) return;
- if (service->username) HeapFree(GetProcessHeap(), 0, service->username);
- if (service->password) {
- SecureZeroMemory(service->password, service->passwordlen);
- HeapFree(GetProcessHeap(), 0, service->password);
- }
- if (service->env) HeapFree(GetProcessHeap(), 0, service->env);
- if (service->env_extra) HeapFree(GetProcessHeap(), 0, service->env_extra);
- if (service->handle) CloseServiceHandle(service->handle);
- if (service->process_handle) CloseHandle(service->process_handle);
- if (service->wait_handle) UnregisterWait(service->process_handle);
- if (service->throttle_section_initialised) DeleteCriticalSection(&service->throttle_section);
- if (service->throttle_timer) CloseHandle(service->throttle_timer);
- HeapFree(GetProcessHeap(), 0, service);
- }
- /* About to install the service */
- int pre_install_service(int argc, TCHAR **argv) {
- nssm_service_t *service = alloc_nssm_service();
- set_nssm_service_defaults(service);
- if (argc) _sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), argv[0]);
- /* Show the dialogue box if we didn't give the service name and path */
- if (argc < 2) return nssm_gui(IDD_INSTALL, service);
- if (! service) {
- print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("service"), _T("pre_install_service()"));
- return 1;
- }
- _sntprintf_s(service->exe, _countof(service->exe), _TRUNCATE, _T("%s"), argv[1]);
- /* Arguments are optional */
- size_t flagslen = 0;
- size_t s = 0;
- int i;
- for (i = 2; i < argc; i++) flagslen += _tcslen(argv[i]) + 1;
- if (! flagslen) flagslen = 1;
- if (flagslen > _countof(service->flags)) {
- print_message(stderr, NSSM_MESSAGE_FLAGS_TOO_LONG);
- return 2;
- }
- for (i = 2; i < argc; i++) {
- size_t len = _tcslen(argv[i]);
- memmove(service->flags + s, argv[i], len * sizeof(TCHAR));
- s += len;
- if (i < argc - 1) service->flags[s++] = _T(' ');
- }
- /* Work out directory name */
- _sntprintf_s(service->dir, _countof(service->dir), _TRUNCATE, _T("%s"), service->exe);
- strip_basename(service->dir);
- int ret = install_service(service);
- cleanup_nssm_service(service);
- return ret;
- }
- /* About to edit the service. */
- int pre_edit_service(int argc, TCHAR **argv) {
- /* Require service name. */
- if (argc < 2) return usage(1);
- /* Are we editing on the command line? */
- enum { MODE_EDITING, MODE_GETTING, MODE_SETTING, MODE_RESETTING } mode = MODE_EDITING;
- const TCHAR *verb = argv[0];
- const TCHAR *service_name = argv[1];
- bool getting = false;
- bool unsetting = false;
- /* Minimum number of arguments. */
- int mandatory = 2;
- /* Index of first value. */
- int remainder = 3;
- int i;
- if (str_equiv(verb, _T("get"))) {
- mandatory = 3;
- mode = MODE_GETTING;
- }
- else if (str_equiv(verb, _T("set"))) {
- mandatory = 4;
- mode = MODE_SETTING;
- }
- else if (str_equiv(verb, _T("reset")) || str_equiv(verb, _T("unset"))) {
- mandatory = 3;
- mode = MODE_RESETTING;
- }
- if (argc < mandatory) return usage(1);
- const TCHAR *parameter = 0;
- settings_t *setting = 0;
- TCHAR *additional;
- /* Validate the parameter. */
- if (mandatory > 2) {
- bool additional_mandatory = false;
- parameter = argv[2];
- for (i = 0; settings[i].name; i++) {
- setting = &settings[i];
- if (! str_equiv(setting->name, parameter)) continue;
- if (((setting->additional & ADDITIONAL_GETTING) && mode == MODE_GETTING) || ((setting->additional & ADDITIONAL_SETTING) && mode == MODE_SETTING) || ((setting->additional & ADDITIONAL_RESETTING) && mode == MODE_RESETTING)) {
- additional_mandatory = true;
- mandatory++;
- }
- break;
- }
- if (! settings[i].name) {
- print_message(stderr, NSSM_MESSAGE_INVALID_PARAMETER, parameter);
- for (i = 0; settings[i].name; i++) _ftprintf(stderr, _T("%s\n"), settings[i].name);
- return 1;
- }
- if (argc < mandatory) return usage(1);
- additional = 0;
- if (additional_mandatory) {
- additional = argv[3];
- remainder = 4;
- }
- else additional = argv[remainder];
- }
- nssm_service_t *service = alloc_nssm_service();
- _sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), service_name);
- /* Open service manager */
- SC_HANDLE services = open_service_manager();
- if (! services) {
- print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
- return 2;
- }
- /* Try to open the service */
- service->handle = open_service(services, service->name, service->name, _countof(service->name));
- if (! service->handle) {
- CloseServiceHandle(services);
- return 3;
- }
- /* Get system details. */
- QUERY_SERVICE_CONFIG *qsc = query_service_config(service->name, service->handle);
- if (! qsc) {
- CloseHandle(service->handle);
- CloseServiceHandle(services);
- return 4;
- }
- service->type = qsc->dwServiceType;
- if (! (service->type & SERVICE_WIN32_OWN_PROCESS)) {
- if (mode != MODE_GETTING) {
- HeapFree(GetProcessHeap(), 0, qsc);
- CloseHandle(service->handle);
- CloseServiceHandle(services);
- print_message(stderr, NSSM_MESSAGE_CANNOT_EDIT, service->name, NSSM_WIN32_OWN_PROCESS, 0);
- return 3;
- }
- }
- if (get_service_startup(service->name, service->handle, qsc, &service->startup)) {
- if (mode != MODE_GETTING) {
- HeapFree(GetProcessHeap(), 0, qsc);
- CloseHandle(service->handle);
- CloseServiceHandle(services);
- return 4;
- }
- }
- if (get_service_username(service->name, qsc, &service->username, &service->usernamelen)) {
- if (mode != MODE_GETTING) {
- HeapFree(GetProcessHeap(), 0, qsc);
- CloseHandle(service->handle);
- CloseServiceHandle(services);
- return 5;
- }
- }
- _sntprintf_s(service->displayname, _countof(service->displayname), _TRUNCATE, _T("%s"), qsc->lpDisplayName);
- /* Get the canonical service name. We open it case insensitively. */
- unsigned long bufsize = _countof(service->name);
- GetServiceKeyName(services, service->displayname, service->name, &bufsize);
- /* Remember the executable in case it isn't NSSM. */
- _sntprintf_s(service->image, _countof(service->image), _TRUNCATE, _T("%s"), qsc->lpBinaryPathName);
- HeapFree(GetProcessHeap(), 0, qsc);
- /* Get extended system details. */
- if (get_service_description(service->name, service->handle, _countof(service->description), service->description)) {
- if (mode != MODE_GETTING) {
- CloseHandle(service->handle);
- CloseServiceHandle(services);
- return 6;
- }
- }
- /* Get NSSM details. */
- get_parameters(service, 0);
- CloseServiceHandle(services);
- if (! service->exe[0]) {
- service->native = true;
- if (mode != MODE_GETTING) print_message(stderr, NSSM_MESSAGE_INVALID_SERVICE, service->name, NSSM, service->image);
- }
- /* Editing with the GUI. */
- if (mode == MODE_EDITING) {
- nssm_gui(IDD_EDIT, service);
- return 0;
- }
- /* Trying to manage App* parameters for a non-NSSM service. */
- if (! setting->native && service->native) {
- CloseHandle(service->handle);
- print_message(stderr, NSSM_MESSAGE_NATIVE_PARAMETER, setting->name, NSSM);
- return 1;
- }
- HKEY key;
- value_t value;
- int ret;
- if (mode == MODE_GETTING) {
- if (! service->native) {
- key = open_registry(service->name, KEY_READ);
- if (! key) return 4;
- }
- if (setting->native) ret = get_setting(service->name, service->handle, setting, &value, additional);
- else ret = get_setting(service->name, key, setting, &value, additional);
- if (ret < 0) {
- CloseHandle(service->handle);
- return 5;
- }
- switch (setting->type) {
- case REG_EXPAND_SZ:
- case REG_MULTI_SZ:
- case REG_SZ:
- _tprintf(_T("%s\n"), value.string ? value.string : _T(""));
- HeapFree(GetProcessHeap(), 0, value.string);
- break;
- case REG_DWORD:
- _tprintf(_T("%u\n"), value.numeric);
- break;
- }
- if (! service->native) RegCloseKey(key);
- CloseHandle(service->handle);
- return 0;
- }
- /* Build the value. */
- if (mode == MODE_RESETTING) {
- /* Unset the parameter. */
- value.string = 0;
- }
- else {
- /* Set the parameter. */
- size_t len = 0;
- size_t delimiterlen = (setting->additional & ADDITIONAL_CRLF) ? 2 : 1;
- for (i = remainder; i < argc; i++) len += _tcslen(argv[i]) + delimiterlen;
- len++;
- value.string = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, len * sizeof(TCHAR));
- if (! value.string) {
- print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("value"), _T("edit_service()"));
- CloseHandle(service->handle);
- return 2;
- }
- size_t s = 0;
- for (i = remainder; i < argc; i++) {
- size_t len = _tcslen(argv[i]);
- memmove(value.string + s, argv[i], len * sizeof(TCHAR));
- s += len;
- if (i < argc - 1) {
- if (setting->additional & ADDITIONAL_CRLF) {
- value.string[s++] = _T('\r');
- value.string[s++] = _T('\n');
- }
- else value.string[s++] = _T(' ');
- }
- }
- value.string[s] = _T('\0');
- }
- if (! service->native) {
- key = open_registry(service->name, KEY_WRITE);
- if (! key) {
- if (value.string) HeapFree(GetProcessHeap(), 0, value.string);
- return 4;
- }
- }
- if (setting->native) ret = set_setting(service->name, service->handle, setting, &value, additional);
- else ret = set_setting(service->name, key, setting, &value, additional);
- if (value.string) HeapFree(GetProcessHeap(), 0, value.string);
- if (ret < 0) {
- if (! service->native) RegCloseKey(key);
- CloseHandle(service->handle);
- return 6;
- }
- if (! service->native) RegCloseKey(key);
- CloseHandle(service->handle);
- return 0;
- }
- /* About to remove the service */
- int pre_remove_service(int argc, TCHAR **argv) {
- nssm_service_t *service = alloc_nssm_service();
- set_nssm_service_defaults(service);
- if (argc) _sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), argv[0]);
- /* Show dialogue box if we didn't pass service name and "confirm" */
- if (argc < 2) return nssm_gui(IDD_REMOVE, service);
- if (str_equiv(argv[1], _T("confirm"))) {
- int ret = remove_service(service);
- cleanup_nssm_service(service);
- return ret;
- }
- print_message(stderr, NSSM_MESSAGE_PRE_REMOVE_SERVICE);
- return 100;
- }
- /* Install the service */
- int install_service(nssm_service_t *service) {
- if (! service) return 1;
- /* Open service manager */
- SC_HANDLE services = open_service_manager();
- if (! services) {
- print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
- cleanup_nssm_service(service);
- return 2;
- }
- /* Get path of this program */
- 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, 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, error_string(GetLastError()));
- CloseServiceHandle(services);
- return 5;
- }
- if (edit_service(service, false)) {
- DeleteService(service->handle);
- CloseServiceHandle(services);
- return 6;
- }
- print_message(stdout, NSSM_MESSAGE_SERVICE_INSTALLED, service->name);
- /* Cleanup */
- CloseServiceHandle(services);
- return 0;
- }
- /* Edit the service. */
- int edit_service(nssm_service_t *service, bool editing) {
- if (! service) return 1;
- /*
- The only two valid flags for service type are SERVICE_WIN32_OWN_PROCESS
- and SERVICE_INTERACTIVE_PROCESS.
- */
- service->type &= SERVICE_INTERACTIVE_PROCESS;
- service->type |= SERVICE_WIN32_OWN_PROCESS;
- /* Startup type. */
- unsigned long startup;
- switch (service->startup) {
- case NSSM_STARTUP_MANUAL: startup = SERVICE_DEMAND_START; break;
- case NSSM_STARTUP_DISABLED: startup = SERVICE_DISABLED; break;
- default: startup = SERVICE_AUTO_START;
- }
- /* Display name. */
- if (! service->displayname[0]) _sntprintf_s(service->displayname, _countof(service->displayname), _TRUNCATE, _T("%s"), service->name);
- /*
- Username must be NULL if we aren't changing or an account name.
- We must explicitly use LOCALSYSTEM to change it when we are editing.
- Password must be NULL if we aren't changing, a password or "".
- Empty passwords are valid but we won't allow them in the GUI.
- */
- TCHAR *username = 0;
- TCHAR *password = 0;
- if (service->usernamelen) {
- username = service->username;
- if (service->passwordlen) password = service->password;
- else password = _T("");
- }
- else if (editing) username = NSSM_LOCALSYSTEM_ACCOUNT;
- if (grant_logon_as_service(username)) {
- print_message(stderr, NSSM_MESSAGE_GRANT_LOGON_AS_SERVICE_FAILED, username);
- return 5;
- }
- if (! ChangeServiceConfig(service->handle, service->type, startup, SERVICE_NO_CHANGE, 0, 0, 0, 0, username, password, service->displayname)) {
- print_message(stderr, NSSM_MESSAGE_CHANGESERVICECONFIG_FAILED, error_string(GetLastError()));
- return 5;
- }
- if (service->description[0] || editing) {
- set_service_description(service->name, service->handle, service->description);
- }
- SERVICE_DELAYED_AUTO_START_INFO delayed;
- ZeroMemory(&delayed, sizeof(delayed));
- if (service->startup == NSSM_STARTUP_DELAYED) delayed.fDelayedAutostart = 1;
- else delayed.fDelayedAutostart = 0;
- /* Delayed startup isn't supported until Vista. */
- if (! ChangeServiceConfig2(service->handle, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, &delayed)) {
- unsigned long error = GetLastError();
- /* Pre-Vista we expect to fail with ERROR_INVALID_LEVEL */
- if (error != ERROR_INVALID_LEVEL) {
- log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SERVICE_CONFIG_DELAYED_AUTO_START_INFO_FAILED, service->name, error_string(error), 0);
- }
- }
- /* Don't mess with parameters which aren't ours. */
- if (! service->native) {
- /* Now we need to put the parameters into the registry */
- if (create_parameters(service, editing)) {
- print_message(stderr, NSSM_MESSAGE_CREATE_PARAMETERS_FAILED);
- return 6;
- }
- set_service_recovery(service);
- }
- return 0;
- }
- /* Control a service. */
- 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) {
- print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
- return 2;
- }
- SC_HANDLE service_handle = open_service(services, service_name, canonical_name, _countof(canonical_name));
- if (! service_handle) {
- CloseServiceHandle(services);
- return 3;
- }
- int ret;
- unsigned long error;
- SERVICE_STATUS service_status;
- if (control == 0) {
- ret = StartService(service_handle, (unsigned long) argc, (const TCHAR **) argv);
- error = GetLastError();
- 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;
- }
- else {
- _ftprintf(stderr, _T("%s: %s"), canonical_name, error_string(error));
- return 1;
- }
- }
- else if (control == SERVICE_CONTROL_INTERROGATE) {
- /*
- We could actually send an INTERROGATE control but that won't return
- any information if the service is stopped and we don't care about
- the extra details it might give us in any case. So we'll fake it.
- */
- ret = QueryServiceStatus(service_handle, &service_status);
- error = GetLastError();
- if (ret) {
- switch (service_status.dwCurrentState) {
- case SERVICE_STOPPED: _tprintf(_T("SERVICE_STOPPED\n")); break;
- case SERVICE_START_PENDING: _tprintf(_T("SERVICE_START_PENDING\n")); break;
- case SERVICE_STOP_PENDING: _tprintf(_T("SERVICE_STOP_PENDING\n")); break;
- case SERVICE_RUNNING: _tprintf(_T("SERVICE_RUNNING\n")); break;
- case SERVICE_CONTINUE_PENDING: _tprintf(_T("SERVICE_CONTINUE_PENDING\n")); break;
- case SERVICE_PAUSE_PENDING: _tprintf(_T("SERVICE_PAUSE_PENDING\n")); break;
- case SERVICE_PAUSED: _tprintf(_T("SERVICE_PAUSED\n")); break;
- default: _tprintf(_T("?\n")); return 1;
- }
- return 0;
- }
- else {
- _ftprintf(stderr, _T("%s: %s\n"), canonical_name, error_string(error));
- return 1;
- }
- }
- else {
- ret = ControlService(service_handle, control, &service_status);
- error = GetLastError();
- 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;
- }
- else {
- _ftprintf(stderr, _T("%s: %s"), canonical_name, error_string(error));
- return 1;
- }
- }
- }
- /* Remove the service */
- int remove_service(nssm_service_t *service) {
- if (! service) return 1;
- /* Open service manager */
- SC_HANDLE services = open_service_manager();
- if (! services) {
- print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
- return 2;
- }
- /* Try to open the service */
- service->handle = open_service(services, service->name, service->name, _countof(service->name));
- if (! service->handle) {
- CloseServiceHandle(services);
- return 3;
- }
- /* Get the canonical service name. We open it case insensitively. */
- unsigned long bufsize = _countof(service->displayname);
- GetServiceDisplayName(services, service->name, service->displayname, &bufsize);
- bufsize = _countof(service->name);
- GetServiceKeyName(services, service->displayname, service->name, &bufsize);
- /* Try to delete the service */
- if (! DeleteService(service->handle)) {
- print_message(stderr, NSSM_MESSAGE_DELETESERVICE_FAILED);
- CloseServiceHandle(services);
- return 4;
- }
- /* Cleanup */
- CloseServiceHandle(services);
- print_message(stdout, NSSM_MESSAGE_SERVICE_REMOVED, service->name);
- return 0;
- }
- /* Service initialisation */
- void WINAPI service_main(unsigned long argc, TCHAR **argv) {
- nssm_service_t *service = alloc_nssm_service();
- if (! service) return;
- if (_sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), argv[0]) < 0) {
- log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("service->name"), _T("service_main()"), 0);
- return;
- }
- /* We can use a condition variable in a critical section on Vista or later. */
- if (imports.SleepConditionVariableCS && imports.WakeConditionVariable) use_critical_section = true;
- else use_critical_section = false;
- /* Initialise status */
- ZeroMemory(&service->status, sizeof(service->status));
- service->status.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS;
- service->status.dwControlsAccepted = SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE;
- service->status.dwWin32ExitCode = NO_ERROR;
- service->status.dwServiceSpecificExitCode = 0;
- service->status.dwCheckPoint = 0;
- service->status.dwWaitHint = NSSM_WAITHINT_MARGIN;
- /* Signal we AREN'T running the server */
- service->process_handle = 0;
- service->pid = 0;
- /* Register control handler */
- service->status_handle = RegisterServiceCtrlHandlerEx(NSSM, service_control_handler, (void *) service);
- if (! service->status_handle) {
- log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_REGISTERSERVICECTRLHANDER_FAILED, error_string(GetLastError()), 0);
- return;
- }
- log_service_control(service->name, 0, true);
- service->status.dwCurrentState = SERVICE_START_PENDING;
- service->status.dwWaitHint = service->throttle_delay + NSSM_WAITHINT_MARGIN;
- SetServiceStatus(service->status_handle, &service->status);
- if (is_admin) {
- /* Try to create the exit action parameters; we don't care if it fails */
- create_exit_action(service->name, exit_action_strings[0], false);
- SC_HANDLE services = open_service_manager();
- if (services) {
- service->handle = OpenService(services, service->name, SC_MANAGER_ALL_ACCESS);
- set_service_recovery(service);
- CloseServiceHandle(services);
- }
- }
- /* Used for signalling a resume if the service pauses when throttled. */
- if (use_critical_section) {
- InitializeCriticalSection(&service->throttle_section);
- service->throttle_section_initialised = true;
- }
- else {
- service->throttle_timer = CreateWaitableTimer(0, 1, 0);
- if (! service->throttle_timer) {
- log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_CREATEWAITABLETIMER_FAILED, service->name, error_string(GetLastError()), 0);
- }
- }
- monitor_service(service);
- }
- /* Make sure service recovery actions are taken where necessary */
- void set_service_recovery(nssm_service_t *service) {
- SERVICE_FAILURE_ACTIONS_FLAG flag;
- ZeroMemory(&flag, sizeof(flag));
- flag.fFailureActionsOnNonCrashFailures = true;
- /* This functionality was added in Vista so the call may fail */
- if (! ChangeServiceConfig2(service->handle, SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, &flag)) {
- unsigned long error = GetLastError();
- /* Pre-Vista we expect to fail with ERROR_INVALID_LEVEL */
- if (error != ERROR_INVALID_LEVEL) {
- log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SERVICE_CONFIG_FAILURE_ACTIONS_FAILED, service->name, error_string(error), 0);
- }
- }
- }
- int monitor_service(nssm_service_t *service) {
- /* Set service status to started */
- int ret = start_service(service);
- if (ret) {
- TCHAR code[16];
- _sntprintf_s(code, _countof(code), _TRUNCATE, _T("%d"), ret);
- log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_START_SERVICE_FAILED, service->exe, service->name, ret, 0);
- return ret;
- }
- log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_STARTED_SERVICE, service->exe, service->flags, service->name, service->dir, 0);
- /* Monitor service */
- if (! RegisterWaitForSingleObject(&service->wait_handle, service->process_handle, end_service, (void *) service, INFINITE, WT_EXECUTEONLYONCE | WT_EXECUTELONGFUNCTION)) {
- log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_REGISTERWAITFORSINGLEOBJECT_FAILED, service->name, service->exe, error_string(GetLastError()), 0);
- }
- return 0;
- }
- TCHAR *service_control_text(unsigned long control) {
- switch (control) {
- /* HACK: there is no SERVICE_CONTROL_START constant */
- case 0: return _T("START");
- case SERVICE_CONTROL_STOP: return _T("STOP");
- case SERVICE_CONTROL_SHUTDOWN: return _T("SHUTDOWN");
- case SERVICE_CONTROL_PAUSE: return _T("PAUSE");
- case SERVICE_CONTROL_CONTINUE: return _T("CONTINUE");
- case SERVICE_CONTROL_INTERROGATE: return _T("INTERROGATE");
- default: return 0;
- }
- }
- void log_service_control(TCHAR *service_name, unsigned long control, bool handled) {
- TCHAR *text = service_control_text(control);
- unsigned long event;
- if (! text) {
- /* "0x" + 8 x hex + NULL */
- text = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, 11 * sizeof(TCHAR));
- if (! text) {
- log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("control code"), _T("log_service_control()"), 0);
- return;
- }
- if (_sntprintf_s(text, 11, _TRUNCATE, _T("0x%08x"), control) < 0) {
- log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("control code"), _T("log_service_control()"), 0);
- HeapFree(GetProcessHeap(), 0, text);
- return;
- }
- event = NSSM_EVENT_SERVICE_CONTROL_UNKNOWN;
- }
- else if (handled) event = NSSM_EVENT_SERVICE_CONTROL_HANDLED;
- else event = NSSM_EVENT_SERVICE_CONTROL_NOT_HANDLED;
- log_event(EVENTLOG_INFORMATION_TYPE, event, service_name, text, 0);
- if (event == NSSM_EVENT_SERVICE_CONTROL_UNKNOWN) {
- HeapFree(GetProcessHeap(), 0, text);
- }
- }
- /* Service control handler */
- unsigned long WINAPI service_control_handler(unsigned long control, unsigned long event, void *data, void *context) {
- nssm_service_t *service = (nssm_service_t *) context;
- switch (control) {
- case SERVICE_CONTROL_INTERROGATE:
- /* We always keep the service status up-to-date so this is a no-op. */
- return NO_ERROR;
- case SERVICE_CONTROL_SHUTDOWN:
- case SERVICE_CONTROL_STOP:
- log_service_control(service->name, control, true);
- /*
- We MUST acknowledge the stop request promptly but we're committed to
- waiting for the application to exit. Spawn a new thread to wait
- while we acknowledge the request.
- */
- if (! CreateThread(NULL, 0, shutdown_service, context, 0, NULL)) {
- log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATETHREAD_FAILED, error_string(GetLastError()), 0);
- /*
- We couldn't create a thread to tidy up so we'll have to force the tidyup
- to complete in time in this thread.
- */
- service->kill_console_delay = NSSM_KILL_CONSOLE_GRACE_PERIOD;
- service->kill_window_delay = NSSM_KILL_WINDOW_GRACE_PERIOD;
- service->kill_threads_delay = NSSM_KILL_THREADS_GRACE_PERIOD;
- stop_service(service, 0, true, true);
- }
- return NO_ERROR;
- case SERVICE_CONTROL_CONTINUE:
- log_service_control(service->name, control, true);
- service->throttle = 0;
- if (use_critical_section) imports.WakeConditionVariable(&service->throttle_condition);
- else {
- if (! service->throttle_timer) return ERROR_CALL_NOT_IMPLEMENTED;
- ZeroMemory(&service->throttle_duetime, sizeof(service->throttle_duetime));
- SetWaitableTimer(service->throttle_timer, &service->throttle_duetime, 0, 0, 0, 0);
- }
- service->status.dwCurrentState = SERVICE_CONTINUE_PENDING;
- service->status.dwWaitHint = throttle_milliseconds(service->throttle) + NSSM_WAITHINT_MARGIN;
- log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_RESET_THROTTLE, service->name, 0);
- SetServiceStatus(service->status_handle, &service->status);
- return NO_ERROR;
- case SERVICE_CONTROL_PAUSE:
- /*
- We don't accept pause messages but it isn't possible to register
- only for continue messages so we have to handle this case.
- */
- log_service_control(service->name, control, false);
- return ERROR_CALL_NOT_IMPLEMENTED;
- }
- /* Unknown control */
- log_service_control(service->name, control, false);
- return ERROR_CALL_NOT_IMPLEMENTED;
- }
- /* Start the service */
- int start_service(nssm_service_t *service) {
- service->stopping = false;
- service->allow_restart = true;
- if (service->process_handle) return 0;
- /* Allocate a STARTUPINFO structure for a new process */
- STARTUPINFO si;
- ZeroMemory(&si, sizeof(si));
- si.cb = sizeof(si);
- /* Allocate a PROCESSINFO structure for the process */
- PROCESS_INFORMATION pi;
- ZeroMemory(&pi, sizeof(pi));
- /* Get startup parameters */
- int ret = get_parameters(service, &si);
- if (ret) {
- log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GET_PARAMETERS_FAILED, service->name, 0);
- return stop_service(service, 2, true, true);
- }
- /* Launch executable with arguments */
- TCHAR cmd[CMD_LENGTH];
- if (_sntprintf_s(cmd, _countof(cmd), _TRUNCATE, _T("\"%s\" %s"), service->exe, service->flags) < 0) {
- log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("command line"), _T("start_service"), 0);
- close_output_handles(&si);
- return stop_service(service, 2, true, true);
- }
- throttle_restart(service);
- bool inherit_handles = false;
- if (si.dwFlags & STARTF_USESTDHANDLES) inherit_handles = true;
- unsigned long flags = service->priority & priority_mask();
- if (service->affinity) flags |= CREATE_SUSPENDED;
- #ifdef UNICODE
- flags |= CREATE_UNICODE_ENVIRONMENT;
- #endif
- if (! CreateProcess(0, cmd, 0, 0, inherit_handles, flags, service->env, service->dir, &si, &pi)) {
- unsigned long exitcode = 3;
- unsigned long error = GetLastError();
- if (error == ERROR_INVALID_PARAMETER && service->env) {
- log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEPROCESS_FAILED_INVALID_ENVIRONMENT, service->name, service->exe, NSSM_REG_ENV, 0);
- if (test_environment(service->env)) exitcode = 4;
- }
- else log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEPROCESS_FAILED, service->name, service->exe, error_string(error), 0);
- close_output_handles(&si);
- return stop_service(service, exitcode, true, true);
- }
- service->process_handle = pi.hProcess;
- service->pid = pi.dwProcessId;
- if (get_process_creation_time(service->process_handle, &service->creation_time)) ZeroMemory(&service->creation_time, sizeof(service->creation_time));
- close_output_handles(&si);
- 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
- but be mindful of the fact that we are blocking the service control manager
- so abandon the wait before too much time has elapsed.
- */
- unsigned long delay = service->throttle_delay;
- if (delay > NSSM_SERVICE_STATUS_DEADLINE) {
- TCHAR delay_milliseconds[16];
- _sntprintf_s(delay_milliseconds, _countof(delay_milliseconds), _TRUNCATE, _T("%lu"), delay);
- TCHAR deadline_milliseconds[16];
- _sntprintf_s(deadline_milliseconds, _countof(deadline_milliseconds), _TRUNCATE, _T("%lu"), NSSM_SERVICE_STATUS_DEADLINE);
- log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_STARTUP_DELAY_TOO_LONG, service->name, delay_milliseconds, NSSM, deadline_milliseconds, 0);
- delay = NSSM_SERVICE_STATUS_DEADLINE;
- }
- unsigned long deadline = WaitForSingleObject(service->process_handle, delay);
- /* Signal successful start */
- service->status.dwCurrentState = SERVICE_RUNNING;
- SetServiceStatus(service->status_handle, &service->status);
- /* Continue waiting for a clean startup. */
- if (deadline == WAIT_TIMEOUT) {
- if (service->throttle_delay > delay) {
- if (WaitForSingleObject(service->process_handle, service->throttle_delay - delay) == WAIT_TIMEOUT) service->throttle = 0;
- }
- else service->throttle = 0;
- }
- return 0;
- }
- /* Stop the service */
- int stop_service(nssm_service_t *service, unsigned long exitcode, bool graceful, bool default_action) {
- service->allow_restart = false;
- if (service->wait_handle) {
- UnregisterWait(service->wait_handle);
- service->wait_handle = 0;
- }
- if (default_action && ! exitcode && ! graceful) {
- log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_GRACEFUL_SUICIDE, service->name, service->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);
- graceful = true;
- }
- /* Signal we are stopping */
- if (graceful) {
- service->status.dwCurrentState = SERVICE_STOP_PENDING;
- service->status.dwWaitHint = NSSM_WAITHINT_MARGIN;
- SetServiceStatus(service->status_handle, &service->status);
- }
- /* Nothing to do if service isn't running */
- if (service->pid) {
- /* Shut down service */
- log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_TERMINATEPROCESS, service->name, service->exe, 0);
- kill_process(service, service->process_handle, service->pid, 0);
- }
- else log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_PROCESS_ALREADY_STOPPED, service->name, service->exe, 0);
- end_service((void *) service, true);
- /* Signal we stopped */
- if (graceful) {
- service->status.dwCurrentState = SERVICE_STOPPED;
- if (exitcode) {
- service->status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
- service->status.dwServiceSpecificExitCode = exitcode;
- }
- else {
- service->status.dwWin32ExitCode = NO_ERROR;
- service->status.dwServiceSpecificExitCode = 0;
- }
- SetServiceStatus(service->status_handle, &service->status);
- }
- return exitcode;
- }
- /* Callback function triggered when the server exits */
- void CALLBACK end_service(void *arg, unsigned char why) {
- nssm_service_t *service = (nssm_service_t *) arg;
- if (service->stopping) return;
- service->stopping = true;
- /* Check exit code */
- unsigned long exitcode = 0;
- TCHAR code[16];
- if (service->process_handle) {
- GetExitCodeProcess(service->process_handle, &exitcode);
- if (exitcode == STILL_ACTIVE || get_process_exit_time(service->process_handle, &service->exit_time)) GetSystemTimeAsFileTime(&service->exit_time);
- CloseHandle(service->process_handle);
- }
- else GetSystemTimeAsFileTime(&service->exit_time);
- service->process_handle = 0;
- /*
- Log that the service ended BEFORE logging about killing the process
- tree. See below for the possible values of the why argument.
- */
- if (! why) {
- _sntprintf_s(code, _countof(code), _TRUNCATE, _T("%lu"), exitcode);
- log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_ENDED_SERVICE, service->exe, service->name, code, 0);
- }
- /* Clean up. */
- if (exitcode == STILL_ACTIVE) exitcode = 0;
- if (service->pid) kill_process_tree(service, service->pid, exitcode, service->pid);
- service->pid = 0;
- /*
- The why argument is true if our wait timed out or false otherwise.
- Our wait is infinite so why will never be true when called by the system.
- If it is indeed true, assume we were called from stop_service() because
- this is a controlled shutdown, and don't take any restart action.
- */
- if (why) return;
- if (! service->allow_restart) return;
- /* What action should we take? */
- int action = NSSM_EXIT_RESTART;
- TCHAR action_string[ACTION_LEN];
- bool default_action;
- if (! get_exit_action(service->name, &exitcode, action_string, &default_action)) {
- for (int i = 0; exit_action_strings[i]; i++) {
- if (! _tcsnicmp((const TCHAR *) action_string, exit_action_strings[i], ACTION_LEN)) {
- action = i;
- break;
- }
- }
- }
- switch (action) {
- /* Try to restart the service or return failure code to service manager */
- case NSSM_EXIT_RESTART:
- log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_RESTART, service->name, code, exit_action_strings[action], service->exe, 0);
- while (monitor_service(service)) {
- log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_RESTART_SERVICE_FAILED, service->exe, service->name, 0);
- Sleep(30000);
- }
- break;
- /* Do nothing, just like srvany would */
- case NSSM_EXIT_IGNORE:
- log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_IGNORE, service->name, code, exit_action_strings[action], service->exe, 0);
- Sleep(INFINITE);
- break;
- /* Tell the service manager we are finished */
- case NSSM_EXIT_REALLY:
- log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_REALLY, service->name, code, exit_action_strings[action], 0);
- stop_service(service, exitcode, true, default_action);
- break;
- /* Fake a crash so pre-Vista service managers will run recovery actions. */
- case NSSM_EXIT_UNCLEAN:
- log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_UNCLEAN, service->name, code, exit_action_strings[action], 0);
- stop_service(service, exitcode, false, default_action);
- free_imports();
- exit(exitcode);
- break;
- }
- }
- 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);
- 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 (use_critical_section) EnterCriticalSection(&service->throttle_section);
- else if (service->throttle_timer) {
- ZeroMemory(&service->throttle_duetime, sizeof(service->throttle_duetime));
- service->throttle_duetime.QuadPart = 0 - (ms * 10000LL);
- SetWaitableTimer(service->throttle_timer, &service->throttle_duetime, 0, 0, 0, 0);
- }
- service->status.dwCurrentState = SERVICE_PAUSED;
- SetServiceStatus(service->status_handle, &service->status);
- if (use_critical_section) {
- imports.SleepConditionVariableCS(&service->throttle_condition, &service->throttle_section, ms);
- LeaveCriticalSection(&service->throttle_section);
- }
- else {
- if (service->throttle_timer) WaitForSingleObject(service->throttle_timer, INFINITE);
- else Sleep(ms);
- }
- }
- /*
- When responding to a stop (or any other) request we need to set dwWaitHint to
- the number of milliseconds we expect the operation to take, and optionally
- increase dwCheckPoint. If dwWaitHint milliseconds elapses without the
- operation completing or dwCheckPoint increasing, the system will consider the
- service to be hung.
- However the system will consider the service to be hung after 30000
- milliseconds regardless of the value of dwWaitHint if dwCheckPoint has not
- changed. Therefore if we want to wait longer than that we must periodically
- increase dwCheckPoint.
- Furthermore, it will consider the service to be hung after 60000 milliseconds
- regardless of the value of dwCheckPoint unless dwWaitHint is increased every
- time dwCheckPoint is also increased.
- Our strategy then is to retrieve the initial dwWaitHint and wait for
- NSSM_SERVICE_STATUS_DEADLINE milliseconds. If the process is still running
- and we haven't finished waiting we increment dwCheckPoint and add whichever is
- smaller of NSSM_SERVICE_STATUS_DEADLINE or the remaining timeout to
- dwWaitHint.
- Only doing both these things will prevent the system from killing the service.
- Returns: 1 if the wait timed out.
- 0 if the wait completed.
- -1 on error.
- */
- int await_shutdown(nssm_service_t *service, TCHAR *function_name, unsigned long timeout) {
- unsigned long interval;
- unsigned long waithint;
- unsigned long ret;
- unsigned long waited;
- TCHAR interval_milliseconds[16];
- TCHAR timeout_milliseconds[16];
- TCHAR waited_milliseconds[16];
- TCHAR *function = function_name;
- /* Add brackets to function name. */
- size_t funclen = _tcslen(function_name) + 3;
- TCHAR *func = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, funclen * sizeof(TCHAR));
- if (func) {
- if (_sntprintf_s(func, funclen, _TRUNCATE, _T("%s()"), function_name) > -1) function = func;
- }
- _sntprintf_s(timeout_milliseconds, _countof(timeout_milliseconds), _TRUNCATE, _T("%lu"), timeout);
- waithint = service->status.dwWaitHint;
- waited = 0;
- while (waited < timeout) {
- interval = timeout - waited;
- if (interval > NSSM_SERVICE_STATUS_DEADLINE) interval = NSSM_SERVICE_STATUS_DEADLINE;
- service->status.dwCurrentState = SERVICE_STOP_PENDING;
- service->status.dwWaitHint += interval;
- service->status.dwCheckPoint++;
- SetServiceStatus(service->status_handle, &service->status);
- if (waited) {
- _sntprintf_s(waited_milliseconds, _countof(waited_milliseconds), _TRUNCATE, _T("%lu"), waited);
- _sntprintf_s(interval_milliseconds, _countof(interval_milliseconds), _TRUNCATE, _T("%lu"), interval);
- log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_AWAITING_SHUTDOWN, function, service->name, waited_milliseconds, interval_milliseconds, timeout_milliseconds, 0);
- }
- switch (WaitForSingleObject(service->process_handle, interval)) {
- case WAIT_OBJECT_0:
- ret = 0;
- goto awaited;
- case WAIT_TIMEOUT:
- ret = 1;
- break;
- default:
- ret = -1;
- goto awaited;
- }
- waited += interval;
- }
- awaited:
- if (func) HeapFree(GetProcessHeap(), 0, func);
- return ret;
- }
|