procmon.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. /* DOCDOC parsed_process_specifier_t */
  35. struct parsed_process_specifier_t {
  36. pid_t pid;
  37. };
  38. /** Parse the process specifier given in <b>process_spec</b> into
  39. * *<b>ppspec</b>. Return 0 on success; return -1 and store an error
  40. * message into *<b>msg</b> on failure. The caller must not free the
  41. * returned error message. */
  42. static int
  43. parse_process_specifier(const char *process_spec,
  44. struct parsed_process_specifier_t *ppspec,
  45. const char **msg)
  46. {
  47. long pid_l;
  48. int pid_ok = 0;
  49. char *pspec_next;
  50. /* If we're lucky, long will turn out to be large enough to hold a
  51. * PID everywhere that Tor runs. */
  52. pid_l = tor_parse_long(process_spec, 0, 1, LONG_MAX, &pid_ok, &pspec_next);
  53. /* Reserve room in the ‘process specifier’ for additional
  54. * (platform-specific) identifying information beyond the PID, to
  55. * make our process-existence checks a bit less racy in a future
  56. * version. */
  57. if ((*pspec_next != 0) && (*pspec_next != ' ') && (*pspec_next != ':')) {
  58. pid_ok = 0;
  59. }
  60. ppspec->pid = (pid_t)(pid_l);
  61. if (!pid_ok || (pid_l != (long)(ppspec->pid))) {
  62. *msg = "invalid PID";
  63. goto err;
  64. }
  65. return 0;
  66. err:
  67. return -1;
  68. }
  69. /* DOCDOC tor_process_monitor_t */
  70. struct tor_process_monitor_t {
  71. /** Log domain for warning messages. */
  72. log_domain_mask_t log_domain;
  73. /** All systems: The best we can do in general is poll for the
  74. * process's existence by PID periodically, and hope that the kernel
  75. * doesn't reassign the same PID to another process between our
  76. * polls. */
  77. pid_t pid;
  78. #ifdef _WIN32
  79. /** Windows-only: Should we poll hproc? If false, poll pid
  80. * instead. */
  81. int poll_hproc;
  82. /** Windows-only: Get a handle to the process (if possible) and
  83. * periodically check whether the process we have a handle to has
  84. * ended. */
  85. HANDLE hproc;
  86. /* XXX023 We can and should have Libevent watch hproc for us,
  87. * if/when some version of Libevent 2.x can be told to do so. */
  88. #endif
  89. /* XXX023 On Linux, we can and should receive the 22nd
  90. * (space-delimited) field (‘starttime’) of /proc/$PID/stat from the
  91. * owning controller and store it, and poll once in a while to see
  92. * whether it has changed -- if so, the kernel has *definitely*
  93. * reassigned the owning controller's PID and we should exit. On
  94. * FreeBSD, we can do the same trick using either the 8th
  95. * space-delimited field of /proc/$PID/status on the seven FBSD
  96. * systems whose admins have mounted procfs, or the start-time field
  97. * of the process-information structure returned by kvmgetprocs() on
  98. * any system. The latter is ickier. */
  99. /* XXX023 On FreeBSD (and possibly other kqueue systems), we can and
  100. * should arrange to receive EVFILT_PROC NOTE_EXIT notifications for
  101. * pid, so we don't have to do such a heavyweight poll operation in
  102. * order to avoid the PID-reassignment race condition. (We would
  103. * still need to poll our own kqueue periodically until some version
  104. * of Libevent 2.x learns to receive these events for us.) */
  105. /** A Libevent event structure, to either poll for the process's
  106. * existence or receive a notification when the process ends. */
  107. struct event *e;
  108. /** A callback to be called when the process ends. */
  109. tor_procmon_callback_t cb;
  110. void *cb_arg; /**< A user-specified pointer to be passed to cb. */
  111. };
  112. /** Verify that the process specifier given in <b>process_spec</b> is
  113. * syntactically valid. Return 0 on success; return -1 and store an
  114. * error message into *<b>msg</b> on failure. The caller must not
  115. * free the returned error message. */
  116. int
  117. tor_validate_process_specifier(const char *process_spec,
  118. const char **msg)
  119. {
  120. struct parsed_process_specifier_t ppspec;
  121. tor_assert(msg != NULL);
  122. *msg = NULL;
  123. return parse_process_specifier(process_spec, &ppspec, msg);
  124. }
  125. #ifdef HAVE_EVENT2_EVENT_H
  126. #define PERIODIC_TIMER_FLAGS EV_PERSIST
  127. #else
  128. #define PERIODIC_TIMER_FLAGS (0)
  129. #endif
  130. /* DOCDOC poll_interval_tv */
  131. static struct timeval poll_interval_tv = {15, 0};
  132. /* Note: If you port this file to plain Libevent 2, you can make
  133. * poll_interval_tv const. It has to be non-const here because in
  134. * libevent 1.x, event_add expects a pointer to a non-const struct
  135. * timeval. */
  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(sizeof(tor_process_monitor_t));
  153. struct parsed_process_specifier_t ppspec;
  154. tor_assert(msg != NULL);
  155. *msg = NULL;
  156. if (procmon == NULL) {
  157. *msg = "out of memory";
  158. goto err;
  159. }
  160. procmon->log_domain = log_domain;
  161. if (parse_process_specifier(process_spec, &ppspec, msg))
  162. goto err;
  163. procmon->pid = ppspec.pid;
  164. #ifdef _WIN32
  165. procmon->hproc = OpenProcess(PROCESS_QUERY_INFORMATION | SYNCHRONIZE,
  166. FALSE,
  167. procmon->pid);
  168. if (procmon->hproc != NULL) {
  169. procmon->poll_hproc = 1;
  170. log_info(procmon->log_domain, "Successfully opened handle to process %d; "
  171. "monitoring it.",
  172. (int)(procmon->pid));
  173. } else {
  174. /* If we couldn't get a handle to the process, we'll try again the
  175. * first time we poll. */
  176. log_info(procmon->log_domain, "Failed to open handle to process %d; will "
  177. "try again later.",
  178. (int)(procmon->pid));
  179. }
  180. #endif
  181. procmon->cb = cb;
  182. procmon->cb_arg = cb_arg;
  183. #ifdef PROCMON_POLLS
  184. procmon->e = tor_event_new(base, -1 /* no FD */, PERIODIC_TIMER_FLAGS,
  185. tor_process_monitor_poll_cb, procmon);
  186. /* Note: If you port this file to plain Libevent 2, check that
  187. * procmon->e is non-NULL. We don't need to here because
  188. * tor_evtimer_new never returns NULL. */
  189. evtimer_add(procmon->e, &poll_interval_tv);
  190. #else
  191. #error OOPS?
  192. #endif
  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(evutil_socket_t unused1, short unused2,
  203. void *procmon_)
  204. {
  205. tor_process_monitor_t *procmon = (tor_process_monitor_t *)(procmon_);
  206. int its_dead_jim;
  207. (void)unused1; (void)unused2;
  208. tor_assert(procmon != NULL);
  209. #ifdef _WIN32
  210. if (procmon->poll_hproc) {
  211. DWORD exit_code;
  212. if (!GetExitCodeProcess(procmon->hproc, &exit_code)) {
  213. char *errmsg = format_win32_error(GetLastError());
  214. log_warn(procmon->log_domain, "Error \"%s\" occurred while polling "
  215. "handle for monitored process %d; assuming 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 %d.",
  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 %d, and error code %lu (%s) is not 'invalid "
  248. "parameter' -- assuming the process is still alive.",
  249. procmon->pid,
  250. err_code, errmsg);
  251. tor_free(errmsg);
  252. }
  253. }
  254. #else
  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
  259. log(its_dead_jim ? LOG_NOTICE : LOG_INFO,
  260. procmon->log_domain, "Monitored process %d is %s.",
  261. (int)procmon->pid,
  262. its_dead_jim ? "dead" : "still alive");
  263. if (its_dead_jim) {
  264. procmon->cb(procmon->cb_arg);
  265. #ifndef HAVE_EVENT2_EVENT_H
  266. } else {
  267. evtimer_add(procmon->e, &poll_interval_tv);
  268. #endif
  269. }
  270. }
  271. #endif
  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. tor_event_free(procmon->e);
  284. tor_free(procmon);
  285. }