Merge branch 'master' of ssh://tonvoon@nagiosplug.git.sourceforge.net/gitroot/nagiosp...
[monitoring-plugins.git] / plugins / check_tcp.c
blob178bd5688dec52abeeb72667b595ba7c65709ab5
1 /*****************************************************************************
2 *
3 * Nagios check_tcp plugin
4 *
5 * License: GPL
6 * Copyright (c) 1999-2008 Nagios Plugins Development Team
7 *
8 * Description:
9 *
10 * This file contains the check_tcp plugin
13 * This program is free software: you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation, either version 3 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26 * $Id$
28 *****************************************************************************/
30 /* progname "check_tcp" changes depending on symlink called */
31 char *progname;
32 const char *copyright = "1999-2008";
33 const char *email = "nagiosplug-devel@lists.sourceforge.net";
35 #include "common.h"
36 #include "netutils.h"
37 #include "utils.h"
38 #include "utils_tcp.h"
40 #ifdef HAVE_SSL
41 static int check_cert = FALSE;
42 static int days_till_exp;
43 # define my_recv(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_read(buf, len) : read(sd, buf, len))
44 # define my_send(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0))
45 #else
46 # define my_recv(buf, len) read(sd, buf, len)
47 # define my_send(buf, len) send(sd, buf, len, 0)
48 #endif
50 /* int my_recv(char *, size_t); */
51 static int process_arguments (int, char **);
52 void print_help (void);
53 void print_usage (void);
55 #define EXPECT server_expect[0]
56 static char *SERVICE = "TCP";
57 static char *SEND = NULL;
58 static char *QUIT = NULL;
59 static int PROTOCOL = IPPROTO_TCP; /* most common is default */
60 static int PORT = 0;
62 static int server_port = 0;
63 static char *server_address = NULL;
64 static char *server_send = NULL;
65 static char *server_quit = NULL;
66 static char **server_expect;
67 static size_t server_expect_count = 0;
68 static size_t maxbytes = 0;
69 static char **warn_codes = NULL;
70 static size_t warn_codes_count = 0;
71 static char **crit_codes = NULL;
72 static size_t crit_codes_count = 0;
73 static unsigned int delay = 0;
74 static double warning_time = 0;
75 static double critical_time = 0;
76 static double elapsed_time = 0;
77 static long microsec;
78 static int sd = 0;
79 #define MAXBUF 1024
80 static char buffer[MAXBUF];
81 static int expect_mismatch_state = STATE_WARNING;
83 #define FLAG_SSL 0x01
84 #define FLAG_VERBOSE 0x02
85 #define FLAG_EXACT_MATCH 0x04
86 #define FLAG_TIME_WARN 0x08
87 #define FLAG_TIME_CRIT 0x10
88 #define FLAG_HIDE_OUTPUT 0x20
89 #define FLAG_MATCH_ALL 0x40
90 static size_t flags = FLAG_EXACT_MATCH;
92 int
93 main (int argc, char **argv)
95 int result = STATE_UNKNOWN;
96 int i;
97 char *status = NULL;
98 struct timeval tv;
99 size_t len;
100 int match = -1;
102 setlocale (LC_ALL, "");
103 bindtextdomain (PACKAGE, LOCALEDIR);
104 textdomain (PACKAGE);
106 /* determine program- and service-name quickly */
107 progname = strrchr(argv[0], '/');
108 if(progname != NULL) progname++;
109 else progname = argv[0];
111 len = strlen(progname);
112 if(len > 6 && !memcmp(progname, "check_", 6)) {
113 SERVICE = strdup(progname + 6);
114 for(i = 0; i < len - 6; i++)
115 SERVICE[i] = toupper(SERVICE[i]);
118 /* set up a resonable buffer at first (will be realloc()'ed if
119 * user specifies other options) */
120 server_expect = calloc(sizeof(char *), 2);
122 /* determine defaults for this service's protocol */
123 if (!strncmp(SERVICE, "UDP", 3)) {
124 PROTOCOL = IPPROTO_UDP;
126 else if (!strncmp(SERVICE, "FTP", 3)) {
127 EXPECT = "220";
128 QUIT = "QUIT\r\n";
129 PORT = 21;
131 else if (!strncmp(SERVICE, "POP", 3) || !strncmp(SERVICE, "POP3", 4)) {
132 EXPECT = "+OK";
133 QUIT = "QUIT\r\n";
134 PORT = 110;
136 else if (!strncmp(SERVICE, "SMTP", 4)) {
137 EXPECT = "220";
138 QUIT = "QUIT\r\n";
139 PORT = 25;
141 else if (!strncmp(SERVICE, "IMAP", 4)) {
142 EXPECT = "* OK";
143 QUIT = "a1 LOGOUT\r\n";
144 PORT = 143;
146 #ifdef HAVE_SSL
147 else if (!strncmp(SERVICE, "SIMAP", 5)) {
148 EXPECT = "* OK";
149 QUIT = "a1 LOGOUT\r\n";
150 flags |= FLAG_SSL;
151 PORT = 993;
153 else if (!strncmp(SERVICE, "SPOP", 4)) {
154 EXPECT = "+OK";
155 QUIT = "QUIT\r\n";
156 flags |= FLAG_SSL;
157 PORT = 995;
159 else if (!strncmp(SERVICE, "SSMTP", 5)) {
160 EXPECT = "220";
161 QUIT = "QUIT\r\n";
162 flags |= FLAG_SSL;
163 PORT = 465;
165 else if (!strncmp(SERVICE, "JABBER", 6)) {
166 SEND = "<stream:stream to=\'host\' xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'>\n";
167 EXPECT = "<?xml version=\'1.0\'?><stream:stream xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'";
168 QUIT = "</stream:stream>\n";
169 flags |= FLAG_HIDE_OUTPUT;
170 PORT = 5222;
172 else if (!strncmp (SERVICE, "NNTPS", 5)) {
173 server_expect_count = 2;
174 server_expect[0] = "200";
175 server_expect[1] = "201";
176 QUIT = "QUIT\r\n";
177 flags |= FLAG_SSL;
178 PORT = 563;
180 #endif
181 else if (!strncmp (SERVICE, "NNTP", 4)) {
182 server_expect_count = 2;
183 server_expect = malloc(sizeof(char *) * server_expect_count);
184 server_expect[0] = strdup("200");
185 server_expect[1] = strdup("201");
186 QUIT = "QUIT\r\n";
187 PORT = 119;
189 else if (!strncmp(SERVICE, "CLAMD", 5)) {
190 SEND = "PING";
191 EXPECT = "PONG";
192 QUIT = NULL;
193 PORT = 3310;
195 /* fallthrough check, so it's supposed to use reverse matching */
196 else if (strcmp (SERVICE, "TCP"))
197 usage (_("CRITICAL - Generic check_tcp called with unknown service\n"));
199 server_address = "127.0.0.1";
200 server_port = PORT;
201 server_send = SEND;
202 server_quit = QUIT;
203 status = NULL;
205 /* Parse extra opts if any */
206 argv=np_extra_opts (&argc, argv, progname);
208 if (process_arguments (argc, argv) == ERROR)
209 usage4 (_("Could not parse arguments"));
211 if(flags & FLAG_VERBOSE) {
212 printf("Using service %s\n", SERVICE);
213 printf("Port: %d\n", server_port);
214 printf("flags: 0x%x\n", (int)flags);
217 if(EXPECT && !server_expect_count)
218 server_expect_count++;
220 if(PROTOCOL==IPPROTO_UDP && !(server_expect_count && server_send)){
221 usage(_("With UDP checks, a send/expect string must be specified."));
224 /* set up the timer */
225 signal (SIGALRM, socket_timeout_alarm_handler);
226 alarm (socket_timeout);
228 /* try to connect to the host at the given port number */
229 gettimeofday (&tv, NULL);
231 result = np_net_connect (server_address, server_port, &sd, PROTOCOL);
232 if (result == STATE_CRITICAL) return STATE_CRITICAL;
234 #ifdef HAVE_SSL
235 if (flags & FLAG_SSL){
236 result = np_net_ssl_init(sd);
237 if (result == STATE_OK && check_cert == TRUE) {
238 result = np_net_ssl_check_cert(days_till_exp);
239 if(result != STATE_OK) {
240 printf(_("CRITICAL - Cannot retrieve server certificate.\n"));
244 if(result != STATE_OK){
245 np_net_ssl_cleanup();
246 if(sd) close(sd);
247 return result;
249 #endif /* HAVE_SSL */
251 if (server_send != NULL) { /* Something to send? */
252 my_send(server_send, strlen(server_send));
255 if (delay > 0) {
256 tv.tv_sec += delay;
257 sleep (delay);
260 if(flags & FLAG_VERBOSE) {
261 if (server_send) {
262 printf("Send string: %s\n", server_send);
264 if (server_quit) {
265 printf("Quit string: %s\n", server_quit);
267 printf("server_expect_count: %d\n", (int)server_expect_count);
268 for(i = 0; i < server_expect_count; i++)
269 printf("\t%d: %s\n", i, server_expect[i]);
272 /* if(len) later on, we know we have a non-NULL response */
273 len = 0;
274 if (server_expect_count) {
276 /* watch for the expect string */
277 while ((i = my_recv(buffer, sizeof(buffer))) > 0) {
278 status = realloc(status, len + i + 1);
279 memcpy(&status[len], buffer, i);
280 len += i;
282 /* stop reading if user-forced or data-starved */
283 if(i < sizeof(buffer) || (maxbytes && len >= maxbytes))
284 break;
286 if (maxbytes && len >= maxbytes)
287 break;
290 /* no data when expected, so return critical */
291 if (len == 0)
292 die (STATE_CRITICAL, _("No data received from host\n"));
294 /* force null-termination and strip whitespace from end of output */
295 status[len--] = '\0';
296 /* print raw output if we're debugging */
297 if(flags & FLAG_VERBOSE)
298 printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n",
299 (int)len + 1, status);
300 while(isspace(status[len])) status[len--] = '\0';
302 match = np_expect_match(status,
303 server_expect,
304 server_expect_count,
305 (flags & FLAG_MATCH_ALL ? TRUE : FALSE),
306 (flags & FLAG_EXACT_MATCH ? TRUE : FALSE),
307 (flags & FLAG_VERBOSE ? TRUE : FALSE));
310 if (server_quit != NULL) {
311 my_send(server_quit, strlen(server_quit));
313 #ifdef HAVE_SSL
314 np_net_ssl_cleanup();
315 #endif
316 if (sd) close (sd);
318 microsec = deltime (tv);
319 elapsed_time = (double)microsec / 1.0e6;
321 if (flags & FLAG_TIME_CRIT && elapsed_time > critical_time)
322 result = STATE_CRITICAL;
323 else if (flags & FLAG_TIME_WARN && elapsed_time > warning_time)
324 result = STATE_WARNING;
326 /* did we get the response we hoped? */
327 if(match == FALSE && result != STATE_CRITICAL)
328 result = expect_mismatch_state;
330 /* reset the alarm */
331 alarm (0);
333 /* this is a bit stupid, because we don't want to print the
334 * response time (which can look ok to the user) if we didn't get
335 * the response we were looking for. if-else */
336 printf("%s %s - ", SERVICE, state_text(result));
338 if(match == FALSE && len && !(flags & FLAG_HIDE_OUTPUT))
339 printf("Unexpected response from host/socket: %s", status);
340 else {
341 if(match == FALSE)
342 printf("Unexpected response from host/socket on ");
343 else
344 printf("%.3f second response time on ", elapsed_time);
345 if(server_address[0] != '/')
346 printf("port %d", server_port);
347 else
348 printf("socket %s", server_address);
351 if (match != FALSE && !(flags & FLAG_HIDE_OUTPUT) && len)
352 printf (" [%s]", status);
354 /* perf-data doesn't apply when server doesn't talk properly,
355 * so print all zeroes on warn and crit. Use fperfdata since
356 * localisation settings can make different outputs */
357 if(match == FALSE)
358 printf ("|%s",
359 fperfdata ("time", elapsed_time, "s",
360 (flags & FLAG_TIME_WARN ? TRUE : FALSE), 0,
361 (flags & FLAG_TIME_CRIT ? TRUE : FALSE), 0,
362 TRUE, 0,
363 TRUE, socket_timeout)
365 else
366 printf("|%s",
367 fperfdata ("time", elapsed_time, "s",
368 (flags & FLAG_TIME_WARN ? TRUE : FALSE), warning_time,
369 (flags & FLAG_TIME_CRIT ? TRUE : FALSE), critical_time,
370 TRUE, 0,
371 TRUE, socket_timeout)
374 putchar('\n');
375 return result;
380 /* process command-line arguments */
381 static int
382 process_arguments (int argc, char **argv)
384 int c;
385 int escape = 0;
387 int option = 0;
388 static struct option longopts[] = {
389 {"hostname", required_argument, 0, 'H'},
390 {"critical", required_argument, 0, 'c'},
391 {"warning", required_argument, 0, 'w'},
392 {"critical-codes", required_argument, 0, 'C'},
393 {"warning-codes", required_argument, 0, 'W'},
394 {"timeout", required_argument, 0, 't'},
395 {"protocol", required_argument, 0, 'P'}, /* FIXME: Unhandled */
396 {"port", required_argument, 0, 'p'},
397 {"escape", no_argument, 0, 'E'},
398 {"all", no_argument, 0, 'A'},
399 {"send", required_argument, 0, 's'},
400 {"expect", required_argument, 0, 'e'},
401 {"maxbytes", required_argument, 0, 'm'},
402 {"quit", required_argument, 0, 'q'},
403 {"jail", no_argument, 0, 'j'},
404 {"delay", required_argument, 0, 'd'},
405 {"refuse", required_argument, 0, 'r'},
406 {"mismatch", required_argument, 0, 'M'},
407 {"use-ipv4", no_argument, 0, '4'},
408 {"use-ipv6", no_argument, 0, '6'},
409 {"verbose", no_argument, 0, 'v'},
410 {"version", no_argument, 0, 'V'},
411 {"help", no_argument, 0, 'h'},
412 {"ssl", no_argument, 0, 'S'},
413 {"certificate", required_argument, 0, 'D'},
414 {0, 0, 0, 0}
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");
430 if (!is_option (argv[1])) {
431 server_address = argv[1];
432 argv[1] = argv[0];
433 argv = &argv[1];
434 argc--;
437 while (1) {
438 c = getopt_long (argc, argv, "+hVv46EAH: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 usage5 ();
447 case 'h': /* help */
448 print_help ();
449 exit (STATE_OK);
450 case 'V': /* version */
451 print_revision (progname, NP_VERSION);
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 flags &= ~FLAG_EXACT_MATCH;
511 if (server_expect_count == 0)
512 server_expect = malloc (sizeof (char *) * (++server_expect_count));
513 else
514 server_expect = realloc (server_expect, sizeof (char *) * (++server_expect_count));
515 server_expect[server_expect_count - 1] = optarg;
516 break;
517 case 'm':
518 if (!is_intpos (optarg))
519 usage4 (_("Maxbytes must be a positive integer"));
520 else
521 maxbytes = strtol (optarg, NULL, 0);
522 break;
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 case 'A':
575 flags |= FLAG_MATCH_ALL;
576 break;
580 if (server_address == NULL)
581 usage4 (_("You must provide a server address"));
582 else if (server_address[0] != '/' && is_host (server_address) == FALSE)
583 die (STATE_CRITICAL, "%s %s - %s: %s\n", SERVICE, state_text(STATE_CRITICAL), _("Invalid hostname, address or socket"), server_address);
585 return TRUE;
589 void
590 print_help (void)
592 print_revision (progname, NP_VERSION);
594 printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
595 printf (COPYRIGHT, copyright, email);
597 printf (_("This plugin tests %s connections with the specified host (or unix socket).\n\n"),
598 SERVICE);
600 print_usage ();
602 printf (UT_HELP_VRSN);
603 printf (UT_EXTRA_OPTS);
605 printf (UT_HOST_PORT, 'p', "none");
607 printf (UT_IPv46);
609 printf (" %s\n", "-E, --escape");
610 printf (" %s\n", _("Can use \\n, \\r, \\t or \\ in send or quit string. Must come before send or quit option"));
611 printf (" %s\n", _("Default: nothing added to send, \\r\\n added to end of quit"));
612 printf (" %s\n", "-s, --send=STRING");
613 printf (" %s\n", _("String to send to the server"));
614 printf (" %s\n", "-e, --expect=STRING");
615 printf (" %s %s\n", _("String to expect in server response"), _("(may be repeated)"));
616 printf (" %s\n", "-A, --all");
617 printf (" %s\n", _("All expect strings need to occur in server response. Default is any"));
618 printf (" %s\n", "-q, --quit=STRING");
619 printf (" %s\n", _("String to send server to initiate a clean close of the connection"));
620 printf (" %s\n", "-r, --refuse=ok|warn|crit");
621 printf (" %s\n", _("Accept TCP refusals with states ok, warn, crit (default: crit)"));
622 printf (" %s\n", "-M, --mismatch=ok|warn|crit");
623 printf (" %s\n", _("Accept expected string mismatches with states ok, warn, crit (default: warn)"));
624 printf (" %s\n", "-j, --jail");
625 printf (" %s\n", _("Hide output from TCP socket"));
626 printf (" %s\n", "-m, --maxbytes=INTEGER");
627 printf (" %s\n", _("Close connection once more than this number of bytes are received"));
628 printf (" %s\n", "-d, --delay=INTEGER");
629 printf (" %s\n", _("Seconds to wait between sending string and polling for response"));
631 #ifdef HAVE_SSL
632 printf (" %s\n", "-D, --certificate=INTEGER");
633 printf (" %s\n", _("Minimum number of days a certificate has to be valid."));
634 printf (" %s\n", "-S, --ssl");
635 printf (" %s\n", _("Use SSL for the connection."));
636 #endif
638 printf (UT_WARN_CRIT);
640 printf (UT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
642 printf (UT_VERBOSE);
644 printf (UT_SUPPORT);
648 void
649 print_usage (void)
651 printf ("%s\n", _("Usage:"));
652 printf ("%s -H host -p port [-w <warning time>] [-c <critical time>] [-s <send string>]\n",progname);
653 printf ("[-e <expect string>] [-q <quit string>][-m <maximum bytes>] [-d <delay>]\n");
654 printf ("[-t <timeout seconds>] [-r <refuse state>] [-M <mismatch state>] [-v] [-4|-6] [-j]\n");
655 printf ("[-D <days to cert expiry>] [-S <use SSL>] [-E]\n");