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