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", PORT);
200 printf("flags: 0x%x\n", (int)flags);
201 }
203 if(EXPECT && !server_expect_count)
204 server_expect_count++;
206 /* set up the timer */
207 signal (SIGALRM, socket_timeout_alarm_handler);
208 alarm (socket_timeout);
210 /* try to connect to the host at the given port number */
211 gettimeofday (&tv, NULL);
213 result = np_net_connect (server_address, server_port, &sd, PROTOCOL);
214 if (result == STATE_CRITICAL) return STATE_CRITICAL;
216 #ifdef HAVE_SSL
217 if (flags & FLAG_SSL){
218 result = np_net_ssl_init(sd);
219 if (result == STATE_OK && check_cert == TRUE) {
220 result = np_net_ssl_check_cert(days_till_exp);
221 if(result != STATE_OK) {
222 printf(_("CRITICAL - Cannot retrieve server certificate.\n"));
223 }
224 }
225 }
226 if(result != STATE_OK){
227 np_net_ssl_cleanup();
228 if(sd) close(sd);
229 return result;
230 }
231 #endif /* HAVE_SSL */
233 if (server_send != NULL) { /* Something to send? */
234 my_send(server_send, strlen(server_send));
235 }
237 if (delay > 0) {
238 tv.tv_sec += delay;
239 sleep (delay);
240 }
242 if(flags & FLAG_VERBOSE) {
243 printf("server_expect_count: %d\n", (int)server_expect_count);
244 for(i = 0; i < server_expect_count; i++)
245 printf("\t%d: %s\n", i, server_expect[i]);
246 }
248 /* if(len) later on, we know we have a non-NULL response */
249 len = 0;
250 if (server_expect_count) {
252 /* watch for the expect string */
253 while ((i = my_recv(buffer, sizeof(buffer))) > 0) {
254 status = realloc(status, len + i + 1);
255 memcpy(&status[len], buffer, i);
256 len += i;
258 /* stop reading if user-forced or data-starved */
259 if(i < sizeof(buffer) || (maxbytes && len >= maxbytes))
260 break;
262 if (maxbytes && len >= maxbytes)
263 break;
264 }
266 /* no data when expected, so return critical */
267 if (len == 0)
268 die (STATE_CRITICAL, _("No data received from host\n"));
270 /* force null-termination and strip whitespace from end of output */
271 status[len--] = '\0';
272 /* print raw output if we're debugging */
273 if(flags & FLAG_VERBOSE)
274 printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n",
275 (int)len + 1, status);
276 while(isspace(status[len])) status[len--] = '\0';
278 for (i = 0; i < server_expect_count; i++) {
279 match = -2; /* tag it so we know if we tried and failed */
280 if (flags & FLAG_VERBOSE)
281 printf ("looking for [%s] %s [%s]\n", server_expect[i],
282 (flags & FLAG_EXACT_MATCH) ? "in beginning of" : "anywhere in",
283 status);
285 /* match it. math first in short-circuit */
286 if ((flags & FLAG_EXACT_MATCH && !strncmp(status, server_expect[i], strlen(server_expect[i]))) ||
287 (!(flags & FLAG_EXACT_MATCH) && strstr(status, server_expect[i])))
288 {
289 if(flags & FLAG_VERBOSE) puts("found it");
290 match = i;
291 break;
292 }
293 }
294 }
296 if (server_quit != NULL) {
297 my_send(server_quit, strlen(server_quit));
298 }
299 #ifdef HAVE_SSL
300 np_net_ssl_cleanup();
301 #endif
302 if (sd) close (sd);
304 microsec = deltime (tv);
305 elapsed_time = (double)microsec / 1.0e6;
307 if (flags & FLAG_TIME_CRIT && elapsed_time > critical_time)
308 result = STATE_CRITICAL;
309 else if (flags & FLAG_TIME_WARN && elapsed_time > warning_time)
310 result = STATE_WARNING;
312 /* did we get the response we hoped? */
313 if(match == -2 && result != STATE_CRITICAL)
314 result = expect_mismatch_state;
316 /* reset the alarm */
317 alarm (0);
319 /* this is a bit stupid, because we don't want to print the
320 * response time (which can look ok to the user) if we didn't get
321 * the response we were looking for. if-else */
322 printf(_("%s %s - "), SERVICE, state_text(result));
324 if(match == -2 && len && !(flags & FLAG_HIDE_OUTPUT))
325 printf("Unexpected response from host/socket: %s", status);
326 else {
327 printf("%.3f second response time on ", elapsed_time);
328 if(server_address[0] != '/')
329 printf("port %d", server_port);
330 else
331 printf("socket %s", server_address);
332 }
334 if (match != -2 && !(flags & FLAG_HIDE_OUTPUT) && len)
335 printf (" [%s]", status);
337 /* perf-data doesn't apply when server doesn't talk properly,
338 * so print all zeroes on warn and crit */
339 if(match == -2)
340 printf ("|time=%fs;0.0;0.0;0.0;0.0", elapsed_time);
341 else
342 printf("|%s",
343 fperfdata ("time", elapsed_time, "s",
344 TRUE, warning_time,
345 TRUE, critical_time,
346 TRUE, 0,
347 TRUE, socket_timeout)
348 );
350 putchar('\n');
351 return result;
352 }
356 /* process command-line arguments */
357 static int
358 process_arguments (int argc, char **argv)
359 {
360 int c;
362 int option = 0;
363 static struct option longopts[] = {
364 {"hostname", required_argument, 0, 'H'},
365 {"critical-time", required_argument, 0, 'c'},
366 {"warning-time", required_argument, 0, 'w'},
367 {"critical-codes", required_argument, 0, 'C'},
368 {"warning-codes", required_argument, 0, 'W'},
369 {"timeout", required_argument, 0, 't'},
370 {"protocol", required_argument, 0, 'P'},
371 {"port", required_argument, 0, 'p'},
372 {"send", required_argument, 0, 's'},
373 {"expect", required_argument, 0, 'e'},
374 {"maxbytes", required_argument, 0, 'm'},
375 {"quit", required_argument, 0, 'q'},
376 {"jail", required_argument, 0, 'j'},
377 {"delay", required_argument, 0, 'd'},
378 {"refuse", required_argument, 0, 'r'},
379 {"mismatch", required_argument, 0, 'M'},
380 {"use-ipv4", no_argument, 0, '4'},
381 {"use-ipv6", no_argument, 0, '6'},
382 {"verbose", no_argument, 0, 'v'},
383 {"version", no_argument, 0, 'V'},
384 {"help", no_argument, 0, 'h'},
385 #ifdef HAVE_SSL
386 {"ssl", no_argument, 0, 'S'},
387 {"certificate", required_argument, 0, 'D'},
388 #endif
389 {0, 0, 0, 0}
390 };
392 if (argc < 2)
393 usage4 (_("No arguments found"));
395 /* backwards compatibility */
396 for (c = 1; c < argc; c++) {
397 if (strcmp ("-to", argv[c]) == 0)
398 strcpy (argv[c], "-t");
399 else if (strcmp ("-wt", argv[c]) == 0)
400 strcpy (argv[c], "-w");
401 else if (strcmp ("-ct", argv[c]) == 0)
402 strcpy (argv[c], "-c");
403 }
405 if (!is_option (argv[1])) {
406 server_address = argv[1];
407 argv[1] = argv[0];
408 argv = &argv[1];
409 argc--;
410 }
412 while (1) {
413 c = getopt_long (argc, argv, "+hVv46H:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:",
414 longopts, &option);
416 if (c == -1 || c == EOF || c == 1)
417 break;
419 switch (c) {
420 case '?': /* print short usage statement if args not parsable */
421 usage2 (_("Unknown argument"), optarg);
422 case 'h': /* help */
423 print_help ();
424 exit (STATE_OK);
425 case 'V': /* version */
426 print_revision (progname, revision);
427 exit (STATE_OK);
428 case 'v': /* verbose mode */
429 flags |= FLAG_VERBOSE;
430 break;
431 case '4':
432 address_family = AF_INET;
433 break;
434 case '6':
435 #ifdef USE_IPV6
436 address_family = AF_INET6;
437 #else
438 usage4 (_("IPv6 support not available"));
439 #endif
440 break;
441 case 'H': /* hostname */
442 server_address = optarg;
443 break;
444 case 'c': /* critical */
445 if (!is_intnonneg (optarg))
446 usage4 (_("Critical threshold must be a positive integer"));
447 else
448 critical_time = strtod (optarg, NULL);
449 flags |= FLAG_TIME_CRIT;
450 break;
451 case 'j': /* hide output */
452 flags |= FLAG_HIDE_OUTPUT;
453 break;
454 case 'w': /* warning */
455 if (!is_intnonneg (optarg))
456 usage4 (_("Warning threshold must be a positive integer"));
457 else
458 warning_time = strtod (optarg, NULL);
459 flags |= FLAG_TIME_WARN;
460 break;
461 case 'C':
462 crit_codes = realloc (crit_codes, ++crit_codes_count);
463 crit_codes[crit_codes_count - 1] = optarg;
464 break;
465 case 'W':
466 warn_codes = realloc (warn_codes, ++warn_codes_count);
467 warn_codes[warn_codes_count - 1] = optarg;
468 break;
469 case 't': /* timeout */
470 if (!is_intpos (optarg))
471 usage4 (_("Timeout interval must be a positive integer"));
472 else
473 socket_timeout = atoi (optarg);
474 break;
475 case 'p': /* port */
476 if (!is_intpos (optarg))
477 usage4 (_("Port must be a positive integer"));
478 else
479 server_port = atoi (optarg);
480 break;
481 case 's':
482 server_send = optarg;
483 break;
484 case 'e': /* expect string (may be repeated) */
485 EXPECT = NULL;
486 flags &= ~FLAG_EXACT_MATCH;
487 if (server_expect_count == 0)
488 server_expect = malloc (sizeof (char *) * (++server_expect_count));
489 else
490 server_expect = realloc (server_expect, sizeof (char *) * (++server_expect_count));
491 server_expect[server_expect_count - 1] = optarg;
492 break;
493 case 'm':
494 if (!is_intpos (optarg))
495 usage4 (_("Maxbytes must be a positive integer"));
496 else
497 maxbytes = strtol (optarg, NULL, 0);
498 case 'q':
499 asprintf(&server_quit, "%s\r\n", optarg);
500 break;
501 case 'r':
502 if (!strncmp(optarg,"ok",2))
503 econn_refuse_state = STATE_OK;
504 else if (!strncmp(optarg,"warn",4))
505 econn_refuse_state = STATE_WARNING;
506 else if (!strncmp(optarg,"crit",4))
507 econn_refuse_state = STATE_CRITICAL;
508 else
509 usage4 (_("Refuse must be one of ok, warn, crit"));
510 break;
511 case 'M':
512 if (!strncmp(optarg,"ok",2))
513 expect_mismatch_state = STATE_OK;
514 else if (!strncmp(optarg,"warn",4))
515 expect_mismatch_state = STATE_WARNING;
516 else if (!strncmp(optarg,"crit",4))
517 expect_mismatch_state = STATE_CRITICAL;
518 else
519 usage4 (_("Mismatch must be one of ok, warn, crit"));
520 break;
521 case 'd':
522 if (is_intpos (optarg))
523 delay = atoi (optarg);
524 else
525 usage4 (_("Delay must be a positive integer"));
526 break;
527 case 'D': /* Check SSL cert validity - days 'til certificate expiration */
528 #ifdef HAVE_SSL
529 # ifdef USE_OPENSSL /* XXX */
530 if (!is_intnonneg (optarg))
531 usage2 (_("Invalid certificate expiration period"), optarg);
532 days_till_exp = atoi (optarg);
533 check_cert = TRUE;
534 flags |= FLAG_SSL;
535 break;
536 # endif /* USE_OPENSSL */
537 #endif
538 /* fallthrough if we don't have ssl */
539 case 'S':
540 #ifdef HAVE_SSL
541 flags |= FLAG_SSL;
542 #else
543 die (STATE_UNKNOWN, _("Invalid option - SSL is not available"));
544 #endif
545 break;
546 }
547 }
549 if (server_address == NULL)
550 usage4 (_("You must provide a server address"));
551 else if (server_address[0] != '/' && is_host (server_address) == FALSE)
552 die (STATE_CRITICAL, "%s: %s - %s\n", progname, _("Invalid hostname, address or socket"), server_address);
554 return TRUE;
555 }
558 void
559 print_help (void)
560 {
561 print_revision (progname, revision);
563 printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
564 printf (COPYRIGHT, copyright, email);
566 printf (_("This plugin tests %s connections with the specified host (or unix socket).\n\n"),
567 SERVICE);
569 print_usage ();
571 printf (_(UT_HELP_VRSN));
573 printf (_(UT_HOST_PORT), 'p', "none");
575 printf (_(UT_IPv46));
577 printf (_("\
578 -s, --send=STRING\n\
579 String to send to the server\n\
580 -e, --expect=STRING\n\
581 String to expect in server response\n\
582 -q, --quit=STRING\n\
583 String to send server to initiate a clean close of the connection\n"));
585 printf (_("\
586 -r, --refuse=ok|warn|crit\n\
587 Accept tcp refusals with states ok, warn, crit (default: crit)\n\
588 -M, --mismatch=ok|warn|crit\n\
589 Accept expected string mismatches with states ok, warn, crit (default: warn)\n\
590 -j, --jail\n\
591 Hide output from TCP socket\n\
592 -m, --maxbytes=INTEGER\n\
593 Close connection once more than this number of bytes are received\n\
594 -d, --delay=INTEGER\n\
595 Seconds to wait between sending string and polling for response\n"));
597 #ifdef HAVE_SSL
598 printf (_("\
599 -D, --certificate=INTEGER\n\
600 Minimum number of days a certificate has to be valid.\n\
601 -S, --ssl\n\
602 Use SSL for the connection.\n"));
603 #endif
605 printf (_(UT_WARN_CRIT));
607 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
609 printf (_(UT_VERBOSE));
611 printf (_(UT_SUPPORT));
612 }
615 void
616 print_usage (void)
617 {
618 printf ("\
619 Usage: %s -H host -p port [-w <warning time>] [-c <critical time>]\n\
620 [-s <send string>] [-e <expect string>] [-q <quit string>]\n\
621 [-m <maximum bytes>] [-d <delay>] [-t <timeout seconds>]\n\
622 [-r <refuse state>] [-M <mismatch state>] [-v] [-4|-6] [-j]\n\
623 [-D <days to cert expiry>] [-S <use SSL>]\n", progname);
624 }