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