1 /*****************************************************************************
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.
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.
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.
17 $Id$
19 *****************************************************************************/
21 /* progname "check_tcp" changes depending on symlink called */
22 char *progname;
23 const char *revision = "$Revision$";
24 const char *copyright = "1999-2004";
25 const char *email = "nagiosplug-devel@lists.sourceforge.net";
27 #include "common.h"
28 #include "netutils.h"
29 #include "utils.h"
31 #ifdef HAVE_SSL
32 static int check_cert = FALSE;
33 static int days_till_exp;
34 # define my_recv(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_read(buf, len) : read(sd, buf, len))
35 # define my_send(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0))
36 #else
37 # define my_recv(buf, len) read(sd, buf, len)
38 # define my_send(buf, len) send(sd, buf, len, 0)
39 #endif
41 /* int my_recv(char *, size_t); */
42 static int process_arguments (int, char **);
43 void print_help (void);
44 void print_usage (void);
46 #define EXPECT server_expect[0]
47 static char *SERVICE = "TCP";
48 static char *SEND = NULL;
49 static char *QUIT = NULL;
50 static int PROTOCOL = IPPROTO_TCP; /* most common is default */
51 static int PORT = 0;
53 static int server_port = 0;
54 static char *server_address = NULL;
55 static char *server_send = NULL;
56 static char *server_quit = NULL;
57 static char **server_expect;
58 static size_t server_expect_count = 0;
59 static size_t maxbytes = 0;
60 static char **warn_codes = NULL;
61 static size_t warn_codes_count = 0;
62 static char **crit_codes = NULL;
63 static size_t crit_codes_count = 0;
64 static unsigned int delay = 0;
65 static double warning_time = 0;
66 static double critical_time = 0;
67 static double elapsed_time = 0;
68 static long microsec;
69 static int sd = 0;
70 #define MAXBUF 1024
71 static char buffer[MAXBUF];
72 static int expect_mismatch_state = STATE_WARNING;
74 #define FLAG_SSL 0x01
75 #define FLAG_VERBOSE 0x02
76 #define FLAG_EXACT_MATCH 0x04
77 #define FLAG_TIME_WARN 0x08
78 #define FLAG_TIME_CRIT 0x10
79 #define FLAG_HIDE_OUTPUT 0x20
80 static size_t flags = FLAG_EXACT_MATCH;
82 int
83 main (int argc, char **argv)
84 {
85 int result = STATE_UNKNOWN;
86 int i;
87 char *status = NULL;
88 struct timeval tv;
89 size_t len, match = -1;
91 setlocale (LC_ALL, "");
92 bindtextdomain (PACKAGE, LOCALEDIR);
93 textdomain (PACKAGE);
95 /* determine program- and service-name quickly */
96 progname = strrchr(argv[0], '/');
97 if(progname != NULL) progname++;
98 else progname = argv[0];
100 len = strlen(progname);
101 if(len > 6 && !memcmp(progname, "check_", 6)) {
102 SERVICE = progname + 6;
103 for(i = 0; i < len - 6; i++)
104 SERVICE[i] = toupper(SERVICE[i]);
105 }
107 /* set up a resonable buffer at first (will be realloc()'ed if
108 * user specifies other options) */
109 server_expect = calloc(sizeof(char *), 2);
111 /* determine defaults for this service's protocol */
112 if (!strncmp(SERVICE, "UDP", 3)) {
113 PROTOCOL = IPPROTO_UDP;
114 }
115 else if (!strncmp(SERVICE, "FTP", 3)) {
116 EXPECT = "220";
117 QUIT = "QUIT\r\n";
118 PORT = 21;
119 }
120 else if (!strncmp(SERVICE, "POP", 3) || !strncmp(SERVICE, "POP3", 4)) {
121 EXPECT = "+OK";
122 QUIT = "QUIT\r\n";
123 PORT = 110;
124 }
125 else if (!strncmp(SERVICE, "SMTP", 4)) {
126 EXPECT = "220";
127 QUIT = "QUIT\r\n";
128 PORT = 25;
129 }
130 else if (!strncmp(SERVICE, "IMAP", 4)) {
131 EXPECT = "* OK";
132 QUIT = "a1 LOGOUT\r\n";
133 PORT = 143;
134 }
135 #ifdef HAVE_SSL
136 else if (!strncmp(SERVICE, "SIMAP", 5)) {
137 EXPECT = "* OK";
138 QUIT = "a1 LOGOUT\r\n";
139 flags |= FLAG_SSL;
140 PORT = 993;
141 }
142 else if (!strncmp(SERVICE, "SPOP", 4)) {
143 EXPECT = "+OK";
144 QUIT = "QUIT\r\n";
145 flags |= FLAG_SSL;
146 PORT = 995;
147 }
148 else if (!strncmp(SERVICE, "SSMTP", 5)) {
149 EXPECT = "220";
150 QUIT = "QUIT\r\n";
151 flags |= FLAG_SSL;
152 PORT = 465;
153 }
154 else if (!strncmp(SERVICE, "JABBER", 6)) {
155 SEND = "<stream:stream to=\'host\' xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'>\n";
156 EXPECT = "<?xml version=\'1.0\'?><stream:stream xmlns:stream=\'http://etherx.jabber.org/streams\'";
157 QUIT = "</stream:stream>\n";
158 flags |= FLAG_SSL | FLAG_HIDE_OUTPUT;
159 PORT = 5222;
160 }
161 else if (!strncmp (SERVICE, "NNTPS", 5)) {
162 server_expect_count = 2;
163 server_expect[0] = "200";
164 server_expect[1] = "201";
165 QUIT = "QUIT\r\n";
166 flags |= FLAG_SSL;
167 PORT = 563;
168 }
169 #endif
170 else if (!strncmp (SERVICE, "NNTP", 4)) {
171 server_expect_count = 2;
172 server_expect = malloc(sizeof(char *) * server_expect_count);
173 server_expect[0] = strdup("200");
174 server_expect[1] = strdup("201");
175 QUIT = "QUIT\r\n";
176 PORT = 119;
177 }
178 else if (!strncmp(SERVICE, "CLAMD", 5)) {
179 SEND = "PING";
180 EXPECT = "PONG";
181 QUIT = NULL;
182 PORT = 3310;
183 }
184 /* fallthrough check, so it's supposed to use reverse matching */
185 else if (strcmp (SERVICE, "TCP"))
186 usage (_("CRITICAL - Generic check_tcp called with unknown service\n"));
188 server_address = "127.0.0.1";
189 server_port = PORT;
190 server_send = SEND;
191 server_quit = QUIT;
192 status = NULL;
194 if (process_arguments (argc, argv) == ERROR)
195 usage4 (_("Could not parse arguments"));
197 if(flags & FLAG_VERBOSE) {
198 printf("Using service %s\n", SERVICE);
199 printf("Port: %d\n", server_port);
200 printf("flags: 0x%x\n", (int)flags);
201 }
203 if(EXPECT && !server_expect_count)
204 server_expect_count++;
206 if(PROTOCOL==IPPROTO_UDP && !(server_expect_count && server_send)){
207 usage(_("With UDP checks, a send/expect string must be specified."));
208 }
210 /* set up the timer */
211 signal (SIGALRM, socket_timeout_alarm_handler);
212 alarm (socket_timeout);
214 /* try to connect to the host at the given port number */
215 gettimeofday (&tv, NULL);
217 result = np_net_connect (server_address, server_port, &sd, PROTOCOL);
218 if (result == STATE_CRITICAL) return STATE_CRITICAL;
220 #ifdef HAVE_SSL
221 if (flags & FLAG_SSL){
222 result = np_net_ssl_init(sd);
223 if (result == STATE_OK && check_cert == TRUE) {
224 result = np_net_ssl_check_cert(days_till_exp);
225 if(result != STATE_OK) {
226 printf(_("CRITICAL - Cannot retrieve server certificate.\n"));
227 }
228 }
229 }
230 if(result != STATE_OK){
231 np_net_ssl_cleanup();
232 if(sd) close(sd);
233 return result;
234 }
235 #endif /* HAVE_SSL */
237 if (server_send != NULL) { /* Something to send? */
238 my_send(server_send, strlen(server_send));
239 }
241 if (delay > 0) {
242 tv.tv_sec += delay;
243 sleep (delay);
244 }
246 if(flags & FLAG_VERBOSE) {
247 if (server_send) {
248 printf("Send string: %s\n", server_send);
249 }
250 if (server_quit) {
251 printf("Quit string: %s\n", server_quit);
252 }
253 printf("server_expect_count: %d\n", (int)server_expect_count);
254 for(i = 0; i < server_expect_count; i++)
255 printf("\t%d: %s\n", i, server_expect[i]);
256 }
258 /* if(len) later on, we know we have a non-NULL response */
259 len = 0;
260 if (server_expect_count) {
262 /* watch for the expect string */
263 while ((i = my_recv(buffer, sizeof(buffer))) > 0) {
264 status = realloc(status, len + i + 1);
265 memcpy(&status[len], buffer, i);
266 len += i;
268 /* stop reading if user-forced or data-starved */
269 if(i < sizeof(buffer) || (maxbytes && len >= maxbytes))
270 break;
272 if (maxbytes && len >= maxbytes)
273 break;
274 }
276 /* no data when expected, so return critical */
277 if (len == 0)
278 die (STATE_CRITICAL, _("No data received from host\n"));
280 /* force null-termination and strip whitespace from end of output */
281 status[len--] = '\0';
282 /* print raw output if we're debugging */
283 if(flags & FLAG_VERBOSE)
284 printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n",
285 (int)len + 1, status);
286 while(isspace(status[len])) status[len--] = '\0';
288 for (i = 0; i < server_expect_count; i++) {
289 match = -2; /* tag it so we know if we tried and failed */
290 if (flags & FLAG_VERBOSE)
291 printf ("looking for [%s] %s [%s]\n", server_expect[i],
292 (flags & FLAG_EXACT_MATCH) ? "in beginning of" : "anywhere in",
293 status);
295 /* match it. math first in short-circuit */
296 if ((flags & FLAG_EXACT_MATCH && !strncmp(status, server_expect[i], strlen(server_expect[i]))) ||
297 (!(flags & FLAG_EXACT_MATCH) && strstr(status, server_expect[i])))
298 {
299 if(flags & FLAG_VERBOSE) puts("found it");
300 match = i;
301 break;
302 }
303 }
304 }
306 if (server_quit != NULL) {
307 my_send(server_quit, strlen(server_quit));
308 }
309 #ifdef HAVE_SSL
310 np_net_ssl_cleanup();
311 #endif
312 if (sd) close (sd);
314 microsec = deltime (tv);
315 elapsed_time = (double)microsec / 1.0e6;
317 if (flags & FLAG_TIME_CRIT && elapsed_time > critical_time)
318 result = STATE_CRITICAL;
319 else if (flags & FLAG_TIME_WARN && elapsed_time > warning_time)
320 result = STATE_WARNING;
322 /* did we get the response we hoped? */
323 if(match == -2 && result != STATE_CRITICAL)
324 result = expect_mismatch_state;
326 /* reset the alarm */
327 alarm (0);
329 /* this is a bit stupid, because we don't want to print the
330 * response time (which can look ok to the user) if we didn't get
331 * the response we were looking for. if-else */
332 printf(_("%s %s - "), SERVICE, state_text(result));
334 if(match == -2 && len && !(flags & FLAG_HIDE_OUTPUT))
335 printf("Unexpected response from host/socket: %s", status);
336 else {
337 printf("%.3f second response time on ", elapsed_time);
338 if(server_address[0] != '/')
339 printf("port %d", server_port);
340 else
341 printf("socket %s", server_address);
342 }
344 if (match != -2 && !(flags & FLAG_HIDE_OUTPUT) && len)
345 printf (" [%s]", status);
347 /* perf-data doesn't apply when server doesn't talk properly,
348 * so print all zeroes on warn and crit */
349 if(match == -2)
350 printf ("|time=%fs;0.0;0.0;0.0;0.0", elapsed_time);
351 else
352 printf("|%s",
353 fperfdata ("time", elapsed_time, "s",
354 TRUE, warning_time,
355 TRUE, critical_time,
356 TRUE, 0,
357 TRUE, socket_timeout)
358 );
360 putchar('\n');
361 return result;
362 }
366 /* process command-line arguments */
367 static int
368 process_arguments (int argc, char **argv)
369 {
370 int c;
371 int escape = 0;
373 int option = 0;
374 static struct option longopts[] = {
375 {"hostname", required_argument, 0, 'H'},
376 {"critical-time", required_argument, 0, 'c'},
377 {"warning-time", required_argument, 0, 'w'},
378 {"critical-codes", required_argument, 0, 'C'},
379 {"warning-codes", required_argument, 0, 'W'},
380 {"timeout", required_argument, 0, 't'},
381 {"protocol", required_argument, 0, 'P'},
382 {"port", required_argument, 0, 'p'},
383 {"escape", required_argument, 0, 'E'},
384 {"send", required_argument, 0, 's'},
385 {"expect", required_argument, 0, 'e'},
386 {"maxbytes", required_argument, 0, 'm'},
387 {"quit", required_argument, 0, 'q'},
388 {"jail", required_argument, 0, 'j'},
389 {"delay", required_argument, 0, 'd'},
390 {"refuse", required_argument, 0, 'r'},
391 {"mismatch", required_argument, 0, 'M'},
392 {"use-ipv4", no_argument, 0, '4'},
393 {"use-ipv6", no_argument, 0, '6'},
394 {"verbose", no_argument, 0, 'v'},
395 {"version", no_argument, 0, 'V'},
396 {"help", no_argument, 0, 'h'},
397 #ifdef HAVE_SSL
398 {"ssl", no_argument, 0, 'S'},
399 {"certificate", required_argument, 0, 'D'},
400 #endif
401 {0, 0, 0, 0}
402 };
404 if (argc < 2)
405 usage4 (_("No arguments found"));
407 /* backwards compatibility */
408 for (c = 1; c < argc; c++) {
409 if (strcmp ("-to", argv[c]) == 0)
410 strcpy (argv[c], "-t");
411 else if (strcmp ("-wt", argv[c]) == 0)
412 strcpy (argv[c], "-w");
413 else if (strcmp ("-ct", argv[c]) == 0)
414 strcpy (argv[c], "-c");
415 }
417 if (!is_option (argv[1])) {
418 server_address = argv[1];
419 argv[1] = argv[0];
420 argv = &argv[1];
421 argc--;
422 }
424 while (1) {
425 c = getopt_long (argc, argv, "+hVv46EH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:",
426 longopts, &option);
428 if (c == -1 || c == EOF || c == 1)
429 break;
431 switch (c) {
432 case '?': /* print short usage statement if args not parsable */
433 usage2 (_("Unknown argument"), optarg);
434 case 'h': /* help */
435 print_help ();
436 exit (STATE_OK);
437 case 'V': /* version */
438 print_revision (progname, revision);
439 exit (STATE_OK);
440 case 'v': /* verbose mode */
441 flags |= FLAG_VERBOSE;
442 break;
443 case '4':
444 address_family = AF_INET;
445 break;
446 case '6':
447 #ifdef USE_IPV6
448 address_family = AF_INET6;
449 #else
450 usage4 (_("IPv6 support not available"));
451 #endif
452 break;
453 case 'H': /* hostname */
454 server_address = optarg;
455 break;
456 case 'c': /* critical */
457 if (!is_intnonneg (optarg))
458 usage4 (_("Critical threshold must be a positive integer"));
459 else
460 critical_time = strtod (optarg, NULL);
461 flags |= FLAG_TIME_CRIT;
462 break;
463 case 'j': /* hide output */
464 flags |= FLAG_HIDE_OUTPUT;
465 break;
466 case 'w': /* warning */
467 if (!is_intnonneg (optarg))
468 usage4 (_("Warning threshold must be a positive integer"));
469 else
470 warning_time = strtod (optarg, NULL);
471 flags |= FLAG_TIME_WARN;
472 break;
473 case 'C':
474 crit_codes = realloc (crit_codes, ++crit_codes_count);
475 crit_codes[crit_codes_count - 1] = optarg;
476 break;
477 case 'W':
478 warn_codes = realloc (warn_codes, ++warn_codes_count);
479 warn_codes[warn_codes_count - 1] = optarg;
480 break;
481 case 't': /* timeout */
482 if (!is_intpos (optarg))
483 usage4 (_("Timeout interval must be a positive integer"));
484 else
485 socket_timeout = atoi (optarg);
486 break;
487 case 'p': /* port */
488 if (!is_intpos (optarg))
489 usage4 (_("Port must be a positive integer"));
490 else
491 server_port = atoi (optarg);
492 break;
493 case 'E':
494 escape = 1;
495 break;
496 case 's':
497 if (escape)
498 server_send = np_escaped_string(optarg);
499 else
500 asprintf(&server_send, "%s", optarg);
501 break;
502 case 'e': /* expect string (may be repeated) */
503 EXPECT = NULL;
504 flags &= ~FLAG_EXACT_MATCH;
505 if (server_expect_count == 0)
506 server_expect = malloc (sizeof (char *) * (++server_expect_count));
507 else
508 server_expect = realloc (server_expect, sizeof (char *) * (++server_expect_count));
509 server_expect[server_expect_count - 1] = optarg;
510 break;
511 case 'm':
512 if (!is_intpos (optarg))
513 usage4 (_("Maxbytes must be a positive integer"));
514 else
515 maxbytes = strtol (optarg, NULL, 0);
516 case 'q':
517 if (escape)
518 server_quit = np_escaped_string(optarg);
519 else
520 asprintf(&server_quit, "%s\r\n", optarg);
521 break;
522 case 'r':
523 if (!strncmp(optarg,"ok",2))
524 econn_refuse_state = STATE_OK;
525 else if (!strncmp(optarg,"warn",4))
526 econn_refuse_state = STATE_WARNING;
527 else if (!strncmp(optarg,"crit",4))
528 econn_refuse_state = STATE_CRITICAL;
529 else
530 usage4 (_("Refuse must be one of ok, warn, crit"));
531 break;
532 case 'M':
533 if (!strncmp(optarg,"ok",2))
534 expect_mismatch_state = STATE_OK;
535 else if (!strncmp(optarg,"warn",4))
536 expect_mismatch_state = STATE_WARNING;
537 else if (!strncmp(optarg,"crit",4))
538 expect_mismatch_state = STATE_CRITICAL;
539 else
540 usage4 (_("Mismatch must be one of ok, warn, crit"));
541 break;
542 case 'd':
543 if (is_intpos (optarg))
544 delay = atoi (optarg);
545 else
546 usage4 (_("Delay must be a positive integer"));
547 break;
548 case 'D': /* Check SSL cert validity - days 'til certificate expiration */
549 #ifdef HAVE_SSL
550 # ifdef USE_OPENSSL /* XXX */
551 if (!is_intnonneg (optarg))
552 usage2 (_("Invalid certificate expiration period"), optarg);
553 days_till_exp = atoi (optarg);
554 check_cert = TRUE;
555 flags |= FLAG_SSL;
556 break;
557 # endif /* USE_OPENSSL */
558 #endif
559 /* fallthrough if we don't have ssl */
560 case 'S':
561 #ifdef HAVE_SSL
562 flags |= FLAG_SSL;
563 #else
564 die (STATE_UNKNOWN, _("Invalid option - SSL is not available"));
565 #endif
566 break;
567 }
568 }
570 if (server_address == NULL)
571 usage4 (_("You must provide a server address"));
572 else if (server_address[0] != '/' && is_host (server_address) == FALSE)
573 die (STATE_CRITICAL, "%s: %s - %s\n", progname, _("Invalid hostname, address or socket"), server_address);
575 return TRUE;
576 }
579 void
580 print_help (void)
581 {
582 print_revision (progname, revision);
584 printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
585 printf (COPYRIGHT, copyright, email);
587 printf (_("This plugin tests %s connections with the specified host (or unix socket).\n\n"),
588 SERVICE);
590 print_usage ();
592 printf (_(UT_HELP_VRSN));
594 printf (_(UT_HOST_PORT), 'p', "none");
596 printf (_(UT_IPv46));
598 printf (_("\
599 -E, --escape\n\
600 Can use \\n, \\r, \\t or \\ in send or quit string.\n\
601 Default: nothing added to send, \\r\\n added to end of quit\n\
602 -s, --send=STRING\n\
603 String to send to the server\n\
604 -e, --expect=STRING\n\
605 String to expect in server response\n\
606 -q, --quit=STRING\n\
607 String to send server to initiate a clean close of the connection\n"));
609 printf (_("\
610 -r, --refuse=ok|warn|crit\n\
611 Accept tcp refusals with states ok, warn, crit (default: crit)\n\
612 -M, --mismatch=ok|warn|crit\n\
613 Accept expected string mismatches with states ok, warn, crit (default: warn)\n\
614 -j, --jail\n\
615 Hide output from TCP socket\n\
616 -m, --maxbytes=INTEGER\n\
617 Close connection once more than this number of bytes are received\n\
618 -d, --delay=INTEGER\n\
619 Seconds to wait between sending string and polling for response\n"));
621 #ifdef HAVE_SSL
622 printf (_("\
623 -D, --certificate=INTEGER\n\
624 Minimum number of days a certificate has to be valid.\n\
625 -S, --ssl\n\
626 Use SSL for the connection.\n"));
627 #endif
629 printf (_(UT_WARN_CRIT));
631 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
633 printf (_(UT_VERBOSE));
635 printf (_(UT_SUPPORT));
636 }
639 void
640 print_usage (void)
641 {
642 printf ("\
643 Usage: %s -H host -p port [-w <warning time>] [-c <critical time>]\n\
644 [-s <send string>] [-e <expect string>] [-q <quit string>]\n\
645 [-m <maximum bytes>] [-d <delay>] [-t <timeout seconds>]\n\
646 [-r <refuse state>] [-M <mismatch state>] [-v] [-4|-6] [-j]\n\
647 [-D <days to cert expiry>] [-S <use SSL>] [-E]\n", progname);
648 }