Code

62efc8c7e4bd80e730424677f071d42792eab868
[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]\n\
31         [-e expect] [-W wait] [-t to_sec] [-r refuse_state] [-v]\n";
33 const char *options = "\
34  -H, --hostname=ADDRESS\n\
35     Host name argument for servers using host headers (use numeric\n\
36     address if possible to bypass DNS lookup).\n\
37  -p, --port=INTEGER\n\
38     Port number\n\
39  -s, --send=STRING\n\
40     String to send to the server\n\
41  -e, --expect=STRING\n\
42     String to expect in server response\n\
43  -W, --wait=INTEGER\n\
44     Seconds to wait between sending string and polling for response\n\
45  -w, --warning=DOUBLE\n\
46     Response time to result in warning status (seconds)\n\
47  -c, --critical=DOUBLE\n\
48     Response time to result in critical status (seconds)\n\
49  -t, --timeout=INTEGER\n\
50     Seconds before connection times out (default: %d)\n\
51  -r, --refuse=ok|warn|crit\n\
52     Accept tcp refusals with states ok, warn, crit (default: crit)\n\
53  -v\n\
54     Show details for command-line debugging (do not use with nagios server)\n";
56 const char *standard_options = "\
57  -h, --help\n\
58     Print detailed help screen\n\
59  -V, --version\n\
60     Print version information";
62 #include "config.h"
63 #include "common.h"
64 #include "netutils.h"
65 #include "utils.h"
67 #ifdef HAVE_SSL_H
68 #  include <rsa.h>
69 #  include <crypto.h>
70 #  include <x509.h>
71 #  include <pem.h>
72 #  include <ssl.h>
73 #  include <err.h>
74 #else
75 #  ifdef HAVE_OPENSSL_SSL_H
76 #    include <openssl/rsa.h>
77 #    include <openssl/crypto.h>
78 #    include <openssl/x509.h>
79 #    include <openssl/pem.h>
80 #    include <openssl/ssl.h>
81 #    include <openssl/err.h>
82 #  endif
83 #endif
85 #ifdef HAVE_SSL
86 SSL_CTX *ctx;
87 SSL *ssl;
88 int connect_SSL (void);
89 #endif
91 enum {
92         TCP_PROTOCOL = 1,
93         UDP_PROTOCOL = 2,
94         MAXBUF = 1024
95 };
97 int process_arguments (int, char **);
98 void print_usage (void);
99 void print_help (void);
100 int my_recv (void);
102 char *SERVICE = NULL;
103 char *SEND = NULL;
104 char *EXPECT = NULL;
105 char *QUIT = NULL;
106 int PROTOCOL = 0;
107 int PORT = 0;
109 int server_port = 0;
110 char *server_address = NULL;
111 char *server_send = NULL;
112 char *server_quit = NULL;
113 char **server_expect = NULL;
114 int server_expect_count = 0;
115 char **warn_codes = NULL;
116 int warn_codes_count = 0;
117 char **crit_codes = NULL;
118 int crit_codes_count = 0;
119 int delay = 0;
120 double warning_time = 0;
121 int check_warning_time = FALSE;
122 double critical_time = 0;
123 int check_critical_time = FALSE;
124 double elapsed_time = 0;
125 int verbose = FALSE;
126 int use_ssl = FALSE;
127 int sd = 0;
128 char *buffer = "";
130 int
131 main (int argc, char **argv)
133         int result;
134         int i;
135         char *status = "";
136         struct timeval tv;
138         if (strstr (argv[0], "check_udp")) {
139                 progname = strdup ("check_udp");
140                 SERVICE = strdup ("UDP");
141                 SEND = NULL;
142                 EXPECT = NULL;
143                 QUIT = NULL;
144                 PROTOCOL = UDP_PROTOCOL;
145                 PORT = 0;
146         }
147         else if (strstr (argv[0], "check_tcp")) {
148                 progname = strdup ("check_tcp");
149                 SERVICE = strdup ("TCP");
150                 SEND = NULL;
151                 EXPECT = NULL;
152                 QUIT = NULL;
153                 PROTOCOL = TCP_PROTOCOL;
154                 PORT = 0;
155         }
156         else if (strstr (argv[0], "check_ftp")) {
157                 progname = strdup ("check_ftp");
158                 SERVICE = strdup ("FTP");
159                 SEND = NULL;
160                 EXPECT = strdup ("220");
161                 QUIT = strdup ("QUIT\r\n");
162                 PROTOCOL = TCP_PROTOCOL;
163                 PORT = 21;
164         }
165         else if (strstr (argv[0], "check_smtp")) {
166                 progname = strdup ("check_smtp");
167                 SERVICE = strdup ("SMTP");
168                 SEND = NULL;
169                 EXPECT = strdup ("220");
170                 QUIT = strdup ("QUIT\r\n");
171                 PROTOCOL = TCP_PROTOCOL;
172                 PORT = 25;
173         }
174         else if (strstr (argv[0], "check_pop")) {
175                 progname = strdup ("check_pop");
176                 SERVICE = strdup ("POP");
177                 SEND = NULL;
178                 EXPECT = strdup ("+OK");
179                 QUIT = strdup ("QUIT\r\n");
180                 PROTOCOL = TCP_PROTOCOL;
181                 PORT = 110;
182         }
183         else if (strstr (argv[0], "check_imap")) {
184                 progname = strdup ("check_imap");
185                 SERVICE = strdup ("IMAP");
186                 SEND = NULL;
187                 EXPECT = strdup ("* OK");
188                 QUIT = strdup ("a1 LOGOUT\r\n");
189                 PROTOCOL = TCP_PROTOCOL;
190                 PORT = 143;
191         }
192 #ifdef HAVE_SSL
193         else if (strstr(argv[0],"check_simap")) {
194                 progname = strdup ("check_simap");
195                 SERVICE = strdup ("SIMAP");
196                 SEND=NULL;
197                 EXPECT = strdup ("* OK");
198                 QUIT = strdup ("a1 LOGOUT\r\n");
199                 PROTOCOL=TCP_PROTOCOL;
200                 use_ssl=TRUE;
201                 PORT=993;
202         }
203         else if (strstr(argv[0],"check_spop")) {
204                 progname = strdup ("check_spop");
205                 SERVICE = strdup ("SPOP");
206                 SEND=NULL;
207                 EXPECT = strdup ("+OK");
208                 QUIT = strdup ("QUIT\r\n");
209                 PROTOCOL=TCP_PROTOCOL;
210                 use_ssl=TRUE;
211                 PORT=995;
212         }
213 #endif
214         else if (strstr (argv[0], "check_nntp")) {
215                 progname = strdup ("check_nntp");
216                 SERVICE = strdup ("NNTP");
217                 SEND = NULL;
218                 EXPECT = NULL;
219                 server_expect = realloc (server_expect, ++server_expect_count);
220                 asprintf (&server_expect[server_expect_count - 1], "200");
221                 server_expect = realloc (server_expect, ++server_expect_count);
222                 asprintf (&server_expect[server_expect_count - 1], "201");
223                 asprintf (&QUIT, "QUIT\r\n");
224                 PROTOCOL = TCP_PROTOCOL;
225                 PORT = 119;
226         }
227         else {
228                 usage ("ERROR: Generic check_tcp called with unknown service\n");
229         }
231         server_address = strdup ("127.0.0.1");
232         server_port = PORT;
233         server_send = SEND;
234         server_quit = QUIT;
236         if (process_arguments (argc, argv) == ERROR)
237                 usage ("Could not parse arguments\n");
239         /* use default expect if none listed in process_arguments() */
240         if (EXPECT && server_expect_count == 0) {
241                 server_expect = malloc (++server_expect_count);
242                 server_expect[server_expect_count - 1] = EXPECT;
243         }
245         /* initialize alarm signal handling */
246         signal (SIGALRM, socket_timeout_alarm_handler);
248         /* set socket timeout */
249         alarm (socket_timeout);
251         /* try to connect to the host at the given port number */
252         gettimeofday (&tv, NULL);
253 #ifdef HAVE_SSL
254         if (use_ssl)
255                 result = connect_SSL ();
256         else
257 #endif
258                 {
259                         if (PROTOCOL == UDP_PROTOCOL)
260                                 result = my_udp_connect (server_address, server_port, &sd);
261                         else
262                                 /* default is TCP */
263                                 result = my_tcp_connect (server_address, server_port, &sd);
264                 }
266         if (result == STATE_CRITICAL)
267                 return STATE_CRITICAL;
269         if (server_send != NULL) {              /* Something to send? */
270                 asprintf (&server_send, "%s\r\n", server_send);
271 #ifdef HAVE_SSL
272                 if (use_ssl)
273                         SSL_write(ssl, server_send, strlen (server_send));
274                 else
275 #endif
276                         send (sd, server_send, strlen (server_send), 0);
277         }
279         if (delay > 0) {
280                 tv.tv_sec += delay;
281                 sleep (delay);
282         }
284         if (server_send || server_expect_count > 0) {
286                 buffer = malloc (MAXBUF);
287                 memset (buffer, '\0', MAXBUF);
288                 /* watch for the expect string */
289                 while ((i = my_recv ()) > 0) {
290                         buffer[i] = '\0';
291                         asprintf (&status, "%s%s", status, buffer);
292                         if (buffer[i-2] == '\r' && buffer[i-1] == '\n')
293                                 break;
294                 }
296                 /* return a CRITICAL status if we couldn't read any data */
297                 if (status == NULL)
298                         terminate (STATE_CRITICAL, "No data received from host\n");
300                 strip (status);
302                 if (status && verbose)
303                         printf ("%s\n", status);
305                 if (server_expect_count > 0) {
306                         for (i = 0;; i++) {
307                                 if (verbose)
308                                         printf ("%d %d\n", i, server_expect_count);
309                                 if (i >= server_expect_count)
310                                         terminate (STATE_WARNING, "Invalid response from host\n");
311                                 if (strstr (status, server_expect[i]))
312                                         break;
313                         }
314                 }
315         }
317         if (server_quit != NULL) {
318 #ifdef HAVE_SSL
319                 if (use_ssl) {
320                         SSL_write (ssl, server_quit, strlen (server_quit));
321                         SSL_shutdown (ssl);
322                         SSL_free (ssl);
323                         SSL_CTX_free (ctx);
324                 }
325                 else {
326 #endif
327                         send (sd, server_quit, strlen (server_quit), 0);
328 #ifdef HAVE_SSL
329                 }
330 #endif
331         }
333         /* close the connection */
334         if (sd)
335                 close (sd);
337         elapsed_time = delta_time (tv);
339         if (check_critical_time == TRUE && elapsed_time > critical_time)
340                 result = STATE_CRITICAL;
341         else if (check_warning_time == TRUE && elapsed_time > warning_time)
342                 result = STATE_WARNING;
344         /* reset the alarm */
345         alarm (0);
347         printf
348                 ("%s %s%s - %.3f second response time on port %d",
349                  SERVICE,
350                  state_text (result),
351                  (was_refused) ? " (refused)" : "",
352                  elapsed_time, server_port);
354         if (status && strlen(status) > 0)
355                 printf (" [%s]", status);
357         printf ("|time=%.3f\n", elapsed_time);
359         return result;
368 /* process command-line arguments */
369 int
370 process_arguments (int argc, char **argv)
372         int c;
374         int option_index = 0;
375         static struct option long_options[] = {
376                 {"hostname", required_argument, 0, 'H'},
377                 {"critical-time", required_argument, 0, 'c'},
378                 {"warning-time", required_argument, 0, 'w'},
379                 {"critical-codes", required_argument, 0, 'C'},
380                 {"warning-codes", required_argument, 0, 'W'},
381                 {"timeout", required_argument, 0, 't'},
382                 {"protocol", required_argument, 0, 'P'},
383                 {"port", required_argument, 0, 'p'},
384                 {"send", required_argument, 0, 's'},
385                 {"expect", required_argument, 0, 'e'},
386                 {"quit", required_argument, 0, 'q'},
387                 {"delay", required_argument, 0, 'd'},
388                 {"refuse", required_argument, 0, 'r'},
389                 {"verbose", no_argument, 0, 'v'},
390                 {"version", no_argument, 0, 'V'},
391                 {"help", no_argument, 0, 'h'},
392                 {0, 0, 0, 0}
393         };
395         if (argc < 2)
396                 usage ("No arguments found\n");
398         /* backwards compatibility */
399         for (c = 1; c < argc; c++) {
400                 if (strcmp ("-to", argv[c]) == 0)
401                         strcpy (argv[c], "-t");
402                 else if (strcmp ("-wt", argv[c]) == 0)
403                         strcpy (argv[c], "-w");
404                 else if (strcmp ("-ct", argv[c]) == 0)
405                         strcpy (argv[c], "-c");
406         }
408         if (!is_option (argv[1])) {
409                 server_address = argv[1];
410                 argv[1] = argv[0];
411                 argv = &argv[1];
412                 argc--;
413         }
415         while (1) {
416                 c = getopt_long (argc, argv, "+hVvH:s:e:q:c:w:t:p:C:W:d:Sr:", long_options,
417                                                                          &option_index);
419                 if (c == -1 || c == EOF || c == 1)
420                         break;
422                 switch (c) {
423                 case '?':                 /* print short usage statement if args not parsable */
424                         printf ("%s: Unknown argument: %s\n\n", progname, optarg);
425                         print_usage ();
426                         exit (STATE_UNKNOWN);
427                 case 'h':                 /* help */
428                         print_help ();
429                         exit (STATE_OK);
430                 case 'V':                 /* version */
431                         print_revision (progname, "$Revision$");
432                         exit (STATE_OK);
433                 case 'v':                 /* verbose mode */
434                         verbose = TRUE;
435                         break;
436                 case 'H':                 /* hostname */
437                         if (is_host (optarg) == FALSE)
438                                 usage2 ("invalid host name or address", optarg);
439                         server_address = optarg;
440                         break;
441                 case 'c':                 /* critical */
442                         if (!is_intnonneg (optarg))
443                                 usage ("Critical threshold must be a nonnegative integer\n");
444                         critical_time = strtod (optarg, NULL);
445                         check_critical_time = TRUE;
446                         break;
447                 case 'w':                 /* warning */
448                         if (!is_intnonneg (optarg))
449                                 usage ("Warning threshold must be a nonnegative integer\n");
450                         warning_time = strtod (optarg, NULL);
451                         check_warning_time = TRUE;
452                         break;
453                 case 'C':
454                         crit_codes = realloc (crit_codes, ++crit_codes_count);
455                         crit_codes[crit_codes_count - 1] = optarg;
456                         break;
457                 case 'W':
458                         warn_codes = realloc (warn_codes, ++warn_codes_count);
459                         warn_codes[warn_codes_count - 1] = optarg;
460                         break;
461                 case 't':                 /* timeout */
462                         if (!is_intpos (optarg))
463                                 usage ("Timeout interval must be a positive integer\n");
464                         socket_timeout = atoi (optarg);
465                         break;
466                 case 'p':                 /* port */
467                         if (!is_intpos (optarg))
468                                 usage ("Server port must be a positive integer\n");
469                         server_port = atoi (optarg);
470                         break;
471                 case 's':
472                         server_send = optarg;
473                         break;
474                 case 'e': /* expect string (may be repeated) */
475                         EXPECT = NULL;
476                         if (server_expect_count == 0)
477                                 server_expect = malloc (++server_expect_count);
478                         else
479                                 server_expect = realloc (server_expect, ++server_expect_count);
480                         server_expect[server_expect_count - 1] = optarg;
481                         break;
482                 case 'q':
483                         server_quit = optarg;
484                         break;
485                 case 'r':
486                         if (!strncmp(optarg,"ok",2))
487                                 econn_refuse_state = STATE_OK;
488                         else if (!strncmp(optarg,"warn",4))
489                                 econn_refuse_state = STATE_WARNING;
490                         else if (!strncmp(optarg,"crit",4))
491                                 econn_refuse_state = STATE_CRITICAL;
492                         else
493                                 usage ("Refuse mut be one of ok, warn, crit\n");
494                         break;
495                 case 'd':
496                         if (is_intpos (optarg))
497                                 delay = atoi (optarg);
498                         else
499                                 usage ("Delay must be a positive integer\n");
500                         break;
501                 case 'S':
502 #ifndef HAVE_SSL
503                         terminate (STATE_UNKNOWN,
504                                 "SSL support not available. Install OpenSSL and recompile.");
505 #endif
506                         use_ssl = TRUE;
507                         break;
508                 }
509         }
511         if (server_address == NULL)
512                 usage ("You must provide a server address\n");
514         return OK;
517 void
518 print_help (void)
520         print_revision (progname, revision);
521         printf ("Copyright (c) %s %s\n\t<%s>\n\n",
522                 copyright, authors, email);
523         printf (summary, SERVICE);
524         print_usage ();
525         printf ("\nOptions:\n");
526         printf (options, DEFAULT_SOCKET_TIMEOUT);
527         printf (standard_options);
528         support ();
531 void
532 print_usage (void)
534         printf ("Usage: %s %s\n", progname, option_summary);
535         printf ("       %s (-h|--help)\n", progname);
536         printf ("       %s (-V|--version)\n", progname);
539 #ifdef HAVE_SSL
540 int
541 connect_SSL (void)
543   SSL_METHOD *meth;
545   /* Initialize SSL context */
546   SSLeay_add_ssl_algorithms ();
547   meth = SSLv2_client_method ();
548   SSL_load_error_strings ();
549   if ((ctx = SSL_CTX_new (meth)) == NULL)
550     {
551       printf ("ERROR: Cannot create SSL context.\n");
552       return STATE_CRITICAL;
553     }
555   /* Initialize alarm signal handling */
556   signal (SIGALRM, socket_timeout_alarm_handler);
558   /* Set socket timeout */
559   alarm (socket_timeout);
561   /* Save start time */
562   time (&start_time);
564   /* Make TCP connection */
565   if (my_tcp_connect (server_address, server_port, &sd) == STATE_OK && was_refused == FALSE)
566     {
567     /* Do the SSL handshake */
568       if ((ssl = SSL_new (ctx)) != NULL)
569       {
570         SSL_set_fd (ssl, sd);
571         if (SSL_connect (ssl) != -1)
572           return OK;
573         ERR_print_errors_fp (stderr);
574       }
575       else
576       {
577         printf ("ERROR: Cannot initiate SSL handshake.\n");
578       }
579       SSL_free (ssl);
580     }
582   SSL_CTX_free (ctx);
583   close (sd);
585   return STATE_CRITICAL;
587 #endif
591 int
592 my_recv (void)
594         int i;
596 #ifdef HAVE_SSL
597         if (use_ssl) {
598                 i = SSL_read (ssl, buffer, MAXBUF - 1);
599         }
600         else {
601 #endif
602                 i = read (sd, buffer, MAXBUF - 1);
603 #ifdef HAVE_SSL
604         }
605 #endif
607         return i;