From bb16b73130519cf5e93340480c8fd5e7e696a15f Mon Sep 17 00:00:00 2001 From: nafets Date: Mon, 17 Nov 2014 23:00:45 +0100 Subject: added option to exit with an warning, if there is output on STDERR --- plugins/check_by_ssh.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_by_ssh.c b/plugins/check_by_ssh.c index a877f888..bc172c97 100644 --- a/plugins/check_by_ssh.c +++ b/plugins/check_by_ssh.c @@ -49,6 +49,7 @@ unsigned int commands = 0; unsigned int services = 0; int skip_stdout = 0; int skip_stderr = 0; +int warn_on_stderr = 0; char *remotecmd = NULL; char **commargv = NULL; int commargc = 0; @@ -109,7 +110,10 @@ main (int argc, char **argv) if(chld_err.lines > skip_stderr) { printf (_("Remote command execution failed: %s\n"), chld_err.line[skip_stderr]); - return max_state_alt(result, STATE_UNKNOWN); + if ( warn_on_stderr ) + return max_state_alt(result, STATE_WARNING); + else + return max_state_alt(result, STATE_UNKNOWN); } /* this is simple if we're not supposed to be passive. @@ -182,6 +186,7 @@ process_arguments (int argc, char **argv) {"skip", optional_argument, 0, 'S'}, /* backwards compatibility */ {"skip-stdout", optional_argument, 0, 'S'}, {"skip-stderr", optional_argument, 0, 'E'}, + {"warn-on-stderr", no_argument, 0, 'W'}, {"proto1", no_argument, 0, '1'}, {"proto2", no_argument, 0, '2'}, {"use-ipv4", no_argument, 0, '4'}, @@ -301,6 +306,9 @@ process_arguments (int argc, char **argv) else skip_stderr = atoi (optarg); break; + case 'W': /* exit with warning if there is an output on stderr */ + warn_on_stderr = 1; + break; case 'o': /* Extra options for the ssh command */ comm_append("-o"); comm_append(optarg); @@ -408,6 +416,8 @@ print_help (void) printf (" %s\n", _("Ignore all or (if specified) first n lines on STDOUT [optional]")); printf (" %s\n", "-E, --skip-stderr[=n]"); printf (" %s\n", _("Ignore all or (if specified) first n lines on STDERR [optional]")); + printf (" %s\n", "-W, --warn-on-stderr]"); + printf (" %s\n", _("Exit with an warning, if there is an output on STDERR")); printf (" %s\n", "-f"); printf (" %s\n", _("tells ssh to fork rather than create a tty [optional]. This will always return OK if ssh is executed")); printf (" %s\n","-C, --command='COMMAND STRING'"); @@ -460,7 +470,7 @@ print_usage (void) { printf ("%s\n", _("Usage:")); printf (" %s -H -C [-fqv] [-1|-2] [-4|-6]\n" - " [-S [lines]] [-E [lines]] [-t timeout] [-i identity]\n" + " [-S [lines]] [-E [lines]] [-W] [-t timeout] [-i identity]\n" " [-l user] [-n name] [-s servicelist] [-O outputfile]\n" " [-p port] [-o ssh-option] [-F configfile]\n", progname); -- cgit v1.2.3-74-g34f1 From 23436a18516e66469aeb4d81329d62ee4bfa7a51 Mon Sep 17 00:00:00 2001 From: Klaus Ethgen Date: Wed, 28 Oct 2015 00:38:47 +0100 Subject: Fixing the stuff that is broken on btrfs (Closes #1357) --- plugins/check_disk.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/check_disk.c b/plugins/check_disk.c index 874a0ee0..b3386842 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -1038,10 +1038,7 @@ get_stats (struct parameter_list *p, struct fs_usage *fsp) { void get_path_stats (struct parameter_list *p, struct fs_usage *fsp) { - /* 2007-12-08 - Workaround for Gnulib reporting insanely high available - * space on BSD (the actual value should be negative but fsp->fsu_bavail - * is unsigned) */ - p->available = fsp->fsu_bavail > fsp->fsu_bfree ? 0 : fsp->fsu_bavail; + p->available = fsp->fsu_bavail; p->available_to_root = fsp->fsu_bfree; p->used = fsp->fsu_blocks - fsp->fsu_bfree; if (freespace_ignore_reserved) { -- cgit v1.2.3-74-g34f1 From 05ac8a98a85e748643e6f2ab268587e6f78244f6 Mon Sep 17 00:00:00 2001 From: Elan Ruusamäe Date: Thu, 3 Mar 2016 21:31:27 +0200 Subject: understang ping6 output from iputils package --- plugins/check_ping.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) (limited to 'plugins') diff --git a/plugins/check_ping.c b/plugins/check_ping.c index 423ecbe5..36de7cf6 100644 --- a/plugins/check_ping.c +++ b/plugins/check_ping.c @@ -521,12 +521,13 @@ int error_scan (char buf[MAX_INPUT_BUFFER], const char *addr) { if (strstr (buf, "Network is unreachable") || - strstr (buf, "Destination Net Unreachable") + strstr (buf, "Destination Net Unreachable") || + strstr (buf, "No route") ) die (STATE_CRITICAL, _("CRITICAL - Network Unreachable (%s)\n"), addr); - else if (strstr (buf, "Destination Host Unreachable")) + else if (strstr (buf, "Destination Host Unreachable") || strstr(buf, "Address unreachable")) die (STATE_CRITICAL, _("CRITICAL - Host Unreachable (%s)\n"), addr); - else if (strstr (buf, "Destination Port Unreachable")) + else if (strstr (buf, "Destination Port Unreachable") || strstr(buf, "Port unreachable")) die (STATE_CRITICAL, _("CRITICAL - Bogus ICMP: Port Unreachable (%s)\n"), addr); else if (strstr (buf, "Destination Protocol Unreachable")) die (STATE_CRITICAL, _("CRITICAL - Bogus ICMP: Protocol Unreachable (%s)\n"), addr); @@ -534,11 +535,11 @@ error_scan (char buf[MAX_INPUT_BUFFER], const char *addr) die (STATE_CRITICAL, _("CRITICAL - Network Prohibited (%s)\n"), addr); else if (strstr (buf, "Destination Host Prohibited")) die (STATE_CRITICAL, _("CRITICAL - Host Prohibited (%s)\n"), addr); - else if (strstr (buf, "Packet filtered")) + else if (strstr (buf, "Packet filtered") || strstr(buf, "Administratively prohibited")) die (STATE_CRITICAL, _("CRITICAL - Packet Filtered (%s)\n"), addr); else if (strstr (buf, "unknown host" )) die (STATE_CRITICAL, _("CRITICAL - Host not found (%s)\n"), addr); - else if (strstr (buf, "Time to live exceeded")) + else if (strstr (buf, "Time to live exceeded") || strstr(buf, "Time exceeded")) die (STATE_CRITICAL, _("CRITICAL - Time to live exceeded (%s)\n"), addr); else if (strstr (buf, "Destination unreachable: ")) die (STATE_CRITICAL, _("CRITICAL - Destination Unreachable (%s)\n"), addr); -- cgit v1.2.3-74-g34f1 From c85281d25bb4b0fc12a45b2732620f51a10344be Mon Sep 17 00:00:00 2001 From: Gerhard Lausser Date: Tue, 7 Feb 2017 14:15:47 +0100 Subject: check_snmp: put the "c" (to mark a counter) after the perfdata value --- plugins/check_snmp.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_snmp.c b/plugins/check_snmp.c index da9638c4..b5abac18 100644 --- a/plugins/check_snmp.c +++ b/plugins/check_snmp.c @@ -576,6 +576,9 @@ main (int argc, char **argv) len = sizeof(perfstr)-strlen(perfstr)-1; strncat(perfstr, show, len>ptr-show ? ptr-show : len); + if (type) + strncat(perfstr, type, sizeof(perfstr)-strlen(perfstr)-1); + if (warning_thresholds) { strncat(perfstr, ";", sizeof(perfstr)-strlen(perfstr)-1); strncat(perfstr, warning_thresholds, sizeof(perfstr)-strlen(perfstr)-1); @@ -588,8 +591,6 @@ main (int argc, char **argv) strncat(perfstr, critical_thresholds, sizeof(perfstr)-strlen(perfstr)-1); } - if (type) - strncat(perfstr, type, sizeof(perfstr)-strlen(perfstr)-1); strncat(perfstr, " ", sizeof(perfstr)-strlen(perfstr)-1); } } -- cgit v1.2.3-74-g34f1 From 09a2210c477932c8df40ff820414b3a9bbec10fb Mon Sep 17 00:00:00 2001 From: Rasp8e Date: Tue, 17 Oct 2017 15:19:43 +0200 Subject: Adding Proxy-Authorization and extra headers in the case of connection through PROXY to HTTPS --- plugins/check_http.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index 86a36c20..2e393eb2 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -916,6 +916,21 @@ check_http (void) if (verbose) printf ("Entering CONNECT tunnel mode with proxy %s:%d to dst %s:%d\n", server_address, server_port, host_name, HTTPS_PORT); asprintf (&buf, "%s %s:%d HTTP/1.1\r\n%s\r\n", http_method, host_name, HTTPS_PORT, user_agent); + if (strlen(proxy_auth)) { + base64_encode_alloc (proxy_auth, strlen (proxy_auth), &auth); + xasprintf (&buf, "%sProxy-Authorization: Basic %s\r\n", buf, auth); + } + /* optionally send any other header tag */ + if (http_opt_headers_count) { + for (i = 0; i < http_opt_headers_count ; i++) { + if (force_host_header != http_opt_headers[i]) { + xasprintf (&buf, "%s%s\r\n", buf, http_opt_headers[i]); + } + } + /* This cannot be free'd here because a redirection will then try to access this and segfault */ + /* Covered in a testcase in tests/check_http.t */ + /* free(http_opt_headers); */ + } asprintf (&buf, "%sProxy-Connection: keep-alive\r\n", buf); asprintf (&buf, "%sHost: %s\r\n", buf, host_name); /* we finished our request, send empty line with CRLF */ -- cgit v1.2.3-74-g34f1 From 22c00bbe47d2bed5e77ad1d494502c4697a86abb Mon Sep 17 00:00:00 2001 From: Stefan Bethke Date: Wed, 10 Oct 2018 00:40:07 +0200 Subject: Docs check_http: make -C obvious You need to read the docs carefully to realize that check_http has two modes of operation: the regular HTTP checks, and a TLS certificate check. Only one of these can be run in a single invocation. Fixes #1553 --- plugins/check_http.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index 86a36c20..d540bf7d 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -1532,6 +1532,10 @@ print_help (void) print_usage (); +#ifdef HAVE_SSL + printf (_("In the first form, make an HTTP request.")); + printf (_("In the second form, connect to the server and check the TLS certificate.")); +#endif printf (_("NOTE: One or both of -H and -I must be specified")); printf ("\n"); @@ -1688,6 +1692,8 @@ print_usage (void) printf (" [-b proxy_auth] [-f ]\n"); printf (" [-e ] [-d string] [-s string] [-l] [-r | -R ]\n"); printf (" [-P string] [-m :] [-4|-6] [-N] [-M ]\n"); - printf (" [-A string] [-k string] [-S ] [--sni] [-C [,]]\n"); + printf (" [-A string] [-k string] [-S ] [--sni]\n"); printf (" [-T ] [-j method]\n"); + printf (" %s -H | -I -C [,]\n",progname); + printf (" [-p ] [-t ] [-4|-6] [--sni]\n"); } -- cgit v1.2.3-74-g34f1 From 0a58acc7052d4962d8fe68aeb6919b59dfdef1cf Mon Sep 17 00:00:00 2001 From: Tomas Mozes Date: Wed, 5 Dec 2018 12:50:53 +0100 Subject: plugins: check_http: Increase regexp limit --- plugins/check_http.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index 856e1e90..a25f1ec0 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -72,7 +72,7 @@ int maximum_age = -1; enum { REGS = 2, - MAX_RE_SIZE = 256 + MAX_RE_SIZE = 1024 }; #include "regex.h" regex_t preg; -- cgit v1.2.3-74-g34f1 From 11af74de386ba7c02d5d0e53f2500b5029a4537d Mon Sep 17 00:00:00 2001 From: mdavranche Date: Tue, 18 Aug 2020 15:37:38 -0400 Subject: check_swap: Handle cached swap --- plugins/check_swap.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_swap.c b/plugins/check_swap.c index 0ff0c770..ce3f1d7f 100644 --- a/plugins/check_swap.c +++ b/plugins/check_swap.c @@ -133,7 +133,7 @@ main (int argc, char **argv) xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent); } } - else if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%[TotalFre]%*[:] %f %*[k]%*[B]", str, &tmp_mb)) { + else if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%[TotalFreCchd]%*[:] %f %*[k]%*[B]", str, &tmp_mb)) { if (verbose >= 3) { printf("Got %s with %f\n", str, tmp_mb); } @@ -142,7 +142,10 @@ main (int argc, char **argv) dsktotal_mb = tmp_mb / 1024; } else if (strcmp ("Free", str) == 0) { - dskfree_mb = tmp_mb / 1024; + dskfree_mb = dskfree_mb + tmp_mb / 1024; + } + else if (strcmp ("Cached", str) == 0) { + dskfree_mb = dskfree_mb + tmp_mb / 1024; } } } -- cgit v1.2.3-74-g34f1 From b8b87b55d61aceff03107b0335347257f429e9ad Mon Sep 17 00:00:00 2001 From: ghciv6 Date: Tue, 15 Sep 2020 21:36:27 +0200 Subject: - fix for issue #1562 1st compare then free up resources --- plugins/check_mysql_query.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'plugins') diff --git a/plugins/check_mysql_query.c b/plugins/check_mysql_query.c index 49a14dd3..ac2fb15d 100644 --- a/plugins/check_mysql_query.c +++ b/plugins/check_mysql_query.c @@ -136,18 +136,18 @@ main (int argc, char **argv) die (STATE_CRITICAL, "QUERY %s: Fetch row error - %s\n", _("CRITICAL"), error); } - /* free the result */ - mysql_free_result (res); - - /* close the connection */ - mysql_close (&mysql); - if (! is_numeric(row[0])) { die (STATE_CRITICAL, "QUERY %s: %s - '%s'\n", _("CRITICAL"), _("Is not a numeric"), row[0]); } value = strtod(row[0], NULL); + /* free the result */ + mysql_free_result (res); + + /* close the connection */ + mysql_close (&mysql); + if (verbose >= 3) printf("mysql result: %f\n", value); -- cgit v1.2.3-74-g34f1 From ad99755033f33a301abc1815d746644067bc297a Mon Sep 17 00:00:00 2001 From: Rolf Eike Beer Date: Mon, 2 Nov 2020 20:05:56 +0100 Subject: check_dns: split multiple IP addresses passed in one -a argument --- plugins/check_dns.c | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) (limited to 'plugins') diff --git a/plugins/check_dns.c b/plugins/check_dns.c index b90f50e6..0f2e6541 100644 --- a/plugins/check_dns.c +++ b/plugins/check_dns.c @@ -473,9 +473,23 @@ process_arguments (int argc, char **argv) case 'a': /* expected address */ if (strlen (optarg) >= ADDRESS_LENGTH) die (STATE_UNKNOWN, _("Input buffer overflow\n")); - expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**)); - expected_address[expected_address_cnt] = strdup(optarg); - expected_address_cnt++; + if (strchr(optarg, ',') != NULL) { + char *comma = strchr(optarg, ','); + while (comma != NULL) { + expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**)); + expected_address[expected_address_cnt] = strndup(optarg, comma - optarg); + expected_address_cnt++; + optarg = comma + 1; + comma = strchr(optarg, ','); + } + expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**)); + expected_address[expected_address_cnt] = strdup(optarg); + expected_address_cnt++; + } else { + expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**)); + expected_address[expected_address_cnt] = strdup(optarg); + expected_address_cnt++; + } break; case 'A': /* expect authority */ expect_authority = TRUE; -- cgit v1.2.3-74-g34f1 From 8eaccee190734a12763a51aaa8a46f324f6742ec Mon Sep 17 00:00:00 2001 From: Wolfgang Karall-Ahlborn Date: Sun, 3 Jan 2021 11:27:44 +0100 Subject: check_procs -- exchange needle and haystack in strstr() for proper state match --- plugins/check_procs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_procs.c b/plugins/check_procs.c index f7917c34..0de6be93 100644 --- a/plugins/check_procs.c +++ b/plugins/check_procs.c @@ -265,7 +265,7 @@ main (int argc, char **argv) } } - if ((options & STAT) && (strstr (statopts, procstat))) + if ((options & STAT) && (strstr (procstat, statopts))) resultsum |= STAT; if ((options & ARGS) && procargs && (strstr (procargs, args) != NULL)) resultsum |= ARGS; -- cgit v1.2.3-74-g34f1 From 9076ea36f70dbd643de4102a88dbd2f18847af16 Mon Sep 17 00:00:00 2001 From: Wolfgang Karall-Ahlborn Date: Sun, 3 Jan 2021 12:18:31 +0100 Subject: check_procs -- update test data too --- plugins/tests/check_procs.t | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/tests/check_procs.t b/plugins/tests/check_procs.t index 54d43d9b..6d710159 100755 --- a/plugins/tests/check_procs.t +++ b/plugins/tests/check_procs.t @@ -83,7 +83,7 @@ is( $result->output, 'PROCS OK: 3 processes with RSS >= 100000 | procs=3;;;0;', $result = NPTest->testCmd( "$command -s S" ); is( $result->return_code, 0, "Checking filter for sleeping processes" ); -like( $result->output, '/^PROCS OK: 44 processes with STATE = S/', "Output correct" ); +like( $result->output, '/^PROCS OK: 88 processes with STATE = S/', "Output correct" ); $result = NPTest->testCmd( "$command -s Z" ); is( $result->return_code, 0, "Checking filter for zombies" ); -- cgit v1.2.3-74-g34f1 From ede8defad4f44478f69e148022b542a694498087 Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Tue, 19 Jan 2021 18:32:27 +0100 Subject: check_curl: fixed help, usage and errors for TLS 1.3 --- plugins/check_curl.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 2d69b310..ef77918b 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -1354,7 +1354,7 @@ process_arguments (int argc, char **argv) ssl_version = CURL_SSLVERSION_DEFAULT; #endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0) */ else - usage4 (_("Invalid option - Valid SSL/TLS versions: 2, 3, 1, 1.1, 1.2 (with optional '+' suffix)")); + usage4 (_("Invalid option - Valid SSL/TLS versions: 2, 3, 1, 1.1, 1.2, 1.3 (with optional '+' suffix)")); } #if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0) if (got_plus) { @@ -1659,7 +1659,7 @@ print_help (void) printf (" %s\n", "-S, --ssl=VERSION[+]"); printf (" %s\n", _("Connect via SSL. Port defaults to 443. VERSION is optional, and prevents")); printf (" %s\n", _("auto-negotiation (2 = SSLv2, 3 = SSLv3, 1 = TLSv1, 1.1 = TLSv1.1,")); - printf (" %s\n", _("1.2 = TLSv1.2). With a '+' suffix, newer versions are also accepted.")); + printf (" %s\n", _("1.2 = TLSv1.2, 1.3 = TLSv1.3). With a '+' suffix, newer versions are also accepted.")); printf (" %s\n", _("Note: SSLv2 and SSLv3 are deprecated and are usually disabled in libcurl")); printf (" %s\n", "--sni"); printf (" %s\n", _("Enable SSL/TLS hostname extension support (SNI)")); -- cgit v1.2.3-74-g34f1 From d9a5d1faf0400b9da47dee516c035da1a93dc12c Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Tue, 19 Jan 2021 18:35:41 +0100 Subject: check_curl: fixed a potential buffer overflow in url buffer --- plugins/check_curl.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index ef77918b..a3f63f16 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -1041,7 +1041,7 @@ redir (curlhelp_write_curlbuf* header_buf) const UriPathSegmentA* p = uri.pathHead; for (; p; p = p->next) { strncat (new_url, "/", DEFAULT_BUFFER_SIZE); - strncat (new_url, uri_string (p->text, buf, DEFAULT_BUFFER_SIZE), DEFAULT_BUFFER_SIZE); + strncat (new_url, uri_string (p->text, buf, DEFAULT_BUFFER_SIZE), DEFAULT_BUFFER_SIZE-1); } } -- cgit v1.2.3-74-g34f1 From dae075e65a38c65352d04f8c8fdfa21e2056d01c Mon Sep 17 00:00:00 2001 From: Florian Lohoff Date: Mon, 15 Feb 2021 15:34:07 +0100 Subject: Using snprintf which honors the buffers size and guarantees null termination. (Closes: #1601) As strcpy may overflow the resulting buffer: flo@p5:~$ /tmp/f/usr/lib/nagios/plugins/check_pgsql -d "$(seq 1 10000)" *** buffer overflow detected ***: terminated Aborted I would propose to change the code rather like this, using snprintf which honors the buffers size and guarantees null termination. --- plugins/check_pgsql.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_pgsql.c b/plugins/check_pgsql.c index 11ce6916..b8fc5f1d 100644 --- a/plugins/check_pgsql.c +++ b/plugins/check_pgsql.c @@ -347,7 +347,7 @@ process_arguments (int argc, char **argv) if (!is_pg_dbname (optarg)) /* checks length and valid chars */ usage2 (_("Database name is not valid"), optarg); else /* we know length, and know optarg is terminated, so us strcpy */ - strcpy (dbName, optarg); + snprintf(dbName, NAMEDATALEN, "%s", optarg); break; case 'l': /* login name */ if (!is_pg_logname (optarg)) -- cgit v1.2.3-74-g34f1 From 0f926a3566fb6f3333f3a24e47e2ad204fd0fba4 Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Mon, 8 Mar 2021 19:46:43 +0100 Subject: check_curl: added string_statuscode function for printing HTTP/1.1 and HTTP/2 correctly --- plugins/check_curl.c | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index a3f63f16..8f274c26 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -296,6 +296,28 @@ CURLcode sslctxfun(CURL *curl, SSL_CTX *sslctx, void *parm) #endif /* USE_OPENSSL */ #endif /* HAVE_SSL */ +/* returns a string "HTTP/1.x" or "HTTP/2" */ +static char *string_statuscode (int major, int minor) +{ + static char buf[10]; + + switch (major) { + case 1: + snprintf (buf, sizeof (buf), "HTTP/%d.%d", major, minor); + break; + case 2: + case 3: + snprintf (buf, sizeof (buf), "HTTP/%d", major); + break; + default: + /* assuming here HTTP/N with N>=4 */ + snprintf (buf, sizeof (buf), "HTTP/%d", major); + break; + } + + return buf; +} + /* Checks if the server 'reply' is one of the expected 'statuscodes' */ static int expected_statuscode (const char *reply, const char *statuscodes) @@ -746,7 +768,8 @@ GOT_FIRST_CERT: if (curlhelp_parse_statusline (header_buf.buf, &status_line) < 0) { snprintf (msg, DEFAULT_BUFFER_SIZE, "Unparsable status line in %.3g seconds response time|%s\n", total_time, perfstring); - die (STATE_CRITICAL, "HTTP CRITICAL HTTP/1.x %ld unknown - %s", code, msg); + /* we cannot know the major/minor version here for sure as we cannot parse the first line */ + die (STATE_CRITICAL, "HTTP CRITICAL HTTP/x.x %ld unknown - %s", code, msg); } /* get result code from cURL */ @@ -823,8 +846,8 @@ GOT_FIRST_CERT: /* check status codes, set exit status accordingly */ if( status_line.http_code != code ) { - die (STATE_CRITICAL, _("HTTP CRITICAL HTTP/%d.%d %d %s - different HTTP codes (cUrl has %ld)\n"), - status_line.http_major, status_line.http_minor, + die (STATE_CRITICAL, _("HTTP CRITICAL %s %d %s - different HTTP codes (cUrl has %ld)\n"), + string_statuscode (status_line.http_major, status_line.http_minor), status_line.http_code, status_line.msg, code); } @@ -895,8 +918,8 @@ GOT_FIRST_CERT: msg[strlen(msg)-3] = '\0'; /* TODO: separate _() msg and status code: die (result, "HTTP %s: %s\n", state_text(result), msg); */ - die (result, "HTTP %s: HTTP/%d.%d %d %s%s%s - %d bytes in %.3f second response time %s|%s\n", - state_text(result), status_line.http_major, status_line.http_minor, + die (result, "HTTP %s: %s %d %s%s%s - %d bytes in %.3f second response time %s|%s\n", + state_text(result), string_statuscode (status_line.http_major, status_line.http_minor), status_line.http_code, status_line.msg, strlen(msg) > 0 ? " - " : "", msg, page_len, total_time, -- cgit v1.2.3-74-g34f1 From 5cfc93d995cfd5cc7d1a469f3c1276c4884da2a2 Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Thu, 11 Mar 2021 13:33:16 +0100 Subject: fix check_curl crash if http header contains leading spaces check_curl crashes when a (broken) http server returns invalid http header with leading spaces or double colons. This PR adds a fix and a test case for this. Signed-off-by: Sven Nierlein --- plugins/check_curl.c | 2 +- plugins/tests/check_curl.t | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 2d69b310..ef96218c 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -2037,7 +2037,7 @@ get_header_value (const struct phr_header* headers, const size_t nof_headers, co { int i; for( i = 0; i < nof_headers; i++ ) { - if( strncasecmp( header, headers[i].name, max( headers[i].name_len, 4 ) ) == 0 ) { + if(headers[i].name != NULL && strncasecmp( header, headers[i].name, max( headers[i].name_len, 4 ) ) == 0 ) { return strndup( headers[i].value, headers[i].value_len ); } } diff --git a/plugins/tests/check_curl.t b/plugins/tests/check_curl.t index 1afbe4bb..0caad23d 100755 --- a/plugins/tests/check_curl.t +++ b/plugins/tests/check_curl.t @@ -21,7 +21,7 @@ use FindBin qw($Bin); $ENV{'LC_TIME'} = "C"; -my $common_tests = 70; +my $common_tests = 72; my $ssl_only_tests = 8; # Check that all dependent modules are available eval "use HTTP::Daemon 6.01;"; @@ -188,6 +188,12 @@ sub run_server { $c->send_basic_header; $c->send_header('foo'); $c->send_crlf; + } elsif ($r->url->path eq "/header_broken_check") { + $c->send_basic_header; + $c->send_header('foo'); + print $c "Test1:: broken\n"; + print $c " Test2: leading whitespace\n"; + $c->send_crlf; } elsif ($r->url->path eq "/virtual_port") { # return sent Host header $c->send_basic_header; @@ -247,7 +253,7 @@ my $cmd; # advanced checks with virtual hostname and virtual port SKIP: { skip "libcurl version is smaller than $required_version", 6 unless $use_advanced_checks; - + # http without virtual port $cmd = "./$plugin -H $virtual_host -I 127.0.0.1 -p $port_http -u /virtual_port -r ^$virtual_host:$port_http\$"; $result = NPTest->testCmd( $cmd ); @@ -259,7 +265,7 @@ SKIP: { $result = NPTest->testCmd( $cmd ); is( $result->return_code, 0, $cmd); like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); - + # http with virtual port (80) $cmd = "./$plugin -H $virtual_host:80 -I 127.0.0.1 -p $port_http -u /virtual_port -r ^$virtual_host\$"; $result = NPTest->testCmd( $cmd ); @@ -321,6 +327,10 @@ sub run_common_tests { is( $result->return_code, 2, "Missing header string check"); like( $result->output, qr%^HTTP CRITICAL: HTTP/1\.1 200 OK - header 'bar' not found on 'https?://127\.0\.0\.1:\d+/header_check'%, "Shows search string and location"); + $result = NPTest->testCmd( "$command -u /header_broken_check" ); + is( $result->return_code, 0, "header_check search for string"); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - 138 bytes in [\d\.]+ second/', "Output correct" ); + my $cmd; $cmd = "$command -u /slow"; $result = NPTest->testCmd( $cmd ); -- cgit v1.2.3-74-g34f1 From 2482950e267a752b37d696c10ea091dc62d6d8a7 Mon Sep 17 00:00:00 2001 From: Barak Shohat Date: Tue, 6 Apr 2021 16:35:20 +0300 Subject: Updated check_curl.c to display a specific human-readable error message where possible --- plugins/check_curl.c | 6 +++--- plugins/t/check_curl.t | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 8f274c26..8cb2ff49 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -313,8 +313,8 @@ static char *string_statuscode (int major, int minor) /* assuming here HTTP/N with N>=4 */ snprintf (buf, sizeof (buf), "HTTP/%d", major); break; - } - + } + return buf; } @@ -662,7 +662,7 @@ check_http (void) /* Curl errors, result in critical Nagios state */ if (res != CURLE_OK) { snprintf (msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host on port %d: cURL returned %d - %s"), - server_port, res, curl_easy_strerror(res)); + server_port, res, errbuf[0] ? errbuf : curl_easy_strerror(res)); die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); } diff --git a/plugins/t/check_curl.t b/plugins/t/check_curl.t index 4bff538a..cc65f037 100644 --- a/plugins/t/check_curl.t +++ b/plugins/t/check_curl.t @@ -46,7 +46,7 @@ $res = NPTest->testCmd( ); cmp_ok( $res->return_code, '==', 2, "Webserver $host_nonresponsive not responding" ); # was CRITICAL only, but both check_curl and check_http print HTTP CRITICAL (puzzle?!) -cmp_ok( $res->output, 'eq', "HTTP CRITICAL - Invalid HTTP response received from host on port 80: cURL returned 28 - Timeout was reached", "Output OK"); +like( $res->output, "/HTTP CRITICAL - Invalid HTTP response received from host on port 80: cURL returned 28 - Connection timed out after/", "Output OK"); $res = NPTest->testCmd( "./$plugin $hostname_invalid -wt 1 -ct 2" @@ -56,7 +56,7 @@ cmp_ok( $res->return_code, '==', 2, "Webserver $hostname_invalid not valid" ); # On Debian, it is Name or service not known, on Darwin, it is No address associated with nodename # Is also possible to get a socket timeout if DNS is not responding fast enough # cURL gives us consistent strings from it's own 'lib/strerror.c' -like( $res->output, "/cURL returned 6 - Couldn't resolve host name/", "Output OK"); +like( $res->output, "/cURL returned 6 - Could not resolve host:/", "Output OK"); # host header checks $res = NPTest->testCmd("./$plugin -v -H $host_tcp_http"); -- cgit v1.2.3-74-g34f1 From 6993c216955a54845d98dc568534613334c0b545 Mon Sep 17 00:00:00 2001 From: Barak Shohat Date: Wed, 7 Apr 2021 12:34:46 +0300 Subject: Add an option to check_curl to verify the peer certificate & host using the system CA's --- plugins/check_curl.c | 17 ++++++++++++++--- plugins/t/check_curl.t | 5 ++++- 2 files changed, 18 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 8f274c26..19f80b74 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -195,6 +195,7 @@ int ssl_version = CURL_SSLVERSION_DEFAULT; char *client_cert = NULL; char *client_privkey = NULL; char *ca_cert = NULL; +int verify_peer_and_host = FALSE; int is_openssl_callback = FALSE; #if defined(HAVE_SSL) && defined(USE_OPENSSL) X509 *cert = NULL; @@ -489,9 +490,11 @@ check_http (void) if (client_privkey) handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLKEY, client_privkey), "CURLOPT_SSLKEY"); if (ca_cert) { + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CAINFO, ca_cert), "CURLOPT_CAINFO"); + } + if (ca_cert || verify_peer_and_host) { /* per default if we have a CA verify both the peer and the * hostname in the certificate, can be switched off later */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CAINFO, ca_cert), "CURLOPT_CAINFO"); handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_SSL_VERIFYPEER, 1), "CURLOPT_SSL_VERIFYPEER"); handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_SSL_VERIFYHOST, 2), "CURLOPT_SSL_VERIFYHOST"); } else { @@ -1159,6 +1162,7 @@ process_arguments (int argc, char **argv) {"client-cert", required_argument, 0, 'J'}, {"private-key", required_argument, 0, 'K'}, {"ca-cert", required_argument, 0, CA_CERT_OPTION}, + {"verify-cert", no_argument, 0, 'D'}, {"useragent", required_argument, 0, 'A'}, {"header", required_argument, 0, 'k'}, {"no-body", no_argument, 0, 'N'}, @@ -1193,7 +1197,7 @@ process_arguments (int argc, char **argv) server_url = strdup(DEFAULT_SERVER_URL); while (1) { - c = getopt_long (argc, argv, "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:d:e:p:s:R:r:u:f:C:J:K:nlLS::m:M:NE", longopts, &option); + c = getopt_long (argc, argv, "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:d:e:p:s:R:r:u:f:C:J:K:DnlLS::m:M:NE", longopts, &option); if (c == -1 || c == EOF || c == 1) break; @@ -1332,6 +1336,11 @@ process_arguments (int argc, char **argv) test_file(optarg); ca_cert = optarg; goto enable_ssl; +#endif +#ifdef LIBCURL_FEATURE_SSL + case 'D': /* verify peer certificate & host */ + verify_peer_and_host = TRUE; + goto enable_ssl; #endif case 'S': /* use SSL */ #ifdef LIBCURL_FEATURE_SSL @@ -1703,6 +1712,8 @@ print_help (void) printf (" %s\n", _("matching the client certificate")); printf (" %s\n", "--ca-cert=FILE"); printf (" %s\n", _("CA certificate file to verify peer against")); + printf (" %s\n", "-D, --verify-cert"); + printf (" %s\n", _("Verify the peer's SSL certificate and hostname")); #endif printf (" %s\n", "-e, --expect=STRING"); @@ -1836,7 +1847,7 @@ print_usage (void) { printf ("%s\n", _("Usage:")); printf (" %s -H | -I [-u ] [-p ]\n",progname); - printf (" [-J ] [-K ] [--ca-cert ]\n"); + printf (" [-J ] [-K ] [--ca-cert ] [-D]\n"); printf (" [-w ] [-c ] [-t ] [-L] [-E] [-a auth]\n"); printf (" [-b proxy_auth] [-f ]\n"); printf (" [-e ] [-d string] [-s string] [-l] [-r | -R ]\n"); diff --git a/plugins/t/check_curl.t b/plugins/t/check_curl.t index 4bff538a..55577add 100644 --- a/plugins/t/check_curl.t +++ b/plugins/t/check_curl.t @@ -9,7 +9,7 @@ use Test::More; use POSIX qw/mktime strftime/; use NPTest; -plan tests => 57; +plan tests => 58; my $successOutput = '/OK.*HTTP.*second/'; @@ -94,6 +94,9 @@ SKIP: { $res = NPTest->testCmd("./$plugin -v -H $host_tls_http:443 -S -p 443"); like( $res->output, '/^Host: '.$host_tls_http.'\s*$/ms', "Host Header OK" ); + + $res = NPTest->testCmd("./$plugin -v -H $host_tls_http -D -p 443"); + like( $res->output, '/(^Host: '.$host_tls_http.'\s*$)|(cURL returned 60)/ms', "Host Header OK" ); }; SKIP: { -- cgit v1.2.3-74-g34f1 From f90aec83cb20263401ab620d07e4914355d9681d Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Thu, 8 Apr 2021 14:07:20 +0200 Subject: check_curl: Increase regexp limit (to 1024 as in check_http) --- plugins/check_curl.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 8125ee84..f900f160 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -117,7 +117,7 @@ typedef enum curlhelp_ssl_library { enum { REGS = 2, - MAX_RE_SIZE = 256 + MAX_RE_SIZE = 1024 }; #include "regex.h" regex_t preg; -- cgit v1.2.3-74-g34f1 From a6acea7941a2a5519ab49d13b5adf946a50b5ea5 Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Thu, 8 Apr 2021 14:15:54 +0200 Subject: check_curl: make -C obvious (from check_http) --- plugins/check_curl.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index f900f160..892300ae 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -1852,9 +1852,11 @@ print_usage (void) printf (" [-b proxy_auth] [-f ]\n"); printf (" [-e ] [-d string] [-s string] [-l] [-r | -R ]\n"); printf (" [-P string] [-m :] [-4|-6] [-N] [-M ]\n"); - printf (" [-A string] [-k string] [-S ] [--sni] [-C [,]]\n"); + printf (" [-A string] [-k string] [-S ] [--sni]\n"); printf (" [-T ] [-j method]\n"); printf (" [--http-version=]\n"); + printf (" %s -H | -I -C [,]\n",progname); + printf (" [-p ] [-t ] [-4|-6] [--sni]\n"); printf ("\n"); printf ("%s\n", _("WARNING: check_curl is experimental. Please use")); printf ("%s\n\n", _("check_http if you need a stable version.")); -- cgit v1.2.3-74-g34f1 From 1debd29b573f4d81eeba4d7f78f797c348b231ce Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Thu, 8 Apr 2021 15:14:53 +0200 Subject: check_curl: make -C obvious (from check_http, part 2) --- plugins/check_curl.c | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 892300ae..8fc97f40 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -1858,6 +1858,10 @@ print_usage (void) printf (" %s -H | -I -C [,]\n",progname); printf (" [-p ] [-t ] [-4|-6] [--sni]\n"); printf ("\n"); +#ifdef LIBCURL_FEATURE_SSL + printf ("%s\n", _("In the first form, make an HTTP request.")); + printf ("%s\n\n", _("In the second form, connect to the server and check the TLS certificate.")); +#endif printf ("%s\n", _("WARNING: check_curl is experimental. Please use")); printf ("%s\n\n", _("check_http if you need a stable version.")); } -- cgit v1.2.3-74-g34f1 From cd358cd08a6ddceece836788078ec96b5f8eb0c5 Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Thu, 8 Apr 2021 20:39:48 +0200 Subject: check_curl: backported --show-body/-B to print body (from check_http) --- plugins/check_curl.c | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 8fc97f40..99833f6f 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -145,6 +145,7 @@ thresholds *thlds; char user_agent[DEFAULT_BUFFER_SIZE]; int verbose = 0; int show_extended_perfdata = FALSE; +int show_body = FALSE; int min_page_len = 0; int max_page_len = 0; int redir_depth = 0; @@ -792,7 +793,9 @@ GOT_FIRST_CERT: snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host: %s\n"), status_line.first_line); else snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host on port %d: %s\n"), server_port, status_line.first_line); - die (STATE_CRITICAL, "HTTP CRITICAL - %s", msg); + die (STATE_CRITICAL, "HTTP CRITICAL - %s%s%s", msg, + show_body ? "\n" : "", + show_body ? body_buf.buf : ""); } if( server_expect_yn ) { @@ -921,13 +924,15 @@ GOT_FIRST_CERT: msg[strlen(msg)-3] = '\0'; /* TODO: separate _() msg and status code: die (result, "HTTP %s: %s\n", state_text(result), msg); */ - die (result, "HTTP %s: %s %d %s%s%s - %d bytes in %.3f second response time %s|%s\n", + die (result, "HTTP %s: %s %d %s%s%s - %d bytes in %.3f second response time %s|%s\n%s%s", state_text(result), string_statuscode (status_line.http_major, status_line.http_minor), status_line.http_code, status_line.msg, strlen(msg) > 0 ? " - " : "", msg, page_len, total_time, (display_html ? "" : ""), - perfstring); + perfstring, + (show_body ? body_buf.buf : ""), + (show_body ? "\n" : "") ); /* proper cleanup after die? */ curlhelp_free_statusline(&status_line); @@ -1173,6 +1178,7 @@ process_arguments (int argc, char **argv) {"use-ipv4", no_argument, 0, '4'}, {"use-ipv6", no_argument, 0, '6'}, {"extended-perfdata", no_argument, 0, 'E'}, + {"show-body", no_argument, 0, 'B'}, {"http-version", required_argument, 0, HTTP_VERSION_OPTION}, {0, 0, 0, 0} }; @@ -1197,7 +1203,7 @@ process_arguments (int argc, char **argv) server_url = strdup(DEFAULT_SERVER_URL); while (1) { - c = getopt_long (argc, argv, "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:d:e:p:s:R:r:u:f:C:J:K:DnlLS::m:M:NE", longopts, &option); + c = getopt_long (argc, argv, "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:d:e:p:s:R:r:u:f:C:J:K:DnlLS::m:M:NEB", longopts, &option); if (c == -1 || c == EOF || c == 1) break; @@ -1545,6 +1551,9 @@ process_arguments (int argc, char **argv) case 'E': /* show extended perfdata */ show_extended_perfdata = TRUE; break; + case 'B': /* print body content after status line */ + show_body = TRUE; + break; case HTTP_VERSION_OPTION: curl_http_version = CURL_HTTP_VERSION_NONE; if (strcmp (optarg, "1.0") == 0) { @@ -1757,6 +1766,8 @@ print_help (void) printf (" %s\n", _("Any other tags to be sent in http header. Use multiple times for additional headers")); printf (" %s\n", "-E, --extended-perfdata"); printf (" %s\n", _("Print additional performance data")); + printf (" %s\n", "-B, --show-body"); + printf (" %s\n", _("Print body content below status line")); printf (" %s\n", "-L, --link"); printf (" %s\n", _("Wrap output in HTML link (obsoleted by urlize)")); printf (" %s\n", "-f, --onredirect="); -- cgit v1.2.3-74-g34f1 From f0ac7fcc7c40fab04c00fbbc8c091e89e77b0f74 Mon Sep 17 00:00:00 2001 From: Barak Shohat Date: Mon, 12 Apr 2021 19:06:27 +0300 Subject: check_curl: Fix bug where headers beginning with HTTP_ cause the status line parsing to fail. --- plugins/check_curl.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 99833f6f..3e0a6f94 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -1995,7 +1995,7 @@ curlhelp_parse_statusline (const char *buf, curlhelp_statusline *status_line) char *first_line_buf; /* find last start of a new header */ - start = strrstr2 (buf, "\r\nHTTP"); + start = strrstr2 (buf, "\r\nHTTP/"); if (start != NULL) { start += 2; buf = start; -- cgit v1.2.3-74-g34f1 From 444a3579b2168eda949943a060bddff9ec95fd99 Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Mon, 12 Apr 2021 17:21:47 +0200 Subject: fix fping test in case of dns errors, fping returns an unknown and thats ok. --- plugins/t/check_fping.t | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) (limited to 'plugins') diff --git a/plugins/t/check_fping.t b/plugins/t/check_fping.t index 342b0a7e..03a6110e 100644 --- a/plugins/t/check_fping.t +++ b/plugins/t/check_fping.t @@ -12,9 +12,6 @@ use vars qw($tests); BEGIN {$tests = 4; plan tests => $tests} -my $successOutput = '/^FPING OK - /'; -my $failureOutput = '/^FPING CRITICAL - /'; - my $host_responsive = getTestParameter("NP_HOST_RESPONSIVE", "The hostname of system responsive to network requests", "localhost"); 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"); @@ -29,9 +26,9 @@ if( ! -x "./check_fping") { elsif ( $> != 0 && (!$fping || ! -u $fping)) { $t += skipMsg( "./check_fping", $tests ); } else { - $t += checkCmd( "./check_fping $host_responsive", 0, $successOutput ); - $t += checkCmd( "./check_fping $host_nonresponsive", [ 1, 2 ] ); - $t += checkCmd( "./check_fping $hostname_invalid", [ 1, 2 ] ); + $t += checkCmd( "./check_fping $host_responsive", 0, '/^FPING OK - /' ); + $t += checkCmd( "./check_fping $host_nonresponsive", 2, '/^FPING CRITICAL - /' ); + $t += checkCmd( "./check_fping $hostname_invalid", 3, '/^FPING UNKNOWN - /' ); } exit(0) if defined($Test::Harness::VERSION); -- cgit v1.2.3-74-g34f1 From fc71e3f9304ed51f3fd7ca544f38a30a590c8ba5 Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Tue, 13 Apr 2021 09:15:12 +0200 Subject: migrate travis ci to github actions --- .github/NPTest.cache | 54 +++++++++++++++++++++++ .github/prepare_debian.sh | 99 +++++++++++++++++++++++++++++++++++++++++++ .github/workflows/test.yml | 77 +++++++++++++++++++++++++++++++++ .travis.yml | 98 ------------------------------------------ plugins/t/NPTest.cache.travis | 54 ----------------------- 5 files changed, 230 insertions(+), 152 deletions(-) create mode 100644 .github/NPTest.cache create mode 100755 .github/prepare_debian.sh create mode 100644 .github/workflows/test.yml delete mode 100644 .travis.yml delete mode 100644 plugins/t/NPTest.cache.travis (limited to 'plugins') diff --git a/.github/NPTest.cache b/.github/NPTest.cache new file mode 100644 index 00000000..232305a7 --- /dev/null +++ b/.github/NPTest.cache @@ -0,0 +1,54 @@ +{ + 'NP_ALLOW_SUDO' => 'yes', + 'NP_DNS_SERVER' => '8.8.8.8', + 'NP_GOOD_NTP_SERVICE' => '', + 'NP_HOST_DHCP_RESPONSIVE' => '', + 'NP_HOST_HPJD_PORT_INVALID' => '161', + 'NP_HOST_HPJD_PORT_VALID' => '', + 'NP_HOSTNAME_INVALID_CIDR' => '130.133.8.39/30', + 'NP_HOSTNAME_INVALID' => 'nosuchhost', + 'NP_HOSTNAME_VALID_CIDR' => '130.133.8.41/30', + 'NP_HOSTNAME_VALID_IP' => '130.133.8.40', + 'NP_HOSTNAME_VALID' => 'monitoring-plugins.org', + 'NP_HOSTNAME_VALID_REVERSE' => 'orwell.monitoring-plugins.org.', + 'NP_HOST_NONRESPONSIVE' => '192.168.1.2', + 'NP_HOST_RESPONSIVE' => 'localhost', + 'NP_HOST_SMB' => '', + 'NP_HOST_SNMP' => '', + 'NP_HOST_TCP_FTP' => '', + 'NP_HOST_TCP_HPJD' => '', + 'NP_HOST_TCP_HTTP2' => 'test.monitoring-plugins.org', + 'NP_HOST_TCP_HTTP' => 'localhost', + 'NP_HOST_TCP_IMAP' => 'imap.web.de', + 'NP_HOST_TCP_JABBER' => 'jabber.org', + 'NP_HOST_TCP_LDAP' => 'localhost', + 'NP_HOST_TCP_POP' => 'pop.web.de', + 'NP_HOST_TCP_PROXY' => 'localhost', + 'NP_HOST_TCP_SMTP' => 'localhost', + 'NP_HOST_TCP_SMTP_NOTLS' => '', + 'NP_HOST_TCP_SMTP_TLS' => '', + 'NP_HOST_TLS_CERT' => 'localhost', + 'NP_HOST_TLS_HTTP' => 'localhost', + 'NP_HOST_UDP_TIME' => 'none', + 'NP_INTERNET_ACCESS' => 'yes', + 'NP_LDAP_BASE_DN' => 'dc=nodomain', + 'NP_MOUNTPOINT2_VALID' => '/media/ramdisk1', + 'NP_MOUNTPOINT_VALID' => '/', + 'NP_MYSQL_LOGIN_DETAILS' => '-u root -d test', + 'NP_MYSQL_SERVER' => 'localhost', + 'NP_MYSQL_SOCKET' => '/var/run/mysqld/mysqld.sock', + 'NP_MYSQL_WITH_SLAVE' => '', + 'NP_MYSQL_WITH_SLAVE_LOGIN' => '', + 'NP_NO_NTP_SERVICE' => 'localhost', + 'NP_PORT_TCP_PROXY' => '3128', + 'NP_SMB_SHARE' => '', + 'NP_SMB_SHARE_DENY' => '', + 'NP_SMB_SHARE_SPC' => '', + 'NP_SMB_VALID_USER' => '', + 'NP_SMB_VALID_USER_PASS' => '', + 'NP_SNMP_COMMUNITY' => '', + 'NP_SNMP_USER' => '', + 'NP_SSH_CONFIGFILE' => '~/.ssh/config', + 'NP_SSH_HOST' => 'localhost', + 'NP_SSH_IDENTITY' => '~/.ssh/id_rsa' +} diff --git a/.github/prepare_debian.sh b/.github/prepare_debian.sh new file mode 100755 index 00000000..40053206 --- /dev/null +++ b/.github/prepare_debian.sh @@ -0,0 +1,99 @@ +#!/bin/bash + +set -x +set -e + +export DEBIAN_FRONTEND=noninteractive + +apt-get update +apt-get -y install software-properties-common +if [ $(lsb_release -is) = "Debian" ]; then + apt-add-repository non-free + apt-get update +fi +apt-get -y install perl autotools-dev libdbi-dev libldap2-dev libpq-dev libradcli-dev libnet-snmp-perl procps +apt-get -y install libdbi0-dev libdbd-sqlite3 libssl-dev dnsutils snmp-mibs-downloader libsnmp-perl snmpd +apt-get -y install fping snmp netcat smbclient vsftpd apache2 ssl-cert postfix libhttp-daemon-ssl-perl +apt-get -y install libdbd-sybase-perl libnet-dns-perl +apt-get -y install slapd ldap-utils +apt-get -y install gcc make autoconf automake gettext +apt-get -y install faketime +apt-get -y install libmonitoring-plugin-perl +apt-get -y install libcurl4-openssl-dev +apt-get -y install liburiparser-dev +apt-get -y install squid +apt-get -y install openssh-server +apt-get -y install mariadb-server mariadb-client libmariadb-dev +apt-get -y install cron iputils-ping +apt-get -y install iproute2 + +# remove ipv6 interface from hosts +if [ $(ip addr show | grep "inet6 ::1" | wc -l) -eq "0" ]; then + sed '/^::1/d' /etc/hosts > /tmp/hosts + cp -f /tmp/hosts /etc/hosts +fi + +ip addr show + +cat /etc/hosts + + +# apache +a2enmod ssl +a2ensite default-ssl +make-ssl-cert generate-default-snakeoil --force-overwrite +service apache2 start + +# squid +cp tools/squid.conf /etc/squid/squid.conf +service squid start + +# mariadb +service mariadb start +mysql -e "create database IF NOT EXISTS test;" -uroot + +# ldap +sed -e 's/cn=admin,dc=nodomain/'$(/usr/sbin/slapcat|grep ^dn:|awk '{print $2}')'/' -i .github/NPTest.cache +service slapd start + +# sshd +ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa +cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys +service ssh start +sleep 1 +ssh-keyscan localhost >> ~/.ssh/known_hosts +touch ~/.ssh/config + +# start one login session, required for check_users +( ssh -n -tt root@localhost "top" < /dev/null >/dev/null 2>&1 & ) +sleep 1 +who +ssh root@localhost "top -b -n 1" + +# snmpd +for DIR in /usr/share/snmp/mibs /usr/share/mibs; do + rm -f $DIR/ietf/SNMPv2-PDU \ + $DIR/ietf/IPSEC-SPD-MIB \ + $DIR/ietf/IPATM-IPMC-MIB \ + $DIR/iana/IANA-IPPM-METRICS-REGISTRY-MIB +done +mkdir -p /var/lib/snmp/mib_indexes +sed -e 's/^agentaddress.*/agentaddress 127.0.0.1/' -i /etc/snmp/snmpd.conf +service snmpd start + +# start cron, will be used by check_nagios +cron + +# start postfix +service postfix start + +# start ftpd +service vsftpd start + +# hostname +sed "/NP_HOST_TLS_CERT/s/.*/'NP_HOST_TLS_CERT' => '$(hostname)',/" -i /src/.github/NPTest.cache + +# create some test files to lower inodes +for i in $(seq 10); do + touch /media/ramdisk2/test.$1 +done diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..4c3497d0 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,77 @@ +name: Test + +on: + push: + branches: + - '*' + pull_request: + +jobs: +# macos: +# name: Running tests on ${{ matrix.os }} +# strategy: +# fail-fast: false +# matrix: +# os: +# - macos-10.15 +# runs-on: ${{ matrix.os }} +# steps: +# +# - name: Git clone repository +# uses: actions/checkout@v2 +# #- name: Setup tmate session, see https://github.com/marketplace/actions/debugging-with-tmate +# # uses: mxschmitt/action-tmate@v3 +# - name: Prepare machine +# run: | +# brew install automake +# - name: Run the tests +# run: | +# tools/setup \ +# && ./configure --enable-libtap \ +# && make \ +# && make test + + linux: + runs-on: ubuntu-latest + name: Running tests on ${{ matrix.distro }} + strategy: + fail-fast: false + matrix: + distro: + #- 'debian:10' + - 'debian:testing' + #- 'ubuntu:20.10' + #- 'centos:7' + #- 'centos:8' + include: + #- distro: 'debian:10' + # prepare: .github/prepare_debian.sh + - distro: 'debian:testing' + prepare: .github/prepare_debian.sh + #- distro: 'ubuntu:20.10' + # prepare: .github/prepare_debian.sh + #- distro: 'centos:7' + # prepare: .github/prepare_centos.sh + #- distro: 'centos:8' + # prepare: .github/prepare_centos.sh + steps: + - name: Git clone repository + uses: actions/checkout@v2 + #- name: Setup tmate session, see https://github.com/marketplace/actions/debugging-with-tmate + # uses: mxschmitt/action-tmate@v3 + - name: Run the tests on ${{ matrix.distro }} + run: | + docker volume create --driver local --opt type=tmpfs --opt device=tmpfs --opt o=size=100m,uid=1000 tmp-vol + docker run \ + -e NPTEST_ACCEPTDEFAULT=1 \ + -e NPTEST_CACHE="/src/.github/NPTest.cache" \ + -w /src -v ${PWD}:/src \ + --tmpfs /media/ramdisk1 \ + --mount source=tmp-vol,destination=/src,target=/media/ramdisk2 \ + ${{ matrix.distro }} \ + /bin/sh -c '${{ matrix.prepare }} && \ + tools/setup && \ + ./configure --enable-libtap && \ + make && \ + make test' + docker volume rm tmp-vol diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 3d9fe64e..00000000 --- a/.travis.yml +++ /dev/null @@ -1,98 +0,0 @@ -sudo: required -dist: xenial -language: c - -env: - global: - # This is the encrypted COVERITY_SCAN_TOKEN, created via the "travis - # encrypt" command using the project repository's public key. - - secure: "ggJ9c/VfKcwtrwz/My+ne4My7D8g3qi3vz5Hh+yLiri0+oIXCy313ZD6ssIEY/5beQZEOnuHhBgBJd/Y3clSQNc2M9fRNc+wxOkIO992lgnY0MZJN3y9MLfpqUbTClhU9Fst0qXQqGpI6UI8yz1tj7yKi7DPrycJLRrjMpyTfyo=" - -matrix: - include: - - compiler: "gcc" - os: linux - env: - - PLATFORM=linux BITS=64 HOST=x86_64 - addons: - coverity_scan: - project: - name: "monitoring-plugins/monitoring-plugins" - description: "Monitoring Plugins" - notification_email: team@monitoring-plugins.org - build_command_prepend: tools/setup && ./configure - build_command: make - branch_pattern: coverity.* - - compiler: "clang" - os: linux - env: - - PLATFORM=linux BITS=64 HOST=x86_64 - -before_install: - # Trusty related fixed - # multiverse is no on trusty activated (https://github.com/travis-ci/travis-ci/issues/4979) - - sudo apt-get install -qq --no-install-recommends software-properties-common - - sudo add-apt-repository "deb http://archive.ubuntu.com/ubuntu/ trusty multiverse" && sudo add-apt-repository "deb http://archive.ubuntu.com/ubuntu/ trusty-updates multiverse" - # /etc/hosts has IPv6 hosts (https://github.com/travis-ci/travis-ci/issues/4978) - - sudo [ $(ip addr show | grep "inet6 ::1" | wc -l) -eq "0" ] || sudo sed -i '/^::1/d' /etc/hosts - # Trusty has running ntpd on localhost, but we don't like that for our tests - - "sudo killall -9 ntpd ||:" - # Trusty has no swap, lets create some - - sudo fallocate -l 20M /swapfile; sudo chmod 600 /swapfile; sudo mkswap /swapfile; sudo swapon /swapfile - - sudo apt-get update -qq - - sudo apt-get purge -qq gawk - -install: - - sudo apt-get install -qq --no-install-recommends perl autotools-dev libdbi-dev libldap2-dev libpq-dev libmysqlclient-dev libradcli-dev libkrb5-dev libnet-snmp-perl procps - - sudo apt-get install -qq --no-install-recommends libdbi0-dev libdbd-sqlite3 libssl-dev dnsutils snmp-mibs-downloader libsnmp-perl snmpd - - sudo apt-get install -qq --no-install-recommends fping snmp netcat smbclient fping pure-ftpd apache2 ssl-cert postfix libhttp-daemon-ssl-perl - - sudo apt-get install -qq --no-install-recommends libdbd-sybase-perl libnet-dns-perl - - sudo apt-get install -qq --no-install-recommends slapd ldap-utils - - sudo apt-get install -qq --no-install-recommends autoconf automake - - sudo apt-get install -qq --no-install-recommends faketime - - sudo apt-get install -qq --no-install-recommends libmonitoring-plugin-perl - - sudo apt-get install -qq --no-install-recommends libcurl4-openssl-dev - - sudo apt-get install -qq --no-install-recommends liburiparser-dev - - sudo apt-get install -qq --no-install-recommends squid - # Trusty related dependencies (not yet provided) - - test "$(dpkg -l | grep -E "mysql-(client|server)-[0-9].[0-9]" | grep -c ^ii)" -gt 0 || sudo apt-get install -qq --no-install-recommends mariadb-client mariadb-server - # enable ssl apache - - sudo a2enmod ssl - - sudo a2ensite default-ssl - - sudo make-ssl-cert generate-default-snakeoil --force-overwrite - - sudo service apache2 reload - - sudo cp tools/squid.conf /etc/squid/squid.conf - - sudo service squid reload - - sudo service mysql restart - -before_script: - # ensure we have a test database in place for tests - - mysql -e "create database IF NOT EXISTS test;" -uroot - # Detect LDAP configuration (seems volatile on trusty env) - - sed -e 's/cn=admin,dc=nodomain/'$(sudo /usr/sbin/slapcat|grep ^dn:|grep cn=|awk '{print $2}')'/' -i plugins/t/NPTest.cache.travis - - tools/setup - - ./configure --enable-libtap - - make - - export NPTEST_ACCEPTDEFAULT=1 - - export NPTEST_CACHE="$(pwd)/plugins/t/NPTest.cache.travis" - - ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa - - cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys - - ssh-keyscan localhost >> ~/.ssh/known_hosts - - touch ~/.ssh/config - - sudo rm -f /usr/share/mibs/ietf/SNMPv2-PDU /usr/share/mibs/ietf/IPSEC-SPD-MIB /usr/share/mibs/ietf/IPATM-IPMC-MIB /usr/share/mibs/iana/IANA-IPPM-METRICS-REGISTRY-MIB - - sudo mkdir -p /var/lib/snmp/mib_indexes - - sudo mkdir /media/ramdisk && sudo chmod 777 /media/ramdisk && sudo mount -t tmpfs -o size=20% none /media/ramdisk - - sed "/NP_HOST_TLS_CERT/s/.*/'NP_HOST_TLS_CERT' => '$(hostname)',/" -i $NPTEST_CACHE - -script: - - if [ "$COVERITY_SCAN_BRANCH" != 1 ]; then make test; fi - -notifications: - irc: - channels: - - "chat.freenode.net#Monitoring-Plugins" - on_success: change - on_failure: always - skip_join: true - email: - # - team@monitoring-plugins.org diff --git a/plugins/t/NPTest.cache.travis b/plugins/t/NPTest.cache.travis deleted file mode 100644 index 9b9f8059..00000000 --- a/plugins/t/NPTest.cache.travis +++ /dev/null @@ -1,54 +0,0 @@ -{ - 'NP_ALLOW_SUDO' => 'yes', - 'NP_DNS_SERVER' => '8.8.8.8', - 'NP_GOOD_NTP_SERVICE' => '', - 'NP_HOST_DHCP_RESPONSIVE' => '', - 'NP_HOST_HPJD_PORT_INVALID' => '161', - 'NP_HOST_HPJD_PORT_VALID' => '', - 'NP_HOSTNAME_INVALID_CIDR' => '130.133.8.39/30', - 'NP_HOSTNAME_INVALID' => 'nosuchhost', - 'NP_HOSTNAME_VALID_CIDR' => '130.133.8.41/30', - 'NP_HOSTNAME_VALID_IP' => '130.133.8.40', - 'NP_HOSTNAME_VALID' => 'monitoring-plugins.org', - 'NP_HOSTNAME_VALID_REVERSE' => 'orwell.monitoring-plugins.org.', - 'NP_HOST_NONRESPONSIVE' => '10.0.0.1', - 'NP_HOST_RESPONSIVE' => 'localhost', - 'NP_HOST_SMB' => '', - 'NP_HOST_SNMP' => '', - 'NP_HOST_TCP_FTP' => '', - 'NP_HOST_TCP_HPJD' => '', - 'NP_HOST_TCP_HTTP2' => 'test.monitoring-plugins.org', - 'NP_HOST_TCP_HTTP' => 'localhost', - 'NP_HOST_TCP_IMAP' => 'imap.web.de', - 'NP_HOST_TCP_JABBER' => 'jabber.org', - 'NP_HOST_TCP_LDAP' => 'localhost', - 'NP_HOST_TCP_POP' => 'pop.web.de', - 'NP_HOST_TCP_PROXY' => 'localhost', - 'NP_HOST_TCP_SMTP' => 'localhost', - 'NP_HOST_TCP_SMTP_NOTLS' => '', - 'NP_HOST_TCP_SMTP_TLS' => '', - 'NP_HOST_TLS_CERT' => 'localhost, - 'NP_HOST_TLS_HTTP' => 'localhost', - 'NP_HOST_UDP_TIME' => 'none', - 'NP_INTERNET_ACCESS' => 'yes', - 'NP_LDAP_BASE_DN' => 'cn=admin,dc=nodomain', - 'NP_MOUNTPOINT2_VALID' => '/media/ramdisk', - 'NP_MOUNTPOINT_VALID' => '/', - 'NP_MYSQL_LOGIN_DETAILS' => '-u root -d test', - 'NP_MYSQL_SERVER' => 'localhost', - 'NP_MYSQL_SOCKET' => '/var/run/mysqld/mysqld.sock', - 'NP_MYSQL_WITH_SLAVE' => '', - 'NP_MYSQL_WITH_SLAVE_LOGIN' => '', - 'NP_NO_NTP_SERVICE' => 'localhost', - 'NP_PORT_TCP_PROXY' => '3128', - 'NP_SMB_SHARE' => '', - 'NP_SMB_SHARE_DENY' => '', - 'NP_SMB_SHARE_SPC' => '', - 'NP_SMB_VALID_USER' => '', - 'NP_SMB_VALID_USER_PASS' => '', - 'NP_SNMP_COMMUNITY' => '', - 'NP_SNMP_USER' => '', - 'NP_SSH_CONFIGFILE' => '~/.ssh/config', - 'NP_SSH_HOST' => 'localhost', - 'NP_SSH_IDENTITY' => '~/.ssh/id_rsa' -} -- cgit v1.2.3-74-g34f1 From 5ab03a70950cecf5fe4ab52a3c4f9b0f6ac98939 Mon Sep 17 00:00:00 2001 From: Aksel Sjögren Date: Wed, 28 Apr 2021 15:48:20 +0200 Subject: Fix conditional tests for check_http, check_curl Set correct number of tests in skip- blocks to avoid the error "Bad plan. You planned 50 tests but ran 55" when run with/without /usr/bin/faketime and NP_INTERNET_ACCESS=yes/no. --- plugins/t/check_curl.t | 4 ++-- plugins/t/check_http.t | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/t/check_curl.t b/plugins/t/check_curl.t index a4f1dfb3..4f4124b3 100644 --- a/plugins/t/check_curl.t +++ b/plugins/t/check_curl.t @@ -84,7 +84,7 @@ like( $res->output, '/^Host: testhost:8001\s*$/ms', "Host Header OK" ); like( $res->output, '/CURLOPT_URL: http:\/\/'.$host_tcp_http.':80\//ms', "Url OK" ); SKIP: { - skip "No internet access", 3 if $internet_access eq "no"; + skip "No internet access", 4 if $internet_access eq "no"; $res = NPTest->testCmd("./$plugin -v -H $host_tls_http -S"); like( $res->output, '/^Host: '.$host_tls_http.'\s*$/ms', "Host Header OK" ); @@ -120,7 +120,7 @@ SKIP: { cmp_ok( $res->return_code, "==", 0, "And also when not found"); } SKIP: { - skip "No internet access", 16 if $internet_access eq "no"; + skip "No internet access", 28 if $internet_access eq "no"; $res = NPTest->testCmd( "./$plugin --ssl $host_tls_http" diff --git a/plugins/t/check_http.t b/plugins/t/check_http.t index e92681e9..c137f7b4 100644 --- a/plugins/t/check_http.t +++ b/plugins/t/check_http.t @@ -103,7 +103,7 @@ SKIP: { cmp_ok( $res->return_code, "==", 0, "And also when not found"); } SKIP: { - skip "No internet access", 16 if $internet_access eq "no"; + skip "No internet access", 23 if $internet_access eq "no"; $res = NPTest->testCmd( "./$plugin --ssl $host_tls_http" @@ -135,7 +135,7 @@ SKIP: { # run some certificate checks with faketime SKIP: { - skip "No faketime binary found", 12 if !$faketime; + skip "No faketime binary found", 7 if !$faketime; $res = NPTest->testCmd("LC_TIME=C TZ=UTC ./$plugin -C 1 $host_tls_http"); like($res->output, qr/OK - Certificate '$host_tls_cert' will expire on/, "Catch cert output"); is( $res->return_code, 0, "Catch cert output exit code" ); -- cgit v1.2.3-74-g34f1 From ae2fe683e3a5e2254473777b0249efe66f24d26c Mon Sep 17 00:00:00 2001 From: Jacob Hansen Date: Tue, 18 May 2021 15:19:43 +0200 Subject: check_curl.t: Adjust test to use -f curl It appears that `-f follow` doesn't work correctly in `check_curl` at the moment. Test adjusted to use `-f curl` instead. Issue for the above created: https://github.com/monitoring-plugins/monitoring-plugins/issues/1685 Signed-off-by: Jacob Hansen --- plugins/t/check_curl.t | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/t/check_curl.t b/plugins/t/check_curl.t index 4f4124b3..45ee5339 100644 --- a/plugins/t/check_curl.t +++ b/plugins/t/check_curl.t @@ -193,8 +193,7 @@ SKIP: { ); cmp_ok( $res->return_code, "==", 0, "Can read https for www.e-paycobalt.com (uses AES certificate)" ); - - $res = NPTest->testCmd( "./$plugin -H www.mozilla.com -u /firefox -f follow" ); + $res = NPTest->testCmd( "./$plugin -H www.mozilla.com -u /firefox -f curl" ); is( $res->return_code, 0, "Redirection based on location is okay"); $res = NPTest->testCmd( "./$plugin -H www.mozilla.com --extended-perfdata" ); -- cgit v1.2.3-74-g34f1 From 0bbcb60f02d6f78561f684adb0294870a3522e4f Mon Sep 17 00:00:00 2001 From: Jacob Hansen Date: Wed, 19 May 2021 13:13:47 +0200 Subject: Refactor check_fping * Set correct amount of tests based on conditionals. * When running the test as non-root, we would previously check is the setuid bit is set. This doesn't seem to be needed, so just check if the binary is executable for the user running the test. * Use cmp_ok to check if tests succeeds rather than couting. Signed-off-by: Jacob Hansen --- plugins/t/check_fping.t | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) (limited to 'plugins') diff --git a/plugins/t/check_fping.t b/plugins/t/check_fping.t index 03a6110e..67b357b2 100644 --- a/plugins/t/check_fping.t +++ b/plugins/t/check_fping.t @@ -5,31 +5,30 @@ # use strict; -use Test; +use Test::More; use NPTest; -use vars qw($tests); - -BEGIN {$tests = 4; plan tests => $tests} - my $host_responsive = getTestParameter("NP_HOST_RESPONSIVE", "The hostname of system responsive to network requests", "localhost"); 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 $t; +my $res; my $fping = qx(which fping 2> /dev/null); chomp($fping); if( ! -x "./check_fping") { - $t += skipMissingCmd( "./check_fping", $tests ); + plan skip_all => "check_fping not found, skipping tests"; } -elsif ( $> != 0 && (!$fping || ! -u $fping)) { - $t += skipMsg( "./check_fping", $tests ); +elsif ( !$fping || !-x $fping ) { + plan skip_all => "fping not found or cannot be executed, skipping tests"; } else { - $t += checkCmd( "./check_fping $host_responsive", 0, '/^FPING OK - /' ); - $t += checkCmd( "./check_fping $host_nonresponsive", 2, '/^FPING CRITICAL - /' ); - $t += checkCmd( "./check_fping $hostname_invalid", 3, '/^FPING UNKNOWN - /' ); -} + plan tests => 3; + $res = NPTest->testCmd( "./check_fping $host_responsive" ); + cmp_ok( $res->return_code, '==', 0, "Responsive host returns OK"); -exit(0) if defined($Test::Harness::VERSION); -exit($tests - $t); + $res = NPTest->testCmd( "./check_fping $host_nonresponsive" ); + cmp_ok( $res->return_code, '==', 2, "Non-Responsive host returns Critical"); + + $res = NPTest->testCmd( "./check_fping $hostname_invalid" ); + cmp_ok( $res->return_code, '==', 3, "Invalid host returns Unknown"); +} -- cgit v1.2.3-74-g34f1 From eb75d847ae31a86768b06926bc2323f7c16f07b9 Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Thu, 20 May 2021 18:04:49 +0200 Subject: tests: increase startup sleep github action might fail from to time otherwise --- plugins/tests/check_curl.t | 5 +++-- plugins/tests/check_http.t | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/tests/check_curl.t b/plugins/tests/check_curl.t index 0caad23d..29cb03f2 100755 --- a/plugins/tests/check_curl.t +++ b/plugins/tests/check_curl.t @@ -126,8 +126,6 @@ if ($pid) { exit; } } - # give our webservers some time to startup - sleep(1); } else { # Child #print "child\n"; @@ -140,6 +138,9 @@ if ($pid) { exit; } +# give our webservers some time to startup +sleep(3); + # Run the same server on http and https sub run_server { my $d = shift; diff --git a/plugins/tests/check_http.t b/plugins/tests/check_http.t index 2f051fad..0f56950f 100755 --- a/plugins/tests/check_http.t +++ b/plugins/tests/check_http.t @@ -102,8 +102,6 @@ if ($pid) { exit; } } - # give our webservers some time to startup - sleep(1); } else { # Child #print "child\n"; @@ -116,6 +114,9 @@ if ($pid) { exit; } +# give our webservers some time to startup +sleep(3); + # Run the same server on http and https sub run_server { my $d = shift; -- cgit v1.2.3-74-g34f1 From b428cc17f75682465e6f1e59b32fdec02b87ceac Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Thu, 20 May 2021 20:57:59 +0200 Subject: tests: ignore sigpipes in https test daemon check_http closes the connection after checking the certificate with -C. This leads to sigpipe errors when the ssl daemon wants to send a response and the daemon quits which makes the subsequent tests fail. --- plugins/tests/check_http.t | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/tests/check_http.t b/plugins/tests/check_http.t index 0f56950f..188f5e75 100755 --- a/plugins/tests/check_http.t +++ b/plugins/tests/check_http.t @@ -91,6 +91,8 @@ if ($pid) { exit; } } else { + # closing the connection after -C cert checks make the daemon exit with a sigpipe otherwise + local $SIG{'PIPE'} = 'IGNORE'; my $d = HTTP::Daemon::SSL->new( LocalPort => $port_https, LocalAddr => "127.0.0.1", @@ -415,22 +417,24 @@ sub run_common_tests { # stickyport - on full urlS port is set back to 80 otherwise $cmd = "$command -f stickyport -u /redir_external -t 5 -s redirected"; + alarm(2); eval { local $SIG{ALRM} = sub { die "alarm\n" }; - alarm(2); $result = NPTest->testCmd( $cmd ); - alarm(0); }; + }; isnt( $@, "alarm\n", $cmd ); + alarm(0); is( $result->return_code, 0, $cmd ); # Let's hope there won't be any web server on :80 returning "redirected"! $cmd = "$command -f sticky -u /redir_external -t 5 -s redirected"; + alarm(2); eval { local $SIG{ALRM} = sub { die "alarm\n" }; - alarm(2); $result = NPTest->testCmd( $cmd ); - alarm(0); }; + }; isnt( $@, "alarm\n", $cmd ); + alarm(0); isnt( $result->return_code, 0, $cmd ); # Test an external address - timeout -- cgit v1.2.3-74-g34f1 From 63cb7ecfcf8d5b6c9f2be704eee7fa7cd9216f88 Mon Sep 17 00:00:00 2001 From: Barak Shohat Date: Mon, 24 May 2021 13:42:43 +0300 Subject: check_curl.c: bugfix: verify certificates option should not force SSL to be used --- plugins/check_curl.c | 2 +- plugins/t/check_curl.t | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 3e0a6f94..d29db0a6 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -1346,7 +1346,7 @@ process_arguments (int argc, char **argv) #ifdef LIBCURL_FEATURE_SSL case 'D': /* verify peer certificate & host */ verify_peer_and_host = TRUE; - goto enable_ssl; + break; #endif case 'S': /* use SSL */ #ifdef LIBCURL_FEATURE_SSL diff --git a/plugins/t/check_curl.t b/plugins/t/check_curl.t index 45ee5339..ada6a045 100644 --- a/plugins/t/check_curl.t +++ b/plugins/t/check_curl.t @@ -95,7 +95,7 @@ SKIP: { $res = NPTest->testCmd("./$plugin -v -H $host_tls_http:443 -S -p 443"); like( $res->output, '/^Host: '.$host_tls_http.'\s*$/ms', "Host Header OK" ); - $res = NPTest->testCmd("./$plugin -v -H $host_tls_http -D -p 443"); + $res = NPTest->testCmd("./$plugin -v -H $host_tls_http -D -S -p 443"); like( $res->output, '/(^Host: '.$host_tls_http.'\s*$)|(cURL returned 60)/ms', "Host Header OK" ); }; -- cgit v1.2.3-74-g34f1 From beb609ffcf8c24c133f59829e0d3d82102661b82 Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Thu, 27 May 2021 15:32:08 +0200 Subject: check_curl: - added verbose output in verify_callback - pin refcounting for certs (avoid subject extraction error when checking certs in is_openssl_callback mode) --- plugins/check_curl.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 3e0a6f94..59e398b2 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -285,6 +285,18 @@ int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) * TODO: is the last certificate always the server certificate? */ cert = X509_STORE_CTX_get_current_cert(x509_ctx); + X509_up_ref(cert); + if (verbose>=2) { + puts("* SSL verify callback with certificate:"); + X509_NAME *subject, *issuer; + printf("* issuer:\n"); + issuer = X509_get_issuer_name( cert ); + X509_NAME_print_ex_fp(stdout, issuer, 5, XN_FLAG_MULTILINE); + printf("* curl verify_callback:\n* subject:\n"); + subject = X509_get_subject_name( cert ); + X509_NAME_print_ex_fp(stdout, subject, 5, XN_FLAG_MULTILINE); + puts(""); + } return 1; } -- cgit v1.2.3-74-g34f1 From 20e9451fadb452636bc4b395fcb6aaf93a477c23 Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Thu, 24 Jun 2021 11:02:28 +0200 Subject: added option --enable-automatic-decompression --- plugins/check_curl.c | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 59e398b2..d4442f51 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -206,6 +206,7 @@ int maximum_age = -1; int address_family = AF_UNSPEC; curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN; int curl_http_version = CURL_HTTP_VERSION_NONE; +int automatic_decompression = FALSE; int process_arguments (int, char**); void handle_curl_option_return_code (CURLcode res, const char* option); @@ -383,6 +384,13 @@ check_http (void) /* print everything on stdout like check_http would do */ handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_STDERR, stdout), "CURLOPT_STDERR"); + if (automatic_decompression) +#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 21, 6) + handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, ""), "CURLOPT_ACCEPT_ENCODING"); +#else + handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_ENCODING, ""), "CURLOPT_ENCODING"); +#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 21, 6) */ + /* initialize buffer for body of the answer */ if (curlhelp_initwritebuffer(&body_buf) < 0) die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for body\n"); @@ -1149,7 +1157,8 @@ process_arguments (int argc, char **argv) INVERT_REGEX = CHAR_MAX + 1, SNI_OPTION, CA_CERT_OPTION, - HTTP_VERSION_OPTION + HTTP_VERSION_OPTION, + AUTOMATIC_DECOMPRESSION }; int option = 0; @@ -1192,6 +1201,7 @@ process_arguments (int argc, char **argv) {"extended-perfdata", no_argument, 0, 'E'}, {"show-body", no_argument, 0, 'B'}, {"http-version", required_argument, 0, HTTP_VERSION_OPTION}, + {"enable-automatic-decompression", no_argument, 0, AUTOMATIC_DECOMPRESSION}, {0, 0, 0, 0} }; @@ -1583,6 +1593,9 @@ process_arguments (int argc, char **argv) exit (STATE_WARNING); } break; + case AUTOMATIC_DECOMPRESSION: + automatic_decompression = TRUE; + break; case '?': /* print short usage statement if args not parsable */ usage5 (); @@ -1793,6 +1806,8 @@ print_help (void) printf (" %s\n", "--http-version=VERSION"); printf (" %s\n", _("Connect via specific HTTP protocol.")); printf (" %s\n", _("1.0 = HTTP/1.0, 1.1 = HTTP/1.1, 2.0 = HTTP/2 (HTTP/2 will fail without -S)")); + printf (" %s\n", "--enable-automatic-decompression"); + printf (" %s\n", _("Enable automatic decompression of body (CURLOPT_ACCEPT_ENCODING).")); printf ("\n"); printf (UT_WARN_CRIT); -- cgit v1.2.3-74-g34f1 From a1af8be9781ccdf36087a9e42fa18cfd468f1401 Mon Sep 17 00:00:00 2001 From: Daniel Uhlmann Date: Thu, 24 Jun 2021 11:37:14 +0200 Subject: changed 'STATE_CRITICAL' to 'STATE_WARNING' for infinite loop --- plugins/check_http.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index 0b712665..34fb4f01 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -1453,8 +1453,8 @@ redir (char *pos, char *status_line) !strncmp(server_address, addr, MAX_IPV4_HOSTLENGTH) && (host_name && !strncmp(host_name, addr, MAX_IPV4_HOSTLENGTH)) && !strcmp(server_url, url)) - die (STATE_WARNING, - _("HTTP WARNING - redirection creates an infinite loop - %s://%s:%d%s%s\n"), + die (STATE_CRITICAL, + _("HTTP CRITICAL - redirection creates an infinite loop - %s://%s:%d%s%s\n"), type, addr, i, url, (display_html ? "" : "")); strcpy (server_type, type); -- cgit v1.2.3-74-g34f1 From 0b6838ffcaf372df419059771dd42f1bd69644c0 Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Thu, 24 Jun 2021 17:08:20 +0000 Subject: fix for missing X509_up_ref on old systems with only OpenSSL 1.0 --- plugins/check_curl.c | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index d4442f51..daf64b0b 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -55,6 +55,10 @@ const char *email = "devel@monitoring-plugins.org"; #include +#if defined(HAVE_SSL) && defined(USE_OPENSSL) +#include +#endif + #define MAKE_LIBCURL_VERSION(major, minor, patch) ((major)*0x10000 + (minor)*0x100 + (patch)) #define DEFAULT_BUFFER_SIZE 2048 @@ -286,7 +290,9 @@ int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) * TODO: is the last certificate always the server certificate? */ cert = X509_STORE_CTX_get_current_cert(x509_ctx); +#if OPENSSL_VERSION_NUMBER >= 0x10100000L X509_up_ref(cert); +#endif if (verbose>=2) { puts("* SSL verify callback with certificate:"); X509_NAME *subject, *issuer; -- cgit v1.2.3-74-g34f1 From 6e5ee70d07c0a8515acdc3ad52716285a4b7f77b Mon Sep 17 00:00:00 2001 From: Lorenz Kästle Date: Fri, 25 Jun 2021 12:12:48 +0200 Subject: Let ssh decide if a host is valid, enables usage of ssh .config file --- plugins/check_by_ssh.c | 2 -- 1 file changed, 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_by_ssh.c b/plugins/check_by_ssh.c index 13d8bc3b..485bf3be 100644 --- a/plugins/check_by_ssh.c +++ b/plugins/check_by_ssh.c @@ -230,7 +230,6 @@ process_arguments (int argc, char **argv) timeout_interval = atoi (optarg); break; case 'H': /* host */ - host_or_die(optarg); hostname = optarg; break; case 'p': /* port number */ @@ -329,7 +328,6 @@ process_arguments (int argc, char **argv) if (c <= argc) { die (STATE_UNKNOWN, _("%s: You must provide a host name\n"), progname); } - host_or_die(argv[c]); hostname = argv[c++]; } -- cgit v1.2.3-74-g34f1 From 6e696643a5701ddd18945593743286b35b5944cb Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Sun, 4 Jul 2021 18:43:42 +0200 Subject: check_curl: changed to STATE_CRITICAL for infinite loops (-ffollow) --- plugins/check_curl.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index daf64b0b..ba08c36b 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -1106,8 +1106,8 @@ redir (curlhelp_write_curlbuf* header_buf) !strncmp(server_address, new_host, MAX_IPV4_HOSTLENGTH) && (host_name && !strncmp(host_name, new_host, MAX_IPV4_HOSTLENGTH)) && !strcmp(server_url, new_url)) - die (STATE_WARNING, - _("HTTP WARNING - redirection creates an infinite loop - %s://%s:%d%s%s\n"), + die (STATE_CRITICAL, + _("HTTP CRITICAL - redirection creates an infinite loop - %s://%s:%d%s%s\n"), use_ssl ? "https" : "http", new_host, new_port, new_url, (display_html ? "" : "")); /* set new values for redirected request */ -- cgit v1.2.3-74-g34f1 From 3f5c54c7830b0529030bb08e2c333497e70b6eb1 Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Sun, 25 Jul 2021 18:39:07 +0200 Subject: check_curl: fixed DNS caching for SSL hostnames (avoid CURLOPT_RESOLVE entry errors) --- plugins/check_curl.c | 54 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 51 insertions(+), 3 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index ba08c36b..2c91a275 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -59,6 +59,8 @@ const char *email = "devel@monitoring-plugins.org"; #include #endif +#include + #define MAKE_LIBCURL_VERSION(major, minor, patch) ((major)*0x10000 + (minor)*0x100 + (patch)) #define DEFAULT_BUFFER_SIZE 2048 @@ -369,6 +371,46 @@ handle_curl_option_return_code (CURLcode res, const char* option) } } +int +lookup_host (const char *host, char *buf, size_t buflen) +{ + struct addrinfo hints, *res, *result; + int errcode; + void *ptr; + + memset (&hints, 0, sizeof (hints)); + hints.ai_family = address_family; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags |= AI_CANONNAME; + + errcode = getaddrinfo (host, NULL, &hints, &result); + if (errcode != 0) + return errcode; + + res = result; + + while (res) { + inet_ntop (res->ai_family, res->ai_addr->sa_data, buf, buflen); + switch (res->ai_family) { + case AF_INET: + ptr = &((struct sockaddr_in *) res->ai_addr)->sin_addr; + break; + case AF_INET6: + ptr = &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr; + break; + } + inet_ntop (res->ai_family, ptr, buf, buflen); + if (verbose >= 1) + printf ("* getaddrinfo IPv%d address: %s\n", + res->ai_family == PF_INET6 ? 6 : 4, buf); + res = res->ai_next; + } + + freeaddrinfo(result); + + return 0; +} + int check_http (void) { @@ -376,6 +418,9 @@ check_http (void) int page_len = 0; int i; char *force_host_header = NULL; + struct curl_slist *host = NULL; + char addrstr[100]; + char dnscache[DEFAULT_BUFFER_SIZE]; /* initialize curl */ if (curl_global_init (CURL_GLOBAL_DEFAULT) != CURLE_OK) @@ -418,9 +463,12 @@ check_http (void) // fill dns resolve cache to make curl connect to the given server_address instead of the host_name, only required for ssl, because we use the host_name later on to make SNI happy if(use_ssl && host_name != NULL) { - struct curl_slist *host = NULL; - char dnscache[DEFAULT_BUFFER_SIZE]; - snprintf (dnscache, DEFAULT_BUFFER_SIZE, "%s:%d:%s", host_name, server_port, server_address); + if ( (res=lookup_host (server_address, addrstr, 100)) != 0) { + snprintf (msg, DEFAULT_BUFFER_SIZE, _("Unable to lookup IP address for '%s': getaddrinfo returned %d - %s"), + server_address, res, gai_strerror (res)); + die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); + } + snprintf (dnscache, DEFAULT_BUFFER_SIZE, "%s:%d:%s", host_name, server_port, addrstr); host = curl_slist_append(NULL, dnscache); curl_easy_setopt(curl, CURLOPT_RESOLVE, host); if (verbose>=1) -- cgit v1.2.3-74-g34f1 From de5503063e4ea455a7a0a57afcc467a2041c859f Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Sun, 25 Jul 2021 18:49:06 +0200 Subject: check_curl: fixed a potential buffer overflow in retir/uri_string --- plugins/check_curl.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 2c91a275..5990b95b 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -1033,8 +1033,8 @@ char* uri_string (const UriTextRangeA range, char* buf, size_t buflen) { if (!range.first) return "(null)"; - strncpy (buf, range.first, max (buflen, range.afterLast - range.first)); - buf[max (buflen, range.afterLast - range.first)] = '\0'; + strncpy (buf, range.first, max (buflen-1, range.afterLast - range.first)); + buf[max (buflen-1, range.afterLast - range.first)] = '\0'; buf[range.afterLast - range.first] = '\0'; return buf; } -- cgit v1.2.3-74-g34f1 From 70f55ca9db87f639856e0548a57081c886e09d14 Mon Sep 17 00:00:00 2001 From: Jonny007-MKD Date: Sun, 23 Feb 2020 15:02:43 +0100 Subject: check_dns: add --expect-nxdomain --- NEWS | 1 + plugins/check_dns.c | 61 +++++++++++++++++++++++++++++++++++++-------------- plugins/t/check_dns.t | 12 ++++++++-- 3 files changed, 56 insertions(+), 18 deletions(-) (limited to 'plugins') diff --git a/NEWS b/NEWS index 4061c033..3790e8a0 100644 --- a/NEWS +++ b/NEWS @@ -13,6 +13,7 @@ This file documents the major additions and syntax changes between releases. check_dns: Accept CIDR check_dns: allow unsorted addresses check_dns: allow forcing complete match of all addresses + check_dns: option to expect NXDOMAIN check_apt: add --only-critical switch check_apt: add -l/--list option to print packages check_file_age: add range checking diff --git a/plugins/check_dns.c b/plugins/check_dns.c index 0f2e6541..0c10f09b 100644 --- a/plugins/check_dns.c +++ b/plugins/check_dns.c @@ -41,7 +41,7 @@ const char *email = "devel@monitoring-plugins.org"; int process_arguments (int, char **); int validate_arguments (void); -int error_scan (char *); +int error_scan (char *, int*); int ip_match_cidr(const char *, const char *); unsigned long ip2long(const char *); void print_help (void); @@ -54,6 +54,7 @@ char ptr_server[ADDRESS_LENGTH] = ""; int verbose = FALSE; char **expected_address = NULL; int expected_address_cnt = 0; +int expect_nxdomain = FALSE; int expect_authority = FALSE; int all_match = FALSE; @@ -87,6 +88,7 @@ main (int argc, char **argv) int parse_address = FALSE; /* This flag scans for Address: but only after Name: */ output chld_out, chld_err; size_t i; + int is_nxdomain = FALSE; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); @@ -186,7 +188,7 @@ main (int argc, char **argv) } - result = error_scan (chld_out.line[i]); + result = error_scan (chld_out.line[i], &is_nxdomain); if (result != STATE_OK) { msg = strchr (chld_out.line[i], ':'); if(msg) msg++; @@ -199,8 +201,8 @@ main (int argc, char **argv) if (verbose) puts(chld_err.line[i]); - if (error_scan (chld_err.line[i]) != STATE_OK) { - result = max_state (result, error_scan (chld_err.line[i])); + if (error_scan (chld_err.line[i], &is_nxdomain) != STATE_OK) { + result = max_state (result, error_scan (chld_err.line[i], &is_nxdomain)); msg = strchr(input_buffer, ':'); if(msg) msg++; @@ -209,6 +211,10 @@ main (int argc, char **argv) } } + if (is_nxdomain && !expect_nxdomain) { + die (STATE_CRITICAL, _("Domain '%s' was not found by the server\n"), query_address); + } + if (addresses) { int i,slen; char *adrp; @@ -260,6 +266,16 @@ main (int argc, char **argv) } } + if (expect_nxdomain) { + if (!is_nxdomain) { + result = STATE_CRITICAL; + xasprintf(&msg, _("Domain '%s' was found by the server: '%s'\n"), query_address, address); + } else { + if (address == NULL) free(address); + address = "NXDOMAIN"; + } + } + /* check if authoritative */ if (result == STATE_OK && expect_authority && non_authoritative) { result = STATE_CRITICAL; @@ -339,9 +355,15 @@ ip2long(const char* src) { } int -error_scan (char *input_buffer) +error_scan (char *input_buffer, int* is_nxdomain) { + const int nxdomain = strstr (input_buffer, "Non-existent") || + strstr (input_buffer, "** server can't find") || + strstr (input_buffer, "** Can't find") || + strstr (input_buffer, "NXDOMAIN"); + if (nxdomain) *is_nxdomain = TRUE; + /* the DNS lookup timed out */ if (strstr (input_buffer, _("Note: nslookup is deprecated and may be removed from future releases.")) || strstr (input_buffer, _("Consider using the `dig' or `host' programs instead. Run nslookup with")) || @@ -360,7 +382,7 @@ error_scan (char *input_buffer) /* Connection was refused */ else if (strstr (input_buffer, "Connection refused") || - strstr (input_buffer, "Couldn't find server") || + strstr (input_buffer, "Couldn't find server") || strstr (input_buffer, "Refused") || (strstr (input_buffer, "** server can't find") && strstr (input_buffer, ": REFUSED"))) @@ -374,13 +396,6 @@ error_scan (char *input_buffer) else if (strstr (input_buffer, "No information")) die (STATE_CRITICAL, _("No information returned by DNS server at %s\n"), dns_server); - /* Host or domain name does not exist */ - else if (strstr (input_buffer, "Non-existent") || - strstr (input_buffer, "** server can't find") || - strstr (input_buffer, "** Can't find") || - strstr (input_buffer,"NXDOMAIN")) - die (STATE_CRITICAL, _("Domain %s was not found by the server\n"), query_address); - /* Network is unreachable */ else if (strstr (input_buffer, "Network is unreachable")) die (STATE_CRITICAL, _("Network is unreachable\n")); @@ -417,6 +432,7 @@ process_arguments (int argc, char **argv) {"server", required_argument, 0, 's'}, {"reverse-server", required_argument, 0, 'r'}, {"expected-address", required_argument, 0, 'a'}, + {"expect-nxdomain", no_argument, 0, 'n'}, {"expect-authority", no_argument, 0, 'A'}, {"all", no_argument, 0, 'L'}, {"warning", required_argument, 0, 'w'}, @@ -432,7 +448,7 @@ process_arguments (int argc, char **argv) strcpy (argv[c], "-t"); while (1) { - c = getopt_long (argc, argv, "hVvALt:H:s:r:a:w:c:", long_opts, &opt_index); + c = getopt_long (argc, argv, "hVvALnt:H:s:r:a:w:c:", long_opts, &opt_index); if (c == -1 || c == EOF) break; @@ -491,6 +507,9 @@ process_arguments (int argc, char **argv) expected_address_cnt++; } break; + case 'n': /* expect NXDOMAIN */ + expect_nxdomain = TRUE; + break; case 'A': /* expect authority */ expect_authority = TRUE; break; @@ -532,8 +551,15 @@ process_arguments (int argc, char **argv) int validate_arguments () { - if (query_address[0] == 0) + if (query_address[0] == 0) { + printf ("missing --host argument\n"); + return ERROR; + } + + if (expected_address_cnt > 0 && expect_nxdomain) { + printf ("--expected-address and --expect-nxdomain cannot be combined\n"); return ERROR; + } return OK; } @@ -566,6 +592,9 @@ print_help (void) printf (" %s\n", _("Optional IP-ADDRESS/CIDR you expect the DNS server to return. HOST must end")); printf (" %s\n", _("with a dot (.). This option can be repeated multiple times (Returns OK if any")); printf (" %s\n", _("value matches).")); + printf (" -n, --expect-nxdomain\n"); + printf (" %s\n", _("Expect the DNS server to return NXDOMAIN (i.e. the domain was not found)")); + printf (" %s\n", _("Cannot be used together with -a")); printf (" -A, --expect-authority\n"); printf (" %s\n", _("Optionally expect the DNS server to be authoritative for the lookup")); printf (" -w, --warning=seconds\n"); @@ -586,5 +615,5 @@ void print_usage (void) { printf ("%s\n", _("Usage:")); - printf ("%s -H host [-s server] [-a expected-address] [-A] [-t timeout] [-w warn] [-c crit] [-L]\n", progname); + printf ("%s -H host [-s server] [-a expected-address] [-n] [-A] [-t timeout] [-w warn] [-c crit] [-L]\n", progname); } diff --git a/plugins/t/check_dns.t b/plugins/t/check_dns.t index cdfbe60d..1e7d5340 100644 --- a/plugins/t/check_dns.t +++ b/plugins/t/check_dns.t @@ -10,7 +10,7 @@ use NPTest; plan skip_all => "check_dns not compiled" unless (-x "check_dns"); -plan tests => 19; +plan tests => 23; my $successOutput = '/DNS OK: [\.0-9]+ seconds? response time/'; @@ -58,7 +58,7 @@ my $dns_server = getTestParameter( my $host_nonresponsive = getTestParameter( "NP_HOST_NONRESPONSIVE", "The hostname of system not responsive to network requests", - "10.0.0.1", + "192.0.2.0", ); my $res; @@ -105,3 +105,11 @@ cmp_ok( $res->return_code, '==', 0, "Got expected address"); $res = NPTest->testCmd("./check_dns -H $hostname_valid -a $hostname_invalid_cidr -t 5"); cmp_ok( $res->return_code, '==', 2, "Got wrong address"); like ( $res->output, "/^DNS CRITICAL.*expected '$hostname_invalid_cidr' but got '$hostname_valid_ip'".'$/', "Output OK"); + +$res = NPTest->testCmd("./check_dns -H $hostname_valid -n"); +cmp_ok( $res->return_code, '==', 2, "Found $hostname_valid"); +like ( $res->output, "/^DNS CRITICAL.*Domain '$hostname_valid' was found by the server:/", "Output OK"); + +$res = NPTest->testCmd("./check_dns -H $hostname_invalid -n"); +cmp_ok( $res->return_code, '==', 0, "Did not find $hostname_invalid"); +like ( $res->output, $successOutput, "Output OK" ); -- cgit v1.2.3-74-g34f1 From 2056c5853175e6ad0e041ff3776e10d9e612b521 Mon Sep 17 00:00:00 2001 From: Jonny007-MKD Date: Sun, 23 Feb 2020 15:05:42 +0100 Subject: check_dns: Fix memory leak --- plugins/check_dns.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_dns.c b/plugins/check_dns.c index 0c10f09b..2f944f92 100644 --- a/plugins/check_dns.c +++ b/plugins/check_dns.c @@ -271,7 +271,7 @@ main (int argc, char **argv) result = STATE_CRITICAL; xasprintf(&msg, _("Domain '%s' was found by the server: '%s'\n"), query_address, address); } else { - if (address == NULL) free(address); + if (address != NULL) free(address); address = "NXDOMAIN"; } } -- cgit v1.2.3-74-g34f1 From cfc43a327526d838db5ec81f5594df4a14319786 Mon Sep 17 00:00:00 2001 From: Jonny007-MKD Date: Mon, 24 May 2021 20:40:02 +0200 Subject: Improvements suggested by tobiaswiese --- plugins/check_dns.c | 4 ++-- plugins/t/check_dns.t | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'plugins') diff --git a/plugins/check_dns.c b/plugins/check_dns.c index 2f944f92..9de6caf5 100644 --- a/plugins/check_dns.c +++ b/plugins/check_dns.c @@ -41,7 +41,7 @@ const char *email = "devel@monitoring-plugins.org"; int process_arguments (int, char **); int validate_arguments (void); -int error_scan (char *, int*); +int error_scan (char *, int *); int ip_match_cidr(const char *, const char *); unsigned long ip2long(const char *); void print_help (void); @@ -355,7 +355,7 @@ ip2long(const char* src) { } int -error_scan (char *input_buffer, int* is_nxdomain) +error_scan (char *input_buffer, int *is_nxdomain) { const int nxdomain = strstr (input_buffer, "Non-existent") || diff --git a/plugins/t/check_dns.t b/plugins/t/check_dns.t index 1e7d5340..afb2062d 100644 --- a/plugins/t/check_dns.t +++ b/plugins/t/check_dns.t @@ -58,7 +58,7 @@ my $dns_server = getTestParameter( my $host_nonresponsive = getTestParameter( "NP_HOST_NONRESPONSIVE", "The hostname of system not responsive to network requests", - "192.0.2.0", + "10.0.0.1", ); my $res; -- cgit v1.2.3-74-g34f1 From 66e245375992c3942dbd5761f8b991e52bf5f9ab Mon Sep 17 00:00:00 2001 From: rincewind Date: Sat, 25 Sep 2021 23:24:34 +0200 Subject: Introduce new perfdata functions and stuff for using (u)int64_t --- plugins/utils.c | 120 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ plugins/utils.h | 10 +++++ 2 files changed, 130 insertions(+) (limited to 'plugins') diff --git a/plugins/utils.c b/plugins/utils.c index 348ec022..011f715d 100644 --- a/plugins/utils.c +++ b/plugins/utils.c @@ -27,6 +27,8 @@ #include "utils_base.h" #include #include +#include +#include #include @@ -239,6 +241,46 @@ is_intnonneg (char *number) return FALSE; } +/* + * Checks whether the number in the string _number_ can be put inside a int64_t + * On success the number will be written to the _target_ address, if _target_ is not set + * to NULL. + */ +bool is_int64(char *number, int64_t *target) { + errno = 0; + uint64_t tmp = strtoll(number, NULL, 10); + if (errno != 0) { + return false; + } + if (tmp < INT64_MIN || tmp > INT64_MAX) { + return false; + } + if (target != NULL) { + *target = tmp; + } + return true; +} + +/* + * Checks whether the number in the string _number_ can be put inside a uint64_t + * On success the number will be written to the _target_ address, if _target_ is not set + * to NULL. + */ +bool is_uint64(char *number, uint64_t *target) { + errno = 0; + uint64_t tmp = strtoll(number, NULL, 10); + if (errno != 0) { + return false; + } + if (tmp < 0 || tmp > UINT64_MAX) { + return false; + } + if (target != NULL) { + *target = tmp; + } + return true; +} + int is_intpercent (char *number) { @@ -556,6 +598,84 @@ char *perfdata (const char *label, } +char *perfdata_uint64 (const char *label, + uint64_t val, + const char *uom, + int warnp, + uint64_t warn, + int critp, + uint64_t crit, + int minp, + uint64_t minv, + int maxp, + uint64_t maxv) +{ + char *data = NULL; + + if (strpbrk (label, "'= ")) + xasprintf (&data, "'%s'=%ld%s;", label, val, uom); + else + xasprintf (&data, "%s=%ld%s;", label, val, uom); + + if (warnp) + xasprintf (&data, "%s%ld;", data, warn); + else + xasprintf (&data, "%s;", data); + + if (critp) + xasprintf (&data, "%s%ld;", data, crit); + else + xasprintf (&data, "%s;", data); + + if (minp) + xasprintf (&data, "%s%ld", data, minv); + + if (maxp) + xasprintf (&data, "%s;%ld", data, maxv); + + return data; +} + + +char *perfdata_int64 (const char *label, + int64_t val, + const char *uom, + int warnp, + int64_t warn, + int critp, + int64_t crit, + int minp, + int64_t minv, + int maxp, + int64_t maxv) +{ + char *data = NULL; + + if (strpbrk (label, "'= ")) + xasprintf (&data, "'%s'=%ld%s;", label, val, uom); + else + xasprintf (&data, "%s=%ld%s;", label, val, uom); + + if (warnp) + xasprintf (&data, "%s%ld;", data, warn); + else + xasprintf (&data, "%s;", data); + + if (critp) + xasprintf (&data, "%s%ld;", data, crit); + else + xasprintf (&data, "%s;", data); + + if (minp) + xasprintf (&data, "%s%ld", data, minv); + + if (maxp) + xasprintf (&data, "%s;%ld", data, maxv); + + return data; +} + + char *fperfdata (const char *label, double val, const char *uom, diff --git a/plugins/utils.h b/plugins/utils.h index 33a20547..91a9c3f9 100644 --- a/plugins/utils.h +++ b/plugins/utils.h @@ -16,6 +16,9 @@ suite of plugins. */ /* now some functions etc are being defined in ../lib/utils_base.c */ #include "utils_base.h" + +#include + #ifdef NP_EXTRA_OPTS /* Include extra-opts functions if compiled in */ #include "extra_opts.h" @@ -38,6 +41,7 @@ int is_intpos (char *); int is_intneg (char *); int is_intnonneg (char *); int is_intpercent (char *); +bool is_uint64(char *number, uint64_t *target); int is_numeric (char *); int is_positive (char *); @@ -88,6 +92,12 @@ void usage_va(const char *fmt, ...) __attribute__((noreturn)); char *perfdata (const char *, long int, const char *, int, long int, int, long int, int, long int, int, long int); +char *perfdata_uint64 (const char *, uint64_t , const char *, int, uint64_t, + int, uint64_t, int, uint64_t, int, uint64_t); + +char *perfdata_int64 (const char *, int64_t, const char *, int, int64_t, + int, int64_t, int, int64_t, int, int64_t); + char *fperfdata (const char *, double, const char *, int, double, int, double, int, double, int, double); -- cgit v1.2.3-74-g34f1 From 4621427ba8cbfab4815e65d35a728ad51ad8c391 Mon Sep 17 00:00:00 2001 From: rincewind Date: Sat, 25 Sep 2021 23:24:45 +0200 Subject: check_swap: Fix perfdata und thresholds for big values and simplify code The original problem was https://github.com/monitoring-plugins/monitoring-plugins/pull/1705 where the performance data output of check_swap did not conform to the parser logic of a monitoring system (which decided to go for "correct" SI or IEC units. The PR was accompanied by a change to byte values in the performance data which broke the _perfdata_ helper function which could not handle values of this size. The fix for this, was to use _fperfdata_ which could, but would use float values. I didn't like that (since all values here are discreet) and this is my proposal for a fix for the problem. It introduces some helper functions which do now explicitely work with (u)int64_t, including a special version of the _perfdata_ helper. In the process of introducing this to check_swap, I stumbled over several sections of the check_swap code which I found problematic. Therefore I tried to simplify the code and make it more readable and less redundant. I am kinda sorry about this, but sincerely hope my changes can be helpful. --- plugins/check_swap.c | 239 +++++++++++++++++++++++++++++---------------------- 1 file changed, 137 insertions(+), 102 deletions(-) (limited to 'plugins') diff --git a/plugins/check_swap.c b/plugins/check_swap.c index 0ff0c770..25bcb3d5 100644 --- a/plugins/check_swap.c +++ b/plugins/check_swap.c @@ -34,6 +34,10 @@ const char *email = "devel@monitoring-plugins.org"; #include "common.h" #include "popen.h" #include "utils.h" +#include +#include +#include +#include #ifdef HAVE_DECL_SWAPCTL # ifdef HAVE_SYS_PARAM_H @@ -51,26 +55,30 @@ const char *email = "devel@monitoring-plugins.org"; # define SWAP_CONVERSION 1 #endif -int check_swap (int usp, float free_swap_mb, float total_swap_mb); +typedef struct { + bool is_percentage; + uint64_t value; +} threshold_t; + +int check_swap (float free_swap_mb, float total_swap_mb); int process_arguments (int argc, char **argv); int validate_arguments (void); void print_usage (void); void print_help (void); -int warn_percent = 0; -int crit_percent = 0; -float warn_size_bytes = 0; -float crit_size_bytes = 0; +threshold_t warn; +threshold_t crit; int verbose; -int allswaps; +bool allswaps; int no_swap_state = STATE_CRITICAL; int main (int argc, char **argv) { - int percent_used, percent; - float total_swap_mb = 0, used_swap_mb = 0, free_swap_mb = 0; - float dsktotal_mb = 0, dskused_mb = 0, dskfree_mb = 0, tmp_mb = 0; + unsigned int percent_used, percent; + uint64_t total_swap_mb = 0, used_swap_mb = 0, free_swap_mb = 0; + uint64_t dsktotal_mb = 0, dskused_mb = 0, dskfree_mb = 0; + uint64_t tmp_KB = 0; int result = STATE_UNKNOWN; char input_buffer[MAX_INPUT_BUFFER]; #ifdef HAVE_PROC_MEMINFO @@ -116,10 +124,15 @@ main (int argc, char **argv) } fp = fopen (PROC_MEMINFO, "r"); while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) { - if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%*[:] %f %f %f", &dsktotal_mb, &dskused_mb, &dskfree_mb) == 3) { - dsktotal_mb = dsktotal_mb / 1048576; /* Apply conversion */ - dskused_mb = dskused_mb / 1048576; - dskfree_mb = dskfree_mb / 1048576; + /* + * The following sscanf call looks for a line looking like: "Swap: 123 123 123" + * On which kind of system this format exists, I can not say, but I wanted to + * document this for people who are not adapt with sscanf anymore, like me + */ + if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%*[:] %lu %lu %lu", &dsktotal_mb, &dskused_mb, &dskfree_mb) == 3) { + dsktotal_mb = dsktotal_mb / (1024 * 1024); /* Apply conversion */ + dskused_mb = dskused_mb / (1024 * 1024); + dskfree_mb = dskfree_mb / (1024 * 1024); total_swap_mb += dsktotal_mb; used_swap_mb += dskused_mb; free_swap_mb += dskfree_mb; @@ -128,21 +141,25 @@ main (int argc, char **argv) percent=100.0; else percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb)); - result = max_state (result, check_swap (percent, dskfree_mb, dsktotal_mb)); + result = max_state (result, check_swap (dskfree_mb, dsktotal_mb)); if (verbose) xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent); } } - else if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%[TotalFre]%*[:] %f %*[k]%*[B]", str, &tmp_mb)) { + /* + * The following sscanf call looks for lines looking like: "SwapTotal: 123" and "SwapFree: 123" + * This format exists at least on Debian Linux with a 5.* kernel + */ + else if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%[TotalFre]%*[:] %lu %*[k]%*[B]", str, &tmp_KB)) { if (verbose >= 3) { - printf("Got %s with %f\n", str, tmp_mb); + printf("Got %s with %lu\n", str, tmp_KB); } /* I think this part is always in Kb, so convert to mb */ if (strcmp ("Total", str) == 0) { - dsktotal_mb = tmp_mb / 1024; + dsktotal_mb = tmp_KB / 1024; } else if (strcmp ("Free", str) == 0) { - dskfree_mb = tmp_mb / 1024; + dskfree_mb = tmp_KB / 1024; } } } @@ -227,7 +244,7 @@ main (int argc, char **argv) free_swap_mb += dskfree_mb; if (allswaps) { percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb)); - result = max_state (result, check_swap (percent, dskfree_mb, dsktotal_mb)); + result = max_state (result, check_swap (dskfree_mb, dsktotal_mb)); if (verbose) xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent); } @@ -289,7 +306,7 @@ main (int argc, char **argv) if(allswaps && dsktotal_mb > 0){ percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb)); - result = max_state (result, check_swap (percent, dskfree_mb, dsktotal_mb)); + result = max_state (result, check_swap (dskfree_mb, dsktotal_mb)); if (verbose) { xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent); } @@ -328,7 +345,7 @@ main (int argc, char **argv) if(allswaps && dsktotal_mb > 0){ percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb)); - result = max_state (result, check_swap (percent, dskfree_mb, dsktotal_mb)); + result = max_state (result, check_swap(dskfree_mb, dsktotal_mb)); if (verbose) { xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent); } @@ -355,14 +372,19 @@ main (int argc, char **argv) status = "- Swap is either disabled, not present, or of zero size. "; } - result = max_state (result, check_swap (percent_used, free_swap_mb, total_swap_mb)); - printf (_("SWAP %s - %d%% free (%d MB out of %d MB) %s|"), + result = max_state (result, check_swap(free_swap_mb, total_swap_mb)); + printf (_("SWAP %s - %d%% free (%dMB out of %dMB) %s|"), state_text (result), (100 - percent_used), (int) free_swap_mb, (int) total_swap_mb, status); - puts (perfdata ("swap", (long) free_swap_mb, "MB", - TRUE, (long) max (warn_size_bytes/(1024 * 1024), warn_percent/100.0*total_swap_mb), - TRUE, (long) max (crit_size_bytes/(1024 * 1024), crit_percent/100.0*total_swap_mb), + uint64_t warn_print = warn.value; + if (warn.is_percentage) warn_print = warn.value * (total_swap_mb *1024 *1024/100); + uint64_t crit_print = crit.value; + if (crit.is_percentage) crit_print = crit.value * (total_swap_mb *1024 *1024/100); + + puts (perfdata_uint64 ("swap", free_swap_mb *1024 *1024, "B", + TRUE, warn_print, + TRUE, crit_print, TRUE, 0, TRUE, (long) total_swap_mb)); @@ -370,26 +392,37 @@ main (int argc, char **argv) } - int -check_swap (int usp, float free_swap_mb, float total_swap_mb) +check_swap(float free_swap_mb, float total_swap_mb) { if (!total_swap_mb) return no_swap_state; - int result = STATE_UNKNOWN; - float free_swap = free_swap_mb * (1024 * 1024); /* Convert back to bytes as warn and crit specified in bytes */ - if (usp >= 0 && crit_percent != 0 && usp >= (100.0 - crit_percent)) - result = STATE_CRITICAL; - else if (crit_size_bytes > 0 && free_swap <= crit_size_bytes) - result = STATE_CRITICAL; - else if (usp >= 0 && warn_percent != 0 && usp >= (100.0 - warn_percent)) - result = STATE_WARNING; - else if (warn_size_bytes > 0 && free_swap <= warn_size_bytes) - result = STATE_WARNING; - else if (usp >= 0.0) - result = STATE_OK; - return result; + uint64_t free_swap = free_swap_mb * (1024 * 1024); /* Convert back to bytes as warn and crit specified in bytes */ + + if (!crit.is_percentage && crit.value <= free_swap) return STATE_CRITICAL; + if (!warn.is_percentage && warn.value <= free_swap) return STATE_WARNING; + + + uint64_t usage_percentage = ((total_swap_mb - free_swap_mb) / total_swap_mb) * 100; + + if (crit.is_percentage && + usage_percentage >= 0 && + crit.value != 0 && + usage_percentage >= (100 - crit.value)) + { + return STATE_CRITICAL; + } + + if (warn.is_percentage && + usage_percentage >= 0 && + warn.value != 0 && + usage_percentage >= (100 - warn.value)) + { + return STATE_WARNING; + } + + return STATE_OK; } @@ -422,42 +455,67 @@ process_arguments (int argc, char **argv) break; switch (c) { - case 'w': /* warning size threshold */ - if (is_intnonneg (optarg)) { - warn_size_bytes = (float) atoi (optarg); - break; - } - else if (strstr (optarg, ",") && - strstr (optarg, "%") && - sscanf (optarg, "%f,%d%%", &warn_size_bytes, &warn_percent) == 2) { - warn_size_bytes = floorf(warn_size_bytes); - break; - } - else if (strstr (optarg, "%") && - sscanf (optarg, "%d%%", &warn_percent) == 1) { - break; - } - else { - usage4 (_("Warning threshold must be integer or percentage!")); - } - case 'c': /* critical size threshold */ - if (is_intnonneg (optarg)) { - crit_size_bytes = (float) atoi (optarg); - break; - } - else if (strstr (optarg, ",") && - strstr (optarg, "%") && - sscanf (optarg, "%f,%d%%", &crit_size_bytes, &crit_percent) == 2) { - crit_size_bytes = floorf(crit_size_bytes); - break; - } - else if (strstr (optarg, "%") && - sscanf (optarg, "%d%%", &crit_percent) == 1) { - break; - } - else { - usage4 (_("Critical threshold must be integer or percentage!")); + case 'w': /* warning size threshold */ + { + /* + * We expect either a positive integer value without a unit, which means + * the unit is Bytes or a positive integer value and a percentage sign (%), + * which means the value must be with 0 and 100 and is relative to the total swap + */ + size_t length; + length = strlen(optarg); + + if (optarg[length - 1] == '%') { + // It's percentage! + warn.is_percentage = true; + optarg[length - 1] = '\0'; + if (is_uint64(optarg, &warn.value)) { + if (warn.value > 100) { + usage4 (_("Warning threshold percentage must be <= 100!")); + } else { + break; + } + } + } else { + // It's Bytes + warn.is_percentage = false; + if (is_uint64(optarg, &warn.value)) { + break; + } else { + usage4 (_("Warning threshold be positive integer or percentage!")); + } + } } + case 'c': /* critical size threshold */ + { + /* + * We expect either a positive integer value without a unit, which means + * the unit is Bytes or a positive integer value and a percentage sign (%), + * which means the value must be with 0 and 100 and is relative to the total swap + */ + size_t length; + length = strlen(optarg); + + if (optarg[length - 1] == '%') { + // It's percentage! + crit.is_percentage = true; + optarg[length - 1] = '\0'; + if (is_uint64(optarg, &crit.value)) { + if (crit.value> 100) { + usage4 (_("Critical threshold percentage must be <= 100!")); + } else { + break; + } + } + } else { + crit.is_percentage = false; + if (is_uint64(optarg, &crit.value)) { + break; + } else { + usage4 (_("Critical threshold be positive integer or percentage!")); + } + } + } case 'a': /* all swap */ allswaps = TRUE; break; @@ -482,23 +540,6 @@ process_arguments (int argc, char **argv) c = optind; if (c == argc) return validate_arguments (); - if (warn_percent == 0 && is_intnonneg (argv[c])) - warn_percent = atoi (argv[c++]); - - if (c == argc) - return validate_arguments (); - if (crit_percent == 0 && is_intnonneg (argv[c])) - crit_percent = atoi (argv[c++]); - - if (c == argc) - return validate_arguments (); - if (warn_size_bytes == 0 && is_intnonneg (argv[c])) - warn_size_bytes = (float) atoi (argv[c++]); - - if (c == argc) - return validate_arguments (); - if (crit_size_bytes == 0 && is_intnonneg (argv[c])) - crit_size_bytes = (float) atoi (argv[c++]); return validate_arguments (); } @@ -508,17 +549,12 @@ process_arguments (int argc, char **argv) int validate_arguments (void) { - if (warn_percent == 0 && crit_percent == 0 && warn_size_bytes == 0 - && crit_size_bytes == 0) { + if (warn.value == 0 && crit.value == 0) { return ERROR; } - else if (warn_percent < crit_percent) { - usage4 - (_("Warning percentage should be more than critical percentage")); - } - else if (warn_size_bytes < crit_size_bytes) { + else if (warn.value < crit.value) { usage4 - (_("Warning free space should be more than critical free space")); + (_("Warning should be more than critical")); } return OK; } @@ -564,7 +600,6 @@ print_help (void) } - void print_usage (void) { -- cgit v1.2.3-74-g34f1 From 280ae58ed8e340f8096cf37f60c84f99d6723537 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Sun, 26 Sep 2021 00:34:44 +0200 Subject: Remove spaces from tests --- plugins/t/check_swap.t | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'plugins') diff --git a/plugins/t/check_swap.t b/plugins/t/check_swap.t index e44adc90..de9e0f05 100644 --- a/plugins/t/check_swap.t +++ b/plugins/t/check_swap.t @@ -8,9 +8,9 @@ use strict; use Test::More tests => 8; use NPTest; -my $successOutput = '/^SWAP OK - [0-9]+\% free \([0-9]+ MB out of [0-9]+ MB\)/'; -my $failureOutput = '/^SWAP CRITICAL - [0-9]+\% free \([0-9]+ MB out of [0-9]+ MB\)/'; -my $warnOutput = '/^SWAP WARNING - [0-9]+\% free \([0-9]+ MB out of [0-9]+ MB\)/'; +my $successOutput = '/^SWAP OK - [0-9]+\% free \([0-9]+MB out of [0-9]+MB\)/'; +my $failureOutput = '/^SWAP CRITICAL - [0-9]+\% free \([0-9]+MB out of [0-9]+MB\)/'; +my $warnOutput = '/^SWAP WARNING - [0-9]+\% free \([0-9]+MB out of [0-9]+MB\)/'; my $result; -- cgit v1.2.3-74-g34f1 From f55ea7632f4284a0b8858361270337bd9fde9a60 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Sun, 26 Sep 2021 01:34:45 +0200 Subject: Fix comparing logic --- plugins/check_swap.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_swap.c b/plugins/check_swap.c index 25bcb3d5..6dec9b28 100644 --- a/plugins/check_swap.c +++ b/plugins/check_swap.c @@ -400,8 +400,8 @@ check_swap(float free_swap_mb, float total_swap_mb) uint64_t free_swap = free_swap_mb * (1024 * 1024); /* Convert back to bytes as warn and crit specified in bytes */ - if (!crit.is_percentage && crit.value <= free_swap) return STATE_CRITICAL; - if (!warn.is_percentage && warn.value <= free_swap) return STATE_WARNING; + if (!crit.is_percentage && crit.value >= free_swap) return STATE_CRITICAL; + if (!warn.is_percentage && warn.value >= free_swap) return STATE_WARNING; uint64_t usage_percentage = ((total_swap_mb - free_swap_mb) / total_swap_mb) * 100; -- cgit v1.2.3-74-g34f1 From d2f2da175eda5a06291a974d971968a1241d7935 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Sat, 2 Oct 2021 12:47:50 +0200 Subject: Change all to comments to old comment style --- plugins/check_swap.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'plugins') diff --git a/plugins/check_swap.c b/plugins/check_swap.c index 6dec9b28..4d124a35 100644 --- a/plugins/check_swap.c +++ b/plugins/check_swap.c @@ -466,7 +466,7 @@ process_arguments (int argc, char **argv) length = strlen(optarg); if (optarg[length - 1] == '%') { - // It's percentage! + /* It's percentage */ warn.is_percentage = true; optarg[length - 1] = '\0'; if (is_uint64(optarg, &warn.value)) { @@ -477,7 +477,7 @@ process_arguments (int argc, char **argv) } } } else { - // It's Bytes + /* It's Bytes */ warn.is_percentage = false; if (is_uint64(optarg, &warn.value)) { break; @@ -497,7 +497,7 @@ process_arguments (int argc, char **argv) length = strlen(optarg); if (optarg[length - 1] == '%') { - // It's percentage! + /* It's percentage */ crit.is_percentage = true; optarg[length - 1] = '\0'; if (is_uint64(optarg, &crit.value)) { @@ -508,6 +508,7 @@ process_arguments (int argc, char **argv) } } } else { + /* It's Bytes */ crit.is_percentage = false; if (is_uint64(optarg, &crit.value)) { break; -- cgit v1.2.3-74-g34f1 From 46c5327e348540ab04dc37d42f6d1c5408179fa6 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Sat, 2 Oct 2021 23:37:12 +0200 Subject: Revert to poor man's logic --- plugins/check_swap.c | 13 ++++++------- plugins/utils.c | 16 ++++++++-------- plugins/utils.h | 5 ++--- 3 files changed, 16 insertions(+), 18 deletions(-) (limited to 'plugins') diff --git a/plugins/check_swap.c b/plugins/check_swap.c index 4d124a35..685c2cc5 100644 --- a/plugins/check_swap.c +++ b/plugins/check_swap.c @@ -37,7 +37,6 @@ const char *email = "devel@monitoring-plugins.org"; #include #include #include -#include #ifdef HAVE_DECL_SWAPCTL # ifdef HAVE_SYS_PARAM_H @@ -56,7 +55,7 @@ const char *email = "devel@monitoring-plugins.org"; #endif typedef struct { - bool is_percentage; + int is_percentage; uint64_t value; } threshold_t; @@ -69,7 +68,7 @@ void print_help (void); threshold_t warn; threshold_t crit; int verbose; -bool allswaps; +int allswaps; int no_swap_state = STATE_CRITICAL; int @@ -467,7 +466,7 @@ process_arguments (int argc, char **argv) if (optarg[length - 1] == '%') { /* It's percentage */ - warn.is_percentage = true; + warn.is_percentage = 1; optarg[length - 1] = '\0'; if (is_uint64(optarg, &warn.value)) { if (warn.value > 100) { @@ -478,7 +477,7 @@ process_arguments (int argc, char **argv) } } else { /* It's Bytes */ - warn.is_percentage = false; + warn.is_percentage = 0; if (is_uint64(optarg, &warn.value)) { break; } else { @@ -498,7 +497,7 @@ process_arguments (int argc, char **argv) if (optarg[length - 1] == '%') { /* It's percentage */ - crit.is_percentage = true; + crit.is_percentage = 1; optarg[length - 1] = '\0'; if (is_uint64(optarg, &crit.value)) { if (crit.value> 100) { @@ -509,7 +508,7 @@ process_arguments (int argc, char **argv) } } else { /* It's Bytes */ - crit.is_percentage = false; + crit.is_percentage = 0; if (is_uint64(optarg, &crit.value)) { break; } else { diff --git a/plugins/utils.c b/plugins/utils.c index 011f715d..f7f8952f 100644 --- a/plugins/utils.c +++ b/plugins/utils.c @@ -246,19 +246,19 @@ is_intnonneg (char *number) * On success the number will be written to the _target_ address, if _target_ is not set * to NULL. */ -bool is_int64(char *number, int64_t *target) { +int is_int64(char *number, int64_t *target) { errno = 0; uint64_t tmp = strtoll(number, NULL, 10); if (errno != 0) { - return false; + return 0; } if (tmp < INT64_MIN || tmp > INT64_MAX) { - return false; + return 0; } if (target != NULL) { *target = tmp; } - return true; + return 1; } /* @@ -266,19 +266,19 @@ bool is_int64(char *number, int64_t *target) { * On success the number will be written to the _target_ address, if _target_ is not set * to NULL. */ -bool is_uint64(char *number, uint64_t *target) { +int is_uint64(char *number, uint64_t *target) { errno = 0; uint64_t tmp = strtoll(number, NULL, 10); if (errno != 0) { - return false; + return 0; } if (tmp < 0 || tmp > UINT64_MAX) { - return false; + return 0; } if (target != NULL) { *target = tmp; } - return true; + return 1; } int diff --git a/plugins/utils.h b/plugins/utils.h index 91a9c3f9..5b54da3c 100644 --- a/plugins/utils.h +++ b/plugins/utils.h @@ -17,8 +17,6 @@ suite of plugins. */ #include "utils_base.h" -#include - #ifdef NP_EXTRA_OPTS /* Include extra-opts functions if compiled in */ #include "extra_opts.h" @@ -41,7 +39,8 @@ int is_intpos (char *); int is_intneg (char *); int is_intnonneg (char *); int is_intpercent (char *); -bool is_uint64(char *number, uint64_t *target); +int is_uint64(char *number, uint64_t *target); +int is_int64(char *number, int64_t *target); int is_numeric (char *); int is_positive (char *); -- cgit v1.2.3-74-g34f1 From a08215368e5f9dc0164fcce9f5591c5310fdeb8c Mon Sep 17 00:00:00 2001 From: Harald Jenny Date: Mon, 5 Jul 2021 10:29:09 +0200 Subject: Create check_load.c just a cosmetic fix so the load plugin display a LOAD prefix before check results --- plugins/check_load.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_load.c b/plugins/check_load.c index bf7b94b4..0e4de54e 100644 --- a/plugins/check_load.c +++ b/plugins/check_load.c @@ -209,7 +209,7 @@ main (int argc, char **argv) else if(la[i] > wload[i]) result = STATE_WARNING; } - printf("%s - %s|", state_text(result), status_line); + printf("LOAD %s - %s|", state_text(result), status_line); for(i = 0; i < 3; i++) printf("load%d=%.3f;%.3f;%.3f;0; ", nums[i], la[i], wload[i], cload[i]); -- cgit v1.2.3-74-g34f1 From e79ada81a696e3c826b383e3ff7cbc8f91bf46a4 Mon Sep 17 00:00:00 2001 From: Harald Jenny Date: Mon, 5 Jul 2021 10:30:39 +0200 Subject: Update check_load.t adjust tests for new plugin output --- plugins/t/check_load.t | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/t/check_load.t b/plugins/t/check_load.t index 55f6f752..60837ef6 100644 --- a/plugins/t/check_load.t +++ b/plugins/t/check_load.t @@ -11,8 +11,8 @@ use NPTest; my $res; my $loadValue = "[0-9]+\.?[0-9]+"; -my $successOutput = "/^OK - load average: $loadValue, $loadValue, $loadValue/"; -my $failureOutput = "/^CRITICAL - load average: $loadValue, $loadValue, $loadValue/"; +my $successOutput = "/^LOAD OK - load average: $loadValue, $loadValue, $loadValue/"; +my $failureOutput = "/^LOAD CRITICAL - load average: $loadValue, $loadValue, $loadValue/"; plan tests => 11; -- cgit v1.2.3-74-g34f1 From 078c69d2ddf6b7dd2dfef5ca0f3013a723ec0268 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 25 Oct 2021 17:34:13 +0200 Subject: Recognice IEC binary units and format accordingly to base2 (always) --- plugins/check_disk.c | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) (limited to 'plugins') diff --git a/plugins/check_disk.c b/plugins/check_disk.c index a2735195..07862283 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -574,21 +574,24 @@ process_arguments (int argc, char **argv) case 'u': if (units) free(units); - if (! strcmp (optarg, "bytes")) { + if (! strcasecmp (optarg, "bytes")) { mult = (uintmax_t)1; units = strdup ("B"); - } else if (! strcmp (optarg, "kB")) { + } else if ( (! strcmp (optarg, "kB")) || (!strcmp(optarg, "KiB")) ) { mult = (uintmax_t)1024; - units = strdup ("kB"); - } else if (! strcmp (optarg, "MB")) { + units = strdup ("kiB"); + } else if ( (! strcmp (optarg, "MB")) || (!strcmp(optarg, "MiB")) ) { mult = (uintmax_t)1024 * 1024; - units = strdup ("MB"); - } else if (! strcmp (optarg, "GB")) { + units = strdup ("MiB"); + } else if ( (! strcmp (optarg, "GB")) || (!strcmp(optarg, "GiB")) ) { mult = (uintmax_t)1024 * 1024 * 1024; - units = strdup ("GB"); - } else if (! strcmp (optarg, "TB")) { + units = strdup ("GiB"); + } else if ( (! strcmp (optarg, "TB")) || (!strcmp(optarg, "TiB")) ) { mult = (uintmax_t)1024 * 1024 * 1024 * 1024; - units = strdup ("TB"); + units = strdup ("TiB"); + } else if ( (! strcmp (optarg, "PB")) || (!strcmp(optarg, "PiB")) ) { + mult = (uintmax_t)1024 * 1024 * 1024 * 1024 * 1024; + units = strdup ("PiB"); } else { die (STATE_UNKNOWN, _("unit type %s not known\n"), optarg); } @@ -599,13 +602,13 @@ process_arguments (int argc, char **argv) mult = 1024; if (units) free(units); - units = strdup ("kB"); + units = strdup ("kiB"); break; case 'm': /* display mountpoint */ mult = 1024 * 1024; if (units) free(units); - units = strdup ("MB"); + units = strdup ("MiB"); break; case 'L': stat_remote_fs = 1; @@ -812,7 +815,7 @@ process_arguments (int argc, char **argv) } if (units == NULL) { - units = strdup ("MB"); + units = strdup ("MiB"); mult = (uintmax_t)1024 * 1024; } -- cgit v1.2.3-74-g34f1 From 8f2cfd1c805f68a21e221f9ea629800be1c88af8 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 25 Oct 2021 17:35:29 +0200 Subject: Reformat a little bit for easier reading --- plugins/check_disk.c | 48 ++++++++++++++++++++++++++++++++---------------- 1 file changed, 32 insertions(+), 16 deletions(-) (limited to 'plugins') diff --git a/plugins/check_disk.c b/plugins/check_disk.c index 07862283..00afcad2 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -288,8 +288,17 @@ main (int argc, char **argv) get_stats (path, &fsp); if (verbose >= 3) { - printf ("For %s, used_pct=%g free_pct=%g used_units=%g free_units=%g total_units=%g used_inodes_pct=%g free_inodes_pct=%g fsp.fsu_blocksize=%llu mult=%llu\n", - me->me_mountdir, path->dused_pct, path->dfree_pct, path->dused_units, path->dfree_units, path->dtotal_units, path->dused_inodes_percent, path->dfree_inodes_percent, fsp.fsu_blocksize, mult); + printf ("For %s, used_pct=%g free_pct=%g used_units=%llu free_units=%llu total_units=%llu used_inodes_pct=%g free_inodes_pct=%g fsp.fsu_blocksize=%llu mult=%llu\n", + me->me_mountdir, + path->dused_pct, + path->dfree_pct, + path->dused_units, + path->dfree_units, + path->dtotal_units, + path->dused_inodes_percent, + path->dfree_inodes_percent, + fsp.fsu_blocksize, + mult); } /* Threshold comparisons */ @@ -344,12 +353,13 @@ main (int argc, char **argv) /* Nb: *_high_tide are unset when == UINT_MAX */ xasprintf (&perf, "%s %s", perf, - perfdata ((!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, - path->dused_units, units, - (warning_high_tide != UINT_MAX ? TRUE : FALSE), warning_high_tide, - (critical_high_tide != UINT_MAX ? TRUE : FALSE), critical_high_tide, - TRUE, 0, - TRUE, path->dtotal_units)); + perfdata_uint64 ( + (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, + path->dused_units * mult, "B", + (warning_high_tide == UINT64_MAX ? FALSE : TRUE), warning_high_tide * mult, + (critical_high_tide == UINT64_MAX ? FALSE : TRUE), critical_high_tide * mult, + TRUE, 0, + TRUE, path->dtotal_units * mult)); if (display_inodes_perfdata) { /* *_high_tide must be reinitialized at each run */ @@ -366,12 +376,12 @@ main (int argc, char **argv) xasprintf (&perf_ilabel, "%s (inodes)", (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir); /* Nb: *_high_tide are unset when == UINT_MAX */ xasprintf (&perf, "%s %s", perf, - perfdata (perf_ilabel, - path->inodes_used, "", - (warning_high_tide != UINT_MAX ? TRUE : FALSE), warning_high_tide, - (critical_high_tide != UINT_MAX ? TRUE : FALSE), critical_high_tide, - TRUE, 0, - TRUE, path->inodes_total)); + perfdata_uint64 (perf_ilabel, + path->inodes_used, "", + (warning_high_tide != UINT64_MAX ? TRUE : FALSE), warning_high_tide, + (critical_high_tide != UINT64_MAX ? TRUE : FALSE), critical_high_tide, + TRUE, 0, + TRUE, path->inodes_total)); } if (disk_result==STATE_OK && erronly && !verbose) @@ -1055,8 +1065,14 @@ get_stats (struct parameter_list *p, struct fs_usage *fsp) { } if (verbose >= 3) printf("Group %s now has: used_units=%g free_units=%g total_units=%g fsu_blocksize=%llu mult=%llu\n", - p->group, tmpfsp.fsu_bavail, tmpfsp.fsu_blocksize, p->best_match->me_mountdir, p->dused_units, - p->dfree_units, p->dtotal_units, mult); + p->group, + tmpfsp.fsu_bavail, + tmpfsp.fsu_blocksize, + p->best_match->me_mountdir, + p->dused_units, + p->dfree_units, + p->dtotal_units, + mult); } /* modify devname and mountdir for output */ p->best_match->me_mountdir = p->best_match->me_devname = p->group; -- cgit v1.2.3-74-g34f1 From 50fc9b73a2127c8ed1944b8e3fd5f0f7b64ca8ec Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 25 Oct 2021 17:36:58 +0200 Subject: Switch to uint64_t --- lib/utils_disk.h | 2 +- plugins/check_disk.c | 24 +++++++++++------------- 2 files changed, 12 insertions(+), 14 deletions(-) (limited to 'plugins') diff --git a/lib/utils_disk.h b/lib/utils_disk.h index 999270cd..bf52e4ce 100644 --- a/lib/utils_disk.h +++ b/lib/utils_disk.h @@ -27,7 +27,7 @@ struct parameter_list uintmax_t total, available, available_to_root, used, inodes_free, inodes_free_to_root, inodes_used, inodes_total; double dfree_pct, dused_pct; - double dused_units, dfree_units, dtotal_units; + uint64_t dused_units, dfree_units, dtotal_units; double dused_inodes_percent, dfree_inodes_percent; }; diff --git a/plugins/check_disk.c b/plugins/check_disk.c index 00afcad2..ecde4e59 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -172,8 +172,6 @@ main (int argc, char **argv) char *preamble; char *flag_header; double inode_space_pct; - double warning_high_tide; - double critical_high_tide; int temp_result; struct mount_entry *me; @@ -335,23 +333,23 @@ main (int argc, char **argv) */ /* *_high_tide must be reinitialized at each run */ - warning_high_tide = UINT_MAX; - critical_high_tide = UINT_MAX; + uint64_t warning_high_tide = UINT64_MAX; + uint64_t critical_high_tide = UINT64_MAX; if (path->freespace_units->warning != NULL) { warning_high_tide = path->dtotal_units - path->freespace_units->warning->end; } if (path->freespace_percent->warning != NULL) { - warning_high_tide = abs( min( (double) warning_high_tide, (double) (1.0 - path->freespace_percent->warning->end/100)*path->dtotal_units )); + warning_high_tide = llabs( min( (double) warning_high_tide, (1.0 - path->freespace_percent->warning->end / 100 * path->dtotal_units) )); } if (path->freespace_units->critical != NULL) { critical_high_tide = path->dtotal_units - path->freespace_units->critical->end; } if (path->freespace_percent->critical != NULL) { - critical_high_tide = abs( min( (double) critical_high_tide, (double) (1.0 - path->freespace_percent->critical->end/100)*path->dtotal_units )); + critical_high_tide = llabs( min( (double) critical_high_tide, (double) (1.0 - path->freespace_percent->critical->end/100)*path->dtotal_units )); } - /* Nb: *_high_tide are unset when == UINT_MAX */ + /* Nb: *_high_tide are unset when == UINT64_MAX */ xasprintf (&perf, "%s %s", perf, perfdata_uint64 ( (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, @@ -363,18 +361,18 @@ main (int argc, char **argv) if (display_inodes_perfdata) { /* *_high_tide must be reinitialized at each run */ - warning_high_tide = UINT_MAX; - critical_high_tide = UINT_MAX; + warning_high_tide = UINT64_MAX; + critical_high_tide = UINT64_MAX; if (path->freeinodes_percent->warning != NULL) { - warning_high_tide = abs( min( (double) warning_high_tide, (double) (1.0 - path->freeinodes_percent->warning->end/100)*path->inodes_total )); + warning_high_tide = llabs( min( (double) warning_high_tide, (double) (1.0 - path->freeinodes_percent->warning->end/100)*path->inodes_total )); } if (path->freeinodes_percent->critical != NULL) { - critical_high_tide = abs( min( (double) critical_high_tide, (double) (1.0 - path->freeinodes_percent->critical->end/100)*path->inodes_total )); + critical_high_tide = llabs( min( (double) critical_high_tide, (double) (1.0 - path->freeinodes_percent->critical->end/100)*path->inodes_total )); } xasprintf (&perf_ilabel, "%s (inodes)", (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir); - /* Nb: *_high_tide are unset when == UINT_MAX */ + /* Nb: *_high_tide are unset when == UINT64_MAX */ xasprintf (&perf, "%s %s", perf, perfdata_uint64 (perf_ilabel, path->inodes_used, "", @@ -392,7 +390,7 @@ main (int argc, char **argv) } else { xasprintf(&flag_header, ""); } - xasprintf (&output, "%s%s %s %.0f %s (%.0f%%", + xasprintf (&output, "%s%s %s %llu%s (%.0f%%", output, flag_header, (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, path->dfree_units, -- cgit v1.2.3-74-g34f1 From d3af7a353e75dadf283c58ad49cfe2dc81a4c9ce Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 25 Oct 2021 17:42:00 +0200 Subject: Remove useless lines and fix some formatting --- plugins/utils.c | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) (limited to 'plugins') diff --git a/plugins/utils.c b/plugins/utils.c index f7f8952f..ff0e55d4 100644 --- a/plugins/utils.c +++ b/plugins/utils.c @@ -601,12 +601,16 @@ char *perfdata (const char *label, char *perfdata_uint64 (const char *label, uint64_t val, const char *uom, + int warnp, uint64_t warn, + int critp, uint64_t crit, + int minp, uint64_t minv, + int maxp, uint64_t maxv) { @@ -618,20 +622,16 @@ char *perfdata_uint64 (const char *label, xasprintf (&data, "%s=%ld%s;", label, val, uom); if (warnp) - xasprintf (&data, "%s%ld;", data, warn); - else - xasprintf (&data, "%s;", data); + xasprintf (&data, "%s%lu;", data, warn); if (critp) - xasprintf (&data, "%s%ld;", data, crit); - else - xasprintf (&data, "%s;", data); + xasprintf (&data, "%s%lu;", data, crit); if (minp) - xasprintf (&data, "%s%ld", data, minv); + xasprintf (&data, "%s%lu", data, minv); if (maxp) - xasprintf (&data, "%s;%ld", data, maxv); + xasprintf (&data, "%s;%lu", data, maxv); return data; } @@ -658,13 +658,9 @@ char *perfdata_int64 (const char *label, if (warnp) xasprintf (&data, "%s%ld;", data, warn); - else - xasprintf (&data, "%s;", data); if (critp) xasprintf (&data, "%s%ld;", data, crit); - else - xasprintf (&data, "%s;", data); if (minp) xasprintf (&data, "%s%ld", data, minv); -- cgit v1.2.3-74-g34f1 From 726a29a3ac4b155536099b8cae2bd517d56fb5f8 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 26 Oct 2021 12:50:14 +0200 Subject: Fix some tests --- plugins/t/check_disk.t | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'plugins') diff --git a/plugins/t/check_disk.t b/plugins/t/check_disk.t index fdd8769b..ec527e7f 100644 --- a/plugins/t/check_disk.t +++ b/plugins/t/check_disk.t @@ -88,8 +88,9 @@ $result = NPTest->testCmd( ); $_ = $result->perf_output; my ($warn_absth_data, $crit_absth_data, $total_absth_data) = (m/=.[^;]*;(\d+);(\d+);\d+;(\d+)/); -is ($warn_absth_data, $total_absth_data - 20, "Wrong warning in perf data using absolute thresholds"); -is ($crit_absth_data, $total_absth_data - 10, "Wrong critical in perf data using absolute thresholds"); +# default unit is MiB, but perfdata is always bytes +is ($warn_absth_data, $total_absth_data - (20 * (2 ** 20)), "Wrong warning in perf data using absolute thresholds"); +is ($crit_absth_data, $total_absth_data - (10 * (2 ** 20)), "Wrong critical in perf data using absolute thresholds"); # Then check percent thresholds. $result = NPTest->testCmd( @@ -119,7 +120,7 @@ like ( $result->only_output, qr/$more_free/, "Have disk name in text"); $result = NPTest->testCmd( "./check_disk -w 1 -c 1 -p $more_free -p $less_free" ); cmp_ok( $result->return_code, '==', 0, "At least 1 MB available on $more_free and $less_free"); $_ = $result->output; -my ($free_mb_on_mp1, $free_mb_on_mp2) = (m/(\d+) MB .* (\d+) MB /g); +my ($free_mb_on_mp1, $free_mb_on_mp2) = (m/(\d+)MiB .* (\d+)MiB /g); my $free_mb_on_all = $free_mb_on_mp1 + $free_mb_on_mp2; -- cgit v1.2.3-74-g34f1 From 1c0882def0d9ce4ed5b2d443884138622e6d839b Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 26 Oct 2021 13:05:57 +0200 Subject: hopefully fix warning high tide with percentage --- plugins/check_disk.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_disk.c b/plugins/check_disk.c index ecde4e59..1778b613 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -340,7 +340,7 @@ main (int argc, char **argv) warning_high_tide = path->dtotal_units - path->freespace_units->warning->end; } if (path->freespace_percent->warning != NULL) { - warning_high_tide = llabs( min( (double) warning_high_tide, (1.0 - path->freespace_percent->warning->end / 100 * path->dtotal_units) )); + warning_high_tide = llabs( min( (double) warning_high_tide, (double) (1.0 - path->freespace_percent->warning->end/100)* path->dtotal_units )); } if (path->freespace_units->critical != NULL) { critical_high_tide = path->dtotal_units - path->freespace_units->critical->end; -- cgit v1.2.3-74-g34f1 From 6e0586c8e35c3990631f73d8cdb89b70751994c3 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 26 Oct 2021 16:53:01 +0200 Subject: Reform some arithmetical operations for more clarity --- plugins/check_disk.c | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) (limited to 'plugins') diff --git a/plugins/check_disk.c b/plugins/check_disk.c index 1778b613..71eab531 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -334,19 +334,21 @@ main (int argc, char **argv) /* *_high_tide must be reinitialized at each run */ uint64_t warning_high_tide = UINT64_MAX; - uint64_t critical_high_tide = UINT64_MAX; if (path->freespace_units->warning != NULL) { - warning_high_tide = path->dtotal_units - path->freespace_units->warning->end; + warning_high_tide = (path->dtotal_units - path->freespace_units->warning->end) * mult; } if (path->freespace_percent->warning != NULL) { - warning_high_tide = llabs( min( (double) warning_high_tide, (double) (1.0 - path->freespace_percent->warning->end/100)* path->dtotal_units )); + warning_high_tide = min( warning_high_tide, (uint64_t)((1.0 - path->freespace_percent->warning->end/100) * (path->dtotal_units * mult)) ); } + + uint64_t critical_high_tide = UINT64_MAX; + if (path->freespace_units->critical != NULL) { - critical_high_tide = path->dtotal_units - path->freespace_units->critical->end; + critical_high_tide = (path->dtotal_units - path->freespace_units->critical->end) * mult; } if (path->freespace_percent->critical != NULL) { - critical_high_tide = llabs( min( (double) critical_high_tide, (double) (1.0 - path->freespace_percent->critical->end/100)*path->dtotal_units )); + critical_high_tide = min( critical_high_tide, (uint64_t)((1.0 - path->freespace_percent->critical->end/100) * (path->dtotal_units * mult)) ); } /* Nb: *_high_tide are unset when == UINT64_MAX */ @@ -354,8 +356,8 @@ main (int argc, char **argv) perfdata_uint64 ( (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, path->dused_units * mult, "B", - (warning_high_tide == UINT64_MAX ? FALSE : TRUE), warning_high_tide * mult, - (critical_high_tide == UINT64_MAX ? FALSE : TRUE), critical_high_tide * mult, + (warning_high_tide == UINT64_MAX ? FALSE : TRUE), warning_high_tide, + (critical_high_tide == UINT64_MAX ? FALSE : TRUE), critical_high_tide, TRUE, 0, TRUE, path->dtotal_units * mult)); -- cgit v1.2.3-74-g34f1 From 73ed8109e5ba1c61f8ba435fd4324318d0751f18 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 26 Oct 2021 20:47:28 +0200 Subject: Re-add separation semicolons for perfdata, which I deleted --- plugins/utils.c | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) (limited to 'plugins') diff --git a/plugins/utils.c b/plugins/utils.c index ff0e55d4..c0dce255 100644 --- a/plugins/utils.c +++ b/plugins/utils.c @@ -617,18 +617,22 @@ char *perfdata_uint64 (const char *label, char *data = NULL; if (strpbrk (label, "'= ")) - xasprintf (&data, "'%s'=%ld%s;", label, val, uom); + xasprintf (&data, "'%s'=%ld%s", label, val, uom); else - xasprintf (&data, "%s=%ld%s;", label, val, uom); + xasprintf (&data, "%s=%ld%s", label, val, uom); + xasprintf (&data, "%s;", data); if (warnp) - xasprintf (&data, "%s%lu;", data, warn); + xasprintf (&data, "%s%lu", data, warn); + xasprintf (&data, "%s;", data); if (critp) - xasprintf (&data, "%s%lu;", data, crit); + xasprintf (&data, "%s%lu", data, crit); + xasprintf (&data, "%s;", data); if (minp) xasprintf (&data, "%s%lu", data, minv); + xasprintf (&data, "%s;", data); if (maxp) xasprintf (&data, "%s;%lu", data, maxv); @@ -652,18 +656,22 @@ char *perfdata_int64 (const char *label, char *data = NULL; if (strpbrk (label, "'= ")) - xasprintf (&data, "'%s'=%ld%s;", label, val, uom); + xasprintf (&data, "'%s'=%ld%s", label, val, uom); else - xasprintf (&data, "%s=%ld%s;", label, val, uom); + xasprintf (&data, "%s=%ld%s", label, val, uom); + xasprintf (&data, "%s;", data); if (warnp) - xasprintf (&data, "%s%ld;", data, warn); + xasprintf (&data, "%s%ld", data, warn); + xasprintf (&data, "%s;", data); if (critp) - xasprintf (&data, "%s%ld;", data, crit); + xasprintf (&data, "%s%ld", data, crit); + xasprintf (&data, "%s;", data); if (minp) xasprintf (&data, "%s%ld", data, minv); + xasprintf (&data, "%s;", data); if (maxp) xasprintf (&data, "%s;%ld", data, maxv); -- cgit v1.2.3-74-g34f1 From 4c8ab67dd31c526d1c73653319ba537cec3000a5 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 26 Oct 2021 21:09:55 +0200 Subject: Fix my own errors for real this time and add some comments, so I wont do them again --- plugins/utils.c | 64 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 32 insertions(+), 32 deletions(-) (limited to 'plugins') diff --git a/plugins/utils.c b/plugins/utils.c index c0dce255..ebdae2e1 100644 --- a/plugins/utils.c +++ b/plugins/utils.c @@ -601,41 +601,39 @@ char *perfdata (const char *label, char *perfdata_uint64 (const char *label, uint64_t val, const char *uom, - - int warnp, + int warnp, /* Warning present */ uint64_t warn, - - int critp, + int critp, /* Critical present */ uint64_t crit, - - int minp, + int minp, /* Minimum present */ uint64_t minv, - - int maxp, + int maxp, /* Maximum present */ uint64_t maxv) { char *data = NULL; if (strpbrk (label, "'= ")) - xasprintf (&data, "'%s'=%ld%s", label, val, uom); + xasprintf (&data, "'%s'=%ld%s;", label, val, uom); else - xasprintf (&data, "%s=%ld%s", label, val, uom); - xasprintf (&data, "%s;", data); + xasprintf (&data, "%s=%ld%s;", label, val, uom); if (warnp) - xasprintf (&data, "%s%lu", data, warn); - xasprintf (&data, "%s;", data); + xasprintf (&data, "%s%lu;", data, warn); + else + xasprintf (&data, "%s;", data); if (critp) - xasprintf (&data, "%s%lu", data, crit); - xasprintf (&data, "%s;", data); + xasprintf (&data, "%s%lu;", data, crit); + else + xasprintf (&data, "%s;", data); if (minp) - xasprintf (&data, "%s%lu", data, minv); - xasprintf (&data, "%s;", data); + xasprintf (&data, "%s%lu;", data, minv); + else + xasprintf (&data, "%s;", data); if (maxp) - xasprintf (&data, "%s;%lu", data, maxv); + xasprintf (&data, "%s%lu", data, maxv); return data; } @@ -644,37 +642,39 @@ char *perfdata_uint64 (const char *label, char *perfdata_int64 (const char *label, int64_t val, const char *uom, - int warnp, + int warnp, /* Warning present */ int64_t warn, - int critp, + int critp, /* Critical present */ int64_t crit, - int minp, + int minp, /* Minimum present */ int64_t minv, - int maxp, + int maxp, /* Maximum present */ int64_t maxv) { char *data = NULL; if (strpbrk (label, "'= ")) - xasprintf (&data, "'%s'=%ld%s", label, val, uom); + xasprintf (&data, "'%s'=%ld%s;", label, val, uom); else - xasprintf (&data, "%s=%ld%s", label, val, uom); - xasprintf (&data, "%s;", data); + xasprintf (&data, "%s=%ld%s;", label, val, uom); if (warnp) - xasprintf (&data, "%s%ld", data, warn); - xasprintf (&data, "%s;", data); + xasprintf (&data, "%s%ld;", data, warn); + else + xasprintf (&data, "%s;", data); if (critp) - xasprintf (&data, "%s%ld", data, crit); - xasprintf (&data, "%s;", data); + xasprintf (&data, "%s%ld;", data, crit); + else + xasprintf (&data, "%s;", data); if (minp) - xasprintf (&data, "%s%ld", data, minv); - xasprintf (&data, "%s;", data); + xasprintf (&data, "%s%ld;", data, minv); + else + xasprintf (&data, "%s;", data); if (maxp) - xasprintf (&data, "%s;%ld", data, maxv); + xasprintf (&data, "%s%ld", data, maxv); return data; } -- cgit v1.2.3-74-g34f1 From 5974b0481c280d8de9c52ff2d7b99fcf4be99b5d Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Wed, 27 Oct 2021 12:44:21 +0200 Subject: Remove whitespace at the end of lines --- plugins/check_disk.c | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) (limited to 'plugins') diff --git a/plugins/check_disk.c b/plugins/check_disk.c index 71eab531..cc6dbb70 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -1,29 +1,29 @@ /***************************************************************************** -* +* * Monitoring check_disk plugin -* +* * License: GPL * Copyright (c) 1999-2008 Monitoring Plugins Development Team -* +* * Description: -* +* * This file contains the check_disk plugin -* -* +* +* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. -* +* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. -* +* * You should have received a copy of the GNU General Public License * along with this program. If not, see . -* -* +* +* *****************************************************************************/ const char *progname = "check_disk"; @@ -253,7 +253,7 @@ main (int argc, char **argv) /* Remove filesystems already seen */ if (np_seen_name(seen, me->me_mountdir)) { continue; - } + } np_add_name(&seen, me->me_mountdir); if (path->group == NULL) { @@ -1039,20 +1039,20 @@ get_stats (struct parameter_list *p, struct fs_usage *fsp) { if (p_list->group && ! (strcmp(p_list->group, p->group))) { stat_path(p_list); get_fs_usage (p_list->best_match->me_mountdir, p_list->best_match->me_devname, &tmpfsp); - get_path_stats(p_list, &tmpfsp); + get_path_stats(p_list, &tmpfsp); if (verbose >= 3) printf("Group %s: adding %llu blocks sized %llu, (%s) used_units=%g free_units=%g total_units=%g fsu_blocksize=%llu mult=%llu\n", p_list->group, tmpfsp.fsu_bavail, tmpfsp.fsu_blocksize, p_list->best_match->me_mountdir, p_list->dused_units, p_list->dfree_units, p_list->dtotal_units, mult); - /* prevent counting the first FS of a group twice since its parameter_list entry + /* prevent counting the first FS of a group twice since its parameter_list entry * is used to carry the information of all file systems of the entire group */ if (! first) { p->total += p_list->total; p->available += p_list->available; p->available_to_root += p_list->available_to_root; p->used += p_list->used; - + p->dused_units += p_list->dused_units; p->dfree_units += p_list->dfree_units; p->dtotal_units += p_list->dtotal_units; @@ -1063,7 +1063,7 @@ get_stats (struct parameter_list *p, struct fs_usage *fsp) { } first = 0; } - if (verbose >= 3) + if (verbose >= 3) printf("Group %s now has: used_units=%g free_units=%g total_units=%g fsu_blocksize=%llu mult=%llu\n", p->group, tmpfsp.fsu_bavail, @@ -1082,7 +1082,7 @@ get_stats (struct parameter_list *p, struct fs_usage *fsp) { p->dfree_pct = 100 - p->dused_pct; p->dused_inodes_percent = calculate_percent(p->inodes_total - p->inodes_free, p->inodes_total); p->dfree_inodes_percent = 100 - p->dused_inodes_percent; - + } void @@ -1097,7 +1097,7 @@ get_path_stats (struct parameter_list *p, struct fs_usage *fsp) { /* default behaviour : take all the blocks into account */ p->total = fsp->fsu_blocks; } - + p->dused_units = p->used*fsp->fsu_blocksize/mult; p->dfree_units = p->available*fsp->fsu_blocksize/mult; p->dtotal_units = p->total*fsp->fsu_blocksize/mult; -- cgit v1.2.3-74-g34f1 From 884327ee21b25be3ce1b5627bb40339e14545256 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Wed, 27 Oct 2021 12:47:08 +0200 Subject: Replace tabs with spaces and do some formatting --- plugins/check_disk.c | 109 +++++++++++++++++++++++++-------------------------- 1 file changed, 54 insertions(+), 55 deletions(-) (limited to 'plugins') diff --git a/plugins/check_disk.c b/plugins/check_disk.c index cc6dbb70..c526d056 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -46,7 +46,7 @@ const char *email = "devel@monitoring-plugins.org"; #include #include "fsusage.h" #include "mountlist.h" -#include "intprops.h" /* necessary for TYPE_MAXIMUM */ +#include "intprops.h" /* necessary for TYPE_MAXIMUM */ #if HAVE_LIMITS_H # include #endif @@ -243,10 +243,10 @@ main (int argc, char **argv) #ifdef __CYGWIN__ if (strncmp(path->name, "/cygdrive/", 10) != 0 || strlen(path->name) > 11) - continue; + continue; snprintf(mountdir, sizeof(mountdir), "%s:\\", me->me_mountdir + 10); if (GetDriveType(mountdir) != DRIVE_FIXED) - me->me_remote = 1; + me->me_remote = 1; #endif /* Filters */ @@ -287,16 +287,16 @@ main (int argc, char **argv) if (verbose >= 3) { printf ("For %s, used_pct=%g free_pct=%g used_units=%llu free_units=%llu total_units=%llu used_inodes_pct=%g free_inodes_pct=%g fsp.fsu_blocksize=%llu mult=%llu\n", - me->me_mountdir, - path->dused_pct, - path->dfree_pct, - path->dused_units, - path->dfree_units, - path->dtotal_units, - path->dused_inodes_percent, - path->dfree_inodes_percent, - fsp.fsu_blocksize, - mult); + me->me_mountdir, + path->dused_pct, + path->dfree_pct, + path->dused_units, + path->dfree_units, + path->dtotal_units, + path->dused_inodes_percent, + path->dfree_inodes_percent, + fsp.fsu_blocksize, + mult); } /* Threshold comparisons */ @@ -333,7 +333,7 @@ main (int argc, char **argv) */ /* *_high_tide must be reinitialized at each run */ - uint64_t warning_high_tide = UINT64_MAX; + uint64_t warning_high_tide = UINT64_MAX; if (path->freespace_units->warning != NULL) { warning_high_tide = (path->dtotal_units - path->freespace_units->warning->end) * mult; @@ -342,7 +342,7 @@ main (int argc, char **argv) warning_high_tide = min( warning_high_tide, (uint64_t)((1.0 - path->freespace_percent->warning->end/100) * (path->dtotal_units * mult)) ); } - uint64_t critical_high_tide = UINT64_MAX; + uint64_t critical_high_tide = UINT64_MAX; if (path->freespace_units->critical != NULL) { critical_high_tide = (path->dtotal_units - path->freespace_units->critical->end) * mult; @@ -353,13 +353,13 @@ main (int argc, char **argv) /* Nb: *_high_tide are unset when == UINT64_MAX */ xasprintf (&perf, "%s %s", perf, - perfdata_uint64 ( - (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, - path->dused_units * mult, "B", - (warning_high_tide == UINT64_MAX ? FALSE : TRUE), warning_high_tide, - (critical_high_tide == UINT64_MAX ? FALSE : TRUE), critical_high_tide, - TRUE, 0, - TRUE, path->dtotal_units * mult)); + perfdata_uint64 ( + (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, + path->dused_units * mult, "B", + (warning_high_tide == UINT64_MAX ? FALSE : TRUE), warning_high_tide, + (critical_high_tide == UINT64_MAX ? FALSE : TRUE), critical_high_tide, + TRUE, 0, + TRUE, path->dtotal_units * mult)); if (display_inodes_perfdata) { /* *_high_tide must be reinitialized at each run */ @@ -376,37 +376,36 @@ main (int argc, char **argv) xasprintf (&perf_ilabel, "%s (inodes)", (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir); /* Nb: *_high_tide are unset when == UINT64_MAX */ xasprintf (&perf, "%s %s", perf, - perfdata_uint64 (perf_ilabel, - path->inodes_used, "", - (warning_high_tide != UINT64_MAX ? TRUE : FALSE), warning_high_tide, - (critical_high_tide != UINT64_MAX ? TRUE : FALSE), critical_high_tide, - TRUE, 0, - TRUE, path->inodes_total)); + perfdata_uint64 (perf_ilabel, + path->inodes_used, "", + (warning_high_tide != UINT64_MAX ? TRUE : FALSE), warning_high_tide, + (critical_high_tide != UINT64_MAX ? TRUE : FALSE), critical_high_tide, + TRUE, 0, + TRUE, path->inodes_total)); } if (disk_result==STATE_OK && erronly && !verbose) continue; - if(disk_result && verbose >= 1) { - xasprintf(&flag_header, " %s [", state_text (disk_result)); - } else { - xasprintf(&flag_header, ""); - } - xasprintf (&output, "%s%s %s %llu%s (%.0f%%", - output, flag_header, - (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, - path->dfree_units, - units, - path->dfree_pct); - if (path->dused_inodes_percent < 0) { - xasprintf(&output, "%s inode=-)%s;", output, (disk_result ? "]" : "")); - } else { - xasprintf(&output, "%s inode=%.0f%%)%s;", output, path->dfree_inodes_percent, ((disk_result && verbose >= 1) ? "]" : "")); - } + if(disk_result && verbose >= 1) { + xasprintf(&flag_header, " %s [", state_text (disk_result)); + } else { + xasprintf(&flag_header, ""); + } + xasprintf (&output, "%s%s %s %llu%s (%.0f%%", + output, flag_header, + (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, + path->dfree_units, + units, + path->dfree_pct); + if (path->dused_inodes_percent < 0) { + xasprintf(&output, "%s inode=-)%s;", output, (disk_result ? "]" : "")); + } else { + xasprintf(&output, "%s inode=%.0f%%)%s;", output, path->dfree_inodes_percent, ((disk_result && verbose >= 1) ? "]" : "")); + } free(flag_header); /* TODO: Need to do a similar debug line - xasprintf (&details, _("%s\n\ -%.0f of %.0f %s (%.0f%% inode=%.0f%%) free on %s (type %s mounted on %s) warn:%lu crit:%lu warn%%:%.0f%% crit%%:%.0f%%"), + xasprintf (&details, _("%s\n\%.0f of %.0f %s (%.0f%% inode=%.0f%%) free on %s (type %s mounted on %s) warn:%lu crit:%lu warn%%:%.0f%% crit%%:%.0f%%"), details, dfree_units, dtotal_units, units, dfree_pct, inode_space_pct, me->me_devname, me->me_type, me->me_mountdir, (unsigned long)w_df, (unsigned long)c_df, w_dfp, c_dfp); @@ -567,14 +566,14 @@ process_arguments (int argc, char **argv) } break; - case 'W': /* warning inode threshold */ + case 'W': /* warning inode threshold */ if (*optarg == '@') { warn_freeinodes_percent = optarg; } else { xasprintf(&warn_freeinodes_percent, "@%s", optarg); } break; - case 'K': /* critical inode threshold */ + case 'K': /* critical inode threshold */ if (*optarg == '@') { crit_freeinodes_percent = optarg; } else { @@ -1066,19 +1065,19 @@ get_stats (struct parameter_list *p, struct fs_usage *fsp) { if (verbose >= 3) printf("Group %s now has: used_units=%g free_units=%g total_units=%g fsu_blocksize=%llu mult=%llu\n", p->group, - tmpfsp.fsu_bavail, - tmpfsp.fsu_blocksize, - p->best_match->me_mountdir, - p->dused_units, + tmpfsp.fsu_bavail, + tmpfsp.fsu_blocksize, + p->best_match->me_mountdir, + p->dused_units, p->dfree_units, - p->dtotal_units, - mult); + p->dtotal_units, + mult); } /* modify devname and mountdir for output */ p->best_match->me_mountdir = p->best_match->me_devname = p->group; } /* finally calculate percentages for either plain FS or summed up group */ - p->dused_pct = calculate_percent( p->used, p->used + p->available ); /* used + available can never be > uintmax */ + p->dused_pct = calculate_percent( p->used, p->used + p->available ); /* used + available can never be > uintmax */ p->dfree_pct = 100 - p->dused_pct; p->dused_inodes_percent = calculate_percent(p->inodes_total - p->inodes_free, p->inodes_total); p->dfree_inodes_percent = 100 - p->dused_inodes_percent; -- cgit v1.2.3-74-g34f1 From 0bd45c200b64de1918ad4546e09083c529ea39a3 Mon Sep 17 00:00:00 2001 From: Geert Hendrickx Date: Thu, 28 Oct 2021 23:08:02 +0200 Subject: check_smtp: add -L flag to support LMTP (LHLO instead of HELO/EHLO). --- plugins/check_smtp.c | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/check_smtp.c b/plugins/check_smtp.c index d37c57c8..c1e92dff 100644 --- a/plugins/check_smtp.c +++ b/plugins/check_smtp.c @@ -55,6 +55,7 @@ enum { #define SMTP_EXPECT "220" #define SMTP_HELO "HELO " #define SMTP_EHLO "EHLO " +#define SMTP_LHLO "LHLO " #define SMTP_QUIT "QUIT\r\n" #define SMTP_STARTTLS "STARTTLS\r\n" #define SMTP_AUTH_LOGIN "AUTH LOGIN\r\n" @@ -102,6 +103,7 @@ int check_critical_time = FALSE; int verbose = 0; int use_ssl = FALSE; short use_ehlo = FALSE; +short use_lhlo = FALSE; short ssl_established = 0; char *localhostname = NULL; int sd; @@ -152,7 +154,9 @@ main (int argc, char **argv) return STATE_CRITICAL; } } - if(use_ehlo) + if(use_lhlo) + xasprintf (&helocmd, "%s%s%s", SMTP_LHLO, localhostname, "\r\n"); + else if(use_ehlo) xasprintf (&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n"); else xasprintf (&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n"); @@ -197,7 +201,7 @@ main (int argc, char **argv) if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) { printf (_("recv() failed\n")); return STATE_WARNING; - } else if(use_ehlo){ + } else if(use_ehlo || use_lhlo){ if(strstr(buffer, "250 STARTTLS") != NULL || strstr(buffer, "250-STARTTLS") != NULL){ supports_tls=TRUE; @@ -470,6 +474,7 @@ process_arguments (int argc, char **argv) {"use-ipv4", no_argument, 0, '4'}, {"use-ipv6", no_argument, 0, '6'}, {"help", no_argument, 0, 'h'}, + {"lmtp", no_argument, 0, 'L'}, {"starttls",no_argument,0,'S'}, {"certificate",required_argument,0,'D'}, {"ignore-quit-failure",no_argument,0,'q'}, @@ -489,7 +494,7 @@ process_arguments (int argc, char **argv) } while (1) { - c = getopt_long (argc, argv, "+hVv46t:p:f:e:c:w:H:C:R:SD:F:A:U:P:q", + c = getopt_long (argc, argv, "+hVv46Lt:p:f:e:c:w:H:C:R:SD:F:A:U:P:q", longopts, &option); if (c == -1 || c == EOF) @@ -616,6 +621,9 @@ process_arguments (int argc, char **argv) use_ssl = TRUE; use_ehlo = TRUE; break; + case 'L': + use_lhlo = TRUE; + break; case '4': address_family = AF_INET; break; @@ -824,6 +832,8 @@ print_help (void) printf (" %s\n", _("SMTP AUTH username")); printf (" %s\n", "-P, --authpass=STRING"); printf (" %s\n", _("SMTP AUTH password")); + printf (" %s\n", "-L, --lmtp"); + printf (" %s\n", _("Send LHLO instead of HELO/EHLO")); printf (" %s\n", "-q, --ignore-quit-failure"); printf (" %s\n", _("Ignore failure when sending QUIT command to server")); @@ -850,6 +860,6 @@ print_usage (void) printf ("%s\n", _("Usage:")); printf ("%s -H host [-p port] [-4|-6] [-e expect] [-C command] [-R response] [-f from addr]\n", progname); printf ("[-A authtype -U authuser -P authpass] [-w warn] [-c crit] [-t timeout] [-q]\n"); - printf ("[-F fqdn] [-S] [-D warn days cert expire[,crit days cert expire]] [-v] \n"); + printf ("[-F fqdn] [-S] [-L] [-D warn days cert expire[,crit days cert expire]] [-v] \n"); } -- cgit v1.2.3-74-g34f1 From 1738d14c0cae83a24927f34e11a673c7e29baa04 Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Mon, 25 Oct 2021 10:15:40 +0200 Subject: check_procs: remove trailing whitespace --- plugins/check_procs.c | 50 +++++++++++++++++++++++++------------------------- 1 file changed, 25 insertions(+), 25 deletions(-) (limited to 'plugins') diff --git a/plugins/check_procs.c b/plugins/check_procs.c index f7917c34..bae429de 100644 --- a/plugins/check_procs.c +++ b/plugins/check_procs.c @@ -1,34 +1,34 @@ /***************************************************************************** -* +* * Monitoring check_procs plugin -* +* * License: GPL * Copyright (c) 2000-2008 Monitoring Plugins Development Team -* +* * Description: -* +* * This file contains the check_procs plugin -* +* * Checks all processes and generates WARNING or CRITICAL states if the * specified metric is outside the required threshold ranges. The metric * defaults to number of processes. Search filters can be applied to limit * the processes to check. -* -* +* +* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. -* +* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. -* +* * You should have received a copy of the GNU General Public License * along with this program. If not, see . -* -* +* +* *****************************************************************************/ const char *progname = "check_procs"; @@ -50,7 +50,7 @@ const char *email = "devel@monitoring-plugins.org"; int process_arguments (int, char **); int validate_arguments (void); -int convert_to_seconds (char *); +int convert_to_seconds (char *); void print_help (void); void print_usage (void); @@ -230,9 +230,9 @@ main (int argc, char **argv) procseconds = convert_to_seconds(procetime); if (verbose >= 3) - printf ("proc#=%d uid=%d vsz=%d rss=%d pid=%d ppid=%d pcpu=%.2f stat=%s etime=%s prog=%s args=%s\n", + printf ("proc#=%d uid=%d vsz=%d rss=%d pid=%d ppid=%d pcpu=%.2f stat=%s etime=%s prog=%s args=%s\n", procs, procuid, procvsz, procrss, - procpid, procppid, procpcpu, procstat, + procpid, procppid, procpcpu, procstat, procetime, procprog, procargs); /* Ignore self */ @@ -292,9 +292,9 @@ main (int argc, char **argv) procs++; if (verbose >= 2) { - printf ("Matched: uid=%d vsz=%d rss=%d pid=%d ppid=%d pcpu=%.2f stat=%s etime=%s prog=%s args=%s\n", + printf ("Matched: uid=%d vsz=%d rss=%d pid=%d ppid=%d pcpu=%.2f stat=%s etime=%s prog=%s args=%s\n", procuid, procvsz, procrss, - procpid, procppid, procpcpu, procstat, + procpid, procppid, procpcpu, procstat, procetime, procprog, procargs); } @@ -320,7 +320,7 @@ main (int argc, char **argv) result = max_state (result, i); } } - } + } /* This should not happen */ else if (verbose) { printf(_("Not parseable: %s"), input_buffer); @@ -332,7 +332,7 @@ main (int argc, char **argv) return STATE_UNKNOWN; } - if ( result == STATE_UNKNOWN ) + if ( result == STATE_UNKNOWN ) result = STATE_OK; /* Needed if procs found, but none match filter */ @@ -352,9 +352,9 @@ main (int argc, char **argv) if (metric != METRIC_PROCS) { printf (_("%d crit, %d warn out of "), crit, warn); } - } + } printf (ngettext ("%d process", "%d processes", (unsigned long) procs), procs); - + if (strcmp(fmt,"") != 0) { printf (_(" with %s"), fmt); } @@ -440,7 +440,7 @@ process_arguments (int argc, char **argv) break; case 'c': /* critical threshold */ critical_range = optarg; - break; + break; case 'w': /* warning threshold */ warning_range = optarg; break; @@ -542,11 +542,11 @@ process_arguments (int argc, char **argv) if ( strcmp(optarg, "PROCS") == 0) { metric = METRIC_PROCS; break; - } + } else if ( strcmp(optarg, "VSZ") == 0) { metric = METRIC_VSZ; break; - } + } else if ( strcmp(optarg, "RSS") == 0 ) { metric = METRIC_RSS; break; @@ -559,7 +559,7 @@ process_arguments (int argc, char **argv) metric = METRIC_ELAPSED; break; } - + usage4 (_("Metric must be one of PROCS, VSZ, RSS, CPU, ELAPSED!")); case 'k': /* linux kernel thread filter */ kthread_filter = 1; @@ -642,7 +642,7 @@ convert_to_seconds(char *etime) { seconds = 0; for (ptr = etime; *ptr != '\0'; ptr++) { - + if (*ptr == '-') { hyphcnt++; continue; -- cgit v1.2.3-74-g34f1 From 282ccd4a8bbaa5d99c7c0cf6eba963ee3c0bff3a Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Mon, 25 Oct 2021 17:28:17 +0200 Subject: check_procs: improve ps args autodetection one of the first ps commands in the configure.ac is `axwo 'stat comm vsz rss user uid pid ppid args'` which works on most modern linux systems (checked debian 10/11 and centos 7/8). But this test misses the etime argument. Therefore `check_procs --metric=ELAPSED` does not work. To fix this, we simply do the same test including etime before that one. Signed-off-by: Sven Nierlein --- configure.ac | 10 ++++++++++ plugins/tests/check_procs.t | 11 +++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/configure.ac b/configure.ac index 7c17dcd1..dfc37b5e 100644 --- a/configure.ac +++ b/configure.ac @@ -783,6 +783,16 @@ dnl ac_cv_ps_format=["%*s %d %d %d %d %*d %*d %d %d%*[ 0123456789abcdef]%[OSRZT dnl ac_cv_ps_cols=8 dnl AC_MSG_RESULT([$ac_cv_ps_command]) +dnl This one is the exact same test as the next one but includes etime +elif ps axwo 'stat comm vsz rss user uid pid ppid etime args' 2>/dev/null | \ + egrep -i ["^ *STAT +[UCOMAND]+ +VSZ +RSS +USER +UID +PID +PPID +ELAPSED +COMMAND"] > /dev/null +then + ac_cv_ps_varlist="[procstat,&procuid,&procpid,&procppid,&procvsz,&procrss,&procpcpu,procetime,procprog,&pos]" + ac_cv_ps_command="$PATH_TO_PS axwo 'stat uid pid ppid vsz rss pcpu etime comm args'" + ac_cv_ps_format="%s %d %d %d %d %d %f %s %s %n" + ac_cv_ps_cols=10 + AC_MSG_RESULT([$ac_cv_ps_command]) + dnl Some gnu/linux systems (debian for one) don't like -axwo and need axwo. dnl so test for this first... elif ps axwo 'stat comm vsz rss user uid pid ppid args' 2>/dev/null | \ diff --git a/plugins/tests/check_procs.t b/plugins/tests/check_procs.t index 54d43d9b..7f612e8a 100755 --- a/plugins/tests/check_procs.t +++ b/plugins/tests/check_procs.t @@ -69,9 +69,13 @@ SKIP: { like( $result->output, '/^PROCS OK: 0 processes with UID = -2 \(nobody\), args \'UsB\'/', "Output correct" ); }; -$result = NPTest->testCmd( "$command --ereg-argument-array='mdworker.*501'" ); -is( $result->return_code, 0, "Checking regexp search of arguments" ); -is( $result->output, "PROCS OK: 1 process with regex args 'mdworker.*501' | procs=1;;;0;", "Output correct" ); +SKIP: { + skip 'check_procs is compiled with etime format support', 2 if `$command -vvv` =~ m/etime/mx; + + $result = NPTest->testCmd( "$command --ereg-argument-array='mdworker.*501'" ); + is( $result->return_code, 0, "Checking regexp search of arguments" ); + is( $result->output, "PROCS OK: 1 process with regex args 'mdworker.*501' | procs=1;;;0;", "Output correct" ); +} $result = NPTest->testCmd( "$command --vsz 1000000" ); is( $result->return_code, 0, "Checking filter by VSZ" ); @@ -129,4 +133,3 @@ is( $result->output, 'RSS CRITICAL: 5 crit, 0 warn out of 95 processes [WindowSe $result = NPTest->testCmd( "$command --ereg-argument-array='(nosuchname|nosuch2name)'" ); is( $result->return_code, 0, "Checking no pipe symbol in output" ); is( $result->output, "PROCS OK: 0 processes with regex args '(nosuchname,nosuch2name)' | procs=0;;;0;", "Output correct" ); - -- cgit v1.2.3-74-g34f1 From 1fda28f12424be232ac88399e72e95c2bc2d5421 Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Tue, 26 Oct 2021 11:16:38 +0200 Subject: remove unused test file Signed-off-by: Sven Nierlein --- plugins/tests/var/ps_axwo.debian | 84 ---------------------------------------- 1 file changed, 84 deletions(-) delete mode 100644 plugins/tests/var/ps_axwo.debian (limited to 'plugins') diff --git a/plugins/tests/var/ps_axwo.debian b/plugins/tests/var/ps_axwo.debian deleted file mode 100644 index 37a2d35e..00000000 --- a/plugins/tests/var/ps_axwo.debian +++ /dev/null @@ -1,84 +0,0 @@ -STAT UID PID PPID VSZ RSS %CPU COMMAND COMMAND -S 0 1 0 1504 428 0.0 init init [2] -SN 0 2 1 0 0 0.0 ksoftirqd/0 [ksoftirqd/0] -S< 0 3 1 0 0 0.0 events/0 [events/0] -S< 0 4 3 0 0 0.0 khelper [khelper] -S< 0 5 3 0 0 0.0 kacpid [kacpid] -S< 0 38 3 0 0 0.0 kblockd/0 [kblockd/0] -S 0 48 3 0 0 0.0 pdflush [pdflush] -S< 0 51 3 0 0 0.0 aio/0 [aio/0] -S 0 50 1 0 0 0.0 kswapd0 [kswapd0] -S 0 193 1 0 0 0.0 kseriod [kseriod] -S 0 214 1 0 0 0.0 scsi_eh_0 [scsi_eh_0] -S 0 221 1 0 0 0.0 khubd [khubd] -S 0 299 1 0 0 0.3 kjournald [kjournald] -S 0 1148 1 0 0 0.0 pciehpd_event [pciehpd_event] -S 0 1168 1 0 0 0.0 shpchpd_event [shpchpd_event] -Ss 1 1795 1 1612 276 0.0 portmap /sbin/portmap -Ss 0 2200 1 1652 568 0.0 vmware-guestd /usr/sbin/vmware-guestd --background /var/run/vmware-guestd.pid -Ss 0 2209 1 2240 532 0.0 inetd /usr/sbin/inetd -Ss 0 2319 1 3468 792 0.0 sshd /usr/sbin/sshd -Ss 0 2323 1 2468 676 0.0 rpc.statd /sbin/rpc.statd -Ss 1 2332 1 1684 488 0.0 atd /usr/sbin/atd -Ss 0 2335 1 1764 636 0.0 cron /usr/sbin/cron -Ss+ 0 2350 1 1500 348 0.0 getty /sbin/getty 38400 tty1 -Ss+ 0 2351 1 1500 348 0.0 getty /sbin/getty 38400 tty2 -Ss+ 0 2352 1 1500 348 0.0 getty /sbin/getty 38400 tty3 -Ss+ 0 2353 1 1500 348 0.0 getty /sbin/getty 38400 tty4 -Ss+ 0 2354 1 1500 348 0.0 getty /sbin/getty 38400 tty5 -Ss+ 0 2355 1 1500 348 0.0 getty /sbin/getty 38400 tty6 -S 0 6907 1 2308 892 0.0 mysqld_safe /bin/sh /usr/bin/mysqld_safe -S 103 6944 6907 123220 27724 0.0 mysqld /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --user=mysql --pid-file=/var/run/mysqld/mysqld.pid --skip-locking --port=3306 --socket=/var/run/mysqld/mysqld.sock -S 0 6945 6907 1488 420 0.0 logger logger -p daemon.err -t mysqld_safe -i -t mysqld -S 1001 17778 1 6436 1588 0.0 snmpd /usr/sbin/snmpd -u nagios -Lsd -Lf /dev/null -p/var/run/snmpd.pid -Ss 0 17789 1 9496 5556 0.0 snmptrapd /usr/sbin/snmptrapd -t -m ALL -M /usr/share/snmp/mibs:/usr/local/monitoring/snmp/load -p /var/run/snmptrapd.pid -Ss 0 847 2319 14452 1752 0.0 sshd sshd: tonvoon [priv] -S 1000 857 847 14616 1832 0.0 sshd sshd: tonvoon@pts/3 -Ss 1000 860 857 2984 1620 0.0 bash -bash -S 0 868 860 2588 1428 0.0 bash -su -S+ 1001 877 868 2652 1568 0.0 bash -su -S 0 6086 3 0 0 0.0 pdflush [pdflush] -Ss 0 17832 2319 14452 1752 0.0 sshd sshd: tonvoon [priv] -S 1000 18155 17832 14620 1840 0.0 sshd sshd: tonvoon@pts/0 -Ss 1000 18156 18155 2984 1620 0.0 bash -bash -S 0 18518 18156 2588 1428 0.0 bash -su -S 1001 18955 18518 2672 1600 0.0 bash -su -Ss 0 21683 2319 14452 1756 0.0 sshd sshd: tonvoon [priv] -S 1000 21742 21683 14620 1896 0.0 sshd sshd: tonvoon@pts/1 -Ss 1000 21743 21742 2984 1620 0.0 bash -bash -S 0 21748 21743 2592 1432 0.0 bash -su -S 1001 21757 21748 2620 1540 0.0 bash -su -Ss 0 2334 2319 14452 1756 0.0 sshd sshd: tonvoon [priv] -S 1000 2343 2334 14620 1840 0.0 sshd sshd: tonvoon@pts/2 -Ss 1000 2344 2343 2984 1620 0.0 bash -bash -S 0 2349 2344 2592 1432 0.0 bash -su -S+ 1001 2364 2349 2620 1520 0.0 bash -su -T 1001 2454 2364 2096 1032 0.0 vi vi configure.in.rej -S+ 1001 8500 21757 69604 52576 0.0 opsview_web_ser /usr/bin/perl -w ./script/opsview_web_server.pl -f -d -Ss 0 7609 2319 14452 1756 0.0 sshd sshd: tonvoon [priv] -S 1000 7617 7609 14460 1828 0.0 sshd sshd: tonvoon@pts/4 -Ss 1000 7618 7617 2984 1620 0.0 bash -bash -S 0 7623 7618 2592 1432 0.0 bash -su -S+ 1001 7632 7623 2620 1528 0.0 bash -su -Ss 1001 12678 1 20784 17728 0.0 opsviewd opsviewd -Ss 0 832 1 14512 6360 0.0 apache2 /usr/sbin/apache2 -k start -DSSL -S 33 842 832 14648 6596 0.0 apache2 /usr/sbin/apache2 -k start -DSSL -S 33 843 832 14512 6504 0.0 apache2 /usr/sbin/apache2 -k start -DSSL -S 33 844 832 14512 6476 0.0 apache2 /usr/sbin/apache2 -k start -DSSL -S 33 845 832 14512 6476 0.0 apache2 /usr/sbin/apache2 -k start -DSSL -S 33 846 832 14512 6476 0.0 apache2 /usr/sbin/apache2 -k start -DSSL -Ss 7 4081 1 2464 884 0.0 lpd /usr/sbin/lpd -s -S 33 26484 832 14512 6476 0.0 apache2 /usr/sbin/apache2 -k start -DSSL -Ss 1001 22324 1 20252 1612 0.1 nagios ../../bin/nagios -d /usr/local/nagios/etc/nagios.cfg -Ss 0 23336 2319 14452 1756 0.0 sshd sshd: tonvoon [priv] -S 1000 23339 23336 14620 1840 0.0 sshd sshd: tonvoon@pts/5 -Ss 1000 23340 23339 2996 1636 0.0 bash -bash -S 0 23367 23340 3020 1628 0.0 bash bash -S 1001 23370 23367 3064 1748 0.0 bash bash -Ss 1001 23783 1 3220 764 0.0 ndo2db /usr/local/nagios/bin/ndo2db -c /usr/local/nagios/etc/ndo2db.cfg -Ss 1001 23784 1 6428 4948 0.0 import_ndologsd import_ndologsd -S+ 1001 9803 18955 4132 1936 0.0 ssh ssh altinity@cube02.lei.altinity -S 1001 22505 22324 20256 1616 0.0 nagios ../../bin/nagios -d /usr/local/nagios/etc/nagios.cfg -S 1001 22506 22505 1676 608 0.0 check_ping /usr/local/libexec/check_ping -H 192.168.10.23 -w 3000.0,80% -c 5000.0,100% -p 1 -S 1001 22507 22506 1660 492 0.0 ping /bin/ping -n -U -w 10 -c 1 192.168.10.23 -R+ 1001 22508 23370 2308 680 0.0 ps ps axwo stat uid pid ppid vsz rss pcpu comm args -- cgit v1.2.3-74-g34f1 From c3abdb9267567ac9b40ef4a8f3b585c7ab87bac6 Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Tue, 26 Oct 2021 13:34:02 +0200 Subject: check_procs: add test for elapsed time --- plugins/tests/check_procs.t | 13 ++- plugins/tests/var/ps-axwo.debian | 219 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 230 insertions(+), 2 deletions(-) create mode 100644 plugins/tests/var/ps-axwo.debian (limited to 'plugins') diff --git a/plugins/tests/check_procs.t b/plugins/tests/check_procs.t index 7f612e8a..fcea404e 100755 --- a/plugins/tests/check_procs.t +++ b/plugins/tests/check_procs.t @@ -8,13 +8,14 @@ use Test::More; use NPTest; if (-x "./check_procs") { - plan tests => 50; + plan tests => 52; } else { plan skip_all => "No check_procs compiled"; } my $result; -my $command = "./check_procs --input-file=tests/var/ps-axwo.darwin"; +my $command = "./check_procs --input-file=tests/var/ps-axwo.darwin"; +my $cmd_etime = "./check_procs --input-file=tests/var/ps-axwo.debian"; $result = NPTest->testCmd( "$command" ); is( $result->return_code, 0, "Run with no options" ); @@ -77,6 +78,14 @@ SKIP: { is( $result->output, "PROCS OK: 1 process with regex args 'mdworker.*501' | procs=1;;;0;", "Output correct" ); } +SKIP: { + skip 'check_procs is compiled without etime format support', 2 if `$cmd_etime -vvv` !~ m/etime/mx; + + $result = NPTest->testCmd( "$cmd_etime -m ELAPSED -C apache2 -w 1000 -c 2000" ); + is( $result->return_code, 2, "Checking elapsed time threshold" ); + is( $result->output, "ELAPSED CRITICAL: 10 crit, 0 warn out of 10 processes with command name 'apache2' | procs=10;;;0; procs_warn=0;;;0; procs_crit=10;;;0;", "Output correct" ); +} + $result = NPTest->testCmd( "$command --vsz 1000000" ); is( $result->return_code, 0, "Checking filter by VSZ" ); is( $result->output, 'PROCS OK: 24 processes with VSZ >= 1000000 | procs=24;;;0;', "Output correct" ); diff --git a/plugins/tests/var/ps-axwo.debian b/plugins/tests/var/ps-axwo.debian new file mode 100644 index 00000000..5889e9a4 --- /dev/null +++ b/plugins/tests/var/ps-axwo.debian @@ -0,0 +1,219 @@ +STAT UID PID PPID VSZ RSS %CPU ELAPSED COMMAND COMMAND +Ss 0 1 0 167244 7144 0.1 26-03:07:26 systemd /lib/systemd/systemd --system --deserialize 17 +S 0 2 0 0 0 0.0 26-03:07:26 kthreadd [kthreadd] +I< 0 3 2 0 0 0.0 26-03:07:26 rcu_gp [rcu_gp] +I< 0 4 2 0 0 0.0 26-03:07:26 rcu_par_gp [rcu_par_gp] +I< 0 6 2 0 0 0.0 26-03:07:26 kworker/0:0H-ev [kworker/0:0H-events_highpri] +I< 0 9 2 0 0 0.0 26-03:07:26 mm_percpu_wq [mm_percpu_wq] +S 0 10 2 0 0 0.0 26-03:07:26 rcu_tasks_rude_ [rcu_tasks_rude_] +S 0 11 2 0 0 0.0 26-03:07:26 rcu_tasks_trace [rcu_tasks_trace] +S 0 12 2 0 0 0.0 26-03:07:26 ksoftirqd/0 [ksoftirqd/0] +I 0 13 2 0 0 0.0 26-03:07:26 rcu_sched [rcu_sched] +S 0 14 2 0 0 0.0 26-03:07:26 migration/0 [migration/0] +S 0 15 2 0 0 0.0 26-03:07:26 cpuhp/0 [cpuhp/0] +S 0 16 2 0 0 0.0 26-03:07:26 cpuhp/1 [cpuhp/1] +S 0 17 2 0 0 0.0 26-03:07:26 migration/1 [migration/1] +S 0 18 2 0 0 0.0 26-03:07:26 ksoftirqd/1 [ksoftirqd/1] +I< 0 20 2 0 0 0.0 26-03:07:26 kworker/1:0H-ev [kworker/1:0H-events_highpri] +S 0 21 2 0 0 0.0 26-03:07:26 cpuhp/2 [cpuhp/2] +S 0 22 2 0 0 0.0 26-03:07:26 migration/2 [migration/2] +S 0 23 2 0 0 0.0 26-03:07:26 ksoftirqd/2 [ksoftirqd/2] +I< 0 25 2 0 0 0.0 26-03:07:26 kworker/2:0H-ev [kworker/2:0H-events_highpri] +S 0 26 2 0 0 0.0 26-03:07:26 cpuhp/3 [cpuhp/3] +S 0 27 2 0 0 0.0 26-03:07:26 migration/3 [migration/3] +S 0 28 2 0 0 0.0 26-03:07:26 ksoftirqd/3 [ksoftirqd/3] +I< 0 30 2 0 0 0.0 26-03:07:26 kworker/3:0H-ev [kworker/3:0H-events_highpri] +S 0 35 2 0 0 0.0 26-03:07:26 kdevtmpfs [kdevtmpfs] +I< 0 36 2 0 0 0.0 26-03:07:26 netns [netns] +S 0 37 2 0 0 0.0 26-03:07:26 kauditd [kauditd] +S 0 38 2 0 0 0.0 26-03:07:26 khungtaskd [khungtaskd] +S 0 39 2 0 0 0.0 26-03:07:26 oom_reaper [oom_reaper] +I< 0 40 2 0 0 0.0 26-03:07:26 writeback [writeback] +S 0 41 2 0 0 0.0 26-03:07:26 kcompactd0 [kcompactd0] +SN 0 42 2 0 0 0.0 26-03:07:26 ksmd [ksmd] +SN 0 43 2 0 0 0.0 26-03:07:26 khugepaged [khugepaged] +I< 0 62 2 0 0 0.0 26-03:07:26 kintegrityd [kintegrityd] +I< 0 63 2 0 0 0.0 26-03:07:26 kblockd [kblockd] +I< 0 64 2 0 0 0.0 26-03:07:26 blkcg_punt_bio [blkcg_punt_bio] +I< 0 65 2 0 0 0.0 26-03:07:26 edac-poller [edac-poller] +I< 0 66 2 0 0 0.0 26-03:07:26 devfreq_wq [devfreq_wq] +I< 0 67 2 0 0 0.0 26-03:07:26 kworker/2:1H-ev [kworker/2:1H-events_highpri] +S 0 70 2 0 0 0.3 26-03:07:25 kswapd0 [kswapd0] +I< 0 71 2 0 0 0.0 26-03:07:25 kthrotld [kthrotld] +I< 0 72 2 0 0 0.0 26-03:07:25 acpi_thermal_pm [acpi_thermal_pm] +I< 0 74 2 0 0 0.0 26-03:07:25 ipv6_addrconf [ipv6_addrconf] +I< 0 80 2 0 0 0.0 26-03:07:25 kworker/3:1H-ev [kworker/3:1H-events_highpri] +I< 0 84 2 0 0 0.0 26-03:07:25 kstrp [kstrp] +I< 0 87 2 0 0 0.0 26-03:07:25 zswap-shrink [zswap-shrink] +I< 0 110 2 0 0 0.0 26-03:07:25 kworker/0:1H-ev [kworker/0:1H-events_highpri] +I< 0 141 2 0 0 0.0 26-03:07:25 ata_sff [ata_sff] +S 0 143 2 0 0 0.0 26-03:07:25 scsi_eh_0 [scsi_eh_0] +I< 0 144 2 0 0 0.0 26-03:07:25 scsi_tmf_0 [scsi_tmf_0] +S 0 145 2 0 0 0.0 26-03:07:25 scsi_eh_1 [scsi_eh_1] +I< 0 146 2 0 0 0.0 26-03:07:25 scsi_tmf_1 [scsi_tmf_1] +S 0 147 2 0 0 0.0 26-03:07:25 scsi_eh_2 [scsi_eh_2] +I< 0 148 2 0 0 0.0 26-03:07:25 scsi_tmf_2 [scsi_tmf_2] +S 0 149 2 0 0 0.0 26-03:07:25 scsi_eh_3 [scsi_eh_3] +I< 0 150 2 0 0 0.0 26-03:07:25 scsi_tmf_3 [scsi_tmf_3] +S 0 151 2 0 0 0.0 26-03:07:25 scsi_eh_4 [scsi_eh_4] +I< 0 152 2 0 0 0.0 26-03:07:25 scsi_tmf_4 [scsi_tmf_4] +S 0 153 2 0 0 0.0 26-03:07:25 scsi_eh_5 [scsi_eh_5] +I< 0 154 2 0 0 0.0 26-03:07:25 scsi_tmf_5 [scsi_tmf_5] +S 0 158 2 0 0 0.0 26-03:07:25 card0-crtc0 [card0-crtc0] +S 0 159 2 0 0 0.0 26-03:07:25 card0-crtc1 [card0-crtc1] +S 0 160 2 0 0 0.0 26-03:07:25 card0-crtc2 [card0-crtc2] +I< 0 162 2 0 0 0.0 26-03:07:25 kworker/1:1H-ev [kworker/1:1H-events_highpri] +S 0 163 2 0 0 0.0 26-03:07:25 scsi_eh_6 [scsi_eh_6] +I< 0 164 2 0 0 0.0 26-03:07:25 scsi_tmf_6 [scsi_tmf_6] +S 0 165 2 0 0 0.0 26-03:07:25 usb-storage [usb-storage] +I< 0 167 2 0 0 0.0 26-03:07:25 uas [uas] +I< 0 176 2 0 0 0.0 26-03:07:25 kdmflush [kdmflush] +I< 0 177 2 0 0 0.0 26-03:07:25 kdmflush [kdmflush] +S 0 202 2 0 0 0.0 26-03:07:24 scsi_eh_7 [scsi_eh_7] +I< 0 203 2 0 0 0.0 26-03:07:24 scsi_tmf_7 [scsi_tmf_7] +S 0 204 2 0 0 0.0 26-03:07:24 usb-storage [usb-storage] +I< 0 232 2 0 0 0.0 26-03:07:23 btrfs-worker [btrfs-worker] +I< 0 233 2 0 0 0.0 26-03:07:23 btrfs-worker-hi [btrfs-worker-hi] +I< 0 234 2 0 0 0.0 26-03:07:23 btrfs-delalloc [btrfs-delalloc] +I< 0 235 2 0 0 0.0 26-03:07:23 btrfs-flush_del [btrfs-flush_del] +I< 0 236 2 0 0 0.0 26-03:07:23 btrfs-cache [btrfs-cache] +I< 0 237 2 0 0 0.0 26-03:07:23 btrfs-fixup [btrfs-fixup] +I< 0 238 2 0 0 0.0 26-03:07:23 btrfs-endio [btrfs-endio] +I< 0 239 2 0 0 0.0 26-03:07:23 btrfs-endio-met [btrfs-endio-met] +I< 0 240 2 0 0 0.0 26-03:07:23 btrfs-endio-met [btrfs-endio-met] +I< 0 241 2 0 0 0.0 26-03:07:23 btrfs-endio-rai [btrfs-endio-rai] +I< 0 242 2 0 0 0.0 26-03:07:23 btrfs-rmw [btrfs-rmw] +I< 0 243 2 0 0 0.0 26-03:07:23 btrfs-endio-wri [btrfs-endio-wri] +I< 0 244 2 0 0 0.0 26-03:07:23 btrfs-freespace [btrfs-freespace] +I< 0 245 2 0 0 0.0 26-03:07:23 btrfs-delayed-m [btrfs-delayed-m] +I< 0 246 2 0 0 0.0 26-03:07:23 btrfs-readahead [btrfs-readahead] +I< 0 247 2 0 0 0.0 26-03:07:23 btrfs-qgroup-re [btrfs-qgroup-re] +S 0 248 2 0 0 0.0 26-03:07:23 btrfs-cleaner [btrfs-cleaner] +S 0 249 2 0 0 0.2 26-03:07:23 btrfs-transacti [btrfs-transacti] +I< 0 317 2 0 0 0.0 26-03:07:22 rpciod [rpciod] +I< 0 322 2 0 0 0.0 26-03:07:22 xprtiod [xprtiod] +S 0 381 2 0 0 0.0 26-03:07:22 irq/133-mei_me [irq/133-mei_me] +S 0 422 2 0 0 0.0 26-03:07:22 watchdogd [watchdogd] +I< 0 523 2 0 0 0.0 26-03:07:22 led_workqueue [led_workqueue] +I< 0 583 2 0 0 0.0 26-03:07:22 cryptd [cryptd] +I< 0 590 2 0 0 0.0 26-03:07:22 ext4-rsv-conver [ext4-rsv-conver] +Ss 104 693 1 12324 4292 0.5 26-03:07:21 dbus-daemon /usr/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation --syslog-only +Ss 0 731 1 575120 1368 0.0 26-03:07:21 systemd-logind /lib/systemd/systemd-logind +Ssl 0 1111 1 121248 732 0.0 26-03:07:18 unattended-upgr /usr/bin/python3 /usr/share/unattended-upgrades/unattended-upgrade-shutdown --wait-for-signal +S 0 1141 2 0 0 0.0 26-03:07:18 lockd [lockd] +I< 0 1459 2 0 0 0.0 26-03:07:16 nfsiod [nfsiod] +S 0 1621 2 0 0 0.0 26-03:07:15 NFSv4 callback [NFSv4 callback] +Ssl 0 1771 1 1548340 676 0.0 26-03:07:13 libvirtd /usr/sbin/libvirtd +I< 0 24315 2 0 0 0.0 26-02:49:02 cifsiod [cifsiod] +I< 0 24316 2 0 0 0.0 26-02:49:02 smb3decryptd [smb3decryptd] +I< 0 24317 2 0 0 0.0 26-02:49:02 cifsfileinfoput [cifsfileinfoput] +I< 0 24318 2 0 0 0.0 26-02:49:02 cifsoplockd [cifsoplockd] +I< 0 24319 2 0 0 0.0 26-02:49:02 cifs-dfscache [cifs-dfscache] +S 0 24322 2 0 0 0.0 26-02:49:02 cifsd [cifsd] +I< 0 24413 2 0 0 0.0 26-02:48:57 btrfs-worker [btrfs-worker] +I< 0 24414 2 0 0 0.0 26-02:48:57 btrfs-worker-hi [btrfs-worker-hi] +I< 0 24415 2 0 0 0.0 26-02:48:57 btrfs-delalloc [btrfs-delalloc] +I< 0 24416 2 0 0 0.0 26-02:48:57 btrfs-flush_del [btrfs-flush_del] +I< 0 24418 2 0 0 0.0 26-02:48:57 btrfs-cache [btrfs-cache] +I< 0 24419 2 0 0 0.0 26-02:48:57 btrfs-fixup [btrfs-fixup] +I< 0 24420 2 0 0 0.0 26-02:48:57 btrfs-endio [btrfs-endio] +I< 0 24421 2 0 0 0.0 26-02:48:57 btrfs-endio-met [btrfs-endio-met] +I< 0 24422 2 0 0 0.0 26-02:48:57 btrfs-endio-met [btrfs-endio-met] +I< 0 24423 2 0 0 0.0 26-02:48:57 btrfs-endio-rai [btrfs-endio-rai] +I< 0 24424 2 0 0 0.0 26-02:48:57 btrfs-rmw [btrfs-rmw] +I< 0 24425 2 0 0 0.0 26-02:48:57 btrfs-endio-wri [btrfs-endio-wri] +I< 0 24426 2 0 0 0.0 26-02:48:57 btrfs-freespace [btrfs-freespace] +I< 0 24427 2 0 0 0.0 26-02:48:57 btrfs-delayed-m [btrfs-delayed-m] +I< 0 24428 2 0 0 0.0 26-02:48:57 btrfs-readahead [btrfs-readahead] +I< 0 24429 2 0 0 0.0 26-02:48:57 btrfs-qgroup-re [btrfs-qgroup-re] +S 0 24450 2 0 0 0.0 26-02:48:53 btrfs-cleaner [btrfs-cleaner] +S 0 24451 2 0 0 0.0 26-02:48:53 btrfs-transacti [btrfs-transacti] +I< 0 747708 2 0 0 0.0 16-21:06:20 xfsalloc [xfsalloc] +I< 0 747709 2 0 0 0.0 16-21:06:20 xfs_mru_cache [xfs_mru_cache] +S 0 747713 2 0 0 0.0 16-21:06:20 jfsIO [jfsIO] +S 0 747714 2 0 0 0.0 16-21:06:20 jfsCommit [jfsCommit] +S 0 747715 2 0 0 0.0 16-21:06:20 jfsCommit [jfsCommit] +S 0 747716 2 0 0 0.0 16-21:06:20 jfsCommit [jfsCommit] +S 0 747717 2 0 0 0.0 16-21:06:20 jfsCommit [jfsCommit] +S 0 747718 2 0 0 0.0 16-21:06:20 jfsSync [jfsSync] +Ss 0 1071687 1 105976 28304 0.0 3-03:12:31 systemd-journal /lib/systemd/systemd-journald +Ss 0 1934146 1 25672 4704 0.0 11:19:31 cupsd /usr/sbin/cupsd -l +Ssl 0 1934148 1 182868 8540 0.0 11:19:31 cups-browsed /usr/sbin/cups-browsed +S 13 1934155 3392655 5752 88 0.0 11:19:31 pinger (pinger) +S< 33 1934166 3393034 57996 5460 0.0 11:19:31 apache2 /usr/sbin/apache2 -k start +S< 33 1934167 3393034 216944 13892 0.0 11:19:30 apache2 /usr/sbin/apache2 -k start +S< 33 1934168 3393034 216944 13756 0.0 11:19:30 apache2 /usr/sbin/apache2 -k start +S< 33 1934169 3393034 216936 13732 0.0 11:19:30 apache2 /usr/sbin/apache2 -k start +S< 33 1934170 3393034 216944 13888 0.0 11:19:30 apache2 /usr/sbin/apache2 -k start +S< 33 1934172 3393034 216944 15388 0.0 11:19:30 apache2 /usr/sbin/apache2 -k start +S< 33 1934701 3393034 216936 13736 0.0 11:19:29 apache2 /usr/sbin/apache2 -k start +S< 33 1935056 3393034 216920 13724 0.0 11:19:28 apache2 /usr/sbin/apache2 -k start +S 7 1936834 1934146 16652 832 0.0 11:18:12 dbus /usr/lib/cups/notifier/dbus dbus:// +S< 33 1955909 3393034 216928 13792 0.0 11:00:25 apache2 /usr/sbin/apache2 -k start +I< 0 2531464 2 0 0 0.0 06:35:47 kworker/u9:0-i9 [kworker/u9:0-i915_flip] +I 0 2570506 2 0 0 0.0 06:27:41 kworker/1:0-cgr [kworker/1:0-cgroup_destroy] +I 0 2596195 2 0 0 0.0 06:21:52 kworker/1:1-eve [kworker/1:1-events] +I 0 2785341 2 0 0 0.0 03:34:16 kworker/u8:8-bt [kworker/u8:8-btrfs-endio-write] +I 0 2785520 2 0 0 0.0 03:33:50 kworker/3:0-eve [kworker/3:0-events] +I 0 2798669 2 0 0 0.0 03:21:09 kworker/u8:5-bt [kworker/u8:5-btrfs-endio-write] +Ss 0 2803015 1 5616 3108 0.0 03:17:54 cron /usr/sbin/cron -f +I 0 2845483 2 0 0 0.0 02:38:11 kworker/0:3-eve [kworker/0:3-events] +I 0 2939490 2 0 0 0.1 01:10:32 kworker/0:0-eve [kworker/0:0-events] +I 0 2939754 2 0 0 0.0 01:10:26 kworker/u8:1-i9 [kworker/u8:1-i915] +I 0 2942040 2 0 0 0.0 01:08:02 kworker/u8:7-bt [kworker/u8:7-btrfs-endio-meta] +S 117 2954268 3392551 40044 5772 0.0 56:37 pickup pickup -l -t unix -u -c +I 0 2965195 2 0 0 0.0 46:00 kworker/u8:0-bt [kworker/u8:0-btrfs-worker] +I 0 2977972 2 0 0 0.0 33:54 kworker/u8:2-bt [kworker/u8:2-btrfs-endio-write] +I 0 2985488 2 0 0 0.0 27:02 kworker/u8:3-bl [kworker/u8:3-blkcg_punt_bio] +I 0 2987519 2 0 0 1.0 25:15 kworker/2:1-eve [kworker/2:1-events] +I 0 2987601 2 0 0 0.0 25:03 kworker/u8:9-i9 [kworker/u8:9-i915] +I< 0 2995218 2 0 0 0.0 18:41 kworker/u9:2-xp [kworker/u9:2-xprtiod] +I 0 2997170 2 0 0 0.0 16:41 kworker/3:1-rcu [kworker/3:1-rcu_gp] +I 0 3001264 2 0 0 0.0 13:01 kworker/u8:4-bt [kworker/u8:4-btrfs-endio-write] +I 0 3004697 2 0 0 0.7 09:41 kworker/2:0-eve [kworker/2:0-events] +I 0 3010619 2 0 0 1.0 04:29 kworker/2:2-eve [kworker/2:2-events] +I 0 3014612 2 0 0 0.0 00:41 kworker/3:2-eve [kworker/3:2-events] +S 0 3015082 2803015 6716 3028 0.0 00:30 cron /usr/sbin/CRON -f +I 0 3015382 2 0 0 0.0 00:00 kworker/u8:6-bt [kworker/u8:6-btrfs-endio-meta] +Ss 1 3392068 1 5592 504 0.0 15-02:34:39 atd /usr/sbin/atd -f +Ssl 0 3392072 1 235796 1740 0.0 15-02:34:39 accounts-daemon /usr/libexec/accounts-daemon +Ssl 106 3392076 1 315708 6128 0.0 15-02:34:39 colord /usr/libexec/colord +Ss 0 3392083 1 8120 720 0.0 15-02:34:39 haveged /usr/sbin/haveged --Foreground --verbose=1 +Ss 0 3392090 1 5168 132 0.0 15-02:34:39 blkmapd /usr/sbin/blkmapd +SNsl 111 3392094 1 155648 440 0.0 15-02:34:39 rtkit-daemon /usr/libexec/rtkit-daemon +Ssl 0 3392097 1 290168 1352 0.0 15-02:34:39 packagekitd /usr/libexec/packagekitd +Ss 128 3392100 1 7960 448 0.0 15-02:34:39 rpcbind /sbin/rpcbind -f -w +Ss 0 3392114 1 13432 616 0.0 15-02:34:39 systemd-machine /lib/systemd/systemd-machined +Ss 0 3392118 1 13316 848 0.0 15-02:34:39 sshd sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups +Ssl 0 3392124 1 244072 2456 0.0 15-02:34:39 upowerd /usr/libexec/upowerd +Ssl 0 3392138 1 1634748 10684 0.0 15-02:34:39 containerd /usr/bin/containerd +Ssl 0 3392139 1 222768 1784 0.0 15-02:34:39 rsyslogd /usr/sbin/rsyslogd -n -iNONE +Ss 13 3392140 1 3344 152 0.0 15-02:34:39 polipo /usr/bin/polipo -c /etc/polipo/config pidFile=/var/run/polipo/polipo.pid daemonise=true +Ssl 119 3392156 1 76472 1688 0.0 15-02:34:39 ntpd /usr/sbin/ntpd -p /var/run/ntpd.pid -g -u 119:126 +Ss 120 3392168 1 4656 276 0.0 15-02:34:39 rpc.statd /sbin/rpc.statd --no-notify +Ss 0 3392171 1 5072 432 0.0 15-02:34:39 rpc.mountd /usr/sbin/rpc.mountd --manage-gids +Ss 0 3392176 1 5008 288 0.0 15-02:34:39 rpc.idmapd /usr/sbin/rpc.idmapd +Ss 105 3392184 1 15544 6816 3.5 15-02:34:39 avahi-daemon avahi-daemon: running [tsui.local] +Ss 0 3392186 1 25288 3860 0.0 15-02:34:39 systemd-udevd /lib/systemd/systemd-udevd +S 105 3392190 3392184 8788 52 0.0 15-02:34:39 avahi-daemon avahi-daemon: chroot helper +Ssl 0 3392197 1 396120 4188 0.0 15-02:34:39 udisksd /usr/libexec/udisks2/udisksd +Ssl 0 3392214 1 237504 6632 0.0 15-02:34:39 polkitd /usr/libexec/polkitd --no-debug +Ss 0 3392284 1 9684 560 0.0 15-02:34:38 xinetd /usr/sbin/xinetd -pidfile /run/xinetd.pid -stayalive -inetd_compat -inetd_ipv6 +Ssl 0 3392285 1 314840 1352 0.0 15-02:34:38 ModemManager /usr/sbin/ModemManager +Ss 0 3392317 1 2352 140 0.0 15-02:34:38 acpid /usr/sbin/acpid +S 0 3392400 2 0 0 0.0 15-02:34:38 nfsd [nfsd] +S 0 3392401 2 0 0 0.0 15-02:34:38 nfsd [nfsd] +S 0 3392402 2 0 0 0.0 15-02:34:38 nfsd [nfsd] +S 0 3392403 2 0 0 0.0 15-02:34:38 nfsd [nfsd] +S 0 3392404 2 0 0 0.0 15-02:34:38 nfsd [nfsd] +S 0 3392405 2 0 0 0.0 15-02:34:38 nfsd [nfsd] +S 0 3392407 2 0 0 0.0 15-02:34:38 nfsd [nfsd] +S 0 3392410 2 0 0 0.0 15-02:34:38 nfsd [nfsd] +Ss 0 3392551 1 40092 1304 0.0 15-02:34:37 master /usr/lib/postfix/sbin/master -w +S 117 3392553 3392551 40156 568 0.0 15-02:34:37 qmgr qmgr -l -t unix -u +Ss 0 3392650 1 63652 4 0.0 15-02:34:36 squid /usr/sbin/squid --foreground -sYC +Ssl 116 3392652 1 1675196 93848 0.0 15-02:34:36 mariadbd /usr/sbin/mariadbd +S 13 3392655 3392650 81776 21232 0.0 15-02:34:36 squid (squid-1) --kid squid-1 --foreground -sYC +S 13 3392657 3392655 5572 68 0.0 15-02:34:36 log_file_daemon (logfile-daemon) /var/log/squid/access.log +S Date: Wed, 17 Nov 2021 11:58:41 +0100 Subject: check_snmp: fix performance thresholds when using multiple oids when using check_snmp with multiple oids it simply printed the unparsed content from -w/-c into the thresholds for each oid. So each oid contained the hole -w from all oids. ./check_snmp ... -o iso.3.6.1.2.1.25.1.3.0,iso.3.6.1.2.1.25.1.5.0 -w '1,2' -c '3,4' before: SNMP ... | HOST-RESOURCES-MIB::hrSystemInitialLoadDevice.0=393216;1,2;3,4 HOST-RESOURCES-MIB::hrSystemNumUsers.0=24;1,2;3,4 after: SNMP ... | HOST-RESOURCES-MIB::hrSystemInitialLoadDevice.0=393216;1;3 HOST-RESOURCES-MIB::hrSystemNumUsers.0=24;2;4 This also applies to fixed thresholds since check_snmp translates negative infinities from: '~:-1' to '@-1:~' --- lib/utils_base.c | 2 +- lib/utils_base.h | 1 + plugins/check_snmp.c | 9 +++++++-- plugins/tests/check_snmp.t | 17 ++++++++++++++--- 4 files changed, 23 insertions(+), 6 deletions(-) (limited to 'plugins') diff --git a/lib/utils_base.c b/lib/utils_base.c index fd7058da..08fa215c 100644 --- a/lib/utils_base.c +++ b/lib/utils_base.c @@ -128,6 +128,7 @@ range temp_range->end = 0; temp_range->end_infinity = TRUE; temp_range->alert_on = OUTSIDE; + temp_range->text = strdup(str); if (str[0] == '@') { temp_range->alert_on = INSIDE; @@ -706,4 +707,3 @@ void np_state_write_string(time_t data_time, char *data_string) { np_free(temp_file); } - diff --git a/lib/utils_base.h b/lib/utils_base.h index d7e7dffa..9482f23b 100644 --- a/lib/utils_base.h +++ b/lib/utils_base.h @@ -23,6 +23,7 @@ typedef struct range_struct { double end; int end_infinity; int alert_on; /* OUTSIDE (default) or INSIDE */ + char* text; /* original unparsed text input */ } range; typedef struct thresholds_struct { diff --git a/plugins/check_snmp.c b/plugins/check_snmp.c index afc568b2..58d46b11 100644 --- a/plugins/check_snmp.c +++ b/plugins/check_snmp.c @@ -468,6 +468,9 @@ main (int argc, char **argv) /* Process this block for numeric comparisons */ /* Make some special values,like Timeticks numeric only if a threshold is defined */ if (thlds[i]->warning || thlds[i]->critical || calculate_rate) { + if (verbose > 2) { + print_thresholds(" thresholds", thlds[i]); + } ptr = strpbrk (show, "-0123456789"); if (ptr == NULL) die (STATE_UNKNOWN,_("No valid data returned (%s)\n"), show); @@ -581,14 +584,16 @@ main (int argc, char **argv) if (warning_thresholds) { strncat(perfstr, ";", sizeof(perfstr)-strlen(perfstr)-1); - strncat(perfstr, warning_thresholds, sizeof(perfstr)-strlen(perfstr)-1); + if(thlds[i]->warning && thlds[i]->warning->text) + strncat(perfstr, thlds[i]->warning->text, sizeof(perfstr)-strlen(perfstr)-1); } if (critical_thresholds) { if (!warning_thresholds) strncat(perfstr, ";", sizeof(perfstr)-strlen(perfstr)-1); strncat(perfstr, ";", sizeof(perfstr)-strlen(perfstr)-1); - strncat(perfstr, critical_thresholds, sizeof(perfstr)-strlen(perfstr)-1); + if(thlds[i]->critical && thlds[i]->critical->text) + strncat(perfstr, thlds[i]->critical->text, sizeof(perfstr)-strlen(perfstr)-1); } strncat(perfstr, " ", sizeof(perfstr)-strlen(perfstr)-1); diff --git a/plugins/tests/check_snmp.t b/plugins/tests/check_snmp.t index 85d6bf55..0a77fa8a 100755 --- a/plugins/tests/check_snmp.t +++ b/plugins/tests/check_snmp.t @@ -9,7 +9,7 @@ use NPTest; use FindBin qw($Bin); use POSIX qw/strftime/; -my $tests = 67; +my $tests = 73; # Check that all dependent modules are available eval { require NetSNMP::OID; @@ -251,9 +251,20 @@ is($res->output, 'SNMP CRITICAL - *-4* | iso.3.6.1.4.1.8072.3.2.67.17=-4;-2:;-3: $res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.18 -c '~:-6.5'" ); is($res->return_code, 0, "Negative float OK" ); -is($res->output, 'SNMP OK - -6.6 | iso.3.6.1.4.1.8072.3.2.67.18=-6.6;;~:-6.5 ', "Negative float OK output" ); +is($res->output, 'SNMP OK - -6.6 | iso.3.6.1.4.1.8072.3.2.67.18=-6.6;;@-6.5:~ ', "Negative float OK output" ); $res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.18 -w '~:-6.65' -c '~:-6.55'" ); is($res->return_code, 1, "Negative float WARNING" ); -is($res->output, 'SNMP WARNING - *-6.6* | iso.3.6.1.4.1.8072.3.2.67.18=-6.6;~:-6.65;~:-6.55 ', "Negative float WARNING output" ); +is($res->output, 'SNMP WARNING - *-6.6* | iso.3.6.1.4.1.8072.3.2.67.18=-6.6;@-6.65:~;@-6.55:~ ', "Negative float WARNING output" ); +$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10,.1.3.6.1.4.1.8072.3.2.67.17 -w '1:100000,-10:20' -c '2:200000,-20:30'" ); +is($res->return_code, 0, "Multiple OIDs with thresholds" ); +like($res->output, '/SNMP OK - \d+ -4 | iso.3.6.1.4.1.8072.3.2.67.10=\d+c;1:100000;2:200000 iso.3.6.1.4.1.8072.3.2.67.17=-4;-10:20;-20:30/', "Multiple OIDs with thresholds output" ); + +$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10,.1.3.6.1.4.1.8072.3.2.67.17 -w '1:100000,-1:2' -c '2:200000,-20:30'" ); +is($res->return_code, 1, "Multiple OIDs with thresholds" ); +like($res->output, '/SNMP WARNING - \d+ \*-4\* | iso.3.6.1.4.1.8072.3.2.67.10=\d+c;1:100000;2:200000 iso.3.6.1.4.1.8072.3.2.67.17=-4;-10:20;-20:30/', "Multiple OIDs with thresholds output" ); + +$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10,.1.3.6.1.4.1.8072.3.2.67.17 -w 1,2 -c 1" ); +is($res->return_code, 2, "Multiple OIDs with some thresholds" ); +like($res->output, '/SNMP CRITICAL - \*\d+\* \*-4\* | iso.3.6.1.4.1.8072.3.2.67.10=\d+c;1;2 iso.3.6.1.4.1.8072.3.2.67.17=-4;;/', "Multiple OIDs with thresholds output" ); -- cgit v1.2.3-74-g34f1 From 27d96dcf23c44c74d0a2be7ea94f47798e37030a Mon Sep 17 00:00:00 2001 From: rincewind Date: Fri, 9 Jul 2021 16:07:23 +0200 Subject: Do not show RTA if no connection was possible --- plugins/check_ping.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/check_ping.c b/plugins/check_ping.c index 423ecbe5..7d58b103 100644 --- a/plugins/check_ping.c +++ b/plugins/check_ping.c @@ -37,6 +37,8 @@ const char *email = "devel@monitoring-plugins.org"; #include "popen.h" #include "utils.h" +#include + #define WARN_DUPLICATES "DUPLICATES FOUND! " #define UNKNOWN_TRIP_TIME -1.0 /* -1 seconds */ @@ -163,10 +165,14 @@ main (int argc, char **argv) printf (""); /* Print performance data */ - printf("|%s", fperfdata ("rta", (double) rta, "ms", - wrta>0?TRUE:FALSE, wrta, - crta>0?TRUE:FALSE, crta, - TRUE, 0, FALSE, 0)); + if (pl != 100) { + printf("|%s", fperfdata ("rta", (double) rta, "ms", + wrta>0?TRUE:FALSE, wrta, + crta>0?TRUE:FALSE, crta, + TRUE, 0, FALSE, 0)); + } else { + printf("|"); + } printf(" %s\n", perfdata ("pl", (long) pl, "%", wpl>0?TRUE:FALSE, wpl, cpl>0?TRUE:FALSE, cpl, -- cgit v1.2.3-74-g34f1 From 0214ec1918abf589f15b70948ddba641a9729ce3 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Wed, 17 Nov 2021 14:09:11 +0100 Subject: Show RTA as unknown if it can not be determined --- plugins/check_ping.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_ping.c b/plugins/check_ping.c index 7d58b103..6aa43ed8 100644 --- a/plugins/check_ping.c +++ b/plugins/check_ping.c @@ -171,7 +171,7 @@ main (int argc, char **argv) crta>0?TRUE:FALSE, crta, TRUE, 0, FALSE, 0)); } else { - printf("|"); + printf("| rta=U;;;;;"); } printf(" %s\n", perfdata ("pl", (long) pl, "%", wpl>0?TRUE:FALSE, wpl, -- cgit v1.2.3-74-g34f1 From 1c53c4f541db3afdc3a2975121b69064d53f7ef3 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Wed, 17 Nov 2021 15:45:17 +0100 Subject: homogenize perfdata function and fix small bug with missing semicolon --- plugins/utils.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/utils.c b/plugins/utils.c index ebdae2e1..17dd5814 100644 --- a/plugins/utils.c +++ b/plugins/utils.c @@ -589,10 +589,12 @@ char *perfdata (const char *label, xasprintf (&data, "%s;", data); if (minp) - xasprintf (&data, "%s%ld", data, minv); + xasprintf (&data, "%s%ld;", data, minv); + else + xasprintf (&data, "%s;", data); if (maxp) - xasprintf (&data, "%s;%ld", data, maxv); + xasprintf (&data, "%s%ld", data, maxv); return data; } -- cgit v1.2.3-74-g34f1 From e030c2d17c10446bda840d66f6753b9bf573d715 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Wed, 17 Nov 2021 15:45:49 +0100 Subject: Add thresholds even if value is missing --- plugins/check_ping.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_ping.c b/plugins/check_ping.c index 6aa43ed8..ba7af373 100644 --- a/plugins/check_ping.c +++ b/plugins/check_ping.c @@ -171,7 +171,7 @@ main (int argc, char **argv) crta>0?TRUE:FALSE, crta, TRUE, 0, FALSE, 0)); } else { - printf("| rta=U;;;;;"); + printf("| rta=U;%f;%f;;", wrta, crta); } printf(" %s\n", perfdata ("pl", (long) pl, "%", wpl>0?TRUE:FALSE, wpl, -- cgit v1.2.3-74-g34f1 From ee3449dee7578f1b0508b9ceb0c14a0d72a67646 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Fri, 19 Nov 2021 00:34:44 +0100 Subject: Small fix to threshold validation and style (indentation) fixes --- plugins/check_swap.c | 43 +++++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 20 deletions(-) (limited to 'plugins') diff --git a/plugins/check_swap.c b/plugins/check_swap.c index 685c2cc5..7f71bf7e 100644 --- a/plugins/check_swap.c +++ b/plugins/check_swap.c @@ -552,9 +552,12 @@ validate_arguments (void) if (warn.value == 0 && crit.value == 0) { return ERROR; } - else if (warn.value < crit.value) { - usage4 - (_("Warning should be more than critical")); + else if ((warn.is_percentage == crit.is_percentage) && (warn.value < crit.value)) { + /* This is NOT triggered if warn and crit are different units, e.g warn is percentage + * and crit is absolut. We cannot determine the condition at this point since we + * dont know the value of total swap yet + */ + usage4(_("Warning should be more than critical")); } return OK; } @@ -570,7 +573,7 @@ print_help (void) printf ("%s\n", _("Check swap space on local machine.")); - printf ("\n\n"); + printf ("\n\n"); print_usage (); @@ -578,23 +581,23 @@ print_help (void) printf (UT_EXTRA_OPTS); printf (" %s\n", "-w, --warning=INTEGER"); - printf (" %s\n", _("Exit with WARNING status if less than INTEGER bytes of swap space are free")); - printf (" %s\n", "-w, --warning=PERCENT%%"); - printf (" %s\n", _("Exit with WARNING status if less than PERCENT of swap space is free")); - printf (" %s\n", "-c, --critical=INTEGER"); - printf (" %s\n", _("Exit with CRITICAL status if less than INTEGER bytes of swap space are free")); - printf (" %s\n", "-c, --critical=PERCENT%%"); - printf (" %s\n", _("Exit with CRITICAL status if less than PERCENT of swap space is free")); - printf (" %s\n", "-a, --allswaps"); - printf (" %s\n", _("Conduct comparisons for all swap partitions, one by one")); - printf (" %s\n", "-n, --no-swap="); - printf (" %s %s\n", _("Resulting state when there is no swap regardless of thresholds. Default:"), state_text(no_swap_state)); + printf (" %s\n", _("Exit with WARNING status if less than INTEGER bytes of swap space are free")); + printf (" %s\n", "-w, --warning=PERCENT%"); + printf (" %s\n", _("Exit with WARNING status if less than PERCENT of swap space is free")); + printf (" %s\n", "-c, --critical=INTEGER"); + printf (" %s\n", _("Exit with CRITICAL status if less than INTEGER bytes of swap space are free")); + printf (" %s\n", "-c, --critical=PERCENT%"); + printf (" %s\n", _("Exit with CRITICAL status if less than PERCENT of swap space is free")); + printf (" %s\n", "-a, --allswaps"); + printf (" %s\n", _("Conduct comparisons for all swap partitions, one by one")); + printf (" %s\n", "-n, --no-swap="); + printf (" %s %s\n", _("Resulting state when there is no swap regardless of thresholds. Default:"), state_text(no_swap_state)); printf (UT_VERBOSE); printf ("\n"); - printf ("%s\n", _("Notes:")); - printf (" %s\n", _("Both INTEGER and PERCENT thresholds can be specified, they are all checked.")); - printf (" %s\n", _("On AIX, if -a is specified, uses lsps -a, otherwise uses lsps -s.")); + printf ("%s\n", _("Notes:")); + printf (" %s\n", _("Both INTEGER and PERCENT thresholds can be specified, they are all checked.")); + printf (" %s\n", _("On AIX, if -a is specified, uses lsps -a, otherwise uses lsps -s.")); printf (UT_SUPPORT); } @@ -604,6 +607,6 @@ void print_usage (void) { printf ("%s\n", _("Usage:")); - printf (" %s [-av] -w %% -c %%\n",progname); - printf (" -w -c [-n ]\n"); + printf (" %s [-av] -w %% -c %%\n",progname); + printf (" -w -c [-n ]\n"); } -- cgit v1.2.3-74-g34f1 From a1fe4df6a3a146b50c4fd700acdf8baf848874aa Mon Sep 17 00:00:00 2001 From: Lorenz Kästle Date: Mon, 19 Apr 2021 11:51:30 +0200 Subject: Fixed option description authpassword -> authpasswd + whitespaces --- plugins/check_snmp.c | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) (limited to 'plugins') diff --git a/plugins/check_snmp.c b/plugins/check_snmp.c index 58d46b11..88422b15 100644 --- a/plugins/check_snmp.c +++ b/plugins/check_snmp.c @@ -1,31 +1,31 @@ /***************************************************************************** -* +* * Monitoring check_snmp plugin -* +* * License: GPL * Copyright (c) 1999-2007 Monitoring Plugins Development Team -* +* * Description: -* +* * This file contains the check_snmp plugin -* +* * Check status of remote machines and obtain system information via SNMP -* -* +* +* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. -* +* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. -* +* * You should have received a copy of the GNU General Public License * along with this program. If not, see . -* -* +* +* *****************************************************************************/ const char *progname = "check_snmp"; @@ -315,7 +315,7 @@ main (int argc, char **argv) for (i = 0; i < numcontext; i++) { command_line[10 + i] = contextargs[i]; } - + for (i = 0; i < numauthpriv; i++) { command_line[10 + numcontext + i] = authpriv[i]; } @@ -329,7 +329,7 @@ main (int argc, char **argv) for (i = 0; i < numoids; i++) { command_line[10 + numcontext + numauthpriv + 1 + i] = oids[i]; - xasprintf(&cl_hidden_auth, "%s %s", cl_hidden_auth, oids[i]); + xasprintf(&cl_hidden_auth, "%s %s", cl_hidden_auth, oids[i]); } command_line[10 + numcontext + numauthpriv + 1 + numoids] = NULL; @@ -398,14 +398,14 @@ main (int argc, char **argv) /* We strip out the datatype indicator for PHBs */ if (strstr (response, "Gauge: ")) { show = strstr (response, "Gauge: ") + 7; - } + } else if (strstr (response, "Gauge32: ")) { show = strstr (response, "Gauge32: ") + 9; - } + } else if (strstr (response, "Counter32: ")) { show = strstr (response, "Counter32: ") + 11; is_counter=1; - if(!calculate_rate) + if(!calculate_rate) strcpy(type, "c"); } else if (strstr (response, "Counter64: ")) { @@ -607,7 +607,7 @@ main (int argc, char **argv) state_string=malloc(string_length); if(state_string==NULL) die(STATE_UNKNOWN, _("Cannot malloc")); - + current_length=0; for(i=0; i 2) printf("State string=%s\n",state_string); - + /* This is not strictly the same as time now, but any subtle variations will cancel out */ np_state_write_string(current_time, state_string ); if(previous_state==NULL) { @@ -1006,7 +1006,7 @@ validate_arguments () contextargs[0] = strdup ("-n"); contextargs[1] = strdup (context); } - + if (seclevel == NULL) xasprintf(&seclevel, "noAuthNoPriv"); @@ -1166,7 +1166,7 @@ print_help (void) printf ("(%s \"%s\")\n", _("default is") ,DEFAULT_COMMUNITY); printf (" %s\n", "-U, --secname=USERNAME"); printf (" %s\n", _("SNMPv3 username")); - printf (" %s\n", "-A, --authpassword=PASSWORD"); + printf (" %s\n", "-A, --authpasswd=PASSWORD"); printf (" %s\n", _("SNMPv3 authentication password")); printf (" %s\n", "-X, --privpasswd=PASSWORD"); printf (" %s\n", _("SNMPv3 privacy password")); -- cgit v1.2.3-74-g34f1 From cf9dccbec22e15a475cd6d5b160f503a04348a0d Mon Sep 17 00:00:00 2001 From: Lorenz Kästle Date: Mon, 19 Apr 2021 12:22:16 +0200 Subject: Revert "Fixed option description authpassword -> authpasswd + whitespaces" This reverts commit b27e639725f680411aaa78dd9aa59cfff84ad0c5. --- plugins/check_snmp.c | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) (limited to 'plugins') diff --git a/plugins/check_snmp.c b/plugins/check_snmp.c index 88422b15..58d46b11 100644 --- a/plugins/check_snmp.c +++ b/plugins/check_snmp.c @@ -1,31 +1,31 @@ /***************************************************************************** -* +* * Monitoring check_snmp plugin -* +* * License: GPL * Copyright (c) 1999-2007 Monitoring Plugins Development Team -* +* * Description: -* +* * This file contains the check_snmp plugin -* +* * Check status of remote machines and obtain system information via SNMP -* -* +* +* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. -* +* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. -* +* * You should have received a copy of the GNU General Public License * along with this program. If not, see . -* -* +* +* *****************************************************************************/ const char *progname = "check_snmp"; @@ -315,7 +315,7 @@ main (int argc, char **argv) for (i = 0; i < numcontext; i++) { command_line[10 + i] = contextargs[i]; } - + for (i = 0; i < numauthpriv; i++) { command_line[10 + numcontext + i] = authpriv[i]; } @@ -329,7 +329,7 @@ main (int argc, char **argv) for (i = 0; i < numoids; i++) { command_line[10 + numcontext + numauthpriv + 1 + i] = oids[i]; - xasprintf(&cl_hidden_auth, "%s %s", cl_hidden_auth, oids[i]); + xasprintf(&cl_hidden_auth, "%s %s", cl_hidden_auth, oids[i]); } command_line[10 + numcontext + numauthpriv + 1 + numoids] = NULL; @@ -398,14 +398,14 @@ main (int argc, char **argv) /* We strip out the datatype indicator for PHBs */ if (strstr (response, "Gauge: ")) { show = strstr (response, "Gauge: ") + 7; - } + } else if (strstr (response, "Gauge32: ")) { show = strstr (response, "Gauge32: ") + 9; - } + } else if (strstr (response, "Counter32: ")) { show = strstr (response, "Counter32: ") + 11; is_counter=1; - if(!calculate_rate) + if(!calculate_rate) strcpy(type, "c"); } else if (strstr (response, "Counter64: ")) { @@ -607,7 +607,7 @@ main (int argc, char **argv) state_string=malloc(string_length); if(state_string==NULL) die(STATE_UNKNOWN, _("Cannot malloc")); - + current_length=0; for(i=0; i 2) printf("State string=%s\n",state_string); - + /* This is not strictly the same as time now, but any subtle variations will cancel out */ np_state_write_string(current_time, state_string ); if(previous_state==NULL) { @@ -1006,7 +1006,7 @@ validate_arguments () contextargs[0] = strdup ("-n"); contextargs[1] = strdup (context); } - + if (seclevel == NULL) xasprintf(&seclevel, "noAuthNoPriv"); @@ -1166,7 +1166,7 @@ print_help (void) printf ("(%s \"%s\")\n", _("default is") ,DEFAULT_COMMUNITY); printf (" %s\n", "-U, --secname=USERNAME"); printf (" %s\n", _("SNMPv3 username")); - printf (" %s\n", "-A, --authpasswd=PASSWORD"); + printf (" %s\n", "-A, --authpassword=PASSWORD"); printf (" %s\n", _("SNMPv3 authentication password")); printf (" %s\n", "-X, --privpasswd=PASSWORD"); printf (" %s\n", _("SNMPv3 privacy password")); -- cgit v1.2.3-74-g34f1 From c46447af659e96d78c2f02e1295e887a4d12cd36 Mon Sep 17 00:00:00 2001 From: Lorenz Kästle Date: Mon, 19 Apr 2021 12:23:42 +0200 Subject: Fix option description authpassword -> authpasswd --- plugins/check_snmp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_snmp.c b/plugins/check_snmp.c index 58d46b11..abe54cfb 100644 --- a/plugins/check_snmp.c +++ b/plugins/check_snmp.c @@ -1166,7 +1166,7 @@ print_help (void) printf ("(%s \"%s\")\n", _("default is") ,DEFAULT_COMMUNITY); printf (" %s\n", "-U, --secname=USERNAME"); printf (" %s\n", _("SNMPv3 username")); - printf (" %s\n", "-A, --authpassword=PASSWORD"); + printf (" %s\n", "-A, --authpasswd=PASSWORD"); printf (" %s\n", _("SNMPv3 authentication password")); printf (" %s\n", "-X, --privpasswd=PASSWORD"); printf (" %s\n", _("SNMPv3 privacy password")); -- cgit v1.2.3-74-g34f1 From f961b7f7bd5d10328bf152cbc015271180165f0f Mon Sep 17 00:00:00 2001 From: Linda Guo Date: Fri, 19 Nov 2021 13:25:09 +1100 Subject: Allows check_ldap to get password from env variable It's not secure to provide LDAP password through command line option because other users on the same host can see the password in 'ps' command output. This change allows check_ldap to get password from environment variable. --- plugins/check_ldap.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_ldap.c b/plugins/check_ldap.c index bc7bd44c..845a4f52 100644 --- a/plugins/check_ldap.c +++ b/plugins/check_ldap.c @@ -432,6 +432,9 @@ validate_arguments () set_thresholds(&entries_thresholds, warn_entries, crit_entries); } + if (ld_passwd==NULL) + ld_passwd = getenv("LDAP_PASSWORD"); + return OK; } @@ -465,7 +468,7 @@ print_help (void) printf (" %s\n", "-D [--bind]"); printf (" %s\n", _("ldap bind DN (if required)")); printf (" %s\n", "-P [--pass]"); - printf (" %s\n", _("ldap password (if required)")); + printf (" %s\n", _("ldap password (if required, or set the password through environment variable 'LDAP_PASSWORD')")); printf (" %s\n", "-T [--starttls]"); printf (" %s\n", _("use starttls mechanism introduced in protocol version 3")); printf (" %s\n", "-S [--ssl]"); -- cgit v1.2.3-74-g34f1 From f291934f2cd7124e62deb6de5fca98d2506d3c45 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Sun, 21 Nov 2021 02:43:01 +0100 Subject: Update Url to qstat --- plugins/check_game.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_game.c b/plugins/check_game.c index 709dae1b..a534b69b 100644 --- a/plugins/check_game.c +++ b/plugins/check_game.c @@ -318,7 +318,7 @@ print_help (void) printf ("%s\n", _("Notes:")); printf (" %s\n", _("This plugin uses the 'qstat' command, the popular game server status query tool.")); printf (" %s\n", _("If you don't have the package installed, you will need to download it from")); - printf (" %s\n", _("http://www.activesw.com/people/steve/qstat.html before you can use this plugin.")); + printf (" %s\n", _("https://github.com/multiplay/qstat before you can use this plugin.")); printf (UT_SUPPORT); } -- cgit v1.2.3-74-g34f1 From 09bfb1b482f428b1c11f68b5be7d134ba5e3b457 Mon Sep 17 00:00:00 2001 From: PhiBo Date: Wed, 24 Nov 2021 11:23:47 +0100 Subject: Fix possible overflow in check_ups (Fixes: #1030) --- plugins/check_ups.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_ups.c b/plugins/check_ups.c index e9e56a51..0de37a20 100644 --- a/plugins/check_ups.c +++ b/plugins/check_ups.c @@ -402,7 +402,10 @@ get_ups_variable (const char *varname, char *buf, size_t buflen) /* create the command string to send to the UPS daemon */ /* Add LOGOUT to avoid read failure logs */ - sprintf (send_buffer, "GET VAR %s %s\nLOGOUT\n", ups_name, varname); + if (snprintf (send_buffer, sizeof(send_buffer), "GET VAR %s %s\nLOGOUT\n", ups_name, varname) >= sizeof(send_buffer)) { + printf("%s\n", _("UPS name to long for buffer")); + return ERROR; + } /* send the command to the daemon and get a response back */ if (process_tcp_request -- cgit v1.2.3-74-g34f1 From e2f24a5af3fe407035c8c57f539148f2d694973b Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Wed, 24 Nov 2021 14:25:42 +0100 Subject: Fix CodeQL checks --- plugins-root/check_icmp.c | 4 ++-- plugins/check_disk.c | 16 ++++++++++------ plugins/check_hpjd.c | 2 +- plugins/check_swap.c | 2 +- 4 files changed, 14 insertions(+), 10 deletions(-) (limited to 'plugins') diff --git a/plugins-root/check_icmp.c b/plugins-root/check_icmp.c index 519b93c6..bcf6c5f5 100644 --- a/plugins-root/check_icmp.c +++ b/plugins-root/check_icmp.c @@ -502,7 +502,7 @@ main(int argc, char **argv) icmp_data_size = size; icmp_pkt_size = size + ICMP_MINLEN; } else - usage_va("ICMP data length must be between: %d and %d", + usage_va("ICMP data length must be between: %ul and %ul", sizeof(struct icmp) + sizeof(struct icmp_ping_data), MAX_PING_DATA - 1); break; @@ -1293,7 +1293,7 @@ add_target_ip(char *arg, struct sockaddr_storage *in) if(!host) { char straddr[INET6_ADDRSTRLEN]; parse_address((struct sockaddr_storage*)&in, straddr, sizeof(straddr)); - crash("add_target_ip(%s, %s): malloc(%d) failed", + crash("add_target_ip(%s, %s): malloc(%ul) failed", arg, straddr, sizeof(struct rta_host)); } memset(host, 0, sizeof(struct rta_host)); diff --git a/plugins/check_disk.c b/plugins/check_disk.c index c526d056..f032378c 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -1040,9 +1040,15 @@ get_stats (struct parameter_list *p, struct fs_usage *fsp) { get_fs_usage (p_list->best_match->me_mountdir, p_list->best_match->me_devname, &tmpfsp); get_path_stats(p_list, &tmpfsp); if (verbose >= 3) - printf("Group %s: adding %llu blocks sized %llu, (%s) used_units=%g free_units=%g total_units=%g fsu_blocksize=%llu mult=%llu\n", - p_list->group, tmpfsp.fsu_bavail, tmpfsp.fsu_blocksize, p_list->best_match->me_mountdir, p_list->dused_units, p_list->dfree_units, - p_list->dtotal_units, mult); + printf("Group %s: adding %llu blocks sized %llu, (%s) used_units=%g free_units=%g total_units=%g mult=%llu\n", + p_list->group, + tmpfsp.fsu_blocks, + tmpfsp.fsu_blocksize, + p_list->best_match->me_mountdir, + p_list->dused_units, + p_list->dfree_units, + p_list->dtotal_units, + mult); /* prevent counting the first FS of a group twice since its parameter_list entry * is used to carry the information of all file systems of the entire group */ @@ -1065,12 +1071,10 @@ get_stats (struct parameter_list *p, struct fs_usage *fsp) { if (verbose >= 3) printf("Group %s now has: used_units=%g free_units=%g total_units=%g fsu_blocksize=%llu mult=%llu\n", p->group, - tmpfsp.fsu_bavail, - tmpfsp.fsu_blocksize, - p->best_match->me_mountdir, p->dused_units, p->dfree_units, p->dtotal_units, + tmpfsp.fsu_blocksize, mult); } /* modify devname and mountdir for output */ diff --git a/plugins/check_hpjd.c b/plugins/check_hpjd.c index 65465567..d3d72d7e 100644 --- a/plugins/check_hpjd.c +++ b/plugins/check_hpjd.c @@ -121,7 +121,7 @@ main (int argc, char **argv) HPJD_GD_DOOR_OPEN, HPJD_GD_PAPER_OUTPUT, HPJD_GD_STATUS_DISPLAY); /* get the command to run */ - sprintf (command_line, "%s -OQa -m : -v 1 -c %s %s:%hd %s", PATH_TO_SNMPGET, community, + sprintf (command_line, "%s -OQa -m : -v 1 -c %s %s:%s %s", PATH_TO_SNMPGET, community, address, port, query_string); /* run the command */ diff --git a/plugins/check_swap.c b/plugins/check_swap.c index 7f71bf7e..00bdcdd8 100644 --- a/plugins/check_swap.c +++ b/plugins/check_swap.c @@ -142,7 +142,7 @@ main (int argc, char **argv) percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb)); result = max_state (result, check_swap (dskfree_mb, dsktotal_mb)); if (verbose) - xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent); + xasprintf (&status, "%s [%ul (%d%%)]", status, dskfree_mb, 100 - percent); } } /* -- cgit v1.2.3-74-g34f1 From 40d4e8a057a77e357c26d701c5fd304b51787b93 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Wed, 24 Nov 2021 15:38:18 +0100 Subject: check_hpjd: Fixing port option --- plugins/check_hpjd.c | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) (limited to 'plugins') diff --git a/plugins/check_hpjd.c b/plugins/check_hpjd.c index d3d72d7e..c4b44178 100644 --- a/plugins/check_hpjd.c +++ b/plugins/check_hpjd.c @@ -66,7 +66,7 @@ void print_usage (void); char *community = NULL; char *address = NULL; -char *port = NULL; +unsigned int port = 0; int check_paper_out = 1; int @@ -121,8 +121,12 @@ main (int argc, char **argv) HPJD_GD_DOOR_OPEN, HPJD_GD_PAPER_OUTPUT, HPJD_GD_STATUS_DISPLAY); /* get the command to run */ - sprintf (command_line, "%s -OQa -m : -v 1 -c %s %s:%s %s", PATH_TO_SNMPGET, community, - address, port, query_string); + sprintf (command_line, "%s -OQa -m : -v 1 -c %s %s:%u %s", + PATH_TO_SNMPGET, + community, + address, + port, + query_string); /* run the command */ child_process = spopen (command_line); @@ -380,11 +384,8 @@ process_arguments (int argc, char **argv) community = strdup (DEFAULT_COMMUNITY); } - if (port == NULL) { - if (argv[c] != NULL ) - port = argv[c]; - else - port = atoi (DEFAULT_PORT); + if (port == 0) { + port = atoi(DEFAULT_PORT); } return validate_arguments (); -- cgit v1.2.3-74-g34f1 From d28bab4dbdf5b5be37b70164dd4a6d55e0ca9380 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Wed, 24 Nov 2021 19:02:17 +0100 Subject: More wrong printf formatting --- plugins-root/check_icmp.c | 4 ++-- plugins/check_disk.c | 4 ++-- plugins/check_swap.c | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) (limited to 'plugins') diff --git a/plugins-root/check_icmp.c b/plugins-root/check_icmp.c index bcf6c5f5..01ae174a 100644 --- a/plugins-root/check_icmp.c +++ b/plugins-root/check_icmp.c @@ -502,7 +502,7 @@ main(int argc, char **argv) icmp_data_size = size; icmp_pkt_size = size + ICMP_MINLEN; } else - usage_va("ICMP data length must be between: %ul and %ul", + usage_va("ICMP data length must be between: %lu and %lu", sizeof(struct icmp) + sizeof(struct icmp_ping_data), MAX_PING_DATA - 1); break; @@ -1293,7 +1293,7 @@ add_target_ip(char *arg, struct sockaddr_storage *in) if(!host) { char straddr[INET6_ADDRSTRLEN]; parse_address((struct sockaddr_storage*)&in, straddr, sizeof(straddr)); - crash("add_target_ip(%s, %s): malloc(%ul) failed", + crash("add_target_ip(%s, %s): malloc(%lu) failed", arg, straddr, sizeof(struct rta_host)); } memset(host, 0, sizeof(struct rta_host)); diff --git a/plugins/check_disk.c b/plugins/check_disk.c index f032378c..54befcad 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -1040,7 +1040,7 @@ get_stats (struct parameter_list *p, struct fs_usage *fsp) { get_fs_usage (p_list->best_match->me_mountdir, p_list->best_match->me_devname, &tmpfsp); get_path_stats(p_list, &tmpfsp); if (verbose >= 3) - printf("Group %s: adding %llu blocks sized %llu, (%s) used_units=%g free_units=%g total_units=%g mult=%llu\n", + printf("Group %s: adding %llu blocks sized %llu, (%s) used_units=%lu free_units=%llu total_units=%llu mult=%llu\n", p_list->group, tmpfsp.fsu_blocks, tmpfsp.fsu_blocksize, @@ -1069,7 +1069,7 @@ get_stats (struct parameter_list *p, struct fs_usage *fsp) { first = 0; } if (verbose >= 3) - printf("Group %s now has: used_units=%g free_units=%g total_units=%g fsu_blocksize=%llu mult=%llu\n", + printf("Group %s now has: used_units=%llu free_units=%llu total_units=%llu fsu_blocksize=%llu mult=%llu\n", p->group, p->dused_units, p->dfree_units, diff --git a/plugins/check_swap.c b/plugins/check_swap.c index 00bdcdd8..7da26cfc 100644 --- a/plugins/check_swap.c +++ b/plugins/check_swap.c @@ -142,7 +142,7 @@ main (int argc, char **argv) percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb)); result = max_state (result, check_swap (dskfree_mb, dsktotal_mb)); if (verbose) - xasprintf (&status, "%s [%ul (%d%%)]", status, dskfree_mb, 100 - percent); + xasprintf (&status, "%s [%lu (%d%%)]", status, dskfree_mb, 100 - percent); } } /* -- cgit v1.2.3-74-g34f1 From d496d6523bd0def281f001ddfb2a3f467bd9a4a6 Mon Sep 17 00:00:00 2001 From: Lorenz Kästle Date: Mon, 3 Jan 2022 14:07:54 +0100 Subject: Rename tmp variable to get even with master --- plugins/check_swap.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/check_swap.c b/plugins/check_swap.c index 2b8013ba..bb854beb 100644 --- a/plugins/check_swap.c +++ b/plugins/check_swap.c @@ -145,12 +145,12 @@ main (int argc, char **argv) xasprintf (&status, "%s [%lu (%d%%)]", status, dskfree_mb, 100 - percent); } } - + /* * The following sscanf call looks for lines looking like: "SwapTotal: 123" and "SwapFree: 123" * This format exists at least on Debian Linux with a 5.* kernel */ - else if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%[TotalFreCchd]%*[:] %f %*[k]%*[B]", str, &tmp_mb)) { + else if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%[TotalFreCchd]%*[:] %f %*[k]%*[B]", str, &tmp_KB)) { if (verbose >= 3) { printf("Got %s with %lu\n", str, tmp_KB); } @@ -159,10 +159,10 @@ main (int argc, char **argv) dsktotal_mb = tmp_KB / 1024; } else if (strcmp ("Free", str) == 0) { - dskfree_mb = dskfree_mb + tmp_mb / 1024; + dskfree_mb = dskfree_mb + tmp_KB / 1024; } else if (strcmp ("Cached", str) == 0) { - dskfree_mb = dskfree_mb + tmp_mb / 1024; + dskfree_mb = dskfree_mb + tmp_KB / 1024; } } } -- cgit v1.2.3-74-g34f1 From a1f328900049852d9a2b4c810c28b49e2101e337 Mon Sep 17 00:00:00 2001 From: Ken D Date: Mon, 19 Jun 2017 14:06:05 -0500 Subject: Added option for null zero length string exit codes When using a large distributed network with the same group of checks used against a large number of devices, occationally there are missing cards in a few devices that are present in other devices. Rather than having a large number of unknown results, disable active checking on those large number of result or having to create a unique check configuration for those devices. This option allows you to select an OK, WARNING, CRITICAL or UNKNOWN status while still retaining the default behavior when not present. This also allows a for the check to immediately start checks as intended should the hardware be added that the check is looking for. --- plugins/check_snmp.c | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) (limited to 'plugins') diff --git a/plugins/check_snmp.c b/plugins/check_snmp.c index abe54cfb..66d761c6 100644 --- a/plugins/check_snmp.c +++ b/plugins/check_snmp.c @@ -113,6 +113,7 @@ char *authproto = NULL; char *privproto = NULL; char *authpasswd = NULL; char *privpasswd = NULL; +int nulloid = 3; char **oids = NULL; size_t oids_size = 0; char *label; @@ -472,8 +473,16 @@ main (int argc, char **argv) print_thresholds(" thresholds", thlds[i]); } ptr = strpbrk (show, "-0123456789"); - if (ptr == NULL) - die (STATE_UNKNOWN,_("No valid data returned (%s)\n"), show); + if (ptr == NULL){ + if (nulloid == 3) + die (STATE_UNKNOWN,_("No valid data returned (%s)\n"), show); + else if (nulloid == 0) + die (STATE_OK,_("No valid data returned (%s)\n"), show); + else if (nulloid == 1) + die (STATE_WARNING,_("No valid data returned (%s)\n"), show); + else if (nulloid == 2) + die (STATE_CRITICAL,_("No valid data returned (%s)\n"), show); + } while (i >= response_size) { response_size += OID_COUNT_STEP; response_value = realloc(response_value, response_size * sizeof(*response_value)); @@ -661,6 +670,7 @@ process_arguments (int argc, char **argv) {"oid", required_argument, 0, 'o'}, {"object", required_argument, 0, 'o'}, {"delimiter", required_argument, 0, 'd'}, + {"nulloid", required_argument, 0, 'z'}, {"output-delimiter", required_argument, 0, 'D'}, {"string", required_argument, 0, 's'}, {"timeout", required_argument, 0, 't'}, @@ -705,7 +715,7 @@ process_arguments (int argc, char **argv) } while (1) { - c = getopt_long (argc, argv, "nhvVO46t:c:w:H:C:o:e:E:d:D:s:t:R:r:l:u:p:m:P:N:L:U:a:x:A:X:", + c = getopt_long (argc, argv, "nhvVO46t:c:w:H:C:o:e:E:d:D:s:t:R:r:l:u:p:m:P:N:L:U:a:x:A:X:z:", longopts, &option); if (c == -1 || c == EOF) @@ -816,6 +826,12 @@ process_arguments (int argc, char **argv) eval_method[j+1] |= CRIT_PRESENT; } break; + case 'z': /* Null OID Return Check */ + if (!is_integer (optarg)) + usage2 (_("Exit status must be a positive integer"), optarg); + else + nulloid = atoi(optarg); + break; case 's': /* string or substring */ strncpy (string_value, optarg, sizeof (string_value) - 1); string_value[sizeof (string_value) - 1] = 0; @@ -1181,6 +1197,14 @@ print_help (void) printf (" %s \"%s\"\n", _("Delimiter to use when parsing returned data. Default is"), DEFAULT_DELIMITER); printf (" %s\n", _("Any data on the right hand side of the delimiter is considered")); printf (" %s\n", _("to be the data that should be used in the evaluation.")); + printf (" %s\n", "-z, --nulloid=#"); + printf (" %s\n", _("If the check returns a 0 length string or NULL value")); + printf (" %s\n", _("This option allows you to choose what status you want it to exit")); + printf (" %s\n", _("Excluding this option renders the default exit of 3(STATE_UNKNOWN)")); + printf (" %s\n", _("0 = OK")); + printf (" %s\n", _("1 = WARNING")); + printf (" %s\n", _("2 = CRITICAL")); + printf (" %s\n", _("3 = UNKNOWN")); /* Tests Against Integers */ printf (" %s\n", "-w, --warning=THRESHOLD(s)"); -- cgit v1.2.3-74-g34f1 From 69fed9d08363085e8f6689bc8c9df2e9ad0f4cdb Mon Sep 17 00:00:00 2001 From: Ken D Date: Mon, 27 Aug 2018 09:53:11 -0500 Subject: Updated int state to human readable --- plugins/check_snmp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_snmp.c b/plugins/check_snmp.c index 66d761c6..bd13e579 100644 --- a/plugins/check_snmp.c +++ b/plugins/check_snmp.c @@ -113,7 +113,7 @@ char *authproto = NULL; char *privproto = NULL; char *authpasswd = NULL; char *privpasswd = NULL; -int nulloid = 3; +int nulloid = STATE_UNKNOWN; char **oids = NULL; size_t oids_size = 0; char *label; -- cgit v1.2.3-74-g34f1 From 3b252b9ae61b5e5c577ea57f3c6bf00c3bb7517d Mon Sep 17 00:00:00 2001 From: "Mark A. Ziesemer" Date: Sat, 22 Jan 2022 08:58:59 -0600 Subject: Trivial source code formatting only: Use tabs consistently for source code indentation (whitespace), as per https://github.com/monitoring-plugins/monitoring-plugins/blob/master/CODING . (#1424) Looks good, thank you very much. --- plugins/check_ping.c | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) (limited to 'plugins') diff --git a/plugins/check_ping.c b/plugins/check_ping.c index 5ea11294..741f732e 100644 --- a/plugins/check_ping.c +++ b/plugins/check_ping.c @@ -140,7 +140,7 @@ main (int argc, char **argv) if (pl == UNKNOWN_PACKET_LOSS || rta < 0.0) { printf ("%s\n", cmd); die (STATE_UNKNOWN, - _("CRITICAL - Could not interpret output from ping command\n")); + _("CRITICAL - Could not interpret output from ping command\n")); } if (pl >= cpl || rta >= crta || rta < 0) @@ -554,7 +554,7 @@ error_scan (char buf[MAX_INPUT_BUFFER], const char *addr) if (warn_text == NULL) warn_text = strdup (_(WARN_DUPLICATES)); else if (! strstr (warn_text, _(WARN_DUPLICATES)) && - xasprintf (&warn_text, "%s %s", warn_text, _(WARN_DUPLICATES)) == -1) + xasprintf (&warn_text, "%s %s", warn_text, _(WARN_DUPLICATES)) == -1) die (STATE_UNKNOWN, _("Unable to realloc warn_text\n")); return (STATE_WARNING); } @@ -574,7 +574,7 @@ print_help (void) printf (_("Use ping to check connection statistics for a remote host.")); - printf ("\n\n"); + printf ("\n\n"); print_usage (); @@ -584,29 +584,29 @@ print_help (void) printf (UT_IPv46); printf (" %s\n", "-H, --hostname=HOST"); - printf (" %s\n", _("host to ping")); - printf (" %s\n", "-w, --warning=THRESHOLD"); - printf (" %s\n", _("warning threshold pair")); - printf (" %s\n", "-c, --critical=THRESHOLD"); - printf (" %s\n", _("critical threshold pair")); - printf (" %s\n", "-p, --packets=INTEGER"); - printf (" %s ", _("number of ICMP ECHO packets to send")); - printf (_("(Default: %d)\n"), DEFAULT_MAX_PACKETS); - printf (" %s\n", "-L, --link"); - printf (" %s\n", _("show HTML in the plugin output (obsoleted by urlize)")); + printf (" %s\n", _("host to ping")); + printf (" %s\n", "-w, --warning=THRESHOLD"); + printf (" %s\n", _("warning threshold pair")); + printf (" %s\n", "-c, --critical=THRESHOLD"); + printf (" %s\n", _("critical threshold pair")); + printf (" %s\n", "-p, --packets=INTEGER"); + printf (" %s ", _("number of ICMP ECHO packets to send")); + printf (_("(Default: %d)\n"), DEFAULT_MAX_PACKETS); + printf (" %s\n", "-L, --link"); + printf (" %s\n", _("show HTML in the plugin output (obsoleted by urlize)")); printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - printf ("\n"); + printf ("\n"); printf ("%s\n", _("THRESHOLD is ,% where is the round trip average travel")); - printf ("%s\n", _("time (ms) which triggers a WARNING or CRITICAL state, and is the")); - printf ("%s\n", _("percentage of packet loss to trigger an alarm state.")); + printf ("%s\n", _("time (ms) which triggers a WARNING or CRITICAL state, and is the")); + printf ("%s\n", _("percentage of packet loss to trigger an alarm state.")); - printf ("\n"); + printf ("\n"); printf ("%s\n", _("This plugin uses the ping command to probe the specified host for packet loss")); - printf ("%s\n", _("(percentage) and round trip average (milliseconds). It can produce HTML output")); - printf ("%s\n", _("linking to a traceroute CGI contributed by Ian Cass. The CGI can be found in")); - printf ("%s\n", _("the contrib area of the downloads section at http://www.nagios.org/")); + printf ("%s\n", _("(percentage) and round trip average (milliseconds). It can produce HTML output")); + printf ("%s\n", _("linking to a traceroute CGI contributed by Ian Cass. The CGI can be found in")); + printf ("%s\n", _("the contrib area of the downloads section at http://www.nagios.org/")); printf (UT_SUPPORT); } @@ -614,7 +614,7 @@ print_help (void) void print_usage (void) { - printf ("%s\n", _("Usage:")); + printf ("%s\n", _("Usage:")); printf ("%s -H -w ,%% -c ,%%\n", progname); - printf (" [-p packets] [-t timeout] [-4|-6]\n"); + printf (" [-p packets] [-t timeout] [-4|-6]\n"); } -- cgit v1.2.3-74-g34f1 From cf669f5ff51b746569ded30e990b9d53e5234da0 Mon Sep 17 00:00:00 2001 From: Lorenz <12514511+RincewindsHat@users.noreply.github.com> Date: Sat, 22 Jan 2022 22:23:13 +0100 Subject: Trivial printf fix and a little bit of code style (#1695) * Fix several warnings (and some downright bugs probably) with formating in check_disk Update to master * Fix merge error, I forgot the last time * Fix indentation Co-authored-by: rincewind --- plugins/check_disk.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_disk.c b/plugins/check_disk.c index 54befcad..9652f453 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -230,8 +230,10 @@ main (int argc, char **argv) /* Process for every path in list */ for (path = path_select_list; path; path=path->name_next) { if (verbose >= 3 && path->freespace_percent->warning != NULL && path->freespace_percent->critical != NULL) - printf("Thresholds(pct) for %s warn: %f crit %f\n",path->name, path->freespace_percent->warning->end, - path->freespace_percent->critical->end); + printf("Thresholds(pct) for %s warn: %f crit %f\n", + path->name, + path->freespace_percent->warning->end, + path->freespace_percent->critical->end); if (verbose >= 3 && path->group != NULL) printf("Group of %s: %s\n",path->name,path->group); -- cgit v1.2.3-74-g34f1 From b14e251d0f28cc2acb93df79da099bb3cdb5ec08 Mon Sep 17 00:00:00 2001 From: Jan Wagner Date: Fri, 21 Jan 2022 11:04:14 +0100 Subject: Implements 'host-alive' mode (Closes. #1027) To reduce the check-duration, it addes a host-alive flag which stops testing after the first successful reply. --- plugins/check_fping.c | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_fping.c b/plugins/check_fping.c index 521d0fef..540650ae 100644 --- a/plugins/check_fping.c +++ b/plugins/check_fping.c @@ -65,6 +65,7 @@ double crta; double wrta; int cpl_p = FALSE; int wpl_p = FALSE; +int alive_p = FALSE; int crta_p = FALSE; int wrta_p = FALSE; @@ -150,6 +151,19 @@ main (int argc, char **argv) if (result = spclose (child_process)) /* need to use max_state not max */ status = max_state (status, STATE_WARNING); + if (alive_p && strstr (buf, "avg, 0% loss)")){ + rtastr = strstr (buf, "ms ("); + rtastr = 1 + index (rtastr, '('); + rta = strtod (rtastr, NULL); + loss=strtod ("0",NULL); + die (STATE_OK, + _("FPING %s - %s (rta=%f ms)|%s %s\n"), + state_text (STATE_OK), server_name,rta, + perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, TRUE, 0, TRUE, 100), + fperfdata ("rta", rta/1.0e3, "s", wrta_p, wrta/1.0e3, crta_p, crta/1.0e3, TRUE, 0, FALSE, 0)); + + } + if (result > 1 ) { status = max_state (status, STATE_UNKNOWN); @@ -275,6 +289,9 @@ process_arguments (int argc, char **argv) static struct option longopts[] = { {"hostname", required_argument, 0, 'H'}, {"sourceip", required_argument, 0, 'S'}, + case 'a': /* host alive mode */ + alive_p = TRUE; + break; {"sourceif", required_argument, 0, 'I'}, {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, @@ -304,7 +321,7 @@ process_arguments (int argc, char **argv) } while (1) { - c = getopt_long (argc, argv, "+hVvH:S:c:w:b:n:T:i:I:46", longopts, &option); + c = getopt_long (argc, argv, "+hVvaH:S:c:w:b:n:T:i:I:46", longopts, &option); if (c == -1 || c == EOF || c == 1) break; @@ -416,6 +433,9 @@ get_threshold (char *arg, char *rv[2]) arg2 = 1 + strpbrk (arg1, ",:"); if (arg2) { + printf (" %s\n", "-a"); + printf (" %s\n", _("Return OK after first successfull reply")); + arg1[strcspn (arg1, ",:")] = 0; if (strstr (arg1, "%") && strstr (arg2, "%")) die (STATE_UNKNOWN, -- cgit v1.2.3-74-g34f1 From 3bcc64396d8768d984eb58eb0a80213c2a8528ca Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Sat, 22 Jan 2022 20:01:49 +0100 Subject: Fixes the positioning of the code and some other changes --- plugins/check_fping.c | 53 +++++++++++++++++++++++++-------------------------- 1 file changed, 26 insertions(+), 27 deletions(-) (limited to 'plugins') diff --git a/plugins/check_fping.c b/plugins/check_fping.c index 540650ae..be9362ad 100644 --- a/plugins/check_fping.c +++ b/plugins/check_fping.c @@ -37,6 +37,7 @@ const char *email = "devel@monitoring-plugins.org"; #include "popen.h" #include "netutils.h" #include "utils.h" +#include enum { PACKET_COUNT = 1, @@ -65,7 +66,7 @@ double crta; double wrta; int cpl_p = FALSE; int wpl_p = FALSE; -int alive_p = FALSE; +bool alive_p = FALSE; int crta_p = FALSE; int wrta_p = FALSE; @@ -148,23 +149,12 @@ main (int argc, char **argv) (void) fclose (child_stderr); /* close the pipe */ - if (result = spclose (child_process)) + result = spclose (child_process); + if (result) { /* need to use max_state not max */ status = max_state (status, STATE_WARNING); - if (alive_p && strstr (buf, "avg, 0% loss)")){ - rtastr = strstr (buf, "ms ("); - rtastr = 1 + index (rtastr, '('); - rta = strtod (rtastr, NULL); - loss=strtod ("0",NULL); - die (STATE_OK, - _("FPING %s - %s (rta=%f ms)|%s %s\n"), - state_text (STATE_OK), server_name,rta, - perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, TRUE, 0, TRUE, 100), - fperfdata ("rta", rta/1.0e3, "s", wrta_p, wrta/1.0e3, crta_p, crta/1.0e3, TRUE, 0, FALSE, 0)); - } - if (result > 1 ) { status = max_state (status, STATE_UNKNOWN); if (result == 2) { @@ -185,10 +175,7 @@ main (int argc, char **argv) } - -int -textscan (char *buf) -{ +int textscan (char *buf) { char *rtastr = NULL; char *losstr = NULL; char *xmtstr = NULL; @@ -197,6 +184,20 @@ textscan (char *buf) double xmt; int status = STATE_UNKNOWN; + /* stops testing after the first successful reply. */ + if (alive_p && strstr(buf, "avg, 0% loss)")) { + rtastr = strstr (buf, "ms ("); + rtastr = 1 + index(rtastr, '('); + rta = strtod(rtastr, NULL); + loss=strtod("0",NULL); + die (STATE_OK, + _("FPING %s - %s (rta=%f ms)|%s\n"), + state_text (STATE_OK), server_name,rta, + /* No loss since we only waited for the first reply + perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, TRUE, 0, TRUE, 100), */ + fperfdata ("rta", rta/1.0e3, "s", wrta_p, wrta/1.0e3, crta_p, crta/1.0e3, TRUE, 0, FALSE, 0)); + } + if (strstr (buf, "not found")) { die (STATE_CRITICAL, _("FPING UNKNOWN - %s not found\n"), server_name); @@ -289,12 +290,10 @@ process_arguments (int argc, char **argv) static struct option longopts[] = { {"hostname", required_argument, 0, 'H'}, {"sourceip", required_argument, 0, 'S'}, - case 'a': /* host alive mode */ - alive_p = TRUE; - break; {"sourceif", required_argument, 0, 'I'}, {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, + {"alive", no_argument, 0, 'a'}, {"bytes", required_argument, 0, 'b'}, {"number", required_argument, 0, 'n'}, {"target-timeout", required_argument, 0, 'T'}, @@ -329,6 +328,9 @@ process_arguments (int argc, char **argv) switch (c) { case '?': /* print short usage statement if args not parsable */ usage5 (); + case 'a': /* host alive mode */ + alive_p = TRUE; + break; case 'h': /* help */ print_help (); exit (STATE_UNKNOWN); @@ -433,9 +435,6 @@ get_threshold (char *arg, char *rv[2]) arg2 = 1 + strpbrk (arg1, ",:"); if (arg2) { - printf (" %s\n", "-a"); - printf (" %s\n", _("Return OK after first successfull reply")); - arg1[strcspn (arg1, ",:")] = 0; if (strstr (arg1, "%") && strstr (arg2, "%")) die (STATE_UNKNOWN, @@ -466,9 +465,7 @@ get_threshold (char *arg, char *rv[2]) } -void -print_help (void) -{ +void print_help (void) { print_revision (progname, NP_VERSION); @@ -494,6 +491,8 @@ print_help (void) printf (" %s\n", _("warning threshold pair")); printf (" %s\n", "-c, --critical=THRESHOLD"); printf (" %s\n", _("critical threshold pair")); + printf (" %s\n", "-a, --alive"); + printf (" %s\n", _("Return OK after first successfull reply")); printf (" %s\n", "-b, --bytes=INTEGER"); printf (" %s (default: %d)\n", _("size of ICMP packet"),PACKET_SIZE); printf (" %s\n", "-n, --number=INTEGER"); -- cgit v1.2.3-74-g34f1 From e2397167c7e5c7a02b68de45de946f63706e7d12 Mon Sep 17 00:00:00 2001 From: datamuc Date: Tue, 25 Jan 2022 10:57:02 +0100 Subject: add --queryname parameter to check_pgsql (#1741) This is used in the long output instead of the actual query. So instead of OK - 'select stuff from various, tables where some_stuff is null and other_stuff is not null' returned 42 one can use --queryname=check_greatest_basket and it will print OK - check_greatest_basket returned 42 That's nicer for alerting purposes, at least in our use case. --- plugins/check_pgsql.c | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_pgsql.c b/plugins/check_pgsql.c index b8fc5f1d..c893386c 100644 --- a/plugins/check_pgsql.c +++ b/plugins/check_pgsql.c @@ -85,6 +85,8 @@ char *pgparams = NULL; double twarn = (double)DEFAULT_WARN; double tcrit = (double)DEFAULT_CRIT; char *pgquery = NULL; +#define OPTID_QUERYNAME -1000 +char *pgqueryname = NULL; char *query_warning = NULL; char *query_critical = NULL; thresholds *qthresholds = NULL; @@ -285,6 +287,7 @@ process_arguments (int argc, char **argv) {"database", required_argument, 0, 'd'}, {"option", required_argument, 0, 'o'}, {"query", required_argument, 0, 'q'}, + {"queryname", required_argument, 0, OPTID_QUERYNAME}, {"query_critical", required_argument, 0, 'C'}, {"query_warning", required_argument, 0, 'W'}, {"verbose", no_argument, 0, 'v'}, @@ -368,6 +371,9 @@ process_arguments (int argc, char **argv) case 'q': pgquery = optarg; break; + case OPTID_QUERYNAME: + pgqueryname = optarg; + break; case 'v': verbose++; break; @@ -529,6 +535,9 @@ print_help (void) printf (" %s\n", "-q, --query=STRING"); printf (" %s\n", _("SQL query to run. Only first column in first row will be read")); + printf (" %s\n", "--queryname=STRING"); + printf (" %s\n", _("A name for the query, this string is used instead of the query")); + printf (" %s\n", _("in the long output of the plugin")); printf (" %s\n", "-W, --query-warning=RANGE"); printf (" %s\n", _("SQL query value to result in warning status (double)")); printf (" %s\n", "-C, --query-critical=RANGE"); @@ -642,7 +651,13 @@ do_query (PGconn *conn, char *query) : (my_status == STATE_CRITICAL) ? _("CRITICAL") : _("UNKNOWN")); - printf (_("'%s' returned %f"), query, value); + if(pgqueryname) { + printf (_("%s returned %f"), pgqueryname, value); + } + else { + printf (_("'%s' returned %f"), query, value); + } + printf ("|query=%f;%s;%s;;\n", value, query_warning ? query_warning : "", query_critical ? query_critical : ""); -- cgit v1.2.3-74-g34f1 From 737412f7391ae430a51e8f2c2a3b1ab2d35a6394 Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Sat, 29 Jan 2022 11:11:36 +0100 Subject: check_http and check_curl: added --max-redirs=N option (feature #1684) --- plugins/check_curl.c | 16 ++++++++++++++-- plugins/check_http.c | 20 ++++++++++++++++---- 2 files changed, 30 insertions(+), 6 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 14cc8463..32d919fe 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -66,13 +66,13 @@ const char *email = "devel@monitoring-plugins.org"; #define DEFAULT_BUFFER_SIZE 2048 #define DEFAULT_SERVER_URL "/" #define HTTP_EXPECT "HTTP/" -#define DEFAULT_MAX_REDIRS 15 #define INET_ADDR_MAX_SIZE INET6_ADDRSTRLEN enum { MAX_IPV4_HOSTLENGTH = 255, HTTP_PORT = 80, HTTPS_PORT = 443, - MAX_PORT = 65535 + MAX_PORT = 65535, + DEFAULT_MAX_REDIRS = 15 }; enum { @@ -1210,6 +1210,7 @@ process_arguments (int argc, char **argv) enum { INVERT_REGEX = CHAR_MAX + 1, SNI_OPTION, + MAX_REDIRS_OPTION, CA_CERT_OPTION, HTTP_VERSION_OPTION, AUTOMATIC_DECOMPRESSION @@ -1254,6 +1255,7 @@ process_arguments (int argc, char **argv) {"use-ipv6", no_argument, 0, '6'}, {"extended-perfdata", no_argument, 0, 'E'}, {"show-body", no_argument, 0, 'B'}, + {"max-redirs", required_argument, 0, MAX_REDIRS_OPTION}, {"http-version", required_argument, 0, HTTP_VERSION_OPTION}, {"enable-automatic-decompression", no_argument, 0, AUTOMATIC_DECOMPRESSION}, {0, 0, 0, 0} @@ -1512,6 +1514,13 @@ process_arguments (int argc, char **argv) use_sni = TRUE; break; #endif /* LIBCURL_FEATURE_SSL */ + case MAX_REDIRS_OPTION: + if (!is_intnonneg (optarg)) + usage2 (_("Invalid max_redirs count"), optarg); + else { + max_depth = atoi (optarg); + } + break; case 'f': /* onredirect */ if (!strcmp (optarg, "ok")) onredirect = STATE_OK; @@ -1854,6 +1863,9 @@ print_help (void) printf (" %s\n", _("specified IP address. stickyport also ensures port stays the same.")); printf (" %s\n", _("follow uses the old redirection algorithm of check_http.")); printf (" %s\n", _("curl uses CURL_FOLLOWLOCATION built into libcurl.")); + printf (" %s\n", "--max-redirs=INTEGER"); + printf (" %s", _("Maximal number of redirects (default: ")); + printf ("%d)\n", DEFAULT_MAX_REDIRS); printf (" %s\n", "-m, --pagesize=INTEGER<:INTEGER>"); printf (" %s\n", _("Minimum page size required (bytes) : Maximum page size required (bytes)")); printf ("\n"); diff --git a/plugins/check_http.c b/plugins/check_http.c index 34fb4f01..df2a79c2 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -52,7 +52,8 @@ enum { MAX_IPV4_HOSTLENGTH = 255, HTTP_PORT = 80, HTTPS_PORT = 443, - MAX_PORT = 65535 + MAX_PORT = 65535, + DEFAULT_MAX_REDIRS = 15 }; #ifdef HAVE_SSL @@ -125,7 +126,7 @@ int sd; int min_page_len = 0; int max_page_len = 0; int redir_depth = 0; -int max_depth = 15; +int max_depth = DEFAULT_MAX_REDIRS; char *http_method; char *http_method_proxy; char *http_post_data; @@ -203,7 +204,8 @@ process_arguments (int argc, char **argv) enum { INVERT_REGEX = CHAR_MAX + 1, - SNI_OPTION + SNI_OPTION, + MAX_REDIRS_OPTION }; int option = 0; @@ -242,6 +244,7 @@ process_arguments (int argc, char **argv) {"use-ipv6", no_argument, 0, '6'}, {"extended-perfdata", no_argument, 0, 'E'}, {"show-body", no_argument, 0, 'B'}, + {"max-redirs", required_argument, 0, MAX_REDIRS_OPTION}, {0, 0, 0, 0} }; @@ -373,6 +376,13 @@ process_arguments (int argc, char **argv) case SNI_OPTION: use_sni = TRUE; break; + case MAX_REDIRS_OPTION: + if (!is_intnonneg (optarg)) + usage2 (_("Invalid max_redirs count"), optarg); + else { + max_depth = atoi (optarg); + } + break; case 'f': /* onredirect */ if (!strcmp (optarg, "stickyport")) onredirect = STATE_DEPENDENT, followsticky = STICKY_HOST|STICKY_PORT; @@ -1657,9 +1667,11 @@ print_help (void) printf (" %s\n", "-f, --onredirect="); printf (" %s\n", _("How to handle redirected pages. sticky is like follow but stick to the")); printf (" %s\n", _("specified IP address. stickyport also ensures port stays the same.")); + printf (" %s\n", "--max-redirs=INTEGER"); + printf (" %s", _("Maximal number of redirects (default: ")); + printf ("%d)\n", DEFAULT_MAX_REDIRS); printf (" %s\n", "-m, --pagesize=INTEGER<:INTEGER>"); printf (" %s\n", _("Minimum page size required (bytes) : Maximum page size required (bytes)")); - printf (UT_WARN_CRIT); printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); -- cgit v1.2.3-74-g34f1 From ee2a60fc4e26828b115051564706f8fbc4c4b153 Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Thu, 27 Jan 2022 10:00:58 +0100 Subject: fixed -ffollow for HTTP/2.0 (Fixes #1685): added major_version parsing to PicoHTTPParser --- plugins/check_curl.c | 6 +++--- plugins/picohttpparser/picohttpparser.c | 30 ++++++++++++++++++------------ plugins/picohttpparser/picohttpparser.h | 4 ++-- 3 files changed, 23 insertions(+), 17 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 32d919fe..7da84de4 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -1054,7 +1054,7 @@ redir (curlhelp_write_curlbuf* header_buf) char *new_url; int res = phr_parse_response (header_buf->buf, header_buf->buflen, - &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen, + &status_line.http_major, &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen, headers, &nof_headers, 0); location = get_header_value (headers, nof_headers, "location"); @@ -2200,7 +2200,7 @@ check_document_dates (const curlhelp_write_curlbuf *header_buf, char (*msg)[DEFA size_t msglen; int res = phr_parse_response (header_buf->buf, header_buf->buflen, - &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen, + &status_line.http_major, &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen, headers, &nof_headers, 0); server_date = get_header_value (headers, nof_headers, "date"); @@ -2258,7 +2258,7 @@ get_content_length (const curlhelp_write_curlbuf* header_buf, const curlhelp_wri curlhelp_statusline status_line; int res = phr_parse_response (header_buf->buf, header_buf->buflen, - &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen, + &status_line.http_major, &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen, headers, &nof_headers, 0); content_length_s = get_header_value (headers, nof_headers, "content-length"); diff --git a/plugins/picohttpparser/picohttpparser.c b/plugins/picohttpparser/picohttpparser.c index 74ccc3ef..d9680b79 100644 --- a/plugins/picohttpparser/picohttpparser.c +++ b/plugins/picohttpparser/picohttpparser.c @@ -242,7 +242,7 @@ static const char *is_complete(const char *buf, const char *buf_end, size_t last } while (0) /* returned pointer is always within [buf, buf_end), or null */ -static const char *parse_http_version(const char *buf, const char *buf_end, int *minor_version, int *ret) +static const char *parse_http_version(const char *buf, const char *buf_end, int *major_version, int *minor_version, int *ret) { /* we want at least [HTTP/1.] to try to parse */ if (buf_end - buf < 9) { @@ -254,9 +254,13 @@ static const char *parse_http_version(const char *buf, const char *buf_end, int EXPECT_CHAR_NO_CHECK('T'); EXPECT_CHAR_NO_CHECK('P'); EXPECT_CHAR_NO_CHECK('/'); - EXPECT_CHAR_NO_CHECK('1'); - EXPECT_CHAR_NO_CHECK('.'); - PARSE_INT(minor_version, 1); + PARSE_INT(major_version, 1); + if (*major_version == 1) { + EXPECT_CHAR_NO_CHECK('.'); + PARSE_INT(minor_version, 1); + } else { + *minor_version = 0; + } return buf; } @@ -339,7 +343,7 @@ static const char *parse_headers(const char *buf, const char *buf_end, struct ph } static const char *parse_request(const char *buf, const char *buf_end, const char **method, size_t *method_len, const char **path, - size_t *path_len, int *minor_version, struct phr_header *headers, size_t *num_headers, + size_t *path_len, int *major_version, int *minor_version, struct phr_header *headers, size_t *num_headers, size_t max_headers, int *ret) { /* skip first empty line (some clients add CRLF after POST content) */ @@ -364,7 +368,7 @@ static const char *parse_request(const char *buf, const char *buf_end, const cha *ret = -1; return NULL; } - if ((buf = parse_http_version(buf, buf_end, minor_version, ret)) == NULL) { + if ((buf = parse_http_version(buf, buf_end, major_version, minor_version, ret)) == NULL) { return NULL; } if (*buf == '\015') { @@ -381,7 +385,7 @@ static const char *parse_request(const char *buf, const char *buf_end, const cha } int phr_parse_request(const char *buf_start, size_t len, const char **method, size_t *method_len, const char **path, - size_t *path_len, int *minor_version, struct phr_header *headers, size_t *num_headers, size_t last_len) + size_t *path_len, int *major_version, int *minor_version, struct phr_header *headers, size_t *num_headers, size_t last_len) { const char *buf = buf_start, *buf_end = buf_start + len; size_t max_headers = *num_headers; @@ -391,6 +395,7 @@ int phr_parse_request(const char *buf_start, size_t len, const char **method, si *method_len = 0; *path = NULL; *path_len = 0; + *major_version = -1; *minor_version = -1; *num_headers = 0; @@ -400,7 +405,7 @@ int phr_parse_request(const char *buf_start, size_t len, const char **method, si return r; } - if ((buf = parse_request(buf, buf_end, method, method_len, path, path_len, minor_version, headers, num_headers, max_headers, + if ((buf = parse_request(buf, buf_end, method, method_len, path, path_len, major_version, minor_version, headers, num_headers, max_headers, &r)) == NULL) { return r; } @@ -408,11 +413,11 @@ int phr_parse_request(const char *buf_start, size_t len, const char **method, si return (int)(buf - buf_start); } -static const char *parse_response(const char *buf, const char *buf_end, int *minor_version, int *status, const char **msg, +static const char *parse_response(const char *buf, const char *buf_end, int *major_version, int *minor_version, int *status, const char **msg, size_t *msg_len, struct phr_header *headers, size_t *num_headers, size_t max_headers, int *ret) { /* parse "HTTP/1.x" */ - if ((buf = parse_http_version(buf, buf_end, minor_version, ret)) == NULL) { + if ((buf = parse_http_version(buf, buf_end, major_version, minor_version, ret)) == NULL) { return NULL; } /* skip space */ @@ -451,13 +456,14 @@ static const char *parse_response(const char *buf, const char *buf_end, int *min return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret); } -int phr_parse_response(const char *buf_start, size_t len, int *minor_version, int *status, const char **msg, size_t *msg_len, +int phr_parse_response(const char *buf_start, size_t len, int *major_version, int *minor_version, int *status, const char **msg, size_t *msg_len, struct phr_header *headers, size_t *num_headers, size_t last_len) { const char *buf = buf_start, *buf_end = buf + len; size_t max_headers = *num_headers; int r; + *major_version = -1; *minor_version = -1; *status = 0; *msg = NULL; @@ -470,7 +476,7 @@ int phr_parse_response(const char *buf_start, size_t len, int *minor_version, in return r; } - if ((buf = parse_response(buf, buf_end, minor_version, status, msg, msg_len, headers, num_headers, max_headers, &r)) == NULL) { + if ((buf = parse_response(buf, buf_end, major_version, minor_version, status, msg, msg_len, headers, num_headers, max_headers, &r)) == NULL) { return r; } diff --git a/plugins/picohttpparser/picohttpparser.h b/plugins/picohttpparser/picohttpparser.h index 0849f844..8f13b36f 100644 --- a/plugins/picohttpparser/picohttpparser.h +++ b/plugins/picohttpparser/picohttpparser.h @@ -49,10 +49,10 @@ struct phr_header { /* returns number of bytes consumed if successful, -2 if request is partial, * -1 if failed */ int phr_parse_request(const char *buf, size_t len, const char **method, size_t *method_len, const char **path, size_t *path_len, - int *minor_version, struct phr_header *headers, size_t *num_headers, size_t last_len); + int *major_version, int *minor_version, struct phr_header *headers, size_t *num_headers, size_t last_len); /* ditto */ -int phr_parse_response(const char *_buf, size_t len, int *minor_version, int *status, const char **msg, size_t *msg_len, +int phr_parse_response(const char *_buf, size_t len, int *major_version, int *minor_version, int *status, const char **msg, size_t *msg_len, struct phr_header *headers, size_t *num_headers, size_t last_len); /* ditto */ -- cgit v1.2.3-74-g34f1 From 31bdbfce92de2dc7717fe13a8d1ca8e7dbf850d4 Mon Sep 17 00:00:00 2001 From: Tobias Wiese Date: Sun, 23 May 2021 01:39:15 +0200 Subject: sslutils: use chain from client certificates sslutils used to load only the first certificate when it was given a client certificate file. Added tests for check_http to connect to a http server that expects a client certificate (simple and with chain). Signed-off-by: Tobias Wiese --- plugins/sslutils.c | 2 +- plugins/tests/certs/.gitignore | 2 + plugins/tests/certs/client-cert.pem | 22 ++ plugins/tests/certs/client-key.pem | 28 +++ plugins/tests/certs/clientca-cert.pem | 25 +++ plugins/tests/certs/clientca-key.pem | 28 +++ plugins/tests/certs/clientchain-cert.pem | 45 +++++ plugins/tests/certs/clientchain-key.pem | 28 +++ plugins/tests/certs/clientintermediate-cert.pem | 23 +++ plugins/tests/certs/clientintermediate-key.pem | 28 +++ plugins/tests/certs/expired-cert.pem | 32 +-- plugins/tests/certs/expired-key.pem | 52 ++--- plugins/tests/certs/ext.cnf | 2 + plugins/tests/certs/generate-certs.sh | 63 ++++++ plugins/tests/certs/server-cert.pem | 44 ++-- plugins/tests/certs/server-key.pem | 52 ++--- plugins/tests/check_curl.t | 10 +- plugins/tests/check_http.t | 256 ++++++++++++++---------- 18 files changed, 538 insertions(+), 204 deletions(-) create mode 100644 plugins/tests/certs/.gitignore create mode 100644 plugins/tests/certs/client-cert.pem create mode 100644 plugins/tests/certs/client-key.pem create mode 100644 plugins/tests/certs/clientca-cert.pem create mode 100644 plugins/tests/certs/clientca-key.pem create mode 100644 plugins/tests/certs/clientchain-cert.pem create mode 100644 plugins/tests/certs/clientchain-key.pem create mode 100644 plugins/tests/certs/clientintermediate-cert.pem create mode 100644 plugins/tests/certs/clientintermediate-key.pem create mode 100644 plugins/tests/certs/ext.cnf create mode 100755 plugins/tests/certs/generate-certs.sh (limited to 'plugins') diff --git a/plugins/sslutils.c b/plugins/sslutils.c index 14f6579d..286273f6 100644 --- a/plugins/sslutils.c +++ b/plugins/sslutils.c @@ -134,7 +134,7 @@ int np_net_ssl_init_with_hostname_version_and_cert(int sd, char *host_name, int return STATE_CRITICAL; } if (cert && privkey) { - SSL_CTX_use_certificate_file(c, cert, SSL_FILETYPE_PEM); + SSL_CTX_use_certificate_chain_file(c, cert); SSL_CTX_use_PrivateKey_file(c, privkey, SSL_FILETYPE_PEM); #ifdef USE_OPENSSL if (!SSL_CTX_check_private_key(c)) { diff --git a/plugins/tests/certs/.gitignore b/plugins/tests/certs/.gitignore new file mode 100644 index 00000000..79acaaa5 --- /dev/null +++ b/plugins/tests/certs/.gitignore @@ -0,0 +1,2 @@ +/*.csr +/*.srl diff --git a/plugins/tests/certs/client-cert.pem b/plugins/tests/certs/client-cert.pem new file mode 100644 index 00000000..5709750d --- /dev/null +++ b/plugins/tests/certs/client-cert.pem @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDtDCCApwCAQIwDQYJKoZIhvcNAQELBQAwgaAxCzAJBgNVBAYTAkRFMRAwDgYD +VQQIDAdCYXZhcmlhMQ8wDQYDVQQHDAZNdW5pY2gxGzAZBgNVBAoMEk1vbml0b3Jp +bmcgUGx1Z2luczEkMCIGA1UEAwwbTW9uaXRvcmluZyBQbHVnaW5zIENsaWVudENB +MSswKQYJKoZIhvcNAQkBFhxkZXZlbEBtb25pdG9yaW5nLXBsdWdpbnMub3JnMB4X +DTIxMDIyODIxMDIxMloXDTMwMTEyODIxMDIxMlowgZ4xCzAJBgNVBAYTAkRFMRAw +DgYDVQQIDAdCYXZhcmlhMQ8wDQYDVQQHDAZNdW5pY2gxGzAZBgNVBAoMEk1vbml0 +b3JpbmcgUGx1Z2luczEiMCAGA1UEAwwZTW9uaXRvcmluZyBQbHVnaW5zIENsaWVu +dDErMCkGCSqGSIb3DQEJARYcZGV2ZWxAbW9uaXRvcmluZy1wbHVnaW5zLm9yZzCC +ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAM3EiqfFPomm5dZQPGYG5SrF +rPvyqseXTzCkwUIUzGf+Sfm3s13zx7e3ije/04yKhTXgK59EQ793q7E2aWhSOz3s +hwKKdylFkOIyc5jgbAfF1/pLZMK209rLt/mMRksXCRXYrHdTjRMx1ev4C2407+8Y +8qkf77DuYQmUqCQe7DPOvqLeagdw9JcLGmQNTKHg3fl6wyRl5K1Bsy+qXu2XvEjZ +0Ng7n8LHjOUkTqUEJndOxci9gL5cHU5ttul/GW34dKOtTuMU/pQX6/ywYusOGVOx +RYI76OolRqj5BqbNctDIB/obe2RLo+UVx74/0jAxtH4XS23pYjO7NUpJcytsVG8C +AwEAATANBgkqhkiG9w0BAQsFAAOCAQEAYfaY5n4pCq0NWPCdeVVRr4nr+GAfv1TC +/PKcGuEoJZKt7TQT+OOA5yeZMZb53OvtA49D1r9aoJzWe946KElWOEBqxDRi5Cdr +wkqpwGcPT2RfAqA3/cvQZ1XsquboXrCf7ajdl5OC64bs2jkqCFh9gnxuI140g8Ar +Njol8BFxRPaYWOnwuQwmh/2t0FJqr3WSD85HrNqtxUSNGbTdSsvCfgF0v7QVkvLG +3/cbx6z5hxzj2JUjhMnCvn+EbasoJt4xyBFvg67Q2229SMwu9YNqS63GVoKUqhCB +4Gl5v31qx8dAFKuRvnez3ze/6oohwmakZkst4hcQdgZocHhzesvKlg== +-----END CERTIFICATE----- diff --git a/plugins/tests/certs/client-key.pem b/plugins/tests/certs/client-key.pem new file mode 100644 index 00000000..09b6761d --- /dev/null +++ b/plugins/tests/certs/client-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDNxIqnxT6JpuXW +UDxmBuUqxaz78qrHl08wpMFCFMxn/kn5t7Nd88e3t4o3v9OMioU14CufREO/d6ux +NmloUjs97IcCincpRZDiMnOY4GwHxdf6S2TCttPay7f5jEZLFwkV2Kx3U40TMdXr ++AtuNO/vGPKpH++w7mEJlKgkHuwzzr6i3moHcPSXCxpkDUyh4N35esMkZeStQbMv +ql7tl7xI2dDYO5/Cx4zlJE6lBCZ3TsXIvYC+XB1Obbbpfxlt+HSjrU7jFP6UF+v8 +sGLrDhlTsUWCO+jqJUao+QamzXLQyAf6G3tkS6PlFce+P9IwMbR+F0tt6WIzuzVK +SXMrbFRvAgMBAAECggEBALtc2pB3p0E6KpAiEU0pvCRdSO1FgsIpAd+eNadRPur2 +fi+XWQkUwGeGBaJL1npja3aqP65PP40pj7nWfNaUAgOZyznCEU0QXiPJor6yo0vU +l5v+aKpwRao107i0RRF80TYGTMx+1LeEqnCqNOZN56gERHlBbkTiWpOZvBzf1143 +oegTcyM6+Ee6+FYNhHaDyIYD0md1S2wGR+IBPet6HwWiakLNKahFPa7lOLIKfmmD +iTtifcbf4724wSe44a0uTeP4JrquZSeIKakm8MEmffmYqpycnaakYefd0Xc5UEsH ++VbhKpOWGY3d8FKHqUsTa+6QyXb2uFPo6A+yWm0pdJECgYEA7Prd5sbWACvXOcHT +ONDBAgyfAVDQwOXi3D4dk6D5mg+/jxl5ZQY5slszJrwsLFtoEzXtYpNfTy3cpNOp +JLbBDZYnqty+5tD8t3/Zv2IBXCAgvuk5CgfJWP5FNAfiyUEE6Vbp6J/5/vAnODsa +fxZryN5UsH0X8ew7AlbfcVNyj4kCgYEA3khetIgn+GR6sv9jFRdCT6aJbp0xMsms +6F4v3L5FG4Kp+SwDHL1bVOhieJ5g8odYp9hDbgTEEqbJfNmyCOu9+OQmZ/mztku7 +6reU8HhYBIvi+hFeJmvqKpdIgU0Zveg4Bst5QordmhPk8AHjBC4xvQ++uh7rwYKd +WVsS08bGDjcCgYEAlAuNARUKsASzakOqHv5a9VrJIttH7povBYRQmd+gzxwzgcRa +UEB5XvEWnYZE2lkoRYgVCtYiXqa6BsasDmGVbVV25okNQckhd8mJUMR7MQBpNJsi +pR+EK/J9bSnYBf52gQdpDYiTdy60ca6KuQZaw5wRsEgV426+1pFK+dM16HECgYBY +cTsdYb9lmbUoW201CxgbUQwFsw3MQ2pE2pT4o8wjcg3nUpe6a61XT08+5uV0Gl4w +CmBp+gN52Fr7DjNEUWg5C64sWLIkqmWOspTUSU3cITyiex6W8wEtCRyUNfU0Fp2U +Nol87HvXvmqtBFMraqXnr8gXjg4H5MxurUoEcWaEaQKBgCT4iIGZwW0Qf2rkFC7B +xObzVGefivVVbaf8/c/LRO8TMLdnExkShMOmCzHeHV4mMEZDLbMOusHCI7xm10EX +l3L1I1Kyqnhm1RH3e7TVWgkTmIDW3V5Fgrhm1jx5Iz6et4sb4Uh+bZq9tTLyqfZY +8s0yJUrfpjRggfk7eUs5s7aY +-----END PRIVATE KEY----- diff --git a/plugins/tests/certs/clientca-cert.pem b/plugins/tests/certs/clientca-cert.pem new file mode 100644 index 00000000..9ce7cd7d --- /dev/null +++ b/plugins/tests/certs/clientca-cert.pem @@ -0,0 +1,25 @@ +-----BEGIN CERTIFICATE----- +MIIEIzCCAwugAwIBAgIUL9Jfp5zv5B29NgDsNEFU2OM/UHswDQYJKoZIhvcNAQEL +BQAwgaAxCzAJBgNVBAYTAkRFMRAwDgYDVQQIDAdCYXZhcmlhMQ8wDQYDVQQHDAZN +dW5pY2gxGzAZBgNVBAoMEk1vbml0b3JpbmcgUGx1Z2luczEkMCIGA1UEAwwbTW9u +aXRvcmluZyBQbHVnaW5zIENsaWVudENBMSswKQYJKoZIhvcNAQkBFhxkZXZlbEBt +b25pdG9yaW5nLXBsdWdpbnMub3JnMB4XDTIxMDIyODIxMDIxMVoXDTMwMTEyODIx +MDIxMVowgaAxCzAJBgNVBAYTAkRFMRAwDgYDVQQIDAdCYXZhcmlhMQ8wDQYDVQQH +DAZNdW5pY2gxGzAZBgNVBAoMEk1vbml0b3JpbmcgUGx1Z2luczEkMCIGA1UEAwwb +TW9uaXRvcmluZyBQbHVnaW5zIENsaWVudENBMSswKQYJKoZIhvcNAQkBFhxkZXZl +bEBtb25pdG9yaW5nLXBsdWdpbnMub3JnMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A +MIIBCgKCAQEAyxiWsGrsJFHw3VR0pqHviXUfbfKMw8LaCxI5EQZfInsMVkBIGWEW +tFW6qDuAOsMdzsrKOnQRNNt852ts/0Uz++z8zysoauAGpc4JnCZuM5A1DU5CFXBx +w6Ax+1ft3UsTt8C6kfLfs8mPCbtNVqAHrMrIqDxsNSRRxQSqkzp1vD8rwSKcbB1h +u2+lut1bEqMe7dp89jKOtc6G/1tHUFQuLAGFoX/qk9yPscmQNzL6YbLP4m9r/416 +PsxWsAfyY97hmoYo6mSCue5LmeanOsjf4Kzq90hIJRwrpiUGmxGjW+tPLEhQBZw6 +C2wHyN74YIJYX2xREz2ijT0mgsqdhO5ZxwIDAQABo1MwUTAdBgNVHQ4EFgQUtsP9 +Z3fKkhmFp97Kh/cW/UqHMIMwHwYDVR0jBBgwFoAUtsP9Z3fKkhmFp97Kh/cW/UqH +MIMwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEApO5o+YECwTEv +s+elDJZQ20UYwDSiU9Lpf4EcdnRv6FAb5UlhfRTH3ZdKCc/HX7kcKuy3PsF+b8Pw +EusoKito9OlNEOF5HYAI9/J54/qceqn+SC0INsISeE19PvT0dma7lBSj4OvBv0IS +GYbdztVaKLWqYgYs0mcEzteUc4MZcy1/C+Ru1i1Kp2s9/vIeAw2PV2+kpWtw88Pb +FRJomGngP/hQdwniayCltG/Q1smS4iFEHNI5ayLZj1qJGMHwzqGiRr4KknJKfHzv +fl4NQaFyMY31s1FRIS6QVIRFHVzUAlKZTdzwqEJygg3fUS9n9uDBnyDI/sW7DQuj +yjSmYRS1hw== +-----END CERTIFICATE----- diff --git a/plugins/tests/certs/clientca-key.pem b/plugins/tests/certs/clientca-key.pem new file mode 100644 index 00000000..a939f035 --- /dev/null +++ b/plugins/tests/certs/clientca-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDLGJawauwkUfDd +VHSmoe+JdR9t8ozDwtoLEjkRBl8iewxWQEgZYRa0VbqoO4A6wx3Oyso6dBE023zn +a2z/RTP77PzPKyhq4AalzgmcJm4zkDUNTkIVcHHDoDH7V+3dSxO3wLqR8t+zyY8J +u01WoAesysioPGw1JFHFBKqTOnW8PyvBIpxsHWG7b6W63VsSox7t2nz2Mo61zob/ +W0dQVC4sAYWhf+qT3I+xyZA3Mvphss/ib2v/jXo+zFawB/Jj3uGahijqZIK57kuZ +5qc6yN/grOr3SEglHCumJQabEaNb608sSFAFnDoLbAfI3vhgglhfbFETPaKNPSaC +yp2E7lnHAgMBAAECggEAJqAWiJbNMlsjI/Tb+pTxqYLM52wpuVFlhpWApOxBS517 +SywOikUcvE9RoI0wZfyVvq5yp4tLenID3z9fC21t5Yu8yOm8VhclLINy8G+epc/X +RyCLEOjBuiLNXq/qXRvaNChDU16NjPPYcFFe9AqbaxFl+BkFu1Wc94tbpYSIv7Qt +L6iBxUTXdgvLM5doa9AazIQzJx+jUsVCgRVQQf3zsLqtp9hH0Pfq+KWFIy5TA+bG +0NFmYyQndRjtT0ihWGuNU7D8AXa+z7abzk+HydIlx4D//vGgdNq92QYPdnu2BBya +5Fs6LkmkUonX/I8FbkLbRKkQWNPMt+Ks21t3xcVBgQKBgQDn4HuHVCPwxgU6Mv+5 +0sHJXYBq1fDzrUt0+iTtYkRqViX+9Mp4sUpYgXext/wXFLcKzQQp5B0g1dLYLSRS +KwhsdiN0J7ZcoP1GMStw8zsayRTf8C3WRU6aACqyFiylYbyh56XomfYgwhja/7l9 +pzpVJD9ecG+mLVAyAkJtK2JolQKBgQDgOZfvrQj0L4QG+9E5VmFc3PE+6k3g+zDO +MWqTSh0fOHqdTEyet4bMC4DogXGVsvw0/UKwbrGHOk0+ltA5VyKUtK/whSutr/+S +nhCHljhV0XUN/I3OFcvezFjM3g0oC4uy1cL30hoM4IfeHM1d3EYse9N1Y/Op+mR6 +Sx+fEku16wKBgQC0KQ7RjuZ95N2a4pUe5En9EtD8MU4Nhs/iC5k1d+yAUn8jIT9P +lzCUo8NEKheMN2Qg2Dor8jlPkdNIc4qM7TKWUxQo49IlFlCzgPCnydRac3HsrMhw +e1ke/pIt3FzEArR1d27I0xcRTL3TKm4M2ynPjWJPFj0peHue33KNL/A+IQKBgEpL +awd0Sxo1wEZcG9gmwf32C01wbzuTn3lCsHB7Ryj4GtCR3nVclCJ50U24zjzu4Fhi +bj1tgA8xhzSs3fOR5phlQkKsrWtQfJtFGm8CnEn7LBDlVMsrN7Dr/qRrEuro4HHy +GDbq+8y2fO5glr955BqLMOadprf0imRnDeQ0OLffAoGBAJio+X+xpglgMOC4BeH9 +9LcYi9nUEw8MDJNGo9/3e0XKA7spd3HShLDvt8YZhFJ2m168qBpGfezuw0+jpWxy +PV9q0dokAgDx4pvCzIKaptZ1D30CWXJZHq25VK1tA41PCUIOh8JD5+R0MpxA5rn2 +DbqL4Vq7K7K0imGENYhHdyM+ +-----END PRIVATE KEY----- diff --git a/plugins/tests/certs/clientchain-cert.pem b/plugins/tests/certs/clientchain-cert.pem new file mode 100644 index 00000000..acd1e3e8 --- /dev/null +++ b/plugins/tests/certs/clientchain-cert.pem @@ -0,0 +1,45 @@ +-----BEGIN CERTIFICATE----- +MIIDuTCCAqECAQQwDQYJKoZIhvcNAQELBQAwgaAxCzAJBgNVBAYTAkRFMRAwDgYD +VQQIDAdCYXZhcmlhMQ8wDQYDVQQHDAZNdW5pY2gxGzAZBgNVBAoMEk1vbml0b3Jp +bmcgUGx1Z2luczEkMCIGA1UEAwwbTW9uaXRvcmluZyBQbHVnaW5zIENsaWVudENB +MSswKQYJKoZIhvcNAQkBFhxkZXZlbEBtb25pdG9yaW5nLXBsdWdpbnMub3JnMB4X +DTIxMDIyODIxMDIxMloXDTMwMTEyODIxMDIxMlowgaMxCzAJBgNVBAYTAkRFMRAw +DgYDVQQIDAdCYXZhcmlhMQ8wDQYDVQQHDAZNdW5pY2gxGzAZBgNVBAoMEk1vbml0 +b3JpbmcgUGx1Z2luczEnMCUGA1UEAwweTW9uaXRvcmluZyBQbHVnaW5zIENsaWVu +dENoYWluMSswKQYJKoZIhvcNAQkBFhxkZXZlbEBtb25pdG9yaW5nLXBsdWdpbnMu +b3JnMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAphvoJBbi/rDvm3+X +8xok0sLCJvCRuUpSbU5wEmREQlkoOGmWK4l6r1JyOphKRBo8+n2MxPiCMvAmTrqx +VlBmkcmyrwWj392Nga+2SLWTziASk5nFrrhV6U79PkgXnETV2Wk1/FNVIFkB8N+B +undsTce8LLiCs7hfA5CK7ctJg8fqsAsmgKBNGzBRWwkbvxZPd6xlY6foIJeD7PQ2 +elvTmrD6WXSZq7GshFpDEkL3AifqrPMdsTnbBpyGgJ/fBM1b2dx9k53e25mgEQmn +iSuYQxn08BsUT0FOvav8ksZLBQz859fuqCtwhikpODO635fD9zK5YkBPlVl+/5xo +SvKOywIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQBh4zeSKjENfY+VDLtPssaNQz2a +R1ioY40lZ0WoihDSrfG32dqTK/R2YsLKBABjJ7uRYS1NIBMrtS2OktK8BWD5IUTF +FuGuWilu6IWiTKZrLiZh1rsilNDVqwhorRPxDnbF+qVt9EMIvzKnKdJLGF+CWHN9 +yYJDeTD8MK5uR7zUJR3PsgW4ve5pFTi7z2UJ/xRvgOds6bmeeQnvaWDEL7k2+hrr +0G899A086NL3htzaOnIllg0xo2D1o4ToncAJn+cUQVJmHZSg9HYiD4Lg3z8uXPAl +rt/MX7dBm4dnImLXbSg7N3e8FdUtz+kZT9z+beKAeIe9JTbpxtsVUTzUZBBA +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIID2jCCAsKgAwIBAgIBAzANBgkqhkiG9w0BAQsFADCBoDELMAkGA1UEBhMCREUx +EDAOBgNVBAgMB0JhdmFyaWExDzANBgNVBAcMBk11bmljaDEbMBkGA1UECgwSTW9u +aXRvcmluZyBQbHVnaW5zMSQwIgYDVQQDDBtNb25pdG9yaW5nIFBsdWdpbnMgQ2xp +ZW50Q0ExKzApBgkqhkiG9w0BCQEWHGRldmVsQG1vbml0b3JpbmctcGx1Z2lucy5v +cmcwHhcNMjEwMjI4MjEwMjEyWhcNMzAxMTI4MjEwMjEyWjCBqjELMAkGA1UEBhMC +REUxEDAOBgNVBAgMB0JhdmFyaWExDzANBgNVBAcMBk11bmljaDEbMBkGA1UECgwS +TW9uaXRvcmluZyBQbHVnaW5zMS4wLAYDVQQDDCVNb25pdG9yaW5nIFBsdWdpbnMg +Q2xpZW50SW50ZXJtZWRpYXRlMSswKQYJKoZIhvcNAQkBFhxkZXZlbEBtb25pdG9y +aW5nLXBsdWdpbnMub3JnMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA +6rUgOZ9pAOxrcgeeOT3Vmu1YmY2O/C9tXhpKzDzjTaWUzcdDg00KdsjXfgbDzSiV +uvMzjX63aKpmqeFG+05D2VzQGit3knqerUgl10FnTotiJGF5CU5/gY1aPxTJ7rj2 +tD6LINBkJcPTyQ4MoJT19pssvCax9erY1RxoXxLblJ+31C+VvrftdmBP4nVKXK26 +4anb1oUQhkgpXpJimJBmF+v7NbDs1Wh21Be80KXUh9SKgePhSQblr2QlRcA7jLgJ +4PMjZ+KYF+da+4RB7s+DvTXVDMn9AL84E1w5Ut1E8XZV+u4RjWPvNdhK/7GnuxOR +C9SdxonqkPQ8hiI7thP9bQIDAQABoxMwETAPBgNVHRMBAf8EBTADAQH/MA0GCSqG +SIb3DQEBCwUAA4IBAQDKQeiDbyr0/7sEhX33MmTDv84GeWgKl9qqHecx+d/0vImb +c8XHK0PDa4lVqo/BW4P1hjKzpt2DW35kbOhuqGqM0lasIczef43aCDDEBLwstAe6 +qMoyWGVGoAQbpwT3li2pMrsIYoPwMvoSGNUphjrkdpviff2POkLly7a5RrR1X3qt +Dai6eYbeMCr9NdgW7AZ5++/sKlFoe+zVk/Ed31s4D2lh3awrApZhVgcoquPmEwpt +gm+OgRmHw50U4SF3ZaJPwDyLMbx+clH/bgUg0+Za9e53Br1NtGKmw7hh/7CG/hy0 +yxeLd930pH4vZu7s0XM56N/ckkfUzRkAH8dSmhH4 +-----END CERTIFICATE----- diff --git a/plugins/tests/certs/clientchain-key.pem b/plugins/tests/certs/clientchain-key.pem new file mode 100644 index 00000000..0263604f --- /dev/null +++ b/plugins/tests/certs/clientchain-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCmG+gkFuL+sO+b +f5fzGiTSwsIm8JG5SlJtTnASZERCWSg4aZYriXqvUnI6mEpEGjz6fYzE+IIy8CZO +urFWUGaRybKvBaPf3Y2Br7ZItZPOIBKTmcWuuFXpTv0+SBecRNXZaTX8U1UgWQHw +34G6d2xNx7wsuIKzuF8DkIrty0mDx+qwCyaAoE0bMFFbCRu/Fk93rGVjp+ggl4Ps +9DZ6W9OasPpZdJmrsayEWkMSQvcCJ+qs8x2xOdsGnIaAn98EzVvZ3H2Tnd7bmaAR +CaeJK5hDGfTwGxRPQU69q/ySxksFDPzn1+6oK3CGKSk4M7rfl8P3MrliQE+VWX7/ +nGhK8o7LAgMBAAECggEAAfTqMyKh4eYrrGVAYPi53lG0/8htrwUVG3yFDXJo628p +biCwSCsCavZJqi8JEOxOM5UvB1L2FauGh/7i/+VKkAUUOcOTPpvZguGTACBDcXYn +Qd3Z2kkJmgn4Kbenr4uQCVOX8zT4F710rGW1nYCyoefsa4pw37UYSW52dH6kiwzW +9k4X251nDMl/twBdOcjZbL768IEa5l4nySLpUNwfrVbSb1NzBoH0dVioh3DTLjt6 +gaShW4eIpaKczht1U97n6/7WNLl6vHX/mR99k/py8OhzhR1ccYpd2IfSHAWyQT0M +K8BoNnkjICrr9oc0FCr2BVJa3IzKHlhukF4GTZiGYQKBgQDWCHTwAmwL4FFEBVhj +pZne/sjaZc8TzPPxA8SkmxwDIZrM7tSu7qUuYgWTM432jZbLILWTyGfXf2PpqyF6 +wOpoBJj1ETkre8ZfRmYvsSvS5vtjF3Drszol+XvZnOclfB5VG3m5P2vYkQ8wI9OE +Y5jUBgDj0RsCNd8QnrC1u54U/wKBgQDGrd5y8S9kUT0P0lkZit7bYjSPJExtClXt +V7YNTjELrVCdc0jranxBWaub8NP3e6TGTi9HiQWvk2eOAS2qyccqlK4+YAK5XO3D +EpFUNNcClq8CErw2POuCAKajrPuSp6vd6q8h4lTzDExVctQS4R9fRKKFBKkPUV5G +UiKFllnKNQKBgQDBGIQXfLfpxwjKK2BhFihKDOc8UhmOrZtvV4zzTJTrJkg4l0f+ +QoN34ytQcHSleXwP6oSmvWkh/GYxjBj6XE2eZndwsYc4ecSwdB0A7gCxl345Gg7g +NqRBWmGoJGxNXzsmYVFiFZvAmK5xKgFMMWbR8lCfOCn7xopmviSC8K9gFQKBgFRb +KmH/SbH8VELNews/TVQ0pEBKlzCM/OLjJOcNVgGxOtM/Say677sHibeST0168AFK +3QQwh3t+yK8gjPVA6xGHQ1w0g7OUY1c6IP5x2QC+XdwxfDxDLXNrN1WzcrVX/78f +j/CBGrR/ekGlmanSb/GRQLfdvLJGSBLveLzjk4gpAoGBANN9RUm/aRz3dDBWex46 +kJ15xKJfLZiUeyDvY5+5d7YF4/tw5LU4XmKQNhiojHecykrTzPUMaGyMrbMPNn32 +WFW9CKMjuBEwWpMDJJb1/5NLEvpwu++sr7bUPZkQl76ot6OqgNHodbP8ATqrNr80 +5b8FrEN1LyfkTbabxNyAWcA0 +-----END PRIVATE KEY----- diff --git a/plugins/tests/certs/clientintermediate-cert.pem b/plugins/tests/certs/clientintermediate-cert.pem new file mode 100644 index 00000000..608a8fa2 --- /dev/null +++ b/plugins/tests/certs/clientintermediate-cert.pem @@ -0,0 +1,23 @@ +-----BEGIN CERTIFICATE----- +MIID2jCCAsKgAwIBAgIBAzANBgkqhkiG9w0BAQsFADCBoDELMAkGA1UEBhMCREUx +EDAOBgNVBAgMB0JhdmFyaWExDzANBgNVBAcMBk11bmljaDEbMBkGA1UECgwSTW9u +aXRvcmluZyBQbHVnaW5zMSQwIgYDVQQDDBtNb25pdG9yaW5nIFBsdWdpbnMgQ2xp +ZW50Q0ExKzApBgkqhkiG9w0BCQEWHGRldmVsQG1vbml0b3JpbmctcGx1Z2lucy5v +cmcwHhcNMjEwMjI4MjEwMjEyWhcNMzAxMTI4MjEwMjEyWjCBqjELMAkGA1UEBhMC +REUxEDAOBgNVBAgMB0JhdmFyaWExDzANBgNVBAcMBk11bmljaDEbMBkGA1UECgwS +TW9uaXRvcmluZyBQbHVnaW5zMS4wLAYDVQQDDCVNb25pdG9yaW5nIFBsdWdpbnMg +Q2xpZW50SW50ZXJtZWRpYXRlMSswKQYJKoZIhvcNAQkBFhxkZXZlbEBtb25pdG9y +aW5nLXBsdWdpbnMub3JnMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA +6rUgOZ9pAOxrcgeeOT3Vmu1YmY2O/C9tXhpKzDzjTaWUzcdDg00KdsjXfgbDzSiV +uvMzjX63aKpmqeFG+05D2VzQGit3knqerUgl10FnTotiJGF5CU5/gY1aPxTJ7rj2 +tD6LINBkJcPTyQ4MoJT19pssvCax9erY1RxoXxLblJ+31C+VvrftdmBP4nVKXK26 +4anb1oUQhkgpXpJimJBmF+v7NbDs1Wh21Be80KXUh9SKgePhSQblr2QlRcA7jLgJ +4PMjZ+KYF+da+4RB7s+DvTXVDMn9AL84E1w5Ut1E8XZV+u4RjWPvNdhK/7GnuxOR +C9SdxonqkPQ8hiI7thP9bQIDAQABoxMwETAPBgNVHRMBAf8EBTADAQH/MA0GCSqG +SIb3DQEBCwUAA4IBAQDKQeiDbyr0/7sEhX33MmTDv84GeWgKl9qqHecx+d/0vImb +c8XHK0PDa4lVqo/BW4P1hjKzpt2DW35kbOhuqGqM0lasIczef43aCDDEBLwstAe6 +qMoyWGVGoAQbpwT3li2pMrsIYoPwMvoSGNUphjrkdpviff2POkLly7a5RrR1X3qt +Dai6eYbeMCr9NdgW7AZ5++/sKlFoe+zVk/Ed31s4D2lh3awrApZhVgcoquPmEwpt +gm+OgRmHw50U4SF3ZaJPwDyLMbx+clH/bgUg0+Za9e53Br1NtGKmw7hh/7CG/hy0 +yxeLd930pH4vZu7s0XM56N/ckkfUzRkAH8dSmhH4 +-----END CERTIFICATE----- diff --git a/plugins/tests/certs/clientintermediate-key.pem b/plugins/tests/certs/clientintermediate-key.pem new file mode 100644 index 00000000..13f68874 --- /dev/null +++ b/plugins/tests/certs/clientintermediate-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDqtSA5n2kA7Gty +B545PdWa7ViZjY78L21eGkrMPONNpZTNx0ODTQp2yNd+BsPNKJW68zONfrdoqmap +4Ub7TkPZXNAaK3eSep6tSCXXQWdOi2IkYXkJTn+BjVo/FMnuuPa0Posg0GQlw9PJ +DgyglPX2myy8JrH16tjVHGhfEtuUn7fUL5W+t+12YE/idUpcrbrhqdvWhRCGSCle +kmKYkGYX6/s1sOzVaHbUF7zQpdSH1IqB4+FJBuWvZCVFwDuMuAng8yNn4pgX51r7 +hEHuz4O9NdUMyf0AvzgTXDlS3UTxdlX67hGNY+812Er/sae7E5EL1J3GieqQ9DyG +Iju2E/1tAgMBAAECggEACyYJXtNUoIeaXvM/r8ZhJBfMEpcnyJDUKBklnmfyABky +ZUfmzBDXw2as3b6ihFc+LYAp3bm8KouVjtI1lfBUxrli5StVZa7PZLm9mmjv6Eo0 +ojfDEQ8afWPieoaZRO6iQVOLNkbPyv9vSuiQ7vvEZy9dw54u69h47j6IMqPprDiG +ropUNeGAvTnh1Vf9/8aCHEvHUNHcc4zjzGiQ+E60JgnbpGVeJKoeiMgrQE0yjweo +KyKA47Y6vqP6+AxAaPplXtmrx2UCbMjktHNvLvg42+2UlLS5roiwmJYEN9c6iT6t +y82MJrjEFGZyLG2u6ZQANSJiIWaCnOyT1o2deJ8NoQKBgQD7UxivDTuljQD0so+E +JX9UaFZ9PgS+8LC9v56PciL4XQ7bcCVP5vVgZZPABiQ9i989Wq7qI042Jrfu5qtE +SthlOAu80GvAQV+Oujwo7ZzM6ciQtjMsj63r2uayWXnmQ07QcIg7x7y161Pt9Bqr +LIDrqHziIj/lzT7+6QKZaQwFaQKBgQDvEuSC14CBlMhy2jji71kB/3Ya3c+8dP+A +kQZL9wEWK4a4dm8IaTS8jl1/luhQUzFRMyh2rWaTqqigSe3dvs5DRblhE5NPwTSI +9TO7t1EnzjW3R8LxZZsySyiSFnZ/8mR0empxq0Mov37OdXBj0tXuuzREf/hwijWh +WuLxJUSjZQKBgAIDZ2Y3l+u6lnBfYdDwL/XwJAk6zvTsnq3WdCG4C1mr/St62YGr +WvnbtnRKWE356d7m9BHCGKVMaBrM1EBmzRb6fPWVQde3blmJWmQFi0UE9mtaWkyY +Fg+WoFR7bQOQNHhs/lpkPjnC2dhFJVWLtLiuj9mL5rEjlMab/T5XXhZJAoGBAMEP +FZ8fXbPGrTQqSwPfWpZFcF9zvbynEmkFM/uGRMddcNZnNXSqWJ7nrFNLTuEGvW2g +DU4A6zPV/YQrDz4hRjmHBZOCFlSyZbUvpY4yFAQ7/p66AY+kiHZNwT5vi1P5Luvs +qyaNsZcnRMR+i7rg2EeHv0aNvNdMlNBvL5KikNINAoGAU2P/phdwJOUcqgHavQcQ +ureTEyZ5i5AeNomNeHSj0slG24V9nxOqEL7D00JKln7oAPovYBUWocEnF39uBJe0 +p0Hy7fCCK6EI8/0QyiQuuZmJfDEEvjQqE6irONNH63r2UwDEpDNGFvGsZNuWHLZc +SXADu5oSNu6o6IydiyOx528= +-----END PRIVATE KEY----- diff --git a/plugins/tests/certs/expired-cert.pem b/plugins/tests/certs/expired-cert.pem index 77a9166e..87fc8e47 100644 --- a/plugins/tests/certs/expired-cert.pem +++ b/plugins/tests/certs/expired-cert.pem @@ -1,24 +1,24 @@ -----BEGIN CERTIFICATE----- -MIIEETCCAvmgAwIBAgIUFDsP6WnV/uqeQMpD/DYSqouE13kwDQYJKoZIhvcNAQEL +MIIEETCCAvmgAwIBAgIUVDKkhcUoYFnjYCw12tScPIqQzqIwDQYJKoZIhvcNAQEL BQAwgZcxCzAJBgNVBAYTAkRFMRAwDgYDVQQIDAdCYXZhcmlhMQ8wDQYDVQQHDAZN dW5pY2gxGzAZBgNVBAoMEk1vbml0b3JpbmcgUGx1Z2luczEbMBkGA1UEAwwSTW9u aXRvcmluZyBQbHVnaW5zMSswKQYJKoZIhvcNAQkBFhxkZXZlbEBtb25pdG9yaW5n -LXBsdWdpbnMub3JnMB4XDTA4MDEwMTExMDAyNloXDTA4MDEwMjExMDAyNlowgZcx +LXBsdWdpbnMub3JnMB4XDTA4MDEwMTEyMDAwMFoXDTA4MDEwMjEyMDAwMFowgZcx CzAJBgNVBAYTAkRFMRAwDgYDVQQIDAdCYXZhcmlhMQ8wDQYDVQQHDAZNdW5pY2gx GzAZBgNVBAoMEk1vbml0b3JpbmcgUGx1Z2luczEbMBkGA1UEAwwSTW9uaXRvcmlu ZyBQbHVnaW5zMSswKQYJKoZIhvcNAQkBFhxkZXZlbEBtb25pdG9yaW5nLXBsdWdp -bnMub3JnMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyeHKwKFjJWUX -YHKsisypUf9dHlIPQAISyGP1BX6UL26ZLvE6kKbx3LFQ9W2POGoQWlzFiB1soGeV -WDd0U0JtWdCKmOXWdcXpupQlTSUtRCMDQkfqLN8GR5TBTd73rezp5mz08nMfLwu0 -p5VQ191Ui8JHFgrAOalAn8Uw5De8vj4VmTXmU5NJ2UFoC0ddU/Th/lwRCayHc1cn -MVq2F7c/uhMUUQYNBmJy0pxoHawp+j9NKl/xIYsjgQNgahQyNuswuGHjaEwhPu+7 -G03XsW4ehu+H1898M/MkSln6LQAU1syoJ8ypPM8tV+zgx4uwj7udnZ2hceN95uW7 -0PWg5DQyUwIDAQABo1MwUTAdBgNVHQ4EFgQUt9ps3KJ1XiMuy/ijFBjMzf6jgwkw -HwYDVR0jBBgwFoAUt9ps3KJ1XiMuy/ijFBjMzf6jgwkwDwYDVR0TAQH/BAUwAwEB -/zANBgkqhkiG9w0BAQsFAAOCAQEAVPBZwMHbrnHFbmhbcPuvYd5cxk0uSVNAUzsl -2biCq5P+ZHo10VHGygXtdV4utqk/IrAt2u5qSxycWPStCtAgTd3Q8ncfjOkaHM4z -2bxTkhLyQeU8NWPuDBqDszo2GOaFTv+lm36LEKiAfqB1tjQVePSkycdrWIhkamBV -EgMe6uHLdU7QQk1ajQfrBdakN1beqki/dKieA6gm+XF/QS4SSYINmsHB/2X5cT9U -b/KMB8xurCnuJQuk1P4VsSkJCOSeHjWZgK9pKNdsIJZr4wDVfhjQgU0XT6xakSf7 -eCaHtO0VKsbLZoiTmpxidjsdYiXyeKYIQNtUpTjyJ5V/cZsq9w== +bnMub3JnMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwg1dmGT3rVqM +beVWWLy8EAiq9re07AF8sTERy9oIYF5EUq9f0xO53mwwqIWV77O9mF99/kDFGQuQ +NOnICMSHXNtMXEXzfBaMighw0uyCh1o/VCejNQ5x/HU8aLh930g5DIcOJQ3fZ4v9 +8kBaie7+aPgRMVDM1vIrILfedq9Kt56zvPizkXhDeqxjKyIZdrdoBlX5zAfftWtY +HpQ+lkThSSXqQnchN6S2JFejmRtsNnceDVOBBdvlzmH0NlfwjynLK3/EJooTsINy +i9dXD8/Oe8r+UA+nokWvnWC2IAUJjpxW+XAyTG/NofGwX+PwquT0YD5cSlODIwZA +WAimygWLqQIDAQABo1MwUTAdBgNVHQ4EFgQUsKyJAwR9OXWEcSZMQz73GfpxCJIw +HwYDVR0jBBgwFoAUsKyJAwR9OXWEcSZMQz73GfpxCJIwDwYDVR0TAQH/BAUwAwEB +/zANBgkqhkiG9w0BAQsFAAOCAQEAYKFGX7J3Fc/T9s278w61E2dSsY4DS/mjSDik +fMWvod6eKw0fE3wJOnkWxjEH3VywTY6CmHd/oiJOaD8lr/Vk+BJfYNVBaVNmguyg +4LXoWz9Benx0bAIeuDbNAhOvA4H4aIz8UrD9lKFvKdRp42gPMLtMEbzbLcBdT95D +6BX7EhYm7vTnpitLPgFxVCsJ1JFqv2AQfUm+IkqQkezPs5x0tWLyrvCDNRGJ0kfv +UuowpUZXDOh3k1vB+xaSOFviieLaCW8TSdd5FZgI2HQj4e6vCKsMGuKKZXrMUTI/ +qtrFlUfsOuwourfC5LMHtCyYo5B3uvAWT1eTXxhrGqyleSlxJQ== -----END CERTIFICATE----- diff --git a/plugins/tests/certs/expired-key.pem b/plugins/tests/certs/expired-key.pem index c1510b2d..c5bba569 100644 --- a/plugins/tests/certs/expired-key.pem +++ b/plugins/tests/certs/expired-key.pem @@ -1,28 +1,28 @@ -----BEGIN PRIVATE KEY----- -MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDJ4crAoWMlZRdg -cqyKzKlR/10eUg9AAhLIY/UFfpQvbpku8TqQpvHcsVD1bY84ahBaXMWIHWygZ5VY -N3RTQm1Z0IqY5dZ1xem6lCVNJS1EIwNCR+os3wZHlMFN3vet7OnmbPTycx8vC7Sn -lVDX3VSLwkcWCsA5qUCfxTDkN7y+PhWZNeZTk0nZQWgLR11T9OH+XBEJrIdzVycx -WrYXtz+6ExRRBg0GYnLSnGgdrCn6P00qX/EhiyOBA2BqFDI26zC4YeNoTCE+77sb -Tdexbh6G74fXz3wz8yRKWfotABTWzKgnzKk8zy1X7ODHi7CPu52dnaFx433m5bvQ -9aDkNDJTAgMBAAECggEACrLFfNnQmD24NGs/S4e2/VpsA9xTZI/3kNkDNgxULANP -aNZtxRajwI9A/BCXQ2UTgsZhzWnJxOJYXrlpl7PweY78mUesysb3MOUC6QisUm0M -kimfdktHWOnAKLFFLNleN9DUVjjVkTeslijqhNX80f80py1grG2UuCLKCX4OqYIm -qACE8TMmSZLz42AO96TndNtKplQ8LuGLEmByW95wEfhx3Gm4ckkL7qII/U3DnQXr -0T+3xLaj+eNJzYDpIFZiw4sNzOuAyCz+4Cc4sPDuMnzquXF+enpkemoycC1RmEpG -KIDTwmFsc8TrbGV0qifC6fsCrDivdYLqL7R/q3IBQQKBgQDmfvO3VYTEKY8NA+AT -5s6+7NTxRsXxJUCEhCNBWimSH3EzmBAvrodLY6A0oYg8i81bgNX1I9GPVXJZ/QA7 -ukd84HUIQoGS5Usmo4rp+kz4P6KkLXDemZtWPU5GXxicfajHRQlkbW6St6SpV7IS -ibJcDADeoiaPL1xvue1ToP/LoQKBgQDgOFHjYpep00gabvjXfYW7vhrg1vVwaKUM -rf0+UW8Exk4nbBw0eEC2YjxIwzdktlkdbzGaXYULnhg8GnfxYesMOpCLPw1JdB8o -ixETAFpW5bKrUsjEFRUGhzWnsCSFIQ4smpmtGLTxOQ8AkoDdORY5Z+Wv7JtFF6Do -PSoblckZcwKBgB3TD3YJesRnHDty5OuuUdIikuslXTd2uoJrFqS+JeLibqNeabnB -u3/lxDULMbWj4U6VvRmbKOKDC+jY887Gq7lc0cff0yROxwqY3sCnwo3crg7QUmp7 -Nb5S8G3qoCSfndcq96wm/Me/O28uCbycVJfUdchY8uRUHIHYbP0FOBQBAoGBAMgh -fPX4imaKr1DovDObVkK87EDDnU84GBm5MtDs3qrkVd3aIVK0Aw7HoAdSN58tI12i -YiPmVVqJQhhjh6tsOuAvZdTj8ngdrbICbrsHFZt6an+A5LIgHyQ0iy+hiPdLCdvG -ImTeKKMmyr04Bs1upueWVO0xw2VoMbcY4Py+NUEBAoGASQqedfCSKGLT+5lLZrhP -CbFVMmswEPjBcRb1trcuA09vfExn9FfUNFnnw3i9miprED5kufvAjb+6nduXizKg -7HQYHCwVvakgtXgbiDMaNgYZcjWm+MdnfiwLJjJTO3DfI1JF2PJ8y9R95DPlAkDm -xH3OV8KV4UiTEVxS7ksmGzY= +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDCDV2YZPetWoxt +5VZYvLwQCKr2t7TsAXyxMRHL2ghgXkRSr1/TE7nebDCohZXvs72YX33+QMUZC5A0 +6cgIxIdc20xcRfN8FoyKCHDS7IKHWj9UJ6M1DnH8dTxouH3fSDkMhw4lDd9ni/3y +QFqJ7v5o+BExUMzW8isgt952r0q3nrO8+LOReEN6rGMrIhl2t2gGVfnMB9+1a1ge +lD6WROFJJepCdyE3pLYkV6OZG2w2dx4NU4EF2+XOYfQ2V/CPKcsrf8QmihOwg3KL +11cPz857yv5QD6eiRa+dYLYgBQmOnFb5cDJMb82h8bBf4/Cq5PRgPlxKU4MjBkBY +CKbKBYupAgMBAAECggEBAJ2mdCKJ7LoWdT4W8pZ3BqZUFGkKCF8wOhhOUDH3+ZQp +IYK3XbdDMF7mMIXIuW4a7W4sLlTwU/Ar98U1JMESwRIMS7YvUke+ngDKKLcDVGwY +Qpjg9vP0v2Al8qT1NbW/nDF0S2aJJbWfAvnblHK5ClFHL9iL107NQYJ8PqzXbnFL +gCQRiZxVHlrbn/73ZUMHPGEoU0711U9hSjrsqrRuSAMC+V38s4HxOomZWutlVAHF +HwClNZBqRO+a2njPyUuV9DM/rl5Tm9IQ89iFo3/QEORICK77HjJYhi+UzdfI5F35 +UntRJt+WLaiAP+K6Vt6oxHSm58qXnOkeLzaAunTTie0CgYEA6OLYfme8xe5zYXWX +rqmKNYdcVfMkvL+vUfVT475o/piRtE54JC1LYWEFAN8paxEWHD5HZMy0+ONNXfGm +zyNNTN/Lagz4WcpdFzKQmhfdro7DzRiDfdvwSLmaZDyE41PPPVVvfrI9IeDiUNY4 +nWLSb3sWo96Iuns+RoMqeA9wkqsCgYEA1U/UqeVQVTPlrWyiB2VXoI1xvFCCJTf8 +4NC0gcisxLRrtINk0BwrUJrRy0x1OLpJWiKwUl/W1GgvPPfhbYcUOb669JNtTIjY +FeIZblCTjz9GzKKmXeDciXvccyEdCJVUlPO3/e2JiJ4mCDjULprifq0a2gcQevFS +PfqVULhBOvsCgYB5KfS7J1vGmv36ucSWAe0/VlKLATqe3RfpCzt/JQTZWSWNaroF +EG/ElUaWIoUZCEW5oglg/0Q0rYYGF4DTCingkhrx7ReVF70BIbSsBzi15d8nKNbY +t4I3RCF4fyggYe1TmsysXS2DH85/gkToVY7oo2CvF0uJwi8vXnTNDDNkiwKBgHKs +mAc94BHt9GtnGzQepx0I7TvvjAe2MZwqlt+uojKdS8mfWXMHscGDeYVxdRMqEoUC +YQfnvfYyjDKaj/XxyE3C237gQsICTyh0hHdpmepIeidIyWdumyDOFZVPF+ylWvM4 +kpFQQb/QRWHmKyti2KCBLw5G/fUaBryLGfprE6ZBAoGBANy5rr41A679UQZ0abev +bOZb7YWOHYp/wReJaQbvLAyR30os3aEY/0ht9S+OWdrgGMezPKvsx2Sqr/CwoFXI +esiklpknr11maEPxnQJYi4FYiXS1a3NCg7yBvKzFEgx2XnMAC3s6zhuZXaFq4zNu +pm5Btrq/NZqtVXovS+UhGLvJ -----END PRIVATE KEY----- diff --git a/plugins/tests/certs/ext.cnf b/plugins/tests/certs/ext.cnf new file mode 100644 index 00000000..d09cee13 --- /dev/null +++ b/plugins/tests/certs/ext.cnf @@ -0,0 +1,2 @@ +[ client_ca ] +basicConstraints = critical, CA:true diff --git a/plugins/tests/certs/generate-certs.sh b/plugins/tests/certs/generate-certs.sh new file mode 100755 index 00000000..78660a26 --- /dev/null +++ b/plugins/tests/certs/generate-certs.sh @@ -0,0 +1,63 @@ +#!/bin/sh -e +# +# Recreates the https server certificates +# +# Set the GEN_EXPIRED environment variable to also regenerate +# the expired certificate. + +cd "$(dirname "$0")" +trap 'rm -f *.csr; rm -f clientca-cert.srl' EXIT + +subj() { + c="DE" + st="Bavaria" + l="Munich" + o="Monitoring Plugins" + cn="Monitoring Plugins" + emailAddress="devel@monitoring-plugins.org" + + if [ -n "$1" ]; then + # Add to CN + cn="$cn $1" + fi + + printf "/C=%s/ST=%s/L=%s/O=%s/CN=%s/emailAddress=%s" \ + "$c" "$st" "$l" "$o" "$cn" "$emailAddress" +} + +# server +openssl req -new -x509 -days 3560 -nodes \ + -keyout server-key.pem -out server-cert.pem \ + -subj "$(subj)" +# server, expired +# there is generally no need to regenerate this, as it will stay epxired +[ -n "$GEN_EXPIRED" ] && TZ=UTC faketime -f '2008-01-01 12:00:00' \ + openssl req -new -x509 -days 1 -nodes \ + -keyout expired-key.pem -out expired-cert.pem \ + -subj "$(subj)" + +# client, ca +openssl req -new -x509 -days 3560 -nodes \ + -keyout clientca-key.pem -out clientca-cert.pem \ + -subj "$(subj ClientCA)" +echo "01" >clientca-cert.srl +# client +openssl req -new -nodes \ + -keyout client-key.pem -out client-cert.csr \ + -subj "$(subj Client)" +openssl x509 -days 3560 -req -CA clientca-cert.pem -CAkey clientca-key.pem \ + -in client-cert.csr -out client-cert.pem +# client, intermediate +openssl req -new -nodes \ + -keyout clientintermediate-key.pem -out clientintermediate-cert.csr \ + -subj "$(subj ClientIntermediate)" +openssl x509 -days 3560 -req -CA clientca-cert.pem -CAkey clientca-key.pem \ + -extfile ext.cnf -extensions client_ca \ + -in clientintermediate-cert.csr -out clientintermediate-cert.pem +# client, chain +openssl req -new -nodes \ + -keyout clientchain-key.pem -out clientchain-cert.csr \ + -subj "$(subj ClientChain)" +openssl x509 -days 3560 -req -CA clientca-cert.pem -CAkey clientca-key.pem \ + -in clientchain-cert.csr -out clientchain-cert.pem +cat clientintermediate-cert.pem >>clientchain-cert.pem diff --git a/plugins/tests/certs/server-cert.pem b/plugins/tests/certs/server-cert.pem index b84b91d2..d1249ef1 100644 --- a/plugins/tests/certs/server-cert.pem +++ b/plugins/tests/certs/server-cert.pem @@ -1,24 +1,24 @@ -----BEGIN CERTIFICATE----- -MIIEBjCCAu6gAwIBAgIJANbQ5QQrKhUGMA0GCSqGSIb3DQEBCwUAMIGXMQswCQYD -VQQGEwJERTEQMA4GA1UECAwHQmF2YXJpYTEPMA0GA1UEBwwGTXVuaWNoMRswGQYD -VQQKDBJNb25pdG9yaW5nIFBsdWdpbnMxGzAZBgNVBAMMEk1vbml0b3JpbmcgUGx1 -Z2luczErMCkGCSqGSIb3DQEJARYcZGV2ZWxAbW9uaXRvcmluZy1wbHVnaW5zLm9y -ZzAeFw0xOTAyMTkxNTMxNDRaFw0yOTAyMTYxNTMxNDRaMIGXMQswCQYDVQQGEwJE -RTEQMA4GA1UECAwHQmF2YXJpYTEPMA0GA1UEBwwGTXVuaWNoMRswGQYDVQQKDBJN -b25pdG9yaW5nIFBsdWdpbnMxGzAZBgNVBAMMEk1vbml0b3JpbmcgUGx1Z2luczEr -MCkGCSqGSIb3DQEJARYcZGV2ZWxAbW9uaXRvcmluZy1wbHVnaW5zLm9yZzCCASIw -DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKgV2yp8pQvJuN+aJGdAe6Hd0tja -uteCPcNIcM92WLOF69TLTSYon1XDon4tHTh4Z5d4lD8bfsGzFVBmDSgWidhAUf+v -EqEXwbp293ej/Frc0pXCvmrz6kI1tWrLtQhL/VdbxFYxhV7JjKb+PY3SxGFpSLPe -PQ/5SwVndv7rZIwcjseL22K5Uy2TIrkgzzm2pRs/IvoxRybYr/+LGoHyrtJC6AO8 -ylp8A/etL0gwtUvRnrnZeTQ2pA1uZ5QN3anTL8JP/ZRZYNegIkaawqMtTKbhM6pi -u3/4a3Uppvt0y7vmGfQlYejxCpICnMrvHMpw8L58zv/98AbCGjDU3UwCt6MCAwEA -AaNTMFEwHQYDVR0OBBYEFG/UH6nGYPlVcM75UXzXBF5GZyrcMB8GA1UdIwQYMBaA -FG/UH6nGYPlVcM75UXzXBF5GZyrcMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN -AQELBQADggEBAGwitJPOnlIKLndNf+iCLMIs0dxsl8kAaejFcjoT0n4ja7Y6Zrqz -VSIidzz9vQWvy24xKJpAOdj/iLRHCUOG+Pf5fA6+/FiuqXr6gE2/lm0eC58BNONr -E5OzjQ/VoQ8RX4hDntgu6FYbaVa/vhwn16igt9qmdNGGZXf2/+DM3JADwyaA4EK8 -vm7KdofX9zkxXecHPNvf3jiVLPiDDt6tkGpHPEsyP/yc+RUdltUeZvHfliV0cCuC -jJX+Fm9ysjSpHIFFr+jUMuMHibWoOD8iy3eYxfCDoWsH488pCbj8MNuAq6vd6DBk -bOZxDz43vjWuYMkwXJTxJQh7Pne6kK0vE1g= +MIIEETCCAvmgAwIBAgIUZwOhY4myaCUaPek3NM+MxbLG9vwwDQYJKoZIhvcNAQEL +BQAwgZcxCzAJBgNVBAYTAkRFMRAwDgYDVQQIDAdCYXZhcmlhMQ8wDQYDVQQHDAZN +dW5pY2gxGzAZBgNVBAoMEk1vbml0b3JpbmcgUGx1Z2luczEbMBkGA1UEAwwSTW9u +aXRvcmluZyBQbHVnaW5zMSswKQYJKoZIhvcNAQkBFhxkZXZlbEBtb25pdG9yaW5n +LXBsdWdpbnMub3JnMB4XDTIxMDIyODIxMDIxMVoXDTMwMTEyODIxMDIxMVowgZcx +CzAJBgNVBAYTAkRFMRAwDgYDVQQIDAdCYXZhcmlhMQ8wDQYDVQQHDAZNdW5pY2gx +GzAZBgNVBAoMEk1vbml0b3JpbmcgUGx1Z2luczEbMBkGA1UEAwwSTW9uaXRvcmlu +ZyBQbHVnaW5zMSswKQYJKoZIhvcNAQkBFhxkZXZlbEBtb25pdG9yaW5nLXBsdWdp +bnMub3JnMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2/3eBA4WG6xz +LfM6xcWywxThb1Rp7XAW3ewQd9/PdoWXEe8BJWlLfyYi1drLMcsDywhLkKmW4Vp9 +1R4PAkiljjrB/ZaUMDLJ1ri3dwX4RvXG7crsU3QWFWCBOrf5V2FTRQ2m/H/KyB/6 +rVZANsU47HqTFSPiUm2j7P3wx/wtHeYC+qmNG7zZTjAYPYxfKiod0lytTSmb+h54 +6lxn3+VPEXZAQZlLvPnm/58JnXGrUv7B2yocf5MhKkLJOrGxH2hfwKISfaj2gpOV +m4PUVYiDzCSpq1fPvwbUxIvdO27xprx+mrGOFM6f2UCEOc35w8FSmYiR2yQTnEJK +pbSQD6t1jQIDAQABo1MwUTAdBgNVHQ4EFgQUMeYgglT2aWDlF8KEeF2376AlTGYw +HwYDVR0jBBgwFoAUMeYgglT2aWDlF8KEeF2376AlTGYwDwYDVR0TAQH/BAUwAwEB +/zANBgkqhkiG9w0BAQsFAAOCAQEAFcEg83rTJdgkp7JLYqK0j8JogSHNlDYchr/r +VxKBgQwfnjSp5A8d5+uTQ9s3QDabw8v7YeSrzYXbbjuWZ61mnl84tzOQ8LMeESnC +CBXRCxB8Ow22WsVTVJq279SGYT+cZrdsmqGVWDi1A0C5kH+XTLAioG5CZmmxemD/ +S92ZoRxGyYfg33r+3X6EMcEYtHKGxCUa3EPcPOL4dq2F3nOnyjiWPZm3786H3NY2 +nsYwrEhAdUFtbYSsV5O0c/Zlc33fmTfh654ab35io1DtwmFo7q8J532dUE007EN0 +mIQmhdrjNJJHIftgSt0fuN5m48oLOnX7vvkz+X0WLWfVTtMr0w== -----END CERTIFICATE----- diff --git a/plugins/tests/certs/server-key.pem b/plugins/tests/certs/server-key.pem index 11947555..0de63f8f 100644 --- a/plugins/tests/certs/server-key.pem +++ b/plugins/tests/certs/server-key.pem @@ -1,28 +1,28 @@ -----BEGIN PRIVATE KEY----- -MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCoFdsqfKULybjf -miRnQHuh3dLY2rrXgj3DSHDPdlizhevUy00mKJ9Vw6J+LR04eGeXeJQ/G37BsxVQ -Zg0oFonYQFH/rxKhF8G6dvd3o/xa3NKVwr5q8+pCNbVqy7UIS/1XW8RWMYVeyYym -/j2N0sRhaUiz3j0P+UsFZ3b+62SMHI7Hi9tiuVMtkyK5IM85tqUbPyL6MUcm2K// -ixqB8q7SQugDvMpafAP3rS9IMLVL0Z652Xk0NqQNbmeUDd2p0y/CT/2UWWDXoCJG -msKjLUym4TOqYrt/+Gt1Kab7dMu75hn0JWHo8QqSApzK7xzKcPC+fM7//fAGwhow -1N1MArejAgMBAAECggEANuvdTwanTzC8jaNqHaq+OuemS2E9B8nwsGxtH/zFgvNR -WZiMPtmrJnTkFWJcV+VPw/iMSAqN4nDHmBugVOb4Z4asxGTKK4T9shXJSnh0rqPU -00ZsvbmxY6z0+E5TesCJqQ+9GYTY1V357V7JchvaOxIRxWPqg9urHbru8OCtW/I5 -Fh5HPUZlgCvlMpjlhyjydIf/oXyVA3RNsXlwe8+2cKuGIrjEzm2j9o3VF0sctTX0 -ItP8A9qDmDQN7GIWX0MW6gncojpS1omC2wcFsdjj/xfPyiDal1X4aq/2YqG8351c -YlM/+6Va0u9WWE/i64gASTAVqpMV4Yg8y0gGycuA0QKBgQDbgI2QeLd3FvMcURiU -l3w9qJgw/Jp3jaNC/9LkVGGz4f4lKKB67lPZvI4noMK8GqO/LcXgqP/RY1oJojoA -/6JKVvzYGASZ7VgMoG9bk1AneP1PGdibuTUEwimGlcObxnDFIC/yjwPFu3jIdqdS -zZi1RZzyqAogN5y3SBEypSmn9wKBgQDECKsqqlcizmCl8v5aVk875AzGN+DOHZqx -bkmztlnLO/2e2Fmk3G5Vvnui0FYisf8Eq19tUTQCF6lSfJlGQeFAT119wkFZhLu+ -FfLGqoEMH0ijJg/8PpdpFRK3I94YcISoTNN6yxMvE6xdDGfKCt5a+IX5bwQi9Zdc -B242gEc6tQKBgA6tM8n7KFlAIZU9HuWgk2AUC8kKutFPmSD7tgAqXDYI4FNfugs+ -MEEYyHCB4UNujJBV4Ss6YZCAkh6eyD4U2aca1eElCfm40vBVMdzvpqZdAqLtWXxg -D9l3mgszrFaYGCY2Fr6jLV9lP5g3xsxUjudf9jSLY9HvpfzjRrMaNATVAoGBALTl -/vYfPMucwKlC5B7++J0e4/7iv6vUu9SyHocdZh1anb9AjPDKjXLIlZT4RhQ8R0XK -0wOw5JpttU2uN08TKkbLNk3/vYhbKVjPLjrQSseh8sjDLgsqw1QwIxYnniLVakVY -p+rvjSNrNyqicQCMKQavwgocvSd5lJRTMwxOMezlAoGBAKWj71BX+0CK00/2S6lC -TcNcuUPG0d8y1czZ4q6tUlG4htwq1FMOpaghATXjkdsOGTLS+H1aA0Kt7Ai9zDhc -/bzOJEJ+jvBXV4Gcs7jl1r/HTKv0tT9ZSI5Vzkida0rfqxDGzcMVlLuCdH0cb8Iu -N0wdmCAqlQwHR13+F1zrAD7V +MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDb/d4EDhYbrHMt +8zrFxbLDFOFvVGntcBbd7BB33892hZcR7wElaUt/JiLV2ssxywPLCEuQqZbhWn3V +Hg8CSKWOOsH9lpQwMsnWuLd3BfhG9cbtyuxTdBYVYIE6t/lXYVNFDab8f8rIH/qt +VkA2xTjsepMVI+JSbaPs/fDH/C0d5gL6qY0bvNlOMBg9jF8qKh3SXK1NKZv6Hnjq +XGff5U8RdkBBmUu8+eb/nwmdcatS/sHbKhx/kyEqQsk6sbEfaF/AohJ9qPaCk5Wb +g9RViIPMJKmrV8+/BtTEi907bvGmvH6asY4Uzp/ZQIQ5zfnDwVKZiJHbJBOcQkql +tJAPq3WNAgMBAAECggEBAIvJDUjQVpXxByL8eazviT5SR0jBf6mC3tTWykQRb7ck +/bBEiRrnhDRf3CS9KP4TvO5G8BUU3a2GHYzM08akuKXeiiODidfyfbQ1nUZBAdi9 +FVFF7tK8YcflkVfpTMOMMSggm6m33fc58sQvmQ/0U85XuJvnOEkeJ9pQJa49e8GR +lpCQImF7ygltHPEz4o8qOtNMuPxiHOxpc517+ozQULZk153NTfGok1XctDFFZ3YX +8okLSfcqZ28mdHYSvI9xf60Cm7cT9tunXHwZ0f1esTFiVYpAp+oTJqtdYxr/fYlL +oO8G8iIQ7LjdJfgo84PscpKdSRCq3BfnmER1Eyg6hrUCgYEA/0hL5Y/haz/2jYGy +aa8yZSuD1ZcWtj7pLKrBQnHPHIHsjSBggWhopvonCFvCjgSS1pOFOUAwMGc0T+Dw +rWo3w8cEUyECl3Bw8gbCWtRXaigzU9TPgCWyx1j5dTopQhLObzS/m7fJFElnYNru +jqhsUfWS+NKk8a5+A7i9lv4iBLMCgYEA3Jws3Lfj/Xs7LljrvryTMpPthvUGBcyt +U9Qmf1Hmur90RP5V1rx4FqPQzIeaGQyZDNIUnkhBSqQZNCts3Rzay7N4uQzk8OEg +S8Llnw76wLwi0SJ4okDtT5tpTR6fcS0M9lGN+zvvfUB4+ul8oub0pMcyme/pywEz +ap+x3xAQPL8CgYEAiYOBVtTNof9fqdRurh1w8SyipKDx3BRBeQ02c7tozLt0GIWT +VsJOdXwVIJyFTglKrAnlXvSjwL8nX8wU+eVYyr5fJwSGJ9urC8T2VwVBXW7wTz04 +1Zf5GQdlwW8mIHCPATqR6Kj0yVfNN1BX50L0rqWxmRWnQoUzXn/aqQaWfp8CgYAW +9693/zEeR8EejyVkAy/z+RCml0XcPrXg31pusPErihkpwazgIVkDSmTHlmqFpxkc +C5cX73/UrIbvNoIr9wAUawfrhBsltNpu6MiNKbsTa8LYMRWMFuReAFkTLVf+KWmL +D2yPtmq1iIvP25UdRJw9t3teKWsWtnZK6HtVNM/r8wKBgQDKlqUpy8r4KK+S2w80 +H7rAQJo1DgXsYrgSa2gfppSKro4lm3ltyAfVIrKQKP7uCo9xTGKVQAUPttMs2+17 +nwbwvt7/nG7G1Dk/C/t6b7SJ80VY5b9ZZKIJ0wOjajLufSjPNCe0ZTRn32XusZUn +nYGB5/QXYr5WGV9YhAkRsFJYgA== -----END PRIVATE KEY----- diff --git a/plugins/tests/check_curl.t b/plugins/tests/check_curl.t index 29cb03f2..aa72ef67 100755 --- a/plugins/tests/check_curl.t +++ b/plugins/tests/check_curl.t @@ -228,23 +228,25 @@ SKIP: { skip "HTTP::Daemon::SSL not installed", $common_tests + $ssl_only_tests if ! exists $servers->{https}; run_common_tests( { command => "$command -p $port_https", ssl => 1 } ); + my $expiry = "Thu Nov 28 21:02:11 2030 +0000"; + $result = NPTest->testCmd( "$command -p $port_https -S -C 14" ); is( $result->return_code, 0, "$command -p $port_https -S -C 14" ); - is( $result->output, "OK - Certificate 'Monitoring Plugins' will expire on Fri Feb 16 15:31:44 2029 +0000.", "output ok" ); + is( $result->output, "OK - Certificate 'Monitoring Plugins' will expire on $expiry.", "output ok" ); $result = NPTest->testCmd( "$command -p $port_https -S -C 14000" ); is( $result->return_code, 1, "$command -p $port_https -S -C 14000" ); - like( $result->output, '/WARNING - Certificate \'Monitoring Plugins\' expires in \d+ day\(s\) \(Fri Feb 16 15:31:44 2029 \+0000\)./', "output ok" ); + like( $result->output, '/WARNING - Certificate \'Monitoring Plugins\' expires in \d+ day\(s\) \(' . quotemeta($expiry) . '\)./', "output ok" ); # Expired cert tests $result = NPTest->testCmd( "$command -p $port_https -S -C 13960,14000" ); is( $result->return_code, 2, "$command -p $port_https -S -C 13960,14000" ); - like( $result->output, '/CRITICAL - Certificate \'Monitoring Plugins\' expires in \d+ day\(s\) \(Fri Feb 16 15:31:44 2029 \+0000\)./', "output ok" ); + like( $result->output, '/CRITICAL - Certificate \'Monitoring Plugins\' expires in \d+ day\(s\) \(' . quotemeta($expiry) . '\)./', "output ok" ); $result = NPTest->testCmd( "$command -p $port_https_expired -S -C 7" ); is( $result->return_code, 2, "$command -p $port_https_expired -S -C 7" ); is( $result->output, - 'CRITICAL - Certificate \'Monitoring Plugins\' expired on Wed Jan 2 11:00:26 2008 +0000.', + 'CRITICAL - Certificate \'Monitoring Plugins\' expired on Wed Jan 2 12:00:00 2008 +0000.', "output ok" ); } diff --git a/plugins/tests/check_http.t b/plugins/tests/check_http.t index 188f5e75..ea11b2ac 100755 --- a/plugins/tests/check_http.t +++ b/plugins/tests/check_http.t @@ -3,16 +3,7 @@ # Test check_http by having an actual HTTP server running # # To create the https server certificate: -# openssl req -new -x509 -keyout server-key.pem -out server-cert.pem -days 3650 -nodes -# to create a new expired certificate: -# faketime '2008-01-01 12:00:00' openssl req -new -x509 -keyout expired-key.pem -out expired-cert.pem -days 1 -nodes -# Country Name (2 letter code) [AU]:DE -# State or Province Name (full name) [Some-State]:Bavaria -# Locality Name (eg, city) []:Munich -# Organization Name (eg, company) [Internet Widgits Pty Ltd]:Monitoring Plugins -# Organizational Unit Name (eg, section) []: -# Common Name (e.g. server FQDN or YOUR name) []:Monitoring Plugins -# Email Address []:devel@monitoring-plugins.org +# ./certs/generate-certs.sh use strict; use Test::More; @@ -23,7 +14,7 @@ $ENV{'LC_TIME'} = "C"; my $common_tests = 70; my $virtual_port_tests = 8; -my $ssl_only_tests = 8; +my $ssl_only_tests = 12; # Check that all dependent modules are available eval "use HTTP::Daemon 6.01;"; plan skip_all => 'HTTP::Daemon >= 6.01 required' if $@; @@ -59,61 +50,87 @@ $HTTP::Daemon::VERSION = "1.00"; my $port_http = 50000 + int(rand(1000)); my $port_https = $port_http + 1; my $port_https_expired = $port_http + 2; +my $port_https_clientcert = $port_http + 3; # This array keeps sockets around for implementing timeouts my @persist; # Start up all servers my @pids; -my $pid = fork(); -if ($pid) { - # Parent - push @pids, $pid; - if (exists $servers->{https}) { - # Fork a normal HTTPS server - $pid = fork(); - if ($pid) { - # Parent - push @pids, $pid; - # Fork an expired cert server - $pid = fork(); - if ($pid) { - push @pids, $pid; - } else { - my $d = HTTP::Daemon::SSL->new( - LocalPort => $port_https_expired, - LocalAddr => "127.0.0.1", - SSL_cert_file => "$Bin/certs/expired-cert.pem", - SSL_key_file => "$Bin/certs/expired-key.pem", - ) || die; - print "Please contact https expired at: url, ">\n"; - run_server( $d ); - exit; - } - } else { - # closing the connection after -C cert checks make the daemon exit with a sigpipe otherwise - local $SIG{'PIPE'} = 'IGNORE'; - my $d = HTTP::Daemon::SSL->new( - LocalPort => $port_https, - LocalAddr => "127.0.0.1", - SSL_cert_file => "$Bin/certs/server-cert.pem", - SSL_key_file => "$Bin/certs/server-key.pem", - ) || die; - print "Please contact https at: url, ">\n"; - run_server( $d ); - exit; - } - } -} else { - # Child - #print "child\n"; +# Fork a HTTP server +my $pid = fork; +defined $pid or die "Failed to fork"; +if (!$pid) { + undef @pids; my $d = HTTP::Daemon->new( LocalPort => $port_http, LocalAddr => "127.0.0.1", ) || die; print "Please contact http at: url, ">\n"; run_server( $d ); - exit; + die "webserver stopped"; +} +push @pids, $pid; + +if (exists $servers->{https}) { + # Fork a normal HTTPS server + $pid = fork; + defined $pid or die "Failed to fork"; + if (!$pid) { + undef @pids; + # closing the connection after -C cert checks make the daemon exit with a sigpipe otherwise + local $SIG{'PIPE'} = 'IGNORE'; + my $d = HTTP::Daemon::SSL->new( + LocalPort => $port_https, + LocalAddr => "127.0.0.1", + SSL_cert_file => "$Bin/certs/server-cert.pem", + SSL_key_file => "$Bin/certs/server-key.pem", + ) || die; + print "Please contact https at: url, ">\n"; + run_server( $d ); + die "webserver stopped"; + } + push @pids, $pid; + + # Fork an expired cert server + $pid = fork; + defined $pid or die "Failed to fork"; + if (!$pid) { + undef @pids; + # closing the connection after -C cert checks make the daemon exit with a sigpipe otherwise + local $SIG{'PIPE'} = 'IGNORE'; + my $d = HTTP::Daemon::SSL->new( + LocalPort => $port_https_expired, + LocalAddr => "127.0.0.1", + SSL_cert_file => "$Bin/certs/expired-cert.pem", + SSL_key_file => "$Bin/certs/expired-key.pem", + ) || die; + print "Please contact https expired at: url, ">\n"; + run_server( $d ); + die "webserver stopped"; + } + push @pids, $pid; + + # Fork an client cert expecting server + $pid = fork; + defined $pid or die "Failed to fork"; + if (!$pid) { + undef @pids; + # closing the connection after -C cert checks make the daemon exit with a sigpipe otherwise + local $SIG{'PIPE'} = 'IGNORE'; + my $d = HTTP::Daemon::SSL->new( + LocalPort => $port_https_clientcert, + LocalAddr => "127.0.0.1", + SSL_cert_file => "$Bin/certs/server-cert.pem", + SSL_key_file => "$Bin/certs/server-key.pem", + SSL_verify_mode => IO::Socket::SSL->SSL_VERIFY_PEER | IO::Socket::SSL->SSL_VERIFY_FAIL_IF_NO_PEER_CERT, + SSL_ca_file => "$Bin/certs/clientca-cert.pem", + ) || die; + print "Please contact https client cert at: url, ">\n"; + run_server( $d ); + die "webserver stopped"; + } + push @pids, $pid; } # give our webservers some time to startup @@ -122,60 +139,62 @@ sleep(3); # Run the same server on http and https sub run_server { my $d = shift; - MAINLOOP: while (my $c = $d->accept ) { - while (my $r = $c->get_request) { - if ($r->method eq "GET" and $r->url->path =~ m^/statuscode/(\d+)^) { - $c->send_basic_header($1); - $c->send_crlf; - } elsif ($r->method eq "GET" and $r->url->path =~ m^/file/(.*)^) { - $c->send_basic_header; - $c->send_crlf; - $c->send_file_response("$Bin/var/$1"); - } elsif ($r->method eq "GET" and $r->url->path eq "/slow") { - $c->send_basic_header; - $c->send_crlf; - sleep 1; - $c->send_response("slow"); - } elsif ($r->url->path eq "/method") { - if ($r->method eq "DELETE") { - $c->send_error(HTTP::Status->RC_METHOD_NOT_ALLOWED); - } elsif ($r->method eq "foo") { - $c->send_error(HTTP::Status->RC_NOT_IMPLEMENTED); + while (1) { + MAINLOOP: while (my $c = $d->accept) { + while (my $r = $c->get_request) { + if ($r->method eq "GET" and $r->url->path =~ m^/statuscode/(\d+)^) { + $c->send_basic_header($1); + $c->send_crlf; + } elsif ($r->method eq "GET" and $r->url->path =~ m^/file/(.*)^) { + $c->send_basic_header; + $c->send_crlf; + $c->send_file_response("$Bin/var/$1"); + } elsif ($r->method eq "GET" and $r->url->path eq "/slow") { + $c->send_basic_header; + $c->send_crlf; + sleep 1; + $c->send_response("slow"); + } elsif ($r->url->path eq "/method") { + if ($r->method eq "DELETE") { + $c->send_error(HTTP::Status->RC_METHOD_NOT_ALLOWED); + } elsif ($r->method eq "foo") { + $c->send_error(HTTP::Status->RC_NOT_IMPLEMENTED); + } else { + $c->send_status_line(200, $r->method); + } + } elsif ($r->url->path eq "/postdata") { + $c->send_basic_header; + $c->send_crlf; + $c->send_response($r->method.":".$r->content); + } elsif ($r->url->path eq "/redirect") { + $c->send_redirect( "/redirect2" ); + } elsif ($r->url->path eq "/redir_external") { + $c->send_redirect(($d->isa('HTTP::Daemon::SSL') ? "https" : "http") . "://169.254.169.254/redirect2" ); + } elsif ($r->url->path eq "/redirect2") { + $c->send_basic_header; + $c->send_crlf; + $c->send_response(HTTP::Response->new( 200, 'OK', undef, 'redirected' )); + } elsif ($r->url->path eq "/redir_timeout") { + $c->send_redirect( "/timeout" ); + } elsif ($r->url->path eq "/timeout") { + # Keep $c from being destroyed, but prevent severe leaks + unshift @persist, $c; + delete($persist[1000]); + next MAINLOOP; + } elsif ($r->url->path eq "/header_check") { + $c->send_basic_header; + $c->send_header('foo'); + $c->send_crlf; + } elsif ($r->url->path eq "/virtual_port") { + # return sent Host header + $c->send_basic_header; + $c->send_crlf; + $c->send_response(HTTP::Response->new( 200, 'OK', undef, $r->header ('Host'))); } else { - $c->send_status_line(200, $r->method); + $c->send_error(HTTP::Status->RC_FORBIDDEN); } - } elsif ($r->url->path eq "/postdata") { - $c->send_basic_header; - $c->send_crlf; - $c->send_response($r->method.":".$r->content); - } elsif ($r->url->path eq "/redirect") { - $c->send_redirect( "/redirect2" ); - } elsif ($r->url->path eq "/redir_external") { - $c->send_redirect(($d->isa('HTTP::Daemon::SSL') ? "https" : "http") . "://169.254.169.254/redirect2" ); - } elsif ($r->url->path eq "/redirect2") { - $c->send_basic_header; - $c->send_crlf; - $c->send_response(HTTP::Response->new( 200, 'OK', undef, 'redirected' )); - } elsif ($r->url->path eq "/redir_timeout") { - $c->send_redirect( "/timeout" ); - } elsif ($r->url->path eq "/timeout") { - # Keep $c from being destroyed, but prevent severe leaks - unshift @persist, $c; - delete($persist[1000]); - next MAINLOOP; - } elsif ($r->url->path eq "/header_check") { - $c->send_basic_header; - $c->send_header('foo'); - $c->send_crlf; - } elsif ($r->url->path eq "/virtual_port") { - # return sent Host header - $c->send_basic_header; - $c->send_crlf; - $c->send_response(HTTP::Response->new( 200, 'OK', undef, $r->header ('Host'))); - } else { - $c->send_error(HTTP::Status->RC_FORBIDDEN); + $c->close; } - $c->close; } } } @@ -200,25 +219,44 @@ SKIP: { skip "HTTP::Daemon::SSL not installed", $common_tests + $ssl_only_tests if ! exists $servers->{https}; run_common_tests( { command => "$command -p $port_https", ssl => 1 } ); + my $expiry = "Thu Nov 28 21:02:11 2030 +0000"; + $result = NPTest->testCmd( "$command -p $port_https -S -C 14" ); is( $result->return_code, 0, "$command -p $port_https -S -C 14" ); - is( $result->output, "OK - Certificate 'Monitoring Plugins' will expire on Fri Feb 16 15:31:44 2029 +0000.", "output ok" ); + is( $result->output, "OK - Certificate 'Monitoring Plugins' will expire on $expiry.", "output ok" ); $result = NPTest->testCmd( "$command -p $port_https -S -C 14000" ); is( $result->return_code, 1, "$command -p $port_https -S -C 14000" ); - like( $result->output, '/WARNING - Certificate \'Monitoring Plugins\' expires in \d+ day\(s\) \(Fri Feb 16 15:31:44 2029 \+0000\)./', "output ok" ); + like( $result->output, '/WARNING - Certificate \'Monitoring Plugins\' expires in \d+ day\(s\) \(' . quotemeta($expiry) . '\)./', "output ok" ); # Expired cert tests $result = NPTest->testCmd( "$command -p $port_https -S -C 13960,14000" ); is( $result->return_code, 2, "$command -p $port_https -S -C 13960,14000" ); - like( $result->output, '/CRITICAL - Certificate \'Monitoring Plugins\' expires in \d+ day\(s\) \(Fri Feb 16 15:31:44 2029 \+0000\)./', "output ok" ); + like( $result->output, '/CRITICAL - Certificate \'Monitoring Plugins\' expires in \d+ day\(s\) \(' . quotemeta($expiry) . '\)./', "output ok" ); $result = NPTest->testCmd( "$command -p $port_https_expired -S -C 7" ); is( $result->return_code, 2, "$command -p $port_https_expired -S -C 7" ); is( $result->output, - 'CRITICAL - Certificate \'Monitoring Plugins\' expired on Wed Jan 2 11:00:26 2008 +0000.', + 'CRITICAL - Certificate \'Monitoring Plugins\' expired on Wed Jan 2 12:00:00 2008 +0000.', "output ok" ); + # client cert tests + my $cmd; + $cmd = "$command -p $port_https_clientcert" + . " -J \"$Bin/certs/client-cert.pem\"" + . " -K \"$Bin/certs/client-key.pem\"" + . " -u /statuscode/200"; + $result = NPTest->testCmd($cmd); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + $cmd = "$command -p $port_https_clientcert" + . " -J \"$Bin/certs/clientchain-cert.pem\"" + . " -K \"$Bin/certs/clientchain-key.pem\"" + . " -u /statuscode/200"; + $result = NPTest->testCmd($cmd); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); } my $cmd; -- cgit v1.2.3-74-g34f1 From e781e0d1010b57da0e468cb7e9afb03860870218 Mon Sep 17 00:00:00 2001 From: Lorenz <12514511+RincewindsHat@users.noreply.github.com> Date: Sun, 30 Jan 2022 12:44:02 +0100 Subject: Fix double percentage sign in usage (#1743) --- plugins/check_procs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_procs.c b/plugins/check_procs.c index 48723404..a025ee89 100644 --- a/plugins/check_procs.c +++ b/plugins/check_procs.c @@ -775,7 +775,7 @@ be the total number of running processes\n\n")); printf (" %s\n", "check_procs -w 50000 -c 100000 --metric=VSZ"); printf (" %s\n\n", _("Alert if VSZ of any processes over 50K or 100K")); printf (" %s\n", "check_procs -w 10 -c 20 --metric=CPU"); - printf (" %s\n", _("Alert if CPU of any processes over 10%% or 20%%")); + printf (" %s\n", _("Alert if CPU of any processes over 10\% or 20\%")); printf (UT_SUPPORT); } -- cgit v1.2.3-74-g34f1 From d485b64ef0c08eb04fd6152b61b167c5edadab02 Mon Sep 17 00:00:00 2001 From: Lorenz <12514511+RincewindsHat@users.noreply.github.com> Date: Sun, 30 Jan 2022 19:41:36 +0100 Subject: Description for -M was the wrong way around (#1746) Using -M should show the mountpoint instead of the device the file system originated from. Seems like this was not the case for a long time and now the default is to show the mount point. Using `-M` reverts to showing the (block) device instead. The usage Description was adjusted with this commit. --- plugins/check_disk.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_disk.c b/plugins/check_disk.c index 9652f453..66c5dd39 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -961,7 +961,7 @@ print_help (void) printf (" %s\n", _("Only check local filesystems against thresholds. Yet call stat on remote filesystems")); printf (" %s\n", _("to test if they are accessible (e.g. to detect Stale NFS Handles)")); printf (" %s\n", "-M, --mountpoint"); - printf (" %s\n", _("Display the mountpoint instead of the partition")); + printf (" %s\n", _("Display the (block) device instead of the mount point")); printf (" %s\n", "-m, --megabytes"); printf (" %s\n", _("Same as '--units MB'")); printf (" %s\n", "-A, --all"); -- cgit v1.2.3-74-g34f1 From 455fdc1072b85e7d05783546d9e99ed2e61716de Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Sun, 10 Apr 2022 16:31:47 +0200 Subject: check_http: added option --continue-after-certificate (#1761) --- plugins/check_http.c | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index df2a79c2..f8ec853b 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -58,6 +58,7 @@ enum { #ifdef HAVE_SSL int check_cert = FALSE; +int continue_after_check_cert = FALSE; int ssl_version = 0; int days_till_exp_warn, days_till_exp_crit; char *randbuff; @@ -205,7 +206,8 @@ process_arguments (int argc, char **argv) enum { INVERT_REGEX = CHAR_MAX + 1, SNI_OPTION, - MAX_REDIRS_OPTION + MAX_REDIRS_OPTION, + CONTINUE_AFTER_CHECK_CERT }; int option = 0; @@ -233,6 +235,7 @@ process_arguments (int argc, char **argv) {"certificate", required_argument, 0, 'C'}, {"client-cert", required_argument, 0, 'J'}, {"private-key", required_argument, 0, 'K'}, + {"continue-after-certificate", no_argument, 0, CONTINUE_AFTER_CHECK_CERT}, {"useragent", required_argument, 0, 'A'}, {"header", required_argument, 0, 'k'}, {"no-body", no_argument, 0, 'N'}, @@ -331,6 +334,11 @@ process_arguments (int argc, char **argv) } check_cert = TRUE; goto enable_ssl; +#endif + case CONTINUE_AFTER_CHECK_CERT: /* don't stop after the certificate is checked */ +#ifdef HAVE_SSL + continue_after_check_cert = TRUE; + break; #endif case 'J': /* use client certificate */ #ifdef HAVE_SSL @@ -981,9 +989,11 @@ check_http (void) elapsed_time_ssl = (double)microsec_ssl / 1.0e6; if (check_cert == TRUE) { result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit); - if (sd) close(sd); - np_net_ssl_cleanup(); - return result; + if (continue_after_check_cert == FALSE) { + if (sd) close(sd); + np_net_ssl_cleanup(); + return result; + } } } #endif /* HAVE_SSL */ @@ -1608,7 +1618,11 @@ print_help (void) printf (" %s\n", _("Enable SSL/TLS hostname extension support (SNI)")); printf (" %s\n", "-C, --certificate=INTEGER[,INTEGER]"); printf (" %s\n", _("Minimum number of days a certificate has to be valid. Port defaults to 443")); - printf (" %s\n", _("(when this option is used the URL is not checked.)")); + printf (" %s\n", _("(when this option is used the URL is not checked by default. You can use")); + printf (" %s\n", _(" --continue-after-certificate to override this behavior)")); + printf (" %s\n", "--continue-after-certificate"); + printf (" %s\n", _("Allows the HTTP check to continue after performing the certificate check.")); + printf (" %s\n", _("Does nothing unless -C is used.")); printf (" %s\n", "-J, --client-cert=FILE"); printf (" %s\n", _("Name of file that contains the client certificate (PEM format)")); printf (" %s\n", _("to be used in establishing the SSL session")); -- cgit v1.2.3-74-g34f1 From a96bdd7349926f2f18aba07db02c5ed472f4caf6 Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Sun, 10 Apr 2022 16:31:53 +0200 Subject: check_curl: added option --continue-after-certificate (#1761) --- plugins/check_curl.c | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 7da84de4..a69854a8 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -193,6 +193,7 @@ int followsticky = STICKY_NONE; int use_ssl = FALSE; int use_sni = TRUE; int check_cert = FALSE; +int continue_after_check_cert = FALSE; typedef union { struct curl_slist* to_info; struct curl_certinfo* to_certinfo; @@ -754,7 +755,9 @@ check_http (void) * and we actually have OpenSSL in the monitoring tools */ result = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit); - return result; + if (continue_after_check_cert == FALSE) { + return result; + } #else /* USE_OPENSSL */ die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates - OpenSSL callback used and not linked against OpenSSL\n"); #endif /* USE_OPENSSL */ @@ -794,13 +797,17 @@ GOT_FIRST_CERT: } BIO_free (cert_BIO); result = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit); - return result; + if (continue_after_check_cert == FALSE) { + return result; + } #else /* USE_OPENSSL */ /* We assume we don't have OpenSSL and np_net_ssl_check_certificate at our disposal, * so we use the libcurl CURLINFO data */ result = net_noopenssl_check_certificate(&cert_ptr, days_till_exp_warn, days_till_exp_crit); - return result; + if (continue_after_check_cert == FALSE) { + return result; + } #endif /* USE_OPENSSL */ } else { snprintf (msg, DEFAULT_BUFFER_SIZE, _("Cannot retrieve certificates - cURL returned %d - %s"), @@ -1211,6 +1218,7 @@ process_arguments (int argc, char **argv) INVERT_REGEX = CHAR_MAX + 1, SNI_OPTION, MAX_REDIRS_OPTION, + CONTINUE_AFTER_CHECK_CERT, CA_CERT_OPTION, HTTP_VERSION_OPTION, AUTOMATIC_DECOMPRESSION @@ -1244,6 +1252,7 @@ process_arguments (int argc, char **argv) {"private-key", required_argument, 0, 'K'}, {"ca-cert", required_argument, 0, CA_CERT_OPTION}, {"verify-cert", no_argument, 0, 'D'}, + {"continue-after-certificate", no_argument, 0, CONTINUE_AFTER_CHECK_CERT}, {"useragent", required_argument, 0, 'A'}, {"header", required_argument, 0, 'k'}, {"no-body", no_argument, 0, 'N'}, @@ -1402,6 +1411,11 @@ process_arguments (int argc, char **argv) } check_cert = TRUE; goto enable_ssl; +#endif + case CONTINUE_AFTER_CHECK_CERT: /* don't stop after the certificate is checked */ +#ifdef HAVE_SSL + continue_after_check_cert = TRUE; + break; #endif case 'J': /* use client certificate */ #ifdef LIBCURL_FEATURE_SSL @@ -1800,7 +1814,11 @@ print_help (void) #endif printf (" %s\n", "-C, --certificate=INTEGER[,INTEGER]"); printf (" %s\n", _("Minimum number of days a certificate has to be valid. Port defaults to 443")); - printf (" %s\n", _("(when this option is used the URL is not checked.)")); + printf (" %s\n", _("(when this option is used the URL is not checked by default. You can use")); + printf (" %s\n", _(" --continue-after-certificate to override this behavior)")); + printf (" %s\n", "--continue-after-certificate"); + printf (" %s\n", _("Allows the HTTP check to continue after performing the certificate check.")); + printf (" %s\n", _("Does nothing unless -C is used.")); printf (" %s\n", "-J, --client-cert=FILE"); printf (" %s\n", _("Name of file that contains the client certificate (PEM format)")); printf (" %s\n", _("to be used in establishing the SSL session")); -- cgit v1.2.3-74-g34f1 From ccf4ed25f9c96e4d0cd647bbd8d91f38df75dfc0 Mon Sep 17 00:00:00 2001 From: "Archie L. Cobbs" Date: Thu, 14 Jul 2022 01:47:54 -0500 Subject: check_by_ssh: Add "-U" flag (#1123). (#1774) This causes a 255 exit value from ssh(1), which indicates a connection failure, to return UNKNOWN instead of CRITICAL; similar to check_nrpe's "-u" flag. --- plugins/check_by_ssh.c | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_by_ssh.c b/plugins/check_by_ssh.c index 39d49070..1ad547ed 100644 --- a/plugins/check_by_ssh.c +++ b/plugins/check_by_ssh.c @@ -50,6 +50,7 @@ unsigned int services = 0; int skip_stdout = 0; int skip_stderr = 0; int warn_on_stderr = 0; +bool unknown_timeout = FALSE; char *remotecmd = NULL; char **commargv = NULL; int commargc = 0; @@ -101,6 +102,13 @@ main (int argc, char **argv) result = cmd_run_array (commargv, &chld_out, &chld_err, 0); + /* SSH returns 255 if connection attempt fails; include the first line of error output */ + if (result == 255 && unknown_timeout) { + printf (_("SSH connection failed: %s\n"), + chld_err.lines > 0 ? chld_err.line[0] : "(no error output)"); + return STATE_UNKNOWN; + } + if (verbose) { for(i = 0; i < chld_out.lines; i++) printf("stdout: %s\n", chld_out.line[i]); @@ -180,6 +188,7 @@ process_arguments (int argc, char **argv) {"verbose", no_argument, 0, 'v'}, {"fork", no_argument, 0, 'f'}, {"timeout", required_argument, 0, 't'}, + {"unknown-timeout", no_argument, 0, 'U'}, {"host", required_argument, 0, 'H'}, /* backward compatibility */ {"hostname", required_argument, 0, 'H'}, {"port", required_argument,0,'p'}, @@ -212,7 +221,7 @@ process_arguments (int argc, char **argv) strcpy (argv[c], "-t"); while (1) { - c = getopt_long (argc, argv, "Vvh1246fqt:H:O:p:i:u:l:C:S::E::n:s:o:F:", longopts, + c = getopt_long (argc, argv, "Vvh1246fqt:UH:O:p:i:u:l:C:S::E::n:s:o:F:", longopts, &option); if (c == -1 || c == EOF) @@ -234,6 +243,9 @@ process_arguments (int argc, char **argv) else timeout_interval = atoi (optarg); break; + case 'U': + unknown_timeout = TRUE; + break; case 'H': /* host */ hostname = optarg; break; @@ -445,6 +457,8 @@ print_help (void) printf (" %s\n", _("Tell ssh to suppress warning and diagnostic messages [optional]")); printf (UT_WARN_CRIT); printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + printf (" %s\n","-U, --unknown-timeout"); + printf (" %s\n", _("Make connection problems return UNKNOWN instead of CRITICAL")); printf (UT_VERBOSE); printf("\n"); printf (" %s\n", _("The most common mode of use is to refer to a local identity file with")); @@ -474,7 +488,7 @@ void print_usage (void) { printf ("%s\n", _("Usage:")); - printf (" %s -H -C [-fqv] [-1|-2] [-4|-6]\n" + printf (" %s -H -C [-fqvU] [-1|-2] [-4|-6]\n" " [-S [lines]] [-E [lines]] [-W] [-t timeout] [-i identity]\n" " [-l user] [-n name] [-s servicelist] [-O outputfile]\n" " [-p port] [-o ssh-option] [-F configfile]\n", -- cgit v1.2.3-74-g34f1 From 65fc7064295ac70d1388fa4db4d4d2cddd531e24 Mon Sep 17 00:00:00 2001 From: Lorenz <12514511+RincewindsHat@users.noreply.github.com> Date: Wed, 20 Jul 2022 13:33:49 +0200 Subject: Remove check_http and check_curl test which are somehow always failing (#1777) * Remove failing checks for check_http * Remove failing checks for check_curl --- plugins/t/check_curl.t | 7 +------ plugins/t/check_http.t | 8 +------- 2 files changed, 2 insertions(+), 13 deletions(-) (limited to 'plugins') diff --git a/plugins/t/check_curl.t b/plugins/t/check_curl.t index ada6a045..693f4b25 100644 --- a/plugins/t/check_curl.t +++ b/plugins/t/check_curl.t @@ -9,7 +9,7 @@ use Test::More; use POSIX qw/mktime strftime/; use NPTest; -plan tests => 58; +plan tests => 57; my $successOutput = '/OK.*HTTP.*second/'; @@ -188,11 +188,6 @@ SKIP: { like ( $res->output, '/time_connect=[\d\.]+/', 'Extended Performance Data Output OK' ); like ( $res->output, '/time_ssl=[\d\.]+/', 'Extended Performance Data SSL Output OK' ); - $res = NPTest->testCmd( - "./$plugin --ssl -H www.e-paycobalt.com" - ); - cmp_ok( $res->return_code, "==", 0, "Can read https for www.e-paycobalt.com (uses AES certificate)" ); - $res = NPTest->testCmd( "./$plugin -H www.mozilla.com -u /firefox -f curl" ); is( $res->return_code, 0, "Redirection based on location is okay"); diff --git a/plugins/t/check_http.t b/plugins/t/check_http.t index c137f7b4..0c866229 100644 --- a/plugins/t/check_http.t +++ b/plugins/t/check_http.t @@ -9,7 +9,7 @@ use Test::More; use POSIX qw/mktime strftime/; use NPTest; -plan tests => 50; +plan tests => 49; my $successOutput = '/OK.*HTTP.*second/'; @@ -166,12 +166,6 @@ SKIP: { like ( $res->output, '/time_connect=[\d\.]+/', 'Extended Performance Data Output OK' ); like ( $res->output, '/time_ssl=[\d\.]+/', 'Extended Performance Data SSL Output OK' ); - $res = NPTest->testCmd( - "./$plugin --ssl -H www.e-paycobalt.com" - ); - cmp_ok( $res->return_code, "==", 0, "Can read https for www.e-paycobalt.com (uses AES certificate)" ); - - $res = NPTest->testCmd( "./$plugin -H www.mozilla.com -u /firefox -f follow" ); is( $res->return_code, 0, "Redirection based on location is okay"); -- cgit v1.2.3-74-g34f1 From 9f2a9ca3d72023ff9b5707d1872c54d65edc9017 Mon Sep 17 00:00:00 2001 From: adrb Date: Sun, 24 Jul 2022 16:44:16 +0200 Subject: check_snmp: Segfault if number of processed lines is greater than number of thresholds Segfault at line 489 if number of processed lines is greater than number (#1589) of thresholds Co-authored-by: Lorenz <12514511+RincewindsHat@users.noreply.github.com> --- plugins/check_snmp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_snmp.c b/plugins/check_snmp.c index bd13e579..2601ccd8 100644 --- a/plugins/check_snmp.c +++ b/plugins/check_snmp.c @@ -376,7 +376,7 @@ main (int argc, char **argv) } } - for (line=0, i=0; line < chld_out.lines; line++, i++) { + for (line=0, i=0; line < chld_out.lines && i < numoids ; line++, i++) { if(calculate_rate) conv = "%.10g"; else -- cgit v1.2.3-74-g34f1 From a01de7b33dee837e7a474d9e00131942d7f177f0 Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Mon, 25 Jul 2022 10:00:18 +0200 Subject: fix parsing swap values (#1780) tmp_KB changed from float to uint64, so change the sscanf format accordingly. --- plugins/check_swap.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_swap.c b/plugins/check_swap.c index bb854beb..6c9418f2 100644 --- a/plugins/check_swap.c +++ b/plugins/check_swap.c @@ -150,7 +150,7 @@ main (int argc, char **argv) * The following sscanf call looks for lines looking like: "SwapTotal: 123" and "SwapFree: 123" * This format exists at least on Debian Linux with a 5.* kernel */ - else if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%[TotalFreCchd]%*[:] %f %*[k]%*[B]", str, &tmp_KB)) { + else if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%[TotalFreCchd]%*[:] %lu %*[k]%*[B]", str, &tmp_KB)) { if (verbose >= 3) { printf("Got %s with %lu\n", str, tmp_KB); } -- cgit v1.2.3-74-g34f1 From 3ad5fe9d84138da1451429bfac3b9b4024393d25 Mon Sep 17 00:00:00 2001 From: Lorenz <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 25 Jul 2022 10:11:43 +0200 Subject: check_swap: Fix unit for total in perfdata (#1779) * check_swap: Fix unit for total in perfdata * Remove trailing whitespaces --- plugins/check_swap.c | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'plugins') diff --git a/plugins/check_swap.c b/plugins/check_swap.c index 6c9418f2..ff58b15f 100644 --- a/plugins/check_swap.c +++ b/plugins/check_swap.c @@ -1,30 +1,30 @@ /***************************************************************************** -* +* * Monitoring check_swap plugin -* +* * License: GPL * Copyright (c) 2000 Karl DeBisschop (kdebisschop@users.sourceforge.net) * Copyright (c) 2000-2007 Monitoring Plugins Development Team -* +* * Description: -* +* * This file contains the check_swap plugin -* -* +* +* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. -* +* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. -* +* * You should have received a copy of the GNU General Public License * along with this program. If not, see . -* -* +* +* *****************************************************************************/ const char *progname = "check_swap"; @@ -389,7 +389,7 @@ main (int argc, char **argv) TRUE, warn_print, TRUE, crit_print, TRUE, 0, - TRUE, (long) total_swap_mb)); + TRUE, (long) total_swap_mb * 1024 * 1024)); return result; } -- cgit v1.2.3-74-g34f1 From fbbc9fcbd566db60058047870fbd6a2105e96663 Mon Sep 17 00:00:00 2001 From: Lorenz <12514511+RincewindsHat@users.noreply.github.com> Date: Sun, 11 Sep 2022 06:29:17 +0200 Subject: Check swap compiler warnings (#1756) * Fix compiler warnings * Fix superfluous whitespaces --- plugins/check_swap.c | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) (limited to 'plugins') diff --git a/plugins/check_swap.c b/plugins/check_swap.c index ff58b15f..a607da1e 100644 --- a/plugins/check_swap.c +++ b/plugins/check_swap.c @@ -410,7 +410,6 @@ check_swap(float free_swap_mb, float total_swap_mb) uint64_t usage_percentage = ((total_swap_mb - free_swap_mb) / total_swap_mb) * 100; if (crit.is_percentage && - usage_percentage >= 0 && crit.value != 0 && usage_percentage >= (100 - crit.value)) { @@ -418,7 +417,6 @@ check_swap(float free_swap_mb, float total_swap_mb) } if (warn.is_percentage && - usage_percentage >= 0 && warn.value != 0 && usage_percentage >= (100 - warn.value)) { @@ -475,10 +473,9 @@ process_arguments (int argc, char **argv) if (is_uint64(optarg, &warn.value)) { if (warn.value > 100) { usage4 (_("Warning threshold percentage must be <= 100!")); - } else { - break; } } + break; } else { /* It's Bytes */ warn.is_percentage = 0; @@ -506,10 +503,9 @@ process_arguments (int argc, char **argv) if (is_uint64(optarg, &crit.value)) { if (crit.value> 100) { usage4 (_("Critical threshold percentage must be <= 100!")); - } else { - break; } } + break; } else { /* It's Bytes */ crit.is_percentage = 0; @@ -527,6 +523,7 @@ process_arguments (int argc, char **argv) if ((no_swap_state = mp_translate_state(optarg)) == ERROR) { usage4 (_("no-swap result must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); } + break; case 'v': /* verbose */ verbose++; break; -- cgit v1.2.3-74-g34f1 From a9cdbc8959a7722494700aaddc63f0c7e0d34062 Mon Sep 17 00:00:00 2001 From: Lorenz <12514511+RincewindsHat@users.noreply.github.com> Date: Sun, 11 Sep 2022 06:29:36 +0200 Subject: Check load compiler warnings (#1759) * Fix compiler warnings due to implizit conversion and formats * Make includes more specific and complement them * Formatting fixes --- plugins/check_load.c | 66 ++++++++++++++++++++++++++-------------------------- 1 file changed, 33 insertions(+), 33 deletions(-) (limited to 'plugins') diff --git a/plugins/check_load.c b/plugins/check_load.c index 0e4de54e..d1bb30a4 100644 --- a/plugins/check_load.c +++ b/plugins/check_load.c @@ -1,41 +1,43 @@ /***************************************************************************** -* +* * Monitoring check_load plugin -* +* * License: GPL * Copyright (c) 1999-2007 Monitoring Plugins Development Team -* +* * Description: -* +* * This file contains the check_load plugin -* +* * This plugin tests the current system load average. -* -* +* +* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. -* +* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. -* +* * You should have received a copy of the GNU General Public License * along with this program. If not, see . -* -* +* +* *****************************************************************************/ const char *progname = "check_load"; const char *copyright = "1999-2007"; const char *email = "devel@monitoring-plugins.org"; -#include "common.h" -#include "runcmd.h" -#include "utils.h" -#include "popen.h" +#include "./common.h" +#include "./runcmd.h" +#include "./utils.h" +#include "./popen.h" + +#include #ifdef HAVE_SYS_LOADAVG_H #include @@ -101,7 +103,7 @@ get_threshold(char *arg, double *th) int main (int argc, char **argv) { - int result; + int result = -1; int i; long numcpus; @@ -164,7 +166,7 @@ main (int argc, char **argv) sscanf (input_buffer, "%*[^l]load averages: %lf, %lf, %lf", &la1, &la5, &la15); } else { - printf (_("could not parse load from uptime %s: %s\n"), PATH_TO_UPTIME, result); + printf (_("could not parse load from uptime %s: %d\n"), PATH_TO_UPTIME, result); return STATE_UNKNOWN; } @@ -289,7 +291,6 @@ process_arguments (int argc, char **argv) } - static int validate_arguments (void) { @@ -310,7 +311,6 @@ validate_arguments (void) } - void print_help (void) { @@ -321,7 +321,7 @@ print_help (void) printf (_("This plugin tests the current system load average.")); - printf ("\n\n"); + printf ("\n\n"); print_usage (); @@ -329,15 +329,15 @@ print_help (void) printf (UT_EXTRA_OPTS); printf (" %s\n", "-w, --warning=WLOAD1,WLOAD5,WLOAD15"); - printf (" %s\n", _("Exit with WARNING status if load average exceeds WLOADn")); - printf (" %s\n", "-c, --critical=CLOAD1,CLOAD5,CLOAD15"); - printf (" %s\n", _("Exit with CRITICAL status if load average exceed CLOADn")); - printf (" %s\n", _("the load average format is the same used by \"uptime\" and \"w\"")); - printf (" %s\n", "-r, --percpu"); - printf (" %s\n", _("Divide the load averages by the number of CPUs (when possible)")); - printf (" %s\n", "-n, --procs-to-show=NUMBER_OF_PROCS"); - printf (" %s\n", _("Number of processes to show when printing the top consuming processes.")); - printf (" %s\n", _("NUMBER_OF_PROCS=0 disables this feature. Default value is 0")); + printf (" %s\n", _("Exit with WARNING status if load average exceeds WLOADn")); + printf (" %s\n", "-c, --critical=CLOAD1,CLOAD5,CLOAD15"); + printf (" %s\n", _("Exit with CRITICAL status if load average exceed CLOADn")); + printf (" %s\n", _("the load average format is the same used by \"uptime\" and \"w\"")); + printf (" %s\n", "-r, --percpu"); + printf (" %s\n", _("Divide the load averages by the number of CPUs (when possible)")); + printf (" %s\n", "-n, --procs-to-show=NUMBER_OF_PROCS"); + printf (" %s\n", _("Number of processes to show when printing the top consuming processes.")); + printf (" %s\n", _("NUMBER_OF_PROCS=0 disables this feature. Default value is 0")); printf (UT_SUPPORT); } @@ -345,8 +345,8 @@ print_help (void) void print_usage (void) { - printf ("%s\n", _("Usage:")); - printf ("%s [-r] -w WLOAD1,WLOAD5,WLOAD15 -c CLOAD1,CLOAD5,CLOAD15 [-n NUMBER_OF_PROCS]\n", progname); + printf ("%s\n", _("Usage:")); + printf ("%s [-r] -w WLOAD1,WLOAD5,WLOAD15 -c CLOAD1,CLOAD5,CLOAD15 [-n NUMBER_OF_PROCS]\n", progname); } #ifdef PS_USES_PROCPCPU @@ -384,8 +384,8 @@ static int print_top_consuming_processes() { #ifdef PS_USES_PROCPCPU qsort(chld_out.line + 1, chld_out.lines - 1, sizeof(char*), cmpstringp); #endif /* PS_USES_PROCPCPU */ - int lines_to_show = chld_out.lines < (n_procs_to_show + 1) - ? chld_out.lines : n_procs_to_show + 1; + int lines_to_show = chld_out.lines < (size_t)(n_procs_to_show + 1) + ? (int)chld_out.lines : n_procs_to_show + 1; for (i = 0; i < lines_to_show; i += 1) { printf("%s\n", chld_out.line[i]); } -- cgit v1.2.3-74-g34f1 From ef5796255268cd663a4e66820cf1bd883055ba00 Mon Sep 17 00:00:00 2001 From: Lorenz <12514511+RincewindsHat@users.noreply.github.com> Date: Sun, 11 Sep 2022 06:29:58 +0200 Subject: Check disk compiler warnings (#1758) * Use unused variable * Proper format strings for printf * Use proper functions for absolute values * Remove and add comments at some places --- plugins/check_disk.c | 67 +++++++--------------------------------------------- 1 file changed, 8 insertions(+), 59 deletions(-) (limited to 'plugins') diff --git a/plugins/check_disk.c b/plugins/check_disk.c index 66c5dd39..7018c6fd 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -171,7 +171,6 @@ main (int argc, char **argv) char *perf_ilabel; char *preamble; char *flag_header; - double inode_space_pct; int temp_result; struct mount_entry *me; @@ -288,7 +287,7 @@ main (int argc, char **argv) get_stats (path, &fsp); if (verbose >= 3) { - printf ("For %s, used_pct=%g free_pct=%g used_units=%llu free_units=%llu total_units=%llu used_inodes_pct=%g free_inodes_pct=%g fsp.fsu_blocksize=%llu mult=%llu\n", + printf ("For %s, used_pct=%g free_pct=%g used_units=%lu free_units=%lu total_units=%lu used_inodes_pct=%g free_inodes_pct=%g fsp.fsu_blocksize=%lu mult=%lu\n", me->me_mountdir, path->dused_pct, path->dfree_pct, @@ -369,10 +368,10 @@ main (int argc, char **argv) critical_high_tide = UINT64_MAX; if (path->freeinodes_percent->warning != NULL) { - warning_high_tide = llabs( min( (double) warning_high_tide, (double) (1.0 - path->freeinodes_percent->warning->end/100)*path->inodes_total )); + warning_high_tide = (uint64_t) fabs( min( (double) warning_high_tide, (double) (1.0 - path->freeinodes_percent->warning->end/100)*path->inodes_total )); } if (path->freeinodes_percent->critical != NULL) { - critical_high_tide = llabs( min( (double) critical_high_tide, (double) (1.0 - path->freeinodes_percent->critical->end/100)*path->inodes_total )); + critical_high_tide = (uint64_t) fabs( min( (double) critical_high_tide, (double) (1.0 - path->freeinodes_percent->critical->end/100)*path->inodes_total )); } xasprintf (&perf_ilabel, "%s (inodes)", (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir); @@ -406,15 +405,7 @@ main (int argc, char **argv) xasprintf(&output, "%s inode=%.0f%%)%s;", output, path->dfree_inodes_percent, ((disk_result && verbose >= 1) ? "]" : "")); } free(flag_header); - /* TODO: Need to do a similar debug line - xasprintf (&details, _("%s\n\%.0f of %.0f %s (%.0f%% inode=%.0f%%) free on %s (type %s mounted on %s) warn:%lu crit:%lu warn%%:%.0f%% crit%%:%.0f%%"), - details, dfree_units, dtotal_units, units, dfree_pct, inode_space_pct, - me->me_devname, me->me_type, me->me_mountdir, - (unsigned long)w_df, (unsigned long)c_df, w_dfp, c_dfp); - */ - } - } if (verbose >= 2) @@ -689,6 +680,7 @@ process_arguments (int argc, char **argv) break; case 'I': cflags |= REG_ICASE; + // Intentional fallthrough case 'i': if (!path_selected) die (STATE_UNKNOWN, "DISK %s: %s\n", _("UNKNOWN"), _("Paths need to be selected before using -i/-I. Use -A to select all paths explicitly")); @@ -728,8 +720,10 @@ process_arguments (int argc, char **argv) case 'A': optarg = strdup(".*"); + // Intentional fallthrough case 'R': cflags |= REG_ICASE; + // Intentional fallthrough case 'r': if (! (warn_freespace_units || crit_freespace_units || warn_freespace_percent || crit_freespace_percent || warn_usedspace_units || crit_usedspace_units || @@ -862,51 +856,6 @@ set_all_thresholds (struct parameter_list *path) set_thresholds(&path->freeinodes_percent, warn_freeinodes_percent, crit_freeinodes_percent); } -/* TODO: Remove? - -int -validate_arguments (uintmax_t w, uintmax_t c, double wp, double cp, double iwp, double icp, char *mypath) -{ - if (w < 0 && c < 0 && wp < 0.0 && cp < 0.0) { - printf (_("INPUT ERROR: No thresholds specified")); - print_path (mypath); - return ERROR; - } - else if ((wp >= 0.0 || cp >= 0.0) && - (wp < 0.0 || cp < 0.0 || wp > 100.0 || cp > 100.0 || cp > wp)) { - printf (_("\ -INPUT ERROR: C_DFP (%f) should be less than W_DFP (%.1f) and both should be between zero and 100 percent, inclusive"), - cp, wp); - print_path (mypath); - return ERROR; - } - else if ((iwp >= 0.0 || icp >= 0.0) && - (iwp < 0.0 || icp < 0.0 || iwp > 100.0 || icp > 100.0 || icp > iwp)) { - printf (_("\ -INPUT ERROR: C_IDFP (%f) should be less than W_IDFP (%.1f) and both should be between zero and 100 percent, inclusive"), - icp, iwp); - print_path (mypath); - return ERROR; - } - else if ((w > 0 || c > 0) && (w == 0 || c == 0 || c > w)) { - printf (_("\ -INPUT ERROR: C_DF (%lu) should be less than W_DF (%lu) and both should be greater than zero"), - (unsigned long)c, (unsigned long)w); - print_path (mypath); - return ERROR; - } - - return OK; -} - -*/ - - - - - - - void print_help (void) { @@ -1042,7 +991,7 @@ get_stats (struct parameter_list *p, struct fs_usage *fsp) { get_fs_usage (p_list->best_match->me_mountdir, p_list->best_match->me_devname, &tmpfsp); get_path_stats(p_list, &tmpfsp); if (verbose >= 3) - printf("Group %s: adding %llu blocks sized %llu, (%s) used_units=%lu free_units=%llu total_units=%llu mult=%llu\n", + printf("Group %s: adding %lu blocks sized %lu, (%s) used_units=%lu free_units=%lu total_units=%lu mult=%lu\n", p_list->group, tmpfsp.fsu_blocks, tmpfsp.fsu_blocksize, @@ -1071,7 +1020,7 @@ get_stats (struct parameter_list *p, struct fs_usage *fsp) { first = 0; } if (verbose >= 3) - printf("Group %s now has: used_units=%llu free_units=%llu total_units=%llu fsu_blocksize=%llu mult=%llu\n", + printf("Group %s now has: used_units=%lu free_units=%lu total_units=%lu fsu_blocksize=%lu mult=%lu\n", p->group, p->dused_units, p->dfree_units, -- cgit v1.2.3-74-g34f1 From b89aee56964f7d933f2da5f371e32b4d7db9410b Mon Sep 17 00:00:00 2001 From: Lorenz <12514511+RincewindsHat@users.noreply.github.com> Date: Wed, 14 Sep 2022 10:54:46 +0200 Subject: Check ntp remove unused variables (#1781) * Remove unused argument * Fix typo in comment --- plugins/check_ntp.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/check_ntp.c b/plugins/check_ntp.c index 914b40ce..8b776ba1 100644 --- a/plugins/check_ntp.c +++ b/plugins/check_ntp.c @@ -355,7 +355,7 @@ int best_offset_server(const ntp_server_results *slist, int nservers){ * - we also "manually" handle resolving host names and connecting, because * we have to do it in a way that our lazy macros don't handle currently :( */ double offset_request(const char *host, int *status){ - int i=0, j=0, ga_result=0, num_hosts=0, *socklist=NULL, respnum=0; + int i=0, ga_result=0, num_hosts=0, *socklist=NULL, respnum=0; int servers_completed=0, one_read=0, servers_readable=0, best_index=-1; time_t now_time=0, start_ts=0; ntp_message *req=NULL; @@ -488,7 +488,7 @@ double offset_request(const char *host, int *status){ /* cleanup */ /* FIXME: Not closing the socket to avoid re-use of the local port * which can cause old NTP packets to be read instead of NTP control - * pactets in jitter_request(). THERE MUST BE ANOTHER WAY... + * packets in jitter_request(). THERE MUST BE ANOTHER WAY... * for(j=0; j Date: Mon, 11 Apr 2016 12:52:02 -0500 Subject: Added ability to correctly check redirects with reference format //test.server.com/folder Referenced redirect of the format //www.server.com/folder would result in check_http trying to contact http://hostname:80//www.server.com/folder instead of http://www.server.com/folder. Referenced redirect of this format is listed in rfc3986 ( https://tools.ietf.org/html/rfc3986 ). It should work as expected now. --- plugins/check_http.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index f8ec853b..36f3b253 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -1364,6 +1364,9 @@ check_http (void) #define HD3 URI_HTTP "://" URI_HOST ":" URI_PORT #define HD4 URI_HTTP "://" URI_HOST #define HD5 URI_PATH +/* relative reference redirect like //www.site.org/test https://tools.ietf.org/html/rfc3986 */ +#define HD6 "//" URI_HOST "/" URI_PATH + void redir (char *pos, char *status_line) @@ -1440,6 +1443,21 @@ redir (char *pos, char *status_line) use_ssl = server_type_check (type); i = server_port_check (use_ssl); } + else if (sscanf (pos, HD6, addr, url) == 2) { + //get type from + if(use_ssl){ + //i = server_port_check (use_ssl); + strcpy (type,"https"); + } + //else if(sscanf(server_url,URI_HTTP,type)==1 ){ + //} + else{ + strcpy (type, server_type); + } + xasprintf (&url, "/%s", url); + use_ssl = server_type_check (type); + i = server_port_check (use_ssl); + } /* URI_PATH */ else if (sscanf (pos, HD5, url) == 1) { -- cgit v1.2.3-74-g34f1 From d57d2b0bdda192dc50e17ebeb8becfe249c3f8e3 Mon Sep 17 00:00:00 2001 From: Eric Wunderlin Date: Tue, 12 Apr 2016 09:00:08 -0500 Subject: Remove unused code --- plugins/check_http.c | 4 ---- 1 file changed, 4 deletions(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index 36f3b253..59755acd 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -1444,13 +1444,9 @@ redir (char *pos, char *status_line) i = server_port_check (use_ssl); } else if (sscanf (pos, HD6, addr, url) == 2) { - //get type from if(use_ssl){ - //i = server_port_check (use_ssl); strcpy (type,"https"); } - //else if(sscanf(server_url,URI_HTTP,type)==1 ){ - //} else{ strcpy (type, server_type); } -- cgit v1.2.3-74-g34f1 From e2e405596a070ec3b830696ecf574ee3a243c7b1 Mon Sep 17 00:00:00 2001 From: "John C. Frickson" Date: Mon, 21 Nov 2016 22:40:39 +0100 Subject: I had to make a couple of small changes. --- plugins/check_http.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index 59755acd..fb38bc5b 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -1363,10 +1363,9 @@ check_http (void) #define HD2 URI_HTTP "://" URI_HOST "/" URI_PATH #define HD3 URI_HTTP "://" URI_HOST ":" URI_PORT #define HD4 URI_HTTP "://" URI_HOST -#define HD5 URI_PATH /* relative reference redirect like //www.site.org/test https://tools.ietf.org/html/rfc3986 */ -#define HD6 "//" URI_HOST "/" URI_PATH - +#define HD5 "//" URI_HOST "/" URI_PATH +#define HD5 URI_PATH void redir (char *pos, char *status_line) @@ -1443,7 +1442,8 @@ redir (char *pos, char *status_line) use_ssl = server_type_check (type); i = server_port_check (use_ssl); } - else if (sscanf (pos, HD6, addr, url) == 2) { + /* URI_HTTP, URI_HOST, URI_PATH */ + else if (sscanf (pos, HD5, addr, url) == 2) { if(use_ssl){ strcpy (type,"https"); } @@ -1456,7 +1456,7 @@ redir (char *pos, char *status_line) } /* URI_PATH */ - else if (sscanf (pos, HD5, url) == 1) { + else if (sscanf (pos, HD6, url) == 1) { /* relative url */ if ((url[0] != '/')) { if ((x = strrchr(server_url, '/'))) -- cgit v1.2.3-74-g34f1 From 80872917294340a1e399b8a100c5a81c4f719220 Mon Sep 17 00:00:00 2001 From: Jan Wagner Date: Sat, 31 Dec 2016 13:57:44 +0100 Subject: check_http: Fix HD6 definition --- plugins/check_http.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index fb38bc5b..ff39c591 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -1365,7 +1365,7 @@ check_http (void) #define HD4 URI_HTTP "://" URI_HOST /* relative reference redirect like //www.site.org/test https://tools.ietf.org/html/rfc3986 */ #define HD5 "//" URI_HOST "/" URI_PATH -#define HD5 URI_PATH +#define HD6 URI_PATH void redir (char *pos, char *status_line) -- cgit v1.2.3-74-g34f1 From b90a5757f77cdc0434fa3f45cf59c63b9e695d90 Mon Sep 17 00:00:00 2001 From: Lorenz <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 19 Sep 2022 10:23:49 +0200 Subject: Display total and scaled load values if check_load scales the values by number of CPUs (#1778) * Renew copyright * Display more verbose output, if scaled load values are used * Actually use scaled value for determining status and print the fitting perfdata depending on input parameters * Add test cases for scaled mode --- plugins/check_load.c | 56 +++++++++++++++++++++++++++++++++++--------------- plugins/t/check_load.t | 15 ++++++++++---- 2 files changed, 51 insertions(+), 20 deletions(-) (limited to 'plugins') diff --git a/plugins/check_load.c b/plugins/check_load.c index d1bb30a4..00f7c877 100644 --- a/plugins/check_load.c +++ b/plugins/check_load.c @@ -29,7 +29,7 @@ *****************************************************************************/ const char *progname = "check_load"; -const char *copyright = "1999-2007"; +const char *copyright = "1999-2022"; const char *email = "devel@monitoring-plugins.org"; #include "./common.h" @@ -70,7 +70,7 @@ double cload[3] = { 0.0, 0.0, 0.0 }; #define la15 la[2] char *status_line; -int take_into_account_cpus = 0; +bool take_into_account_cpus = false; static void get_threshold(char *arg, double *th) @@ -178,13 +178,6 @@ main (int argc, char **argv) # endif #endif - if (take_into_account_cpus == 1) { - if ((numcpus = GET_NUMBER_OF_CPUS()) > 0) { - la[0] = la[0] / numcpus; - la[1] = la[1] / numcpus; - la[2] = la[2] / numcpus; - } - } if ((la[0] < 0.0) || (la[1] < 0.0) || (la[2] < 0.0)) { #ifdef HAVE_GETLOADAVG printf (_("Error in getloadavg()\n")); @@ -202,18 +195,49 @@ main (int argc, char **argv) result = STATE_OK; xasprintf(&status_line, _("load average: %.2f, %.2f, %.2f"), la1, la5, la15); + xasprintf(&status_line, ("total %s"), status_line); + + + double scaled_la[3] = { 0.0, 0.0, 0.0 }; + bool is_using_scaled_load_values = false; + + if (take_into_account_cpus == true && (numcpus = GET_NUMBER_OF_CPUS()) > 0) { + is_using_scaled_load_values = true; + + scaled_la[0] = la[0] / numcpus; + scaled_la[1] = la[1] / numcpus; + scaled_la[2] = la[2] / numcpus; + + char *tmp = NULL; + xasprintf(&tmp, _("load average: %.2f, %.2f, %.2f"), scaled_la[0], scaled_la[1], scaled_la[2]); + xasprintf(&status_line, "scaled %s - %s", tmp, status_line); + } for(i = 0; i < 3; i++) { - if(la[i] > cload[i]) { - result = STATE_CRITICAL; - break; + if (is_using_scaled_load_values) { + if(scaled_la[i] > cload[i]) { + result = STATE_CRITICAL; + break; + } + else if(scaled_la[i] > wload[i]) result = STATE_WARNING; + } else { + if(la[i] > cload[i]) { + result = STATE_CRITICAL; + break; + } + else if(la[i] > wload[i]) result = STATE_WARNING; } - else if(la[i] > wload[i]) result = STATE_WARNING; } printf("LOAD %s - %s|", state_text(result), status_line); - for(i = 0; i < 3; i++) - printf("load%d=%.3f;%.3f;%.3f;0; ", nums[i], la[i], wload[i], cload[i]); + for(i = 0; i < 3; i++) { + if (is_using_scaled_load_values) { + printf("load%d=%.3f;;;0; ", nums[i], la[i]); + printf("scaled_load%d=%.3f;%.3f;%.3f;0; ", nums[i], scaled_la[i], wload[i], cload[i]); + } else { + printf("load%d=%.3f;%.3f;%.3f;0; ", nums[i], la[i], wload[i], cload[i]); + } + } putchar('\n'); if (n_procs_to_show > 0) { @@ -257,7 +281,7 @@ process_arguments (int argc, char **argv) get_threshold(optarg, cload); break; case 'r': /* Divide load average by number of CPUs */ - take_into_account_cpus = 1; + take_into_account_cpus = true; break; case 'V': /* version */ print_revision (progname, NP_VERSION); diff --git a/plugins/t/check_load.t b/plugins/t/check_load.t index 60837ef6..bba8947c 100644 --- a/plugins/t/check_load.t +++ b/plugins/t/check_load.t @@ -11,10 +11,12 @@ use NPTest; my $res; my $loadValue = "[0-9]+\.?[0-9]+"; -my $successOutput = "/^LOAD OK - load average: $loadValue, $loadValue, $loadValue/"; -my $failureOutput = "/^LOAD CRITICAL - load average: $loadValue, $loadValue, $loadValue/"; +my $successOutput = "/^LOAD OK - total load average: $loadValue, $loadValue, $loadValue/"; +my $successScaledOutput = "/^LOAD OK - scaled load average: $loadValue, $loadValue, $loadValue - total load average: $loadValue, $loadValue, $loadValue/"; +my $failureOutput = "/^LOAD CRITICAL - total load average: $loadValue, $loadValue, $loadValue/"; +my $failurScaledOutput = "/^LOAD CRITICAL - scaled load average: $loadValue, $loadValue, $loadValue - total load average: $loadValue, $loadValue, $loadValue/"; -plan tests => 11; +plan tests => 13; $res = NPTest->testCmd( "./check_load -w 100,100,100 -c 100,100,100" ); cmp_ok( $res->return_code, 'eq', 0, "load not over 100"); @@ -26,7 +28,7 @@ like( $res->output, $failureOutput, "Output OK"); $res = NPTest->testCmd( "./check_load -r -w 0,0,0 -c 0,0,0" ); cmp_ok( $res->return_code, 'eq', 2, "Load over 0 with per cpu division"); -like( $res->output, $failureOutput, "Output OK"); +like( $res->output, $failurScaledOutput, "Output OK"); $res = NPTest->testCmd( "./check_load -w 100 -c 100,110" ); cmp_ok( $res->return_code, 'eq', 0, "Plugin can handle non-triplet-arguments"); @@ -34,3 +36,8 @@ like( $res->output, $successOutput, "Output OK"); like( $res->perf_output, "/load1=$loadValue;100.000;100.000/", "Test handling of non triplet thresholds (load1)"); like( $res->perf_output, "/load5=$loadValue;100.000;110.000/", "Test handling of non triplet thresholds (load5)"); like( $res->perf_output, "/load15=$loadValue;100.000;110.000/", "Test handling of non triplet thresholds (load15)"); + + +$res = NPTest->testCmd( "./check_load -w 100,100,100 -c 100,100,100 -r" ); +cmp_ok( $res->return_code, 'eq', 0, "load not over 100"); +like( $res->output, $successScaledOutput, "Output OK"); -- cgit v1.2.3-74-g34f1 From 817ac2e5dad1ce5d0e0ea96fa7f726566251b08d Mon Sep 17 00:00:00 2001 From: Andreas Baumann <202930+andreasbaumann@users.noreply.github.com> Date: Fri, 21 Oct 2022 18:31:12 +0200 Subject: using PRId64 and PRIu64 instead of %ld directly (#1800) --- plugins/utils.c | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) (limited to 'plugins') diff --git a/plugins/utils.c b/plugins/utils.c index 17dd5814..f75cf03b 100644 --- a/plugins/utils.c +++ b/plugins/utils.c @@ -615,27 +615,27 @@ char *perfdata_uint64 (const char *label, char *data = NULL; if (strpbrk (label, "'= ")) - xasprintf (&data, "'%s'=%ld%s;", label, val, uom); + xasprintf (&data, "'%s'=%" PRId64 "%s;", label, val, uom); else - xasprintf (&data, "%s=%ld%s;", label, val, uom); + xasprintf (&data, "%s=%" PRId64 "%s;", label, val, uom); if (warnp) - xasprintf (&data, "%s%lu;", data, warn); + xasprintf (&data, "%s%" PRIu64 ";", data, warn); else xasprintf (&data, "%s;", data); if (critp) - xasprintf (&data, "%s%lu;", data, crit); + xasprintf (&data, "%s%" PRIu64 ";", data, crit); else xasprintf (&data, "%s;", data); if (minp) - xasprintf (&data, "%s%lu;", data, minv); + xasprintf (&data, "%s%" PRIu64 ";", data, minv); else xasprintf (&data, "%s;", data); if (maxp) - xasprintf (&data, "%s%lu", data, maxv); + xasprintf (&data, "%s%" PRIu64, data, maxv); return data; } @@ -656,27 +656,27 @@ char *perfdata_int64 (const char *label, char *data = NULL; if (strpbrk (label, "'= ")) - xasprintf (&data, "'%s'=%ld%s;", label, val, uom); + xasprintf (&data, "'%s'=%" PRId64 "%s;", label, val, uom); else - xasprintf (&data, "%s=%ld%s;", label, val, uom); + xasprintf (&data, "%s=%" PRId64 "%s;", label, val, uom); if (warnp) - xasprintf (&data, "%s%ld;", data, warn); + xasprintf (&data, "%s%" PRId64 ";", data, warn); else xasprintf (&data, "%s;", data); if (critp) - xasprintf (&data, "%s%ld;", data, crit); + xasprintf (&data, "%s%" PRId64 ";", data, crit); else xasprintf (&data, "%s;", data); if (minp) - xasprintf (&data, "%s%ld;", data, minv); + xasprintf (&data, "%s%" PRId64 ";", data, minv); else xasprintf (&data, "%s;", data); if (maxp) - xasprintf (&data, "%s%ld", data, maxv); + xasprintf (&data, "%s%" PRId64, data, maxv); return data; } -- cgit v1.2.3-74-g34f1 From eb2dfdd5c24b87198b66397b224d6406c468a0bc Mon Sep 17 00:00:00 2001 From: Andreas Baumann <202930+andreasbaumann@users.noreply.github.com> Date: Thu, 27 Oct 2022 22:48:18 +0200 Subject: fixed two PRId64 to PRIu64 in perfdata_uint64 (#1802) --- plugins/utils.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/utils.c b/plugins/utils.c index f75cf03b..b4214c61 100644 --- a/plugins/utils.c +++ b/plugins/utils.c @@ -615,9 +615,9 @@ char *perfdata_uint64 (const char *label, char *data = NULL; if (strpbrk (label, "'= ")) - xasprintf (&data, "'%s'=%" PRId64 "%s;", label, val, uom); + xasprintf (&data, "'%s'=%" PRIu64 "%s;", label, val, uom); else - xasprintf (&data, "%s=%" PRId64 "%s;", label, val, uom); + xasprintf (&data, "%s=%" PRIu64 "%s;", label, val, uom); if (warnp) xasprintf (&data, "%s%" PRIu64 ";", data, warn); -- cgit v1.2.3-74-g34f1 From 2d9c6276d0a380f831bf94734359f071d0c7e958 Mon Sep 17 00:00:00 2001 From: waja Date: Fri, 4 Nov 2022 19:16:01 +0100 Subject: Removing is_pg_dbname alltogether,using postgres API. (Closes: #1660) (#1803) The problem is that check_pgsql validates the Database name and has different assumptions that postgres itself. I fail to see a reason to validate the database name here. Postgres'es API should do this - So i would suggest a fix like this by removing is_pg_dbname alltogether. Co-authored-by: Florian Lohoff --- plugins/check_pgsql.c | 48 ++++-------------------------------------------- 1 file changed, 4 insertions(+), 44 deletions(-) (limited to 'plugins') diff --git a/plugins/check_pgsql.c b/plugins/check_pgsql.c index c893386c..c26cd439 100644 --- a/plugins/check_pgsql.c +++ b/plugins/check_pgsql.c @@ -69,7 +69,6 @@ int process_arguments (int, char **); int validate_arguments (void); void print_usage (void); void print_help (void); -int is_pg_dbname (char *); int is_pg_logname (char *); int do_query (PGconn *, char *); @@ -347,10 +346,10 @@ process_arguments (int argc, char **argv) pgport = optarg; break; case 'd': /* database name */ - if (!is_pg_dbname (optarg)) /* checks length and valid chars */ - usage2 (_("Database name is not valid"), optarg); - else /* we know length, and know optarg is terminated, so us strcpy */ - snprintf(dbName, NAMEDATALEN, "%s", optarg); + if (strlen(optarg) >= NAMEDATALEN) { + usage2 (_("Database name exceeds the maximum length"), optarg); + } + snprintf(dbName, NAMEDATALEN, "%s", optarg); break; case 'l': /* login name */ if (!is_pg_logname (optarg)) @@ -414,45 +413,6 @@ validate_arguments () return OK; } - -/****************************************************************************** - -@@- - -is_pg_dbname - -&PROTO_is_pg_dbname; - -Given a database name, this function returns TRUE if the string -is a valid PostgreSQL database name, and returns false if it is -not. - -Valid PostgreSQL database names are less than &NAMEDATALEN; -characters long and consist of letters, numbers, and underscores. The -first character cannot be a number, however. - - --@@ -******************************************************************************/ - - - -int -is_pg_dbname (char *dbname) -{ - char txt[NAMEDATALEN]; - char tmp[NAMEDATALEN]; - if (strlen (dbname) > NAMEDATALEN - 1) - return (FALSE); - strncpy (txt, dbname, NAMEDATALEN - 1); - txt[NAMEDATALEN - 1] = 0; - if (sscanf (txt, "%[_a-zA-Z]%[^_a-zA-Z0-9-]", tmp, tmp) == 1) - return (TRUE); - if (sscanf (txt, "%[_a-zA-Z]%[_a-zA-Z0-9-]%[^_a-zA-Z0-9-]", tmp, tmp, tmp) == - 2) return (TRUE); - return (FALSE); -} - /** the tango program should eventually create an entity here based on the -- cgit v1.2.3-74-g34f1 From edc84e5d669089fa3f047dc52740679e7cb58fc1 Mon Sep 17 00:00:00 2001 From: Lorenz <12514511+RincewindsHat@users.noreply.github.com> Date: Sat, 5 Nov 2022 13:59:45 +0100 Subject: Remove superflous CRLF in HTTP-Requests in check_http (#1798) * Remove superflous CRLF in HTTP-Requests in check_http --- plugins/check_http.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index ff39c591..41d47816 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -1070,9 +1070,8 @@ check_http (void) } xasprintf (&buf, "%sContent-Length: %i\r\n\r\n", buf, (int)strlen (http_post_data)); - xasprintf (&buf, "%s%s%s", buf, http_post_data, CRLF); - } - else { + xasprintf (&buf, "%s%s", buf, http_post_data); + } else { /* or just a newline so the server knows we're done with the request */ xasprintf (&buf, "%s%s", buf, CRLF); } -- cgit v1.2.3-74-g34f1 From 4a5ddd201119260028db6a4f27027d72aa9a160a Mon Sep 17 00:00:00 2001 From: Lorenz <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 7 Nov 2022 17:48:28 +0100 Subject: Check curl detect ipv6 (#1809) * If server_address is an IPv6 address surround it with brackets * If the message is too short, we should not have an underflow * Add simple conditional test case available if IPv6 is --- .github/workflows/test.yml | 2 +- plugins/check_curl.c | 22 ++++++++++++++++++---- plugins/t/check_curl.t | 39 ++++++++++++++++++++++++++++----------- 3 files changed, 47 insertions(+), 16 deletions(-) (limited to 'plugins') diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d2785a41..80d49f7e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -40,7 +40,7 @@ jobs: ${{ matrix.distro }} \ /bin/sh -c '${{ matrix.prepare }} && \ tools/setup && \ - ./configure --enable-libtap --with-ipv6=no && \ + ./configure --enable-libtap --with-ipv6=no && \ make && \ make test' docker container prune -f diff --git a/plugins/check_curl.c b/plugins/check_curl.c index a69854a8..2ad373c0 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -476,6 +476,18 @@ check_http (void) printf ("* curl CURLOPT_RESOLVE: %s\n", dnscache); } + // If server_address is an IPv6 address it must be surround by square brackets + struct in6_addr tmp_in_addr; + if (inet_pton(AF_INET6, server_address, &tmp_in_addr) == 1) { + char *new_server_address = malloc(strlen(server_address) + 3); + if (new_server_address == NULL) { + die(STATE_UNKNOWN, "HTTP UNKNOWN - Unable to allocate memory\n"); + } + snprintf(new_server_address, strlen(server_address)+3, "[%s]", server_address); + free(server_address); + server_address = new_server_address; + } + /* compose URL: use the address we want to connect to, set Host: header later */ snprintf (url, DEFAULT_BUFFER_SIZE, "%s://%s:%d%s", use_ssl ? "https" : "http", @@ -999,10 +1011,12 @@ GOT_FIRST_CERT: result = max_state_alt(get_status(total_time, thlds), result); /* Cut-off trailing characters */ - if(msg[strlen(msg)-2] == ',') - msg[strlen(msg)-2] = '\0'; - else - msg[strlen(msg)-3] = '\0'; + if (strlen(msg) >= 2) { + if(msg[strlen(msg)-2] == ',') + msg[strlen(msg)-2] = '\0'; + else + msg[strlen(msg)-3] = '\0'; + } /* TODO: separate _() msg and status code: die (result, "HTTP %s: %s\n", state_text(result), msg); */ die (result, "HTTP %s: %s %d %s%s%s - %d bytes in %.3f second response time %s|%s\n%s%s", diff --git a/plugins/t/check_curl.t b/plugins/t/check_curl.t index 693f4b25..eae98cc1 100644 --- a/plugins/t/check_curl.t +++ b/plugins/t/check_curl.t @@ -1,15 +1,22 @@ #! /usr/bin/perl -w -I .. # -# HyperText Transfer Protocol (HTTP) Test via check_http +# HyperText Transfer Protocol (HTTP) Test via check_curl # # use strict; use Test::More; use POSIX qw/mktime strftime/; -use NPTest; -plan tests => 57; +use vars qw($tests $has_ipv6); + +BEGIN { + use NPTest; + $has_ipv6 = NPTest::has_ipv6(); + $tests = $has_ipv6 ? 59 : 57; + plan tests => $tests; +} + my $successOutput = '/OK.*HTTP.*second/'; @@ -18,6 +25,7 @@ my $plugin = 'check_http'; $plugin = 'check_curl' if $0 =~ m/check_curl/mx; my $host_tcp_http = getTestParameter("NP_HOST_TCP_HTTP", "A host providing the HTTP Service (a web server)", "localhost"); +my $host_tcp_http_ipv6 = getTestParameter("NP_HOST_TCP_HTTP_IPV6", "An IPv6 address providing a HTTP Service (a web server)", "::1"); my $host_tls_http = getTestParameter("NP_HOST_TLS_HTTP", "A host providing the HTTPS Service (a tls web server)", "localhost"); my $host_tls_cert = getTestParameter("NP_HOST_TLS_CERT", "the common name of the certificate.", "localhost"); my $host_nonresponsive = getTestParameter("NP_HOST_NONRESPONSIVE", "The hostname of system not responsive to network requests", "10.0.0.1"); @@ -31,26 +39,35 @@ my $faketime = -x '/usr/bin/faketime' ? 1 : 0; $res = NPTest->testCmd( - "./$plugin $host_tcp_http -wt 300 -ct 600" - ); + "./$plugin $host_tcp_http -wt 300 -ct 600" + ); cmp_ok( $res->return_code, '==', 0, "Webserver $host_tcp_http responded" ); like( $res->output, $successOutput, "Output OK" ); +if ($has_ipv6) { + # Test for IPv6 formatting + $res = NPTest->testCmd( + "./$plugin -I $host_tcp_http_ipv6 -wt 300 -ct 600" + ); + cmp_ok( $res->return_code, '==', 0, "IPv6 URL formatting is working" ); + like( $res->output, $successOutput, "Output OK" ); +} + $res = NPTest->testCmd( - "./$plugin $host_tcp_http -wt 300 -ct 600 -v -v -v -k 'bob:there' -k 'carl:frown'" - ); + "./$plugin $host_tcp_http -wt 300 -ct 600 -v -v -v -k 'bob:there' -k 'carl:frown'" + ); like( $res->output, '/bob:there\r\ncarl:frown\r\n/', "Got headers with multiple -k options" ); $res = NPTest->testCmd( - "./$plugin $host_nonresponsive -wt 1 -ct 2 -t 3" - ); + "./$plugin $host_nonresponsive -wt 1 -ct 2 -t 3" + ); cmp_ok( $res->return_code, '==', 2, "Webserver $host_nonresponsive not responding" ); # was CRITICAL only, but both check_curl and check_http print HTTP CRITICAL (puzzle?!) like( $res->output, "/HTTP CRITICAL - Invalid HTTP response received from host on port 80: cURL returned 28 - Connection timed out after/", "Output OK"); $res = NPTest->testCmd( - "./$plugin $hostname_invalid -wt 1 -ct 2" - ); + "./$plugin $hostname_invalid -wt 1 -ct 2" + ); cmp_ok( $res->return_code, '==', 2, "Webserver $hostname_invalid not valid" ); # The first part of the message comes from the OS catalogue, so cannot check this. # On Debian, it is Name or service not known, on Darwin, it is No address associated with nodename -- cgit v1.2.3-74-g34f1 From a517c62c1b536c934c92e4ac0f75b49bab927dca Mon Sep 17 00:00:00 2001 From: Aksel Sjögren Date: Tue, 29 Nov 2022 14:24:07 +0100 Subject: check_http: fix test plan MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix test plan when run with NP_INTERNET_ACCESS=no, where the correct number of steps must be skipped. Caused by a removed test in 65fc7064295ac70d1388fa4db4d4d2cddd531e24. Signed-off-by: Aksel Sjögren --- plugins/t/check_http.t | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/t/check_http.t b/plugins/t/check_http.t index 0c866229..1ca52f61 100644 --- a/plugins/t/check_http.t +++ b/plugins/t/check_http.t @@ -103,7 +103,7 @@ SKIP: { cmp_ok( $res->return_code, "==", 0, "And also when not found"); } SKIP: { - skip "No internet access", 23 if $internet_access eq "no"; + skip "No internet access", 22 if $internet_access eq "no"; $res = NPTest->testCmd( "./$plugin --ssl $host_tls_http" -- cgit v1.2.3-74-g34f1 From 28553e8d1cc56de12e4c9f7705a92f0e0e86d9d9 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 19 Dec 2022 17:15:49 +0100 Subject: Fix unknown escape sequence error output --- plugins/check_apt.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_apt.c b/plugins/check_apt.c index d7be5750..f70fec16 100644 --- a/plugins/check_apt.c +++ b/plugins/check_apt.c @@ -530,7 +530,7 @@ print_help (void) printf (" %s\n", _("this REGEXP, the plugin will return CRITICAL status. Can be specified")); printf (" %s\n", _("multiple times like above. Default is a regexp matching security")); printf (" %s\n", _("upgrades for Debian and Ubuntu:")); - printf (" \t\%s\n", SECURITY_RE); + printf (" \t%s\n", SECURITY_RE); printf (" %s\n", _("Note that the package must first match the include list before its")); printf (" %s\n", _("information is compared against the critical list.")); printf (" %s\n", "-o, --only-critical"); -- cgit v1.2.3-74-g34f1 From 0551151a578dd5da1dbf0ae2e5c5224c491bf0c9 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 19 Dec 2022 17:16:00 +0100 Subject: Remove trailing whitespaces --- plugins/check_apt.c | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) (limited to 'plugins') diff --git a/plugins/check_apt.c b/plugins/check_apt.c index f70fec16..af3563a1 100644 --- a/plugins/check_apt.c +++ b/plugins/check_apt.c @@ -1,32 +1,32 @@ /***************************************************************************** -* +* * Monitoring check_apt plugin -* +* * License: GPL * Copyright (c) 2006-2008 Monitoring Plugins Development Team -* +* * Original author: Sean Finney -* +* * Description: -* +* * This file contains the check_apt plugin -* +* * Check for available updates in apt package management systems -* -* +* +* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. -* +* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. -* +* * You should have received a copy of the GNU General Public License * along with this program. If not, see . -* +* *****************************************************************************/ const char *progname = "check_apt"; @@ -269,7 +269,7 @@ int run_upgrade(int *pkgcount, int *secpkgcount, char ***pkglist, char ***secpkg die(STATE_UNKNOWN, _("%s: Error compiling regexp: %s"), progname, rerrbuf); } } - + if(do_exclude!=NULL){ regres=regcomp(&ereg, do_exclude, REG_EXTENDED); if(regres!=0) { @@ -278,7 +278,7 @@ int run_upgrade(int *pkgcount, int *secpkgcount, char ***pkglist, char ***secpkg progname, rerrbuf); } } - + const char *crit_ptr = (do_critical != NULL) ? do_critical : SECURITY_RE; regres=regcomp(&sreg, crit_ptr, REG_EXTENDED); if(regres!=0) { @@ -295,7 +295,7 @@ int run_upgrade(int *pkgcount, int *secpkgcount, char ***pkglist, char ***secpkg /* run the upgrade */ result = np_runcmd(cmdline, &chld_out, &chld_err, 0); } - + /* apt-get upgrade only changes exit status if there is an * internal error when run in dry-run mode. therefore we will * treat such an error as UNKNOWN */ -- cgit v1.2.3-74-g34f1 From 763862a61cf5a7ba1a10f607022aac2434c79f57 Mon Sep 17 00:00:00 2001 From: Danijel Tasov Date: Wed, 21 Dec 2022 14:48:11 +0100 Subject: make check_http faster with larger files The current implementation becomes exponentially slower with growing response size. See also: https://github.com/nagios-plugins/nagios-plugins/blob/release-2.4.2/plugins/check_http.c#L1199-L1204 Test: $ mkdir web $ nohup python3 -m http.server -d web 5080 & $ perl -E 'say "0123456789" for (1..2_000_000)' >| web/file.txt $ ./check_http.orig -t 200 -v -I localhost -p 5080 -u /file.txt > test1.txt real 0m26.893s user 0m12.661s sys 0m14.221s $ time ./check_http -t 200 -v -I localhost -p 5080 -u /file.txt > test2.txt real 0m0.038s user 0m0.011s sys 0m0.027s $ diff -u test[12].txt --- test1.txt 2022-12-21 14:58:28.720260811 +0100 +++ test2.txt 2022-12-21 14:58:42.640008604 +0100 @@ -7,7 +7,7 @@ STATUS: HTTP/1.0 200 OK **** HEADER **** Server: SimpleHTTP/0.6 Python/3.9.2 -Date: Wed, 21 Dec 2022 13:58:01 GMT +Date: Wed, 21 Dec 2022 13:58:42 GMT Content-type: text/plain Content-Length: 22000000 Last-Modified: Wed, 21 Dec 2022 13:57:58 GMT @@ -2000013,4 +2000013,4 @@ 0123456789 0123456789 -HTTP OK: HTTP/1.0 200 OK - 22000191 bytes in 26.860 second response time |time=26.860182s;;;0.000000;200.000000 size=22000191B;;;0; +HTTP OK: HTTP/1.0 200 OK - 22000191 bytes in 0.016 second response time |time=0.016412s;;;0.000000;200.000000 size=22000191B;;;0; --- plugins/check_http.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index 41d47816..1835a2d0 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -1095,9 +1095,14 @@ check_http (void) *pos = ' '; } buffer[i] = '\0'; - xasprintf (&full_page_new, "%s%s", full_page, buffer); - free (full_page); + + if ((full_page_new = realloc(full_page, pagesize + i + 1)) == NULL) + die (STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate memory for full_page\n")); + + memmove(&full_page_new[pagesize], buffer, i + 1); + full_page = full_page_new; + pagesize += i; if (no_body && document_headers_done (full_page)) { -- cgit v1.2.3-74-g34f1 From 765b29f09bd3bc2a938260caa5f263343aafadb7 Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Thu, 22 Dec 2022 12:51:18 +0100 Subject: check_curl: fix checking large bodys (#1823) check_curl fails on large pages: HTTP CRITICAL - Invalid HTTP response received from host on port 5080: cURL returned 23 - Failure writing output to destination for example trying to run check_curl on the test from #1822 I guess the idea is to double the buffer size each time it is to small. But the code exponentially grows the buffer size which works well 2-3 times, but then fails. --- plugins/check_curl.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 2ad373c0..55de22fd 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -2024,9 +2024,12 @@ curlhelp_buffer_write_callback (void *buffer, size_t size, size_t nmemb, void *s curlhelp_write_curlbuf *buf = (curlhelp_write_curlbuf *)stream; while (buf->bufsize < buf->buflen + size * nmemb + 1) { - buf->bufsize *= buf->bufsize * 2; + buf->bufsize = buf->bufsize * 2; buf->buf = (char *)realloc (buf->buf, buf->bufsize); - if (buf->buf == NULL) return -1; + if (buf->buf == NULL) { + fprintf(stderr, "malloc failed (%d) %s\n", errno, strerror(errno)); + return -1; + } } memcpy (buf->buf + buf->buflen, buffer, size * nmemb); -- cgit v1.2.3-74-g34f1 From c35bf8966a593d7926470121269b08ec00883593 Mon Sep 17 00:00:00 2001 From: Wolfgang Nieder Date: Sat, 7 Jul 2018 09:12:44 +0200 Subject: add 'multiplier' to modify current value --- plugins/check_snmp.c | 84 +++++++++++++++++++++++++++++++++------------- plugins/tests/check_snmp.t | 12 +++++-- 2 files changed, 70 insertions(+), 26 deletions(-) (limited to 'plugins') diff --git a/plugins/check_snmp.c b/plugins/check_snmp.c index 2601ccd8..d407609f 100644 --- a/plugins/check_snmp.c +++ b/plugins/check_snmp.c @@ -1,31 +1,31 @@ /***************************************************************************** -* +* * Monitoring check_snmp plugin -* +* * License: GPL * Copyright (c) 1999-2007 Monitoring Plugins Development Team -* +* * Description: -* +* * This file contains the check_snmp plugin -* +* * Check status of remote machines and obtain system information via SNMP -* -* +* +* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. -* +* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. -* +* * You should have received a copy of the GNU General Public License * along with this program. If not, see . -* -* +* +* *****************************************************************************/ const char *progname = "check_snmp"; @@ -90,6 +90,7 @@ char *thisarg (char *str); char *nextarg (char *str); void print_usage (void); void print_help (void); +char *multiply (char *str); #include "regex.h" char regex_expect[MAX_INPUT_BUFFER] = ""; @@ -154,6 +155,8 @@ double *previous_value; size_t previous_size = OID_COUNT_STEP; int perf_labels = 1; char* ip_version = ""; +double multiplier = 1.0; +char *fmtstr = ""; static char *fix_snmp_range(char *th) { @@ -316,7 +319,7 @@ main (int argc, char **argv) for (i = 0; i < numcontext; i++) { command_line[10 + i] = contextargs[i]; } - + for (i = 0; i < numauthpriv; i++) { command_line[10 + numcontext + i] = authpriv[i]; } @@ -330,7 +333,7 @@ main (int argc, char **argv) for (i = 0; i < numoids; i++) { command_line[10 + numcontext + numauthpriv + 1 + i] = oids[i]; - xasprintf(&cl_hidden_auth, "%s %s", cl_hidden_auth, oids[i]); + xasprintf(&cl_hidden_auth, "%s %s", cl_hidden_auth, oids[i]); } command_line[10 + numcontext + numauthpriv + 1 + numoids] = NULL; @@ -398,15 +401,15 @@ main (int argc, char **argv) is_counter=0; /* We strip out the datatype indicator for PHBs */ if (strstr (response, "Gauge: ")) { - show = strstr (response, "Gauge: ") + 7; - } + show = multiply (strstr (response, "Gauge: ") + 7); + } else if (strstr (response, "Gauge32: ")) { - show = strstr (response, "Gauge32: ") + 9; - } + show = multiply (strstr (response, "Gauge32: ") + 9); + } else if (strstr (response, "Counter32: ")) { show = strstr (response, "Counter32: ") + 11; is_counter=1; - if(!calculate_rate) + if(!calculate_rate) strcpy(type, "c"); } else if (strstr (response, "Counter64: ")) { @@ -416,7 +419,10 @@ main (int argc, char **argv) strcpy(type, "c"); } else if (strstr (response, "INTEGER: ")) { - show = strstr (response, "INTEGER: ") + 9; + show = multiply (strstr (response, "INTEGER: ") + 9); + if (fmtstr != "") { + conv = fmtstr; + } } else if (strstr (response, "OID: ")) { show = strstr (response, "OID: ") + 5; @@ -616,7 +622,7 @@ main (int argc, char **argv) state_string=malloc(string_length); if(state_string==NULL) die(STATE_UNKNOWN, _("Cannot malloc")); - + current_length=0; for(i=0; i 2) printf("State string=%s\n",state_string); - + /* This is not strictly the same as time now, but any subtle variations will cancel out */ np_state_write_string(current_time, state_string ); if(previous_state==NULL) { @@ -698,6 +704,8 @@ process_arguments (int argc, char **argv) {"perf-oids", no_argument, 0, 'O'}, {"ipv4", no_argument, 0, '4'}, {"ipv6", no_argument, 0, '6'}, + {"multiplier", required_argument, 0, 'M'}, + {"fmtstr", required_argument, 0, 'f'}, {0, 0, 0, 0} }; @@ -715,7 +723,7 @@ process_arguments (int argc, char **argv) } while (1) { - c = getopt_long (argc, argv, "nhvVO46t:c:w:H:C:o:e:E:d:D:s:t:R:r:l:u:p:m:P:N:L:U:a:x:A:X:z:", + c = getopt_long (argc, argv, "nhvVO46t:c:w:H:C:o:e:E:d:D:s:t:R:r:l:u:p:m:P:N:L:U:a:x:A:X:M:f:z:", longopts, &option); if (c == -1 || c == EOF) @@ -953,6 +961,16 @@ process_arguments (int argc, char **argv) if(verbose>2) printf("IPv6 detected! Will pass \"udp6:\" to snmpget.\n"); break; + case 'M': + if ( strspn( optarg, "0123456789.," ) == strlen( optarg ) ) { + multiplier=strtod(optarg,NULL); + } + break; + case 'f': + if (multiplier != 1.0) { + fmtstr=optarg; + } + break; } } @@ -1022,7 +1040,7 @@ validate_arguments () contextargs[0] = strdup ("-n"); contextargs[1] = strdup (context); } - + if (seclevel == NULL) xasprintf(&seclevel, "noAuthNoPriv"); @@ -1143,6 +1161,21 @@ nextarg (char *str) +/* multiply result (values 0 < n < 1 work as divider) */ +char * +multiply (char *str) +{ + double val = strtod (str, NULL); + val *= multiplier; + if (val == (int)val) { + sprintf(str, "%.0f", val); + } else { + sprintf(str, "%f", val); + } + return str; +} + + void print_help (void) { @@ -1235,6 +1268,10 @@ print_help (void) printf (" %s\n", _("Units label(s) for output data (e.g., 'sec.').")); printf (" %s\n", "-D, --output-delimiter=STRING"); printf (" %s\n", _("Separates output on multiple OID requests")); + printf (" %s\n", "-M, --multiplier=FLOAT"); + printf (" %s\n", _("Multiplies current value, 0 < n < 1 works as divider, defaults to 1")); + printf (" %s\n", "-f, --fmtstr=STRING"); + printf (" %s\n", _("C-style format string for float values (see option -M)")); printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); printf (" %s\n", _("NOTE the final timeout value is calculated using this formula: timeout_interval * retries + 5")); @@ -1287,4 +1324,5 @@ print_usage (void) printf ("[-l label] [-u units] [-p port-number] [-d delimiter] [-D output-delimiter]\n"); printf ("[-m miblist] [-P snmp version] [-N context] [-L seclevel] [-U secname]\n"); printf ("[-a authproto] [-A authpasswd] [-x privproto] [-X privpasswd] [-4|6]\n"); + printf ("[-M multiplier [-f format]]\n"); } diff --git a/plugins/tests/check_snmp.t b/plugins/tests/check_snmp.t index 0a77fa8a..e9cc0213 100755 --- a/plugins/tests/check_snmp.t +++ b/plugins/tests/check_snmp.t @@ -9,7 +9,7 @@ use NPTest; use FindBin qw($Bin); use POSIX qw/strftime/; -my $tests = 73; +my $tests = 75; # Check that all dependent modules are available eval { require NetSNMP::OID; @@ -57,9 +57,9 @@ if ($pid) { exec("snmpd -c tests/conf/snmpd.conf -C -f -r udp:$port_snmp"); } -END { +END { foreach my $pid (@pids) { - if ($pid) { print "Killing $pid\n"; kill "INT", $pid } + if ($pid) { print "Killing $pid\n"; kill "INT", $pid } } }; @@ -268,3 +268,9 @@ like($res->output, '/SNMP WARNING - \d+ \*-4\* | iso.3.6.1.4.1.8072.3.2.67.10=\d $res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10,.1.3.6.1.4.1.8072.3.2.67.17 -w 1,2 -c 1" ); is($res->return_code, 2, "Multiple OIDs with some thresholds" ); like($res->output, '/SNMP CRITICAL - \*\d+\* \*-4\* | iso.3.6.1.4.1.8072.3.2.67.10=\d+c;1;2 iso.3.6.1.4.1.8072.3.2.67.17=-4;;/', "Multiple OIDs with thresholds output" ); + +$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.2.1.25.2.2.0 -M .125 "); +is($res->return_code, 0, "Multiply OK" ); + +$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.2.1.25.2.2.0 --multiplier=.0009765625 -f '%.3f' "); +is($res->return_code, 0, "Multiply format OK" ); -- cgit v1.2.3-74-g34f1 From def946bd9792ffff34b865449b18eea6e8f116af Mon Sep 17 00:00:00 2001 From: Robert Bohne Date: Fri, 11 Nov 2022 11:10:44 +0100 Subject: Improve tests for check_snmp & multiply option --- plugins/tests/check_snmp.t | 20 +++++++++++++++----- plugins/tests/check_snmp_agent.pl | 8 ++++---- 2 files changed, 19 insertions(+), 9 deletions(-) (limited to 'plugins') diff --git a/plugins/tests/check_snmp.t b/plugins/tests/check_snmp.t index e9cc0213..bb5b8db6 100755 --- a/plugins/tests/check_snmp.t +++ b/plugins/tests/check_snmp.t @@ -9,7 +9,7 @@ use NPTest; use FindBin qw($Bin); use POSIX qw/strftime/; -my $tests = 75; +my $tests = 81; # Check that all dependent modules are available eval { require NetSNMP::OID; @@ -269,8 +269,18 @@ $res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1 is($res->return_code, 2, "Multiple OIDs with some thresholds" ); like($res->output, '/SNMP CRITICAL - \*\d+\* \*-4\* | iso.3.6.1.4.1.8072.3.2.67.10=\d+c;1;2 iso.3.6.1.4.1.8072.3.2.67.17=-4;;/', "Multiple OIDs with thresholds output" ); -$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.2.1.25.2.2.0 -M .125 "); -is($res->return_code, 0, "Multiply OK" ); +$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.19"); +is($res->return_code, 0, "Test plain .1.3.6.1.4.1.8072.3.2.67.6 RC" ); +is($res->output,'SNMP OK - 42 | iso.3.6.1.4.1.8072.3.2.67.19=42 ', "Test plain value of .1.3.6.1.4.1.8072.3.2.67.1" ); -$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.2.1.25.2.2.0 --multiplier=.0009765625 -f '%.3f' "); -is($res->return_code, 0, "Multiply format OK" ); +$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.19 -M .1"); +is($res->return_code, 0, "Test multiply RC" ); +is($res->output,'SNMP OK - 4.200000 | iso.3.6.1.4.1.8072.3.2.67.19=4.200000 ' , "Test multiply .1 output" ); + +$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.19 --multiplier=.1 -f '%.2f' "); +is($res->return_code, 0, "Test multiply RC + format" ); +is($res->output, 'SNMP OK - 4.200000 | iso.3.6.1.4.1.8072.3.2.67.19=4.200000 ', "Test multiply .1 output + format" ); + +$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.19 --multiplier=.1 -f '%.2f' -w 1"); +is($res->return_code, 1, "Test multiply RC + format + thresholds" ); +is($res->output, 'SNMP WARNING - *4.20* | iso.3.6.1.4.1.8072.3.2.67.19=4.20;1 ', "Test multiply .1 output + format + thresholds" ); diff --git a/plugins/tests/check_snmp_agent.pl b/plugins/tests/check_snmp_agent.pl index 0e41d575..38912e98 100644 --- a/plugins/tests/check_snmp_agent.pl +++ b/plugins/tests/check_snmp_agent.pl @@ -32,11 +32,11 @@ my $multilin5 = 'And now have fun with with this: "C:\\" because we\'re not done yet!'; # Next are arrays of indexes (Type, initial value and increments) -# 0..16 <---- please update comment when adding/removing fields -my @fields = (ASN_OCTET_STR, ASN_OCTET_STR, ASN_OCTET_STR, ASN_OCTET_STR, ASN_OCTET_STR, ASN_UNSIGNED, ASN_UNSIGNED, ASN_COUNTER, ASN_COUNTER64, ASN_UNSIGNED, ASN_COUNTER, ASN_OCTET_STR, ASN_OCTET_STR, ASN_OCTET_STR, ASN_OCTET_STR, ASN_OCTET_STR, ASN_INTEGER, ASN_OCTET_STR, ASN_OCTET_STR ); -my @values = ($multiline, $multilin2, $multilin3, $multilin4, $multilin5, 4294965296, 1000, 4294965296, uint64("18446744073709351616"), int(rand(2**32)), 64000, "stringtests", "3.5", "87.4startswithnumberbutshouldbestring", '555"I said"', 'CUSTOM CHECK OK: foo is 12345', -2, '-4', '-6.6' ); +# 0..19 <---- please update comment when adding/removing fields +my @fields = (ASN_OCTET_STR, ASN_OCTET_STR, ASN_OCTET_STR, ASN_OCTET_STR, ASN_OCTET_STR, ASN_UNSIGNED, ASN_UNSIGNED, ASN_COUNTER, ASN_COUNTER64, ASN_UNSIGNED, ASN_COUNTER, ASN_OCTET_STR, ASN_OCTET_STR, ASN_OCTET_STR, ASN_OCTET_STR, ASN_OCTET_STR, ASN_INTEGER, ASN_OCTET_STR, ASN_OCTET_STR, ASN_INTEGER ); +my @values = ($multiline, $multilin2, $multilin3, $multilin4, $multilin5, 4294965296, 1000, 4294965296, uint64("18446744073709351616"), int(rand(2**32)), 64000, "stringtests", "3.5", "87.4startswithnumberbutshouldbestring", '555"I said"', 'CUSTOM CHECK OK: foo is 12345', -2, '-4', '-6.6', 42 ); # undef increments are randomized -my @incrts = (undef, undef, undef, undef, undef, 1000, -500, 1000, 100000, undef, 666, undef, undef, undef, undef, undef, -1, undef, undef ); +my @incrts = (undef, undef, undef, undef, undef, 1000, -500, 1000, 100000, undef, 666, undef, undef, undef, undef, undef, -1, undef, undef, 0 ); # Number of elements in our OID my $oidelts; -- cgit v1.2.3-74-g34f1 From 9ba8f5ed66004c102bb626e47bb36dc9d0388632 Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Thu, 22 Dec 2022 12:02:52 +0100 Subject: check_snmp: always apply format when applying multiplier --- plugins/check_snmp.c | 6 +++++- plugins/tests/check_snmp.t | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_snmp.c b/plugins/check_snmp.c index d407609f..56bad880 100644 --- a/plugins/check_snmp.c +++ b/plugins/check_snmp.c @@ -1167,10 +1167,14 @@ multiply (char *str) { double val = strtod (str, NULL); val *= multiplier; + char *conv = "%f"; + if (fmtstr != "") { + conv = fmtstr; + } if (val == (int)val) { sprintf(str, "%.0f", val); } else { - sprintf(str, "%f", val); + sprintf(str, conv, val); } return str; } diff --git a/plugins/tests/check_snmp.t b/plugins/tests/check_snmp.t index bb5b8db6..bc03ec60 100755 --- a/plugins/tests/check_snmp.t +++ b/plugins/tests/check_snmp.t @@ -279,7 +279,7 @@ is($res->output,'SNMP OK - 4.200000 | iso.3.6.1.4.1.8072.3.2.67.19=4.200000 ' , $res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.19 --multiplier=.1 -f '%.2f' "); is($res->return_code, 0, "Test multiply RC + format" ); -is($res->output, 'SNMP OK - 4.200000 | iso.3.6.1.4.1.8072.3.2.67.19=4.200000 ', "Test multiply .1 output + format" ); +is($res->output, 'SNMP OK - 4.20 | iso.3.6.1.4.1.8072.3.2.67.19=4.20 ', "Test multiply .1 output + format" ); $res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.19 --multiplier=.1 -f '%.2f' -w 1"); is($res->return_code, 1, "Test multiply RC + format + thresholds" ); -- cgit v1.2.3-74-g34f1 From 698eed58f80b9706acc0d9da166eb8eab5cd081d Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Sun, 13 Nov 2022 14:47:29 +0100 Subject: Use real booleans instead of ints --- plugins/check_http.c | 111 +++++++++++++++++++++++++-------------------------- 1 file changed, 55 insertions(+), 56 deletions(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index 1835a2d0..b1effd8d 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -57,8 +57,8 @@ enum { }; #ifdef HAVE_SSL -int check_cert = FALSE; -int continue_after_check_cert = FALSE; +bool check_cert = false; +bool continue_after_check_cert = false; int ssl_version = 0; int days_till_exp_warn, days_till_exp_crit; char *randbuff; @@ -69,7 +69,7 @@ X509 *server_cert; # define my_recv(buf, len) read(sd, buf, len) # define my_send(buf, len) send(sd, buf, len, 0) #endif /* HAVE_SSL */ -int no_body = FALSE; +bool no_body = false; int maximum_age = -1; enum { @@ -91,7 +91,7 @@ struct timeval tv_temp; #define HTTP_URL "/" #define CRLF "\r\n" -int specify_port = FALSE; +bool specify_port = false; int server_port = HTTP_PORT; int virtual_port = 0; char server_port_text[6] = ""; @@ -113,16 +113,16 @@ char *critical_thresholds = NULL; thresholds *thlds; char user_auth[MAX_INPUT_BUFFER] = ""; char proxy_auth[MAX_INPUT_BUFFER] = ""; -int display_html = FALSE; +bool display_html = false; char **http_opt_headers; int http_opt_headers_count = 0; int onredirect = STATE_OK; int followsticky = STICKY_NONE; -int use_ssl = FALSE; -int use_sni = FALSE; -int verbose = FALSE; -int show_extended_perfdata = FALSE; -int show_body = FALSE; +bool use_ssl = false; +bool use_sni = false; +bool verbose = false; +bool show_extended_perfdata = false; +bool show_body = false; int sd; int min_page_len = 0; int max_page_len = 0; @@ -136,10 +136,10 @@ char buffer[MAX_INPUT_BUFFER]; char *client_cert = NULL; char *client_privkey = NULL; -int process_arguments (int, char **); +bool process_arguments (int, char **); int check_http (void); void redir (char *pos, char *status_line); -int server_type_check(const char *type); +bool server_type_check(const char *type); int server_port_check(int ssl_flag); char *perfd_time (double microsec); char *perfd_time_connect (double microsec); @@ -169,10 +169,10 @@ main (int argc, char **argv) /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); - if (process_arguments (argc, argv) == ERROR) + if (process_arguments (argc, argv) == false) usage4 (_("Could not parse arguments")); - if (display_html == TRUE) + if (display_html == true) printf ("", use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port, server_url); @@ -196,8 +196,7 @@ test_file (char *path) } /* process command-line arguments */ -int -process_arguments (int argc, char **argv) +bool process_arguments (int argc, char **argv) { int c = 1; char *p; @@ -252,7 +251,7 @@ process_arguments (int argc, char **argv) }; if (argc < 2) - return ERROR; + return false; for (c = 1; c < argc; c++) { if (strcmp ("-to", argv[c]) == 0) @@ -308,10 +307,10 @@ process_arguments (int argc, char **argv) /* xasprintf (&http_opt_headers, "%s", optarg); */ break; case 'L': /* show html link */ - display_html = TRUE; + display_html = true; break; case 'n': /* do not show html link */ - display_html = FALSE; + display_html = false; break; case 'C': /* Check SSL cert validity */ #ifdef HAVE_SSL @@ -332,12 +331,12 @@ process_arguments (int argc, char **argv) usage2 (_("Invalid certificate expiration period"), optarg); days_till_exp_warn = atoi (optarg); } - check_cert = TRUE; + check_cert = true; goto enable_ssl; #endif case CONTINUE_AFTER_CHECK_CERT: /* don't stop after the certificate is checked */ #ifdef HAVE_SSL - continue_after_check_cert = TRUE; + continue_after_check_cert = true; break; #endif case 'J': /* use client certificate */ @@ -357,7 +356,7 @@ process_arguments (int argc, char **argv) enable_ssl: /* ssl_version initialized to 0 as a default. Only set if it's non-zero. This helps when we include multiple parameters, like -S and -C combinations */ - use_ssl = TRUE; + use_ssl = true; if (c=='S' && optarg != NULL) { int got_plus = strchr(optarg, '+') != NULL; @@ -374,7 +373,7 @@ process_arguments (int argc, char **argv) else usage4 (_("Invalid option - Valid SSL/TLS versions: 2, 3, 1, 1.1, 1.2 (with optional '+' suffix)")); } - if (specify_port == FALSE) + if (specify_port == false) server_port = HTTPS_PORT; #else /* -C -J and -K fall through to here without SSL */ @@ -382,7 +381,7 @@ process_arguments (int argc, char **argv) #endif break; case SNI_OPTION: - use_sni = TRUE; + use_sni = true; break; case MAX_REDIRS_OPTION: if (!is_intnonneg (optarg)) @@ -420,7 +419,7 @@ process_arguments (int argc, char **argv) host_name_length = strlen (host_name) - strlen (p) - 1; free (host_name); host_name = strndup (optarg, host_name_length); - if (specify_port == FALSE) + if (specify_port == false) server_port = virtual_port; } } else if ((p = strchr (host_name, ':')) != NULL @@ -430,7 +429,7 @@ process_arguments (int argc, char **argv) host_name_length = strlen (host_name) - strlen (p) - 1; free (host_name); host_name = strndup (optarg, host_name_length); - if (specify_port == FALSE) + if (specify_port == false) server_port = virtual_port; } break; @@ -446,7 +445,7 @@ process_arguments (int argc, char **argv) usage2 (_("Invalid port number"), optarg); else { server_port = atoi (optarg); - specify_port = TRUE; + specify_port = true; } break; case 'a': /* authorization info */ @@ -502,7 +501,7 @@ process_arguments (int argc, char **argv) if (errcode != 0) { (void) regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); printf (_("Could Not Compile Regular Expression: %s"), errbuf); - return ERROR; + return false; } break; case INVERT_REGEX: @@ -519,7 +518,7 @@ process_arguments (int argc, char **argv) #endif break; case 'v': /* verbose */ - verbose = TRUE; + verbose = true; break; case 'm': /* min_page_length */ { @@ -544,7 +543,7 @@ process_arguments (int argc, char **argv) break; } case 'N': /* no-body */ - no_body = TRUE; + no_body = true; break; case 'M': /* max-age */ { @@ -565,10 +564,10 @@ process_arguments (int argc, char **argv) } break; case 'E': /* show extended perfdata */ - show_extended_perfdata = TRUE; + show_extended_perfdata = true; break; case 'B': /* print body content after status line */ - show_body = TRUE; + show_body = true; break; } } @@ -605,7 +604,7 @@ process_arguments (int argc, char **argv) if (virtual_port == 0) virtual_port = server_port; - return TRUE; + return true; } @@ -945,7 +944,7 @@ check_http (void) /* @20100414, public[at]frank4dd.com, http://www.frank4dd.com/howto */ if ( server_address != NULL && strcmp(http_method, "CONNECT") == 0 - && host_name != NULL && use_ssl == TRUE) { + && host_name != NULL && use_ssl == true) { if (verbose) printf ("Entering CONNECT tunnel mode with proxy %s:%d to dst %s:%d\n", server_address, server_port, host_name, HTTPS_PORT); asprintf (&buf, "%s %s:%d HTTP/1.1\r\n%s\r\n", http_method, host_name, HTTPS_PORT, user_agent); @@ -979,7 +978,7 @@ check_http (void) } #ifdef HAVE_SSL elapsed_time_connect = (double)microsec_connect / 1.0e6; - if (use_ssl == TRUE) { + if (use_ssl == true) { gettimeofday (&tv_temp, NULL); result = np_net_ssl_init_with_hostname_version_and_cert(sd, (use_sni ? host_name : NULL), ssl_version, client_cert, client_privkey); if (verbose) printf ("SSL initialized\n"); @@ -987,9 +986,9 @@ check_http (void) die (STATE_CRITICAL, NULL); microsec_ssl = deltime (tv_temp); elapsed_time_ssl = (double)microsec_ssl / 1.0e6; - if (check_cert == TRUE) { + if (check_cert == true) { result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit); - if (continue_after_check_cert == FALSE) { + if (continue_after_check_cert == false) { if (sd) close(sd); np_net_ssl_cleanup(); return result; @@ -999,7 +998,7 @@ check_http (void) #endif /* HAVE_SSL */ if ( server_address != NULL && strcmp(http_method, "CONNECT") == 0 - && host_name != NULL && use_ssl == TRUE) + && host_name != NULL && use_ssl == true) asprintf (&buf, "%s %s %s\r\n%s\r\n", http_method_proxy, server_url, host_name ? "HTTP/1.1" : "HTTP/1.0", user_agent); else asprintf (&buf, "%s %s %s\r\n%s\r\n", http_method, server_url, host_name ? "HTTP/1.1" : "HTTP/1.0", user_agent); @@ -1027,10 +1026,10 @@ check_http (void) * 14.23). Some server applications/configurations cause trouble if the * (default) port is explicitly specified in the "Host:" header line. */ - if ((use_ssl == FALSE && virtual_port == HTTP_PORT) || - (use_ssl == TRUE && virtual_port == HTTPS_PORT) || + if ((use_ssl == false && virtual_port == HTTP_PORT) || + (use_ssl == true && virtual_port == HTTPS_PORT) || (server_address != NULL && strcmp(http_method, "CONNECT") == 0 - && host_name != NULL && use_ssl == TRUE)) + && host_name != NULL && use_ssl == true)) xasprintf (&buf, "%sHost: %s\r\n", buf, host_name); else xasprintf (&buf, "%sHost: %s:%d\r\n", buf, host_name, virtual_port); @@ -1334,7 +1333,7 @@ check_http (void) perfd_time (elapsed_time), perfd_size (page_len), perfd_time_connect (elapsed_time_connect), - use_ssl == TRUE ? perfd_time_ssl (elapsed_time_ssl) : "", + use_ssl == true ? perfd_time_ssl (elapsed_time_ssl) : "", perfd_time_headers (elapsed_time_headers), perfd_time_firstbyte (elapsed_time_firstbyte), perfd_time_transfer (elapsed_time_transfer)); @@ -1529,13 +1528,13 @@ redir (char *pos, char *status_line) } -int +bool server_type_check (const char *type) { if (strcmp (type, "https")) - return FALSE; + return false; else - return TRUE; + return true; } int @@ -1550,42 +1549,42 @@ server_port_check (int ssl_flag) char *perfd_time (double elapsed_time) { return fperfdata ("time", elapsed_time, "s", - thlds->warning?TRUE:FALSE, thlds->warning?thlds->warning->end:0, - thlds->critical?TRUE:FALSE, thlds->critical?thlds->critical->end:0, - TRUE, 0, TRUE, socket_timeout); + thlds->warning?true:false, thlds->warning?thlds->warning->end:0, + thlds->critical?true:false, thlds->critical?thlds->critical->end:0, + true, 0, true, socket_timeout); } char *perfd_time_connect (double elapsed_time_connect) { - return fperfdata ("time_connect", elapsed_time_connect, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout); + return fperfdata ("time_connect", elapsed_time_connect, "s", false, 0, false, 0, false, 0, true, socket_timeout); } char *perfd_time_ssl (double elapsed_time_ssl) { - return fperfdata ("time_ssl", elapsed_time_ssl, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout); + return fperfdata ("time_ssl", elapsed_time_ssl, "s", false, 0, false, 0, false, 0, true, socket_timeout); } char *perfd_time_headers (double elapsed_time_headers) { - return fperfdata ("time_headers", elapsed_time_headers, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout); + return fperfdata ("time_headers", elapsed_time_headers, "s", false, 0, false, 0, false, 0, true, socket_timeout); } char *perfd_time_firstbyte (double elapsed_time_firstbyte) { - return fperfdata ("time_firstbyte", elapsed_time_firstbyte, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout); + return fperfdata ("time_firstbyte", elapsed_time_firstbyte, "s", false, 0, false, 0, false, 0, true, socket_timeout); } char *perfd_time_transfer (double elapsed_time_transfer) { - return fperfdata ("time_transfer", elapsed_time_transfer, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout); + return fperfdata ("time_transfer", elapsed_time_transfer, "s", false, 0, false, 0, false, 0, true, socket_timeout); } char *perfd_size (int page_len) { return perfdata ("size", page_len, "B", - (min_page_len>0?TRUE:FALSE), min_page_len, - (min_page_len>0?TRUE:FALSE), 0, - TRUE, 0, FALSE, 0); + (min_page_len>0?true:false), min_page_len, + (min_page_len>0?true:false), 0, + true, 0, false, 0); } void -- cgit v1.2.3-74-g34f1 From 2752f910999c57092219d22635a46be8d78a60c2 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Sun, 13 Nov 2022 14:47:54 +0100 Subject: Update copyright --- plugins/check_http.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index b1effd8d..0f652ef8 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -34,7 +34,7 @@ /* splint -I. -I../../plugins -I../../lib/ -I/usr/kerberos/include/ ../../plugins/check_http.c */ const char *progname = "check_http"; -const char *copyright = "1999-2013"; +const char *copyright = "1999-2022"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v1.2.3-74-g34f1 From d2a05e0d12e93b06ef1357e6dffd2842d40e0aa8 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Sun, 13 Nov 2022 18:48:26 +0100 Subject: Document process_arguments a little bit better --- plugins/check_http.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index 0f652ef8..6c6810fe 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -195,7 +195,10 @@ test_file (char *path) usage2 (_("file does not exist or is not readable"), path); } -/* process command-line arguments */ +/* + * process command-line arguments + * returns true on succes, false otherwise + */ bool process_arguments (int argc, char **argv) { int c = 1; -- cgit v1.2.3-74-g34f1 From 2315f59835a51dc29a16c435ca5cbda7039c433a Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Sun, 13 Nov 2022 18:54:21 +0100 Subject: clang format --- plugins/check_http.c | 1685 ++++++++++++++++++++++++++------------------------ 1 file changed, 872 insertions(+), 813 deletions(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index 6c6810fe..440c8422 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -1,46 +1,47 @@ /***************************************************************************** -* -* Monitoring check_http plugin -* -* License: GPL -* Copyright (c) 1999-2013 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_http plugin -* -* This plugin tests the HTTP service on the specified host. It can test -* normal (http) and secure (https) servers, follow redirects, search for -* strings and regular expressions, check connection times, and report on -* certificate expiration times. -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ - -/* splint -I. -I../../plugins -I../../lib/ -I/usr/kerberos/include/ ../../plugins/check_http.c */ + * + * Monitoring check_http plugin + * + * License: GPL + * Copyright (c) 1999-2013 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_http plugin + * + * This plugin tests the HTTP service on the specified host. It can test + * normal (http) and secure (https) servers, follow redirects, search for + * strings and regular expressions, check connection times, and report on + * certificate expiration times. + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ + +/* splint -I. -I../../plugins -I../../lib/ -I/usr/kerberos/include/ + * ../../plugins/check_http.c */ const char *progname = "check_http"; const char *copyright = "1999-2022"; const char *email = "devel@monitoring-plugins.org"; +#include "base64.h" #include "common.h" #include "netutils.h" #include "utils.h" -#include "base64.h" #include #define STICKY_NONE 0 @@ -63,19 +64,18 @@ int ssl_version = 0; int days_till_exp_warn, days_till_exp_crit; char *randbuff; X509 *server_cert; -# define my_recv(buf, len) ((use_ssl) ? np_net_ssl_read(buf, len) : read(sd, buf, len)) -# define my_send(buf, len) ((use_ssl) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0)) +#define my_recv(buf, len) \ + ((use_ssl) ? np_net_ssl_read(buf, len) : read(sd, buf, len)) +#define my_send(buf, len) \ + ((use_ssl) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0)) #else /* ifndef HAVE_SSL */ -# define my_recv(buf, len) read(sd, buf, len) -# define my_send(buf, len) send(sd, buf, len, 0) +#define my_recv(buf, len) read(sd, buf, len) +#define my_send(buf, len) send(sd, buf, len, 0) #endif /* HAVE_SSL */ bool no_body = false; int maximum_age = -1; -enum { - REGS = 2, - MAX_RE_SIZE = 1024 -}; +enum { REGS = 2, MAX_RE_SIZE = 1024 }; #include "regex.h" regex_t preg; regmatch_t pmatch[REGS]; @@ -136,71 +136,67 @@ char buffer[MAX_INPUT_BUFFER]; char *client_cert = NULL; char *client_privkey = NULL; -bool process_arguments (int, char **); -int check_http (void); -void redir (char *pos, char *status_line); +bool process_arguments(int, char **); +int check_http(void); +void redir(char *pos, char *status_line); bool server_type_check(const char *type); int server_port_check(int ssl_flag); -char *perfd_time (double microsec); -char *perfd_time_connect (double microsec); -char *perfd_time_ssl (double microsec); -char *perfd_time_firstbyte (double microsec); -char *perfd_time_headers (double microsec); -char *perfd_time_transfer (double microsec); -char *perfd_size (int page_len); -void print_help (void); -void print_usage (void); - -int -main (int argc, char **argv) -{ +char *perfd_time(double microsec); +char *perfd_time_connect(double microsec); +char *perfd_time_ssl(double microsec); +char *perfd_time_firstbyte(double microsec); +char *perfd_time_headers(double microsec); +char *perfd_time_transfer(double microsec); +char *perfd_size(int page_len); +void print_help(void); +void print_usage(void); + +int main(int argc, char **argv) { int result = STATE_UNKNOWN; - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); - /* Set default URL. Must be malloced for subsequent realloc if --onredirect=follow */ + /* Set default URL. Must be malloced for subsequent realloc if + * --onredirect=follow */ server_url = strdup(HTTP_URL); server_url_length = strlen(server_url); - xasprintf (&user_agent, "User-Agent: check_http/v%s (monitoring-plugins %s)", + xasprintf(&user_agent, "User-Agent: check_http/v%s (monitoring-plugins %s)", NP_VERSION, VERSION); /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if (process_arguments (argc, argv) == false) - usage4 (_("Could not parse arguments")); + if (process_arguments(argc, argv) == false) + usage4(_("Could not parse arguments")); if (display_html == true) - printf ("", - use_ssl ? "https" : "http", host_name ? host_name : server_address, - server_port, server_url); + printf("", + use_ssl ? "https" : "http", host_name ? host_name : server_address, + server_port, server_url); /* initialize alarm signal handling, set socket timeout, start timer */ - (void) signal (SIGALRM, socket_timeout_alarm_handler); - (void) alarm (socket_timeout); - gettimeofday (&tv, NULL); + (void)signal(SIGALRM, socket_timeout_alarm_handler); + (void)alarm(socket_timeout); + gettimeofday(&tv, NULL); - result = check_http (); + result = check_http(); return result; } /* check whether a file exists */ -void -test_file (char *path) -{ +void test_file(char *path) { if (access(path, R_OK) == 0) return; - usage2 (_("file does not exist or is not readable"), path); + usage2(_("file does not exist or is not readable"), path); } /* * process command-line arguments * returns true on succes, false otherwise - */ -bool process_arguments (int argc, char **argv) -{ + */ +bool process_arguments(int argc, char **argv) { int c = 1; char *p; char *temp; @@ -214,83 +210,85 @@ bool process_arguments (int argc, char **argv) int option = 0; static struct option longopts[] = { - STD_LONG_OPTS, - {"link", no_argument, 0, 'L'}, - {"nohtml", no_argument, 0, 'n'}, - {"ssl", optional_argument, 0, 'S'}, - {"sni", no_argument, 0, SNI_OPTION}, - {"post", required_argument, 0, 'P'}, - {"method", required_argument, 0, 'j'}, - {"IP-address", required_argument, 0, 'I'}, - {"url", required_argument, 0, 'u'}, - {"port", required_argument, 0, 'p'}, - {"authorization", required_argument, 0, 'a'}, - {"proxy-authorization", required_argument, 0, 'b'}, - {"header-string", required_argument, 0, 'd'}, - {"string", required_argument, 0, 's'}, - {"expect", required_argument, 0, 'e'}, - {"regex", required_argument, 0, 'r'}, - {"ereg", required_argument, 0, 'r'}, - {"eregi", required_argument, 0, 'R'}, - {"linespan", no_argument, 0, 'l'}, - {"onredirect", required_argument, 0, 'f'}, - {"certificate", required_argument, 0, 'C'}, - {"client-cert", required_argument, 0, 'J'}, - {"private-key", required_argument, 0, 'K'}, - {"continue-after-certificate", no_argument, 0, CONTINUE_AFTER_CHECK_CERT}, - {"useragent", required_argument, 0, 'A'}, - {"header", required_argument, 0, 'k'}, - {"no-body", no_argument, 0, 'N'}, - {"max-age", required_argument, 0, 'M'}, - {"content-type", required_argument, 0, 'T'}, - {"pagesize", required_argument, 0, 'm'}, - {"invert-regex", no_argument, NULL, INVERT_REGEX}, - {"use-ipv4", no_argument, 0, '4'}, - {"use-ipv6", no_argument, 0, '6'}, - {"extended-perfdata", no_argument, 0, 'E'}, - {"show-body", no_argument, 0, 'B'}, - {"max-redirs", required_argument, 0, MAX_REDIRS_OPTION}, - {0, 0, 0, 0} - }; + STD_LONG_OPTS, + {"link", no_argument, 0, 'L'}, + {"nohtml", no_argument, 0, 'n'}, + {"ssl", optional_argument, 0, 'S'}, + {"sni", no_argument, 0, SNI_OPTION}, + {"post", required_argument, 0, 'P'}, + {"method", required_argument, 0, 'j'}, + {"IP-address", required_argument, 0, 'I'}, + {"url", required_argument, 0, 'u'}, + {"port", required_argument, 0, 'p'}, + {"authorization", required_argument, 0, 'a'}, + {"proxy-authorization", required_argument, 0, 'b'}, + {"header-string", required_argument, 0, 'd'}, + {"string", required_argument, 0, 's'}, + {"expect", required_argument, 0, 'e'}, + {"regex", required_argument, 0, 'r'}, + {"ereg", required_argument, 0, 'r'}, + {"eregi", required_argument, 0, 'R'}, + {"linespan", no_argument, 0, 'l'}, + {"onredirect", required_argument, 0, 'f'}, + {"certificate", required_argument, 0, 'C'}, + {"client-cert", required_argument, 0, 'J'}, + {"private-key", required_argument, 0, 'K'}, + {"continue-after-certificate", no_argument, 0, CONTINUE_AFTER_CHECK_CERT}, + {"useragent", required_argument, 0, 'A'}, + {"header", required_argument, 0, 'k'}, + {"no-body", no_argument, 0, 'N'}, + {"max-age", required_argument, 0, 'M'}, + {"content-type", required_argument, 0, 'T'}, + {"pagesize", required_argument, 0, 'm'}, + {"invert-regex", no_argument, NULL, INVERT_REGEX}, + {"use-ipv4", no_argument, 0, '4'}, + {"use-ipv6", no_argument, 0, '6'}, + {"extended-perfdata", no_argument, 0, 'E'}, + {"show-body", no_argument, 0, 'B'}, + {"max-redirs", required_argument, 0, MAX_REDIRS_OPTION}, + {0, 0, 0, 0}}; if (argc < 2) return false; for (c = 1; c < argc; c++) { - if (strcmp ("-to", argv[c]) == 0) - strcpy (argv[c], "-t"); - if (strcmp ("-hn", argv[c]) == 0) - strcpy (argv[c], "-H"); - if (strcmp ("-wt", argv[c]) == 0) - strcpy (argv[c], "-w"); - if (strcmp ("-ct", argv[c]) == 0) - strcpy (argv[c], "-c"); - if (strcmp ("-nohtml", argv[c]) == 0) - strcpy (argv[c], "-n"); + if (strcmp("-to", argv[c]) == 0) + strcpy(argv[c], "-t"); + if (strcmp("-hn", argv[c]) == 0) + strcpy(argv[c], "-H"); + if (strcmp("-wt", argv[c]) == 0) + strcpy(argv[c], "-w"); + if (strcmp("-ct", argv[c]) == 0) + strcpy(argv[c], "-c"); + if (strcmp("-nohtml", argv[c]) == 0) + strcpy(argv[c], "-n"); } while (1) { - c = getopt_long (argc, argv, "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:d:e:p:s:R:r:u:f:C:J:K:nlLS::m:M:NEB", longopts, &option); + c = getopt_long( + argc, argv, + "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:d:e:p:s:R:r:u:f:C:J:K:nlLS::m:M:NEB", + longopts, &option); if (c == -1 || c == EOF) break; switch (c) { case '?': /* usage */ - usage5 (); + usage5(); break; case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); + print_help(); + exit(STATE_UNKNOWN); break; case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); break; case 't': /* timeout period */ - if (!is_intnonneg (optarg)) - usage2 (_("Timeout interval must be a positive integer"), optarg); + if (!is_intnonneg(optarg)) + usage2(_("Timeout interval must be a positive integer"), optarg); else - socket_timeout = atoi (optarg); + socket_timeout = atoi(optarg); break; case 'c': /* critical time threshold */ critical_thresholds = optarg; @@ -299,13 +297,14 @@ bool process_arguments (int argc, char **argv) warning_thresholds = optarg; break; case 'A': /* User Agent String */ - xasprintf (&user_agent, "User-Agent: %s", optarg); + xasprintf(&user_agent, "User-Agent: %s", optarg); break; case 'k': /* Additional headers */ if (http_opt_headers_count == 0) - http_opt_headers = malloc (sizeof (char *) * (++http_opt_headers_count)); + http_opt_headers = malloc(sizeof(char *) * (++http_opt_headers_count)); else - http_opt_headers = realloc (http_opt_headers, sizeof (char *) * (++http_opt_headers_count)); + http_opt_headers = realloc(http_opt_headers, + sizeof(char *) * (++http_opt_headers_count)); http_opt_headers[http_opt_headers_count - 1] = optarg; /* xasprintf (&http_opt_headers, "%s", optarg); */ break; @@ -317,27 +316,27 @@ bool process_arguments (int argc, char **argv) break; case 'C': /* Check SSL cert validity */ #ifdef HAVE_SSL - if ((temp=strchr(optarg,','))!=NULL) { - *temp='\0'; - if (!is_intnonneg (optarg)) - usage2 (_("Invalid certificate expiration period"), optarg); + if ((temp = strchr(optarg, ',')) != NULL) { + *temp = '\0'; + if (!is_intnonneg(optarg)) + usage2(_("Invalid certificate expiration period"), optarg); days_till_exp_warn = atoi(optarg); - *temp=','; + *temp = ','; temp++; - if (!is_intnonneg (temp)) - usage2 (_("Invalid certificate expiration period"), temp); - days_till_exp_crit = atoi (temp); - } - else { - days_till_exp_crit=0; - if (!is_intnonneg (optarg)) - usage2 (_("Invalid certificate expiration period"), optarg); - days_till_exp_warn = atoi (optarg); + if (!is_intnonneg(temp)) + usage2(_("Invalid certificate expiration period"), temp); + days_till_exp_crit = atoi(temp); + } else { + days_till_exp_crit = 0; + if (!is_intnonneg(optarg)) + usage2(_("Invalid certificate expiration period"), optarg); + days_till_exp_warn = atoi(optarg); } check_cert = true; goto enable_ssl; #endif - case CONTINUE_AFTER_CHECK_CERT: /* don't stop after the certificate is checked */ + case CONTINUE_AFTER_CHECK_CERT: /* don't stop after the certificate is + checked */ #ifdef HAVE_SSL continue_after_check_cert = true; break; @@ -357,15 +356,16 @@ bool process_arguments (int argc, char **argv) case 'S': /* use SSL */ #ifdef HAVE_SSL enable_ssl: - /* ssl_version initialized to 0 as a default. Only set if it's non-zero. This helps when we include multiple - parameters, like -S and -C combinations */ + /* ssl_version initialized to 0 as a default. Only set if it's non-zero. + This helps when we include multiple parameters, like -S and -C + combinations */ use_ssl = true; - if (c=='S' && optarg != NULL) { + if (c == 'S' && optarg != NULL) { int got_plus = strchr(optarg, '+') != NULL; - if (!strncmp (optarg, "1.2", 3)) + if (!strncmp(optarg, "1.2", 3)) ssl_version = got_plus ? MP_TLSv1_2_OR_NEWER : MP_TLSv1_2; - else if (!strncmp (optarg, "1.1", 3)) + else if (!strncmp(optarg, "1.1", 3)) ssl_version = got_plus ? MP_TLSv1_1_OR_NEWER : MP_TLSv1_1; else if (optarg[0] == '1') ssl_version = got_plus ? MP_TLSv1_OR_NEWER : MP_TLSv1; @@ -374,101 +374,104 @@ bool process_arguments (int argc, char **argv) else if (optarg[0] == '2') ssl_version = got_plus ? MP_SSLv2_OR_NEWER : MP_SSLv2; else - usage4 (_("Invalid option - Valid SSL/TLS versions: 2, 3, 1, 1.1, 1.2 (with optional '+' suffix)")); + usage4(_("Invalid option - Valid SSL/TLS versions: 2, 3, 1, 1.1, 1.2 " + "(with optional '+' suffix)")); } if (specify_port == false) server_port = HTTPS_PORT; #else /* -C -J and -K fall through to here without SSL */ - usage4 (_("Invalid option - SSL is not available")); + usage4(_("Invalid option - SSL is not available")); #endif break; case SNI_OPTION: use_sni = true; break; case MAX_REDIRS_OPTION: - if (!is_intnonneg (optarg)) - usage2 (_("Invalid max_redirs count"), optarg); + if (!is_intnonneg(optarg)) + usage2(_("Invalid max_redirs count"), optarg); else { - max_depth = atoi (optarg); + max_depth = atoi(optarg); } - break; + break; case 'f': /* onredirect */ - if (!strcmp (optarg, "stickyport")) - onredirect = STATE_DEPENDENT, followsticky = STICKY_HOST|STICKY_PORT; - else if (!strcmp (optarg, "sticky")) + if (!strcmp(optarg, "stickyport")) + onredirect = STATE_DEPENDENT, followsticky = STICKY_HOST | STICKY_PORT; + else if (!strcmp(optarg, "sticky")) onredirect = STATE_DEPENDENT, followsticky = STICKY_HOST; - else if (!strcmp (optarg, "follow")) + else if (!strcmp(optarg, "follow")) onredirect = STATE_DEPENDENT, followsticky = STICKY_NONE; - else if (!strcmp (optarg, "unknown")) + else if (!strcmp(optarg, "unknown")) onredirect = STATE_UNKNOWN; - else if (!strcmp (optarg, "ok")) + else if (!strcmp(optarg, "ok")) onredirect = STATE_OK; - else if (!strcmp (optarg, "warning")) + else if (!strcmp(optarg, "warning")) onredirect = STATE_WARNING; - else if (!strcmp (optarg, "critical")) + else if (!strcmp(optarg, "critical")) onredirect = STATE_CRITICAL; - else usage2 (_("Invalid onredirect option"), optarg); + else + usage2(_("Invalid onredirect option"), optarg); if (verbose) printf(_("option f:%d \n"), onredirect); break; /* Note: H, I, and u must be malloc'd or will fail on redirects */ case 'H': /* Host Name (virtual host) */ - host_name = strdup (optarg); + host_name = strdup(optarg); if (host_name[0] == '[') { - if ((p = strstr (host_name, "]:")) != NULL) { /* [IPv6]:port */ - virtual_port = atoi (p + 2); + if ((p = strstr(host_name, "]:")) != NULL) { /* [IPv6]:port */ + virtual_port = atoi(p + 2); /* cut off the port */ - host_name_length = strlen (host_name) - strlen (p) - 1; - free (host_name); - host_name = strndup (optarg, host_name_length); - if (specify_port == false) - server_port = virtual_port; - } - } else if ((p = strchr (host_name, ':')) != NULL - && strchr (++p, ':') == NULL) { /* IPv4:port or host:port */ - virtual_port = atoi (p); - /* cut off the port */ - host_name_length = strlen (host_name) - strlen (p) - 1; - free (host_name); - host_name = strndup (optarg, host_name_length); + host_name_length = strlen(host_name) - strlen(p) - 1; + free(host_name); + host_name = strndup(optarg, host_name_length); if (specify_port == false) server_port = virtual_port; } + } else if ((p = strchr(host_name, ':')) != NULL && + strchr(++p, ':') == NULL) { /* IPv4:port or host:port */ + virtual_port = atoi(p); + /* cut off the port */ + host_name_length = strlen(host_name) - strlen(p) - 1; + free(host_name); + host_name = strndup(optarg, host_name_length); + if (specify_port == false) + server_port = virtual_port; + } break; case 'I': /* Server IP-address */ - server_address = strdup (optarg); + server_address = strdup(optarg); break; case 'u': /* URL path */ - server_url = strdup (optarg); - server_url_length = strlen (server_url); + server_url = strdup(optarg); + server_url_length = strlen(server_url); break; case 'p': /* Server port */ - if (!is_intnonneg (optarg)) - usage2 (_("Invalid port number"), optarg); + if (!is_intnonneg(optarg)) + usage2(_("Invalid port number"), optarg); else { - server_port = atoi (optarg); + server_port = atoi(optarg); specify_port = true; } break; case 'a': /* authorization info */ - strncpy (user_auth, optarg, MAX_INPUT_BUFFER - 1); + strncpy(user_auth, optarg, MAX_INPUT_BUFFER - 1); user_auth[MAX_INPUT_BUFFER - 1] = 0; break; case 'b': /* proxy-authorization info */ - strncpy (proxy_auth, optarg, MAX_INPUT_BUFFER - 1); + strncpy(proxy_auth, optarg, MAX_INPUT_BUFFER - 1); proxy_auth[MAX_INPUT_BUFFER - 1] = 0; break; - case 'P': /* HTTP POST data in URL encoded format; ignored if settings already */ - if (! http_post_data) - http_post_data = strdup (optarg); - if (! http_method) + case 'P': /* HTTP POST data in URL encoded format; ignored if settings + already */ + if (!http_post_data) + http_post_data = strdup(optarg); + if (!http_method) http_method = strdup("POST"); break; case 'j': /* Set HTTP method */ if (http_method) free(http_method); - http_method = strdup (optarg); + http_method = strdup(optarg); char *tmp; if ((tmp = strstr(http_method, ":")) > 0) { tmp[0] = '\0'; @@ -477,20 +480,20 @@ bool process_arguments (int argc, char **argv) } break; case 'd': /* string or substring */ - strncpy (header_expect, optarg, MAX_INPUT_BUFFER - 1); + strncpy(header_expect, optarg, MAX_INPUT_BUFFER - 1); header_expect[MAX_INPUT_BUFFER - 1] = 0; break; case 's': /* string or substring */ - strncpy (string_expect, optarg, MAX_INPUT_BUFFER - 1); + strncpy(string_expect, optarg, MAX_INPUT_BUFFER - 1); string_expect[MAX_INPUT_BUFFER - 1] = 0; break; case 'e': /* string or substring */ - strncpy (server_expect, optarg, MAX_INPUT_BUFFER - 1); + strncpy(server_expect, optarg, MAX_INPUT_BUFFER - 1); server_expect[MAX_INPUT_BUFFER - 1] = 0; server_expect_yn = 1; break; case 'T': /* Content-type */ - xasprintf (&http_content_type, "%s", optarg); + xasprintf(&http_content_type, "%s", optarg); break; case 'l': /* linespan */ cflags &= ~REG_NEWLINE; @@ -498,12 +501,12 @@ bool process_arguments (int argc, char **argv) case 'R': /* regex */ cflags |= REG_ICASE; case 'r': /* regex */ - strncpy (regexp, optarg, MAX_RE_SIZE - 1); + strncpy(regexp, optarg, MAX_RE_SIZE - 1); regexp[MAX_RE_SIZE - 1] = 0; - errcode = regcomp (&preg, regexp, cflags); + errcode = regcomp(&preg, regexp, cflags); if (errcode != 0) { - (void) regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); - printf (_("Could Not Compile Regular Expression: %s"), errbuf); + (void)regerror(errcode, &preg, errbuf, MAX_INPUT_BUFFER); + printf(_("Could Not Compile Regular Expression: %s"), errbuf); return false; } break; @@ -517,55 +520,53 @@ bool process_arguments (int argc, char **argv) #ifdef USE_IPV6 address_family = AF_INET6; #else - usage4 (_("IPv6 support not available")); + usage4(_("IPv6 support not available")); #endif break; case 'v': /* verbose */ verbose = true; break; case 'm': /* min_page_length */ - { + { char *tmp; if (strchr(optarg, ':') != (char *)NULL) { /* range, so get two values, min:max */ tmp = strtok(optarg, ":"); if (tmp == NULL) { printf("Bad format: try \"-m min:max\"\n"); - exit (STATE_WARNING); + exit(STATE_WARNING); } else min_page_len = atoi(tmp); tmp = strtok(NULL, ":"); if (tmp == NULL) { printf("Bad format: try \"-m min:max\"\n"); - exit (STATE_WARNING); + exit(STATE_WARNING); } else max_page_len = atoi(tmp); } else - min_page_len = atoi (optarg); + min_page_len = atoi(optarg); break; - } + } case 'N': /* no-body */ no_body = true; break; case 'M': /* max-age */ - { - int L = strlen(optarg); - if (L && optarg[L-1] == 'm') - maximum_age = atoi (optarg) * 60; - else if (L && optarg[L-1] == 'h') - maximum_age = atoi (optarg) * 60 * 60; - else if (L && optarg[L-1] == 'd') - maximum_age = atoi (optarg) * 60 * 60 * 24; - else if (L && (optarg[L-1] == 's' || - isdigit (optarg[L-1]))) - maximum_age = atoi (optarg); - else { - fprintf (stderr, "unparsable max-age: %s\n", optarg); - exit (STATE_WARNING); - } - } - break; + { + int L = strlen(optarg); + if (L && optarg[L - 1] == 'm') + maximum_age = atoi(optarg) * 60; + else if (L && optarg[L - 1] == 'h') + maximum_age = atoi(optarg) * 60 * 60; + else if (L && optarg[L - 1] == 'd') + maximum_age = atoi(optarg) * 60 * 60 * 24; + else if (L && (optarg[L - 1] == 's' || isdigit(optarg[L - 1]))) + maximum_age = atoi(optarg); + else { + fprintf(stderr, "unparsable max-age: %s\n", optarg); + exit(STATE_WARNING); + } + } break; case 'E': /* show extended perfdata */ show_extended_perfdata = true; break; @@ -578,31 +579,32 @@ bool process_arguments (int argc, char **argv) c = optind; if (server_address == NULL && c < argc) - server_address = strdup (argv[c++]); + server_address = strdup(argv[c++]); if (host_name == NULL && c < argc) - host_name = strdup (argv[c++]); + host_name = strdup(argv[c++]); if (server_address == NULL) { if (host_name == NULL) - usage4 (_("You must specify a server address or host name")); + usage4(_("You must specify a server address or host name")); else - server_address = strdup (host_name); + server_address = strdup(host_name); } set_thresholds(&thlds, warning_thresholds, critical_thresholds); - if (critical_thresholds && thlds->critical->end>(double)socket_timeout) + if (critical_thresholds && thlds->critical->end > (double)socket_timeout) socket_timeout = (int)thlds->critical->end + 1; if (http_method == NULL) - http_method = strdup ("GET"); + http_method = strdup("GET"); if (http_method_proxy == NULL) - http_method_proxy = strdup ("GET"); + http_method_proxy = strdup("GET"); if (client_cert && !client_privkey) - usage4 (_("If you use a client certificate you must also specify a private key file")); + usage4(_("If you use a client certificate you must also specify a private " + "key file")); if (virtual_port == 0) virtual_port = server_port; @@ -610,89 +612,68 @@ bool process_arguments (int argc, char **argv) return true; } - - /* Returns 1 if we're done processing the document body; 0 to keep going */ -static int -document_headers_done (char *full_page) -{ +static int document_headers_done(char *full_page) { const char *body; for (body = full_page; *body; body++) { - if (!strncmp (body, "\n\n", 2) || !strncmp (body, "\n\r\n", 3)) + if (!strncmp(body, "\n\n", 2) || !strncmp(body, "\n\r\n", 3)) break; } if (!*body) - return 0; /* haven't read end of headers yet */ + return 0; /* haven't read end of headers yet */ full_page[body - full_page] = 0; return 1; } -static time_t -parse_time_string (const char *string) -{ +static time_t parse_time_string(const char *string) { struct tm tm; time_t t; - memset (&tm, 0, sizeof(tm)); + memset(&tm, 0, sizeof(tm)); /* Like this: Tue, 25 Dec 2001 02:59:03 GMT */ - if (isupper (string[0]) && /* Tue */ - islower (string[1]) && - islower (string[2]) && - ',' == string[3] && - ' ' == string[4] && - (isdigit(string[5]) || string[5] == ' ') && /* 25 */ - isdigit (string[6]) && - ' ' == string[7] && - isupper (string[8]) && /* Dec */ - islower (string[9]) && - islower (string[10]) && - ' ' == string[11] && - isdigit (string[12]) && /* 2001 */ - isdigit (string[13]) && - isdigit (string[14]) && - isdigit (string[15]) && - ' ' == string[16] && - isdigit (string[17]) && /* 02: */ - isdigit (string[18]) && - ':' == string[19] && - isdigit (string[20]) && /* 59: */ - isdigit (string[21]) && - ':' == string[22] && - isdigit (string[23]) && /* 03 */ - isdigit (string[24]) && - ' ' == string[25] && - 'G' == string[26] && /* GMT */ - 'M' == string[27] && /* GMT */ - 'T' == string[28]) { - - tm.tm_sec = 10 * (string[23]-'0') + (string[24]-'0'); - tm.tm_min = 10 * (string[20]-'0') + (string[21]-'0'); - tm.tm_hour = 10 * (string[17]-'0') + (string[18]-'0'); - tm.tm_mday = 10 * (string[5] == ' ' ? 0 : string[5]-'0') + (string[6]-'0'); - tm.tm_mon = (!strncmp (string+8, "Jan", 3) ? 0 : - !strncmp (string+8, "Feb", 3) ? 1 : - !strncmp (string+8, "Mar", 3) ? 2 : - !strncmp (string+8, "Apr", 3) ? 3 : - !strncmp (string+8, "May", 3) ? 4 : - !strncmp (string+8, "Jun", 3) ? 5 : - !strncmp (string+8, "Jul", 3) ? 6 : - !strncmp (string+8, "Aug", 3) ? 7 : - !strncmp (string+8, "Sep", 3) ? 8 : - !strncmp (string+8, "Oct", 3) ? 9 : - !strncmp (string+8, "Nov", 3) ? 10 : - !strncmp (string+8, "Dec", 3) ? 11 : - -1); - tm.tm_year = ((1000 * (string[12]-'0') + - 100 * (string[13]-'0') + - 10 * (string[14]-'0') + - (string[15]-'0')) - - 1900); - - tm.tm_isdst = 0; /* GMT is never in DST, right? */ + if (isupper(string[0]) && /* Tue */ + islower(string[1]) && islower(string[2]) && ',' == string[3] && + ' ' == string[4] && (isdigit(string[5]) || string[5] == ' ') && /* 25 */ + isdigit(string[6]) && ' ' == string[7] && isupper(string[8]) && /* Dec */ + islower(string[9]) && islower(string[10]) && ' ' == string[11] && + isdigit(string[12]) && /* 2001 */ + isdigit(string[13]) && isdigit(string[14]) && isdigit(string[15]) && + ' ' == string[16] && isdigit(string[17]) && /* 02: */ + isdigit(string[18]) && ':' == string[19] && + isdigit(string[20]) && /* 59: */ + isdigit(string[21]) && ':' == string[22] && + isdigit(string[23]) && /* 03 */ + isdigit(string[24]) && ' ' == string[25] && 'G' == string[26] && /* GMT */ + 'M' == string[27] && /* GMT */ + 'T' == string[28]) { + + tm.tm_sec = 10 * (string[23] - '0') + (string[24] - '0'); + tm.tm_min = 10 * (string[20] - '0') + (string[21] - '0'); + tm.tm_hour = 10 * (string[17] - '0') + (string[18] - '0'); + tm.tm_mday = + 10 * (string[5] == ' ' ? 0 : string[5] - '0') + (string[6] - '0'); + tm.tm_mon = (!strncmp(string + 8, "Jan", 3) ? 0 + : !strncmp(string + 8, "Feb", 3) ? 1 + : !strncmp(string + 8, "Mar", 3) ? 2 + : !strncmp(string + 8, "Apr", 3) ? 3 + : !strncmp(string + 8, "May", 3) ? 4 + : !strncmp(string + 8, "Jun", 3) ? 5 + : !strncmp(string + 8, "Jul", 3) ? 6 + : !strncmp(string + 8, "Aug", 3) ? 7 + : !strncmp(string + 8, "Sep", 3) ? 8 + : !strncmp(string + 8, "Oct", 3) ? 9 + : !strncmp(string + 8, "Nov", 3) ? 10 + : !strncmp(string + 8, "Dec", 3) ? 11 + : -1); + tm.tm_year = ((1000 * (string[12] - '0') + 100 * (string[13] - '0') + + 10 * (string[14] - '0') + (string[15] - '0')) - + 1900); + + tm.tm_isdst = 0; /* GMT is never in DST, right? */ if (tm.tm_mon < 0 || tm.tm_mday < 1 || tm.tm_mday > 31) return 0; @@ -704,14 +685,15 @@ parse_time_string (const char *string) so it doesn't matter what time zone we parse them in. */ - t = mktime (&tm); - if (t == (time_t) -1) t = 0; + t = mktime(&tm); + if (t == (time_t)-1) + t = 0; if (verbose) { const char *s = string; while (*s && *s != '\r' && *s != '\n') - fputc (*s++, stdout); - printf (" ==> %lu\n", (unsigned long) t); + fputc(*s++, stdout); + printf(" ==> %lu\n", (unsigned long)t); } return t; @@ -722,28 +704,24 @@ parse_time_string (const char *string) } /* Checks if the server 'reply' is one of the expected 'statuscodes' */ -static int -expected_statuscode (const char *reply, const char *statuscodes) -{ +static int expected_statuscode(const char *reply, const char *statuscodes) { char *expected, *code; int result = 0; - if ((expected = strdup (statuscodes)) == NULL) - die (STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n")); + if ((expected = strdup(statuscodes)) == NULL) + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n")); - for (code = strtok (expected, ","); code != NULL; code = strtok (NULL, ",")) - if (strstr (reply, code) != NULL) { + for (code = strtok(expected, ","); code != NULL; code = strtok(NULL, ",")) + if (strstr(reply, code) != NULL) { result = 1; break; } - free (expected); + free(expected); return result; } -static int -check_document_dates (const char *headers, char **msg) -{ +static int check_document_dates(const char *headers, char **msg) { const char *s; char *server_date = 0; char *document_date = 0; @@ -771,73 +749,78 @@ check_document_dates (const char *headers, char **msg) s++; /* Process this header. */ - if (value && value > field+2) { - char *ff = (char *) malloc (value-field); + if (value && value > field + 2) { + char *ff = (char *)malloc(value - field); char *ss = ff; - while (field < value-1) + while (field < value - 1) *ss++ = tolower(*field++); *ss++ = 0; - if (!strcmp (ff, "date") || !strcmp (ff, "last-modified")) { + if (!strcmp(ff, "date") || !strcmp(ff, "last-modified")) { const char *e; - while (*value && isspace (*value)) + while (*value && isspace(*value)) value++; for (e = value; *e && *e != '\r' && *e != '\n'; e++) ; - ss = (char *) malloc (e - value + 1); - strncpy (ss, value, e - value); + ss = (char *)malloc(e - value + 1); + strncpy(ss, value, e - value); ss[e - value] = 0; - if (!strcmp (ff, "date")) { - if (server_date) free (server_date); + if (!strcmp(ff, "date")) { + if (server_date) + free(server_date); server_date = ss; } else { - if (document_date) free (document_date); + if (document_date) + free(document_date); document_date = ss; } } - free (ff); + free(ff); } } /* Done parsing the body. Now check the dates we (hopefully) parsed. */ if (!server_date || !*server_date) { - xasprintf (msg, _("%sServer date unknown, "), *msg); + xasprintf(msg, _("%sServer date unknown, "), *msg); date_result = max_state_alt(STATE_UNKNOWN, date_result); } else if (!document_date || !*document_date) { - xasprintf (msg, _("%sDocument modification date unknown, "), *msg); + xasprintf(msg, _("%sDocument modification date unknown, "), *msg); date_result = max_state_alt(STATE_CRITICAL, date_result); } else { - time_t srv_data = parse_time_string (server_date); - time_t doc_data = parse_time_string (document_date); + time_t srv_data = parse_time_string(server_date); + time_t doc_data = parse_time_string(document_date); if (srv_data <= 0) { - xasprintf (msg, _("%sServer date \"%100s\" unparsable, "), *msg, server_date); + xasprintf(msg, _("%sServer date \"%100s\" unparsable, "), *msg, + server_date); date_result = max_state_alt(STATE_CRITICAL, date_result); } else if (doc_data <= 0) { - xasprintf (msg, _("%sDocument date \"%100s\" unparsable, "), *msg, document_date); + xasprintf(msg, _("%sDocument date \"%100s\" unparsable, "), *msg, + document_date); date_result = max_state_alt(STATE_CRITICAL, date_result); } else if (doc_data > srv_data + 30) { - xasprintf (msg, _("%sDocument is %d seconds in the future, "), *msg, (int)doc_data - (int)srv_data); + xasprintf(msg, _("%sDocument is %d seconds in the future, "), *msg, + (int)doc_data - (int)srv_data); date_result = max_state_alt(STATE_CRITICAL, date_result); } else if (doc_data < srv_data - maximum_age) { int n = (srv_data - doc_data); if (n > (60 * 60 * 24 * 2)) { - xasprintf (msg, _("%sLast modified %.1f days ago, "), *msg, ((float) n) / (60 * 60 * 24)); + xasprintf(msg, _("%sLast modified %.1f days ago, "), *msg, + ((float)n) / (60 * 60 * 24)); date_result = max_state_alt(STATE_CRITICAL, date_result); } else { - xasprintf (msg, _("%sLast modified %d:%02d:%02d ago, "), *msg, n / (60 * 60), (n / 60) % 60, n % 60); + xasprintf(msg, _("%sLast modified %d:%02d:%02d ago, "), *msg, + n / (60 * 60), (n / 60) % 60, n % 60); date_result = max_state_alt(STATE_CRITICAL, date_result); } } - free (server_date); - free (document_date); + free(server_date); + free(document_date); } return date_result; } -int -get_content_length (const char *headers) -{ +int get_content_length(const char *headers) { const char *s; int content_length = 0; @@ -863,50 +846,46 @@ get_content_length (const char *headers) s++; /* Process this header. */ - if (value && value > field+2) { - char *ff = (char *) malloc (value-field); + if (value && value > field + 2) { + char *ff = (char *)malloc(value - field); char *ss = ff; - while (field < value-1) + while (field < value - 1) *ss++ = tolower(*field++); *ss++ = 0; - if (!strcmp (ff, "content-length")) { + if (!strcmp(ff, "content-length")) { const char *e; - while (*value && isspace (*value)) + while (*value && isspace(*value)) value++; for (e = value; *e && *e != '\r' && *e != '\n'; e++) ; - ss = (char *) malloc (e - value + 1); - strncpy (ss, value, e - value); + ss = (char *)malloc(e - value + 1); + strncpy(ss, value, e - value); ss[e - value] = 0; content_length = atoi(ss); - free (ss); + free(ss); } - free (ff); + free(ff); } } return (content_length); } -char * -prepend_slash (char *path) -{ +char *prepend_slash(char *path) { char *newpath; if (path[0] == '/') return path; - if ((newpath = malloc (strlen(path) + 2)) == NULL) - die (STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n")); + if ((newpath = malloc(strlen(path) + 2)) == NULL) + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n")); newpath[0] = '/'; - strcpy (newpath + 1, path); - free (path); + strcpy(newpath + 1, path); + free(path); return newpath; } -int -check_http (void) -{ +int check_http(void) { char *msg; char *status_line; char *status_code; @@ -937,62 +916,73 @@ check_http (void) char *force_host_header = NULL; /* try to connect to the host at the given port number */ - gettimeofday (&tv_temp, NULL); - if (my_tcp_connect (server_address, server_port, &sd) != STATE_OK) - die (STATE_CRITICAL, _("HTTP CRITICAL - Unable to open TCP socket\n")); - microsec_connect = deltime (tv_temp); + gettimeofday(&tv_temp, NULL); + if (my_tcp_connect(server_address, server_port, &sd) != STATE_OK) + die(STATE_CRITICAL, _("HTTP CRITICAL - Unable to open TCP socket\n")); + microsec_connect = deltime(tv_temp); - /* if we are called with the -I option, the -j method is CONNECT and */ - /* we received -S for SSL, then we tunnel the request through a proxy*/ - /* @20100414, public[at]frank4dd.com, http://www.frank4dd.com/howto */ + /* if we are called with the -I option, the -j method is CONNECT and */ + /* we received -S for SSL, then we tunnel the request through a proxy*/ + /* @20100414, public[at]frank4dd.com, http://www.frank4dd.com/howto */ - if ( server_address != NULL && strcmp(http_method, "CONNECT") == 0 - && host_name != NULL && use_ssl == true) { + if (server_address != NULL && strcmp(http_method, "CONNECT") == 0 && + host_name != NULL && use_ssl == true) { - if (verbose) printf ("Entering CONNECT tunnel mode with proxy %s:%d to dst %s:%d\n", server_address, server_port, host_name, HTTPS_PORT); - asprintf (&buf, "%s %s:%d HTTP/1.1\r\n%s\r\n", http_method, host_name, HTTPS_PORT, user_agent); + if (verbose) + printf("Entering CONNECT tunnel mode with proxy %s:%d to dst %s:%d\n", + server_address, server_port, host_name, HTTPS_PORT); + asprintf(&buf, "%s %s:%d HTTP/1.1\r\n%s\r\n", http_method, host_name, + HTTPS_PORT, user_agent); if (strlen(proxy_auth)) { - base64_encode_alloc (proxy_auth, strlen (proxy_auth), &auth); - xasprintf (&buf, "%sProxy-Authorization: Basic %s\r\n", buf, auth); + base64_encode_alloc(proxy_auth, strlen(proxy_auth), &auth); + xasprintf(&buf, "%sProxy-Authorization: Basic %s\r\n", buf, auth); } /* optionally send any other header tag */ if (http_opt_headers_count) { - for (i = 0; i < http_opt_headers_count ; i++) { + for (i = 0; i < http_opt_headers_count; i++) { if (force_host_header != http_opt_headers[i]) { - xasprintf (&buf, "%s%s\r\n", buf, http_opt_headers[i]); + xasprintf(&buf, "%s%s\r\n", buf, http_opt_headers[i]); } } - /* This cannot be free'd here because a redirection will then try to access this and segfault */ + /* This cannot be free'd here because a redirection will then try to + * access this and segfault */ /* Covered in a testcase in tests/check_http.t */ /* free(http_opt_headers); */ } - asprintf (&buf, "%sProxy-Connection: keep-alive\r\n", buf); - asprintf (&buf, "%sHost: %s\r\n", buf, host_name); + asprintf(&buf, "%sProxy-Connection: keep-alive\r\n", buf); + asprintf(&buf, "%sHost: %s\r\n", buf, host_name); /* we finished our request, send empty line with CRLF */ - asprintf (&buf, "%s%s", buf, CRLF); - if (verbose) printf ("%s\n", buf); - send(sd, buf, strlen (buf), 0); - buf[0]='\0'; - - if (verbose) printf ("Receive response from proxy\n"); - read (sd, buffer, MAX_INPUT_BUFFER-1); - if (verbose) printf ("%s", buffer); + asprintf(&buf, "%s%s", buf, CRLF); + if (verbose) + printf("%s\n", buf); + send(sd, buf, strlen(buf), 0); + buf[0] = '\0'; + + if (verbose) + printf("Receive response from proxy\n"); + read(sd, buffer, MAX_INPUT_BUFFER - 1); + if (verbose) + printf("%s", buffer); /* Here we should check if we got HTTP/1.1 200 Connection established */ } #ifdef HAVE_SSL elapsed_time_connect = (double)microsec_connect / 1.0e6; if (use_ssl == true) { - gettimeofday (&tv_temp, NULL); - result = np_net_ssl_init_with_hostname_version_and_cert(sd, (use_sni ? host_name : NULL), ssl_version, client_cert, client_privkey); - if (verbose) printf ("SSL initialized\n"); + gettimeofday(&tv_temp, NULL); + result = np_net_ssl_init_with_hostname_version_and_cert( + sd, (use_sni ? host_name : NULL), ssl_version, client_cert, + client_privkey); + if (verbose) + printf("SSL initialized\n"); if (result != STATE_OK) - die (STATE_CRITICAL, NULL); - microsec_ssl = deltime (tv_temp); + die(STATE_CRITICAL, NULL); + microsec_ssl = deltime(tv_temp); elapsed_time_ssl = (double)microsec_ssl / 1.0e6; if (check_cert == true) { result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit); if (continue_after_check_cert == false) { - if (sd) close(sd); + if (sd) + close(sd); np_net_ssl_cleanup(); return result; } @@ -1000,18 +990,20 @@ check_http (void) } #endif /* HAVE_SSL */ - if ( server_address != NULL && strcmp(http_method, "CONNECT") == 0 - && host_name != NULL && use_ssl == true) - asprintf (&buf, "%s %s %s\r\n%s\r\n", http_method_proxy, server_url, host_name ? "HTTP/1.1" : "HTTP/1.0", user_agent); + if (server_address != NULL && strcmp(http_method, "CONNECT") == 0 && + host_name != NULL && use_ssl == true) + asprintf(&buf, "%s %s %s\r\n%s\r\n", http_method_proxy, server_url, + host_name ? "HTTP/1.1" : "HTTP/1.0", user_agent); else - asprintf (&buf, "%s %s %s\r\n%s\r\n", http_method, server_url, host_name ? "HTTP/1.1" : "HTTP/1.0", user_agent); + asprintf(&buf, "%s %s %s\r\n%s\r\n", http_method, server_url, + host_name ? "HTTP/1.1" : "HTTP/1.0", user_agent); /* tell HTTP/1.1 servers not to keep the connection alive */ - xasprintf (&buf, "%sConnection: close\r\n", buf); + xasprintf(&buf, "%sConnection: close\r\n", buf); /* check if Host header is explicitly set in options */ if (http_opt_headers_count) { - for (i = 0; i < http_opt_headers_count ; i++) { + for (i = 0; i < http_opt_headers_count; i++) { if (strncmp(http_opt_headers[i], "Host:", 5) == 0) { force_host_header = http_opt_headers[i]; } @@ -1021,9 +1013,8 @@ check_http (void) /* optionally send the host header info */ if (host_name) { if (force_host_header) { - xasprintf (&buf, "%s%s\r\n", buf, force_host_header); - } - else { + xasprintf(&buf, "%s%s\r\n", buf, force_host_header); + } else { /* * Specify the port only if we're using a non-default port (see RFC 2616, * 14.23). Some server applications/configurations cause trouble if the @@ -1031,65 +1022,69 @@ check_http (void) */ if ((use_ssl == false && virtual_port == HTTP_PORT) || (use_ssl == true && virtual_port == HTTPS_PORT) || - (server_address != NULL && strcmp(http_method, "CONNECT") == 0 - && host_name != NULL && use_ssl == true)) - xasprintf (&buf, "%sHost: %s\r\n", buf, host_name); + (server_address != NULL && strcmp(http_method, "CONNECT") == 0 && + host_name != NULL && use_ssl == true)) + xasprintf(&buf, "%sHost: %s\r\n", buf, host_name); else - xasprintf (&buf, "%sHost: %s:%d\r\n", buf, host_name, virtual_port); + xasprintf(&buf, "%sHost: %s:%d\r\n", buf, host_name, virtual_port); } } /* optionally send any other header tag */ if (http_opt_headers_count) { - for (i = 0; i < http_opt_headers_count ; i++) { + for (i = 0; i < http_opt_headers_count; i++) { if (force_host_header != http_opt_headers[i]) { - xasprintf (&buf, "%s%s\r\n", buf, http_opt_headers[i]); + xasprintf(&buf, "%s%s\r\n", buf, http_opt_headers[i]); } } - /* This cannot be free'd here because a redirection will then try to access this and segfault */ + /* This cannot be free'd here because a redirection will then try to access + * this and segfault */ /* Covered in a testcase in tests/check_http.t */ /* free(http_opt_headers); */ } /* optionally send the authentication info */ if (strlen(user_auth)) { - base64_encode_alloc (user_auth, strlen (user_auth), &auth); - xasprintf (&buf, "%sAuthorization: Basic %s\r\n", buf, auth); + base64_encode_alloc(user_auth, strlen(user_auth), &auth); + xasprintf(&buf, "%sAuthorization: Basic %s\r\n", buf, auth); } /* optionally send the proxy authentication info */ if (strlen(proxy_auth)) { - base64_encode_alloc (proxy_auth, strlen (proxy_auth), &auth); - xasprintf (&buf, "%sProxy-Authorization: Basic %s\r\n", buf, auth); + base64_encode_alloc(proxy_auth, strlen(proxy_auth), &auth); + xasprintf(&buf, "%sProxy-Authorization: Basic %s\r\n", buf, auth); } /* either send http POST data (any data, not only POST)*/ if (http_post_data) { if (http_content_type) { - xasprintf (&buf, "%sContent-Type: %s\r\n", buf, http_content_type); + xasprintf(&buf, "%sContent-Type: %s\r\n", buf, http_content_type); } else { - xasprintf (&buf, "%sContent-Type: application/x-www-form-urlencoded\r\n", buf); + xasprintf(&buf, "%sContent-Type: application/x-www-form-urlencoded\r\n", + buf); } - xasprintf (&buf, "%sContent-Length: %i\r\n\r\n", buf, (int)strlen (http_post_data)); - xasprintf (&buf, "%s%s", buf, http_post_data); + xasprintf(&buf, "%sContent-Length: %i\r\n\r\n", buf, + (int)strlen(http_post_data)); + xasprintf(&buf, "%s%s", buf, http_post_data); } else { /* or just a newline so the server knows we're done with the request */ - xasprintf (&buf, "%s%s", buf, CRLF); + xasprintf(&buf, "%s%s", buf, CRLF); } - if (verbose) printf ("%s\n", buf); - gettimeofday (&tv_temp, NULL); - my_send (buf, strlen (buf)); - microsec_headers = deltime (tv_temp); + if (verbose) + printf("%s\n", buf); + gettimeofday(&tv_temp, NULL); + my_send(buf, strlen(buf)); + microsec_headers = deltime(tv_temp); elapsed_time_headers = (double)microsec_headers / 1.0e6; /* fetch the page */ full_page = strdup(""); - gettimeofday (&tv_temp, NULL); - while ((i = my_recv (buffer, MAX_INPUT_BUFFER-1)) > 0) { + gettimeofday(&tv_temp, NULL); + while ((i = my_recv(buffer, MAX_INPUT_BUFFER - 1)) > 0) { if ((i >= 1) && (elapsed_time_firstbyte <= 0.000001)) { - microsec_firstbyte = deltime (tv_temp); + microsec_firstbyte = deltime(tv_temp); elapsed_time_firstbyte = (double)microsec_firstbyte / 1.0e6; } while (pos = memchr(buffer, '\0', i)) { @@ -1107,12 +1102,12 @@ check_http (void) pagesize += i; - if (no_body && document_headers_done (full_page)) { - i = 0; - break; - } + if (no_body && document_headers_done(full_page)) { + i = 0; + break; + } } - microsec_transfer = deltime (tv_temp); + microsec_transfer = deltime(tv_temp); elapsed_time_transfer = (double)microsec_transfer / 1.0e6; if (i < 0 && errno != ECONNRESET) { @@ -1129,176 +1124,187 @@ check_http (void) else { */ #endif - die (STATE_CRITICAL, _("HTTP CRITICAL - Error on receive\n")); + die(STATE_CRITICAL, _("HTTP CRITICAL - Error on receive\n")); #ifdef HAVE_SSL - /* XXX - } - */ + /* XXX + } + */ #endif } /* return a CRITICAL status if we couldn't read any data */ - if (pagesize == (size_t) 0) - die (STATE_CRITICAL, _("HTTP CRITICAL - No data received from host\n")); + if (pagesize == (size_t)0) + die(STATE_CRITICAL, _("HTTP CRITICAL - No data received from host\n")); /* close the connection */ - if (sd) close(sd); + if (sd) + close(sd); #ifdef HAVE_SSL np_net_ssl_cleanup(); #endif /* Save check time */ - microsec = deltime (tv); + microsec = deltime(tv); elapsed_time = (double)microsec / 1.0e6; /* leave full_page untouched so we can free it later */ page = full_page; if (verbose) - printf ("%s://%s:%d%s is %d characters\n", - use_ssl ? "https" : "http", server_address, - server_port, server_url, (int)pagesize); + printf("%s://%s:%d%s is %d characters\n", use_ssl ? "https" : "http", + server_address, server_port, server_url, (int)pagesize); /* find status line and null-terminate it */ status_line = page; - page += (size_t) strcspn (page, "\r\n"); + page += (size_t)strcspn(page, "\r\n"); pos = page; - page += (size_t) strspn (page, "\r\n"); + page += (size_t)strspn(page, "\r\n"); status_line[strcspn(status_line, "\r\n")] = 0; - strip (status_line); + strip(status_line); if (verbose) - printf ("STATUS: %s\n", status_line); + printf("STATUS: %s\n", status_line); /* find header info and null-terminate it */ header = page; - while (strcspn (page, "\r\n") > 0) { - page += (size_t) strcspn (page, "\r\n"); + while (strcspn(page, "\r\n") > 0) { + page += (size_t)strcspn(page, "\r\n"); pos = page; - if ((strspn (page, "\r") == 1 && strspn (page, "\r\n") >= 2) || - (strspn (page, "\n") == 1 && strspn (page, "\r\n") >= 2)) - page += (size_t) 2; + if ((strspn(page, "\r") == 1 && strspn(page, "\r\n") >= 2) || + (strspn(page, "\n") == 1 && strspn(page, "\r\n") >= 2)) + page += (size_t)2; else - page += (size_t) 1; + page += (size_t)1; } - page += (size_t) strspn (page, "\r\n"); + page += (size_t)strspn(page, "\r\n"); header[pos - header] = 0; if (verbose) - printf ("**** HEADER ****\n%s\n**** CONTENT ****\n%s\n", header, - (no_body ? " [[ skipped ]]" : page)); + printf("**** HEADER ****\n%s\n**** CONTENT ****\n%s\n", header, + (no_body ? " [[ skipped ]]" : page)); /* make sure the status line matches the response we are looking for */ - if (!expected_statuscode (status_line, server_expect)) { + if (!expected_statuscode(status_line, server_expect)) { if (server_port == HTTP_PORT) - xasprintf (&msg, - _("Invalid HTTP response received from host: %s\n"), + xasprintf(&msg, _("Invalid HTTP response received from host: %s\n"), status_line); else - xasprintf (&msg, + xasprintf(&msg, _("Invalid HTTP response received from host on port %d: %s\n"), server_port, status_line); if (show_body) - xasprintf (&msg, _("%s\n%s"), msg, page); - die (STATE_CRITICAL, "HTTP CRITICAL - %s", msg); + xasprintf(&msg, _("%s\n%s"), msg, page); + die(STATE_CRITICAL, "HTTP CRITICAL - %s", msg); } - /* Bypass normal status line check if server_expect was set by user and not default */ - /* NOTE: After this if/else block msg *MUST* be an asprintf-allocated string */ - if ( server_expect_yn ) { - xasprintf (&msg, - _("Status line output matched \"%s\" - "), server_expect); + /* Bypass normal status line check if server_expect was set by user and not + * default */ + /* NOTE: After this if/else block msg *MUST* be an asprintf-allocated string + */ + if (server_expect_yn) { + xasprintf(&msg, _("Status line output matched \"%s\" - "), server_expect); if (verbose) - printf ("%s\n",msg); - } - else { + printf("%s\n", msg); + } else { /* Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF */ /* HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT */ /* Status-Code = 3 DIGITS */ - status_code = strchr (status_line, ' ') + sizeof (char); - if (strspn (status_code, "1234567890") != 3) - die (STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status Line (%s)\n"), status_line); + status_code = strchr(status_line, ' ') + sizeof(char); + if (strspn(status_code, "1234567890") != 3) + die(STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status Line (%s)\n"), + status_line); - http_status = atoi (status_code); + http_status = atoi(status_code); /* check the return code */ if (http_status >= 600 || http_status < 100) { - die (STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status (%s)\n"), status_line); + die(STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status (%s)\n"), + status_line); } /* server errors result in a critical state */ else if (http_status >= 500) { - xasprintf (&msg, _("%s - "), status_line); + xasprintf(&msg, _("%s - "), status_line); result = STATE_CRITICAL; } /* client errors result in a warning state */ else if (http_status >= 400) { - xasprintf (&msg, _("%s - "), status_line); + xasprintf(&msg, _("%s - "), status_line); result = max_state_alt(STATE_WARNING, result); } /* check redirected page if specified */ else if (http_status >= 300) { if (onredirect == STATE_DEPENDENT) - redir (header, status_line); + redir(header, status_line); else result = max_state_alt(onredirect, result); - xasprintf (&msg, _("%s - "), status_line); + xasprintf(&msg, _("%s - "), status_line); } /* end if (http_status >= 300) */ else { /* Print OK status anyway */ - xasprintf (&msg, _("%s - "), status_line); + xasprintf(&msg, _("%s - "), status_line); } } /* end else (server_expect_yn) */ - /* reset the alarm - must be called *after* redir or we'll never die on redirects! */ - alarm (0); + /* reset the alarm - must be called *after* redir or we'll never die on + * redirects! */ + alarm(0); if (maximum_age >= 0) { result = max_state_alt(check_document_dates(header, &msg), result); } /* Page and Header content checks go here */ - if (strlen (header_expect)) { - if (!strstr (header, header_expect)) { - strncpy(&output_header_search[0],header_expect,sizeof(output_header_search)); - if(output_header_search[sizeof(output_header_search)-1]!='\0') { - bcopy("...",&output_header_search[sizeof(output_header_search)-4],4); + if (strlen(header_expect)) { + if (!strstr(header, header_expect)) { + strncpy(&output_header_search[0], header_expect, + sizeof(output_header_search)); + if (output_header_search[sizeof(output_header_search) - 1] != '\0') { + bcopy("...", &output_header_search[sizeof(output_header_search) - 4], + 4); } - xasprintf (&msg, _("%sheader '%s' not found on '%s://%s:%d%s', "), msg, output_header_search, use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port, server_url); + xasprintf(&msg, _("%sheader '%s' not found on '%s://%s:%d%s', "), msg, + output_header_search, use_ssl ? "https" : "http", + host_name ? host_name : server_address, server_port, + server_url); result = STATE_CRITICAL; } } - - if (strlen (string_expect)) { - if (!strstr (page, string_expect)) { - strncpy(&output_string_search[0],string_expect,sizeof(output_string_search)); - if(output_string_search[sizeof(output_string_search)-1]!='\0') { - bcopy("...",&output_string_search[sizeof(output_string_search)-4],4); + if (strlen(string_expect)) { + if (!strstr(page, string_expect)) { + strncpy(&output_string_search[0], string_expect, + sizeof(output_string_search)); + if (output_string_search[sizeof(output_string_search) - 1] != '\0') { + bcopy("...", &output_string_search[sizeof(output_string_search) - 4], + 4); } - xasprintf (&msg, _("%sstring '%s' not found on '%s://%s:%d%s', "), msg, output_string_search, use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port, server_url); + xasprintf(&msg, _("%sstring '%s' not found on '%s://%s:%d%s', "), msg, + output_string_search, use_ssl ? "https" : "http", + host_name ? host_name : server_address, server_port, + server_url); result = STATE_CRITICAL; } } - if (strlen (regexp)) { - errcode = regexec (&preg, page, REGS, pmatch, 0); - if ((errcode == 0 && invert_regex == 0) || (errcode == REG_NOMATCH && invert_regex == 1)) { + if (strlen(regexp)) { + errcode = regexec(&preg, page, REGS, pmatch, 0); + if ((errcode == 0 && invert_regex == 0) || + (errcode == REG_NOMATCH && invert_regex == 1)) { /* OK - No-op to avoid changing the logic around it */ result = max_state_alt(STATE_OK, result); - } - else if ((errcode == REG_NOMATCH && invert_regex == 0) || (errcode == 0 && invert_regex == 1)) { + } else if ((errcode == REG_NOMATCH && invert_regex == 0) || + (errcode == 0 && invert_regex == 1)) { if (invert_regex == 0) - xasprintf (&msg, _("%spattern not found, "), msg); + xasprintf(&msg, _("%spattern not found, "), msg); else - xasprintf (&msg, _("%spattern found, "), msg); + xasprintf(&msg, _("%spattern found, "), msg); result = STATE_CRITICAL; - } - else { + } else { /* FIXME: Shouldn't that be UNKNOWN? */ - regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); - xasprintf (&msg, _("%sExecute Error: %s, "), msg, errbuf); + regerror(errcode, &preg, errbuf, MAX_INPUT_BUFFER); + xasprintf(&msg, _("%sExecute Error: %s, "), msg, errbuf); result = STATE_CRITICAL; } } @@ -1314,68 +1320,64 @@ check_http (void) */ page_len = pagesize; if ((max_page_len > 0) && (page_len > max_page_len)) { - xasprintf (&msg, _("%spage size %d too large, "), msg, page_len); + xasprintf(&msg, _("%spage size %d too large, "), msg, page_len); result = max_state_alt(STATE_WARNING, result); } else if ((min_page_len > 0) && (page_len < min_page_len)) { - xasprintf (&msg, _("%spage size %d too small, "), msg, page_len); + xasprintf(&msg, _("%spage size %d too small, "), msg, page_len); result = max_state_alt(STATE_WARNING, result); } /* Cut-off trailing characters */ - if(msg[strlen(msg)-2] == ',') - msg[strlen(msg)-2] = '\0'; + if (msg[strlen(msg) - 2] == ',') + msg[strlen(msg) - 2] = '\0'; else - msg[strlen(msg)-3] = '\0'; + msg[strlen(msg) - 3] = '\0'; /* check elapsed time */ if (show_extended_perfdata) - xasprintf (&msg, - _("%s - %d bytes in %.3f second response time %s|%s %s %s %s %s %s %s"), - msg, page_len, elapsed_time, - (display_html ? "" : ""), - perfd_time (elapsed_time), - perfd_size (page_len), - perfd_time_connect (elapsed_time_connect), - use_ssl == true ? perfd_time_ssl (elapsed_time_ssl) : "", - perfd_time_headers (elapsed_time_headers), - perfd_time_firstbyte (elapsed_time_firstbyte), - perfd_time_transfer (elapsed_time_transfer)); + xasprintf( + &msg, + _("%s - %d bytes in %.3f second response time %s|%s %s %s %s %s %s %s"), + msg, page_len, elapsed_time, (display_html ? "" : ""), + perfd_time(elapsed_time), perfd_size(page_len), + perfd_time_connect(elapsed_time_connect), + use_ssl == true ? perfd_time_ssl(elapsed_time_ssl) : "", + perfd_time_headers(elapsed_time_headers), + perfd_time_firstbyte(elapsed_time_firstbyte), + perfd_time_transfer(elapsed_time_transfer)); else - xasprintf (&msg, - _("%s - %d bytes in %.3f second response time %s|%s %s"), - msg, page_len, elapsed_time, - (display_html ? "" : ""), - perfd_time (elapsed_time), - perfd_size (page_len)); + xasprintf(&msg, _("%s - %d bytes in %.3f second response time %s|%s %s"), + msg, page_len, elapsed_time, (display_html ? "" : ""), + perfd_time(elapsed_time), perfd_size(page_len)); if (show_body) - xasprintf (&msg, _("%s\n%s"), msg, page); + xasprintf(&msg, _("%s\n%s"), msg, page); result = max_state_alt(get_status(elapsed_time, thlds), result); - die (result, "HTTP %s: %s\n", state_text(result), msg); + die(result, "HTTP %s: %s\n", state_text(result), msg); /* die failed? */ return STATE_UNKNOWN; } - - /* per RFC 2396 */ #define URI_HTTP "%5[HTPShtps]" -#define URI_HOST "%255[-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]" +#define URI_HOST \ + "%255[-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]" #define URI_PORT "%6d" /* MAX_PORT's width is 5 chars, 6 to detect overflow */ -#define URI_PATH "%[-_.!~*'();/?:@&=+$,%#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]" +#define URI_PATH \ + "%[-_.!~*'();/" \ + "?:@&=+$,%#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]" #define HD1 URI_HTTP "://" URI_HOST ":" URI_PORT "/" URI_PATH #define HD2 URI_HTTP "://" URI_HOST "/" URI_PATH #define HD3 URI_HTTP "://" URI_HOST ":" URI_PORT #define HD4 URI_HTTP "://" URI_HOST -/* relative reference redirect like //www.site.org/test https://tools.ietf.org/html/rfc3986 */ +/* relative reference redirect like //www.site.org/test + * https://tools.ietf.org/html/rfc3986 */ #define HD5 "//" URI_HOST "/" URI_PATH #define HD6 URI_PATH -void -redir (char *pos, char *status_line) -{ +void redir(char *pos, char *status_line) { int i = 0; char *x; char xx[2]; @@ -1383,101 +1385,101 @@ redir (char *pos, char *status_line) char *addr; char *url; - addr = malloc (MAX_IPV4_HOSTLENGTH + 1); + addr = malloc(MAX_IPV4_HOSTLENGTH + 1); if (addr == NULL) - die (STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate addr\n")); + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate addr\n")); memset(addr, 0, MAX_IPV4_HOSTLENGTH); - url = malloc (strcspn (pos, "\r\n")); + url = malloc(strcspn(pos, "\r\n")); if (url == NULL) - die (STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n")); + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n")); while (pos) { - sscanf (pos, "%1[Ll]%*1[Oo]%*1[Cc]%*1[Aa]%*1[Tt]%*1[Ii]%*1[Oo]%*1[Nn]:%n", xx, &i); + sscanf(pos, "%1[Ll]%*1[Oo]%*1[Cc]%*1[Aa]%*1[Tt]%*1[Ii]%*1[Oo]%*1[Nn]:%n", + xx, &i); if (i == 0) { - pos += (size_t) strcspn (pos, "\r\n"); - pos += (size_t) strspn (pos, "\r\n"); + pos += (size_t)strcspn(pos, "\r\n"); + pos += (size_t)strspn(pos, "\r\n"); if (strlen(pos) == 0) - die (STATE_UNKNOWN, - _("HTTP UNKNOWN - Could not find redirect location - %s%s\n"), - status_line, (display_html ? "" : "")); + die(STATE_UNKNOWN, + _("HTTP UNKNOWN - Could not find redirect location - %s%s\n"), + status_line, (display_html ? "" : "")); continue; } pos += i; - pos += strspn (pos, " \t"); + pos += strspn(pos, " \t"); /* * RFC 2616 (4.2): ``Header fields can be extended over multiple lines by * preceding each extra line with at least one SP or HT.'' */ - for (; (i = strspn (pos, "\r\n")); pos += i) { + for (; (i = strspn(pos, "\r\n")); pos += i) { pos += i; - if (!(i = strspn (pos, " \t"))) { - die (STATE_UNKNOWN, _("HTTP UNKNOWN - Empty redirect location%s\n"), - display_html ? "" : ""); + if (!(i = strspn(pos, " \t"))) { + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Empty redirect location%s\n"), + display_html ? "" : ""); } } - url = realloc (url, strcspn (pos, "\r\n") + 1); + url = realloc(url, strcspn(pos, "\r\n") + 1); if (url == NULL) - die (STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n")); + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n")); /* URI_HTTP, URI_HOST, URI_PORT, URI_PATH */ - if (sscanf (pos, HD1, type, addr, &i, url) == 4) { - url = prepend_slash (url); - use_ssl = server_type_check (type); + if (sscanf(pos, HD1, type, addr, &i, url) == 4) { + url = prepend_slash(url); + use_ssl = server_type_check(type); } /* URI_HTTP URI_HOST URI_PATH */ - else if (sscanf (pos, HD2, type, addr, url) == 3 ) { - url = prepend_slash (url); - use_ssl = server_type_check (type); - i = server_port_check (use_ssl); + else if (sscanf(pos, HD2, type, addr, url) == 3) { + url = prepend_slash(url); + use_ssl = server_type_check(type); + i = server_port_check(use_ssl); } /* URI_HTTP URI_HOST URI_PORT */ - else if (sscanf (pos, HD3, type, addr, &i) == 3) { - strcpy (url, HTTP_URL); - use_ssl = server_type_check (type); + else if (sscanf(pos, HD3, type, addr, &i) == 3) { + strcpy(url, HTTP_URL); + use_ssl = server_type_check(type); } /* URI_HTTP URI_HOST */ - else if (sscanf (pos, HD4, type, addr) == 2) { - strcpy (url, HTTP_URL); - use_ssl = server_type_check (type); - i = server_port_check (use_ssl); + else if (sscanf(pos, HD4, type, addr) == 2) { + strcpy(url, HTTP_URL); + use_ssl = server_type_check(type); + i = server_port_check(use_ssl); } /* URI_HTTP, URI_HOST, URI_PATH */ - else if (sscanf (pos, HD5, addr, url) == 2) { - if(use_ssl){ - strcpy (type,"https"); - } - else{ - strcpy (type, server_type); + else if (sscanf(pos, HD5, addr, url) == 2) { + if (use_ssl) { + strcpy(type, "https"); + } else { + strcpy(type, server_type); } - xasprintf (&url, "/%s", url); - use_ssl = server_type_check (type); - i = server_port_check (use_ssl); + xasprintf(&url, "/%s", url); + use_ssl = server_type_check(type); + i = server_port_check(use_ssl); } /* URI_PATH */ - else if (sscanf (pos, HD6, url) == 1) { + else if (sscanf(pos, HD6, url) == 1) { /* relative url */ if ((url[0] != '/')) { if ((x = strrchr(server_url, '/'))) *x = '\0'; - xasprintf (&url, "%s/%s", server_url, url); + xasprintf(&url, "%s/%s", server_url, url); } i = server_port; - strcpy (type, server_type); - strcpy (addr, host_name ? host_name : server_address); + strcpy(type, server_type); + strcpy(addr, host_name ? host_name : server_address); } else { - die (STATE_UNKNOWN, - _("HTTP UNKNOWN - Could not parse redirect location - %s%s\n"), - pos, (display_html ? "" : "")); + die(STATE_UNKNOWN, + _("HTTP UNKNOWN - Could not parse redirect location - %s%s\n"), pos, + (display_html ? "" : "")); } break; @@ -1485,299 +1487,356 @@ redir (char *pos, char *status_line) } /* end while (pos) */ if (++redir_depth > max_depth) - die (STATE_WARNING, - _("HTTP WARNING - maximum redirection depth %d exceeded - %s://%s:%d%s%s\n"), - max_depth, type, addr, i, url, (display_html ? "" : "")); + die(STATE_WARNING, + _("HTTP WARNING - maximum redirection depth %d exceeded - " + "%s://%s:%d%s%s\n"), + max_depth, type, addr, i, url, (display_html ? "" : "")); - if (server_port==i && - !strncmp(server_address, addr, MAX_IPV4_HOSTLENGTH) && + if (server_port == i && !strncmp(server_address, addr, MAX_IPV4_HOSTLENGTH) && (host_name && !strncmp(host_name, addr, MAX_IPV4_HOSTLENGTH)) && !strcmp(server_url, url)) - die (STATE_CRITICAL, - _("HTTP CRITICAL - redirection creates an infinite loop - %s://%s:%d%s%s\n"), - type, addr, i, url, (display_html ? "" : "")); + die(STATE_CRITICAL, + _("HTTP CRITICAL - redirection creates an infinite loop - " + "%s://%s:%d%s%s\n"), + type, addr, i, url, (display_html ? "" : "")); - strcpy (server_type, type); + strcpy(server_type, type); - free (host_name); - host_name = strndup (addr, MAX_IPV4_HOSTLENGTH); + free(host_name); + host_name = strndup(addr, MAX_IPV4_HOSTLENGTH); if (!(followsticky & STICKY_HOST)) { - free (server_address); - server_address = strndup (addr, MAX_IPV4_HOSTLENGTH); + free(server_address); + server_address = strndup(addr, MAX_IPV4_HOSTLENGTH); } if (!(followsticky & STICKY_PORT)) { server_port = i; } - free (server_url); + free(server_url); server_url = url; if (server_port > MAX_PORT) - die (STATE_UNKNOWN, - _("HTTP UNKNOWN - Redirection to port above %d - %s://%s:%d%s%s\n"), - MAX_PORT, server_type, server_address, server_port, server_url, - display_html ? "" : ""); + die(STATE_UNKNOWN, + _("HTTP UNKNOWN - Redirection to port above %d - %s://%s:%d%s%s\n"), + MAX_PORT, server_type, server_address, server_port, server_url, + display_html ? "" : ""); /* reset virtual port */ virtual_port = server_port; if (verbose) - printf (_("Redirection to %s://%s:%d%s\n"), server_type, - host_name ? host_name : server_address, server_port, server_url); + printf(_("Redirection to %s://%s:%d%s\n"), server_type, + host_name ? host_name : server_address, server_port, server_url); free(addr); - check_http (); + check_http(); } - -bool -server_type_check (const char *type) -{ - if (strcmp (type, "https")) +bool server_type_check(const char *type) { + if (strcmp(type, "https")) return false; else return true; } -int -server_port_check (int ssl_flag) -{ +int server_port_check(int ssl_flag) { if (ssl_flag) return HTTPS_PORT; else return HTTP_PORT; } -char *perfd_time (double elapsed_time) -{ - return fperfdata ("time", elapsed_time, "s", - thlds->warning?true:false, thlds->warning?thlds->warning->end:0, - thlds->critical?true:false, thlds->critical?thlds->critical->end:0, - true, 0, true, socket_timeout); +char *perfd_time(double elapsed_time) { + return fperfdata("time", elapsed_time, "s", thlds->warning ? true : false, + thlds->warning ? thlds->warning->end : 0, + thlds->critical ? true : false, + thlds->critical ? thlds->critical->end : 0, true, 0, true, + socket_timeout); } -char *perfd_time_connect (double elapsed_time_connect) -{ - return fperfdata ("time_connect", elapsed_time_connect, "s", false, 0, false, 0, false, 0, true, socket_timeout); +char *perfd_time_connect(double elapsed_time_connect) { + return fperfdata("time_connect", elapsed_time_connect, "s", false, 0, false, + 0, false, 0, true, socket_timeout); } -char *perfd_time_ssl (double elapsed_time_ssl) -{ - return fperfdata ("time_ssl", elapsed_time_ssl, "s", false, 0, false, 0, false, 0, true, socket_timeout); +char *perfd_time_ssl(double elapsed_time_ssl) { + return fperfdata("time_ssl", elapsed_time_ssl, "s", false, 0, false, 0, false, + 0, true, socket_timeout); } -char *perfd_time_headers (double elapsed_time_headers) -{ - return fperfdata ("time_headers", elapsed_time_headers, "s", false, 0, false, 0, false, 0, true, socket_timeout); +char *perfd_time_headers(double elapsed_time_headers) { + return fperfdata("time_headers", elapsed_time_headers, "s", false, 0, false, + 0, false, 0, true, socket_timeout); } -char *perfd_time_firstbyte (double elapsed_time_firstbyte) -{ - return fperfdata ("time_firstbyte", elapsed_time_firstbyte, "s", false, 0, false, 0, false, 0, true, socket_timeout); +char *perfd_time_firstbyte(double elapsed_time_firstbyte) { + return fperfdata("time_firstbyte", elapsed_time_firstbyte, "s", false, 0, + false, 0, false, 0, true, socket_timeout); } -char *perfd_time_transfer (double elapsed_time_transfer) -{ - return fperfdata ("time_transfer", elapsed_time_transfer, "s", false, 0, false, 0, false, 0, true, socket_timeout); +char *perfd_time_transfer(double elapsed_time_transfer) { + return fperfdata("time_transfer", elapsed_time_transfer, "s", false, 0, false, + 0, false, 0, true, socket_timeout); } -char *perfd_size (int page_len) -{ - return perfdata ("size", page_len, "B", - (min_page_len>0?true:false), min_page_len, - (min_page_len>0?true:false), 0, - true, 0, false, 0); +char *perfd_size(int page_len) { + return perfdata("size", page_len, "B", (min_page_len > 0 ? true : false), + min_page_len, (min_page_len > 0 ? true : false), 0, true, 0, + false, 0); } -void -print_help (void) -{ - print_revision (progname, NP_VERSION); +void print_help(void) { + print_revision(progname, NP_VERSION); - printf ("Copyright (c) 1999 Ethan Galstad \n"); - printf (COPYRIGHT, copyright, email); + printf("Copyright (c) 1999 Ethan Galstad \n"); + printf(COPYRIGHT, copyright, email); - printf ("%s\n", _("This plugin tests the HTTP service on the specified host. It can test")); - printf ("%s\n", _("normal (http) and secure (https) servers, follow redirects, search for")); - printf ("%s\n", _("strings and regular expressions, check connection times, and report on")); - printf ("%s\n", _("certificate expiration times.")); + printf("%s\n", _("This plugin tests the HTTP service on the specified host. " + "It can test")); + printf("%s\n", _("normal (http) and secure (https) servers, follow " + "redirects, search for")); + printf("%s\n", _("strings and regular expressions, check connection times, " + "and report on")); + printf("%s\n", _("certificate expiration times.")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); #ifdef HAVE_SSL - printf (_("In the first form, make an HTTP request.")); - printf (_("In the second form, connect to the server and check the TLS certificate.")); + printf(_("In the first form, make an HTTP request.")); + printf(_("In the second form, connect to the server and check the TLS " + "certificate.")); #endif - printf (_("NOTE: One or both of -H and -I must be specified")); + printf(_("NOTE: One or both of -H and -I must be specified")); - printf ("\n"); + printf("\n"); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); - printf (" %s\n", "-H, --hostname=ADDRESS"); - printf (" %s\n", _("Host name argument for servers using host headers (virtual host)")); - printf (" %s\n", _("Append a port to include it in the header (eg: example.com:5000)")); - printf (" %s\n", "-I, --IP-address=ADDRESS"); - printf (" %s\n", _("IP address or name (use numeric address if possible to bypass DNS lookup).")); - printf (" %s\n", "-p, --port=INTEGER"); - printf (" %s", _("Port number (default: ")); - printf ("%d)\n", HTTP_PORT); + printf(" %s\n", "-H, --hostname=ADDRESS"); + printf(" %s\n", + _("Host name argument for servers using host headers (virtual host)")); + printf(" %s\n", + _("Append a port to include it in the header (eg: example.com:5000)")); + printf(" %s\n", "-I, --IP-address=ADDRESS"); + printf(" %s\n", _("IP address or name (use numeric address if possible to " + "bypass DNS lookup).")); + printf(" %s\n", "-p, --port=INTEGER"); + printf(" %s", _("Port number (default: ")); + printf("%d)\n", HTTP_PORT); - printf (UT_IPv46); + printf(UT_IPv46); #ifdef HAVE_SSL - printf (" %s\n", "-S, --ssl=VERSION[+]"); - printf (" %s\n", _("Connect via SSL. Port defaults to 443. VERSION is optional, and prevents")); - printf (" %s\n", _("auto-negotiation (2 = SSLv2, 3 = SSLv3, 1 = TLSv1, 1.1 = TLSv1.1,")); - printf (" %s\n", _("1.2 = TLSv1.2). With a '+' suffix, newer versions are also accepted.")); - printf (" %s\n", "--sni"); - printf (" %s\n", _("Enable SSL/TLS hostname extension support (SNI)")); - printf (" %s\n", "-C, --certificate=INTEGER[,INTEGER]"); - printf (" %s\n", _("Minimum number of days a certificate has to be valid. Port defaults to 443")); - printf (" %s\n", _("(when this option is used the URL is not checked by default. You can use")); - printf (" %s\n", _(" --continue-after-certificate to override this behavior)")); - printf (" %s\n", "--continue-after-certificate"); - printf (" %s\n", _("Allows the HTTP check to continue after performing the certificate check.")); - printf (" %s\n", _("Does nothing unless -C is used.")); - printf (" %s\n", "-J, --client-cert=FILE"); - printf (" %s\n", _("Name of file that contains the client certificate (PEM format)")); - printf (" %s\n", _("to be used in establishing the SSL session")); - printf (" %s\n", "-K, --private-key=FILE"); - printf (" %s\n", _("Name of file containing the private key (PEM format)")); - printf (" %s\n", _("matching the client certificate")); + printf(" %s\n", "-S, --ssl=VERSION[+]"); + printf(" %s\n", _("Connect via SSL. Port defaults to 443. VERSION is " + "optional, and prevents")); + printf( + " %s\n", + _("auto-negotiation (2 = SSLv2, 3 = SSLv3, 1 = TLSv1, 1.1 = TLSv1.1,")); + printf(" %s\n", _("1.2 = TLSv1.2). With a '+' suffix, newer versions are " + "also accepted.")); + printf(" %s\n", "--sni"); + printf(" %s\n", _("Enable SSL/TLS hostname extension support (SNI)")); + printf(" %s\n", "-C, --certificate=INTEGER[,INTEGER]"); + printf(" %s\n", _("Minimum number of days a certificate has to be valid. " + "Port defaults to 443")); + printf(" %s\n", _("(when this option is used the URL is not checked by " + "default. You can use")); + printf(" %s\n", + _(" --continue-after-certificate to override this behavior)")); + printf(" %s\n", "--continue-after-certificate"); + printf(" %s\n", _("Allows the HTTP check to continue after performing the " + "certificate check.")); + printf(" %s\n", _("Does nothing unless -C is used.")); + printf(" %s\n", "-J, --client-cert=FILE"); + printf(" %s\n", + _("Name of file that contains the client certificate (PEM format)")); + printf(" %s\n", _("to be used in establishing the SSL session")); + printf(" %s\n", "-K, --private-key=FILE"); + printf(" %s\n", _("Name of file containing the private key (PEM format)")); + printf(" %s\n", _("matching the client certificate")); #endif - printf (" %s\n", "-e, --expect=STRING"); - printf (" %s\n", _("Comma-delimited list of strings, at least one of them is expected in")); - printf (" %s", _("the first (status) line of the server response (default: ")); - printf ("%s)\n", HTTP_EXPECT); - printf (" %s\n", _("If specified skips all other status line logic (ex: 3xx, 4xx, 5xx processing)")); - printf (" %s\n", "-d, --header-string=STRING"); - printf (" %s\n", _("String to expect in the response headers")); - printf (" %s\n", "-s, --string=STRING"); - printf (" %s\n", _("String to expect in the content")); - printf (" %s\n", "-u, --url=PATH"); - printf (" %s\n", _("URL to GET or POST (default: /)")); - printf (" %s\n", "-P, --post=STRING"); - printf (" %s\n", _("URL encoded http POST data")); - printf (" %s\n", "-j, --method=STRING (for example: HEAD, OPTIONS, TRACE, PUT, DELETE, CONNECT, CONNECT:POST)"); - printf (" %s\n", _("Set HTTP method.")); - printf (" %s\n", "-N, --no-body"); - printf (" %s\n", _("Don't wait for document body: stop reading after headers.")); - printf (" %s\n", _("(Note that this still does an HTTP GET or POST, not a HEAD.)")); - printf (" %s\n", "-M, --max-age=SECONDS"); - printf (" %s\n", _("Warn if document is more than SECONDS old. the number can also be of")); - printf (" %s\n", _("the form \"10m\" for minutes, \"10h\" for hours, or \"10d\" for days.")); - printf (" %s\n", "-T, --content-type=STRING"); - printf (" %s\n", _("specify Content-Type header media type when POSTing\n")); - - printf (" %s\n", "-l, --linespan"); - printf (" %s\n", _("Allow regex to span newlines (must precede -r or -R)")); - printf (" %s\n", "-r, --regex, --ereg=STRING"); - printf (" %s\n", _("Search page for regex STRING")); - printf (" %s\n", "-R, --eregi=STRING"); - printf (" %s\n", _("Search page for case-insensitive regex STRING")); - printf (" %s\n", "--invert-regex"); - printf (" %s\n", _("Return CRITICAL if found, OK if not\n")); - - printf (" %s\n", "-a, --authorization=AUTH_PAIR"); - printf (" %s\n", _("Username:password on sites with basic authentication")); - printf (" %s\n", "-b, --proxy-authorization=AUTH_PAIR"); - printf (" %s\n", _("Username:password on proxy-servers with basic authentication")); - printf (" %s\n", "-A, --useragent=STRING"); - printf (" %s\n", _("String to be sent in http header as \"User Agent\"")); - printf (" %s\n", "-k, --header=STRING"); - printf (" %s\n", _("Any other tags to be sent in http header. Use multiple times for additional headers")); - printf (" %s\n", "-E, --extended-perfdata"); - printf (" %s\n", _("Print additional performance data")); - printf (" %s\n", "-B, --show-body"); - printf (" %s\n", _("Print body content below status line")); - printf (" %s\n", "-L, --link"); - printf (" %s\n", _("Wrap output in HTML link (obsoleted by urlize)")); - printf (" %s\n", "-f, --onredirect="); - printf (" %s\n", _("How to handle redirected pages. sticky is like follow but stick to the")); - printf (" %s\n", _("specified IP address. stickyport also ensures port stays the same.")); - printf (" %s\n", "--max-redirs=INTEGER"); - printf (" %s", _("Maximal number of redirects (default: ")); - printf ("%d)\n", DEFAULT_MAX_REDIRS); - printf (" %s\n", "-m, --pagesize=INTEGER<:INTEGER>"); - printf (" %s\n", _("Minimum page size required (bytes) : Maximum page size required (bytes)")); - printf (UT_WARN_CRIT); - - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - - printf (UT_VERBOSE); - - printf ("\n"); - printf ("%s\n", _("Notes:")); - printf (" %s\n", _("This plugin will attempt to open an HTTP connection with the host.")); - printf (" %s\n", _("Successful connects return STATE_OK, refusals and timeouts return STATE_CRITICAL")); - printf (" %s\n", _("other errors return STATE_UNKNOWN. Successful connects, but incorrect response")); - printf (" %s\n", _("messages from the host result in STATE_WARNING return values. If you are")); - printf (" %s\n", _("checking a virtual server that uses 'host headers' you must supply the FQDN")); - printf (" %s\n", _("(fully qualified domain name) as the [host_name] argument.")); + printf(" %s\n", "-e, --expect=STRING"); + printf(" %s\n", _("Comma-delimited list of strings, at least one of them " + "is expected in")); + printf(" %s", + _("the first (status) line of the server response (default: ")); + printf("%s)\n", HTTP_EXPECT); + printf(" %s\n", _("If specified skips all other status line logic (ex: " + "3xx, 4xx, 5xx processing)")); + printf(" %s\n", "-d, --header-string=STRING"); + printf(" %s\n", _("String to expect in the response headers")); + printf(" %s\n", "-s, --string=STRING"); + printf(" %s\n", _("String to expect in the content")); + printf(" %s\n", "-u, --url=PATH"); + printf(" %s\n", _("URL to GET or POST (default: /)")); + printf(" %s\n", "-P, --post=STRING"); + printf(" %s\n", _("URL encoded http POST data")); + printf(" %s\n", "-j, --method=STRING (for example: HEAD, OPTIONS, TRACE, " + "PUT, DELETE, CONNECT, CONNECT:POST)"); + printf(" %s\n", _("Set HTTP method.")); + printf(" %s\n", "-N, --no-body"); + printf(" %s\n", + _("Don't wait for document body: stop reading after headers.")); + printf(" %s\n", + _("(Note that this still does an HTTP GET or POST, not a HEAD.)")); + printf(" %s\n", "-M, --max-age=SECONDS"); + printf(" %s\n", _("Warn if document is more than SECONDS old. the number " + "can also be of")); + printf(" %s\n", _("the form \"10m\" for minutes, \"10h\" for hours, or " + "\"10d\" for days.")); + printf(" %s\n", "-T, --content-type=STRING"); + printf(" %s\n", + _("specify Content-Type header media type when POSTing\n")); + + printf(" %s\n", "-l, --linespan"); + printf(" %s\n", _("Allow regex to span newlines (must precede -r or -R)")); + printf(" %s\n", "-r, --regex, --ereg=STRING"); + printf(" %s\n", _("Search page for regex STRING")); + printf(" %s\n", "-R, --eregi=STRING"); + printf(" %s\n", _("Search page for case-insensitive regex STRING")); + printf(" %s\n", "--invert-regex"); + printf(" %s\n", _("Return CRITICAL if found, OK if not\n")); + + printf(" %s\n", "-a, --authorization=AUTH_PAIR"); + printf(" %s\n", _("Username:password on sites with basic authentication")); + printf(" %s\n", "-b, --proxy-authorization=AUTH_PAIR"); + printf(" %s\n", + _("Username:password on proxy-servers with basic authentication")); + printf(" %s\n", "-A, --useragent=STRING"); + printf(" %s\n", _("String to be sent in http header as \"User Agent\"")); + printf(" %s\n", "-k, --header=STRING"); + printf(" %s\n", _("Any other tags to be sent in http header. Use multiple " + "times for additional headers")); + printf(" %s\n", "-E, --extended-perfdata"); + printf(" %s\n", _("Print additional performance data")); + printf(" %s\n", "-B, --show-body"); + printf(" %s\n", _("Print body content below status line")); + printf(" %s\n", "-L, --link"); + printf(" %s\n", _("Wrap output in HTML link (obsoleted by urlize)")); + printf(" %s\n", + "-f, --onredirect="); + printf(" %s\n", _("How to handle redirected pages. sticky is like follow " + "but stick to the")); + printf( + " %s\n", + _("specified IP address. stickyport also ensures port stays the same.")); + printf(" %s\n", "--max-redirs=INTEGER"); + printf(" %s", _("Maximal number of redirects (default: ")); + printf("%d)\n", DEFAULT_MAX_REDIRS); + printf(" %s\n", "-m, --pagesize=INTEGER<:INTEGER>"); + printf(" %s\n", _("Minimum page size required (bytes) : Maximum page size " + "required (bytes)")); + printf(UT_WARN_CRIT); + + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + + printf(UT_VERBOSE); + + printf("\n"); + printf("%s\n", _("Notes:")); + printf( + " %s\n", + _("This plugin will attempt to open an HTTP connection with the host.")); + printf(" %s\n", _("Successful connects return STATE_OK, refusals and " + "timeouts return STATE_CRITICAL")); + printf(" %s\n", _("other errors return STATE_UNKNOWN. Successful connects, " + "but incorrect response")); + printf(" %s\n", _("messages from the host result in STATE_WARNING return " + "values. If you are")); + printf(" %s\n", _("checking a virtual server that uses 'host headers' you " + "must supply the FQDN")); + printf(" %s\n", + _("(fully qualified domain name) as the [host_name] argument.")); #ifdef HAVE_SSL - printf ("\n"); - printf (" %s\n", _("This plugin can also check whether an SSL enabled web server is able to")); - printf (" %s\n", _("serve content (optionally within a specified time) or whether the X509 ")); - printf (" %s\n", _("certificate is still valid for the specified number of days.")); - printf ("\n"); - printf (" %s\n", _("Please note that this plugin does not check if the presented server")); - printf (" %s\n", _("certificate matches the hostname of the server, or if the certificate")); - printf (" %s\n", _("has a valid chain of trust to one of the locally installed CAs.")); - printf ("\n"); - printf ("%s\n", _("Examples:")); - printf (" %s\n\n", "CHECK CONTENT: check_http -w 5 -c 10 --ssl -H www.verisign.com"); - printf (" %s\n", _("When the 'www.verisign.com' server returns its content within 5 seconds,")); - printf (" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds")); - printf (" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,")); - printf (" %s\n", _("a STATE_CRITICAL will be returned.")); - printf ("\n"); - printf (" %s\n\n", "CHECK CERTIFICATE: check_http -H www.verisign.com -C 14"); - printf (" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 14 days,")); - printf (" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than")); - printf (" %s\n", _("14 days, a STATE_WARNING is returned. A STATE_CRITICAL will be returned when")); - printf (" %s\n\n", _("the certificate is expired.")); - printf ("\n"); - printf (" %s\n\n", "CHECK CERTIFICATE: check_http -H www.verisign.com -C 30,14"); - printf (" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 30 days,")); - printf (" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than")); - printf (" %s\n", _("30 days, but more than 14 days, a STATE_WARNING is returned.")); - printf (" %s\n", _("A STATE_CRITICAL will be returned when certificate expires in less than 14 days")); - - printf (" %s\n\n", "CHECK SSL WEBSERVER CONTENT VIA PROXY USING HTTP 1.1 CONNECT: "); - printf (" %s\n", _("check_http -I 192.168.100.35 -p 80 -u https://www.verisign.com/ -S -j CONNECT -H www.verisign.com ")); - printf (" %s\n", _("all these options are needed: -I -p -u -S(sl) -j CONNECT -H ")); - printf (" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds")); - printf (" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,")); - printf (" %s\n", _("a STATE_CRITICAL will be returned. By adding a colon to the method you can set the method used")); - printf (" %s\n", _("inside the proxied connection: -j CONNECT:POST")); + printf("\n"); + printf(" %s\n", _("This plugin can also check whether an SSL enabled web " + "server is able to")); + printf(" %s\n", _("serve content (optionally within a specified time) or " + "whether the X509 ")); + printf(" %s\n", + _("certificate is still valid for the specified number of days.")); + printf("\n"); + printf( + " %s\n", + _("Please note that this plugin does not check if the presented server")); + printf(" %s\n", _("certificate matches the hostname of the server, or if the " + "certificate")); + printf(" %s\n", + _("has a valid chain of trust to one of the locally installed CAs.")); + printf("\n"); + printf("%s\n", _("Examples:")); + printf(" %s\n\n", + "CHECK CONTENT: check_http -w 5 -c 10 --ssl -H www.verisign.com"); + printf(" %s\n", _("When the 'www.verisign.com' server returns its content " + "within 5 seconds,")); + printf(" %s\n", _("a STATE_OK will be returned. When the server returns its " + "content but exceeds")); + printf(" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. " + "When an error occurs,")); + printf(" %s\n", _("a STATE_CRITICAL will be returned.")); + printf("\n"); + printf(" %s\n\n", "CHECK CERTIFICATE: check_http -H www.verisign.com -C 14"); + printf(" %s\n", _("When the certificate of 'www.verisign.com' is valid for " + "more than 14 days,")); + printf(" %s\n", _("a STATE_OK is returned. When the certificate is still " + "valid, but for less than")); + printf(" %s\n", _("14 days, a STATE_WARNING is returned. A STATE_CRITICAL " + "will be returned when")); + printf(" %s\n\n", _("the certificate is expired.")); + printf("\n"); + printf(" %s\n\n", + "CHECK CERTIFICATE: check_http -H www.verisign.com -C 30,14"); + printf(" %s\n", _("When the certificate of 'www.verisign.com' is valid for " + "more than 30 days,")); + printf(" %s\n", _("a STATE_OK is returned. When the certificate is still " + "valid, but for less than")); + printf(" %s\n", + _("30 days, but more than 14 days, a STATE_WARNING is returned.")); + printf(" %s\n", _("A STATE_CRITICAL will be returned when certificate " + "expires in less than 14 days")); + + printf(" %s\n\n", + "CHECK SSL WEBSERVER CONTENT VIA PROXY USING HTTP 1.1 CONNECT: "); + printf(" %s\n", + _("check_http -I 192.168.100.35 -p 80 -u https://www.verisign.com/ -S " + "-j CONNECT -H www.verisign.com ")); + printf(" %s\n", _("all these options are needed: -I -p " + "-u -S(sl) -j CONNECT -H ")); + printf(" %s\n", _("a STATE_OK will be returned. When the server returns its " + "content but exceeds")); + printf(" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. " + "When an error occurs,")); + printf(" %s\n", _("a STATE_CRITICAL will be returned. By adding a colon to " + "the method you can set the method used")); + printf(" %s\n", _("inside the proxied connection: -j CONNECT:POST")); #endif - printf (UT_SUPPORT); - + printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf (" %s -H | -I [-u ] [-p ]\n",progname); - printf (" [-J ] [-K ]\n"); - printf (" [-w ] [-c ] [-t ] [-L] [-E] [-a auth]\n"); - printf (" [-b proxy_auth] [-f ]\n"); - printf (" [-e ] [-d string] [-s string] [-l] [-r | -R ]\n"); - printf (" [-P string] [-m :] [-4|-6] [-N] [-M ]\n"); - printf (" [-A string] [-k string] [-S ] [--sni]\n"); - printf (" [-T ] [-j method]\n"); - printf (" %s -H | -I -C [,]\n",progname); - printf (" [-p ] [-t ] [-4|-6] [--sni]\n"); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf(" %s -H | -I [-u ] [-p ]\n", progname); + printf(" [-J ] [-K ]\n"); + printf(" [-w ] [-c ] [-t ] [-L] " + "[-E] [-a auth]\n"); + printf(" [-b proxy_auth] [-f " + "]\n"); + printf(" [-e ] [-d string] [-s string] [-l] [-r | -R " + "]\n"); + printf(" [-P string] [-m :] [-4|-6] [-N] [-M " + "]\n"); + printf(" [-A string] [-k string] [-S ] [--sni]\n"); + printf(" [-T ] [-j method]\n"); + printf(" %s -H | -I -C [,]\n", + progname); + printf(" [-p ] [-t ] [-4|-6] [--sni]\n"); } -- cgit v1.2.3-74-g34f1 From c0c096d2ef0d838e869a63aba07e6538e46db674 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Sun, 13 Nov 2022 19:01:33 +0100 Subject: Remove dead code --- plugins/check_http.c | 18 ------------------ 1 file changed, 18 deletions(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index 440c8422..ca8746b7 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -1111,25 +1111,7 @@ int check_http(void) { elapsed_time_transfer = (double)microsec_transfer / 1.0e6; if (i < 0 && errno != ECONNRESET) { -#ifdef HAVE_SSL - /* - if (use_ssl) { - sslerr=SSL_get_error(ssl, i); - if ( sslerr == SSL_ERROR_SSL ) { - die (STATE_WARNING, _("HTTP WARNING - Client Certificate Required\n")); - } else { - die (STATE_CRITICAL, _("HTTP CRITICAL - Error on receive\n")); - } - } - else { - */ -#endif die(STATE_CRITICAL, _("HTTP CRITICAL - Error on receive\n")); -#ifdef HAVE_SSL - /* XXX - } - */ -#endif } /* return a CRITICAL status if we couldn't read any data */ -- cgit v1.2.3-74-g34f1 From d4502f246f367af5e1d6b3944116f1d86beb5811 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Sun, 13 Nov 2022 23:03:25 +0100 Subject: Remove legacy comments and add some new ones --- plugins/check_http.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index ca8746b7..859e3e35 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -31,9 +31,6 @@ * *****************************************************************************/ -/* splint -I. -I../../plugins -I../../lib/ -I/usr/kerberos/include/ - * ../../plugins/check_http.c */ - const char *progname = "check_http"; const char *copyright = "1999-2022"; const char *email = "devel@monitoring-plugins.org"; @@ -136,6 +133,7 @@ char buffer[MAX_INPUT_BUFFER]; char *client_cert = NULL; char *client_privkey = NULL; +// Forward function declarations bool process_arguments(int, char **); int check_http(void); void redir(char *pos, char *status_line); -- cgit v1.2.3-74-g34f1 From 2c658383d5c7742d289e07116c948c6905555405 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Sun, 13 Nov 2022 23:06:51 +0100 Subject: Restructure code a bit to put things where they are actually needed --- plugins/check_http.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index 859e3e35..a2c7571b 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -103,8 +103,6 @@ int server_expect_yn = 0; char server_expect[MAX_INPUT_BUFFER] = HTTP_EXPECT; char header_expect[MAX_INPUT_BUFFER] = ""; char string_expect[MAX_INPUT_BUFFER] = ""; -char output_header_search[30] = ""; -char output_string_search[30] = ""; char *warning_thresholds = NULL; char *critical_thresholds = NULL; thresholds *thlds; @@ -1236,8 +1234,10 @@ int check_http(void) { } /* Page and Header content checks go here */ - if (strlen(header_expect)) { - if (!strstr(header, header_expect)) { + if (strlen(header_expect) > 0) { + if (strstr(header, header_expect) == NULL) { + // We did not find the header, the rest is for building the output and setting the state + char output_header_search[30] = ""; strncpy(&output_header_search[0], header_expect, sizeof(output_header_search)); if (output_header_search[sizeof(output_header_search) - 1] != '\0') { @@ -1254,6 +1254,8 @@ int check_http(void) { if (strlen(string_expect)) { if (!strstr(page, string_expect)) { + // We found the string the body, the rest is for building the output + char output_string_search[30] = ""; strncpy(&output_string_search[0], string_expect, sizeof(output_string_search)); if (output_string_search[sizeof(output_string_search) - 1] != '\0') { @@ -1268,7 +1270,7 @@ int check_http(void) { } } - if (strlen(regexp)) { + if (strlen(regexp) > 0) { errcode = regexec(&preg, page, REGS, pmatch, 0); if ((errcode == 0 && invert_regex == 0) || (errcode == REG_NOMATCH && invert_regex == 1)) { -- cgit v1.2.3-74-g34f1 From afe92468a54ec44cdda35e46a1eabd0d0de78840 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Sun, 13 Nov 2022 23:07:14 +0100 Subject: Implement chunked encoding decoding --- plugins/check_http.c | 103 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 102 insertions(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index a2c7571b..5710cfe1 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -146,6 +146,7 @@ char *perfd_time_transfer(double microsec); char *perfd_size(int page_len); void print_help(void); void print_usage(void); +char *unchunk_content(char *content); int main(int argc, char **argv) { int result = STATE_UNKNOWN; @@ -1252,7 +1253,26 @@ int check_http(void) { } } - if (strlen(string_expect)) { + // At this point we should test if the content is chunked and unchunk it, so + // it can be searched (and possibly printed) + const char *chunked_header_regex_string = "Transfer-Encoding:\\s*chunked\\s*"CRLF; + regex_t chunked_header_regex; + + if (regcomp(&chunked_header_regex, chunked_header_regex_string, 0)) { + die(STATE_UNKNOWN, "HTTP %s: %s\n", state_text(STATE_UNKNOWN), "Failed to compile chunked_header_regex regex"); + } + + regmatch_t chre_pmatch[1]; // We actually do not care about this, since we only want to know IF it was found + + if (regexec(&chunked_header_regex, header, 1, chre_pmatch, 0) == 0) { + // We actually found the chunked header + char *tmp = unchunk_content(page); + if (tmp == NULL) { + die(STATE_UNKNOWN, "HTTP %s: %s\n", state_text(STATE_UNKNOWN), "Failed to unchunk message body"); + } + } + + if (strlen(string_expect) > 0) { if (!strstr(page, string_expect)) { // We found the string the body, the rest is for building the output char output_string_search[30] = ""; @@ -1342,6 +1362,87 @@ int check_http(void) { return STATE_UNKNOWN; } +/* Receivces a pointer to the beginning of the body of a HTTP message + * which is chunked and returns a pointer to a freshly allocated memory + * region containing the unchunked body or NULL if something failed. + * The result must be freed by the caller. + */ +char *unchunk_content(const char *content) { + // https://en.wikipedia.org/wiki/Chunked_transfer_encoding + // https://www.rfc-editor.org/rfc/rfc7230#section-4.1 + char *result = NULL; + size_t content_length = strlen(content); + char *start_of_chunk, end_of_chunk; + long size_of_chunk; + char *pointer = content; + char *endptr; + long length_of_chunk = 0; + size_t overall_size = 0; + char *result_ptr; + + while (true) { + size_of_chunk = strtol(pointer, &endptr, 16); + if (size_of_chunk == LONG_MIN || size_of_chunk == LONG_MAX) { + // Apparently underflow or overflow, should not happen + if (verbose) { + printf("Got an underflow or overflow from strtol at: %u\n", __LINE__); + } + return NULL; + } + if (endptr == pointer) { + // Apparently this was not a number + if (verbose) { + printf("Chunked content did not start with a number at all (Line: %u)\n", __LINE__); + } + return NULL + } + + // So, we got the length of the chunk + if (*endptr == ';') { + // Chunk extension starts here + // TODO + while (*endptr != '\r') { + endptr++; + } + } + + start_of_chunk = endptr + 2; + end_of_chunk = start_of_chunk + size_of_chunk; + length_of_chunk = end_of_chunk - start_of_chunk; + + if (length_of_chunk == 0) { + // Chunk length is 0, so this is the last one + break; + } + + overall_size += length_of_chunk; + + if (result == NULL) { + result = (char *)calloc(length_of_chunk, sizeof(char)); + if (result == NULL) { + if (verbose) { + printf("Failed to allocate memory for unchunked body\n"); + } + return NULL; + } + result_ptr = result; + } else { + void *tmp = realloc(result, overall_size); + if (tmp == NULL) { + if (verbose) { + printf("Failed to allocate memory for unchunked body\n"); + } + return NULL; + } + } + + memcpy(result_ptr, start_of_chunk, size_of_chunk); + result_ptr = result_ptr + size_of_chunk; + } + + return result +} + /* per RFC 2396 */ #define URI_HTTP "%5[HTPShtps]" #define URI_HOST \ -- cgit v1.2.3-74-g34f1 From 48d6ef2557605d9815e242c4a4f19c0dcdc37c28 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 14 Nov 2022 00:32:44 +0100 Subject: Undo sorting of header file includes, it breaks the build --- plugins/check_http.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index 5710cfe1..5e4536e4 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -35,8 +35,10 @@ const char *progname = "check_http"; const char *copyright = "1999-2022"; const char *email = "devel@monitoring-plugins.org"; -#include "base64.h" +// Do NOT sort those headers, it will break the build +// TODO: Fix this #include "common.h" +#include "base64.h" #include "netutils.h" #include "utils.h" #include -- cgit v1.2.3-74-g34f1 From 1ac8f35301db3a5e3e77c06e487a28365c546e3f Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 14 Nov 2022 00:33:26 +0100 Subject: Fix type of unchunk_content function declaration --- plugins/check_http.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index 5e4536e4..3e021c56 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -148,7 +148,7 @@ char *perfd_time_transfer(double microsec); char *perfd_size(int page_len); void print_help(void); void print_usage(void); -char *unchunk_content(char *content); +char *unchunk_content(const char *content); int main(int argc, char **argv) { int result = STATE_UNKNOWN; -- cgit v1.2.3-74-g34f1 From 3e63e61f6ae062fd1e8c8c962c0bb603cf88856c Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 14 Nov 2022 00:34:13 +0100 Subject: Fix chunked header detection regex --- plugins/check_http.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index 3e021c56..1f7bd0b3 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -1257,10 +1257,10 @@ int check_http(void) { // At this point we should test if the content is chunked and unchunk it, so // it can be searched (and possibly printed) - const char *chunked_header_regex_string = "Transfer-Encoding:\\s*chunked\\s*"CRLF; + const char *chunked_header_regex_string = "Transfer-Encoding: *chunked *"; regex_t chunked_header_regex; - if (regcomp(&chunked_header_regex, chunked_header_regex_string, 0)) { + if (regcomp(&chunked_header_regex, chunked_header_regex_string, REG_ICASE)) { die(STATE_UNKNOWN, "HTTP %s: %s\n", state_text(STATE_UNKNOWN), "Failed to compile chunked_header_regex regex"); } -- cgit v1.2.3-74-g34f1 From 029168276fc3a02daa676c4fcc7a597e3319929a Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 14 Nov 2022 00:35:19 +0100 Subject: Fix several bug in the implementation of unchunking --- plugins/check_http.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index 1f7bd0b3..d5b6b374 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -1267,11 +1267,15 @@ int check_http(void) { regmatch_t chre_pmatch[1]; // We actually do not care about this, since we only want to know IF it was found if (regexec(&chunked_header_regex, header, 1, chre_pmatch, 0) == 0) { + if (verbose) { + printf("Found chunked content\n"); + } // We actually found the chunked header char *tmp = unchunk_content(page); if (tmp == NULL) { die(STATE_UNKNOWN, "HTTP %s: %s\n", state_text(STATE_UNKNOWN), "Failed to unchunk message body"); } + page = tmp; } if (strlen(string_expect) > 0) { @@ -1374,9 +1378,10 @@ char *unchunk_content(const char *content) { // https://www.rfc-editor.org/rfc/rfc7230#section-4.1 char *result = NULL; size_t content_length = strlen(content); - char *start_of_chunk, end_of_chunk; + char *start_of_chunk; + char* end_of_chunk; long size_of_chunk; - char *pointer = content; + const char *pointer = content; char *endptr; long length_of_chunk = 0; size_t overall_size = 0; @@ -1396,13 +1401,12 @@ char *unchunk_content(const char *content) { if (verbose) { printf("Chunked content did not start with a number at all (Line: %u)\n", __LINE__); } - return NULL + return NULL; } // So, we got the length of the chunk if (*endptr == ';') { // Chunk extension starts here - // TODO while (*endptr != '\r') { endptr++; } @@ -1410,7 +1414,8 @@ char *unchunk_content(const char *content) { start_of_chunk = endptr + 2; end_of_chunk = start_of_chunk + size_of_chunk; - length_of_chunk = end_of_chunk - start_of_chunk; + length_of_chunk = (long)(end_of_chunk - start_of_chunk); + pointer = end_of_chunk + 2; //Next number should be here if (length_of_chunk == 0) { // Chunk length is 0, so this is the last one @@ -1442,7 +1447,8 @@ char *unchunk_content(const char *content) { result_ptr = result_ptr + size_of_chunk; } - return result + result[overall_size] = '\0'; + return result; } /* per RFC 2396 */ -- cgit v1.2.3-74-g34f1 From 67d10625307a1bcd5def7cc298314706cef78182 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 22 Dec 2022 11:40:19 +0100 Subject: Undo clang formatting --- plugins/check_http.c | 1635 ++++++++++++++++++++++++-------------------------- 1 file changed, 790 insertions(+), 845 deletions(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index d5b6b374..dbaa0d78 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -1,35 +1,35 @@ /***************************************************************************** - * - * Monitoring check_http plugin - * - * License: GPL - * Copyright (c) 1999-2013 Monitoring Plugins Development Team - * - * Description: - * - * This file contains the check_http plugin - * - * This plugin tests the HTTP service on the specified host. It can test - * normal (http) and secure (https) servers, follow redirects, search for - * strings and regular expressions, check connection times, and report on - * certificate expiration times. - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - * - *****************************************************************************/ +* +* Monitoring check_http plugin +* +* License: GPL +* Copyright (c) 1999-2013 Monitoring Plugins Development Team +* +* Description: +* +* This file contains the check_http plugin +* +* This plugin tests the HTTP service on the specified host. It can test +* normal (http) and secure (https) servers, follow redirects, search for +* strings and regular expressions, check connection times, and report on +* certificate expiration times. +* +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see . +* +* +*****************************************************************************/ const char *progname = "check_http"; const char *copyright = "1999-2022"; @@ -41,6 +41,7 @@ const char *email = "devel@monitoring-plugins.org"; #include "base64.h" #include "netutils.h" #include "utils.h" +#include "base64.h" #include #define STICKY_NONE 0 @@ -63,18 +64,19 @@ int ssl_version = 0; int days_till_exp_warn, days_till_exp_crit; char *randbuff; X509 *server_cert; -#define my_recv(buf, len) \ - ((use_ssl) ? np_net_ssl_read(buf, len) : read(sd, buf, len)) -#define my_send(buf, len) \ - ((use_ssl) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0)) +# define my_recv(buf, len) ((use_ssl) ? np_net_ssl_read(buf, len) : read(sd, buf, len)) +# define my_send(buf, len) ((use_ssl) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0)) #else /* ifndef HAVE_SSL */ -#define my_recv(buf, len) read(sd, buf, len) -#define my_send(buf, len) send(sd, buf, len, 0) +# define my_recv(buf, len) read(sd, buf, len) +# define my_send(buf, len) send(sd, buf, len, 0) #endif /* HAVE_SSL */ bool no_body = false; int maximum_age = -1; -enum { REGS = 2, MAX_RE_SIZE = 1024 }; +enum { + REGS = 2, + MAX_RE_SIZE = 1024 +}; #include "regex.h" regex_t preg; regmatch_t pmatch[REGS]; @@ -134,68 +136,72 @@ char *client_cert = NULL; char *client_privkey = NULL; // Forward function declarations -bool process_arguments(int, char **); -int check_http(void); -void redir(char *pos, char *status_line); +bool process_arguments (int, char **); +int check_http (void); +void redir (char *pos, char *status_line); bool server_type_check(const char *type); int server_port_check(int ssl_flag); -char *perfd_time(double microsec); -char *perfd_time_connect(double microsec); -char *perfd_time_ssl(double microsec); -char *perfd_time_firstbyte(double microsec); -char *perfd_time_headers(double microsec); -char *perfd_time_transfer(double microsec); -char *perfd_size(int page_len); -void print_help(void); -void print_usage(void); +char *perfd_time (double microsec); +char *perfd_time_connect (double microsec); +char *perfd_time_ssl (double microsec); +char *perfd_time_firstbyte (double microsec); +char *perfd_time_headers (double microsec); +char *perfd_time_transfer (double microsec); +char *perfd_size (int page_len); +void print_help (void); +void print_usage (void); char *unchunk_content(const char *content); -int main(int argc, char **argv) { +int +main (int argc, char **argv) +{ int result = STATE_UNKNOWN; - setlocale(LC_ALL, ""); - bindtextdomain(PACKAGE, LOCALEDIR); - textdomain(PACKAGE); + setlocale (LC_ALL, ""); + bindtextdomain (PACKAGE, LOCALEDIR); + textdomain (PACKAGE); - /* Set default URL. Must be malloced for subsequent realloc if - * --onredirect=follow */ + /* Set default URL. Must be malloced for subsequent realloc if --onredirect=follow */ server_url = strdup(HTTP_URL); server_url_length = strlen(server_url); - xasprintf(&user_agent, "User-Agent: check_http/v%s (monitoring-plugins %s)", + xasprintf (&user_agent, "User-Agent: check_http/v%s (monitoring-plugins %s)", NP_VERSION, VERSION); /* Parse extra opts if any */ - argv = np_extra_opts(&argc, argv, progname); + argv=np_extra_opts (&argc, argv, progname); - if (process_arguments(argc, argv) == false) - usage4(_("Could not parse arguments")); + if (process_arguments (argc, argv) == false) + usage4 (_("Could not parse arguments")); if (display_html == true) - printf("", - use_ssl ? "https" : "http", host_name ? host_name : server_address, - server_port, server_url); + printf ("", + use_ssl ? "https" : "http", host_name ? host_name : server_address, + server_port, server_url); /* initialize alarm signal handling, set socket timeout, start timer */ - (void)signal(SIGALRM, socket_timeout_alarm_handler); - (void)alarm(socket_timeout); - gettimeofday(&tv, NULL); + (void) signal (SIGALRM, socket_timeout_alarm_handler); + (void) alarm (socket_timeout); + gettimeofday (&tv, NULL); - result = check_http(); + result = check_http (); return result; } /* check whether a file exists */ -void test_file(char *path) { +void +test_file (char *path) +{ if (access(path, R_OK) == 0) return; - usage2(_("file does not exist or is not readable"), path); + usage2 (_("file does not exist or is not readable"), path); } /* * process command-line arguments * returns true on succes, false otherwise - */ -bool process_arguments(int argc, char **argv) { + */ +bool process_arguments (int argc, char **argv) +{ int c = 1; char *p; char *temp; @@ -209,85 +215,83 @@ bool process_arguments(int argc, char **argv) { int option = 0; static struct option longopts[] = { - STD_LONG_OPTS, - {"link", no_argument, 0, 'L'}, - {"nohtml", no_argument, 0, 'n'}, - {"ssl", optional_argument, 0, 'S'}, - {"sni", no_argument, 0, SNI_OPTION}, - {"post", required_argument, 0, 'P'}, - {"method", required_argument, 0, 'j'}, - {"IP-address", required_argument, 0, 'I'}, - {"url", required_argument, 0, 'u'}, - {"port", required_argument, 0, 'p'}, - {"authorization", required_argument, 0, 'a'}, - {"proxy-authorization", required_argument, 0, 'b'}, - {"header-string", required_argument, 0, 'd'}, - {"string", required_argument, 0, 's'}, - {"expect", required_argument, 0, 'e'}, - {"regex", required_argument, 0, 'r'}, - {"ereg", required_argument, 0, 'r'}, - {"eregi", required_argument, 0, 'R'}, - {"linespan", no_argument, 0, 'l'}, - {"onredirect", required_argument, 0, 'f'}, - {"certificate", required_argument, 0, 'C'}, - {"client-cert", required_argument, 0, 'J'}, - {"private-key", required_argument, 0, 'K'}, - {"continue-after-certificate", no_argument, 0, CONTINUE_AFTER_CHECK_CERT}, - {"useragent", required_argument, 0, 'A'}, - {"header", required_argument, 0, 'k'}, - {"no-body", no_argument, 0, 'N'}, - {"max-age", required_argument, 0, 'M'}, - {"content-type", required_argument, 0, 'T'}, - {"pagesize", required_argument, 0, 'm'}, - {"invert-regex", no_argument, NULL, INVERT_REGEX}, - {"use-ipv4", no_argument, 0, '4'}, - {"use-ipv6", no_argument, 0, '6'}, - {"extended-perfdata", no_argument, 0, 'E'}, - {"show-body", no_argument, 0, 'B'}, - {"max-redirs", required_argument, 0, MAX_REDIRS_OPTION}, - {0, 0, 0, 0}}; + STD_LONG_OPTS, + {"link", no_argument, 0, 'L'}, + {"nohtml", no_argument, 0, 'n'}, + {"ssl", optional_argument, 0, 'S'}, + {"sni", no_argument, 0, SNI_OPTION}, + {"post", required_argument, 0, 'P'}, + {"method", required_argument, 0, 'j'}, + {"IP-address", required_argument, 0, 'I'}, + {"url", required_argument, 0, 'u'}, + {"port", required_argument, 0, 'p'}, + {"authorization", required_argument, 0, 'a'}, + {"proxy-authorization", required_argument, 0, 'b'}, + {"header-string", required_argument, 0, 'd'}, + {"string", required_argument, 0, 's'}, + {"expect", required_argument, 0, 'e'}, + {"regex", required_argument, 0, 'r'}, + {"ereg", required_argument, 0, 'r'}, + {"eregi", required_argument, 0, 'R'}, + {"linespan", no_argument, 0, 'l'}, + {"onredirect", required_argument, 0, 'f'}, + {"certificate", required_argument, 0, 'C'}, + {"client-cert", required_argument, 0, 'J'}, + {"private-key", required_argument, 0, 'K'}, + {"continue-after-certificate", no_argument, 0, CONTINUE_AFTER_CHECK_CERT}, + {"useragent", required_argument, 0, 'A'}, + {"header", required_argument, 0, 'k'}, + {"no-body", no_argument, 0, 'N'}, + {"max-age", required_argument, 0, 'M'}, + {"content-type", required_argument, 0, 'T'}, + {"pagesize", required_argument, 0, 'm'}, + {"invert-regex", no_argument, NULL, INVERT_REGEX}, + {"use-ipv4", no_argument, 0, '4'}, + {"use-ipv6", no_argument, 0, '6'}, + {"extended-perfdata", no_argument, 0, 'E'}, + {"show-body", no_argument, 0, 'B'}, + {"max-redirs", required_argument, 0, MAX_REDIRS_OPTION}, + {0, 0, 0, 0} + }; if (argc < 2) return false; for (c = 1; c < argc; c++) { - if (strcmp("-to", argv[c]) == 0) - strcpy(argv[c], "-t"); - if (strcmp("-hn", argv[c]) == 0) - strcpy(argv[c], "-H"); - if (strcmp("-wt", argv[c]) == 0) - strcpy(argv[c], "-w"); - if (strcmp("-ct", argv[c]) == 0) - strcpy(argv[c], "-c"); - if (strcmp("-nohtml", argv[c]) == 0) - strcpy(argv[c], "-n"); + if (strcmp ("-to", argv[c]) == 0) + strcpy (argv[c], "-t"); + if (strcmp ("-hn", argv[c]) == 0) + strcpy (argv[c], "-H"); + if (strcmp ("-wt", argv[c]) == 0) + strcpy (argv[c], "-w"); + if (strcmp ("-ct", argv[c]) == 0) + strcpy (argv[c], "-c"); + if (strcmp ("-nohtml", argv[c]) == 0) + strcpy (argv[c], "-n"); } while (1) { - c = getopt_long( - argc, argv, - "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:d:e:p:s:R:r:u:f:C:J:K:nlLS::m:M:NEB", - longopts, &option); + c = getopt_long (argc, argv, "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:d:e:p:s:R:r:u:f:C:J:K:nlLS::m:M:NEB", longopts, &option); if (c == -1 || c == EOF) break; switch (c) { case '?': /* usage */ - usage5(); + usage5 (); break; case 'h': /* help */ - print_help(); - exit(STATE_UNKNOWN); + print_help (); + exit (STATE_UNKNOWN); break; case 'V': /* version */ - print_revision(progname, NP_VERSION); - exit(STATE_UNKNOWN); + print_revision (progname, NP_VERSION); + exit (STATE_UNKNOWN); break; case 't': /* timeout period */ - if (!is_intnonneg(optarg)) - usage2(_("Timeout interval must be a positive integer"), optarg); + if (!is_intnonneg (optarg)) + usage2 (_("Timeout interval must be a positive integer"), optarg); else - socket_timeout = atoi(optarg); + socket_timeout = atoi (optarg); break; case 'c': /* critical time threshold */ critical_thresholds = optarg; @@ -296,14 +300,13 @@ bool process_arguments(int argc, char **argv) { warning_thresholds = optarg; break; case 'A': /* User Agent String */ - xasprintf(&user_agent, "User-Agent: %s", optarg); + xasprintf (&user_agent, "User-Agent: %s", optarg); break; case 'k': /* Additional headers */ if (http_opt_headers_count == 0) - http_opt_headers = malloc(sizeof(char *) * (++http_opt_headers_count)); + http_opt_headers = malloc (sizeof (char *) * (++http_opt_headers_count)); else - http_opt_headers = realloc(http_opt_headers, - sizeof(char *) * (++http_opt_headers_count)); + http_opt_headers = realloc (http_opt_headers, sizeof (char *) * (++http_opt_headers_count)); http_opt_headers[http_opt_headers_count - 1] = optarg; /* xasprintf (&http_opt_headers, "%s", optarg); */ break; @@ -315,27 +318,27 @@ bool process_arguments(int argc, char **argv) { break; case 'C': /* Check SSL cert validity */ #ifdef HAVE_SSL - if ((temp = strchr(optarg, ',')) != NULL) { - *temp = '\0'; - if (!is_intnonneg(optarg)) - usage2(_("Invalid certificate expiration period"), optarg); + if ((temp=strchr(optarg,','))!=NULL) { + *temp='\0'; + if (!is_intnonneg (optarg)) + usage2 (_("Invalid certificate expiration period"), optarg); days_till_exp_warn = atoi(optarg); - *temp = ','; + *temp=','; temp++; - if (!is_intnonneg(temp)) - usage2(_("Invalid certificate expiration period"), temp); - days_till_exp_crit = atoi(temp); - } else { - days_till_exp_crit = 0; - if (!is_intnonneg(optarg)) - usage2(_("Invalid certificate expiration period"), optarg); - days_till_exp_warn = atoi(optarg); + if (!is_intnonneg (temp)) + usage2 (_("Invalid certificate expiration period"), temp); + days_till_exp_crit = atoi (temp); + } + else { + days_till_exp_crit=0; + if (!is_intnonneg (optarg)) + usage2 (_("Invalid certificate expiration period"), optarg); + days_till_exp_warn = atoi (optarg); } check_cert = true; goto enable_ssl; #endif - case CONTINUE_AFTER_CHECK_CERT: /* don't stop after the certificate is - checked */ + case CONTINUE_AFTER_CHECK_CERT: /* don't stop after the certificate is checked */ #ifdef HAVE_SSL continue_after_check_cert = true; break; @@ -355,16 +358,15 @@ bool process_arguments(int argc, char **argv) { case 'S': /* use SSL */ #ifdef HAVE_SSL enable_ssl: - /* ssl_version initialized to 0 as a default. Only set if it's non-zero. - This helps when we include multiple parameters, like -S and -C - combinations */ + /* ssl_version initialized to 0 as a default. Only set if it's non-zero. This helps when we include multiple + parameters, like -S and -C combinations */ use_ssl = true; - if (c == 'S' && optarg != NULL) { + if (c=='S' && optarg != NULL) { int got_plus = strchr(optarg, '+') != NULL; - if (!strncmp(optarg, "1.2", 3)) + if (!strncmp (optarg, "1.2", 3)) ssl_version = got_plus ? MP_TLSv1_2_OR_NEWER : MP_TLSv1_2; - else if (!strncmp(optarg, "1.1", 3)) + else if (!strncmp (optarg, "1.1", 3)) ssl_version = got_plus ? MP_TLSv1_1_OR_NEWER : MP_TLSv1_1; else if (optarg[0] == '1') ssl_version = got_plus ? MP_TLSv1_OR_NEWER : MP_TLSv1; @@ -373,104 +375,101 @@ bool process_arguments(int argc, char **argv) { else if (optarg[0] == '2') ssl_version = got_plus ? MP_SSLv2_OR_NEWER : MP_SSLv2; else - usage4(_("Invalid option - Valid SSL/TLS versions: 2, 3, 1, 1.1, 1.2 " - "(with optional '+' suffix)")); + usage4 (_("Invalid option - Valid SSL/TLS versions: 2, 3, 1, 1.1, 1.2 (with optional '+' suffix)")); } if (specify_port == false) server_port = HTTPS_PORT; #else /* -C -J and -K fall through to here without SSL */ - usage4(_("Invalid option - SSL is not available")); + usage4 (_("Invalid option - SSL is not available")); #endif break; case SNI_OPTION: use_sni = true; break; case MAX_REDIRS_OPTION: - if (!is_intnonneg(optarg)) - usage2(_("Invalid max_redirs count"), optarg); + if (!is_intnonneg (optarg)) + usage2 (_("Invalid max_redirs count"), optarg); else { - max_depth = atoi(optarg); + max_depth = atoi (optarg); } - break; + break; case 'f': /* onredirect */ - if (!strcmp(optarg, "stickyport")) - onredirect = STATE_DEPENDENT, followsticky = STICKY_HOST | STICKY_PORT; - else if (!strcmp(optarg, "sticky")) + if (!strcmp (optarg, "stickyport")) + onredirect = STATE_DEPENDENT, followsticky = STICKY_HOST|STICKY_PORT; + else if (!strcmp (optarg, "sticky")) onredirect = STATE_DEPENDENT, followsticky = STICKY_HOST; - else if (!strcmp(optarg, "follow")) + else if (!strcmp (optarg, "follow")) onredirect = STATE_DEPENDENT, followsticky = STICKY_NONE; - else if (!strcmp(optarg, "unknown")) + else if (!strcmp (optarg, "unknown")) onredirect = STATE_UNKNOWN; - else if (!strcmp(optarg, "ok")) + else if (!strcmp (optarg, "ok")) onredirect = STATE_OK; - else if (!strcmp(optarg, "warning")) + else if (!strcmp (optarg, "warning")) onredirect = STATE_WARNING; - else if (!strcmp(optarg, "critical")) + else if (!strcmp (optarg, "critical")) onredirect = STATE_CRITICAL; - else - usage2(_("Invalid onredirect option"), optarg); + else usage2 (_("Invalid onredirect option"), optarg); if (verbose) printf(_("option f:%d \n"), onredirect); break; /* Note: H, I, and u must be malloc'd or will fail on redirects */ case 'H': /* Host Name (virtual host) */ - host_name = strdup(optarg); + host_name = strdup (optarg); if (host_name[0] == '[') { - if ((p = strstr(host_name, "]:")) != NULL) { /* [IPv6]:port */ - virtual_port = atoi(p + 2); + if ((p = strstr (host_name, "]:")) != NULL) { /* [IPv6]:port */ + virtual_port = atoi (p + 2); /* cut off the port */ - host_name_length = strlen(host_name) - strlen(p) - 1; - free(host_name); - host_name = strndup(optarg, host_name_length); + host_name_length = strlen (host_name) - strlen (p) - 1; + free (host_name); + host_name = strndup (optarg, host_name_length); + if (specify_port == false) + server_port = virtual_port; + } + } else if ((p = strchr (host_name, ':')) != NULL + && strchr (++p, ':') == NULL) { /* IPv4:port or host:port */ + virtual_port = atoi (p); + /* cut off the port */ + host_name_length = strlen (host_name) - strlen (p) - 1; + free (host_name); + host_name = strndup (optarg, host_name_length); if (specify_port == false) server_port = virtual_port; } - } else if ((p = strchr(host_name, ':')) != NULL && - strchr(++p, ':') == NULL) { /* IPv4:port or host:port */ - virtual_port = atoi(p); - /* cut off the port */ - host_name_length = strlen(host_name) - strlen(p) - 1; - free(host_name); - host_name = strndup(optarg, host_name_length); - if (specify_port == false) - server_port = virtual_port; - } break; case 'I': /* Server IP-address */ - server_address = strdup(optarg); + server_address = strdup (optarg); break; case 'u': /* URL path */ - server_url = strdup(optarg); - server_url_length = strlen(server_url); + server_url = strdup (optarg); + server_url_length = strlen (server_url); break; case 'p': /* Server port */ - if (!is_intnonneg(optarg)) - usage2(_("Invalid port number"), optarg); + if (!is_intnonneg (optarg)) + usage2 (_("Invalid port number"), optarg); else { - server_port = atoi(optarg); + server_port = atoi (optarg); specify_port = true; } break; case 'a': /* authorization info */ - strncpy(user_auth, optarg, MAX_INPUT_BUFFER - 1); + strncpy (user_auth, optarg, MAX_INPUT_BUFFER - 1); user_auth[MAX_INPUT_BUFFER - 1] = 0; break; case 'b': /* proxy-authorization info */ - strncpy(proxy_auth, optarg, MAX_INPUT_BUFFER - 1); + strncpy (proxy_auth, optarg, MAX_INPUT_BUFFER - 1); proxy_auth[MAX_INPUT_BUFFER - 1] = 0; break; - case 'P': /* HTTP POST data in URL encoded format; ignored if settings - already */ - if (!http_post_data) - http_post_data = strdup(optarg); - if (!http_method) + case 'P': /* HTTP POST data in URL encoded format; ignored if settings already */ + if (! http_post_data) + http_post_data = strdup (optarg); + if (! http_method) http_method = strdup("POST"); break; case 'j': /* Set HTTP method */ if (http_method) free(http_method); - http_method = strdup(optarg); + http_method = strdup (optarg); char *tmp; if ((tmp = strstr(http_method, ":")) > 0) { tmp[0] = '\0'; @@ -479,20 +478,20 @@ bool process_arguments(int argc, char **argv) { } break; case 'd': /* string or substring */ - strncpy(header_expect, optarg, MAX_INPUT_BUFFER - 1); + strncpy (header_expect, optarg, MAX_INPUT_BUFFER - 1); header_expect[MAX_INPUT_BUFFER - 1] = 0; break; case 's': /* string or substring */ - strncpy(string_expect, optarg, MAX_INPUT_BUFFER - 1); + strncpy (string_expect, optarg, MAX_INPUT_BUFFER - 1); string_expect[MAX_INPUT_BUFFER - 1] = 0; break; case 'e': /* string or substring */ - strncpy(server_expect, optarg, MAX_INPUT_BUFFER - 1); + strncpy (server_expect, optarg, MAX_INPUT_BUFFER - 1); server_expect[MAX_INPUT_BUFFER - 1] = 0; server_expect_yn = 1; break; case 'T': /* Content-type */ - xasprintf(&http_content_type, "%s", optarg); + xasprintf (&http_content_type, "%s", optarg); break; case 'l': /* linespan */ cflags &= ~REG_NEWLINE; @@ -500,12 +499,12 @@ bool process_arguments(int argc, char **argv) { case 'R': /* regex */ cflags |= REG_ICASE; case 'r': /* regex */ - strncpy(regexp, optarg, MAX_RE_SIZE - 1); + strncpy (regexp, optarg, MAX_RE_SIZE - 1); regexp[MAX_RE_SIZE - 1] = 0; - errcode = regcomp(&preg, regexp, cflags); + errcode = regcomp (&preg, regexp, cflags); if (errcode != 0) { - (void)regerror(errcode, &preg, errbuf, MAX_INPUT_BUFFER); - printf(_("Could Not Compile Regular Expression: %s"), errbuf); + (void) regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); + printf (_("Could Not Compile Regular Expression: %s"), errbuf); return false; } break; @@ -519,53 +518,55 @@ bool process_arguments(int argc, char **argv) { #ifdef USE_IPV6 address_family = AF_INET6; #else - usage4(_("IPv6 support not available")); + usage4 (_("IPv6 support not available")); #endif break; case 'v': /* verbose */ verbose = true; break; case 'm': /* min_page_length */ - { + { char *tmp; if (strchr(optarg, ':') != (char *)NULL) { /* range, so get two values, min:max */ tmp = strtok(optarg, ":"); if (tmp == NULL) { printf("Bad format: try \"-m min:max\"\n"); - exit(STATE_WARNING); + exit (STATE_WARNING); } else min_page_len = atoi(tmp); tmp = strtok(NULL, ":"); if (tmp == NULL) { printf("Bad format: try \"-m min:max\"\n"); - exit(STATE_WARNING); + exit (STATE_WARNING); } else max_page_len = atoi(tmp); } else - min_page_len = atoi(optarg); + min_page_len = atoi (optarg); break; - } + } case 'N': /* no-body */ no_body = true; break; case 'M': /* max-age */ - { - int L = strlen(optarg); - if (L && optarg[L - 1] == 'm') - maximum_age = atoi(optarg) * 60; - else if (L && optarg[L - 1] == 'h') - maximum_age = atoi(optarg) * 60 * 60; - else if (L && optarg[L - 1] == 'd') - maximum_age = atoi(optarg) * 60 * 60 * 24; - else if (L && (optarg[L - 1] == 's' || isdigit(optarg[L - 1]))) - maximum_age = atoi(optarg); - else { - fprintf(stderr, "unparsable max-age: %s\n", optarg); - exit(STATE_WARNING); - } - } break; + { + int L = strlen(optarg); + if (L && optarg[L-1] == 'm') + maximum_age = atoi (optarg) * 60; + else if (L && optarg[L-1] == 'h') + maximum_age = atoi (optarg) * 60 * 60; + else if (L && optarg[L-1] == 'd') + maximum_age = atoi (optarg) * 60 * 60 * 24; + else if (L && (optarg[L-1] == 's' || + isdigit (optarg[L-1]))) + maximum_age = atoi (optarg); + else { + fprintf (stderr, "unparsable max-age: %s\n", optarg); + exit (STATE_WARNING); + } + } + break; case 'E': /* show extended perfdata */ show_extended_perfdata = true; break; @@ -578,32 +579,31 @@ bool process_arguments(int argc, char **argv) { c = optind; if (server_address == NULL && c < argc) - server_address = strdup(argv[c++]); + server_address = strdup (argv[c++]); if (host_name == NULL && c < argc) - host_name = strdup(argv[c++]); + host_name = strdup (argv[c++]); if (server_address == NULL) { if (host_name == NULL) - usage4(_("You must specify a server address or host name")); + usage4 (_("You must specify a server address or host name")); else - server_address = strdup(host_name); + server_address = strdup (host_name); } set_thresholds(&thlds, warning_thresholds, critical_thresholds); - if (critical_thresholds && thlds->critical->end > (double)socket_timeout) + if (critical_thresholds && thlds->critical->end>(double)socket_timeout) socket_timeout = (int)thlds->critical->end + 1; if (http_method == NULL) - http_method = strdup("GET"); + http_method = strdup ("GET"); if (http_method_proxy == NULL) - http_method_proxy = strdup("GET"); + http_method_proxy = strdup ("GET"); if (client_cert && !client_privkey) - usage4(_("If you use a client certificate you must also specify a private " - "key file")); + usage4 (_("If you use a client certificate you must also specify a private key file")); if (virtual_port == 0) virtual_port = server_port; @@ -611,68 +611,89 @@ bool process_arguments(int argc, char **argv) { return true; } + + /* Returns 1 if we're done processing the document body; 0 to keep going */ -static int document_headers_done(char *full_page) { +static int +document_headers_done (char *full_page) +{ const char *body; for (body = full_page; *body; body++) { - if (!strncmp(body, "\n\n", 2) || !strncmp(body, "\n\r\n", 3)) + if (!strncmp (body, "\n\n", 2) || !strncmp (body, "\n\r\n", 3)) break; } if (!*body) - return 0; /* haven't read end of headers yet */ + return 0; /* haven't read end of headers yet */ full_page[body - full_page] = 0; return 1; } -static time_t parse_time_string(const char *string) { +static time_t +parse_time_string (const char *string) +{ struct tm tm; time_t t; - memset(&tm, 0, sizeof(tm)); + memset (&tm, 0, sizeof(tm)); /* Like this: Tue, 25 Dec 2001 02:59:03 GMT */ - if (isupper(string[0]) && /* Tue */ - islower(string[1]) && islower(string[2]) && ',' == string[3] && - ' ' == string[4] && (isdigit(string[5]) || string[5] == ' ') && /* 25 */ - isdigit(string[6]) && ' ' == string[7] && isupper(string[8]) && /* Dec */ - islower(string[9]) && islower(string[10]) && ' ' == string[11] && - isdigit(string[12]) && /* 2001 */ - isdigit(string[13]) && isdigit(string[14]) && isdigit(string[15]) && - ' ' == string[16] && isdigit(string[17]) && /* 02: */ - isdigit(string[18]) && ':' == string[19] && - isdigit(string[20]) && /* 59: */ - isdigit(string[21]) && ':' == string[22] && - isdigit(string[23]) && /* 03 */ - isdigit(string[24]) && ' ' == string[25] && 'G' == string[26] && /* GMT */ - 'M' == string[27] && /* GMT */ - 'T' == string[28]) { - - tm.tm_sec = 10 * (string[23] - '0') + (string[24] - '0'); - tm.tm_min = 10 * (string[20] - '0') + (string[21] - '0'); - tm.tm_hour = 10 * (string[17] - '0') + (string[18] - '0'); - tm.tm_mday = - 10 * (string[5] == ' ' ? 0 : string[5] - '0') + (string[6] - '0'); - tm.tm_mon = (!strncmp(string + 8, "Jan", 3) ? 0 - : !strncmp(string + 8, "Feb", 3) ? 1 - : !strncmp(string + 8, "Mar", 3) ? 2 - : !strncmp(string + 8, "Apr", 3) ? 3 - : !strncmp(string + 8, "May", 3) ? 4 - : !strncmp(string + 8, "Jun", 3) ? 5 - : !strncmp(string + 8, "Jul", 3) ? 6 - : !strncmp(string + 8, "Aug", 3) ? 7 - : !strncmp(string + 8, "Sep", 3) ? 8 - : !strncmp(string + 8, "Oct", 3) ? 9 - : !strncmp(string + 8, "Nov", 3) ? 10 - : !strncmp(string + 8, "Dec", 3) ? 11 - : -1); - tm.tm_year = ((1000 * (string[12] - '0') + 100 * (string[13] - '0') + - 10 * (string[14] - '0') + (string[15] - '0')) - - 1900); - - tm.tm_isdst = 0; /* GMT is never in DST, right? */ + if (isupper (string[0]) && /* Tue */ + islower (string[1]) && + islower (string[2]) && + ',' == string[3] && + ' ' == string[4] && + (isdigit(string[5]) || string[5] == ' ') && /* 25 */ + isdigit (string[6]) && + ' ' == string[7] && + isupper (string[8]) && /* Dec */ + islower (string[9]) && + islower (string[10]) && + ' ' == string[11] && + isdigit (string[12]) && /* 2001 */ + isdigit (string[13]) && + isdigit (string[14]) && + isdigit (string[15]) && + ' ' == string[16] && + isdigit (string[17]) && /* 02: */ + isdigit (string[18]) && + ':' == string[19] && + isdigit (string[20]) && /* 59: */ + isdigit (string[21]) && + ':' == string[22] && + isdigit (string[23]) && /* 03 */ + isdigit (string[24]) && + ' ' == string[25] && + 'G' == string[26] && /* GMT */ + 'M' == string[27] && /* GMT */ + 'T' == string[28]) { + + tm.tm_sec = 10 * (string[23]-'0') + (string[24]-'0'); + tm.tm_min = 10 * (string[20]-'0') + (string[21]-'0'); + tm.tm_hour = 10 * (string[17]-'0') + (string[18]-'0'); + tm.tm_mday = 10 * (string[5] == ' ' ? 0 : string[5]-'0') + (string[6]-'0'); + tm.tm_mon = (!strncmp (string+8, "Jan", 3) ? 0 : + !strncmp (string+8, "Feb", 3) ? 1 : + !strncmp (string+8, "Mar", 3) ? 2 : + !strncmp (string+8, "Apr", 3) ? 3 : + !strncmp (string+8, "May", 3) ? 4 : + !strncmp (string+8, "Jun", 3) ? 5 : + !strncmp (string+8, "Jul", 3) ? 6 : + !strncmp (string+8, "Aug", 3) ? 7 : + !strncmp (string+8, "Sep", 3) ? 8 : + !strncmp (string+8, "Oct", 3) ? 9 : + !strncmp (string+8, "Nov", 3) ? 10 : + !strncmp (string+8, "Dec", 3) ? 11 : + -1); + tm.tm_year = ((1000 * (string[12]-'0') + + 100 * (string[13]-'0') + + 10 * (string[14]-'0') + + (string[15]-'0')) + - 1900); + + tm.tm_isdst = 0; /* GMT is never in DST, right? */ if (tm.tm_mon < 0 || tm.tm_mday < 1 || tm.tm_mday > 31) return 0; @@ -684,15 +705,14 @@ static time_t parse_time_string(const char *string) { so it doesn't matter what time zone we parse them in. */ - t = mktime(&tm); - if (t == (time_t)-1) - t = 0; + t = mktime (&tm); + if (t == (time_t) -1) t = 0; if (verbose) { const char *s = string; while (*s && *s != '\r' && *s != '\n') - fputc(*s++, stdout); - printf(" ==> %lu\n", (unsigned long)t); + fputc (*s++, stdout); + printf (" ==> %lu\n", (unsigned long) t); } return t; @@ -703,24 +723,28 @@ static time_t parse_time_string(const char *string) { } /* Checks if the server 'reply' is one of the expected 'statuscodes' */ -static int expected_statuscode(const char *reply, const char *statuscodes) { +static int +expected_statuscode (const char *reply, const char *statuscodes) +{ char *expected, *code; int result = 0; - if ((expected = strdup(statuscodes)) == NULL) - die(STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n")); + if ((expected = strdup (statuscodes)) == NULL) + die (STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n")); - for (code = strtok(expected, ","); code != NULL; code = strtok(NULL, ",")) - if (strstr(reply, code) != NULL) { + for (code = strtok (expected, ","); code != NULL; code = strtok (NULL, ",")) + if (strstr (reply, code) != NULL) { result = 1; break; } - free(expected); + free (expected); return result; } -static int check_document_dates(const char *headers, char **msg) { +static int +check_document_dates (const char *headers, char **msg) +{ const char *s; char *server_date = 0; char *document_date = 0; @@ -748,78 +772,73 @@ static int check_document_dates(const char *headers, char **msg) { s++; /* Process this header. */ - if (value && value > field + 2) { - char *ff = (char *)malloc(value - field); + if (value && value > field+2) { + char *ff = (char *) malloc (value-field); char *ss = ff; - while (field < value - 1) + while (field < value-1) *ss++ = tolower(*field++); *ss++ = 0; - if (!strcmp(ff, "date") || !strcmp(ff, "last-modified")) { + if (!strcmp (ff, "date") || !strcmp (ff, "last-modified")) { const char *e; - while (*value && isspace(*value)) + while (*value && isspace (*value)) value++; for (e = value; *e && *e != '\r' && *e != '\n'; e++) ; - ss = (char *)malloc(e - value + 1); - strncpy(ss, value, e - value); + ss = (char *) malloc (e - value + 1); + strncpy (ss, value, e - value); ss[e - value] = 0; - if (!strcmp(ff, "date")) { - if (server_date) - free(server_date); + if (!strcmp (ff, "date")) { + if (server_date) free (server_date); server_date = ss; } else { - if (document_date) - free(document_date); + if (document_date) free (document_date); document_date = ss; } } - free(ff); + free (ff); } } /* Done parsing the body. Now check the dates we (hopefully) parsed. */ if (!server_date || !*server_date) { - xasprintf(msg, _("%sServer date unknown, "), *msg); + xasprintf (msg, _("%sServer date unknown, "), *msg); date_result = max_state_alt(STATE_UNKNOWN, date_result); } else if (!document_date || !*document_date) { - xasprintf(msg, _("%sDocument modification date unknown, "), *msg); + xasprintf (msg, _("%sDocument modification date unknown, "), *msg); date_result = max_state_alt(STATE_CRITICAL, date_result); } else { - time_t srv_data = parse_time_string(server_date); - time_t doc_data = parse_time_string(document_date); + time_t srv_data = parse_time_string (server_date); + time_t doc_data = parse_time_string (document_date); if (srv_data <= 0) { - xasprintf(msg, _("%sServer date \"%100s\" unparsable, "), *msg, - server_date); + xasprintf (msg, _("%sServer date \"%100s\" unparsable, "), *msg, server_date); date_result = max_state_alt(STATE_CRITICAL, date_result); } else if (doc_data <= 0) { - xasprintf(msg, _("%sDocument date \"%100s\" unparsable, "), *msg, - document_date); + xasprintf (msg, _("%sDocument date \"%100s\" unparsable, "), *msg, document_date); date_result = max_state_alt(STATE_CRITICAL, date_result); } else if (doc_data > srv_data + 30) { - xasprintf(msg, _("%sDocument is %d seconds in the future, "), *msg, - (int)doc_data - (int)srv_data); + xasprintf (msg, _("%sDocument is %d seconds in the future, "), *msg, (int)doc_data - (int)srv_data); date_result = max_state_alt(STATE_CRITICAL, date_result); } else if (doc_data < srv_data - maximum_age) { int n = (srv_data - doc_data); if (n > (60 * 60 * 24 * 2)) { - xasprintf(msg, _("%sLast modified %.1f days ago, "), *msg, - ((float)n) / (60 * 60 * 24)); + xasprintf (msg, _("%sLast modified %.1f days ago, "), *msg, ((float) n) / (60 * 60 * 24)); date_result = max_state_alt(STATE_CRITICAL, date_result); } else { - xasprintf(msg, _("%sLast modified %d:%02d:%02d ago, "), *msg, - n / (60 * 60), (n / 60) % 60, n % 60); + xasprintf (msg, _("%sLast modified %d:%02d:%02d ago, "), *msg, n / (60 * 60), (n / 60) % 60, n % 60); date_result = max_state_alt(STATE_CRITICAL, date_result); } } - free(server_date); - free(document_date); + free (server_date); + free (document_date); } return date_result; } -int get_content_length(const char *headers) { +int +get_content_length (const char *headers) +{ const char *s; int content_length = 0; @@ -845,46 +864,50 @@ int get_content_length(const char *headers) { s++; /* Process this header. */ - if (value && value > field + 2) { - char *ff = (char *)malloc(value - field); + if (value && value > field+2) { + char *ff = (char *) malloc (value-field); char *ss = ff; - while (field < value - 1) + while (field < value-1) *ss++ = tolower(*field++); *ss++ = 0; - if (!strcmp(ff, "content-length")) { + if (!strcmp (ff, "content-length")) { const char *e; - while (*value && isspace(*value)) + while (*value && isspace (*value)) value++; for (e = value; *e && *e != '\r' && *e != '\n'; e++) ; - ss = (char *)malloc(e - value + 1); - strncpy(ss, value, e - value); + ss = (char *) malloc (e - value + 1); + strncpy (ss, value, e - value); ss[e - value] = 0; content_length = atoi(ss); - free(ss); + free (ss); } - free(ff); + free (ff); } } return (content_length); } -char *prepend_slash(char *path) { +char * +prepend_slash (char *path) +{ char *newpath; if (path[0] == '/') return path; - if ((newpath = malloc(strlen(path) + 2)) == NULL) - die(STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n")); + if ((newpath = malloc (strlen(path) + 2)) == NULL) + die (STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n")); newpath[0] = '/'; - strcpy(newpath + 1, path); - free(path); + strcpy (newpath + 1, path); + free (path); return newpath; } -int check_http(void) { +int +check_http (void) +{ char *msg; char *status_line; char *status_code; @@ -915,73 +938,62 @@ int check_http(void) { char *force_host_header = NULL; /* try to connect to the host at the given port number */ - gettimeofday(&tv_temp, NULL); - if (my_tcp_connect(server_address, server_port, &sd) != STATE_OK) - die(STATE_CRITICAL, _("HTTP CRITICAL - Unable to open TCP socket\n")); - microsec_connect = deltime(tv_temp); + gettimeofday (&tv_temp, NULL); + if (my_tcp_connect (server_address, server_port, &sd) != STATE_OK) + die (STATE_CRITICAL, _("HTTP CRITICAL - Unable to open TCP socket\n")); + microsec_connect = deltime (tv_temp); - /* if we are called with the -I option, the -j method is CONNECT and */ - /* we received -S for SSL, then we tunnel the request through a proxy*/ - /* @20100414, public[at]frank4dd.com, http://www.frank4dd.com/howto */ + /* if we are called with the -I option, the -j method is CONNECT and */ + /* we received -S for SSL, then we tunnel the request through a proxy*/ + /* @20100414, public[at]frank4dd.com, http://www.frank4dd.com/howto */ - if (server_address != NULL && strcmp(http_method, "CONNECT") == 0 && - host_name != NULL && use_ssl == true) { + if ( server_address != NULL && strcmp(http_method, "CONNECT") == 0 + && host_name != NULL && use_ssl == true) { - if (verbose) - printf("Entering CONNECT tunnel mode with proxy %s:%d to dst %s:%d\n", - server_address, server_port, host_name, HTTPS_PORT); - asprintf(&buf, "%s %s:%d HTTP/1.1\r\n%s\r\n", http_method, host_name, - HTTPS_PORT, user_agent); + if (verbose) printf ("Entering CONNECT tunnel mode with proxy %s:%d to dst %s:%d\n", server_address, server_port, host_name, HTTPS_PORT); + asprintf (&buf, "%s %s:%d HTTP/1.1\r\n%s\r\n", http_method, host_name, HTTPS_PORT, user_agent); if (strlen(proxy_auth)) { - base64_encode_alloc(proxy_auth, strlen(proxy_auth), &auth); - xasprintf(&buf, "%sProxy-Authorization: Basic %s\r\n", buf, auth); + base64_encode_alloc (proxy_auth, strlen (proxy_auth), &auth); + xasprintf (&buf, "%sProxy-Authorization: Basic %s\r\n", buf, auth); } /* optionally send any other header tag */ if (http_opt_headers_count) { - for (i = 0; i < http_opt_headers_count; i++) { + for (i = 0; i < http_opt_headers_count ; i++) { if (force_host_header != http_opt_headers[i]) { - xasprintf(&buf, "%s%s\r\n", buf, http_opt_headers[i]); + xasprintf (&buf, "%s%s\r\n", buf, http_opt_headers[i]); } } - /* This cannot be free'd here because a redirection will then try to - * access this and segfault */ + /* This cannot be free'd here because a redirection will then try to access this and segfault */ /* Covered in a testcase in tests/check_http.t */ /* free(http_opt_headers); */ } - asprintf(&buf, "%sProxy-Connection: keep-alive\r\n", buf); - asprintf(&buf, "%sHost: %s\r\n", buf, host_name); + asprintf (&buf, "%sProxy-Connection: keep-alive\r\n", buf); + asprintf (&buf, "%sHost: %s\r\n", buf, host_name); /* we finished our request, send empty line with CRLF */ - asprintf(&buf, "%s%s", buf, CRLF); - if (verbose) - printf("%s\n", buf); - send(sd, buf, strlen(buf), 0); - buf[0] = '\0'; - - if (verbose) - printf("Receive response from proxy\n"); - read(sd, buffer, MAX_INPUT_BUFFER - 1); - if (verbose) - printf("%s", buffer); + asprintf (&buf, "%s%s", buf, CRLF); + if (verbose) printf ("%s\n", buf); + send(sd, buf, strlen (buf), 0); + buf[0]='\0'; + + if (verbose) printf ("Receive response from proxy\n"); + read (sd, buffer, MAX_INPUT_BUFFER-1); + if (verbose) printf ("%s", buffer); /* Here we should check if we got HTTP/1.1 200 Connection established */ } #ifdef HAVE_SSL elapsed_time_connect = (double)microsec_connect / 1.0e6; if (use_ssl == true) { - gettimeofday(&tv_temp, NULL); - result = np_net_ssl_init_with_hostname_version_and_cert( - sd, (use_sni ? host_name : NULL), ssl_version, client_cert, - client_privkey); - if (verbose) - printf("SSL initialized\n"); + gettimeofday (&tv_temp, NULL); + result = np_net_ssl_init_with_hostname_version_and_cert(sd, (use_sni ? host_name : NULL), ssl_version, client_cert, client_privkey); + if (verbose) printf ("SSL initialized\n"); if (result != STATE_OK) - die(STATE_CRITICAL, NULL); - microsec_ssl = deltime(tv_temp); + die (STATE_CRITICAL, NULL); + microsec_ssl = deltime (tv_temp); elapsed_time_ssl = (double)microsec_ssl / 1.0e6; if (check_cert == true) { result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit); if (continue_after_check_cert == false) { - if (sd) - close(sd); + if (sd) close(sd); np_net_ssl_cleanup(); return result; } @@ -989,20 +1001,18 @@ int check_http(void) { } #endif /* HAVE_SSL */ - if (server_address != NULL && strcmp(http_method, "CONNECT") == 0 && - host_name != NULL && use_ssl == true) - asprintf(&buf, "%s %s %s\r\n%s\r\n", http_method_proxy, server_url, - host_name ? "HTTP/1.1" : "HTTP/1.0", user_agent); + if ( server_address != NULL && strcmp(http_method, "CONNECT") == 0 + && host_name != NULL && use_ssl == true) + asprintf (&buf, "%s %s %s\r\n%s\r\n", http_method_proxy, server_url, host_name ? "HTTP/1.1" : "HTTP/1.0", user_agent); else - asprintf(&buf, "%s %s %s\r\n%s\r\n", http_method, server_url, - host_name ? "HTTP/1.1" : "HTTP/1.0", user_agent); + asprintf (&buf, "%s %s %s\r\n%s\r\n", http_method, server_url, host_name ? "HTTP/1.1" : "HTTP/1.0", user_agent); /* tell HTTP/1.1 servers not to keep the connection alive */ - xasprintf(&buf, "%sConnection: close\r\n", buf); + xasprintf (&buf, "%sConnection: close\r\n", buf); /* check if Host header is explicitly set in options */ if (http_opt_headers_count) { - for (i = 0; i < http_opt_headers_count; i++) { + for (i = 0; i < http_opt_headers_count ; i++) { if (strncmp(http_opt_headers[i], "Host:", 5) == 0) { force_host_header = http_opt_headers[i]; } @@ -1012,8 +1022,9 @@ int check_http(void) { /* optionally send the host header info */ if (host_name) { if (force_host_header) { - xasprintf(&buf, "%s%s\r\n", buf, force_host_header); - } else { + xasprintf (&buf, "%s%s\r\n", buf, force_host_header); + } + else { /* * Specify the port only if we're using a non-default port (see RFC 2616, * 14.23). Some server applications/configurations cause trouble if the @@ -1021,69 +1032,65 @@ int check_http(void) { */ if ((use_ssl == false && virtual_port == HTTP_PORT) || (use_ssl == true && virtual_port == HTTPS_PORT) || - (server_address != NULL && strcmp(http_method, "CONNECT") == 0 && - host_name != NULL && use_ssl == true)) - xasprintf(&buf, "%sHost: %s\r\n", buf, host_name); + (server_address != NULL && strcmp(http_method, "CONNECT") == 0 + && host_name != NULL && use_ssl == true)) + xasprintf (&buf, "%sHost: %s\r\n", buf, host_name); else - xasprintf(&buf, "%sHost: %s:%d\r\n", buf, host_name, virtual_port); + xasprintf (&buf, "%sHost: %s:%d\r\n", buf, host_name, virtual_port); } } /* optionally send any other header tag */ if (http_opt_headers_count) { - for (i = 0; i < http_opt_headers_count; i++) { + for (i = 0; i < http_opt_headers_count ; i++) { if (force_host_header != http_opt_headers[i]) { - xasprintf(&buf, "%s%s\r\n", buf, http_opt_headers[i]); + xasprintf (&buf, "%s%s\r\n", buf, http_opt_headers[i]); } } - /* This cannot be free'd here because a redirection will then try to access - * this and segfault */ + /* This cannot be free'd here because a redirection will then try to access this and segfault */ /* Covered in a testcase in tests/check_http.t */ /* free(http_opt_headers); */ } /* optionally send the authentication info */ if (strlen(user_auth)) { - base64_encode_alloc(user_auth, strlen(user_auth), &auth); - xasprintf(&buf, "%sAuthorization: Basic %s\r\n", buf, auth); + base64_encode_alloc (user_auth, strlen (user_auth), &auth); + xasprintf (&buf, "%sAuthorization: Basic %s\r\n", buf, auth); } /* optionally send the proxy authentication info */ if (strlen(proxy_auth)) { - base64_encode_alloc(proxy_auth, strlen(proxy_auth), &auth); - xasprintf(&buf, "%sProxy-Authorization: Basic %s\r\n", buf, auth); + base64_encode_alloc (proxy_auth, strlen (proxy_auth), &auth); + xasprintf (&buf, "%sProxy-Authorization: Basic %s\r\n", buf, auth); } /* either send http POST data (any data, not only POST)*/ if (http_post_data) { if (http_content_type) { - xasprintf(&buf, "%sContent-Type: %s\r\n", buf, http_content_type); + xasprintf (&buf, "%sContent-Type: %s\r\n", buf, http_content_type); } else { - xasprintf(&buf, "%sContent-Type: application/x-www-form-urlencoded\r\n", - buf); + xasprintf (&buf, "%sContent-Type: application/x-www-form-urlencoded\r\n", buf); } - xasprintf(&buf, "%sContent-Length: %i\r\n\r\n", buf, - (int)strlen(http_post_data)); - xasprintf(&buf, "%s%s", buf, http_post_data); + xasprintf (&buf, "%sContent-Length: %i\r\n\r\n", buf, (int)strlen (http_post_data)); + xasprintf (&buf, "%s%s", buf, http_post_data); } else { /* or just a newline so the server knows we're done with the request */ - xasprintf(&buf, "%s%s", buf, CRLF); + xasprintf (&buf, "%s%s", buf, CRLF); } - if (verbose) - printf("%s\n", buf); - gettimeofday(&tv_temp, NULL); - my_send(buf, strlen(buf)); - microsec_headers = deltime(tv_temp); + if (verbose) printf ("%s\n", buf); + gettimeofday (&tv_temp, NULL); + my_send (buf, strlen (buf)); + microsec_headers = deltime (tv_temp); elapsed_time_headers = (double)microsec_headers / 1.0e6; /* fetch the page */ full_page = strdup(""); - gettimeofday(&tv_temp, NULL); - while ((i = my_recv(buffer, MAX_INPUT_BUFFER - 1)) > 0) { + gettimeofday (&tv_temp, NULL); + while ((i = my_recv (buffer, MAX_INPUT_BUFFER-1)) > 0) { if ((i >= 1) && (elapsed_time_firstbyte <= 0.000001)) { - microsec_firstbyte = deltime(tv_temp); + microsec_firstbyte = deltime (tv_temp); elapsed_time_firstbyte = (double)microsec_firstbyte / 1.0e6; } while (pos = memchr(buffer, '\0', i)) { @@ -1101,12 +1108,12 @@ int check_http(void) { pagesize += i; - if (no_body && document_headers_done(full_page)) { - i = 0; - break; - } + if (no_body && document_headers_done (full_page)) { + i = 0; + break; + } } - microsec_transfer = deltime(tv_temp); + microsec_transfer = deltime (tv_temp); elapsed_time_transfer = (double)microsec_transfer / 1.0e6; if (i < 0 && errno != ECONNRESET) { @@ -1114,123 +1121,121 @@ int check_http(void) { } /* return a CRITICAL status if we couldn't read any data */ - if (pagesize == (size_t)0) - die(STATE_CRITICAL, _("HTTP CRITICAL - No data received from host\n")); + if (pagesize == (size_t) 0) + die (STATE_CRITICAL, _("HTTP CRITICAL - No data received from host\n")); /* close the connection */ - if (sd) - close(sd); + if (sd) close(sd); #ifdef HAVE_SSL np_net_ssl_cleanup(); #endif /* Save check time */ - microsec = deltime(tv); + microsec = deltime (tv); elapsed_time = (double)microsec / 1.0e6; /* leave full_page untouched so we can free it later */ page = full_page; if (verbose) - printf("%s://%s:%d%s is %d characters\n", use_ssl ? "https" : "http", - server_address, server_port, server_url, (int)pagesize); + printf ("%s://%s:%d%s is %d characters\n", + use_ssl ? "https" : "http", server_address, + server_port, server_url, (int)pagesize); /* find status line and null-terminate it */ status_line = page; - page += (size_t)strcspn(page, "\r\n"); + page += (size_t) strcspn (page, "\r\n"); pos = page; - page += (size_t)strspn(page, "\r\n"); + page += (size_t) strspn (page, "\r\n"); status_line[strcspn(status_line, "\r\n")] = 0; - strip(status_line); + strip (status_line); if (verbose) - printf("STATUS: %s\n", status_line); + printf ("STATUS: %s\n", status_line); /* find header info and null-terminate it */ header = page; - while (strcspn(page, "\r\n") > 0) { - page += (size_t)strcspn(page, "\r\n"); + while (strcspn (page, "\r\n") > 0) { + page += (size_t) strcspn (page, "\r\n"); pos = page; - if ((strspn(page, "\r") == 1 && strspn(page, "\r\n") >= 2) || - (strspn(page, "\n") == 1 && strspn(page, "\r\n") >= 2)) - page += (size_t)2; + if ((strspn (page, "\r") == 1 && strspn (page, "\r\n") >= 2) || + (strspn (page, "\n") == 1 && strspn (page, "\r\n") >= 2)) + page += (size_t) 2; else - page += (size_t)1; + page += (size_t) 1; } - page += (size_t)strspn(page, "\r\n"); + page += (size_t) strspn (page, "\r\n"); header[pos - header] = 0; if (verbose) - printf("**** HEADER ****\n%s\n**** CONTENT ****\n%s\n", header, - (no_body ? " [[ skipped ]]" : page)); + printf ("**** HEADER ****\n%s\n**** CONTENT ****\n%s\n", header, + (no_body ? " [[ skipped ]]" : page)); /* make sure the status line matches the response we are looking for */ - if (!expected_statuscode(status_line, server_expect)) { + if (!expected_statuscode (status_line, server_expect)) { if (server_port == HTTP_PORT) - xasprintf(&msg, _("Invalid HTTP response received from host: %s\n"), + xasprintf (&msg, + _("Invalid HTTP response received from host: %s\n"), status_line); else - xasprintf(&msg, + xasprintf (&msg, _("Invalid HTTP response received from host on port %d: %s\n"), server_port, status_line); if (show_body) - xasprintf(&msg, _("%s\n%s"), msg, page); - die(STATE_CRITICAL, "HTTP CRITICAL - %s", msg); + xasprintf (&msg, _("%s\n%s"), msg, page); + die (STATE_CRITICAL, "HTTP CRITICAL - %s", msg); } - /* Bypass normal status line check if server_expect was set by user and not - * default */ - /* NOTE: After this if/else block msg *MUST* be an asprintf-allocated string - */ - if (server_expect_yn) { - xasprintf(&msg, _("Status line output matched \"%s\" - "), server_expect); + /* Bypass normal status line check if server_expect was set by user and not default */ + /* NOTE: After this if/else block msg *MUST* be an asprintf-allocated string */ + if ( server_expect_yn ) { + xasprintf (&msg, + _("Status line output matched \"%s\" - "), server_expect); if (verbose) - printf("%s\n", msg); - } else { + printf ("%s\n",msg); + } + else { /* Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF */ /* HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT */ /* Status-Code = 3 DIGITS */ - status_code = strchr(status_line, ' ') + sizeof(char); - if (strspn(status_code, "1234567890") != 3) - die(STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status Line (%s)\n"), - status_line); + status_code = strchr (status_line, ' ') + sizeof (char); + if (strspn (status_code, "1234567890") != 3) + die (STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status Line (%s)\n"), status_line); - http_status = atoi(status_code); + http_status = atoi (status_code); /* check the return code */ if (http_status >= 600 || http_status < 100) { - die(STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status (%s)\n"), - status_line); + die (STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status (%s)\n"), status_line); } /* server errors result in a critical state */ else if (http_status >= 500) { - xasprintf(&msg, _("%s - "), status_line); + xasprintf (&msg, _("%s - "), status_line); result = STATE_CRITICAL; } /* client errors result in a warning state */ else if (http_status >= 400) { - xasprintf(&msg, _("%s - "), status_line); + xasprintf (&msg, _("%s - "), status_line); result = max_state_alt(STATE_WARNING, result); } /* check redirected page if specified */ else if (http_status >= 300) { if (onredirect == STATE_DEPENDENT) - redir(header, status_line); + redir (header, status_line); else result = max_state_alt(onredirect, result); - xasprintf(&msg, _("%s - "), status_line); + xasprintf (&msg, _("%s - "), status_line); } /* end if (http_status >= 300) */ else { /* Print OK status anyway */ - xasprintf(&msg, _("%s - "), status_line); + xasprintf (&msg, _("%s - "), status_line); } } /* end else (server_expect_yn) */ - /* reset the alarm - must be called *after* redir or we'll never die on - * redirects! */ - alarm(0); + /* reset the alarm - must be called *after* redir or we'll never die on redirects! */ + alarm (0); if (maximum_age >= 0) { result = max_state_alt(check_document_dates(header, &msg), result); @@ -1247,10 +1252,7 @@ int check_http(void) { bcopy("...", &output_header_search[sizeof(output_header_search) - 4], 4); } - xasprintf(&msg, _("%sheader '%s' not found on '%s://%s:%d%s', "), msg, - output_header_search, use_ssl ? "https" : "http", - host_name ? host_name : server_address, server_port, - server_url); + xasprintf (&msg, _("%sheader '%s' not found on '%s://%s:%d%s', "), msg, output_header_search, use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port, server_url); result = STATE_CRITICAL; } } @@ -1288,10 +1290,7 @@ int check_http(void) { bcopy("...", &output_string_search[sizeof(output_string_search) - 4], 4); } - xasprintf(&msg, _("%sstring '%s' not found on '%s://%s:%d%s', "), msg, - output_string_search, use_ssl ? "https" : "http", - host_name ? host_name : server_address, server_port, - server_url); + xasprintf (&msg, _("%sstring '%s' not found on '%s://%s:%d%s', "), msg, output_string_search, use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port, server_url); result = STATE_CRITICAL; } } @@ -1302,17 +1301,18 @@ int check_http(void) { (errcode == REG_NOMATCH && invert_regex == 1)) { /* OK - No-op to avoid changing the logic around it */ result = max_state_alt(STATE_OK, result); - } else if ((errcode == REG_NOMATCH && invert_regex == 0) || - (errcode == 0 && invert_regex == 1)) { + } + else if ((errcode == REG_NOMATCH && invert_regex == 0) || (errcode == 0 && invert_regex == 1)) { if (invert_regex == 0) - xasprintf(&msg, _("%spattern not found, "), msg); + xasprintf (&msg, _("%spattern not found, "), msg); else - xasprintf(&msg, _("%spattern found, "), msg); + xasprintf (&msg, _("%spattern found, "), msg); result = STATE_CRITICAL; - } else { + } + else { /* FIXME: Shouldn't that be UNKNOWN? */ - regerror(errcode, &preg, errbuf, MAX_INPUT_BUFFER); - xasprintf(&msg, _("%sExecute Error: %s, "), msg, errbuf); + regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); + xasprintf (&msg, _("%sExecute Error: %s, "), msg, errbuf); result = STATE_CRITICAL; } } @@ -1328,42 +1328,46 @@ int check_http(void) { */ page_len = pagesize; if ((max_page_len > 0) && (page_len > max_page_len)) { - xasprintf(&msg, _("%spage size %d too large, "), msg, page_len); + xasprintf (&msg, _("%spage size %d too large, "), msg, page_len); result = max_state_alt(STATE_WARNING, result); } else if ((min_page_len > 0) && (page_len < min_page_len)) { - xasprintf(&msg, _("%spage size %d too small, "), msg, page_len); + xasprintf (&msg, _("%spage size %d too small, "), msg, page_len); result = max_state_alt(STATE_WARNING, result); } /* Cut-off trailing characters */ - if (msg[strlen(msg) - 2] == ',') - msg[strlen(msg) - 2] = '\0'; + if(msg[strlen(msg)-2] == ',') + msg[strlen(msg)-2] = '\0'; else - msg[strlen(msg) - 3] = '\0'; + msg[strlen(msg)-3] = '\0'; /* check elapsed time */ if (show_extended_perfdata) - xasprintf( - &msg, - _("%s - %d bytes in %.3f second response time %s|%s %s %s %s %s %s %s"), - msg, page_len, elapsed_time, (display_html ? "" : ""), - perfd_time(elapsed_time), perfd_size(page_len), - perfd_time_connect(elapsed_time_connect), - use_ssl == true ? perfd_time_ssl(elapsed_time_ssl) : "", - perfd_time_headers(elapsed_time_headers), - perfd_time_firstbyte(elapsed_time_firstbyte), - perfd_time_transfer(elapsed_time_transfer)); + xasprintf (&msg, + _("%s - %d bytes in %.3f second response time %s|%s %s %s %s %s %s %s"), + msg, page_len, elapsed_time, + (display_html ? "" : ""), + perfd_time (elapsed_time), + perfd_size (page_len), + perfd_time_connect (elapsed_time_connect), + use_ssl == true ? perfd_time_ssl (elapsed_time_ssl) : "", + perfd_time_headers (elapsed_time_headers), + perfd_time_firstbyte (elapsed_time_firstbyte), + perfd_time_transfer (elapsed_time_transfer)); else - xasprintf(&msg, _("%s - %d bytes in %.3f second response time %s|%s %s"), - msg, page_len, elapsed_time, (display_html ? "" : ""), - perfd_time(elapsed_time), perfd_size(page_len)); + xasprintf (&msg, + _("%s - %d bytes in %.3f second response time %s|%s %s"), + msg, page_len, elapsed_time, + (display_html ? "" : ""), + perfd_time (elapsed_time), + perfd_size (page_len)); if (show_body) - xasprintf(&msg, _("%s\n%s"), msg, page); + xasprintf (&msg, _("%s\n%s"), msg, page); result = max_state_alt(get_status(elapsed_time, thlds), result); - die(result, "HTTP %s: %s\n", state_text(result), msg); + die (result, "HTTP %s: %s\n", state_text(result), msg); /* die failed? */ return STATE_UNKNOWN; } @@ -1453,22 +1457,20 @@ char *unchunk_content(const char *content) { /* per RFC 2396 */ #define URI_HTTP "%5[HTPShtps]" -#define URI_HOST \ - "%255[-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]" +#define URI_HOST "%255[-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]" #define URI_PORT "%6d" /* MAX_PORT's width is 5 chars, 6 to detect overflow */ -#define URI_PATH \ - "%[-_.!~*'();/" \ - "?:@&=+$,%#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]" +#define URI_PATH "%[-_.!~*'();/?:@&=+$,%#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]" #define HD1 URI_HTTP "://" URI_HOST ":" URI_PORT "/" URI_PATH #define HD2 URI_HTTP "://" URI_HOST "/" URI_PATH #define HD3 URI_HTTP "://" URI_HOST ":" URI_PORT #define HD4 URI_HTTP "://" URI_HOST -/* relative reference redirect like //www.site.org/test - * https://tools.ietf.org/html/rfc3986 */ +/* relative reference redirect like //www.site.org/test https://tools.ietf.org/html/rfc3986 */ #define HD5 "//" URI_HOST "/" URI_PATH #define HD6 URI_PATH -void redir(char *pos, char *status_line) { +void +redir (char *pos, char *status_line) +{ int i = 0; char *x; char xx[2]; @@ -1476,101 +1478,101 @@ void redir(char *pos, char *status_line) { char *addr; char *url; - addr = malloc(MAX_IPV4_HOSTLENGTH + 1); + addr = malloc (MAX_IPV4_HOSTLENGTH + 1); if (addr == NULL) - die(STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate addr\n")); + die (STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate addr\n")); memset(addr, 0, MAX_IPV4_HOSTLENGTH); - url = malloc(strcspn(pos, "\r\n")); + url = malloc (strcspn (pos, "\r\n")); if (url == NULL) - die(STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n")); + die (STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n")); while (pos) { - sscanf(pos, "%1[Ll]%*1[Oo]%*1[Cc]%*1[Aa]%*1[Tt]%*1[Ii]%*1[Oo]%*1[Nn]:%n", - xx, &i); + sscanf (pos, "%1[Ll]%*1[Oo]%*1[Cc]%*1[Aa]%*1[Tt]%*1[Ii]%*1[Oo]%*1[Nn]:%n", xx, &i); if (i == 0) { - pos += (size_t)strcspn(pos, "\r\n"); - pos += (size_t)strspn(pos, "\r\n"); + pos += (size_t) strcspn (pos, "\r\n"); + pos += (size_t) strspn (pos, "\r\n"); if (strlen(pos) == 0) - die(STATE_UNKNOWN, - _("HTTP UNKNOWN - Could not find redirect location - %s%s\n"), - status_line, (display_html ? "" : "")); + die (STATE_UNKNOWN, + _("HTTP UNKNOWN - Could not find redirect location - %s%s\n"), + status_line, (display_html ? "" : "")); continue; } pos += i; - pos += strspn(pos, " \t"); + pos += strspn (pos, " \t"); /* * RFC 2616 (4.2): ``Header fields can be extended over multiple lines by * preceding each extra line with at least one SP or HT.'' */ - for (; (i = strspn(pos, "\r\n")); pos += i) { + for (; (i = strspn (pos, "\r\n")); pos += i) { pos += i; - if (!(i = strspn(pos, " \t"))) { - die(STATE_UNKNOWN, _("HTTP UNKNOWN - Empty redirect location%s\n"), - display_html ? "" : ""); + if (!(i = strspn (pos, " \t"))) { + die (STATE_UNKNOWN, _("HTTP UNKNOWN - Empty redirect location%s\n"), + display_html ? "" : ""); } } - url = realloc(url, strcspn(pos, "\r\n") + 1); + url = realloc (url, strcspn (pos, "\r\n") + 1); if (url == NULL) - die(STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n")); + die (STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n")); /* URI_HTTP, URI_HOST, URI_PORT, URI_PATH */ - if (sscanf(pos, HD1, type, addr, &i, url) == 4) { - url = prepend_slash(url); - use_ssl = server_type_check(type); + if (sscanf (pos, HD1, type, addr, &i, url) == 4) { + url = prepend_slash (url); + use_ssl = server_type_check (type); } /* URI_HTTP URI_HOST URI_PATH */ - else if (sscanf(pos, HD2, type, addr, url) == 3) { - url = prepend_slash(url); - use_ssl = server_type_check(type); - i = server_port_check(use_ssl); + else if (sscanf (pos, HD2, type, addr, url) == 3 ) { + url = prepend_slash (url); + use_ssl = server_type_check (type); + i = server_port_check (use_ssl); } /* URI_HTTP URI_HOST URI_PORT */ - else if (sscanf(pos, HD3, type, addr, &i) == 3) { - strcpy(url, HTTP_URL); - use_ssl = server_type_check(type); + else if (sscanf (pos, HD3, type, addr, &i) == 3) { + strcpy (url, HTTP_URL); + use_ssl = server_type_check (type); } /* URI_HTTP URI_HOST */ - else if (sscanf(pos, HD4, type, addr) == 2) { - strcpy(url, HTTP_URL); - use_ssl = server_type_check(type); - i = server_port_check(use_ssl); + else if (sscanf (pos, HD4, type, addr) == 2) { + strcpy (url, HTTP_URL); + use_ssl = server_type_check (type); + i = server_port_check (use_ssl); } /* URI_HTTP, URI_HOST, URI_PATH */ - else if (sscanf(pos, HD5, addr, url) == 2) { - if (use_ssl) { - strcpy(type, "https"); - } else { - strcpy(type, server_type); + else if (sscanf (pos, HD5, addr, url) == 2) { + if(use_ssl){ + strcpy (type,"https"); } - xasprintf(&url, "/%s", url); - use_ssl = server_type_check(type); - i = server_port_check(use_ssl); + else{ + strcpy (type, server_type); + } + xasprintf (&url, "/%s", url); + use_ssl = server_type_check (type); + i = server_port_check (use_ssl); } /* URI_PATH */ - else if (sscanf(pos, HD6, url) == 1) { + else if (sscanf (pos, HD6, url) == 1) { /* relative url */ if ((url[0] != '/')) { if ((x = strrchr(server_url, '/'))) *x = '\0'; - xasprintf(&url, "%s/%s", server_url, url); + xasprintf (&url, "%s/%s", server_url, url); } i = server_port; - strcpy(type, server_type); - strcpy(addr, host_name ? host_name : server_address); + strcpy (type, server_type); + strcpy (addr, host_name ? host_name : server_address); } else { - die(STATE_UNKNOWN, - _("HTTP UNKNOWN - Could not parse redirect location - %s%s\n"), pos, - (display_html ? "" : "")); + die (STATE_UNKNOWN, + _("HTTP UNKNOWN - Could not parse redirect location - %s%s\n"), + pos, (display_html ? "" : "")); } break; @@ -1578,356 +1580,299 @@ void redir(char *pos, char *status_line) { } /* end while (pos) */ if (++redir_depth > max_depth) - die(STATE_WARNING, - _("HTTP WARNING - maximum redirection depth %d exceeded - " - "%s://%s:%d%s%s\n"), - max_depth, type, addr, i, url, (display_html ? "" : "")); + die (STATE_WARNING, + _("HTTP WARNING - maximum redirection depth %d exceeded - %s://%s:%d%s%s\n"), + max_depth, type, addr, i, url, (display_html ? "" : "")); - if (server_port == i && !strncmp(server_address, addr, MAX_IPV4_HOSTLENGTH) && + if (server_port==i && + !strncmp(server_address, addr, MAX_IPV4_HOSTLENGTH) && (host_name && !strncmp(host_name, addr, MAX_IPV4_HOSTLENGTH)) && !strcmp(server_url, url)) - die(STATE_CRITICAL, - _("HTTP CRITICAL - redirection creates an infinite loop - " - "%s://%s:%d%s%s\n"), - type, addr, i, url, (display_html ? "" : "")); + die (STATE_CRITICAL, + _("HTTP CRITICAL - redirection creates an infinite loop - %s://%s:%d%s%s\n"), + type, addr, i, url, (display_html ? "" : "")); - strcpy(server_type, type); + strcpy (server_type, type); - free(host_name); - host_name = strndup(addr, MAX_IPV4_HOSTLENGTH); + free (host_name); + host_name = strndup (addr, MAX_IPV4_HOSTLENGTH); if (!(followsticky & STICKY_HOST)) { - free(server_address); - server_address = strndup(addr, MAX_IPV4_HOSTLENGTH); + free (server_address); + server_address = strndup (addr, MAX_IPV4_HOSTLENGTH); } if (!(followsticky & STICKY_PORT)) { server_port = i; } - free(server_url); + free (server_url); server_url = url; if (server_port > MAX_PORT) - die(STATE_UNKNOWN, - _("HTTP UNKNOWN - Redirection to port above %d - %s://%s:%d%s%s\n"), - MAX_PORT, server_type, server_address, server_port, server_url, - display_html ? "" : ""); + die (STATE_UNKNOWN, + _("HTTP UNKNOWN - Redirection to port above %d - %s://%s:%d%s%s\n"), + MAX_PORT, server_type, server_address, server_port, server_url, + display_html ? "" : ""); /* reset virtual port */ virtual_port = server_port; if (verbose) - printf(_("Redirection to %s://%s:%d%s\n"), server_type, - host_name ? host_name : server_address, server_port, server_url); + printf (_("Redirection to %s://%s:%d%s\n"), server_type, + host_name ? host_name : server_address, server_port, server_url); free(addr); - check_http(); + check_http (); } -bool server_type_check(const char *type) { - if (strcmp(type, "https")) + +bool +server_type_check (const char *type) +{ + if (strcmp (type, "https")) return false; else return true; } -int server_port_check(int ssl_flag) { +int +server_port_check (int ssl_flag) +{ if (ssl_flag) return HTTPS_PORT; else return HTTP_PORT; } -char *perfd_time(double elapsed_time) { - return fperfdata("time", elapsed_time, "s", thlds->warning ? true : false, - thlds->warning ? thlds->warning->end : 0, - thlds->critical ? true : false, - thlds->critical ? thlds->critical->end : 0, true, 0, true, - socket_timeout); +char *perfd_time (double elapsed_time) +{ + return fperfdata ("time", elapsed_time, "s", + thlds->warning?true:false, thlds->warning?thlds->warning->end:0, + thlds->critical?true:false, thlds->critical?thlds->critical->end:0, + true, 0, true, socket_timeout); } -char *perfd_time_connect(double elapsed_time_connect) { - return fperfdata("time_connect", elapsed_time_connect, "s", false, 0, false, - 0, false, 0, true, socket_timeout); +char *perfd_time_connect (double elapsed_time_connect) +{ + return fperfdata ("time_connect", elapsed_time_connect, "s", false, 0, false, 0, false, 0, true, socket_timeout); } -char *perfd_time_ssl(double elapsed_time_ssl) { - return fperfdata("time_ssl", elapsed_time_ssl, "s", false, 0, false, 0, false, - 0, true, socket_timeout); +char *perfd_time_ssl (double elapsed_time_ssl) +{ + return fperfdata ("time_ssl", elapsed_time_ssl, "s", false, 0, false, 0, false, 0, true, socket_timeout); } -char *perfd_time_headers(double elapsed_time_headers) { - return fperfdata("time_headers", elapsed_time_headers, "s", false, 0, false, - 0, false, 0, true, socket_timeout); +char *perfd_time_headers (double elapsed_time_headers) +{ + return fperfdata ("time_headers", elapsed_time_headers, "s", false, 0, false, 0, false, 0, true, socket_timeout); } -char *perfd_time_firstbyte(double elapsed_time_firstbyte) { - return fperfdata("time_firstbyte", elapsed_time_firstbyte, "s", false, 0, - false, 0, false, 0, true, socket_timeout); +char *perfd_time_firstbyte (double elapsed_time_firstbyte) +{ + return fperfdata ("time_firstbyte", elapsed_time_firstbyte, "s", false, 0, false, 0, false, 0, true, socket_timeout); } -char *perfd_time_transfer(double elapsed_time_transfer) { - return fperfdata("time_transfer", elapsed_time_transfer, "s", false, 0, false, - 0, false, 0, true, socket_timeout); +char *perfd_time_transfer (double elapsed_time_transfer) +{ + return fperfdata ("time_transfer", elapsed_time_transfer, "s", false, 0, false, 0, false, 0, true, socket_timeout); } -char *perfd_size(int page_len) { - return perfdata("size", page_len, "B", (min_page_len > 0 ? true : false), - min_page_len, (min_page_len > 0 ? true : false), 0, true, 0, - false, 0); +char *perfd_size (int page_len) +{ + return perfdata ("size", page_len, "B", + (min_page_len>0?true:false), min_page_len, + (min_page_len>0?true:false), 0, + true, 0, false, 0); } -void print_help(void) { - print_revision(progname, NP_VERSION); +void +print_help (void) +{ + print_revision (progname, NP_VERSION); - printf("Copyright (c) 1999 Ethan Galstad \n"); - printf(COPYRIGHT, copyright, email); + printf ("Copyright (c) 1999 Ethan Galstad \n"); + printf (COPYRIGHT, copyright, email); - printf("%s\n", _("This plugin tests the HTTP service on the specified host. " - "It can test")); - printf("%s\n", _("normal (http) and secure (https) servers, follow " - "redirects, search for")); - printf("%s\n", _("strings and regular expressions, check connection times, " - "and report on")); - printf("%s\n", _("certificate expiration times.")); + printf ("%s\n", _("This plugin tests the HTTP service on the specified host. It can test")); + printf ("%s\n", _("normal (http) and secure (https) servers, follow redirects, search for")); + printf ("%s\n", _("strings and regular expressions, check connection times, and report on")); + printf ("%s\n", _("certificate expiration times.")); - printf("\n\n"); + printf ("\n\n"); - print_usage(); + print_usage (); #ifdef HAVE_SSL - printf(_("In the first form, make an HTTP request.")); - printf(_("In the second form, connect to the server and check the TLS " - "certificate.")); + printf (_("In the first form, make an HTTP request.")); + printf (_("In the second form, connect to the server and check the TLS certificate.")); #endif - printf(_("NOTE: One or both of -H and -I must be specified")); + printf (_("NOTE: One or both of -H and -I must be specified")); - printf("\n"); + printf ("\n"); - printf(UT_HELP_VRSN); - printf(UT_EXTRA_OPTS); + printf (UT_HELP_VRSN); + printf (UT_EXTRA_OPTS); - printf(" %s\n", "-H, --hostname=ADDRESS"); - printf(" %s\n", - _("Host name argument for servers using host headers (virtual host)")); - printf(" %s\n", - _("Append a port to include it in the header (eg: example.com:5000)")); - printf(" %s\n", "-I, --IP-address=ADDRESS"); - printf(" %s\n", _("IP address or name (use numeric address if possible to " - "bypass DNS lookup).")); - printf(" %s\n", "-p, --port=INTEGER"); - printf(" %s", _("Port number (default: ")); - printf("%d)\n", HTTP_PORT); + printf (" %s\n", "-H, --hostname=ADDRESS"); + printf (" %s\n", _("Host name argument for servers using host headers (virtual host)")); + printf (" %s\n", _("Append a port to include it in the header (eg: example.com:5000)")); + printf (" %s\n", "-I, --IP-address=ADDRESS"); + printf (" %s\n", _("IP address or name (use numeric address if possible to bypass DNS lookup).")); + printf (" %s\n", "-p, --port=INTEGER"); + printf (" %s", _("Port number (default: ")); + printf ("%d)\n", HTTP_PORT); - printf(UT_IPv46); + printf (UT_IPv46); #ifdef HAVE_SSL - printf(" %s\n", "-S, --ssl=VERSION[+]"); - printf(" %s\n", _("Connect via SSL. Port defaults to 443. VERSION is " - "optional, and prevents")); - printf( - " %s\n", - _("auto-negotiation (2 = SSLv2, 3 = SSLv3, 1 = TLSv1, 1.1 = TLSv1.1,")); - printf(" %s\n", _("1.2 = TLSv1.2). With a '+' suffix, newer versions are " - "also accepted.")); - printf(" %s\n", "--sni"); - printf(" %s\n", _("Enable SSL/TLS hostname extension support (SNI)")); - printf(" %s\n", "-C, --certificate=INTEGER[,INTEGER]"); - printf(" %s\n", _("Minimum number of days a certificate has to be valid. " - "Port defaults to 443")); - printf(" %s\n", _("(when this option is used the URL is not checked by " - "default. You can use")); - printf(" %s\n", - _(" --continue-after-certificate to override this behavior)")); - printf(" %s\n", "--continue-after-certificate"); - printf(" %s\n", _("Allows the HTTP check to continue after performing the " - "certificate check.")); - printf(" %s\n", _("Does nothing unless -C is used.")); - printf(" %s\n", "-J, --client-cert=FILE"); - printf(" %s\n", - _("Name of file that contains the client certificate (PEM format)")); - printf(" %s\n", _("to be used in establishing the SSL session")); - printf(" %s\n", "-K, --private-key=FILE"); - printf(" %s\n", _("Name of file containing the private key (PEM format)")); - printf(" %s\n", _("matching the client certificate")); + printf (" %s\n", "-S, --ssl=VERSION[+]"); + printf (" %s\n", _("Connect via SSL. Port defaults to 443. VERSION is optional, and prevents")); + printf (" %s\n", _("auto-negotiation (2 = SSLv2, 3 = SSLv3, 1 = TLSv1, 1.1 = TLSv1.1,")); + printf (" %s\n", _("1.2 = TLSv1.2). With a '+' suffix, newer versions are also accepted.")); + printf (" %s\n", "--sni"); + printf (" %s\n", _("Enable SSL/TLS hostname extension support (SNI)")); + printf (" %s\n", "-C, --certificate=INTEGER[,INTEGER]"); + printf (" %s\n", _("Minimum number of days a certificate has to be valid. Port defaults to 443")); + printf (" %s\n", _("(when this option is used the URL is not checked by default. You can use")); + printf (" %s\n", _(" --continue-after-certificate to override this behavior)")); + printf (" %s\n", "--continue-after-certificate"); + printf (" %s\n", _("Allows the HTTP check to continue after performing the certificate check.")); + printf (" %s\n", _("Does nothing unless -C is used.")); + printf (" %s\n", "-J, --client-cert=FILE"); + printf (" %s\n", _("Name of file that contains the client certificate (PEM format)")); + printf (" %s\n", _("to be used in establishing the SSL session")); + printf (" %s\n", "-K, --private-key=FILE"); + printf (" %s\n", _("Name of file containing the private key (PEM format)")); + printf (" %s\n", _("matching the client certificate")); #endif - printf(" %s\n", "-e, --expect=STRING"); - printf(" %s\n", _("Comma-delimited list of strings, at least one of them " - "is expected in")); - printf(" %s", - _("the first (status) line of the server response (default: ")); - printf("%s)\n", HTTP_EXPECT); - printf(" %s\n", _("If specified skips all other status line logic (ex: " - "3xx, 4xx, 5xx processing)")); - printf(" %s\n", "-d, --header-string=STRING"); - printf(" %s\n", _("String to expect in the response headers")); - printf(" %s\n", "-s, --string=STRING"); - printf(" %s\n", _("String to expect in the content")); - printf(" %s\n", "-u, --url=PATH"); - printf(" %s\n", _("URL to GET or POST (default: /)")); - printf(" %s\n", "-P, --post=STRING"); - printf(" %s\n", _("URL encoded http POST data")); - printf(" %s\n", "-j, --method=STRING (for example: HEAD, OPTIONS, TRACE, " - "PUT, DELETE, CONNECT, CONNECT:POST)"); - printf(" %s\n", _("Set HTTP method.")); - printf(" %s\n", "-N, --no-body"); - printf(" %s\n", - _("Don't wait for document body: stop reading after headers.")); - printf(" %s\n", - _("(Note that this still does an HTTP GET or POST, not a HEAD.)")); - printf(" %s\n", "-M, --max-age=SECONDS"); - printf(" %s\n", _("Warn if document is more than SECONDS old. the number " - "can also be of")); - printf(" %s\n", _("the form \"10m\" for minutes, \"10h\" for hours, or " - "\"10d\" for days.")); - printf(" %s\n", "-T, --content-type=STRING"); - printf(" %s\n", - _("specify Content-Type header media type when POSTing\n")); - - printf(" %s\n", "-l, --linespan"); - printf(" %s\n", _("Allow regex to span newlines (must precede -r or -R)")); - printf(" %s\n", "-r, --regex, --ereg=STRING"); - printf(" %s\n", _("Search page for regex STRING")); - printf(" %s\n", "-R, --eregi=STRING"); - printf(" %s\n", _("Search page for case-insensitive regex STRING")); - printf(" %s\n", "--invert-regex"); - printf(" %s\n", _("Return CRITICAL if found, OK if not\n")); - - printf(" %s\n", "-a, --authorization=AUTH_PAIR"); - printf(" %s\n", _("Username:password on sites with basic authentication")); - printf(" %s\n", "-b, --proxy-authorization=AUTH_PAIR"); - printf(" %s\n", - _("Username:password on proxy-servers with basic authentication")); - printf(" %s\n", "-A, --useragent=STRING"); - printf(" %s\n", _("String to be sent in http header as \"User Agent\"")); - printf(" %s\n", "-k, --header=STRING"); - printf(" %s\n", _("Any other tags to be sent in http header. Use multiple " - "times for additional headers")); - printf(" %s\n", "-E, --extended-perfdata"); - printf(" %s\n", _("Print additional performance data")); - printf(" %s\n", "-B, --show-body"); - printf(" %s\n", _("Print body content below status line")); - printf(" %s\n", "-L, --link"); - printf(" %s\n", _("Wrap output in HTML link (obsoleted by urlize)")); - printf(" %s\n", - "-f, --onredirect="); - printf(" %s\n", _("How to handle redirected pages. sticky is like follow " - "but stick to the")); - printf( - " %s\n", - _("specified IP address. stickyport also ensures port stays the same.")); - printf(" %s\n", "--max-redirs=INTEGER"); - printf(" %s", _("Maximal number of redirects (default: ")); - printf("%d)\n", DEFAULT_MAX_REDIRS); - printf(" %s\n", "-m, --pagesize=INTEGER<:INTEGER>"); - printf(" %s\n", _("Minimum page size required (bytes) : Maximum page size " - "required (bytes)")); - printf(UT_WARN_CRIT); - - printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - - printf(UT_VERBOSE); - - printf("\n"); - printf("%s\n", _("Notes:")); - printf( - " %s\n", - _("This plugin will attempt to open an HTTP connection with the host.")); - printf(" %s\n", _("Successful connects return STATE_OK, refusals and " - "timeouts return STATE_CRITICAL")); - printf(" %s\n", _("other errors return STATE_UNKNOWN. Successful connects, " - "but incorrect response")); - printf(" %s\n", _("messages from the host result in STATE_WARNING return " - "values. If you are")); - printf(" %s\n", _("checking a virtual server that uses 'host headers' you " - "must supply the FQDN")); - printf(" %s\n", - _("(fully qualified domain name) as the [host_name] argument.")); + printf (" %s\n", "-e, --expect=STRING"); + printf (" %s\n", _("Comma-delimited list of strings, at least one of them is expected in")); + printf (" %s", _("the first (status) line of the server response (default: ")); + printf ("%s)\n", HTTP_EXPECT); + printf (" %s\n", _("If specified skips all other status line logic (ex: 3xx, 4xx, 5xx processing)")); + printf (" %s\n", "-d, --header-string=STRING"); + printf (" %s\n", _("String to expect in the response headers")); + printf (" %s\n", "-s, --string=STRING"); + printf (" %s\n", _("String to expect in the content")); + printf (" %s\n", "-u, --url=PATH"); + printf (" %s\n", _("URL to GET or POST (default: /)")); + printf (" %s\n", "-P, --post=STRING"); + printf (" %s\n", _("URL encoded http POST data")); + printf (" %s\n", "-j, --method=STRING (for example: HEAD, OPTIONS, TRACE, PUT, DELETE, CONNECT, CONNECT:POST)"); + printf (" %s\n", _("Set HTTP method.")); + printf (" %s\n", "-N, --no-body"); + printf (" %s\n", _("Don't wait for document body: stop reading after headers.")); + printf (" %s\n", _("(Note that this still does an HTTP GET or POST, not a HEAD.)")); + printf (" %s\n", "-M, --max-age=SECONDS"); + printf (" %s\n", _("Warn if document is more than SECONDS old. the number can also be of")); + printf (" %s\n", _("the form \"10m\" for minutes, \"10h\" for hours, or \"10d\" for days.")); + printf (" %s\n", "-T, --content-type=STRING"); + printf (" %s\n", _("specify Content-Type header media type when POSTing\n")); + + printf (" %s\n", "-l, --linespan"); + printf (" %s\n", _("Allow regex to span newlines (must precede -r or -R)")); + printf (" %s\n", "-r, --regex, --ereg=STRING"); + printf (" %s\n", _("Search page for regex STRING")); + printf (" %s\n", "-R, --eregi=STRING"); + printf (" %s\n", _("Search page for case-insensitive regex STRING")); + printf (" %s\n", "--invert-regex"); + printf (" %s\n", _("Return CRITICAL if found, OK if not\n")); + + printf (" %s\n", "-a, --authorization=AUTH_PAIR"); + printf (" %s\n", _("Username:password on sites with basic authentication")); + printf (" %s\n", "-b, --proxy-authorization=AUTH_PAIR"); + printf (" %s\n", _("Username:password on proxy-servers with basic authentication")); + printf (" %s\n", "-A, --useragent=STRING"); + printf (" %s\n", _("String to be sent in http header as \"User Agent\"")); + printf (" %s\n", "-k, --header=STRING"); + printf (" %s\n", _("Any other tags to be sent in http header. Use multiple times for additional headers")); + printf (" %s\n", "-E, --extended-perfdata"); + printf (" %s\n", _("Print additional performance data")); + printf (" %s\n", "-B, --show-body"); + printf (" %s\n", _("Print body content below status line")); + printf (" %s\n", "-L, --link"); + printf (" %s\n", _("Wrap output in HTML link (obsoleted by urlize)")); + printf (" %s\n", "-f, --onredirect="); + printf (" %s\n", _("How to handle redirected pages. sticky is like follow but stick to the")); + printf (" %s\n", _("specified IP address. stickyport also ensures port stays the same.")); + printf (" %s\n", "--max-redirs=INTEGER"); + printf (" %s", _("Maximal number of redirects (default: ")); + printf ("%d)\n", DEFAULT_MAX_REDIRS); + printf (" %s\n", "-m, --pagesize=INTEGER<:INTEGER>"); + printf (" %s\n", _("Minimum page size required (bytes) : Maximum page size required (bytes)")); + printf (UT_WARN_CRIT); + + printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + + printf (UT_VERBOSE); + + printf ("\n"); + printf ("%s\n", _("Notes:")); + printf (" %s\n", _("This plugin will attempt to open an HTTP connection with the host.")); + printf (" %s\n", _("Successful connects return STATE_OK, refusals and timeouts return STATE_CRITICAL")); + printf (" %s\n", _("other errors return STATE_UNKNOWN. Successful connects, but incorrect response")); + printf (" %s\n", _("messages from the host result in STATE_WARNING return values. If you are")); + printf (" %s\n", _("checking a virtual server that uses 'host headers' you must supply the FQDN")); + printf (" %s\n", _("(fully qualified domain name) as the [host_name] argument.")); #ifdef HAVE_SSL - printf("\n"); - printf(" %s\n", _("This plugin can also check whether an SSL enabled web " - "server is able to")); - printf(" %s\n", _("serve content (optionally within a specified time) or " - "whether the X509 ")); - printf(" %s\n", - _("certificate is still valid for the specified number of days.")); - printf("\n"); - printf( - " %s\n", - _("Please note that this plugin does not check if the presented server")); - printf(" %s\n", _("certificate matches the hostname of the server, or if the " - "certificate")); - printf(" %s\n", - _("has a valid chain of trust to one of the locally installed CAs.")); - printf("\n"); - printf("%s\n", _("Examples:")); - printf(" %s\n\n", - "CHECK CONTENT: check_http -w 5 -c 10 --ssl -H www.verisign.com"); - printf(" %s\n", _("When the 'www.verisign.com' server returns its content " - "within 5 seconds,")); - printf(" %s\n", _("a STATE_OK will be returned. When the server returns its " - "content but exceeds")); - printf(" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. " - "When an error occurs,")); - printf(" %s\n", _("a STATE_CRITICAL will be returned.")); - printf("\n"); - printf(" %s\n\n", "CHECK CERTIFICATE: check_http -H www.verisign.com -C 14"); - printf(" %s\n", _("When the certificate of 'www.verisign.com' is valid for " - "more than 14 days,")); - printf(" %s\n", _("a STATE_OK is returned. When the certificate is still " - "valid, but for less than")); - printf(" %s\n", _("14 days, a STATE_WARNING is returned. A STATE_CRITICAL " - "will be returned when")); - printf(" %s\n\n", _("the certificate is expired.")); - printf("\n"); - printf(" %s\n\n", - "CHECK CERTIFICATE: check_http -H www.verisign.com -C 30,14"); - printf(" %s\n", _("When the certificate of 'www.verisign.com' is valid for " - "more than 30 days,")); - printf(" %s\n", _("a STATE_OK is returned. When the certificate is still " - "valid, but for less than")); - printf(" %s\n", - _("30 days, but more than 14 days, a STATE_WARNING is returned.")); - printf(" %s\n", _("A STATE_CRITICAL will be returned when certificate " - "expires in less than 14 days")); - - printf(" %s\n\n", - "CHECK SSL WEBSERVER CONTENT VIA PROXY USING HTTP 1.1 CONNECT: "); - printf(" %s\n", - _("check_http -I 192.168.100.35 -p 80 -u https://www.verisign.com/ -S " - "-j CONNECT -H www.verisign.com ")); - printf(" %s\n", _("all these options are needed: -I -p " - "-u -S(sl) -j CONNECT -H ")); - printf(" %s\n", _("a STATE_OK will be returned. When the server returns its " - "content but exceeds")); - printf(" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. " - "When an error occurs,")); - printf(" %s\n", _("a STATE_CRITICAL will be returned. By adding a colon to " - "the method you can set the method used")); - printf(" %s\n", _("inside the proxied connection: -j CONNECT:POST")); + printf ("\n"); + printf (" %s\n", _("This plugin can also check whether an SSL enabled web server is able to")); + printf (" %s\n", _("serve content (optionally within a specified time) or whether the X509 ")); + printf (" %s\n", _("certificate is still valid for the specified number of days.")); + printf ("\n"); + printf (" %s\n", _("Please note that this plugin does not check if the presented server")); + printf (" %s\n", _("certificate matches the hostname of the server, or if the certificate")); + printf (" %s\n", _("has a valid chain of trust to one of the locally installed CAs.")); + printf ("\n"); + printf ("%s\n", _("Examples:")); + printf (" %s\n\n", "CHECK CONTENT: check_http -w 5 -c 10 --ssl -H www.verisign.com"); + printf (" %s\n", _("When the 'www.verisign.com' server returns its content within 5 seconds,")); + printf (" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds")); + printf (" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,")); + printf (" %s\n", _("a STATE_CRITICAL will be returned.")); + printf ("\n"); + printf (" %s\n\n", "CHECK CERTIFICATE: check_http -H www.verisign.com -C 14"); + printf (" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 14 days,")); + printf (" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than")); + printf (" %s\n", _("14 days, a STATE_WARNING is returned. A STATE_CRITICAL will be returned when")); + printf (" %s\n\n", _("the certificate is expired.")); + printf ("\n"); + printf (" %s\n\n", "CHECK CERTIFICATE: check_http -H www.verisign.com -C 30,14"); + printf (" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 30 days,")); + printf (" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than")); + printf (" %s\n", _("30 days, but more than 14 days, a STATE_WARNING is returned.")); + printf (" %s\n", _("A STATE_CRITICAL will be returned when certificate expires in less than 14 days")); + + printf (" %s\n\n", "CHECK SSL WEBSERVER CONTENT VIA PROXY USING HTTP 1.1 CONNECT: "); + printf (" %s\n", _("check_http -I 192.168.100.35 -p 80 -u https://www.verisign.com/ -S -j CONNECT -H www.verisign.com ")); + printf (" %s\n", _("all these options are needed: -I -p -u -S(sl) -j CONNECT -H ")); + printf (" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds")); + printf (" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,")); + printf (" %s\n", _("a STATE_CRITICAL will be returned. By adding a colon to the method you can set the method used")); + printf (" %s\n", _("inside the proxied connection: -j CONNECT:POST")); #endif - printf(UT_SUPPORT); + printf (UT_SUPPORT); + } -void print_usage(void) { - printf("%s\n", _("Usage:")); - printf(" %s -H | -I [-u ] [-p ]\n", progname); - printf(" [-J ] [-K ]\n"); - printf(" [-w ] [-c ] [-t ] [-L] " - "[-E] [-a auth]\n"); - printf(" [-b proxy_auth] [-f " - "]\n"); - printf(" [-e ] [-d string] [-s string] [-l] [-r | -R " - "]\n"); - printf(" [-P string] [-m :] [-4|-6] [-N] [-M " - "]\n"); - printf(" [-A string] [-k string] [-S ] [--sni]\n"); - printf(" [-T ] [-j method]\n"); - printf(" %s -H | -I -C [,]\n", - progname); - printf(" [-p ] [-t ] [-4|-6] [--sni]\n"); + + +void +print_usage (void) +{ + printf ("%s\n", _("Usage:")); + printf (" %s -H | -I [-u ] [-p ]\n",progname); + printf (" [-J ] [-K ]\n"); + printf (" [-w ] [-c ] [-t ] [-L] [-E] [-a auth]\n"); + printf (" [-b proxy_auth] [-f ]\n"); + printf (" [-e ] [-d string] [-s string] [-l] [-r | -R ]\n"); + printf (" [-P string] [-m :] [-4|-6] [-N] [-M ]\n"); + printf (" [-A string] [-k string] [-S ] [--sni]\n"); + printf (" [-T ] [-j method]\n"); + printf (" %s -H | -I -C [,]\n",progname); + printf (" [-p ] [-t ] [-4|-6] [--sni]\n"); } -- cgit v1.2.3-74-g34f1 From 6ed7a75c3b4565af54b8fd4d96225a36a705a0fd Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 22 Dec 2022 13:16:19 +0100 Subject: Reformat a part to increase readability --- plugins/check_http.c | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index dbaa0d78..a9c22389 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -1246,13 +1246,23 @@ check_http (void) if (strstr(header, header_expect) == NULL) { // We did not find the header, the rest is for building the output and setting the state char output_header_search[30] = ""; + strncpy(&output_header_search[0], header_expect, sizeof(output_header_search)); + if (output_header_search[sizeof(output_header_search) - 1] != '\0') { - bcopy("...", &output_header_search[sizeof(output_header_search) - 4], - 4); + bcopy("...", + &output_header_search[sizeof(output_header_search) - 4], + 4); } - xasprintf (&msg, _("%sheader '%s' not found on '%s://%s:%d%s', "), msg, output_header_search, use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port, server_url); + + xasprintf (&msg, + _("%sheader '%s' not found on '%s://%s:%d%s', "), + msg, + output_header_search, use_ssl ? "https" : "http", + host_name ? host_name : server_address, server_port, + server_url); + result = STATE_CRITICAL; } } -- cgit v1.2.3-74-g34f1 From c256af44fb23a4749faa5f3fce167a9d9a4367d7 Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Thu, 22 Dec 2022 14:06:08 +0100 Subject: check_http/check_curl: add chunked encoding test --- plugins/tests/check_curl.t | 18 +++++++++++++++++- plugins/tests/check_http.t | 18 +++++++++++++++++- 2 files changed, 34 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/tests/check_curl.t b/plugins/tests/check_curl.t index aa72ef67..86bfb538 100755 --- a/plugins/tests/check_curl.t +++ b/plugins/tests/check_curl.t @@ -21,7 +21,7 @@ use FindBin qw($Bin); $ENV{'LC_TIME'} = "C"; -my $common_tests = 72; +my $common_tests = 74; my $ssl_only_tests = 8; # Check that all dependent modules are available eval "use HTTP::Daemon 6.01;"; @@ -200,6 +200,17 @@ sub run_server { $c->send_basic_header; $c->send_crlf; $c->send_response(HTTP::Response->new( 200, 'OK', undef, $r->header ('Host'))); + } elsif ($r->url->path eq "/chunked") { + $c->send_basic_header; + $c->send_header('Transfer-Encoding', "chunked"); + $c->send_crlf; + my $chunks = ["chunked", "encoding", "test\n"]; + $c->send_response(HTTP::Response->new( 200, 'OK', undef, sub { + my $chunk = shift @{$chunks}; + return unless $chunk; + sleep(1); + return($chunk); + })); } else { $c->send_error(HTTP::Status->RC_FORBIDDEN); } @@ -508,4 +519,9 @@ sub run_common_tests { }; is( $@, "", $cmd ); + $cmd = "$command -u /chunked -s 'chunkedencodingtest'"; + eval { + $result = NPTest->testCmd( $cmd, 5 ); + }; + is( $@, "", $cmd ); } diff --git a/plugins/tests/check_http.t b/plugins/tests/check_http.t index ea11b2ac..132c6659 100755 --- a/plugins/tests/check_http.t +++ b/plugins/tests/check_http.t @@ -12,7 +12,7 @@ use FindBin qw($Bin); $ENV{'LC_TIME'} = "C"; -my $common_tests = 70; +my $common_tests = 72; my $virtual_port_tests = 8; my $ssl_only_tests = 12; # Check that all dependent modules are available @@ -190,6 +190,17 @@ sub run_server { $c->send_basic_header; $c->send_crlf; $c->send_response(HTTP::Response->new( 200, 'OK', undef, $r->header ('Host'))); + } elsif ($r->url->path eq "/chunked") { + $c->send_basic_header; + $c->send_header('Transfer-Encoding', "chunked"); + $c->send_crlf; + my $chunks = ["chunked", "encoding", "test\n"]; + $c->send_response(HTTP::Response->new( 200, 'OK', undef, sub { + my $chunk = shift @{$chunks}; + return unless $chunk; + sleep(1); + return($chunk); + })); } else { $c->send_error(HTTP::Status->RC_FORBIDDEN); } @@ -497,4 +508,9 @@ sub run_common_tests { }; is( $@, "", $cmd ); + $cmd = "$command -u /chunked -s 'chunkedencodingtest'"; + eval { + $result = NPTest->testCmd( $cmd, 5 ); + }; + is( $@, "", $cmd ); } -- cgit v1.2.3-74-g34f1 From 07561a67abb02688955433db5b4a38b23523a754 Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Thu, 22 Dec 2022 14:58:01 +0100 Subject: tests: fix chunked encoding test server --- plugins/tests/check_curl.t | 29 ++++++++++++++--------------- plugins/tests/check_http.t | 7 ++----- 2 files changed, 16 insertions(+), 20 deletions(-) (limited to 'plugins') diff --git a/plugins/tests/check_curl.t b/plugins/tests/check_curl.t index 86bfb538..72f2b7c2 100755 --- a/plugins/tests/check_curl.t +++ b/plugins/tests/check_curl.t @@ -21,7 +21,7 @@ use FindBin qw($Bin); $ENV{'LC_TIME'} = "C"; -my $common_tests = 74; +my $common_tests = 73; my $ssl_only_tests = 8; # Check that all dependent modules are available eval "use HTTP::Daemon 6.01;"; @@ -200,17 +200,14 @@ sub run_server { $c->send_basic_header; $c->send_crlf; $c->send_response(HTTP::Response->new( 200, 'OK', undef, $r->header ('Host'))); - } elsif ($r->url->path eq "/chunked") { - $c->send_basic_header; - $c->send_header('Transfer-Encoding', "chunked"); - $c->send_crlf; - my $chunks = ["chunked", "encoding", "test\n"]; - $c->send_response(HTTP::Response->new( 200, 'OK', undef, sub { - my $chunk = shift @{$chunks}; - return unless $chunk; - sleep(1); - return($chunk); - })); + } elsif ($r->url->path eq "/chunked") { + my $chunks = ["chunked", "encoding", "test\n"]; + $c->send_response(HTTP::Response->new( 200, 'OK', undef, sub { + my $chunk = shift @{$chunks}; + return unless $chunk; + sleep(1); + return($chunk); + })); } else { $c->send_error(HTTP::Status->RC_FORBIDDEN); } @@ -483,7 +480,8 @@ sub run_common_tests { local $SIG{ALRM} = sub { die "alarm\n" }; alarm(2); $result = NPTest->testCmd( $cmd ); - alarm(0); }; + }; + alarm(0); isnt( $@, "alarm\n", $cmd ); is( $result->return_code, 0, $cmd ); @@ -493,7 +491,8 @@ sub run_common_tests { local $SIG{ALRM} = sub { die "alarm\n" }; alarm(2); $result = NPTest->testCmd( $cmd ); - alarm(0); }; + }; + alarm(0); isnt( $@, "alarm\n", $cmd ); isnt( $result->return_code, 0, $cmd ); @@ -519,7 +518,7 @@ sub run_common_tests { }; is( $@, "", $cmd ); - $cmd = "$command -u /chunked -s 'chunkedencodingtest'"; + $cmd = "$command -u /chunked -s 'chunkedencodingtest' -d 'Transfer-Encoding: chunked'"; eval { $result = NPTest->testCmd( $cmd, 5 ); }; diff --git a/plugins/tests/check_http.t b/plugins/tests/check_http.t index 132c6659..d766ac37 100755 --- a/plugins/tests/check_http.t +++ b/plugins/tests/check_http.t @@ -12,7 +12,7 @@ use FindBin qw($Bin); $ENV{'LC_TIME'} = "C"; -my $common_tests = 72; +my $common_tests = 71; my $virtual_port_tests = 8; my $ssl_only_tests = 12; # Check that all dependent modules are available @@ -191,9 +191,6 @@ sub run_server { $c->send_crlf; $c->send_response(HTTP::Response->new( 200, 'OK', undef, $r->header ('Host'))); } elsif ($r->url->path eq "/chunked") { - $c->send_basic_header; - $c->send_header('Transfer-Encoding', "chunked"); - $c->send_crlf; my $chunks = ["chunked", "encoding", "test\n"]; $c->send_response(HTTP::Response->new( 200, 'OK', undef, sub { my $chunk = shift @{$chunks}; @@ -508,7 +505,7 @@ sub run_common_tests { }; is( $@, "", $cmd ); - $cmd = "$command -u /chunked -s 'chunkedencodingtest'"; + $cmd = "$command -u /chunked -s 'chunkedencodingtest' -d 'Transfer-Encoding: chunked'"; eval { $result = NPTest->testCmd( $cmd, 5 ); }; -- cgit v1.2.3-74-g34f1 From 0899e41f5075d661153eb2c77ace1734a8f66bfa Mon Sep 17 00:00:00 2001 From: Lorenz <12514511+RincewindsHat@users.noreply.github.com> Date: Sun, 8 Jan 2023 17:23:53 +0100 Subject: Check apt usage (#1793) * Remove trailing whitespaces * Use real booleans * Fix comment * Put upgrade options in the root sections Co-authored-by: waja --- plugins/check_apt.c | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) (limited to 'plugins') diff --git a/plugins/check_apt.c b/plugins/check_apt.c index af3563a1..312909b7 100644 --- a/plugins/check_apt.c +++ b/plugins/check_apt.c @@ -76,9 +76,9 @@ int cmpstringp(const void *p1, const void *p2); /* configuration variables */ static int verbose = 0; /* -v */ -static int list = 0; /* list packages available for upgrade */ -static int do_update = 0; /* whether to call apt-get update */ -static int only_critical = 0; /* whether to warn about non-critical updates */ +static bool list = false; /* list packages available for upgrade */ +static bool do_update = false; /* whether to call apt-get update */ +static bool only_critical = false; /* whether to warn about non-critical updates */ static upgrade_type upgrade = UPGRADE; /* which type of upgrade to do */ static char *upgrade_opts = NULL; /* options to override defaults for upgrade */ static char *update_opts = NULL; /* options to override defaults for update */ @@ -119,7 +119,7 @@ int main (int argc, char **argv) { if(sec_count > 0){ result = max_state(result, STATE_CRITICAL); - } else if(packages_available >= packages_warning && only_critical == 0){ + } else if(packages_available >= packages_warning && only_critical == false){ result = max_state(result, STATE_WARNING); } else if(result > STATE_UNKNOWN){ result = STATE_UNKNOWN; @@ -144,7 +144,7 @@ int main (int argc, char **argv) { for(i = 0; i < sec_count; i++) printf("%s (security)\n", secpackages_list[i]); - if (only_critical == 0) { + if (only_critical == false) { for(i = 0; i < packages_available - sec_count; i++) printf("%s\n", packages_list[i]); } @@ -166,7 +166,7 @@ int process_arguments (int argc, char **argv) { {"upgrade", optional_argument, 0, 'U'}, {"no-upgrade", no_argument, 0, 'n'}, {"dist-upgrade", optional_argument, 0, 'd'}, - {"list", no_argument, 0, 'l'}, + {"list", no_argument, false, 'l'}, {"include", required_argument, 0, 'i'}, {"exclude", required_argument, 0, 'e'}, {"critical", required_argument, 0, 'c'}, @@ -212,14 +212,14 @@ int process_arguments (int argc, char **argv) { upgrade=NO_UPGRADE; break; case 'u': - do_update=1; + do_update=true; if(optarg!=NULL){ update_opts=strdup(optarg); if(update_opts==NULL) die(STATE_UNKNOWN, "strdup failed"); } break; case 'l': - list=1; + list=true; break; case 'i': do_include=add_to_regexp(do_include, optarg); @@ -231,7 +231,7 @@ int process_arguments (int argc, char **argv) { do_critical=add_to_regexp(do_critical, optarg); break; case 'o': - only_critical=1; + only_critical=true; break; case INPUT_FILE_OPT: input_filename = optarg; @@ -371,7 +371,7 @@ int run_update(void){ struct output chld_out, chld_err; char *cmdline; - /* run the upgrade */ + /* run the update */ cmdline = construct_cmdline(NO_UPGRADE, update_opts); result = np_runcmd(cmdline, &chld_out, &chld_err, 0); /* apt-get update changes exit status if it can't fetch packages. @@ -501,16 +501,6 @@ print_help (void) printf(UT_PLUG_TIMEOUT, timeout_interval); - printf (" %s\n", "-U, --upgrade=OPTS"); - printf (" %s\n", _("[Default] Perform an upgrade. If an optional OPTS argument is provided,")); - printf (" %s\n", _("apt-get will be run with these command line options instead of the")); - printf (" %s", _("default ")); - printf ("(%s).\n", UPGRADE_DEFAULT_OPTS); - printf (" %s\n", _("Note that you may be required to have root privileges if you do not use")); - printf (" %s\n", _("the default options.")); - printf (" %s\n", "-d, --dist-upgrade=OPTS"); - printf (" %s\n", _("Perform a dist-upgrade instead of normal upgrade. Like with -U OPTS")); - printf (" %s\n", _("can be provided to override the default options.")); printf (" %s\n", "-n, --no-upgrade"); printf (" %s\n", _("Do not run the upgrade. Probably not useful (without -u at least).")); printf (" %s\n", "-l, --list"); @@ -547,6 +537,16 @@ print_help (void) printf (" %s\n", _("the default options. Note: you may also need to adjust the global")); printf (" %s\n", _("timeout (with -t) to prevent the plugin from timing out if apt-get")); printf (" %s\n", _("upgrade is expected to take longer than the default timeout.")); + printf (" %s\n", "-U, --upgrade=OPTS"); + printf (" %s\n", _("Perform an upgrade. If an optional OPTS argument is provided,")); + printf (" %s\n", _("apt-get will be run with these command line options instead of the")); + printf (" %s", _("default ")); + printf ("(%s).\n", UPGRADE_DEFAULT_OPTS); + printf (" %s\n", _("Note that you may be required to have root privileges if you do not use")); + printf (" %s\n", _("the default options, which will only run a simulation and NOT perform the upgrade")); + printf (" %s\n", "-d, --dist-upgrade=OPTS"); + printf (" %s\n", _("Perform a dist-upgrade instead of normal upgrade. Like with -U OPTS")); + printf (" %s\n", _("can be provided to override the default options.")); printf(UT_SUPPORT); } -- cgit v1.2.3-74-g34f1 From 72147140ed6c9a06db722930e893c90a230e6da9 Mon Sep 17 00:00:00 2001 From: waja Date: Tue, 17 Jan 2023 15:42:54 +0100 Subject: Fixing spelling errors (#1826) --- plugins/check_apt.c | 2 +- plugins/check_curl.c | 2 +- plugins/check_fping.c | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'plugins') diff --git a/plugins/check_apt.c b/plugins/check_apt.c index 312909b7..fa982ae3 100644 --- a/plugins/check_apt.c +++ b/plugins/check_apt.c @@ -528,7 +528,7 @@ print_help (void) printf (" %s\n", _("of upgrades will be printed, but any non-critical upgrades will not cause")); printf (" %s\n", _("the plugin to return WARNING status.")); printf (" %s\n", "-w, --packages-warning"); - printf (" %s\n", _("Minumum number of packages available for upgrade to return WARNING status.")); + printf (" %s\n", _("Minimum number of packages available for upgrade to return WARNING status.")); printf (" %s\n\n", _("Default is 1 package.")); printf ("%s\n\n", _("The following options require root privileges and should be used with care:")); diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 55de22fd..c6593df1 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -1680,7 +1680,7 @@ process_arguments (int argc, char **argv) curl_http_version = CURL_HTTP_VERSION_NONE; #endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 33, 0) */ } else { - fprintf (stderr, "unkown http-version parameter: %s\n", optarg); + fprintf (stderr, "unknown http-version parameter: %s\n", optarg); exit (STATE_WARNING); } break; diff --git a/plugins/check_fping.c b/plugins/check_fping.c index be9362ad..db433162 100644 --- a/plugins/check_fping.c +++ b/plugins/check_fping.c @@ -492,7 +492,7 @@ void print_help (void) { printf (" %s\n", "-c, --critical=THRESHOLD"); printf (" %s\n", _("critical threshold pair")); printf (" %s\n", "-a, --alive"); - printf (" %s\n", _("Return OK after first successfull reply")); + printf (" %s\n", _("Return OK after first successful reply")); printf (" %s\n", "-b, --bytes=INTEGER"); printf (" %s (default: %d)\n", _("size of ICMP packet"),PACKET_SIZE); printf (" %s\n", "-n, --number=INTEGER"); -- cgit v1.2.3-74-g34f1 From f4930aee28ccb664691809e7dcc9198eb81429c5 Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Thu, 19 Jan 2023 23:29:01 +0100 Subject: fix check_snmp regex matches the multiplier function always tried to extract a number, even if the result is a string because of using a mib. before: ``` ./check_snmp -H hostname -P2c -c public -o IF-MIB::ifAdminStatus.11466 -vvv -r 0 /usr/bin/snmpget -Le -t 10 -r 5 -m ALL -v 2c [context] [authpriv] 10.0.13.11:161 IF-MIB::ifAdminStatus.11466 IF-MIB::ifAdminStatus.11466 = INTEGER: up(1) Processing oid 1 (line 1) oidname: IF-MIB::ifAdminStatus.11466 response: = INTEGER: up(1) SNMP OK - 0 | IF-MIB::ifAdminStatus.11466=0;; ``` the regexp 0 matches, even if the actual result is "up(1)". after this patch: ``` ./check_snmp -H hostname -P2c -c public -o IF-MIB::ifAdminStatus.11466 -vvv -r 0 /usr/bin/snmpget -Le -t 10 -r 5 -m ALL -v 2c [context] [authpriv] 10.0.13.11:161 IF-MIB::ifAdminStatus.11466 IF-MIB::ifAdminStatus.11466 = INTEGER: up(1) Processing oid 1 (line 1) oidname: IF-MIB::ifAdminStatus.11466 response: = INTEGER: up(1) SNMP CRITICAL - *up(1)* | ``` --- plugins/check_snmp.c | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_snmp.c b/plugins/check_snmp.c index 56bad880..d3968a27 100644 --- a/plugins/check_snmp.c +++ b/plugins/check_snmp.c @@ -1165,17 +1165,36 @@ nextarg (char *str) char * multiply (char *str) { - double val = strtod (str, NULL); - val *= multiplier; + char *endptr; + double val; char *conv = "%f"; + + if(verbose>2) + printf(" multiply input: %s\n", str); + + val = strtod (str, &endptr); + if ((val == 0.0) && (endptr == str)) { + if(multiplier != 1) { + die(STATE_UNKNOWN, _("multiplier set (%.1f), but input is not a number: %s"), multiplier, str); + } + return str; + } + + if(verbose>2) + printf(" multiply extracted double: %f\n", val); + val *= multiplier; if (fmtstr != "") { conv = fmtstr; } if (val == (int)val) { sprintf(str, "%.0f", val); } else { + if(verbose>2) + printf(" multiply using format: %s\n", conv); sprintf(str, conv, val); } + if(verbose>2) + printf(" multiply result: %s\n", str); return str; } -- cgit v1.2.3-74-g34f1 From 67b472f9d1d29b9de5312c46f13ca4f5a656c4da Mon Sep 17 00:00:00 2001 From: Lorenz <12514511+RincewindsHat@users.noreply.github.com> Date: Fri, 20 Jan 2023 12:08:15 +0100 Subject: check_disk: Clarify usage possibilites (#1745) * Clarify usage possibilites of check_disk * Remove superfluous newlines Co-authored-by: waja --- plugins/check_disk.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_disk.c b/plugins/check_disk.c index 7018c6fd..6de17f86 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -951,7 +951,7 @@ void print_usage (void) { printf ("%s\n", _("Usage:")); - printf (" %s -w limit -c limit [-W limit] [-K limit] {-p path | -x device}\n", progname); + printf (" %s {-w absolute_limit |-w percentage_limit% | -W inode_percentage_limit } {-c absolute_limit|-c percentage_limit% | -K inode_percentage_limit } {-p path | -x device}\n", progname); printf ("[-C] [-E] [-e] [-f] [-g group ] [-k] [-l] [-M] [-m] [-R path ] [-r path ]\n"); printf ("[-t timeout] [-u unit] [-v] [-X type] [-N type]\n"); } -- cgit v1.2.3-74-g34f1 From d9528c265b96a5a0f0c2e43ac74ab3921a2987e1 Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 30 Jan 2023 12:45:20 +0100 Subject: check_http: Fix memory reallocation error in chunk decoding logic This patch should fix an error with the way memory reallocation was used, which resulted in "realloc(): invalid next size". It is not completely clear to me as to what caused this problem, but apparently one can not depend handing a pointer to "realloc(3)" and expect that it still works afterwards, but one should/must use the one returned by the function. Also this patch replaces a variable which was used to remember the position in the array by just computing that from the current values. --- plugins/check_http.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index a9c22389..c23625e9 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -1399,7 +1399,6 @@ char *unchunk_content(const char *content) { char *endptr; long length_of_chunk = 0; size_t overall_size = 0; - char *result_ptr; while (true) { size_of_chunk = strtol(pointer, &endptr, 16); @@ -1446,7 +1445,6 @@ char *unchunk_content(const char *content) { } return NULL; } - result_ptr = result; } else { void *tmp = realloc(result, overall_size); if (tmp == NULL) { @@ -1454,11 +1452,12 @@ char *unchunk_content(const char *content) { printf("Failed to allocate memory for unchunked body\n"); } return NULL; + } else { + result = tmp; } } - memcpy(result_ptr, start_of_chunk, size_of_chunk); - result_ptr = result_ptr + size_of_chunk; + memcpy(result + (overall_size - size_of_chunk), start_of_chunk, size_of_chunk); } result[overall_size] = '\0'; -- cgit v1.2.3-74-g34f1 From d3fbcd122012af7733de3b80a692f79ad69057b2 Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 30 Jan 2023 13:33:46 +0100 Subject: check_http: Add space for ending NULL byte in array for chunked encoding --- plugins/check_http.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index c23625e9..5fa310f5 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -1438,7 +1438,8 @@ char *unchunk_content(const char *content) { overall_size += length_of_chunk; if (result == NULL) { - result = (char *)calloc(length_of_chunk, sizeof(char)); + // Size of the chunk plus the ending NULL byte + result = (char *)malloc(length_of_chunk +1); if (result == NULL) { if (verbose) { printf("Failed to allocate memory for unchunked body\n"); @@ -1446,7 +1447,8 @@ char *unchunk_content(const char *content) { return NULL; } } else { - void *tmp = realloc(result, overall_size); + // Enlarge memory to the new size plus the ending NULL byte + void *tmp = realloc(result, overall_size +1); if (tmp == NULL) { if (verbose) { printf("Failed to allocate memory for unchunked body\n"); -- cgit v1.2.3-74-g34f1 From 05ab60f8084daecf314c0a54fab19f3b169ea216 Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Wed, 1 Feb 2023 00:56:44 +0100 Subject: check_disk: Remove weird code (workaround?) which broke with gnulib update --- plugins/check_disk.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_disk.c b/plugins/check_disk.c index 6de17f86..935acce0 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -1056,7 +1056,7 @@ get_path_stats (struct parameter_list *p, struct fs_usage *fsp) { p->dfree_units = p->available*fsp->fsu_blocksize/mult; p->dtotal_units = p->total*fsp->fsu_blocksize/mult; /* Free file nodes. Not sure the workaround is required, but in case...*/ - p->inodes_free = fsp->fsu_favail > fsp->fsu_ffree ? 0 : fsp->fsu_favail; + p->inodes_free = fsp->fsu_ffree; p->inodes_free_to_root = fsp->fsu_ffree; /* Free file nodes for root. */ p->inodes_used = fsp->fsu_files - fsp->fsu_ffree; if (freespace_ignore_reserved) { -- cgit v1.2.3-74-g34f1 From f79eb4f2caf168e0599be3702244771791e23934 Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Wed, 1 Feb 2023 00:57:42 +0100 Subject: Link plugins against libcrypto to make hashes available --- plugins-root/Makefile.am | 2 +- plugins/Makefile.am | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'plugins') diff --git a/plugins-root/Makefile.am b/plugins-root/Makefile.am index 7cd2675a..40aa020d 100644 --- a/plugins-root/Makefile.am +++ b/plugins-root/Makefile.am @@ -26,7 +26,7 @@ EXTRA_PROGRAMS = pst3 EXTRA_DIST = t pst3.c -BASEOBJS = ../plugins/utils.o ../lib/libmonitoringplug.a ../gl/libgnu.a +BASEOBJS = ../plugins/utils.o ../lib/libmonitoringplug.a ../gl/libgnu.a $(LIB_CRYPTO) NETOBJS = ../plugins/netutils.o $(BASEOBJS) $(EXTRA_NETOBJS) NETLIBS = $(NETOBJS) $(SOCKETLIBS) diff --git a/plugins/Makefile.am b/plugins/Makefile.am index 3fde54d6..ab59eb73 100644 --- a/plugins/Makefile.am +++ b/plugins/Makefile.am @@ -51,10 +51,10 @@ noinst_LIBRARIES = libnpcommon.a libnpcommon_a_SOURCES = utils.c netutils.c sslutils.c runcmd.c \ popen.c utils.h netutils.h popen.h common.h runcmd.c runcmd.h -BASEOBJS = libnpcommon.a ../lib/libmonitoringplug.a ../gl/libgnu.a +BASEOBJS = libnpcommon.a ../lib/libmonitoringplug.a ../gl/libgnu.a $(LIB_CRYPTO) NETOBJS = $(BASEOBJS) $(EXTRA_NETOBLS) NETLIBS = $(NETOBJS) $(SOCKETLIBS) -SSLOBJS = $(BASEOBJS) $(NETLIBS) $(SSLLIBS) +SSLOBJS = $(BASEOBJS) $(NETLIBS) $(SSLLIBS) $(LIB_CRYPTO) TESTS_ENVIRONMENT = perl -I $(top_builddir) -I $(top_srcdir) -- cgit v1.2.3-74-g34f1 From c4704e163ebf54277ff901f06f09126ef3a3bc7f Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 2 Feb 2023 12:03:44 +0100 Subject: sslutils.c: Move function after a function it uses to avoid forward declarations --- plugins/sslutils.c | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) (limited to 'plugins') diff --git a/plugins/sslutils.c b/plugins/sslutils.c index 286273f6..4f12ddaf 100644 --- a/plugins/sslutils.c +++ b/plugins/sslutils.c @@ -191,17 +191,6 @@ int np_net_ssl_read(void *buf, int num) { return SSL_read(s, buf, num); } -int np_net_ssl_check_cert(int days_till_exp_warn, int days_till_exp_crit){ -# ifdef USE_OPENSSL - X509 *certificate = NULL; - certificate=SSL_get_peer_certificate(s); - return(np_net_ssl_check_certificate(certificate, days_till_exp_warn, days_till_exp_crit)); -# else /* ifndef USE_OPENSSL */ - printf("%s\n", _("WARNING - Plugin does not support checking certificates.")); - return STATE_WARNING; -# endif /* USE_OPENSSL */ -} - int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int days_till_exp_crit){ # ifdef USE_OPENSSL X509_NAME *subj=NULL; @@ -328,4 +317,16 @@ int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int # endif /* USE_OPENSSL */ } +int np_net_ssl_check_cert(int days_till_exp_warn, int days_till_exp_crit){ +# ifdef USE_OPENSSL + X509 *certificate = NULL; + certificate=SSL_get_peer_certificate(s); + return(np_net_ssl_check_certificate(certificate, days_till_exp_warn, days_till_exp_crit)); +# else /* ifndef USE_OPENSSL */ + printf("%s\n", _("WARNING - Plugin does not support checking certificates.")); + return STATE_WARNING; +# endif /* USE_OPENSSL */ +} + + #endif /* HAVE_SSL */ -- cgit v1.2.3-74-g34f1 From 6f0ce3804a396ce89c09f50123e5f31b5b525b31 Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Sat, 4 Feb 2023 16:19:46 +0100 Subject: fallback to SSL_CTX_use_certificate_file for gnutls --- plugins/sslutils.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/sslutils.c b/plugins/sslutils.c index 286273f6..d542c499 100644 --- a/plugins/sslutils.c +++ b/plugins/sslutils.c @@ -134,7 +134,18 @@ int np_net_ssl_init_with_hostname_version_and_cert(int sd, char *host_name, int return STATE_CRITICAL; } if (cert && privkey) { - SSL_CTX_use_certificate_chain_file(c, cert); +#ifdef USE_OPENSSL + if (!SSL_CTX_use_certificate_chain_file(c, cert)) { +#else +#if USE_GNUTLS + if (!SSL_CTX_use_certificate_file(c, cert, SSL_FILETYPE_PEM)) { +#else +#error Unported for unknown SSL library +#endif +#endif + printf ("%s\n", _("CRITICAL - Unable to open certificate chain file!\n")); + return STATE_CRITICAL; + } SSL_CTX_use_PrivateKey_file(c, privkey, SSL_FILETYPE_PEM); #ifdef USE_OPENSSL if (!SSL_CTX_check_private_key(c)) { -- cgit v1.2.3-74-g34f1 From 53f07a468db98247dc4012de0ee678f29cc2bfec Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Sun, 5 Feb 2023 20:34:41 +0100 Subject: using CURLOPT_REDIR_PROTOCOLS_STR instead of CURLOPT_REDIR_PROTOCOLS for curl >= 7.85.0 --- plugins/check_curl.c | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index c6593df1..7916eb55 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -688,9 +688,13 @@ check_http (void) handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_MAXREDIRS, max_depth+1), "CURLOPT_MAXREDIRS"); /* for now allow only http and https (we are a http(s) check plugin in the end) */ +#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 85, 0) + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_REDIR_PROTOCOLS_STR, "http,https"), "CURLOPT_REDIR_PROTOCOLS_STR"); +#else #if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 4) handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS), "CURLOPT_REDIRECT_PROTOCOLS"); #endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 4) */ +#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 85, 4) */ /* TODO: handle the following aspects of redirection, make them * command line options too later: -- cgit v1.2.3-74-g34f1 From 6d3e44d2d8395076060e9c741e9b173dc5d57b76 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 6 Feb 2023 11:39:44 +0100 Subject: check_http: Handle chunked encoding without actual content correctly --- plugins/check_http.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_http.c b/plugins/check_http.c index 5fa310f5..8dda046f 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -1462,7 +1462,13 @@ char *unchunk_content(const char *content) { memcpy(result + (overall_size - size_of_chunk), start_of_chunk, size_of_chunk); } - result[overall_size] = '\0'; + if (overall_size == 0 && result == NULL) { + // We might just have received the end chunk without previous content, so result is never allocated + result = calloc(1, sizeof(char)); + // No error handling here, we can only return NULL anyway + } else { + result[overall_size] = '\0'; + } return result; } -- cgit v1.2.3-74-g34f1 From 03efbb8e4f736bf2df5d9477dd4191501fe035ea Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 6 Feb 2023 12:15:46 +0100 Subject: check_http: Implement special case test for zero size chunk only --- plugins/tests/check_http.t | 70 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 69 insertions(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/tests/check_http.t b/plugins/tests/check_http.t index d766ac37..6078b274 100755 --- a/plugins/tests/check_http.t +++ b/plugins/tests/check_http.t @@ -9,12 +9,14 @@ use strict; use Test::More; use NPTest; use FindBin qw($Bin); +use IO::Socket::INET; $ENV{'LC_TIME'} = "C"; my $common_tests = 71; my $virtual_port_tests = 8; my $ssl_only_tests = 12; +my $chunked_encoding_special_tests = 1; # Check that all dependent modules are available eval "use HTTP::Daemon 6.01;"; plan skip_all => 'HTTP::Daemon >= 6.01 required' if $@; @@ -30,7 +32,7 @@ if ($@) { plan skip_all => "Missing required module for test: $@"; } else { if (-x "./$plugin") { - plan tests => $common_tests * 2 + $ssl_only_tests + $virtual_port_tests; + plan tests => $common_tests * 2 + $ssl_only_tests + $virtual_port_tests + $chunked_encoding_special_tests; } else { plan skip_all => "No $plugin compiled"; } @@ -51,6 +53,7 @@ my $port_http = 50000 + int(rand(1000)); my $port_https = $port_http + 1; my $port_https_expired = $port_http + 2; my $port_https_clientcert = $port_http + 3; +my $port_hacked_http = $port_http + 4; # This array keeps sockets around for implementing timeouts my @persist; @@ -72,6 +75,28 @@ if (!$pid) { } push @pids, $pid; +# Fork the hacked HTTP server +undef $pid; +$pid = fork; +defined $pid or die "Failed to fork"; +if (!$pid) { + # this is the fork + undef @pids; + my $socket = new IO::Socket::INET ( + LocalHost => '0.0.0.0', + LocalPort => $port_hacked_http, + Proto => 'tcp', + Listen => 5, + Reuse => 1 + ); + die "cannot create socket $!n" unless $socket; + my $local_sock = $socket->sockport(); + print "server waiting for client connection on port $local_sock\n"; + run_hacked_http_server ( $socket ); + die "hacked http server stopped"; +} +push @pids, $pid; + if (exists $servers->{https}) { # Fork a normal HTTPS server $pid = fork; @@ -207,6 +232,37 @@ sub run_server { } } +sub run_hacked_http_server { + my $socket = shift; + + # auto-flush on socket + $| = 1; + + + while(1) + { + # waiting for a new client connection + my $client_socket = $socket->accept(); + + # get information about a newly connected client + my $client_address = $client_socket->peerhost(); + my $client_portn = $client_socket->peerport(); + print "connection from $client_address:$client_portn"; + + # read up to 1024 characters from the connected client + my $data = ""; + $client_socket->recv($data, 1024); + print "received data: $data"; + + # write response data to the connected client + $data = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n"; + $client_socket->send($data); + + # notify client that response has been sent + shutdown($client_socket, 1); + } +} + END { foreach my $pid (@pids) { if ($pid) { print "Killing $pid\n"; kill "INT", $pid } @@ -222,6 +278,7 @@ if ($ARGV[0] && $ARGV[0] eq "-d") { my $result; my $command = "./$plugin -H 127.0.0.1"; +run_chunked_encoding_special_test( {command => "$command -p $port_hacked_http"}); run_common_tests( { command => "$command -p $port_http" } ); SKIP: { skip "HTTP::Daemon::SSL not installed", $common_tests + $ssl_only_tests if ! exists $servers->{https}; @@ -511,3 +568,14 @@ sub run_common_tests { }; is( $@, "", $cmd ); } + +sub run_chunked_encoding_special_test { + my ($opts) = @_; + my $command = $opts->{command}; + + $cmd = "$command -u / -s 'ChunkedEncodingSpecialTest'"; + eval { + $result = NPTest->testCmd( $cmd, 5 ); + }; + is( $@, "", $cmd ); +} -- cgit v1.2.3-74-g34f1 From 28b5a1cc454774474b98037acd283a1da4c3f7ad Mon Sep 17 00:00:00 2001 From: Lorenz Kästle <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 9 Feb 2023 00:35:20 +0100 Subject: Make preprocessor fallback for gnutls more readable --- plugins/sslutils.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'plugins') diff --git a/plugins/sslutils.c b/plugins/sslutils.c index d542c499..a7d80196 100644 --- a/plugins/sslutils.c +++ b/plugins/sslutils.c @@ -136,12 +136,10 @@ int np_net_ssl_init_with_hostname_version_and_cert(int sd, char *host_name, int if (cert && privkey) { #ifdef USE_OPENSSL if (!SSL_CTX_use_certificate_chain_file(c, cert)) { -#else -#if USE_GNUTLS +#elif USE_GNUTLS if (!SSL_CTX_use_certificate_file(c, cert, SSL_FILETYPE_PEM)) { #else #error Unported for unknown SSL library -#endif #endif printf ("%s\n", _("CRITICAL - Unable to open certificate chain file!\n")); return STATE_CRITICAL; -- cgit v1.2.3-74-g34f1 From 27b0c6964559ba60ff6c7a626d51e62e5256ed62 Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Sat, 11 Feb 2023 18:39:24 +0100 Subject: fixed regerror is MAX_INPUT_BUFFER writting into too small errbuf --- plugins/check_curl.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 7916eb55..406f6f88 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -173,7 +173,7 @@ double time_connect; double time_appconnect; double time_headers; double time_firstbyte; -char errbuf[CURL_ERROR_SIZE+1]; +char errbuf[MAX_INPUT_BUFFER]; CURLcode res; char url[DEFAULT_BUFFER_SIZE]; char msg[DEFAULT_BUFFER_SIZE]; -- cgit v1.2.3-74-g34f1 From f6978deaa1bf7c6a7196363104ebfcef143080ab Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Sat, 11 Feb 2023 19:11:07 +0100 Subject: added --cookie-jar and doing proper cleanup of libcurl --- plugins/check_curl.c | 47 ++++++++++++++++++++++++++++++++++------------- 1 file changed, 34 insertions(+), 13 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 406f6f88..35d1237b 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -214,6 +214,7 @@ int address_family = AF_UNSPEC; curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN; int curl_http_version = CURL_HTTP_VERSION_NONE; int automatic_decompression = FALSE; +char *cookie_jar_file = NULL; int process_arguments (int, char**); void handle_curl_option_return_code (CURLcode res, const char* option); @@ -412,6 +413,19 @@ lookup_host (const char *host, char *buf, size_t buflen) return 0; } +static void +cleanup (void) +{ + curlhelp_free_statusline(&status_line); + curl_easy_cleanup (curl); + curl_global_cleanup (); + curlhelp_freewritebuffer (&body_buf); + curlhelp_freewritebuffer (&header_buf); + if (!strcmp (http_method, "PUT")) { + curlhelp_freereadbuffer (&put_buf); + } +} + int check_http (void) { @@ -743,7 +757,16 @@ check_http (void) handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_INFILESIZE, (curl_off_t)strlen (http_post_data)), "CURLOPT_INFILESIZE"); } } + + /* cookie handling */ + if (cookie_jar_file != NULL) { + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_COOKIEJAR, cookie_jar_file), "CURLOPT_COOKIEJAR"); + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_COOKIEFILE, cookie_jar_file), "CURLOPT_COOKIEFILE"); + } + /* register cleanup function to shut down libcurl properly */ + atexit (cleanup); + /* do the request */ res = curl_easy_perform(curl); @@ -1021,7 +1044,7 @@ GOT_FIRST_CERT: else msg[strlen(msg)-3] = '\0'; } - + /* TODO: separate _() msg and status code: die (result, "HTTP %s: %s\n", state_text(result), msg); */ die (result, "HTTP %s: %s %d %s%s%s - %d bytes in %.3f second response time %s|%s\n%s%s", state_text(result), string_statuscode (status_line.http_major, status_line.http_minor), @@ -1033,16 +1056,6 @@ GOT_FIRST_CERT: (show_body ? body_buf.buf : ""), (show_body ? "\n" : "") ); - /* proper cleanup after die? */ - curlhelp_free_statusline(&status_line); - curl_easy_cleanup (curl); - curl_global_cleanup (); - curlhelp_freewritebuffer (&body_buf); - curlhelp_freewritebuffer (&header_buf); - if (!strcmp (http_method, "PUT")) { - curlhelp_freereadbuffer (&put_buf); - } - return result; } @@ -1239,7 +1252,8 @@ process_arguments (int argc, char **argv) CONTINUE_AFTER_CHECK_CERT, CA_CERT_OPTION, HTTP_VERSION_OPTION, - AUTOMATIC_DECOMPRESSION + AUTOMATIC_DECOMPRESSION, + COOKIE_JAR }; int option = 0; @@ -1285,6 +1299,7 @@ process_arguments (int argc, char **argv) {"max-redirs", required_argument, 0, MAX_REDIRS_OPTION}, {"http-version", required_argument, 0, HTTP_VERSION_OPTION}, {"enable-automatic-decompression", no_argument, 0, AUTOMATIC_DECOMPRESSION}, + {"cookie-jar", required_argument, 0, COOKIE_JAR}, {0, 0, 0, 0} }; @@ -1691,6 +1706,9 @@ process_arguments (int argc, char **argv) case AUTOMATIC_DECOMPRESSION: automatic_decompression = TRUE; break; + case COOKIE_JAR: + cookie_jar_file = optarg; + break; case '?': /* print short usage statement if args not parsable */ usage5 (); @@ -1910,6 +1928,8 @@ print_help (void) printf (" %s\n", _("1.0 = HTTP/1.0, 1.1 = HTTP/1.1, 2.0 = HTTP/2 (HTTP/2 will fail without -S)")); printf (" %s\n", "--enable-automatic-decompression"); printf (" %s\n", _("Enable automatic decompression of body (CURLOPT_ACCEPT_ENCODING).")); + printf (" %s\n", "---cookie-jar=FILE"); + printf (" %s\n", _("Store cookies in the cookie jar and send them out when requested.")); printf ("\n"); printf (UT_WARN_CRIT); @@ -1994,7 +2014,8 @@ print_usage (void) printf (" [-P string] [-m :] [-4|-6] [-N] [-M ]\n"); printf (" [-A string] [-k string] [-S ] [--sni]\n"); printf (" [-T ] [-j method]\n"); - printf (" [--http-version=]\n"); + printf (" [--http-version=] [--enable-automatic-decompression]\n"); + printf (" [--cookie-jar=\n"); printf (" %s -H | -I -C [,]\n",progname); printf (" [-p ] [-t ] [-4|-6] [--sni]\n"); printf ("\n"); -- cgit v1.2.3-74-g34f1 From 40da85e6913ba4898f5a80772c7b3ea0cba0d3eb Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Sun, 12 Feb 2023 12:11:38 +0100 Subject: better cleanup of curl structures and buffers --- plugins/check_curl.c | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 35d1237b..a49cac8a 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -161,9 +161,13 @@ char *http_post_data = NULL; char *http_content_type = NULL; CURL *curl; struct curl_slist *header_list = NULL; +int body_buf_initialized = 0; curlhelp_write_curlbuf body_buf; +int header_buf_initialized = 0; curlhelp_write_curlbuf header_buf; +int status_line_initialized = 0; curlhelp_statusline status_line; +int put_buf_initialized = 0; curlhelp_read_curlbuf put_buf; char http_header[DEFAULT_BUFFER_SIZE]; long code; @@ -416,14 +420,12 @@ lookup_host (const char *host, char *buf, size_t buflen) static void cleanup (void) { - curlhelp_free_statusline(&status_line); + if (status_line_initialized) curlhelp_free_statusline(&status_line); curl_easy_cleanup (curl); curl_global_cleanup (); - curlhelp_freewritebuffer (&body_buf); - curlhelp_freewritebuffer (&header_buf); - if (!strcmp (http_method, "PUT")) { - curlhelp_freereadbuffer (&put_buf); - } + if (body_buf_initialized) curlhelp_freewritebuffer (&body_buf); + if (header_buf_initialized) curlhelp_freewritebuffer (&header_buf); + if (put_buf_initialized) curlhelp_freereadbuffer (&put_buf); } int @@ -441,9 +443,14 @@ check_http (void) if (curl_global_init (CURL_GLOBAL_DEFAULT) != CURLE_OK) die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_global_init failed\n"); - if ((curl = curl_easy_init()) == NULL) + if ((curl = curl_easy_init()) == NULL) { + curl_global_cleanup (); die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_easy_init failed\n"); + } + /* register cleanup function to shut down libcurl properly */ + atexit (cleanup); + if (verbose >= 1) handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_VERBOSE, TRUE), "CURLOPT_VERBOSE"); @@ -460,12 +467,14 @@ check_http (void) /* initialize buffer for body of the answer */ if (curlhelp_initwritebuffer(&body_buf) < 0) die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for body\n"); + body_buf_initialized = 1; handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback), "CURLOPT_WRITEFUNCTION"); handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEDATA, (void *)&body_buf), "CURLOPT_WRITEDATA"); /* initialize buffer for header of the answer */ if (curlhelp_initwritebuffer( &header_buf ) < 0) die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for header\n" ); + header_buf_initialized = 1; handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_HEADERFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback), "CURLOPT_HEADERFUNCTION"); handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEHEADER, (void *)&header_buf), "CURLOPT_WRITEHEADER"); @@ -752,7 +761,9 @@ check_http (void) handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_POSTFIELDS, http_post_data), "CURLOPT_POSTFIELDS"); } else if (!strcmp(http_method, "PUT")) { handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_READFUNCTION, (curl_read_callback)curlhelp_buffer_read_callback), "CURLOPT_READFUNCTION"); - curlhelp_initreadbuffer (&put_buf, http_post_data, strlen (http_post_data)); + if (curlhelp_initreadbuffer (&put_buf, http_post_data, strlen (http_post_data)) < 0) + die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating read buffer for PUT\n"); + put_buf_initialized = 1; handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_READDATA, (void *)&put_buf), "CURLOPT_READDATA"); handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_INFILESIZE, (curl_off_t)strlen (http_post_data)), "CURLOPT_INFILESIZE"); } @@ -764,9 +775,6 @@ check_http (void) handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_COOKIEFILE, cookie_jar_file), "CURLOPT_COOKIEFILE"); } - /* register cleanup function to shut down libcurl properly */ - atexit (cleanup); - /* do the request */ res = curl_easy_perform(curl); @@ -2159,6 +2167,7 @@ curlhelp_parse_statusline (const char *buf, curlhelp_statusline *status_line) first_line_len = (size_t)(first_line_end - buf); status_line->first_line = (char *)malloc (first_line_len + 1); + status_line_initialized = 1; if (status_line->first_line == NULL) return -1; memcpy (status_line->first_line, buf, first_line_len); status_line->first_line[first_line_len] = '\0'; -- cgit v1.2.3-74-g34f1 From 6563267c3ad84bcc4779d282b5ae20520a4a2a6b Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Sun, 12 Feb 2023 13:16:25 +0100 Subject: fixed double frees when doing old-style redirects --- plugins/check_curl.c | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index a49cac8a..1127d601 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -160,6 +160,8 @@ char *http_method = NULL; char *http_post_data = NULL; char *http_content_type = NULL; CURL *curl; +int curl_global_initialized = 0; +int curl_easy_initialized = 0; struct curl_slist *header_list = NULL; int body_buf_initialized = 0; curlhelp_write_curlbuf body_buf; @@ -421,11 +423,17 @@ static void cleanup (void) { if (status_line_initialized) curlhelp_free_statusline(&status_line); - curl_easy_cleanup (curl); - curl_global_cleanup (); + status_line_initialized = 0; + if (curl_easy_initialized) curl_easy_cleanup (curl); + curl_easy_initialized = 0; + if (curl_global_initialized) curl_global_cleanup (); + curl_global_initialized = 0; if (body_buf_initialized) curlhelp_freewritebuffer (&body_buf); + body_buf_initialized = 0; if (header_buf_initialized) curlhelp_freewritebuffer (&header_buf); + header_buf_initialized = 0; if (put_buf_initialized) curlhelp_freereadbuffer (&put_buf); + put_buf_initialized = 0; } int @@ -442,11 +450,12 @@ check_http (void) /* initialize curl */ if (curl_global_init (CURL_GLOBAL_DEFAULT) != CURLE_OK) die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_global_init failed\n"); + curl_global_initialized = 1; if ((curl = curl_easy_init()) == NULL) { - curl_global_cleanup (); die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_easy_init failed\n"); } + curl_easy_initialized = 1; /* register cleanup function to shut down libcurl properly */ atexit (cleanup); @@ -903,6 +912,7 @@ GOT_FIRST_CERT: /* we cannot know the major/minor version here for sure as we cannot parse the first line */ die (STATE_CRITICAL, "HTTP CRITICAL HTTP/x.x %ld unknown - %s", code, msg); } + status_line_initialized = 1; /* get result code from cURL */ handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &code), "CURLINFO_RESPONSE_CODE"); @@ -1234,6 +1244,7 @@ redir (curlhelp_write_curlbuf* header_buf) * attached to the URL in Location */ + cleanup (); check_http (); } @@ -2167,7 +2178,6 @@ curlhelp_parse_statusline (const char *buf, curlhelp_statusline *status_line) first_line_len = (size_t)(first_line_end - buf); status_line->first_line = (char *)malloc (first_line_len + 1); - status_line_initialized = 1; if (status_line->first_line == NULL) return -1; memcpy (status_line->first_line, buf, first_line_len); status_line->first_line[first_line_len] = '\0'; -- cgit v1.2.3-74-g34f1 From 8e1bbf5e6ed4069d4256bf549a408bb8759861fa Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Sun, 12 Feb 2023 15:09:02 +0100 Subject: changed #else/#if to #elif in libcurl library checks --- plugins/check_curl.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 1127d601..284cf4ea 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -722,11 +722,9 @@ check_http (void) /* for now allow only http and https (we are a http(s) check plugin in the end) */ #if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 85, 0) handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_REDIR_PROTOCOLS_STR, "http,https"), "CURLOPT_REDIR_PROTOCOLS_STR"); -#else -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 4) +#elif LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 4) handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS), "CURLOPT_REDIRECT_PROTOCOLS"); -#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 4) */ -#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 85, 4) */ +#endif /* TODO: handle the following aspects of redirection, make them * command line options too later: -- cgit v1.2.3-74-g34f1 From ad6b638acb420f4416b10cf52fdd6c75c3c8e6fa Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Fri, 17 Feb 2023 14:03:55 +0100 Subject: using real boolean in check_curl --- plugins/check_curl.c | 160 ++++++++++++++++++++++++++------------------------- 1 file changed, 82 insertions(+), 78 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 284cf4ea..c37d45d9 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -37,6 +37,7 @@ const char *progname = "check_curl"; const char *copyright = "2006-2019"; const char *email = "devel@monitoring-plugins.org"; +#include #include #include "common.h" @@ -131,14 +132,14 @@ regmatch_t pmatch[REGS]; char regexp[MAX_RE_SIZE]; int cflags = REG_NOSUB | REG_EXTENDED | REG_NEWLINE; int errcode; -int invert_regex = 0; +bool invert_regex = false; char *server_address = NULL; char *host_name = NULL; char *server_url = 0; char server_ip[DEFAULT_BUFFER_SIZE]; struct curl_slist *server_ips = NULL; -int specify_port = FALSE; +bool specify_port = false; unsigned short server_port = HTTP_PORT; unsigned short virtual_port = 0; int host_name_length; @@ -150,8 +151,8 @@ int days_till_exp_warn, days_till_exp_crit; thresholds *thlds; char user_agent[DEFAULT_BUFFER_SIZE]; int verbose = 0; -int show_extended_perfdata = FALSE; -int show_body = FALSE; +bool show_extended_perfdata = false; +bool show_body = false; int min_page_len = 0; int max_page_len = 0; int redir_depth = 0; @@ -160,16 +161,16 @@ char *http_method = NULL; char *http_post_data = NULL; char *http_content_type = NULL; CURL *curl; -int curl_global_initialized = 0; -int curl_easy_initialized = 0; +bool curl_global_initialized = false; +bool curl_easy_initialized = false; struct curl_slist *header_list = NULL; -int body_buf_initialized = 0; +bool body_buf_initialized = false; curlhelp_write_curlbuf body_buf; -int header_buf_initialized = 0; +bool header_buf_initialized = false; curlhelp_write_curlbuf header_buf; -int status_line_initialized = 0; +bool status_line_initialized = false; curlhelp_statusline status_line; -int put_buf_initialized = 0; +bool put_buf_initialized = false; curlhelp_read_curlbuf put_buf; char http_header[DEFAULT_BUFFER_SIZE]; long code; @@ -192,14 +193,14 @@ char user_auth[MAX_INPUT_BUFFER] = ""; char proxy_auth[MAX_INPUT_BUFFER] = ""; char **http_opt_headers; int http_opt_headers_count = 0; -int display_html = FALSE; +bool display_html = false; int onredirect = STATE_OK; int followmethod = FOLLOW_HTTP_CURL; int followsticky = STICKY_NONE; -int use_ssl = FALSE; -int use_sni = TRUE; -int check_cert = FALSE; -int continue_after_check_cert = FALSE; +bool use_ssl = false; +bool use_sni = true; +bool check_cert = false; +bool continue_after_check_cert = false; typedef union { struct curl_slist* to_info; struct curl_certinfo* to_certinfo; @@ -209,20 +210,20 @@ int ssl_version = CURL_SSLVERSION_DEFAULT; char *client_cert = NULL; char *client_privkey = NULL; char *ca_cert = NULL; -int verify_peer_and_host = FALSE; -int is_openssl_callback = FALSE; +bool verify_peer_and_host = false; +bool is_openssl_callback = false; #if defined(HAVE_SSL) && defined(USE_OPENSSL) X509 *cert = NULL; #endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */ -int no_body = FALSE; +bool no_body = false; int maximum_age = -1; int address_family = AF_UNSPEC; curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN; int curl_http_version = CURL_HTTP_VERSION_NONE; -int automatic_decompression = FALSE; +bool automatic_decompression = false; char *cookie_jar_file = NULL; -int process_arguments (int, char**); +bool process_arguments (int, char**); void handle_curl_option_return_code (CURLcode res, const char* option); int check_http (void); void redir (curlhelp_write_curlbuf*); @@ -276,10 +277,10 @@ main (int argc, char **argv) progname, NP_VERSION, VERSION, curl_version()); /* parse arguments */ - if (process_arguments (argc, argv) == ERROR) + if (process_arguments (argc, argv) == false) usage4 (_("Could not parse arguments")); - if (display_html == TRUE) + if (display_html) printf ("", use_ssl ? "https" : "http", host_name ? host_name : server_address, @@ -423,17 +424,17 @@ static void cleanup (void) { if (status_line_initialized) curlhelp_free_statusline(&status_line); - status_line_initialized = 0; + status_line_initialized = false; if (curl_easy_initialized) curl_easy_cleanup (curl); - curl_easy_initialized = 0; + curl_easy_initialized = false; if (curl_global_initialized) curl_global_cleanup (); - curl_global_initialized = 0; + curl_global_initialized = false; if (body_buf_initialized) curlhelp_freewritebuffer (&body_buf); - body_buf_initialized = 0; + body_buf_initialized = false; if (header_buf_initialized) curlhelp_freewritebuffer (&header_buf); - header_buf_initialized = 0; + header_buf_initialized = false; if (put_buf_initialized) curlhelp_freereadbuffer (&put_buf); - put_buf_initialized = 0; + put_buf_initialized = false; } int @@ -450,18 +451,18 @@ check_http (void) /* initialize curl */ if (curl_global_init (CURL_GLOBAL_DEFAULT) != CURLE_OK) die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_global_init failed\n"); - curl_global_initialized = 1; + curl_global_initialized = true; if ((curl = curl_easy_init()) == NULL) { die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_easy_init failed\n"); } - curl_easy_initialized = 1; + curl_easy_initialized = true; /* register cleanup function to shut down libcurl properly */ atexit (cleanup); if (verbose >= 1) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_VERBOSE, TRUE), "CURLOPT_VERBOSE"); + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_VERBOSE, 1), "CURLOPT_VERBOSE"); /* print everything on stdout like check_http would do */ handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_STDERR, stdout), "CURLOPT_STDERR"); @@ -476,14 +477,14 @@ check_http (void) /* initialize buffer for body of the answer */ if (curlhelp_initwritebuffer(&body_buf) < 0) die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for body\n"); - body_buf_initialized = 1; + body_buf_initialized = true; handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback), "CURLOPT_WRITEFUNCTION"); handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEDATA, (void *)&body_buf), "CURLOPT_WRITEDATA"); /* initialize buffer for header of the answer */ if (curlhelp_initwritebuffer( &header_buf ) < 0) die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for header\n" ); - header_buf_initialized = 1; + header_buf_initialized = true; handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_HEADERFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback), "CURLOPT_HEADERFUNCTION"); handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEHEADER, (void *)&header_buf), "CURLOPT_WRITEHEADER"); @@ -544,7 +545,7 @@ check_http (void) /* disable body for HEAD request */ if (http_method && !strcmp (http_method, "HEAD" )) { - no_body = TRUE; + no_body = true; } /* set HTTP protocol version */ @@ -641,7 +642,7 @@ check_http (void) #ifdef USE_OPENSSL /* libcurl and monitoring plugins built with OpenSSL, good */ handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION"); - is_openssl_callback = TRUE; + is_openssl_callback = true; #else /* USE_OPENSSL */ #endif /* USE_OPENSSL */ /* libcurl is built with OpenSSL, monitoring plugins, so falling @@ -770,7 +771,7 @@ check_http (void) handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_READFUNCTION, (curl_read_callback)curlhelp_buffer_read_callback), "CURLOPT_READFUNCTION"); if (curlhelp_initreadbuffer (&put_buf, http_post_data, strlen (http_post_data)) < 0) die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating read buffer for PUT\n"); - put_buf_initialized = 1; + put_buf_initialized = true; handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_READDATA, (void *)&put_buf), "CURLOPT_READDATA"); handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_INFILESIZE, (curl_off_t)strlen (http_post_data)), "CURLOPT_INFILESIZE"); } @@ -801,15 +802,15 @@ check_http (void) /* certificate checks */ #ifdef LIBCURL_FEATURE_SSL - if (use_ssl == TRUE) { - if (check_cert == TRUE) { + if (use_ssl) { + if (check_cert) { if (is_openssl_callback) { #ifdef USE_OPENSSL /* check certificate with OpenSSL functions, curl has been built against OpenSSL * and we actually have OpenSSL in the monitoring tools */ result = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit); - if (continue_after_check_cert == FALSE) { + if (!continue_after_check_cert) { return result; } #else /* USE_OPENSSL */ @@ -851,7 +852,7 @@ GOT_FIRST_CERT: } BIO_free (cert_BIO); result = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit); - if (continue_after_check_cert == FALSE) { + if (!continue_after_check_cert) { return result; } #else /* USE_OPENSSL */ @@ -859,7 +860,7 @@ GOT_FIRST_CERT: * so we use the libcurl CURLINFO data */ result = net_noopenssl_check_certificate(&cert_ptr, days_till_exp_warn, days_till_exp_crit); - if (continue_after_check_cert == FALSE) { + if (!continue_after_check_cert) { return result; } #endif /* USE_OPENSSL */ @@ -887,7 +888,7 @@ GOT_FIRST_CERT: perfd_time(total_time), perfd_size(page_len), perfd_time_connect(time_connect), - use_ssl == TRUE ? perfd_time_ssl (time_appconnect-time_connect) : "", + use_ssl ? perfd_time_ssl (time_appconnect-time_connect) : "", perfd_time_headers(time_headers - time_appconnect), perfd_time_firstbyte(time_firstbyte - time_headers), perfd_time_transfer(total_time-time_firstbyte) @@ -910,7 +911,7 @@ GOT_FIRST_CERT: /* we cannot know the major/minor version here for sure as we cannot parse the first line */ die (STATE_CRITICAL, "HTTP CRITICAL HTTP/x.x %ld unknown - %s", code, msg); } - status_line_initialized = 1; + status_line_initialized = true; /* get result code from cURL */ handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &code), "CURLINFO_RESPONSE_CODE"); @@ -1023,12 +1024,12 @@ GOT_FIRST_CERT: if (strlen (regexp)) { errcode = regexec (&preg, body_buf.buf, REGS, pmatch, 0); - if ((errcode == 0 && invert_regex == 0) || (errcode == REG_NOMATCH && invert_regex == 1)) { + if ((errcode == 0 && !invert_regex) || (errcode == REG_NOMATCH && invert_regex)) { /* OK - No-op to avoid changing the logic around it */ result = max_state_alt(STATE_OK, result); } - else if ((errcode == REG_NOMATCH && invert_regex == 0) || (errcode == 0 && invert_regex == 1)) { - if (invert_regex == 0) + else if ((errcode == REG_NOMATCH && !invert_regex) || (errcode == 0 && invert_regex)) { + if (!invert_regex) snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spattern not found, "), msg); else snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spattern found, "), msg); @@ -1167,7 +1168,10 @@ redir (curlhelp_write_curlbuf* header_buf) } } - use_ssl = !uri_strcmp (uri.scheme, "https"); + if (!uri_strcmp (uri.scheme, "https")) + use_ssl = true; + else + use_ssl = false; /* we do a sloppy test here only, because uriparser would have failed * above, if the port would be invalid, we just check for MAX_PORT @@ -1255,7 +1259,7 @@ test_file (char *path) usage2 (_("file does not exist or is not readable"), path); } -int +bool process_arguments (int argc, char **argv) { char *p; @@ -1321,7 +1325,7 @@ process_arguments (int argc, char **argv) }; if (argc < 2) - return ERROR; + return false; /* support check_http compatible arguments */ for (c = 1; c < argc; c++) { @@ -1401,7 +1405,7 @@ process_arguments (int argc, char **argv) if( strtol(optarg, NULL, 10) > MAX_PORT) usage2 (_("Invalid port number, supplied port number is too big"), optarg); server_port = (unsigned short)strtol(optarg, NULL, 10); - specify_port = TRUE; + specify_port = true; } break; case 'a': /* authorization info */ @@ -1435,10 +1439,10 @@ process_arguments (int argc, char **argv) http_opt_headers[http_opt_headers_count - 1] = optarg; break; case 'L': /* show html link */ - display_html = TRUE; + display_html = true; break; case 'n': /* do not show html link */ - display_html = FALSE; + display_html = false; break; case 'C': /* Check SSL cert validity */ #ifdef LIBCURL_FEATURE_SSL @@ -1459,12 +1463,12 @@ process_arguments (int argc, char **argv) usage2 (_("Invalid certificate expiration period"), optarg); days_till_exp_warn = atoi (optarg); } - check_cert = TRUE; + check_cert = true; goto enable_ssl; #endif case CONTINUE_AFTER_CHECK_CERT: /* don't stop after the certificate is checked */ #ifdef HAVE_SSL - continue_after_check_cert = TRUE; + continue_after_check_cert = true; break; #endif case 'J': /* use client certificate */ @@ -1487,13 +1491,13 @@ process_arguments (int argc, char **argv) #endif #ifdef LIBCURL_FEATURE_SSL case 'D': /* verify peer certificate & host */ - verify_peer_and_host = TRUE; + verify_peer_and_host = true; break; #endif case 'S': /* use SSL */ #ifdef LIBCURL_FEATURE_SSL enable_ssl: - use_ssl = TRUE; + use_ssl = true; /* ssl_version initialized to CURL_SSLVERSION_DEFAULT as a default. * Only set if it's non-zero. This helps when we include multiple * parameters, like -S and -C combinations */ @@ -1567,15 +1571,15 @@ process_arguments (int argc, char **argv) #endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0) */ if (verbose >= 2) printf(_("* Set SSL/TLS version to %d\n"), ssl_version); - if (specify_port == FALSE) + if (!specify_port) server_port = HTTPS_PORT; break; #else /* LIBCURL_FEATURE_SSL */ /* -C -J and -K fall through to here without SSL */ usage4 (_("Invalid option - SSL is not available")); break; - case SNI_OPTION: /* --sni is parsed, but ignored, the default is TRUE with libcurl */ - use_sni = TRUE; + case SNI_OPTION: /* --sni is parsed, but ignored, the default is true with libcurl */ + use_sni = true; break; #endif /* LIBCURL_FEATURE_SSL */ case MAX_REDIRS_OPTION: @@ -1636,11 +1640,11 @@ process_arguments (int argc, char **argv) if (errcode != 0) { (void) regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); printf (_("Could Not Compile Regular Expression: %s"), errbuf); - return ERROR; + return false; } break; case INVERT_REGEX: - invert_regex = 1; + invert_regex = true; break; case '4': address_family = AF_INET; @@ -1675,7 +1679,7 @@ process_arguments (int argc, char **argv) break; } case 'N': /* no-body */ - no_body = TRUE; + no_body = true; break; case 'M': /* max-age */ { @@ -1698,10 +1702,10 @@ process_arguments (int argc, char **argv) } break; case 'E': /* show extended perfdata */ - show_extended_perfdata = TRUE; + show_extended_perfdata = true; break; case 'B': /* print body content after status line */ - show_body = TRUE; + show_body = true; break; case HTTP_VERSION_OPTION: curl_http_version = CURL_HTTP_VERSION_NONE; @@ -1721,7 +1725,7 @@ process_arguments (int argc, char **argv) } break; case AUTOMATIC_DECOMPRESSION: - automatic_decompression = TRUE; + automatic_decompression = true; break; case COOKIE_JAR: cookie_jar_file = optarg; @@ -1765,52 +1769,52 @@ process_arguments (int argc, char **argv) virtual_port = server_port; else { if ((use_ssl && server_port == HTTPS_PORT) || (!use_ssl && server_port == HTTP_PORT)) - if(specify_port == FALSE) + if(!specify_port) server_port = virtual_port; } - return TRUE; + return true; } char *perfd_time (double elapsed_time) { return fperfdata ("time", elapsed_time, "s", - thlds->warning?TRUE:FALSE, thlds->warning?thlds->warning->end:0, - thlds->critical?TRUE:FALSE, thlds->critical?thlds->critical->end:0, - TRUE, 0, TRUE, socket_timeout); + thlds->warning?true:false, thlds->warning?thlds->warning->end:0, + thlds->critical?true:false, thlds->critical?thlds->critical->end:0, + true, 0, true, socket_timeout); } char *perfd_time_connect (double elapsed_time_connect) { - return fperfdata ("time_connect", elapsed_time_connect, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout); + return fperfdata ("time_connect", elapsed_time_connect, "s", false, 0, false, 0, false, 0, true, socket_timeout); } char *perfd_time_ssl (double elapsed_time_ssl) { - return fperfdata ("time_ssl", elapsed_time_ssl, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout); + return fperfdata ("time_ssl", elapsed_time_ssl, "s", false, 0, false, 0, false, 0, true, socket_timeout); } char *perfd_time_headers (double elapsed_time_headers) { - return fperfdata ("time_headers", elapsed_time_headers, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout); + return fperfdata ("time_headers", elapsed_time_headers, "s", false, 0, false, 0, false, 0, true, socket_timeout); } char *perfd_time_firstbyte (double elapsed_time_firstbyte) { - return fperfdata ("time_firstbyte", elapsed_time_firstbyte, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout); + return fperfdata ("time_firstbyte", elapsed_time_firstbyte, "s", false, 0, false, 0, false, 0, true, socket_timeout); } char *perfd_time_transfer (double elapsed_time_transfer) { - return fperfdata ("time_transfer", elapsed_time_transfer, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout); + return fperfdata ("time_transfer", elapsed_time_transfer, "s", false, 0, false, 0, false, 0, true, socket_timeout); } char *perfd_size (int page_len) { return perfdata ("size", page_len, "B", - (min_page_len>0?TRUE:FALSE), min_page_len, - (min_page_len>0?TRUE:FALSE), 0, - TRUE, 0, FALSE, 0); + (min_page_len>0?true:false), min_page_len, + (min_page_len>0?true:false), 0, + true, 0, false, 0); } void -- cgit v1.2.3-74-g34f1