process.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. #include "nssm.h"
  2. extern imports_t imports;
  3. int get_process_creation_time(HANDLE process_handle, FILETIME *ft) {
  4. FILETIME creation_time, exit_time, kernel_time, user_time;
  5. if (! GetProcessTimes(process_handle, &creation_time, &exit_time, &kernel_time, &user_time)) {
  6. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GETPROCESSTIMES_FAILED, error_string(GetLastError()), 0);
  7. return 1;
  8. }
  9. memmove(ft, &creation_time, sizeof(creation_time));
  10. return 0;
  11. }
  12. int get_process_exit_time(HANDLE process_handle, FILETIME *ft) {
  13. FILETIME creation_time, exit_time, kernel_time, user_time;
  14. if (! GetProcessTimes(process_handle, &creation_time, &exit_time, &kernel_time, &user_time)) {
  15. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GETPROCESSTIMES_FAILED, error_string(GetLastError()), 0);
  16. return 1;
  17. }
  18. memmove(ft, &exit_time, sizeof(exit_time));
  19. return 0;
  20. }
  21. int check_parent(nssm_service_t *service, PROCESSENTRY32 *pe, unsigned long ppid) {
  22. /* Check parent process ID matches. */
  23. if (pe->th32ParentProcessID != ppid) return 1;
  24. /*
  25. Process IDs can be reused so do a sanity check by making sure the child
  26. has been running for less time than the parent.
  27. Though unlikely, it's possible that the parent exited and its process ID
  28. was already reused, so we'll also compare against its exit time.
  29. */
  30. HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION, false, pe->th32ProcessID);
  31. if (! process_handle) {
  32. TCHAR pid_string[16];
  33. _sntprintf_s(pid_string, _countof(pid_string), _TRUNCATE, _T("%lu"), pe->th32ProcessID);
  34. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OPENPROCESS_FAILED, pid_string, service->name, error_string(GetLastError()), 0);
  35. return 2;
  36. }
  37. FILETIME ft;
  38. if (get_process_creation_time(process_handle, &ft)) {
  39. CloseHandle(process_handle);
  40. return 3;
  41. }
  42. CloseHandle(process_handle);
  43. /* Verify that the parent's creation time is not later. */
  44. if (CompareFileTime(&service->creation_time, &ft) > 0) return 4;
  45. /* Verify that the parent's exit time is not earlier. */
  46. if (CompareFileTime(&service->exit_time, &ft) < 0) return 5;
  47. return 0;
  48. }
  49. /* Send some window messages and hope the window respects one or more. */
  50. int CALLBACK kill_window(HWND window, LPARAM arg) {
  51. kill_t *k = (kill_t *) arg;
  52. unsigned long pid;
  53. if (! GetWindowThreadProcessId(window, &pid)) return 1;
  54. if (pid != k->pid) return 1;
  55. /* First try sending WM_CLOSE to request that the window close. */
  56. k->signalled |= PostMessage(window, WM_CLOSE, k->exitcode, 0);
  57. /*
  58. Then tell the window that the user is logging off and it should exit
  59. without worrying about saving any data.
  60. */
  61. k->signalled |= PostMessage(window, WM_ENDSESSION, 1, ENDSESSION_CLOSEAPP | ENDSESSION_CRITICAL | ENDSESSION_LOGOFF);
  62. return 1;
  63. }
  64. /*
  65. Try to post a message to the message queues of threads associated with the
  66. given process ID. Not all threads have message queues so there's no
  67. guarantee of success, and we don't want to be left waiting for unsignalled
  68. processes so this function returns only true if at least one thread was
  69. successfully prodded.
  70. */
  71. int kill_threads(TCHAR *service_name, kill_t *k) {
  72. int ret = 0;
  73. /* Get a snapshot of all threads in the system. */
  74. HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
  75. if (! snapshot) {
  76. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATETOOLHELP32SNAPSHOT_THREAD_FAILED, service_name, error_string(GetLastError()), 0);
  77. return 0;
  78. }
  79. THREADENTRY32 te;
  80. ZeroMemory(&te, sizeof(te));
  81. te.dwSize = sizeof(te);
  82. if (! Thread32First(snapshot, &te)) {
  83. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_THREAD_ENUMERATE_FAILED, service_name, error_string(GetLastError()), 0);
  84. CloseHandle(snapshot);
  85. return 0;
  86. }
  87. /* This thread belongs to the doomed process so signal it. */
  88. if (te.th32OwnerProcessID == k->pid) {
  89. ret |= PostThreadMessage(te.th32ThreadID, WM_QUIT, k->exitcode, 0);
  90. }
  91. while (true) {
  92. /* Try to get the next thread. */
  93. if (! Thread32Next(snapshot, &te)) {
  94. unsigned long error = GetLastError();
  95. if (error == ERROR_NO_MORE_FILES) break;
  96. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_THREAD_ENUMERATE_FAILED, service_name, error_string(GetLastError()), 0);
  97. CloseHandle(snapshot);
  98. return ret;
  99. }
  100. if (te.th32OwnerProcessID == k->pid) {
  101. ret |= PostThreadMessage(te.th32ThreadID, WM_QUIT, k->exitcode, 0);
  102. }
  103. }
  104. CloseHandle(snapshot);
  105. return ret;
  106. }
  107. /* Give the process a chance to die gracefully. */
  108. int kill_process(nssm_service_t *service, HANDLE process_handle, unsigned long pid, unsigned long exitcode) {
  109. /* Shouldn't happen. */
  110. if (! service) return 1;
  111. if (! pid) return 1;
  112. if (! process_handle) return 1;
  113. unsigned long ret;
  114. if (GetExitCodeProcess(process_handle, &ret)) {
  115. if (ret != STILL_ACTIVE) return 1;
  116. }
  117. kill_t k = { pid, exitcode, 0 };
  118. /* Try to send a Control-C event to the console. */
  119. if (service->stop_method & NSSM_STOP_METHOD_CONSOLE) {
  120. if (! kill_console(service)) return 1;
  121. }
  122. /*
  123. Try to post messages to the windows belonging to the given process ID.
  124. If the process is a console application it won't have any windows so there's
  125. no guarantee of success.
  126. */
  127. if (service->stop_method & NSSM_STOP_METHOD_WINDOW) {
  128. EnumWindows((WNDENUMPROC) kill_window, (LPARAM) &k);
  129. if (k.signalled) {
  130. if (! await_shutdown(service, _T(__FUNCTION__), service->kill_window_delay)) return 1;
  131. }
  132. }
  133. /*
  134. Try to post messages to any thread message queues associated with the
  135. process. Console applications might have them (but probably won't) so
  136. there's still no guarantee of success.
  137. */
  138. if (service->stop_method & NSSM_STOP_METHOD_THREADS) {
  139. if (kill_threads(service->name, &k)) {
  140. if (! await_shutdown(service, _T(__FUNCTION__), service->kill_threads_delay)) return 1;
  141. }
  142. }
  143. /* We tried being nice. Time for extreme prejudice. */
  144. if (service->stop_method & NSSM_STOP_METHOD_TERMINATE) {
  145. return TerminateProcess(service->process_handle, exitcode);
  146. }
  147. return 0;
  148. }
  149. /* Simulate a Control-C event to our console (shared with the app). */
  150. int kill_console(nssm_service_t *service) {
  151. unsigned long ret;
  152. if (! service) return 1;
  153. /* Check we loaded AttachConsole(). */
  154. if (! imports.AttachConsole) return 4;
  155. /* Try to attach to the process's console. */
  156. if (! imports.AttachConsole(service->pid)) {
  157. ret = GetLastError();
  158. switch (ret) {
  159. case ERROR_INVALID_HANDLE:
  160. /* The app doesn't have a console. */
  161. return 1;
  162. case ERROR_GEN_FAILURE:
  163. /* The app already exited. */
  164. return 2;
  165. case ERROR_ACCESS_DENIED:
  166. default:
  167. /* We already have a console. */
  168. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_ATTACHCONSOLE_FAILED, service->name, error_string(ret), 0);
  169. return 3;
  170. }
  171. }
  172. /* Ignore the event ourselves. */
  173. ret = 0;
  174. if (! SetConsoleCtrlHandler(0, TRUE)) {
  175. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SETCONSOLECTRLHANDLER_FAILED, service->name, error_string(GetLastError()), 0);
  176. ret = 4;
  177. }
  178. /* Send the event. */
  179. if (! ret) {
  180. if (! GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0)) {
  181. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GENERATECONSOLECTRLEVENT_FAILED, service->name, error_string(GetLastError()), 0);
  182. ret = 5;
  183. }
  184. }
  185. /* Detach from the console. */
  186. if (! FreeConsole()) {
  187. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_FREECONSOLE_FAILED, service->name, error_string(GetLastError()), 0);
  188. }
  189. /* Wait for process to exit. */
  190. if (await_shutdown(service, _T(__FUNCTION__), service->kill_console_delay)) ret = 6;
  191. return ret;
  192. }
  193. void kill_process_tree(nssm_service_t *service, unsigned long pid, unsigned long exitcode, unsigned long ppid) {
  194. /* Shouldn't happen unless the service failed to start. */
  195. if (! pid) return;
  196. TCHAR pid_string[16], code[16];
  197. _sntprintf_s(pid_string, _countof(pid_string), _TRUNCATE, _T("%lu"), pid);
  198. _sntprintf_s(code, _countof(code), _TRUNCATE, _T("%lu"), exitcode);
  199. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_KILLING, service->name, pid_string, code, 0);
  200. /* Get a snapshot of all processes in the system. */
  201. HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  202. if (! snapshot) {
  203. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATETOOLHELP32SNAPSHOT_PROCESS_FAILED, service->name, error_string(GetLastError()), 0);
  204. return;
  205. }
  206. PROCESSENTRY32 pe;
  207. ZeroMemory(&pe, sizeof(pe));
  208. pe.dwSize = sizeof(pe);
  209. if (! Process32First(snapshot, &pe)) {
  210. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_PROCESS_ENUMERATE_FAILED, service->name, error_string(GetLastError()), 0);
  211. CloseHandle(snapshot);
  212. return;
  213. }
  214. /* This is a child of the doomed process so kill it. */
  215. if (! check_parent(service, &pe, pid)) kill_process_tree(service, pe.th32ProcessID, exitcode, ppid);
  216. while (true) {
  217. /* Try to get the next process. */
  218. if (! Process32Next(snapshot, &pe)) {
  219. unsigned long ret = GetLastError();
  220. if (ret == ERROR_NO_MORE_FILES) break;
  221. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_PROCESS_ENUMERATE_FAILED, service->name, error_string(GetLastError()), 0);
  222. CloseHandle(snapshot);
  223. return;
  224. }
  225. if (! check_parent(service, &pe, pid)) kill_process_tree(service, pe.th32ProcessID, exitcode, ppid);
  226. }
  227. CloseHandle(snapshot);
  228. /* We will need a process handle in order to call TerminateProcess() later. */
  229. HANDLE process_handle = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_TERMINATE, false, pid);
  230. if (! process_handle) {
  231. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OPENPROCESS_FAILED, pid_string, service->name, error_string(GetLastError()), 0);
  232. return;
  233. }
  234. TCHAR ppid_string[16];
  235. _sntprintf_s(ppid_string, _countof(ppid_string), _TRUNCATE, _T("%lu"), ppid);
  236. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_KILL_PROCESS_TREE, pid_string, ppid_string, service->name, 0);
  237. if (! kill_process(service, process_handle, pid, exitcode)) {
  238. /* Maybe it already died. */
  239. unsigned long ret;
  240. if (! GetExitCodeProcess(process_handle, &ret) || ret == STILL_ACTIVE) {
  241. if (service->stop_method & NSSM_STOP_METHOD_TERMINATE) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_TERMINATEPROCESS_FAILED, pid_string, service->name, error_string(GetLastError()), 0);
  242. else log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_PROCESS_STILL_ACTIVE, service->name, pid_string, NSSM, NSSM_REG_STOP_METHOD_SKIP, 0);
  243. }
  244. }
  245. CloseHandle(process_handle);
  246. }