service.cpp 50 KB

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