service.cpp 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399
  1. #include "nssm.h"
  2. bool is_admin;
  3. bool use_critical_section;
  4. extern imports_t imports;
  5. extern settings_t settings[];
  6. const TCHAR *exit_action_strings[] = { _T("Restart"), _T("Ignore"), _T("Exit"), _T("Suicide"), 0 };
  7. const TCHAR *startup_strings[] = { _T("SERVICE_AUTO_START"), _T("SERVICE_DELAYED_AUTO_START"), _T("SERVICE_DEMAND_START"), _T("SERVICE_DISABLED"), 0 };
  8. 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 };
  9. static hook_thread_t hook_threads = { NULL, 0 };
  10. typedef struct {
  11. int first;
  12. int last;
  13. } list_t;
  14. /*
  15. Check the status in response to a control.
  16. Returns: 1 if the status is expected, eg STOP following CONTROL_STOP.
  17. 0 if the status is desired, eg STOPPED following CONTROL_STOP.
  18. -1 if the status is undesired, eg STOPPED following CONTROL_START.
  19. */
  20. static inline int service_control_response(unsigned long control, unsigned long status) {
  21. switch (control) {
  22. case NSSM_SERVICE_CONTROL_START:
  23. switch (status) {
  24. case SERVICE_START_PENDING:
  25. return 1;
  26. case SERVICE_RUNNING:
  27. return 0;
  28. default:
  29. return -1;
  30. }
  31. case SERVICE_CONTROL_STOP:
  32. case SERVICE_CONTROL_SHUTDOWN:
  33. switch (status) {
  34. case SERVICE_RUNNING:
  35. case SERVICE_STOP_PENDING:
  36. return 1;
  37. case SERVICE_STOPPED:
  38. return 0;
  39. default:
  40. return -1;
  41. }
  42. case SERVICE_CONTROL_PAUSE:
  43. switch (status) {
  44. case SERVICE_PAUSE_PENDING:
  45. return 1;
  46. case SERVICE_PAUSED:
  47. return 0;
  48. default:
  49. return -1;
  50. }
  51. case SERVICE_CONTROL_CONTINUE:
  52. switch (status) {
  53. case SERVICE_CONTINUE_PENDING:
  54. return 1;
  55. case SERVICE_RUNNING:
  56. return 0;
  57. default:
  58. return -1;
  59. }
  60. case SERVICE_CONTROL_INTERROGATE:
  61. case NSSM_SERVICE_CONTROL_ROTATE:
  62. return 0;
  63. }
  64. return 0;
  65. }
  66. static inline int await_service_control_response(unsigned long control, SC_HANDLE service_handle, SERVICE_STATUS *service_status, unsigned long initial_status, unsigned long cutoff) {
  67. int tries = 0;
  68. unsigned long checkpoint = 0;
  69. unsigned long waithint = 0;
  70. unsigned long waited = 0;
  71. while (QueryServiceStatus(service_handle, service_status)) {
  72. int response = service_control_response(control, service_status->dwCurrentState);
  73. /* Alas we can't WaitForSingleObject() on an SC_HANDLE. */
  74. if (! response) return response;
  75. if (response > 0 || service_status->dwCurrentState == initial_status) {
  76. if (service_status->dwCheckPoint != checkpoint || service_status->dwWaitHint != waithint) tries = 0;
  77. checkpoint = service_status->dwCheckPoint;
  78. waithint = service_status->dwWaitHint;
  79. if (++tries > 10) tries = 10;
  80. unsigned long wait = 50 * tries;
  81. if (cutoff) {
  82. if (waited > cutoff) return response;
  83. waited += wait;
  84. }
  85. Sleep(wait);
  86. }
  87. else return response;
  88. }
  89. return -1;
  90. }
  91. static inline int await_service_control_response(unsigned long control, SC_HANDLE service_handle, SERVICE_STATUS *service_status, unsigned long initial_status) {
  92. return await_service_control_response(control, service_handle, service_status, initial_status, 0);
  93. }
  94. static inline void wait_for_hooks(nssm_service_t *service, bool notify) {
  95. SERVICE_STATUS_HANDLE status_handle;
  96. SERVICE_STATUS *status;
  97. /* On a clean shutdown we need to keep the service's status up-to-date. */
  98. if (notify) {
  99. status_handle = service->status_handle;
  100. status = &service->status;
  101. }
  102. else {
  103. status_handle = NULL;
  104. status = NULL;
  105. }
  106. EnterCriticalSection(&service->hook_section);
  107. await_hook_threads(&hook_threads, status_handle, status, NSSM_HOOK_THREAD_DEADLINE);
  108. LeaveCriticalSection(&service->hook_section);
  109. }
  110. int affinity_mask_to_string(__int64 mask, TCHAR **string) {
  111. if (! string) return 1;
  112. if (! mask) {
  113. *string = 0;
  114. return 0;
  115. }
  116. __int64 i, n;
  117. /* SetProcessAffinityMask() accepts a mask of up to 64 processors. */
  118. list_t set[64];
  119. for (n = 0; n < _countof(set); n++) set[n].first = set[n].last = -1;
  120. for (i = 0, n = 0; i < _countof(set); i++) {
  121. if (mask & (1LL << i)) {
  122. if (set[n].first == -1) set[n].first = set[n].last = (int) i;
  123. else if (set[n].last == (int) i - 1) set[n].last = (int) i;
  124. else {
  125. n++;
  126. set[n].first = set[n].last = (int) i;
  127. }
  128. }
  129. }
  130. /* Worst case is 2x2 characters for first and last CPU plus - and/or , */
  131. size_t len = (size_t) (n + 1) * 6;
  132. *string = (TCHAR *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len * sizeof(TCHAR));
  133. if (! string) return 2;
  134. size_t s = 0;
  135. int ret;
  136. for (i = 0; i <= n; i++) {
  137. if (i) (*string)[s++] = _T(',');
  138. ret = _sntprintf_s(*string + s, 3, _TRUNCATE, _T("%u"), set[i].first);
  139. if (ret < 0) {
  140. HeapFree(GetProcessHeap(), 0, *string);
  141. *string = 0;
  142. return 3;
  143. }
  144. else s += ret;
  145. if (set[i].last != set[i].first) {
  146. ret =_sntprintf_s(*string + s, 4, _TRUNCATE, _T("%c%u"), (set[i].last == set[i].first + 1) ? _T(',') : _T('-'), set[i].last);
  147. if (ret < 0) {
  148. HeapFree(GetProcessHeap(), 0, *string);
  149. *string = 0;
  150. return 4;
  151. }
  152. else s += ret;
  153. }
  154. }
  155. return 0;
  156. }
  157. int affinity_string_to_mask(TCHAR *string, __int64 *mask) {
  158. if (! mask) return 1;
  159. *mask = 0LL;
  160. if (! string) return 0;
  161. list_t set[64];
  162. TCHAR *s = string;
  163. TCHAR *end;
  164. int ret;
  165. int i;
  166. int n = 0;
  167. unsigned long number;
  168. for (n = 0; n < _countof(set); n++) set[n].first = set[n].last = -1;
  169. n = 0;
  170. while (*s) {
  171. ret = str_number(s, &number, &end);
  172. s = end;
  173. if (ret == 0 || ret == 2) {
  174. if (number >= _countof(set)) return 2;
  175. set[n].first = set[n].last = (int) number;
  176. switch (*s) {
  177. case 0:
  178. break;
  179. case _T(','):
  180. n++;
  181. s++;
  182. break;
  183. case _T('-'):
  184. if (! *(++s)) return 3;
  185. ret = str_number(s, &number, &end);
  186. if (ret == 0 || ret == 2) {
  187. s = end;
  188. if (! *s || *s == _T(',')) {
  189. set[n].last = (int) number;
  190. if (! *s) break;
  191. n++;
  192. s++;
  193. }
  194. else return 3;
  195. }
  196. else return 3;
  197. break;
  198. default:
  199. return 3;
  200. }
  201. }
  202. else return 4;
  203. }
  204. for (i = 0; i <= n; i++) {
  205. for (int j = set[i].first; j <= set[i].last; j++) (__int64) *mask |= (1LL << (__int64) j);
  206. }
  207. return 0;
  208. }
  209. unsigned long priority_mask() {
  210. return REALTIME_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | ABOVE_NORMAL_PRIORITY_CLASS | NORMAL_PRIORITY_CLASS | BELOW_NORMAL_PRIORITY_CLASS | IDLE_PRIORITY_CLASS;
  211. }
  212. int priority_constant_to_index(unsigned long constant) {
  213. switch (constant & priority_mask()) {
  214. case REALTIME_PRIORITY_CLASS: return NSSM_REALTIME_PRIORITY;
  215. case HIGH_PRIORITY_CLASS: return NSSM_HIGH_PRIORITY;
  216. case ABOVE_NORMAL_PRIORITY_CLASS: return NSSM_ABOVE_NORMAL_PRIORITY;
  217. case BELOW_NORMAL_PRIORITY_CLASS: return NSSM_BELOW_NORMAL_PRIORITY;
  218. case IDLE_PRIORITY_CLASS: return NSSM_IDLE_PRIORITY;
  219. }
  220. return NSSM_NORMAL_PRIORITY;
  221. }
  222. unsigned long priority_index_to_constant(int index) {
  223. switch (index) {
  224. case NSSM_REALTIME_PRIORITY: return REALTIME_PRIORITY_CLASS;
  225. case NSSM_HIGH_PRIORITY: return HIGH_PRIORITY_CLASS;
  226. case NSSM_ABOVE_NORMAL_PRIORITY: return ABOVE_NORMAL_PRIORITY_CLASS;
  227. case NSSM_BELOW_NORMAL_PRIORITY: return BELOW_NORMAL_PRIORITY_CLASS;
  228. case NSSM_IDLE_PRIORITY: return IDLE_PRIORITY_CLASS;
  229. }
  230. return NORMAL_PRIORITY_CLASS;
  231. }
  232. static inline unsigned long throttle_milliseconds(unsigned long throttle) {
  233. if (throttle > 7) throttle = 8;
  234. /* pow() operates on doubles. */
  235. unsigned long ret = 1; for (unsigned long i = 1; i < throttle; i++) ret *= 2;
  236. return ret * 1000;
  237. }
  238. void set_service_environment(nssm_service_t *service) {
  239. if (! service) return;
  240. /*
  241. We have to duplicate the block because this function will be called
  242. multiple times between registry reads.
  243. */
  244. if (service->env) duplicate_environment_strings(service->env);
  245. if (! service->env_extra) return;
  246. TCHAR *env_extra = copy_environment_block(service->env_extra);
  247. if (! env_extra) return;
  248. set_environment_block(env_extra);
  249. HeapFree(GetProcessHeap(), 0, env_extra);
  250. }
  251. void unset_service_environment(nssm_service_t *service) {
  252. if (! service) return;
  253. duplicate_environment_strings(service->initial_env);
  254. }
  255. /*
  256. Wrapper to be called in a new thread so that we can acknowledge a STOP
  257. control immediately.
  258. */
  259. static unsigned long WINAPI shutdown_service(void *arg) {
  260. return stop_service((nssm_service_t *) arg, 0, true, true);
  261. }
  262. /*
  263. Wrapper to be called in a new thread so that we can acknowledge start
  264. immediately.
  265. */
  266. static unsigned long WINAPI launch_service(void *arg) {
  267. return monitor_service((nssm_service_t *) arg);
  268. }
  269. /* Connect to the service manager */
  270. SC_HANDLE open_service_manager(unsigned long access) {
  271. SC_HANDLE ret = OpenSCManager(0, SERVICES_ACTIVE_DATABASE, access);
  272. if (! ret) {
  273. if (is_admin) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OPENSCMANAGER_FAILED, 0);
  274. return 0;
  275. }
  276. return ret;
  277. }
  278. /* Open a service by name or display name. */
  279. SC_HANDLE open_service(SC_HANDLE services, TCHAR *service_name, unsigned long access, TCHAR *canonical_name, unsigned long canonical_namelen) {
  280. SC_HANDLE service_handle = OpenService(services, service_name, access);
  281. if (service_handle) {
  282. if (canonical_name && canonical_name != service_name) {
  283. TCHAR displayname[SERVICE_NAME_LENGTH];
  284. unsigned long displayname_len = (unsigned long) _countof(displayname);
  285. GetServiceDisplayName(services, service_name, displayname, &displayname_len);
  286. unsigned long keyname_len = canonical_namelen;
  287. GetServiceKeyName(services, displayname, canonical_name, &keyname_len);
  288. }
  289. return service_handle;
  290. }
  291. unsigned long error = GetLastError();
  292. if (error != ERROR_SERVICE_DOES_NOT_EXIST) {
  293. print_message(stderr, NSSM_MESSAGE_OPENSERVICE_FAILED, error_string(GetLastError()));
  294. return 0;
  295. }
  296. /* We can't look for a display name because there's no buffer to store it. */
  297. if (! canonical_name) {
  298. print_message(stderr, NSSM_MESSAGE_OPENSERVICE_FAILED, error_string(GetLastError()));
  299. return 0;
  300. }
  301. unsigned long bufsize, required, count, i;
  302. unsigned long resume = 0;
  303. EnumServicesStatusEx(services, SC_ENUM_PROCESS_INFO, SERVICE_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_KERNEL_DRIVER | SERVICE_WIN32, SERVICE_STATE_ALL, 0, 0, &required, &count, &resume, 0);
  304. error = GetLastError();
  305. if (error != ERROR_MORE_DATA) {
  306. print_message(stderr, NSSM_MESSAGE_ENUMSERVICESSTATUS_FAILED, error_string(GetLastError()));
  307. return 0;
  308. }
  309. ENUM_SERVICE_STATUS_PROCESS *status = (ENUM_SERVICE_STATUS_PROCESS *) HeapAlloc(GetProcessHeap(), 0, required);
  310. if (! status) {
  311. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("ENUM_SERVICE_STATUS_PROCESS"), _T("open_service()"));
  312. return 0;
  313. }
  314. bufsize = required;
  315. while (true) {
  316. /*
  317. EnumServicesStatusEx() returns:
  318. 1 when it retrieved data and there's no more data to come.
  319. 0 and sets last error to ERROR_MORE_DATA when it retrieved data and
  320. there's more data to come.
  321. 0 and sets last error to something else on error.
  322. */
  323. int ret = EnumServicesStatusEx(services, SC_ENUM_PROCESS_INFO, SERVICE_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_KERNEL_DRIVER | SERVICE_WIN32, SERVICE_STATE_ALL, (LPBYTE) status, bufsize, &required, &count, &resume, 0);
  324. if (! ret) {
  325. error = GetLastError();
  326. if (error != ERROR_MORE_DATA) {
  327. HeapFree(GetProcessHeap(), 0, status);
  328. print_message(stderr, NSSM_MESSAGE_ENUMSERVICESSTATUS_FAILED, error_string(GetLastError()));
  329. return 0;
  330. }
  331. }
  332. for (i = 0; i < count; i++) {
  333. if (str_equiv(status[i].lpDisplayName, service_name)) {
  334. if (_sntprintf_s(canonical_name, canonical_namelen, _TRUNCATE, _T("%s"), status[i].lpServiceName) < 0) {
  335. HeapFree(GetProcessHeap(), 0, status);
  336. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("canonical_name"), _T("open_service()"));
  337. return 0;
  338. }
  339. HeapFree(GetProcessHeap(), 0, status);
  340. return open_service(services, canonical_name, access, 0, 0);
  341. }
  342. }
  343. if (ret) break;
  344. }
  345. /* Recurse so we can get an error message. */
  346. return open_service(services, service_name, access, 0, 0);
  347. }
  348. QUERY_SERVICE_CONFIG *query_service_config(const TCHAR *service_name, SC_HANDLE service_handle) {
  349. QUERY_SERVICE_CONFIG *qsc;
  350. unsigned long bufsize;
  351. unsigned long error;
  352. QueryServiceConfig(service_handle, 0, 0, &bufsize);
  353. error = GetLastError();
  354. if (error == ERROR_INSUFFICIENT_BUFFER) {
  355. qsc = (QUERY_SERVICE_CONFIG *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bufsize);
  356. if (! qsc) {
  357. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("QUERY_SERVICE_CONFIG"), _T("query_service_config()"), 0);
  358. return 0;
  359. }
  360. }
  361. else {
  362. print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG_FAILED, service_name, error_string(error), 0);
  363. return 0;
  364. }
  365. if (! QueryServiceConfig(service_handle, qsc, bufsize, &bufsize)) {
  366. HeapFree(GetProcessHeap(), 0, qsc);
  367. print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG_FAILED, service_name, error_string(GetLastError()), 0);
  368. return 0;
  369. }
  370. return qsc;
  371. }
  372. /* WILL NOT allocate a new string if the identifier is already present. */
  373. int prepend_service_group_identifier(TCHAR *group, TCHAR **canon) {
  374. if (! group || ! group[0] || group[0] == SC_GROUP_IDENTIFIER) {
  375. *canon = group;
  376. return 0;
  377. }
  378. size_t len = _tcslen(group) + 1;
  379. *canon = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(TCHAR));
  380. if (! *canon) {
  381. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("canon"), _T("prepend_service_group_identifier()"));
  382. return 1;
  383. }
  384. TCHAR *s = *canon;
  385. *s++ = SC_GROUP_IDENTIFIER;
  386. memmove(s, group, len * sizeof(TCHAR));
  387. (*canon)[len] = _T('\0');
  388. return 0;
  389. }
  390. int append_to_dependencies(TCHAR *dependencies, unsigned long dependencieslen, TCHAR *string, TCHAR **newdependencies, unsigned long *newlen, int type) {
  391. *newlen = 0;
  392. TCHAR *canon = 0;
  393. if (type == DEPENDENCY_GROUPS) {
  394. if (prepend_service_group_identifier(string, &canon)) return 1;
  395. }
  396. else canon = string;
  397. int ret = append_to_double_null(dependencies, dependencieslen, newdependencies, newlen, canon, 0, false);
  398. if (canon && canon != string) HeapFree(GetProcessHeap(), 0, canon);
  399. return ret;
  400. }
  401. int remove_from_dependencies(TCHAR *dependencies, unsigned long dependencieslen, TCHAR *string, TCHAR **newdependencies, unsigned long *newlen, int type) {
  402. *newlen = 0;
  403. TCHAR *canon = 0;
  404. if (type == DEPENDENCY_GROUPS) {
  405. if (prepend_service_group_identifier(string, &canon)) return 1;
  406. }
  407. else canon = string;
  408. int ret = remove_from_double_null(dependencies, dependencieslen, newdependencies, newlen, canon, 0, false);
  409. if (canon && canon != string) HeapFree(GetProcessHeap(), 0, canon);
  410. return ret;
  411. }
  412. int set_service_dependencies(const TCHAR *service_name, SC_HANDLE service_handle, TCHAR *buffer) {
  413. TCHAR *dependencies = _T("");
  414. unsigned long num_dependencies = 0;
  415. if (buffer && buffer[0]) {
  416. SC_HANDLE services = open_service_manager(SC_MANAGER_CONNECT | SC_MANAGER_ENUMERATE_SERVICE);
  417. if (! services) {
  418. print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
  419. return 1;
  420. }
  421. /*
  422. Count the dependencies then allocate a buffer big enough for their
  423. canonical names, ie n * SERVICE_NAME_LENGTH.
  424. */
  425. TCHAR *s;
  426. TCHAR *groups = 0;
  427. for (s = buffer; *s; s++) {
  428. num_dependencies++;
  429. if (*s == SC_GROUP_IDENTIFIER) groups = s;
  430. while (*s) s++;
  431. }
  432. /* At least one dependency is a group so we need to verify them. */
  433. if (groups) {
  434. HKEY key;
  435. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, NSSM_REGISTRY_GROUPS, 0, KEY_READ, &key)) {
  436. _ftprintf(stderr, _T("%s: %s\n"), NSSM_REGISTRY_GROUPS, error_string(GetLastError()));
  437. return 2;
  438. }
  439. unsigned long type;
  440. unsigned long groupslen;
  441. unsigned long ret = RegQueryValueEx(key, NSSM_REG_GROUPS, 0, &type, NULL, &groupslen);
  442. if (ret == ERROR_SUCCESS) {
  443. groups = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, groupslen);
  444. if (! groups) {
  445. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("groups"), _T("set_service_dependencies()"));
  446. return 3;
  447. }
  448. ret = RegQueryValueEx(key, NSSM_REG_GROUPS, 0, &type, (unsigned char *) groups, &groupslen);
  449. if (ret != ERROR_SUCCESS) {
  450. _ftprintf(stderr, _T("%s\\%s: %s"), NSSM_REGISTRY_GROUPS, NSSM_REG_GROUPS, error_string(GetLastError()));
  451. HeapFree(GetProcessHeap(), 0, groups);
  452. RegCloseKey(key);
  453. return 4;
  454. }
  455. }
  456. else if (ret != ERROR_FILE_NOT_FOUND) {
  457. _ftprintf(stderr, _T("%s\\%s: %s"), NSSM_REGISTRY_GROUPS, NSSM_REG_GROUPS, error_string(GetLastError()));
  458. RegCloseKey(key);
  459. return 4;
  460. }
  461. RegCloseKey(key);
  462. }
  463. unsigned long dependencieslen = (num_dependencies * SERVICE_NAME_LENGTH) + 2;
  464. dependencies = (TCHAR *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dependencieslen * sizeof(TCHAR));
  465. size_t i = 0;
  466. TCHAR dependency[SERVICE_NAME_LENGTH];
  467. for (s = buffer; *s; s++) {
  468. /* Group? */
  469. if (*s == SC_GROUP_IDENTIFIER) {
  470. TCHAR *group = s + 1;
  471. bool ok = false;
  472. if (*group) {
  473. for (TCHAR *g = groups; *g; g++) {
  474. if (str_equiv(g, group)) {
  475. ok = true;
  476. /* Set canonical name. */
  477. memmove(group, g, _tcslen(g) * sizeof(TCHAR));
  478. break;
  479. }
  480. while (*g) g++;
  481. }
  482. }
  483. if (ok) _sntprintf_s(dependency, _countof(dependency), _TRUNCATE, _T("%s"), s);
  484. else {
  485. HeapFree(GetProcessHeap(), 0, dependencies);
  486. if (groups) HeapFree(GetProcessHeap(), 0, groups);
  487. _ftprintf(stderr, _T("%s: %s"), s, error_string(ERROR_SERVICE_DEPENDENCY_DELETED));
  488. return 5;
  489. }
  490. }
  491. else {
  492. SC_HANDLE dependency_handle = open_service(services, s, SERVICE_QUERY_STATUS, dependency, _countof(dependency));
  493. if (! dependency_handle) {
  494. HeapFree(GetProcessHeap(), 0, dependencies);
  495. if (groups) HeapFree(GetProcessHeap(), 0, groups);
  496. CloseServiceHandle(services);
  497. _ftprintf(stderr, _T("%s: %s"), s, error_string(ERROR_SERVICE_DEPENDENCY_DELETED));
  498. return 5;
  499. }
  500. }
  501. size_t len = _tcslen(dependency) + 1;
  502. memmove(dependencies + i, dependency, len * sizeof(TCHAR));
  503. i += len;
  504. while (*s) s++;
  505. }
  506. if (groups) HeapFree(GetProcessHeap(), 0, groups);
  507. CloseServiceHandle(services);
  508. }
  509. if (! ChangeServiceConfig(service_handle, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, 0, 0, 0, dependencies, 0, 0, 0)) {
  510. if (num_dependencies) HeapFree(GetProcessHeap(), 0, dependencies);
  511. print_message(stderr, NSSM_MESSAGE_CHANGESERVICECONFIG_FAILED, error_string(GetLastError()));
  512. return -1;
  513. }
  514. if (num_dependencies) HeapFree(GetProcessHeap(), 0, dependencies);
  515. return 0;
  516. }
  517. int get_service_dependencies(const TCHAR *service_name, SC_HANDLE service_handle, TCHAR **buffer, unsigned long *bufsize, int type) {
  518. if (! buffer) return 1;
  519. if (! bufsize) return 2;
  520. *buffer = 0;
  521. *bufsize = 0;
  522. QUERY_SERVICE_CONFIG *qsc = query_service_config(service_name, service_handle);
  523. if (! qsc) return 3;
  524. if (! qsc->lpDependencies || ! qsc->lpDependencies[0]) {
  525. HeapFree(GetProcessHeap(), 0, qsc);
  526. return 0;
  527. }
  528. /* lpDependencies is doubly NULL terminated. */
  529. while (qsc->lpDependencies[*bufsize]) {
  530. while (qsc->lpDependencies[*bufsize]) ++*bufsize;
  531. ++*bufsize;
  532. }
  533. *bufsize += 2;
  534. *buffer = (TCHAR *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *bufsize * sizeof(TCHAR));
  535. if (! *buffer) {
  536. *bufsize = 0;
  537. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("lpDependencies"), _T("get_service_dependencies()"));
  538. HeapFree(GetProcessHeap(), 0, qsc);
  539. return 4;
  540. }
  541. if (type == DEPENDENCY_ALL) memmove(*buffer, qsc->lpDependencies, *bufsize * sizeof(TCHAR));
  542. else {
  543. TCHAR *s;
  544. size_t i = 0;
  545. *bufsize = 0;
  546. for (s = qsc->lpDependencies; *s; s++) {
  547. /* Only copy the appropriate type of dependency. */
  548. if ((*s == SC_GROUP_IDENTIFIER && type & DEPENDENCY_GROUPS) || (*s != SC_GROUP_IDENTIFIER && type & DEPENDENCY_SERVICES)) {
  549. size_t len = _tcslen(s) + 1;
  550. *bufsize += (unsigned long) len;
  551. memmove(*buffer + i, s, len * sizeof(TCHAR));
  552. i += len;
  553. }
  554. while (*s) s++;
  555. }
  556. ++*bufsize;
  557. }
  558. HeapFree(GetProcessHeap(), 0, qsc);
  559. if (! *buffer[0]) {
  560. HeapFree(GetProcessHeap(), 0, *buffer);
  561. *buffer = 0;
  562. *bufsize = 0;
  563. }
  564. return 0;
  565. }
  566. int get_service_dependencies(const TCHAR *service_name, SC_HANDLE service_handle, TCHAR **buffer, unsigned long *bufsize) {
  567. return get_service_dependencies(service_name, service_handle, buffer, bufsize, DEPENDENCY_ALL);
  568. }
  569. int set_service_description(const TCHAR *service_name, SC_HANDLE service_handle, TCHAR *buffer) {
  570. SERVICE_DESCRIPTION description;
  571. ZeroMemory(&description, sizeof(description));
  572. /*
  573. lpDescription must be NULL if we aren't changing, the new description
  574. or "".
  575. */
  576. if (buffer && buffer[0]) description.lpDescription = buffer;
  577. else description.lpDescription = _T("");
  578. if (ChangeServiceConfig2(service_handle, SERVICE_CONFIG_DESCRIPTION, &description)) return 0;
  579. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SERVICE_CONFIG_DESCRIPTION_FAILED, service_name, error_string(GetLastError()), 0);
  580. return 1;
  581. }
  582. int get_service_description(const TCHAR *service_name, SC_HANDLE service_handle, unsigned long len, TCHAR *buffer) {
  583. if (! buffer) return 1;
  584. unsigned long bufsize;
  585. QueryServiceConfig2(service_handle, SERVICE_CONFIG_DESCRIPTION, 0, 0, &bufsize);
  586. unsigned long error = GetLastError();
  587. if (error == ERROR_INSUFFICIENT_BUFFER) {
  588. SERVICE_DESCRIPTION *description = (SERVICE_DESCRIPTION *) HeapAlloc(GetProcessHeap(), 0, bufsize);
  589. if (! description) {
  590. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("SERVICE_CONFIG_DESCRIPTION"), _T("get_service_description()"));
  591. return 2;
  592. }
  593. if (QueryServiceConfig2(service_handle, SERVICE_CONFIG_DESCRIPTION, (unsigned char *) description, bufsize, &bufsize)) {
  594. if (description->lpDescription) _sntprintf_s(buffer, len, _TRUNCATE, _T("%s"), description->lpDescription);
  595. else ZeroMemory(buffer, len * sizeof(TCHAR));
  596. HeapFree(GetProcessHeap(), 0, description);
  597. return 0;
  598. }
  599. else {
  600. HeapFree(GetProcessHeap(), 0, description);
  601. print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG2_FAILED, service_name, _T("SERVICE_CONFIG_DESCRIPTION"), error_string(error));
  602. return 3;
  603. }
  604. }
  605. else {
  606. print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG2_FAILED, service_name, _T("SERVICE_CONFIG_DESCRIPTION"), error_string(error));
  607. return 4;
  608. }
  609. }
  610. int get_service_startup(const TCHAR *service_name, SC_HANDLE service_handle, const QUERY_SERVICE_CONFIG *qsc, unsigned long *startup) {
  611. if (! qsc) return 1;
  612. switch (qsc->dwStartType) {
  613. case SERVICE_DEMAND_START: *startup = NSSM_STARTUP_MANUAL; break;
  614. case SERVICE_DISABLED: *startup = NSSM_STARTUP_DISABLED; break;
  615. default: *startup = NSSM_STARTUP_AUTOMATIC;
  616. }
  617. if (*startup != NSSM_STARTUP_AUTOMATIC) return 0;
  618. /* Check for delayed start. */
  619. unsigned long bufsize;
  620. unsigned long error;
  621. QueryServiceConfig2(service_handle, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, 0, 0, &bufsize);
  622. error = GetLastError();
  623. if (error == ERROR_INSUFFICIENT_BUFFER) {
  624. SERVICE_DELAYED_AUTO_START_INFO *info = (SERVICE_DELAYED_AUTO_START_INFO *) HeapAlloc(GetProcessHeap(), 0, bufsize);
  625. if (! info) {
  626. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("SERVICE_DELAYED_AUTO_START_INFO"), _T("get_service_startup()"));
  627. return 2;
  628. }
  629. if (QueryServiceConfig2(service_handle, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, (unsigned char *) info, bufsize, &bufsize)) {
  630. if (info->fDelayedAutostart) *startup = NSSM_STARTUP_DELAYED;
  631. HeapFree(GetProcessHeap(), 0, info);
  632. return 0;
  633. }
  634. else {
  635. error = GetLastError();
  636. if (error != ERROR_INVALID_LEVEL) {
  637. print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG2_FAILED, service_name, _T("SERVICE_CONFIG_DELAYED_AUTO_START_INFO"), error_string(error));
  638. return 3;
  639. }
  640. }
  641. }
  642. else if (error != ERROR_INVALID_LEVEL) {
  643. print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG2_FAILED, service_name, _T("SERVICE_DELAYED_AUTO_START_INFO"), error_string(error));
  644. return 3;
  645. }
  646. return 0;
  647. }
  648. int get_service_username(const TCHAR *service_name, const QUERY_SERVICE_CONFIG *qsc, TCHAR **username, size_t *usernamelen) {
  649. if (! username) return 1;
  650. if (! usernamelen) return 1;
  651. *username = 0;
  652. *usernamelen = 0;
  653. if (! qsc) return 1;
  654. if (qsc->lpServiceStartName[0]) {
  655. if (is_localsystem(qsc->lpServiceStartName)) return 0;
  656. size_t len = _tcslen(qsc->lpServiceStartName);
  657. *username = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(TCHAR));
  658. if (! *username) {
  659. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("username"), _T("get_service_username()"));
  660. return 2;
  661. }
  662. memmove(*username, qsc->lpServiceStartName, (len + 1) * sizeof(TCHAR));
  663. *usernamelen = len;
  664. }
  665. return 0;
  666. }
  667. /* Set default values which aren't zero. */
  668. void set_nssm_service_defaults(nssm_service_t *service) {
  669. if (! service) return;
  670. service->type = SERVICE_WIN32_OWN_PROCESS;
  671. service->priority = NORMAL_PRIORITY_CLASS;
  672. service->stdin_sharing = NSSM_STDIN_SHARING;
  673. service->stdin_disposition = NSSM_STDIN_DISPOSITION;
  674. service->stdin_flags = NSSM_STDIN_FLAGS;
  675. service->stdout_sharing = NSSM_STDOUT_SHARING;
  676. service->stdout_disposition = NSSM_STDOUT_DISPOSITION;
  677. service->stdout_flags = NSSM_STDOUT_FLAGS;
  678. service->stderr_sharing = NSSM_STDERR_SHARING;
  679. service->stderr_disposition = NSSM_STDERR_DISPOSITION;
  680. service->stderr_flags = NSSM_STDERR_FLAGS;
  681. service->throttle_delay = NSSM_RESET_THROTTLE_RESTART;
  682. service->stop_method = ~0;
  683. service->kill_console_delay = NSSM_KILL_CONSOLE_GRACE_PERIOD;
  684. service->kill_window_delay = NSSM_KILL_WINDOW_GRACE_PERIOD;
  685. service->kill_threads_delay = NSSM_KILL_THREADS_GRACE_PERIOD;
  686. service->kill_process_tree = 1;
  687. }
  688. /* Allocate and zero memory for a service. */
  689. nssm_service_t *alloc_nssm_service() {
  690. nssm_service_t *service = (nssm_service_t *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(nssm_service_t));
  691. if (! service) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("service"), _T("alloc_nssm_service()"), 0);
  692. return service;
  693. }
  694. /* Free memory for a service. */
  695. void cleanup_nssm_service(nssm_service_t *service) {
  696. if (! service) return;
  697. if (service->username) HeapFree(GetProcessHeap(), 0, service->username);
  698. if (service->password) {
  699. SecureZeroMemory(service->password, service->passwordlen * sizeof(TCHAR));
  700. HeapFree(GetProcessHeap(), 0, service->password);
  701. }
  702. if (service->dependencies) HeapFree(GetProcessHeap(), 0, service->dependencies);
  703. if (service->env) HeapFree(GetProcessHeap(), 0, service->env);
  704. if (service->env_extra) HeapFree(GetProcessHeap(), 0, service->env_extra);
  705. if (service->handle) CloseServiceHandle(service->handle);
  706. if (service->process_handle) CloseHandle(service->process_handle);
  707. if (service->wait_handle) UnregisterWait(service->wait_handle);
  708. if (service->throttle_section_initialised) DeleteCriticalSection(&service->throttle_section);
  709. if (service->throttle_timer) CloseHandle(service->throttle_timer);
  710. if (service->hook_section_initialised) DeleteCriticalSection(&service->hook_section);
  711. if (service->initial_env) HeapFree(GetProcessHeap(), 0, service->initial_env);
  712. HeapFree(GetProcessHeap(), 0, service);
  713. }
  714. /* About to install the service */
  715. int pre_install_service(int argc, TCHAR **argv) {
  716. nssm_service_t *service = alloc_nssm_service();
  717. set_nssm_service_defaults(service);
  718. if (argc) _sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), argv[0]);
  719. /* Show the dialogue box if we didn't give the service name and path */
  720. if (argc < 2) return nssm_gui(IDD_INSTALL, service);
  721. if (! service) {
  722. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("service"), _T("pre_install_service()"));
  723. return 1;
  724. }
  725. _sntprintf_s(service->exe, _countof(service->exe), _TRUNCATE, _T("%s"), argv[1]);
  726. /* Arguments are optional */
  727. size_t flagslen = 0;
  728. size_t s = 0;
  729. int i;
  730. for (i = 2; i < argc; i++) flagslen += _tcslen(argv[i]) + 1;
  731. if (! flagslen) flagslen = 1;
  732. if (flagslen > _countof(service->flags)) {
  733. print_message(stderr, NSSM_MESSAGE_FLAGS_TOO_LONG);
  734. return 2;
  735. }
  736. for (i = 2; i < argc; i++) {
  737. size_t len = _tcslen(argv[i]);
  738. memmove(service->flags + s, argv[i], len * sizeof(TCHAR));
  739. s += len;
  740. if (i < argc - 1) service->flags[s++] = _T(' ');
  741. }
  742. /* Work out directory name */
  743. _sntprintf_s(service->dir, _countof(service->dir), _TRUNCATE, _T("%s"), service->exe);
  744. strip_basename(service->dir);
  745. int ret = install_service(service);
  746. cleanup_nssm_service(service);
  747. return ret;
  748. }
  749. /* About to edit the service. */
  750. int pre_edit_service(int argc, TCHAR **argv) {
  751. /* Require service name. */
  752. if (argc < 2) return usage(1);
  753. /* Are we editing on the command line? */
  754. enum { MODE_EDITING, MODE_GETTING, MODE_SETTING, MODE_RESETTING, MODE_DUMPING } mode = MODE_EDITING;
  755. const TCHAR *verb = argv[0];
  756. const TCHAR *service_name = argv[1];
  757. bool getting = false;
  758. bool unsetting = false;
  759. /* Minimum number of arguments. */
  760. int mandatory = 2;
  761. /* Index of first value. */
  762. int remainder = 3;
  763. int i;
  764. if (str_equiv(verb, _T("get"))) {
  765. mandatory = 3;
  766. mode = MODE_GETTING;
  767. }
  768. else if (str_equiv(verb, _T("set"))) {
  769. mandatory = 4;
  770. mode = MODE_SETTING;
  771. }
  772. else if (str_equiv(verb, _T("reset")) || str_equiv(verb, _T("unset"))) {
  773. mandatory = 3;
  774. mode = MODE_RESETTING;
  775. }
  776. else if (str_equiv(verb, _T("dump"))) {
  777. mandatory = 1;
  778. remainder = 2;
  779. mode = MODE_DUMPING;
  780. }
  781. if (argc < mandatory) return usage(1);
  782. const TCHAR *parameter = 0;
  783. settings_t *setting = 0;
  784. TCHAR *additional;
  785. /* Validate the parameter. */
  786. if (mandatory > 2) {
  787. bool additional_mandatory = false;
  788. parameter = argv[2];
  789. for (i = 0; settings[i].name; i++) {
  790. setting = &settings[i];
  791. if (! str_equiv(setting->name, parameter)) continue;
  792. if (((setting->additional & ADDITIONAL_GETTING) && mode == MODE_GETTING) || ((setting->additional & ADDITIONAL_SETTING) && mode == MODE_SETTING) || ((setting->additional & ADDITIONAL_RESETTING) && mode == MODE_RESETTING)) {
  793. additional_mandatory = true;
  794. mandatory++;
  795. }
  796. break;
  797. }
  798. if (! settings[i].name) {
  799. print_message(stderr, NSSM_MESSAGE_INVALID_PARAMETER, parameter);
  800. for (i = 0; settings[i].name; i++) _ftprintf(stderr, _T("%s\n"), settings[i].name);
  801. return 1;
  802. }
  803. additional = 0;
  804. if (additional_mandatory) {
  805. if (argc < mandatory) {
  806. print_message(stderr, NSSM_MESSAGE_MISSING_SUBPARAMETER, parameter);
  807. return 1;
  808. }
  809. additional = argv[3];
  810. remainder = 4;
  811. }
  812. else if (str_equiv(setting->name, NSSM_NATIVE_OBJECTNAME) && mode == MODE_SETTING) {
  813. additional = argv[3];
  814. remainder = 4;
  815. }
  816. else {
  817. additional = argv[remainder];
  818. if (argc < mandatory) return usage(1);
  819. }
  820. }
  821. nssm_service_t *service = alloc_nssm_service();
  822. _sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), service_name);
  823. /* Open service manager */
  824. SC_HANDLE services = open_service_manager(SC_MANAGER_CONNECT | SC_MANAGER_ENUMERATE_SERVICE);
  825. if (! services) {
  826. print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
  827. return 2;
  828. }
  829. /* Try to open the service */
  830. unsigned long access = SERVICE_QUERY_CONFIG;
  831. if (mode != MODE_GETTING) access |= SERVICE_CHANGE_CONFIG;
  832. service->handle = open_service(services, service->name, access, service->name, _countof(service->name));
  833. if (! service->handle) {
  834. CloseServiceHandle(services);
  835. return 3;
  836. }
  837. /* Get system details. */
  838. QUERY_SERVICE_CONFIG *qsc = query_service_config(service->name, service->handle);
  839. if (! qsc) {
  840. CloseServiceHandle(service->handle);
  841. CloseServiceHandle(services);
  842. return 4;
  843. }
  844. service->type = qsc->dwServiceType;
  845. if (! (service->type & SERVICE_WIN32_OWN_PROCESS)) {
  846. if (mode != MODE_GETTING && mode != MODE_DUMPING) {
  847. HeapFree(GetProcessHeap(), 0, qsc);
  848. CloseServiceHandle(service->handle);
  849. CloseServiceHandle(services);
  850. print_message(stderr, NSSM_MESSAGE_CANNOT_EDIT, service->name, NSSM_WIN32_OWN_PROCESS, 0);
  851. return 3;
  852. }
  853. }
  854. if (get_service_startup(service->name, service->handle, qsc, &service->startup)) {
  855. if (mode != MODE_GETTING && mode != MODE_DUMPING) {
  856. HeapFree(GetProcessHeap(), 0, qsc);
  857. CloseServiceHandle(service->handle);
  858. CloseServiceHandle(services);
  859. return 4;
  860. }
  861. }
  862. if (get_service_username(service->name, qsc, &service->username, &service->usernamelen)) {
  863. if (mode != MODE_GETTING && mode != MODE_DUMPING) {
  864. HeapFree(GetProcessHeap(), 0, qsc);
  865. CloseServiceHandle(service->handle);
  866. CloseServiceHandle(services);
  867. return 5;
  868. }
  869. }
  870. _sntprintf_s(service->displayname, _countof(service->displayname), _TRUNCATE, _T("%s"), qsc->lpDisplayName);
  871. /* Get the canonical service name. We open it case insensitively. */
  872. unsigned long bufsize = _countof(service->name);
  873. GetServiceKeyName(services, service->displayname, service->name, &bufsize);
  874. /* Remember the executable in case it isn't NSSM. */
  875. _sntprintf_s(service->image, _countof(service->image), _TRUNCATE, _T("%s"), qsc->lpBinaryPathName);
  876. HeapFree(GetProcessHeap(), 0, qsc);
  877. /* Get extended system details. */
  878. if (get_service_description(service->name, service->handle, _countof(service->description), service->description)) {
  879. if (mode != MODE_GETTING && mode != MODE_DUMPING) {
  880. CloseServiceHandle(service->handle);
  881. CloseServiceHandle(services);
  882. return 6;
  883. }
  884. }
  885. if (get_service_dependencies(service->name, service->handle, &service->dependencies, &service->dependencieslen)) {
  886. if (mode != MODE_GETTING && mode != MODE_DUMPING) {
  887. CloseServiceHandle(service->handle);
  888. CloseServiceHandle(services);
  889. return 7;
  890. }
  891. }
  892. /* Get NSSM details. */
  893. get_parameters(service, 0);
  894. CloseServiceHandle(services);
  895. if (! service->exe[0]) {
  896. service->native = true;
  897. if (mode != MODE_GETTING && mode != MODE_DUMPING) print_message(stderr, NSSM_MESSAGE_INVALID_SERVICE, service->name, NSSM, service->image);
  898. }
  899. /* Editing with the GUI. */
  900. if (mode == MODE_EDITING) {
  901. nssm_gui(IDD_EDIT, service);
  902. return 0;
  903. }
  904. HKEY key;
  905. value_t value;
  906. int ret;
  907. if (mode == MODE_DUMPING) {
  908. TCHAR *service_name = service->name;
  909. if (argc > remainder) service_name = argv[remainder];
  910. if (service->native) key = 0;
  911. else {
  912. key = open_registry(service->name, KEY_READ);
  913. if (! key) return 4;
  914. }
  915. TCHAR quoted_service_name[SERVICE_NAME_LENGTH * 2];
  916. TCHAR quoted_exe[EXE_LENGTH * 2];
  917. TCHAR quoted_nssm[EXE_LENGTH * 2];
  918. if (quote(service_name, quoted_service_name, _countof(quoted_service_name))) return 5;
  919. if (quote(service->exe, quoted_exe, _countof(quoted_exe))) return 6;
  920. if (quote(nssm_exe(), quoted_nssm, _countof(quoted_nssm))) return 6;
  921. _tprintf(_T("%s install %s %s\n"), quoted_nssm, quoted_service_name, quoted_exe);
  922. ret = 0;
  923. for (i = 0; settings[i].name; i++) {
  924. setting = &settings[i];
  925. if (! setting->native && service->native) continue;
  926. if (dump_setting(service_name, key, service->handle, setting)) ret++;
  927. }
  928. if (! service->native) RegCloseKey(key);
  929. CloseServiceHandle(service->handle);
  930. if (ret) return 1;
  931. return 0;
  932. }
  933. /* Trying to manage App* parameters for a non-NSSM service. */
  934. if (! setting->native && service->native) {
  935. CloseServiceHandle(service->handle);
  936. print_message(stderr, NSSM_MESSAGE_NATIVE_PARAMETER, setting->name, NSSM);
  937. return 1;
  938. }
  939. if (mode == MODE_GETTING) {
  940. if (! service->native) {
  941. key = open_registry(service->name, KEY_READ);
  942. if (! key) return 4;
  943. }
  944. if (setting->native) ret = get_setting(service->name, service->handle, setting, &value, additional);
  945. else ret = get_setting(service->name, key, setting, &value, additional);
  946. if (ret < 0) {
  947. CloseServiceHandle(service->handle);
  948. return 5;
  949. }
  950. switch (setting->type) {
  951. case REG_EXPAND_SZ:
  952. case REG_MULTI_SZ:
  953. case REG_SZ:
  954. _tprintf(_T("%s\n"), value.string ? value.string : _T(""));
  955. HeapFree(GetProcessHeap(), 0, value.string);
  956. break;
  957. case REG_DWORD:
  958. _tprintf(_T("%lu\n"), value.numeric);
  959. break;
  960. }
  961. if (! service->native) RegCloseKey(key);
  962. CloseServiceHandle(service->handle);
  963. return 0;
  964. }
  965. /* Build the value. */
  966. if (mode == MODE_RESETTING) {
  967. /* Unset the parameter. */
  968. value.string = 0;
  969. }
  970. else if (remainder == argc) {
  971. value.string = 0;
  972. }
  973. else {
  974. /* Set the parameter. */
  975. size_t len = 0;
  976. size_t delimiterlen = (setting->additional & ADDITIONAL_CRLF) ? 2 : 1;
  977. for (i = remainder; i < argc; i++) len += _tcslen(argv[i]) + delimiterlen;
  978. len++;
  979. value.string = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, len * sizeof(TCHAR));
  980. if (! value.string) {
  981. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("value"), _T("edit_service()"));
  982. CloseServiceHandle(service->handle);
  983. return 2;
  984. }
  985. size_t s = 0;
  986. for (i = remainder; i < argc; i++) {
  987. size_t len = _tcslen(argv[i]);
  988. memmove(value.string + s, argv[i], len * sizeof(TCHAR));
  989. s += len;
  990. if (i < argc - 1) {
  991. if (setting->additional & ADDITIONAL_CRLF) {
  992. value.string[s++] = _T('\r');
  993. value.string[s++] = _T('\n');
  994. }
  995. else value.string[s++] = _T(' ');
  996. }
  997. }
  998. value.string[s] = _T('\0');
  999. }
  1000. if (! service->native) {
  1001. key = open_registry(service->name, KEY_READ | KEY_WRITE);
  1002. if (! key) {
  1003. if (value.string) HeapFree(GetProcessHeap(), 0, value.string);
  1004. return 4;
  1005. }
  1006. }
  1007. if (setting->native) ret = set_setting(service->name, service->handle, setting, &value, additional);
  1008. else ret = set_setting(service->name, key, setting, &value, additional);
  1009. if (value.string) HeapFree(GetProcessHeap(), 0, value.string);
  1010. if (ret < 0) {
  1011. if (! service->native) RegCloseKey(key);
  1012. CloseServiceHandle(service->handle);
  1013. return 6;
  1014. }
  1015. if (! service->native) RegCloseKey(key);
  1016. CloseServiceHandle(service->handle);
  1017. return 0;
  1018. }
  1019. /* About to remove the service */
  1020. int pre_remove_service(int argc, TCHAR **argv) {
  1021. nssm_service_t *service = alloc_nssm_service();
  1022. set_nssm_service_defaults(service);
  1023. if (argc) _sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), argv[0]);
  1024. /* Show dialogue box if we didn't pass service name and "confirm" */
  1025. if (argc < 2) return nssm_gui(IDD_REMOVE, service);
  1026. if (str_equiv(argv[1], _T("confirm"))) {
  1027. int ret = remove_service(service);
  1028. cleanup_nssm_service(service);
  1029. return ret;
  1030. }
  1031. print_message(stderr, NSSM_MESSAGE_PRE_REMOVE_SERVICE);
  1032. return 100;
  1033. }
  1034. /* Install the service */
  1035. int install_service(nssm_service_t *service) {
  1036. if (! service) return 1;
  1037. /* Open service manager */
  1038. SC_HANDLE services = open_service_manager(SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE);
  1039. if (! services) {
  1040. print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
  1041. cleanup_nssm_service(service);
  1042. return 2;
  1043. }
  1044. /* Get path of this program */
  1045. _sntprintf_s(service->image, _countof(service->image), _TRUNCATE, _T("%s"), nssm_imagepath());
  1046. /* Create the service - settings will be changed in edit_service() */
  1047. 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);
  1048. if (! service->handle) {
  1049. print_message(stderr, NSSM_MESSAGE_CREATESERVICE_FAILED, error_string(GetLastError()));
  1050. CloseServiceHandle(services);
  1051. return 5;
  1052. }
  1053. if (edit_service(service, false)) {
  1054. DeleteService(service->handle);
  1055. CloseServiceHandle(services);
  1056. return 6;
  1057. }
  1058. print_message(stdout, NSSM_MESSAGE_SERVICE_INSTALLED, service->name);
  1059. /* Cleanup */
  1060. CloseServiceHandle(services);
  1061. return 0;
  1062. }
  1063. /* Edit the service. */
  1064. int edit_service(nssm_service_t *service, bool editing) {
  1065. if (! service) return 1;
  1066. /*
  1067. The only two valid flags for service type are SERVICE_WIN32_OWN_PROCESS
  1068. and SERVICE_INTERACTIVE_PROCESS.
  1069. */
  1070. service->type &= SERVICE_INTERACTIVE_PROCESS;
  1071. service->type |= SERVICE_WIN32_OWN_PROCESS;
  1072. /* Startup type. */
  1073. unsigned long startup;
  1074. switch (service->startup) {
  1075. case NSSM_STARTUP_MANUAL: startup = SERVICE_DEMAND_START; break;
  1076. case NSSM_STARTUP_DISABLED: startup = SERVICE_DISABLED; break;
  1077. default: startup = SERVICE_AUTO_START;
  1078. }
  1079. /* Display name. */
  1080. if (! service->displayname[0]) _sntprintf_s(service->displayname, _countof(service->displayname), _TRUNCATE, _T("%s"), service->name);
  1081. /*
  1082. Username must be NULL if we aren't changing or an account name.
  1083. We must explicitly use LOCALSYSTEM to change it when we are editing.
  1084. Password must be NULL if we aren't changing, a password or "".
  1085. Empty passwords are valid but we won't allow them in the GUI.
  1086. */
  1087. TCHAR *username = 0;
  1088. TCHAR *canon = 0;
  1089. TCHAR *password = 0;
  1090. boolean virtual_account = false;
  1091. if (service->usernamelen) {
  1092. username = service->username;
  1093. if (is_virtual_account(service->name, username)) {
  1094. virtual_account = true;
  1095. canon = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, (service->usernamelen + 1) * sizeof(TCHAR));
  1096. if (! canon) {
  1097. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("canon"), _T("edit_service()"));
  1098. return 5;
  1099. }
  1100. memmove(canon, username, (service->usernamelen + 1) * sizeof(TCHAR));
  1101. }
  1102. else {
  1103. if (canonicalise_username(username, &canon)) return 5;
  1104. if (service->passwordlen) password = service->password;
  1105. }
  1106. }
  1107. else if (editing) username = canon = NSSM_LOCALSYSTEM_ACCOUNT;
  1108. if (! virtual_account) {
  1109. if (well_known_username(canon)) password = _T("");
  1110. else {
  1111. if (grant_logon_as_service(canon)) {
  1112. if (canon != username) HeapFree(GetProcessHeap(), 0, canon);
  1113. print_message(stderr, NSSM_MESSAGE_GRANT_LOGON_AS_SERVICE_FAILED, username);
  1114. return 5;
  1115. }
  1116. }
  1117. }
  1118. TCHAR *dependencies = _T("");
  1119. if (service->dependencieslen) dependencies = 0; /* Change later. */
  1120. if (! ChangeServiceConfig(service->handle, service->type, startup, SERVICE_NO_CHANGE, 0, 0, 0, dependencies, canon, password, service->displayname)) {
  1121. if (canon != username) HeapFree(GetProcessHeap(), 0, canon);
  1122. print_message(stderr, NSSM_MESSAGE_CHANGESERVICECONFIG_FAILED, error_string(GetLastError()));
  1123. return 5;
  1124. }
  1125. if (canon != username) HeapFree(GetProcessHeap(), 0, canon);
  1126. if (service->dependencieslen) {
  1127. if (set_service_dependencies(service->name, service->handle, service->dependencies)) return 5;
  1128. }
  1129. if (service->description[0] || editing) {
  1130. set_service_description(service->name, service->handle, service->description);
  1131. }
  1132. SERVICE_DELAYED_AUTO_START_INFO delayed;
  1133. ZeroMemory(&delayed, sizeof(delayed));
  1134. if (service->startup == NSSM_STARTUP_DELAYED) delayed.fDelayedAutostart = 1;
  1135. else delayed.fDelayedAutostart = 0;
  1136. /* Delayed startup isn't supported until Vista. */
  1137. if (! ChangeServiceConfig2(service->handle, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, &delayed)) {
  1138. unsigned long error = GetLastError();
  1139. /* Pre-Vista we expect to fail with ERROR_INVALID_LEVEL */
  1140. if (error != ERROR_INVALID_LEVEL) {
  1141. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SERVICE_CONFIG_DELAYED_AUTO_START_INFO_FAILED, service->name, error_string(error), 0);
  1142. }
  1143. }
  1144. /* Don't mess with parameters which aren't ours. */
  1145. if (! service->native) {
  1146. /* Now we need to put the parameters into the registry */
  1147. if (create_parameters(service, editing)) {
  1148. print_message(stderr, NSSM_MESSAGE_CREATE_PARAMETERS_FAILED);
  1149. return 6;
  1150. }
  1151. set_service_recovery(service);
  1152. }
  1153. return 0;
  1154. }
  1155. /* Control a service. */
  1156. int control_service(unsigned long control, int argc, TCHAR **argv, bool return_status) {
  1157. if (argc < 1) return usage(1);
  1158. TCHAR *service_name = argv[0];
  1159. TCHAR canonical_name[SERVICE_NAME_LENGTH];
  1160. SC_HANDLE services = open_service_manager(SC_MANAGER_CONNECT | SC_MANAGER_ENUMERATE_SERVICE);
  1161. if (! services) {
  1162. print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
  1163. if (return_status) return 0;
  1164. return 2;
  1165. }
  1166. unsigned long access = SERVICE_QUERY_STATUS;
  1167. switch (control) {
  1168. case NSSM_SERVICE_CONTROL_START:
  1169. access |= SERVICE_START;
  1170. break;
  1171. case SERVICE_CONTROL_CONTINUE:
  1172. case SERVICE_CONTROL_PAUSE:
  1173. access |= SERVICE_PAUSE_CONTINUE;
  1174. break;
  1175. case SERVICE_CONTROL_STOP:
  1176. access |= SERVICE_STOP;
  1177. break;
  1178. case NSSM_SERVICE_CONTROL_ROTATE:
  1179. access |= SERVICE_USER_DEFINED_CONTROL;
  1180. break;
  1181. }
  1182. SC_HANDLE service_handle = open_service(services, service_name, access, canonical_name, _countof(canonical_name));
  1183. if (! service_handle) {
  1184. CloseServiceHandle(services);
  1185. if (return_status) return 0;
  1186. return 3;
  1187. }
  1188. int ret;
  1189. unsigned long error;
  1190. SERVICE_STATUS service_status;
  1191. if (control == NSSM_SERVICE_CONTROL_START) {
  1192. unsigned long initial_status = SERVICE_STOPPED;
  1193. ret = StartService(service_handle, (unsigned long) argc, (const TCHAR **) argv);
  1194. error = GetLastError();
  1195. CloseServiceHandle(services);
  1196. if (error == ERROR_IO_PENDING) {
  1197. /*
  1198. Older versions of Windows return immediately with ERROR_IO_PENDING
  1199. indicate that the operation is still in progress. Newer versions
  1200. will return it if there really is a delay.
  1201. */
  1202. ret = 1;
  1203. error = ERROR_SUCCESS;
  1204. }
  1205. if (ret) {
  1206. unsigned long cutoff = 0;
  1207. /* If we manage the service, respect the throttle time. */
  1208. HKEY key = open_registry(service_name, 0, KEY_READ, false);
  1209. if (key) {
  1210. if (get_number(key, NSSM_REG_THROTTLE, &cutoff, false) != 1) cutoff = NSSM_RESET_THROTTLE_RESTART;
  1211. RegCloseKey(key);
  1212. }
  1213. int response = await_service_control_response(control, service_handle, &service_status, initial_status, cutoff);
  1214. CloseServiceHandle(service_handle);
  1215. if (response) {
  1216. print_message(stderr, NSSM_MESSAGE_BAD_CONTROL_RESPONSE, canonical_name, service_status_text(service_status.dwCurrentState), service_control_text(control));
  1217. if (return_status) return 0;
  1218. return 1;
  1219. }
  1220. else _tprintf(_T("%s: %s: %s"), canonical_name, service_control_text(control), error_string(error));
  1221. return 0;
  1222. }
  1223. else {
  1224. CloseServiceHandle(service_handle);
  1225. _ftprintf(stderr, _T("%s: %s: %s"), canonical_name, service_control_text(control), error_string(error));
  1226. if (return_status) return 0;
  1227. return 1;
  1228. }
  1229. }
  1230. else if (control == SERVICE_CONTROL_INTERROGATE) {
  1231. /*
  1232. We could actually send an INTERROGATE control but that won't return
  1233. any information if the service is stopped and we don't care about
  1234. the extra details it might give us in any case. So we'll fake it.
  1235. */
  1236. ret = QueryServiceStatus(service_handle, &service_status);
  1237. error = GetLastError();
  1238. if (ret) {
  1239. _tprintf(_T("%s\n"), service_status_text(service_status.dwCurrentState));
  1240. if (return_status) return service_status.dwCurrentState;
  1241. return 0;
  1242. }
  1243. else {
  1244. _ftprintf(stderr, _T("%s: %s\n"), canonical_name, error_string(error));
  1245. if (return_status) return 0;
  1246. return 1;
  1247. }
  1248. }
  1249. else {
  1250. ret = ControlService(service_handle, control, &service_status);
  1251. unsigned long initial_status = service_status.dwCurrentState;
  1252. error = GetLastError();
  1253. CloseServiceHandle(services);
  1254. if (error == ERROR_IO_PENDING) {
  1255. ret = 1;
  1256. error = ERROR_SUCCESS;
  1257. }
  1258. if (ret) {
  1259. int response = await_service_control_response(control, service_handle, &service_status, initial_status);
  1260. CloseServiceHandle(service_handle);
  1261. if (response) {
  1262. print_message(stderr, NSSM_MESSAGE_BAD_CONTROL_RESPONSE, canonical_name, service_status_text(service_status.dwCurrentState), service_control_text(control));
  1263. if (return_status) return 0;
  1264. return 1;
  1265. }
  1266. else _tprintf(_T("%s: %s: %s"), canonical_name, service_control_text(control), error_string(error));
  1267. if (return_status) return service_status.dwCurrentState;
  1268. return 0;
  1269. }
  1270. else {
  1271. CloseServiceHandle(service_handle);
  1272. _ftprintf(stderr, _T("%s: %s: %s"), canonical_name, service_control_text(control), error_string(error));
  1273. if (error == ERROR_SERVICE_NOT_ACTIVE) {
  1274. if (control == SERVICE_CONTROL_SHUTDOWN || control == SERVICE_CONTROL_STOP) {
  1275. if (return_status) return SERVICE_STOPPED;
  1276. return 0;
  1277. }
  1278. }
  1279. if (return_status) return 0;
  1280. return 1;
  1281. }
  1282. }
  1283. }
  1284. int control_service(unsigned long control, int argc, TCHAR **argv) {
  1285. return control_service(control, argc, argv, false);
  1286. }
  1287. /* Remove the service */
  1288. int remove_service(nssm_service_t *service) {
  1289. if (! service) return 1;
  1290. /* Open service manager */
  1291. SC_HANDLE services = open_service_manager(SC_MANAGER_CONNECT | SC_MANAGER_ENUMERATE_SERVICE);
  1292. if (! services) {
  1293. print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
  1294. return 2;
  1295. }
  1296. /* Try to open the service */
  1297. service->handle = open_service(services, service->name, DELETE, service->name, _countof(service->name));
  1298. if (! service->handle) {
  1299. CloseServiceHandle(services);
  1300. return 3;
  1301. }
  1302. /* Get the canonical service name. We open it case insensitively. */
  1303. unsigned long bufsize = _countof(service->displayname);
  1304. GetServiceDisplayName(services, service->name, service->displayname, &bufsize);
  1305. bufsize = _countof(service->name);
  1306. GetServiceKeyName(services, service->displayname, service->name, &bufsize);
  1307. /* Try to delete the service */
  1308. if (! DeleteService(service->handle)) {
  1309. print_message(stderr, NSSM_MESSAGE_DELETESERVICE_FAILED);
  1310. CloseServiceHandle(services);
  1311. return 4;
  1312. }
  1313. /* Cleanup */
  1314. CloseServiceHandle(services);
  1315. print_message(stdout, NSSM_MESSAGE_SERVICE_REMOVED, service->name);
  1316. return 0;
  1317. }
  1318. /* Service initialisation */
  1319. void WINAPI service_main(unsigned long argc, TCHAR **argv) {
  1320. nssm_service_t *service = alloc_nssm_service();
  1321. if (! service) return;
  1322. static volatile bool await_debugger = (argc > 1 && str_equiv(argv[1], _T("debug")));
  1323. while (await_debugger) Sleep(1000);
  1324. if (_sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), argv[0]) < 0) {
  1325. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("service->name"), _T("service_main()"), 0);
  1326. return;
  1327. }
  1328. /* We can use a condition variable in a critical section on Vista or later. */
  1329. if (imports.SleepConditionVariableCS && imports.WakeConditionVariable) use_critical_section = true;
  1330. else use_critical_section = false;
  1331. /* Initialise status */
  1332. ZeroMemory(&service->status, sizeof(service->status));
  1333. service->status.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS;
  1334. service->status.dwControlsAccepted = 0;
  1335. service->status.dwWin32ExitCode = NO_ERROR;
  1336. service->status.dwServiceSpecificExitCode = 0;
  1337. service->status.dwCheckPoint = 0;
  1338. service->status.dwWaitHint = NSSM_WAITHINT_MARGIN;
  1339. /* Signal we AREN'T running the server */
  1340. service->process_handle = 0;
  1341. service->pid = 0;
  1342. /* Register control handler */
  1343. service->status_handle = RegisterServiceCtrlHandlerEx(NSSM, service_control_handler, (void *) service);
  1344. if (! service->status_handle) {
  1345. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_REGISTERSERVICECTRLHANDER_FAILED, error_string(GetLastError()), 0);
  1346. return;
  1347. }
  1348. log_service_control(service->name, 0, true);
  1349. service->status.dwCurrentState = SERVICE_START_PENDING;
  1350. service->status.dwWaitHint = service->throttle_delay + NSSM_WAITHINT_MARGIN;
  1351. SetServiceStatus(service->status_handle, &service->status);
  1352. if (is_admin) {
  1353. /* Try to create the exit action parameters; we don't care if it fails */
  1354. create_exit_action(service->name, exit_action_strings[0], false);
  1355. SC_HANDLE services = open_service_manager(SC_MANAGER_CONNECT);
  1356. if (services) {
  1357. service->handle = open_service(services, service->name, SERVICE_CHANGE_CONFIG, 0, 0);
  1358. set_service_recovery(service);
  1359. /* Remember our display name. */
  1360. unsigned long displayname_len = _countof(service->displayname);
  1361. GetServiceDisplayName(services, service->name, service->displayname, &displayname_len);
  1362. CloseServiceHandle(services);
  1363. }
  1364. }
  1365. /* Used for signalling a resume if the service pauses when throttled. */
  1366. if (use_critical_section) {
  1367. InitializeCriticalSection(&service->throttle_section);
  1368. service->throttle_section_initialised = true;
  1369. }
  1370. else {
  1371. service->throttle_timer = CreateWaitableTimer(0, 1, 0);
  1372. if (! service->throttle_timer) {
  1373. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_CREATEWAITABLETIMER_FAILED, service->name, error_string(GetLastError()), 0);
  1374. }
  1375. }
  1376. /* Critical section for hooks. */
  1377. InitializeCriticalSection(&service->hook_section);
  1378. service->hook_section_initialised = true;
  1379. /* Remember our initial environment. */
  1380. service->initial_env = copy_environment();
  1381. /* Remember our creation time. */
  1382. if (get_process_creation_time(GetCurrentProcess(), &service->nssm_creation_time)) ZeroMemory(&service->nssm_creation_time, sizeof(service->nssm_creation_time));
  1383. service->allow_restart = true;
  1384. if (! CreateThread(NULL, 0, launch_service, (void *) service, 0, NULL)) {
  1385. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATETHREAD_FAILED, error_string(GetLastError()), 0);
  1386. stop_service(service, 0, true, true);
  1387. }
  1388. }
  1389. /* Make sure service recovery actions are taken where necessary */
  1390. void set_service_recovery(nssm_service_t *service) {
  1391. SERVICE_FAILURE_ACTIONS_FLAG flag;
  1392. ZeroMemory(&flag, sizeof(flag));
  1393. flag.fFailureActionsOnNonCrashFailures = true;
  1394. /* This functionality was added in Vista so the call may fail */
  1395. if (! ChangeServiceConfig2(service->handle, SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, &flag)) {
  1396. unsigned long error = GetLastError();
  1397. /* Pre-Vista we expect to fail with ERROR_INVALID_LEVEL */
  1398. if (error != ERROR_INVALID_LEVEL) {
  1399. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SERVICE_CONFIG_FAILURE_ACTIONS_FAILED, service->name, error_string(error), 0);
  1400. }
  1401. }
  1402. }
  1403. int monitor_service(nssm_service_t *service) {
  1404. /* Set service status to started */
  1405. int ret = start_service(service);
  1406. if (ret) {
  1407. TCHAR code[16];
  1408. _sntprintf_s(code, _countof(code), _TRUNCATE, _T("%d"), ret);
  1409. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_START_SERVICE_FAILED, service->exe, service->name, ret, 0);
  1410. return ret;
  1411. }
  1412. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_STARTED_SERVICE, service->exe, service->flags, service->name, service->dir, 0);
  1413. /* Monitor service */
  1414. if (! RegisterWaitForSingleObject(&service->wait_handle, service->process_handle, end_service, (void *) service, INFINITE, WT_EXECUTEONLYONCE | WT_EXECUTELONGFUNCTION)) {
  1415. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_REGISTERWAITFORSINGLEOBJECT_FAILED, service->name, service->exe, error_string(GetLastError()), 0);
  1416. }
  1417. return 0;
  1418. }
  1419. TCHAR *service_control_text(unsigned long control) {
  1420. switch (control) {
  1421. /* HACK: there is no SERVICE_CONTROL_START constant */
  1422. case NSSM_SERVICE_CONTROL_START: return _T("START");
  1423. case SERVICE_CONTROL_STOP: return _T("STOP");
  1424. case SERVICE_CONTROL_SHUTDOWN: return _T("SHUTDOWN");
  1425. case SERVICE_CONTROL_PAUSE: return _T("PAUSE");
  1426. case SERVICE_CONTROL_CONTINUE: return _T("CONTINUE");
  1427. case SERVICE_CONTROL_INTERROGATE: return _T("INTERROGATE");
  1428. case NSSM_SERVICE_CONTROL_ROTATE: return _T("ROTATE");
  1429. case SERVICE_CONTROL_POWEREVENT: return _T("POWEREVENT");
  1430. default: return 0;
  1431. }
  1432. }
  1433. TCHAR *service_status_text(unsigned long status) {
  1434. switch (status) {
  1435. case SERVICE_STOPPED: return _T("SERVICE_STOPPED");
  1436. case SERVICE_START_PENDING: return _T("SERVICE_START_PENDING");
  1437. case SERVICE_STOP_PENDING: return _T("SERVICE_STOP_PENDING");
  1438. case SERVICE_RUNNING: return _T("SERVICE_RUNNING");
  1439. case SERVICE_CONTINUE_PENDING: return _T("SERVICE_CONTINUE_PENDING");
  1440. case SERVICE_PAUSE_PENDING: return _T("SERVICE_PAUSE_PENDING");
  1441. case SERVICE_PAUSED: return _T("SERVICE_PAUSED");
  1442. default: return 0;
  1443. }
  1444. }
  1445. void log_service_control(TCHAR *service_name, unsigned long control, bool handled) {
  1446. TCHAR *text = service_control_text(control);
  1447. unsigned long event;
  1448. if (! text) {
  1449. /* "0x" + 8 x hex + NULL */
  1450. text = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, 11 * sizeof(TCHAR));
  1451. if (! text) {
  1452. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("control code"), _T("log_service_control()"), 0);
  1453. return;
  1454. }
  1455. if (_sntprintf_s(text, 11, _TRUNCATE, _T("0x%08x"), control) < 0) {
  1456. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("control code"), _T("log_service_control()"), 0);
  1457. HeapFree(GetProcessHeap(), 0, text);
  1458. return;
  1459. }
  1460. event = NSSM_EVENT_SERVICE_CONTROL_UNKNOWN;
  1461. }
  1462. else if (handled) event = NSSM_EVENT_SERVICE_CONTROL_HANDLED;
  1463. else event = NSSM_EVENT_SERVICE_CONTROL_NOT_HANDLED;
  1464. log_event(EVENTLOG_INFORMATION_TYPE, event, service_name, text, 0);
  1465. if (event == NSSM_EVENT_SERVICE_CONTROL_UNKNOWN) {
  1466. HeapFree(GetProcessHeap(), 0, text);
  1467. }
  1468. }
  1469. /* Service control handler */
  1470. unsigned long WINAPI service_control_handler(unsigned long control, unsigned long event, void *data, void *context) {
  1471. nssm_service_t *service = (nssm_service_t *) context;
  1472. switch (control) {
  1473. case SERVICE_CONTROL_INTERROGATE:
  1474. /* We always keep the service status up-to-date so this is a no-op. */
  1475. return NO_ERROR;
  1476. case SERVICE_CONTROL_SHUTDOWN:
  1477. case SERVICE_CONTROL_STOP:
  1478. service->last_control = control;
  1479. log_service_control(service->name, control, true);
  1480. /* Immediately block further controls. */
  1481. service->allow_restart = false;
  1482. service->status.dwCurrentState = SERVICE_STOP_PENDING;
  1483. service->status.dwControlsAccepted = 0;
  1484. SetServiceStatus(service->status_handle, &service->status);
  1485. /* Pre-stop hook. */
  1486. nssm_hook(&hook_threads, service, NSSM_HOOK_EVENT_STOP, NSSM_HOOK_ACTION_PRE, &control, NSSM_SERVICE_STATUS_DEADLINE, false);
  1487. /*
  1488. We MUST acknowledge the stop request promptly but we're committed to
  1489. waiting for the application to exit. Spawn a new thread to wait
  1490. while we acknowledge the request.
  1491. */
  1492. if (! CreateThread(NULL, 0, shutdown_service, context, 0, NULL)) {
  1493. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATETHREAD_FAILED, error_string(GetLastError()), 0);
  1494. /*
  1495. We couldn't create a thread to tidy up so we'll have to force the tidyup
  1496. to complete in time in this thread.
  1497. */
  1498. service->kill_console_delay = NSSM_KILL_CONSOLE_GRACE_PERIOD;
  1499. service->kill_window_delay = NSSM_KILL_WINDOW_GRACE_PERIOD;
  1500. service->kill_threads_delay = NSSM_KILL_THREADS_GRACE_PERIOD;
  1501. stop_service(service, 0, true, true);
  1502. }
  1503. return NO_ERROR;
  1504. case SERVICE_CONTROL_CONTINUE:
  1505. service->last_control = control;
  1506. log_service_control(service->name, control, true);
  1507. service->throttle = 0;
  1508. if (use_critical_section) imports.WakeConditionVariable(&service->throttle_condition);
  1509. else {
  1510. if (! service->throttle_timer) return ERROR_CALL_NOT_IMPLEMENTED;
  1511. ZeroMemory(&service->throttle_duetime, sizeof(service->throttle_duetime));
  1512. SetWaitableTimer(service->throttle_timer, &service->throttle_duetime, 0, 0, 0, 0);
  1513. }
  1514. /* We can't continue if the application is running! */
  1515. if (! service->process_handle) service->status.dwCurrentState = SERVICE_CONTINUE_PENDING;
  1516. service->status.dwWaitHint = throttle_milliseconds(service->throttle) + NSSM_WAITHINT_MARGIN;
  1517. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_RESET_THROTTLE, service->name, 0);
  1518. SetServiceStatus(service->status_handle, &service->status);
  1519. return NO_ERROR;
  1520. case SERVICE_CONTROL_PAUSE:
  1521. /*
  1522. We don't accept pause messages but it isn't possible to register
  1523. only for continue messages so we have to handle this case.
  1524. */
  1525. log_service_control(service->name, control, false);
  1526. return ERROR_CALL_NOT_IMPLEMENTED;
  1527. case NSSM_SERVICE_CONTROL_ROTATE:
  1528. service->last_control = control;
  1529. log_service_control(service->name, control, true);
  1530. (void) nssm_hook(&hook_threads, service, NSSM_HOOK_EVENT_ROTATE, NSSM_HOOK_ACTION_PRE, &control, NSSM_HOOK_DEADLINE, false);
  1531. if (service->rotate_stdout_online == NSSM_ROTATE_ONLINE) service->rotate_stdout_online = NSSM_ROTATE_ONLINE_ASAP;
  1532. if (service->rotate_stderr_online == NSSM_ROTATE_ONLINE) service->rotate_stderr_online = NSSM_ROTATE_ONLINE_ASAP;
  1533. (void) nssm_hook(&hook_threads, service, NSSM_HOOK_EVENT_ROTATE, NSSM_HOOK_ACTION_POST, &control);
  1534. return NO_ERROR;
  1535. case SERVICE_CONTROL_POWEREVENT:
  1536. /* Resume from suspend. */
  1537. if (event == PBT_APMRESUMEAUTOMATIC) {
  1538. service->last_control = control;
  1539. log_service_control(service->name, control, true);
  1540. (void) nssm_hook(&hook_threads, service, NSSM_HOOK_EVENT_POWER, NSSM_HOOK_ACTION_RESUME, &control);
  1541. return NO_ERROR;
  1542. }
  1543. /* Battery low or changed to A/C power or something. */
  1544. if (event == PBT_APMPOWERSTATUSCHANGE) {
  1545. service->last_control = control;
  1546. log_service_control(service->name, control, true);
  1547. (void) nssm_hook(&hook_threads, service, NSSM_HOOK_EVENT_POWER, NSSM_HOOK_ACTION_CHANGE, &control);
  1548. return NO_ERROR;
  1549. }
  1550. log_service_control(service->name, control, false);
  1551. return NO_ERROR;
  1552. }
  1553. /* Unknown control */
  1554. log_service_control(service->name, control, false);
  1555. return ERROR_CALL_NOT_IMPLEMENTED;
  1556. }
  1557. /* Start the service */
  1558. int start_service(nssm_service_t *service) {
  1559. service->stopping = false;
  1560. if (service->process_handle) return 0;
  1561. service->start_requested_count++;
  1562. /* Allocate a STARTUPINFO structure for a new process */
  1563. STARTUPINFO si;
  1564. ZeroMemory(&si, sizeof(si));
  1565. si.cb = sizeof(si);
  1566. /* Allocate a PROCESSINFO structure for the process */
  1567. PROCESS_INFORMATION pi;
  1568. ZeroMemory(&pi, sizeof(pi));
  1569. /* Get startup parameters */
  1570. int ret = get_parameters(service, &si);
  1571. if (ret) {
  1572. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GET_PARAMETERS_FAILED, service->name, 0);
  1573. unset_service_environment(service);
  1574. return stop_service(service, 2, true, true);
  1575. }
  1576. /* Launch executable with arguments */
  1577. TCHAR cmd[CMD_LENGTH];
  1578. if (_sntprintf_s(cmd, _countof(cmd), _TRUNCATE, _T("\"%s\" %s"), service->exe, service->flags) < 0) {
  1579. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("command line"), _T("start_service"), 0);
  1580. unset_service_environment(service);
  1581. return stop_service(service, 2, true, true);
  1582. }
  1583. throttle_restart(service);
  1584. service->status.dwCurrentState = SERVICE_START_PENDING;
  1585. service->status.dwControlsAccepted = SERVICE_ACCEPT_POWEREVENT | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_STOP;
  1586. SetServiceStatus(service->status_handle, &service->status);
  1587. unsigned long control = NSSM_SERVICE_CONTROL_START;
  1588. /* Did another thread receive a stop control? */
  1589. if (service->allow_restart) {
  1590. /* Set up I/O redirection. */
  1591. if (get_output_handles(service, &si)) {
  1592. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GET_OUTPUT_HANDLES_FAILED, service->name, 0);
  1593. FreeConsole();
  1594. close_output_handles(&si);
  1595. unset_service_environment(service);
  1596. return stop_service(service, 4, true, true);
  1597. }
  1598. FreeConsole();
  1599. /* Pre-start hook. May need I/O to have been redirected already. */
  1600. if (nssm_hook(&hook_threads, service, NSSM_HOOK_EVENT_START, NSSM_HOOK_ACTION_PRE, &control, NSSM_SERVICE_STATUS_DEADLINE, false) == NSSM_HOOK_STATUS_ABORT) {
  1601. TCHAR code[16];
  1602. _sntprintf_s(code, _countof(code), _TRUNCATE, _T("%lu"), NSSM_HOOK_STATUS_ABORT);
  1603. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_PRESTART_HOOK_ABORT, NSSM_HOOK_EVENT_START, NSSM_HOOK_ACTION_PRE, service->name, code, 0);
  1604. unset_service_environment(service);
  1605. return stop_service(service, 5, true, true);
  1606. }
  1607. /* The pre-start hook will have cleaned the environment. */
  1608. set_service_environment(service);
  1609. bool inherit_handles = false;
  1610. if (si.dwFlags & STARTF_USESTDHANDLES) inherit_handles = true;
  1611. unsigned long flags = service->priority & priority_mask();
  1612. if (service->affinity) flags |= CREATE_SUSPENDED;
  1613. if (! service->no_console) flags |= CREATE_NEW_CONSOLE;
  1614. if (! CreateProcess(0, cmd, 0, 0, inherit_handles, flags, 0, service->dir, &si, &pi)) {
  1615. unsigned long exitcode = 3;
  1616. unsigned long error = GetLastError();
  1617. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEPROCESS_FAILED, service->name, service->exe, error_string(error), 0);
  1618. close_output_handles(&si);
  1619. unset_service_environment(service);
  1620. return stop_service(service, exitcode, true, true);
  1621. }
  1622. service->start_count++;
  1623. service->process_handle = pi.hProcess;
  1624. service->pid = pi.dwProcessId;
  1625. if (get_process_creation_time(service->process_handle, &service->creation_time)) ZeroMemory(&service->creation_time, sizeof(service->creation_time));
  1626. close_output_handles(&si);
  1627. if (service->affinity) {
  1628. /*
  1629. We are explicitly storing service->affinity as a 64-bit unsigned integer
  1630. so that we can parse it regardless of whether we're running in 32-bit
  1631. or 64-bit mode. The arguments to SetProcessAffinityMask(), however, are
  1632. defined as type DWORD_PTR and hence limited to 32 bits on a 32-bit system
  1633. (or when running the 32-bit NSSM).
  1634. The result is a lot of seemingly-unnecessary casting throughout the code
  1635. and potentially confusion when we actually try to start the service.
  1636. Having said that, however, it's unlikely that we're actually going to
  1637. run in 32-bit mode on a system which has more than 32 CPUs so the
  1638. likelihood of seeing a confusing situation is somewhat diminished.
  1639. */
  1640. DWORD_PTR affinity, system_affinity;
  1641. if (GetProcessAffinityMask(service->process_handle, &affinity, &system_affinity)) affinity = service->affinity & system_affinity;
  1642. else {
  1643. affinity = (DWORD_PTR) service->affinity;
  1644. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GETPROCESSAFFINITYMASK_FAILED, service->name, error_string(GetLastError()), 0);
  1645. }
  1646. if (! SetProcessAffinityMask(service->process_handle, affinity)) {
  1647. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_SETPROCESSAFFINITYMASK_FAILED, service->name, error_string(GetLastError()), 0);
  1648. }
  1649. ResumeThread(pi.hThread);
  1650. }
  1651. }
  1652. /* Restore our environment. */
  1653. unset_service_environment(service);
  1654. /*
  1655. Wait for a clean startup before changing the service status to RUNNING
  1656. but be mindful of the fact that we are blocking the service control manager
  1657. so abandon the wait before too much time has elapsed.
  1658. */
  1659. if (await_single_handle(service->status_handle, &service->status, service->process_handle, service->name, _T("start_service"), service->throttle_delay) == 1) service->throttle = 0;
  1660. /* Did another thread receive a stop control? */
  1661. if (! service->allow_restart) return 0;
  1662. /* Signal successful start */
  1663. service->status.dwCurrentState = SERVICE_RUNNING;
  1664. service->status.dwControlsAccepted &= ~SERVICE_ACCEPT_PAUSE_CONTINUE;
  1665. SetServiceStatus(service->status_handle, &service->status);
  1666. /* Post-start hook. */
  1667. if (! service->throttle) {
  1668. (void) nssm_hook(&hook_threads, service, NSSM_HOOK_EVENT_START, NSSM_HOOK_ACTION_POST, &control);
  1669. }
  1670. /* Ensure the restart delay is always applied. */
  1671. if (service->restart_delay && ! service->throttle) service->throttle++;
  1672. return 0;
  1673. }
  1674. /* Stop the service */
  1675. int stop_service(nssm_service_t *service, unsigned long exitcode, bool graceful, bool default_action) {
  1676. service->allow_restart = false;
  1677. if (service->wait_handle) {
  1678. UnregisterWait(service->wait_handle);
  1679. service->wait_handle = 0;
  1680. }
  1681. service->rotate_stdout_online = service->rotate_stderr_online = NSSM_ROTATE_OFFLINE;
  1682. if (default_action && ! exitcode && ! graceful) {
  1683. 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);
  1684. graceful = true;
  1685. }
  1686. /* Signal we are stopping */
  1687. if (graceful) {
  1688. service->status.dwCurrentState = SERVICE_STOP_PENDING;
  1689. service->status.dwWaitHint = NSSM_WAITHINT_MARGIN;
  1690. SetServiceStatus(service->status_handle, &service->status);
  1691. }
  1692. /* Nothing to do if service isn't running */
  1693. if (service->pid) {
  1694. /* Shut down service */
  1695. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_TERMINATEPROCESS, service->name, service->exe, 0);
  1696. kill_t k;
  1697. service_kill_t(service, &k);
  1698. k.exitcode = 0;
  1699. kill_process(&k);
  1700. }
  1701. else log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_PROCESS_ALREADY_STOPPED, service->name, service->exe, 0);
  1702. end_service((void *) service, true);
  1703. /* Signal we stopped */
  1704. if (graceful) {
  1705. service->status.dwCurrentState = SERVICE_STOP_PENDING;
  1706. wait_for_hooks(service, true);
  1707. service->status.dwCurrentState = SERVICE_STOPPED;
  1708. if (exitcode) {
  1709. service->status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
  1710. service->status.dwServiceSpecificExitCode = exitcode;
  1711. }
  1712. else {
  1713. service->status.dwWin32ExitCode = NO_ERROR;
  1714. service->status.dwServiceSpecificExitCode = 0;
  1715. }
  1716. SetServiceStatus(service->status_handle, &service->status);
  1717. }
  1718. return exitcode;
  1719. }
  1720. /* Callback function triggered when the server exits */
  1721. void CALLBACK end_service(void *arg, unsigned char why) {
  1722. nssm_service_t *service = (nssm_service_t *) arg;
  1723. if (service->stopping) return;
  1724. service->stopping = true;
  1725. service->rotate_stdout_online = service->rotate_stderr_online = NSSM_ROTATE_OFFLINE;
  1726. /* Use now as a dummy exit time. */
  1727. GetSystemTimeAsFileTime(&service->exit_time);
  1728. /* Check exit code */
  1729. unsigned long exitcode = 0;
  1730. TCHAR code[16];
  1731. if (service->process_handle) {
  1732. GetExitCodeProcess(service->process_handle, &exitcode);
  1733. service->exitcode = exitcode;
  1734. /* Check real exit time. */
  1735. if (exitcode != STILL_ACTIVE) get_process_exit_time(service->process_handle, &service->exit_time);
  1736. CloseHandle(service->process_handle);
  1737. }
  1738. service->process_handle = 0;
  1739. /*
  1740. Log that the service ended BEFORE logging about killing the process
  1741. tree. See below for the possible values of the why argument.
  1742. */
  1743. if (! why) {
  1744. _sntprintf_s(code, _countof(code), _TRUNCATE, _T("%lu"), exitcode);
  1745. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_ENDED_SERVICE, service->exe, service->name, code, 0);
  1746. }
  1747. /* Clean up. */
  1748. if (exitcode == STILL_ACTIVE) exitcode = 0;
  1749. if (service->pid && service->kill_process_tree) {
  1750. kill_t k;
  1751. service_kill_t(service, &k);
  1752. kill_process_tree(&k, service->pid);
  1753. }
  1754. service->pid = 0;
  1755. /* Exit hook. */
  1756. service->exit_count++;
  1757. (void) nssm_hook(&hook_threads, service, NSSM_HOOK_EVENT_EXIT, NSSM_HOOK_ACTION_POST, NULL, NSSM_HOOK_DEADLINE, true);
  1758. /* Exit logging threads. */
  1759. cleanup_loggers(service);
  1760. /*
  1761. The why argument is true if our wait timed out or false otherwise.
  1762. Our wait is infinite so why will never be true when called by the system.
  1763. If it is indeed true, assume we were called from stop_service() because
  1764. this is a controlled shutdown, and don't take any restart action.
  1765. */
  1766. if (why) return;
  1767. if (! service->allow_restart) return;
  1768. /* What action should we take? */
  1769. int action = NSSM_EXIT_RESTART;
  1770. TCHAR action_string[ACTION_LEN];
  1771. bool default_action;
  1772. if (! get_exit_action(service->name, &exitcode, action_string, &default_action)) {
  1773. for (int i = 0; exit_action_strings[i]; i++) {
  1774. if (! _tcsnicmp((const TCHAR *) action_string, exit_action_strings[i], ACTION_LEN)) {
  1775. action = i;
  1776. break;
  1777. }
  1778. }
  1779. }
  1780. switch (action) {
  1781. /* Try to restart the service or return failure code to service manager */
  1782. case NSSM_EXIT_RESTART:
  1783. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_RESTART, service->name, code, exit_action_strings[action], service->exe, 0);
  1784. while (monitor_service(service)) {
  1785. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_RESTART_SERVICE_FAILED, service->exe, service->name, 0);
  1786. Sleep(30000);
  1787. }
  1788. break;
  1789. /* Do nothing, just like srvany would */
  1790. case NSSM_EXIT_IGNORE:
  1791. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_IGNORE, service->name, code, exit_action_strings[action], service->exe, 0);
  1792. wait_for_hooks(service, false);
  1793. Sleep(INFINITE);
  1794. break;
  1795. /* Tell the service manager we are finished */
  1796. case NSSM_EXIT_REALLY:
  1797. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_REALLY, service->name, code, exit_action_strings[action], 0);
  1798. stop_service(service, exitcode, true, default_action);
  1799. break;
  1800. /* Fake a crash so pre-Vista service managers will run recovery actions. */
  1801. case NSSM_EXIT_UNCLEAN:
  1802. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_EXIT_UNCLEAN, service->name, code, exit_action_strings[action], 0);
  1803. stop_service(service, exitcode, false, default_action);
  1804. wait_for_hooks(service, false);
  1805. nssm_exit(exitcode);
  1806. }
  1807. }
  1808. void throttle_restart(nssm_service_t *service) {
  1809. /* This can't be a restart if the service is already running. */
  1810. if (! service->throttle++) return;
  1811. unsigned long ms;
  1812. unsigned long throttle_ms = throttle_milliseconds(service->throttle);
  1813. TCHAR threshold[8], milliseconds[8];
  1814. if (service->restart_delay > throttle_ms) ms = service->restart_delay;
  1815. else ms = throttle_ms;
  1816. _sntprintf_s(milliseconds, _countof(milliseconds), _TRUNCATE, _T("%lu"), ms);
  1817. if (service->throttle == 1 && service->restart_delay > throttle_ms) log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_RESTART_DELAY, service->name, milliseconds, 0);
  1818. else {
  1819. _sntprintf_s(threshold, _countof(threshold), _TRUNCATE, _T("%lu"), service->throttle_delay);
  1820. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_THROTTLED, service->name, threshold, milliseconds, 0);
  1821. }
  1822. if (use_critical_section) EnterCriticalSection(&service->throttle_section);
  1823. else if (service->throttle_timer) {
  1824. ZeroMemory(&service->throttle_duetime, sizeof(service->throttle_duetime));
  1825. service->throttle_duetime.QuadPart = 0 - (ms * 10000LL);
  1826. SetWaitableTimer(service->throttle_timer, &service->throttle_duetime, 0, 0, 0, 0);
  1827. }
  1828. service->status.dwCurrentState = SERVICE_PAUSED;
  1829. service->status.dwControlsAccepted |= SERVICE_ACCEPT_PAUSE_CONTINUE;
  1830. SetServiceStatus(service->status_handle, &service->status);
  1831. if (use_critical_section) {
  1832. imports.SleepConditionVariableCS(&service->throttle_condition, &service->throttle_section, ms);
  1833. LeaveCriticalSection(&service->throttle_section);
  1834. }
  1835. else {
  1836. if (service->throttle_timer) WaitForSingleObject(service->throttle_timer, INFINITE);
  1837. else Sleep(ms);
  1838. }
  1839. }
  1840. /*
  1841. When responding to a stop (or any other) request we need to set dwWaitHint to
  1842. the number of milliseconds we expect the operation to take, and optionally
  1843. increase dwCheckPoint. If dwWaitHint milliseconds elapses without the
  1844. operation completing or dwCheckPoint increasing, the system will consider the
  1845. service to be hung.
  1846. However the system will consider the service to be hung after 30000
  1847. milliseconds regardless of the value of dwWaitHint if dwCheckPoint has not
  1848. changed. Therefore if we want to wait longer than that we must periodically
  1849. increase dwCheckPoint.
  1850. Furthermore, it will consider the service to be hung after 60000 milliseconds
  1851. regardless of the value of dwCheckPoint unless dwWaitHint is increased every
  1852. time dwCheckPoint is also increased.
  1853. Our strategy then is to retrieve the initial dwWaitHint and wait for
  1854. NSSM_SERVICE_STATUS_DEADLINE milliseconds. If the process is still running
  1855. and we haven't finished waiting we increment dwCheckPoint and add whichever is
  1856. smaller of NSSM_SERVICE_STATUS_DEADLINE or the remaining timeout to
  1857. dwWaitHint.
  1858. Only doing both these things will prevent the system from killing the service.
  1859. If the status_handle and service_status arguments are omitted, this function
  1860. will not try to update the service manager but it will still log to the
  1861. event log that it is waiting for a handle.
  1862. Returns: 1 if the wait timed out.
  1863. 0 if the wait completed.
  1864. -1 on error.
  1865. */
  1866. int await_single_handle(SERVICE_STATUS_HANDLE status_handle, SERVICE_STATUS *status, HANDLE handle, TCHAR *name, TCHAR *function_name, unsigned long timeout) {
  1867. unsigned long interval;
  1868. unsigned long ret;
  1869. unsigned long waited;
  1870. TCHAR interval_milliseconds[16];
  1871. TCHAR timeout_milliseconds[16];
  1872. TCHAR waited_milliseconds[16];
  1873. TCHAR *function = function_name;
  1874. /* Add brackets to function name. */
  1875. size_t funclen = _tcslen(function_name) + 3;
  1876. TCHAR *func = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, funclen * sizeof(TCHAR));
  1877. if (func) {
  1878. if (_sntprintf_s(func, funclen, _TRUNCATE, _T("%s()"), function_name) > -1) function = func;
  1879. }
  1880. _sntprintf_s(timeout_milliseconds, _countof(timeout_milliseconds), _TRUNCATE, _T("%lu"), timeout);
  1881. waited = 0;
  1882. while (waited < timeout) {
  1883. interval = timeout - waited;
  1884. if (interval > NSSM_SERVICE_STATUS_DEADLINE) interval = NSSM_SERVICE_STATUS_DEADLINE;
  1885. if (status) {
  1886. status->dwWaitHint += interval;
  1887. status->dwCheckPoint++;
  1888. SetServiceStatus(status_handle, status);
  1889. }
  1890. if (waited) {
  1891. _sntprintf_s(waited_milliseconds, _countof(waited_milliseconds), _TRUNCATE, _T("%lu"), waited);
  1892. _sntprintf_s(interval_milliseconds, _countof(interval_milliseconds), _TRUNCATE, _T("%lu"), interval);
  1893. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_AWAITING_SINGLE_HANDLE, function, name, waited_milliseconds, interval_milliseconds, timeout_milliseconds, 0);
  1894. }
  1895. switch (WaitForSingleObject(handle, interval)) {
  1896. case WAIT_OBJECT_0:
  1897. ret = 0;
  1898. goto awaited;
  1899. case WAIT_TIMEOUT:
  1900. ret = 1;
  1901. break;
  1902. default:
  1903. ret = -1;
  1904. goto awaited;
  1905. }
  1906. waited += interval;
  1907. }
  1908. awaited:
  1909. if (func) HeapFree(GetProcessHeap(), 0, func);
  1910. return ret;
  1911. }
  1912. int list_nssm_services(int argc, TCHAR **argv) {
  1913. bool including_native = (argc > 0 && str_equiv(argv[0], _T("all")));
  1914. /* Open service manager. */
  1915. SC_HANDLE services = open_service_manager(SC_MANAGER_CONNECT | SC_MANAGER_ENUMERATE_SERVICE);
  1916. if (! services) {
  1917. print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
  1918. return 1;
  1919. }
  1920. unsigned long bufsize, required, count, i;
  1921. unsigned long resume = 0;
  1922. EnumServicesStatusEx(services, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL, 0, 0, &required, &count, &resume, 0);
  1923. unsigned long error = GetLastError();
  1924. if (error != ERROR_MORE_DATA) {
  1925. print_message(stderr, NSSM_MESSAGE_ENUMSERVICESSTATUS_FAILED, error_string(GetLastError()));
  1926. return 2;
  1927. }
  1928. ENUM_SERVICE_STATUS_PROCESS *status = (ENUM_SERVICE_STATUS_PROCESS *) HeapAlloc(GetProcessHeap(), 0, required);
  1929. if (! status) {
  1930. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("ENUM_SERVICE_STATUS_PROCESS"), _T("list_nssm_services()"));
  1931. return 3;
  1932. }
  1933. bufsize = required;
  1934. while (true) {
  1935. int ret = EnumServicesStatusEx(services, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL, (LPBYTE) status, bufsize, &required, &count, &resume, 0);
  1936. if (! ret) {
  1937. error = GetLastError();
  1938. if (error != ERROR_MORE_DATA) {
  1939. HeapFree(GetProcessHeap(), 0, status);
  1940. print_message(stderr, NSSM_MESSAGE_ENUMSERVICESSTATUS_FAILED, error_string(GetLastError()));
  1941. return 4;
  1942. }
  1943. }
  1944. for (i = 0; i < count; i++) {
  1945. /* Try to get the service parameters. */
  1946. nssm_service_t *service = alloc_nssm_service();
  1947. if (! service) {
  1948. HeapFree(GetProcessHeap(), 0, status);
  1949. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("nssm_service_t"), _T("list_nssm_services()"));
  1950. return 5;
  1951. }
  1952. _sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), status[i].lpServiceName);
  1953. get_parameters(service, 0);
  1954. /* We manage the service if we have an Application. */
  1955. if (including_native || service->exe[0]) _tprintf(_T("%s\n"), service->name);
  1956. cleanup_nssm_service(service);
  1957. }
  1958. if (ret) break;
  1959. }
  1960. HeapFree(GetProcessHeap(), 0, status);
  1961. return 0;
  1962. }
  1963. int service_process_tree(int argc, TCHAR **argv) {
  1964. int errors = 0;
  1965. if (argc < 1) return usage(1);
  1966. SC_HANDLE services = open_service_manager(SC_MANAGER_CONNECT);
  1967. if (! services) {
  1968. print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
  1969. return 1;
  1970. }
  1971. /*
  1972. We need SeDebugPrivilege to read the process tree.
  1973. We ignore failure here so that an error will be printed later when we
  1974. try to open a process handle.
  1975. */
  1976. HANDLE token = get_debug_token();
  1977. TCHAR canonical_name[SERVICE_NAME_LENGTH];
  1978. SERVICE_STATUS_PROCESS service_status;
  1979. nssm_service_t *service;
  1980. kill_t k;
  1981. int i;
  1982. for (i = 0; i < argc; i++) {
  1983. TCHAR *service_name = argv[i];
  1984. SC_HANDLE service_handle = open_service(services, service_name, SERVICE_QUERY_STATUS, canonical_name, _countof(canonical_name));
  1985. if (! service_handle) {
  1986. errors++;
  1987. continue;
  1988. }
  1989. unsigned long size;
  1990. int ret = QueryServiceStatusEx(service_handle, SC_STATUS_PROCESS_INFO, (LPBYTE) &service_status, sizeof(service_status), &size);
  1991. long error = GetLastError();
  1992. CloseServiceHandle(service_handle);
  1993. if (! ret) {
  1994. _ftprintf(stderr, _T("%s: %s\n"), canonical_name, error_string(error));
  1995. errors++;
  1996. continue;
  1997. }
  1998. ZeroMemory(&k, sizeof(k));
  1999. k.pid = service_status.dwProcessId;
  2000. if (! k.pid) continue;
  2001. k.process_handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, k.pid);
  2002. if (! k.process_handle) {
  2003. _ftprintf(stderr, _T("%s: %lu: %s\n"), canonical_name, k.pid, error_string(GetLastError()));
  2004. continue;
  2005. }
  2006. if (get_process_creation_time(k.process_handle, &k.creation_time)) continue;
  2007. /* Dummy exit time so we can check processes' parents. */
  2008. GetSystemTimeAsFileTime(&k.exit_time);
  2009. service = alloc_nssm_service();
  2010. if (! service) {
  2011. errors++;
  2012. continue;
  2013. }
  2014. _sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), canonical_name);
  2015. k.name = service->name;
  2016. walk_process_tree(service, print_process, &k, k.pid);
  2017. cleanup_nssm_service(service);
  2018. }
  2019. CloseServiceHandle(services);
  2020. if (token != INVALID_HANDLE_VALUE) CloseHandle(token);
  2021. return errors;
  2022. }