procmon.c 11 KB

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