Code

Added -4 and -6 command line options into check_http, check_ldap and
[nagiosplug.git] / plugins / check_tcp.c
1 /*****************************************************************************
2 *
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.
7 *
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.
12 *
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.
16 *
17 *****************************************************************************/
19 /* progname changes depending on symlink called */
20 char *progname = "check_tcp";
21 const char *revision = "$Revision$";
22 const char *copyright = "2002-2003";
23 const char *authors = "Nagios Plugin Development Team";
24 const char *email = "nagiosplug-devel@lists.sourceforge.net";
26 const char *summary = "\
27 This plugin tests %s connections with the specified host.\n";
29 const char *option_summary = "\
30 -H host -p port [-w warn_time] [-c crit_time] [-s send_string]\n\
31         [-e expect_string] [-q quit_string] [-m maxbytes] [-d delay]\n\
32         [-t to_sec] [-r refuse_state] [-v] [-4|-6]\n";
34 const char *options = "\
35  -H, --hostname=ADDRESS\n\
36     Host name argument for servers using host headers (use numeric\n\
37     address if possible to bypass DNS lookup).\n\
38  -p, --port=INTEGER\n\
39     Port number\n\
40  -4, --use-ipv4\n\
41     Use IPv4 connection\n\
42  -6, --use-ipv6\n\
43     Use IPv6 connection\n\
44  -s, --send=STRING\n\
45     String to send to the server\n\
46  -e, --expect=STRING\n\
47     String to expect in server response\n\
48  -q, --quit=STRING\n\
49     String to send server to initiate a clean close of the connection\n\
50  -m, --maxbytes=INTEGER\n\
51     Close connection once more than this number of bytes are received\n\
52  -d, --delay=INTEGER\n\
53     Seconds to wait between sending string and polling for response\n\
54  -w, --warning=DOUBLE\n\
55     Response time to result in warning status (seconds)\n\
56  -c, --critical=DOUBLE\n\
57     Response time to result in critical status (seconds)\n\
58  -t, --timeout=INTEGER\n\
59     Seconds before connection times out (default: %d)\n\
60  -r, --refuse=ok|warn|crit\n\
61     Accept tcp refusals with states ok, warn, crit (default: crit)\n\
62  -v, --verbose\n\
63     Show details for command-line debugging (Nagios may truncate output)\n";
65 const char *standard_options = "\
66  -h, --help\n\
67     Print detailed help screen\n\
68  -V, --version\n\
69     Print version information\n\n";
71 #include "config.h"
72 #include "common.h"
73 #include "netutils.h"
74 #include "utils.h"
76 #ifdef HAVE_SSL_H
77 #  include <rsa.h>
78 #  include <crypto.h>
79 #  include <x509.h>
80 #  include <pem.h>
81 #  include <ssl.h>
82 #  include <err.h>
83 #else
84 #  ifdef HAVE_OPENSSL_SSL_H
85 #    include <openssl/rsa.h>
86 #    include <openssl/crypto.h>
87 #    include <openssl/x509.h>
88 #    include <openssl/pem.h>
89 #    include <openssl/ssl.h>
90 #    include <openssl/err.h>
91 #  endif
92 #endif
94 #ifdef HAVE_SSL
95 SSL_CTX *ctx;
96 SSL *ssl;
97 int connect_SSL (void);
98 #endif
100 enum {
101         TCP_PROTOCOL = 1,
102         UDP_PROTOCOL = 2,
103         MAXBUF = 1024
104 };
106 int process_arguments (int, char **);
107 void print_usage (void);
108 void print_help (void);
109 int my_recv (void);
111 char *SERVICE = NULL;
112 char *SEND = NULL;
113 char *EXPECT = NULL;
114 char *QUIT = NULL;
115 int PROTOCOL = 0;
116 int PORT = 0;
118 int server_port = 0;
119 char *server_address = NULL;
120 char *server_send = NULL;
121 char *server_quit = NULL;
122 char **server_expect = NULL;
123 int server_expect_count = 0;
124 int maxbytes = 0;
125 char **warn_codes = NULL;
126 int warn_codes_count = 0;
127 char **crit_codes = NULL;
128 int crit_codes_count = 0;
129 int delay = 0;
130 double warning_time = 0;
131 int check_warning_time = FALSE;
132 double critical_time = 0;
133 int check_critical_time = FALSE;
134 double elapsed_time = 0;
135 int verbose = FALSE;
136 int use_ssl = FALSE;
137 int sd = 0;
138 char *buffer = "";
140 int
141 main (int argc, char **argv)
143         int result;
144         int i;
145         char *status = "";
146         struct timeval tv;
148         if (strstr (argv[0], "check_udp")) {
149                 progname = strdup ("check_udp");
150                 SERVICE = strdup ("UDP");
151                 SEND = NULL;
152                 EXPECT = NULL;
153                 QUIT = NULL;
154                 PROTOCOL = UDP_PROTOCOL;
155                 PORT = 0;
156         }
157         else if (strstr (argv[0], "check_tcp")) {
158                 progname = strdup ("check_tcp");
159                 SERVICE = strdup ("TCP");
160                 SEND = NULL;
161                 EXPECT = NULL;
162                 QUIT = NULL;
163                 PROTOCOL = TCP_PROTOCOL;
164                 PORT = 0;
165         }
166         else if (strstr (argv[0], "check_ftp")) {
167                 progname = strdup ("check_ftp");
168                 SERVICE = strdup ("FTP");
169                 SEND = NULL;
170                 EXPECT = strdup ("220");
171                 QUIT = strdup ("QUIT\r\n");
172                 PROTOCOL = TCP_PROTOCOL;
173                 PORT = 21;
174         }
175         else if (strstr (argv[0], "check_smtp")) {
176                 progname = strdup ("check_smtp");
177                 SERVICE = strdup ("SMTP");
178                 SEND = NULL;
179                 EXPECT = strdup ("220");
180                 QUIT = strdup ("QUIT\r\n");
181                 PROTOCOL = TCP_PROTOCOL;
182                 PORT = 25;
183         }
184         else if (strstr (argv[0], "check_pop")) {
185                 progname = strdup ("check_pop");
186                 SERVICE = strdup ("POP");
187                 SEND = NULL;
188                 EXPECT = strdup ("+OK");
189                 QUIT = strdup ("QUIT\r\n");
190                 PROTOCOL = TCP_PROTOCOL;
191                 PORT = 110;
192         }
193         else if (strstr (argv[0], "check_imap")) {
194                 progname = strdup ("check_imap");
195                 SERVICE = strdup ("IMAP");
196                 SEND = NULL;
197                 EXPECT = strdup ("* OK");
198                 QUIT = strdup ("a1 LOGOUT\r\n");
199                 PROTOCOL = TCP_PROTOCOL;
200                 PORT = 143;
201         }
202 #ifdef HAVE_SSL
203         else if (strstr(argv[0],"check_simap")) {
204                 progname = strdup ("check_simap");
205                 SERVICE = strdup ("SIMAP");
206                 SEND=NULL;
207                 EXPECT = strdup ("* OK");
208                 QUIT = strdup ("a1 LOGOUT\r\n");
209                 PROTOCOL=TCP_PROTOCOL;
210                 use_ssl=TRUE;
211                 PORT=993;
212         }
213         else if (strstr(argv[0],"check_spop")) {
214                 progname = strdup ("check_spop");
215                 SERVICE = strdup ("SPOP");
216                 SEND=NULL;
217                 EXPECT = strdup ("+OK");
218                 QUIT = strdup ("QUIT\r\n");
219                 PROTOCOL=TCP_PROTOCOL;
220                 use_ssl=TRUE;
221                 PORT=995;
222         }
223 #endif
224         else if (strstr (argv[0], "check_nntp")) {
225                 progname = strdup ("check_nntp");
226                 SERVICE = strdup ("NNTP");
227                 SEND = NULL;
228                 EXPECT = NULL;
229                 server_expect = realloc (server_expect, ++server_expect_count);
230                 asprintf (&server_expect[server_expect_count - 1], "200");
231                 server_expect = realloc (server_expect, ++server_expect_count);
232                 asprintf (&server_expect[server_expect_count - 1], "201");
233                 asprintf (&QUIT, "QUIT\r\n");
234                 PROTOCOL = TCP_PROTOCOL;
235                 PORT = 119;
236         }
237         else {
238                 usage ("ERROR: Generic check_tcp called with unknown service\n");
239         }
241         server_address = strdup ("127.0.0.1");
242         server_port = PORT;
243         server_send = SEND;
244         server_quit = QUIT;
246         if (process_arguments (argc, argv) == ERROR)
247                 usage ("Could not parse arguments\n");
249         /* use default expect if none listed in process_arguments() */
250         if (EXPECT && server_expect_count == 0) {
251                 server_expect = malloc (++server_expect_count);
252                 server_expect[server_expect_count - 1] = EXPECT;
253         }
255         /* initialize alarm signal handling */
256         signal (SIGALRM, socket_timeout_alarm_handler);
258         /* set socket timeout */
259         alarm (socket_timeout);
261         /* try to connect to the host at the given port number */
262         gettimeofday (&tv, NULL);
263 #ifdef HAVE_SSL
264         if (use_ssl)
265                 result = connect_SSL ();
266         else
267 #endif
268                 {
269                         if (PROTOCOL == UDP_PROTOCOL)
270                                 result = my_udp_connect (server_address, server_port, &sd);
271                         else
272                                 /* default is TCP */
273                                 result = my_tcp_connect (server_address, server_port, &sd);
274                 }
276         if (result == STATE_CRITICAL)
277                 return STATE_CRITICAL;
279         if (server_send != NULL) {              /* Something to send? */
280                 asprintf (&server_send, "%s\r\n", server_send);
281 #ifdef HAVE_SSL
282                 if (use_ssl)
283                         SSL_write(ssl, server_send, strlen (server_send));
284                 else
285 #endif
286                         send (sd, server_send, strlen (server_send), 0);
287         }
289         if (delay > 0) {
290                 tv.tv_sec += delay;
291                 sleep (delay);
292         }
294         if (server_send || server_expect_count > 0) {
296                 buffer = malloc (MAXBUF);
297                 memset (buffer, '\0', MAXBUF);
298                 /* watch for the expect string */
299                 while ((i = my_recv ()) > 0) {
300                         buffer[i] = '\0';
301                         asprintf (&status, "%s%s", status, buffer);
302                         if (buffer[i-2] == '\r' && buffer[i-1] == '\n')
303                                 break;
304                         if (maxbytes>0 && strlen(status)>=maxbytes)
305                                 break;
306                 }
308                 /* return a CRITICAL status if we couldn't read any data */
309                 if (status == NULL)
310                         terminate (STATE_CRITICAL, "No data received from host\n");
312                 strip (status);
314                 if (status && verbose)
315                         printf ("%s\n", status);
317                 if (server_expect_count > 0) {
318                         for (i = 0;; i++) {
319                                 if (verbose)
320                                         printf ("%d %d\n", i, server_expect_count);
321                                 if (i >= server_expect_count)
322                                         terminate (STATE_WARNING, "Invalid response from host\n");
323                                 if (strstr (status, server_expect[i]))
324                                         break;
325                         }
326                 }
327         }
329         if (server_quit != NULL) {
330 #ifdef HAVE_SSL
331                 if (use_ssl) {
332                         SSL_write (ssl, server_quit, strlen (server_quit));
333                         SSL_shutdown (ssl);
334                         SSL_free (ssl);
335                         SSL_CTX_free (ctx);
336                 }
337                 else {
338 #endif
339                         send (sd, server_quit, strlen (server_quit), 0);
340 #ifdef HAVE_SSL
341                 }
342 #endif
343         }
345         /* close the connection */
346         if (sd)
347                 close (sd);
349         elapsed_time = delta_time (tv);
351         if (check_critical_time == TRUE && elapsed_time > critical_time)
352                 result = STATE_CRITICAL;
353         else if (check_warning_time == TRUE && elapsed_time > warning_time)
354                 result = STATE_WARNING;
356         /* reset the alarm */
357         alarm (0);
359         printf
360                 ("%s %s%s - %.3f second response time on port %d",
361                  SERVICE,
362                  state_text (result),
363                  (was_refused) ? " (refused)" : "",
364                  elapsed_time, server_port);
366         if (status && strlen(status) > 0)
367                 printf (" [%s]", status);
369         printf ("|time=%.3f\n", elapsed_time);
371         return result;
373 \f
377 /* process command-line arguments */
378 int
379 process_arguments (int argc, char **argv)
381         int c;
383         int option_index = 0;
384         static struct option long_options[] = {
385                 {"hostname", required_argument, 0, 'H'},
386                 {"critical-time", required_argument, 0, 'c'},
387                 {"warning-time", required_argument, 0, 'w'},
388                 {"critical-codes", required_argument, 0, 'C'},
389                 {"warning-codes", required_argument, 0, 'W'},
390                 {"timeout", required_argument, 0, 't'},
391                 {"protocol", required_argument, 0, 'P'},
392                 {"port", required_argument, 0, 'p'},
393                 {"send", required_argument, 0, 's'},
394                 {"expect", required_argument, 0, 'e'},
395                 {"maxbytes", required_argument, 0, 'm'},
396                 {"quit", required_argument, 0, 'q'},
397                 {"delay", required_argument, 0, 'd'},
398                 {"refuse", required_argument, 0, 'r'},
399                 {"use-ipv4", no_argument, 0, '4'},
400                 {"use-ipv6", no_argument, 0, '6'},
401                 {"verbose", no_argument, 0, 'v'},
402                 {"version", no_argument, 0, 'V'},
403                 {"help", no_argument, 0, 'h'},
404                 {0, 0, 0, 0}
405         };
407         if (argc < 2)
408                 usage ("No arguments found\n");
410         /* backwards compatibility */
411         for (c = 1; c < argc; c++) {
412                 if (strcmp ("-to", argv[c]) == 0)
413                         strcpy (argv[c], "-t");
414                 else if (strcmp ("-wt", argv[c]) == 0)
415                         strcpy (argv[c], "-w");
416                 else if (strcmp ("-ct", argv[c]) == 0)
417                         strcpy (argv[c], "-c");
418         }
420         if (!is_option (argv[1])) {
421                 server_address = argv[1];
422                 argv[1] = argv[0];
423                 argv = &argv[1];
424                 argc--;
425         }
427         while (1) {
428                 c = getopt_long (argc, argv, "+hVv46H:s:e:q:m:c:w:t:p:C:W:d:Sr:",
429                                  long_options, &option_index);
431                 if (c == -1 || c == EOF || c == 1)
432                         break;
434                 switch (c) {
435                 case '?':                 /* print short usage statement if args not parsable */
436                         printf ("%s: Unknown argument: %s\n\n", progname, optarg);
437                         print_usage ();
438                         exit (STATE_UNKNOWN);
439                 case 'h':                 /* help */
440                         print_help ();
441                         exit (STATE_OK);
442                 case 'V':                 /* version */
443                         print_revision (progname, "$Revision$");
444                         exit (STATE_OK);
445                 case 'v':                 /* verbose mode */
446                         verbose = TRUE;
447                         break;
448                 case '4':
449                         address_family = AF_INET;
450                         break;
451                 case '6':
452 #ifdef USE_IPV6
453                         address_family = AF_INET6;
454 #else
455                         usage ("IPv6 support not available\n");
456 #endif
457                         break;
458                 case 'H':                 /* hostname */
459                         if (is_host (optarg) == FALSE)
460                                 usage2 ("invalid host name or address", optarg);
461                         server_address = optarg;
462                         break;
463                 case 'c':                 /* critical */
464                         if (!is_intnonneg (optarg))
465                                 usage ("Critical threshold must be a nonnegative integer\n");
466                         critical_time = strtod (optarg, NULL);
467                         check_critical_time = TRUE;
468                         break;
469                 case 'w':                 /* warning */
470                         if (!is_intnonneg (optarg))
471                                 usage ("Warning threshold must be a nonnegative integer\n");
472                         warning_time = strtod (optarg, NULL);
473                         check_warning_time = TRUE;
474                         break;
475                 case 'C':
476                         crit_codes = realloc (crit_codes, ++crit_codes_count);
477                         crit_codes[crit_codes_count - 1] = optarg;
478                         break;
479                 case 'W':
480                         warn_codes = realloc (warn_codes, ++warn_codes_count);
481                         warn_codes[warn_codes_count - 1] = optarg;
482                         break;
483                 case 't':                 /* timeout */
484                         if (!is_intpos (optarg))
485                                 usage ("Timeout interval must be a positive integer\n");
486                         socket_timeout = atoi (optarg);
487                         break;
488                 case 'p':                 /* port */
489                         if (!is_intpos (optarg))
490                                 usage ("Server port must be a positive integer\n");
491                         server_port = atoi (optarg);
492                         break;
493                 case 's':
494                         server_send = optarg;
495                         break;
496                 case 'e': /* expect string (may be repeated) */
497                         EXPECT = NULL;
498                         if (server_expect_count == 0)
499                                 server_expect = malloc (++server_expect_count);
500                         else
501                                 server_expect = realloc (server_expect, ++server_expect_count);
502                         server_expect[server_expect_count - 1] = optarg;
503                         break;
504                 case 'm':
505                         if (!is_intpos (optarg))
506                                 usage ("Maxbytes must be a positive integer\n");
507                         maxbytes = atoi (optarg);
508                 case 'q':
509                         server_quit = optarg;
510                         break;
511                 case 'r':
512                         if (!strncmp(optarg,"ok",2))
513                                 econn_refuse_state = STATE_OK;
514                         else if (!strncmp(optarg,"warn",4))
515                                 econn_refuse_state = STATE_WARNING;
516                         else if (!strncmp(optarg,"crit",4))
517                                 econn_refuse_state = STATE_CRITICAL;
518                         else
519                                 usage ("Refuse mut be one of ok, warn, crit\n");
520                         break;
521                 case 'd':
522                         if (is_intpos (optarg))
523                                 delay = atoi (optarg);
524                         else
525                                 usage ("Delay must be a positive integer\n");
526                         break;
527                 case 'S':
528 #ifndef HAVE_SSL
529                         terminate (STATE_UNKNOWN,
530                                 "SSL support not available. Install OpenSSL and recompile.");
531 #endif
532                         use_ssl = TRUE;
533                         break;
534                 }
535         }
537         if (server_address == NULL)
538                 usage ("You must provide a server address\n");
540         return OK;
542 \f
546 void
547 print_help (void)
549         print_revision (progname, revision);
550         printf ("Copyright (c) %s %s\n\t<%s>\n\n", copyright, authors, email);
551         printf (summary, SERVICE);
552         print_usage ();
553         printf ("\nOptions:\n");
554         printf (options, DEFAULT_SOCKET_TIMEOUT);
555         printf (standard_options);
556         support ();
559 void
560 print_usage (void)
562         printf ("Usage: %s %s\n", progname, option_summary);
563         printf ("       %s (-h|--help)\n", progname);
564         printf ("       %s (-V|--version)\n", progname);
566 \f
570 #ifdef HAVE_SSL
571 int
572 connect_SSL (void)
574   SSL_METHOD *meth;
576   /* Initialize SSL context */
577   SSLeay_add_ssl_algorithms ();
578   meth = SSLv2_client_method ();
579   SSL_load_error_strings ();
580   if ((ctx = SSL_CTX_new (meth)) == NULL)
581     {
582       printf ("ERROR: Cannot create SSL context.\n");
583       return STATE_CRITICAL;
584     }
586   /* Initialize alarm signal handling */
587   signal (SIGALRM, socket_timeout_alarm_handler);
589   /* Set socket timeout */
590   alarm (socket_timeout);
592   /* Save start time */
593   time (&start_time);
595   /* Make TCP connection */
596   if (my_tcp_connect (server_address, server_port, &sd) == STATE_OK && was_refused == FALSE)
597     {
598     /* Do the SSL handshake */
599       if ((ssl = SSL_new (ctx)) != NULL)
600       {
601         SSL_set_fd (ssl, sd);
602         if (SSL_connect (ssl) != -1)
603           return OK;
604         ERR_print_errors_fp (stderr);
605       }
606       else
607       {
608         printf ("ERROR: Cannot initiate SSL handshake.\n");
609       }
610       SSL_free (ssl);
611     }
613   SSL_CTX_free (ctx);
614   close (sd);
616   return STATE_CRITICAL;
618 #endif
622 int
623 my_recv (void)
625         int i;
627 #ifdef HAVE_SSL
628         if (use_ssl) {
629                 i = SSL_read (ssl, buffer, MAXBUF - 1);
630         }
631         else {
632 #endif
633                 i = read (sd, buffer, MAXBUF - 1);
634 #ifdef HAVE_SSL
635         }
636 #endif
638         return i;