procmon.c 11 KB

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