Code

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