1 /*****************************************************************************
2 *
3 * Monitoring run command utilities
4 *
5 * License: GPL
6 * Copyright (c) 2005-2006 Monitoring Plugins Development Team
7 *
8 * Description :
9 *
10 * A simple interface to executing programs from other programs, using an
11 * optimized and safe popen()-like implementation. It is considered safe
12 * in that no shell needs to be spawned and the environment passed to the
13 * execve()'d program is essentially empty.
14 *
15 * The code in this file is a derivative of popen.c which in turn was taken
16 * from "Advanced Programming for the Unix Environment" by W. Richard Stevens.
17 *
18 * Care has been taken to make sure the functions are async-safe. The one
19 * function which isn't is cmd_init() which it doesn't make sense to
20 * call twice anyway, so the api as a whole should be considered async-safe.
21 *
22 *
23 * This program is free software: you can redistribute it and/or modify
24 * it under the terms of the GNU General Public License as published by
25 * the Free Software Foundation, either version 3 of the License, or
26 * (at your option) any later version.
27 *
28 * This program is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
31 * GNU General Public License for more details.
32 *
33 * You should have received a copy of the GNU General Public License
34 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
35 *
36 *
37 *****************************************************************************/
38 
39 #define NAGIOSPLUG_API_C 1
40 
41 /** includes **/
42 #include "common.h"
43 #include "utils.h"
44 #include "utils_cmd.h"
45 #include "utils_base.h"
46 #include <fcntl.h>
47 
48 #ifdef HAVE_SYS_WAIT_H
49 # include <sys/wait.h>
50 #endif
51 
52 /* used in _cmd_open to pass the environment to commands */
53 extern char **environ;
54 
55 /** macros **/
56 #ifndef WEXITSTATUS
57 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
58 #endif
59 
60 #ifndef WIFEXITED
61 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
62 #endif
63 
64 /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
65 #if defined(SIG_IGN) && !defined(SIG_ERR)
66 # define SIG_ERR ((Sigfunc *)-1)
67 #endif
68 
69 /** prototypes **/
70 static int _cmd_open (char *const *, int *, int *)
71 	__attribute__ ((__nonnull__ (1, 2, 3)));
72 
73 static int _cmd_fetch_output (int, output *, int)
74 	__attribute__ ((__nonnull__ (2)));
75 
76 static int _cmd_close (int);
77 
78 /* prototype imported from utils.h */
79 extern void die (int, const char *, ...)
80 	__attribute__ ((__noreturn__, __format__ (__printf__, 2, 3)));
81 
82 
83 /* this function is NOT async-safe. It is exported so multithreaded
84  * plugins (or other apps) can call it prior to running any commands
85  * through this api and thus achieve async-safeness throughout the api */
86 void
cmd_init(void)87 cmd_init (void)
88 {
89 #ifndef maxfd
90 	if (!maxfd && (maxfd = sysconf (_SC_OPEN_MAX)) < 0) {
91 		/* possibly log or emit a warning here, since there's no
92 		 * guarantee that our guess at maxfd will be adequate */
93 		maxfd = DEFAULT_MAXFD;
94 	}
95 #endif
96 
97 	/* if maxfd is unnaturally high, we force it to a lower value
98 	 * ( e.g. on SunOS, when ulimit is set to unlimited: 2147483647 this would cause
99 	 * a segfault when following calloc is called ...  ) */
100 
101 	if ( maxfd > MAXFD_LIMIT ) {
102 		maxfd = MAXFD_LIMIT;
103 	}
104 
105 	if (!_cmd_pids)
106 		_cmd_pids = calloc (maxfd, sizeof (pid_t));
107 }
108 
109 
110 /* Start running a command, array style */
111 static int
_cmd_open(char * const * argv,int * pfd,int * pfderr)112 _cmd_open (char *const *argv, int *pfd, int *pfderr)
113 {
114 	pid_t pid;
115 #ifdef RLIMIT_CORE
116 	struct rlimit limit;
117 #endif
118 
119 	int i = 0;
120 
121 	/* if no command was passed, return with no error */
122 	if (argv == NULL)
123 		return -1;
124 
125 	if (!_cmd_pids)
126 		CMD_INIT;
127 
128 	setenv("LC_ALL", "C", 1);
129 
130 	if (pipe (pfd) < 0 || pipe (pfderr) < 0 || (pid = fork ()) < 0)
131 		return -1;									/* errno set by the failing function */
132 
133 	/* child runs exceve() and _exit. */
134 	if (pid == 0) {
135 #ifdef 	RLIMIT_CORE
136 		/* the program we execve shouldn't leave core files */
137 		getrlimit (RLIMIT_CORE, &limit);
138 		limit.rlim_cur = 0;
139 		setrlimit (RLIMIT_CORE, &limit);
140 #endif
141 		close (pfd[0]);
142 		if (pfd[1] != STDOUT_FILENO) {
143 			dup2 (pfd[1], STDOUT_FILENO);
144 			close (pfd[1]);
145 		}
146 		close (pfderr[0]);
147 		if (pfderr[1] != STDERR_FILENO) {
148 			dup2 (pfderr[1], STDERR_FILENO);
149 			close (pfderr[1]);
150 		}
151 
152 		/* close all descriptors in _cmd_pids[]
153 		 * This is executed in a separate address space (pure child),
154 		 * so we don't have to worry about async safety */
155 		for (i = 0; i < maxfd; i++)
156 			if (_cmd_pids[i] > 0)
157 				close (i);
158 
159 		execve (argv[0], argv, environ);
160 		_exit (STATE_UNKNOWN);
161 	}
162 
163 	/* parent picks up execution here */
164 	/* close childs descriptors in our address space */
165 	close (pfd[1]);
166 	close (pfderr[1]);
167 
168 	/* tag our file's entry in the pid-list and return it */
169 	_cmd_pids[pfd[0]] = pid;
170 
171 	return pfd[0];
172 }
173 
174 static int
_cmd_close(int fd)175 _cmd_close (int fd)
176 {
177 	int status;
178 	pid_t pid;
179 
180 	/* make sure the provided fd was opened */
181 	if (fd < 0 || fd > maxfd || !_cmd_pids || (pid = _cmd_pids[fd]) == 0)
182 		return -1;
183 
184 	_cmd_pids[fd] = 0;
185 	if (close (fd) == -1)
186 		return -1;
187 
188 	/* EINTR is ok (sort of), everything else is bad */
189 	while (waitpid (pid, &status, 0) < 0)
190 		if (errno != EINTR)
191 			return -1;
192 
193 	/* return child's termination status */
194 	return (WIFEXITED (status)) ? WEXITSTATUS (status) : -1;
195 }
196 
197 
198 static int
_cmd_fetch_output(int fd,output * op,int flags)199 _cmd_fetch_output (int fd, output * op, int flags)
200 {
201 	size_t len = 0, i = 0, lineno = 0;
202 	size_t rsf = 6, ary_size = 0;	/* rsf = right shift factor, dec'ed uncond once */
203 	char *buf = NULL;
204 	int ret;
205 	char tmpbuf[4096];
206 
207 	op->buf = NULL;
208 	op->buflen = 0;
209 	while ((ret = read (fd, tmpbuf, sizeof (tmpbuf))) > 0) {
210 		len = (size_t) ret;
211 		op->buf = realloc (op->buf, op->buflen + len + 1);
212 		memcpy (op->buf + op->buflen, tmpbuf, len);
213 		op->buflen += len;
214 		i++;
215 	}
216 
217 	if (ret < 0) {
218 		printf ("read() returned %d: %s\n", ret, strerror (errno));
219 		return ret;
220 	}
221 
222 	/* some plugins may want to keep output unbroken, and some commands
223 	 * will yield no output, so return here for those */
224 	if (flags & CMD_NO_ARRAYS || !op->buf || !op->buflen)
225 		return op->buflen;
226 
227 	/* and some may want both */
228 	if (flags & CMD_NO_ASSOC) {
229 		buf = malloc (op->buflen);
230 		memcpy (buf, op->buf, op->buflen);
231 	}
232 	else
233 		buf = op->buf;
234 
235 	op->line = NULL;
236 	op->lens = NULL;
237 	i = 0;
238 	while (i < op->buflen) {
239 		/* make sure we have enough memory */
240 		if (lineno >= ary_size) {
241 			/* ary_size must never be zero */
242 			do {
243 				ary_size = op->buflen >> --rsf;
244 			} while (!ary_size);
245 
246 			op->line = realloc (op->line, ary_size * sizeof (char *));
247 			op->lens = realloc (op->lens, ary_size * sizeof (size_t));
248 		}
249 
250 		/* set the pointer to the string */
251 		op->line[lineno] = &buf[i];
252 
253 		/* hop to next newline or end of buffer */
254 		while (buf[i] != '\n' && i < op->buflen)
255 			i++;
256 		buf[i] = '\0';
257 
258 		/* calculate the string length using pointer difference */
259 		op->lens[lineno] = (size_t) & buf[i] - (size_t) op->line[lineno];
260 
261 		lineno++;
262 		i++;
263 	}
264 
265 	return lineno;
266 }
267 
268 
269 int
cmd_run(const char * cmdstring,output * out,output * err,int flags)270 cmd_run (const char *cmdstring, output * out, output * err, int flags)
271 {
272 	int fd, pfd_out[2], pfd_err[2];
273 	int i = 0, argc;
274 	size_t cmdlen;
275 	char **argv = NULL;
276 	char *cmd = NULL;
277 	char *str = NULL;
278 
279 	if (cmdstring == NULL)
280 		return -1;
281 
282 	/* initialize the structs */
283 	if (out)
284 		memset (out, 0, sizeof (output));
285 	if (err)
286 		memset (err, 0, sizeof (output));
287 
288 	/* make copy of command string so strtok() doesn't silently modify it */
289 	/* (the calling program may want to access it later) */
290 	cmdlen = strlen (cmdstring);
291 	if ((cmd = malloc (cmdlen + 1)) == NULL)
292 		return -1;
293 	memcpy (cmd, cmdstring, cmdlen);
294 	cmd[cmdlen] = '\0';
295 
296 	/* This is not a shell, so we don't handle "???" */
297 	if (strstr (cmdstring, "\"")) return -1;
298 
299 	/* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
300 	if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
301 		return -1;
302 
303 	/* each arg must be whitespace-separated, so args can be a maximum
304 	 * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
305 	argc = (cmdlen >> 1) + 2;
306 	argv = calloc (sizeof (char *), argc);
307 
308 	if (argv == NULL) {
309 		printf ("%s\n", _("Could not malloc argv array in popen()"));
310 		return -1;
311 	}
312 
313 	/* get command arguments (stupidly, but fairly quickly) */
314 	while (cmd) {
315 		str = cmd;
316 		str += strspn (str, " \t\r\n");	/* trim any leading whitespace */
317 
318 		if (strstr (str, "'") == str) {	/* handle SIMPLE quoted strings */
319 			str++;
320 			if (!strstr (str, "'"))
321 				return -1;							/* balanced? */
322 			cmd = 1 + strstr (str, "'");
323 			str[strcspn (str, "'")] = 0;
324 		}
325 		else {
326 			if (strpbrk (str, " \t\r\n")) {
327 				cmd = 1 + strpbrk (str, " \t\r\n");
328 				str[strcspn (str, " \t\r\n")] = 0;
329 			}
330 			else {
331 				cmd = NULL;
332 			}
333 		}
334 
335 		if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
336 			cmd = NULL;
337 
338 		argv[i++] = str;
339 	}
340 
341 	return cmd_run_array (argv, out, err, flags);
342 }
343 
344 int
cmd_run_array(char * const * argv,output * out,output * err,int flags)345 cmd_run_array (char *const *argv, output * out, output * err, int flags)
346 {
347 	int fd, pfd_out[2], pfd_err[2];
348 
349 	/* initialize the structs */
350 	if (out)
351 		memset (out, 0, sizeof (output));
352 	if (err)
353 		memset (err, 0, sizeof (output));
354 
355 	if ((fd = _cmd_open (argv, pfd_out, pfd_err)) == -1)
356 		die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), argv[0]);
357 
358 	if (out)
359 		out->lines = _cmd_fetch_output (pfd_out[0], out, flags);
360 	if (err)
361 		err->lines = _cmd_fetch_output (pfd_err[0], err, flags);
362 
363 	return _cmd_close (fd);
364 }
365 
366 int
cmd_file_read(char * filename,output * out,int flags)367 cmd_file_read ( char *filename, output *out, int flags)
368 {
369 	int fd;
370 	if(out)
371 		memset (out, 0, sizeof(output));
372 
373 	if ((fd = open(filename, O_RDONLY)) == -1) {
374 		die( STATE_UNKNOWN, _("Error opening %s: %s"), filename, strerror(errno) );
375 	}
376 
377 	if(out)
378 		out->lines = _cmd_fetch_output (fd, out, flags);
379 
380 	if (close(fd) == -1)
381 		die( STATE_UNKNOWN, _("Error closing %s: %s"), filename, strerror(errno) );
382 
383 	return 0;
384 }
385 
386 void
timeout_alarm_handler(int signo)387 timeout_alarm_handler (int signo)
388 {
389 	size_t i;
390 	if (signo == SIGALRM) {
391 		printf (_("%s - Plugin timed out after %d seconds\n"),
392 						state_text(timeout_state), timeout_interval);
393 
394 		if(_cmd_pids) for(i = 0; i < maxfd; i++) {
395 			if(_cmd_pids[i] != 0) kill(_cmd_pids[i], SIGKILL);
396 		}
397 
398 		exit (timeout_state);
399 	}
400 }
401