check_procs: Assume we have stat()
[monitoring-plugins.git] / plugins / check_tcp.c
blobce966c38351daf3d3f08653aae14bf59b13ff33e
1 /*****************************************************************************
3 * Nagios check_tcp plugin
5 * License: GPL
6 * Copyright (c) 1999-2008 Nagios Plugins Development Team
8 * Description:
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_warn, days_till_exp_crit;
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 int host_specified = FALSE;
65 static char *server_send = NULL;
66 static char *server_quit = NULL;
67 static char **server_expect;
68 static size_t server_expect_count = 0;
69 static size_t maxbytes = 0;
70 static char **warn_codes = NULL;
71 static size_t warn_codes_count = 0;
72 static char **crit_codes = NULL;
73 static size_t crit_codes_count = 0;
74 static unsigned int delay = 0;
75 static double warning_time = 0;
76 static double critical_time = 0;
77 static double elapsed_time = 0;
78 static long microsec;
79 static int sd = 0;
80 #define MAXBUF 1024
81 static char buffer[MAXBUF];
82 static int expect_mismatch_state = STATE_WARNING;
84 #define FLAG_SSL 0x01
85 #define FLAG_VERBOSE 0x02
86 #define FLAG_EXACT_MATCH 0x04
87 #define FLAG_TIME_WARN 0x08
88 #define FLAG_TIME_CRIT 0x10
89 #define FLAG_HIDE_OUTPUT 0x20
90 #define FLAG_MATCH_ALL 0x40
91 static size_t flags = FLAG_EXACT_MATCH;
93 int
94 main (int argc, char **argv)
96 int result = STATE_UNKNOWN;
97 int i;
98 char *status = NULL;
99 struct timeval tv;
100 size_t len;
101 int match = -1;
103 setlocale (LC_ALL, "");
104 bindtextdomain (PACKAGE, LOCALEDIR);
105 textdomain (PACKAGE);
107 /* determine program- and service-name quickly */
108 progname = strrchr(argv[0], '/');
109 if(progname != NULL) progname++;
110 else progname = argv[0];
112 len = strlen(progname);
113 if(len > 6 && !memcmp(progname, "check_", 6)) {
114 SERVICE = strdup(progname + 6);
115 for(i = 0; i < len - 6; i++)
116 SERVICE[i] = toupper(SERVICE[i]);
119 /* set up a resonable buffer at first (will be realloc()'ed if
120 * user specifies other options) */
121 server_expect = calloc(sizeof(char *), 2);
123 /* determine defaults for this service's protocol */
124 if (!strncmp(SERVICE, "UDP", 3)) {
125 PROTOCOL = IPPROTO_UDP;
127 else if (!strncmp(SERVICE, "FTP", 3)) {
128 EXPECT = "220";
129 QUIT = "QUIT\r\n";
130 PORT = 21;
132 else if (!strncmp(SERVICE, "POP", 3) || !strncmp(SERVICE, "POP3", 4)) {
133 EXPECT = "+OK";
134 QUIT = "QUIT\r\n";
135 PORT = 110;
137 else if (!strncmp(SERVICE, "SMTP", 4)) {
138 EXPECT = "220";
139 QUIT = "QUIT\r\n";
140 PORT = 25;
142 else if (!strncmp(SERVICE, "IMAP", 4)) {
143 EXPECT = "* OK";
144 QUIT = "a1 LOGOUT\r\n";
145 PORT = 143;
147 #ifdef HAVE_SSL
148 else if (!strncmp(SERVICE, "SIMAP", 5)) {
149 EXPECT = "* OK";
150 QUIT = "a1 LOGOUT\r\n";
151 flags |= FLAG_SSL;
152 PORT = 993;
154 else if (!strncmp(SERVICE, "SPOP", 4)) {
155 EXPECT = "+OK";
156 QUIT = "QUIT\r\n";
157 flags |= FLAG_SSL;
158 PORT = 995;
160 else if (!strncmp(SERVICE, "SSMTP", 5)) {
161 EXPECT = "220";
162 QUIT = "QUIT\r\n";
163 flags |= FLAG_SSL;
164 PORT = 465;
166 else if (!strncmp(SERVICE, "JABBER", 6)) {
167 SEND = "<stream:stream to=\'host\' xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'>\n";
168 EXPECT = "<?xml version=\'1.0\'?><stream:stream xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'";
169 QUIT = "</stream:stream>\n";
170 flags |= FLAG_HIDE_OUTPUT;
171 PORT = 5222;
173 else if (!strncmp (SERVICE, "NNTPS", 5)) {
174 server_expect_count = 2;
175 server_expect[0] = "200";
176 server_expect[1] = "201";
177 QUIT = "QUIT\r\n";
178 flags |= FLAG_SSL;
179 PORT = 563;
181 #endif
182 else if (!strncmp (SERVICE, "NNTP", 4)) {
183 server_expect_count = 2;
184 server_expect = malloc(sizeof(char *) * server_expect_count);
185 server_expect[0] = strdup("200");
186 server_expect[1] = strdup("201");
187 QUIT = "QUIT\r\n";
188 PORT = 119;
190 else if (!strncmp(SERVICE, "CLAMD", 5)) {
191 SEND = "PING";
192 EXPECT = "PONG";
193 QUIT = NULL;
194 PORT = 3310;
196 /* fallthrough check, so it's supposed to use reverse matching */
197 else if (strcmp (SERVICE, "TCP"))
198 usage (_("CRITICAL - Generic check_tcp called with unknown service\n"));
200 server_address = "127.0.0.1";
201 server_port = PORT;
202 server_send = SEND;
203 server_quit = QUIT;
204 status = NULL;
206 /* Parse extra opts if any */
207 argv=np_extra_opts (&argc, argv, progname);
209 if (process_arguments (argc, argv) == ERROR)
210 usage4 (_("Could not parse arguments"));
212 if(flags & FLAG_VERBOSE) {
213 printf("Using service %s\n", SERVICE);
214 printf("Port: %d\n", server_port);
215 printf("flags: 0x%x\n", (int)flags);
218 if(EXPECT && !server_expect_count)
219 server_expect_count++;
221 if(PROTOCOL==IPPROTO_UDP && !(server_expect_count && server_send)){
222 usage(_("With UDP checks, a send/expect string must be specified."));
225 /* set up the timer */
226 signal (SIGALRM, socket_timeout_alarm_handler);
227 alarm (socket_timeout);
229 /* try to connect to the host at the given port number */
230 gettimeofday (&tv, NULL);
232 result = np_net_connect (server_address, server_port, &sd, PROTOCOL);
233 if (result == STATE_CRITICAL) return STATE_CRITICAL;
235 #ifdef HAVE_SSL
236 if (flags & FLAG_SSL){
237 result = np_net_ssl_init(sd);
238 if (result == STATE_OK && check_cert == TRUE) {
239 result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit);
242 if(result != STATE_OK){
243 np_net_ssl_cleanup();
244 if(sd) close(sd);
245 return result;
247 #endif /* HAVE_SSL */
249 if (server_send != NULL) { /* Something to send? */
250 my_send(server_send, strlen(server_send));
253 if (delay > 0) {
254 tv.tv_sec += delay;
255 sleep (delay);
258 if(flags & FLAG_VERBOSE) {
259 if (server_send) {
260 printf("Send string: %s\n", server_send);
262 if (server_quit) {
263 printf("Quit string: %s\n", server_quit);
265 printf("server_expect_count: %d\n", (int)server_expect_count);
266 for(i = 0; i < server_expect_count; i++)
267 printf("\t%d: %s\n", i, server_expect[i]);
270 /* if(len) later on, we know we have a non-NULL response */
271 len = 0;
272 if (server_expect_count) {
274 /* watch for the expect string */
275 while ((i = my_recv(buffer, sizeof(buffer))) > 0) {
276 status = realloc(status, len + i + 1);
277 memcpy(&status[len], buffer, i);
278 len += i;
280 /* stop reading if user-forced or data-starved */
281 if(i < sizeof(buffer) || (maxbytes && len >= maxbytes))
282 break;
284 if (maxbytes && len >= maxbytes)
285 break;
288 /* no data when expected, so return critical */
289 if (len == 0)
290 die (STATE_CRITICAL, _("No data received from host\n"));
292 /* force null-termination and strip whitespace from end of output */
293 status[len--] = '\0';
294 /* print raw output if we're debugging */
295 if(flags & FLAG_VERBOSE)
296 printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n",
297 (int)len + 1, status);
298 while(isspace(status[len])) status[len--] = '\0';
300 match = np_expect_match(status,
301 server_expect,
302 server_expect_count,
303 (flags & FLAG_MATCH_ALL ? TRUE : FALSE),
304 (flags & FLAG_EXACT_MATCH ? TRUE : FALSE),
305 (flags & FLAG_VERBOSE ? TRUE : FALSE));
308 if (server_quit != NULL) {
309 my_send(server_quit, strlen(server_quit));
311 #ifdef HAVE_SSL
312 np_net_ssl_cleanup();
313 #endif
314 if (sd) close (sd);
316 microsec = deltime (tv);
317 elapsed_time = (double)microsec / 1.0e6;
319 if (flags & FLAG_TIME_CRIT && elapsed_time > critical_time)
320 result = STATE_CRITICAL;
321 else if (flags & FLAG_TIME_WARN && elapsed_time > warning_time)
322 result = STATE_WARNING;
324 /* did we get the response we hoped? */
325 if(match == FALSE && result != STATE_CRITICAL)
326 result = expect_mismatch_state;
328 /* reset the alarm */
329 alarm (0);
331 /* this is a bit stupid, because we don't want to print the
332 * response time (which can look ok to the user) if we didn't get
333 * the response we were looking for. if-else */
334 printf("%s %s - ", SERVICE, state_text(result));
336 if(match == FALSE && len && !(flags & FLAG_HIDE_OUTPUT))
337 printf("Unexpected response from host/socket: %s", status);
338 else {
339 if(match == FALSE)
340 printf("Unexpected response from host/socket on ");
341 else
342 printf("%.3f second response time on ", elapsed_time);
343 if(server_address[0] != '/')
344 printf("port %d", server_port);
345 else
346 printf("socket %s", server_address);
349 if (match != FALSE && !(flags & FLAG_HIDE_OUTPUT) && len)
350 printf (" [%s]", status);
352 /* perf-data doesn't apply when server doesn't talk properly,
353 * so print all zeroes on warn and crit. Use fperfdata since
354 * localisation settings can make different outputs */
355 if(match == FALSE)
356 printf ("|%s",
357 fperfdata ("time", elapsed_time, "s",
358 (flags & FLAG_TIME_WARN ? TRUE : FALSE), 0,
359 (flags & FLAG_TIME_CRIT ? TRUE : FALSE), 0,
360 TRUE, 0,
361 TRUE, socket_timeout)
363 else
364 printf("|%s",
365 fperfdata ("time", elapsed_time, "s",
366 (flags & FLAG_TIME_WARN ? TRUE : FALSE), warning_time,
367 (flags & FLAG_TIME_CRIT ? TRUE : FALSE), critical_time,
368 TRUE, 0,
369 TRUE, socket_timeout)
372 putchar('\n');
373 return result;
378 /* process command-line arguments */
379 static int
380 process_arguments (int argc, char **argv)
382 int c;
383 int escape = 0;
384 char *temp;
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'}, /* FIXME: Unhandled */
395 {"port", required_argument, 0, 'p'},
396 {"escape", no_argument, 0, 'E'},
397 {"all", no_argument, 0, 'A'},
398 {"send", required_argument, 0, 's'},
399 {"expect", required_argument, 0, 'e'},
400 {"maxbytes", required_argument, 0, 'm'},
401 {"quit", required_argument, 0, 'q'},
402 {"jail", no_argument, 0, 'j'},
403 {"delay", required_argument, 0, 'd'},
404 {"refuse", required_argument, 0, 'r'},
405 {"mismatch", required_argument, 0, 'M'},
406 {"use-ipv4", no_argument, 0, '4'},
407 {"use-ipv6", no_argument, 0, '6'},
408 {"verbose", no_argument, 0, 'v'},
409 {"version", no_argument, 0, 'V'},
410 {"help", no_argument, 0, 'h'},
411 {"ssl", no_argument, 0, 'S'},
412 {"certificate", required_argument, 0, 'D'},
413 {0, 0, 0, 0}
416 if (argc < 2)
417 usage4 (_("No arguments found"));
419 /* backwards compatibility */
420 for (c = 1; c < argc; c++) {
421 if (strcmp ("-to", argv[c]) == 0)
422 strcpy (argv[c], "-t");
423 else if (strcmp ("-wt", argv[c]) == 0)
424 strcpy (argv[c], "-w");
425 else if (strcmp ("-ct", argv[c]) == 0)
426 strcpy (argv[c], "-c");
429 if (!is_option (argv[1])) {
430 server_address = argv[1];
431 argv[1] = argv[0];
432 argv = &argv[1];
433 argc--;
436 while (1) {
437 c = getopt_long (argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:",
438 longopts, &option);
440 if (c == -1 || c == EOF || c == 1)
441 break;
443 switch (c) {
444 case '?': /* print short usage statement if args not parsable */
445 usage5 ();
446 case 'h': /* help */
447 print_help ();
448 exit (STATE_OK);
449 case 'V': /* version */
450 print_revision (progname, NP_VERSION);
451 exit (STATE_OK);
452 case 'v': /* verbose mode */
453 flags |= FLAG_VERBOSE;
454 break;
455 case '4':
456 address_family = AF_INET;
457 break;
458 case '6':
459 #ifdef USE_IPV6
460 address_family = AF_INET6;
461 #else
462 usage4 (_("IPv6 support not available"));
463 #endif
464 break;
465 case 'H': /* hostname */
466 host_specified = TRUE;
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 xasprintf(&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 xasprintf(&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 ((temp=strchr(optarg,','))!=NULL) {
559 *temp='\0';
560 if (!is_intnonneg (optarg))
561 usage2 (_("Invalid certificate expiration period"), optarg); days_till_exp_warn = atoi(optarg);
562 *temp=',';
563 temp++;
564 if (!is_intnonneg (temp))
565 usage2 (_("Invalid certificate expiration period"), temp);
566 days_till_exp_crit = atoi (temp);
568 else {
569 days_till_exp_crit=0;
570 if (!is_intnonneg (optarg))
571 usage2 (_("Invalid certificate expiration period"), optarg);
572 days_till_exp_warn = atoi (optarg);
574 check_cert = TRUE;
575 flags |= FLAG_SSL;
576 break;
577 # endif /* USE_OPENSSL */
578 #endif
579 /* fallthrough if we don't have ssl */
580 case 'S':
581 #ifdef HAVE_SSL
582 flags |= FLAG_SSL;
583 #else
584 die (STATE_UNKNOWN, _("Invalid option - SSL is not available"));
585 #endif
586 break;
587 case 'A':
588 flags |= FLAG_MATCH_ALL;
589 break;
593 c = optind;
594 if(host_specified == FALSE && c < argc)
595 server_address = strdup (argv[c++]);
597 if (server_address == NULL)
598 usage4 (_("You must provide a server address"));
599 else if (server_address[0] != '/' && is_host (server_address) == FALSE)
600 die (STATE_CRITICAL, "%s %s - %s: %s\n", SERVICE, state_text(STATE_CRITICAL), _("Invalid hostname, address or socket"), server_address);
602 return TRUE;
606 void
607 print_help (void)
609 print_revision (progname, NP_VERSION);
611 printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
612 printf (COPYRIGHT, copyright, email);
614 printf (_("This plugin tests %s connections with the specified host (or unix socket).\n\n"),
615 SERVICE);
617 print_usage ();
619 printf (UT_HELP_VRSN);
620 printf (UT_EXTRA_OPTS);
622 printf (UT_HOST_PORT, 'p', "none");
624 printf (UT_IPv46);
626 printf (" %s\n", "-E, --escape");
627 printf (" %s\n", _("Can use \\n, \\r, \\t or \\ in send or quit string. Must come before send or quit option"));
628 printf (" %s\n", _("Default: nothing added to send, \\r\\n added to end of quit"));
629 printf (" %s\n", "-s, --send=STRING");
630 printf (" %s\n", _("String to send to the server"));
631 printf (" %s\n", "-e, --expect=STRING");
632 printf (" %s %s\n", _("String to expect in server response"), _("(may be repeated)"));
633 printf (" %s\n", "-A, --all");
634 printf (" %s\n", _("All expect strings need to occur in server response. Default is any"));
635 printf (" %s\n", "-q, --quit=STRING");
636 printf (" %s\n", _("String to send server to initiate a clean close of the connection"));
637 printf (" %s\n", "-r, --refuse=ok|warn|crit");
638 printf (" %s\n", _("Accept TCP refusals with states ok, warn, crit (default: crit)"));
639 printf (" %s\n", "-M, --mismatch=ok|warn|crit");
640 printf (" %s\n", _("Accept expected string mismatches with states ok, warn, crit (default: warn)"));
641 printf (" %s\n", "-j, --jail");
642 printf (" %s\n", _("Hide output from TCP socket"));
643 printf (" %s\n", "-m, --maxbytes=INTEGER");
644 printf (" %s\n", _("Close connection once more than this number of bytes are received"));
645 printf (" %s\n", "-d, --delay=INTEGER");
646 printf (" %s\n", _("Seconds to wait between sending string and polling for response"));
648 #ifdef HAVE_SSL
649 printf (" %s\n", "-D, --certificate=INTEGER[,INTEGER]");
650 printf (" %s\n", _("Minimum number of days a certificate has to be valid."));
651 printf (" %s\n", _("1st is #days for warning, 2nd is critical (if not specified - 0)."));
652 printf (" %s\n", "-S, --ssl");
653 printf (" %s\n", _("Use SSL for the connection."));
654 #endif
656 printf (UT_WARN_CRIT);
658 printf (UT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
660 printf (UT_VERBOSE);
662 printf (UT_SUPPORT);
666 void
667 print_usage (void)
669 printf ("%s\n", _("Usage:"));
670 printf ("%s -H host -p port [-w <warning time>] [-c <critical time>] [-s <send string>]\n",progname);
671 printf ("[-e <expect string>] [-q <quit string>][-m <maximum bytes>] [-d <delay>]\n");
672 printf ("[-t <timeout seconds>] [-r <refuse state>] [-M <mismatch state>] [-v] [-4|-6] [-j]\n");
673 printf ("[-D <warn days cert expire>[,<crit days cert expire>]] [-S <use SSL>] [-E]\n");