From 554bf3e5256f5489aed0cd56f0c600bcb281a7f5 Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 4 Mar 2025 11:02:33 +0100 Subject: Refactor check_tcp and implement new output format --- plugins/check_tcp.c | 742 ++++++++++++++++++++++++------------------- plugins/check_tcp.d/config.h | 78 +++++ 2 files changed, 493 insertions(+), 327 deletions(-) create mode 100644 plugins/check_tcp.d/config.h (limited to 'plugins') diff --git a/plugins/check_tcp.c b/plugins/check_tcp.c index 49ad096c..f93152e5 100644 --- a/plugins/check_tcp.c +++ b/plugins/check_tcp.c @@ -3,7 +3,7 @@ * Monitoring check_tcp plugin * * License: GPL - * Copyright (c) 1999-2024 Monitoring Plugins Development Team + * Copyright (c) 1999-2025 Monitoring Plugins Development Team * * Description: * @@ -28,75 +28,63 @@ *****************************************************************************/ /* progname "check_tcp" changes depending on symlink called */ +#include "states.h" char *progname; -const char *copyright = "1999-2024"; +const char *copyright = "1999-2025"; const char *email = "devel@monitoring-plugins.org"; -#include "common.h" -#include "netutils.h" -#include "utils.h" -#include "utils_tcp.h" +#include "./common.h" +#include "./netutils.h" +#include "./utils.h" +#include "./check_tcp.d/config.h" +#include #include #include +ssize_t my_recv(char *buf, size_t len) { #ifdef HAVE_SSL -static bool check_cert = false; -static int days_till_exp_warn, days_till_exp_crit; -# define my_recv(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_read(buf, len) : read(sd, buf, len)) -# define my_send(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0)) + return np_net_ssl_read(buf, (int)len); #else -# define my_recv(buf, len) read(sd, buf, len) -# define my_send(buf, len) send(sd, buf, len, 0) -#endif + return read(socket_descriptor, buf, len); +#endif // HAVE_SSL +} + +ssize_t my_send(char *buf, size_t len) { +#ifdef HAVE_SSL + return np_net_ssl_write(buf, (int)len); +#else + return write(socket_descriptor, buf, len); +#endif // HAVE_SSL +} + +typedef struct process_arguments_wrapper { + int errorcode; + check_tcp_config config; +} process_arguments_wrapper; /* int my_recv(char *, size_t); */ -static int process_arguments(int /*argc*/, char ** /*argv*/); -static void print_help(void); +static process_arguments_wrapper process_arguments(int /*argc*/, char ** /*argv*/, check_tcp_config /*config*/); +void print_help(const char *service); void print_usage(void); -#define EXPECT server_expect[0] -static char *SERVICE = "TCP"; -static char *SEND = NULL; -static char *QUIT = NULL; -static int PROTOCOL = IPPROTO_TCP; /* most common is default */ -static int PORT = 0; -static int READ_TIMEOUT = 2; - -static int server_port = 0; -static char *server_address = NULL; -static bool host_specified = false; -static char *server_send = NULL; -static char *server_quit = NULL; -static char **server_expect; -static size_t server_expect_count = 0; -static ssize_t maxbytes = 0; -static char **warn_codes = NULL; -static size_t warn_codes_count = 0; -static char **crit_codes = NULL; -static size_t crit_codes_count = 0; -static unsigned int delay = 0; -static double warning_time = 0; -static double critical_time = 0; -static double elapsed_time = 0; -static long microsec; -static int sd = 0; -#define MAXBUF 1024 -static char buffer[MAXBUF]; -static int expect_mismatch_state = STATE_WARNING; -static int match_flags = NP_MATCH_EXACT; +int verbosity = 0; -#ifdef HAVE_SSL -static char *sni = NULL; -static bool sni_specified = false; -#endif +static const int READ_TIMEOUT = 2; -#define FLAG_SSL 0x01 -#define FLAG_VERBOSE 0x02 -#define FLAG_TIME_WARN 0x04 -#define FLAG_TIME_CRIT 0x08 -#define FLAG_HIDE_OUTPUT 0x10 -static size_t flags; +const int MAXBUF = 1024; + +const int DEFAULT_FTP_PORT = 21; +const int DEFAULT_POP_PORT = 110; +const int DEFAULT_SPOP_PORT = 995; +const int DEFAULT_SMTP_PORT = 25; +const int DEFAULT_SSMTP_PORT = 465; +const int DEFAULT_IMAP_PORT = 143; +const int DEFAULT_SIMAP_PORT = 993; +const int DEFAULT_XMPP_C2S_PORT = 5222; +const int DEFAULT_NNTP_PORT = 119; +const int DEFAULT_NNTPS_PORT = 563; +const int DEFAULT_CLAMD_PORT = 3310; int main(int argc, char **argv) { setlocale(LC_ALL, ""); @@ -105,279 +93,371 @@ int main(int argc, char **argv) { /* determine program- and service-name quickly */ progname = strrchr(argv[0], '/'); - if (progname != NULL) + if (progname != NULL) { progname++; - else + } else { progname = argv[0]; + } + + // Initialize config here with values from above, + // might be changed by on disk config or cli commands + check_tcp_config config = check_tcp_config_init(); size_t prog_name_len = strlen(progname); - if (prog_name_len > 6 && !memcmp(progname, "check_", 6)) { - SERVICE = strdup(progname + 6); - for (size_t i = 0; i < prog_name_len - 6; i++) - SERVICE[i] = toupper(SERVICE[i]); + const size_t prefix_length = strlen("check_"); + + if (prog_name_len <= prefix_length) { + die(STATE_UNKNOWN, _("Weird progname")); + } + + if (!memcmp(progname, "check_", prefix_length)) { + config.service = strdup(progname + prefix_length); + if (config.service == NULL) { + die(STATE_UNKNOWN, _("Allocation failed")); + } + + for (size_t i = 0; i < prog_name_len - prefix_length; i++) { + config.service[i] = toupper(config.service[i]); + } } /* set up a reasonable buffer at first (will be realloc()'ed if * user specifies other options) */ - server_expect = calloc(2, sizeof(char *)); + config.server_expect = calloc(2, sizeof(char *)); + + if (config.server_expect == NULL) { + die(STATE_UNKNOWN, _("Allocation failed")); + } /* determine defaults for this service's protocol */ - if (!strncmp(SERVICE, "UDP", 3)) { - PROTOCOL = IPPROTO_UDP; - } else if (!strncmp(SERVICE, "FTP", 3)) { - EXPECT = "220"; - QUIT = "QUIT\r\n"; - PORT = 21; - } else if (!strncmp(SERVICE, "POP", 3) || !strncmp(SERVICE, "POP3", 4)) { - EXPECT = "+OK"; - QUIT = "QUIT\r\n"; - PORT = 110; - } else if (!strncmp(SERVICE, "SMTP", 4)) { - EXPECT = "220"; - QUIT = "QUIT\r\n"; - PORT = 25; - } else if (!strncmp(SERVICE, "IMAP", 4)) { - EXPECT = "* OK"; - QUIT = "a1 LOGOUT\r\n"; - PORT = 143; + if (!strncmp(config.service, "UDP", strlen("UDP"))) { + config.protocol = IPPROTO_UDP; + } else if (!strncmp(config.service, "FTP", strlen("FTP"))) { + config.server_expect[0] = "220"; + config.quit = "QUIT\r\n"; + config.server_port = DEFAULT_FTP_PORT; + } else if (!strncmp(config.service, "POP", strlen("POP")) || !strncmp(config.service, "POP3", strlen("POP3"))) { + config.server_expect[0] = "+OK"; + config.quit = "QUIT\r\n"; + config.server_port = DEFAULT_POP_PORT; + } else if (!strncmp(config.service, "SMTP", strlen("SMTP"))) { + config.server_expect[0] = "220"; + config.quit = "QUIT\r\n"; + config.server_port = DEFAULT_SMTP_PORT; + } else if (!strncmp(config.service, "IMAP", strlen("IMAP"))) { + config.server_expect[0] = "* OK"; + config.quit = "a1 LOGOUT\r\n"; + config.server_port = DEFAULT_IMAP_PORT; } #ifdef HAVE_SSL - else if (!strncmp(SERVICE, "SIMAP", 5)) { - EXPECT = "* OK"; - QUIT = "a1 LOGOUT\r\n"; - flags |= FLAG_SSL; - PORT = 993; - } else if (!strncmp(SERVICE, "SPOP", 4)) { - EXPECT = "+OK"; - QUIT = "QUIT\r\n"; - flags |= FLAG_SSL; - PORT = 995; - } else if (!strncmp(SERVICE, "SSMTP", 5)) { - EXPECT = "220"; - QUIT = "QUIT\r\n"; - flags |= FLAG_SSL; - PORT = 465; - } else if (!strncmp(SERVICE, "JABBER", 6)) { - SEND = "\n"; - EXPECT = "\n"; - flags |= FLAG_HIDE_OUTPUT; - PORT = 5222; - } else if (!strncmp(SERVICE, "NNTPS", 5)) { - server_expect_count = 2; - server_expect[0] = "200"; - server_expect[1] = "201"; - QUIT = "QUIT\r\n"; - flags |= FLAG_SSL; - PORT = 563; + else if (!strncmp(config.service, "SIMAP", strlen("SIMAP"))) { + config.server_expect[0] = "* OK"; + config.quit = "a1 LOGOUT\r\n"; + config.use_tls = true; + config.server_port = DEFAULT_SIMAP_PORT; + } else if (!strncmp(config.service, "SPOP", strlen("SPOP"))) { + config.server_expect[0] = "+OK"; + config.quit = "QUIT\r\n"; + config.use_tls = true; + config.server_port = DEFAULT_SPOP_PORT; + } else if (!strncmp(config.service, "SSMTP", strlen("SSMTP"))) { + config.server_expect[0] = "220"; + config.quit = "QUIT\r\n"; + config.use_tls = true; + config.server_port = DEFAULT_SSMTP_PORT; + } else if (!strncmp(config.service, "JABBER", strlen("JABBER"))) { + config.send = "\n"; + config.server_expect[0] = "\n"; + config.hide_output = true; + config.server_port = DEFAULT_XMPP_C2S_PORT; + } else if (!strncmp(config.service, "NNTPS", strlen("NNTPS"))) { + config.server_expect_count = 2; + config.server_expect[0] = "200"; + config.server_expect[1] = "201"; + config.quit = "QUIT\r\n"; + config.use_tls = true; + config.server_port = DEFAULT_NNTPS_PORT; } #endif - else if (!strncmp(SERVICE, "NNTP", 4)) { - server_expect_count = 2; - server_expect = malloc(sizeof(char *) * server_expect_count); - server_expect[0] = strdup("200"); - server_expect[1] = strdup("201"); - QUIT = "QUIT\r\n"; - PORT = 119; - } else if (!strncmp(SERVICE, "CLAMD", 5)) { - SEND = "PING"; - EXPECT = "PONG"; - QUIT = NULL; - PORT = 3310; + else if (!strncmp(config.service, "NNTP", strlen("NNTP"))) { + config.server_expect_count = 2; + char **tmp = realloc(config.server_expect, config.server_expect_count * sizeof(char *)); + if (tmp == NULL) { + free(config.server_expect); + die(STATE_UNKNOWN, _("Allocation failed")); + } + config.server_expect = tmp; + + config.server_expect[0] = strdup("200"); + config.server_expect[1] = strdup("201"); + config.quit = "QUIT\r\n"; + config.server_port = DEFAULT_NNTP_PORT; + } else if (!strncmp(config.service, "CLAMD", strlen("CLAMD"))) { + config.send = "PING"; + config.server_expect[0] = "PONG"; + config.quit = NULL; + config.server_port = DEFAULT_CLAMD_PORT; } /* fallthrough check, so it's supposed to use reverse matching */ - else if (strcmp(SERVICE, "TCP")) + else if (strcmp(config.service, "TCP")) { usage(_("CRITICAL - Generic check_tcp called with unknown service\n")); - - server_address = "127.0.0.1"; - server_port = PORT; - server_send = SEND; - server_quit = QUIT; - char *status = NULL; + } /* Parse extra opts if any */ argv = np_extra_opts(&argc, argv, progname); - if (process_arguments(argc, argv) == ERROR) + process_arguments_wrapper paw = process_arguments(argc, argv, config); + if (paw.errorcode == ERROR) { usage4(_("Could not parse arguments")); + } + + config = paw.config; - if (flags & FLAG_VERBOSE) { - printf("Using service %s\n", SERVICE); - printf("Port: %d\n", server_port); - printf("flags: 0x%x\n", (int)flags); + if (verbosity > 0) { + printf("Using service %s\n", config.service); + printf("Port: %d\n", config.server_port); } - if (EXPECT && !server_expect_count) - server_expect_count++; + if ((config.server_expect_count == 0) && config.server_expect[0]) { + config.server_expect_count++; + } - if (PROTOCOL == IPPROTO_UDP && !(server_expect_count && server_send)) { + if (config.protocol == IPPROTO_UDP && !(config.server_expect_count && config.send)) { usage(_("With UDP checks, a send/expect string must be specified.")); } + // Initialize check stuff before setting timers + mp_check overall = mp_check_init(); + /* set up the timer */ signal(SIGALRM, socket_timeout_alarm_handler); alarm(socket_timeout); /* try to connect to the host at the given port number */ - struct timeval tv; - gettimeofday(&tv, NULL); - - int result = STATE_UNKNOWN; - result = np_net_connect(server_address, server_port, &sd, PROTOCOL); - if (result == STATE_CRITICAL) - return econn_refuse_state; + struct timeval start_time; + gettimeofday(&start_time, NULL); + + int socket_descriptor = 0; + mp_subcheck inital_connect_result = mp_subcheck_init(); + + // Try initial connection + if (np_net_connect(config.server_address, config.server_port, &socket_descriptor, config.protocol) == STATE_CRITICAL) { + // Early exit here, we got connection refused + inital_connect_result = mp_set_subcheck_state(inital_connect_result, config.econn_refuse_state); + xasprintf(&inital_connect_result.output, "Connection to %s on port %i was REFUSED", config.server_address, config.server_port); + mp_add_subcheck_to_check(&overall, inital_connect_result); + mp_exit(overall); + } else { + inital_connect_result = mp_set_subcheck_state(inital_connect_result, STATE_OK); + xasprintf(&inital_connect_result.output, "Connection to %s on port %i was a SUCCESS", config.server_address, config.server_port); + mp_add_subcheck_to_check(&overall, inital_connect_result); + } #ifdef HAVE_SSL - if (flags & FLAG_SSL) { - result = np_net_ssl_init_with_hostname(sd, (sni_specified ? sni : NULL)); - if (result == STATE_OK && check_cert) { - result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit); + if (config.use_tls) { + mp_subcheck tls_connection_result = mp_subcheck_init(); + int result = np_net_ssl_init_with_hostname(socket_descriptor, (config.sni_specified ? config.sni : NULL)); + tls_connection_result = mp_set_subcheck_state(tls_connection_result, result); + + if (result == STATE_OK) { + xasprintf(&tls_connection_result.output, "TLS connection succeded"); + + if (config.check_cert) { + result = np_net_ssl_check_cert(config.days_till_exp_warn, config.days_till_exp_crit); + + mp_subcheck tls_certificate_lifetime_result = mp_subcheck_init(); + tls_certificate_lifetime_result = mp_set_subcheck_state(tls_certificate_lifetime_result, result); + + if (result == STATE_OK) { + xasprintf(&tls_certificate_lifetime_result.output, "Certificate lifetime is within thresholds"); + } else if (result == STATE_WARNING) { + xasprintf(&tls_certificate_lifetime_result.output, "Certificate lifetime is violating warning threshold (%i)", + config.days_till_exp_warn); + } else if (result == STATE_CRITICAL) { + xasprintf(&tls_certificate_lifetime_result.output, "Certificate lifetime is violating critical threshold (%i)", + config.days_till_exp_crit); + } else { + xasprintf(&tls_certificate_lifetime_result.output, "Certificate lifetime is somehow unknown"); + } + + mp_add_subcheck_to_subcheck(&tls_connection_result, tls_certificate_lifetime_result); + } + + mp_add_subcheck_to_check(&overall, tls_connection_result); + } else { + xasprintf(&tls_connection_result.output, "TLS connection failed"); + mp_add_subcheck_to_check(&overall, tls_connection_result); + + if (socket_descriptor) { + close(socket_descriptor); + } + np_net_ssl_cleanup(); + + mp_exit(overall); } } - if (result != STATE_OK) { - if (sd) - close(sd); - np_net_ssl_cleanup(); - return result; - } #endif /* HAVE_SSL */ - if (server_send != NULL) { /* Something to send? */ - my_send(server_send, strlen(server_send)); + if (config.send != NULL) { /* Something to send? */ + my_send(config.send, strlen(config.send)); } - if (delay > 0) { - tv.tv_sec += delay; - sleep(delay); + if (config.delay > 0) { + start_time.tv_sec += config.delay; + sleep(config.delay); } - if (flags & FLAG_VERBOSE) { - if (server_send) { - printf("Send string: %s\n", server_send); + if (verbosity > 0) { + if (config.send) { + printf("Send string: %s\n", config.send); } - if (server_quit) { - printf("Quit string: %s\n", server_quit); + if (config.quit) { + printf("Quit string: %s\n", config.quit); + } + printf("server_expect_count: %d\n", (int)config.server_expect_count); + for (size_t i = 0; i < config.server_expect_count; i++) { + printf("\t%zd: %s\n", i, config.server_expect[i]); } - printf("server_expect_count: %d\n", (int)server_expect_count); - for (size_t i = 0; i < server_expect_count; i++) - printf("\t%zd: %s\n", i, server_expect[i]); } /* if(len) later on, we know we have a non-NULL response */ ssize_t len = 0; - + char *status = NULL; int match = -1; - struct timeval timeout; - fd_set rfds; - FD_ZERO(&rfds); - if (server_expect_count) { + mp_subcheck expected_data_result = mp_subcheck_init(); + + if (config.server_expect_count) { ssize_t received = 0; + char buffer[MAXBUF]; /* watch for the expect string */ while ((received = my_recv(buffer, sizeof(buffer))) > 0) { status = realloc(status, len + received + 1); + + if (status == NULL) { + die(STATE_UNKNOWN, _("Allocation failed")); + } + memcpy(&status[len], buffer, received); len += received; status[len] = '\0'; /* stop reading if user-forced */ - if (maxbytes && len >= maxbytes) + if (config.maxbytes && len >= config.maxbytes) { break; + } - if ((match = np_expect_match(status, server_expect, server_expect_count, match_flags)) != NP_MATCH_RETRY) + if ((match = np_expect_match(status, config.server_expect, config.server_expect_count, config.match_flags)) != NP_MATCH_RETRY) { break; + } + + fd_set rfds; + FD_ZERO(&rfds); + FD_SET(socket_descriptor, &rfds); /* some protocols wait for further input, so make sure we don't wait forever */ - FD_SET(sd, &rfds); + struct timeval timeout; timeout.tv_sec = READ_TIMEOUT; timeout.tv_usec = 0; - if (select(sd + 1, &rfds, NULL, NULL, &timeout) <= 0) + + if (select(socket_descriptor + 1, &rfds, NULL, NULL, &timeout) <= 0) { break; + } } - if (match == NP_MATCH_RETRY) + if (match == NP_MATCH_RETRY) { match = NP_MATCH_FAILURE; + } /* no data when expected, so return critical */ - if (len == 0) - die(STATE_CRITICAL, _("No data received from host\n")); + if (len == 0) { + xasprintf(&expected_data_result.output, "Received no data when some was expected"); + expected_data_result = mp_set_subcheck_state(expected_data_result, STATE_CRITICAL); + mp_add_subcheck_to_check(&overall, expected_data_result); + mp_exit(overall); + } /* print raw output if we're debugging */ - if (flags & FLAG_VERBOSE) + if (verbosity > 0) { printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n", (int)len + 1, status); + } /* strip whitespace from end of output */ - while (--len > 0 && isspace(status[len])) + while (--len > 0 && isspace(status[len])) { status[len] = '\0'; + } + } + + if (config.quit != NULL) { + my_send(config.quit, strlen(config.quit)); } - if (server_quit != NULL) { - my_send(server_quit, strlen(server_quit)); + if (socket_descriptor) { + close(socket_descriptor); } - if (sd) - close(sd); #ifdef HAVE_SSL np_net_ssl_cleanup(); #endif - microsec = deltime(tv); - elapsed_time = (double)microsec / 1.0e6; + long microsec = deltime(start_time); + double elapsed_time = (double)microsec / 1.0e6; - if (flags & FLAG_TIME_CRIT && elapsed_time > critical_time) - result = STATE_CRITICAL; - else if (flags & FLAG_TIME_WARN && elapsed_time > warning_time) - result = STATE_WARNING; + mp_subcheck elapsed_time_result = mp_subcheck_init(); - /* did we get the response we hoped? */ - if (match == NP_MATCH_FAILURE && result != STATE_CRITICAL) - result = expect_mismatch_state; + mp_perfdata time_pd = perfdata_init(); + time_pd = mp_set_pd_value(time_pd, elapsed_time); + time_pd.label = "time"; + time_pd.uom = "s"; - /* reset the alarm */ - alarm(0); + if (config.critical_time_set && elapsed_time > config.critical_time) { + xasprintf(&elapsed_time_result.output, "Connection time %fs exceeded critical threshold (%f)", elapsed_time, config.critical_time); + + elapsed_time_result = mp_set_subcheck_state(elapsed_time_result, STATE_CRITICAL); + time_pd.crit_present = true; + mp_range crit_val = mp_range_init(); + + crit_val.end = mp_create_pd_value(config.critical_time); + crit_val.end_infinity = false; + + time_pd.crit = crit_val; + } else if (config.warning_time_set && elapsed_time > config.warning_time) { + xasprintf(&elapsed_time_result.output, "Connection time %fs exceeded warning threshold (%f)", elapsed_time, config.critical_time); - /* this is a bit stupid, because we don't want to print the - * response time (which can look ok to the user) if we didn't get - * the response we were looking for. if-else */ - printf("%s %s - ", SERVICE, state_text(result)); - - if (match == NP_MATCH_FAILURE && len && !(flags & FLAG_HIDE_OUTPUT)) - printf("Unexpected response from host/socket: %s", status); - else { - if (match == NP_MATCH_FAILURE) - printf("Unexpected response from host/socket on "); - else - printf("%.3f second response time on ", elapsed_time); - if (server_address[0] != '/') { - if (host_specified) - printf("%s port %d", server_address, server_port); - else - printf("port %d", server_port); - } else - printf("socket %s", server_address); + elapsed_time_result = mp_set_subcheck_state(elapsed_time_result, STATE_WARNING); + time_pd.warn_present = true; + mp_range warn_val = mp_range_init(); + warn_val.end = mp_create_pd_value(config.critical_time); + warn_val.end_infinity = false; + + time_pd.warn = warn_val; + } else { + elapsed_time_result = mp_set_subcheck_state(elapsed_time_result, STATE_OK); + xasprintf(&elapsed_time_result.output, "Connection time %fs is within thresholds", elapsed_time); } - if (match != NP_MATCH_FAILURE && !(flags & FLAG_HIDE_OUTPUT) && len) - printf(" [%s]", status); + mp_add_perfdata_to_subcheck(&elapsed_time_result, time_pd); + mp_add_subcheck_to_check(&overall, elapsed_time_result); - /* perf-data doesn't apply when server doesn't talk properly, - * so print all zeroes on warn and crit. Use fperfdata since - * localisation settings can make different outputs */ - if (match == NP_MATCH_FAILURE) - printf("|%s", fperfdata("time", elapsed_time, "s", (flags & FLAG_TIME_WARN ? true : false), 0, - (flags & FLAG_TIME_CRIT ? true : false), 0, true, 0, true, socket_timeout)); - else - printf("|%s", fperfdata("time", elapsed_time, "s", (flags & FLAG_TIME_WARN ? true : false), warning_time, - (flags & FLAG_TIME_CRIT ? true : false), critical_time, true, 0, true, socket_timeout)); + /* did we get the response we hoped? */ + if (match == NP_MATCH_FAILURE) { + expected_data_result = mp_set_subcheck_state(expected_data_result, config.expect_mismatch_state); + xasprintf(&expected_data_result.output, "Answer failed to match expectation"); + mp_add_subcheck_to_check(&overall, expected_data_result); + } - putchar('\n'); - return result; + /* reset the alarm */ + alarm(0); + + mp_exit(overall); } /* process command-line arguments */ -static int process_arguments(int argc, char **argv) { +static process_arguments_wrapper process_arguments(int argc, char **argv, check_tcp_config config) { enum { SNI_OPTION = CHAR_MAX + 1 }; + int option = 0; static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, @@ -406,52 +486,44 @@ static int process_arguments(int argc, char **argv) { {"certificate", required_argument, 0, 'D'}, {0, 0, 0, 0}}; - if (argc < 2) + if (argc < 2) { usage4(_("No arguments found")); - - /* backwards compatibility */ - for (int i = 1; i < argc; i++) { - if (strcmp("-to", argv[i]) == 0) - strcpy(argv[i], "-t"); - else if (strcmp("-wt", argv[i]) == 0) - strcpy(argv[i], "-w"); - else if (strcmp("-ct", argv[i]) == 0) - strcpy(argv[i], "-c"); } if (!is_option(argv[1])) { - server_address = argv[1]; + config.server_address = argv[1]; argv[1] = argv[0]; argv = &argv[1]; argc--; } - int option_char; + int c; bool escape = false; + while (true) { - int option = 0; - option_char = getopt_long(argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:", longopts, &option); + c = getopt_long(argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:", longopts, &option); - if (option_char == -1 || option_char == EOF || option_char == 1) + if (c == -1 || c == EOF || c == 1) { break; + } - switch (option_char) { + switch (c) { case '?': /* print short usage statement if args not parsable */ usage5(); case 'h': /* help */ - print_help(); + print_help(config.service); exit(STATE_UNKNOWN); case 'V': /* version */ print_revision(progname, NP_VERSION); exit(STATE_UNKNOWN); case 'v': /* verbose mode */ - flags |= FLAG_VERBOSE; - match_flags |= NP_MATCH_VERBOSE; + verbosity++; + config.match_flags |= NP_MATCH_VERBOSE; break; - case '4': + case '4': // Apparently unused TODO address_family = AF_INET; break; - case '6': + case '6': // Apparently unused TODO #ifdef USE_IPV6 address_family = AF_INET6; #else @@ -459,163 +531,178 @@ static int process_arguments(int argc, char **argv) { #endif break; case 'H': /* hostname */ - host_specified = true; - server_address = optarg; + config.host_specified = true; + config.server_address = optarg; break; case 'c': /* critical */ - critical_time = strtod(optarg, NULL); - flags |= FLAG_TIME_CRIT; + config.critical_time = strtod(optarg, NULL); + config.critical_time_set = true; break; case 'j': /* hide output */ - flags |= FLAG_HIDE_OUTPUT; + config.hide_output = true; break; case 'w': /* warning */ - warning_time = strtod(optarg, NULL); - flags |= FLAG_TIME_WARN; - break; - case 'C': - crit_codes = realloc(crit_codes, ++crit_codes_count); - crit_codes[crit_codes_count - 1] = optarg; - break; - case 'W': - warn_codes = realloc(warn_codes, ++warn_codes_count); - warn_codes[warn_codes_count - 1] = optarg; + config.warning_time = strtod(optarg, NULL); + config.warning_time_set = true; break; case 't': /* timeout */ - if (!is_intpos(optarg)) + if (!is_intpos(optarg)) { usage4(_("Timeout interval must be a positive integer")); - else + } else { socket_timeout = atoi(optarg); + } break; case 'p': /* port */ - if (!is_intpos(optarg)) + if (!is_intpos(optarg)) { usage4(_("Port must be a positive integer")); - else - server_port = atoi(optarg); + } else { + config.server_port = atoi(optarg); + } break; case 'E': escape = true; break; case 's': - if (escape) - server_send = np_escaped_string(optarg); - else - xasprintf(&server_send, "%s", optarg); + if (escape) { + config.send = np_escaped_string(optarg); + } else { + xasprintf(&config.send, "%s", optarg); + } break; case 'e': /* expect string (may be repeated) */ - match_flags &= ~NP_MATCH_EXACT; - if (server_expect_count == 0) - server_expect = malloc(sizeof(char *) * (++server_expect_count)); - else - server_expect = realloc(server_expect, sizeof(char *) * (++server_expect_count)); - server_expect[server_expect_count - 1] = optarg; + config.match_flags &= ~NP_MATCH_EXACT; + if (config.server_expect_count == 0) { + config.server_expect = malloc(sizeof(char *) * (++config.server_expect_count)); + } else { + config.server_expect = realloc(config.server_expect, sizeof(char *) * (++config.server_expect_count)); + } + + if (config.server_expect == NULL) { + die(STATE_UNKNOWN, _("Allocation failed")); + } + config.server_expect[config.server_expect_count - 1] = optarg; break; case 'm': - if (!is_intpos(optarg)) + if (!is_intpos(optarg)) { usage4(_("Maxbytes must be a positive integer")); - else - maxbytes = strtol(optarg, NULL, 0); + } else { + config.maxbytes = strtol(optarg, NULL, 0); + } break; case 'q': - if (escape) - server_quit = np_escaped_string(optarg); - else - xasprintf(&server_quit, "%s\r\n", optarg); + if (escape) { + config.quit = np_escaped_string(optarg); + } else { + xasprintf(&config.quit, "%s\r\n", optarg); + } break; case 'r': - if (!strncmp(optarg, "ok", 2)) - econn_refuse_state = STATE_OK; - else if (!strncmp(optarg, "warn", 4)) - econn_refuse_state = STATE_WARNING; - else if (!strncmp(optarg, "crit", 4)) - econn_refuse_state = STATE_CRITICAL; - else + if (!strncmp(optarg, "ok", 2)) { + config.econn_refuse_state = STATE_OK; + } else if (!strncmp(optarg, "warn", 4)) { + config.econn_refuse_state = STATE_WARNING; + } else if (!strncmp(optarg, "crit", 4)) { + config.econn_refuse_state = STATE_CRITICAL; + } else { usage4(_("Refuse must be one of ok, warn, crit")); + } break; case 'M': - if (!strncmp(optarg, "ok", 2)) - expect_mismatch_state = STATE_OK; - else if (!strncmp(optarg, "warn", 4)) - expect_mismatch_state = STATE_WARNING; - else if (!strncmp(optarg, "crit", 4)) - expect_mismatch_state = STATE_CRITICAL; - else + if (!strncmp(optarg, "ok", 2)) { + config.expect_mismatch_state = STATE_OK; + } else if (!strncmp(optarg, "warn", 4)) { + config.expect_mismatch_state = STATE_WARNING; + } else if (!strncmp(optarg, "crit", 4)) { + config.expect_mismatch_state = STATE_CRITICAL; + } else { usage4(_("Mismatch must be one of ok, warn, crit")); + } break; case 'd': - if (is_intpos(optarg)) - delay = atoi(optarg); - else + if (is_intpos(optarg)) { + config.delay = atoi(optarg); + } else { usage4(_("Delay must be a positive integer")); + } break; - case 'D': { /* Check SSL cert validity - days 'til certificate expiration */ + case 'D': /* Check SSL cert validity - days 'til certificate expiration */ #ifdef HAVE_SSL # ifdef USE_OPENSSL /* XXX */ + { char *temp; if ((temp = strchr(optarg, ',')) != NULL) { *temp = '\0'; - if (!is_intnonneg(optarg)) + if (!is_intnonneg(optarg)) { usage2(_("Invalid certificate expiration period"), optarg); - days_till_exp_warn = atoi(optarg); + } + config.days_till_exp_warn = atoi(optarg); *temp = ','; temp++; - if (!is_intnonneg(temp)) + if (!is_intnonneg(temp)) { usage2(_("Invalid certificate expiration period"), temp); - days_till_exp_crit = atoi(temp); + } + config.days_till_exp_crit = atoi(temp); } else { - days_till_exp_crit = 0; - if (!is_intnonneg(optarg)) + config.days_till_exp_crit = 0; + if (!is_intnonneg(optarg)) { usage2(_("Invalid certificate expiration period"), optarg); - days_till_exp_warn = atoi(optarg); + } + config.days_till_exp_warn = atoi(optarg); } - check_cert = true; - flags |= FLAG_SSL; + config.check_cert = true; + config.use_tls = true; } break; # endif /* USE_OPENSSL */ #endif /* fallthrough if we don't have ssl */ case 'S': #ifdef HAVE_SSL - flags |= FLAG_SSL; + config.use_tls = true; #else die(STATE_UNKNOWN, _("Invalid option - SSL is not available")); #endif break; case SNI_OPTION: #ifdef HAVE_SSL - flags |= FLAG_SSL; - sni_specified = true; - sni = optarg; + config.use_tls = true; + config.sni_specified = true; + config.sni = optarg; #else die(STATE_UNKNOWN, _("Invalid option - SSL is not available")); #endif break; case 'A': - match_flags |= NP_MATCH_ALL; + config.match_flags |= NP_MATCH_ALL; break; } } - option_char = optind; - if (!host_specified && option_char < argc) - server_address = strdup(argv[option_char++]); + c = optind; + if (!config.host_specified && c < argc) { + config.server_address = strdup(argv[c++]); + } - if (server_address == NULL) + if (config.server_address == NULL) { usage4(_("You must provide a server address")); - else if (server_address[0] != '/' && !is_host(server_address)) - die(STATE_CRITICAL, "%s %s - %s: %s\n", SERVICE, state_text(STATE_CRITICAL), _("Invalid hostname, address or socket"), - server_address); + } else if (config.server_address[0] != '/' && !is_host(config.server_address)) { + die(STATE_CRITICAL, "%s %s - %s: %s\n", config.service, state_text(STATE_CRITICAL), _("Invalid hostname, address or socket"), + config.server_address); + } - return OK; + process_arguments_wrapper result = { + .config = config, + .errorcode = OK, + }; + return result; } -void print_help(void) { +void print_help(const char *service) { print_revision(progname, NP_VERSION); printf("Copyright (c) 1999 Ethan Galstad \n"); printf(COPYRIGHT, copyright, email); - printf(_("This plugin tests %s connections with the specified host (or unix socket).\n\n"), SERVICE); + printf(_("This plugin tests %s connections with the specified host (or unix socket).\n\n"), service); print_usage(); @@ -662,6 +749,7 @@ void print_help(void) { printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + printf(UT_OUTPUT_FORMAT); printf(UT_VERBOSE); printf(UT_SUPPORT); diff --git a/plugins/check_tcp.d/config.h b/plugins/check_tcp.d/config.h new file mode 100644 index 00000000..7ecf51a6 --- /dev/null +++ b/plugins/check_tcp.d/config.h @@ -0,0 +1,78 @@ +#pragma once + +#include "../common.h" +#include "../../lib/utils_tcp.h" +#include + +typedef struct check_tcp_config { + char *server_address; + bool host_specified; + int server_port; // TODO can this be a uint16? + + int protocol; /* most common is default */ + char *service; + char *send; + char *quit; + char **server_expect; + size_t server_expect_count; +#ifdef HAVE_SSL + bool use_tls; + char *sni; + bool sni_specified; + bool check_cert; + int days_till_exp_warn; + int days_till_exp_crit; +#endif // HAVE_SSL + int match_flags; + int expect_mismatch_state; + unsigned int delay; + + bool warning_time_set; + double warning_time; + bool critical_time_set; + double critical_time; + + int econn_refuse_state; + + ssize_t maxbytes; + + bool hide_output; +} check_tcp_config; + +check_tcp_config check_tcp_config_init() { + check_tcp_config result = { + .server_address = "127.0.0.1", + .host_specified = false, + .server_port = 0, + + .protocol = IPPROTO_TCP, + .service = "TCP", + .send = NULL, + .quit = NULL, + .server_expect = NULL, + .server_expect_count = 0, +#ifdef HAVE_SSL + .use_tls = false, + .sni = NULL, + .sni_specified = false, + .check_cert = false, + .days_till_exp_warn = 0, + .days_till_exp_crit = 0, +#endif // HAVE_SSL + .match_flags = NP_MATCH_EXACT, + .expect_mismatch_state = STATE_WARNING, + .delay = 0, + + .warning_time_set = false, + .warning_time = 0, + .critical_time_set = false, + .critical_time = 0, + + .econn_refuse_state = STATE_CRITICAL, + + .maxbytes = 0, + + .hide_output = false, + }; + return result; +} -- cgit v1.2.3-74-g34f1 From d5ed6a2d8f3f3f388e5d1f2f7a8fc3ee2c9b6007 Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 13 Mar 2025 00:43:22 +0100 Subject: check_tcp: small improvement + output format picker --- plugins/check_tcp.c | 46 +++++++++++++++++++++++++++++--------------- plugins/check_tcp.d/config.h | 9 +++++++-- 2 files changed, 38 insertions(+), 17 deletions(-) (limited to 'plugins') diff --git a/plugins/check_tcp.c b/plugins/check_tcp.c index f93152e5..793cfe7e 100644 --- a/plugins/check_tcp.c +++ b/plugins/check_tcp.c @@ -28,7 +28,6 @@ *****************************************************************************/ /* progname "check_tcp" changes depending on symlink called */ -#include "states.h" char *progname; const char *copyright = "1999-2025"; const char *email = "devel@monitoring-plugins.org"; @@ -37,6 +36,7 @@ const char *email = "devel@monitoring-plugins.org"; #include "./netutils.h" #include "./utils.h" #include "./check_tcp.d/config.h" +#include "states.h" #include #include @@ -61,10 +61,10 @@ ssize_t my_send(char *buf, size_t len) { typedef struct process_arguments_wrapper { int errorcode; check_tcp_config config; -} process_arguments_wrapper; +} check_tcp_config_wrapper; /* int my_recv(char *, size_t); */ -static process_arguments_wrapper process_arguments(int /*argc*/, char ** /*argv*/, check_tcp_config /*config*/); +static check_tcp_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/, check_tcp_config /*config*/); void print_help(const char *service); void print_usage(void); @@ -207,7 +207,7 @@ int main(int argc, char **argv) { /* Parse extra opts if any */ argv = np_extra_opts(&argc, argv, progname); - process_arguments_wrapper paw = process_arguments(argc, argv, config); + check_tcp_config_wrapper paw = process_arguments(argc, argv, config); if (paw.errorcode == ERROR) { usage4(_("Could not parse arguments")); } @@ -229,6 +229,9 @@ int main(int argc, char **argv) { // Initialize check stuff before setting timers mp_check overall = mp_check_init(); + if (config.output_format_set) { + overall.format = config.output_format; + } /* set up the timer */ signal(SIGALRM, socket_timeout_alarm_handler); @@ -452,12 +455,12 @@ int main(int argc, char **argv) { } /* process command-line arguments */ -static process_arguments_wrapper process_arguments(int argc, char **argv, check_tcp_config config) { +static check_tcp_config_wrapper process_arguments(int argc, char **argv, check_tcp_config config) { enum { - SNI_OPTION = CHAR_MAX + 1 + SNI_OPTION = CHAR_MAX + 1, + output_format_index, }; - int option = 0; static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, @@ -484,6 +487,7 @@ static process_arguments_wrapper process_arguments(int argc, char **argv, check_ {"ssl", no_argument, 0, 'S'}, {"sni", required_argument, 0, SNI_OPTION}, {"certificate", required_argument, 0, 'D'}, + {"output-format", required_argument, 0, output_format_index}, {0, 0, 0, 0}}; if (argc < 2) { @@ -497,17 +501,17 @@ static process_arguments_wrapper process_arguments(int argc, char **argv, check_ argc--; } - int c; bool escape = false; while (true) { - c = getopt_long(argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:", longopts, &option); + int option = 0; + int option_index = getopt_long(argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:", longopts, &option); - if (c == -1 || c == EOF || c == 1) { + if (option_index == -1 || option_index == EOF || option_index == 1) { break; } - switch (c) { + switch (option_index) { case '?': /* print short usage statement if args not parsable */ usage5(); case 'h': /* help */ @@ -674,12 +678,24 @@ static process_arguments_wrapper process_arguments(int argc, char **argv, check_ case 'A': config.match_flags |= NP_MATCH_ALL; break; + case output_format_index: { + parsed_output_format parser = mp_parse_output_format(optarg); + if (!parser.parsing_success) { + // TODO List all available formats here, maybe add anothoer usage function + printf("Invalid output format: %s\n", optarg); + exit(STATE_UNKNOWN); + } + + config.output_format_set = true; + config.output_format = parser.output_format; + break; + } } } - c = optind; - if (!config.host_specified && c < argc) { - config.server_address = strdup(argv[c++]); + int index = optind; + if (!config.host_specified && index < argc) { + config.server_address = strdup(argv[index++]); } if (config.server_address == NULL) { @@ -689,7 +705,7 @@ static process_arguments_wrapper process_arguments(int argc, char **argv, check_ config.server_address); } - process_arguments_wrapper result = { + check_tcp_config_wrapper result = { .config = config, .errorcode = OK, }; diff --git a/plugins/check_tcp.d/config.h b/plugins/check_tcp.d/config.h index 7ecf51a6..41db7224 100644 --- a/plugins/check_tcp.d/config.h +++ b/plugins/check_tcp.d/config.h @@ -1,10 +1,10 @@ #pragma once -#include "../common.h" #include "../../lib/utils_tcp.h" +#include "output.h" #include -typedef struct check_tcp_config { +typedef struct { char *server_address; bool host_specified; int server_port; // TODO can this be a uint16? @@ -37,6 +37,9 @@ typedef struct check_tcp_config { ssize_t maxbytes; bool hide_output; + + bool output_format_set; + mp_output_format output_format; } check_tcp_config; check_tcp_config check_tcp_config_init() { @@ -73,6 +76,8 @@ check_tcp_config check_tcp_config_init() { .maxbytes = 0, .hide_output = false, + + .output_format_set = false, }; return result; } -- cgit v1.2.3-74-g34f1 From 44e4e467c678d481dfc74ade1beb47e199ea67dd Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 13 Mar 2025 00:43:46 +0100 Subject: Do not print on failed network connections --- plugins/netutils.c | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) (limited to 'plugins') diff --git a/plugins/netutils.c b/plugins/netutils.c index ee81912a..5f118a9e 100644 --- a/plugins/netutils.c +++ b/plugins/netutils.c @@ -177,7 +177,7 @@ int np_net_connect(const char *host_name, int port, int *sd, int proto) { result = getaddrinfo(host, port_str, &hints, &res); if (result != 0) { - printf("%s\n", gai_strerror(result)); + // printf("%s\n", gai_strerror(result)); return STATE_UNKNOWN; } @@ -187,7 +187,7 @@ int np_net_connect(const char *host_name, int port, int *sd, int proto) { *sd = socket(r->ai_family, socktype, r->ai_protocol); if (*sd < 0) { - printf("%s\n", _("Socket creation failed")); + // printf("%s\n", _("Socket creation failed")); freeaddrinfo(r); return STATE_UNKNOWN; } @@ -237,10 +237,11 @@ int np_net_connect(const char *host_name, int port, int *sd, int proto) { case STATE_OK: case STATE_WARNING: /* user wants WARN or OK on refusal, or... */ case STATE_CRITICAL: /* user did not set econn_refuse_state, or wanted critical */ - if (is_socket) - printf("connect to file socket %s: %s\n", host_name, strerror(errno)); - else - printf("connect to address %s and port %d: %s\n", host_name, port, strerror(errno)); + if (is_socket) { + // printf("connect to file socket %s: %s\n", host_name, strerror(errno)); + } else { + // printf("connect to address %s and port %d: %s\n", host_name, port, strerror(errno)); + } return STATE_CRITICAL; break; default: /* it's a logic error if we do not end up in STATE_(OK|WARNING|CRITICAL) */ @@ -248,10 +249,11 @@ int np_net_connect(const char *host_name, int port, int *sd, int proto) { break; } } else { - if (is_socket) - printf("connect to file socket %s: %s\n", host_name, strerror(errno)); - else - printf("connect to address %s and port %d: %s\n", host_name, port, strerror(errno)); + if (is_socket) { + // printf("connect to file socket %s: %s\n", host_name, strerror(errno)); + } else { + // printf("connect to address %s and port %d: %s\n", host_name, port, strerror(errno)); + } return STATE_CRITICAL; } } -- cgit v1.2.3-74-g34f1 From 89df16e7503539c2b0da7e95375b470559bb94ec Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 13 Mar 2025 00:44:35 +0100 Subject: Adapt tests --- plugins/t/check_tcp.t | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'plugins') diff --git a/plugins/t/check_tcp.t b/plugins/t/check_tcp.t index cb4de53d..b47caab3 100644 --- a/plugins/t/check_tcp.t +++ b/plugins/t/check_tcp.t @@ -21,19 +21,19 @@ my $host_nonresponsive = getTestParameter("NP_HOST_NONRESPONSIVE", "The hostname my $hostname_invalid = getTestParameter("NP_HOSTNAME_INVALID", "An invalid (not known to DNS) hostname", "nosuchhost"); my $internet_access = getTestParameter("NP_INTERNET_ACCESS", "Is this system directly connected to the internet?", "yes"); -my $successOutput = '/^TCP OK\s-\s+[0-9]?\.?[0-9]+ second response time on port [0-9]+/'; +my $successOutput = '/Connection time\s+[0-9]?\.?[0-9]+s is within thresholds+/'; -my $failedExpect = '/^TCP WARNING\s-\sUnexpected response from host/socket on port [0-9]+/'; +my $failedExpect = '/\sUnexpected response from host/socket on port [0-9]+/'; my $t; $tests = $tests - 4 if $internet_access eq "no"; plan tests => $tests; -$t += checkCmd( "./check_tcp $host_tcp_http -p 80 -wt 300 -ct 600", 0, $successOutput ); -$t += checkCmd( "./check_tcp $host_tcp_http -p 81 -wt 0 -ct 0 -to 1", 2 ); # use invalid port for this test -$t += checkCmd( "./check_tcp $host_nonresponsive -p 80 -wt 0 -ct 0 -to 1", 2 ); -$t += checkCmd( "./check_tcp $hostname_invalid -p 80 -wt 0 -ct 0 -to 1", 2 ); +$t += checkCmd( "./check_tcp $host_tcp_http -p 80 -w 300 -c 600", 0, $successOutput ); +$t += checkCmd( "./check_tcp $host_tcp_http -p 81 -w 0 -c 0 -t 1", 2 ); # use invalid port for this test +$t += checkCmd( "./check_tcp $host_nonresponsive -p 80 -w 0 -c 0 -t 1", 2 ); +$t += checkCmd( "./check_tcp $hostname_invalid -p 80 -w 0 -c 0 -t 1", 2 ); if($internet_access ne "no") { $t += checkCmd( "./check_tcp -S -D 1 -H $host_tls_http -p 443", 0 ); $t += checkCmd( "./check_tcp -S -D 9000,1 -H $host_tls_http -p 443", 1 ); -- cgit v1.2.3-74-g34f1 From fa4a03e1a80d3de8c85172834326d51b936f316a Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 13 Mar 2025 00:49:16 +0100 Subject: use new output picker --- plugins/check_tcp.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_tcp.c b/plugins/check_tcp.c index 793cfe7e..2cc6c398 100644 --- a/plugins/check_tcp.c +++ b/plugins/check_tcp.c @@ -28,6 +28,7 @@ *****************************************************************************/ /* progname "check_tcp" changes depending on symlink called */ +#include "output.h" char *progname; const char *copyright = "1999-2025"; const char *email = "devel@monitoring-plugins.org"; @@ -230,7 +231,7 @@ int main(int argc, char **argv) { // Initialize check stuff before setting timers mp_check overall = mp_check_init(); if (config.output_format_set) { - overall.format = config.output_format; + mp_set_format(config.output_format); } /* set up the timer */ -- cgit v1.2.3-74-g34f1 From a2e9ade442bb93d632d7ef5b734103b4e1e4b07a Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 13 Mar 2025 00:50:51 +0100 Subject: Fix typo --- plugins/check_tcp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_tcp.c b/plugins/check_tcp.c index 2cc6c398..2878fd60 100644 --- a/plugins/check_tcp.c +++ b/plugins/check_tcp.c @@ -265,7 +265,7 @@ int main(int argc, char **argv) { tls_connection_result = mp_set_subcheck_state(tls_connection_result, result); if (result == STATE_OK) { - xasprintf(&tls_connection_result.output, "TLS connection succeded"); + xasprintf(&tls_connection_result.output, "TLS connection succeeded"); if (config.check_cert) { result = np_net_ssl_check_cert(config.days_till_exp_warn, config.days_till_exp_crit); -- cgit v1.2.3-74-g34f1 From 4dd024388e1f8be894e50dd0eb74d5c9f86b4233 Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 13 Mar 2025 11:37:20 +0100 Subject: check_tcp: small cleanup --- plugins/check_tcp.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/check_tcp.c b/plugins/check_tcp.c index 2878fd60..833cdc0c 100644 --- a/plugins/check_tcp.c +++ b/plugins/check_tcp.c @@ -28,7 +28,6 @@ *****************************************************************************/ /* progname "check_tcp" changes depending on symlink called */ -#include "output.h" char *progname; const char *copyright = "1999-2025"; const char *email = "devel@monitoring-plugins.org"; @@ -37,6 +36,7 @@ const char *email = "devel@monitoring-plugins.org"; #include "./netutils.h" #include "./utils.h" #include "./check_tcp.d/config.h" +#include "output.h" #include "states.h" #include @@ -59,12 +59,10 @@ ssize_t my_send(char *buf, size_t len) { #endif // HAVE_SSL } -typedef struct process_arguments_wrapper { +typedef struct { int errorcode; check_tcp_config config; } check_tcp_config_wrapper; - -/* int my_recv(char *, size_t); */ static check_tcp_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/, check_tcp_config /*config*/); void print_help(const char *service); void print_usage(void); -- cgit v1.2.3-74-g34f1 From be4618bf6429bddbd9208a88f460c028074fe8c0 Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 13 Mar 2025 11:37:52 +0100 Subject: check_tcp: patch backwards compatibility in again --- plugins/check_tcp.c | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'plugins') diff --git a/plugins/check_tcp.c b/plugins/check_tcp.c index 833cdc0c..d2ebc16d 100644 --- a/plugins/check_tcp.c +++ b/plugins/check_tcp.c @@ -493,6 +493,17 @@ static check_tcp_config_wrapper process_arguments(int argc, char **argv, check_t usage4(_("No arguments found")); } + /* backwards compatibility */ + for (int i = 1; i < argc; i++) { + if (strcmp("-to", argv[i]) == 0) { + strcpy(argv[i], "-t"); + } else if (strcmp("-wt", argv[i]) == 0) { + strcpy(argv[i], "-w"); + } else if (strcmp("-ct", argv[i]) == 0) { + strcpy(argv[i], "-c"); + } + } + if (!is_option(argv[1])) { config.server_address = argv[1]; argv[1] = argv[0]; -- cgit v1.2.3-74-g34f1 From a693cc0aa3d79f85115be48bcd81c0ec371e78a0 Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 13 Mar 2025 12:24:45 +0100 Subject: Fix TLS/non-TLS send/recv logic --- plugins/check_tcp.c | 45 ++++++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 21 deletions(-) (limited to 'plugins') diff --git a/plugins/check_tcp.c b/plugins/check_tcp.c index d2ebc16d..8cd86460 100644 --- a/plugins/check_tcp.c +++ b/plugins/check_tcp.c @@ -43,20 +43,22 @@ const char *email = "devel@monitoring-plugins.org"; #include #include -ssize_t my_recv(char *buf, size_t len) { +ssize_t my_recv(int socket_descriptor, char *buf, size_t len, bool use_tls) { #ifdef HAVE_SSL - return np_net_ssl_read(buf, (int)len); -#else + if (use_tls) { + return np_net_ssl_read(buf, (int)len); + } +#endif return read(socket_descriptor, buf, len); -#endif // HAVE_SSL } -ssize_t my_send(char *buf, size_t len) { +ssize_t my_send(int socket_descriptor, char *buf, size_t len, bool use_tls) { #ifdef HAVE_SSL - return np_net_ssl_write(buf, (int)len); -#else + if (use_tls) { + return np_net_ssl_write(buf, (int)len); + } +#endif return write(socket_descriptor, buf, len); -#endif // HAVE_SSL } typedef struct { @@ -302,7 +304,7 @@ int main(int argc, char **argv) { #endif /* HAVE_SSL */ if (config.send != NULL) { /* Something to send? */ - my_send(config.send, strlen(config.send)); + my_send(socket_descriptor, config.send, strlen(config.send), config.use_tls); } if (config.delay > 0) { @@ -325,8 +327,8 @@ int main(int argc, char **argv) { /* if(len) later on, we know we have a non-NULL response */ ssize_t len = 0; - char *status = NULL; - int match = -1; + char *received_buffer = NULL; + enum np_match_result match = NP_MATCH_NONE; mp_subcheck expected_data_result = mp_subcheck_init(); if (config.server_expect_count) { @@ -334,23 +336,24 @@ int main(int argc, char **argv) { char buffer[MAXBUF]; /* watch for the expect string */ - while ((received = my_recv(buffer, sizeof(buffer))) > 0) { - status = realloc(status, len + received + 1); + while ((received = my_recv(socket_descriptor, buffer, sizeof(buffer), config.use_tls)) > 0) { + received_buffer = realloc(received_buffer, len + received + 1); - if (status == NULL) { + if (received_buffer == NULL) { die(STATE_UNKNOWN, _("Allocation failed")); } - memcpy(&status[len], buffer, received); + memcpy(&received_buffer[len], buffer, received); len += received; - status[len] = '\0'; + received_buffer[len] = '\0'; /* stop reading if user-forced */ if (config.maxbytes && len >= config.maxbytes) { break; } - if ((match = np_expect_match(status, config.server_expect, config.server_expect_count, config.match_flags)) != NP_MATCH_RETRY) { + if ((match = np_expect_match(received_buffer, config.server_expect, config.server_expect_count, config.match_flags)) != + NP_MATCH_RETRY) { break; } @@ -382,16 +385,16 @@ int main(int argc, char **argv) { /* print raw output if we're debugging */ if (verbosity > 0) { - printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n", (int)len + 1, status); + printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n", (int)len + 1, received_buffer); } /* strip whitespace from end of output */ - while (--len > 0 && isspace(status[len])) { - status[len] = '\0'; + while (--len > 0 && isspace(received_buffer[len])) { + received_buffer[len] = '\0'; } } if (config.quit != NULL) { - my_send(config.quit, strlen(config.quit)); + my_send(socket_descriptor, config.quit, strlen(config.quit), config.use_tls); } if (socket_descriptor) { -- cgit v1.2.3-74-g34f1 From c8014631de0f7927d8c75ff87225b5a24e9b9942 Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 13 Mar 2025 12:25:29 +0100 Subject: check_tcp: add output if answer matches expectations --- plugins/check_tcp.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_tcp.c b/plugins/check_tcp.c index 8cd86460..d1f6b84f 100644 --- a/plugins/check_tcp.c +++ b/plugins/check_tcp.c @@ -261,7 +261,7 @@ int main(int argc, char **argv) { #ifdef HAVE_SSL if (config.use_tls) { mp_subcheck tls_connection_result = mp_subcheck_init(); - int result = np_net_ssl_init_with_hostname(socket_descriptor, (config.sni_specified ? config.sni : NULL)); + mp_state_enum result = np_net_ssl_init_with_hostname(socket_descriptor, (config.sni_specified ? config.sni : NULL)); tls_connection_result = mp_set_subcheck_state(tls_connection_result, result); if (result == STATE_OK) { @@ -448,6 +448,10 @@ int main(int argc, char **argv) { expected_data_result = mp_set_subcheck_state(expected_data_result, config.expect_mismatch_state); xasprintf(&expected_data_result.output, "Answer failed to match expectation"); mp_add_subcheck_to_check(&overall, expected_data_result); + } else if (match == NP_MATCH_SUCCESS) { + expected_data_result = mp_set_subcheck_state(expected_data_result, STATE_OK); + xasprintf(&expected_data_result.output, "The answer of the server matched the expectation"); + mp_add_subcheck_to_check(&overall, expected_data_result); } /* reset the alarm */ -- cgit v1.2.3-74-g34f1 From 44211a672959494849476c45ff761181e62762ff Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 13 Mar 2025 12:59:40 +0100 Subject: Adapt tests more --- plugins/t/check_ftp.t | 2 +- plugins/t/check_jabber.t | 4 ++-- plugins/t/check_udp.t | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) (limited to 'plugins') diff --git a/plugins/t/check_ftp.t b/plugins/t/check_ftp.t index 93a7d7c3..a2f79dca 100644 --- a/plugins/t/check_ftp.t +++ b/plugins/t/check_ftp.t @@ -15,7 +15,7 @@ my $host_tcp_ftp = getTestParameter("NP_HOST_TCP_FTP", "A host providing t my $host_nonresponsive = getTestParameter("NP_HOST_NONRESPONSIVE", "The hostname of system not responsive to network requests", "10.0.0.1"); my $hostname_invalid = getTestParameter("NP_HOSTNAME_INVALID", "An invalid (not known to DNS) hostname", "nosuchhost"); -my $successOutput = '/FTP OK -\s+[0-9]?\.?[0-9]+ second response time/'; +my $successOutput = '/Connection time\s+[0-9]?\.?[0-9]+/'; my $t; diff --git a/plugins/t/check_jabber.t b/plugins/t/check_jabber.t index 08cadcbd..dc46f4c3 100644 --- a/plugins/t/check_jabber.t +++ b/plugins/t/check_jabber.t @@ -15,11 +15,11 @@ my $host_nonresponsive = getTestParameter("NP_HOST_NONRESPONSIVE", "The hostname my $hostname_invalid = getTestParameter("NP_HOSTNAME_INVALID", "An invalid (not known to DNS) hostname", "nosuchhost"); -my $jabberOK = '/JABBER OK\s-\s\d+\.\d+\ssecond response time on '.$host_tcp_jabber.' port 5222/'; +my $jabberOK = '/Connection to '.$host_tcp_jabber.' on port 5222/'; my $jabberUnresponsive = '/Socket timeout after\s\d+\sseconds/'; -my $jabberInvalid = '/JABBER CRITICAL - Invalid hostname, address or socket:\s.+/'; +my $jabberInvalid = '/Invalid hostname, address or socket:\s.+/'; my $r; diff --git a/plugins/t/check_udp.t b/plugins/t/check_udp.t index 6c47d095..5cb9e6dc 100644 --- a/plugins/t/check_udp.t +++ b/plugins/t/check_udp.t @@ -28,7 +28,7 @@ like ( $res->output, '/With UDP checks, a send/expect string must be specified. $res = NPTest->testCmd( "./check_udp -H localhost -p 3333 -s foo -e bar" ); cmp_ok( $res->return_code, '==', 2, "Errors correctly because no udp service running" ); -like ( $res->output, '/No data received from host/', "Output OK"); +like ( $res->output, '/Received no data /', "Output OK"); my $nc; if(system("which nc.traditional >/dev/null 2>&1") == 0) { @@ -48,7 +48,7 @@ SKIP: { sleep 1; $res = NPTest->testCmd( "./check_udp -H localhost -p 3333 -s '' -e barbar -4" ); cmp_ok( $res->return_code, '==', 0, "Got barbar response back" ); - like ( $res->output, '/\[barbar\]/', "Output OK"); + like ( $res->output, '/answer of the server matched/', "Output OK"); close NC; # Start up a udp server listening on port 3333, quit after 3 seconds -- cgit v1.2.3-74-g34f1 From 285000a2ad1198046275f5bd5b47227f1cd66471 Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 13 Mar 2025 13:00:05 +0100 Subject: small fixes to check_tcp config --- plugins/check_tcp.d/config.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/check_tcp.d/config.h b/plugins/check_tcp.d/config.h index 41db7224..dc25d79e 100644 --- a/plugins/check_tcp.d/config.h +++ b/plugins/check_tcp.d/config.h @@ -2,6 +2,7 @@ #include "../../lib/utils_tcp.h" #include "output.h" +#include "states.h" #include typedef struct { @@ -15,8 +16,8 @@ typedef struct { char *quit; char **server_expect; size_t server_expect_count; -#ifdef HAVE_SSL bool use_tls; +#ifdef HAVE_SSL char *sni; bool sni_specified; bool check_cert; @@ -24,7 +25,7 @@ typedef struct { int days_till_exp_crit; #endif // HAVE_SSL int match_flags; - int expect_mismatch_state; + mp_state_enum expect_mismatch_state; unsigned int delay; bool warning_time_set; @@ -32,7 +33,7 @@ typedef struct { bool critical_time_set; double critical_time; - int econn_refuse_state; + mp_state_enum econn_refuse_state; ssize_t maxbytes; @@ -54,8 +55,8 @@ check_tcp_config check_tcp_config_init() { .quit = NULL, .server_expect = NULL, .server_expect_count = 0, -#ifdef HAVE_SSL .use_tls = false, +#ifdef HAVE_SSL .sni = NULL, .sni_specified = false, .check_cert = false, -- cgit v1.2.3-74-g34f1 From c61b5ef06a83b5fa2d48b256532f30ec5def3658 Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 13 Mar 2025 13:21:10 +0100 Subject: Update more tests to current output --- plugins/t/check_tcp.t | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/t/check_tcp.t b/plugins/t/check_tcp.t index b47caab3..5c8fd0be 100644 --- a/plugins/t/check_tcp.t +++ b/plugins/t/check_tcp.t @@ -23,7 +23,7 @@ my $internet_access = getTestParameter("NP_INTERNET_ACCESS", "Is this system my $successOutput = '/Connection time\s+[0-9]?\.?[0-9]+s is within thresholds+/'; -my $failedExpect = '/\sUnexpected response from host/socket on port [0-9]+/'; +my $failedExpect = '/Answer failed to match/'; my $t; -- cgit v1.2.3-74-g34f1 From 0111359c72e2fc13049b5c33a7e1449cd0cdf666 Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 13 Mar 2025 14:48:20 +0100 Subject: check_tcp: Actually account for certificate lifetime checks --- plugins/check_tcp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_tcp.c b/plugins/check_tcp.c index d1f6b84f..22dcc74e 100644 --- a/plugins/check_tcp.c +++ b/plugins/check_tcp.c @@ -262,7 +262,7 @@ int main(int argc, char **argv) { if (config.use_tls) { mp_subcheck tls_connection_result = mp_subcheck_init(); mp_state_enum result = np_net_ssl_init_with_hostname(socket_descriptor, (config.sni_specified ? config.sni : NULL)); - tls_connection_result = mp_set_subcheck_state(tls_connection_result, result); + tls_connection_result = mp_set_subcheck_default_state(tls_connection_result, result); if (result == STATE_OK) { xasprintf(&tls_connection_result.output, "TLS connection succeeded"); -- cgit v1.2.3-74-g34f1 From d2596feaa090c73353412d252cfb7938a9141f9b Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 13 Mar 2025 14:59:35 +0100 Subject: Add forgotten Makefile change --- plugins/Makefile.am | 1 + 1 file changed, 1 insertion(+) (limited to 'plugins') diff --git a/plugins/Makefile.am b/plugins/Makefile.am index 9e4924c3..30ca63d1 100644 --- a/plugins/Makefile.am +++ b/plugins/Makefile.am @@ -58,6 +58,7 @@ EXTRA_DIST = t \ check_time.d \ check_nagios.d \ check_dbi.d \ + check_tcp.d \ check_real.d \ check_ssh.d \ check_nt.d \ -- cgit v1.2.3-74-g34f1