xref: /freebsd/sbin/hastd/hooks.c (revision 076ad2f836d5f49dc1375f1677335a48fe0d4b82)
1 /*-
2  * Copyright (c) 2010 The FreeBSD Foundation
3  * Copyright (c) 2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
4  * All rights reserved.
5  *
6  * This software was developed by Pawel Jakub Dawidek under sponsorship from
7  * the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/types.h>
35 #include <sys/sysctl.h>
36 #include <sys/wait.h>
37 
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <paths.h>
41 #include <signal.h>
42 #include <stdbool.h>
43 #include <stdint.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <syslog.h>
48 #include <unistd.h>
49 
50 #include <pjdlog.h>
51 
52 #include "hooks.h"
53 #include "subr.h"
54 #include "synch.h"
55 
56 /* Report processes that are running for too long not often than this value. */
57 #define	REPORT_INTERVAL	60
58 
59 /* Are we initialized? */
60 static bool hooks_initialized = false;
61 
62 /*
63  * Keep all processes we forked on a global queue, so we can report nicely
64  * when they finish or report that they are running for a long time.
65  */
66 #define	HOOKPROC_MAGIC_ALLOCATED	0x80090ca
67 #define	HOOKPROC_MAGIC_ONLIST		0x80090c0
68 struct hookproc {
69 	/* Magic. */
70 	int	hp_magic;
71 	/* PID of a forked child. */
72 	pid_t	hp_pid;
73 	/* When process were forked? */
74 	time_t	hp_birthtime;
75 	/* When we logged previous reported? */
76 	time_t	hp_lastreport;
77 	/* Path to executable and all the arguments we passed. */
78 	char	hp_comm[PATH_MAX];
79 	TAILQ_ENTRY(hookproc) hp_next;
80 };
81 static TAILQ_HEAD(, hookproc) hookprocs;
82 static pthread_mutex_t hookprocs_lock;
83 
84 static void hook_remove(struct hookproc *hp);
85 static void hook_free(struct hookproc *hp);
86 
87 static void
88 descriptors(void)
89 {
90 	int fd;
91 
92 	/*
93 	 * Close all (or almost all) descriptors.
94 	 */
95 	if (pjdlog_mode_get() == PJDLOG_MODE_STD) {
96 		closefrom(MAX(MAX(STDIN_FILENO, STDOUT_FILENO),
97 		    STDERR_FILENO) + 1);
98 		return;
99 	}
100 
101 	closefrom(0);
102 
103 	/*
104 	 * Redirect stdin, stdout and stderr to /dev/null.
105 	 */
106 	fd = open(_PATH_DEVNULL, O_RDONLY);
107 	if (fd == -1) {
108 		pjdlog_errno(LOG_WARNING, "Unable to open %s for reading",
109 		    _PATH_DEVNULL);
110 	} else if (fd != STDIN_FILENO) {
111 		if (dup2(fd, STDIN_FILENO) == -1) {
112 			pjdlog_errno(LOG_WARNING,
113 			    "Unable to duplicate descriptor for stdin");
114 		}
115 		close(fd);
116 	}
117 	fd = open(_PATH_DEVNULL, O_WRONLY);
118 	if (fd == -1) {
119 		pjdlog_errno(LOG_WARNING, "Unable to open %s for writing",
120 		    _PATH_DEVNULL);
121 	} else {
122 		if (fd != STDOUT_FILENO && dup2(fd, STDOUT_FILENO) == -1) {
123 			pjdlog_errno(LOG_WARNING,
124 			    "Unable to duplicate descriptor for stdout");
125 		}
126 		if (fd != STDERR_FILENO && dup2(fd, STDERR_FILENO) == -1) {
127 			pjdlog_errno(LOG_WARNING,
128 			    "Unable to duplicate descriptor for stderr");
129 		}
130 		if (fd != STDOUT_FILENO && fd != STDERR_FILENO)
131 			close(fd);
132 	}
133 }
134 
135 void
136 hook_init(void)
137 {
138 
139 	PJDLOG_ASSERT(!hooks_initialized);
140 
141 	mtx_init(&hookprocs_lock);
142 	TAILQ_INIT(&hookprocs);
143 	hooks_initialized = true;
144 }
145 
146 void
147 hook_fini(void)
148 {
149 	struct hookproc *hp;
150 
151 	PJDLOG_ASSERT(hooks_initialized);
152 
153 	mtx_lock(&hookprocs_lock);
154 	while ((hp = TAILQ_FIRST(&hookprocs)) != NULL) {
155 		PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ONLIST);
156 		PJDLOG_ASSERT(hp->hp_pid > 0);
157 
158 		hook_remove(hp);
159 		hook_free(hp);
160 	}
161 	mtx_unlock(&hookprocs_lock);
162 
163 	mtx_destroy(&hookprocs_lock);
164 	TAILQ_INIT(&hookprocs);
165 	hooks_initialized = false;
166 }
167 
168 static struct hookproc *
169 hook_alloc(const char *path, char **args)
170 {
171 	struct hookproc *hp;
172 	unsigned int ii;
173 
174 	hp = malloc(sizeof(*hp));
175 	if (hp == NULL) {
176 		pjdlog_error("Unable to allocate %zu bytes of memory for a hook.",
177 		    sizeof(*hp));
178 		return (NULL);
179 	}
180 
181 	hp->hp_pid = 0;
182 	hp->hp_birthtime = hp->hp_lastreport = time(NULL);
183 	(void)strlcpy(hp->hp_comm, path, sizeof(hp->hp_comm));
184 	/* We start at 2nd argument as we don't want to have exec name twice. */
185 	for (ii = 1; args[ii] != NULL; ii++) {
186 		(void)snprlcat(hp->hp_comm, sizeof(hp->hp_comm), " %s",
187 		    args[ii]);
188 	}
189 	if (strlen(hp->hp_comm) >= sizeof(hp->hp_comm) - 1) {
190 		pjdlog_error("Exec path too long, correct configuration file.");
191 		free(hp);
192 		return (NULL);
193 	}
194 	hp->hp_magic = HOOKPROC_MAGIC_ALLOCATED;
195 	return (hp);
196 }
197 
198 static void
199 hook_add(struct hookproc *hp, pid_t pid)
200 {
201 
202 	PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ALLOCATED);
203 	PJDLOG_ASSERT(hp->hp_pid == 0);
204 
205 	hp->hp_pid = pid;
206 	mtx_lock(&hookprocs_lock);
207 	hp->hp_magic = HOOKPROC_MAGIC_ONLIST;
208 	TAILQ_INSERT_TAIL(&hookprocs, hp, hp_next);
209 	mtx_unlock(&hookprocs_lock);
210 }
211 
212 static void
213 hook_remove(struct hookproc *hp)
214 {
215 
216 	PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ONLIST);
217 	PJDLOG_ASSERT(hp->hp_pid > 0);
218 	PJDLOG_ASSERT(mtx_owned(&hookprocs_lock));
219 
220 	TAILQ_REMOVE(&hookprocs, hp, hp_next);
221 	hp->hp_magic = HOOKPROC_MAGIC_ALLOCATED;
222 }
223 
224 static void
225 hook_free(struct hookproc *hp)
226 {
227 
228 	PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ALLOCATED);
229 	PJDLOG_ASSERT(hp->hp_pid > 0);
230 
231 	hp->hp_magic = 0;
232 	free(hp);
233 }
234 
235 static struct hookproc *
236 hook_find(pid_t pid)
237 {
238 	struct hookproc *hp;
239 
240 	PJDLOG_ASSERT(mtx_owned(&hookprocs_lock));
241 
242 	TAILQ_FOREACH(hp, &hookprocs, hp_next) {
243 		PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ONLIST);
244 		PJDLOG_ASSERT(hp->hp_pid > 0);
245 
246 		if (hp->hp_pid == pid)
247 			break;
248 	}
249 
250 	return (hp);
251 }
252 
253 void
254 hook_check_one(pid_t pid, int status)
255 {
256 	struct hookproc *hp;
257 
258 	mtx_lock(&hookprocs_lock);
259 	hp = hook_find(pid);
260 	if (hp == NULL) {
261 		mtx_unlock(&hookprocs_lock);
262 		pjdlog_debug(1, "Unknown process pid=%u", pid);
263 		return;
264 	}
265 	hook_remove(hp);
266 	mtx_unlock(&hookprocs_lock);
267 	if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
268 		pjdlog_debug(1, "Hook exited gracefully (pid=%u, cmd=[%s]).",
269 		    pid, hp->hp_comm);
270 	} else if (WIFSIGNALED(status)) {
271 		pjdlog_error("Hook was killed (pid=%u, signal=%d, cmd=[%s]).",
272 		    pid, WTERMSIG(status), hp->hp_comm);
273 	} else {
274 		pjdlog_error("Hook exited ungracefully (pid=%u, exitcode=%d, cmd=[%s]).",
275 		    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1,
276 		    hp->hp_comm);
277 	}
278 	hook_free(hp);
279 }
280 
281 void
282 hook_check(void)
283 {
284 	struct hookproc *hp, *hp2;
285 	time_t now;
286 
287 	PJDLOG_ASSERT(hooks_initialized);
288 
289 	pjdlog_debug(2, "Checking hooks.");
290 
291 	/*
292 	 * Report about processes that are running for a long time.
293 	 */
294 	now = time(NULL);
295 	mtx_lock(&hookprocs_lock);
296 	TAILQ_FOREACH_SAFE(hp, &hookprocs, hp_next, hp2) {
297 		PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ONLIST);
298 		PJDLOG_ASSERT(hp->hp_pid > 0);
299 
300 		/*
301 		 * If process doesn't exists we somehow missed it.
302 		 * Not much can be done expect for logging this situation.
303 		 */
304 		if (kill(hp->hp_pid, 0) == -1 && errno == ESRCH) {
305 			pjdlog_warning("Hook disappeared (pid=%u, cmd=[%s]).",
306 			    hp->hp_pid, hp->hp_comm);
307 			hook_remove(hp);
308 			hook_free(hp);
309 			continue;
310 		}
311 
312 		/*
313 		 * Skip proccesses younger than 1 minute.
314 		 */
315 		if (now - hp->hp_lastreport < REPORT_INTERVAL)
316 			continue;
317 
318 		/*
319 		 * Hook is running for too long, report it.
320 		 */
321 		pjdlog_warning("Hook is running for %ju seconds (pid=%u, cmd=[%s]).",
322 		    (uintmax_t)(now - hp->hp_birthtime), hp->hp_pid,
323 		    hp->hp_comm);
324 		hp->hp_lastreport = now;
325 	}
326 	mtx_unlock(&hookprocs_lock);
327 }
328 
329 void
330 hook_exec(const char *path, ...)
331 {
332 	va_list ap;
333 
334 	va_start(ap, path);
335 	hook_execv(path, ap);
336 	va_end(ap);
337 }
338 
339 void
340 hook_execv(const char *path, va_list ap)
341 {
342 	struct hookproc *hp;
343 	char *args[64];
344 	unsigned int ii;
345 	sigset_t mask;
346 	pid_t pid;
347 
348 	PJDLOG_ASSERT(hooks_initialized);
349 
350 	if (path == NULL || path[0] == '\0')
351 		return;
352 
353 	memset(args, 0, sizeof(args));
354 	args[0] = __DECONST(char *, path);
355 	for (ii = 1; ii < sizeof(args) / sizeof(args[0]); ii++) {
356 		args[ii] = va_arg(ap, char *);
357 		if (args[ii] == NULL)
358 			break;
359 	}
360 	PJDLOG_ASSERT(ii < sizeof(args) / sizeof(args[0]));
361 
362 	hp = hook_alloc(path, args);
363 	if (hp == NULL)
364 		return;
365 
366 	pjdlog_debug(1, "Executing hook: %s", hp->hp_comm);
367 
368 	pid = fork();
369 	switch (pid) {
370 	case -1:	/* Error. */
371 		pjdlog_errno(LOG_ERR, "Unable to fork to execute %s", path);
372 		hook_free(hp);
373 		return;
374 	case 0:		/* Child. */
375 		descriptors();
376 		PJDLOG_VERIFY(sigemptyset(&mask) == 0);
377 		PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
378 		/*
379 		 * Dummy handler set for SIGCHLD in the parent will be restored
380 		 * to SIG_IGN on execv(3) below, so there is no need to do
381 		 * anything with it.
382 		 */
383 		execv(path, args);
384 		pjdlog_errno(LOG_ERR, "Unable to execute %s", path);
385 		exit(EX_SOFTWARE);
386 	default:	/* Parent. */
387 		hook_add(hp, pid);
388 		break;
389 	}
390 }
391