procmon.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /* Copyright (c) 2011-2018, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file procmon.c
  5. * \brief Process-termination monitor functions
  6. **/
  7. #include "common/procmon.h"
  8. #include "lib/log/torlog.h"
  9. #include "lib/log/util_bug.h"
  10. #include "lib/log/win32err.h"
  11. #include "lib/malloc/util_malloc.h"
  12. #include "lib/string/parse_int.h"
  13. #ifdef HAVE_SIGNAL_H
  14. #include <signal.h>
  15. #endif
  16. #ifdef HAVE_ERRNO_H
  17. #include <errno.h>
  18. #endif
  19. #ifdef _WIN32
  20. #include <windows.h>
  21. #endif
  22. #if (0 == SIZEOF_PID_T) && defined(_WIN32)
  23. /* Windows does not define pid_t sometimes, but _getpid() returns an int.
  24. * Everybody else needs to have a pid_t. */
  25. typedef int pid_t;
  26. #define PID_T_FORMAT "%d"
  27. #elif (SIZEOF_PID_T == SIZEOF_INT) || (SIZEOF_PID_T == SIZEOF_SHORT)
  28. #define PID_T_FORMAT "%d"
  29. #elif (SIZEOF_PID_T == SIZEOF_LONG)
  30. #define PID_T_FORMAT "%ld"
  31. #elif (SIZEOF_PID_T == SIZEOF_INT64_T)
  32. #define PID_T_FORMAT I64_FORMAT
  33. #else
  34. #error Unknown: SIZEOF_PID_T
  35. #endif /* (0 == SIZEOF_PID_T) && defined(_WIN32) || ... */
  36. /* Define to 1 if process-termination monitors on this OS and Libevent
  37. version must poll for process termination themselves. */
  38. #define PROCMON_POLLS 1
  39. /* Currently we need to poll in some way on all systems. */
  40. #ifdef PROCMON_POLLS
  41. static void tor_process_monitor_poll_cb(periodic_timer_t *ev,
  42. void *procmon_);
  43. #endif
  44. /* This struct may contain pointers into the original process
  45. * specifier string, but it should *never* contain anything which
  46. * needs to be freed. */
  47. /* DOCDOC parsed_process_specifier_t */
  48. struct parsed_process_specifier_t {
  49. pid_t pid;
  50. };
  51. /** Parse the process specifier given in <b>process_spec</b> into
  52. * *<b>ppspec</b>. Return 0 on success; return -1 and store an error
  53. * message into *<b>msg</b> on failure. The caller must not free the
  54. * returned error message. */
  55. static int
  56. parse_process_specifier(const char *process_spec,
  57. struct parsed_process_specifier_t *ppspec,
  58. const char **msg)
  59. {
  60. long pid_l;
  61. int pid_ok = 0;
  62. char *pspec_next;
  63. /* If we're lucky, long will turn out to be large enough to hold a
  64. * PID everywhere that Tor runs. */
  65. pid_l = tor_parse_long(process_spec, 10, 1, LONG_MAX, &pid_ok, &pspec_next);
  66. /* Reserve room in the ‘process specifier’ for additional
  67. * (platform-specific) identifying information beyond the PID, to
  68. * make our process-existence checks a bit less racy in a future
  69. * version. */
  70. if ((*pspec_next != 0) && (*pspec_next != ' ') && (*pspec_next != ':')) {
  71. pid_ok = 0;
  72. }
  73. ppspec->pid = (pid_t)(pid_l);
  74. if (!pid_ok || (pid_l != (long)(ppspec->pid))) {
  75. *msg = "invalid PID";
  76. goto err;
  77. }
  78. return 0;
  79. err:
  80. return -1;
  81. }
  82. /* DOCDOC tor_process_monitor_t */
  83. struct tor_process_monitor_t {
  84. /** Log domain for warning messages. */
  85. log_domain_mask_t log_domain;
  86. /** All systems: The best we can do in general is poll for the
  87. * process's existence by PID periodically, and hope that the kernel
  88. * doesn't reassign the same PID to another process between our
  89. * polls. */
  90. pid_t pid;
  91. #ifdef _WIN32
  92. /** Windows-only: Should we poll hproc? If false, poll pid
  93. * instead. */
  94. int poll_hproc;
  95. /** Windows-only: Get a handle to the process (if possible) and
  96. * periodically check whether the process we have a handle to has
  97. * ended. */
  98. HANDLE hproc;
  99. /* XXXX We should have Libevent watch hproc for us,
  100. * if/when some version of Libevent can be told to do so. */
  101. #endif /* defined(_WIN32) */
  102. /* XXXX On Linux, we can and should receive the 22nd
  103. * (space-delimited) field (‘starttime’) of /proc/$PID/stat from the
  104. * owning controller and store it, and poll once in a while to see
  105. * whether it has changed -- if so, the kernel has *definitely*
  106. * reassigned the owning controller's PID and we should exit. On
  107. * FreeBSD, we can do the same trick using either the 8th
  108. * space-delimited field of /proc/$PID/status on the seven FBSD
  109. * systems whose admins have mounted procfs, or the start-time field
  110. * of the process-information structure returned by kvmgetprocs() on
  111. * any system. The latter is ickier. */
  112. /* XXXX On FreeBSD (and possibly other kqueue systems), we can and
  113. * should arrange to receive EVFILT_PROC NOTE_EXIT notifications for
  114. * pid, so we don't have to do such a heavyweight poll operation in
  115. * order to avoid the PID-reassignment race condition. (We would
  116. * still need to poll our own kqueue periodically until some version
  117. * of Libevent 2.x learns to receive these events for us.) */
  118. /** A Libevent event structure, to either poll for the process's
  119. * existence or receive a notification when the process ends. */
  120. periodic_timer_t *e;
  121. /** A callback to be called when the process ends. */
  122. tor_procmon_callback_t cb;
  123. void *cb_arg; /**< A user-specified pointer to be passed to cb. */
  124. };
  125. /** Verify that the process specifier given in <b>process_spec</b> is
  126. * syntactically valid. Return 0 on success; return -1 and store an
  127. * error message into *<b>msg</b> on failure. The caller must not
  128. * free the returned error message. */
  129. int
  130. tor_validate_process_specifier(const char *process_spec,
  131. const char **msg)
  132. {
  133. struct parsed_process_specifier_t ppspec;
  134. tor_assert(msg != NULL);
  135. *msg = NULL;
  136. return parse_process_specifier(process_spec, &ppspec, msg);
  137. }
  138. /* DOCDOC poll_interval_tv */
  139. static const struct timeval poll_interval_tv = {15, 0};
  140. /** Create a process-termination monitor for the process specifier
  141. * given in <b>process_spec</b>. Return a newly allocated
  142. * tor_process_monitor_t on success; return NULL and store an error
  143. * message into *<b>msg</b> on failure. The caller must not free
  144. * the returned error message.
  145. *
  146. * When the monitored process terminates, call
  147. * <b>cb</b>(<b>cb_arg</b>).
  148. */
  149. tor_process_monitor_t *
  150. tor_process_monitor_new(struct event_base *base,
  151. const char *process_spec,
  152. log_domain_mask_t log_domain,
  153. tor_procmon_callback_t cb, void *cb_arg,
  154. const char **msg)
  155. {
  156. tor_process_monitor_t *procmon = tor_malloc_zero(
  157. sizeof(tor_process_monitor_t));
  158. struct parsed_process_specifier_t ppspec;
  159. tor_assert(msg != NULL);
  160. *msg = NULL;
  161. if (procmon == NULL) {
  162. *msg = "out of memory";
  163. goto err;
  164. }
  165. procmon->log_domain = log_domain;
  166. if (parse_process_specifier(process_spec, &ppspec, msg))
  167. goto err;
  168. procmon->pid = ppspec.pid;
  169. #ifdef _WIN32
  170. procmon->hproc = OpenProcess(PROCESS_QUERY_INFORMATION | SYNCHRONIZE,
  171. FALSE,
  172. procmon->pid);
  173. if (procmon->hproc != NULL) {
  174. procmon->poll_hproc = 1;
  175. log_info(procmon->log_domain, "Successfully opened handle to process "
  176. PID_T_FORMAT"; "
  177. "monitoring it.",
  178. procmon->pid);
  179. } else {
  180. /* If we couldn't get a handle to the process, we'll try again the
  181. * first time we poll. */
  182. log_info(procmon->log_domain, "Failed to open handle to process "
  183. PID_T_FORMAT"; will "
  184. "try again later.",
  185. procmon->pid);
  186. }
  187. #endif /* defined(_WIN32) */
  188. procmon->cb = cb;
  189. procmon->cb_arg = cb_arg;
  190. #ifdef PROCMON_POLLS
  191. procmon->e = periodic_timer_new(base,
  192. &poll_interval_tv,
  193. tor_process_monitor_poll_cb, procmon);
  194. #else /* !(defined(PROCMON_POLLS)) */
  195. #error OOPS?
  196. #endif /* defined(PROCMON_POLLS) */
  197. return procmon;
  198. err:
  199. tor_process_monitor_free(procmon);
  200. return NULL;
  201. }
  202. #ifdef PROCMON_POLLS
  203. /** Libevent callback to poll for the existence of the process
  204. * monitored by <b>procmon_</b>. */
  205. static void
  206. tor_process_monitor_poll_cb(periodic_timer_t *event, void *procmon_)
  207. {
  208. (void)event;
  209. tor_process_monitor_t *procmon = (tor_process_monitor_t *)(procmon_);
  210. int its_dead_jim;
  211. tor_assert(procmon != NULL);
  212. #ifdef _WIN32
  213. if (procmon->poll_hproc) {
  214. DWORD exit_code;
  215. if (!GetExitCodeProcess(procmon->hproc, &exit_code)) {
  216. char *errmsg = format_win32_error(GetLastError());
  217. log_warn(procmon->log_domain, "Error \"%s\" occurred while polling "
  218. "handle for monitored process "PID_T_FORMAT"; assuming "
  219. "it's dead.",
  220. errmsg, procmon->pid);
  221. tor_free(errmsg);
  222. its_dead_jim = 1;
  223. } else {
  224. its_dead_jim = (exit_code != STILL_ACTIVE);
  225. }
  226. } else {
  227. /* All we can do is try to open the process, and look at the error
  228. * code if it fails again. */
  229. procmon->hproc = OpenProcess(PROCESS_QUERY_INFORMATION | SYNCHRONIZE,
  230. FALSE,
  231. procmon->pid);
  232. if (procmon->hproc != NULL) {
  233. log_info(procmon->log_domain, "Successfully opened handle to monitored "
  234. "process "PID_T_FORMAT".",
  235. procmon->pid);
  236. its_dead_jim = 0;
  237. procmon->poll_hproc = 1;
  238. } else {
  239. DWORD err_code = GetLastError();
  240. char *errmsg = format_win32_error(err_code);
  241. /* When I tested OpenProcess's error codes on Windows 7, I
  242. * received error code 5 (ERROR_ACCESS_DENIED) for PIDs of
  243. * existing processes that I could not open and error code 87
  244. * (ERROR_INVALID_PARAMETER) for PIDs that were not in use.
  245. * Since the nonexistent-process error code is sane, I'm going
  246. * to assume that all errors other than ERROR_INVALID_PARAMETER
  247. * mean that the process we are monitoring is still alive. */
  248. its_dead_jim = (err_code == ERROR_INVALID_PARAMETER);
  249. if (!its_dead_jim)
  250. log_info(procmon->log_domain, "Failed to open handle to monitored "
  251. "process "PID_T_FORMAT", and error code %lu (%s) is not "
  252. "'invalid parameter' -- assuming the process is still alive.",
  253. procmon->pid,
  254. err_code, errmsg);
  255. tor_free(errmsg);
  256. }
  257. }
  258. #else /* !(defined(_WIN32)) */
  259. /* Unix makes this part easy, if a bit racy. */
  260. its_dead_jim = kill(procmon->pid, 0);
  261. its_dead_jim = its_dead_jim && (errno == ESRCH);
  262. #endif /* defined(_WIN32) */
  263. tor_log(its_dead_jim ? LOG_NOTICE : LOG_INFO,
  264. procmon->log_domain, "Monitored process "PID_T_FORMAT" is %s.",
  265. procmon->pid,
  266. its_dead_jim ? "dead" : "still alive");
  267. if (its_dead_jim) {
  268. procmon->cb(procmon->cb_arg);
  269. }
  270. }
  271. #endif /* defined(PROCMON_POLLS) */
  272. /** Free the process-termination monitor <b>procmon</b>. */
  273. void
  274. tor_process_monitor_free_(tor_process_monitor_t *procmon)
  275. {
  276. if (procmon == NULL)
  277. return;
  278. #ifdef _WIN32
  279. if (procmon->hproc != NULL)
  280. CloseHandle(procmon->hproc);
  281. #endif
  282. if (procmon->e != NULL)
  283. periodic_timer_free(procmon->e);
  284. tor_free(procmon);
  285. }