1 /*****************************************************************************
3 * Monitoring check_tcp plugin
6 * Copyright (c) 1999-2024 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-2024";
33 const char *email
= "devel@monitoring-plugins.org";
38 #include "utils_tcp.h"
41 #include <sys/select.h>
44 static bool 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 /*argc*/, char ** /*argv*/);
55 static 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 bool 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 ssize_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 static char *sni
= NULL
;
91 static bool sni_specified
= false;
95 #define FLAG_VERBOSE 0x02
96 #define FLAG_TIME_WARN 0x04
97 #define FLAG_TIME_CRIT 0x08
98 #define FLAG_HIDE_OUTPUT 0x10
101 int main(int argc
, char **argv
) {
102 setlocale(LC_ALL
, "");
103 bindtextdomain(PACKAGE
, LOCALEDIR
);
106 /* determine program- and service-name quickly */
107 progname
= strrchr(argv
[0], '/');
108 if (progname
!= NULL
)
113 size_t prog_name_len
= strlen(progname
);
114 if (prog_name_len
> 6 && !memcmp(progname
, "check_", 6)) {
115 SERVICE
= strdup(progname
+ 6);
116 for (size_t i
= 0; i
< prog_name_len
- 6; i
++)
117 SERVICE
[i
] = toupper(SERVICE
[i
]);
120 /* set up a reasonable buffer at first (will be realloc()'ed if
121 * user specifies other options) */
122 server_expect
= calloc(2, sizeof(char *));
124 /* determine defaults for this service's protocol */
125 if (!strncmp(SERVICE
, "UDP", 3)) {
126 PROTOCOL
= IPPROTO_UDP
;
127 } else if (!strncmp(SERVICE
, "FTP", 3)) {
131 } else if (!strncmp(SERVICE
, "POP", 3) || !strncmp(SERVICE
, "POP3", 4)) {
135 } else if (!strncmp(SERVICE
, "SMTP", 4)) {
139 } else if (!strncmp(SERVICE
, "IMAP", 4)) {
141 QUIT
= "a1 LOGOUT\r\n";
145 else if (!strncmp(SERVICE
, "SIMAP", 5)) {
147 QUIT
= "a1 LOGOUT\r\n";
150 } else if (!strncmp(SERVICE
, "SPOP", 4)) {
155 } else if (!strncmp(SERVICE
, "SSMTP", 5)) {
160 } else if (!strncmp(SERVICE
, "JABBER", 6)) {
161 SEND
= "<stream:stream to=\'host\' xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'>\n";
162 EXPECT
= "<?xml version=\'1.0\'";
163 QUIT
= "</stream:stream>\n";
164 flags
|= FLAG_HIDE_OUTPUT
;
166 } else if (!strncmp(SERVICE
, "NNTPS", 5)) {
167 server_expect_count
= 2;
168 server_expect
[0] = "200";
169 server_expect
[1] = "201";
175 else if (!strncmp(SERVICE
, "NNTP", 4)) {
176 server_expect_count
= 2;
177 server_expect
= malloc(sizeof(char *) * server_expect_count
);
178 server_expect
[0] = strdup("200");
179 server_expect
[1] = strdup("201");
182 } else if (!strncmp(SERVICE
, "CLAMD", 5)) {
188 /* fallthrough check, so it's supposed to use reverse matching */
189 else if (strcmp(SERVICE
, "TCP"))
190 usage(_("CRITICAL - Generic check_tcp called with unknown service\n"));
192 server_address
= "127.0.0.1";
198 /* Parse extra opts if any */
199 argv
= np_extra_opts(&argc
, argv
, progname
);
201 if (process_arguments(argc
, argv
) == ERROR
)
202 usage4(_("Could not parse arguments"));
204 if (flags
& FLAG_VERBOSE
) {
205 printf("Using service %s\n", SERVICE
);
206 printf("Port: %d\n", server_port
);
207 printf("flags: 0x%x\n", (int)flags
);
210 if (EXPECT
&& !server_expect_count
)
211 server_expect_count
++;
213 if (PROTOCOL
== IPPROTO_UDP
&& !(server_expect_count
&& server_send
)) {
214 usage(_("With UDP checks, a send/expect string must be specified."));
217 /* set up the timer */
218 signal(SIGALRM
, socket_timeout_alarm_handler
);
219 alarm(socket_timeout
);
221 /* try to connect to the host at the given port number */
223 gettimeofday(&tv
, NULL
);
225 int result
= STATE_UNKNOWN
;
226 result
= np_net_connect(server_address
, server_port
, &sd
, PROTOCOL
);
227 if (result
== STATE_CRITICAL
)
228 return econn_refuse_state
;
231 if (flags
& FLAG_SSL
) {
232 result
= np_net_ssl_init_with_hostname(sd
, (sni_specified
? sni
: NULL
));
233 if (result
== STATE_OK
&& check_cert
) {
234 result
= np_net_ssl_check_cert(days_till_exp_warn
, days_till_exp_crit
);
237 if (result
!= STATE_OK
) {
240 np_net_ssl_cleanup();
243 #endif /* HAVE_SSL */
245 if (server_send
!= NULL
) { /* Something to send? */
246 my_send(server_send
, strlen(server_send
));
254 if (flags
& FLAG_VERBOSE
) {
256 printf("Send string: %s\n", server_send
);
259 printf("Quit string: %s\n", server_quit
);
261 printf("server_expect_count: %d\n", (int)server_expect_count
);
262 for (size_t i
= 0; i
< server_expect_count
; i
++)
263 printf("\t%zd: %s\n", i
, server_expect
[i
]);
266 /* if(len) later on, we know we have a non-NULL response */
270 struct timeval timeout
;
273 if (server_expect_count
) {
274 ssize_t received
= 0;
276 /* watch for the expect string */
277 while ((received
= my_recv(buffer
, sizeof(buffer
))) > 0) {
278 status
= realloc(status
, len
+ received
+ 1);
279 memcpy(&status
[len
], buffer
, received
);
283 /* stop reading if user-forced */
284 if (maxbytes
&& len
>= maxbytes
)
287 if ((match
= np_expect_match(status
, server_expect
, server_expect_count
, match_flags
)) != NP_MATCH_RETRY
)
290 /* some protocols wait for further input, so make sure we don't wait forever */
292 timeout
.tv_sec
= READ_TIMEOUT
;
294 if (select(sd
+ 1, &rfds
, NULL
, NULL
, &timeout
) <= 0)
298 if (match
== NP_MATCH_RETRY
)
299 match
= NP_MATCH_FAILURE
;
301 /* no data when expected, so return critical */
303 die(STATE_CRITICAL
, _("No data received from host\n"));
305 /* print raw output if we're debugging */
306 if (flags
& FLAG_VERBOSE
)
307 printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n", (int)len
+ 1, status
);
308 /* strip whitespace from end of output */
309 while (--len
> 0 && isspace(status
[len
]))
313 if (server_quit
!= NULL
) {
314 my_send(server_quit
, strlen(server_quit
));
319 np_net_ssl_cleanup();
322 microsec
= deltime(tv
);
323 elapsed_time
= (double)microsec
/ 1.0e6
;
325 if (flags
& FLAG_TIME_CRIT
&& elapsed_time
> critical_time
)
326 result
= STATE_CRITICAL
;
327 else if (flags
& FLAG_TIME_WARN
&& elapsed_time
> warning_time
)
328 result
= STATE_WARNING
;
330 /* did we get the response we hoped? */
331 if (match
== NP_MATCH_FAILURE
&& result
!= STATE_CRITICAL
)
332 result
= expect_mismatch_state
;
334 /* reset the alarm */
337 /* this is a bit stupid, because we don't want to print the
338 * response time (which can look ok to the user) if we didn't get
339 * the response we were looking for. if-else */
340 printf("%s %s - ", SERVICE
, state_text(result
));
342 if (match
== NP_MATCH_FAILURE
&& len
&& !(flags
& FLAG_HIDE_OUTPUT
))
343 printf("Unexpected response from host/socket: %s", status
);
345 if (match
== NP_MATCH_FAILURE
)
346 printf("Unexpected response from host/socket on ");
348 printf("%.3f second response time on ", elapsed_time
);
349 if (server_address
[0] != '/') {
351 printf("%s port %d", server_address
, server_port
);
353 printf("port %d", server_port
);
355 printf("socket %s", server_address
);
358 if (match
!= NP_MATCH_FAILURE
&& !(flags
& FLAG_HIDE_OUTPUT
) && len
)
359 printf(" [%s]", status
);
361 /* perf-data doesn't apply when server doesn't talk properly,
362 * so print all zeroes on warn and crit. Use fperfdata since
363 * localisation settings can make different outputs */
364 if (match
== NP_MATCH_FAILURE
)
365 printf("|%s", fperfdata("time", elapsed_time
, "s", (flags
& FLAG_TIME_WARN
? true : false), 0,
366 (flags
& FLAG_TIME_CRIT
? true : false), 0, true, 0, true, socket_timeout
));
368 printf("|%s", fperfdata("time", elapsed_time
, "s", (flags
& FLAG_TIME_WARN
? true : false), warning_time
,
369 (flags
& FLAG_TIME_CRIT
? true : false), critical_time
, true, 0, true, socket_timeout
));
375 /* process command-line arguments */
376 static int process_arguments(int argc
, char **argv
) {
378 SNI_OPTION
= CHAR_MAX
+ 1
381 static struct option longopts
[] = {{"hostname", required_argument
, 0, 'H'},
382 {"critical", required_argument
, 0, 'c'},
383 {"warning", 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'}, /* FIXME: Unhandled */
388 {"port", required_argument
, 0, 'p'},
389 {"escape", no_argument
, 0, 'E'},
390 {"all", no_argument
, 0, 'A'},
391 {"send", required_argument
, 0, 's'},
392 {"expect", required_argument
, 0, 'e'},
393 {"maxbytes", required_argument
, 0, 'm'},
394 {"quit", required_argument
, 0, 'q'},
395 {"jail", no_argument
, 0, 'j'},
396 {"delay", required_argument
, 0, 'd'},
397 {"refuse", required_argument
, 0, 'r'},
398 {"mismatch", required_argument
, 0, 'M'},
399 {"use-ipv4", no_argument
, 0, '4'},
400 {"use-ipv6", no_argument
, 0, '6'},
401 {"verbose", no_argument
, 0, 'v'},
402 {"version", no_argument
, 0, 'V'},
403 {"help", no_argument
, 0, 'h'},
404 {"ssl", no_argument
, 0, 'S'},
405 {"sni", required_argument
, 0, SNI_OPTION
},
406 {"certificate", required_argument
, 0, 'D'},
410 usage4(_("No arguments found"));
412 /* backwards compatibility */
413 for (int i
= 1; i
< argc
; i
++) {
414 if (strcmp("-to", argv
[i
]) == 0)
415 strcpy(argv
[i
], "-t");
416 else if (strcmp("-wt", argv
[i
]) == 0)
417 strcpy(argv
[i
], "-w");
418 else if (strcmp("-ct", argv
[i
]) == 0)
419 strcpy(argv
[i
], "-c");
422 if (!is_option(argv
[1])) {
423 server_address
= argv
[1];
433 option_char
= getopt_long(argc
, argv
, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:", longopts
, &option
);
435 if (option_char
== -1 || option_char
== EOF
|| option_char
== 1)
438 switch (option_char
) {
439 case '?': /* print short usage statement if args not parsable */
444 case 'V': /* version */
445 print_revision(progname
, NP_VERSION
);
447 case 'v': /* verbose mode */
448 flags
|= FLAG_VERBOSE
;
449 match_flags
|= NP_MATCH_VERBOSE
;
452 address_family
= AF_INET
;
456 address_family
= AF_INET6
;
458 usage4(_("IPv6 support not available"));
461 case 'H': /* hostname */
462 host_specified
= true;
463 server_address
= optarg
;
465 case 'c': /* critical */
466 critical_time
= strtod(optarg
, NULL
);
467 flags
|= FLAG_TIME_CRIT
;
469 case 'j': /* hide output */
470 flags
|= FLAG_HIDE_OUTPUT
;
472 case 'w': /* warning */
473 warning_time
= strtod(optarg
, NULL
);
474 flags
|= FLAG_TIME_WARN
;
477 crit_codes
= realloc(crit_codes
, ++crit_codes_count
);
478 crit_codes
[crit_codes_count
- 1] = optarg
;
481 warn_codes
= realloc(warn_codes
, ++warn_codes_count
);
482 warn_codes
[warn_codes_count
- 1] = optarg
;
484 case 't': /* timeout */
485 if (!is_intpos(optarg
))
486 usage4(_("Timeout interval must be a positive integer"));
488 socket_timeout
= atoi(optarg
);
491 if (!is_intpos(optarg
))
492 usage4(_("Port must be a positive integer"));
494 server_port
= atoi(optarg
);
501 server_send
= np_escaped_string(optarg
);
503 xasprintf(&server_send
, "%s", optarg
);
505 case 'e': /* expect string (may be repeated) */
506 match_flags
&= ~NP_MATCH_EXACT
;
507 if (server_expect_count
== 0)
508 server_expect
= malloc(sizeof(char *) * (++server_expect_count
));
510 server_expect
= realloc(server_expect
, sizeof(char *) * (++server_expect_count
));
511 server_expect
[server_expect_count
- 1] = optarg
;
514 if (!is_intpos(optarg
))
515 usage4(_("Maxbytes must be a positive integer"));
517 maxbytes
= strtol(optarg
, NULL
, 0);
521 server_quit
= np_escaped_string(optarg
);
523 xasprintf(&server_quit
, "%s\r\n", optarg
);
526 if (!strncmp(optarg
, "ok", 2))
527 econn_refuse_state
= STATE_OK
;
528 else if (!strncmp(optarg
, "warn", 4))
529 econn_refuse_state
= STATE_WARNING
;
530 else if (!strncmp(optarg
, "crit", 4))
531 econn_refuse_state
= STATE_CRITICAL
;
533 usage4(_("Refuse must be one of ok, warn, crit"));
536 if (!strncmp(optarg
, "ok", 2))
537 expect_mismatch_state
= STATE_OK
;
538 else if (!strncmp(optarg
, "warn", 4))
539 expect_mismatch_state
= STATE_WARNING
;
540 else if (!strncmp(optarg
, "crit", 4))
541 expect_mismatch_state
= STATE_CRITICAL
;
543 usage4(_("Mismatch must be one of ok, warn, crit"));
546 if (is_intpos(optarg
))
547 delay
= atoi(optarg
);
549 usage4(_("Delay must be a positive integer"));
551 case 'D': { /* Check SSL cert validity - days 'til certificate expiration */
553 # ifdef USE_OPENSSL /* XXX */
555 if ((temp
= strchr(optarg
, ',')) != NULL
) {
557 if (!is_intnonneg(optarg
))
558 usage2(_("Invalid certificate expiration period"), optarg
);
559 days_till_exp_warn
= atoi(optarg
);
562 if (!is_intnonneg(temp
))
563 usage2(_("Invalid certificate expiration period"), temp
);
564 days_till_exp_crit
= atoi(temp
);
566 days_till_exp_crit
= 0;
567 if (!is_intnonneg(optarg
))
568 usage2(_("Invalid certificate expiration period"), optarg
);
569 days_till_exp_warn
= atoi(optarg
);
574 # endif /* USE_OPENSSL */
576 /* fallthrough if we don't have ssl */
581 die(STATE_UNKNOWN
, _("Invalid option - SSL is not available"));
587 sni_specified
= true;
590 die(STATE_UNKNOWN
, _("Invalid option - SSL is not available"));
594 match_flags
|= NP_MATCH_ALL
;
599 option_char
= optind
;
600 if (!host_specified
&& option_char
< argc
)
601 server_address
= strdup(argv
[option_char
++]);
603 if (server_address
== NULL
)
604 usage4(_("You must provide a server address"));
605 else if (server_address
[0] != '/' && !is_host(server_address
))
606 die(STATE_CRITICAL
, "%s %s - %s: %s\n", SERVICE
, state_text(STATE_CRITICAL
), _("Invalid hostname, address or socket"),
612 void print_help(void) {
613 print_revision(progname
, NP_VERSION
);
615 printf("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
616 printf(COPYRIGHT
, copyright
, email
);
618 printf(_("This plugin tests %s connections with the specified host (or unix socket).\n\n"), SERVICE
);
622 printf(UT_HELP_VRSN
);
623 printf(UT_EXTRA_OPTS
);
625 printf(UT_HOST_PORT
, 'p', "none");
629 printf(" %s\n", "-E, --escape");
630 printf(" %s\n", _("Can use \\n, \\r, \\t or \\\\ in send or quit string. Must come before send or quit option"));
631 printf(" %s\n", _("Default: nothing added to send, \\r\\n added to end of quit"));
632 printf(" %s\n", "-s, --send=STRING");
633 printf(" %s\n", _("String to send to the server"));
634 printf(" %s\n", "-e, --expect=STRING");
635 printf(" %s %s\n", _("String to expect in server response"), _("(may be repeated)"));
636 printf(" %s\n", "-A, --all");
637 printf(" %s\n", _("All expect strings need to occur in server response. Default is any"));
638 printf(" %s\n", "-q, --quit=STRING");
639 printf(" %s\n", _("String to send server to initiate a clean close of the connection"));
640 printf(" %s\n", "-r, --refuse=ok|warn|crit");
641 printf(" %s\n", _("Accept TCP refusals with states ok, warn, crit (default: crit)"));
642 printf(" %s\n", "-M, --mismatch=ok|warn|crit");
643 printf(" %s\n", _("Accept expected string mismatches with states ok, warn, crit (default: warn)"));
644 printf(" %s\n", "-j, --jail");
645 printf(" %s\n", _("Hide output from TCP socket"));
646 printf(" %s\n", "-m, --maxbytes=INTEGER");
647 printf(" %s\n", _("Close connection once more than this number of bytes are received"));
648 printf(" %s\n", "-d, --delay=INTEGER");
649 printf(" %s\n", _("Seconds to wait between sending string and polling for response"));
652 printf(" %s\n", "-D, --certificate=INTEGER[,INTEGER]");
653 printf(" %s\n", _("Minimum number of days a certificate has to be valid."));
654 printf(" %s\n", _("1st is #days for warning, 2nd is critical (if not specified - 0)."));
655 printf(" %s\n", "-S, --ssl");
656 printf(" %s\n", _("Use SSL for the connection."));
657 printf(" %s\n", "--sni=STRING");
658 printf(" %s\n", _("SSL server_name"));
661 printf(UT_WARN_CRIT
);
663 printf(UT_CONN_TIMEOUT
, DEFAULT_SOCKET_TIMEOUT
);
670 void print_usage(void) {
671 printf("%s\n", _("Usage:"));
672 printf("%s -H host -p port [-w <warning time>] [-c <critical time>] [-s <send string>]\n", progname
);
673 printf("[-e <expect string>] [-q <quit string>][-m <maximum bytes>] [-d <delay>]\n");
674 printf("[-t <timeout seconds>] [-r <refuse state>] [-M <mismatch state>] [-v] [-4|-6] [-j]\n");
675 printf("[-D <warn days cert expire>[,<crit days cert expire>]] [-S <use SSL>] [-E]\n");