xref: /freebsd/sbin/hastd/hooks.c (revision 0b3105a37d7adcadcb720112fed4dc4e8040be99)
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 <libgen.h>
41 #include <paths.h>
42 #include <signal.h>
43 #include <stdbool.h>
44 #include <stdint.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <syslog.h>
49 #include <unistd.h>
50 
51 #include <pjdlog.h>
52 
53 #include "hooks.h"
54 #include "subr.h"
55 #include "synch.h"
56 
57 /* Report processes that are running for too long not often than this value. */
58 #define	REPORT_INTERVAL	60
59 
60 /* Are we initialized? */
61 static bool hooks_initialized = false;
62 
63 /*
64  * Keep all processes we forked on a global queue, so we can report nicely
65  * when they finish or report that they are running for a long time.
66  */
67 #define	HOOKPROC_MAGIC_ALLOCATED	0x80090ca
68 #define	HOOKPROC_MAGIC_ONLIST		0x80090c0
69 struct hookproc {
70 	/* Magic. */
71 	int	hp_magic;
72 	/* PID of a forked child. */
73 	pid_t	hp_pid;
74 	/* When process were forked? */
75 	time_t	hp_birthtime;
76 	/* When we logged previous reported? */
77 	time_t	hp_lastreport;
78 	/* Path to executable and all the arguments we passed. */
79 	char	hp_comm[PATH_MAX];
80 	TAILQ_ENTRY(hookproc) hp_next;
81 };
82 static TAILQ_HEAD(, hookproc) hookprocs;
83 static pthread_mutex_t hookprocs_lock;
84 
85 static void hook_remove(struct hookproc *hp);
86 static void hook_free(struct hookproc *hp);
87 
88 static void
89 descriptors(void)
90 {
91 	int fd;
92 
93 	/*
94 	 * Close all (or almost all) descriptors.
95 	 */
96 	if (pjdlog_mode_get() == PJDLOG_MODE_STD) {
97 		closefrom(MAX(MAX(STDIN_FILENO, STDOUT_FILENO),
98 		    STDERR_FILENO) + 1);
99 		return;
100 	}
101 
102 	closefrom(0);
103 
104 	/*
105 	 * Redirect stdin, stdout and stderr to /dev/null.
106 	 */
107 	fd = open(_PATH_DEVNULL, O_RDONLY);
108 	if (fd == -1) {
109 		pjdlog_errno(LOG_WARNING, "Unable to open %s for reading",
110 		    _PATH_DEVNULL);
111 	} else if (fd != STDIN_FILENO) {
112 		if (dup2(fd, STDIN_FILENO) == -1) {
113 			pjdlog_errno(LOG_WARNING,
114 			    "Unable to duplicate descriptor for stdin");
115 		}
116 		close(fd);
117 	}
118 	fd = open(_PATH_DEVNULL, O_WRONLY);
119 	if (fd == -1) {
120 		pjdlog_errno(LOG_WARNING, "Unable to open %s for writing",
121 		    _PATH_DEVNULL);
122 	} else {
123 		if (fd != STDOUT_FILENO && dup2(fd, STDOUT_FILENO) == -1) {
124 			pjdlog_errno(LOG_WARNING,
125 			    "Unable to duplicate descriptor for stdout");
126 		}
127 		if (fd != STDERR_FILENO && dup2(fd, STDERR_FILENO) == -1) {
128 			pjdlog_errno(LOG_WARNING,
129 			    "Unable to duplicate descriptor for stderr");
130 		}
131 		if (fd != STDOUT_FILENO && fd != STDERR_FILENO)
132 			close(fd);
133 	}
134 }
135 
136 void
137 hook_init(void)
138 {
139 
140 	PJDLOG_ASSERT(!hooks_initialized);
141 
142 	mtx_init(&hookprocs_lock);
143 	TAILQ_INIT(&hookprocs);
144 	hooks_initialized = true;
145 }
146 
147 void
148 hook_fini(void)
149 {
150 	struct hookproc *hp;
151 
152 	PJDLOG_ASSERT(hooks_initialized);
153 
154 	mtx_lock(&hookprocs_lock);
155 	while ((hp = TAILQ_FIRST(&hookprocs)) != NULL) {
156 		PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ONLIST);
157 		PJDLOG_ASSERT(hp->hp_pid > 0);
158 
159 		hook_remove(hp);
160 		hook_free(hp);
161 	}
162 	mtx_unlock(&hookprocs_lock);
163 
164 	mtx_destroy(&hookprocs_lock);
165 	TAILQ_INIT(&hookprocs);
166 	hooks_initialized = false;
167 }
168 
169 static struct hookproc *
170 hook_alloc(const char *path, char **args)
171 {
172 	struct hookproc *hp;
173 	unsigned int ii;
174 
175 	hp = malloc(sizeof(*hp));
176 	if (hp == NULL) {
177 		pjdlog_error("Unable to allocate %zu bytes of memory for a hook.",
178 		    sizeof(*hp));
179 		return (NULL);
180 	}
181 
182 	hp->hp_pid = 0;
183 	hp->hp_birthtime = hp->hp_lastreport = time(NULL);
184 	(void)strlcpy(hp->hp_comm, path, sizeof(hp->hp_comm));
185 	/* We start at 2nd argument as we don't want to have exec name twice. */
186 	for (ii = 1; args[ii] != NULL; ii++) {
187 		(void)snprlcat(hp->hp_comm, sizeof(hp->hp_comm), " %s",
188 		    args[ii]);
189 	}
190 	if (strlen(hp->hp_comm) >= sizeof(hp->hp_comm) - 1) {
191 		pjdlog_error("Exec path too long, correct configuration file.");
192 		free(hp);
193 		return (NULL);
194 	}
195 	hp->hp_magic = HOOKPROC_MAGIC_ALLOCATED;
196 	return (hp);
197 }
198 
199 static void
200 hook_add(struct hookproc *hp, pid_t pid)
201 {
202 
203 	PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ALLOCATED);
204 	PJDLOG_ASSERT(hp->hp_pid == 0);
205 
206 	hp->hp_pid = pid;
207 	mtx_lock(&hookprocs_lock);
208 	hp->hp_magic = HOOKPROC_MAGIC_ONLIST;
209 	TAILQ_INSERT_TAIL(&hookprocs, hp, hp_next);
210 	mtx_unlock(&hookprocs_lock);
211 }
212 
213 static void
214 hook_remove(struct hookproc *hp)
215 {
216 
217 	PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ONLIST);
218 	PJDLOG_ASSERT(hp->hp_pid > 0);
219 	PJDLOG_ASSERT(mtx_owned(&hookprocs_lock));
220 
221 	TAILQ_REMOVE(&hookprocs, hp, hp_next);
222 	hp->hp_magic = HOOKPROC_MAGIC_ALLOCATED;
223 }
224 
225 static void
226 hook_free(struct hookproc *hp)
227 {
228 
229 	PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ALLOCATED);
230 	PJDLOG_ASSERT(hp->hp_pid > 0);
231 
232 	hp->hp_magic = 0;
233 	free(hp);
234 }
235 
236 static struct hookproc *
237 hook_find(pid_t pid)
238 {
239 	struct hookproc *hp;
240 
241 	PJDLOG_ASSERT(mtx_owned(&hookprocs_lock));
242 
243 	TAILQ_FOREACH(hp, &hookprocs, hp_next) {
244 		PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ONLIST);
245 		PJDLOG_ASSERT(hp->hp_pid > 0);
246 
247 		if (hp->hp_pid == pid)
248 			break;
249 	}
250 
251 	return (hp);
252 }
253 
254 void
255 hook_check_one(pid_t pid, int status)
256 {
257 	struct hookproc *hp;
258 
259 	mtx_lock(&hookprocs_lock);
260 	hp = hook_find(pid);
261 	if (hp == NULL) {
262 		mtx_unlock(&hookprocs_lock);
263 		pjdlog_debug(1, "Unknown process pid=%u", pid);
264 		return;
265 	}
266 	hook_remove(hp);
267 	mtx_unlock(&hookprocs_lock);
268 	if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
269 		pjdlog_debug(1, "Hook exited gracefully (pid=%u, cmd=[%s]).",
270 		    pid, hp->hp_comm);
271 	} else if (WIFSIGNALED(status)) {
272 		pjdlog_error("Hook was killed (pid=%u, signal=%d, cmd=[%s]).",
273 		    pid, WTERMSIG(status), hp->hp_comm);
274 	} else {
275 		pjdlog_error("Hook exited ungracefully (pid=%u, exitcode=%d, cmd=[%s]).",
276 		    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1,
277 		    hp->hp_comm);
278 	}
279 	hook_free(hp);
280 }
281 
282 void
283 hook_check(void)
284 {
285 	struct hookproc *hp, *hp2;
286 	time_t now;
287 
288 	PJDLOG_ASSERT(hooks_initialized);
289 
290 	pjdlog_debug(2, "Checking hooks.");
291 
292 	/*
293 	 * Report about processes that are running for a long time.
294 	 */
295 	now = time(NULL);
296 	mtx_lock(&hookprocs_lock);
297 	TAILQ_FOREACH_SAFE(hp, &hookprocs, hp_next, hp2) {
298 		PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ONLIST);
299 		PJDLOG_ASSERT(hp->hp_pid > 0);
300 
301 		/*
302 		 * If process doesn't exists we somehow missed it.
303 		 * Not much can be done expect for logging this situation.
304 		 */
305 		if (kill(hp->hp_pid, 0) == -1 && errno == ESRCH) {
306 			pjdlog_warning("Hook disappeared (pid=%u, cmd=[%s]).",
307 			    hp->hp_pid, hp->hp_comm);
308 			hook_remove(hp);
309 			hook_free(hp);
310 			continue;
311 		}
312 
313 		/*
314 		 * Skip proccesses younger than 1 minute.
315 		 */
316 		if (now - hp->hp_lastreport < REPORT_INTERVAL)
317 			continue;
318 
319 		/*
320 		 * Hook is running for too long, report it.
321 		 */
322 		pjdlog_warning("Hook is running for %ju seconds (pid=%u, cmd=[%s]).",
323 		    (uintmax_t)(now - hp->hp_birthtime), hp->hp_pid,
324 		    hp->hp_comm);
325 		hp->hp_lastreport = now;
326 	}
327 	mtx_unlock(&hookprocs_lock);
328 }
329 
330 void
331 hook_exec(const char *path, ...)
332 {
333 	va_list ap;
334 
335 	va_start(ap, path);
336 	hook_execv(path, ap);
337 	va_end(ap);
338 }
339 
340 void
341 hook_execv(const char *path, va_list ap)
342 {
343 	struct hookproc *hp;
344 	char *args[64];
345 	unsigned int ii;
346 	sigset_t mask;
347 	pid_t pid;
348 
349 	PJDLOG_ASSERT(hooks_initialized);
350 
351 	if (path == NULL || path[0] == '\0')
352 		return;
353 
354 	memset(args, 0, sizeof(args));
355 	args[0] = basename(path);
356 	for (ii = 1; ii < sizeof(args) / sizeof(args[0]); ii++) {
357 		args[ii] = va_arg(ap, char *);
358 		if (args[ii] == NULL)
359 			break;
360 	}
361 	PJDLOG_ASSERT(ii < sizeof(args) / sizeof(args[0]));
362 
363 	hp = hook_alloc(path, args);
364 	if (hp == NULL)
365 		return;
366 
367 	pjdlog_debug(1, "Executing hook: %s", hp->hp_comm);
368 
369 	pid = fork();
370 	switch (pid) {
371 	case -1:	/* Error. */
372 		pjdlog_errno(LOG_ERR, "Unable to fork to execute %s", path);
373 		hook_free(hp);
374 		return;
375 	case 0:		/* Child. */
376 		descriptors();
377 		PJDLOG_VERIFY(sigemptyset(&mask) == 0);
378 		PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
379 		/*
380 		 * Dummy handler set for SIGCHLD in the parent will be restored
381 		 * to SIG_IGN on execv(3) below, so there is no need to do
382 		 * anything with it.
383 		 */
384 		execv(path, args);
385 		pjdlog_errno(LOG_ERR, "Unable to execute %s", path);
386 		exit(EX_SOFTWARE);
387 	default:	/* Parent. */
388 		hook_add(hp, pid);
389 		break;
390 	}
391 }
392