Merge pull request #2045 from RincewindsHat/fix/calloc_argument_order
[monitoring-plugins.git] / plugins / runcmd.c
blob748431499d3ca92ea6f21e2b2737d9176009186f
1 /*****************************************************************************
3 * Monitoring run command utilities
5 * License: GPL
6 * Copyright (c) 2005-2024 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 np_runcmd_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 "runcmd.h"
43 #ifdef HAVE_SYS_WAIT_H
44 # include <sys/wait.h>
45 #endif
47 #include "./utils.h"
49 /** macros **/
50 #ifndef WEXITSTATUS
51 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
52 #endif
54 #ifndef WIFEXITED
55 # define WIFEXITED(stat_val) (((stat_val)&255) == 0)
56 #endif
58 /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
59 #if defined(SIG_IGN) && !defined(SIG_ERR)
60 # define SIG_ERR ((Sigfunc *)-1)
61 #endif
63 #include "../lib/maxfd.h"
65 /* This variable must be global, since there's no way the caller
66 * can forcibly slay a dead or ungainly running program otherwise.
67 * Multithreading apps and plugins can initialize it (via NP_RUNCMD_INIT)
68 * in an async safe manner PRIOR to calling np_runcmd() for the first time.
70 * The check for initialized values is atomic and can
71 * occur in any number of threads simultaneously. */
72 static pid_t *np_pids = NULL;
74 /** prototypes **/
75 static int np_runcmd_open(const char *, int *, int *) __attribute__((__nonnull__(1, 2, 3)));
77 static int np_fetch_output(int, output *, int) __attribute__((__nonnull__(2)));
79 static int np_runcmd_close(int);
81 /* prototype imported from utils.h */
82 extern void die(int, const char *, ...) __attribute__((__noreturn__, __format__(__printf__, 2, 3)));
84 /* this function is NOT async-safe. It is exported so multithreaded
85 * plugins (or other apps) can call it prior to running any commands
86 * through this api and thus achieve async-safeness throughout the api */
87 void np_runcmd_init(void) {
88 long maxfd = mp_open_max();
89 if (!np_pids)
90 np_pids = calloc(maxfd, sizeof(pid_t));
93 /* Start running a command */
94 static int np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr) {
95 char *env[2];
96 char *cmd = NULL;
97 char **argv = NULL;
98 char *str;
99 int argc;
100 size_t cmdlen;
101 pid_t pid;
102 #ifdef RLIMIT_CORE
103 struct rlimit limit;
104 #endif
106 int i = 0;
108 if (!np_pids)
109 NP_RUNCMD_INIT;
111 env[0] = strdup("LC_ALL=C");
112 env[1] = NULL;
114 /* make copy of command string so strtok() doesn't silently modify it */
115 /* (the calling program may want to access it later) */
116 cmdlen = strlen(cmdstring);
117 if ((cmd = malloc(cmdlen + 1)) == NULL)
118 return -1;
119 memcpy(cmd, cmdstring, cmdlen);
120 cmd[cmdlen] = '\0';
122 /* This is not a shell, so we don't handle "???" */
123 if (strstr(cmdstring, "\""))
124 return -1;
126 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
127 if (strstr(cmdstring, " ' ") || strstr(cmdstring, "'''"))
128 return -1;
130 /* each arg must be whitespace-separated, so args can be a maximum
131 * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
132 argc = (cmdlen >> 1) + 2;
133 argv = calloc(argc, sizeof(char *));
135 if (argv == NULL) {
136 printf("%s\n", _("Could not malloc argv array in popen()"));
137 return -1;
140 /* get command arguments (stupidly, but fairly quickly) */
141 while (cmd) {
142 str = cmd;
143 str += strspn(str, " \t\r\n"); /* trim any leading whitespace */
145 if (strstr(str, "'") == str) { /* handle SIMPLE quoted strings */
146 str++;
147 if (!strstr(str, "'"))
148 return -1; /* balanced? */
149 cmd = 1 + strstr(str, "'");
150 str[strcspn(str, "'")] = 0;
151 } else {
152 if (strpbrk(str, " \t\r\n")) {
153 cmd = 1 + strpbrk(str, " \t\r\n");
154 str[strcspn(str, " \t\r\n")] = 0;
155 } else {
156 cmd = NULL;
160 if (cmd && strlen(cmd) == strspn(cmd, " \t\r\n"))
161 cmd = NULL;
163 argv[i++] = str;
166 if (pipe(pfd) < 0 || pipe(pfderr) < 0 || (pid = fork()) < 0)
167 return -1; /* errno set by the failing function */
169 /* child runs exceve() and _exit. */
170 if (pid == 0) {
171 #ifdef RLIMIT_CORE
172 /* the program we execve shouldn't leave core files */
173 getrlimit(RLIMIT_CORE, &limit);
174 limit.rlim_cur = 0;
175 setrlimit(RLIMIT_CORE, &limit);
176 #endif
177 close(pfd[0]);
178 if (pfd[1] != STDOUT_FILENO) {
179 dup2(pfd[1], STDOUT_FILENO);
180 close(pfd[1]);
182 close(pfderr[0]);
183 if (pfderr[1] != STDERR_FILENO) {
184 dup2(pfderr[1], STDERR_FILENO);
185 close(pfderr[1]);
188 /* close all descriptors in np_pids[]
189 * This is executed in a separate address space (pure child),
190 * so we don't have to worry about async safety */
191 long maxfd = mp_open_max();
192 for (i = 0; i < maxfd; i++)
193 if (np_pids[i] > 0)
194 close(i);
196 execve(argv[0], argv, env);
197 _exit(STATE_UNKNOWN);
200 /* parent picks up execution here */
201 /* close children descriptors in our address space */
202 close(pfd[1]);
203 close(pfderr[1]);
205 /* tag our file's entry in the pid-list and return it */
206 np_pids[pfd[0]] = pid;
208 return pfd[0];
211 static int np_runcmd_close(int fd) {
212 int status;
213 pid_t pid;
215 /* make sure this fd was opened by popen() */
216 long maxfd = mp_open_max();
217 if (fd < 0 || fd > maxfd || !np_pids || (pid = np_pids[fd]) == 0)
218 return -1;
220 np_pids[fd] = 0;
221 if (close(fd) == -1)
222 return -1;
224 /* EINTR is ok (sort of), everything else is bad */
225 while (waitpid(pid, &status, 0) < 0)
226 if (errno != EINTR)
227 return -1;
229 /* return child's termination status */
230 return (WIFEXITED(status)) ? WEXITSTATUS(status) : -1;
233 void runcmd_timeout_alarm_handler(int signo) {
235 if (signo == SIGALRM)
236 puts(_("CRITICAL - Plugin timed out while executing system call"));
238 long maxfd = mp_open_max();
239 if (np_pids)
240 for (long int i = 0; i < maxfd; i++) {
241 if (np_pids[i] != 0)
242 kill(np_pids[i], SIGKILL);
245 exit(STATE_CRITICAL);
248 static int np_fetch_output(int fd, output *op, int flags) {
249 size_t len = 0, i = 0, lineno = 0;
250 size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
251 char *buf = NULL;
252 int ret;
253 char tmpbuf[4096];
255 op->buf = NULL;
256 op->buflen = 0;
257 while ((ret = read(fd, tmpbuf, sizeof(tmpbuf))) > 0) {
258 len = (size_t)ret;
259 op->buf = realloc(op->buf, op->buflen + len + 1);
260 memcpy(op->buf + op->buflen, tmpbuf, len);
261 op->buflen += len;
262 i++;
265 if (ret < 0) {
266 printf("read() returned %d: %s\n", ret, strerror(errno));
267 return ret;
270 /* some plugins may want to keep output unbroken, and some commands
271 * will yield no output, so return here for those */
272 if (flags & RUNCMD_NO_ARRAYS || !op->buf || !op->buflen)
273 return op->buflen;
275 /* and some may want both */
276 if (flags & RUNCMD_NO_ASSOC) {
277 buf = malloc(op->buflen);
278 memcpy(buf, op->buf, op->buflen);
279 } else
280 buf = op->buf;
282 op->line = NULL;
283 op->lens = NULL;
284 i = 0;
285 while (i < op->buflen) {
286 /* make sure we have enough memory */
287 if (lineno >= ary_size) {
288 /* ary_size must never be zero */
289 do {
290 ary_size = op->buflen >> --rsf;
291 } while (!ary_size);
293 op->line = realloc(op->line, ary_size * sizeof(char *));
294 op->lens = realloc(op->lens, ary_size * sizeof(size_t));
297 /* set the pointer to the string */
298 op->line[lineno] = &buf[i];
300 /* hop to next newline or end of buffer */
301 while (buf[i] != '\n' && i < op->buflen)
302 i++;
303 buf[i] = '\0';
305 /* calculate the string length using pointer difference */
306 op->lens[lineno] = (size_t)&buf[i] - (size_t)op->line[lineno];
308 lineno++;
309 i++;
312 return lineno;
315 int np_runcmd(const char *cmd, output *out, output *err, int flags) {
316 int fd, pfd_out[2], pfd_err[2];
318 /* initialize the structs */
319 if (out)
320 memset(out, 0, sizeof(output));
321 if (err)
322 memset(err, 0, sizeof(output));
324 if ((fd = np_runcmd_open(cmd, pfd_out, pfd_err)) == -1)
325 die(STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd);
327 if (out)
328 out->lines = np_fetch_output(pfd_out[0], out, flags);
329 if (err)
330 err->lines = np_fetch_output(pfd_err[0], err, flags);
332 return np_runcmd_close(fd);