process.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. #include "nssm.h"
  2. extern imports_t imports;
  3. HANDLE get_debug_token() {
  4. long error;
  5. HANDLE token;
  6. if (! OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, false, &token)) {
  7. error = GetLastError();
  8. if (error == ERROR_NO_TOKEN) {
  9. (void) ImpersonateSelf(SecurityImpersonation);
  10. (void) OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, false, &token);
  11. }
  12. }
  13. if (! token) return INVALID_HANDLE_VALUE;
  14. TOKEN_PRIVILEGES privileges, old;
  15. unsigned long size = sizeof(TOKEN_PRIVILEGES);
  16. LUID luid;
  17. if (! LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid)) {
  18. CloseHandle(token);
  19. return INVALID_HANDLE_VALUE;
  20. }
  21. privileges.PrivilegeCount = 1;
  22. privileges.Privileges[0].Luid = luid;
  23. privileges.Privileges[0].Attributes = 0;
  24. if (! AdjustTokenPrivileges(token, false, &privileges, size, &old, &size)) {
  25. CloseHandle(token);
  26. return INVALID_HANDLE_VALUE;
  27. }
  28. old.PrivilegeCount = 1;
  29. old.Privileges[0].Luid = luid;
  30. old.Privileges[0].Attributes |= SE_PRIVILEGE_ENABLED;
  31. if (! AdjustTokenPrivileges(token, false, &old, size, NULL, NULL)) {
  32. CloseHandle(token);
  33. return INVALID_HANDLE_VALUE;
  34. }
  35. return token;
  36. }
  37. void service_kill_t(nssm_service_t *service, kill_t *k) {
  38. if (! service) return;
  39. if (! k) return;
  40. ZeroMemory(k, sizeof(*k));
  41. k->name = service->name;
  42. k->process_handle = service->process_handle;
  43. k->pid = service->pid;
  44. k->exitcode = service->exitcode;
  45. k->stop_method = service->stop_method;
  46. k->kill_console_delay = service->kill_console_delay;
  47. k->kill_window_delay = service->kill_window_delay;
  48. k->kill_threads_delay = service->kill_threads_delay;
  49. k->status_handle = service->status_handle;
  50. k->status = &service->status;
  51. k->creation_time = service->creation_time;
  52. k->exit_time = service->exit_time;
  53. }
  54. int get_process_creation_time(HANDLE process_handle, FILETIME *ft) {
  55. FILETIME creation_time, exit_time, kernel_time, user_time;
  56. if (! GetProcessTimes(process_handle, &creation_time, &exit_time, &kernel_time, &user_time)) {
  57. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GETPROCESSTIMES_FAILED, error_string(GetLastError()), 0);
  58. return 1;
  59. }
  60. memmove(ft, &creation_time, sizeof(creation_time));
  61. return 0;
  62. }
  63. int get_process_exit_time(HANDLE process_handle, FILETIME *ft) {
  64. FILETIME creation_time, exit_time, kernel_time, user_time;
  65. if (! GetProcessTimes(process_handle, &creation_time, &exit_time, &kernel_time, &user_time)) {
  66. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GETPROCESSTIMES_FAILED, error_string(GetLastError()), 0);
  67. return 1;
  68. }
  69. if (! (exit_time.dwLowDateTime || exit_time.dwHighDateTime)) return 2;
  70. memmove(ft, &exit_time, sizeof(exit_time));
  71. return 0;
  72. }
  73. int check_parent(kill_t *k, PROCESSENTRY32 *pe, unsigned long ppid) {
  74. /* Check parent process ID matches. */
  75. if (pe->th32ParentProcessID != ppid) return 1;
  76. /*
  77. Process IDs can be reused so do a sanity check by making sure the child
  78. has been running for less time than the parent.
  79. Though unlikely, it's possible that the parent exited and its process ID
  80. was already reused, so we'll also compare against its exit time.
  81. */
  82. HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION, false, pe->th32ProcessID);
  83. if (! process_handle) {
  84. TCHAR pid_string[16];
  85. _sntprintf_s(pid_string, _countof(pid_string), _TRUNCATE, _T("%lu"), pe->th32ProcessID);
  86. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OPENPROCESS_FAILED, pid_string, k->name, error_string(GetLastError()), 0);
  87. return 2;
  88. }
  89. FILETIME ft;
  90. if (get_process_creation_time(process_handle, &ft)) {
  91. CloseHandle(process_handle);
  92. return 3;
  93. }
  94. CloseHandle(process_handle);
  95. /* Verify that the parent's creation time is not later. */
  96. if (CompareFileTime(&k->creation_time, &ft) > 0) return 4;
  97. /* Verify that the parent's exit time is not earlier. */
  98. if (CompareFileTime(&k->exit_time, &ft) < 0) return 5;
  99. return 0;
  100. }
  101. /* Send some window messages and hope the window respects one or more. */
  102. int CALLBACK kill_window(HWND window, LPARAM arg) {
  103. kill_t *k = (kill_t *) arg;
  104. unsigned long pid;
  105. if (! GetWindowThreadProcessId(window, &pid)) return 1;
  106. if (pid != k->pid) return 1;
  107. /* First try sending WM_CLOSE to request that the window close. */
  108. k->signalled |= PostMessage(window, WM_CLOSE, k->exitcode, 0);
  109. /*
  110. Then tell the window that the user is logging off and it should exit
  111. without worrying about saving any data.
  112. */
  113. k->signalled |= PostMessage(window, WM_ENDSESSION, 1, ENDSESSION_CLOSEAPP | ENDSESSION_CRITICAL | ENDSESSION_LOGOFF);
  114. return 1;
  115. }
  116. /*
  117. Try to post a message to the message queues of threads associated with the
  118. given process ID. Not all threads have message queues so there's no
  119. guarantee of success, and we don't want to be left waiting for unsignalled
  120. processes so this function returns only true if at least one thread was
  121. successfully prodded.
  122. */
  123. int kill_threads(nssm_service_t *service, kill_t *k) {
  124. int ret = 0;
  125. /* Get a snapshot of all threads in the system. */
  126. HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
  127. if (snapshot == INVALID_HANDLE_VALUE) {
  128. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATETOOLHELP32SNAPSHOT_THREAD_FAILED, k->name, error_string(GetLastError()), 0);
  129. return 0;
  130. }
  131. THREADENTRY32 te;
  132. ZeroMemory(&te, sizeof(te));
  133. te.dwSize = sizeof(te);
  134. if (! Thread32First(snapshot, &te)) {
  135. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_THREAD_ENUMERATE_FAILED, k->name, error_string(GetLastError()), 0);
  136. CloseHandle(snapshot);
  137. return 0;
  138. }
  139. /* This thread belongs to the doomed process so signal it. */
  140. if (te.th32OwnerProcessID == k->pid) {
  141. ret |= PostThreadMessage(te.th32ThreadID, WM_QUIT, k->exitcode, 0);
  142. }
  143. while (true) {
  144. /* Try to get the next thread. */
  145. if (! Thread32Next(snapshot, &te)) {
  146. unsigned long error = GetLastError();
  147. if (error == ERROR_NO_MORE_FILES) break;
  148. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_THREAD_ENUMERATE_FAILED, k->name, error_string(GetLastError()), 0);
  149. CloseHandle(snapshot);
  150. return ret;
  151. }
  152. if (te.th32OwnerProcessID == k->pid) {
  153. ret |= PostThreadMessage(te.th32ThreadID, WM_QUIT, k->exitcode, 0);
  154. }
  155. }
  156. CloseHandle(snapshot);
  157. return ret;
  158. }
  159. int kill_threads(kill_t *k) {
  160. return kill_threads(NULL, k);
  161. }
  162. /* Give the process a chance to die gracefully. */
  163. int kill_process(nssm_service_t *service, kill_t *k) {
  164. if (! k) return 1;
  165. unsigned long ret;
  166. if (GetExitCodeProcess(k->process_handle, &ret)) {
  167. if (ret != STILL_ACTIVE) return 1;
  168. }
  169. /* Try to send a Control-C event to the console. */
  170. if (k->stop_method & NSSM_STOP_METHOD_CONSOLE) {
  171. if (! kill_console(k)) return 1;
  172. }
  173. /*
  174. Try to post messages to the windows belonging to the given process ID.
  175. If the process is a console application it won't have any windows so there's
  176. no guarantee of success.
  177. */
  178. if (k->stop_method & NSSM_STOP_METHOD_WINDOW) {
  179. EnumWindows((WNDENUMPROC) kill_window, (LPARAM) k);
  180. if (k->signalled) {
  181. if (! await_single_handle(k->status_handle, k->status, k->process_handle, k->name, _T(__FUNCTION__), k->kill_window_delay)) return 1;
  182. k->signalled = 0;
  183. }
  184. }
  185. /*
  186. Try to post messages to any thread message queues associated with the
  187. process. Console applications might have them (but probably won't) so
  188. there's still no guarantee of success.
  189. */
  190. if (k->stop_method & NSSM_STOP_METHOD_THREADS) {
  191. if (kill_threads(k)) {
  192. if (! await_single_handle(k->status_handle, k->status, k->process_handle, k->name, _T(__FUNCTION__), k->kill_threads_delay)) return 1;
  193. }
  194. }
  195. /* We tried being nice. Time for extreme prejudice. */
  196. if (k->stop_method & NSSM_STOP_METHOD_TERMINATE) {
  197. return TerminateProcess(k->process_handle, k->exitcode);
  198. }
  199. return 0;
  200. }
  201. int kill_process(kill_t *k) {
  202. return kill_process(NULL, k);
  203. }
  204. /* Simulate a Control-C event to our console (shared with the app). */
  205. int kill_console(nssm_service_t *service, kill_t *k) {
  206. unsigned long ret;
  207. if (! k) return 1;
  208. /* Check we loaded AttachConsole(). */
  209. if (! imports.AttachConsole) return 4;
  210. /* Try to attach to the process's console. */
  211. if (! imports.AttachConsole(k->pid)) {
  212. ret = GetLastError();
  213. switch (ret) {
  214. case ERROR_INVALID_HANDLE:
  215. /* The app doesn't have a console. */
  216. return 1;
  217. case ERROR_GEN_FAILURE:
  218. /* The app already exited. */
  219. return 2;
  220. case ERROR_ACCESS_DENIED:
  221. default:
  222. /* We already have a console. */
  223. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_ATTACHCONSOLE_FAILED, k->name, error_string(ret), 0);
  224. return 3;
  225. }
  226. }
  227. /* Ignore the event ourselves. */
  228. ret = 0;
  229. BOOL ignored = SetConsoleCtrlHandler(0, TRUE);
  230. if (! ignored) {
  231. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SETCONSOLECTRLHANDLER_FAILED, k->name, error_string(GetLastError()), 0);
  232. ret = 4;
  233. }
  234. /* Send the event. */
  235. if (! ret) {
  236. if (! GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0)) {
  237. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GENERATECONSOLECTRLEVENT_FAILED, k->name, error_string(GetLastError()), 0);
  238. ret = 5;
  239. }
  240. }
  241. /* Detach from the console. */
  242. if (! FreeConsole()) {
  243. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_FREECONSOLE_FAILED, k->name, error_string(GetLastError()), 0);
  244. }
  245. /* Wait for process to exit. */
  246. if (await_single_handle(k->status_handle, k->status, k->process_handle, k->name, _T(__FUNCTION__), k->kill_console_delay)) ret = 6;
  247. /* Remove our handler. */
  248. if (ignored && ! SetConsoleCtrlHandler(0, FALSE)) {
  249. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SETCONSOLECTRLHANDLER_FAILED, k->name, error_string(GetLastError()), 0);
  250. }
  251. return ret;
  252. }
  253. int kill_console(kill_t *k) {
  254. return kill_console(NULL, k);
  255. }
  256. void walk_process_tree(nssm_service_t *service, walk_function_t fn, kill_t *k, unsigned long ppid) {
  257. if (! k) return;
  258. /* Shouldn't happen unless the service failed to start. */
  259. if (! k->pid) return; /* XXX: needed? */
  260. unsigned long pid = k->pid;
  261. unsigned long depth = k->depth;
  262. TCHAR pid_string[16], code[16];
  263. _sntprintf_s(pid_string, _countof(pid_string), _TRUNCATE, _T("%lu"), pid);
  264. _sntprintf_s(code, _countof(code), _TRUNCATE, _T("%lu"), k->exitcode);
  265. if (fn == kill_process) log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_KILLING, k->name, pid_string, code, 0);
  266. /* We will need a process handle in order to call TerminateProcess() later. */
  267. HANDLE process_handle = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_TERMINATE, false, pid);
  268. if (process_handle) {
  269. /* Kill this process first, then its descendents. */
  270. TCHAR ppid_string[16];
  271. _sntprintf_s(ppid_string, _countof(ppid_string), _TRUNCATE, _T("%lu"), ppid);
  272. if (fn == kill_process) log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_KILL_PROCESS_TREE, pid_string, ppid_string, k->name, 0);
  273. k->process_handle = process_handle; /* XXX: open directly? */
  274. if (! fn(service, k)) {
  275. /* Maybe it already died. */
  276. unsigned long ret;
  277. if (! GetExitCodeProcess(process_handle, &ret) || ret == STILL_ACTIVE) {
  278. if (k->stop_method & NSSM_STOP_METHOD_TERMINATE) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_TERMINATEPROCESS_FAILED, pid_string, k->name, error_string(GetLastError()), 0);
  279. else log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_PROCESS_STILL_ACTIVE, k->name, pid_string, NSSM, NSSM_REG_STOP_METHOD_SKIP, 0);
  280. }
  281. }
  282. CloseHandle(process_handle);
  283. }
  284. else log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OPENPROCESS_FAILED, pid_string, k->name, error_string(GetLastError()), 0);
  285. /* Get a snapshot of all processes in the system. */
  286. HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  287. if (snapshot == INVALID_HANDLE_VALUE) {
  288. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATETOOLHELP32SNAPSHOT_PROCESS_FAILED, k->name, error_string(GetLastError()), 0);
  289. return;
  290. }
  291. PROCESSENTRY32 pe;
  292. ZeroMemory(&pe, sizeof(pe));
  293. pe.dwSize = sizeof(pe);
  294. if (! Process32First(snapshot, &pe)) {
  295. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_PROCESS_ENUMERATE_FAILED, k->name, error_string(GetLastError()), 0);
  296. CloseHandle(snapshot);
  297. return;
  298. }
  299. /* This is a child of the doomed process so kill it. */
  300. k->depth++;
  301. if (! check_parent(k, &pe, pid)) {
  302. k->pid = pe.th32ProcessID;
  303. walk_process_tree(service, fn, k, ppid);
  304. }
  305. k->pid = pid;
  306. while (true) {
  307. /* Try to get the next process. */
  308. if (! Process32Next(snapshot, &pe)) {
  309. unsigned long ret = GetLastError();
  310. if (ret == ERROR_NO_MORE_FILES) break;
  311. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_PROCESS_ENUMERATE_FAILED, k->name, error_string(GetLastError()), 0);
  312. CloseHandle(snapshot);
  313. k->depth = depth;
  314. return;
  315. }
  316. if (! check_parent(k, &pe, pid)) {
  317. k->pid = pe.th32ProcessID;
  318. walk_process_tree(service, fn, k, ppid);
  319. }
  320. k->pid = pid;
  321. }
  322. k->depth = depth;
  323. CloseHandle(snapshot);
  324. }
  325. void kill_process_tree(kill_t *k, unsigned long ppid) {
  326. return walk_process_tree(NULL, kill_process, k, ppid);
  327. }
  328. int print_process(nssm_service_t *service, kill_t *k) {
  329. TCHAR exe[EXE_LENGTH];
  330. TCHAR *buffer = 0;
  331. if (k->depth) {
  332. buffer = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, (k->depth + 1) * sizeof(TCHAR));
  333. if (buffer) {
  334. unsigned long i;
  335. for (i = 0; i < k->depth; i++) buffer[i] = _T(' ');
  336. buffer[i] = _T('\0');
  337. }
  338. }
  339. if (! GetModuleFileNameEx(k->process_handle, NULL, exe, _countof(exe))) _sntprintf_s(exe, _countof(exe), _TRUNCATE, _T("???"));
  340. _tprintf(_T("% 8lu %s%s\n"), k->pid, buffer ? buffer : _T(""), exe);
  341. if (buffer) HeapFree(GetProcessHeap(), 0, buffer);
  342. return 1;
  343. }
  344. int print_process(kill_t *k) {
  345. return print_process(NULL, k);
  346. }