1 /*****************************************************************************
3 * Nagios check_tcp plugin
6 * Copyright (c) 1999-2008 Nagios Plugins Development Team
8 * Last Modified: $Date$
12 * This file contains the check_tcp plugin
15 * This program is free software: you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation, either version 3 of the License, or
18 * (at your option) any later version.
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * You should have received a copy of the GNU General Public License
26 * along with this program. If not, see <http://www.gnu.org/licenses/>.
30 *****************************************************************************/
32 /* progname "check_tcp" changes depending on symlink called */
34 const char *revision
= "$Revision$";
35 const char *copyright
= "1999-2008";
36 const char *email
= "nagiosplug-devel@lists.sourceforge.net";
41 #include "utils_tcp.h"
44 static int check_cert
= FALSE
;
45 static int days_till_exp
;
46 # define my_recv(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_read(buf, len) : read(sd, buf, len))
47 # define my_send(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0))
49 # define my_recv(buf, len) read(sd, buf, len)
50 # define my_send(buf, len) send(sd, buf, len, 0)
53 /* int my_recv(char *, size_t); */
54 static int process_arguments (int, char **);
55 void print_help (void);
56 void print_usage (void);
58 #define EXPECT server_expect[0]
59 static char *SERVICE
= "TCP";
60 static char *SEND
= NULL
;
61 static char *QUIT
= NULL
;
62 static int PROTOCOL
= IPPROTO_TCP
; /* most common is default */
65 static int server_port
= 0;
66 static char *server_address
= NULL
;
67 static char *server_send
= NULL
;
68 static char *server_quit
= NULL
;
69 static char **server_expect
;
70 static size_t server_expect_count
= 0;
71 static size_t maxbytes
= 0;
72 static char **warn_codes
= NULL
;
73 static size_t warn_codes_count
= 0;
74 static char **crit_codes
= NULL
;
75 static size_t crit_codes_count
= 0;
76 static unsigned int delay
= 0;
77 static double warning_time
= 0;
78 static double critical_time
= 0;
79 static double elapsed_time
= 0;
83 static char buffer
[MAXBUF
];
84 static int expect_mismatch_state
= STATE_WARNING
;
87 #define FLAG_VERBOSE 0x02
88 #define FLAG_EXACT_MATCH 0x04
89 #define FLAG_TIME_WARN 0x08
90 #define FLAG_TIME_CRIT 0x10
91 #define FLAG_HIDE_OUTPUT 0x20
92 #define FLAG_MATCH_ALL 0x40
93 static size_t flags
= FLAG_EXACT_MATCH
;
96 main (int argc
, char **argv
)
98 int result
= STATE_UNKNOWN
;
105 setlocale (LC_ALL
, "");
106 bindtextdomain (PACKAGE
, LOCALEDIR
);
107 textdomain (PACKAGE
);
109 /* determine program- and service-name quickly */
110 progname
= strrchr(argv
[0], '/');
111 if(progname
!= NULL
) progname
++;
112 else progname
= argv
[0];
114 len
= strlen(progname
);
115 if(len
> 6 && !memcmp(progname
, "check_", 6)) {
116 SERVICE
= strdup(progname
+ 6);
117 for(i
= 0; i
< len
- 6; i
++)
118 SERVICE
[i
] = toupper(SERVICE
[i
]);
121 /* set up a resonable buffer at first (will be realloc()'ed if
122 * user specifies other options) */
123 server_expect
= calloc(sizeof(char *), 2);
125 /* determine defaults for this service's protocol */
126 if (!strncmp(SERVICE
, "UDP", 3)) {
127 PROTOCOL
= IPPROTO_UDP
;
129 else if (!strncmp(SERVICE
, "FTP", 3)) {
134 else if (!strncmp(SERVICE
, "POP", 3) || !strncmp(SERVICE
, "POP3", 4)) {
139 else if (!strncmp(SERVICE
, "SMTP", 4)) {
144 else if (!strncmp(SERVICE
, "IMAP", 4)) {
146 QUIT
= "a1 LOGOUT\r\n";
150 else if (!strncmp(SERVICE
, "SIMAP", 5)) {
152 QUIT
= "a1 LOGOUT\r\n";
156 else if (!strncmp(SERVICE
, "SPOP", 4)) {
162 else if (!strncmp(SERVICE
, "SSMTP", 5)) {
168 else if (!strncmp(SERVICE
, "JABBER", 6)) {
169 SEND
= "<stream:stream to=\'host\' xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'>\n";
170 EXPECT
= "<?xml version=\'1.0\'?><stream:stream xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'";
171 QUIT
= "</stream:stream>\n";
172 flags
|= FLAG_HIDE_OUTPUT
;
175 else if (!strncmp (SERVICE
, "NNTPS", 5)) {
176 server_expect_count
= 2;
177 server_expect
[0] = "200";
178 server_expect
[1] = "201";
184 else if (!strncmp (SERVICE
, "NNTP", 4)) {
185 server_expect_count
= 2;
186 server_expect
= malloc(sizeof(char *) * server_expect_count
);
187 server_expect
[0] = strdup("200");
188 server_expect
[1] = strdup("201");
192 else if (!strncmp(SERVICE
, "CLAMD", 5)) {
198 /* fallthrough check, so it's supposed to use reverse matching */
199 else if (strcmp (SERVICE
, "TCP"))
200 usage (_("CRITICAL - Generic check_tcp called with unknown service\n"));
202 server_address
= "127.0.0.1";
208 if (process_arguments (argc
, argv
) == ERROR
)
209 usage4 (_("Could not parse arguments"));
211 if(flags
& FLAG_VERBOSE
) {
212 printf("Using service %s\n", SERVICE
);
213 printf("Port: %d\n", server_port
);
214 printf("flags: 0x%x\n", (int)flags
);
217 if(EXPECT
&& !server_expect_count
)
218 server_expect_count
++;
220 if(PROTOCOL
==IPPROTO_UDP
&& !(server_expect_count
&& server_send
)){
221 usage(_("With UDP checks, a send/expect string must be specified."));
224 /* set up the timer */
225 signal (SIGALRM
, socket_timeout_alarm_handler
);
226 alarm (socket_timeout
);
228 /* try to connect to the host at the given port number */
229 gettimeofday (&tv
, NULL
);
231 result
= np_net_connect (server_address
, server_port
, &sd
, PROTOCOL
);
232 if (result
== STATE_CRITICAL
) return STATE_CRITICAL
;
235 if (flags
& FLAG_SSL
){
236 result
= np_net_ssl_init(sd
);
237 if (result
== STATE_OK
&& check_cert
== TRUE
) {
238 result
= np_net_ssl_check_cert(days_till_exp
);
239 if(result
!= STATE_OK
) {
240 printf(_("CRITICAL - Cannot retrieve server certificate.\n"));
244 if(result
!= STATE_OK
){
245 np_net_ssl_cleanup();
249 #endif /* HAVE_SSL */
251 if (server_send
!= NULL
) { /* Something to send? */
252 my_send(server_send
, strlen(server_send
));
260 if(flags
& FLAG_VERBOSE
) {
262 printf("Send string: %s\n", server_send
);
265 printf("Quit string: %s\n", server_quit
);
267 printf("server_expect_count: %d\n", (int)server_expect_count
);
268 for(i
= 0; i
< server_expect_count
; i
++)
269 printf("\t%d: %s\n", i
, server_expect
[i
]);
272 /* if(len) later on, we know we have a non-NULL response */
274 if (server_expect_count
) {
276 /* watch for the expect string */
277 while ((i
= my_recv(buffer
, sizeof(buffer
))) > 0) {
278 status
= realloc(status
, len
+ i
+ 1);
279 memcpy(&status
[len
], buffer
, i
);
282 /* stop reading if user-forced or data-starved */
283 if(i
< sizeof(buffer
) || (maxbytes
&& len
>= maxbytes
))
286 if (maxbytes
&& len
>= maxbytes
)
290 /* no data when expected, so return critical */
292 die (STATE_CRITICAL
, _("No data received from host\n"));
294 /* force null-termination and strip whitespace from end of output */
295 status
[len
--] = '\0';
296 /* print raw output if we're debugging */
297 if(flags
& FLAG_VERBOSE
)
298 printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n",
299 (int)len
+ 1, status
);
300 while(isspace(status
[len
])) status
[len
--] = '\0';
302 match
= np_expect_match(status
,
305 (flags
& FLAG_MATCH_ALL
? TRUE
: FALSE
),
306 (flags
& FLAG_EXACT_MATCH
? TRUE
: FALSE
),
307 (flags
& FLAG_VERBOSE
? TRUE
: FALSE
));
310 if (server_quit
!= NULL
) {
311 my_send(server_quit
, strlen(server_quit
));
314 np_net_ssl_cleanup();
318 microsec
= deltime (tv
);
319 elapsed_time
= (double)microsec
/ 1.0e6
;
321 if (flags
& FLAG_TIME_CRIT
&& elapsed_time
> critical_time
)
322 result
= STATE_CRITICAL
;
323 else if (flags
& FLAG_TIME_WARN
&& elapsed_time
> warning_time
)
324 result
= STATE_WARNING
;
326 /* did we get the response we hoped? */
327 if(match
== FALSE
&& result
!= STATE_CRITICAL
)
328 result
= expect_mismatch_state
;
330 /* reset the alarm */
333 /* this is a bit stupid, because we don't want to print the
334 * response time (which can look ok to the user) if we didn't get
335 * the response we were looking for. if-else */
336 printf("%s %s - ", SERVICE
, state_text(result
));
338 if(match
== FALSE
&& len
&& !(flags
& FLAG_HIDE_OUTPUT
))
339 printf("Unexpected response from host/socket: %s", status
);
342 printf("Unexpected response from host/socket on ");
344 printf("%.3f second response time on ", elapsed_time
);
345 if(server_address
[0] != '/')
346 printf("port %d", server_port
);
348 printf("socket %s", server_address
);
351 if (match
!= FALSE
&& !(flags
& FLAG_HIDE_OUTPUT
) && len
)
352 printf (" [%s]", status
);
354 /* perf-data doesn't apply when server doesn't talk properly,
355 * so print all zeroes on warn and crit. Use fperfdata since
356 * localisation settings can make different outputs */
359 fperfdata ("time", elapsed_time
, "s",
360 (flags
& FLAG_TIME_WARN
? TRUE
: FALSE
), 0,
361 (flags
& FLAG_TIME_CRIT
? TRUE
: FALSE
), 0,
363 TRUE
, socket_timeout
)
367 fperfdata ("time", elapsed_time
, "s",
368 (flags
& FLAG_TIME_WARN
? TRUE
: FALSE
), warning_time
,
369 (flags
& FLAG_TIME_CRIT
? TRUE
: FALSE
), critical_time
,
371 TRUE
, socket_timeout
)
380 /* process command-line arguments */
382 process_arguments (int argc
, char **argv
)
388 static struct option longopts
[] = {
389 {"hostname", required_argument
, 0, 'H'},
390 {"critical", required_argument
, 0, 'c'},
391 {"warning", required_argument
, 0, 'w'},
392 {"critical-codes", required_argument
, 0, 'C'},
393 {"warning-codes", required_argument
, 0, 'W'},
394 {"timeout", required_argument
, 0, 't'},
395 {"protocol", required_argument
, 0, 'P'},
396 {"port", required_argument
, 0, 'p'},
397 {"escape", required_argument
, 0, 'E'},
398 {"all", required_argument
, 0, 'A'},
399 {"send", required_argument
, 0, 's'},
400 {"expect", required_argument
, 0, 'e'},
401 {"maxbytes", required_argument
, 0, 'm'},
402 {"quit", required_argument
, 0, 'q'},
403 {"jail", no_argument
, 0, 'j'},
404 {"delay", required_argument
, 0, 'd'},
405 {"refuse", required_argument
, 0, 'r'},
406 {"mismatch", required_argument
, 0, 'M'},
407 {"use-ipv4", no_argument
, 0, '4'},
408 {"use-ipv6", no_argument
, 0, '6'},
409 {"verbose", no_argument
, 0, 'v'},
410 {"version", no_argument
, 0, 'V'},
411 {"help", no_argument
, 0, 'h'},
413 {"ssl", no_argument
, 0, 'S'},
414 {"certificate", required_argument
, 0, 'D'},
420 usage4 (_("No arguments found"));
422 /* backwards compatibility */
423 for (c
= 1; c
< argc
; c
++) {
424 if (strcmp ("-to", argv
[c
]) == 0)
425 strcpy (argv
[c
], "-t");
426 else if (strcmp ("-wt", argv
[c
]) == 0)
427 strcpy (argv
[c
], "-w");
428 else if (strcmp ("-ct", argv
[c
]) == 0)
429 strcpy (argv
[c
], "-c");
432 if (!is_option (argv
[1])) {
433 server_address
= argv
[1];
440 c
= getopt_long (argc
, argv
, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:",
443 if (c
== -1 || c
== EOF
|| c
== 1)
447 case '?': /* print short usage statement if args not parsable */
452 case 'V': /* version */
453 print_revision (progname
, revision
);
455 case 'v': /* verbose mode */
456 flags
|= FLAG_VERBOSE
;
459 address_family
= AF_INET
;
463 address_family
= AF_INET6
;
465 usage4 (_("IPv6 support not available"));
468 case 'H': /* hostname */
469 server_address
= optarg
;
471 case 'c': /* critical */
472 critical_time
= strtod (optarg
, NULL
);
473 flags
|= FLAG_TIME_CRIT
;
475 case 'j': /* hide output */
476 flags
|= FLAG_HIDE_OUTPUT
;
478 case 'w': /* warning */
479 warning_time
= strtod (optarg
, NULL
);
480 flags
|= FLAG_TIME_WARN
;
483 crit_codes
= realloc (crit_codes
, ++crit_codes_count
);
484 crit_codes
[crit_codes_count
- 1] = optarg
;
487 warn_codes
= realloc (warn_codes
, ++warn_codes_count
);
488 warn_codes
[warn_codes_count
- 1] = optarg
;
490 case 't': /* timeout */
491 if (!is_intpos (optarg
))
492 usage4 (_("Timeout interval must be a positive integer"));
494 socket_timeout
= atoi (optarg
);
497 if (!is_intpos (optarg
))
498 usage4 (_("Port must be a positive integer"));
500 server_port
= atoi (optarg
);
507 server_send
= np_escaped_string(optarg
);
509 asprintf(&server_send
, "%s", optarg
);
511 case 'e': /* expect string (may be repeated) */
512 flags
&= ~FLAG_EXACT_MATCH
;
513 if (server_expect_count
== 0)
514 server_expect
= malloc (sizeof (char *) * (++server_expect_count
));
516 server_expect
= realloc (server_expect
, sizeof (char *) * (++server_expect_count
));
517 server_expect
[server_expect_count
- 1] = optarg
;
520 if (!is_intpos (optarg
))
521 usage4 (_("Maxbytes must be a positive integer"));
523 maxbytes
= strtol (optarg
, NULL
, 0);
527 server_quit
= np_escaped_string(optarg
);
529 asprintf(&server_quit
, "%s\r\n", optarg
);
532 if (!strncmp(optarg
,"ok",2))
533 econn_refuse_state
= STATE_OK
;
534 else if (!strncmp(optarg
,"warn",4))
535 econn_refuse_state
= STATE_WARNING
;
536 else if (!strncmp(optarg
,"crit",4))
537 econn_refuse_state
= STATE_CRITICAL
;
539 usage4 (_("Refuse must be one of ok, warn, crit"));
542 if (!strncmp(optarg
,"ok",2))
543 expect_mismatch_state
= STATE_OK
;
544 else if (!strncmp(optarg
,"warn",4))
545 expect_mismatch_state
= STATE_WARNING
;
546 else if (!strncmp(optarg
,"crit",4))
547 expect_mismatch_state
= STATE_CRITICAL
;
549 usage4 (_("Mismatch must be one of ok, warn, crit"));
552 if (is_intpos (optarg
))
553 delay
= atoi (optarg
);
555 usage4 (_("Delay must be a positive integer"));
557 case 'D': /* Check SSL cert validity - days 'til certificate expiration */
559 # ifdef USE_OPENSSL /* XXX */
560 if (!is_intnonneg (optarg
))
561 usage2 (_("Invalid certificate expiration period"), optarg
);
562 days_till_exp
= atoi (optarg
);
566 # endif /* USE_OPENSSL */
568 /* fallthrough if we don't have ssl */
573 die (STATE_UNKNOWN
, _("Invalid option - SSL is not available"));
577 flags
|= FLAG_MATCH_ALL
;
582 if (server_address
== NULL
)
583 usage4 (_("You must provide a server address"));
584 else if (server_address
[0] != '/' && is_host (server_address
) == FALSE
)
585 die (STATE_CRITICAL
, "%s %s - %s: %s\n", SERVICE
, state_text(STATE_CRITICAL
), _("Invalid hostname, address or socket"), server_address
);
594 print_revision (progname
, revision
);
596 printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
597 printf (COPYRIGHT
, copyright
, email
);
599 printf (_("This plugin tests %s connections with the specified host (or unix socket).\n\n"),
604 printf (_(UT_HELP_VRSN
));
606 printf (_(UT_HOST_PORT
), 'p', "none");
608 printf (_(UT_IPv46
));
610 printf (" %s\n", "-E, --escape");
611 printf (" %s\n", _("Can use \\n, \\r, \\t or \\ in send or quit string. Must come before send or quit option"));
612 printf (" %s\n", _("Default: nothing added to send, \\r\\n added to end of quit"));
613 printf (" %s\n", "-s, --send=STRING");
614 printf (" %s\n", _("String to send to the server"));
615 printf (" %s\n", "-e, --expect=STRING");
616 printf (" %s %s\n", _("String to expect in server response"), _("(may be repeated)"));
617 printf (" %s\n", "-A, --all");
618 printf (" %s\n", _("All expect strings need to occur in server response. Default is any"));
619 printf (" %s\n", "-q, --quit=STRING");
620 printf (" %s\n", _("String to send server to initiate a clean close of the connection"));
621 printf (" %s\n", "-r, --refuse=ok|warn|crit");
622 printf (" %s\n", _("Accept tcp refusals with states ok, warn, crit (default: crit)"));
623 printf (" %s\n", "-M, --mismatch=ok|warn|crit");
624 printf (" %s\n", _("Accept expected string mismatches with states ok, warn, crit (default: warn)"));
625 printf (" %s\n", "-j, --jail");
626 printf (" %s\n", _("Hide output from TCP socket"));
627 printf (" %s\n", "-m, --maxbytes=INTEGER");
628 printf (" %s\n", _("Close connection once more than this number of bytes are received"));
629 printf (" %s\n", "-d, --delay=INTEGER");
630 printf (" %s\n", _("Seconds to wait between sending string and polling for response"));
633 printf (" %s\n", "-D, --certificate=INTEGER");
634 printf (" %s\n", _("Minimum number of days a certificate has to be valid."));
635 printf (" %s\n", "-S, --ssl");
636 printf (" %s\n", _("Use SSL for the connection."));
639 printf (_(UT_WARN_CRIT
));
641 printf (_(UT_TIMEOUT
), DEFAULT_SOCKET_TIMEOUT
);
643 printf (_(UT_VERBOSE
));
645 printf (_(UT_SUPPORT
));
652 printf (_("Usage:"));
653 printf ("%s -H host -p port [-w <warning time>] [-c <critical time>] [-s <send string>]\n",progname
);
654 printf ("[-e <expect string>] [-q <quit string>][-m <maximum bytes>] [-d <delay>]\n");
655 printf ("[-t <timeout seconds>] [-r <refuse state>] [-M <mismatch state>] [-v] [-4|-6] [-j]\n");
656 printf ("[-D <days to cert expiry>] [-S <use SSL>] [-E]\n");