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 = strdup(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=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'";
170 QUIT = "</stream:stream>\n";
171 flags |= 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 if(match == -2)
351 printf("Unexpected response from host/socket on ");
352 else
353 printf("%.3f second response time on ", elapsed_time);
354 if(server_address[0] != '/')
355 printf("port %d", server_port);
356 else
357 printf("socket %s", server_address);
358 }
360 if (match != -2 && !(flags & FLAG_HIDE_OUTPUT) && len)
361 printf (" [%s]", status);
363 /* perf-data doesn't apply when server doesn't talk properly,
364 * so print all zeroes on warn and crit. Use fperfdata since
365 * localisation settings can make different outputs */
366 if(match == -2)
367 printf ("|%s",
368 fperfdata ("time", elapsed_time, "s",
369 TRUE, 0,
370 TRUE, 0,
371 TRUE, 0,
372 TRUE, socket_timeout)
373 );
374 else
375 printf("|%s",
376 fperfdata ("time", elapsed_time, "s",
377 TRUE, warning_time,
378 TRUE, critical_time,
379 TRUE, 0,
380 TRUE, socket_timeout)
381 );
383 putchar('\n');
384 return result;
385 }
389 /* process command-line arguments */
390 static int
391 process_arguments (int argc, char **argv)
392 {
393 int c;
394 int escape = 0;
396 int option = 0;
397 static struct option longopts[] = {
398 {"hostname", required_argument, 0, 'H'},
399 {"critical", required_argument, 0, 'c'},
400 {"warning", required_argument, 0, 'w'},
401 {"critical-codes", required_argument, 0, 'C'},
402 {"warning-codes", required_argument, 0, 'W'},
403 {"timeout", required_argument, 0, 't'},
404 {"protocol", required_argument, 0, 'P'},
405 {"port", required_argument, 0, 'p'},
406 {"escape", required_argument, 0, 'E'},
407 {"send", required_argument, 0, 's'},
408 {"expect", required_argument, 0, 'e'},
409 {"maxbytes", required_argument, 0, 'm'},
410 {"quit", required_argument, 0, 'q'},
411 {"jail", no_argument, 0, 'j'},
412 {"delay", required_argument, 0, 'd'},
413 {"refuse", required_argument, 0, 'r'},
414 {"mismatch", required_argument, 0, 'M'},
415 {"use-ipv4", no_argument, 0, '4'},
416 {"use-ipv6", no_argument, 0, '6'},
417 {"verbose", no_argument, 0, 'v'},
418 {"version", no_argument, 0, 'V'},
419 {"help", no_argument, 0, 'h'},
420 #ifdef HAVE_SSL
421 {"ssl", no_argument, 0, 'S'},
422 {"certificate", required_argument, 0, 'D'},
423 #endif
424 {0, 0, 0, 0}
425 };
427 if (argc < 2)
428 usage4 (_("No arguments found"));
430 /* backwards compatibility */
431 for (c = 1; c < argc; c++) {
432 if (strcmp ("-to", argv[c]) == 0)
433 strcpy (argv[c], "-t");
434 else if (strcmp ("-wt", argv[c]) == 0)
435 strcpy (argv[c], "-w");
436 else if (strcmp ("-ct", argv[c]) == 0)
437 strcpy (argv[c], "-c");
438 }
440 if (!is_option (argv[1])) {
441 server_address = argv[1];
442 argv[1] = argv[0];
443 argv = &argv[1];
444 argc--;
445 }
447 while (1) {
448 c = getopt_long (argc, argv, "+hVv46EH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:",
449 longopts, &option);
451 if (c == -1 || c == EOF || c == 1)
452 break;
454 switch (c) {
455 case '?': /* print short usage statement if args not parsable */
456 usage5 ();
457 case 'h': /* help */
458 print_help ();
459 exit (STATE_OK);
460 case 'V': /* version */
461 print_revision (progname, revision);
462 exit (STATE_OK);
463 case 'v': /* verbose mode */
464 flags |= FLAG_VERBOSE;
465 break;
466 case '4':
467 address_family = AF_INET;
468 break;
469 case '6':
470 #ifdef USE_IPV6
471 address_family = AF_INET6;
472 #else
473 usage4 (_("IPv6 support not available"));
474 #endif
475 break;
476 case 'H': /* hostname */
477 server_address = optarg;
478 break;
479 case 'c': /* critical */
480 critical_time = strtod (optarg, NULL);
481 flags |= FLAG_TIME_CRIT;
482 break;
483 case 'j': /* hide output */
484 flags |= FLAG_HIDE_OUTPUT;
485 break;
486 case 'w': /* warning */
487 warning_time = strtod (optarg, NULL);
488 flags |= FLAG_TIME_WARN;
489 break;
490 case 'C':
491 crit_codes = realloc (crit_codes, ++crit_codes_count);
492 crit_codes[crit_codes_count - 1] = optarg;
493 break;
494 case 'W':
495 warn_codes = realloc (warn_codes, ++warn_codes_count);
496 warn_codes[warn_codes_count - 1] = optarg;
497 break;
498 case 't': /* timeout */
499 if (!is_intpos (optarg))
500 usage4 (_("Timeout interval must be a positive integer"));
501 else
502 socket_timeout = atoi (optarg);
503 break;
504 case 'p': /* port */
505 if (!is_intpos (optarg))
506 usage4 (_("Port must be a positive integer"));
507 else
508 server_port = atoi (optarg);
509 break;
510 case 'E':
511 escape = 1;
512 break;
513 case 's':
514 if (escape)
515 server_send = np_escaped_string(optarg);
516 else
517 asprintf(&server_send, "%s", optarg);
518 break;
519 case 'e': /* expect string (may be repeated) */
520 EXPECT = NULL;
521 flags &= ~FLAG_EXACT_MATCH;
522 if (server_expect_count == 0)
523 server_expect = malloc (sizeof (char *) * (++server_expect_count));
524 else
525 server_expect = realloc (server_expect, sizeof (char *) * (++server_expect_count));
526 server_expect[server_expect_count - 1] = optarg;
527 break;
528 case 'm':
529 if (!is_intpos (optarg))
530 usage4 (_("Maxbytes must be a positive integer"));
531 else
532 maxbytes = strtol (optarg, NULL, 0);
533 break;
534 case 'q':
535 if (escape)
536 server_quit = np_escaped_string(optarg);
537 else
538 asprintf(&server_quit, "%s\r\n", optarg);
539 break;
540 case 'r':
541 if (!strncmp(optarg,"ok",2))
542 econn_refuse_state = STATE_OK;
543 else if (!strncmp(optarg,"warn",4))
544 econn_refuse_state = STATE_WARNING;
545 else if (!strncmp(optarg,"crit",4))
546 econn_refuse_state = STATE_CRITICAL;
547 else
548 usage4 (_("Refuse must be one of ok, warn, crit"));
549 break;
550 case 'M':
551 if (!strncmp(optarg,"ok",2))
552 expect_mismatch_state = STATE_OK;
553 else if (!strncmp(optarg,"warn",4))
554 expect_mismatch_state = STATE_WARNING;
555 else if (!strncmp(optarg,"crit",4))
556 expect_mismatch_state = STATE_CRITICAL;
557 else
558 usage4 (_("Mismatch must be one of ok, warn, crit"));
559 break;
560 case 'd':
561 if (is_intpos (optarg))
562 delay = atoi (optarg);
563 else
564 usage4 (_("Delay must be a positive integer"));
565 break;
566 case 'D': /* Check SSL cert validity - days 'til certificate expiration */
567 #ifdef HAVE_SSL
568 # ifdef USE_OPENSSL /* XXX */
569 if (!is_intnonneg (optarg))
570 usage2 (_("Invalid certificate expiration period"), optarg);
571 days_till_exp = atoi (optarg);
572 check_cert = TRUE;
573 flags |= FLAG_SSL;
574 break;
575 # endif /* USE_OPENSSL */
576 #endif
577 /* fallthrough if we don't have ssl */
578 case 'S':
579 #ifdef HAVE_SSL
580 flags |= FLAG_SSL;
581 #else
582 die (STATE_UNKNOWN, _("Invalid option - SSL is not available"));
583 #endif
584 break;
585 }
586 }
588 if (server_address == NULL)
589 usage4 (_("You must provide a server address"));
590 else if (server_address[0] != '/' && is_host (server_address) == FALSE)
591 die (STATE_CRITICAL, "%s %s - %s: %s\n", SERVICE, state_text(STATE_CRITICAL), _("Invalid hostname, address or socket"), server_address);
593 return TRUE;
594 }
597 void
598 print_help (void)
599 {
600 print_revision (progname, revision);
602 printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
603 printf (COPYRIGHT, copyright, email);
605 printf (_("This plugin tests %s connections with the specified host (or unix socket).\n\n"),
606 SERVICE);
608 print_usage ();
610 printf (_(UT_HELP_VRSN));
612 printf (_(UT_HOST_PORT), 'p', "none");
614 printf (_(UT_IPv46));
616 printf (" %s\n", "-E, --escape");
617 printf (" %s\n", _("Can use \\n, \\r, \\t or \\ in send or quit string. Must come before send or quit option"));
618 printf (" %s\n", _("Default: nothing added to send, \\r\\n added to end of quit"));
619 printf (" %s\n", "-s, --send=STRING");
620 printf (" %s\n", _("String to send to the server"));
621 printf (" %s\n", "-e, --expect=STRING");
622 printf (" %s\n", _("String to expect in server response"));
623 printf (" %s\n", "-q, --quit=STRING");
624 printf (" %s\n", _("String to send server to initiate a clean close of the connection"));
625 printf (" %s\n", "-r, --refuse=ok|warn|crit");
626 printf (" %s\n", _("Accept tcp refusals with states ok, warn, crit (default: crit)"));
627 printf (" %s\n", "-M, --mismatch=ok|warn|crit");
628 printf (" %s\n", _("Accept expected string mismatches with states ok, warn, crit (default: warn)"));
629 printf (" %s\n", "-j, --jail");
630 printf (" %s\n", _("Hide output from TCP socket"));
631 printf (" %s\n", "-m, --maxbytes=INTEGER");
632 printf (" %s\n", _("Close connection once more than this number of bytes are received"));
633 printf (" %s\n", "-d, --delay=INTEGER");
634 printf (" %s\n", _("Seconds to wait between sending string and polling for response"));
636 #ifdef HAVE_SSL
637 printf (" %s\n", "-D, --certificate=INTEGER");
638 printf (" %s\n", _("Minimum number of days a certificate has to be valid."));
639 printf (" %s\n", "-S, --ssl");
640 printf (" %s\n", _("Use SSL for the connection."));
641 #endif
643 printf (_(UT_WARN_CRIT));
645 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
647 printf (_(UT_VERBOSE));
649 printf (_(UT_SUPPORT));
650 }
653 void
654 print_usage (void)
655 {
656 printf (_("Usage:"));
657 printf ("%s -H host -p port [-w <warning time>] [-c <critical time>] [-s <send string>]\n",progname);
658 printf ("[-e <expect string>] [-q <quit string>][-m <maximum bytes>] [-d <delay>]\n");
659 printf ("[-t <timeout seconds>] [-r <refuse state>] [-M <mismatch state>] [-v] [-4|-6] [-j]\n");
660 printf ("[-D <days to cert expiry>] [-S <use SSL>] [-E]\n");
661 }