service.cpp 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749
  1. #include "nssm.h"
  2. /* This is explicitly a wide string. */
  3. #define NSSM_LOGON_AS_SERVICE_RIGHT L"SeServiceLogonRight"
  4. bool is_admin;
  5. bool use_critical_section;
  6. extern imports_t imports;
  7. extern settings_t settings[];
  8. const TCHAR *exit_action_strings[] = { _T("Restart"), _T("Ignore"), _T("Exit"), _T("Suicide"), 0 };
  9. const TCHAR *startup_strings[] = { _T("SERVICE_AUTO_START"), _T("SERVICE_DELAYED_AUTO_START"), _T("SERVICE_DEMAND_START"), _T("SERVICE_DISABLED"), 0 };
  10. 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 };
  11. typedef struct {
  12. int first;
  13. int last;
  14. } list_t;
  15. int affinity_mask_to_string(__int64 mask, TCHAR **string) {
  16. if (! string) return 1;
  17. if (! mask) {
  18. *string = 0;
  19. return 0;
  20. }
  21. __int64 i, n;
  22. /* SetProcessAffinityMask() accepts a mask of up to 64 processors. */
  23. list_t set[64];
  24. for (n = 0; n < _countof(set); n++) set[n].first = set[n].last = -1;
  25. for (i = 0, n = 0; i < _countof(set); i++) {
  26. if (mask & (1LL << i)) {
  27. if (set[n].first == -1) set[n].first = set[n].last = (int) i;
  28. else if (set[n].last == (int) i - 1) set[n].last = (int) i;
  29. else {
  30. n++;
  31. set[n].first = set[n].last = (int) i;
  32. }
  33. }
  34. }
  35. /* Worst case is 2x2 characters for first and last CPU plus - and/or , */
  36. size_t len = (size_t) (n + 1) * 6;
  37. *string = (TCHAR *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len * sizeof(TCHAR));
  38. if (! string) return 2;
  39. size_t s = 0;
  40. int ret;
  41. for (i = 0; i <= n; i++) {
  42. if (i) (*string)[s++] = _T(',');
  43. ret = _sntprintf_s(*string + s, 3, _TRUNCATE, _T("%u"), set[i].first);
  44. if (ret < 0) {
  45. HeapFree(GetProcessHeap(), 0, *string);
  46. *string = 0;
  47. return 3;
  48. }
  49. else s += ret;
  50. if (set[i].last != set[i].first) {
  51. ret =_sntprintf_s(*string + s, 4, _TRUNCATE, _T("%c%u"), (set[i].last == set[i].first + 1) ? _T(',') : _T('-'), set[i].last);
  52. if (ret < 0) {
  53. HeapFree(GetProcessHeap(), 0, *string);
  54. *string = 0;
  55. return 4;
  56. }
  57. else s += ret;
  58. }
  59. }
  60. return 0;
  61. }
  62. int affinity_string_to_mask(TCHAR *string, __int64 *mask) {
  63. if (! mask) return 1;
  64. *mask = 0LL;
  65. if (! string) return 0;
  66. list_t set[64];
  67. TCHAR *s = string;
  68. TCHAR *end;
  69. int ret;
  70. int i;
  71. int n = 0;
  72. unsigned long number;
  73. for (n = 0; n < _countof(set); n++) set[n].first = set[n].last = -1;
  74. n = 0;
  75. while (*s) {
  76. ret = str_number(s, &number, &end);
  77. s = end;
  78. if (ret == 0 || ret == 2) {
  79. if (number >= _countof(set)) return 2;
  80. set[n].first = set[n].last = (int) number;
  81. switch (*s) {
  82. case 0:
  83. break;
  84. case _T(','):
  85. n++;
  86. s++;
  87. break;
  88. case _T('-'):
  89. if (! *(++s)) return 3;
  90. ret = str_number(s, &number, &end);
  91. if (ret == 0 || ret == 2) {
  92. s = end;
  93. if (! *s || *s == _T(',')) {
  94. set[n].last = (int) number;
  95. if (! *s) break;
  96. n++;
  97. s++;
  98. }
  99. else return 3;
  100. }
  101. else return 3;
  102. break;
  103. default:
  104. return 3;
  105. }
  106. }
  107. else return 4;
  108. }
  109. for (i = 0; i <= n; i++) {
  110. for (int j = set[i].first; j <= set[i].last; j++) (__int64) *mask |= (1LL << (__int64) j);
  111. }
  112. return 0;
  113. }
  114. inline unsigned long priority_mask() {
  115. return REALTIME_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | ABOVE_NORMAL_PRIORITY_CLASS | NORMAL_PRIORITY_CLASS | BELOW_NORMAL_PRIORITY_CLASS | IDLE_PRIORITY_CLASS;
  116. }
  117. int priority_constant_to_index(unsigned long constant) {
  118. switch (constant & priority_mask()) {
  119. case REALTIME_PRIORITY_CLASS: return NSSM_REALTIME_PRIORITY;
  120. case HIGH_PRIORITY_CLASS: return NSSM_HIGH_PRIORITY;
  121. case ABOVE_NORMAL_PRIORITY_CLASS: return NSSM_ABOVE_NORMAL_PRIORITY;
  122. case BELOW_NORMAL_PRIORITY_CLASS: return NSSM_BELOW_NORMAL_PRIORITY;
  123. case IDLE_PRIORITY_CLASS: return NSSM_IDLE_PRIORITY;
  124. }
  125. return NSSM_NORMAL_PRIORITY;
  126. }
  127. unsigned long priority_index_to_constant(int index) {
  128. switch (index) {
  129. case NSSM_REALTIME_PRIORITY: return REALTIME_PRIORITY_CLASS;
  130. case NSSM_HIGH_PRIORITY: return HIGH_PRIORITY_CLASS;
  131. case NSSM_ABOVE_NORMAL_PRIORITY: return ABOVE_NORMAL_PRIORITY_CLASS;
  132. case NSSM_BELOW_NORMAL_PRIORITY: return BELOW_NORMAL_PRIORITY_CLASS;
  133. case NSSM_IDLE_PRIORITY: return IDLE_PRIORITY_CLASS;
  134. }
  135. return NORMAL_PRIORITY_CLASS;
  136. }
  137. static inline int throttle_milliseconds(unsigned long throttle) {
  138. /* pow() operates on doubles. */
  139. int ret = 1; for (unsigned long i = 1; i < throttle; i++) ret *= 2;
  140. return ret * 1000;
  141. }
  142. /*
  143. Wrapper to be called in a new thread so that we can acknowledge a STOP
  144. control immediately.
  145. */
  146. static unsigned long WINAPI shutdown_service(void *arg) {
  147. return stop_service((nssm_service_t *) arg, 0, true, true);
  148. }
  149. /* Connect to the service manager */
  150. SC_HANDLE open_service_manager() {
  151. SC_HANDLE ret = OpenSCManager(0, SERVICES_ACTIVE_DATABASE, SC_MANAGER_ALL_ACCESS);
  152. if (! ret) {
  153. if (is_admin) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OPENSCMANAGER_FAILED, 0);
  154. return 0;
  155. }
  156. return ret;
  157. }
  158. /* Open a service by name or display name. */
  159. SC_HANDLE open_service(SC_HANDLE services, TCHAR *service_name, TCHAR *canonical_name, unsigned long canonical_namelen) {
  160. SC_HANDLE service_handle = OpenService(services, service_name, SERVICE_ALL_ACCESS);
  161. if (service_handle) {
  162. if (canonical_name && canonical_name != service_name) {
  163. if (_sntprintf_s(canonical_name, canonical_namelen, _TRUNCATE, _T("%s"), service_name) < 0) {
  164. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("canonical_name"), _T("open_service()"));
  165. return 0;
  166. }
  167. }
  168. return service_handle;
  169. }
  170. unsigned long error = GetLastError();
  171. if (error != ERROR_SERVICE_DOES_NOT_EXIST) {
  172. print_message(stderr, NSSM_MESSAGE_OPENSERVICE_FAILED, error_string(GetLastError()));
  173. return 0;
  174. }
  175. /* We can't look for a display name because there's no buffer to store it. */
  176. if (! canonical_name) {
  177. print_message(stderr, NSSM_MESSAGE_OPENSERVICE_FAILED, error_string(GetLastError()));
  178. return 0;
  179. }
  180. unsigned long bufsize, required, count, i;
  181. unsigned long resume = 0;
  182. EnumServicesStatus(services, SERVICE_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_KERNEL_DRIVER | SERVICE_WIN32, SERVICE_STATE_ALL, 0, 0, &required, &count, &resume);
  183. error = GetLastError();
  184. if (error != ERROR_MORE_DATA) {
  185. print_message(stderr, NSSM_MESSAGE_ENUMSERVICESSTATUS_FAILED, error_string(GetLastError()));
  186. return 0;
  187. }
  188. ENUM_SERVICE_STATUS *status = (ENUM_SERVICE_STATUS *) HeapAlloc(GetProcessHeap(), 0, required);
  189. if (! status) {
  190. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("ENUM_SERVICE_STATUS"), _T("open_service()"));
  191. return 0;
  192. }
  193. bufsize = required;
  194. while (true) {
  195. /*
  196. EnumServicesStatus() returns:
  197. 1 when it retrieved data and there's no more data to come.
  198. 0 and sets last error to ERROR_MORE_DATA when it retrieved data and
  199. there's more data to come.
  200. 0 and sets last error to something else on error.
  201. */
  202. int ret = EnumServicesStatus(services, SERVICE_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_KERNEL_DRIVER | SERVICE_WIN32, SERVICE_STATE_ALL, status, bufsize, &required, &count, &resume);
  203. if (! ret) {
  204. error = GetLastError();
  205. if (error != ERROR_MORE_DATA) {
  206. HeapFree(GetProcessHeap(), 0, status);
  207. print_message(stderr, NSSM_MESSAGE_ENUMSERVICESSTATUS_FAILED, error_string(GetLastError()));
  208. return 0;
  209. }
  210. }
  211. for (i = 0; i < count; i++) {
  212. if (str_equiv(status[i].lpDisplayName, service_name)) {
  213. if (_sntprintf_s(canonical_name, canonical_namelen, _TRUNCATE, _T("%s"), status[i].lpServiceName) < 0) {
  214. HeapFree(GetProcessHeap(), 0, status);
  215. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("canonical_name"), _T("open_service()"));
  216. return 0;
  217. }
  218. HeapFree(GetProcessHeap(), 0, status);
  219. return open_service(services, canonical_name, 0, 0);
  220. }
  221. }
  222. if (ret) break;
  223. }
  224. /* Recurse so we can get an error message. */
  225. return open_service(services, service_name, 0, 0);
  226. }
  227. QUERY_SERVICE_CONFIG *query_service_config(const TCHAR *service_name, SC_HANDLE service_handle) {
  228. QUERY_SERVICE_CONFIG *qsc;
  229. unsigned long bufsize;
  230. unsigned long error;
  231. QueryServiceConfig(service_handle, 0, 0, &bufsize);
  232. error = GetLastError();
  233. if (error == ERROR_INSUFFICIENT_BUFFER) {
  234. qsc = (QUERY_SERVICE_CONFIG *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bufsize);
  235. if (! qsc) {
  236. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("QUERY_SERVICE_CONFIG"), _T("query_service_config()"), 0);
  237. return 0;
  238. }
  239. }
  240. else {
  241. print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG_FAILED, service_name, error_string(error), 0);
  242. return 0;
  243. }
  244. if (! QueryServiceConfig(service_handle, qsc, bufsize, &bufsize)) {
  245. HeapFree(GetProcessHeap(), 0, qsc);
  246. print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG_FAILED, service_name, error_string(GetLastError()), 0);
  247. return 0;
  248. }
  249. return qsc;
  250. }
  251. int set_service_description(const TCHAR *service_name, SC_HANDLE service_handle, TCHAR *buffer) {
  252. SERVICE_DESCRIPTION description;
  253. ZeroMemory(&description, sizeof(description));
  254. /*
  255. lpDescription must be NULL if we aren't changing, the new description
  256. or "".
  257. */
  258. if (buffer && buffer[0]) description.lpDescription = buffer;
  259. else description.lpDescription = _T("");
  260. if (ChangeServiceConfig2(service_handle, SERVICE_CONFIG_DESCRIPTION, &description)) return 0;
  261. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SERVICE_CONFIG_DESCRIPTION_FAILED, service_name, error_string(GetLastError()), 0);
  262. return 1;
  263. }
  264. int get_service_description(const TCHAR *service_name, SC_HANDLE service_handle, unsigned long len, TCHAR *buffer) {
  265. if (! buffer) return 1;
  266. unsigned long bufsize;
  267. QueryServiceConfig2(service_handle, SERVICE_CONFIG_DESCRIPTION, 0, 0, &bufsize);
  268. unsigned long error = GetLastError();
  269. if (error == ERROR_INSUFFICIENT_BUFFER) {
  270. SERVICE_DESCRIPTION *description = (SERVICE_DESCRIPTION *) HeapAlloc(GetProcessHeap(), 0, bufsize);
  271. if (! description) {
  272. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("SERVICE_CONFIG_DESCRIPTION"), _T("get_service_description()"));
  273. return 2;
  274. }
  275. if (QueryServiceConfig2(service_handle, SERVICE_CONFIG_DESCRIPTION, (unsigned char *) description, bufsize, &bufsize)) {
  276. if (description->lpDescription) _sntprintf_s(buffer, len, _TRUNCATE, _T("%s"), description->lpDescription);
  277. else ZeroMemory(buffer, len * sizeof(TCHAR));
  278. HeapFree(GetProcessHeap(), 0, description);
  279. return 0;
  280. }
  281. else {
  282. HeapFree(GetProcessHeap(), 0, description);
  283. print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG2_FAILED, service_name, _T("SERVICE_CONFIG_DESCRIPTION"), error_string(error));
  284. return 3;
  285. }
  286. }
  287. else {
  288. print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG2_FAILED, service_name, _T("SERVICE_CONFIG_DESCRIPTION"), error_string(error));
  289. return 4;
  290. }
  291. return 0;
  292. }
  293. int get_service_startup(const TCHAR *service_name, SC_HANDLE service_handle, const QUERY_SERVICE_CONFIG *qsc, unsigned long *startup) {
  294. if (! qsc) return 1;
  295. switch (qsc->dwStartType) {
  296. case SERVICE_DEMAND_START: *startup = NSSM_STARTUP_MANUAL; break;
  297. case SERVICE_DISABLED: *startup = NSSM_STARTUP_DISABLED; break;
  298. default: *startup = NSSM_STARTUP_AUTOMATIC;
  299. }
  300. if (*startup != NSSM_STARTUP_AUTOMATIC) return 0;
  301. /* Check for delayed start. */
  302. unsigned long bufsize;
  303. unsigned long error;
  304. QueryServiceConfig2(service_handle, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, 0, 0, &bufsize);
  305. error = GetLastError();
  306. if (error == ERROR_INSUFFICIENT_BUFFER) {
  307. SERVICE_DELAYED_AUTO_START_INFO *info = (SERVICE_DELAYED_AUTO_START_INFO *) HeapAlloc(GetProcessHeap(), 0, bufsize);
  308. if (! info) {
  309. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("SERVICE_DELAYED_AUTO_START_INFO"), _T("get_service_startup()"));
  310. return 2;
  311. }
  312. if (QueryServiceConfig2(service_handle, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, (unsigned char *) info, bufsize, &bufsize)) {
  313. if (info->fDelayedAutostart) *startup = NSSM_STARTUP_DELAYED;
  314. HeapFree(GetProcessHeap(), 0, info);
  315. return 0;
  316. }
  317. else {
  318. error = GetLastError();
  319. if (error != ERROR_INVALID_LEVEL) {
  320. print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG2_FAILED, service_name, _T("SERVICE_CONFIG_DELAYED_AUTO_START_INFO"), error_string(error));
  321. return 3;
  322. }
  323. }
  324. }
  325. else if (error != ERROR_INVALID_LEVEL) {
  326. print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG2_FAILED, service_name, _T("SERVICE_DELAYED_AUTO_START_INFO"), error_string(error));
  327. return 3;
  328. }
  329. return 0;
  330. }
  331. int get_service_username(const TCHAR *service_name, const QUERY_SERVICE_CONFIG *qsc, TCHAR **username, size_t *usernamelen) {
  332. if (! username) return 1;
  333. if (! usernamelen) return 1;
  334. *username = 0;
  335. *usernamelen = 0;
  336. if (! qsc) return 1;
  337. if (str_equiv(qsc->lpServiceStartName, NSSM_LOCALSYSTEM_ACCOUNT)) return 0;
  338. size_t len = _tcslen(qsc->lpServiceStartName);
  339. *username = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(TCHAR));
  340. if (! *username) {
  341. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("username"), _T("get_service_username()"));
  342. return 2;
  343. }
  344. memmove(*username, qsc->lpServiceStartName, (len + 1) * sizeof(TCHAR));
  345. *usernamelen = len;
  346. return 0;
  347. }
  348. int grant_logon_as_service(const TCHAR *username) {
  349. if (! username) return 0;
  350. if (str_equiv(username, NSSM_LOCALSYSTEM_ACCOUNT)) return 0;
  351. /* Open Policy object. */
  352. LSA_OBJECT_ATTRIBUTES attributes;
  353. ZeroMemory(&attributes, sizeof(attributes));
  354. LSA_HANDLE policy;
  355. NTSTATUS status = LsaOpenPolicy(0, &attributes, POLICY_ALL_ACCESS, &policy);
  356. if (status) {
  357. print_message(stderr, NSSM_MESSAGE_LSAOPENPOLICY_FAILED, error_string(LsaNtStatusToWinError(status)));
  358. return 1;
  359. }
  360. /* Look up SID for the account. */
  361. LSA_UNICODE_STRING lsa_username;
  362. #ifdef UNICODE
  363. lsa_username.Buffer = (wchar_t *) username;
  364. lsa_username.Length = (unsigned short) _tcslen(username) * sizeof(TCHAR);
  365. lsa_username.MaximumLength = lsa_username.Length + sizeof(TCHAR);
  366. #else
  367. size_t buflen;
  368. mbstowcs_s(&buflen, NULL, 0, username, _TRUNCATE);
  369. lsa_username.MaximumLength = (unsigned short) buflen * sizeof(wchar_t);
  370. lsa_username.Length = lsa_username.MaximumLength - sizeof(wchar_t);
  371. lsa_username.Buffer = (wchar_t *) HeapAlloc(GetProcessHeap(), 0, lsa_username.MaximumLength);
  372. if (lsa_username.Buffer) mbstowcs_s(&buflen, lsa_username.Buffer, lsa_username.MaximumLength, username, _TRUNCATE);
  373. else {
  374. LsaClose(policy);
  375. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("LSA_UNICODE_STRING"), _T("grant_logon_as_service()"));
  376. return 2;
  377. }
  378. #endif
  379. LSA_REFERENCED_DOMAIN_LIST *translated_domains;
  380. LSA_TRANSLATED_SID *translated_sid;
  381. status = LsaLookupNames(policy, 1, &lsa_username, &translated_domains, &translated_sid);
  382. #ifndef UNICODE
  383. HeapFree(GetProcessHeap(), 0, lsa_username.Buffer);
  384. #endif
  385. if (status) {
  386. LsaFreeMemory(translated_domains);
  387. LsaFreeMemory(translated_sid);
  388. LsaClose(policy);
  389. print_message(stderr, NSSM_MESSAGE_LSALOOKUPNAMES_FAILED, username, error_string(LsaNtStatusToWinError(status)));
  390. return 3;
  391. }
  392. if (translated_sid->Use != SidTypeUser) {
  393. LsaFreeMemory(translated_domains);
  394. LsaFreeMemory(translated_sid);
  395. LsaClose(policy);
  396. print_message(stderr, NSSM_GUI_INVALID_USERNAME, username);
  397. return 4;
  398. }
  399. LSA_TRUST_INFORMATION *trust = &translated_domains->Domains[translated_sid->DomainIndex];
  400. if (! trust || ! IsValidSid(trust->Sid)) {
  401. LsaFreeMemory(translated_domains);
  402. LsaFreeMemory(translated_sid);
  403. LsaClose(policy);
  404. print_message(stderr, NSSM_GUI_INVALID_USERNAME, username);
  405. return 4;
  406. }
  407. /* GetSidSubAuthority*() return pointers! */
  408. unsigned char *n = GetSidSubAuthorityCount(trust->Sid);
  409. /* Convert translated SID to SID. */
  410. SID *sid = (SID *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, GetSidLengthRequired(*n + 1));
  411. if (! sid) {
  412. LsaFreeMemory(translated_domains);
  413. LsaFreeMemory(translated_sid);
  414. LsaClose(policy);
  415. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("SID"), _T("grant_logon_as_service"));
  416. return 4;
  417. }
  418. unsigned long error;
  419. if (! InitializeSid(sid, GetSidIdentifierAuthority(trust->Sid), *n + 1)) {
  420. error = GetLastError();
  421. HeapFree(GetProcessHeap(), 0, sid);
  422. LsaFreeMemory(translated_domains);
  423. LsaFreeMemory(translated_sid);
  424. LsaClose(policy);
  425. print_message(stderr, NSSM_MESSAGE_INITIALIZESID_FAILED, username, error_string(error));
  426. return 5;
  427. }
  428. for (unsigned char i = 0; i <= *n; i++) {
  429. unsigned long *sub = GetSidSubAuthority(sid, i);
  430. if (i < *n) *sub = *GetSidSubAuthority(trust->Sid, i);
  431. else *sub = translated_sid->RelativeId;
  432. }
  433. LsaFreeMemory(translated_domains);
  434. LsaFreeMemory(translated_sid);
  435. /* Check if the SID has the "Log on as a service" right. */
  436. LSA_UNICODE_STRING lsa_right;
  437. lsa_right.Buffer = NSSM_LOGON_AS_SERVICE_RIGHT;
  438. lsa_right.Length = (unsigned short) wcslen(lsa_right.Buffer) * sizeof(wchar_t);
  439. lsa_right.MaximumLength = lsa_right.Length + sizeof(wchar_t);
  440. LSA_UNICODE_STRING *rights;
  441. unsigned long count = ~0;
  442. status = LsaEnumerateAccountRights(policy, sid, &rights, &count);
  443. if (status) {
  444. /*
  445. If the account has no rights set LsaEnumerateAccountRights() will return
  446. STATUS_OBJECT_NAME_NOT_FOUND and set count to 0.
  447. */
  448. error = LsaNtStatusToWinError(status);
  449. if (error != ERROR_FILE_NOT_FOUND) {
  450. HeapFree(GetProcessHeap(), 0, sid);
  451. LsaClose(policy);
  452. print_message(stderr, NSSM_MESSAGE_LSAENUMERATEACCOUNTRIGHTS_FAILED, username, error_string(error));
  453. return 4;
  454. }
  455. }
  456. for (unsigned long i = 0; i < count; i++) {
  457. if (rights[i].Length != lsa_right.Length) continue;
  458. if (_wcsnicmp(rights[i].Buffer, lsa_right.Buffer, lsa_right.MaximumLength)) continue;
  459. /* The SID has the right. */
  460. HeapFree(GetProcessHeap(), 0, sid);
  461. LsaFreeMemory(rights);
  462. LsaClose(policy);
  463. return 0;
  464. }
  465. LsaFreeMemory(rights);
  466. /* Add the right. */
  467. status = LsaAddAccountRights(policy, sid, &lsa_right, 1);
  468. HeapFree(GetProcessHeap(), 0, sid);
  469. LsaClose(policy);
  470. if (status) {
  471. print_message(stderr, NSSM_MESSAGE_LSAADDACCOUNTRIGHTS_FAILED, error_string(LsaNtStatusToWinError(status)));
  472. return 5;
  473. }
  474. print_message(stdout, NSSM_MESSAGE_GRANTED_LOGON_AS_SERVICE, username);
  475. return 0;
  476. }
  477. /* Set default values which aren't zero. */
  478. void set_nssm_service_defaults(nssm_service_t *service) {
  479. if (! service) return;
  480. service->type = SERVICE_WIN32_OWN_PROCESS;
  481. service->priority = NORMAL_PRIORITY_CLASS;
  482. service->stdin_sharing = NSSM_STDIN_SHARING;
  483. service->stdin_disposition = NSSM_STDIN_DISPOSITION;
  484. service->stdin_flags = NSSM_STDIN_FLAGS;
  485. service->stdout_sharing = NSSM_STDOUT_SHARING;
  486. service->stdout_disposition = NSSM_STDOUT_DISPOSITION;
  487. service->stdout_flags = NSSM_STDOUT_FLAGS;
  488. service->stderr_sharing = NSSM_STDERR_SHARING;
  489. service->stderr_disposition = NSSM_STDERR_DISPOSITION;
  490. service->stderr_flags = NSSM_STDERR_FLAGS;
  491. service->throttle_delay = NSSM_RESET_THROTTLE_RESTART;
  492. service->stop_method = ~0;
  493. service->kill_console_delay = NSSM_KILL_CONSOLE_GRACE_PERIOD;
  494. service->kill_window_delay = NSSM_KILL_WINDOW_GRACE_PERIOD;
  495. service->kill_threads_delay = NSSM_KILL_THREADS_GRACE_PERIOD;
  496. }
  497. /* Allocate and zero memory for a service. */
  498. nssm_service_t *alloc_nssm_service() {
  499. nssm_service_t *service = (nssm_service_t *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(nssm_service_t));
  500. if (! service) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("service"), _T("alloc_nssm_service()"), 0);
  501. return service;
  502. }
  503. /* Free memory for a service. */
  504. void cleanup_nssm_service(nssm_service_t *service) {
  505. if (! service) return;
  506. if (service->username) HeapFree(GetProcessHeap(), 0, service->username);
  507. if (service->password) {
  508. SecureZeroMemory(service->password, service->passwordlen);
  509. HeapFree(GetProcessHeap(), 0, service->password);
  510. }
  511. if (service->env) HeapFree(GetProcessHeap(), 0, service->env);
  512. if (service->env_extra) HeapFree(GetProcessHeap(), 0, service->env_extra);
  513. if (service->handle) CloseServiceHandle(service->handle);
  514. if (service->process_handle) CloseHandle(service->process_handle);
  515. if (service->wait_handle) UnregisterWait(service->process_handle);
  516. if (service->throttle_section_initialised) DeleteCriticalSection(&service->throttle_section);
  517. if (service->throttle_timer) CloseHandle(service->throttle_timer);
  518. HeapFree(GetProcessHeap(), 0, service);
  519. }
  520. /* About to install the service */
  521. int pre_install_service(int argc, TCHAR **argv) {
  522. nssm_service_t *service = alloc_nssm_service();
  523. set_nssm_service_defaults(service);
  524. if (argc) _sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), argv[0]);
  525. /* Show the dialogue box if we didn't give the service name and path */
  526. if (argc < 2) return nssm_gui(IDD_INSTALL, service);
  527. if (! service) {
  528. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("service"), _T("pre_install_service()"));
  529. return 1;
  530. }
  531. _sntprintf_s(service->exe, _countof(service->exe), _TRUNCATE, _T("%s"), argv[1]);
  532. /* Arguments are optional */
  533. size_t flagslen = 0;
  534. size_t s = 0;
  535. int i;
  536. for (i = 2; i < argc; i++) flagslen += _tcslen(argv[i]) + 1;
  537. if (! flagslen) flagslen = 1;
  538. if (flagslen > _countof(service->flags)) {
  539. print_message(stderr, NSSM_MESSAGE_FLAGS_TOO_LONG);
  540. return 2;
  541. }
  542. for (i = 2; i < argc; i++) {
  543. size_t len = _tcslen(argv[i]);
  544. memmove(service->flags + s, argv[i], len * sizeof(TCHAR));
  545. s += len;
  546. if (i < argc - 1) service->flags[s++] = _T(' ');
  547. }
  548. /* Work out directory name */
  549. _sntprintf_s(service->dir, _countof(service->dir), _TRUNCATE, _T("%s"), service->exe);
  550. strip_basename(service->dir);
  551. int ret = install_service(service);
  552. cleanup_nssm_service(service);
  553. return ret;
  554. }
  555. /* About to edit the service. */
  556. int pre_edit_service(int argc, TCHAR **argv) {
  557. /* Require service name. */
  558. if (argc < 2) return usage(1);
  559. /* Are we editing on the command line? */
  560. enum { MODE_EDITING, MODE_GETTING, MODE_SETTING, MODE_RESETTING } mode = MODE_EDITING;
  561. const TCHAR *verb = argv[0];
  562. const TCHAR *service_name = argv[1];
  563. bool getting = false;
  564. bool unsetting = false;
  565. /* Minimum number of arguments. */
  566. int mandatory = 2;
  567. /* Index of first value. */
  568. int remainder = 3;
  569. int i;
  570. if (str_equiv(verb, _T("get"))) {
  571. mandatory = 3;
  572. mode = MODE_GETTING;
  573. }
  574. else if (str_equiv(verb, _T("set"))) {
  575. mandatory = 4;
  576. mode = MODE_SETTING;
  577. }
  578. else if (str_equiv(verb, _T("reset")) || str_equiv(verb, _T("unset"))) {
  579. mandatory = 3;
  580. mode = MODE_RESETTING;
  581. }
  582. if (argc < mandatory) return usage(1);
  583. const TCHAR *parameter = 0;
  584. settings_t *setting = 0;
  585. TCHAR *additional;
  586. /* Validate the parameter. */
  587. if (mandatory > 2) {
  588. bool additional_mandatory = false;
  589. parameter = argv[2];
  590. for (i = 0; settings[i].name; i++) {
  591. setting = &settings[i];
  592. if (! str_equiv(setting->name, parameter)) continue;
  593. if (((setting->additional & ADDITIONAL_GETTING) && mode == MODE_GETTING) || ((setting->additional & ADDITIONAL_SETTING) && mode == MODE_SETTING) || ((setting->additional & ADDITIONAL_RESETTING) && mode == MODE_RESETTING)) {
  594. additional_mandatory = true;
  595. mandatory++;
  596. }
  597. break;
  598. }
  599. if (! settings[i].name) {
  600. print_message(stderr, NSSM_MESSAGE_INVALID_PARAMETER, parameter);
  601. for (i = 0; settings[i].name; i++) _ftprintf(stderr, _T("%s\n"), settings[i].name);
  602. return 1;
  603. }
  604. if (argc < mandatory) return usage(1);
  605. additional = 0;
  606. if (additional_mandatory) {
  607. additional = argv[3];
  608. remainder = 4;
  609. }
  610. else additional = argv[remainder];
  611. }
  612. nssm_service_t *service = alloc_nssm_service();
  613. _sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), service_name);
  614. /* Open service manager */
  615. SC_HANDLE services = open_service_manager();
  616. if (! services) {
  617. print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
  618. return 2;
  619. }
  620. /* Try to open the service */
  621. service->handle = open_service(services, service->name, service->name, _countof(service->name));
  622. if (! service->handle) {
  623. CloseServiceHandle(services);
  624. return 3;
  625. }
  626. /* Get system details. */
  627. QUERY_SERVICE_CONFIG *qsc = query_service_config(service->name, service->handle);
  628. if (! qsc) {
  629. CloseHandle(service->handle);
  630. CloseServiceHandle(services);
  631. return 4;
  632. }
  633. service->type = qsc->dwServiceType;
  634. if (! (service->type & SERVICE_WIN32_OWN_PROCESS)) {
  635. if (mode != MODE_GETTING) {
  636. HeapFree(GetProcessHeap(), 0, qsc);
  637. CloseHandle(service->handle);
  638. CloseServiceHandle(services);
  639. print_message(stderr, NSSM_MESSAGE_CANNOT_EDIT, service->name, NSSM_WIN32_OWN_PROCESS, 0);
  640. return 3;
  641. }
  642. }
  643. if (get_service_startup(service->name, service->handle, qsc, &service->startup)) {
  644. if (mode != MODE_GETTING) {
  645. HeapFree(GetProcessHeap(), 0, qsc);
  646. CloseHandle(service->handle);
  647. CloseServiceHandle(services);
  648. return 4;
  649. }
  650. }
  651. if (get_service_username(service->name, qsc, &service->username, &service->usernamelen)) {
  652. if (mode != MODE_GETTING) {
  653. HeapFree(GetProcessHeap(), 0, qsc);
  654. CloseHandle(service->handle);
  655. CloseServiceHandle(services);
  656. return 5;
  657. }
  658. }
  659. _sntprintf_s(service->displayname, _countof(service->displayname), _TRUNCATE, _T("%s"), qsc->lpDisplayName);
  660. /* Get the canonical service name. We open it case insensitively. */
  661. unsigned long bufsize = _countof(service->name);
  662. GetServiceKeyName(services, service->displayname, service->name, &bufsize);
  663. /* Remember the executable in case it isn't NSSM. */
  664. _sntprintf_s(service->image, _countof(service->image), _TRUNCATE, _T("%s"), qsc->lpBinaryPathName);
  665. HeapFree(GetProcessHeap(), 0, qsc);
  666. /* Get extended system details. */
  667. if (get_service_description(service->name, service->handle, _countof(service->description), service->description)) {
  668. if (mode != MODE_GETTING) {
  669. CloseHandle(service->handle);
  670. CloseServiceHandle(services);
  671. return 6;
  672. }
  673. }
  674. /* Get NSSM details. */
  675. get_parameters(service, 0);
  676. CloseServiceHandle(services);
  677. if (! service->exe[0]) {
  678. service->native = true;
  679. if (mode != MODE_GETTING) print_message(stderr, NSSM_MESSAGE_INVALID_SERVICE, service->name, NSSM, service->image);
  680. }
  681. /* Editing with the GUI. */
  682. if (mode == MODE_EDITING) {
  683. nssm_gui(IDD_EDIT, service);
  684. return 0;
  685. }
  686. /* Trying to manage App* parameters for a non-NSSM service. */
  687. if (! setting->native && service->native) {
  688. CloseHandle(service->handle);
  689. print_message(stderr, NSSM_MESSAGE_NATIVE_PARAMETER, setting->name, NSSM);
  690. return 1;
  691. }
  692. HKEY key;
  693. value_t value;
  694. int ret;
  695. if (mode == MODE_GETTING) {
  696. if (! service->native) {
  697. key = open_registry(service->name, KEY_READ);
  698. if (! key) return 4;
  699. }
  700. if (setting->native) ret = get_setting(service->name, service->handle, setting, &value, additional);
  701. else ret = get_setting(service->name, key, setting, &value, additional);
  702. if (ret < 0) {
  703. CloseHandle(service->handle);
  704. return 5;
  705. }
  706. switch (setting->type) {
  707. case REG_EXPAND_SZ:
  708. case REG_MULTI_SZ:
  709. case REG_SZ:
  710. _tprintf(_T("%s\n"), value.string ? value.string : _T(""));
  711. HeapFree(GetProcessHeap(), 0, value.string);
  712. break;
  713. case REG_DWORD:
  714. _tprintf(_T("%u\n"), value.numeric);
  715. break;
  716. }
  717. if (! service->native) RegCloseKey(key);
  718. CloseHandle(service->handle);
  719. return 0;
  720. }
  721. /* Build the value. */
  722. if (mode == MODE_RESETTING) {
  723. /* Unset the parameter. */
  724. value.string = 0;
  725. }
  726. else {
  727. /* Set the parameter. */
  728. size_t len = 0;
  729. size_t delimiterlen = (setting->additional & ADDITIONAL_CRLF) ? 2 : 1;
  730. for (i = remainder; i < argc; i++) len += _tcslen(argv[i]) + delimiterlen;
  731. len++;
  732. value.string = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, len * sizeof(TCHAR));
  733. if (! value.string) {
  734. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("value"), _T("edit_service()"));
  735. CloseHandle(service->handle);
  736. return 2;
  737. }
  738. size_t s = 0;
  739. for (i = remainder; i < argc; i++) {
  740. size_t len = _tcslen(argv[i]);
  741. memmove(value.string + s, argv[i], len * sizeof(TCHAR));
  742. s += len;
  743. if (i < argc - 1) {
  744. if (setting->additional & ADDITIONAL_CRLF) {
  745. value.string[s++] = _T('\r');
  746. value.string[s++] = _T('\n');
  747. }
  748. else value.string[s++] = _T(' ');
  749. }
  750. }
  751. value.string[s] = _T('\0');
  752. }
  753. if (! service->native) {
  754. key = open_registry(service->name, KEY_WRITE);
  755. if (! key) {
  756. if (value.string) HeapFree(GetProcessHeap(), 0, value.string);
  757. return 4;
  758. }
  759. }
  760. if (setting->native) ret = set_setting(service->name, service->handle, setting, &value, additional);
  761. else ret = set_setting(service->name, key, setting, &value, additional);
  762. if (value.string) HeapFree(GetProcessHeap(), 0, value.string);
  763. if (ret < 0) {
  764. if (! service->native) RegCloseKey(key);
  765. CloseHandle(service->handle);
  766. return 6;
  767. }
  768. if (! service->native) RegCloseKey(key);
  769. CloseHandle(service->handle);
  770. return 0;
  771. }
  772. /* About to remove the service */
  773. int pre_remove_service(int argc, TCHAR **argv) {
  774. nssm_service_t *service = alloc_nssm_service();
  775. set_nssm_service_defaults(service);
  776. if (argc) _sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), argv[0]);
  777. /* Show dialogue box if we didn't pass service name and "confirm" */
  778. if (argc < 2) return nssm_gui(IDD_REMOVE, service);
  779. if (str_equiv(argv[1], _T("confirm"))) {
  780. int ret = remove_service(service);
  781. cleanup_nssm_service(service);
  782. return ret;
  783. }
  784. print_message(stderr, NSSM_MESSAGE_PRE_REMOVE_SERVICE);
  785. return 100;
  786. }
  787. /* Install the service */
  788. int install_service(nssm_service_t *service) {
  789. if (! service) return 1;
  790. /* Open service manager */
  791. SC_HANDLE services = open_service_manager();
  792. if (! services) {
  793. print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
  794. cleanup_nssm_service(service);
  795. return 2;
  796. }
  797. /* Get path of this program */
  798. GetModuleFileName(0, service->image, _countof(service->image));
  799. /* Create the service - settings will be changed in edit_service() */
  800. 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);
  801. if (! service->handle) {
  802. print_message(stderr, NSSM_MESSAGE_CREATESERVICE_FAILED, error_string(GetLastError()));
  803. CloseServiceHandle(services);
  804. return 5;
  805. }
  806. if (edit_service(service, false)) {
  807. DeleteService(service->handle);
  808. CloseServiceHandle(services);
  809. return 6;
  810. }
  811. print_message(stdout, NSSM_MESSAGE_SERVICE_INSTALLED, service->name);
  812. /* Cleanup */
  813. CloseServiceHandle(services);
  814. return 0;
  815. }
  816. /* Edit the service. */
  817. int edit_service(nssm_service_t *service, bool editing) {
  818. if (! service) return 1;
  819. /*
  820. The only two valid flags for service type are SERVICE_WIN32_OWN_PROCESS
  821. and SERVICE_INTERACTIVE_PROCESS.
  822. */
  823. service->type &= SERVICE_INTERACTIVE_PROCESS;
  824. service->type |= SERVICE_WIN32_OWN_PROCESS;
  825. /* Startup type. */
  826. unsigned long startup;
  827. switch (service->startup) {
  828. case NSSM_STARTUP_MANUAL: startup = SERVICE_DEMAND_START; break;
  829. case NSSM_STARTUP_DISABLED: startup = SERVICE_DISABLED; break;
  830. default: startup = SERVICE_AUTO_START;
  831. }
  832. /* Display name. */
  833. if (! service->displayname[0]) _sntprintf_s(service->displayname, _countof(service->displayname), _TRUNCATE, _T("%s"), service->name);
  834. /*
  835. Username must be NULL if we aren't changing or an account name.
  836. We must explicitly use LOCALSYSTEM to change it when we are editing.
  837. Password must be NULL if we aren't changing, a password or "".
  838. Empty passwords are valid but we won't allow them in the GUI.
  839. */
  840. TCHAR *username = 0;
  841. TCHAR *password = 0;
  842. if (service->usernamelen) {
  843. username = service->username;
  844. if (service->passwordlen) password = service->password;
  845. else password = _T("");
  846. }
  847. else if (editing) username = NSSM_LOCALSYSTEM_ACCOUNT;
  848. if (grant_logon_as_service(username)) {
  849. print_message(stderr, NSSM_MESSAGE_GRANT_LOGON_AS_SERVICE_FAILED, username);
  850. return 5;
  851. }
  852. if (! ChangeServiceConfig(service->handle, service->type, startup, SERVICE_NO_CHANGE, 0, 0, 0, 0, username, password, service->displayname)) {
  853. print_message(stderr, NSSM_MESSAGE_CHANGESERVICECONFIG_FAILED, error_string(GetLastError()));
  854. return 5;
  855. }
  856. if (service->description[0] || editing) {
  857. set_service_description(service->name, service->handle, service->description);
  858. }
  859. SERVICE_DELAYED_AUTO_START_INFO delayed;
  860. ZeroMemory(&delayed, sizeof(delayed));
  861. if (service->startup == NSSM_STARTUP_DELAYED) delayed.fDelayedAutostart = 1;
  862. else delayed.fDelayedAutostart = 0;
  863. /* Delayed startup isn't supported until Vista. */
  864. if (! ChangeServiceConfig2(service->handle, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, &delayed)) {
  865. unsigned long error = GetLastError();
  866. /* Pre-Vista we expect to fail with ERROR_INVALID_LEVEL */
  867. if (error != ERROR_INVALID_LEVEL) {
  868. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SERVICE_CONFIG_DELAYED_AUTO_START_INFO_FAILED, service->name, error_string(error), 0);
  869. }
  870. }
  871. /* Don't mess with parameters which aren't ours. */
  872. if (! service->native) {
  873. /* Now we need to put the parameters into the registry */
  874. if (create_parameters(service, editing)) {
  875. print_message(stderr, NSSM_MESSAGE_CREATE_PARAMETERS_FAILED);
  876. return 6;
  877. }
  878. set_service_recovery(service);
  879. }
  880. return 0;
  881. }
  882. /* Control a service. */
  883. int control_service(unsigned long control, int argc, TCHAR **argv) {
  884. if (argc < 1) return usage(1);
  885. TCHAR *service_name = argv[0];
  886. TCHAR canonical_name[SERVICE_NAME_LENGTH];
  887. SC_HANDLE services = open_service_manager();
  888. if (! services) {
  889. print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
  890. return 2;
  891. }
  892. SC_HANDLE service_handle = open_service(services, service_name, canonical_name, _countof(canonical_name));
  893. if (! service_handle) {
  894. CloseServiceHandle(services);
  895. return 3;
  896. }
  897. int ret;
  898. unsigned long error;
  899. SERVICE_STATUS service_status;
  900. if (control == 0) {
  901. ret = StartService(service_handle, (unsigned long) argc, (const TCHAR **) argv);
  902. error = GetLastError();
  903. CloseHandle(service_handle);
  904. CloseServiceHandle(services);
  905. if (error == ERROR_IO_PENDING) {
  906. /*
  907. Older versions of Windows return immediately with ERROR_IO_PENDING
  908. indicate that the operation is still in progress. Newer versions
  909. will return it if there really is a delay. As far as we're
  910. concerned the operation is a success. We don't claim to offer a
  911. fully-feature service control method; it's just a quick 'n' dirty
  912. interface.
  913. In the future we may identify and handle this situation properly.
  914. */
  915. ret = 1;
  916. error = ERROR_SUCCESS;
  917. }
  918. if (ret) {
  919. _tprintf(_T("%s: %s"), canonical_name, error_string(error));
  920. return 0;
  921. }
  922. else {
  923. _ftprintf(stderr, _T("%s: %s"), canonical_name, error_string(error));
  924. return 1;
  925. }
  926. }
  927. else if (control == SERVICE_CONTROL_INTERROGATE) {
  928. /*
  929. We could actually send an INTERROGATE control but that won't return
  930. any information if the service is stopped and we don't care about
  931. the extra details it might give us in any case. So we'll fake it.
  932. */
  933. ret = QueryServiceStatus(service_handle, &service_status);
  934. error = GetLastError();
  935. if (ret) {
  936. switch (service_status.dwCurrentState) {
  937. case SERVICE_STOPPED: _tprintf(_T("SERVICE_STOPPED\n")); break;
  938. case SERVICE_START_PENDING: _tprintf(_T("SERVICE_START_PENDING\n")); break;
  939. case SERVICE_STOP_PENDING: _tprintf(_T("SERVICE_STOP_PENDING\n")); break;
  940. case SERVICE_RUNNING: _tprintf(_T("SERVICE_RUNNING\n")); break;
  941. case SERVICE_CONTINUE_PENDING: _tprintf(_T("SERVICE_CONTINUE_PENDING\n")); break;
  942. case SERVICE_PAUSE_PENDING: _tprintf(_T("SERVICE_PAUSE_PENDING\n")); break;
  943. case SERVICE_PAUSED: _tprintf(_T("SERVICE_PAUSED\n")); break;
  944. default: _tprintf(_T("?\n")); return 1;
  945. }
  946. return 0;
  947. }
  948. else {
  949. _ftprintf(stderr, _T("%s: %s\n"), canonical_name, error_string(error));
  950. return 1;
  951. }
  952. }
  953. else {
  954. ret = ControlService(service_handle, control, &service_status);
  955. error = GetLastError();
  956. CloseHandle(service_handle);
  957. CloseServiceHandle(services);
  958. if (error == ERROR_IO_PENDING) {
  959. ret = 1;
  960. error = ERROR_SUCCESS;
  961. }
  962. if (ret) {
  963. _tprintf(_T("%s: %s"), canonical_name, error_string(error));
  964. return 0;
  965. }
  966. else {
  967. _ftprintf(stderr, _T("%s: %s"), canonical_name, error_string(error));
  968. return 1;
  969. }
  970. }
  971. }
  972. /* Remove the service */
  973. int remove_service(nssm_service_t *service) {
  974. if (! service) return 1;
  975. /* Open service manager */
  976. SC_HANDLE services = open_service_manager();
  977. if (! services) {
  978. print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
  979. return 2;
  980. }
  981. /* Try to open the service */
  982. service->handle = open_service(services, service->name, service->name, _countof(service->name));
  983. if (! service->handle) {
  984. CloseServiceHandle(services);
  985. return 3;
  986. }
  987. /* Get the canonical service name. We open it case insensitively. */
  988. unsigned long bufsize = _countof(service->displayname);
  989. GetServiceDisplayName(services, service->name, service->displayname, &bufsize);
  990. bufsize = _countof(service->name);
  991. GetServiceKeyName(services, service->displayname, service->name, &bufsize);
  992. /* Try to delete the service */
  993. if (! DeleteService(service->handle)) {
  994. print_message(stderr, NSSM_MESSAGE_DELETESERVICE_FAILED);
  995. CloseServiceHandle(services);
  996. return 4;
  997. }
  998. /* Cleanup */
  999. CloseServiceHandle(services);
  1000. print_message(stdout, NSSM_MESSAGE_SERVICE_REMOVED, service->name);
  1001. return 0;
  1002. }
  1003. /* Service initialisation */
  1004. void WINAPI service_main(unsigned long argc, TCHAR **argv) {
  1005. nssm_service_t *service = alloc_nssm_service();
  1006. if (! service) return;
  1007. if (_sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), argv[0]) < 0) {
  1008. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("service->name"), _T("service_main()"), 0);
  1009. return;
  1010. }
  1011. /* We can use a condition variable in a critical section on Vista or later. */
  1012. if (imports.SleepConditionVariableCS && imports.WakeConditionVariable) use_critical_section = true;
  1013. else use_critical_section = false;
  1014. /* Initialise status */
  1015. ZeroMemory(&service->status, sizeof(service->status));
  1016. service->status.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS;
  1017. service->status.dwControlsAccepted = SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE;
  1018. service->status.dwWin32ExitCode = NO_ERROR;
  1019. service->status.dwServiceSpecificExitCode = 0;
  1020. service->status.dwCheckPoint = 0;
  1021. service->status.dwWaitHint = NSSM_WAITHINT_MARGIN;
  1022. /* Signal we AREN'T running the server */
  1023. service->process_handle = 0;
  1024. service->pid = 0;
  1025. /* Register control handler */
  1026. service->status_handle = RegisterServiceCtrlHandlerEx(NSSM, service_control_handler, (void *) service);
  1027. if (! service->status_handle) {
  1028. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_REGISTERSERVICECTRLHANDER_FAILED, error_string(GetLastError()), 0);
  1029. return;
  1030. }
  1031. log_service_control(service->name, 0, true);
  1032. service->status.dwCurrentState = SERVICE_START_PENDING;
  1033. service->status.dwWaitHint = service->throttle_delay + NSSM_WAITHINT_MARGIN;
  1034. SetServiceStatus(service->status_handle, &service->status);
  1035. if (is_admin) {
  1036. /* Try to create the exit action parameters; we don't care if it fails */
  1037. create_exit_action(service->name, exit_action_strings[0], false);
  1038. SC_HANDLE services = open_service_manager();
  1039. if (services) {
  1040. service->handle = OpenService(services, service->name, SC_MANAGER_ALL_ACCESS);
  1041. set_service_recovery(service);
  1042. CloseServiceHandle(services);
  1043. }
  1044. }
  1045. /* Used for signalling a resume if the service pauses when throttled. */
  1046. if (use_critical_section) {
  1047. InitializeCriticalSection(&service->throttle_section);
  1048. service->throttle_section_initialised = true;
  1049. }
  1050. else {
  1051. service->throttle_timer = CreateWaitableTimer(0, 1, 0);
  1052. if (! service->throttle_timer) {
  1053. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_CREATEWAITABLETIMER_FAILED, service->name, error_string(GetLastError()), 0);
  1054. }
  1055. }
  1056. monitor_service(service);
  1057. }
  1058. /* Make sure service recovery actions are taken where necessary */
  1059. void set_service_recovery(nssm_service_t *service) {
  1060. SERVICE_FAILURE_ACTIONS_FLAG flag;
  1061. ZeroMemory(&flag, sizeof(flag));
  1062. flag.fFailureActionsOnNonCrashFailures = true;
  1063. /* This functionality was added in Vista so the call may fail */
  1064. if (! ChangeServiceConfig2(service->handle, SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, &flag)) {
  1065. unsigned long error = GetLastError();
  1066. /* Pre-Vista we expect to fail with ERROR_INVALID_LEVEL */
  1067. if (error != ERROR_INVALID_LEVEL) {
  1068. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SERVICE_CONFIG_FAILURE_ACTIONS_FAILED, service->name, error_string(error), 0);
  1069. }
  1070. }
  1071. }
  1072. int monitor_service(nssm_service_t *service) {
  1073. /* Set service status to started */
  1074. int ret = start_service(service);
  1075. if (ret) {
  1076. TCHAR code[16];
  1077. _sntprintf_s(code, _countof(code), _TRUNCATE, _T("%d"), ret);
  1078. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_START_SERVICE_FAILED, service->exe, service->name, ret, 0);
  1079. return ret;
  1080. }
  1081. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_STARTED_SERVICE, service->exe, service->flags, service->name, service->dir, 0);
  1082. /* Monitor service */
  1083. if (! RegisterWaitForSingleObject(&service->wait_handle, service->process_handle, end_service, (void *) service, INFINITE, WT_EXECUTEONLYONCE | WT_EXECUTELONGFUNCTION)) {
  1084. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_REGISTERWAITFORSINGLEOBJECT_FAILED, service->name, service->exe, error_string(GetLastError()), 0);
  1085. }
  1086. return 0;
  1087. }
  1088. TCHAR *service_control_text(unsigned long control) {
  1089. switch (control) {
  1090. /* HACK: there is no SERVICE_CONTROL_START constant */
  1091. case 0: return _T("START");
  1092. case SERVICE_CONTROL_STOP: return _T("STOP");
  1093. case SERVICE_CONTROL_SHUTDOWN: return _T("SHUTDOWN");
  1094. case SERVICE_CONTROL_PAUSE: return _T("PAUSE");
  1095. case SERVICE_CONTROL_CONTINUE: return _T("CONTINUE");
  1096. case SERVICE_CONTROL_INTERROGATE: return _T("INTERROGATE");
  1097. default: return 0;
  1098. }
  1099. }
  1100. void log_service_control(TCHAR *service_name, unsigned long control, bool handled) {
  1101. TCHAR *text = service_control_text(control);
  1102. unsigned long event;
  1103. if (! text) {
  1104. /* "0x" + 8 x hex + NULL */
  1105. text = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, 11 * sizeof(TCHAR));
  1106. if (! text) {
  1107. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("control code"), _T("log_service_control()"), 0);
  1108. return;
  1109. }
  1110. if (_sntprintf_s(text, 11, _TRUNCATE, _T("0x%08x"), control) < 0) {
  1111. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("control code"), _T("log_service_control()"), 0);
  1112. HeapFree(GetProcessHeap(), 0, text);
  1113. return;
  1114. }
  1115. event = NSSM_EVENT_SERVICE_CONTROL_UNKNOWN;
  1116. }
  1117. else if (handled) event = NSSM_EVENT_SERVICE_CONTROL_HANDLED;
  1118. else event = NSSM_EVENT_SERVICE_CONTROL_NOT_HANDLED;
  1119. log_event(EVENTLOG_INFORMATION_TYPE, event, service_name, text, 0);
  1120. if (event == NSSM_EVENT_SERVICE_CONTROL_UNKNOWN) {
  1121. HeapFree(GetProcessHeap(), 0, text);
  1122. }
  1123. }
  1124. /* Service control handler */
  1125. unsigned long WINAPI service_control_handler(unsigned long control, unsigned long event, void *data, void *context) {
  1126. nssm_service_t *service = (nssm_service_t *) context;
  1127. switch (control) {
  1128. case SERVICE_CONTROL_INTERROGATE:
  1129. /* We always keep the service status up-to-date so this is a no-op. */
  1130. return NO_ERROR;
  1131. case SERVICE_CONTROL_SHUTDOWN:
  1132. case SERVICE_CONTROL_STOP:
  1133. log_service_control(service->name, control, true);
  1134. /*
  1135. We MUST acknowledge the stop request promptly but we're committed to
  1136. waiting for the application to exit. Spawn a new thread to wait
  1137. while we acknowledge the request.
  1138. */
  1139. if (! CreateThread(NULL, 0, shutdown_service, context, 0, NULL)) {
  1140. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATETHREAD_FAILED, error_string(GetLastError()), 0);
  1141. /*
  1142. We couldn't create a thread to tidy up so we'll have to force the tidyup
  1143. to complete in time in this thread.
  1144. */
  1145. service->kill_console_delay = NSSM_KILL_CONSOLE_GRACE_PERIOD;
  1146. service->kill_window_delay = NSSM_KILL_WINDOW_GRACE_PERIOD;
  1147. service->kill_threads_delay = NSSM_KILL_THREADS_GRACE_PERIOD;
  1148. stop_service(service, 0, true, true);
  1149. }
  1150. return NO_ERROR;
  1151. case SERVICE_CONTROL_CONTINUE:
  1152. log_service_control(service->name, control, true);
  1153. service->throttle = 0;
  1154. if (use_critical_section) imports.WakeConditionVariable(&service->throttle_condition);
  1155. else {
  1156. if (! service->throttle_timer) return ERROR_CALL_NOT_IMPLEMENTED;
  1157. ZeroMemory(&service->throttle_duetime, sizeof(service->throttle_duetime));
  1158. SetWaitableTimer(service->throttle_timer, &service->throttle_duetime, 0, 0, 0, 0);
  1159. }
  1160. service->status.dwCurrentState = SERVICE_CONTINUE_PENDING;
  1161. service->status.dwWaitHint = throttle_milliseconds(service->throttle) + NSSM_WAITHINT_MARGIN;
  1162. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_RESET_THROTTLE, service->name, 0);
  1163. SetServiceStatus(service->status_handle, &service->status);
  1164. return NO_ERROR;
  1165. case SERVICE_CONTROL_PAUSE:
  1166. /*
  1167. We don't accept pause messages but it isn't possible to register
  1168. only for continue messages so we have to handle this case.
  1169. */
  1170. log_service_control(service->name, control, false);
  1171. return ERROR_CALL_NOT_IMPLEMENTED;
  1172. }
  1173. /* Unknown control */
  1174. log_service_control(service->name, control, false);
  1175. return ERROR_CALL_NOT_IMPLEMENTED;
  1176. }
  1177. /* Start the service */
  1178. int start_service(nssm_service_t *service) {
  1179. service->stopping = false;
  1180. service->allow_restart = true;
  1181. if (service->process_handle) return 0;
  1182. /* Allocate a STARTUPINFO structure for a new process */
  1183. STARTUPINFO si;
  1184. ZeroMemory(&si, sizeof(si));
  1185. si.cb = sizeof(si);
  1186. /* Allocate a PROCESSINFO structure for the process */
  1187. PROCESS_INFORMATION pi;
  1188. ZeroMemory(&pi, sizeof(pi));
  1189. /* Get startup parameters */
  1190. int ret = get_parameters(service, &si);
  1191. if (ret) {
  1192. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GET_PARAMETERS_FAILED, service->name, 0);
  1193. return stop_service(service, 2, true, true);
  1194. }
  1195. /* Launch executable with arguments */
  1196. TCHAR cmd[CMD_LENGTH];
  1197. if (_sntprintf_s(cmd, _countof(cmd), _TRUNCATE, _T("\"%s\" %s"), service->exe, service->flags) < 0) {
  1198. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("command line"), _T("start_service"), 0);
  1199. close_output_handles(&si);
  1200. return stop_service(service, 2, true, true);
  1201. }
  1202. throttle_restart(service);
  1203. bool inherit_handles = false;
  1204. if (si.dwFlags & STARTF_USESTDHANDLES) inherit_handles = true;
  1205. unsigned long flags = service->priority & priority_mask();
  1206. if (service->affinity) flags |= CREATE_SUSPENDED;
  1207. #ifdef UNICODE
  1208. flags |= CREATE_UNICODE_ENVIRONMENT;
  1209. #endif
  1210. if (! CreateProcess(0, cmd, 0, 0, inherit_handles, flags, service->env, service->dir, &si, &pi)) {
  1211. unsigned long exitcode = 3;
  1212. unsigned long error = GetLastError();
  1213. if (error == ERROR_INVALID_PARAMETER && service->env) {
  1214. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEPROCESS_FAILED_INVALID_ENVIRONMENT, service->name, service->exe, NSSM_REG_ENV, 0);
  1215. if (test_environment(service->env)) exitcode = 4;
  1216. }
  1217. else log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEPROCESS_FAILED, service->name, service->exe, error_string(error), 0);
  1218. close_output_handles(&si);
  1219. return stop_service(service, exitcode, true, true);
  1220. }
  1221. service->process_handle = pi.hProcess;
  1222. service->pid = pi.dwProcessId;
  1223. if (get_process_creation_time(service->process_handle, &service->creation_time)) ZeroMemory(&service->creation_time, sizeof(service->creation_time));
  1224. close_output_handles(&si);
  1225. if (service->affinity) {
  1226. /*
  1227. We are explicitly storing service->affinity as a 64-bit unsigned integer
  1228. so that we can parse it regardless of whether we're running in 32-bit
  1229. or 64-bit mode. The arguments to SetProcessAffinityMask(), however, are
  1230. defined as type DWORD_PTR and hence limited to 32 bits on a 32-bit system
  1231. (or when running the 32-bit NSSM).
  1232. The result is a lot of seemingly-unnecessary casting throughout the code
  1233. and potentially confusion when we actually try to start the service.
  1234. Having said that, however, it's unlikely that we're actually going to
  1235. run in 32-bit mode on a system which has more than 32 CPUs so the
  1236. likelihood of seeing a confusing situation is somewhat diminished.
  1237. */
  1238. DWORD_PTR affinity, system_affinity;
  1239. if (GetProcessAffinityMask(service->process_handle, &affinity, &system_affinity)) affinity = service->affinity & system_affinity;
  1240. else {
  1241. affinity = (DWORD_PTR) service->affinity;
  1242. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GETPROCESSAFFINITYMASK_FAILED, service->name, error_string(GetLastError()), 0);
  1243. }
  1244. if (! SetProcessAffinityMask(service->process_handle, affinity)) {
  1245. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_SETPROCESSAFFINITYMASK_FAILED, service->name, error_string(GetLastError()), 0);
  1246. }
  1247. ResumeThread(pi.hThread);
  1248. }
  1249. /*
  1250. Wait for a clean startup before changing the service status to RUNNING
  1251. but be mindful of the fact that we are blocking the service control manager
  1252. so abandon the wait before too much time has elapsed.
  1253. */
  1254. unsigned long delay = service->throttle_delay;
  1255. if (delay > NSSM_SERVICE_STATUS_DEADLINE) {
  1256. TCHAR delay_milliseconds[16];
  1257. _sntprintf_s(delay_milliseconds, _countof(delay_milliseconds), _TRUNCATE, _T("%lu"), delay);
  1258. TCHAR deadline_milliseconds[16];
  1259. _sntprintf_s(deadline_milliseconds, _countof(deadline_milliseconds), _TRUNCATE, _T("%lu"), NSSM_SERVICE_STATUS_DEADLINE);
  1260. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_STARTUP_DELAY_TOO_LONG, service->name, delay_milliseconds, NSSM, deadline_milliseconds, 0);
  1261. delay = NSSM_SERVICE_STATUS_DEADLINE;
  1262. }
  1263. unsigned long deadline = WaitForSingleObject(service->process_handle, delay);
  1264. /* Signal successful start */
  1265. service->status.dwCurrentState = SERVICE_RUNNING;
  1266. SetServiceStatus(service->status_handle, &service->status);
  1267. /* Continue waiting for a clean startup. */
  1268. if (deadline == WAIT_TIMEOUT) {
  1269. if (service->throttle_delay > delay) {
  1270. if (WaitForSingleObject(service->process_handle, service->throttle_delay - delay) == WAIT_TIMEOUT) service->throttle = 0;
  1271. }
  1272. else service->throttle = 0;
  1273. }
  1274. return 0;
  1275. }
  1276. /* Stop the service */
  1277. int stop_service(nssm_service_t *service, unsigned long exitcode, bool graceful, bool default_action) {
  1278. service->allow_restart = false;
  1279. if (service->wait_handle) {
  1280. UnregisterWait(service->wait_handle);
  1281. service->wait_handle = 0;
  1282. }
  1283. if (default_action && ! exitcode && ! graceful) {
  1284. 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);
  1285. graceful = true;
  1286. }
  1287. /* Signal we are stopping */
  1288. if (graceful) {
  1289. service->status.dwCurrentState = SERVICE_STOP_PENDING;
  1290. service->status.dwWaitHint = NSSM_WAITHINT_MARGIN;
  1291. SetServiceStatus(service->status_handle, &service->status);
  1292. }
  1293. /* Nothing to do if service isn't running */
  1294. if (service->pid) {
  1295. /* Shut down service */
  1296. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_TERMINATEPROCESS, service->name, service->exe, 0);
  1297. kill_process(service, service->process_handle, service->pid, 0);
  1298. }
  1299. else log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_PROCESS_ALREADY_STOPPED, service->name, service->exe, 0);
  1300. end_service((void *) service, true);
  1301. /* Signal we stopped */
  1302. if (graceful) {
  1303. service->status.dwCurrentState = SERVICE_STOPPED;
  1304. if (exitcode) {
  1305. service->status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
  1306. service->status.dwServiceSpecificExitCode = exitcode;
  1307. }
  1308. else {
  1309. service->status.dwWin32ExitCode = NO_ERROR;
  1310. service->status.dwServiceSpecificExitCode = 0;
  1311. }
  1312. SetServiceStatus(service->status_handle, &service->status);
  1313. }
  1314. return exitcode;
  1315. }
  1316. /* Callback function triggered when the server exits */
  1317. void CALLBACK end_service(void *arg, unsigned char why) {
  1318. nssm_service_t *service = (nssm_service_t *) arg;
  1319. if (service->stopping) return;
  1320. service->stopping = true;
  1321. /* Check exit code */
  1322. unsigned long exitcode = 0;
  1323. TCHAR code[16];
  1324. if (service->process_handle) {
  1325. GetExitCodeProcess(service->process_handle, &exitcode);
  1326. if (exitcode == STILL_ACTIVE || get_process_exit_time(service->process_handle, &service->exit_time)) GetSystemTimeAsFileTime(&service->exit_time);
  1327. CloseHandle(service->process_handle);
  1328. }
  1329. else GetSystemTimeAsFileTime(&service->exit_time);
  1330. service->process_handle = 0;
  1331. /*
  1332. Log that the service ended BEFORE logging about killing the process
  1333. tree. See below for the possible values of the why argument.
  1334. */
  1335. if (! why) {
  1336. _sntprintf_s(code, _countof(code), _TRUNCATE, _T("%lu"), exitcode);
  1337. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_ENDED_SERVICE, service->exe, service->name, code, 0);
  1338. }
  1339. /* Clean up. */
  1340. if (exitcode == STILL_ACTIVE) exitcode = 0;
  1341. if (service->pid) kill_process_tree(service, service->pid, exitcode, service->pid);
  1342. service->pid = 0;
  1343. /*
  1344. The why argument is true if our wait timed out or false otherwise.
  1345. Our wait is infinite so why will never be true when called by the system.
  1346. If it is indeed true, assume we were called from stop_service() because
  1347. this is a controlled shutdown, and don't take any restart action.
  1348. */
  1349. if (why) return;
  1350. if (! service->allow_restart) return;
  1351. /* What action should we take? */
  1352. int action = NSSM_EXIT_RESTART;
  1353. TCHAR action_string[ACTION_LEN];
  1354. bool default_action;
  1355. if (! get_exit_action(service->name, &exitcode, action_string, &default_action)) {
  1356. for (int i = 0; exit_action_strings[i]; i++) {
  1357. if (! _tcsnicmp((const TCHAR *) action_string, exit_action_strings[i], ACTION_LEN)) {
  1358. action = i;
  1359. break;
  1360. }
  1361. }
  1362. }
  1363. switch (action) {
  1364. /* Try to restart the service or return failure code to service manager */
  1365. case NSSM_EXIT_RESTART:
  1366. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_RESTART, service->name, code, exit_action_strings[action], service->exe, 0);
  1367. while (monitor_service(service)) {
  1368. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_RESTART_SERVICE_FAILED, service->exe, service->name, 0);
  1369. Sleep(30000);
  1370. }
  1371. break;
  1372. /* Do nothing, just like srvany would */
  1373. case NSSM_EXIT_IGNORE:
  1374. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_IGNORE, service->name, code, exit_action_strings[action], service->exe, 0);
  1375. Sleep(INFINITE);
  1376. break;
  1377. /* Tell the service manager we are finished */
  1378. case NSSM_EXIT_REALLY:
  1379. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_REALLY, service->name, code, exit_action_strings[action], 0);
  1380. stop_service(service, exitcode, true, default_action);
  1381. break;
  1382. /* Fake a crash so pre-Vista service managers will run recovery actions. */
  1383. case NSSM_EXIT_UNCLEAN:
  1384. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_UNCLEAN, service->name, code, exit_action_strings[action], 0);
  1385. stop_service(service, exitcode, false, default_action);
  1386. free_imports();
  1387. exit(exitcode);
  1388. break;
  1389. }
  1390. }
  1391. void throttle_restart(nssm_service_t *service) {
  1392. /* This can't be a restart if the service is already running. */
  1393. if (! service->throttle++) return;
  1394. int ms = throttle_milliseconds(service->throttle);
  1395. if (service->throttle > 7) service->throttle = 8;
  1396. TCHAR threshold[8], milliseconds[8];
  1397. _sntprintf_s(threshold, _countof(threshold), _TRUNCATE, _T("%lu"), service->throttle_delay);
  1398. _sntprintf_s(milliseconds, _countof(milliseconds), _TRUNCATE, _T("%lu"), ms);
  1399. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_THROTTLED, service->name, threshold, milliseconds, 0);
  1400. if (use_critical_section) EnterCriticalSection(&service->throttle_section);
  1401. else if (service->throttle_timer) {
  1402. ZeroMemory(&service->throttle_duetime, sizeof(service->throttle_duetime));
  1403. service->throttle_duetime.QuadPart = 0 - (ms * 10000LL);
  1404. SetWaitableTimer(service->throttle_timer, &service->throttle_duetime, 0, 0, 0, 0);
  1405. }
  1406. service->status.dwCurrentState = SERVICE_PAUSED;
  1407. SetServiceStatus(service->status_handle, &service->status);
  1408. if (use_critical_section) {
  1409. imports.SleepConditionVariableCS(&service->throttle_condition, &service->throttle_section, ms);
  1410. LeaveCriticalSection(&service->throttle_section);
  1411. }
  1412. else {
  1413. if (service->throttle_timer) WaitForSingleObject(service->throttle_timer, INFINITE);
  1414. else Sleep(ms);
  1415. }
  1416. }
  1417. /*
  1418. When responding to a stop (or any other) request we need to set dwWaitHint to
  1419. the number of milliseconds we expect the operation to take, and optionally
  1420. increase dwCheckPoint. If dwWaitHint milliseconds elapses without the
  1421. operation completing or dwCheckPoint increasing, the system will consider the
  1422. service to be hung.
  1423. However the system will consider the service to be hung after 30000
  1424. milliseconds regardless of the value of dwWaitHint if dwCheckPoint has not
  1425. changed. Therefore if we want to wait longer than that we must periodically
  1426. increase dwCheckPoint.
  1427. Furthermore, it will consider the service to be hung after 60000 milliseconds
  1428. regardless of the value of dwCheckPoint unless dwWaitHint is increased every
  1429. time dwCheckPoint is also increased.
  1430. Our strategy then is to retrieve the initial dwWaitHint and wait for
  1431. NSSM_SERVICE_STATUS_DEADLINE milliseconds. If the process is still running
  1432. and we haven't finished waiting we increment dwCheckPoint and add whichever is
  1433. smaller of NSSM_SERVICE_STATUS_DEADLINE or the remaining timeout to
  1434. dwWaitHint.
  1435. Only doing both these things will prevent the system from killing the service.
  1436. Returns: 1 if the wait timed out.
  1437. 0 if the wait completed.
  1438. -1 on error.
  1439. */
  1440. int await_shutdown(nssm_service_t *service, TCHAR *function_name, unsigned long timeout) {
  1441. unsigned long interval;
  1442. unsigned long waithint;
  1443. unsigned long ret;
  1444. unsigned long waited;
  1445. TCHAR interval_milliseconds[16];
  1446. TCHAR timeout_milliseconds[16];
  1447. TCHAR waited_milliseconds[16];
  1448. TCHAR *function = function_name;
  1449. /* Add brackets to function name. */
  1450. size_t funclen = _tcslen(function_name) + 3;
  1451. TCHAR *func = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, funclen * sizeof(TCHAR));
  1452. if (func) {
  1453. if (_sntprintf_s(func, funclen, _TRUNCATE, _T("%s()"), function_name) > -1) function = func;
  1454. }
  1455. _sntprintf_s(timeout_milliseconds, _countof(timeout_milliseconds), _TRUNCATE, _T("%lu"), timeout);
  1456. waithint = service->status.dwWaitHint;
  1457. waited = 0;
  1458. while (waited < timeout) {
  1459. interval = timeout - waited;
  1460. if (interval > NSSM_SERVICE_STATUS_DEADLINE) interval = NSSM_SERVICE_STATUS_DEADLINE;
  1461. service->status.dwCurrentState = SERVICE_STOP_PENDING;
  1462. service->status.dwWaitHint += interval;
  1463. service->status.dwCheckPoint++;
  1464. SetServiceStatus(service->status_handle, &service->status);
  1465. if (waited) {
  1466. _sntprintf_s(waited_milliseconds, _countof(waited_milliseconds), _TRUNCATE, _T("%lu"), waited);
  1467. _sntprintf_s(interval_milliseconds, _countof(interval_milliseconds), _TRUNCATE, _T("%lu"), interval);
  1468. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_AWAITING_SHUTDOWN, function, service->name, waited_milliseconds, interval_milliseconds, timeout_milliseconds, 0);
  1469. }
  1470. switch (WaitForSingleObject(service->process_handle, interval)) {
  1471. case WAIT_OBJECT_0:
  1472. ret = 0;
  1473. goto awaited;
  1474. case WAIT_TIMEOUT:
  1475. ret = 1;
  1476. break;
  1477. default:
  1478. ret = -1;
  1479. goto awaited;
  1480. }
  1481. waited += interval;
  1482. }
  1483. awaited:
  1484. if (func) HeapFree(GetProcessHeap(), 0, func);
  1485. return ret;
  1486. }