Code

158475e9df692fab9892f227d62ff110baa12590
[nagiosplug.git] / plugins / check_tcp.c
1 /******************************************************************************
2  *
3  * This file is part of the Nagios Plugins.
4  *
5  * Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>
6  *
7  * The Nagios Plugins are free software; you can redistribute them
8  * and/or modify them under the terms of the GNU General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  *
21  * $Id$
22  *
23  *****************************************************************************/
25 #define REVISION "$Revision$"
26 #define DESCRIPTION "Check a TCP port"
27 #define AUTHOR "Ethan Galstad"
28 #define EMAIL "nagios@nagios.org"
29 #define COPYRIGHTDATE "2002"
31 #include "config.h"
32 #include "common.h"
33 #include "netutils.h"
34 #include "utils.h"
36 #ifdef HAVE_SSL_H
37 #include <rsa.h>
38 #include <crypto.h>
39 #include <x509.h>
40 #include <pem.h>
41 #include <ssl.h>
42 #include <err.h>
43 #endif
45 #ifdef HAVE_OPENSSL_SSL_H
46 #include <openssl/rsa.h>
47 #include <openssl/crypto.h>
48 #include <openssl/x509.h>
49 #include <openssl/pem.h>
50 #include <openssl/ssl.h>
51 #include <openssl/err.h>
52 #endif
54 #ifdef HAVE_SSL
55 SSL_CTX *ctx;
56 SSL *ssl;
57 int connect_SSL (void);
58 #endif
60 enum {
61         TCP_PROTOCOL = 1,
62         UDP_PROTOCOL = 2,
63         MAXBUF = 1024
64 };
66 int process_arguments (int, char **);
67 void print_usage (void);
68 void print_help (void);
69 int my_recv (void);
71 char *progname = "check_tcp";
72 char *SERVICE = NULL;
73 char *SEND = NULL;
74 char *EXPECT = NULL;
75 char *QUIT = NULL;
76 int PROTOCOL = 0;
77 int PORT = 0;
79 int server_port = 0;
80 char *server_address = NULL;
81 char *server_send = NULL;
82 char *server_quit = NULL;
83 char **server_expect = NULL;
84 int server_expect_count = 0;
85 char **warn_codes = NULL;
86 int warn_codes_count = 0;
87 char **crit_codes = NULL;
88 int crit_codes_count = 0;
89 int delay = 0;
90 double warning_time = 0;
91 int check_warning_time = FALSE;
92 double critical_time = 0;
93 int check_critical_time = FALSE;
94 double elapsed_time = 0;
95 int verbose = FALSE;
96 int use_ssl = FALSE;
97 int sd = 0;
98 char *buffer = "";
100 int
101 main (int argc, char **argv)
103         int result;
104         int i;
105         char *status = "";
106         struct timeval tv;
108         if (strstr (argv[0], "check_udp")) {
109                 asprintf (&progname, "check_udp");
110                 asprintf (&SERVICE, "UDP");
111                 SEND = NULL;
112                 EXPECT = NULL;
113                 QUIT = NULL;
114                 PROTOCOL = UDP_PROTOCOL;
115                 PORT = 0;
116         }
117         else if (strstr (argv[0], "check_tcp")) {
118                 asprintf (&progname, "check_tcp");
119                 asprintf (&SERVICE, "TCP");
120                 SEND = NULL;
121                 EXPECT = NULL;
122                 QUIT = NULL;
123                 PROTOCOL = TCP_PROTOCOL;
124                 PORT = 0;
125         }
126         else if (strstr (argv[0], "check_ftp")) {
127                 asprintf (&progname, "check_ftp");
128                 asprintf (&SERVICE, "FTP");
129                 SEND = NULL;
130                 asprintf (&EXPECT, "220");
131                 asprintf (&QUIT, "QUIT\r\n");
132                 PROTOCOL = TCP_PROTOCOL;
133                 PORT = 21;
134         }
135         else if (strstr (argv[0], "check_smtp")) {
136                 asprintf (&progname, "check_smtp");
137                 asprintf (&SERVICE, "SMTP");
138                 SEND = NULL;
139                 asprintf (&EXPECT, "220");
140                 asprintf (&QUIT, "QUIT\r\n");
141                 PROTOCOL = TCP_PROTOCOL;
142                 PORT = 25;
143         }
144         else if (strstr (argv[0], "check_pop")) {
145                 asprintf (&progname, "check_pop");
146                 asprintf (&SERVICE, "POP");
147                 SEND = NULL;
148                 asprintf (&EXPECT, "+OK");
149                 asprintf (&QUIT, "QUIT\r\n");
150                 PROTOCOL = TCP_PROTOCOL;
151                 PORT = 110;
152         }
153         else if (strstr (argv[0], "check_imap")) {
154                 asprintf (&progname, "check_imap");
155                 asprintf (&SERVICE, "IMAP");
156                 SEND = NULL;
157                 asprintf (&EXPECT, "* OK");
158                 asprintf (&QUIT, "a1 LOGOUT\r\n");
159                 PROTOCOL = TCP_PROTOCOL;
160                 PORT = 143;
161         }
162 #ifdef HAVE_SSL
163         else if (strstr(argv[0],"check_simap")) {
164                 asprintf (&progname, "check_simap");
165                 asprintf (&SERVICE, "SIMAP");
166                 SEND=NULL;
167                 asprintf (&EXPECT, "* OK");
168                 asprintf (&QUIT, "a1 LOGOUT\r\n");
169                 PROTOCOL=TCP_PROTOCOL;
170                 use_ssl=TRUE;
171                 PORT=993;
172         }
173         else if (strstr(argv[0],"check_spop")) {
174                 asprintf (&progname, "check_spop");
175                 asprintf (&SERVICE, "SPOP");
176                 SEND=NULL;
177                 asprintf (&EXPECT, "+OK");
178                 asprintf (&QUIT, "QUIT\r\n");
179                 PROTOCOL=TCP_PROTOCOL;
180                 use_ssl=TRUE;
181                 PORT=995;
182         }
183 #endif
184         else if (strstr (argv[0], "check_nntp")) {
185                 asprintf (&progname, "check_nntp");
186                 asprintf (&SERVICE, "NNTP");
187                 SEND = NULL;
188                 EXPECT = NULL;
189                 server_expect = realloc (server_expect, ++server_expect_count);
190                 asprintf (&server_expect[server_expect_count - 1], "200");
191                 server_expect = realloc (server_expect, ++server_expect_count);
192                 asprintf (&server_expect[server_expect_count - 1], "201");
193                 asprintf (&QUIT, "QUIT\r\n");
194                 PROTOCOL = TCP_PROTOCOL;
195                 PORT = 119;
196         }
197         else {
198                 usage ("ERROR: Generic check_tcp called with unknown service\n");
199         }
201         asprintf (&server_address, "127.0.0.1");
202         server_port = PORT;
203         server_send = SEND;
204         server_quit = QUIT;
206         if (process_arguments (argc, argv) == ERROR)
207                 usage ("Could not parse arguments\n");
209         /* use default expect if none listed in process_arguments() */
210         if (EXPECT && server_expect_count == 0) {
211                 server_expect = malloc (++server_expect_count);
212                 server_expect[server_expect_count - 1] = EXPECT;
213         }
215         /* initialize alarm signal handling */
216         signal (SIGALRM, socket_timeout_alarm_handler);
218         /* set socket timeout */
219         alarm (socket_timeout);
221         /* try to connect to the host at the given port number */
222         gettimeofday (&tv, NULL);
223 #ifdef HAVE_SSL
224         if (use_ssl)
225                 result = connect_SSL ();
226         else
227 #endif
228                 {
229                         if (PROTOCOL == UDP_PROTOCOL)
230                                 result = my_udp_connect (server_address, server_port, &sd);
231                         else
232                                 /* default is TCP */
233                                 result = my_tcp_connect (server_address, server_port, &sd);
234                 }
236         if (result == STATE_CRITICAL)
237                 return STATE_CRITICAL;
239         if (server_send != NULL) {              /* Something to send? */
240                 asprintf (&server_send, "%s\r\n", server_send);
241 #ifdef HAVE_SSL
242                 if (use_ssl)
243                         SSL_write(ssl, server_send, strlen (server_send));
244                 else
245 #endif
246                         send (sd, server_send, strlen (server_send), 0);
247         }
249         if (delay > 0) {
250                 tv.tv_sec += delay;
251                 sleep (delay);
252         }
254         if (server_send || server_expect_count > 0) {
256                 buffer = malloc (MAXBUF);
257                 memset (buffer, '\0', MAXBUF);
258                 /* watch for the expect string */
259                 while ((i = my_recv ()) > 0) {
260                         buffer[i] = '\0';
261                         asprintf (&status, "%s%s", status, buffer);
262                         if (buffer[i-2] == '\r' && buffer[i-1] == '\n')
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, QUIT, strlen (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);
299         /* close the connection */
300         if (sd)
301                 close (sd);
303         elapsed_time = delta_time (tv);
305         if (check_critical_time == TRUE && elapsed_time > critical_time)
306                 result = STATE_CRITICAL;
307         else if (check_warning_time == TRUE && elapsed_time > warning_time)
308                 result = STATE_WARNING;
310         /* reset the alarm */
311         alarm (0);
313         printf
314                 ("%s %s - %7.3f second response time on port %d",
315                  SERVICE,
316                  state_text (result), elapsed_time, server_port);
318         if (status && strlen(status) > 0)
319                 printf (" [%s]", status);
321         printf ("|time=%7.3f\n", elapsed_time);
323         return result;
332 /* process command-line arguments */
333 int
334 process_arguments (int argc, char **argv)
336         int c;
338         int option_index = 0;
339         static struct option long_options[] = {
340                 {"hostname", required_argument, 0, 'H'},
341                 {"critical-time", required_argument, 0, 'c'},
342                 {"warning-time", required_argument, 0, 'w'},
343                 {"critical-codes", required_argument, 0, 'C'},
344                 {"warning-codes", required_argument, 0, 'W'},
345                 {"timeout", required_argument, 0, 't'},
346                 {"protocol", required_argument, 0, 'P'},
347                 {"port", required_argument, 0, 'p'},
348                 {"send", required_argument, 0, 's'},
349                 {"expect", required_argument, 0, 'e'},
350                 {"quit", required_argument, 0, 'q'},
351                 {"delay", required_argument, 0, 'd'},
352                 {"verbose", no_argument, 0, 'v'},
353                 {"version", no_argument, 0, 'V'},
354                 {"help", no_argument, 0, 'h'},
355                 {0, 0, 0, 0}
356         };
358         if (argc < 2)
359                 usage ("No arguments found\n");
361         /* backwards compatibility */
362         for (c = 1; c < argc; c++) {
363                 if (strcmp ("-to", argv[c]) == 0)
364                         strcpy (argv[c], "-t");
365                 else if (strcmp ("-wt", argv[c]) == 0)
366                         strcpy (argv[c], "-w");
367                 else if (strcmp ("-ct", argv[c]) == 0)
368                         strcpy (argv[c], "-c");
369         }
371         if (!is_option (argv[1])) {
372                 server_address = argv[1];
373                 argv[1] = argv[0];
374                 argv = &argv[1];
375                 argc--;
376         }
378         while (1) {
379                 c = getopt_long (argc, argv, "+hVvH:s:e:q:c:w:t:p:C:W:d:S", long_options,
380                                                                          &option_index);
382                 if (c == -1 || c == EOF || c == 1)
383                         break;
385                 switch (c) {
386                 case '?':                 /* print short usage statement if args not parsable */
387                         printf ("%s: Unknown argument: %s\n\n", progname, optarg);
388                         print_usage ();
389                         exit (STATE_UNKNOWN);
390                 case 'h':                 /* help */
391                         print_help ();
392                         exit (STATE_OK);
393                 case 'V':                 /* version */
394                         print_revision (progname, "$Revision$");
395                         exit (STATE_OK);
396                 case 'v':                 /* verbose mode */
397                         verbose = TRUE;
398                         break;
399                 case 'H':                 /* hostname */
400                         if (is_host (optarg) == FALSE)
401                                 usage2 ("invalid host name or address", optarg);
402                         server_address = optarg;
403                         break;
404                 case 'c':                 /* critical */
405                         if (!is_intnonneg (optarg))
406                                 usage ("Critical threshold must be a nonnegative integer\n");
407                         critical_time = strtod (optarg, NULL);
408                         check_critical_time = TRUE;
409                         break;
410                 case 'w':                 /* warning */
411                         if (!is_intnonneg (optarg))
412                                 usage ("Warning threshold must be a nonnegative integer\n");
413                         warning_time = strtod (optarg, NULL);
414                         check_warning_time = TRUE;
415                         break;
416                 case 'C':
417                         crit_codes = realloc (crit_codes, ++crit_codes_count);
418                         crit_codes[crit_codes_count - 1] = optarg;
419                         break;
420                 case 'W':
421                         warn_codes = realloc (warn_codes, ++warn_codes_count);
422                         warn_codes[warn_codes_count - 1] = optarg;
423                         break;
424                 case 't':                 /* timeout */
425                         if (!is_intpos (optarg))
426                                 usage ("Timeout interval must be a positive integer\n");
427                         socket_timeout = atoi (optarg);
428                         break;
429                 case 'p':                 /* port */
430                         if (!is_intpos (optarg))
431                                 usage ("Server port must be a positive integer\n");
432                         server_port = atoi (optarg);
433                         break;
434                 case 's':
435                         server_send = optarg;
436                         break;
437                 case 'e': /* expect string (may be repeated) */
438                         EXPECT = NULL;
439                         if (server_expect_count == 0)
440                                 server_expect = malloc (++server_expect_count);
441                         else
442                                 server_expect = realloc (server_expect, ++server_expect_count);
443                         server_expect[server_expect_count - 1] = optarg;
444                         break;
445                 case 'q':
446                         server_quit = optarg;
447                         break;
448                 case 'd':
449                         if (is_intpos (optarg))
450                                 delay = atoi (optarg);
451                         else
452                                 usage ("Delay must be a positive integer\n");
453                         break;
454                 case 'S':
455 #ifndef HAVE_SSL
456                         terminate (STATE_UNKNOWN,
457                                 "SSL support not available. Install OpenSSL and recompile.");
458 #endif
459                         use_ssl = TRUE;
460                         break;
461                 }
462         }
464         if (server_address == NULL)
465                 usage ("You must provide a server address\n");
467         return OK;
474 void
475 print_usage (void)
477         printf
478                 ("Usage: %s -H host -p port [-w warn_time] [-c crit_time] [-s send]\n"
479                  "         [-e expect] [-W wait] [-t to_sec] [-v]\n", progname);
486 void
487 print_help (void)
489         print_revision (progname, "$Revision$");
490         printf
491                 ("Copyright (c) 1999 Ethan Galstad (nagios@nagios.org)\n\n"
492                  "This plugin tests %s connections with the specified host.\n\n",
493                  SERVICE);
494         print_usage ();
495         printf
496                 ("Options:\n"
497                  " -H, --hostname=ADDRESS\n"
498                  "    Host name argument for servers using host headers (use numeric\n"
499                  "    address if possible to bypass DNS lookup).\n"
500                  " -p, --port=INTEGER\n"
501                  "    Port number\n"
502                  " -s, --send=STRING\n"
503                  "    String to send to the server\n"
504                  " -e, --expect=STRING\n"
505                  "    String to expect in server response"
506                  " -W, --wait=INTEGER\n"
507                  "    Seconds to wait between sending string and polling for response\n"
508                  " -w, --warning=DOUBLE\n"
509                  "    Response time to result in warning status (seconds)\n"
510                  " -c, --critical=DOUBLE\n"
511                  "    Response time to result in critical status (seconds)\n"
512                  " -t, --timeout=INTEGER\n"
513                  "    Seconds before connection times out (default: %d)\n"
514                  " -v"
515                  "    Show details for command-line debugging (do not use with nagios server)\n"
516                  " -h, --help\n"
517                  "    Print detailed help screen\n"
518                  " -V, --version\n"
519                  "    Print version information\n", DEFAULT_SOCKET_TIMEOUT);
523 #ifdef HAVE_SSL
524 int
525 connect_SSL (void)
527   SSL_METHOD *meth;
529   /* Initialize SSL context */
530   SSLeay_add_ssl_algorithms ();
531   meth = SSLv2_client_method ();
532   SSL_load_error_strings ();
533   if ((ctx = SSL_CTX_new (meth)) == NULL)
534     {
535       printf ("ERROR: Cannot create SSL context.\n");
536       return STATE_CRITICAL;
537     }
539   /* Initialize alarm signal handling */
540   signal (SIGALRM, socket_timeout_alarm_handler);
542   /* Set socket timeout */
543   alarm (socket_timeout);
545   /* Save start time */
546   time (&start_time);
548   /* Make TCP connection */
549   if (my_tcp_connect (server_address, server_port, &sd) == STATE_OK)
550     {
551     /* Do the SSL handshake */
552       if ((ssl = SSL_new (ctx)) != NULL)
553       {
554         SSL_set_fd (ssl, sd);
555         if (SSL_connect (ssl) != -1)
556           return OK;
557         ERR_print_errors_fp (stderr);
558       }
559       else
560       {
561         printf ("ERROR: Cannot initiate SSL handshake.\n");
562       }
563       SSL_free (ssl);
564     }
566   SSL_CTX_free (ctx);
567   close (sd);
569   return STATE_CRITICAL;
571 #endif
575 int
576 my_recv (void)
578         int i;
580 #ifdef HAVE_SSL
581         if (use_ssl) {
582                 i = SSL_read (ssl, buffer, MAXBUF - 1);
583         }
584         else {
585 #endif
586                 i = read (sd, buffer, MAXBUF - 1);
587 #ifdef HAVE_SSL
588         }
589 #endif
591         return i;