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"
43 #include "utils_tcp.h"
45 #ifdef HAVE_SSL
46 static int check_cert = FALSE;
47 static int days_till_exp;
48 # define my_recv(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_read(buf, len) : read(sd, buf, len))
49 # define my_send(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0))
50 #else
51 # define my_recv(buf, len) read(sd, buf, len)
52 # define my_send(buf, len) send(sd, buf, len, 0)
53 #endif
55 /* int my_recv(char *, size_t); */
56 static int process_arguments (int, char **);
57 void print_help (void);
58 void print_usage (void);
60 #define EXPECT server_expect[0]
61 static char *SERVICE = "TCP";
62 static char *SEND = NULL;
63 static char *QUIT = NULL;
64 static int PROTOCOL = IPPROTO_TCP; /* most common is default */
65 static int PORT = 0;
67 static int server_port = 0;
68 static char *server_address = NULL;
69 static char *server_send = NULL;
70 static char *server_quit = NULL;
71 static char **server_expect;
72 static size_t server_expect_count = 0;
73 static size_t maxbytes = 0;
74 static char **warn_codes = NULL;
75 static size_t warn_codes_count = 0;
76 static char **crit_codes = NULL;
77 static size_t crit_codes_count = 0;
78 static unsigned int delay = 0;
79 static double warning_time = 0;
80 static double critical_time = 0;
81 static double elapsed_time = 0;
82 static long microsec;
83 static int sd = 0;
84 #define MAXBUF 1024
85 static char buffer[MAXBUF];
86 static int expect_mismatch_state = STATE_WARNING;
88 #define FLAG_SSL 0x01
89 #define FLAG_VERBOSE 0x02
90 #define FLAG_EXACT_MATCH 0x04
91 #define FLAG_TIME_WARN 0x08
92 #define FLAG_TIME_CRIT 0x10
93 #define FLAG_HIDE_OUTPUT 0x20
94 #define FLAG_MATCH_ALL 0x40
95 static size_t flags = FLAG_EXACT_MATCH;
97 int
98 main (int argc, char **argv)
99 {
100 int result = STATE_UNKNOWN;
101 int i;
102 char *status = NULL;
103 struct timeval tv;
104 size_t len;
105 int match = -1;
107 setlocale (LC_ALL, "");
108 bindtextdomain (PACKAGE, LOCALEDIR);
109 textdomain (PACKAGE);
111 /* determine program- and service-name quickly */
112 progname = strrchr(argv[0], '/');
113 if(progname != NULL) progname++;
114 else progname = argv[0];
116 len = strlen(progname);
117 if(len > 6 && !memcmp(progname, "check_", 6)) {
118 SERVICE = strdup(progname + 6);
119 for(i = 0; i < len - 6; i++)
120 SERVICE[i] = toupper(SERVICE[i]);
121 }
123 /* set up a resonable buffer at first (will be realloc()'ed if
124 * user specifies other options) */
125 server_expect = calloc(sizeof(char *), 2);
127 /* determine defaults for this service's protocol */
128 if (!strncmp(SERVICE, "UDP", 3)) {
129 PROTOCOL = IPPROTO_UDP;
130 }
131 else if (!strncmp(SERVICE, "FTP", 3)) {
132 EXPECT = "220";
133 QUIT = "QUIT\r\n";
134 PORT = 21;
135 }
136 else if (!strncmp(SERVICE, "POP", 3) || !strncmp(SERVICE, "POP3", 4)) {
137 EXPECT = "+OK";
138 QUIT = "QUIT\r\n";
139 PORT = 110;
140 }
141 else if (!strncmp(SERVICE, "SMTP", 4)) {
142 EXPECT = "220";
143 QUIT = "QUIT\r\n";
144 PORT = 25;
145 }
146 else if (!strncmp(SERVICE, "IMAP", 4)) {
147 EXPECT = "* OK";
148 QUIT = "a1 LOGOUT\r\n";
149 PORT = 143;
150 }
151 #ifdef HAVE_SSL
152 else if (!strncmp(SERVICE, "SIMAP", 5)) {
153 EXPECT = "* OK";
154 QUIT = "a1 LOGOUT\r\n";
155 flags |= FLAG_SSL;
156 PORT = 993;
157 }
158 else if (!strncmp(SERVICE, "SPOP", 4)) {
159 EXPECT = "+OK";
160 QUIT = "QUIT\r\n";
161 flags |= FLAG_SSL;
162 PORT = 995;
163 }
164 else if (!strncmp(SERVICE, "SSMTP", 5)) {
165 EXPECT = "220";
166 QUIT = "QUIT\r\n";
167 flags |= FLAG_SSL;
168 PORT = 465;
169 }
170 else if (!strncmp(SERVICE, "JABBER", 6)) {
171 SEND = "<stream:stream to=\'host\' xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'>\n";
172 EXPECT = "<?xml version=\'1.0\'?><stream:stream xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'";
173 QUIT = "</stream:stream>\n";
174 flags |= FLAG_HIDE_OUTPUT;
175 PORT = 5222;
176 }
177 else if (!strncmp (SERVICE, "NNTPS", 5)) {
178 server_expect_count = 2;
179 server_expect[0] = "200";
180 server_expect[1] = "201";
181 QUIT = "QUIT\r\n";
182 flags |= FLAG_SSL;
183 PORT = 563;
184 }
185 #endif
186 else if (!strncmp (SERVICE, "NNTP", 4)) {
187 server_expect_count = 2;
188 server_expect = malloc(sizeof(char *) * server_expect_count);
189 server_expect[0] = strdup("200");
190 server_expect[1] = strdup("201");
191 QUIT = "QUIT\r\n";
192 PORT = 119;
193 }
194 else if (!strncmp(SERVICE, "CLAMD", 5)) {
195 SEND = "PING";
196 EXPECT = "PONG";
197 QUIT = NULL;
198 PORT = 3310;
199 }
200 /* fallthrough check, so it's supposed to use reverse matching */
201 else if (strcmp (SERVICE, "TCP"))
202 usage (_("CRITICAL - Generic check_tcp called with unknown service\n"));
204 server_address = "127.0.0.1";
205 server_port = PORT;
206 server_send = SEND;
207 server_quit = QUIT;
208 status = NULL;
210 if (process_arguments (argc, argv) == ERROR)
211 usage4 (_("Could not parse arguments"));
213 if(flags & FLAG_VERBOSE) {
214 printf("Using service %s\n", SERVICE);
215 printf("Port: %d\n", server_port);
216 printf("flags: 0x%x\n", (int)flags);
217 }
219 if(EXPECT && !server_expect_count)
220 server_expect_count++;
222 if(PROTOCOL==IPPROTO_UDP && !(server_expect_count && server_send)){
223 usage(_("With UDP checks, a send/expect string must be specified."));
224 }
226 /* set up the timer */
227 signal (SIGALRM, socket_timeout_alarm_handler);
228 alarm (socket_timeout);
230 /* try to connect to the host at the given port number */
231 gettimeofday (&tv, NULL);
233 result = np_net_connect (server_address, server_port, &sd, PROTOCOL);
234 if (result == STATE_CRITICAL) return STATE_CRITICAL;
236 #ifdef HAVE_SSL
237 if (flags & FLAG_SSL){
238 result = np_net_ssl_init(sd);
239 if (result == STATE_OK && check_cert == TRUE) {
240 result = np_net_ssl_check_cert(days_till_exp);
241 if(result != STATE_OK) {
242 printf(_("CRITICAL - Cannot retrieve server certificate.\n"));
243 }
244 }
245 }
246 if(result != STATE_OK){
247 np_net_ssl_cleanup();
248 if(sd) close(sd);
249 return result;
250 }
251 #endif /* HAVE_SSL */
253 if (server_send != NULL) { /* Something to send? */
254 my_send(server_send, strlen(server_send));
255 }
257 if (delay > 0) {
258 tv.tv_sec += delay;
259 sleep (delay);
260 }
262 if(flags & FLAG_VERBOSE) {
263 if (server_send) {
264 printf("Send string: %s\n", server_send);
265 }
266 if (server_quit) {
267 printf("Quit string: %s\n", server_quit);
268 }
269 printf("server_expect_count: %d\n", (int)server_expect_count);
270 for(i = 0; i < server_expect_count; i++)
271 printf("\t%d: %s\n", i, server_expect[i]);
272 }
274 /* if(len) later on, we know we have a non-NULL response */
275 len = 0;
276 if (server_expect_count) {
278 /* watch for the expect string */
279 while ((i = my_recv(buffer, sizeof(buffer))) > 0) {
280 status = realloc(status, len + i + 1);
281 memcpy(&status[len], buffer, i);
282 len += i;
284 /* stop reading if user-forced or data-starved */
285 if(i < sizeof(buffer) || (maxbytes && len >= maxbytes))
286 break;
288 if (maxbytes && len >= maxbytes)
289 break;
290 }
292 /* no data when expected, so return critical */
293 if (len == 0)
294 die (STATE_CRITICAL, _("No data received from host\n"));
296 /* force null-termination and strip whitespace from end of output */
297 status[len--] = '\0';
298 /* print raw output if we're debugging */
299 if(flags & FLAG_VERBOSE)
300 printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n",
301 (int)len + 1, status);
302 while(isspace(status[len])) status[len--] = '\0';
304 match = np_expect_match(status,
305 server_expect,
306 server_expect_count,
307 (flags & FLAG_MATCH_ALL ? TRUE : FALSE),
308 (flags & FLAG_EXACT_MATCH ? TRUE : FALSE),
309 (flags & FLAG_VERBOSE ? TRUE : FALSE));
310 }
312 if (server_quit != NULL) {
313 my_send(server_quit, strlen(server_quit));
314 }
315 #ifdef HAVE_SSL
316 np_net_ssl_cleanup();
317 #endif
318 if (sd) close (sd);
320 microsec = deltime (tv);
321 elapsed_time = (double)microsec / 1.0e6;
323 if (flags & FLAG_TIME_CRIT && elapsed_time > critical_time)
324 result = STATE_CRITICAL;
325 else if (flags & FLAG_TIME_WARN && elapsed_time > warning_time)
326 result = STATE_WARNING;
328 /* did we get the response we hoped? */
329 if(match == FALSE && result != STATE_CRITICAL)
330 result = expect_mismatch_state;
332 /* reset the alarm */
333 alarm (0);
335 /* this is a bit stupid, because we don't want to print the
336 * response time (which can look ok to the user) if we didn't get
337 * the response we were looking for. if-else */
338 printf("%s %s - ", SERVICE, state_text(result));
340 if(match == FALSE && len && !(flags & FLAG_HIDE_OUTPUT))
341 printf("Unexpected response from host/socket: %s", status);
342 else {
343 if(match == FALSE)
344 printf("Unexpected response from host/socket on ");
345 else
346 printf("%.3f second response time on ", elapsed_time);
347 if(server_address[0] != '/')
348 printf("port %d", server_port);
349 else
350 printf("socket %s", server_address);
351 }
353 if (match != FALSE && !(flags & FLAG_HIDE_OUTPUT) && len)
354 printf (" [%s]", status);
356 /* perf-data doesn't apply when server doesn't talk properly,
357 * so print all zeroes on warn and crit. Use fperfdata since
358 * localisation settings can make different outputs */
359 if(match == FALSE)
360 printf ("|%s",
361 fperfdata ("time", elapsed_time, "s",
362 (flags & FLAG_TIME_WARN ? TRUE : FALSE), 0,
363 (flags & FLAG_TIME_CRIT ? TRUE : FALSE), 0,
364 TRUE, 0,
365 TRUE, socket_timeout)
366 );
367 else
368 printf("|%s",
369 fperfdata ("time", elapsed_time, "s",
370 (flags & FLAG_TIME_WARN ? TRUE : FALSE), warning_time,
371 (flags & FLAG_TIME_CRIT ? TRUE : FALSE), critical_time,
372 TRUE, 0,
373 TRUE, socket_timeout)
374 );
376 putchar('\n');
377 return result;
378 }
382 /* process command-line arguments */
383 static int
384 process_arguments (int argc, char **argv)
385 {
386 int c;
387 int escape = 0;
389 int option = 0;
390 static struct option longopts[] = {
391 {"hostname", required_argument, 0, 'H'},
392 {"critical", required_argument, 0, 'c'},
393 {"warning", required_argument, 0, 'w'},
394 {"critical-codes", required_argument, 0, 'C'},
395 {"warning-codes", required_argument, 0, 'W'},
396 {"timeout", required_argument, 0, 't'},
397 {"protocol", required_argument, 0, 'P'},
398 {"port", required_argument, 0, 'p'},
399 {"escape", required_argument, 0, 'E'},
400 {"all", required_argument, 0, 'A'},
401 {"send", required_argument, 0, 's'},
402 {"expect", required_argument, 0, 'e'},
403 {"maxbytes", required_argument, 0, 'm'},
404 {"quit", required_argument, 0, 'q'},
405 {"jail", no_argument, 0, 'j'},
406 {"delay", required_argument, 0, 'd'},
407 {"refuse", required_argument, 0, 'r'},
408 {"mismatch", required_argument, 0, 'M'},
409 {"use-ipv4", no_argument, 0, '4'},
410 {"use-ipv6", no_argument, 0, '6'},
411 {"verbose", no_argument, 0, 'v'},
412 {"version", no_argument, 0, 'V'},
413 {"help", no_argument, 0, 'h'},
414 #ifdef HAVE_SSL
415 {"ssl", no_argument, 0, 'S'},
416 {"certificate", required_argument, 0, 'D'},
417 #endif
418 {0, 0, 0, 0}
419 };
421 if (argc < 2)
422 usage4 (_("No arguments found"));
424 /* backwards compatibility */
425 for (c = 1; c < argc; c++) {
426 if (strcmp ("-to", argv[c]) == 0)
427 strcpy (argv[c], "-t");
428 else if (strcmp ("-wt", argv[c]) == 0)
429 strcpy (argv[c], "-w");
430 else if (strcmp ("-ct", argv[c]) == 0)
431 strcpy (argv[c], "-c");
432 }
434 if (!is_option (argv[1])) {
435 server_address = argv[1];
436 argv[1] = argv[0];
437 argv = &argv[1];
438 argc--;
439 }
441 while (1) {
442 c = getopt_long (argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:",
443 longopts, &option);
445 if (c == -1 || c == EOF || c == 1)
446 break;
448 switch (c) {
449 case '?': /* print short usage statement if args not parsable */
450 usage5 ();
451 case 'h': /* help */
452 print_help ();
453 exit (STATE_OK);
454 case 'V': /* version */
455 print_revision (progname, revision);
456 exit (STATE_OK);
457 case 'v': /* verbose mode */
458 flags |= FLAG_VERBOSE;
459 break;
460 case '4':
461 address_family = AF_INET;
462 break;
463 case '6':
464 #ifdef USE_IPV6
465 address_family = AF_INET6;
466 #else
467 usage4 (_("IPv6 support not available"));
468 #endif
469 break;
470 case 'H': /* hostname */
471 server_address = optarg;
472 break;
473 case 'c': /* critical */
474 critical_time = strtod (optarg, NULL);
475 flags |= FLAG_TIME_CRIT;
476 break;
477 case 'j': /* hide output */
478 flags |= FLAG_HIDE_OUTPUT;
479 break;
480 case 'w': /* warning */
481 warning_time = strtod (optarg, NULL);
482 flags |= FLAG_TIME_WARN;
483 break;
484 case 'C':
485 crit_codes = realloc (crit_codes, ++crit_codes_count);
486 crit_codes[crit_codes_count - 1] = optarg;
487 break;
488 case 'W':
489 warn_codes = realloc (warn_codes, ++warn_codes_count);
490 warn_codes[warn_codes_count - 1] = optarg;
491 break;
492 case 't': /* timeout */
493 if (!is_intpos (optarg))
494 usage4 (_("Timeout interval must be a positive integer"));
495 else
496 socket_timeout = atoi (optarg);
497 break;
498 case 'p': /* port */
499 if (!is_intpos (optarg))
500 usage4 (_("Port must be a positive integer"));
501 else
502 server_port = atoi (optarg);
503 break;
504 case 'E':
505 escape = 1;
506 break;
507 case 's':
508 if (escape)
509 server_send = np_escaped_string(optarg);
510 else
511 asprintf(&server_send, "%s", optarg);
512 break;
513 case 'e': /* expect string (may be repeated) */
514 flags &= ~FLAG_EXACT_MATCH;
515 if (server_expect_count == 0)
516 server_expect = malloc (sizeof (char *) * (++server_expect_count));
517 else
518 server_expect = realloc (server_expect, sizeof (char *) * (++server_expect_count));
519 server_expect[server_expect_count - 1] = optarg;
520 break;
521 case 'm':
522 if (!is_intpos (optarg))
523 usage4 (_("Maxbytes must be a positive integer"));
524 else
525 maxbytes = strtol (optarg, NULL, 0);
526 break;
527 case 'q':
528 if (escape)
529 server_quit = np_escaped_string(optarg);
530 else
531 asprintf(&server_quit, "%s\r\n", optarg);
532 break;
533 case 'r':
534 if (!strncmp(optarg,"ok",2))
535 econn_refuse_state = STATE_OK;
536 else if (!strncmp(optarg,"warn",4))
537 econn_refuse_state = STATE_WARNING;
538 else if (!strncmp(optarg,"crit",4))
539 econn_refuse_state = STATE_CRITICAL;
540 else
541 usage4 (_("Refuse must be one of ok, warn, crit"));
542 break;
543 case 'M':
544 if (!strncmp(optarg,"ok",2))
545 expect_mismatch_state = STATE_OK;
546 else if (!strncmp(optarg,"warn",4))
547 expect_mismatch_state = STATE_WARNING;
548 else if (!strncmp(optarg,"crit",4))
549 expect_mismatch_state = STATE_CRITICAL;
550 else
551 usage4 (_("Mismatch must be one of ok, warn, crit"));
552 break;
553 case 'd':
554 if (is_intpos (optarg))
555 delay = atoi (optarg);
556 else
557 usage4 (_("Delay must be a positive integer"));
558 break;
559 case 'D': /* Check SSL cert validity - days 'til certificate expiration */
560 #ifdef HAVE_SSL
561 # ifdef USE_OPENSSL /* XXX */
562 if (!is_intnonneg (optarg))
563 usage2 (_("Invalid certificate expiration period"), optarg);
564 days_till_exp = atoi (optarg);
565 check_cert = TRUE;
566 flags |= FLAG_SSL;
567 break;
568 # endif /* USE_OPENSSL */
569 #endif
570 /* fallthrough if we don't have ssl */
571 case 'S':
572 #ifdef HAVE_SSL
573 flags |= FLAG_SSL;
574 #else
575 die (STATE_UNKNOWN, _("Invalid option - SSL is not available"));
576 #endif
577 break;
578 case 'A':
579 flags |= FLAG_MATCH_ALL;
580 break;
581 }
582 }
584 if (server_address == NULL)
585 usage4 (_("You must provide a server address"));
586 else if (server_address[0] != '/' && is_host (server_address) == FALSE)
587 die (STATE_CRITICAL, "%s %s - %s: %s\n", SERVICE, state_text(STATE_CRITICAL), _("Invalid hostname, address or socket"), server_address);
589 return TRUE;
590 }
593 void
594 print_help (void)
595 {
596 print_revision (progname, revision);
598 printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
599 printf (COPYRIGHT, copyright, email);
601 printf (_("This plugin tests %s connections with the specified host (or unix socket).\n\n"),
602 SERVICE);
604 print_usage ();
606 printf (_(UT_HELP_VRSN));
608 printf (_(UT_HOST_PORT), 'p', "none");
610 printf (_(UT_IPv46));
612 printf (" %s\n", "-E, --escape");
613 printf (" %s\n", _("Can use \\n, \\r, \\t or \\ in send or quit string. Must come before send or quit option"));
614 printf (" %s\n", _("Default: nothing added to send, \\r\\n added to end of quit"));
615 printf (" %s\n", "-s, --send=STRING");
616 printf (" %s\n", _("String to send to the server"));
617 printf (" %s\n", "-e, --expect=STRING");
618 printf (" %s %s\n", _("String to expect in server response"), _("(may be repeated)"));
619 printf (" %s\n", "-A, --all");
620 printf (" %s\n", _("All expect strings need to occur in server response. Default is any"));
621 printf (" %s\n", "-q, --quit=STRING");
622 printf (" %s\n", _("String to send server to initiate a clean close of the connection"));
623 printf (" %s\n", "-r, --refuse=ok|warn|crit");
624 printf (" %s\n", _("Accept tcp refusals with states ok, warn, crit (default: crit)"));
625 printf (" %s\n", "-M, --mismatch=ok|warn|crit");
626 printf (" %s\n", _("Accept expected string mismatches with states ok, warn, crit (default: warn)"));
627 printf (" %s\n", "-j, --jail");
628 printf (" %s\n", _("Hide output from TCP socket"));
629 printf (" %s\n", "-m, --maxbytes=INTEGER");
630 printf (" %s\n", _("Close connection once more than this number of bytes are received"));
631 printf (" %s\n", "-d, --delay=INTEGER");
632 printf (" %s\n", _("Seconds to wait between sending string and polling for response"));
634 #ifdef HAVE_SSL
635 printf (" %s\n", "-D, --certificate=INTEGER");
636 printf (" %s\n", _("Minimum number of days a certificate has to be valid."));
637 printf (" %s\n", "-S, --ssl");
638 printf (" %s\n", _("Use SSL for the connection."));
639 #endif
641 printf (_(UT_WARN_CRIT));
643 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
645 printf (_(UT_VERBOSE));
647 printf (_(UT_SUPPORT));
648 }
651 void
652 print_usage (void)
653 {
654 printf (_("Usage:"));
655 printf ("%s -H host -p port [-w <warning time>] [-c <critical time>] [-s <send string>]\n",progname);
656 printf ("[-e <expect string>] [-q <quit string>][-m <maximum bytes>] [-d <delay>]\n");
657 printf ("[-t <timeout seconds>] [-r <refuse state>] [-M <mismatch state>] [-v] [-4|-6] [-j]\n");
658 printf ("[-D <days to cert expiry>] [-S <use SSL>] [-E]\n");
659 }