check_curl: fix relative redirects on non-standard port
[monitoring-plugins.git] / lib / utils_cmd.c
blob7957ec14d43595d64dd3906639132e7e2e5a29bf
1 /*****************************************************************************
3 * Monitoring run command utilities
5 * License: GPL
6 * Copyright (c) 2005-2006 Monitoring Plugins Development Team
8 * Description :
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.
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.
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.
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.
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.
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/>.
37 *****************************************************************************/
39 #define NAGIOSPLUG_API_C 1
41 /** includes **/
42 #include "common.h"
43 #include "utils.h"
44 #include "utils_cmd.h"
45 /* This variable must be global, since there's no way the caller
46 * can forcibly slay a dead or ungainly running program otherwise.
47 * Multithreading apps and plugins can initialize it (via CMD_INIT)
48 * in an async safe manner PRIOR to calling cmd_run() or cmd_run_array()
49 * for the first time.
51 * The check for initialized values is atomic and can
52 * occur in any number of threads simultaneously. */
53 static pid_t *_cmd_pids = NULL;
55 #include "utils_base.h"
57 #include "./maxfd.h"
59 #include <fcntl.h>
61 #ifdef HAVE_SYS_WAIT_H
62 # include <sys/wait.h>
63 #endif
65 /* used in _cmd_open to pass the environment to commands */
66 extern char **environ;
68 /** macros **/
69 #ifndef WEXITSTATUS
70 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
71 #endif
73 #ifndef WIFEXITED
74 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
75 #endif
77 /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
78 #if defined(SIG_IGN) && !defined(SIG_ERR)
79 # define SIG_ERR ((Sigfunc *)-1)
80 #endif
82 /** prototypes **/
83 static int _cmd_open (char *const *, int *, int *)
84 __attribute__ ((__nonnull__ (1, 2, 3)));
86 static int _cmd_fetch_output (int, output *, int)
87 __attribute__ ((__nonnull__ (2)));
89 static int _cmd_close (int);
91 /* prototype imported from utils.h */
92 extern void die (int, const char *, ...)
93 __attribute__ ((__noreturn__, __format__ (__printf__, 2, 3)));
96 /* this function is NOT async-safe. It is exported so multithreaded
97 * plugins (or other apps) can call it prior to running any commands
98 * through this api and thus achieve async-safeness throughout the api */
99 void
100 cmd_init (void)
102 long maxfd = mp_open_max();
104 /* if maxfd is unnaturally high, we force it to a lower value
105 * ( e.g. on SunOS, when ulimit is set to unlimited: 2147483647 this would cause
106 * a segfault when following calloc is called ... ) */
108 if ( maxfd > MAXFD_LIMIT ) {
109 maxfd = MAXFD_LIMIT;
112 if (!_cmd_pids)
113 _cmd_pids = calloc (maxfd, sizeof (pid_t));
117 /* Start running a command, array style */
118 static int
119 _cmd_open (char *const *argv, int *pfd, int *pfderr)
121 pid_t pid;
122 #ifdef RLIMIT_CORE
123 struct rlimit limit;
124 #endif
126 int i = 0;
128 if (!_cmd_pids)
129 CMD_INIT;
131 setenv("LC_ALL", "C", 1);
133 if (pipe (pfd) < 0 || pipe (pfderr) < 0 || (pid = fork ()) < 0)
134 return -1; /* errno set by the failing function */
136 /* child runs exceve() and _exit. */
137 if (pid == 0) {
138 #ifdef RLIMIT_CORE
139 /* the program we execve shouldn't leave core files */
140 getrlimit (RLIMIT_CORE, &limit);
141 limit.rlim_cur = 0;
142 setrlimit (RLIMIT_CORE, &limit);
143 #endif
144 close (pfd[0]);
145 if (pfd[1] != STDOUT_FILENO) {
146 dup2 (pfd[1], STDOUT_FILENO);
147 close (pfd[1]);
149 close (pfderr[0]);
150 if (pfderr[1] != STDERR_FILENO) {
151 dup2 (pfderr[1], STDERR_FILENO);
152 close (pfderr[1]);
155 /* close all descriptors in _cmd_pids[]
156 * This is executed in a separate address space (pure child),
157 * so we don't have to worry about async safety */
158 long maxfd = mp_open_max();
159 for (i = 0; i < maxfd; i++)
160 if (_cmd_pids[i] > 0)
161 close (i);
163 execve (argv[0], argv, environ);
164 _exit (STATE_UNKNOWN);
167 /* parent picks up execution here */
168 /* close children descriptors in our address space */
169 close (pfd[1]);
170 close (pfderr[1]);
172 /* tag our file's entry in the pid-list and return it */
173 _cmd_pids[pfd[0]] = pid;
175 return pfd[0];
178 static int
179 _cmd_close (int fd)
181 int status;
182 pid_t pid;
184 /* make sure the provided fd was opened */
185 long maxfd = mp_open_max();
186 if (fd < 0 || fd > maxfd || !_cmd_pids || (pid = _cmd_pids[fd]) == 0)
187 return -1;
189 _cmd_pids[fd] = 0;
190 if (close (fd) == -1)
191 return -1;
193 /* EINTR is ok (sort of), everything else is bad */
194 while (waitpid (pid, &status, 0) < 0)
195 if (errno != EINTR)
196 return -1;
198 /* return child's termination status */
199 return (WIFEXITED (status)) ? WEXITSTATUS (status) : -1;
203 static int
204 _cmd_fetch_output (int fd, output * op, int flags)
206 size_t len = 0, i = 0, lineno = 0;
207 size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
208 char *buf = NULL;
209 int ret;
210 char tmpbuf[4096];
212 op->buf = NULL;
213 op->buflen = 0;
214 while ((ret = read (fd, tmpbuf, sizeof (tmpbuf))) > 0) {
215 len = (size_t) ret;
216 op->buf = realloc (op->buf, op->buflen + len + 1);
217 memcpy (op->buf + op->buflen, tmpbuf, len);
218 op->buflen += len;
219 i++;
222 if (ret < 0) {
223 printf ("read() returned %d: %s\n", ret, strerror (errno));
224 return ret;
227 /* some plugins may want to keep output unbroken, and some commands
228 * will yield no output, so return here for those */
229 if (flags & CMD_NO_ARRAYS || !op->buf || !op->buflen)
230 return op->buflen;
232 /* and some may want both */
233 if (flags & CMD_NO_ASSOC) {
234 buf = malloc (op->buflen);
235 memcpy (buf, op->buf, op->buflen);
237 else
238 buf = op->buf;
240 op->line = NULL;
241 op->lens = NULL;
242 i = 0;
243 while (i < op->buflen) {
244 /* make sure we have enough memory */
245 if (lineno >= ary_size) {
246 /* ary_size must never be zero */
247 do {
248 ary_size = op->buflen >> --rsf;
249 } while (!ary_size);
251 op->line = realloc (op->line, ary_size * sizeof (char *));
252 op->lens = realloc (op->lens, ary_size * sizeof (size_t));
255 /* set the pointer to the string */
256 op->line[lineno] = &buf[i];
258 /* hop to next newline or end of buffer */
259 while (buf[i] != '\n' && i < op->buflen)
260 i++;
261 buf[i] = '\0';
263 /* calculate the string length using pointer difference */
264 op->lens[lineno] = (size_t) & buf[i] - (size_t) op->line[lineno];
266 lineno++;
267 i++;
270 return lineno;
275 cmd_run (const char *cmdstring, output * out, output * err, int flags)
277 int i = 0, argc;
278 size_t cmdlen;
279 char **argv = NULL;
280 char *cmd = NULL;
281 char *str = NULL;
283 if (cmdstring == NULL)
284 return -1;
286 /* initialize the structs */
287 if (out)
288 memset (out, 0, sizeof (output));
289 if (err)
290 memset (err, 0, sizeof (output));
292 /* make copy of command string so strtok() doesn't silently modify it */
293 /* (the calling program may want to access it later) */
294 cmdlen = strlen (cmdstring);
295 if ((cmd = malloc (cmdlen + 1)) == NULL)
296 return -1;
297 memcpy (cmd, cmdstring, cmdlen);
298 cmd[cmdlen] = '\0';
300 /* This is not a shell, so we don't handle "???" */
301 if (strstr (cmdstring, "\"")) return -1;
303 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
304 if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
305 return -1;
307 /* each arg must be whitespace-separated, so args can be a maximum
308 * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
309 argc = (cmdlen >> 1) + 2;
310 argv = calloc (sizeof (char *), argc);
312 if (argv == NULL) {
313 printf ("%s\n", _("Could not malloc argv array in popen()"));
314 return -1;
317 /* get command arguments (stupidly, but fairly quickly) */
318 while (cmd) {
319 str = cmd;
320 str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
322 if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
323 str++;
324 if (!strstr (str, "'"))
325 return -1; /* balanced? */
326 cmd = 1 + strstr (str, "'");
327 str[strcspn (str, "'")] = 0;
329 else {
330 if (strpbrk (str, " \t\r\n")) {
331 cmd = 1 + strpbrk (str, " \t\r\n");
332 str[strcspn (str, " \t\r\n")] = 0;
334 else {
335 cmd = NULL;
339 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
340 cmd = NULL;
342 argv[i++] = str;
345 return cmd_run_array (argv, out, err, flags);
349 cmd_run_array (char *const *argv, output * out, output * err, int flags)
351 int fd, pfd_out[2], pfd_err[2];
353 /* initialize the structs */
354 if (out)
355 memset (out, 0, sizeof (output));
356 if (err)
357 memset (err, 0, sizeof (output));
359 if ((fd = _cmd_open (argv, pfd_out, pfd_err)) == -1)
360 die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), argv[0]);
362 if (out)
363 out->lines = _cmd_fetch_output (pfd_out[0], out, flags);
364 if (err)
365 err->lines = _cmd_fetch_output (pfd_err[0], err, flags);
367 return _cmd_close (fd);
371 cmd_file_read ( char *filename, output *out, int flags)
373 int fd;
374 if(out)
375 memset (out, 0, sizeof(output));
377 if ((fd = open(filename, O_RDONLY)) == -1) {
378 die( STATE_UNKNOWN, _("Error opening %s: %s"), filename, strerror(errno) );
381 if(out)
382 out->lines = _cmd_fetch_output (fd, out, flags);
384 if (close(fd) == -1)
385 die( STATE_UNKNOWN, _("Error closing %s: %s"), filename, strerror(errno) );
387 return 0;
390 void
391 timeout_alarm_handler (int signo)
393 if (signo == SIGALRM) {
394 printf (_("%s - Plugin timed out after %d seconds\n"),
395 state_text(timeout_state), timeout_interval);
397 long maxfd = mp_open_max();
398 if(_cmd_pids) for(long int i = 0; i < maxfd; i++) {
399 if(_cmd_pids[i] != 0) kill(_cmd_pids[i], SIGKILL);
402 exit (timeout_state);