Code

=fix segfault on malloc of server_expect for multibyte chars (David Croft)
[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 *****************************************************************************/
19 /* progname "check_tcp" changes depending on symlink called */
20 char *progname;
21 const char *revision = "$Revision$";
22 const char *copyright = "1999-2003";
23 const char *email = "nagiosplug-devel@lists.sourceforge.net";
25 #include "common.h"
26 #include "netutils.h"
27 #include "utils.h"
29 #ifdef HAVE_SSL_H
30 #  include <rsa.h>
31 #  include <crypto.h>
32 #  include <x509.h>
33 #  include <pem.h>
34 #  include <ssl.h>
35 #  include <err.h>
36 #else
37 #  ifdef HAVE_OPENSSL_SSL_H
38 #    include <openssl/rsa.h>
39 #    include <openssl/crypto.h>
40 #    include <openssl/x509.h>
41 #    include <openssl/pem.h>
42 #    include <openssl/ssl.h>
43 #    include <openssl/err.h>
44 #  endif
45 #endif
47 #ifdef HAVE_SSL
48 SSL_CTX *ctx;
49 SSL *ssl;
50 int connect_SSL (void);
51 #endif
53 enum {
54         TCP_PROTOCOL = 1,
55         UDP_PROTOCOL = 2,
56         MAXBUF = 1024
57 };
59 int process_arguments (int, char **);
60 int my_recv (void);
61 void print_help (void);
62 void print_usage (void);
64 char *SERVICE = NULL;
65 char *SEND = NULL;
66 char *EXPECT = NULL;
67 char *QUIT = NULL;
68 int PROTOCOL = 0;
69 int PORT = 0;
71 int server_port = 0;
72 char *server_address = NULL;
73 char *server_send = NULL;
74 char *server_quit = NULL;
75 char **server_expect = NULL;
76 size_t server_expect_count = 0;
77 int maxbytes = 0;
78 char **warn_codes = NULL;
79 size_t warn_codes_count = 0;
80 char **crit_codes = NULL;
81 size_t crit_codes_count = 0;
82 unsigned int delay = 0;
83 double warning_time = 0;
84 int check_warning_time = FALSE;
85 double critical_time = 0;
86 int check_critical_time = FALSE;
87 double elapsed_time = 0;
88 long microsec;
89 int verbose = FALSE;
90 int use_ssl = FALSE;
91 int sd = 0;
92 char *buffer;
98 \f
99 int
100 main (int argc, char **argv)
102         int result;
103         int i;
104         char *status;
105         struct timeval tv;
107         setlocale (LC_ALL, "");
108         bindtextdomain (PACKAGE, LOCALEDIR);
109         textdomain (PACKAGE);
111         if (strstr (argv[0], "check_udp")) {
112                 progname = strdup ("check_udp");
113                 SERVICE = strdup ("UDP");
114                 SEND = NULL;
115                 EXPECT = NULL;
116                 QUIT = NULL;
117                 PROTOCOL = UDP_PROTOCOL;
118                 PORT = 0;
119         }
120         else if (strstr (argv[0], "check_tcp")) {
121                 progname = strdup ("check_tcp");
122                 SERVICE = strdup ("TCP");
123                 SEND = NULL;
124                 EXPECT = NULL;
125                 QUIT = NULL;
126                 PROTOCOL = TCP_PROTOCOL;
127                 PORT = 0;
128         }
129         else if (strstr (argv[0], "check_ftp")) {
130                 progname = strdup ("check_ftp");
131                 SERVICE = strdup ("FTP");
132                 SEND = NULL;
133                 EXPECT = strdup ("220");
134                 QUIT = strdup ("QUIT\r\n");
135                 PROTOCOL = TCP_PROTOCOL;
136                 PORT = 21;
137         }
138         else if (strstr (argv[0], "check_smtp")) {
139                 progname = strdup ("check_smtp");
140                 SERVICE = strdup ("SMTP");
141                 SEND = NULL;
142                 EXPECT = strdup ("220");
143                 QUIT = strdup ("QUIT\r\n");
144                 PROTOCOL = TCP_PROTOCOL;
145                 PORT = 25;
146         }
147         else if (strstr (argv[0], "check_pop")) {
148                 progname = strdup ("check_pop");
149                 SERVICE = strdup ("POP");
150                 SEND = NULL;
151                 EXPECT = strdup ("+OK");
152                 QUIT = strdup ("QUIT\r\n");
153                 PROTOCOL = TCP_PROTOCOL;
154                 PORT = 110;
155         }
156         else if (strstr (argv[0], "check_imap")) {
157                 progname = strdup ("check_imap");
158                 SERVICE = strdup ("IMAP");
159                 SEND = NULL;
160                 EXPECT = strdup ("* OK");
161                 QUIT = strdup ("a1 LOGOUT\r\n");
162                 PROTOCOL = TCP_PROTOCOL;
163                 PORT = 143;
164         }
165 #ifdef HAVE_SSL
166         else if (strstr(argv[0],"check_simap")) {
167                 progname = strdup ("check_simap");
168                 SERVICE = strdup ("SIMAP");
169                 SEND=NULL;
170                 EXPECT = strdup ("* OK");
171                 QUIT = strdup ("a1 LOGOUT\r\n");
172                 PROTOCOL=TCP_PROTOCOL;
173                 use_ssl=TRUE;
174                 PORT=993;
175         }
176         else if (strstr(argv[0],"check_spop")) {
177                 progname = strdup ("check_spop");
178                 SERVICE = strdup ("SPOP");
179                 SEND=NULL;
180                 EXPECT = strdup ("+OK");
181                 QUIT = strdup ("QUIT\r\n");
182                 PROTOCOL=TCP_PROTOCOL;
183                 use_ssl=TRUE;
184                 PORT=995;
185         }
186 #endif
187         else if (strstr (argv[0], "check_nntp")) {
188                 progname = strdup ("check_nntp");
189                 SERVICE = strdup ("NNTP");
190                 SEND = NULL;
191                 EXPECT = NULL;
192                 server_expect = realloc (server_expect, sizeof (char *) * (++server_expect_count));
193                 asprintf (&server_expect[server_expect_count - 1], "200");
194                 server_expect = realloc (server_expect, sizeof (char *) * (++server_expect_count));
195                 asprintf (&server_expect[server_expect_count - 1], "201");
196                 asprintf (&QUIT, "QUIT\r\n");
197                 PROTOCOL = TCP_PROTOCOL;
198                 PORT = 119;
199         }
200         else {
201                 progname = strdup ("check_tcp");
202                 usage (_("ERROR: Generic check_tcp called with unknown service\n"));
203         }
205         server_address = strdup ("127.0.0.1");
206         server_port = PORT;
207         server_send = SEND;
208         server_quit = QUIT;
210         if (process_arguments (argc, argv) == ERROR)
211                 usage (_("Could not parse arguments\n"));
213         /* use default expect if none listed in process_arguments() */
214         if (EXPECT && server_expect_count == 0) {
215                 server_expect = malloc (sizeof (char *) * (++server_expect_count));
216                 server_expect[server_expect_count - 1] = EXPECT;
217         }
219         /* initialize alarm signal handling */
220         signal (SIGALRM, socket_timeout_alarm_handler);
222         /* set socket timeout */
223         alarm (socket_timeout);
225         /* try to connect to the host at the given port number */
226         gettimeofday (&tv, NULL);
227 #ifdef HAVE_SSL
228         if (use_ssl)
229                 result = connect_SSL ();
230         else
231 #endif
232                 {
233                         if (PROTOCOL == UDP_PROTOCOL)
234                                 result = my_udp_connect (server_address, server_port, &sd);
235                         else
236                                 /* default is TCP */
237                                 result = my_tcp_connect (server_address, server_port, &sd);
238                 }
240         if (result == STATE_CRITICAL)
241                 return STATE_CRITICAL;
243         if (server_send != NULL) {              /* Something to send? */
244                 asprintf (&server_send, "%s\r\n", server_send);
245 #ifdef HAVE_SSL
246                 if (use_ssl)
247                         SSL_write(ssl, server_send, (int)strlen(server_send));
248                 else
249 #endif
250                         send (sd, server_send, strlen(server_send), 0);
251         }
253         if (delay > 0) {
254                 tv.tv_sec += delay;
255                 sleep (delay);
256         }
258         if (server_send || server_expect_count > 0) {
260                 buffer = malloc (MAXBUF);
261                 memset (buffer, '\0', MAXBUF);
262                 status = strdup ("");
263                 /* watch for the expect string */
264                 while ((i = my_recv ()) > 0) {
265                         buffer[i] = '\0';
266                         asprintf (&status, "%s%s", status, buffer);
267                         if (buffer[i-2] == '\r' && buffer[i-1] == '\n')
268                                 break;
269                         if (maxbytes>0 && strlen(status) >= (unsigned)maxbytes)
270                                 break;
271                 }
273                 /* return a CRITICAL status if we couldn't read any data */
274                 if (status == NULL)
275                         die (STATE_CRITICAL, _("No data received from host\n"));
277                 strip (status);
279                 if (status && verbose)
280                         printf ("%s\n", status);
282                 if (server_expect_count > 0) {
283                         for (i = 0;; i++) {
284                                 if (verbose)
285                                         printf ("%d %d\n", i, (int)server_expect_count);
286                                 if (i >= (int)server_expect_count)
287                                         die (STATE_WARNING, _("Invalid response from host\n"));
288                                 if (strstr (status, server_expect[i]))
289                                         break;
290                         }
291                 }
292         }
294         if (server_quit != NULL) {
295 #ifdef HAVE_SSL
296                 if (use_ssl) {
297                         SSL_write (ssl, server_quit, (int)strlen(server_quit));
298                         SSL_shutdown (ssl);
299                         SSL_free (ssl);
300                         SSL_CTX_free (ctx);
301                 }
302                 else {
303 #endif
304                         send (sd, server_quit, strlen (server_quit), 0);
305 #ifdef HAVE_SSL
306                 }
307 #endif
308         }
310         /* close the connection */
311         if (sd)
312                 close (sd);
314         microsec = deltime (tv);
315         elapsed_time = (double)microsec / 1.0e6;
317         if (check_critical_time == TRUE && elapsed_time > critical_time)
318                 result = STATE_CRITICAL;
319         else if (check_warning_time == TRUE && elapsed_time > warning_time)
320                 result = STATE_WARNING;
322         /* reset the alarm */
323         alarm (0);
325         printf
326                 (_("%s %s%s - %.3f second response time on port %d"),
327                  SERVICE,
328                  state_text (result),
329                  (was_refused) ? " (refused)" : "",
330                  elapsed_time, server_port);
332         if (status && strlen(status) > 0)
333                 printf (" [%s]", status);
335         printf (" |%s\n", perfdata ("time", microsec, "us",
336                 TRUE, warning_time*1000,
337                 TRUE, critical_time*1000,
338                 TRUE, 0,
339                 TRUE, socket_timeout*1000));
341         return result;
343 \f
347 /* process command-line arguments */
348 int
349 process_arguments (int argc, char **argv)
351         int c;
353         int option = 0;
354         static struct option longopts[] = {
355                 {"hostname", required_argument, 0, 'H'},
356                 {"critical-time", required_argument, 0, 'c'},
357                 {"warning-time", required_argument, 0, 'w'},
358                 {"critical-codes", required_argument, 0, 'C'},
359                 {"warning-codes", required_argument, 0, 'W'},
360                 {"timeout", required_argument, 0, 't'},
361                 {"protocol", required_argument, 0, 'P'},
362                 {"port", required_argument, 0, 'p'},
363                 {"send", required_argument, 0, 's'},
364                 {"expect", required_argument, 0, 'e'},
365                 {"maxbytes", required_argument, 0, 'm'},
366                 {"quit", required_argument, 0, 'q'},
367                 {"delay", required_argument, 0, 'd'},
368                 {"refuse", required_argument, 0, 'r'},
369                 {"use-ipv4", no_argument, 0, '4'},
370                 {"use-ipv6", no_argument, 0, '6'},
371                 {"verbose", no_argument, 0, 'v'},
372                 {"version", no_argument, 0, 'V'},
373                 {"help", no_argument, 0, 'h'},
374                 {0, 0, 0, 0}
375         };
377         if (argc < 2)
378                 usage ("No arguments found\n");
380         /* backwards compatibility */
381         for (c = 1; c < argc; c++) {
382                 if (strcmp ("-to", argv[c]) == 0)
383                         strcpy (argv[c], "-t");
384                 else if (strcmp ("-wt", argv[c]) == 0)
385                         strcpy (argv[c], "-w");
386                 else if (strcmp ("-ct", argv[c]) == 0)
387                         strcpy (argv[c], "-c");
388         }
390         if (!is_option (argv[1])) {
391                 server_address = argv[1];
392                 argv[1] = argv[0];
393                 argv = &argv[1];
394                 argc--;
395         }
397         while (1) {
398                 c = getopt_long (argc, argv, "+hVv46H:s:e:q:m:c:w:t:p:C:W:d:Sr:",
399                                  longopts, &option);
401                 if (c == -1 || c == EOF || c == 1)
402                         break;
404                 switch (c) {
405                 case '?':                 /* print short usage statement if args not parsable */
406                         printf (_("%s: Unknown argument: %s\n\n"), progname, optarg);
407                         print_usage ();
408                         exit (STATE_UNKNOWN);
409                 case 'h':                 /* help */
410                         print_help ();
411                         exit (STATE_OK);
412                 case 'V':                 /* version */
413                         print_revision (progname, "$Revision$");
414                         exit (STATE_OK);
415                 case 'v':                 /* verbose mode */
416                         verbose = TRUE;
417                         break;
418                 case '4':
419                         address_family = AF_INET;
420                         break;
421                 case '6':
422 #ifdef USE_IPV6
423                         address_family = AF_INET6;
424 #else
425                         usage (_("IPv6 support not available\n"));
426 #endif
427                         break;
428                 case 'H':                 /* hostname */
429                         if (is_host (optarg) == FALSE)
430                                 usage2 (_("invalid host name or address"), optarg);
431                         server_address = optarg;
432                         break;
433                 case 'c':                 /* critical */
434                         if (!is_intnonneg (optarg))
435                                 usage (_("Critical threshold must be a nonnegative integer\n"));
436                         else
437                                 critical_time = strtod (optarg, NULL);
438                         check_critical_time = TRUE;
439                         break;
440                 case 'w':                 /* warning */
441                         if (!is_intnonneg (optarg))
442                                 usage (_("Warning threshold must be a nonnegative integer\n"));
443                         else
444                                 warning_time = strtod (optarg, NULL);
445                         check_warning_time = TRUE;
446                         break;
447                 case 'C':
448                         crit_codes = realloc (crit_codes, ++crit_codes_count);
449                         crit_codes[crit_codes_count - 1] = optarg;
450                         break;
451                 case 'W':
452                         warn_codes = realloc (warn_codes, ++warn_codes_count);
453                         warn_codes[warn_codes_count - 1] = optarg;
454                         break;
455                 case 't':                 /* timeout */
456                         if (!is_intpos (optarg))
457                                 usage (_("Timeout interval must be a positive integer\n"));
458                         else
459                                 socket_timeout = atoi (optarg);
460                         break;
461                 case 'p':                 /* port */
462                         if (!is_intpos (optarg))
463                                 usage (_("Server port must be a positive integer\n"));
464                         else
465                                 server_port = atoi (optarg);
466                         break;
467                 case 's':
468                         server_send = optarg;
469                         break;
470                 case 'e': /* expect string (may be repeated) */
471                         EXPECT = NULL;
472                         if (server_expect_count == 0)
473                                 server_expect = malloc (sizeof (char *) * (++server_expect_count));
474                         else
475                                 server_expect = realloc (server_expect, sizeof (char *) * (++server_expect_count));
476                         server_expect[server_expect_count - 1] = optarg;
477                         break;
478                 case 'm':
479                         if (!is_intpos (optarg))
480                                 usage (_("Maxbytes must be a positive integer\n"));
481                         else
482                                 maxbytes = atoi (optarg);
483                 case 'q':
484                         server_quit = optarg;
485                         break;
486                 case 'r':
487                         if (!strncmp(optarg,"ok",2))
488                                 econn_refuse_state = STATE_OK;
489                         else if (!strncmp(optarg,"warn",4))
490                                 econn_refuse_state = STATE_WARNING;
491                         else if (!strncmp(optarg,"crit",4))
492                                 econn_refuse_state = STATE_CRITICAL;
493                         else
494                                 usage (_("Refuse mut be one of ok, warn, crit\n"));
495                         break;
496                 case 'd':
497                         if (is_intpos (optarg))
498                                 delay = atoi (optarg);
499                         else
500                                 usage (_("Delay must be a positive integer\n"));
501                         break;
502                 case 'S':
503 #ifndef HAVE_SSL
504                         die (STATE_UNKNOWN,
505                                 _("SSL support not available. Install OpenSSL and recompile."));
506 #endif
507                         use_ssl = TRUE;
508                         break;
509                 }
510         }
512         if (server_address == NULL)
513                 usage (_("You must provide a server address\n"));
515         return OK;
517 \f
519 #ifdef HAVE_SSL
520 int
521 connect_SSL (void)
523   SSL_METHOD *meth;
525   /* Initialize SSL context */
526   SSLeay_add_ssl_algorithms ();
527   meth = SSLv2_client_method ();
528   SSL_load_error_strings ();
529   if ((ctx = SSL_CTX_new (meth)) == NULL)
530     {
531       printf (_("ERROR: Cannot create SSL context.\n"));
532       return STATE_CRITICAL;
533     }
535   /* Initialize alarm signal handling */
536   signal (SIGALRM, socket_timeout_alarm_handler);
538   /* Set socket timeout */
539   alarm (socket_timeout);
541   /* Save start time */
542   time (&start_time);
544   /* Make TCP connection */
545   if (my_tcp_connect (server_address, server_port, &sd) == STATE_OK && was_refused == FALSE)
546     {
547     /* Do the SSL handshake */
548       if ((ssl = SSL_new (ctx)) != NULL)
549       {
550         SSL_set_fd (ssl, sd);
551         if (SSL_connect (ssl) != -1)
552           return OK;
553         ERR_print_errors_fp (stderr);
554       }
555       else
556       {
557         printf (_("ERROR: Cannot initiate SSL handshake.\n"));
558       }
559       SSL_free (ssl);
560     }
562   SSL_CTX_free (ctx);
563   close (sd);
565   return STATE_CRITICAL;
567 #endif
571 int
572 my_recv (void)
574         int i;
576 #ifdef HAVE_SSL
577         if (use_ssl) {
578                 i = SSL_read (ssl, buffer, MAXBUF - 1);
579         }
580         else {
581 #endif
582                 i = read (sd, buffer, MAXBUF - 1);
583 #ifdef HAVE_SSL
584         }
585 #endif
587         return i;
594 \f
595 void
596 print_help (void)
598         print_revision (progname, revision);
600         printf (_("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n"));
601         printf (_(COPYRIGHT), copyright, email);
603         printf (_("This plugin tests %s connections with the specified host.\n\n"),
604                 SERVICE);
606         print_usage ();
608         printf (_(UT_HELP_VRSN));
610         printf (_(UT_HOST_PORT), 'p', "none");
612         printf (_(UT_IPv46));
614         printf (_("\
615  -s, --send=STRING\n\
616     String to send to the server\n\
617  -e, --expect=STRING\n\
618     String to expect in server response\n\
619  -q, --quit=STRING\n\
620     String to send server to initiate a clean close of the connection\n"));
622         printf (_("\
623  -r, --refuse=ok|warn|crit\n\
624     Accept tcp refusals with states ok, warn, crit (default: crit)\n\
625  -m, --maxbytes=INTEGER\n\
626     Close connection once more than this number of bytes are received\n\
627  -d, --delay=INTEGER\n\
628     Seconds to wait between sending string and polling for response\n"));
630         printf (_(UT_WARN_CRIT));
632         printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
634         printf (_(UT_VERBOSE));
636         printf (_(UT_SUPPORT));
642 void
643 print_usage (void)
645         printf (_("\
646 Usage: %s -H host -p port [-w <warning time>] [-c <critical time>]\n\
647   [-s <send string>] [-e <expect string>] [-q <quit string>]\n\
648   [-m <maximum bytes>] [-d <delay>] [-t <timeout seconds>]\n\
649   [-r <refuse state>] [-v] [-4|-6]\n"), progname);
650         printf ("       %s (-h|--help)\n", progname);
651         printf ("       %s (-V|--version)\n", progname);