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.c676
1 files changed, 478 insertions, 198 deletions
diff --git a/lib/utils_cmd.c b/lib/utils_cmd.c
index 7957ec14..42c81793 100644
--- a/lib/utils_cmd.c
+++ b/lib/utils_cmd.c
@@ -1,46 +1,45 @@
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
41/** includes **/ 41/** includes **/
42#include "common.h" 42#include "common.h"
43#include "utils.h"
44#include "utils_cmd.h" 43#include "utils_cmd.h"
45/* This variable must be global, since there's no way the caller 44/* This variable must be global, since there's no way the caller
46 * can forcibly slay a dead or ungainly running program otherwise. 45 * can forcibly slay a dead or ungainly running program otherwise.
@@ -57,117 +56,181 @@ static pid_t *_cmd_pids = NULL;
57#include "./maxfd.h" 56#include "./maxfd.h"
58 57
59#include <fcntl.h> 58#include <fcntl.h>
59#include <stddef.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 */
66extern char **environ;
67
68/** macros **/ 65/** macros **/
69#ifndef WEXITSTATUS 66#ifndef WEXITSTATUS
70# define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8) 67# define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
71#endif 68#endif
72 69
73#ifndef WIFEXITED 70#ifndef WIFEXITED
74# define WIFEXITED(stat_val) (((stat_val) & 255) == 0) 71# define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
75#endif 72#endif
76 73
77/* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */ 74/* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
78#if defined(SIG_IGN) && !defined(SIG_ERR) 75#if defined(SIG_IGN) && !defined(SIG_ERR)
79# define SIG_ERR ((Sigfunc *)-1) 76# define SIG_ERR ((Sigfunc *)-1)
80#endif 77#endif
81 78
82/** prototypes **/ 79/** prototypes **/
83static int _cmd_open (char *const *, int *, int *) 80static int _cmd_open(char *const *argv, int *pfd, int *pfderr)
84 __attribute__ ((__nonnull__ (1, 2, 3))); 81 __attribute__((__nonnull__(1, 2, 3)));
85
86static int _cmd_fetch_output (int, output *, int)
87 __attribute__ ((__nonnull__ (2)));
88 82
89static int _cmd_close (int); 83static int _cmd_fetch_output(int fileDescriptor, output *cmd_output, int flags)
90 84 __attribute__((__nonnull__(2)));
91/* prototype imported from utils.h */
92extern void die (int, const char *, ...)
93 __attribute__ ((__noreturn__, __format__ (__printf__, 2, 3)));
94 85
86static int _cmd_close(int fileDescriptor);
95 87
96/* this function is NOT async-safe. It is exported so multithreaded 88/* this function is NOT async-safe. It is exported so multithreaded
97 * plugins (or other apps) can call it prior to running any commands 89 * plugins (or other apps) can call it prior to running any commands
98 * through this api and thus achieve async-safeness throughout the api */ 90 * through this api and thus achieve async-safeness throughout the api */
99void 91void cmd_init(void) {
100cmd_init (void)
101{
102 long maxfd = mp_open_max(); 92 long maxfd = mp_open_max();
103 93
104 /* if maxfd is unnaturally high, we force it to a lower value 94 /* 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 95 * ( e.g. on SunOS, when ulimit is set to unlimited: 2147483647 this would cause
106 * a segfault when following calloc is called ... ) */ 96 * a segfault when following calloc is called ... ) */
107 97
108 if ( maxfd > MAXFD_LIMIT ) { 98 if (maxfd > MAXFD_LIMIT) {
109 maxfd = MAXFD_LIMIT; 99 maxfd = MAXFD_LIMIT;
110 } 100 }
111 101
112 if (!_cmd_pids) 102 if (!_cmd_pids) {
113 _cmd_pids = calloc (maxfd, sizeof (pid_t)); 103 _cmd_pids = calloc(maxfd, sizeof(pid_t));
104 }
114} 105}
115 106
107typedef struct {
108 int stdout_pipe_fd[2];
109 int stderr_pipe_fd[2];
110 int file_descriptor;
111 int error_code;
112} int_cmd_open_result;
113static int_cmd_open_result _cmd_open2(char *const *argv) {
114#ifdef RLIMIT_CORE
115 struct rlimit limit;
116#endif
116 117
117/* Start running a command, array style */ 118 if (!_cmd_pids) {
118static int 119 CMD_INIT;
119_cmd_open (char *const *argv, int *pfd, int *pfderr) 120 }
120{ 121
122 setenv("LC_ALL", "C", 1);
123
124 int_cmd_open_result result = {
125 .error_code = 0,
126 .stdout_pipe_fd = {0, 0},
127 .stderr_pipe_fd = {0, 0},
128 };
121 pid_t pid; 129 pid_t pid;
130 if (pipe(result.stdout_pipe_fd) < 0 || pipe(result.stderr_pipe_fd) < 0 || (pid = fork()) < 0) {
131 result.error_code = -1;
132 return result; /* errno set by the failing function */
133 }
134
135 /* child runs exceve() and _exit. */
136 if (pid == 0) {
122#ifdef RLIMIT_CORE 137#ifdef RLIMIT_CORE
123 struct rlimit limit; 138 /* the program we execve shouldn't leave core files */
139 getrlimit(RLIMIT_CORE, &limit);
140 limit.rlim_cur = 0;
141 setrlimit(RLIMIT_CORE, &limit);
124#endif 142#endif
143 close(result.stdout_pipe_fd[0]);
144 if (result.stdout_pipe_fd[1] != STDOUT_FILENO) {
145 dup2(result.stdout_pipe_fd[1], STDOUT_FILENO);
146 close(result.stdout_pipe_fd[1]);
147 }
148 close(result.stderr_pipe_fd[0]);
149 if (result.stderr_pipe_fd[1] != STDERR_FILENO) {
150 dup2(result.stderr_pipe_fd[1], STDERR_FILENO);
151 close(result.stderr_pipe_fd[1]);
152 }
125 153
126 int i = 0; 154 /* close all descriptors in _cmd_pids[]
155 * This is executed in a separate address space (pure child),
156 * so we don't have to worry about async safety */
157 long maxfd = mp_open_max();
158 for (int i = 0; i < maxfd; i++) {
159 if (_cmd_pids[i] > 0) {
160 close(i);
161 }
162 }
163
164 execve(argv[0], argv, environ);
165 _exit(STATE_UNKNOWN);
166 }
127 167
128 if (!_cmd_pids) 168 /* parent picks up execution here */
169 /* close children descriptors in our address space */
170 close(result.stdout_pipe_fd[1]);
171 close(result.stderr_pipe_fd[1]);
172
173 /* tag our file's entry in the pid-list and return it */
174 _cmd_pids[result.stdout_pipe_fd[0]] = pid;
175
176 result.file_descriptor = result.stdout_pipe_fd[0];
177 return result;
178}
179
180/* Start running a command, array style */
181static int _cmd_open(char *const *argv, int *pfd, int *pfderr) {
182#ifdef RLIMIT_CORE
183 struct rlimit limit;
184#endif
185
186 if (!_cmd_pids) {
129 CMD_INIT; 187 CMD_INIT;
188 }
130 189
131 setenv("LC_ALL", "C", 1); 190 setenv("LC_ALL", "C", 1);
132 191
133 if (pipe (pfd) < 0 || pipe (pfderr) < 0 || (pid = fork ()) < 0) 192 pid_t pid;
134 return -1; /* errno set by the failing function */ 193 if (pipe(pfd) < 0 || pipe(pfderr) < 0 || (pid = fork()) < 0) {
194 return -1; /* errno set by the failing function */
195 }
135 196
136 /* child runs exceve() and _exit. */ 197 /* child runs exceve() and _exit. */
137 if (pid == 0) { 198 if (pid == 0) {
138#ifdef RLIMIT_CORE 199#ifdef RLIMIT_CORE
139 /* the program we execve shouldn't leave core files */ 200 /* the program we execve shouldn't leave core files */
140 getrlimit (RLIMIT_CORE, &limit); 201 getrlimit(RLIMIT_CORE, &limit);
141 limit.rlim_cur = 0; 202 limit.rlim_cur = 0;
142 setrlimit (RLIMIT_CORE, &limit); 203 setrlimit(RLIMIT_CORE, &limit);
143#endif 204#endif
144 close (pfd[0]); 205 close(pfd[0]);
145 if (pfd[1] != STDOUT_FILENO) { 206 if (pfd[1] != STDOUT_FILENO) {
146 dup2 (pfd[1], STDOUT_FILENO); 207 dup2(pfd[1], STDOUT_FILENO);
147 close (pfd[1]); 208 close(pfd[1]);
148 } 209 }
149 close (pfderr[0]); 210 close(pfderr[0]);
150 if (pfderr[1] != STDERR_FILENO) { 211 if (pfderr[1] != STDERR_FILENO) {
151 dup2 (pfderr[1], STDERR_FILENO); 212 dup2(pfderr[1], STDERR_FILENO);
152 close (pfderr[1]); 213 close(pfderr[1]);
153 } 214 }
154 215
155 /* close all descriptors in _cmd_pids[] 216 /* close all descriptors in _cmd_pids[]
156 * This is executed in a separate address space (pure child), 217 * This is executed in a separate address space (pure child),
157 * so we don't have to worry about async safety */ 218 * so we don't have to worry about async safety */
158 long maxfd = mp_open_max(); 219 long maxfd = mp_open_max();
159 for (i = 0; i < maxfd; i++) 220 for (int i = 0; i < maxfd; i++) {
160 if (_cmd_pids[i] > 0) 221 if (_cmd_pids[i] > 0) {
161 close (i); 222 close(i);
223 }
224 }
162 225
163 execve (argv[0], argv, environ); 226 execve(argv[0], argv, environ);
164 _exit (STATE_UNKNOWN); 227 _exit(STATE_UNKNOWN);
165 } 228 }
166 229
167 /* parent picks up execution here */ 230 /* parent picks up execution here */
168 /* close children descriptors in our address space */ 231 /* close children descriptors in our address space */
169 close (pfd[1]); 232 close(pfd[1]);
170 close (pfderr[1]); 233 close(pfderr[1]);
171 234
172 /* tag our file's entry in the pid-list and return it */ 235 /* tag our file's entry in the pid-list and return it */
173 _cmd_pids[pfd[0]] = pid; 236 _cmd_pids[pfd[0]] = pid;
@@ -175,94 +238,171 @@ _cmd_open (char *const *argv, int *pfd, int *pfderr)
175 return pfd[0]; 238 return pfd[0];
176} 239}
177 240
178static int 241static int _cmd_close(int fileDescriptor) {
179_cmd_close (int fd)
180{
181 int status;
182 pid_t pid; 242 pid_t pid;
183 243
184 /* make sure the provided fd was opened */ 244 /* make sure the provided fd was opened */
185 long maxfd = mp_open_max(); 245 long maxfd = mp_open_max();
186 if (fd < 0 || fd > maxfd || !_cmd_pids || (pid = _cmd_pids[fd]) == 0) 246 if (fileDescriptor < 0 || fileDescriptor > maxfd || !_cmd_pids ||
247 (pid = _cmd_pids[fileDescriptor]) == 0) {
187 return -1; 248 return -1;
249 }
188 250
189 _cmd_pids[fd] = 0; 251 _cmd_pids[fileDescriptor] = 0;
190 if (close (fd) == -1) 252 if (close(fileDescriptor) == -1) {
191 return -1; 253 return -1;
254 }
192 255
193 /* EINTR is ok (sort of), everything else is bad */ 256 /* EINTR is ok (sort of), everything else is bad */
194 while (waitpid (pid, &status, 0) < 0) 257 int status;
195 if (errno != EINTR) 258 while (waitpid(pid, &status, 0) < 0) {
259 if (errno != EINTR) {
196 return -1; 260 return -1;
261 }
262 }
197 263
198 /* return child's termination status */ 264 /* return child's termination status */
199 return (WIFEXITED (status)) ? WEXITSTATUS (status) : -1; 265 return (WIFEXITED(status)) ? WEXITSTATUS(status) : -1;
200} 266}
201 267
268typedef struct {
269 int error_code;
270 output output_container;
271} int_cmd_fetch_output2;
272static int_cmd_fetch_output2 _cmd_fetch_output2(int fileDescriptor, int flags) {
273 char tmpbuf[4096];
274
275 int_cmd_fetch_output2 result = {
276 .error_code = 0,
277 .output_container =
278 {
279 .buf = NULL,
280 .buflen = 0,
281 .line = NULL,
282 .lines = 0,
283 },
284 };
285 ssize_t ret;
286 while ((ret = read(fileDescriptor, tmpbuf, sizeof(tmpbuf))) > 0) {
287 size_t len = (size_t)ret;
288 result.output_container.buf =
289 realloc(result.output_container.buf, result.output_container.buflen + len + 1);
290 memcpy(result.output_container.buf + result.output_container.buflen, tmpbuf, len);
291 result.output_container.buflen += len;
292 }
202 293
203static int 294 if (ret < 0) {
204_cmd_fetch_output (int fd, output * op, int flags) 295 printf("read() returned %zd: %s\n", ret, strerror(errno));
205{ 296 result.error_code = -1;
206 size_t len = 0, i = 0, lineno = 0; 297 return result;
207 size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */ 298 }
299
300 /* some plugins may want to keep output unbroken, and some commands
301 * will yield no output, so return here for those */
302 if (flags & CMD_NO_ARRAYS || !result.output_container.buf || !result.output_container.buflen) {
303 return result;
304 }
305
306 /* and some may want both */
208 char *buf = NULL; 307 char *buf = NULL;
209 int ret; 308 if (flags & CMD_NO_ASSOC) {
210 char tmpbuf[4096]; 309 buf = malloc(result.output_container.buflen);
310 memcpy(buf, result.output_container.buf, result.output_container.buflen);
311 } else {
312 buf = result.output_container.buf;
313 }
314
315 result.output_container.line = NULL;
316 size_t ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
317 size_t rsf = 6;
318 size_t lineno = 0;
319 for (size_t i = 0; i < result.output_container.buflen;) {
320 /* make sure we have enough memory */
321 if (lineno >= ary_size) {
322 /* ary_size must never be zero */
323 do {
324 ary_size = result.output_container.buflen >> --rsf;
325 } while (!ary_size);
326
327 result.output_container.line =
328 realloc(result.output_container.line, ary_size * sizeof(char *));
329 }
330
331 /* set the pointer to the string */
332 result.output_container.line[lineno] = &buf[i];
333
334 /* hop to next newline or end of buffer */
335 while (buf[i] != '\n' && i < result.output_container.buflen) {
336 i++;
337 }
338 buf[i] = '\0';
211 339
212 op->buf = NULL; 340 lineno++;
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++; 341 i++;
220 } 342 }
221 343
344 result.output_container.lines = lineno;
345
346 return result;
347}
348
349static int _cmd_fetch_output(int fileDescriptor, output *cmd_output, int flags) {
350 char tmpbuf[4096];
351 cmd_output->buf = NULL;
352 cmd_output->buflen = 0;
353 ssize_t ret;
354 while ((ret = read(fileDescriptor, tmpbuf, sizeof(tmpbuf))) > 0) {
355 size_t len = (size_t)ret;
356 cmd_output->buf = realloc(cmd_output->buf, cmd_output->buflen + len + 1);
357 memcpy(cmd_output->buf + cmd_output->buflen, tmpbuf, len);
358 cmd_output->buflen += len;
359 }
360
222 if (ret < 0) { 361 if (ret < 0) {
223 printf ("read() returned %d: %s\n", ret, strerror (errno)); 362 printf("read() returned %zd: %s\n", ret, strerror(errno));
224 return ret; 363 return ret;
225 } 364 }
226 365
227 /* some plugins may want to keep output unbroken, and some commands 366 /* some plugins may want to keep output unbroken, and some commands
228 * will yield no output, so return here for those */ 367 * will yield no output, so return here for those */
229 if (flags & CMD_NO_ARRAYS || !op->buf || !op->buflen) 368 if (flags & CMD_NO_ARRAYS || !cmd_output->buf || !cmd_output->buflen) {
230 return op->buflen; 369 return cmd_output->buflen;
370 }
231 371
232 /* and some may want both */ 372 /* and some may want both */
373 char *buf = NULL;
233 if (flags & CMD_NO_ASSOC) { 374 if (flags & CMD_NO_ASSOC) {
234 buf = malloc (op->buflen); 375 buf = malloc(cmd_output->buflen);
235 memcpy (buf, op->buf, op->buflen); 376 memcpy(buf, cmd_output->buf, cmd_output->buflen);
377 } else {
378 buf = cmd_output->buf;
236 } 379 }
237 else
238 buf = op->buf;
239 380
240 op->line = NULL; 381 cmd_output->line = NULL;
241 op->lens = NULL; 382 size_t i = 0;
242 i = 0; 383 size_t ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
243 while (i < op->buflen) { 384 size_t rsf = 6;
385 size_t lineno = 0;
386 while (i < cmd_output->buflen) {
244 /* make sure we have enough memory */ 387 /* make sure we have enough memory */
245 if (lineno >= ary_size) { 388 if (lineno >= ary_size) {
246 /* ary_size must never be zero */ 389 /* ary_size must never be zero */
247 do { 390 do {
248 ary_size = op->buflen >> --rsf; 391 ary_size = cmd_output->buflen >> --rsf;
249 } while (!ary_size); 392 } while (!ary_size);
250 393
251 op->line = realloc (op->line, ary_size * sizeof (char *)); 394 cmd_output->line = realloc(cmd_output->line, ary_size * sizeof(char *));
252 op->lens = realloc (op->lens, ary_size * sizeof (size_t));
253 } 395 }
254 396
255 /* set the pointer to the string */ 397 /* set the pointer to the string */
256 op->line[lineno] = &buf[i]; 398 cmd_output->line[lineno] = &buf[i];
257 399
258 /* hop to next newline or end of buffer */ 400 /* hop to next newline or end of buffer */
259 while (buf[i] != '\n' && i < op->buflen) 401 while (buf[i] != '\n' && i < cmd_output->buflen) {
260 i++; 402 i++;
403 }
261 buf[i] = '\0'; 404 buf[i] = '\0';
262 405
263 /* calculate the string length using pointer difference */
264 op->lens[lineno] = (size_t) & buf[i] - (size_t) op->line[lineno];
265
266 lineno++; 406 lineno++;
267 i++; 407 i++;
268 } 408 }
@@ -270,135 +410,275 @@ _cmd_fetch_output (int fd, output * op, int flags)
270 return lineno; 410 return lineno;
271} 411}
272 412
273 413int cmd_run(const char *cmdstring, output *out, output *err, int flags) {
274int 414 if (cmdstring == NULL) {
275cmd_run (const char *cmdstring, output * out, output * err, int flags)
276{
277 int i = 0, argc;
278 size_t cmdlen;
279 char **argv = NULL;
280 char *cmd = NULL;
281 char *str = NULL;
282
283 if (cmdstring == NULL)
284 return -1; 415 return -1;
416 }
285 417
286 /* initialize the structs */ 418 /* initialize the structs */
287 if (out) 419 if (out) {
288 memset (out, 0, sizeof (output)); 420 memset(out, 0, sizeof(output));
289 if (err) 421 }
290 memset (err, 0, sizeof (output)); 422 if (err) {
423 memset(err, 0, sizeof(output));
424 }
291 425
292 /* make copy of command string so strtok() doesn't silently modify it */ 426 /* make copy of command string so strtok() doesn't silently modify it */
293 /* (the calling program may want to access it later) */ 427 /* (the calling program may want to access it later) */
294 cmdlen = strlen (cmdstring); 428 size_t cmdlen = strlen(cmdstring);
295 if ((cmd = malloc (cmdlen + 1)) == NULL) 429 char *cmd = NULL;
430 if ((cmd = malloc(cmdlen + 1)) == NULL) {
296 return -1; 431 return -1;
297 memcpy (cmd, cmdstring, cmdlen); 432 }
433 memcpy(cmd, cmdstring, cmdlen);
298 cmd[cmdlen] = '\0'; 434 cmd[cmdlen] = '\0';
299 435
300 /* This is not a shell, so we don't handle "???" */ 436 /* This is not a shell, so we don't handle "???" */
301 if (strstr (cmdstring, "\"")) return -1; 437 if (strstr(cmdstring, "\"")) {
438 return -1;
439 }
302 440
303 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */ 441 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
304 if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''")) 442 if (strstr(cmdstring, " ' ") || strstr(cmdstring, "'''")) {
305 return -1; 443 return -1;
444 }
306 445
307 /* each arg must be whitespace-separated, so args can be a maximum 446 /* 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 */ 447 * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
309 argc = (cmdlen >> 1) + 2; 448 int argc = (cmdlen >> 1) + 2;
310 argv = calloc (sizeof (char *), argc); 449 char **argv = calloc((size_t)argc, sizeof(char *));
311 450
312 if (argv == NULL) { 451 if (argv == NULL) {
313 printf ("%s\n", _("Could not malloc argv array in popen()")); 452 printf("%s\n", _("Could not malloc argv array in popen()"));
314 return -1; 453 return -1;
315 } 454 }
316 455
317 /* get command arguments (stupidly, but fairly quickly) */ 456 /* get command arguments (stupidly, but fairly quickly) */
457 int i = 0;
318 while (cmd) { 458 while (cmd) {
319 str = cmd; 459 char *str = cmd;
320 str += strspn (str, " \t\r\n"); /* trim any leading whitespace */ 460 str += strspn(str, " \t\r\n"); /* trim any leading whitespace */
321 461
322 if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */ 462 if (strstr(str, "'") == str) { /* handle SIMPLE quoted strings */
323 str++; 463 str++;
324 if (!strstr (str, "'")) 464 if (!strstr(str, "'")) {
325 return -1; /* balanced? */ 465 return -1; /* balanced? */
326 cmd = 1 + strstr (str, "'"); 466 }
327 str[strcspn (str, "'")] = 0; 467 cmd = 1 + strstr(str, "'");
468 str[strcspn(str, "'")] = 0;
469 } else {
470 if (strpbrk(str, " \t\r\n")) {
471 cmd = 1 + strpbrk(str, " \t\r\n");
472 str[strcspn(str, " \t\r\n")] = 0;
473 } else {
474 cmd = NULL;
475 }
476 }
477
478 if (cmd && strlen(cmd) == strspn(cmd, " \t\r\n")) {
479 cmd = NULL;
328 } 480 }
329 else { 481
330 if (strpbrk (str, " \t\r\n")) { 482 argv[i++] = str;
331 cmd = 1 + strpbrk (str, " \t\r\n"); 483 }
332 str[strcspn (str, " \t\r\n")] = 0; 484
485 return cmd_run_array(argv, out, err, flags);
486}
487
488cmd_run_result cmd_run2(const char *cmd_string, int flags) {
489 cmd_run_result result = {
490 .cmd_error_code = 0,
491 .error_code = 0,
492 .stderr =
493 {
494 .buf = NULL,
495 .buflen = 0,
496 .line = NULL,
497 .lines = 0,
498 },
499 .stdout =
500 {
501 .buf = NULL,
502 .buflen = 0,
503 .line = NULL,
504 .lines = 0,
505 },
506 };
507
508 if (cmd_string == NULL) {
509 result.error_code = -1;
510 return result;
511 }
512
513 /* make copy of command string so strtok() doesn't silently modify it */
514 /* (the calling program may want to access it later) */
515 char *cmd = strdup(cmd_string);
516 if (cmd == NULL) {
517 result.error_code = -1;
518 return result;
519 }
520
521 /* This is not a shell, so we don't handle "???" */
522 if (strstr(cmd, "\"")) {
523 result.error_code = -1;
524 return result;
525 }
526
527 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
528 if (strstr(cmd, " ' ") || strstr(cmd, "'''")) {
529 result.error_code = -1;
530 return result;
531 }
532
533 /* each arg must be whitespace-separated, so args can be a maximum
534 * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
535 size_t cmdlen = strlen(cmd_string);
536 size_t argc = (cmdlen >> 1) + 2;
537 char **argv = calloc(argc, sizeof(char *));
538
539 if (argv == NULL) {
540 printf("%s\n", _("Could not malloc argv array in popen()"));
541 result.error_code = -1;
542 return result;
543 }
544
545 /* get command arguments (stupidly, but fairly quickly) */
546 for (int i = 0; cmd; i++) {
547 char *str = cmd;
548 str += strspn(str, " \t\r\n"); /* trim any leading whitespace */
549
550 if (strstr(str, "'") == str) { /* handle SIMPLE quoted strings */
551 str++;
552 if (!strstr(str, "'")) {
553 result.error_code = -1;
554 return result; /* balanced? */
333 } 555 }
334 else { 556
557 cmd = 1 + strstr(str, "'");
558 str[strcspn(str, "'")] = 0;
559 } else {
560 if (strpbrk(str, " \t\r\n")) {
561 cmd = 1 + strpbrk(str, " \t\r\n");
562 str[strcspn(str, " \t\r\n")] = 0;
563 } else {
335 cmd = NULL; 564 cmd = NULL;
336 } 565 }
337 } 566 }
338 567
339 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n")) 568 if (cmd && strlen(cmd) == strspn(cmd, " \t\r\n")) {
340 cmd = NULL; 569 cmd = NULL;
570 }
341 571
342 argv[i++] = str; 572 argv[i++] = str;
343 } 573 }
344 574
345 return cmd_run_array (argv, out, err, flags); 575 result = cmd_run_array2(argv, flags);
576
577 return result;
346} 578}
347 579
348int 580cmd_run_result cmd_run_array2(char *const *cmd, int flags) {
349cmd_run_array (char *const *argv, output * out, output * err, int flags) 581 cmd_run_result result = {
350{ 582 .cmd_error_code = 0,
351 int fd, pfd_out[2], pfd_err[2]; 583 .error_code = 0,
584 .stderr =
585 {
586 .buf = NULL,
587 .buflen = 0,
588 .line = NULL,
589 .lines = 0,
590 },
591 .stdout =
592 {
593 .buf = NULL,
594 .buflen = 0,
595 .line = NULL,
596 .lines = 0,
597 },
598 };
599
600 int_cmd_open_result cmd_open_result = _cmd_open2(cmd);
601 if (cmd_open_result.error_code != 0) {
602 // result.error_code = -1;
603 // return result;
604 // TODO properly handle this without dying
605 die(STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd[0]);
606 }
607
608 int file_descriptor = cmd_open_result.file_descriptor;
609 int pfd_out[2] = {cmd_open_result.stdout_pipe_fd[0], cmd_open_result.stdout_pipe_fd[1]};
610 int pfd_err[2] = {cmd_open_result.stderr_pipe_fd[0], cmd_open_result.stderr_pipe_fd[1]};
611
612 int_cmd_fetch_output2 tmp_stdout = _cmd_fetch_output2(pfd_out[0], flags);
613 result.stdout = tmp_stdout.output_container;
614 int_cmd_fetch_output2 tmp_stderr = _cmd_fetch_output2(pfd_err[0], flags);
615 result.stderr = tmp_stderr.output_container;
616
617 result.cmd_error_code = _cmd_close(file_descriptor);
618 return result;
619}
352 620
621int cmd_run_array(char *const *argv, output *out, output *err, int flags) {
353 /* initialize the structs */ 622 /* initialize the structs */
354 if (out) 623 if (out) {
355 memset (out, 0, sizeof (output)); 624 memset(out, 0, sizeof(output));
356 if (err) 625 }
357 memset (err, 0, sizeof (output)); 626 if (err) {
627 memset(err, 0, sizeof(output));
628 }
358 629
359 if ((fd = _cmd_open (argv, pfd_out, pfd_err)) == -1) 630 int fd;
360 die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), argv[0]); 631 int pfd_out[2];
632 int pfd_err[2];
633 if ((fd = _cmd_open(argv, pfd_out, pfd_err)) == -1) {
634 die(STATE_UNKNOWN, _("Could not open pipe: %s\n"), argv[0]);
635 }
361 636
362 if (out) 637 if (out) {
363 out->lines = _cmd_fetch_output (pfd_out[0], out, flags); 638 out->lines = _cmd_fetch_output(pfd_out[0], out, flags);
364 if (err) 639 }
365 err->lines = _cmd_fetch_output (pfd_err[0], err, flags); 640 if (err) {
641 err->lines = _cmd_fetch_output(pfd_err[0], err, flags);
642 }
366 643
367 return _cmd_close (fd); 644 return _cmd_close(fd);
368} 645}
369 646
370int 647int cmd_file_read(const char *filename, output *out, int flags) {
371cmd_file_read ( char *filename, output *out, int flags)
372{
373 int fd; 648 int fd;
374 if(out) 649 if (out) {
375 memset (out, 0, sizeof(output)); 650 memset(out, 0, sizeof(output));
651 }
376 652
377 if ((fd = open(filename, O_RDONLY)) == -1) { 653 if ((fd = open(filename, O_RDONLY)) == -1) {
378 die( STATE_UNKNOWN, _("Error opening %s: %s"), filename, strerror(errno) ); 654 die(STATE_UNKNOWN, _("Error opening %s: %s"), filename, strerror(errno));
379 } 655 }
380 656
381 if(out) 657 if (out) {
382 out->lines = _cmd_fetch_output (fd, out, flags); 658 out->lines = _cmd_fetch_output(fd, out, flags);
659 }
383 660
384 if (close(fd) == -1) 661 if (close(fd) == -1) {
385 die( STATE_UNKNOWN, _("Error closing %s: %s"), filename, strerror(errno) ); 662 die(STATE_UNKNOWN, _("Error closing %s: %s"), filename, strerror(errno));
663 }
386 664
387 return 0; 665 return 0;
388} 666}
389 667
390void 668void timeout_alarm_handler(int signo) {
391timeout_alarm_handler (int signo)
392{
393 if (signo == SIGALRM) { 669 if (signo == SIGALRM) {
394 printf (_("%s - Plugin timed out after %d seconds\n"), 670 printf(_("%s - Plugin timed out after %d seconds\n"), state_text(timeout_state),
395 state_text(timeout_state), timeout_interval); 671 timeout_interval);
396 672
397 long maxfd = mp_open_max(); 673 long maxfd = mp_open_max();
398 if(_cmd_pids) for(long int i = 0; i < maxfd; i++) { 674 if (_cmd_pids) {
399 if(_cmd_pids[i] != 0) kill(_cmd_pids[i], SIGKILL); 675 for (long int i = 0; i < maxfd; i++) {
676 if (_cmd_pids[i] != 0) {
677 kill(_cmd_pids[i], SIGKILL);
678 }
679 }
400 } 680 }
401 681
402 exit (timeout_state); 682 exit(timeout_state);
403 } 683 }
404} 684}