Code

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