1 /*****************************************************************************
3 * Monitoring check_tcp plugin
6 * Copyright (c) 1999-2013 Monitoring Plugins Development Team
10 * This file contains the check_tcp plugin
13 * This program is free software: you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation, either version 3 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program. If not, see <http://www.gnu.org/licenses/>.
28 *****************************************************************************/
30 /* progname "check_tcp" changes depending on symlink called */
32 const char *copyright
= "1999-2008";
33 const char *email
= "devel@monitoring-plugins.org";
38 #include "utils_tcp.h"
41 #include <sys/select.h>
44 static int check_cert
= FALSE
;
45 static int days_till_exp_warn
, days_till_exp_crit
;
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 */
64 static int READ_TIMEOUT
= 2;
66 static int server_port
= 0;
67 static char *server_address
= NULL
;
68 static int host_specified
= FALSE
;
69 static char *server_send
= NULL
;
70 static char *server_quit
= NULL
;
71 static char **server_expect
;
72 static size_t server_expect_count
= 0;
73 static size_t maxbytes
= 0;
74 static char **warn_codes
= NULL
;
75 static size_t warn_codes_count
= 0;
76 static char **crit_codes
= NULL
;
77 static size_t crit_codes_count
= 0;
78 static unsigned int delay
= 0;
79 static double warning_time
= 0;
80 static double critical_time
= 0;
81 static double elapsed_time
= 0;
85 static char buffer
[MAXBUF
];
86 static int expect_mismatch_state
= STATE_WARNING
;
87 static int match_flags
= NP_MATCH_EXACT
;
90 #define FLAG_VERBOSE 0x02
91 #define FLAG_TIME_WARN 0x04
92 #define FLAG_TIME_CRIT 0x08
93 #define FLAG_HIDE_OUTPUT 0x10
97 main (int argc
, char **argv
)
99 int result
= STATE_UNKNOWN
;
103 struct timeval timeout
;
110 setlocale (LC_ALL
, "");
111 bindtextdomain (PACKAGE
, LOCALEDIR
);
112 textdomain (PACKAGE
);
114 /* determine program- and service-name quickly */
115 progname
= strrchr(argv
[0], '/');
116 if(progname
!= NULL
) progname
++;
117 else progname
= argv
[0];
119 len
= strlen(progname
);
120 if(len
> 6 && !memcmp(progname
, "check_", 6)) {
121 SERVICE
= strdup(progname
+ 6);
122 for(i
= 0; i
< len
- 6; i
++)
123 SERVICE
[i
] = toupper(SERVICE
[i
]);
126 /* set up a resonable buffer at first (will be realloc()'ed if
127 * user specifies other options) */
128 server_expect
= calloc(sizeof(char *), 2);
130 /* determine defaults for this service's protocol */
131 if (!strncmp(SERVICE
, "UDP", 3)) {
132 PROTOCOL
= IPPROTO_UDP
;
134 else if (!strncmp(SERVICE
, "FTP", 3)) {
139 else if (!strncmp(SERVICE
, "POP", 3) || !strncmp(SERVICE
, "POP3", 4)) {
144 else if (!strncmp(SERVICE
, "SMTP", 4)) {
149 else if (!strncmp(SERVICE
, "IMAP", 4)) {
151 QUIT
= "a1 LOGOUT\r\n";
155 else if (!strncmp(SERVICE
, "SIMAP", 5)) {
157 QUIT
= "a1 LOGOUT\r\n";
161 else if (!strncmp(SERVICE
, "SPOP", 4)) {
167 else if (!strncmp(SERVICE
, "SSMTP", 5)) {
173 else if (!strncmp(SERVICE
, "JABBER", 6)) {
174 SEND
= "<stream:stream to=\'host\' xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'>\n";
175 EXPECT
= "<?xml version=\'1.0\'";
176 QUIT
= "</stream:stream>\n";
177 flags
|= FLAG_HIDE_OUTPUT
;
180 else if (!strncmp (SERVICE
, "NNTPS", 5)) {
181 server_expect_count
= 2;
182 server_expect
[0] = "200";
183 server_expect
[1] = "201";
189 else if (!strncmp (SERVICE
, "NNTP", 4)) {
190 server_expect_count
= 2;
191 server_expect
= malloc(sizeof(char *) * server_expect_count
);
192 server_expect
[0] = strdup("200");
193 server_expect
[1] = strdup("201");
197 else if (!strncmp(SERVICE
, "CLAMD", 5)) {
203 /* fallthrough check, so it's supposed to use reverse matching */
204 else if (strcmp (SERVICE
, "TCP"))
205 usage (_("CRITICAL - Generic check_tcp called with unknown service\n"));
207 server_address
= "127.0.0.1";
213 /* Parse extra opts if any */
214 argv
=np_extra_opts (&argc
, argv
, progname
);
216 if (process_arguments (argc
, argv
) == ERROR
)
217 usage4 (_("Could not parse arguments"));
219 if(flags
& FLAG_VERBOSE
) {
220 printf("Using service %s\n", SERVICE
);
221 printf("Port: %d\n", server_port
);
222 printf("flags: 0x%x\n", (int)flags
);
225 if(EXPECT
&& !server_expect_count
)
226 server_expect_count
++;
228 if(PROTOCOL
==IPPROTO_UDP
&& !(server_expect_count
&& server_send
)){
229 usage(_("With UDP checks, a send/expect string must be specified."));
232 /* set up the timer */
233 signal (SIGALRM
, socket_timeout_alarm_handler
);
234 alarm (socket_timeout
);
236 /* try to connect to the host at the given port number */
237 gettimeofday (&tv
, NULL
);
239 result
= np_net_connect (server_address
, server_port
, &sd
, PROTOCOL
);
240 if (result
== STATE_CRITICAL
) return STATE_CRITICAL
;
243 if (flags
& FLAG_SSL
){
244 result
= np_net_ssl_init(sd
);
245 if (result
== STATE_OK
&& check_cert
== TRUE
) {
246 result
= np_net_ssl_check_cert(days_till_exp_warn
, days_till_exp_crit
);
249 if(result
!= STATE_OK
){
250 np_net_ssl_cleanup();
254 #endif /* HAVE_SSL */
256 if (server_send
!= NULL
) { /* Something to send? */
257 my_send(server_send
, strlen(server_send
));
265 if(flags
& FLAG_VERBOSE
) {
267 printf("Send string: %s\n", server_send
);
270 printf("Quit string: %s\n", server_quit
);
272 printf("server_expect_count: %d\n", (int)server_expect_count
);
273 for(i
= 0; i
< server_expect_count
; i
++)
274 printf("\t%d: %s\n", i
, server_expect
[i
]);
277 /* if(len) later on, we know we have a non-NULL response */
279 if (server_expect_count
) {
281 /* watch for the expect string */
282 while ((i
= my_recv(buffer
, sizeof(buffer
))) > 0) {
283 status
= realloc(status
, len
+ i
+ 1);
284 memcpy(&status
[len
], buffer
, i
);
288 /* stop reading if user-forced */
289 if (maxbytes
&& len
>= maxbytes
)
292 if ((match
= np_expect_match(status
,
295 match_flags
)) != NP_MATCH_RETRY
)
298 /* some protocols wait for further input, so make sure we don't wait forever */
300 timeout
.tv_sec
= READ_TIMEOUT
;
302 if(select(sd
+ 1, &rfds
, NULL
, NULL
, &timeout
) <= 0)
305 if (match
== NP_MATCH_RETRY
)
306 match
= NP_MATCH_FAILURE
;
308 /* no data when expected, so return critical */
310 die (STATE_CRITICAL
, _("No data received from host\n"));
312 /* print raw output if we're debugging */
313 if(flags
& FLAG_VERBOSE
)
314 printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n",
315 (int)len
+ 1, status
);
316 /* strip whitespace from end of output */
317 while(--len
> 0 && isspace(status
[len
]))
321 if (server_quit
!= NULL
) {
322 my_send(server_quit
, strlen(server_quit
));
325 np_net_ssl_cleanup();
329 microsec
= deltime (tv
);
330 elapsed_time
= (double)microsec
/ 1.0e6
;
332 if (flags
& FLAG_TIME_CRIT
&& elapsed_time
> critical_time
)
333 result
= STATE_CRITICAL
;
334 else if (flags
& FLAG_TIME_WARN
&& elapsed_time
> warning_time
)
335 result
= STATE_WARNING
;
337 /* did we get the response we hoped? */
338 if(match
== NP_MATCH_FAILURE
&& result
!= STATE_CRITICAL
)
339 result
= expect_mismatch_state
;
341 /* reset the alarm */
344 /* this is a bit stupid, because we don't want to print the
345 * response time (which can look ok to the user) if we didn't get
346 * the response we were looking for. if-else */
347 printf("%s %s - ", SERVICE
, state_text(result
));
349 if(match
== NP_MATCH_FAILURE
&& len
&& !(flags
& FLAG_HIDE_OUTPUT
))
350 printf("Unexpected response from host/socket: %s", status
);
352 if(match
== NP_MATCH_FAILURE
)
353 printf("Unexpected response from host/socket on ");
355 printf("%.3f second response time on ", elapsed_time
);
356 if(server_address
[0] != '/') {
359 server_address
, server_port
);
361 printf("port %d", server_port
);
364 printf("socket %s", server_address
);
367 if (match
!= NP_MATCH_FAILURE
&& !(flags
& FLAG_HIDE_OUTPUT
) && len
)
368 printf (" [%s]", status
);
370 /* perf-data doesn't apply when server doesn't talk properly,
371 * so print all zeroes on warn and crit. Use fperfdata since
372 * localisation settings can make different outputs */
373 if(match
== NP_MATCH_FAILURE
)
375 fperfdata ("time", elapsed_time
, "s",
376 (flags
& FLAG_TIME_WARN
? TRUE
: FALSE
), 0,
377 (flags
& FLAG_TIME_CRIT
? TRUE
: FALSE
), 0,
379 TRUE
, socket_timeout
)
383 fperfdata ("time", elapsed_time
, "s",
384 (flags
& FLAG_TIME_WARN
? TRUE
: FALSE
), warning_time
,
385 (flags
& FLAG_TIME_CRIT
? TRUE
: FALSE
), critical_time
,
387 TRUE
, socket_timeout
)
396 /* process command-line arguments */
398 process_arguments (int argc
, char **argv
)
405 static struct option longopts
[] = {
406 {"hostname", required_argument
, 0, 'H'},
407 {"critical", required_argument
, 0, 'c'},
408 {"warning", required_argument
, 0, 'w'},
409 {"critical-codes", required_argument
, 0, 'C'},
410 {"warning-codes", required_argument
, 0, 'W'},
411 {"timeout", required_argument
, 0, 't'},
412 {"protocol", required_argument
, 0, 'P'}, /* FIXME: Unhandled */
413 {"port", required_argument
, 0, 'p'},
414 {"escape", no_argument
, 0, 'E'},
415 {"all", no_argument
, 0, 'A'},
416 {"send", required_argument
, 0, 's'},
417 {"expect", required_argument
, 0, 'e'},
418 {"maxbytes", required_argument
, 0, 'm'},
419 {"quit", required_argument
, 0, 'q'},
420 {"jail", no_argument
, 0, 'j'},
421 {"delay", required_argument
, 0, 'd'},
422 {"refuse", required_argument
, 0, 'r'},
423 {"mismatch", required_argument
, 0, 'M'},
424 {"use-ipv4", no_argument
, 0, '4'},
425 {"use-ipv6", no_argument
, 0, '6'},
426 {"verbose", no_argument
, 0, 'v'},
427 {"version", no_argument
, 0, 'V'},
428 {"help", no_argument
, 0, 'h'},
429 {"ssl", no_argument
, 0, 'S'},
430 {"certificate", required_argument
, 0, 'D'},
435 usage4 (_("No arguments found"));
437 /* backwards compatibility */
438 for (c
= 1; c
< argc
; c
++) {
439 if (strcmp ("-to", argv
[c
]) == 0)
440 strcpy (argv
[c
], "-t");
441 else if (strcmp ("-wt", argv
[c
]) == 0)
442 strcpy (argv
[c
], "-w");
443 else if (strcmp ("-ct", argv
[c
]) == 0)
444 strcpy (argv
[c
], "-c");
447 if (!is_option (argv
[1])) {
448 server_address
= argv
[1];
455 c
= getopt_long (argc
, argv
, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:",
458 if (c
== -1 || c
== EOF
|| c
== 1)
462 case '?': /* print short usage statement if args not parsable */
467 case 'V': /* version */
468 print_revision (progname
, NP_VERSION
);
470 case 'v': /* verbose mode */
471 flags
|= FLAG_VERBOSE
;
472 match_flags
|= NP_MATCH_VERBOSE
;
475 address_family
= AF_INET
;
479 address_family
= AF_INET6
;
481 usage4 (_("IPv6 support not available"));
484 case 'H': /* hostname */
485 host_specified
= TRUE
;
486 server_address
= optarg
;
488 case 'c': /* critical */
489 critical_time
= strtod (optarg
, NULL
);
490 flags
|= FLAG_TIME_CRIT
;
492 case 'j': /* hide output */
493 flags
|= FLAG_HIDE_OUTPUT
;
495 case 'w': /* warning */
496 warning_time
= strtod (optarg
, NULL
);
497 flags
|= FLAG_TIME_WARN
;
500 crit_codes
= realloc (crit_codes
, ++crit_codes_count
);
501 crit_codes
[crit_codes_count
- 1] = optarg
;
504 warn_codes
= realloc (warn_codes
, ++warn_codes_count
);
505 warn_codes
[warn_codes_count
- 1] = optarg
;
507 case 't': /* timeout */
508 if (!is_intpos (optarg
))
509 usage4 (_("Timeout interval must be a positive integer"));
511 socket_timeout
= atoi (optarg
);
514 if (!is_intpos (optarg
))
515 usage4 (_("Port must be a positive integer"));
517 server_port
= atoi (optarg
);
524 server_send
= np_escaped_string(optarg
);
526 xasprintf(&server_send
, "%s", optarg
);
528 case 'e': /* expect string (may be repeated) */
529 match_flags
&= ~NP_MATCH_EXACT
;
530 if (server_expect_count
== 0)
531 server_expect
= malloc (sizeof (char *) * (++server_expect_count
));
533 server_expect
= realloc (server_expect
, sizeof (char *) * (++server_expect_count
));
534 server_expect
[server_expect_count
- 1] = optarg
;
537 if (!is_intpos (optarg
))
538 usage4 (_("Maxbytes must be a positive integer"));
540 maxbytes
= strtol (optarg
, NULL
, 0);
544 server_quit
= np_escaped_string(optarg
);
546 xasprintf(&server_quit
, "%s\r\n", optarg
);
549 if (!strncmp(optarg
,"ok",2))
550 econn_refuse_state
= STATE_OK
;
551 else if (!strncmp(optarg
,"warn",4))
552 econn_refuse_state
= STATE_WARNING
;
553 else if (!strncmp(optarg
,"crit",4))
554 econn_refuse_state
= STATE_CRITICAL
;
556 usage4 (_("Refuse must be one of ok, warn, crit"));
559 if (!strncmp(optarg
,"ok",2))
560 expect_mismatch_state
= STATE_OK
;
561 else if (!strncmp(optarg
,"warn",4))
562 expect_mismatch_state
= STATE_WARNING
;
563 else if (!strncmp(optarg
,"crit",4))
564 expect_mismatch_state
= STATE_CRITICAL
;
566 usage4 (_("Mismatch must be one of ok, warn, crit"));
569 if (is_intpos (optarg
))
570 delay
= atoi (optarg
);
572 usage4 (_("Delay must be a positive integer"));
574 case 'D': /* Check SSL cert validity - days 'til certificate expiration */
576 # ifdef USE_OPENSSL /* XXX */
577 if ((temp
=strchr(optarg
,','))!=NULL
) {
579 if (!is_intnonneg (optarg
))
580 usage2 (_("Invalid certificate expiration period"), optarg
); days_till_exp_warn
= atoi(optarg
);
583 if (!is_intnonneg (temp
))
584 usage2 (_("Invalid certificate expiration period"), temp
);
585 days_till_exp_crit
= atoi (temp
);
588 days_till_exp_crit
=0;
589 if (!is_intnonneg (optarg
))
590 usage2 (_("Invalid certificate expiration period"), optarg
);
591 days_till_exp_warn
= atoi (optarg
);
596 # endif /* USE_OPENSSL */
598 /* fallthrough if we don't have ssl */
603 die (STATE_UNKNOWN
, _("Invalid option - SSL is not available"));
607 match_flags
|= NP_MATCH_ALL
;
613 if(host_specified
== FALSE
&& c
< argc
)
614 server_address
= strdup (argv
[c
++]);
616 if (server_address
== NULL
)
617 usage4 (_("You must provide a server address"));
618 else if (server_address
[0] != '/' && is_host (server_address
) == FALSE
)
619 die (STATE_CRITICAL
, "%s %s - %s: %s\n", SERVICE
, state_text(STATE_CRITICAL
), _("Invalid hostname, address or socket"), server_address
);
628 print_revision (progname
, NP_VERSION
);
630 printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
631 printf (COPYRIGHT
, copyright
, email
);
633 printf (_("This plugin tests %s connections with the specified host (or unix socket).\n\n"),
638 printf (UT_HELP_VRSN
);
639 printf (UT_EXTRA_OPTS
);
641 printf (UT_HOST_PORT
, 'p', "none");
645 printf (" %s\n", "-E, --escape");
646 printf (" %s\n", _("Can use \\n, \\r, \\t or \\ in send or quit string. Must come before send or quit option"));
647 printf (" %s\n", _("Default: nothing added to send, \\r\\n added to end of quit"));
648 printf (" %s\n", "-s, --send=STRING");
649 printf (" %s\n", _("String to send to the server"));
650 printf (" %s\n", "-e, --expect=STRING");
651 printf (" %s %s\n", _("String to expect in server response"), _("(may be repeated)"));
652 printf (" %s\n", "-A, --all");
653 printf (" %s\n", _("All expect strings need to occur in server response. Default is any"));
654 printf (" %s\n", "-q, --quit=STRING");
655 printf (" %s\n", _("String to send server to initiate a clean close of the connection"));
656 printf (" %s\n", "-r, --refuse=ok|warn|crit");
657 printf (" %s\n", _("Accept TCP refusals with states ok, warn, crit (default: crit)"));
658 printf (" %s\n", "-M, --mismatch=ok|warn|crit");
659 printf (" %s\n", _("Accept expected string mismatches with states ok, warn, crit (default: warn)"));
660 printf (" %s\n", "-j, --jail");
661 printf (" %s\n", _("Hide output from TCP socket"));
662 printf (" %s\n", "-m, --maxbytes=INTEGER");
663 printf (" %s\n", _("Close connection once more than this number of bytes are received"));
664 printf (" %s\n", "-d, --delay=INTEGER");
665 printf (" %s\n", _("Seconds to wait between sending string and polling for response"));
668 printf (" %s\n", "-D, --certificate=INTEGER[,INTEGER]");
669 printf (" %s\n", _("Minimum number of days a certificate has to be valid."));
670 printf (" %s\n", _("1st is #days for warning, 2nd is critical (if not specified - 0)."));
671 printf (" %s\n", "-S, --ssl");
672 printf (" %s\n", _("Use SSL for the connection."));
675 printf (UT_WARN_CRIT
);
677 printf (UT_CONN_TIMEOUT
, DEFAULT_SOCKET_TIMEOUT
);
688 printf ("%s\n", _("Usage:"));
689 printf ("%s -H host -p port [-w <warning time>] [-c <critical time>] [-s <send string>]\n",progname
);
690 printf ("[-e <expect string>] [-q <quit string>][-m <maximum bytes>] [-d <delay>]\n");
691 printf ("[-t <timeout seconds>] [-r <refuse state>] [-M <mismatch state>] [-v] [-4|-6] [-j]\n");
692 printf ("[-D <warn days cert expire>[,<crit days cert expire>]] [-S <use SSL>] [-E]\n");