Code

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