procmon.c 10 KB

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