summaryrefslogtreecommitdiffstats
path: root/plugins/check_tcp.c
diff options
context:
space:
mode:
Diffstat (limited to 'plugins/check_tcp.c')
-rw-r--r--plugins/check_tcp.c758
1 files changed, 431 insertions, 327 deletions
diff --git a/plugins/check_tcp.c b/plugins/check_tcp.c
index 49ad096c..793cfe7e 100644
--- a/plugins/check_tcp.c
+++ b/plugins/check_tcp.c
@@ -3,7 +3,7 @@
3 * Monitoring check_tcp plugin 3 * Monitoring check_tcp plugin
4 * 4 *
5 * License: GPL 5 * License: GPL
6 * Copyright (c) 1999-2024 Monitoring Plugins Development Team 6 * Copyright (c) 1999-2025 Monitoring Plugins Development Team
7 * 7 *
8 * Description: 8 * Description:
9 * 9 *
@@ -29,74 +29,62 @@
29 29
30/* progname "check_tcp" changes depending on symlink called */ 30/* progname "check_tcp" changes depending on symlink called */
31char *progname; 31char *progname;
32const char *copyright = "1999-2024"; 32const char *copyright = "1999-2025";
33const char *email = "devel@monitoring-plugins.org"; 33const char *email = "devel@monitoring-plugins.org";
34 34
35#include "common.h" 35#include "./common.h"
36#include "netutils.h" 36#include "./netutils.h"
37#include "utils.h" 37#include "./utils.h"
38#include "utils_tcp.h" 38#include "./check_tcp.d/config.h"
39#include "states.h"
39 40
41#include <sys/types.h>
40#include <ctype.h> 42#include <ctype.h>
41#include <sys/select.h> 43#include <sys/select.h>
42 44
45ssize_t my_recv(char *buf, size_t len) {
43#ifdef HAVE_SSL 46#ifdef HAVE_SSL
44static bool check_cert = false; 47 return np_net_ssl_read(buf, (int)len);
45static int days_till_exp_warn, days_till_exp_crit;
46# define my_recv(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_read(buf, len) : read(sd, buf, len))
47# define my_send(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0))
48#else 48#else
49# define my_recv(buf, len) read(sd, buf, len) 49 return read(socket_descriptor, buf, len);
50# define my_send(buf, len) send(sd, buf, len, 0) 50#endif // HAVE_SSL
51#endif 51}
52
53ssize_t my_send(char *buf, size_t len) {
54#ifdef HAVE_SSL
55 return np_net_ssl_write(buf, (int)len);
56#else
57 return write(socket_descriptor, buf, len);
58#endif // HAVE_SSL
59}
60
61typedef struct process_arguments_wrapper {
62 int errorcode;
63 check_tcp_config config;
64} check_tcp_config_wrapper;
52 65
53/* int my_recv(char *, size_t); */ 66/* int my_recv(char *, size_t); */
54static int process_arguments(int /*argc*/, char ** /*argv*/); 67static check_tcp_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/, check_tcp_config /*config*/);
55static void print_help(void); 68void print_help(const char *service);
56void print_usage(void); 69void print_usage(void);
57 70
58#define EXPECT server_expect[0] 71int verbosity = 0;
59static char *SERVICE = "TCP";
60static char *SEND = NULL;
61static char *QUIT = NULL;
62static int PROTOCOL = IPPROTO_TCP; /* most common is default */
63static int PORT = 0;
64static int READ_TIMEOUT = 2;
65
66static int server_port = 0;
67static char *server_address = NULL;
68static bool host_specified = false;
69static char *server_send = NULL;
70static char *server_quit = NULL;
71static char **server_expect;
72static size_t server_expect_count = 0;
73static ssize_t maxbytes = 0;
74static char **warn_codes = NULL;
75static size_t warn_codes_count = 0;
76static char **crit_codes = NULL;
77static size_t crit_codes_count = 0;
78static unsigned int delay = 0;
79static double warning_time = 0;
80static double critical_time = 0;
81static double elapsed_time = 0;
82static long microsec;
83static int sd = 0;
84#define MAXBUF 1024
85static char buffer[MAXBUF];
86static int expect_mismatch_state = STATE_WARNING;
87static int match_flags = NP_MATCH_EXACT;
88 72
89#ifdef HAVE_SSL 73static const int READ_TIMEOUT = 2;
90static char *sni = NULL; 74
91static bool sni_specified = false; 75const int MAXBUF = 1024;
92#endif
93 76
94#define FLAG_SSL 0x01 77const int DEFAULT_FTP_PORT = 21;
95#define FLAG_VERBOSE 0x02 78const int DEFAULT_POP_PORT = 110;
96#define FLAG_TIME_WARN 0x04 79const int DEFAULT_SPOP_PORT = 995;
97#define FLAG_TIME_CRIT 0x08 80const int DEFAULT_SMTP_PORT = 25;
98#define FLAG_HIDE_OUTPUT 0x10 81const int DEFAULT_SSMTP_PORT = 465;
99static size_t flags; 82const int DEFAULT_IMAP_PORT = 143;
83const int DEFAULT_SIMAP_PORT = 993;
84const int DEFAULT_XMPP_C2S_PORT = 5222;
85const int DEFAULT_NNTP_PORT = 119;
86const int DEFAULT_NNTPS_PORT = 563;
87const int DEFAULT_CLAMD_PORT = 3310;
100 88
101int main(int argc, char **argv) { 89int main(int argc, char **argv) {
102 setlocale(LC_ALL, ""); 90 setlocale(LC_ALL, "");
@@ -105,277 +93,372 @@ int main(int argc, char **argv) {
105 93
106 /* determine program- and service-name quickly */ 94 /* determine program- and service-name quickly */
107 progname = strrchr(argv[0], '/'); 95 progname = strrchr(argv[0], '/');
108 if (progname != NULL) 96 if (progname != NULL) {
109 progname++; 97 progname++;
110 else 98 } else {
111 progname = argv[0]; 99 progname = argv[0];
100 }
101
102 // Initialize config here with values from above,
103 // might be changed by on disk config or cli commands
104 check_tcp_config config = check_tcp_config_init();
112 105
113 size_t prog_name_len = strlen(progname); 106 size_t prog_name_len = strlen(progname);
114 if (prog_name_len > 6 && !memcmp(progname, "check_", 6)) { 107 const size_t prefix_length = strlen("check_");
115 SERVICE = strdup(progname + 6); 108
116 for (size_t i = 0; i < prog_name_len - 6; i++) 109 if (prog_name_len <= prefix_length) {
117 SERVICE[i] = toupper(SERVICE[i]); 110 die(STATE_UNKNOWN, _("Weird progname"));
111 }
112
113 if (!memcmp(progname, "check_", prefix_length)) {
114 config.service = strdup(progname + prefix_length);
115 if (config.service == NULL) {
116 die(STATE_UNKNOWN, _("Allocation failed"));
117 }
118
119 for (size_t i = 0; i < prog_name_len - prefix_length; i++) {
120 config.service[i] = toupper(config.service[i]);
121 }
118 } 122 }
119 123
120 /* set up a reasonable buffer at first (will be realloc()'ed if 124 /* set up a reasonable buffer at first (will be realloc()'ed if
121 * user specifies other options) */ 125 * user specifies other options) */
122 server_expect = calloc(2, sizeof(char *)); 126 config.server_expect = calloc(2, sizeof(char *));
127
128 if (config.server_expect == NULL) {
129 die(STATE_UNKNOWN, _("Allocation failed"));
130 }
123 131
124 /* determine defaults for this service's protocol */ 132 /* determine defaults for this service's protocol */
125 if (!strncmp(SERVICE, "UDP", 3)) { 133 if (!strncmp(config.service, "UDP", strlen("UDP"))) {
126 PROTOCOL = IPPROTO_UDP; 134 config.protocol = IPPROTO_UDP;
127 } else if (!strncmp(SERVICE, "FTP", 3)) { 135 } else if (!strncmp(config.service, "FTP", strlen("FTP"))) {
128 EXPECT = "220"; 136 config.server_expect[0] = "220";
129 QUIT = "QUIT\r\n"; 137 config.quit = "QUIT\r\n";
130 PORT = 21; 138 config.server_port = DEFAULT_FTP_PORT;
131 } else if (!strncmp(SERVICE, "POP", 3) || !strncmp(SERVICE, "POP3", 4)) { 139 } else if (!strncmp(config.service, "POP", strlen("POP")) || !strncmp(config.service, "POP3", strlen("POP3"))) {
132 EXPECT = "+OK"; 140 config.server_expect[0] = "+OK";
133 QUIT = "QUIT\r\n"; 141 config.quit = "QUIT\r\n";
134 PORT = 110; 142 config.server_port = DEFAULT_POP_PORT;
135 } else if (!strncmp(SERVICE, "SMTP", 4)) { 143 } else if (!strncmp(config.service, "SMTP", strlen("SMTP"))) {
136 EXPECT = "220"; 144 config.server_expect[0] = "220";
137 QUIT = "QUIT\r\n"; 145 config.quit = "QUIT\r\n";
138 PORT = 25; 146 config.server_port = DEFAULT_SMTP_PORT;
139 } else if (!strncmp(SERVICE, "IMAP", 4)) { 147 } else if (!strncmp(config.service, "IMAP", strlen("IMAP"))) {
140 EXPECT = "* OK"; 148 config.server_expect[0] = "* OK";
141 QUIT = "a1 LOGOUT\r\n"; 149 config.quit = "a1 LOGOUT\r\n";
142 PORT = 143; 150 config.server_port = DEFAULT_IMAP_PORT;
143 } 151 }
144#ifdef HAVE_SSL 152#ifdef HAVE_SSL
145 else if (!strncmp(SERVICE, "SIMAP", 5)) { 153 else if (!strncmp(config.service, "SIMAP", strlen("SIMAP"))) {
146 EXPECT = "* OK"; 154 config.server_expect[0] = "* OK";
147 QUIT = "a1 LOGOUT\r\n"; 155 config.quit = "a1 LOGOUT\r\n";
148 flags |= FLAG_SSL; 156 config.use_tls = true;
149 PORT = 993; 157 config.server_port = DEFAULT_SIMAP_PORT;
150 } else if (!strncmp(SERVICE, "SPOP", 4)) { 158 } else if (!strncmp(config.service, "SPOP", strlen("SPOP"))) {
151 EXPECT = "+OK"; 159 config.server_expect[0] = "+OK";
152 QUIT = "QUIT\r\n"; 160 config.quit = "QUIT\r\n";
153 flags |= FLAG_SSL; 161 config.use_tls = true;
154 PORT = 995; 162 config.server_port = DEFAULT_SPOP_PORT;
155 } else if (!strncmp(SERVICE, "SSMTP", 5)) { 163 } else if (!strncmp(config.service, "SSMTP", strlen("SSMTP"))) {
156 EXPECT = "220"; 164 config.server_expect[0] = "220";
157 QUIT = "QUIT\r\n"; 165 config.quit = "QUIT\r\n";
158 flags |= FLAG_SSL; 166 config.use_tls = true;
159 PORT = 465; 167 config.server_port = DEFAULT_SSMTP_PORT;
160 } else if (!strncmp(SERVICE, "JABBER", 6)) { 168 } else if (!strncmp(config.service, "JABBER", strlen("JABBER"))) {
161 SEND = "<stream:stream to=\'host\' xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'>\n"; 169 config.send = "<stream:stream to=\'host\' xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'>\n";
162 EXPECT = "<?xml version=\'1.0\'"; 170 config.server_expect[0] = "<?xml version=\'1.0\'";
163 QUIT = "</stream:stream>\n"; 171 config.quit = "</stream:stream>\n";
164 flags |= FLAG_HIDE_OUTPUT; 172 config.hide_output = true;
165 PORT = 5222; 173 config.server_port = DEFAULT_XMPP_C2S_PORT;
166 } else if (!strncmp(SERVICE, "NNTPS", 5)) { 174 } else if (!strncmp(config.service, "NNTPS", strlen("NNTPS"))) {
167 server_expect_count = 2; 175 config.server_expect_count = 2;
168 server_expect[0] = "200"; 176 config.server_expect[0] = "200";
169 server_expect[1] = "201"; 177 config.server_expect[1] = "201";
170 QUIT = "QUIT\r\n"; 178 config.quit = "QUIT\r\n";
171 flags |= FLAG_SSL; 179 config.use_tls = true;
172 PORT = 563; 180 config.server_port = DEFAULT_NNTPS_PORT;
173 } 181 }
174#endif 182#endif
175 else if (!strncmp(SERVICE, "NNTP", 4)) { 183 else if (!strncmp(config.service, "NNTP", strlen("NNTP"))) {
176 server_expect_count = 2; 184 config.server_expect_count = 2;
177 server_expect = malloc(sizeof(char *) * server_expect_count); 185 char **tmp = realloc(config.server_expect, config.server_expect_count * sizeof(char *));
178 server_expect[0] = strdup("200"); 186 if (tmp == NULL) {
179 server_expect[1] = strdup("201"); 187 free(config.server_expect);
180 QUIT = "QUIT\r\n"; 188 die(STATE_UNKNOWN, _("Allocation failed"));
181 PORT = 119; 189 }
182 } else if (!strncmp(SERVICE, "CLAMD", 5)) { 190 config.server_expect = tmp;
183 SEND = "PING"; 191
184 EXPECT = "PONG"; 192 config.server_expect[0] = strdup("200");
185 QUIT = NULL; 193 config.server_expect[1] = strdup("201");
186 PORT = 3310; 194 config.quit = "QUIT\r\n";
195 config.server_port = DEFAULT_NNTP_PORT;
196 } else if (!strncmp(config.service, "CLAMD", strlen("CLAMD"))) {
197 config.send = "PING";
198 config.server_expect[0] = "PONG";
199 config.quit = NULL;
200 config.server_port = DEFAULT_CLAMD_PORT;
187 } 201 }
188 /* fallthrough check, so it's supposed to use reverse matching */ 202 /* fallthrough check, so it's supposed to use reverse matching */
189 else if (strcmp(SERVICE, "TCP")) 203 else if (strcmp(config.service, "TCP")) {
190 usage(_("CRITICAL - Generic check_tcp called with unknown service\n")); 204 usage(_("CRITICAL - Generic check_tcp called with unknown service\n"));
191 205 }
192 server_address = "127.0.0.1";
193 server_port = PORT;
194 server_send = SEND;
195 server_quit = QUIT;
196 char *status = NULL;
197 206
198 /* Parse extra opts if any */ 207 /* Parse extra opts if any */
199 argv = np_extra_opts(&argc, argv, progname); 208 argv = np_extra_opts(&argc, argv, progname);
200 209
201 if (process_arguments(argc, argv) == ERROR) 210 check_tcp_config_wrapper paw = process_arguments(argc, argv, config);
211 if (paw.errorcode == ERROR) {
202 usage4(_("Could not parse arguments")); 212 usage4(_("Could not parse arguments"));
213 }
214
215 config = paw.config;
203 216
204 if (flags & FLAG_VERBOSE) { 217 if (verbosity > 0) {
205 printf("Using service %s\n", SERVICE); 218 printf("Using service %s\n", config.service);
206 printf("Port: %d\n", server_port); 219 printf("Port: %d\n", config.server_port);
207 printf("flags: 0x%x\n", (int)flags);
208 } 220 }
209 221
210 if (EXPECT && !server_expect_count) 222 if ((config.server_expect_count == 0) && config.server_expect[0]) {
211 server_expect_count++; 223 config.server_expect_count++;
224 }
212 225
213 if (PROTOCOL == IPPROTO_UDP && !(server_expect_count && server_send)) { 226 if (config.protocol == IPPROTO_UDP && !(config.server_expect_count && config.send)) {
214 usage(_("With UDP checks, a send/expect string must be specified.")); 227 usage(_("With UDP checks, a send/expect string must be specified."));
215 } 228 }
216 229
230 // Initialize check stuff before setting timers
231 mp_check overall = mp_check_init();
232 if (config.output_format_set) {
233 overall.format = config.output_format;
234 }
235
217 /* set up the timer */ 236 /* set up the timer */
218 signal(SIGALRM, socket_timeout_alarm_handler); 237 signal(SIGALRM, socket_timeout_alarm_handler);
219 alarm(socket_timeout); 238 alarm(socket_timeout);
220 239
221 /* try to connect to the host at the given port number */ 240 /* try to connect to the host at the given port number */
222 struct timeval tv; 241 struct timeval start_time;
223 gettimeofday(&tv, NULL); 242 gettimeofday(&start_time, NULL);
224 243
225 int result = STATE_UNKNOWN; 244 int socket_descriptor = 0;
226 result = np_net_connect(server_address, server_port, &sd, PROTOCOL); 245 mp_subcheck inital_connect_result = mp_subcheck_init();
227 if (result == STATE_CRITICAL) 246
228 return econn_refuse_state; 247 // Try initial connection
248 if (np_net_connect(config.server_address, config.server_port, &socket_descriptor, config.protocol) == STATE_CRITICAL) {
249 // Early exit here, we got connection refused
250 inital_connect_result = mp_set_subcheck_state(inital_connect_result, config.econn_refuse_state);
251 xasprintf(&inital_connect_result.output, "Connection to %s on port %i was REFUSED", config.server_address, config.server_port);
252 mp_add_subcheck_to_check(&overall, inital_connect_result);
253 mp_exit(overall);
254 } else {
255 inital_connect_result = mp_set_subcheck_state(inital_connect_result, STATE_OK);
256 xasprintf(&inital_connect_result.output, "Connection to %s on port %i was a SUCCESS", config.server_address, config.server_port);
257 mp_add_subcheck_to_check(&overall, inital_connect_result);
258 }
229 259
230#ifdef HAVE_SSL 260#ifdef HAVE_SSL
231 if (flags & FLAG_SSL) { 261 if (config.use_tls) {
232 result = np_net_ssl_init_with_hostname(sd, (sni_specified ? sni : NULL)); 262 mp_subcheck tls_connection_result = mp_subcheck_init();
233 if (result == STATE_OK && check_cert) { 263 int result = np_net_ssl_init_with_hostname(socket_descriptor, (config.sni_specified ? config.sni : NULL));
234 result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit); 264 tls_connection_result = mp_set_subcheck_state(tls_connection_result, result);
265
266 if (result == STATE_OK) {
267 xasprintf(&tls_connection_result.output, "TLS connection succeded");
268
269 if (config.check_cert) {
270 result = np_net_ssl_check_cert(config.days_till_exp_warn, config.days_till_exp_crit);
271
272 mp_subcheck tls_certificate_lifetime_result = mp_subcheck_init();
273 tls_certificate_lifetime_result = mp_set_subcheck_state(tls_certificate_lifetime_result, result);
274
275 if (result == STATE_OK) {
276 xasprintf(&tls_certificate_lifetime_result.output, "Certificate lifetime is within thresholds");
277 } else if (result == STATE_WARNING) {
278 xasprintf(&tls_certificate_lifetime_result.output, "Certificate lifetime is violating warning threshold (%i)",
279 config.days_till_exp_warn);
280 } else if (result == STATE_CRITICAL) {
281 xasprintf(&tls_certificate_lifetime_result.output, "Certificate lifetime is violating critical threshold (%i)",
282 config.days_till_exp_crit);
283 } else {
284 xasprintf(&tls_certificate_lifetime_result.output, "Certificate lifetime is somehow unknown");
285 }
286
287 mp_add_subcheck_to_subcheck(&tls_connection_result, tls_certificate_lifetime_result);
288 }
289
290 mp_add_subcheck_to_check(&overall, tls_connection_result);
291 } else {
292 xasprintf(&tls_connection_result.output, "TLS connection failed");
293 mp_add_subcheck_to_check(&overall, tls_connection_result);
294
295 if (socket_descriptor) {
296 close(socket_descriptor);
297 }
298 np_net_ssl_cleanup();
299
300 mp_exit(overall);
235 } 301 }
236 } 302 }
237 if (result != STATE_OK) {
238 if (sd)
239 close(sd);
240 np_net_ssl_cleanup();
241 return result;
242 }
243#endif /* HAVE_SSL */ 303#endif /* HAVE_SSL */
244 304
245 if (server_send != NULL) { /* Something to send? */ 305 if (config.send != NULL) { /* Something to send? */
246 my_send(server_send, strlen(server_send)); 306 my_send(config.send, strlen(config.send));
247 } 307 }
248 308
249 if (delay > 0) { 309 if (config.delay > 0) {
250 tv.tv_sec += delay; 310 start_time.tv_sec += config.delay;
251 sleep(delay); 311 sleep(config.delay);
252 } 312 }
253 313
254 if (flags & FLAG_VERBOSE) { 314 if (verbosity > 0) {
255 if (server_send) { 315 if (config.send) {
256 printf("Send string: %s\n", server_send); 316 printf("Send string: %s\n", config.send);
317 }
318 if (config.quit) {
319 printf("Quit string: %s\n", config.quit);
257 } 320 }
258 if (server_quit) { 321 printf("server_expect_count: %d\n", (int)config.server_expect_count);
259 printf("Quit string: %s\n", server_quit); 322 for (size_t i = 0; i < config.server_expect_count; i++) {
323 printf("\t%zd: %s\n", i, config.server_expect[i]);
260 } 324 }
261 printf("server_expect_count: %d\n", (int)server_expect_count);
262 for (size_t i = 0; i < server_expect_count; i++)
263 printf("\t%zd: %s\n", i, server_expect[i]);
264 } 325 }
265 326
266 /* if(len) later on, we know we have a non-NULL response */ 327 /* if(len) later on, we know we have a non-NULL response */
267 ssize_t len = 0; 328 ssize_t len = 0;
268 329 char *status = NULL;
269 int match = -1; 330 int match = -1;
270 struct timeval timeout; 331 mp_subcheck expected_data_result = mp_subcheck_init();
271 fd_set rfds; 332
272 FD_ZERO(&rfds); 333 if (config.server_expect_count) {
273 if (server_expect_count) {
274 ssize_t received = 0; 334 ssize_t received = 0;
335 char buffer[MAXBUF];
275 336
276 /* watch for the expect string */ 337 /* watch for the expect string */
277 while ((received = my_recv(buffer, sizeof(buffer))) > 0) { 338 while ((received = my_recv(buffer, sizeof(buffer))) > 0) {
278 status = realloc(status, len + received + 1); 339 status = realloc(status, len + received + 1);
340
341 if (status == NULL) {
342 die(STATE_UNKNOWN, _("Allocation failed"));
343 }
344
279 memcpy(&status[len], buffer, received); 345 memcpy(&status[len], buffer, received);
280 len += received; 346 len += received;
281 status[len] = '\0'; 347 status[len] = '\0';
282 348
283 /* stop reading if user-forced */ 349 /* stop reading if user-forced */
284 if (maxbytes && len >= maxbytes) 350 if (config.maxbytes && len >= config.maxbytes) {
285 break; 351 break;
352 }
286 353
287 if ((match = np_expect_match(status, server_expect, server_expect_count, match_flags)) != NP_MATCH_RETRY) 354 if ((match = np_expect_match(status, config.server_expect, config.server_expect_count, config.match_flags)) != NP_MATCH_RETRY) {
288 break; 355 break;
356 }
357
358 fd_set rfds;
359 FD_ZERO(&rfds);
360 FD_SET(socket_descriptor, &rfds);
289 361
290 /* some protocols wait for further input, so make sure we don't wait forever */ 362 /* some protocols wait for further input, so make sure we don't wait forever */
291 FD_SET(sd, &rfds); 363 struct timeval timeout;
292 timeout.tv_sec = READ_TIMEOUT; 364 timeout.tv_sec = READ_TIMEOUT;
293 timeout.tv_usec = 0; 365 timeout.tv_usec = 0;
294 if (select(sd + 1, &rfds, NULL, NULL, &timeout) <= 0) 366
367 if (select(socket_descriptor + 1, &rfds, NULL, NULL, &timeout) <= 0) {
295 break; 368 break;
369 }
296 } 370 }
297 371
298 if (match == NP_MATCH_RETRY) 372 if (match == NP_MATCH_RETRY) {
299 match = NP_MATCH_FAILURE; 373 match = NP_MATCH_FAILURE;
374 }
300 375
301 /* no data when expected, so return critical */ 376 /* no data when expected, so return critical */
302 if (len == 0) 377 if (len == 0) {
303 die(STATE_CRITICAL, _("No data received from host\n")); 378 xasprintf(&expected_data_result.output, "Received no data when some was expected");
379 expected_data_result = mp_set_subcheck_state(expected_data_result, STATE_CRITICAL);
380 mp_add_subcheck_to_check(&overall, expected_data_result);
381 mp_exit(overall);
382 }
304 383
305 /* print raw output if we're debugging */ 384 /* print raw output if we're debugging */
306 if (flags & FLAG_VERBOSE) 385 if (verbosity > 0) {
307 printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n", (int)len + 1, status); 386 printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n", (int)len + 1, status);
387 }
308 /* strip whitespace from end of output */ 388 /* strip whitespace from end of output */
309 while (--len > 0 && isspace(status[len])) 389 while (--len > 0 && isspace(status[len])) {
310 status[len] = '\0'; 390 status[len] = '\0';
391 }
392 }
393
394 if (config.quit != NULL) {
395 my_send(config.quit, strlen(config.quit));
311 } 396 }
312 397
313 if (server_quit != NULL) { 398 if (socket_descriptor) {
314 my_send(server_quit, strlen(server_quit)); 399 close(socket_descriptor);
315 } 400 }
316 if (sd)
317 close(sd);
318#ifdef HAVE_SSL 401#ifdef HAVE_SSL
319 np_net_ssl_cleanup(); 402 np_net_ssl_cleanup();
320#endif 403#endif
321 404
322 microsec = deltime(tv); 405 long microsec = deltime(start_time);
323 elapsed_time = (double)microsec / 1.0e6; 406 double elapsed_time = (double)microsec / 1.0e6;
324 407
325 if (flags & FLAG_TIME_CRIT && elapsed_time > critical_time) 408 mp_subcheck elapsed_time_result = mp_subcheck_init();
326 result = STATE_CRITICAL;
327 else if (flags & FLAG_TIME_WARN && elapsed_time > warning_time)
328 result = STATE_WARNING;
329 409
330 /* did we get the response we hoped? */ 410 mp_perfdata time_pd = perfdata_init();
331 if (match == NP_MATCH_FAILURE && result != STATE_CRITICAL) 411 time_pd = mp_set_pd_value(time_pd, elapsed_time);
332 result = expect_mismatch_state; 412 time_pd.label = "time";
413 time_pd.uom = "s";
333 414
334 /* reset the alarm */ 415 if (config.critical_time_set && elapsed_time > config.critical_time) {
335 alarm(0); 416 xasprintf(&elapsed_time_result.output, "Connection time %fs exceeded critical threshold (%f)", elapsed_time, config.critical_time);
336 417
337 /* this is a bit stupid, because we don't want to print the 418 elapsed_time_result = mp_set_subcheck_state(elapsed_time_result, STATE_CRITICAL);
338 * response time (which can look ok to the user) if we didn't get 419 time_pd.crit_present = true;
339 * the response we were looking for. if-else */ 420 mp_range crit_val = mp_range_init();
340 printf("%s %s - ", SERVICE, state_text(result)); 421
341 422 crit_val.end = mp_create_pd_value(config.critical_time);
342 if (match == NP_MATCH_FAILURE && len && !(flags & FLAG_HIDE_OUTPUT)) 423 crit_val.end_infinity = false;
343 printf("Unexpected response from host/socket: %s", status); 424
344 else { 425 time_pd.crit = crit_val;
345 if (match == NP_MATCH_FAILURE) 426 } else if (config.warning_time_set && elapsed_time > config.warning_time) {
346 printf("Unexpected response from host/socket on "); 427 xasprintf(&elapsed_time_result.output, "Connection time %fs exceeded warning threshold (%f)", elapsed_time, config.critical_time);
347 else 428
348 printf("%.3f second response time on ", elapsed_time); 429 elapsed_time_result = mp_set_subcheck_state(elapsed_time_result, STATE_WARNING);
349 if (server_address[0] != '/') { 430 time_pd.warn_present = true;
350 if (host_specified) 431 mp_range warn_val = mp_range_init();
351 printf("%s port %d", server_address, server_port); 432 warn_val.end = mp_create_pd_value(config.critical_time);
352 else 433 warn_val.end_infinity = false;
353 printf("port %d", server_port); 434
354 } else 435 time_pd.warn = warn_val;
355 printf("socket %s", server_address); 436 } else {
437 elapsed_time_result = mp_set_subcheck_state(elapsed_time_result, STATE_OK);
438 xasprintf(&elapsed_time_result.output, "Connection time %fs is within thresholds", elapsed_time);
356 } 439 }
357 440
358 if (match != NP_MATCH_FAILURE && !(flags & FLAG_HIDE_OUTPUT) && len) 441 mp_add_perfdata_to_subcheck(&elapsed_time_result, time_pd);
359 printf(" [%s]", status); 442 mp_add_subcheck_to_check(&overall, elapsed_time_result);
360 443
361 /* perf-data doesn't apply when server doesn't talk properly, 444 /* did we get the response we hoped? */
362 * so print all zeroes on warn and crit. Use fperfdata since 445 if (match == NP_MATCH_FAILURE) {
363 * localisation settings can make different outputs */ 446 expected_data_result = mp_set_subcheck_state(expected_data_result, config.expect_mismatch_state);
364 if (match == NP_MATCH_FAILURE) 447 xasprintf(&expected_data_result.output, "Answer failed to match expectation");
365 printf("|%s", fperfdata("time", elapsed_time, "s", (flags & FLAG_TIME_WARN ? true : false), 0, 448 mp_add_subcheck_to_check(&overall, expected_data_result);
366 (flags & FLAG_TIME_CRIT ? true : false), 0, true, 0, true, socket_timeout)); 449 }
367 else
368 printf("|%s", fperfdata("time", elapsed_time, "s", (flags & FLAG_TIME_WARN ? true : false), warning_time,
369 (flags & FLAG_TIME_CRIT ? true : false), critical_time, true, 0, true, socket_timeout));
370 450
371 putchar('\n'); 451 /* reset the alarm */
372 return result; 452 alarm(0);
453
454 mp_exit(overall);
373} 455}
374 456
375/* process command-line arguments */ 457/* process command-line arguments */
376static int process_arguments(int argc, char **argv) { 458static check_tcp_config_wrapper process_arguments(int argc, char **argv, check_tcp_config config) {
377 enum { 459 enum {
378 SNI_OPTION = CHAR_MAX + 1 460 SNI_OPTION = CHAR_MAX + 1,
461 output_format_index,
379 }; 462 };
380 463
381 static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, 464 static struct option longopts[] = {{"hostname", required_argument, 0, 'H'},
@@ -404,54 +487,47 @@ static int process_arguments(int argc, char **argv) {
404 {"ssl", no_argument, 0, 'S'}, 487 {"ssl", no_argument, 0, 'S'},
405 {"sni", required_argument, 0, SNI_OPTION}, 488 {"sni", required_argument, 0, SNI_OPTION},
406 {"certificate", required_argument, 0, 'D'}, 489 {"certificate", required_argument, 0, 'D'},
490 {"output-format", required_argument, 0, output_format_index},
407 {0, 0, 0, 0}}; 491 {0, 0, 0, 0}};
408 492
409 if (argc < 2) 493 if (argc < 2) {
410 usage4(_("No arguments found")); 494 usage4(_("No arguments found"));
411
412 /* backwards compatibility */
413 for (int i = 1; i < argc; i++) {
414 if (strcmp("-to", argv[i]) == 0)
415 strcpy(argv[i], "-t");
416 else if (strcmp("-wt", argv[i]) == 0)
417 strcpy(argv[i], "-w");
418 else if (strcmp("-ct", argv[i]) == 0)
419 strcpy(argv[i], "-c");
420 } 495 }
421 496
422 if (!is_option(argv[1])) { 497 if (!is_option(argv[1])) {
423 server_address = argv[1]; 498 config.server_address = argv[1];
424 argv[1] = argv[0]; 499 argv[1] = argv[0];
425 argv = &argv[1]; 500 argv = &argv[1];
426 argc--; 501 argc--;
427 } 502 }
428 503
429 int option_char;
430 bool escape = false; 504 bool escape = false;
505
431 while (true) { 506 while (true) {
432 int option = 0; 507 int option = 0;
433 option_char = getopt_long(argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:", longopts, &option); 508 int option_index = getopt_long(argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:", longopts, &option);
434 509
435 if (option_char == -1 || option_char == EOF || option_char == 1) 510 if (option_index == -1 || option_index == EOF || option_index == 1) {
436 break; 511 break;
512 }
437 513
438 switch (option_char) { 514 switch (option_index) {
439 case '?': /* print short usage statement if args not parsable */ 515 case '?': /* print short usage statement if args not parsable */
440 usage5(); 516 usage5();
441 case 'h': /* help */ 517 case 'h': /* help */
442 print_help(); 518 print_help(config.service);
443 exit(STATE_UNKNOWN); 519 exit(STATE_UNKNOWN);
444 case 'V': /* version */ 520 case 'V': /* version */
445 print_revision(progname, NP_VERSION); 521 print_revision(progname, NP_VERSION);
446 exit(STATE_UNKNOWN); 522 exit(STATE_UNKNOWN);
447 case 'v': /* verbose mode */ 523 case 'v': /* verbose mode */
448 flags |= FLAG_VERBOSE; 524 verbosity++;
449 match_flags |= NP_MATCH_VERBOSE; 525 config.match_flags |= NP_MATCH_VERBOSE;
450 break; 526 break;
451 case '4': 527 case '4': // Apparently unused TODO
452 address_family = AF_INET; 528 address_family = AF_INET;
453 break; 529 break;
454 case '6': 530 case '6': // Apparently unused TODO
455#ifdef USE_IPV6 531#ifdef USE_IPV6
456 address_family = AF_INET6; 532 address_family = AF_INET6;
457#else 533#else
@@ -459,163 +535,190 @@ static int process_arguments(int argc, char **argv) {
459#endif 535#endif
460 break; 536 break;
461 case 'H': /* hostname */ 537 case 'H': /* hostname */
462 host_specified = true; 538 config.host_specified = true;
463 server_address = optarg; 539 config.server_address = optarg;
464 break; 540 break;
465 case 'c': /* critical */ 541 case 'c': /* critical */
466 critical_time = strtod(optarg, NULL); 542 config.critical_time = strtod(optarg, NULL);
467 flags |= FLAG_TIME_CRIT; 543 config.critical_time_set = true;
468 break; 544 break;
469 case 'j': /* hide output */ 545 case 'j': /* hide output */
470 flags |= FLAG_HIDE_OUTPUT; 546 config.hide_output = true;
471 break; 547 break;
472 case 'w': /* warning */ 548 case 'w': /* warning */
473 warning_time = strtod(optarg, NULL); 549 config.warning_time = strtod(optarg, NULL);
474 flags |= FLAG_TIME_WARN; 550 config.warning_time_set = true;
475 break;
476 case 'C':
477 crit_codes = realloc(crit_codes, ++crit_codes_count);
478 crit_codes[crit_codes_count - 1] = optarg;
479 break;
480 case 'W':
481 warn_codes = realloc(warn_codes, ++warn_codes_count);
482 warn_codes[warn_codes_count - 1] = optarg;
483 break; 551 break;
484 case 't': /* timeout */ 552 case 't': /* timeout */
485 if (!is_intpos(optarg)) 553 if (!is_intpos(optarg)) {
486 usage4(_("Timeout interval must be a positive integer")); 554 usage4(_("Timeout interval must be a positive integer"));
487 else 555 } else {
488 socket_timeout = atoi(optarg); 556 socket_timeout = atoi(optarg);
557 }
489 break; 558 break;
490 case 'p': /* port */ 559 case 'p': /* port */
491 if (!is_intpos(optarg)) 560 if (!is_intpos(optarg)) {
492 usage4(_("Port must be a positive integer")); 561 usage4(_("Port must be a positive integer"));
493 else 562 } else {
494 server_port = atoi(optarg); 563 config.server_port = atoi(optarg);
564 }
495 break; 565 break;
496 case 'E': 566 case 'E':
497 escape = true; 567 escape = true;
498 break; 568 break;
499 case 's': 569 case 's':
500 if (escape) 570 if (escape) {
501 server_send = np_escaped_string(optarg); 571 config.send = np_escaped_string(optarg);
502 else 572 } else {
503 xasprintf(&server_send, "%s", optarg); 573 xasprintf(&config.send, "%s", optarg);
574 }
504 break; 575 break;
505 case 'e': /* expect string (may be repeated) */ 576 case 'e': /* expect string (may be repeated) */
506 match_flags &= ~NP_MATCH_EXACT; 577 config.match_flags &= ~NP_MATCH_EXACT;
507 if (server_expect_count == 0) 578 if (config.server_expect_count == 0) {
508 server_expect = malloc(sizeof(char *) * (++server_expect_count)); 579 config.server_expect = malloc(sizeof(char *) * (++config.server_expect_count));
509 else 580 } else {
510 server_expect = realloc(server_expect, sizeof(char *) * (++server_expect_count)); 581 config.server_expect = realloc(config.server_expect, sizeof(char *) * (++config.server_expect_count));
511 server_expect[server_expect_count - 1] = optarg; 582 }
583
584 if (config.server_expect == NULL) {
585 die(STATE_UNKNOWN, _("Allocation failed"));
586 }
587 config.server_expect[config.server_expect_count - 1] = optarg;
512 break; 588 break;
513 case 'm': 589 case 'm':
514 if (!is_intpos(optarg)) 590 if (!is_intpos(optarg)) {
515 usage4(_("Maxbytes must be a positive integer")); 591 usage4(_("Maxbytes must be a positive integer"));
516 else 592 } else {
517 maxbytes = strtol(optarg, NULL, 0); 593 config.maxbytes = strtol(optarg, NULL, 0);
594 }
518 break; 595 break;
519 case 'q': 596 case 'q':
520 if (escape) 597 if (escape) {
521 server_quit = np_escaped_string(optarg); 598 config.quit = np_escaped_string(optarg);
522 else 599 } else {
523 xasprintf(&server_quit, "%s\r\n", optarg); 600 xasprintf(&config.quit, "%s\r\n", optarg);
601 }
524 break; 602 break;
525 case 'r': 603 case 'r':
526 if (!strncmp(optarg, "ok", 2)) 604 if (!strncmp(optarg, "ok", 2)) {
527 econn_refuse_state = STATE_OK; 605 config.econn_refuse_state = STATE_OK;
528 else if (!strncmp(optarg, "warn", 4)) 606 } else if (!strncmp(optarg, "warn", 4)) {
529 econn_refuse_state = STATE_WARNING; 607 config.econn_refuse_state = STATE_WARNING;
530 else if (!strncmp(optarg, "crit", 4)) 608 } else if (!strncmp(optarg, "crit", 4)) {
531 econn_refuse_state = STATE_CRITICAL; 609 config.econn_refuse_state = STATE_CRITICAL;
532 else 610 } else {
533 usage4(_("Refuse must be one of ok, warn, crit")); 611 usage4(_("Refuse must be one of ok, warn, crit"));
612 }
534 break; 613 break;
535 case 'M': 614 case 'M':
536 if (!strncmp(optarg, "ok", 2)) 615 if (!strncmp(optarg, "ok", 2)) {
537 expect_mismatch_state = STATE_OK; 616 config.expect_mismatch_state = STATE_OK;
538 else if (!strncmp(optarg, "warn", 4)) 617 } else if (!strncmp(optarg, "warn", 4)) {
539 expect_mismatch_state = STATE_WARNING; 618 config.expect_mismatch_state = STATE_WARNING;
540 else if (!strncmp(optarg, "crit", 4)) 619 } else if (!strncmp(optarg, "crit", 4)) {
541 expect_mismatch_state = STATE_CRITICAL; 620 config.expect_mismatch_state = STATE_CRITICAL;
542 else 621 } else {
543 usage4(_("Mismatch must be one of ok, warn, crit")); 622 usage4(_("Mismatch must be one of ok, warn, crit"));
623 }
544 break; 624 break;
545 case 'd': 625 case 'd':
546 if (is_intpos(optarg)) 626 if (is_intpos(optarg)) {
547 delay = atoi(optarg); 627 config.delay = atoi(optarg);
548 else 628 } else {
549 usage4(_("Delay must be a positive integer")); 629 usage4(_("Delay must be a positive integer"));
630 }
550 break; 631 break;
551 case 'D': { /* Check SSL cert validity - days 'til certificate expiration */ 632 case 'D': /* Check SSL cert validity - days 'til certificate expiration */
552#ifdef HAVE_SSL 633#ifdef HAVE_SSL
553# ifdef USE_OPENSSL /* XXX */ 634# ifdef USE_OPENSSL /* XXX */
635 {
554 char *temp; 636 char *temp;
555 if ((temp = strchr(optarg, ',')) != NULL) { 637 if ((temp = strchr(optarg, ',')) != NULL) {
556 *temp = '\0'; 638 *temp = '\0';
557 if (!is_intnonneg(optarg)) 639 if (!is_intnonneg(optarg)) {
558 usage2(_("Invalid certificate expiration period"), optarg); 640 usage2(_("Invalid certificate expiration period"), optarg);
559 days_till_exp_warn = atoi(optarg); 641 }
642 config.days_till_exp_warn = atoi(optarg);
560 *temp = ','; 643 *temp = ',';
561 temp++; 644 temp++;
562 if (!is_intnonneg(temp)) 645 if (!is_intnonneg(temp)) {
563 usage2(_("Invalid certificate expiration period"), temp); 646 usage2(_("Invalid certificate expiration period"), temp);
564 days_till_exp_crit = atoi(temp); 647 }
648 config.days_till_exp_crit = atoi(temp);
565 } else { 649 } else {
566 days_till_exp_crit = 0; 650 config.days_till_exp_crit = 0;
567 if (!is_intnonneg(optarg)) 651 if (!is_intnonneg(optarg)) {
568 usage2(_("Invalid certificate expiration period"), optarg); 652 usage2(_("Invalid certificate expiration period"), optarg);
569 days_till_exp_warn = atoi(optarg); 653 }
654 config.days_till_exp_warn = atoi(optarg);
570 } 655 }
571 check_cert = true; 656 config.check_cert = true;
572 flags |= FLAG_SSL; 657 config.use_tls = true;
573 } break; 658 } break;
574# endif /* USE_OPENSSL */ 659# endif /* USE_OPENSSL */
575#endif 660#endif
576 /* fallthrough if we don't have ssl */ 661 /* fallthrough if we don't have ssl */
577 case 'S': 662 case 'S':
578#ifdef HAVE_SSL 663#ifdef HAVE_SSL
579 flags |= FLAG_SSL; 664 config.use_tls = true;
580#else 665#else
581 die(STATE_UNKNOWN, _("Invalid option - SSL is not available")); 666 die(STATE_UNKNOWN, _("Invalid option - SSL is not available"));
582#endif 667#endif
583 break; 668 break;
584 case SNI_OPTION: 669 case SNI_OPTION:
585#ifdef HAVE_SSL 670#ifdef HAVE_SSL
586 flags |= FLAG_SSL; 671 config.use_tls = true;
587 sni_specified = true; 672 config.sni_specified = true;
588 sni = optarg; 673 config.sni = optarg;
589#else 674#else
590 die(STATE_UNKNOWN, _("Invalid option - SSL is not available")); 675 die(STATE_UNKNOWN, _("Invalid option - SSL is not available"));
591#endif 676#endif
592 break; 677 break;
593 case 'A': 678 case 'A':
594 match_flags |= NP_MATCH_ALL; 679 config.match_flags |= NP_MATCH_ALL;
680 break;
681 case output_format_index: {
682 parsed_output_format parser = mp_parse_output_format(optarg);
683 if (!parser.parsing_success) {
684 // TODO List all available formats here, maybe add anothoer usage function
685 printf("Invalid output format: %s\n", optarg);
686 exit(STATE_UNKNOWN);
687 }
688
689 config.output_format_set = true;
690 config.output_format = parser.output_format;
595 break; 691 break;
596 } 692 }
693 }
597 } 694 }
598 695
599 option_char = optind; 696 int index = optind;
600 if (!host_specified && option_char < argc) 697 if (!config.host_specified && index < argc) {
601 server_address = strdup(argv[option_char++]); 698 config.server_address = strdup(argv[index++]);
699 }
602 700
603 if (server_address == NULL) 701 if (config.server_address == NULL) {
604 usage4(_("You must provide a server address")); 702 usage4(_("You must provide a server address"));
605 else if (server_address[0] != '/' && !is_host(server_address)) 703 } else if (config.server_address[0] != '/' && !is_host(config.server_address)) {
606 die(STATE_CRITICAL, "%s %s - %s: %s\n", SERVICE, state_text(STATE_CRITICAL), _("Invalid hostname, address or socket"), 704 die(STATE_CRITICAL, "%s %s - %s: %s\n", config.service, state_text(STATE_CRITICAL), _("Invalid hostname, address or socket"),
607 server_address); 705 config.server_address);
706 }
608 707
609 return OK; 708 check_tcp_config_wrapper result = {
709 .config = config,
710 .errorcode = OK,
711 };
712 return result;
610} 713}
611 714
612void print_help(void) { 715void print_help(const char *service) {
613 print_revision(progname, NP_VERSION); 716 print_revision(progname, NP_VERSION);
614 717
615 printf("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n"); 718 printf("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
616 printf(COPYRIGHT, copyright, email); 719 printf(COPYRIGHT, copyright, email);
617 720
618 printf(_("This plugin tests %s connections with the specified host (or unix socket).\n\n"), SERVICE); 721 printf(_("This plugin tests %s connections with the specified host (or unix socket).\n\n"), service);
619 722
620 print_usage(); 723 print_usage();
621 724
@@ -662,6 +765,7 @@ void print_help(void) {
662 765
663 printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); 766 printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
664 767
768 printf(UT_OUTPUT_FORMAT);
665 printf(UT_VERBOSE); 769 printf(UT_VERBOSE);
666 770
667 printf(UT_SUPPORT); 771 printf(UT_SUPPORT);