1 /*****************************************************************************
3 * Monitoring run command utilities
6 * Copyright (c) 2005-2024 Monitoring Plugins Development Team
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
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()
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"
61 #ifdef HAVE_SYS_WAIT_H
62 # include <sys/wait.h>
65 /* used in _cmd_open to pass the environment to commands */
66 extern char **environ
;
70 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
74 # define WIFEXITED(stat_val) (((stat_val)&255) == 0)
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)
83 static int _cmd_open(char *const *, int *, int *) __attribute__((__nonnull__(1, 2, 3)));
85 static int _cmd_fetch_output(int, output
*, int) __attribute__((__nonnull__(2)));
87 static int _cmd_close(int);
89 /* prototype imported from utils.h */
90 extern void die(int, const char *, ...) __attribute__((__noreturn__
, __format__(__printf__
, 2, 3)));
92 /* this function is NOT async-safe. It is exported so multithreaded
93 * plugins (or other apps) can call it prior to running any commands
94 * through this api and thus achieve async-safeness throughout the api */
96 long maxfd
= mp_open_max();
98 /* if maxfd is unnaturally high, we force it to a lower value
99 * ( e.g. on SunOS, when ulimit is set to unlimited: 2147483647 this would cause
100 * a segfault when following calloc is called ... ) */
102 if (maxfd
> MAXFD_LIMIT
) {
107 _cmd_pids
= calloc(maxfd
, sizeof(pid_t
));
110 /* Start running a command, array style */
111 static int _cmd_open(char *const *argv
, int *pfd
, int *pfderr
) {
122 setenv("LC_ALL", "C", 1);
124 if (pipe(pfd
) < 0 || pipe(pfderr
) < 0 || (pid
= fork()) < 0)
125 return -1; /* errno set by the failing function */
127 /* child runs exceve() and _exit. */
130 /* the program we execve shouldn't leave core files */
131 getrlimit(RLIMIT_CORE
, &limit
);
133 setrlimit(RLIMIT_CORE
, &limit
);
136 if (pfd
[1] != STDOUT_FILENO
) {
137 dup2(pfd
[1], STDOUT_FILENO
);
141 if (pfderr
[1] != STDERR_FILENO
) {
142 dup2(pfderr
[1], STDERR_FILENO
);
146 /* close all descriptors in _cmd_pids[]
147 * This is executed in a separate address space (pure child),
148 * so we don't have to worry about async safety */
149 long maxfd
= mp_open_max();
150 for (i
= 0; i
< maxfd
; i
++)
151 if (_cmd_pids
[i
] > 0)
154 execve(argv
[0], argv
, environ
);
155 _exit(STATE_UNKNOWN
);
158 /* parent picks up execution here */
159 /* close children descriptors in our address space */
163 /* tag our file's entry in the pid-list and return it */
164 _cmd_pids
[pfd
[0]] = pid
;
169 static int _cmd_close(int fd
) {
173 /* make sure the provided fd was opened */
174 long maxfd
= mp_open_max();
175 if (fd
< 0 || fd
> maxfd
|| !_cmd_pids
|| (pid
= _cmd_pids
[fd
]) == 0)
182 /* EINTR is ok (sort of), everything else is bad */
183 while (waitpid(pid
, &status
, 0) < 0)
187 /* return child's termination status */
188 return (WIFEXITED(status
)) ? WEXITSTATUS(status
) : -1;
191 static int _cmd_fetch_output(int fd
, output
*op
, int flags
) {
192 size_t len
= 0, i
= 0, lineno
= 0;
193 size_t rsf
= 6, ary_size
= 0; /* rsf = right shift factor, dec'ed uncond once */
200 while ((ret
= read(fd
, tmpbuf
, sizeof(tmpbuf
))) > 0) {
202 op
->buf
= realloc(op
->buf
, op
->buflen
+ len
+ 1);
203 memcpy(op
->buf
+ op
->buflen
, tmpbuf
, len
);
209 printf("read() returned %d: %s\n", ret
, strerror(errno
));
213 /* some plugins may want to keep output unbroken, and some commands
214 * will yield no output, so return here for those */
215 if (flags
& CMD_NO_ARRAYS
|| !op
->buf
|| !op
->buflen
)
218 /* and some may want both */
219 if (flags
& CMD_NO_ASSOC
) {
220 buf
= malloc(op
->buflen
);
221 memcpy(buf
, op
->buf
, op
->buflen
);
228 while (i
< op
->buflen
) {
229 /* make sure we have enough memory */
230 if (lineno
>= ary_size
) {
231 /* ary_size must never be zero */
233 ary_size
= op
->buflen
>> --rsf
;
236 op
->line
= realloc(op
->line
, ary_size
* sizeof(char *));
237 op
->lens
= realloc(op
->lens
, ary_size
* sizeof(size_t));
240 /* set the pointer to the string */
241 op
->line
[lineno
] = &buf
[i
];
243 /* hop to next newline or end of buffer */
244 while (buf
[i
] != '\n' && i
< op
->buflen
)
248 /* calculate the string length using pointer difference */
249 op
->lens
[lineno
] = (size_t)&buf
[i
] - (size_t)op
->line
[lineno
];
258 int cmd_run(const char *cmdstring
, output
*out
, output
*err
, int flags
) {
265 if (cmdstring
== NULL
)
268 /* initialize the structs */
270 memset(out
, 0, sizeof(output
));
272 memset(err
, 0, sizeof(output
));
274 /* make copy of command string so strtok() doesn't silently modify it */
275 /* (the calling program may want to access it later) */
276 cmdlen
= strlen(cmdstring
);
277 if ((cmd
= malloc(cmdlen
+ 1)) == NULL
)
279 memcpy(cmd
, cmdstring
, cmdlen
);
282 /* This is not a shell, so we don't handle "???" */
283 if (strstr(cmdstring
, "\""))
286 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
287 if (strstr(cmdstring
, " ' ") || strstr(cmdstring
, "'''"))
290 /* each arg must be whitespace-separated, so args can be a maximum
291 * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
292 argc
= (cmdlen
>> 1) + 2;
293 argv
= calloc((size_t)argc
, sizeof(char *));
296 printf("%s\n", _("Could not malloc argv array in popen()"));
300 /* get command arguments (stupidly, but fairly quickly) */
303 str
+= strspn(str
, " \t\r\n"); /* trim any leading whitespace */
305 if (strstr(str
, "'") == str
) { /* handle SIMPLE quoted strings */
307 if (!strstr(str
, "'"))
308 return -1; /* balanced? */
309 cmd
= 1 + strstr(str
, "'");
310 str
[strcspn(str
, "'")] = 0;
312 if (strpbrk(str
, " \t\r\n")) {
313 cmd
= 1 + strpbrk(str
, " \t\r\n");
314 str
[strcspn(str
, " \t\r\n")] = 0;
320 if (cmd
&& strlen(cmd
) == strspn(cmd
, " \t\r\n"))
326 return cmd_run_array(argv
, out
, err
, flags
);
329 int cmd_run_array(char *const *argv
, output
*out
, output
*err
, int flags
) {
330 int fd
, pfd_out
[2], pfd_err
[2];
332 /* initialize the structs */
334 memset(out
, 0, sizeof(output
));
336 memset(err
, 0, sizeof(output
));
338 if ((fd
= _cmd_open(argv
, pfd_out
, pfd_err
)) == -1)
339 die(STATE_UNKNOWN
, _("Could not open pipe: %s\n"), argv
[0]);
342 out
->lines
= _cmd_fetch_output(pfd_out
[0], out
, flags
);
344 err
->lines
= _cmd_fetch_output(pfd_err
[0], err
, flags
);
346 return _cmd_close(fd
);
349 int cmd_file_read(char *filename
, output
*out
, int flags
) {
352 memset(out
, 0, sizeof(output
));
354 if ((fd
= open(filename
, O_RDONLY
)) == -1) {
355 die(STATE_UNKNOWN
, _("Error opening %s: %s"), filename
, strerror(errno
));
359 out
->lines
= _cmd_fetch_output(fd
, out
, flags
);
362 die(STATE_UNKNOWN
, _("Error closing %s: %s"), filename
, strerror(errno
));
367 void timeout_alarm_handler(int signo
) {
368 if (signo
== SIGALRM
) {
369 printf(_("%s - Plugin timed out after %d seconds\n"), state_text(timeout_state
), timeout_interval
);
371 long maxfd
= mp_open_max();
373 for (long int i
= 0; i
< maxfd
; i
++) {
374 if (_cmd_pids
[i
] != 0)
375 kill(_cmd_pids
[i
], SIGKILL
);