From 8cf31437e99167ad9c260e6677b4d1ed31a34d56 Mon Sep 17 00:00:00 2001 From: Kristian Schuster <116557017+KriSchu@users.noreply.github.com> Date: Mon, 24 Oct 2022 17:29:53 +0200 Subject: check_disk: add ignore-missing option to return OK for missing fs There a situations where UNKNOWN or CRITICAL services are not wanted when a filesystem is missing, a regex does not match or the filesystem is inaccessible on a system. This new option helps to have the service in state OK. --- plugins/check_disk.c | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) (limited to 'plugins') diff --git a/plugins/check_disk.c b/plugins/check_disk.c index 7018c6fd..8df9e7ec 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -112,7 +112,8 @@ enum { SYNC_OPTION = CHAR_MAX + 1, NO_SYNC_OPTION, - BLOCK_SIZE_OPTION + BLOCK_SIZE_OPTION, + IGNORE_MISSING }; #ifdef _AIX @@ -140,6 +141,7 @@ int verbose = 0; int erronly = FALSE; int display_mntp = FALSE; int exact_match = FALSE; +int ignore_missing = FALSE; int freespace_ignore_reserved = FALSE; int display_inodes_perfdata = FALSE; char *warn_freespace_units = NULL; @@ -219,7 +221,9 @@ main (int argc, char **argv) temp_list = path_select_list; while (temp_list) { - if (! temp_list->best_match) { + if (! temp_list->best_match && ignore_missing == 1) { + die (STATE_OK, _("DISK %s: %s not found (ignoring)\n"), _("OK"), temp_list->name); + } else if (! temp_list->best_match) { die (STATE_CRITICAL, _("DISK %s: %s not found\n"), _("CRITICAL"), temp_list->name); } @@ -481,6 +485,7 @@ process_arguments (int argc, char **argv) {"ignore-ereg-partition", required_argument, 0, 'i'}, {"ignore-eregi-path", required_argument, 0, 'I'}, {"ignore-eregi-partition", required_argument, 0, 'I'}, + {"ignore-missing", no_argument, 0, IGNORE_MISSING}, {"local", no_argument, 0, 'l'}, {"stat-remote-fs", no_argument, 0, 'L'}, {"iperfdata", no_argument, 0, 'P'}, @@ -718,6 +723,9 @@ process_arguments (int argc, char **argv) cflags = default_cflags; break; + case IGNORE_MISSING: + ignore_missing = 1; + break; case 'A': optarg = strdup(".*"); // Intentional fallthrough @@ -753,7 +761,10 @@ process_arguments (int argc, char **argv) } } - if (!fnd) + if (!fnd && ignore_missing == 1) + die (STATE_OK, "DISK %s: %s - %s\n",_("OK"), + _("Regular expression did not match any path or disk (ignoring)"), optarg); + else if (!fnd) die (STATE_UNKNOWN, "DISK %s: %s - %s\n",_("UNKNOWN"), _("Regular expression did not match any path or disk"), optarg); @@ -923,6 +934,9 @@ print_help (void) printf (" %s\n", _("Regular expression to ignore selected path/partition (case insensitive) (may be repeated)")); printf (" %s\n", "-i, --ignore-ereg-path=PATH, --ignore-ereg-partition=PARTITION"); printf (" %s\n", _("Regular expression to ignore selected path or partition (may be repeated)")); + printf (" %s\n", "--ignore-missing"); + printf (" %s\n", _("Return OK if no filesystem matches, filesystem does not exist or is inaccessible.")); + printf (" %s\n", _("(Provide this option before -r / --ereg-path if used)")); printf (UT_PLUG_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); printf (" %s\n", "-u, --units=STRING"); printf (" %s\n", _("Choose bytes, kB, MB, GB, TB (default: MB)")); @@ -965,8 +979,13 @@ stat_path (struct parameter_list *p) if (stat (p->name, &stat_buf[0])) { if (verbose >= 3) printf("stat failed on %s\n", p->name); - printf("DISK %s - ", _("CRITICAL")); - die (STATE_CRITICAL, _("%s %s: %s\n"), p->name, _("is not accessible"), strerror(errno)); + if (ignore_missing == 1) { + printf("DISK %s - ", _("OK")); + die (STATE_OK, _("%s %s: %s\n"), p->name, _("is not accessible (ignoring)"), strerror(errno)); + } else { + printf("DISK %s - ", _("CRITICAL")); + die (STATE_CRITICAL, _("%s %s: %s\n"), p->name, _("is not accessible"), strerror(errno)); + } } } -- cgit v1.2.3-74-g34f1 From 0d562a356f45f645014c3908178fc13876006f6e Mon Sep 17 00:00:00 2001 From: Kristian Schuster <116557017+KriSchu@users.noreply.github.com> Date: Tue, 25 Oct 2022 20:49:51 +0200 Subject: check_disk: add tests for new option --ignore-missing --- plugins/t/check_disk.t | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'plugins') diff --git a/plugins/t/check_disk.t b/plugins/t/check_disk.t index ec527e7f..bea34a4c 100644 --- a/plugins/t/check_disk.t +++ b/plugins/t/check_disk.t @@ -351,3 +351,18 @@ unlike( $result->output, qr/$mountpoint2_valid/, "output data does not have $mou $result = NPTest->testCmd( "./check_disk -w 0% -c 0% -p $mountpoint_valid -p $mountpoint2_valid -i '^barbazJodsf\$'"); like( $result->output, qr/$mountpoint_valid/, "ignore: output data does have $mountpoint_valid when regex doesn't match"); like( $result->output, qr/$mountpoint2_valid/,"ignore: output data does have $mountpoint2_valid when regex doesn't match"); + +# ignore-missing: exit okay, when fs is not accessible +$result = NPTest->testCmd( "./check_disk --ignore-missing -w 0% -c 0% -p /bob"); +cmp_ok( $result->return_code, '==', 0, "ignore-missing: return okay for not existing filesystem /bob"); +like( $result->output, '/^DISK OK - /bob is not accessible .*$/', 'Output OK'); + +# ignore-missing: exit okay, when regex does not match +$result = NPTest->testCmd( "./check_disk --ignore-missing -w 0% -c 0% -r /bob"); +cmp_ok( $result->return_code, '==', 0, "ignore-missing: return okay for regular expression not matching"); +like( $result->output, '/^DISK OK: Regular expression did not match any path or disk.*$/', 'Output OK'); + +# ignore-missing: exit okay, when fs with exact match (-E) is not found +$result = NPTest->testCmd( "./check_disk --ignore-missing -E -w 0% -c 0% -p /etc"); +cmp_ok( $result->return_code, '==', 0, "ignore-missing: return okay when exact match does not find fs"); +like( $result->output, '/^DISK OK: /etc not found.*$/', 'Output OK'); -- cgit v1.2.3-74-g34f1 From bacacd2cb38c7d7a695a6f75f699168d9df0132d Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Wed, 26 Oct 2022 14:03:22 +0200 Subject: check_disk: adjust test plan --- plugins/t/check_disk.t | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/t/check_disk.t b/plugins/t/check_disk.t index bea34a4c..a534fd4a 100644 --- a/plugins/t/check_disk.t +++ b/plugins/t/check_disk.t @@ -23,7 +23,7 @@ my $mountpoint2_valid = getTestParameter( "NP_MOUNTPOINT2_VALID", "Path to anoth if ($mountpoint_valid eq "" or $mountpoint2_valid eq "") { plan skip_all => "Need 2 mountpoints to test"; } else { - plan tests => 78; + plan tests => 84; } $result = NPTest->testCmd( -- 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 6bbe0b7b0f609ecab831dec9be7690842bf0a0fc Mon Sep 17 00:00:00 2001 From: Stuart Henderson Date: Wed, 8 Feb 2023 16:35:22 +0000 Subject: cope with radcli-1.3.1 RC_BUFFER_LEN radcli 1.3.1 now uses RC_BUFFER_LEN instead of BUFFER_LEN. Add an #ifdef to allow working with either. --- plugins/check_radius.c | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'plugins') diff --git a/plugins/check_radius.c b/plugins/check_radius.c index be1001b4..96a95553 100644 --- a/plugins/check_radius.c +++ b/plugins/check_radius.c @@ -155,7 +155,11 @@ main (int argc, char **argv) { struct sockaddr_storage ss; char name[HOST_NAME_MAX]; +#ifdef RC_BUFFER_LEN + char msg[RC_BUFFER_LEN]; +#else char msg[BUFFER_LEN]; +#endif SEND_DATA data; int result = STATE_UNKNOWN; uint32_t client_id, service; -- 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 From ba78c32018658608a31c293beef89ec82b9ba9d3 Mon Sep 17 00:00:00 2001 From: Kristian Schuster <116557017+KriSchu@users.noreply.github.com> Date: Sun, 19 Feb 2023 22:49:30 +0100 Subject: check_disk: still allow check of available disks with ignore-missing param used Also add reporting of ignored paths. When paths are provided by -p and/ or -r and one path does not match a mounted disk, checking available disks is still possible. Paths provided by -p are reported as ignored, when not available. Due to code structure, this is not possible for -r unfortunately. --- plugins/check_disk.c | 103 ++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 78 insertions(+), 25 deletions(-) (limited to 'plugins') diff --git a/plugins/check_disk.c b/plugins/check_disk.c index 8df9e7ec..c1cfb13c 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -117,7 +117,7 @@ enum }; #ifdef _AIX - #pragma alloca +#pragma alloca #endif int process_arguments (int, char **); @@ -127,7 +127,7 @@ int validate_arguments (uintmax_t, uintmax_t, double, double, double, double, ch void print_help (void); void print_usage (void); double calculate_percent(uintmax_t, uintmax_t); -void stat_path (struct parameter_list *p); +bool stat_path (struct parameter_list *p); void get_stats (struct parameter_list *p, struct fs_usage *fsp); void get_path_stats (struct parameter_list *p, struct fs_usage *fsp); @@ -157,6 +157,7 @@ char *crit_usedinodes_percent = NULL; char *warn_freeinodes_percent = NULL; char *crit_freeinodes_percent = NULL; int path_selected = FALSE; +int path_ignored = FALSE; char *group = NULL; struct stat *stat_buf; struct name_list *seen = NULL; @@ -168,10 +169,12 @@ main (int argc, char **argv) int result = STATE_UNKNOWN; int disk_result = STATE_UNKNOWN; char *output; + char *ignored; char *details; char *perf; char *perf_ilabel; char *preamble; + char *ignored_preamble; char *flag_header; int temp_result; @@ -183,8 +186,10 @@ main (int argc, char **argv) char mountdir[32]; #endif - preamble = strdup (" - free space:"); + preamble = strdup (" free space:"); + ignored_preamble = strdup (" ignored paths:"); output = strdup (""); + ignored = strdup (""); details = strdup (""); perf = strdup (""); perf_ilabel = strdup (""); @@ -205,7 +210,7 @@ main (int argc, char **argv) /* If a list of paths has not been selected, find entire mount list and create list of paths */ - if (path_selected == FALSE) { + if (path_selected == FALSE && path_ignored == FALSE) { for (me = mount_list; me; me = me->me_next) { if (! (path = np_find_parameter(path_select_list, me->me_mountdir))) { path = np_add_parameter(&path_select_list, me->me_mountdir); @@ -215,19 +220,40 @@ main (int argc, char **argv) set_all_thresholds(path); } } - np_set_best_match(path_select_list, mount_list, exact_match); + + if (path_ignored == FALSE) { + np_set_best_match(path_select_list, mount_list, exact_match); + } /* Error if no match found for specified paths */ temp_list = path_select_list; - while (temp_list) { - if (! temp_list->best_match && ignore_missing == 1) { - die (STATE_OK, _("DISK %s: %s not found (ignoring)\n"), _("OK"), temp_list->name); - } else if (! temp_list->best_match) { - die (STATE_CRITICAL, _("DISK %s: %s not found\n"), _("CRITICAL"), temp_list->name); + while (path_select_list) { + if (! path_select_list->best_match && ignore_missing == 1) { + /* If the first element will be deleted, the temp_list must be updated with the new start address as well */ + if (path_select_list == temp_list) { + temp_list = path_select_list->name_next; + } + /* Add path argument to list of ignored paths to inform about missing paths being ignored and not alerted */ + xasprintf (&ignored, "%s %s;", ignored, path_select_list->name); + /* Delete the path from the list so that it is not stat-checked later in the code. */ + path_select_list = np_del_parameter(path_select_list, path_select_list->name_prev); + } else if (! path_select_list->best_match) { + /* Without --ignore-missing option, exit with Critical state. */ + die (STATE_CRITICAL, _("DISK %s: %s not found\n"), _("CRITICAL"), path_select_list->name); + } else { + /* Continue jumping through the list */ + path_select_list = path_select_list->name_next; } + } + + path_select_list = temp_list; - temp_list = temp_list->name_next; + if (! path_select_list && ignore_missing == 1) { + result = STATE_OK; + if (verbose >= 2) { + printf ("None of the provided paths were found\n"); + } } /* Process for every path in list */ @@ -246,6 +272,10 @@ main (int argc, char **argv) me = path->best_match; + if (!me) { + continue; + } + #ifdef __CYGWIN__ if (strncmp(path->name, "/cygdrive/", 10) != 0 || strlen(path->name) > 11) continue; @@ -264,8 +294,12 @@ main (int argc, char **argv) if (path->group == NULL) { /* Skip remote filesystems if we're not interested in them */ if (me->me_remote && show_local_fs) { - if (stat_remote_fs) - stat_path(path); + if (stat_remote_fs) { + if (!stat_path(path) && ignore_missing == 1) { + result = STATE_OK; + xasprintf (&ignored, "%s %s;", ignored, path->name); + } + } continue; /* Skip pseudo fs's if we haven't asked for all fs's */ } else if (me->me_dummy && !show_all_fs) { @@ -284,7 +318,13 @@ main (int argc, char **argv) } } - stat_path(path); + if (!stat_path(path)) { + if (ignore_missing == 1) { + result = STATE_OK; + xasprintf (&ignored, "%s %s;", ignored, path->name); + } + continue; + } get_fs_usage (me->me_mountdir, me->me_devname, &fsp); if (fsp.fsu_blocks && strcmp ("none", me->me_mountdir)) { @@ -415,8 +455,12 @@ main (int argc, char **argv) if (verbose >= 2) xasprintf (&output, "%s%s", output, details); + if (strcmp(output, "") == 0) { + preamble = ""; + xasprintf (&output, " No disks were found for provided parameters;"); + } - printf ("DISK %s%s%s|%s\n", state_text (result), (erronly && result==STATE_OK) ? "" : preamble, output, perf); + printf ("DISK %s -%s%s%s%s|%s\n", state_text (result), ((erronly && result==STATE_OK)) ? "" : preamble, output, (strcmp(ignored, "") == 0) ? "" : ignored_preamble, ignored, perf); return result; } @@ -637,12 +681,19 @@ process_arguments (int argc, char **argv) /* add parameter if not found. overwrite thresholds if path has already been added */ if (! (se = np_find_parameter(path_select_list, optarg))) { se = np_add_parameter(&path_select_list, optarg); + + if (stat(optarg, &stat_buf[0]) && ignore_missing == 1) { + path_ignored = TRUE; + break; + } } se->group = group; set_all_thresholds(se); /* With autofs, it is required to stat() the path before re-populating the mount_list */ - stat_path(se); + if (!stat_path(se)) { + break; + } /* NB: We can't free the old mount_list "just like that": both list pointers and struct * pointers are copied around. One of the reason it wasn't done yet is that other parts * of check_disk need the same kind of cleanup so it'd better be done as a whole */ @@ -761,10 +812,11 @@ process_arguments (int argc, char **argv) } } - if (!fnd && ignore_missing == 1) - die (STATE_OK, "DISK %s: %s - %s\n",_("OK"), - _("Regular expression did not match any path or disk (ignoring)"), optarg); - else if (!fnd) + if (!fnd && ignore_missing == 1) { + path_ignored = TRUE; + /* path_selected = TRUE;*/ + break; + } else if (!fnd) die (STATE_UNKNOWN, "DISK %s: %s - %s\n",_("UNKNOWN"), _("Regular expression did not match any path or disk"), optarg); @@ -936,7 +988,7 @@ print_help (void) printf (" %s\n", _("Regular expression to ignore selected path or partition (may be repeated)")); printf (" %s\n", "--ignore-missing"); printf (" %s\n", _("Return OK if no filesystem matches, filesystem does not exist or is inaccessible.")); - printf (" %s\n", _("(Provide this option before -r / --ereg-path if used)")); + printf (" %s\n", _("(Provide this option before -p / -r / --ereg-path if used)")); printf (UT_PLUG_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); printf (" %s\n", "-u, --units=STRING"); printf (" %s\n", _("Choose bytes, kB, MB, GB, TB (default: MB)")); @@ -970,7 +1022,7 @@ print_usage (void) printf ("[-t timeout] [-u unit] [-v] [-X type] [-N type]\n"); } -void +bool stat_path (struct parameter_list *p) { /* Stat entry to check that dir exists and is accessible */ @@ -980,13 +1032,13 @@ stat_path (struct parameter_list *p) if (verbose >= 3) printf("stat failed on %s\n", p->name); if (ignore_missing == 1) { - printf("DISK %s - ", _("OK")); - die (STATE_OK, _("%s %s: %s\n"), p->name, _("is not accessible (ignoring)"), strerror(errno)); + return false; } else { printf("DISK %s - ", _("CRITICAL")); die (STATE_CRITICAL, _("%s %s: %s\n"), p->name, _("is not accessible"), strerror(errno)); } } + return true; } @@ -1006,7 +1058,8 @@ get_stats (struct parameter_list *p, struct fs_usage *fsp) { continue; #endif if (p_list->group && ! (strcmp(p_list->group, p->group))) { - stat_path(p_list); + if (! stat_path(p_list)) + continue; 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) -- cgit v1.2.3-74-g34f1 From ca3d59cd6918c9e2739e783b721d4c1122640fd3 Mon Sep 17 00:00:00 2001 From: Kristian Schuster <116557017+KriSchu@users.noreply.github.com> Date: Sun, 19 Feb 2023 23:00:21 +0100 Subject: check_disk: add new tests for new ignore-missing feature --- plugins/t/check_disk.t | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) (limited to 'plugins') diff --git a/plugins/t/check_disk.t b/plugins/t/check_disk.t index a534fd4a..275db70d 100644 --- a/plugins/t/check_disk.t +++ b/plugins/t/check_disk.t @@ -23,7 +23,7 @@ my $mountpoint2_valid = getTestParameter( "NP_MOUNTPOINT2_VALID", "Path to anoth if ($mountpoint_valid eq "" or $mountpoint2_valid eq "") { plan skip_all => "Need 2 mountpoints to test"; } else { - plan tests => 84; + plan tests => 86; } $result = NPTest->testCmd( @@ -355,14 +355,24 @@ like( $result->output, qr/$mountpoint2_valid/,"ignore: output data does have $mo # ignore-missing: exit okay, when fs is not accessible $result = NPTest->testCmd( "./check_disk --ignore-missing -w 0% -c 0% -p /bob"); cmp_ok( $result->return_code, '==', 0, "ignore-missing: return okay for not existing filesystem /bob"); -like( $result->output, '/^DISK OK - /bob is not accessible .*$/', 'Output OK'); +like( $result->output, '/^DISK OK - No disks were found for provided parameters; ignored paths: /bob;.*$/', 'Output OK'); # ignore-missing: exit okay, when regex does not match $result = NPTest->testCmd( "./check_disk --ignore-missing -w 0% -c 0% -r /bob"); cmp_ok( $result->return_code, '==', 0, "ignore-missing: return okay for regular expression not matching"); -like( $result->output, '/^DISK OK: Regular expression did not match any path or disk.*$/', 'Output OK'); +like( $result->output, '/^DISK OK - No disks were found for provided parameters;.*$/', 'Output OK'); # ignore-missing: exit okay, when fs with exact match (-E) is not found -$result = NPTest->testCmd( "./check_disk --ignore-missing -E -w 0% -c 0% -p /etc"); +$result = NPTest->testCmd( "./check_disk --ignore-missing -w 0% -c 0% -E -p /etc"); cmp_ok( $result->return_code, '==', 0, "ignore-missing: return okay when exact match does not find fs"); -like( $result->output, '/^DISK OK: /etc not found.*$/', 'Output OK'); +like( $result->output, '/^DISK OK - No disks were found for provided parameters; ignored paths: /etc;.*$/', 'Output OK'); + +# ignore-missing: exit okay, when checking one existing fs and one non-existing fs (regex) +$result = NPTest->testCmd( "./check_disk --ignore-missing -w 0% -c 0% -r '/bob' -r '^/$'"); +cmp_ok( $result->return_code, '==', 0, "ignore-missing: return okay for regular expression not matching"); +like( $result->output, '/^DISK OK - free space: / .*$/', 'Output OK'); + +# ignore-missing: exit okay, when checking one existing fs and one non-existing fs (path) +$result = NPTest->testCmd( "./check_disk --ignore-missing -w 0% -c 0% -p '/bob' -p '/'"); +cmp_ok( $result->return_code, '==', 0, "ignore-missing: return okay for regular expression not matching"); +like( $result->output, '/^DISK OK - free space: / .*; ignored paths: /bob;.*$/', 'Output OK'); \ No newline at end of file -- cgit v1.2.3-74-g34f1 From a58293a0c288ee0e050c79715073da9fbdfc4c58 Mon Sep 17 00:00:00 2001 From: Kristian Schuster <116557017+KriSchu@users.noreply.github.com> Date: Mon, 20 Feb 2023 01:27:23 +0100 Subject: check_disk: fix tests by setting correct test number and escaping line end regex --- plugins/t/check_disk.t | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'plugins') diff --git a/plugins/t/check_disk.t b/plugins/t/check_disk.t index 275db70d..73f1e374 100644 --- a/plugins/t/check_disk.t +++ b/plugins/t/check_disk.t @@ -23,7 +23,7 @@ my $mountpoint2_valid = getTestParameter( "NP_MOUNTPOINT2_VALID", "Path to anoth if ($mountpoint_valid eq "" or $mountpoint2_valid eq "") { plan skip_all => "Need 2 mountpoints to test"; } else { - plan tests => 86; + plan tests => 88; } $result = NPTest->testCmd( @@ -126,7 +126,7 @@ my $free_mb_on_all = $free_mb_on_mp1 + $free_mb_on_mp2; $result = NPTest->testCmd( "./check_disk -e -w 1 -c 1 -p $more_free" ); -is( $result->only_output, "DISK OK", "No print out of disks with -e for OKs"); +is( $result->only_output, "DISK OK - No disks were found for provided parameters;", "No print out of disks with -e for OKs"); $result = NPTest->testCmd( "./check_disk 100 100 $more_free" ); cmp_ok( $result->return_code, '==', 0, "Old syntax okay" ); @@ -368,9 +368,9 @@ cmp_ok( $result->return_code, '==', 0, "ignore-missing: return okay when exact m like( $result->output, '/^DISK OK - No disks were found for provided parameters; ignored paths: /etc;.*$/', 'Output OK'); # ignore-missing: exit okay, when checking one existing fs and one non-existing fs (regex) -$result = NPTest->testCmd( "./check_disk --ignore-missing -w 0% -c 0% -r '/bob' -r '^/$'"); +$result = NPTest->testCmd( "./check_disk --ignore-missing -w 0% -c 0% -r '/bob' -r '^/\$'"); cmp_ok( $result->return_code, '==', 0, "ignore-missing: return okay for regular expression not matching"); -like( $result->output, '/^DISK OK - free space: / .*$/', 'Output OK'); +like( $result->output, '/^DISK OK - free space: \/ .*$/', 'Output OK'); # ignore-missing: exit okay, when checking one existing fs and one non-existing fs (path) $result = NPTest->testCmd( "./check_disk --ignore-missing -w 0% -c 0% -p '/bob' -p '/'"); -- cgit v1.2.3-74-g34f1 From e102b8a49e857a474db516455d2e871e6834ae34 Mon Sep 17 00:00:00 2001 From: Kristian Schuster <116557017+KriSchu@users.noreply.github.com> Date: Mon, 20 Feb 2023 02:03:01 +0100 Subject: check_disk: fix ugly output with -e option and adapt tests accordingly --- plugins/check_disk.c | 10 +++++----- plugins/t/check_disk.t | 8 ++++---- 2 files changed, 9 insertions(+), 9 deletions(-) (limited to 'plugins') diff --git a/plugins/check_disk.c b/plugins/check_disk.c index d32841d8..c52d1df4 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -186,8 +186,8 @@ main (int argc, char **argv) char mountdir[32]; #endif - preamble = strdup (" free space:"); - ignored_preamble = strdup (" ignored paths:"); + preamble = strdup (" - free space:"); + ignored_preamble = strdup (" - ignored paths:"); output = strdup (""); ignored = strdup (""); details = strdup (""); @@ -455,12 +455,12 @@ main (int argc, char **argv) if (verbose >= 2) xasprintf (&output, "%s%s", output, details); - if (strcmp(output, "") == 0) { + if (strcmp(output, "") == 0 && ! erronly) { preamble = ""; - xasprintf (&output, " No disks were found for provided parameters;"); + xasprintf (&output, " - No disks were found for provided parameters;"); } - printf ("DISK %s -%s%s%s%s|%s\n", state_text (result), ((erronly && result==STATE_OK)) ? "" : preamble, output, (strcmp(ignored, "") == 0) ? "" : ignored_preamble, ignored, perf); + printf ("DISK %s%s%s%s%s|%s\n", state_text (result), ((erronly && result==STATE_OK)) ? "" : preamble, output, (strcmp(ignored, "") == 0) ? "" : ignored_preamble, ignored, perf); return result; } diff --git a/plugins/t/check_disk.t b/plugins/t/check_disk.t index 73f1e374..c8f08f51 100644 --- a/plugins/t/check_disk.t +++ b/plugins/t/check_disk.t @@ -126,7 +126,7 @@ my $free_mb_on_all = $free_mb_on_mp1 + $free_mb_on_mp2; $result = NPTest->testCmd( "./check_disk -e -w 1 -c 1 -p $more_free" ); -is( $result->only_output, "DISK OK - No disks were found for provided parameters;", "No print out of disks with -e for OKs"); +is( $result->only_output, "DISK OK", "No print out of disks with -e for OKs"); $result = NPTest->testCmd( "./check_disk 100 100 $more_free" ); cmp_ok( $result->return_code, '==', 0, "Old syntax okay" ); @@ -355,7 +355,7 @@ like( $result->output, qr/$mountpoint2_valid/,"ignore: output data does have $mo # ignore-missing: exit okay, when fs is not accessible $result = NPTest->testCmd( "./check_disk --ignore-missing -w 0% -c 0% -p /bob"); cmp_ok( $result->return_code, '==', 0, "ignore-missing: return okay for not existing filesystem /bob"); -like( $result->output, '/^DISK OK - No disks were found for provided parameters; ignored paths: /bob;.*$/', 'Output OK'); +like( $result->output, '/^DISK OK - No disks were found for provided parameters; - ignored paths: /bob;.*$/', 'Output OK'); # ignore-missing: exit okay, when regex does not match $result = NPTest->testCmd( "./check_disk --ignore-missing -w 0% -c 0% -r /bob"); @@ -365,7 +365,7 @@ like( $result->output, '/^DISK OK - No disks were found for provided parameters; # ignore-missing: exit okay, when fs with exact match (-E) is not found $result = NPTest->testCmd( "./check_disk --ignore-missing -w 0% -c 0% -E -p /etc"); cmp_ok( $result->return_code, '==', 0, "ignore-missing: return okay when exact match does not find fs"); -like( $result->output, '/^DISK OK - No disks were found for provided parameters; ignored paths: /etc;.*$/', 'Output OK'); +like( $result->output, '/^DISK OK - No disks were found for provided parameters; - ignored paths: /etc;.*$/', 'Output OK'); # ignore-missing: exit okay, when checking one existing fs and one non-existing fs (regex) $result = NPTest->testCmd( "./check_disk --ignore-missing -w 0% -c 0% -r '/bob' -r '^/\$'"); @@ -375,4 +375,4 @@ like( $result->output, '/^DISK OK - free space: \/ .*$/', 'Output OK'); # ignore-missing: exit okay, when checking one existing fs and one non-existing fs (path) $result = NPTest->testCmd( "./check_disk --ignore-missing -w 0% -c 0% -p '/bob' -p '/'"); cmp_ok( $result->return_code, '==', 0, "ignore-missing: return okay for regular expression not matching"); -like( $result->output, '/^DISK OK - free space: / .*; ignored paths: /bob;.*$/', 'Output OK'); \ No newline at end of file +like( $result->output, '/^DISK OK - free space: / .*; - ignored paths: /bob;.*$/', 'Output OK'); \ No newline at end of file -- cgit v1.2.3-74-g34f1 From 3e7da5f970d73df91fad32f4dce259d30cdbbd65 Mon Sep 17 00:00:00 2001 From: Kristian Schuster <116557017+KriSchu@users.noreply.github.com> Date: Mon, 6 Mar 2023 14:03:10 +0100 Subject: check_disk: use cleaner code for ignore-missing option - use datatype bool for new vars ignore_missing and path_ignored instead of int - directly initialize preamble and ignored_preamble with their strings --- plugins/check_disk.c | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) (limited to 'plugins') diff --git a/plugins/check_disk.c b/plugins/check_disk.c index c52d1df4..bd84c825 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -141,7 +141,7 @@ int verbose = 0; int erronly = FALSE; int display_mntp = FALSE; int exact_match = FALSE; -int ignore_missing = FALSE; +bool ignore_missing = false; int freespace_ignore_reserved = FALSE; int display_inodes_perfdata = FALSE; char *warn_freespace_units = NULL; @@ -157,7 +157,7 @@ char *crit_usedinodes_percent = NULL; char *warn_freeinodes_percent = NULL; char *crit_freeinodes_percent = NULL; int path_selected = FALSE; -int path_ignored = FALSE; +bool path_ignored = false; char *group = NULL; struct stat *stat_buf; struct name_list *seen = NULL; @@ -173,8 +173,8 @@ main (int argc, char **argv) char *details; char *perf; char *perf_ilabel; - char *preamble; - char *ignored_preamble; + char *preamble = " - free space:"; + char *ignored_preamble = " - ignored paths:"; char *flag_header; int temp_result; @@ -186,8 +186,6 @@ main (int argc, char **argv) char mountdir[32]; #endif - preamble = strdup (" - free space:"); - ignored_preamble = strdup (" - ignored paths:"); output = strdup (""); ignored = strdup (""); details = strdup (""); @@ -210,7 +208,7 @@ main (int argc, char **argv) /* If a list of paths has not been selected, find entire mount list and create list of paths */ - if (path_selected == FALSE && path_ignored == FALSE) { + if (path_selected == FALSE && path_ignored == false) { for (me = mount_list; me; me = me->me_next) { if (! (path = np_find_parameter(path_select_list, me->me_mountdir))) { path = np_add_parameter(&path_select_list, me->me_mountdir); @@ -221,7 +219,7 @@ main (int argc, char **argv) } } - if (path_ignored == FALSE) { + if (path_ignored == false) { np_set_best_match(path_select_list, mount_list, exact_match); } @@ -229,7 +227,7 @@ main (int argc, char **argv) temp_list = path_select_list; while (path_select_list) { - if (! path_select_list->best_match && ignore_missing == 1) { + if (! path_select_list->best_match && ignore_missing == true) { /* If the first element will be deleted, the temp_list must be updated with the new start address as well */ if (path_select_list == temp_list) { temp_list = path_select_list->name_next; @@ -249,7 +247,7 @@ main (int argc, char **argv) path_select_list = temp_list; - if (! path_select_list && ignore_missing == 1) { + if (! path_select_list && ignore_missing == true) { result = STATE_OK; if (verbose >= 2) { printf ("None of the provided paths were found\n"); @@ -295,7 +293,7 @@ main (int argc, char **argv) /* Skip remote filesystems if we're not interested in them */ if (me->me_remote && show_local_fs) { if (stat_remote_fs) { - if (!stat_path(path) && ignore_missing == 1) { + if (!stat_path(path) && ignore_missing == true) { result = STATE_OK; xasprintf (&ignored, "%s %s;", ignored, path->name); } @@ -319,7 +317,7 @@ main (int argc, char **argv) } if (!stat_path(path)) { - if (ignore_missing == 1) { + if (ignore_missing == true) { result = STATE_OK; xasprintf (&ignored, "%s %s;", ignored, path->name); } @@ -682,8 +680,8 @@ process_arguments (int argc, char **argv) if (! (se = np_find_parameter(path_select_list, optarg))) { se = np_add_parameter(&path_select_list, optarg); - if (stat(optarg, &stat_buf[0]) && ignore_missing == 1) { - path_ignored = TRUE; + if (stat(optarg, &stat_buf[0]) && ignore_missing == true) { + path_ignored = true; break; } } @@ -775,7 +773,7 @@ process_arguments (int argc, char **argv) break; case IGNORE_MISSING: - ignore_missing = 1; + ignore_missing = true; break; case 'A': optarg = strdup(".*"); @@ -812,8 +810,8 @@ process_arguments (int argc, char **argv) } } - if (!fnd && ignore_missing == 1) { - path_ignored = TRUE; + if (!fnd && ignore_missing == true) { + path_ignored = true; /* path_selected = TRUE;*/ break; } else if (!fnd) @@ -1031,7 +1029,7 @@ stat_path (struct parameter_list *p) if (stat (p->name, &stat_buf[0])) { if (verbose >= 3) printf("stat failed on %s\n", p->name); - if (ignore_missing == 1) { + if (ignore_missing == true) { return false; } else { printf("DISK %s - ", _("CRITICAL")); -- cgit v1.2.3-74-g34f1 From 03f86b5d0809967855fbaafb4d600dc5b82081fa Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Tue, 7 Mar 2023 19:51:33 +0100 Subject: check_curl: in SSL host caching mode try to connect and bind and take the first getaddrinfo result which succeeds --- plugins/check_curl.c | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index c37d45d9..e1bc98dc 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -386,6 +386,7 @@ lookup_host (const char *host, char *buf, size_t buflen) struct addrinfo hints, *res, *result; int errcode; void *ptr; + int s; memset (&hints, 0, sizeof (hints)); hints.ai_family = address_family; @@ -399,19 +400,26 @@ lookup_host (const char *host, char *buf, size_t buflen) 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; + 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; - 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); + + if (s = socket (res->ai_family, res->ai_socktype, res->ai_protocol) == -1) + continue; + if (bind (s, res->ai_addr, res->ai_addrlen == 0) ) + break; + res = res->ai_next; } -- cgit v1.2.3-74-g34f1 From 2902381c5de01f69d61569b0c8dae6a92e2b9843 Mon Sep 17 00:00:00 2001 From: Barak Shohat Date: Wed, 8 Mar 2023 11:56:43 +0200 Subject: check_curl.c: Include all IPs from getaddrinfo() in curl DNS cache --- plugins/check_curl.c | 39 ++++++++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 13 deletions(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index e1bc98dc..512fb88a 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -384,9 +384,12 @@ int lookup_host (const char *host, char *buf, size_t buflen) { struct addrinfo hints, *res, *result; + char addrstr[100]; + size_t addrstr_len; int errcode; void *ptr; int s; + size_t buflen_remaining = buflen - 1; memset (&hints, 0, sizeof (hints)); hints.ai_family = address_family; @@ -396,33 +399,40 @@ lookup_host (const char *host, char *buf, size_t buflen) errcode = getaddrinfo (host, NULL, &hints, &result); if (errcode != 0) return errcode; - + + strcpy(buf, ""); 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; + break; } - inet_ntop (res->ai_family, ptr, buf, buflen); - if (verbose >= 1) + inet_ntop (res->ai_family, ptr, addrstr, 100); + if (verbose >= 1) { printf ("* getaddrinfo IPv%d address: %s\n", - res->ai_family == PF_INET6 ? 6 : 4, buf); + res->ai_family == PF_INET6 ? 6 : 4, addrstr); + } - if (s = socket (res->ai_family, res->ai_socktype, res->ai_protocol) == -1) - continue; - if (bind (s, res->ai_addr, res->ai_addrlen == 0) ) - break; + // Append all IPs to buf as a comma-separated string + addrstr_len = strlen(addrstr); + if (buflen_remaining > addrstr_len + 1) { + if (buf[0] != NULL) { + strncat(buf, ",", 1); + buflen_remaining -= 1; + } + strncat(buf, addrstr, buflen_remaining); + buflen_remaining -= addrstr_len; + } res = res->ai_next; } - + freeaddrinfo(result); return 0; @@ -453,7 +463,7 @@ check_http (void) int i; char *force_host_header = NULL; struct curl_slist *host = NULL; - char addrstr[100]; + char addrstr[DEFAULT_BUFFER_SIZE/2]; char dnscache[DEFAULT_BUFFER_SIZE]; /* initialize curl */ @@ -505,7 +515,7 @@ 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) { - if ( (res=lookup_host (server_address, addrstr, 100)) != 0) { + if ( (res=lookup_host (server_address, addrstr, DEFAULT_BUFFER_SIZE/2)) != 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); @@ -800,6 +810,9 @@ check_http (void) /* free header and server IP resolve lists, we don't need it anymore */ curl_slist_free_all (header_list); header_list = NULL; curl_slist_free_all (server_ips); server_ips = NULL; + if (host) { + curl_slist_free_all (host); host = NULL; + } /* Curl errors, result in critical Nagios state */ if (res != CURLE_OK) { -- cgit v1.2.3-74-g34f1 From fc927e98db73850e760f490117ed36f2de20270c Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Wed, 8 Mar 2023 16:10:45 +0100 Subject: fixed a wrong compare and a wrong size in strncat --- 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 512fb88a..cc17ef58 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -422,8 +422,8 @@ lookup_host (const char *host, char *buf, size_t buflen) // Append all IPs to buf as a comma-separated string addrstr_len = strlen(addrstr); if (buflen_remaining > addrstr_len + 1) { - if (buf[0] != NULL) { - strncat(buf, ",", 1); + if (buf[0] != '\0') { + strncat(buf, ",", buflen_remaining); buflen_remaining -= 1; } strncat(buf, addrstr, buflen_remaining); -- cgit v1.2.3-74-g34f1 From ea53555f2d6254da5fec0c1061899a01dd5321ec Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Sat, 11 Mar 2023 11:40:00 +0100 Subject: check_curl: removed a superflous variable --- plugins/check_curl.c | 1 - 1 file changed, 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index cc17ef58..e5be1ad5 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -388,7 +388,6 @@ lookup_host (const char *host, char *buf, size_t buflen) size_t addrstr_len; int errcode; void *ptr; - int s; size_t buflen_remaining = buflen - 1; memset (&hints, 0, sizeof (hints)); -- cgit v1.2.3-74-g34f1 From 8a8ee58e8925019b7532e7d14ebe488bb21fb3e6 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 16 Mar 2023 15:26:52 +0100 Subject: check_swap: Remove unnecessary and problematic includes --- plugins/check_swap.c | 3 --- 1 file changed, 3 deletions(-) (limited to 'plugins') diff --git a/plugins/check_swap.c b/plugins/check_swap.c index a607da1e..25d5f21d 100644 --- a/plugins/check_swap.c +++ b/plugins/check_swap.c @@ -34,9 +34,6 @@ const char *email = "devel@monitoring-plugins.org"; #include "common.h" #include "popen.h" #include "utils.h" -#include -#include -#include #ifdef HAVE_DECL_SWAPCTL # ifdef HAVE_SYS_PARAM_H -- cgit v1.2.3-74-g34f1 From cf90f0de7b3c347a6860b50de6a610bd7132668c Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Thu, 16 Mar 2023 16:21:46 +0100 Subject: check_curk: including netinet/in.h (for FreeBSD), fixed an ambigous compare warning --- plugins/check_curl.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/check_curl.c b/plugins/check_curl.c index e5be1ad5..c51914a9 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -55,6 +55,7 @@ const char *email = "devel@monitoring-plugins.org"; #include "uriparser/Uri.h" #include +#include #if defined(HAVE_SSL) && defined(USE_OPENSSL) #include @@ -541,7 +542,7 @@ check_http (void) /* 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", - use_ssl & host_name != NULL ? host_name : server_address, + ( use_ssl & ( host_name != NULL ) ) ? host_name : server_address, server_port, server_url ); -- cgit v1.2.3-74-g34f1 From 9c495e2aefedca270f49987dc31bff983e614281 Mon Sep 17 00:00:00 2001 From: Christian Kujau Date: Mon, 20 Mar 2023 11:35:01 +0100 Subject: check_procs: Implement --exclude-process to exclude specific processes. Signed-off-by: Christian Kujau --- plugins/check_procs.c | 47 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/check_procs.c b/plugins/check_procs.c index a025ee89..d672dd44 100644 --- a/plugins/check_procs.c +++ b/plugins/check_procs.c @@ -70,6 +70,7 @@ int options = 0; /* bitmask of filter criteria to test against */ #define PCPU 256 #define ELAPSED 512 #define EREG_ARGS 1024 +#define EXCLUDE_PROGS 2048 #define KTHREAD_PARENT "kthreadd" /* the parent process of kernel threads: ppid of procs are compared to pid of this proc*/ @@ -93,6 +94,9 @@ int rss; float pcpu; char *statopts; char *prog; +char *exclude_progs; +char **exclude_progs_arr = NULL; +char exclude_progs_counter = 0; char *args; char *input_filename = NULL; regex_t re_args; @@ -250,6 +254,25 @@ main (int argc, char **argv) continue; } + /* Ignore excluded processes by name */ + if(options & EXCLUDE_PROGS) { + int found = 0; + int i = 0; + + for(i=0; i < (exclude_progs_counter); i++) { + if(!strcmp(procprog, exclude_progs_arr[i])) { + found = 1; + } + } + if(found == 0) { + resultsum |= EXCLUDE_PROGS; + } else + { + if(verbose >= 3) + printf("excluding - by ignorelist\n"); + } + } + /* filter kernel threads (childs of KTHREAD_PARENT)*/ /* TODO adapt for other OSes than GNU/Linux sorry for not doing that, but I've no other OSes to test :-( */ @@ -409,6 +432,7 @@ process_arguments (int argc, char **argv) {"input-file", required_argument, 0, CHAR_MAX+2}, {"no-kthreads", required_argument, 0, 'k'}, {"traditional-filter", no_argument, 0, 'T'}, + {"exclude-process", required_argument, 0, 'X'}, {0, 0, 0, 0} }; @@ -417,7 +441,7 @@ process_arguments (int argc, char **argv) strcpy (argv[c], "-t"); while (1) { - c = getopt_long (argc, argv, "Vvhkt:c:w:p:s:u:C:a:z:r:m:P:T", + c = getopt_long (argc, argv, "Vvhkt:c:w:p:s:u:C:a:z:r:m:P:T:X:", longopts, &option); if (c == -1 || c == EOF) @@ -490,6 +514,23 @@ process_arguments (int argc, char **argv) prog); options |= PROG; break; + case 'X': + if(exclude_progs) + break; + else + exclude_progs = optarg; + xasprintf (&fmt, _("%s%sexclude progs '%s'"), (fmt ? fmt : ""), (options ? ", " : ""), + exclude_progs); + char *p = strtok(exclude_progs, ","); + + while(p){ + exclude_progs_arr = realloc(exclude_progs_arr, sizeof(char*) * ++exclude_progs_counter); + exclude_progs_arr[exclude_progs_counter-1] = p; + p = strtok(NULL, ","); + } + + options |= EXCLUDE_PROGS; + break; case 'a': /* args (full path name with args) */ /* TODO: allow this to be passed in with --metric */ if (args) @@ -745,6 +786,8 @@ print_help (void) printf (" %s\n", _("Only scan for processes with args that contain the regex STRING.")); printf (" %s\n", "-C, --command=COMMAND"); printf (" %s\n", _("Only scan for exact matches of COMMAND (without path).")); + printf (" %s\n", "-X, --exclude-process"); + printf (" %s\n", _("Exclude processes which match this comma seperated list")); printf (" %s\n", "-k, --no-kthreads"); printf (" %s\n", _("Only scan for non kernel threads (works on Linux only).")); @@ -786,5 +829,5 @@ print_usage (void) printf ("%s\n", _("Usage:")); printf ("%s -w -c [-m metric] [-s state] [-p ppid]\n", progname); printf (" [-u user] [-r rss] [-z vsz] [-P %%cpu] [-a argument-array]\n"); - printf (" [-C command] [-k] [-t timeout] [-v]\n"); + printf (" [-C command] [-X process_to_exclude] [-k] [-t timeout] [-v]\n"); } -- cgit v1.2.3-74-g34f1 From 3e3e225b3f962993a6139bf5a2c22009b9e9cd32 Mon Sep 17 00:00:00 2001 From: Christian Kujau Date: Tue, 21 Mar 2023 11:26:03 +0100 Subject: check_procs: add a test for the newly added -X option. $ make test [...] perl -I .. -I .. ../test.pl No application (check_curl) found for test harness (check_curl.t) No application (check_snmp) found for test harness (check_snmp.t) ./t/check_procs.t ...... ok ./tests/check_nt.t ..... ok ./tests/check_procs.t .. ok All tests successful. Files=4, Tests=73, 8 wallclock secs ( 0.05 usr 0.02 sys + 0.38 cusr 0.22 csys = 0.67 CPU) Result: PASS Signed-off-by: Christian Kujau --- plugins/tests/check_procs.t | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'plugins') diff --git a/plugins/tests/check_procs.t b/plugins/tests/check_procs.t index 3af218f5..b3a0a301 100755 --- a/plugins/tests/check_procs.t +++ b/plugins/tests/check_procs.t @@ -8,7 +8,7 @@ use Test::More; use NPTest; if (-x "./check_procs") { - plan tests => 52; + plan tests => 54; } else { plan skip_all => "No check_procs compiled"; } @@ -34,9 +34,13 @@ is( $result->return_code, 0, "Checking no threshold breeched" ); is( $result->output, "PROCS OK: 95 processes | procs=95;100;200;0;", "Output correct" ); $result = NPTest->testCmd( "$command -C launchd -c 5" ); -is( $result->return_code, 2, "Checking processes filtered by command name" ); +is( $result->return_code, 2, "Checking processes matched by command name" ); is( $result->output, "PROCS CRITICAL: 6 processes with command name 'launchd' | procs=6;;5;0;", "Output correct" ); +$result = NPTest->testCmd( "$command -X bash -c 5" ); +is( $result->return_code, 2, "Checking processes excluded by command name" ); +is( $result->output, "PROCS CRITICAL: 95 processes with exclude progs 'bash' | procs=95;;5;0;", "Output correct" ); + SKIP: { skip 'user with uid 501 required', 4 unless getpwuid(501); -- cgit v1.2.3-74-g34f1