summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--NEWS3
-rw-r--r--configure.in2
-rw-r--r--lib/Makefile.am4
-rw-r--r--lib/tests/Makefile.am9
-rw-r--r--lib/tests/test_cmd.c210
-rw-r--r--lib/tests/test_cmd.t6
-rw-r--r--lib/utils_cmd.c378
-rw-r--r--lib/utils_cmd.h34
-rw-r--r--plugins/Makefile.am4
-rw-r--r--plugins/negate.c107
-rw-r--r--plugins/t/negate.pl48
-rw-r--r--plugins/t/negate.t79
12 files changed, 771 insertions, 113 deletions
diff --git a/NEWS b/NEWS
index d9ec3f66..6455122c 100644
--- a/NEWS
+++ b/NEWS
@@ -16,6 +16,9 @@ This file documents the major additions and syntax changes between releases.
16 The check_dhcp -r and -s options now accept host names, too 16 The check_dhcp -r and -s options now accept host names, too
17 Fix possible check_icmp bus errors on some (non-x86/AMD64) platforms 17 Fix possible check_icmp bus errors on some (non-x86/AMD64) platforms
18 Fix check_smtp's handling of multiple-packet server responses 18 Fix check_smtp's handling of multiple-packet server responses
19 WARNING: Fix for negate which may break existing commands:
20 - stop evaluating command line options through shell twice
21 - enforce a full path for the command to run
19 22
201.4.9 4th June 2006 231.4.9 4th June 2006
21 Inclusion of contrib/check_cluster2 as check_cluster with some improvements 24 Inclusion of contrib/check_cluster2 as check_cluster with some improvements
diff --git a/configure.in b/configure.in
index 9067978a..dc89b05f 100644
--- a/configure.in
+++ b/configure.in
@@ -155,7 +155,7 @@ AC_SUBST(MATHLIBS)
155 155
156dnl Check for libtap, to run perl-like tests 156dnl Check for libtap, to run perl-like tests
157AC_CHECK_LIB(tap, plan_tests, 157AC_CHECK_LIB(tap, plan_tests,
158 EXTRA_TEST="test_utils test_disk test_tcp" 158 EXTRA_TEST="test_utils test_disk test_tcp test_cmd"
159 AC_SUBST(EXTRA_TEST) 159 AC_SUBST(EXTRA_TEST)
160 ) 160 )
161 161
diff --git a/lib/Makefile.am b/lib/Makefile.am
index 5d0f6352..9dd3a0c2 100644
--- a/lib/Makefile.am
+++ b/lib/Makefile.am
@@ -5,8 +5,8 @@ SUBDIRS = tests
5noinst_LIBRARIES = libnagiosplug.a 5noinst_LIBRARIES = libnagiosplug.a
6 6
7 7
8libnagiosplug_a_SOURCES = utils_base.c utils_disk.c utils_tcp.c 8libnagiosplug_a_SOURCES = utils_base.c utils_disk.c utils_tcp.c utils_cmd.c
9EXTRA_DIST = utils_base.h utils_disk.h utils_tcp.h 9EXTRA_DIST = utils_base.h utils_disk.h utils_tcp.h utils_cmd.h
10 10
11INCLUDES = -I$(srcdir) -I$(top_srcdir)/gl -I$(top_srcdir)/intl -I$(top_srcdir)/plugins 11INCLUDES = -I$(srcdir) -I$(top_srcdir)/gl -I$(top_srcdir)/intl -I$(top_srcdir)/plugins
12 12
diff --git a/lib/tests/Makefile.am b/lib/tests/Makefile.am
index 6594db2f..9ca22d16 100644
--- a/lib/tests/Makefile.am
+++ b/lib/tests/Makefile.am
@@ -7,9 +7,9 @@ check_PROGRAMS = @EXTRA_TEST@
7 7
8INCLUDES = -I$(top_srcdir)/lib -I$(top_srcdir)/gl -I$(top_srcdir)/intl -I$(top_srcdir)/plugins 8INCLUDES = -I$(top_srcdir)/lib -I$(top_srcdir)/gl -I$(top_srcdir)/intl -I$(top_srcdir)/plugins
9 9
10EXTRA_PROGRAMS = test_utils test_disk test_tcp 10EXTRA_PROGRAMS = test_utils test_disk test_tcp test_cmd
11 11
12EXTRA_DIST = test_utils.t test_disk.t test_tcp.t 12EXTRA_DIST = test_utils.t test_disk.t test_tcp.t test_cmd.t
13 13
14LIBS = @LIBINTL@ 14LIBS = @LIBINTL@
15 15
@@ -28,6 +28,11 @@ test_tcp_CFLAGS = -g -I..
28test_tcp_LDFLAGS = -L/usr/local/lib -ltap 28test_tcp_LDFLAGS = -L/usr/local/lib -ltap
29test_tcp_LDADD = ../utils_tcp.o 29test_tcp_LDADD = ../utils_tcp.o
30 30
31test_cmd_SOURCES = test_cmd.c
32test_cmd_CFLAGS = -g -I..
33test_cmd_LDFLAGS = -L/usr/local/lib -ltap
34test_cmd_LDADD = ../utils_cmd.o ../utils_base.o
35
31test: ${noinst_PROGRAMS} 36test: ${noinst_PROGRAMS}
32 perl -MTest::Harness -e '$$Test::Harness::switches=""; runtests(map {$$_ .= ".t"} @ARGV)' $(EXTRA_PROGRAMS) 37 perl -MTest::Harness -e '$$Test::Harness::switches=""; runtests(map {$$_ .= ".t"} @ARGV)' $(EXTRA_PROGRAMS)
33 38
diff --git a/lib/tests/test_cmd.c b/lib/tests/test_cmd.c
new file mode 100644
index 00000000..4da76a9b
--- /dev/null
+++ b/lib/tests/test_cmd.c
@@ -0,0 +1,210 @@
1/******************************************************************************
2
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; either version 2 of the License, or
6 (at your option) any later version.
7
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
16
17 $Id: test_cmd.c 1732 2007-06-03 15:58:22Z psychotrahe $
18
19******************************************************************************/
20
21#include "common.h"
22#include "utils_cmd.h"
23#include "utils_base.h"
24#include "tap.h"
25
26#define COMMAND_LINE 1024
27#define UNSET 65530
28
29char *
30get_command (char *const *line)
31{
32 char *cmd;
33 int i = 0;
34
35 asprintf (&cmd, " %s", line[i++]);
36 while (line[i] != NULL) {
37 asprintf (&cmd, "%s %s", cmd, line[i]);
38 i++;
39 }
40
41 return cmd;
42}
43
44int
45main (int argc, char **argv)
46{
47 char **command_line = malloc (sizeof (char *) * COMMAND_LINE);
48 char *command = NULL;
49 char *perl;
50 output chld_out, chld_err;
51 int c;
52 int result = UNSET;
53
54 plan_tests(47);
55
56 diag ("Running plain echo command, set one");
57
58 /* ensure everything is empty before we begin */
59 memset (&chld_out, 0, sizeof (output));
60 memset (&chld_err, 0, sizeof (output));
61 ok (chld_out.lines == 0, "(initialised) Checking stdout is reset");
62 ok (chld_err.lines == 0, "(initialised) Checking stderr is reset");
63 ok (result == UNSET, "(initialised) Checking exit code is reset");
64
65 command_line[0] = strdup ("/bin/echo");
66 command_line[1] = strdup ("this");
67 command_line[2] = strdup ("is");
68 command_line[3] = strdup ("test");
69 command_line[4] = strdup ("one");
70
71 command = get_command (command_line);
72
73 result = cmd_run_array (command_line, &chld_out, &chld_err, 0);
74 ok (chld_out.lines == 1,
75 "(array) Check for expected number of stdout lines");
76 ok (chld_err.lines == 0,
77 "(array) Check for expected number of stderr lines");
78 ok (strcmp (chld_out.line[0], "this is test one") == 0,
79 "(array) Check for expected stdout output");
80 ok (result == 0, "(array) Checking exit code");
81
82 /* ensure everything is empty again */
83 memset (&chld_out, 0, sizeof (output));
84 memset (&chld_err, 0, sizeof (output));
85 result = UNSET;
86 ok (chld_out.lines == 0, "(initialised) Checking stdout is reset");
87 ok (chld_err.lines == 0, "(initialised) Checking stderr is reset");
88 ok (result == UNSET, "(initialised) Checking exit code is reset");
89
90 result = cmd_run (command, &chld_out, &chld_err, 0);
91
92 ok (chld_out.lines == 1,
93 "(string) Check for expected number of stdout lines");
94 ok (chld_err.lines == 0,
95 "(string) Check for expected number of stderr lines");
96 ok (strcmp (chld_out.line[0], "this is test one") == 0,
97 "(string) Check for expected stdout output");
98 ok (result == 0, "(string) Checking exit code");
99
100 diag ("Running plain echo command, set two");
101
102 /* ensure everything is empty again */
103 memset (&chld_out, 0, sizeof (output));
104 memset (&chld_err, 0, sizeof (output));
105 result = UNSET;
106 ok (chld_out.lines == 0, "(initialised) Checking stdout is reset");
107 ok (chld_err.lines == 0, "(initialised) Checking stderr is reset");
108 ok (result == UNSET, "(initialised) Checking exit code is reset");
109
110 command_line[0] = strdup ("/bin/echo");
111 command_line[1] = strdup ("this is test two");
112 command_line[2] = NULL;
113 command_line[3] = NULL;
114 command_line[4] = NULL;
115
116 result = cmd_run_array (command_line, &chld_out, &chld_err, 0);
117 ok (chld_out.lines == 1,
118 "(array) Check for expected number of stdout lines");
119 ok (chld_err.lines == 0,
120 "(array) Check for expected number of stderr lines");
121 ok (strcmp (chld_out.line[0], "this is test two") == 0,
122 "(array) Check for expected stdout output");
123 ok (result == 0, "(array) Checking exit code");
124
125 /* ensure everything is empty again */
126 memset (&chld_out, 0, sizeof (output));
127 memset (&chld_err, 0, sizeof (output));
128 result = UNSET;
129 ok (chld_out.lines == 0, "(initialised) Checking stdout is reset");
130 ok (chld_err.lines == 0, "(initialised) Checking stderr is reset");
131 ok (result == UNSET, "(initialised) Checking exit code is reset");
132
133 result = cmd_run (command, &chld_out, &chld_err, 0);
134
135 ok (chld_out.lines == 1,
136 "(string) Check for expected number of stdout lines");
137 ok (chld_err.lines == 0,
138 "(string) Check for expected number of stderr lines");
139 ok (strcmp (chld_out.line[0], "this is test one") == 0,
140 "(string) Check for expected stdout output");
141 ok (result == 0, "(string) Checking exit code");
142
143
144 /* ensure everything is empty again */
145 memset (&chld_out, 0, sizeof (output));
146 memset (&chld_err, 0, sizeof (output));
147 result = UNSET;
148 ok (chld_out.lines == 0, "(initialised) Checking stdout is reset");
149 ok (chld_err.lines == 0, "(initialised) Checking stderr is reset");
150 ok (result == UNSET, "(initialised) Checking exit code is reset");
151
152 /* Pass linefeeds via parameters through - those should be evaluated by echo to give multi line output */
153 command_line[0] = strdup("/bin/echo");
154 command_line[1] = strdup("this is a test via echo\nline two\nit's line 3");
155 command_line[2] = strdup("and (note space between '3' and 'and') $$ will not get evaluated");
156
157 result = cmd_run_array (command_line, &chld_out, &chld_err, 0);
158 ok (chld_out.lines == 3,
159 "(array) Check for expected number of stdout lines");
160 ok (chld_err.lines == 0,
161 "(array) Check for expected number of stderr lines");
162 ok (strcmp (chld_out.line[0], "this is a test via echo") == 0,
163 "(array) Check line 1 for expected stdout output");
164 ok (strcmp (chld_out.line[1], "line two") == 0,
165 "(array) Check line 2 for expected stdout output");
166 ok (strcmp (chld_out.line[2], "it's line 3 and (note space between '3' and 'and') $$ will not get evaluated") == 0,
167 "(array) Check line 3 for expected stdout output");
168 ok (result == 0, "(array) Checking exit code");
169
170
171
172 /* ensure everything is empty again */
173 memset (&chld_out, 0, sizeof (output));
174 memset (&chld_err, 0, sizeof (output));
175 result = UNSET;
176 ok (chld_out.lines == 0, "(initialised) Checking stdout is reset");
177 ok (chld_err.lines == 0, "(initialised) Checking stderr is reset");
178 ok (result == UNSET, "(initialised) Checking exit code is reset");
179
180 command = (char *)malloc(COMMAND_LINE);
181 strcpy(command, "/bin/echo3456 non-existant command");
182 result = cmd_run (command, &chld_out, &chld_err, 0);
183
184 ok (chld_out.lines == 0,
185 "Non existant command, so no output");
186 ok (chld_err.lines == 0,
187 "No stderr either");
188 ok (result == 3, "Get return code 3 (?) for non-existant command");
189
190
191 /* ensure everything is empty again */
192 memset (&chld_out, 0, sizeof (output));
193 memset (&chld_err, 0, sizeof (output));
194 result = UNSET;
195
196 command = (char *)malloc(COMMAND_LINE);
197 strcpy(command, "/bin/grep pattern non-existant-file");
198 result = cmd_run (command, &chld_out, &chld_err, 0);
199
200 ok (chld_out.lines == 0,
201 "Grep returns no stdout when file is missing...");
202 ok (chld_err.lines == 1,
203 "...but does give an error line");
204 ok (strstr(chld_err.line[0],"non-existant-file") != NULL, "And missing filename is in error message");
205 ok (result == 2, "Get return code 2 from grep");
206
207
208
209 return exit_status ();
210}
diff --git a/lib/tests/test_cmd.t b/lib/tests/test_cmd.t
new file mode 100644
index 00000000..4dd54ef9
--- /dev/null
+++ b/lib/tests/test_cmd.t
@@ -0,0 +1,6 @@
1#!/usr/bin/perl
2use Test::More;
3if (! -e "./test_cmd") {
4 plan skip_all => "./test_cmd not compiled - please install tap library to test";
5}
6exec "./test_cmd";
diff --git a/lib/utils_cmd.c b/lib/utils_cmd.c
new file mode 100644
index 00000000..c4ceb97e
--- /dev/null
+++ b/lib/utils_cmd.c
@@ -0,0 +1,378 @@
1/****************************************************************************
2 * Nagios run command utilities
3 *
4 * License: GPL
5 * Copyright (c) 2005 nagios-plugins team
6 *
7 * $Id: utils_cmd.c 1434 2006-06-18 19:36:48Z opensides $
8 *
9 * Description :
10 *
11 * A simple interface to executing programs from other programs, using an
12 * optimized and safe popen()-like implementation. It is considered safe
13 * in that no shell needs to be spawned and the environment passed to the
14 * execve()'d program is essentially empty.
15 *
16 *
17 * The code in this file is a derivative of popen.c which in turn was taken
18 * from "Advanced Programming for the Unix Environment" by W. Richard Stevens.
19 *
20 * Care has been taken to make sure the functions are async-safe. The one
21 * function which isn't is cmd_init() which it doesn't make sense to
22 * call twice anyway, so the api as a whole should be considered async-safe.
23 *
24 * License Information:
25 *
26 * This program is free software; you can redistribute it and/or modify
27 * it under the terms of the GNU General Public License as published by
28 * the Free Software Foundation; either version 2 of the License, or
29 * (at your option) any later version.
30 *
31 * This program is distributed in the hope that it will be useful,
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 * GNU General Public License for more details.
35 *
36 * You should have received a copy of the GNU General Public License
37 * along with this program; if not, write to the Free Software
38 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
39 */
40
41#define NAGIOSPLUG_API_C 1
42
43/** includes **/
44#include "common.h"
45#include "utils_cmd.h"
46#include "utils_base.h"
47
48#ifdef HAVE_SYS_WAIT_H
49# include <sys/wait.h>
50#endif
51
52/** macros **/
53#ifndef WEXITSTATUS
54# define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
55#endif
56
57#ifndef WIFEXITED
58# define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
59#endif
60
61/* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
62#if defined(SIG_IGN) && !defined(SIG_ERR)
63# define SIG_ERR ((Sigfunc *)-1)
64#endif
65
66/* This variable must be global, since there's no way the caller
67 * can forcibly slay a dead or ungainly running program otherwise.
68 * Multithreading apps and plugins can initialize it (via CMD_INIT)
69 * in an async safe manner PRIOR to calling cmd_run() or cmd_run_array()
70 * for the first time.
71 *
72 * The check for initialized values is atomic and can
73 * occur in any number of threads simultaneously. */
74static pid_t *_cmd_pids = NULL;
75
76/* Try sysconf(_SC_OPEN_MAX) first, as it can be higher than OPEN_MAX.
77 * If that fails and the macro isn't defined, we fall back to an educated
78 * guess. There's no guarantee that our guess is adequate and the program
79 * will die with SIGSEGV if it isn't and the upper boundary is breached. */
80#ifdef _SC_OPEN_MAX
81static long maxfd = 0;
82#elif defined(OPEN_MAX)
83# define maxfd OPEN_MAX
84#else /* sysconf macro unavailable, so guess (may be wildly inaccurate) */
85# define maxfd 256
86#endif
87
88
89/** prototypes **/
90static int _cmd_open (char *const *, int *, int *)
91 __attribute__ ((__nonnull__ (1, 2, 3)));
92
93static int _cmd_fetch_output (int, output *, int)
94 __attribute__ ((__nonnull__ (2)));
95
96static int _cmd_close (int);
97
98/* prototype imported from utils.h */
99extern void die (int, const char *, ...)
100 __attribute__ ((__noreturn__, __format__ (__printf__, 2, 3)));
101
102
103/* this function is NOT async-safe. It is exported so multithreaded
104 * plugins (or other apps) can call it prior to running any commands
105 * through this api and thus achieve async-safeness throughout the api */
106void
107cmd_init (void)
108{
109#ifndef maxfd
110 if (!maxfd && (maxfd = sysconf (_SC_OPEN_MAX)) < 0) {
111 /* possibly log or emit a warning here, since there's no
112 * guarantee that our guess at maxfd will be adequate */
113 maxfd = 256;
114 }
115#endif
116
117 if (!_cmd_pids)
118 _cmd_pids = calloc (maxfd, sizeof (pid_t));
119}
120
121
122/* Start running a command, array style */
123static int
124_cmd_open (char *const *argv, int *pfd, int *pfderr)
125{
126 char *env[2];
127 pid_t pid;
128#ifdef RLIMIT_CORE
129 struct rlimit limit;
130#endif
131
132 int i = 0;
133
134 /* if no command was passed, return with no error */
135 if (argv == NULL)
136 return -1;
137
138 if (!_cmd_pids)
139 CMD_INIT;
140
141 env[0] = strdup ("LC_ALL=C");
142 env[1] = '\0';
143
144 if (pipe (pfd) < 0 || pipe (pfderr) < 0 || (pid = fork ()) < 0)
145 return -1; /* errno set by the failing function */
146
147 /* child runs exceve() and _exit. */
148 if (pid == 0) {
149#ifdef RLIMIT_CORE
150 /* the program we execve shouldn't leave core files */
151 getrlimit (RLIMIT_CORE, &limit);
152 limit.rlim_cur = 0;
153 setrlimit (RLIMIT_CORE, &limit);
154#endif
155 close (pfd[0]);
156 if (pfd[1] != STDOUT_FILENO) {
157 dup2 (pfd[1], STDOUT_FILENO);
158 close (pfd[1]);
159 }
160 close (pfderr[0]);
161 if (pfderr[1] != STDERR_FILENO) {
162 dup2 (pfderr[1], STDERR_FILENO);
163 close (pfderr[1]);
164 }
165
166 /* close all descriptors in _cmd_pids[]
167 * This is executed in a separate address space (pure child),
168 * so we don't have to worry about async safety */
169 for (i = 0; i < maxfd; i++)
170 if (_cmd_pids[i] > 0)
171 close (i);
172
173 execve (argv[0], argv, env);
174 _exit (STATE_UNKNOWN);
175 }
176
177 /* parent picks up execution here */
178 /* close childs descriptors in our address space */
179 close (pfd[1]);
180 close (pfderr[1]);
181
182 /* tag our file's entry in the pid-list and return it */
183 _cmd_pids[pfd[0]] = pid;
184
185 return pfd[0];
186}
187
188static int
189_cmd_close (int fd)
190{
191 int status;
192 pid_t pid;
193
194 /* make sure the provided fd was opened */
195 if (fd < 0 || fd > maxfd || !_cmd_pids || (pid = _cmd_pids[fd]) == 0)
196 return -1;
197
198 _cmd_pids[fd] = 0;
199 if (close (fd) == -1)
200 return -1;
201
202 /* EINTR is ok (sort of), everything else is bad */
203 while (waitpid (pid, &status, 0) < 0)
204 if (errno != EINTR)
205 return -1;
206
207 /* return child's termination status */
208 return (WIFEXITED (status)) ? WEXITSTATUS (status) : -1;
209}
210
211
212static int
213_cmd_fetch_output (int fd, output * op, int flags)
214{
215 size_t len = 0, i = 0, lineno = 0;
216 size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
217 char *buf = NULL;
218 int ret;
219 char tmpbuf[4096];
220
221 op->buf = NULL;
222 op->buflen = 0;
223 while ((ret = read (fd, tmpbuf, sizeof (tmpbuf))) > 0) {
224 len = (size_t) ret;
225 op->buf = realloc (op->buf, op->buflen + len + 1);
226 memcpy (op->buf + op->buflen, tmpbuf, len);
227 op->buflen += len;
228 i++;
229 }
230
231 if (ret < 0) {
232 printf ("read() returned %d: %s\n", ret, strerror (errno));
233 return ret;
234 }
235
236 /* some plugins may want to keep output unbroken, and some commands
237 * will yield no output, so return here for those */
238 if (flags & CMD_NO_ARRAYS || !op->buf || !op->buflen)
239 return op->buflen;
240
241 /* and some may want both */
242 if (flags & CMD_NO_ASSOC) {
243 buf = malloc (op->buflen);
244 memcpy (buf, op->buf, op->buflen);
245 }
246 else
247 buf = op->buf;
248
249 op->line = NULL;
250 op->lens = NULL;
251 i = 0;
252 while (i < op->buflen) {
253 /* make sure we have enough memory */
254 if (lineno >= ary_size) {
255 /* ary_size must never be zero */
256 do {
257 ary_size = op->buflen >> --rsf;
258 } while (!ary_size);
259
260 op->line = realloc (op->line, ary_size * sizeof (char *));
261 op->lens = realloc (op->lens, ary_size * sizeof (size_t));
262 }
263
264 /* set the pointer to the string */
265 op->line[lineno] = &buf[i];
266
267 /* hop to next newline or end of buffer */
268 while (buf[i] != '\n' && i < op->buflen)
269 i++;
270 buf[i] = '\0';
271
272 /* calculate the string length using pointer difference */
273 op->lens[lineno] = (size_t) & buf[i] - (size_t) op->line[lineno];
274
275 lineno++;
276 i++;
277 }
278
279 return lineno;
280}
281
282
283int
284cmd_run (const char *cmdstring, output * out, output * err, int flags)
285{
286 int fd, pfd_out[2], pfd_err[2];
287 int i = 0, argc;
288 size_t cmdlen;
289 char **argv = NULL;
290 char *cmd = NULL;
291 char *str = NULL;
292
293 if (cmdstring == NULL)
294 return -1;
295
296 /* initialize the structs */
297 if (out)
298 memset (out, 0, sizeof (output));
299 if (err)
300 memset (err, 0, sizeof (output));
301
302 /* make copy of command string so strtok() doesn't silently modify it */
303 /* (the calling program may want to access it later) */
304 cmdlen = strlen (cmdstring);
305 if ((cmd = malloc (cmdlen + 1)) == NULL)
306 return -1;
307 memcpy (cmd, cmdstring, cmdlen);
308 cmd[cmdlen] = '\0';
309
310 /* This is not a shell, so we don't handle "???" */
311 if (strstr (cmdstring, "\"")) return -1;
312
313 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
314 if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
315 return -1;
316
317 /* each arg must be whitespace-separated, so args can be a maximum
318 * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
319 argc = (cmdlen >> 1) + 2;
320 argv = calloc (sizeof (char *), argc);
321
322 if (argv == NULL) {
323 printf ("%s\n", _("Could not malloc argv array in popen()"));
324 return -1;
325 }
326
327 /* get command arguments (stupidly, but fairly quickly) */
328 while (cmd) {
329 str = cmd;
330 str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
331
332 if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
333 str++;
334 if (!strstr (str, "'"))
335 return -1; /* balanced? */
336 cmd = 1 + strstr (str, "'");
337 str[strcspn (str, "'")] = 0;
338 }
339 else {
340 if (strpbrk (str, " \t\r\n")) {
341 cmd = 1 + strpbrk (str, " \t\r\n");
342 str[strcspn (str, " \t\r\n")] = 0;
343 }
344 else {
345 cmd = NULL;
346 }
347 }
348
349 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
350 cmd = NULL;
351
352 argv[i++] = str;
353 }
354
355 return cmd_run_array (argv, out, err, flags);
356}
357
358int
359cmd_run_array (char *const *argv, output * out, output * err, int flags)
360{
361 int fd, pfd_out[2], pfd_err[2];
362
363 /* initialize the structs */
364 if (out)
365 memset (out, 0, sizeof (output));
366 if (err)
367 memset (err, 0, sizeof (output));
368
369 if ((fd = _cmd_open (argv, pfd_out, pfd_err)) == -1)
370 die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), argv[0]);
371
372 if (out)
373 out->lines = _cmd_fetch_output (pfd_out[0], out, flags);
374 if (err)
375 err->lines = _cmd_fetch_output (pfd_err[0], err, flags);
376
377 return _cmd_close (fd);
378}
diff --git a/lib/utils_cmd.h b/lib/utils_cmd.h
new file mode 100644
index 00000000..d54b2b4d
--- /dev/null
+++ b/lib/utils_cmd.h
@@ -0,0 +1,34 @@
1#ifndef _UTILS_CMD_
2#define _UTILS_CMD_
3
4/*
5 * Header file for nagios plugins utils_cmd.c
6 *
7 *
8 */
9
10/** types **/
11struct output
12{
13 char *buf; /* output buffer */
14 size_t buflen; /* output buffer content length */
15 char **line; /* array of lines (points to buf) */
16 size_t *lens; /* string lengths */
17 size_t lines; /* lines of output */
18};
19
20typedef struct output output;
21
22/** prototypes **/
23int cmd_run (const char *, output *, output *, int);
24int cmd_run_array (char *const *, output *, output *, int);
25
26/* only multi-threaded plugins need to bother with this */
27void cmd_init (void);
28#define CMD_INIT cmd_init()
29
30/* possible flags for cmd_run()'s fourth argument */
31#define CMD_NO_ARRAYS 0x01 /* don't populate arrays at all */
32#define CMD_NO_ASSOC 0x02 /* output.line won't point to buf */
33
34#endif /* _UTILS_CMD_ */
diff --git a/plugins/Makefile.am b/plugins/Makefile.am
index 5e3cb0f1..c0486bc1 100644
--- a/plugins/Makefile.am
+++ b/plugins/Makefile.am
@@ -87,7 +87,7 @@ check_ups_LDADD = $(NETLIBS)
87check_users_LDADD = $(BASEOBJS) popen.o 87check_users_LDADD = $(BASEOBJS) popen.o
88check_by_ssh_LDADD = $(NETLIBS) runcmd.o 88check_by_ssh_LDADD = $(NETLIBS) runcmd.o
89check_ide_smart_LDADD = $(BASEOBJS) 89check_ide_smart_LDADD = $(BASEOBJS)
90negate_LDADD = $(BASEOBJS) popen.o 90negate_LDADD = $(BASEOBJS)
91urlize_LDADD = $(BASEOBJS) popen.o 91urlize_LDADD = $(BASEOBJS) popen.o
92 92
93check_apt_DEPENDENCIES = check_apt.c $(BASEOBJS) runcmd.o $(DEPLIBS) 93check_apt_DEPENDENCIES = check_apt.c $(BASEOBJS) runcmd.o $(DEPLIBS)
@@ -126,7 +126,7 @@ check_time_DEPENDENCIES = check_time.c $(NETOBJS) $(DEPLIBS)
126check_ups_DEPENDENCIES = check_ups.c $(NETOBJS) $(DEPLIBS) 126check_ups_DEPENDENCIES = check_ups.c $(NETOBJS) $(DEPLIBS)
127check_users_DEPENDENCIES = check_users.c $(BASEOBJS) popen.o $(DEPLIBS) 127check_users_DEPENDENCIES = check_users.c $(BASEOBJS) popen.o $(DEPLIBS)
128check_by_ssh_DEPENDENCIES = check_by_ssh.c $(NETOBJS) runcmd.o $(DEPLIBS) 128check_by_ssh_DEPENDENCIES = check_by_ssh.c $(NETOBJS) runcmd.o $(DEPLIBS)
129negate_DEPENDENCIES = negate.c $(BASEOBJS) popen.o $(DEPLIBS) 129negate_DEPENDENCIES = negate.c $(BASEOBJS) $(DEPLIBS)
130urlize_DEPENDENCIES = urlize.c $(BASEOBJS) popen.o $(DEPLIBS) 130urlize_DEPENDENCIES = urlize.c $(BASEOBJS) popen.o $(DEPLIBS)
131 131
132############################################################################## 132##############################################################################
diff --git a/plugins/negate.c b/plugins/negate.c
index 8b2dff0e..cbde6a12 100644
--- a/plugins/negate.c
+++ b/plugins/negate.c
@@ -77,12 +77,12 @@ const char *email = "nagiosplug-devel@lists.sourceforge.net";
77 77
78#include "common.h" 78#include "common.h"
79#include "utils.h" 79#include "utils.h"
80#include "popen.h" 80#include "utils_cmd.h"
81 81
82char *command_line; 82//char *command_line;
83 83
84int process_arguments (int, char **); 84static const char **process_arguments (int, char **);
85int validate_arguments (void); 85int validate_arguments (char **);
86void print_help (void); 86void print_help (void);
87void print_usage (void); 87void print_usage (void);
88 88
@@ -93,13 +93,15 @@ main (int argc, char **argv)
93{ 93{
94 int found = 0, result = STATE_UNKNOWN; 94 int found = 0, result = STATE_UNKNOWN;
95 char *buf; 95 char *buf;
96 char **command_line;
97 output chld_out, chld_err;
98 int i;
96 99
97 setlocale (LC_ALL, ""); 100 setlocale (LC_ALL, "");
98 bindtextdomain (PACKAGE, LOCALEDIR); 101 bindtextdomain (PACKAGE, LOCALEDIR);
99 textdomain (PACKAGE); 102 textdomain (PACKAGE);
100 103
101 if (process_arguments (argc, argv) == ERROR) 104 command_line = (char **) process_arguments (argc, argv);
102 usage4 (_("Could not parse arguments"));
103 105
104 /* Set signal handling and alarm */ 106 /* Set signal handling and alarm */
105 if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) 107 if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR)
@@ -107,36 +109,26 @@ main (int argc, char **argv)
107 109
108 (void) alarm ((unsigned) timeout_interval); 110 (void) alarm ((unsigned) timeout_interval);
109 111
110 child_process = spopen (command_line); 112 /* catch when the command is quoted */
111 if (child_process == NULL) 113 if(command_line[1] == NULL) {
112 die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), command_line); 114 result = cmd_run (command_line[0], &chld_out, &chld_err, 0);
113 115 } else {
114 child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r"); 116 result = cmd_run_array (command_line, &chld_out, &chld_err, 0);
115
116 if (child_stderr == NULL) {
117 printf (_("Could not open stderr for %s\n"), command_line);
118 } 117 }
119 118 if (chld_err.lines > 0) {
120 buf = malloc(MAX_INPUT_BUFFER); 119 printf ("Error output from command:\n");
121 while (fgets (buf, MAX_INPUT_BUFFER - 1, child_process)) { 120 for (i = 0; i < chld_err.lines; i++) {
122 found++; 121 printf ("%s\n", chld_err.line[i]);
123 printf ("%s", buf); 122 }
123 exit (STATE_WARNING);
124 } 124 }
125 125
126 if (!found) 126 if (chld_out.lines == 0)
127 die (STATE_UNKNOWN, 127 die (STATE_UNKNOWN, _("No data returned from command\n"));
128 _("%s problem - No data received from host\nCMD: %s\n"),\
129 argv[0], command_line);
130
131 /* close the pipe */
132 result = spclose (child_process);
133
134 /* WARNING if output found on stderr */
135 if (fgets (buf, MAX_INPUT_BUFFER - 1, child_stderr))
136 result = max_state (result, STATE_WARNING);
137 128
138 /* close stderr */ 129 for (i = 0; i < chld_out.lines; i++) {
139 (void) fclose (child_stderr); 130 printf ("%s\n", chld_out.line[i]);
131 }
140 132
141 if (result == STATE_OK) 133 if (result == STATE_OK)
142 exit (STATE_CRITICAL); 134 exit (STATE_CRITICAL);
@@ -167,7 +159,7 @@ is a only a 'timeout' option.</para>
167 159
168 160
169/* process command-line arguments */ 161/* process command-line arguments */
170int 162static const char **
171process_arguments (int argc, char **argv) 163process_arguments (int argc, char **argv)
172{ 164{
173 int c; 165 int c;
@@ -181,8 +173,7 @@ process_arguments (int argc, char **argv)
181 }; 173 };
182 174
183 while (1) { 175 while (1) {
184 c = getopt_long (argc, argv, "+hVt:", 176 c = getopt_long (argc, argv, "+hVt:", longopts, &option);
185 longopts, &option);
186 177
187 if (c == -1 || c == EOF) 178 if (c == -1 || c == EOF)
188 break; 179 break;
@@ -207,12 +198,9 @@ process_arguments (int argc, char **argv)
207 } 198 }
208 } 199 }
209 200
210 asprintf (&command_line, "%s", argv[optind]); 201 validate_arguments (&argv[optind]);
211 for (c = optind+1; c < argc; c++) {
212 asprintf (&command_line, "%s %s", command_line, argv[c]);
213 }
214 202
215 return validate_arguments (); 203 return (const char **) &argv[optind];
216} 204}
217 205
218 206
@@ -230,11 +218,13 @@ process_arguments (int argc, char **argv)
230 218
231 219
232int 220int
233validate_arguments () 221validate_arguments (char **command_line)
234{ 222{
235 if (command_line == NULL) 223 if (command_line[0] == NULL)
236 return ERROR; 224 usage4 (_("Could not parse arguments"));
237 return STATE_OK; 225
226 if (strncmp(command_line[0],"/",1) != 0 && strncmp(command_line[0],"./",2) != 0)
227 usage4 (_("Require path to command"));
238} 228}
239 229
240/****************************************************************************** 230/******************************************************************************
@@ -256,7 +246,7 @@ print_help (void)
256 246
257 printf ("%s\n", _("Negates the status of a plugin (returns OK for CRITICAL, and vice-versa).")); 247 printf ("%s\n", _("Negates the status of a plugin (returns OK for CRITICAL, and vice-versa)."));
258 248
259 printf ("\n\n"); 249 printf ("\n\n");
260 250
261 print_usage (); 251 print_usage ();
262 252
@@ -265,19 +255,20 @@ print_help (void)
265 printf (_(UT_TIMEOUT), DEFAULT_TIMEOUT); 255 printf (_(UT_TIMEOUT), DEFAULT_TIMEOUT);
266 256
267 printf (" %s\n", _("[keep timeout than the plugin timeout to retain CRITICAL status]")); 257 printf (" %s\n", _("[keep timeout than the plugin timeout to retain CRITICAL status]"));
268 printf ("\n"); 258 printf ("\n");
269 printf ("%s\n", _("Examples:")); 259 printf ("%s\n", _("Examples:"));
270 printf (" %s\n", "negate \"/usr/local/nagios/libexec/check_ping -H host\""); 260 printf (" %s\n", "negate /usr/local/nagios/libexec/check_ping -H host");
271 printf (" %s\n", _("Run check_ping and invert result. Must use full path to plugin")); 261 printf (" %s\n", _("Run check_ping and invert result. Must use full path to plugin"));
272 printf (" %s\n", "negate \"/usr/local/nagios/libexec/check_procs -a 'vi negate.c'\""); 262 printf (" %s\n", "negate /usr/local/nagios/libexec/check_procs -a 'vi negate.c'");
273 printf (" %s\n", _("Use single quotes if you need to retain spaces")); 263 printf (" %s\n", _("Use single quotes if you need to retain spaces"));
274 printf (_(UT_VERBOSE)); 264 printf (_(UT_VERBOSE));
275 printf ("\n"); 265 printf ("\n");
276 printf ("%s\n", _("Notes:")); 266 printf ("%s\n", _("Notes:"));
277 printf ("%s\n", _("This plugin is a wrapper to take the output of another plugin and invert it.")); 267 printf ("%s\n", _("This plugin is a wrapper to take the output of another plugin and invert it."));
278 printf ("%s\n", _("If the wrapped plugin returns STATE_OK, the wrapper will return STATE_CRITICAL.")); 268 printf ("%s\n", _("The full path of the plugin must be provided."));
279 printf ("%s\n", _("If the wrapped plugin returns STATE_CRITICAL, the wrapper will return STATE_OK.")); 269 printf ("%s\n", _("If the wrapped plugin returns STATE_OK, the wrapper will return STATE_CRITICAL."));
280 printf ("%s\n", _("Otherwise, the output state of the wrapped plugin is unchanged.")); 270 printf ("%s\n", _("If the wrapped plugin returns STATE_CRITICAL, the wrapper will return STATE_OK."));
271 printf ("%s\n", _("Otherwise, the output state of the wrapped plugin is unchanged."));
281 272
282 printf (_(UT_SUPPORT)); 273 printf (_(UT_SUPPORT));
283} 274}
@@ -287,6 +278,6 @@ print_help (void)
287void 278void
288print_usage (void) 279print_usage (void)
289{ 280{
290 printf (_("Usage:")); 281 printf (_("Usage:"));
291 printf ("%s [-t timeout] <definition of wrapped plugin>\n",progname); 282 printf ("%s [-t timeout] <definition of wrapped plugin>\n",progname);
292} 283}
diff --git a/plugins/t/negate.pl b/plugins/t/negate.pl
deleted file mode 100644
index 6c56d4f4..00000000
--- a/plugins/t/negate.pl
+++ /dev/null
@@ -1,48 +0,0 @@
1#! /usr/bin/perl -w -I ..
2#
3# negate checks
4# Need check_dummy to work for testing
5#
6# $Id$
7#
8
9use strict;
10use Test::More;
11use NPTest;
12
13plan tests => 40;
14
15my $res;
16
17$res = NPTest->testCmd( "./negate" );
18is( $res->return_code, 3, "Not enough parameters");
19like( $res->output, "/Could not parse arguments/", "Could not parse arguments");
20
21$res = NPTest->testCmd( "./negate ./check_dummy 0 'a dummy okay'" );
22is( $res->return_code, 2, "OK changed to CRITICAL" );
23is( $res->output, "OK: a dummy okay" );
24
25$res = NPTest->testCmd( "./negate './check_dummy 0 redsweaterblog'");
26is( $res->return_code, 2, "OK => CRIT with a single quote for command to run" );
27is( $res->output, "OK: redsweaterblog" );
28
29$res = NPTest->testCmd( "./negate ./check_dummy 1 'a warn a day keeps the managers at bay'" );
30is( $res->return_code, 2, "WARN stays same" );
31
32$res = NPTest->testCmd( "./negate ./check_dummy 3 mysterious");
33is( $res->return_code, 3, "UNKNOWN stays same" );
34
35my %state = (
36 ok => 0,
37 warning => 1,
38 critical => 2,
39 unknown => 3,
40 );
41foreach my $current_state (qw(ok warning critical unknown)) {
42 foreach my $new_state (qw(ok warning critical unknown)) {
43 $res = NPTest->testCmd( "./negate --$current_state=$new_state ./check_dummy ".$state{$current_state}." 'Fake $new_state'" );
44 is( $res->return_code, $state{$new_state}, "Got fake $new_state" );
45 is( $res->output, uc($current_state).": Fake $new_state" );
46 }
47}
48
diff --git a/plugins/t/negate.t b/plugins/t/negate.t
new file mode 100644
index 00000000..0efa0ca8
--- /dev/null
+++ b/plugins/t/negate.t
@@ -0,0 +1,79 @@
1#! /usr/bin/perl -w -I ..
2#
3# negate checks
4# Need check_dummy to work for testing
5#
6# $Id: negate.pl 1717 2007-05-24 08:53:50Z tonvoon $
7#
8
9use strict;
10use Test::More;
11use NPTest;
12
13# 47 tests if the "map changes to return codes" patch is applied
14#plan tests => 47;
15plan tests => 15;
16
17my $res;
18
19my $PWD = $ENV{PWD};
20
21$res = NPTest->testCmd( "./negate" );
22is( $res->return_code, 3, "Not enough parameters");
23like( $res->output, "/Could not parse arguments/", "Could not parse arguments");
24
25$res = NPTest->testCmd( "./negate bobthebuilder" );
26is( $res->return_code, 3, "Require full path" );
27like( $res->output, "/Require path to command/", "Appropriate error message");
28
29$res = NPTest->testCmd( "./negate $PWD/check_dummy 0 'a dummy okay'" );
30is( $res->return_code, 2, "OK changed to CRITICAL" );
31is( $res->output, "OK: a dummy okay", "Output as expected" );
32
33$res = NPTest->testCmd( "./negate '$PWD/check_dummy 0 redsweaterblog'");
34is( $res->return_code, 2, "OK => CRIT with a single quote for command to run" );
35is( $res->output, "OK: redsweaterblog", "Output as expected" );
36
37$res = NPTest->testCmd( "./negate $PWD/check_dummy 1 'a warn a day keeps the managers at bay'" );
38is( $res->return_code, 1, "WARN stays same" );
39
40$res = NPTest->testCmd( "./negate $PWD/check_dummy 3 mysterious");
41is( $res->return_code, 3, "UNKNOWN stays same" );
42
43$res = NPTest->testCmd( "./negate \"$PWD/check_dummy 0 'a dummy okay'\"" );
44is( $res->output, "OK: a dummy okay", "Checking slashed quotes - the single quotes are re-evaluated at shell" );
45
46# Output is "OK: a" because check_dummy only returns the first arg
47$res = NPTest->testCmd( "./negate $PWD/check_dummy 0 a dummy okay" );
48is( $res->output, "OK: a", "Multiple args passed as arrays" );
49
50$res = NPTest->testCmd( "./negate $PWD/check_dummy 0 'a dummy okay'" );
51is( $res->output, "OK: a dummy okay", "The quoted string is passed through to subcommand correctly" );
52
53$res = NPTest->testCmd( "./negate '$PWD/check_dummy 0' 'a dummy okay'" );
54is( $res->output, "No data returned from command", "Bad command, as expected (trying to execute './check_dummy 0')");
55
56$res = NPTest->testCmd( './negate $PWD/check_dummy 0 \'$$ a dummy okay\'' );
57is( $res->output, 'OK: $$ a dummy okay', 'Proves that $$ is not being expanded again' );
58
59
60# Remove __DATA__ to run tests with future patch
61__DATA__
62
63TODO: {
64 local $TODO = "Codes can be switched";
65 my %state = (
66 ok => 0,
67 warning => 1,
68 critical => 2,
69 unknown => 3,
70 );
71 foreach my $current_state (qw(ok warning critical unknown)) {
72 foreach my $new_state (qw(ok warning critical unknown)) {
73 $res = NPTest->testCmd( "./negate --$current_state=$new_state ./check_dummy ".$state{$current_state}." 'Fake $new_state'" );
74 is( $res->return_code, $state{$new_state}, "Got fake $new_state" );
75 is( $res->output, uc($current_state).": Fake $new_state" );
76 }
77 }
78}
79