Code

markup for translation
[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 = "1999-2003";
91 const char *email = "nagiosplug-devel@lists.sourceforge.net";
92 \f
96 void
97 print_usage (void)
98 {
99         printf (_("\
100 Usage: %s -H host -p port [-w <warning time>] [-c <critical time>]\n\
101   [-s <send string>] [-e <expect string>] [-q <quit string>]\n\
102   [-m <maximum bytes>] [-d <delay>] [-t <timeout seconds>]\n\
103   [-r <refuse state>] [-v] [-4|-6]\n"), progname);
104         printf ("       %s (-h|--help)\n", progname);
105         printf ("       %s (-V|--version)\n", progname);
107 void
108 print_help (void)
110         print_revision (progname, revision);
112         printf (_(COPYRIGHT), copyright, email);
114         printf (_("This plugin tests %s connections with the specified host.\n\n"),
115                 SERVICE);
117         print_usage ();
119         printf (_(UT_HELP_VRSN));
121         printf (_(UT_HOST_PORT), 'p', "none");
123         printf (_(UT_IPv46));
125         printf (_("\
126  -s, --send=STRING\n\
127     String to send to the server\n\
128  -e, --expect=STRING\n\
129     String to expect in server response\n\
130  -q, --quit=STRING\n\
131     String to send server to initiate a clean close of the connection\n"));
133         printf (_("\
134  -r, --refuse=ok|warn|crit\n\
135     Accept tcp refusals with states ok, warn, crit (default: crit)\n\
136  -m, --maxbytes=INTEGER\n\
137     Close connection once more than this number of bytes are received\n\
138  -d, --delay=INTEGER\n\
139     Seconds to wait between sending string and polling for response\n"));
141         printf (_(UT_WARN_CRIT));
143         printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
145         printf (_(UT_VERBOSE));
147         printf (_(UT_SUPPORT));
149 \f
152 int
153 main (int argc, char **argv)
155         int result;
156         int i;
157         char *status = "";
158         struct timeval tv;
160         setlocale (LC_ALL, "");
161         bindtextdomain (PACKAGE, LOCALEDIR);
162         textdomain (PACKAGE);
164         if (strstr (argv[0], "check_udp")) {
165                 progname = strdup ("check_udp");
166                 SERVICE = strdup ("UDP");
167                 SEND = NULL;
168                 EXPECT = NULL;
169                 QUIT = NULL;
170                 PROTOCOL = UDP_PROTOCOL;
171                 PORT = 0;
172         }
173         else if (strstr (argv[0], "check_tcp")) {
174                 progname = strdup ("check_tcp");
175                 SERVICE = strdup ("TCP");
176                 SEND = NULL;
177                 EXPECT = NULL;
178                 QUIT = NULL;
179                 PROTOCOL = TCP_PROTOCOL;
180                 PORT = 0;
181         }
182         else if (strstr (argv[0], "check_ftp")) {
183                 progname = strdup ("check_ftp");
184                 SERVICE = strdup ("FTP");
185                 SEND = NULL;
186                 EXPECT = strdup ("220");
187                 QUIT = strdup ("QUIT\r\n");
188                 PROTOCOL = TCP_PROTOCOL;
189                 PORT = 21;
190         }
191         else if (strstr (argv[0], "check_smtp")) {
192                 progname = strdup ("check_smtp");
193                 SERVICE = strdup ("SMTP");
194                 SEND = NULL;
195                 EXPECT = strdup ("220");
196                 QUIT = strdup ("QUIT\r\n");
197                 PROTOCOL = TCP_PROTOCOL;
198                 PORT = 25;
199         }
200         else if (strstr (argv[0], "check_pop")) {
201                 progname = strdup ("check_pop");
202                 SERVICE = strdup ("POP");
203                 SEND = NULL;
204                 EXPECT = strdup ("+OK");
205                 QUIT = strdup ("QUIT\r\n");
206                 PROTOCOL = TCP_PROTOCOL;
207                 PORT = 110;
208         }
209         else if (strstr (argv[0], "check_imap")) {
210                 progname = strdup ("check_imap");
211                 SERVICE = strdup ("IMAP");
212                 SEND = NULL;
213                 EXPECT = strdup ("* OK");
214                 QUIT = strdup ("a1 LOGOUT\r\n");
215                 PROTOCOL = TCP_PROTOCOL;
216                 PORT = 143;
217         }
218 #ifdef HAVE_SSL
219         else if (strstr(argv[0],"check_simap")) {
220                 progname = strdup ("check_simap");
221                 SERVICE = strdup ("SIMAP");
222                 SEND=NULL;
223                 EXPECT = strdup ("* OK");
224                 QUIT = strdup ("a1 LOGOUT\r\n");
225                 PROTOCOL=TCP_PROTOCOL;
226                 use_ssl=TRUE;
227                 PORT=993;
228         }
229         else if (strstr(argv[0],"check_spop")) {
230                 progname = strdup ("check_spop");
231                 SERVICE = strdup ("SPOP");
232                 SEND=NULL;
233                 EXPECT = strdup ("+OK");
234                 QUIT = strdup ("QUIT\r\n");
235                 PROTOCOL=TCP_PROTOCOL;
236                 use_ssl=TRUE;
237                 PORT=995;
238         }
239 #endif
240         else if (strstr (argv[0], "check_nntp")) {
241                 progname = strdup ("check_nntp");
242                 SERVICE = strdup ("NNTP");
243                 SEND = NULL;
244                 EXPECT = NULL;
245                 server_expect = realloc (server_expect, ++server_expect_count);
246                 asprintf (&server_expect[server_expect_count - 1], "200");
247                 server_expect = realloc (server_expect, ++server_expect_count);
248                 asprintf (&server_expect[server_expect_count - 1], "201");
249                 asprintf (&QUIT, "QUIT\r\n");
250                 PROTOCOL = TCP_PROTOCOL;
251                 PORT = 119;
252         }
253         else {
254                 usage (_("ERROR: Generic check_tcp called with unknown service\n"));
255         }
257         server_address = strdup ("127.0.0.1");
258         server_port = PORT;
259         server_send = SEND;
260         server_quit = QUIT;
262         if (process_arguments (argc, argv) == ERROR)
263                 usage (_("Could not parse arguments\n"));
265         /* use default expect if none listed in process_arguments() */
266         if (EXPECT && server_expect_count == 0) {
267                 server_expect = malloc (++server_expect_count);
268                 server_expect[server_expect_count - 1] = EXPECT;
269         }
271         /* initialize alarm signal handling */
272         signal (SIGALRM, socket_timeout_alarm_handler);
274         /* set socket timeout */
275         alarm (socket_timeout);
277         /* try to connect to the host at the given port number */
278         gettimeofday (&tv, NULL);
279 #ifdef HAVE_SSL
280         if (use_ssl)
281                 result = connect_SSL ();
282         else
283 #endif
284                 {
285                         if (PROTOCOL == UDP_PROTOCOL)
286                                 result = my_udp_connect (server_address, server_port, &sd);
287                         else
288                                 /* default is TCP */
289                                 result = my_tcp_connect (server_address, server_port, &sd);
290                 }
292         if (result == STATE_CRITICAL)
293                 return STATE_CRITICAL;
295         if (server_send != NULL) {              /* Something to send? */
296                 asprintf (&server_send, "%s\r\n", server_send);
297 #ifdef HAVE_SSL
298                 if (use_ssl)
299                         SSL_write(ssl, server_send, strlen (server_send));
300                 else
301 #endif
302                         send (sd, server_send, strlen (server_send), 0);
303         }
305         if (delay > 0) {
306                 tv.tv_sec += delay;
307                 sleep (delay);
308         }
310         if (server_send || server_expect_count > 0) {
312                 buffer = malloc (MAXBUF);
313                 memset (buffer, '\0', MAXBUF);
314                 /* watch for the expect string */
315                 while ((i = my_recv ()) > 0) {
316                         buffer[i] = '\0';
317                         asprintf (&status, "%s%s", status, buffer);
318                         if (buffer[i-2] == '\r' && buffer[i-1] == '\n')
319                                 break;
320                         if (maxbytes>0 && strlen(status) >= (unsigned)maxbytes)
321                                 break;
322                 }
324                 /* return a CRITICAL status if we couldn't read any data */
325                 if (status == NULL)
326                         terminate (STATE_CRITICAL, _("No data received from host\n"));
328                 strip (status);
330                 if (status && verbose)
331                         printf ("%s\n", status);
333                 if (server_expect_count > 0) {
334                         for (i = 0;; i++) {
335                                 if (verbose)
336                                         printf ("%d %d\n", i, server_expect_count);
337                                 if (i >= server_expect_count)
338                                         terminate (STATE_WARNING, _("Invalid response from host\n"));
339                                 if (strstr (status, server_expect[i]))
340                                         break;
341                         }
342                 }
343         }
345         if (server_quit != NULL) {
346 #ifdef HAVE_SSL
347                 if (use_ssl) {
348                         SSL_write (ssl, server_quit, strlen (server_quit));
349                         SSL_shutdown (ssl);
350                         SSL_free (ssl);
351                         SSL_CTX_free (ctx);
352                 }
353                 else {
354 #endif
355                         send (sd, server_quit, strlen (server_quit), 0);
356 #ifdef HAVE_SSL
357                 }
358 #endif
359         }
361         /* close the connection */
362         if (sd)
363                 close (sd);
365         elapsed_time = delta_time (tv);
367         if (check_critical_time == TRUE && elapsed_time > critical_time)
368                 result = STATE_CRITICAL;
369         else if (check_warning_time == TRUE && elapsed_time > warning_time)
370                 result = STATE_WARNING;
372         /* reset the alarm */
373         alarm (0);
375         printf
376                 (_("%s %s%s - %.3f second response time on port %d"),
377                  SERVICE,
378                  state_text (result),
379                  (was_refused) ? " (refused)" : "",
380                  elapsed_time, server_port);
382         if (status && strlen(status) > 0)
383                 printf (" [%s]", status);
385         printf ("|time=%.3f\n", elapsed_time);
387         return result;
389 \f
393 /* process command-line arguments */
394 int
395 process_arguments (int argc, char **argv)
397         int c;
399         int option_index = 0;
400         static struct option long_options[] = {
401                 {"hostname", required_argument, 0, 'H'},
402                 {"critical-time", required_argument, 0, 'c'},
403                 {"warning-time", required_argument, 0, 'w'},
404                 {"critical-codes", required_argument, 0, 'C'},
405                 {"warning-codes", required_argument, 0, 'W'},
406                 {"timeout", required_argument, 0, 't'},
407                 {"protocol", required_argument, 0, 'P'},
408                 {"port", required_argument, 0, 'p'},
409                 {"send", required_argument, 0, 's'},
410                 {"expect", required_argument, 0, 'e'},
411                 {"maxbytes", required_argument, 0, 'm'},
412                 {"quit", required_argument, 0, 'q'},
413                 {"delay", required_argument, 0, 'd'},
414                 {"refuse", required_argument, 0, 'r'},
415                 {"use-ipv4", no_argument, 0, '4'},
416                 {"use-ipv6", no_argument, 0, '6'},
417                 {"verbose", no_argument, 0, 'v'},
418                 {"version", no_argument, 0, 'V'},
419                 {"help", no_argument, 0, 'h'},
420                 {0, 0, 0, 0}
421         };
423         if (argc < 2)
424                 usage ("No arguments found\n");
426         /* backwards compatibility */
427         for (c = 1; c < argc; c++) {
428                 if (strcmp ("-to", argv[c]) == 0)
429                         strcpy (argv[c], "-t");
430                 else if (strcmp ("-wt", argv[c]) == 0)
431                         strcpy (argv[c], "-w");
432                 else if (strcmp ("-ct", argv[c]) == 0)
433                         strcpy (argv[c], "-c");
434         }
436         if (!is_option (argv[1])) {
437                 server_address = argv[1];
438                 argv[1] = argv[0];
439                 argv = &argv[1];
440                 argc--;
441         }
443         while (1) {
444                 c = getopt_long (argc, argv, "+hVv46H:s:e:q:m:c:w:t:p:C:W:d:Sr:",
445                                  long_options, &option_index);
447                 if (c == -1 || c == EOF || c == 1)
448                         break;
450                 switch (c) {
451                 case '?':                 /* print short usage statement if args not parsable */
452                         printf (_("%s: Unknown argument: %s\n\n"), progname, optarg);
453                         print_usage ();
454                         exit (STATE_UNKNOWN);
455                 case 'h':                 /* help */
456                         print_help ();
457                         exit (STATE_OK);
458                 case 'V':                 /* version */
459                         print_revision (progname, "$Revision$");
460                         exit (STATE_OK);
461                 case 'v':                 /* verbose mode */
462                         verbose = TRUE;
463                         break;
464                 case '4':
465                         address_family = AF_INET;
466                         break;
467                 case '6':
468 #ifdef USE_IPV6
469                         address_family = AF_INET6;
470 #else
471                         usage (_("IPv6 support not available\n"));
472 #endif
473                         break;
474                 case 'H':                 /* hostname */
475                         if (is_host (optarg) == FALSE)
476                                 usage2 (_("invalid host name or address"), optarg);
477                         server_address = optarg;
478                         break;
479                 case 'c':                 /* critical */
480                         if (!is_intnonneg (optarg))
481                                 usage (_("Critical threshold must be a nonnegative integer\n"));
482                         critical_time = strtod (optarg, NULL);
483                         check_critical_time = TRUE;
484                         break;
485                 case 'w':                 /* warning */
486                         if (!is_intnonneg (optarg))
487                                 usage (_("Warning threshold must be a nonnegative integer\n"));
488                         warning_time = strtod (optarg, NULL);
489                         check_warning_time = TRUE;
490                         break;
491                 case 'C':
492                         crit_codes = realloc (crit_codes, ++crit_codes_count);
493                         crit_codes[crit_codes_count - 1] = optarg;
494                         break;
495                 case 'W':
496                         warn_codes = realloc (warn_codes, ++warn_codes_count);
497                         warn_codes[warn_codes_count - 1] = optarg;
498                         break;
499                 case 't':                 /* timeout */
500                         if (!is_intpos (optarg))
501                                 usage (_("Timeout interval must be a positive integer\n"));
502                         socket_timeout = atoi (optarg);
503                         break;
504                 case 'p':                 /* port */
505                         if (!is_intpos (optarg))
506                                 usage (_("Server port must be a positive integer\n"));
507                         server_port = atoi (optarg);
508                         break;
509                 case 's':
510                         server_send = optarg;
511                         break;
512                 case 'e': /* expect string (may be repeated) */
513                         EXPECT = NULL;
514                         if (server_expect_count == 0)
515                                 server_expect = malloc (++server_expect_count);
516                         else
517                                 server_expect = realloc (server_expect, ++server_expect_count);
518                         server_expect[server_expect_count - 1] = optarg;
519                         break;
520                 case 'm':
521                         if (!is_intpos (optarg))
522                                 usage (_("Maxbytes must be a positive integer\n"));
523                         maxbytes = atoi (optarg);
524                 case 'q':
525                         server_quit = optarg;
526                         break;
527                 case 'r':
528                         if (!strncmp(optarg,"ok",2))
529                                 econn_refuse_state = STATE_OK;
530                         else if (!strncmp(optarg,"warn",4))
531                                 econn_refuse_state = STATE_WARNING;
532                         else if (!strncmp(optarg,"crit",4))
533                                 econn_refuse_state = STATE_CRITICAL;
534                         else
535                                 usage (_("Refuse mut be one of ok, warn, crit\n"));
536                         break;
537                 case 'd':
538                         if (is_intpos (optarg))
539                                 delay = atoi (optarg);
540                         else
541                                 usage (_("Delay must be a positive integer\n"));
542                         break;
543                 case 'S':
544 #ifndef HAVE_SSL
545                         terminate (STATE_UNKNOWN,
546                                 _("SSL support not available. Install OpenSSL and recompile."));
547 #endif
548                         use_ssl = TRUE;
549                         break;
550                 }
551         }
553         if (server_address == NULL)
554                 usage (_("You must provide a server address\n"));
556         return OK;
558 \f
560 #ifdef HAVE_SSL
561 int
562 connect_SSL (void)
564   SSL_METHOD *meth;
566   /* Initialize SSL context */
567   SSLeay_add_ssl_algorithms ();
568   meth = SSLv2_client_method ();
569   SSL_load_error_strings ();
570   if ((ctx = SSL_CTX_new (meth)) == NULL)
571     {
572       printf (_("ERROR: Cannot create SSL context.\n"));
573       return STATE_CRITICAL;
574     }
576   /* Initialize alarm signal handling */
577   signal (SIGALRM, socket_timeout_alarm_handler);
579   /* Set socket timeout */
580   alarm (socket_timeout);
582   /* Save start time */
583   time (&start_time);
585   /* Make TCP connection */
586   if (my_tcp_connect (server_address, server_port, &sd) == STATE_OK && was_refused == FALSE)
587     {
588     /* Do the SSL handshake */
589       if ((ssl = SSL_new (ctx)) != NULL)
590       {
591         SSL_set_fd (ssl, sd);
592         if (SSL_connect (ssl) != -1)
593           return OK;
594         ERR_print_errors_fp (stderr);
595       }
596       else
597       {
598         printf (_("ERROR: Cannot initiate SSL handshake.\n"));
599       }
600       SSL_free (ssl);
601     }
603   SSL_CTX_free (ctx);
604   close (sd);
606   return STATE_CRITICAL;
608 #endif
612 int
613 my_recv (void)
615         int i;
617 #ifdef HAVE_SSL
618         if (use_ssl) {
619                 i = SSL_read (ssl, buffer, MAXBUF - 1);
620         }
621         else {
622 #endif
623                 i = read (sd, buffer, MAXBUF - 1);
624 #ifdef HAVE_SSL
625         }
626 #endif
628         return i;