Code

millisecond timing
[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 PROGRAM check_tcp
26 #define DESCRIPTION "Check a TCP port"
27 #define AUTHOR "Ethan Galstad"
28 #define EMAIL "nagios@nagios.org"
29 #define COPYRIGHTDATE "1999"
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 #define TCP_PROTOCOL 1
61 #define UDP_PROTOCOL 2
63 int process_arguments (int, char **);
64 void print_usage (void);
65 void print_help (void);
67 char *PROGNAME = NULL;
68 char *SERVICE = NULL;
69 char *SEND = NULL;
70 char *EXPECT = NULL;
71 char *QUIT = NULL;
72 int PROTOCOL = 0;
73 int PORT = 0;
75 int server_port = 0;
76 char *server_address = NULL;
77 char *server_send = NULL;
78 char *server_quit = NULL;
79 char **server_expect = NULL;
80 int server_expect_count = 0;
81 char **warn_codes = NULL;
82 int warn_codes_count = 0;
83 char **crit_codes = NULL;
84 int crit_codes_count = 0;
85 int delay = 0;
86 double warning_time = 0;
87 int check_warning_time = FALSE;
88 double critical_time = 0;
89 int check_critical_time = FALSE;
90 double elapsed_time = 0;
91 int verbose = FALSE;
92 int use_ssl = FALSE;
93 int sd;
95 int
96 main (int argc, char **argv)
97 {
98         int result;
99         int i;
100         char buffer[MAX_INPUT_BUFFER] = "";
101         char *status = NULL;
102         char *output = NULL;
103         char *ptr = NULL;
104         struct timeval tv;
106         if (strstr (argv[0], "check_udp")) {
107                 PROGNAME = strscpy (PROGNAME, "check_udp");
108                 SERVICE = strscpy (SERVICE, "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 = strscpy (PROGNAME, "check_tcp");
117                 SERVICE = strscpy (SERVICE, "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 = strscpy (PROGNAME, "check_ftp");
126                 SERVICE = strscpy (SERVICE, "FTP");
127                 SEND = NULL;
128                 EXPECT = strscpy (EXPECT, "220");
129                 QUIT = strscpy (QUIT, "QUIT\r\n");
130                 PROTOCOL = TCP_PROTOCOL;
131                 PORT = 21;
132         }
133         else if (strstr (argv[0], "check_smtp")) {
134                 PROGNAME = strscpy (PROGNAME, "check_smtp");
135                 SERVICE = strscpy (SERVICE, "SMTP");
136                 SEND = NULL;
137                 EXPECT = strscpy (EXPECT, "220");
138                 QUIT = strscpy (QUIT, "QUIT\r\n");
139                 PROTOCOL = TCP_PROTOCOL;
140                 PORT = 25;
141         }
142         else if (strstr (argv[0], "check_pop")) {
143                 PROGNAME = strscpy (PROGNAME, "check_pop");
144                 SERVICE = strscpy (SERVICE, "POP");
145                 SEND = NULL;
146                 EXPECT = strscpy (EXPECT, "110");
147                 QUIT = strscpy (QUIT, "QUIT\r\n");
148                 PROTOCOL = TCP_PROTOCOL;
149                 PORT = 110;
150         }
151         else if (strstr (argv[0], "check_imap")) {
152                 PROGNAME = strscpy (PROGNAME, "check_imap");
153                 SERVICE = strscpy (SERVICE, "IMAP");
154                 SEND = NULL;
155                 EXPECT = strscpy (EXPECT, "* OK");
156                 QUIT = strscpy (QUIT, "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=strscpy(PROGNAME,"check_simap");
163                 SERVICE=strscpy(SERVICE,"SIMAP");
164                 SEND=NULL;
165                 EXPECT=strscpy(EXPECT,"* OK");
166                 QUIT=strscpy(QUIT,"a1 LOGOUT\n");
167                 PROTOCOL=TCP_PROTOCOL;
168                 use_ssl=TRUE;
169                 PORT=993;
170         }
171 #endif
172         else if (strstr (argv[0], "check_nntp")) {
173                 PROGNAME = strscpy (PROGNAME, "check_nntp");
174                 SERVICE = strscpy (SERVICE, "NNTP");
175                 SEND = NULL;
176                 EXPECT = NULL;
177                 server_expect = realloc (server_expect, ++server_expect_count);
178                 server_expect[server_expect_count - 1] = strscpy (EXPECT, "200");
179                 server_expect = realloc (server_expect, ++server_expect_count);
180                 server_expect[server_expect_count - 1] = strscpy (NULL, "201");
181                 QUIT = strscpy (QUIT, "QUIT\r\n");
182                 PROTOCOL = TCP_PROTOCOL;
183                 PORT = 119;
184         }
185         else {
186                 usage ("ERROR: Generic check_tcp called with unknown service\n");
187         }
189         server_address = strscpy (NULL, "127.0.0.1");
190         server_port = PORT;
191         server_send = SEND;
192         server_quit = QUIT;
194         if (process_arguments (argc, argv) == ERROR)
195                 usage ("Could not parse arguments\n");
197         /* use default expect if none listed in process_arguments() */
198         if (EXPECT && server_expect_count == 0) {
199                 server_expect = malloc (1);
200                 server_expect[server_expect_count - 1] = EXPECT;
201         }
203         /* initialize alarm signal handling */
204         signal (SIGALRM, socket_timeout_alarm_handler);
206         /* set socket timeout */
207         alarm (socket_timeout);
209         /* try to connect to the host at the given port number */
210         gettimeofday (&tv, NULL);
211 #ifdef HAVE_SSL
212         if (use_ssl)
213                 result = connect_SSL ();
214         else
215 #endif
216                 {
217                         if (PROTOCOL == UDP_PROTOCOL)
218                                 result = my_udp_connect (server_address, server_port, &sd);
219                         else                                                                                                    /* default is TCP */
220                                 result = my_tcp_connect (server_address, server_port, &sd);
221                 }
223         if (result == STATE_CRITICAL)
224                 return STATE_CRITICAL;
226         if (server_send != NULL) {              /* Something to send? */
227                 snprintf (buffer, MAX_INPUT_BUFFER - 1, "%s\r\n", server_send);
228                 buffer[MAX_INPUT_BUFFER - 1] = 0;
229 #ifdef HAVE_SSL
230                 if (use_ssl)
231                         SSL_write(ssl,buffer,strlen(buffer));
232                 else
233 #endif
234                         send (sd, buffer, strlen (buffer), 0);
235         }
237         if (delay > 0) {
238                 tv.tv_sec += delay;
239                 sleep (delay);
240         }
242         if (server_send || server_expect_count > 0) {
244                 asprintf (&status, "");
246                 /* watch for the expect string */
247 #ifdef HAVE_SSL
248                 if (use_ssl && SSL_read (ssl, buffer, MAX_INPUT_BUFFER - 1)>=0)
249                         asprintf (&status, "%s%s", status, buffer);
250                 else
251 #endif
252                         {
253                                 if (recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0) >= 0)
254                                         asprintf (&status, "%s%s", status, buffer);
255                         }
256                 strip (status);
258                 /* return a CRITICAL status if we couldn't read any data */
259                 if (status == NULL)
260                         terminate (STATE_CRITICAL, "No data received from host\n");
262                 if (status && verbose)
263                         printf ("%s\n", status);
265                 if (server_expect_count > 0) {
266                         for (i = 0;; i++) {
267                                 if (verbose)
268                                         printf ("%d %d\n", i, server_expect_count);
269                                 if (i >= server_expect_count)
270                                         terminate (STATE_WARNING, "Invalid response from host\n");
271                                 if (strstr (status, server_expect[i]))
272                                         break;
273                         }
274                 }
275         }
277         if (server_quit)
278 #ifdef HAVE_SSL
279                 if (use_ssl) {
280                         SSL_write (ssl, QUIT, strlen (QUIT));
281                         SSL_shutdown (ssl);
282                         SSL_free (ssl);
283                         SSL_CTX_free (ctx);
284                 }
285                 else
286 #endif
287                 send (sd, server_quit, strlen (server_quit), 0);
289         /* close the connection */
290         close (sd);
292         elapsed_time = delta_time (tv);
294         if (check_critical_time == TRUE && elapsed_time > critical_time)
295                 result = STATE_CRITICAL;
296         else if (check_warning_time == TRUE && elapsed_time > warning_time)
297                 result = STATE_WARNING;
299         /* reset the alarm */
300         alarm (0);
302         printf
303                 ("%s %s - %7.3f second response time on port %d",
304                  SERVICE,
305                  state_text (result), elapsed_time, server_port);
307         if (status)
308                 printf (" [%s]", status);
310         printf ("|time=%7.3f\n", elapsed_time);
312         return result;
321 /* process command-line arguments */
322 int
323 process_arguments (int argc, char **argv)
325         int c;
327 #ifdef HAVE_GETOPT_H
328         int option_index = 0;
329         static struct option long_options[] = {
330                 {"hostname", required_argument, 0, 'H'},
331                 {"critical-time", required_argument, 0, 'c'},
332                 {"warning-time", required_argument, 0, 'w'},
333                 {"critical-codes", required_argument, 0, 'C'},
334                 {"warning-codes", required_argument, 0, 'W'},
335                 {"timeout", required_argument, 0, 't'},
336                 {"protocol", required_argument, 0, 'P'},
337                 {"port", required_argument, 0, 'p'},
338                 {"send", required_argument, 0, 's'},
339                 {"expect", required_argument, 0, 'e'},
340                 {"quit", required_argument, 0, 'q'},
341                 {"delay", required_argument, 0, 'd'},
342                 {"verbose", no_argument, 0, 'v'},
343                 {"version", no_argument, 0, 'V'},
344                 {"help", no_argument, 0, 'h'},
345                 {0, 0, 0, 0}
346         };
347 #endif
349         if (argc < 2)
350                 usage ("No arguments found\n");
352         /* backwards compatibility */
353         for (c = 1; c < argc; c++) {
354                 if (strcmp ("-to", argv[c]) == 0)
355                         strcpy (argv[c], "-t");
356                 else if (strcmp ("-wt", argv[c]) == 0)
357                         strcpy (argv[c], "-w");
358                 else if (strcmp ("-ct", argv[c]) == 0)
359                         strcpy (argv[c], "-c");
360         }
362         if (!is_option (argv[1])) {
363                 server_address = argv[1];
364                 argv[1] = argv[0];
365                 argv = &argv[1];
366                 argc--;
367         }
369         while (1) {
370 #ifdef HAVE_GETOPT_H
371                 c =
372                         getopt_long (argc, argv, "+hVvH:s:e:q:c:w:t:p:C:W:d:S", long_options,
373                                                                          &option_index);
374 #else
375                 c = getopt (argc, argv, "+hVvH:s:e:q:c:w:t:p:C:W:d:S");
376 #endif
378                 if (c == -1 || c == EOF || c == 1)
379                         break;
381                 switch (c) {
382                 case '?':                 /* print short usage statement if args not parsable */
383                         printf ("%s: Unknown argument: %s\n\n", my_basename (argv[0]), optarg);
384                         print_usage ();
385                         exit (STATE_UNKNOWN);
386                 case 'h':                 /* help */
387                         print_help ();
388                         exit (STATE_OK);
389                 case 'V':                 /* version */
390                         print_revision (PROGNAME, "$Revision$");
391                         exit (STATE_OK);
392                 case 'v':                 /* verbose mode */
393                         verbose = TRUE;
394                         break;
395                 case 'H':                 /* hostname */
396                         if (is_host (optarg) == FALSE)
397                                 usage ("Invalid host name/address\n");
398                         server_address = optarg;
399                         break;
400                 case 'c':                 /* critical */
401                         if (!is_intnonneg (optarg))
402                                 usage ("Critical threshold must be a nonnegative integer\n");
403                         critical_time = strtod (optarg, NULL);
404                         check_critical_time = TRUE;
405                         break;
406                 case 'w':                 /* warning */
407                         if (!is_intnonneg (optarg))
408                                 usage ("Warning threshold must be a nonnegative integer\n");
409                         warning_time = strtod (optarg, NULL);
410                         check_warning_time = TRUE;
411                         break;
412                 case 'C':
413                         crit_codes = realloc (crit_codes, ++crit_codes_count);
414                         crit_codes[crit_codes_count - 1] = optarg;
415                         break;
416                 case 'W':
417                         warn_codes = realloc (warn_codes, ++warn_codes_count);
418                         warn_codes[warn_codes_count - 1] = optarg;
419                         break;
420                 case 't':                 /* timeout */
421                         if (!is_intpos (optarg))
422                                 usage ("Timeout interval must be a positive integer\n");
423                         socket_timeout = atoi (optarg);
424                         break;
425                 case 'p':                 /* port */
426                         if (!is_intpos (optarg))
427                                 usage ("Server port must be a positive integer\n");
428                         server_port = atoi (optarg);
429                         break;
430                 case 's':
431                         server_send = optarg;
432                         break;
433                 case 'e': /* expect string (may be repeated) */
434                         EXPECT = NULL;
435                         if (server_expect_count == 0)
436                                 server_expect = malloc (++server_expect_count);
437                         else
438                                 server_expect = realloc (server_expect, ++server_expect_count);
439                         server_expect[server_expect_count - 1] = optarg;
440                         break;
441                 case 'q':
442                         server_quit = optarg;
443                         break;
444                 case 'd':
445                         if (is_intpos (optarg))
446                                 delay = atoi (optarg);
447                         else
448                                 usage ("Delay must be a positive integer\n");
449                         break;
450                 case 'S':
451 #ifndef HAVE_SSL
452                         terminate (STATE_UNKNOWN,
453                                 "SSL support not available. Install OpenSSL and recompile.");
454 #endif
455                         use_ssl = TRUE;
456                         break;
457                 }
458         }
460         if (server_address == NULL)
461                 usage ("You must provide a server address\n");
463         return OK;
470 void
471 print_usage (void)
473         printf
474                 ("Usage: %s -H host -p port [-w warn_time] [-c crit_time] [-s send]\n"
475                  "         [-e expect] [-W wait] [-t to_sec] [-v]\n", PROGNAME);
482 void
483 print_help (void)
485         print_revision (PROGNAME, "$Revision$");
486         printf
487                 ("Copyright (c) 1999 Ethan Galstad (nagios@nagios.org)\n\n"
488                  "This plugin tests %s connections with the specified host.\n\n",
489                  SERVICE);
490         print_usage ();
491         printf
492                 ("Options:\n"
493                  " -H, --hostname=ADDRESS\n"
494                  "    Host name argument for servers using host headers (use numeric\n"
495                  "    address if possible to bypass DNS lookup).\n"
496                  " -p, --port=INTEGER\n"
497                  "    Port number\n"
498                  " -s, --send=STRING\n"
499                  "    String to send to the server\n"
500                  " -e, --expect=STRING\n"
501                  "    String to expect in server response"
502                  " -W, --wait=INTEGER\n"
503                  "    Seconds to wait between sending string and polling for response\n"
504                  " -w, --warning=DOUBLE\n"
505                  "    Response time to result in warning status (seconds)\n"
506                  " -c, --critical=DOUBLE\n"
507                  "    Response time to result in critical status (seconds)\n"
508                  " -t, --timeout=INTEGER\n"
509                  "    Seconds before connection times out (default: %d)\n"
510                  " -v"
511                  "    Show details for command-line debugging (do not use with nagios server)\n"
512                  " -h, --help\n"
513                  "    Print detailed help screen\n"
514                  " -V, --version\n"
515                  "    Print version information\n", DEFAULT_SOCKET_TIMEOUT);
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)
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