procmon.c 11 KB

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