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