hook.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. #include "nssm.h"
  2. typedef struct {
  3. TCHAR *name;
  4. HANDLE process_handle;
  5. unsigned long pid;
  6. unsigned long deadline;
  7. FILETIME creation_time;
  8. kill_t k;
  9. } hook_t;
  10. static unsigned long WINAPI await_hook(void *arg) {
  11. hook_t *hook = (hook_t *) arg;
  12. if (! hook) return NSSM_HOOK_STATUS_ERROR;
  13. int ret = 0;
  14. if (WaitForSingleObject(hook->process_handle, hook->deadline) == WAIT_TIMEOUT) ret = NSSM_HOOK_STATUS_TIMEOUT;
  15. /* Tidy up hook process tree. */
  16. if (hook->name) hook->k.name = hook->name;
  17. else hook->k.name = _T("hook");
  18. hook->k.process_handle = hook->process_handle;
  19. hook->k.pid = hook->pid;
  20. hook->k.stop_method = ~0;
  21. hook->k.kill_console_delay = NSSM_KILL_CONSOLE_GRACE_PERIOD;
  22. hook->k.kill_window_delay = NSSM_KILL_WINDOW_GRACE_PERIOD;
  23. hook->k.kill_threads_delay = NSSM_KILL_THREADS_GRACE_PERIOD;
  24. hook->k.creation_time = hook->creation_time;
  25. GetSystemTimeAsFileTime(&hook->k.exit_time);
  26. kill_process_tree(&hook->k, hook->pid);
  27. if (ret) {
  28. CloseHandle(hook->process_handle);
  29. if (hook->name) HeapFree(GetProcessHeap(), 0, hook->name);
  30. HeapFree(GetProcessHeap(), 0, hook);
  31. return ret;
  32. }
  33. unsigned long exitcode;
  34. GetExitCodeProcess(hook->process_handle, &exitcode);
  35. CloseHandle(hook->process_handle);
  36. if (hook->name) HeapFree(GetProcessHeap(), 0, hook->name);
  37. HeapFree(GetProcessHeap(), 0, hook);
  38. if (exitcode == NSSM_HOOK_STATUS_ABORT) return NSSM_HOOK_STATUS_ABORT;
  39. if (exitcode) return NSSM_HOOK_STATUS_FAILED;
  40. return NSSM_HOOK_STATUS_SUCCESS;
  41. }
  42. static void set_hook_runtime(TCHAR *v, FILETIME *start, FILETIME *now) {
  43. if (start && now) {
  44. ULARGE_INTEGER s;
  45. s.LowPart = start->dwLowDateTime;
  46. s.HighPart = start->dwHighDateTime;
  47. if (s.QuadPart) {
  48. ULARGE_INTEGER t;
  49. t.LowPart = now->dwLowDateTime;
  50. t.HighPart = now->dwHighDateTime;
  51. if (t.QuadPart && t.QuadPart >= s.QuadPart) {
  52. t.QuadPart -= s.QuadPart;
  53. t.QuadPart /= 10000LL;
  54. TCHAR number[16];
  55. _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%llu"), t.QuadPart);
  56. SetEnvironmentVariable(v, number);
  57. return;
  58. }
  59. }
  60. }
  61. SetEnvironmentVariable(v, _T(""));
  62. }
  63. static void add_thread_handle(hook_thread_t *hook_threads, HANDLE thread_handle, TCHAR *name) {
  64. if (! hook_threads) return;
  65. int num_threads = hook_threads->num_threads + 1;
  66. hook_thread_data_t *data = (hook_thread_data_t *) HeapAlloc(GetProcessHeap(), 0, num_threads * sizeof(hook_thread_data_t));
  67. if (! data) {
  68. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("hook_thread_t"), _T("add_thread_handle()"), 0);
  69. return;
  70. }
  71. int i;
  72. for (i = 0; i < hook_threads->num_threads; i++) memmove(&data[i], &hook_threads->data[i], sizeof(data[i]));
  73. memmove(data[i].name, name, sizeof(data[i].name));
  74. data[i].thread_handle = thread_handle;
  75. if (hook_threads->data) HeapFree(GetProcessHeap(), 0, hook_threads->data);
  76. hook_threads->data = data;
  77. hook_threads->num_threads = num_threads;
  78. }
  79. bool valid_hook_name(const TCHAR *hook_event, const TCHAR *hook_action, bool quiet) {
  80. bool valid_event = false;
  81. bool valid_action = false;
  82. /* Exit/Post */
  83. if (str_equiv(hook_event, NSSM_HOOK_EVENT_EXIT)) {
  84. if (str_equiv(hook_action, NSSM_HOOK_ACTION_POST)) return true;
  85. if (quiet) return false;
  86. print_message(stderr, NSSM_MESSAGE_INVALID_HOOK_ACTION, hook_event);
  87. _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_ACTION_POST);
  88. return false;
  89. }
  90. /* Power/{Change,Resume} */
  91. if (str_equiv(hook_event, NSSM_HOOK_EVENT_POWER)) {
  92. if (str_equiv(hook_action, NSSM_HOOK_ACTION_CHANGE)) return true;
  93. if (str_equiv(hook_action, NSSM_HOOK_ACTION_RESUME)) return true;
  94. if (quiet) return false;
  95. print_message(stderr, NSSM_MESSAGE_INVALID_HOOK_ACTION, hook_event);
  96. _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_ACTION_CHANGE);
  97. _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_ACTION_RESUME);
  98. return false;
  99. }
  100. /* Rotate/{Pre,Post} */
  101. if (str_equiv(hook_event, NSSM_HOOK_EVENT_ROTATE)) {
  102. if (str_equiv(hook_action, NSSM_HOOK_ACTION_PRE)) return true;
  103. if (str_equiv(hook_action, NSSM_HOOK_ACTION_POST)) return true;
  104. if (quiet) return false;
  105. print_message(stderr, NSSM_MESSAGE_INVALID_HOOK_ACTION, hook_event);
  106. _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_ACTION_PRE);
  107. _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_ACTION_POST);
  108. return false;
  109. }
  110. /* Start/{Pre,Post} */
  111. if (str_equiv(hook_event, NSSM_HOOK_EVENT_START)) {
  112. if (str_equiv(hook_action, NSSM_HOOK_ACTION_PRE)) return true;
  113. if (str_equiv(hook_action, NSSM_HOOK_ACTION_POST)) return true;
  114. if (quiet) return false;
  115. print_message(stderr, NSSM_MESSAGE_INVALID_HOOK_ACTION, hook_event);
  116. _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_ACTION_PRE);
  117. _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_ACTION_POST);
  118. return false;
  119. }
  120. /* Stop/Pre */
  121. if (str_equiv(hook_event, NSSM_HOOK_EVENT_STOP)) {
  122. if (str_equiv(hook_action, NSSM_HOOK_ACTION_PRE)) return true;
  123. if (quiet) return false;
  124. print_message(stderr, NSSM_MESSAGE_INVALID_HOOK_ACTION, hook_event);
  125. _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_ACTION_PRE);
  126. return false;
  127. }
  128. if (quiet) return false;
  129. print_message(stderr, NSSM_MESSAGE_INVALID_HOOK_EVENT);
  130. _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_EVENT_EXIT);
  131. _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_EVENT_POWER);
  132. _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_EVENT_ROTATE);
  133. _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_EVENT_START);
  134. _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_EVENT_STOP);
  135. return false;
  136. }
  137. void await_hook_threads(hook_thread_t *hook_threads, SERVICE_STATUS_HANDLE status_handle, SERVICE_STATUS *status, unsigned long deadline) {
  138. if (! hook_threads) return;
  139. if (! hook_threads->num_threads) return;
  140. int *retain = (int *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, hook_threads->num_threads * sizeof(int));
  141. if (! retain) {
  142. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("retain"), _T("await_hook_threads()"), 0);
  143. return;
  144. }
  145. /*
  146. We could use WaitForMultipleObjects() but await_single_object() can update
  147. the service status as well.
  148. */
  149. int num_threads = 0;
  150. int i;
  151. for (i = 0; i < hook_threads->num_threads; i++) {
  152. if (deadline) {
  153. if (await_single_handle(status_handle, status, hook_threads->data[i].thread_handle, hook_threads->data[i].name, _T(__FUNCTION__), deadline) != 1) {
  154. CloseHandle(hook_threads->data[i].thread_handle);
  155. continue;
  156. }
  157. }
  158. else if (WaitForSingleObject(hook_threads->data[i].thread_handle, 0) != WAIT_TIMEOUT) {
  159. CloseHandle(hook_threads->data[i].thread_handle);
  160. continue;
  161. }
  162. retain[num_threads++]= i;
  163. }
  164. if (num_threads) {
  165. hook_thread_data_t *data = (hook_thread_data_t *) HeapAlloc(GetProcessHeap(), 0, num_threads * sizeof(hook_thread_data_t));
  166. if (! data) {
  167. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("data"), _T("await_hook_threads()"), 0);
  168. HeapFree(GetProcessHeap(), 0, retain);
  169. return;
  170. }
  171. for (i = 0; i < num_threads; i++) memmove(&data[i], &hook_threads->data[retain[i]], sizeof(data[i]));
  172. HeapFree(GetProcessHeap(), 0, hook_threads->data);
  173. hook_threads->data = data;
  174. hook_threads->num_threads = num_threads;
  175. }
  176. else {
  177. HeapFree(GetProcessHeap(), 0, hook_threads->data);
  178. ZeroMemory(hook_threads, sizeof(*hook_threads));
  179. }
  180. HeapFree(GetProcessHeap(), 0, retain);
  181. }
  182. /*
  183. Returns:
  184. NSSM_HOOK_STATUS_SUCCESS if the hook ran successfully.
  185. NSSM_HOOK_STATUS_NOTFOUND if no hook was found.
  186. NSSM_HOOK_STATUS_ABORT if the hook failed and we should cancel service start.
  187. NSSM_HOOK_STATUS_ERROR on error.
  188. NSSM_HOOK_STATUS_NOTRUN if the hook didn't run.
  189. NSSM_HOOK_STATUS_TIMEOUT if the hook timed out.
  190. NSSM_HOOK_STATUS_FAILED if the hook failed.
  191. */
  192. int nssm_hook(hook_thread_t *hook_threads, nssm_service_t *service, TCHAR *hook_event, TCHAR *hook_action, unsigned long *hook_control, unsigned long deadline, bool async) {
  193. int ret = 0;
  194. hook_t *hook = (hook_t *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(hook_t));
  195. if (! hook) {
  196. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("hook"), _T("nssm_hook()"), 0);
  197. return NSSM_HOOK_STATUS_ERROR;
  198. }
  199. FILETIME now;
  200. GetSystemTimeAsFileTime(&now);
  201. EnterCriticalSection(&service->hook_section);
  202. /* Set the environment. */
  203. set_service_environment(service);
  204. /* ABI version. */
  205. TCHAR number[16];
  206. _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), NSSM_HOOK_VERSION);
  207. SetEnvironmentVariable(NSSM_HOOK_ENV_VERSION, number);
  208. /* Event triggering this action. */
  209. SetEnvironmentVariable(NSSM_HOOK_ENV_EVENT, hook_event);
  210. /* Hook action. */
  211. SetEnvironmentVariable(NSSM_HOOK_ENV_ACTION, hook_action);
  212. /* Control triggering this action. May be empty. */
  213. if (hook_control) SetEnvironmentVariable(NSSM_HOOK_ENV_TRIGGER, service_control_text(*hook_control));
  214. else SetEnvironmentVariable(NSSM_HOOK_ENV_TRIGGER, _T(""));
  215. /* Last control handled. */
  216. SetEnvironmentVariable(NSSM_HOOK_ENV_LAST_CONTROL, service_control_text(service->last_control));
  217. /* Path to NSSM, unquoted for the environment. */
  218. SetEnvironmentVariable(NSSM_HOOK_ENV_IMAGE_PATH, nssm_unquoted_imagepath());
  219. /* NSSM version. */
  220. SetEnvironmentVariable(NSSM_HOOK_ENV_NSSM_CONFIGURATION, NSSM_CONFIGURATION);
  221. SetEnvironmentVariable(NSSM_HOOK_ENV_NSSM_VERSION, NSSM_VERSION);
  222. SetEnvironmentVariable(NSSM_HOOK_ENV_BUILD_DATE, NSSM_DATE);
  223. /* NSSM PID. */
  224. _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), GetCurrentProcessId());
  225. SetEnvironmentVariable(NSSM_HOOK_ENV_PID, number);
  226. /* NSSM runtime. */
  227. set_hook_runtime(NSSM_HOOK_ENV_RUNTIME, &service->nssm_creation_time, &now);
  228. /* Application PID. */
  229. if (service->pid) {
  230. _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), service->pid);
  231. SetEnvironmentVariable(NSSM_HOOK_ENV_APPLICATION_PID, number);
  232. /* Application runtime. */
  233. set_hook_runtime(NSSM_HOOK_ENV_APPLICATION_RUNTIME, &service->creation_time, &now);
  234. /* Exit code. */
  235. SetEnvironmentVariable(NSSM_HOOK_ENV_EXITCODE, _T(""));
  236. }
  237. else {
  238. SetEnvironmentVariable(NSSM_HOOK_ENV_APPLICATION_PID, _T(""));
  239. if (str_equiv(hook_event, NSSM_HOOK_EVENT_START) && str_equiv(hook_action, NSSM_HOOK_ACTION_PRE)) {
  240. SetEnvironmentVariable(NSSM_HOOK_ENV_APPLICATION_RUNTIME, _T(""));
  241. SetEnvironmentVariable(NSSM_HOOK_ENV_EXITCODE, _T(""));
  242. }
  243. else {
  244. set_hook_runtime(NSSM_HOOK_ENV_APPLICATION_RUNTIME, &service->creation_time, &service->exit_time);
  245. /* Exit code. */
  246. _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), service->exitcode);
  247. SetEnvironmentVariable(NSSM_HOOK_ENV_EXITCODE, number);
  248. }
  249. }
  250. /* Deadline for this script. */
  251. _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), deadline);
  252. SetEnvironmentVariable(NSSM_HOOK_ENV_DEADLINE, number);
  253. /* Service name. */
  254. SetEnvironmentVariable(NSSM_HOOK_ENV_SERVICE_NAME, service->name);
  255. SetEnvironmentVariable(NSSM_HOOK_ENV_SERVICE_DISPLAYNAME, service->displayname);
  256. /* Times the service was asked to start. */
  257. _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), service->start_requested_count);
  258. SetEnvironmentVariable(NSSM_HOOK_ENV_START_REQUESTED_COUNT, number);
  259. /* Times the service actually did start. */
  260. _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), service->start_count);
  261. SetEnvironmentVariable(NSSM_HOOK_ENV_START_COUNT, number);
  262. /* Times the service exited. */
  263. _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), service->exit_count);
  264. SetEnvironmentVariable(NSSM_HOOK_ENV_EXIT_COUNT, number);
  265. /* Throttled count. */
  266. _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), service->throttle);
  267. SetEnvironmentVariable(NSSM_HOOK_ENV_THROTTLE_COUNT, number);
  268. /* Command line. */
  269. TCHAR app[CMD_LENGTH];
  270. _sntprintf_s(app, _countof(app), _TRUNCATE, _T("\"%s\" %s"), service->exe, service->flags);
  271. SetEnvironmentVariable(NSSM_HOOK_ENV_COMMAND_LINE, app);
  272. TCHAR cmd[CMD_LENGTH];
  273. if (get_hook(service->name, hook_event, hook_action, cmd, sizeof(cmd))) {
  274. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GET_HOOK_FAILED, hook_event, hook_action, service->name, 0);
  275. unset_service_environment(service);
  276. LeaveCriticalSection(&service->hook_section);
  277. HeapFree(GetProcessHeap(), 0, hook);
  278. return NSSM_HOOK_STATUS_ERROR;
  279. }
  280. /* No hook. */
  281. if (! _tcslen(cmd)) {
  282. unset_service_environment(service);
  283. LeaveCriticalSection(&service->hook_section);
  284. HeapFree(GetProcessHeap(), 0, hook);
  285. return NSSM_HOOK_STATUS_NOTFOUND;
  286. }
  287. /* Run the command. */
  288. STARTUPINFO si;
  289. ZeroMemory(&si, sizeof(si));
  290. si.cb = sizeof(si);
  291. PROCESS_INFORMATION pi;
  292. ZeroMemory(&pi, sizeof(pi));
  293. unsigned long flags = 0;
  294. #ifdef UNICODE
  295. flags |= CREATE_UNICODE_ENVIRONMENT;
  296. #endif
  297. ret = NSSM_HOOK_STATUS_NOTRUN;
  298. if (CreateProcess(0, cmd, 0, 0, false, flags, 0, service->dir, &si, &pi)) {
  299. hook->name = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, HOOK_NAME_LENGTH * sizeof(TCHAR));
  300. if (hook->name) _sntprintf_s(hook->name, HOOK_NAME_LENGTH, _TRUNCATE, _T("%s (%s/%s)"), service->name, hook_event, hook_action);
  301. hook->process_handle = pi.hProcess;
  302. hook->pid = pi.dwProcessId;
  303. hook->deadline = deadline;
  304. if (get_process_creation_time(hook->process_handle, &hook->creation_time)) GetSystemTimeAsFileTime(&hook->creation_time);
  305. unsigned long tid;
  306. HANDLE thread_handle = CreateThread(NULL, 0, await_hook, (void *) hook, 0, &tid);
  307. if (thread_handle) {
  308. if (async) {
  309. ret = 0;
  310. await_hook_threads(hook_threads, service->status_handle, &service->status, 0);
  311. add_thread_handle(hook_threads, thread_handle, hook->name);
  312. }
  313. else {
  314. await_single_handle(service->status_handle, &service->status, thread_handle, hook->name, _T(__FUNCTION__), deadline + NSSM_SERVICE_STATUS_DEADLINE);
  315. unsigned long exitcode;
  316. GetExitCodeThread(thread_handle, &exitcode);
  317. ret = (int) exitcode;
  318. CloseHandle(thread_handle);
  319. }
  320. }
  321. else {
  322. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATETHREAD_FAILED, error_string(GetLastError()), 0);
  323. await_hook(hook);
  324. if (hook->name) HeapFree(GetProcessHeap(), 0, hook->name);
  325. HeapFree(GetProcessHeap(), 0, hook);
  326. }
  327. }
  328. else {
  329. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_HOOK_CREATEPROCESS_FAILED, hook_event, hook_action, service->name, cmd, error_string(GetLastError()), 0);
  330. HeapFree(GetProcessHeap(), 0, hook);
  331. }
  332. /* Restore our environment. */
  333. unset_service_environment(service);
  334. LeaveCriticalSection(&service->hook_section);
  335. return ret;
  336. }
  337. int nssm_hook(hook_thread_t *hook_threads, nssm_service_t *service, TCHAR *hook_event, TCHAR *hook_action, unsigned long *hook_control, unsigned long deadline) {
  338. return nssm_hook(hook_threads, service, hook_event, hook_action, hook_control, deadline, true);
  339. }
  340. int nssm_hook(hook_thread_t *hook_threads, nssm_service_t *service, TCHAR *hook_event, TCHAR *hook_action, unsigned long *hook_control) {
  341. return nssm_hook(hook_threads, service, hook_event, hook_action, hook_control, NSSM_HOOK_DEADLINE);
  342. }