1 /*****************************************************************************
2 *
3 * Nagios check_tcp plugin
4 *
5 * License: GPL
6 * Copyright (c) 1999-2006 nagios-plugins team
7 *
8 * Last Modified: $Date$
9 *
10 * Description:
11 *
12 * This file contains the check_tcp plugin
13 *
14 * License Information:
15 *
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation; either version 2 of the License, or
19 * (at your option) any later version.
20 *
21 * This program is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 * GNU General Public License for more details.
25 *
26 * You should have received a copy of the GNU General Public License
27 * along with this program; if not, write to the Free Software
28 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 *
30 * $Id$
31 *
32 *****************************************************************************/
34 /* progname "check_tcp" changes depending on symlink called */
35 char *progname;
36 const char *revision = "$Revision$";
37 const char *copyright = "1999-2006";
38 const char *email = "nagiosplug-devel@lists.sourceforge.net";
40 #include "common.h"
41 #include "netutils.h"
42 #include "utils.h"
44 #ifdef HAVE_SSL
45 static int check_cert = FALSE;
46 static int days_till_exp;
47 # define my_recv(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_read(buf, len) : read(sd, buf, len))
48 # define my_send(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0))
49 #else
50 # define my_recv(buf, len) read(sd, buf, len)
51 # define my_send(buf, len) send(sd, buf, len, 0)
52 #endif
54 /* int my_recv(char *, size_t); */
55 static int process_arguments (int, char **);
56 void print_help (void);
57 void print_usage (void);
59 #define EXPECT server_expect[0]
60 static char *SERVICE = "TCP";
61 static char *SEND = NULL;
62 static char *QUIT = NULL;
63 static int PROTOCOL = IPPROTO_TCP; /* most common is default */
64 static int PORT = 0;
66 static int server_port = 0;
67 static char *server_address = NULL;
68 static char *server_send = NULL;
69 static char *server_quit = NULL;
70 static char **server_expect;
71 static size_t server_expect_count = 0;
72 static size_t maxbytes = 0;
73 static char **warn_codes = NULL;
74 static size_t warn_codes_count = 0;
75 static char **crit_codes = NULL;
76 static size_t crit_codes_count = 0;
77 static unsigned int delay = 0;
78 static double warning_time = 0;
79 static double critical_time = 0;
80 static double elapsed_time = 0;
81 static long microsec;
82 static int sd = 0;
83 #define MAXBUF 1024
84 static char buffer[MAXBUF];
85 static int expect_mismatch_state = STATE_WARNING;
87 #define FLAG_SSL 0x01
88 #define FLAG_VERBOSE 0x02
89 #define FLAG_EXACT_MATCH 0x04
90 #define FLAG_TIME_WARN 0x08
91 #define FLAG_TIME_CRIT 0x10
92 #define FLAG_HIDE_OUTPUT 0x20
93 static size_t flags = FLAG_EXACT_MATCH;
95 int
96 main (int argc, char **argv)
97 {
98 int result = STATE_UNKNOWN;
99 int i;
100 char *status = NULL;
101 struct timeval tv;
102 size_t len, match = -1;
104 setlocale (LC_ALL, "");
105 bindtextdomain (PACKAGE, LOCALEDIR);
106 textdomain (PACKAGE);
108 /* determine program- and service-name quickly */
109 progname = strrchr(argv[0], '/');
110 if(progname != NULL) progname++;
111 else progname = argv[0];
113 len = strlen(progname);
114 if(len > 6 && !memcmp(progname, "check_", 6)) {
115 SERVICE = progname + 6;
116 for(i = 0; i < len - 6; i++)
117 SERVICE[i] = toupper(SERVICE[i]);
118 }
120 /* set up a resonable buffer at first (will be realloc()'ed if
121 * user specifies other options) */
122 server_expect = calloc(sizeof(char *), 2);
124 /* determine defaults for this service's protocol */
125 if (!strncmp(SERVICE, "UDP", 3)) {
126 PROTOCOL = IPPROTO_UDP;
127 }
128 else if (!strncmp(SERVICE, "FTP", 3)) {
129 EXPECT = "220";
130 QUIT = "QUIT\r\n";
131 PORT = 21;
132 }
133 else if (!strncmp(SERVICE, "POP", 3) || !strncmp(SERVICE, "POP3", 4)) {
134 EXPECT = "+OK";
135 QUIT = "QUIT\r\n";
136 PORT = 110;
137 }
138 else if (!strncmp(SERVICE, "SMTP", 4)) {
139 EXPECT = "220";
140 QUIT = "QUIT\r\n";
141 PORT = 25;
142 }
143 else if (!strncmp(SERVICE, "IMAP", 4)) {
144 EXPECT = "* OK";
145 QUIT = "a1 LOGOUT\r\n";
146 PORT = 143;
147 }
148 #ifdef HAVE_SSL
149 else if (!strncmp(SERVICE, "SIMAP", 5)) {
150 EXPECT = "* OK";
151 QUIT = "a1 LOGOUT\r\n";
152 flags |= FLAG_SSL;
153 PORT = 993;
154 }
155 else if (!strncmp(SERVICE, "SPOP", 4)) {
156 EXPECT = "+OK";
157 QUIT = "QUIT\r\n";
158 flags |= FLAG_SSL;
159 PORT = 995;
160 }
161 else if (!strncmp(SERVICE, "SSMTP", 5)) {
162 EXPECT = "220";
163 QUIT = "QUIT\r\n";
164 flags |= FLAG_SSL;
165 PORT = 465;
166 }
167 else if (!strncmp(SERVICE, "JABBER", 6)) {
168 SEND = "<stream:stream to=\'host\' xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'>\n";
169 EXPECT = "<?xml version=\'1.0\'?><stream:stream xmlns:stream=\'http://etherx.jabber.org/streams\'";
170 QUIT = "</stream:stream>\n";
171 flags |= FLAG_SSL | FLAG_HIDE_OUTPUT;
172 PORT = 5222;
173 }
174 else if (!strncmp (SERVICE, "NNTPS", 5)) {
175 server_expect_count = 2;
176 server_expect[0] = "200";
177 server_expect[1] = "201";
178 QUIT = "QUIT\r\n";
179 flags |= FLAG_SSL;
180 PORT = 563;
181 }
182 #endif
183 else if (!strncmp (SERVICE, "NNTP", 4)) {
184 server_expect_count = 2;
185 server_expect = malloc(sizeof(char *) * server_expect_count);
186 server_expect[0] = strdup("200");
187 server_expect[1] = strdup("201");
188 QUIT = "QUIT\r\n";
189 PORT = 119;
190 }
191 else if (!strncmp(SERVICE, "CLAMD", 5)) {
192 SEND = "PING";
193 EXPECT = "PONG";
194 QUIT = NULL;
195 PORT = 3310;
196 }
197 /* fallthrough check, so it's supposed to use reverse matching */
198 else if (strcmp (SERVICE, "TCP"))
199 usage (_("CRITICAL - Generic check_tcp called with unknown service\n"));
201 server_address = "127.0.0.1";
202 server_port = PORT;
203 server_send = SEND;
204 server_quit = QUIT;
205 status = NULL;
207 if (process_arguments (argc, argv) == ERROR)
208 usage4 (_("Could not parse arguments"));
210 if(flags & FLAG_VERBOSE) {
211 printf("Using service %s\n", SERVICE);
212 printf("Port: %d\n", server_port);
213 printf("flags: 0x%x\n", (int)flags);
214 }
216 if(EXPECT && !server_expect_count)
217 server_expect_count++;
219 if(PROTOCOL==IPPROTO_UDP && !(server_expect_count && server_send)){
220 usage(_("With UDP checks, a send/expect string must be specified."));
221 }
223 /* set up the timer */
224 signal (SIGALRM, socket_timeout_alarm_handler);
225 alarm (socket_timeout);
227 /* try to connect to the host at the given port number */
228 gettimeofday (&tv, NULL);
230 result = np_net_connect (server_address, server_port, &sd, PROTOCOL);
231 if (result == STATE_CRITICAL) return STATE_CRITICAL;
233 #ifdef HAVE_SSL
234 if (flags & FLAG_SSL){
235 result = np_net_ssl_init(sd);
236 if (result == STATE_OK && check_cert == TRUE) {
237 result = np_net_ssl_check_cert(days_till_exp);
238 if(result != STATE_OK) {
239 printf(_("CRITICAL - Cannot retrieve server certificate.\n"));
240 }
241 }
242 }
243 if(result != STATE_OK){
244 np_net_ssl_cleanup();
245 if(sd) close(sd);
246 return result;
247 }
248 #endif /* HAVE_SSL */
250 if (server_send != NULL) { /* Something to send? */
251 my_send(server_send, strlen(server_send));
252 }
254 if (delay > 0) {
255 tv.tv_sec += delay;
256 sleep (delay);
257 }
259 if(flags & FLAG_VERBOSE) {
260 if (server_send) {
261 printf("Send string: %s\n", server_send);
262 }
263 if (server_quit) {
264 printf("Quit string: %s\n", server_quit);
265 }
266 printf("server_expect_count: %d\n", (int)server_expect_count);
267 for(i = 0; i < server_expect_count; i++)
268 printf("\t%d: %s\n", i, server_expect[i]);
269 }
271 /* if(len) later on, we know we have a non-NULL response */
272 len = 0;
273 if (server_expect_count) {
275 /* watch for the expect string */
276 while ((i = my_recv(buffer, sizeof(buffer))) > 0) {
277 status = realloc(status, len + i + 1);
278 memcpy(&status[len], buffer, i);
279 len += i;
281 /* stop reading if user-forced or data-starved */
282 if(i < sizeof(buffer) || (maxbytes && len >= maxbytes))
283 break;
285 if (maxbytes && len >= maxbytes)
286 break;
287 }
289 /* no data when expected, so return critical */
290 if (len == 0)
291 die (STATE_CRITICAL, _("No data received from host\n"));
293 /* force null-termination and strip whitespace from end of output */
294 status[len--] = '\0';
295 /* print raw output if we're debugging */
296 if(flags & FLAG_VERBOSE)
297 printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n",
298 (int)len + 1, status);
299 while(isspace(status[len])) status[len--] = '\0';
301 for (i = 0; i < server_expect_count; i++) {
302 match = -2; /* tag it so we know if we tried and failed */
303 if (flags & FLAG_VERBOSE)
304 printf ("looking for [%s] %s [%s]\n", server_expect[i],
305 (flags & FLAG_EXACT_MATCH) ? "in beginning of" : "anywhere in",
306 status);
308 /* match it. math first in short-circuit */
309 if ((flags & FLAG_EXACT_MATCH && !strncmp(status, server_expect[i], strlen(server_expect[i]))) ||
310 (!(flags & FLAG_EXACT_MATCH) && strstr(status, server_expect[i])))
311 {
312 if(flags & FLAG_VERBOSE) puts("found it");
313 match = i;
314 break;
315 }
316 }
317 }
319 if (server_quit != NULL) {
320 my_send(server_quit, strlen(server_quit));
321 }
322 #ifdef HAVE_SSL
323 np_net_ssl_cleanup();
324 #endif
325 if (sd) close (sd);
327 microsec = deltime (tv);
328 elapsed_time = (double)microsec / 1.0e6;
330 if (flags & FLAG_TIME_CRIT && elapsed_time > critical_time)
331 result = STATE_CRITICAL;
332 else if (flags & FLAG_TIME_WARN && elapsed_time > warning_time)
333 result = STATE_WARNING;
335 /* did we get the response we hoped? */
336 if(match == -2 && result != STATE_CRITICAL)
337 result = expect_mismatch_state;
339 /* reset the alarm */
340 alarm (0);
342 /* this is a bit stupid, because we don't want to print the
343 * response time (which can look ok to the user) if we didn't get
344 * the response we were looking for. if-else */
345 printf(_("%s %s - "), SERVICE, state_text(result));
347 if(match == -2 && len && !(flags & FLAG_HIDE_OUTPUT))
348 printf("Unexpected response from host/socket: %s", status);
349 else {
350 printf("%.3f second response time on ", elapsed_time);
351 if(server_address[0] != '/')
352 printf("port %d", server_port);
353 else
354 printf("socket %s", server_address);
355 }
357 if (match != -2 && !(flags & FLAG_HIDE_OUTPUT) && len)
358 printf (" [%s]", status);
360 /* perf-data doesn't apply when server doesn't talk properly,
361 * so print all zeroes on warn and crit */
362 if(match == -2)
363 printf ("|time=%fs;0.0;0.0;0.0;0.0", elapsed_time);
364 else
365 printf("|%s",
366 fperfdata ("time", elapsed_time, "s",
367 TRUE, warning_time,
368 TRUE, critical_time,
369 TRUE, 0,
370 TRUE, socket_timeout)
371 );
373 putchar('\n');
374 return result;
375 }
379 /* process command-line arguments */
380 static int
381 process_arguments (int argc, char **argv)
382 {
383 int c;
384 int escape = 0;
386 int option = 0;
387 static struct option longopts[] = {
388 {"hostname", required_argument, 0, 'H'},
389 {"critical", required_argument, 0, 'c'},
390 {"warning", required_argument, 0, 'w'},
391 {"critical-codes", required_argument, 0, 'C'},
392 {"warning-codes", required_argument, 0, 'W'},
393 {"timeout", required_argument, 0, 't'},
394 {"protocol", required_argument, 0, 'P'},
395 {"port", required_argument, 0, 'p'},
396 {"escape", required_argument, 0, 'E'},
397 {"send", required_argument, 0, 's'},
398 {"expect", required_argument, 0, 'e'},
399 {"maxbytes", required_argument, 0, 'm'},
400 {"quit", required_argument, 0, 'q'},
401 {"jail", required_argument, 0, 'j'},
402 {"delay", required_argument, 0, 'd'},
403 {"refuse", required_argument, 0, 'r'},
404 {"mismatch", required_argument, 0, 'M'},
405 {"use-ipv4", no_argument, 0, '4'},
406 {"use-ipv6", no_argument, 0, '6'},
407 {"verbose", no_argument, 0, 'v'},
408 {"version", no_argument, 0, 'V'},
409 {"help", no_argument, 0, 'h'},
410 #ifdef HAVE_SSL
411 {"ssl", no_argument, 0, 'S'},
412 {"certificate", required_argument, 0, 'D'},
413 #endif
414 {0, 0, 0, 0}
415 };
417 if (argc < 2)
418 usage4 (_("No arguments found"));
420 /* backwards compatibility */
421 for (c = 1; c < argc; c++) {
422 if (strcmp ("-to", argv[c]) == 0)
423 strcpy (argv[c], "-t");
424 else if (strcmp ("-wt", argv[c]) == 0)
425 strcpy (argv[c], "-w");
426 else if (strcmp ("-ct", argv[c]) == 0)
427 strcpy (argv[c], "-c");
428 }
430 if (!is_option (argv[1])) {
431 server_address = argv[1];
432 argv[1] = argv[0];
433 argv = &argv[1];
434 argc--;
435 }
437 while (1) {
438 c = getopt_long (argc, argv, "+hVv46EH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:",
439 longopts, &option);
441 if (c == -1 || c == EOF || c == 1)
442 break;
444 switch (c) {
445 case '?': /* print short usage statement if args not parsable */
446 usage2 (_("Unknown argument"), optarg);
447 case 'h': /* help */
448 print_help ();
449 exit (STATE_OK);
450 case 'V': /* version */
451 print_revision (progname, revision);
452 exit (STATE_OK);
453 case 'v': /* verbose mode */
454 flags |= FLAG_VERBOSE;
455 break;
456 case '4':
457 address_family = AF_INET;
458 break;
459 case '6':
460 #ifdef USE_IPV6
461 address_family = AF_INET6;
462 #else
463 usage4 (_("IPv6 support not available"));
464 #endif
465 break;
466 case 'H': /* hostname */
467 server_address = optarg;
468 break;
469 case 'c': /* critical */
470 critical_time = strtod (optarg, NULL);
471 flags |= FLAG_TIME_CRIT;
472 break;
473 case 'j': /* hide output */
474 flags |= FLAG_HIDE_OUTPUT;
475 break;
476 case 'w': /* warning */
477 warning_time = strtod (optarg, NULL);
478 flags |= FLAG_TIME_WARN;
479 break;
480 case 'C':
481 crit_codes = realloc (crit_codes, ++crit_codes_count);
482 crit_codes[crit_codes_count - 1] = optarg;
483 break;
484 case 'W':
485 warn_codes = realloc (warn_codes, ++warn_codes_count);
486 warn_codes[warn_codes_count - 1] = optarg;
487 break;
488 case 't': /* timeout */
489 if (!is_intpos (optarg))
490 usage4 (_("Timeout interval must be a positive integer"));
491 else
492 socket_timeout = atoi (optarg);
493 break;
494 case 'p': /* port */
495 if (!is_intpos (optarg))
496 usage4 (_("Port must be a positive integer"));
497 else
498 server_port = atoi (optarg);
499 break;
500 case 'E':
501 escape = 1;
502 break;
503 case 's':
504 if (escape)
505 server_send = np_escaped_string(optarg);
506 else
507 asprintf(&server_send, "%s", optarg);
508 break;
509 case 'e': /* expect string (may be repeated) */
510 EXPECT = NULL;
511 flags &= ~FLAG_EXACT_MATCH;
512 if (server_expect_count == 0)
513 server_expect = malloc (sizeof (char *) * (++server_expect_count));
514 else
515 server_expect = realloc (server_expect, sizeof (char *) * (++server_expect_count));
516 server_expect[server_expect_count - 1] = optarg;
517 break;
518 case 'm':
519 if (!is_intpos (optarg))
520 usage4 (_("Maxbytes must be a positive integer"));
521 else
522 maxbytes = strtol (optarg, NULL, 0);
523 case 'q':
524 if (escape)
525 server_quit = np_escaped_string(optarg);
526 else
527 asprintf(&server_quit, "%s\r\n", optarg);
528 break;
529 case 'r':
530 if (!strncmp(optarg,"ok",2))
531 econn_refuse_state = STATE_OK;
532 else if (!strncmp(optarg,"warn",4))
533 econn_refuse_state = STATE_WARNING;
534 else if (!strncmp(optarg,"crit",4))
535 econn_refuse_state = STATE_CRITICAL;
536 else
537 usage4 (_("Refuse must be one of ok, warn, crit"));
538 break;
539 case 'M':
540 if (!strncmp(optarg,"ok",2))
541 expect_mismatch_state = STATE_OK;
542 else if (!strncmp(optarg,"warn",4))
543 expect_mismatch_state = STATE_WARNING;
544 else if (!strncmp(optarg,"crit",4))
545 expect_mismatch_state = STATE_CRITICAL;
546 else
547 usage4 (_("Mismatch must be one of ok, warn, crit"));
548 break;
549 case 'd':
550 if (is_intpos (optarg))
551 delay = atoi (optarg);
552 else
553 usage4 (_("Delay must be a positive integer"));
554 break;
555 case 'D': /* Check SSL cert validity - days 'til certificate expiration */
556 #ifdef HAVE_SSL
557 # ifdef USE_OPENSSL /* XXX */
558 if (!is_intnonneg (optarg))
559 usage2 (_("Invalid certificate expiration period"), optarg);
560 days_till_exp = atoi (optarg);
561 check_cert = TRUE;
562 flags |= FLAG_SSL;
563 break;
564 # endif /* USE_OPENSSL */
565 #endif
566 /* fallthrough if we don't have ssl */
567 case 'S':
568 #ifdef HAVE_SSL
569 flags |= FLAG_SSL;
570 #else
571 die (STATE_UNKNOWN, _("Invalid option - SSL is not available"));
572 #endif
573 break;
574 }
575 }
577 if (server_address == NULL)
578 usage4 (_("You must provide a server address"));
579 else if (server_address[0] != '/' && is_host (server_address) == FALSE)
580 die (STATE_CRITICAL, "%s: %s - %s\n", progname, _("Invalid hostname, address or socket"), server_address);
582 return TRUE;
583 }
586 void
587 print_help (void)
588 {
589 print_revision (progname, revision);
591 printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
592 printf (COPYRIGHT, copyright, email);
594 printf (_("This plugin tests %s connections with the specified host (or unix socket).\n\n"),
595 SERVICE);
597 print_usage ();
599 printf (_(UT_HELP_VRSN));
601 printf (_(UT_HOST_PORT), 'p', "none");
603 printf (_(UT_IPv46));
605 printf (" %s\n", "-E, --escape");
606 printf (" %s\n", _("Can use \\n, \\r, \\t or \\ in send or quit string."));
607 printf (" %s\n", _("Default: nothing added to send, \\r\\n added to end of quit"));
608 printf (" %s\n", "-s, --send=STRING");
609 printf (" %s\n", _("String to send to the server"));
610 printf (" %s\n", "-e, --expect=STRING");
611 printf (" %s\n", _("String to expect in server response"));
612 printf (" %s\n", "-q, --quit=STRING");
613 printf (" %s\n", _("String to send server to initiate a clean close of the connection"));
614 printf (" %s\n", "-r, --refuse=ok|warn|crit");
615 printf (" %s\n", _("Accept tcp refusals with states ok, warn, crit (default: crit)"));
616 printf (" %s\n", "-M, --mismatch=ok|warn|crit");
617 printf (" %s\n", _("Accept expected string mismatches with states ok, warn, crit (default: warn)"));
618 printf (" %s\n", "-j, --jail");
619 printf (" %s\n", _("Hide output from TCP socket"));
620 printf (" %s\n", "-m, --maxbytes=INTEGER");
621 printf (" %s\n", _("Close connection once more than this number of bytes are received"));
622 printf (" %s\n", "-d, --delay=INTEGER");
623 printf (" %s\n", _("Seconds to wait between sending string and polling for response"));
625 #ifdef HAVE_SSL
626 printf (" %s\n", "-D, --certificate=INTEGER");
627 printf (" %s\n", _("Minimum number of days a certificate has to be valid."));
628 printf (" %s\n", "-S, --ssl");
629 printf (" %s\n", _("Use SSL for the connection."));
630 #endif
632 printf (_(UT_WARN_CRIT));
634 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
636 printf (_(UT_VERBOSE));
638 printf (_(UT_SUPPORT));
639 }
642 void
643 print_usage (void)
644 {
645 printf (_("Usage:"));
646 printf ("%s -H host -p port [-w <warning time>] [-c <critical time>] [-s <send string>]\n",progname);
647 printf ("[-e <expect string>] [-q <quit string>][-m <maximum bytes>] [-d <delay>]\n");
648 printf ("[-t <timeout seconds>] [-r <refuse state>] [-M <mismatch state>] [-v] [-4|-6] [-j]\n");
649 printf ("[-D <days to cert expiry>] [-S <use SSL>] [-E]\n");
650 }