From a3de84594104ac87a91e200d569fb57edacca928 Mon Sep 17 00:00:00 2001 From: Alexandre Anriot Date: Wed, 10 Jun 2020 20:46:27 +0200 Subject: Add -d switch to exclude ifs on a per desc basis diff --git a/plugins-scripts/check_ifstatus.pl b/plugins-scripts/check_ifstatus.pl index 32984e5..0ae3b4c 100755 --- a/plugins-scripts/check_ifstatus.pl +++ b/plugins-scripts/check_ifstatus.pl @@ -97,11 +97,12 @@ my $opt_V ; my $opt_u; my $opt_n; my $opt_x ; +my $opt_d; my %excluded ; my %unused_names ; my @unused_ports ; my %session_opts; - +my @exclude_descriptions; @@ -134,6 +135,7 @@ if (!defined($session)) { } +push(@snmpoids,$snmpLocIfDescr); push(@snmpoids,$snmpIfOperStatus); push(@snmpoids,$snmpIfAdminStatus); push(@snmpoids,$snmpIfDescr); @@ -180,18 +182,28 @@ foreach $key (keys %ifStatus) { if ($ifStatus{$key}{$snmpIfAdminStatus} == 1 ) { #check only if interface is not excluded if (!defined $unused_names{$ifStatus{$key}{$snmpIfDescr}} ) { - # check only if interface type is not listed in %excluded - if (!defined $excluded{$ifStatus{$key}{$snmpIfType}} ) { - if ($ifStatus{$key}{$snmpIfOperStatus} == 1 ) { $ifup++ ; } - if ($ifStatus{$key}{$snmpIfOperStatus} == 2 ) { - $ifdown++ ; - if (defined $ifXTable) { - $ifmessage .= sprintf("%s: down -> %s
\n", $ifStatus{$key}{$snmpIfName}, $ifStatus{$key}{$snmpIfAlias}); - }else{ - $ifmessage .= sprintf("%s: down
\n",$ifStatus{$key}{$snmpIfDescr}); - } + #check only if interface is not excluded (by description) + #counter for matching descriptions + my $match_descr = 0; + foreach my $description (@exclude_descriptions) { + if ($ifStatus{$key}{$snmpLocIfDescr} =~ /^$description/) { $match_descr = 1; } + } + if ($match_descr == 0) { + # check only if interface type is not listed in %excluded + if (!defined $excluded{$ifStatus{$key}{$snmpIfType}} ) { + if ($ifStatus{$key}{$snmpIfOperStatus} == 1 ) { $ifup++ ; } + if ($ifStatus{$key}{$snmpIfOperStatus} == 2 ) { + $ifdown++ ; + if (defined $ifXTable) { + $ifmessage .= sprintf("%s: down -> %s
\n", $ifStatus{$key}{$snmpIfName}, $ifStatus{$key}{$snmpIfAlias}); + }else{ + $ifmessage .= sprintf("%s: down
\n",$ifStatus{$key}{$snmpIfDescr}); + } + } + if ($ifStatus{$key}{$snmpIfOperStatus} == 5 ) { $ifdormant++ ;} + } else { + $ifexclude++; } - if ($ifStatus{$key}{$snmpIfOperStatus} == 5 ) { $ifdormant++ ;} } else { $ifexclude++; } @@ -264,6 +276,9 @@ sub print_help() { printf " the descriptive name. Do not use if you don't know what this is. \n"; printf " -x (--exclude) A comma separated list of ifType values that should be excluded \n"; printf " from the report (default for an empty list is PPP(23).\n"; + printf " -d (--exclude_ports_by_description) A comma separated list of LocIfDescr values that should be excluded \n"; + printf " from the report (default is an empty exclusion list). Done using regexp '/^arg/', ex:\n"; + printf " '-d connect,test' will match with descriptions like 'testing phase' but not 'in testing'.\n"; printf " -n (--unused_ports_by_name) A comma separated list of ifDescr values that should be excluded \n"; printf " from the report (default is an empty exclusion list).\n"; printf " -u (--unused_ports) A comma separated list of ifIndex values that should be excluded \n"; @@ -306,6 +321,7 @@ sub process_arguments() { "I" => \$ifXTable, "ifmib" => \$ifXTable, "x:s" => \$opt_x, "exclude:s" => \$opt_x, "u=s" => \$opt_u, "unused_ports=s" => \$opt_u, + "d=s" => \$opt_d, "exclude_ports_by_description=s" => \$opt_d, "n=s" => \$opt_n, "unused_ports_by_name=s" => \$opt_n, "M=i" => \$maxmsgsize, "maxmsgsize=i" => \$maxmsgsize, "t=i" => \$timeout, "timeout=i" => \$timeout, @@ -414,6 +430,11 @@ sub process_arguments() { } } + # Exclude interfaces by descriptions + if (defined $opt_d) { + @exclude_descriptions = split(/,/,$opt_d); + } + # Excluded interface descriptors if (defined $opt_n) { my @unused = split(/,/,$opt_n); -- cgit v0.10-9-g596f From 46efe803cf8e7b769ca112afc158b76510b01e46 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 19 Aug 2024 15:23:41 +0200 Subject: check_curl: Fix help for state regex option The help output of `check-curl` contained a typo, the real option is `state-regex` and not `regex-state` as the help suggests. Also added the two possible options to avoid confusion. diff --git a/plugins/check_curl.c b/plugins/check_curl.c index e9c15e6..bf46b22 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -2061,8 +2061,8 @@ print_help (void) printf (" %s\n", "--invert-regex"); printf (" %s\n", _("Return STATE if found, OK if not (STATE is CRITICAL, per default)")); printf (" %s\n", _("can be changed with --state--regex)")); - printf (" %s\n", "--regex-state=STATE"); - printf (" %s\n", _("Return STATE if regex is found, OK if not\n")); + printf (" %s\n", "--state-regex=STATE"); + printf (" %s\n", _("Return STATE if regex is found, OK if not\nSTATE can be one of \"critical\",\"warning\"")); 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"); -- cgit v0.10-9-g596f From b6c72064a53da8b173b7406a0a535922dc0cc1b3 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 19 Aug 2024 15:26:52 +0200 Subject: check_curl: Parse state-regex option ignoring case Previously the --state-regex option accepted only "critical" and "warning" as values. This commit changes the strcmp there to strcasecmp to be more tolerant regarding the input. diff --git a/plugins/check_curl.c b/plugins/check_curl.c index bf46b22..38c9710 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -1775,9 +1775,9 @@ process_arguments (int argc, char **argv) invert_regex = true; break; case STATE_REGEX: - if (!strcmp (optarg, "critical")) + if (!strcasecmp (optarg, "critical")) state_regex = STATE_CRITICAL; - else if (!strcmp (optarg, "warning")) + else if (!strcasecmp (optarg, "warning")) state_regex = STATE_WARNING; else usage2 (_("Invalid state-regex option"), optarg); break; -- cgit v0.10-9-g596f From af097aa3642174a2111f0bbcbc8236fff0901e17 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Mon, 19 Aug 2024 15:33:17 +0200 Subject: check_curl: change help for --state-regex again to fix formatting diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 38c9710..214ba74 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -2062,7 +2062,7 @@ print_help (void) printf (" %s\n", _("Return STATE if found, OK if not (STATE is CRITICAL, per default)")); printf (" %s\n", _("can be changed with --state--regex)")); printf (" %s\n", "--state-regex=STATE"); - printf (" %s\n", _("Return STATE if regex is found, OK if not\nSTATE can be one of \"critical\",\"warning\"")); + printf (" %s\n", _("Return STATE if regex is found, OK if not. STATE can be one of \"critical\",\"warning\"")); 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"); -- cgit v0.10-9-g596f From 584cca3a96845d7720c34358340c98c31c765fc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= Date: Wed, 28 Aug 2024 19:19:16 +0200 Subject: check_mysql: remove unused global variables diff --git a/plugins/check_mysql.c b/plugins/check_mysql.c index 6a7daf1..a2a5e32 100644 --- a/plugins/check_mysql.c +++ b/plugins/check_mysql.c @@ -59,7 +59,7 @@ bool ssl = false; char *opt_file = NULL; char *opt_group = NULL; unsigned int db_port = MYSQL_PORT; -int check_slave = 0, warn_sec = 0, crit_sec = 0; +int check_slave = 0; int ignore_auth = 0; int verbose = 0; -- cgit v0.10-9-g596f From 4f7ee057865e75d0eb95874b2404eb21bb5d508f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= Date: Wed, 28 Aug 2024 19:20:31 +0200 Subject: check_mysql: Label some booleans correctly diff --git a/plugins/check_mysql.c b/plugins/check_mysql.c index a2a5e32..15ec04c 100644 --- a/plugins/check_mysql.c +++ b/plugins/check_mysql.c @@ -59,8 +59,8 @@ bool ssl = false; char *opt_file = NULL; char *opt_group = NULL; unsigned int db_port = MYSQL_PORT; -int check_slave = 0; -int ignore_auth = 0; +bool check_slave = false; +bool ignore_auth = false; int verbose = 0; static double warning_time = 0; @@ -456,10 +456,10 @@ process_arguments (int argc, char **argv) db_port = atoi (optarg); break; case 'S': - check_slave = 1; /* check-slave */ + check_slave = true; /* check-slave */ break; case 'n': - ignore_auth = 1; /* ignore-auth */ + ignore_auth = true; /* ignore-auth */ break; case 'w': warning = optarg; -- cgit v0.10-9-g596f From 75d5c512072a019cdf6365bcda02d7eddc237e0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= Date: Thu, 29 Aug 2024 18:20:35 +0200 Subject: Remove experimental state from check_curl diff --git a/plugins/check_curl.c b/plugins/check_curl.c index e9c15e6..e25d7a7 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -2190,8 +2190,6 @@ print_usage (void) printf ("%s\n", _("In the first form, make an HTTP request.")); printf ("%s\n\n", _("In the second form, connect to the server and check the TLS certificate.")); #endif - printf ("%s\n", _("WARNING: check_curl is experimental. Please use")); - printf ("%s\n\n", _("check_http if you need a stable version.")); } void -- cgit v0.10-9-g596f From 3ba660889a8e7a8fc992cfafc910a8f91eafb354 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Fri, 27 Sep 2024 11:57:38 +0200 Subject: check_snmp: Declare most variables as static diff --git a/plugins/check_snmp.c b/plugins/check_snmp.c index 937b3a5..bd1940e 100644 --- a/plugins/check_snmp.c +++ b/plugins/check_snmp.c @@ -86,82 +86,82 @@ const char *email = "devel@monitoring-plugins.org"; -int process_arguments (int, char **); -int validate_arguments (void); -char *thisarg (char *str); -char *nextarg (char *str); +static int process_arguments (int, char **); +static int validate_arguments (void); +static char *thisarg (char *str); +static char *nextarg (char *str); void print_usage (void); -void print_help (void); -char *multiply (char *str); +static void print_help (void); +static char *multiply (char *str); #include "regex.h" -char regex_expect[MAX_INPUT_BUFFER] = ""; -regex_t preg; -regmatch_t pmatch[10]; -char errbuf[MAX_INPUT_BUFFER] = ""; -char perfstr[MAX_INPUT_BUFFER] = "| "; -int cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE; -int eflags = 0; -int errcode, excode; - -char *server_address = NULL; -char *community = NULL; -char **contextargs = NULL; -char *context = NULL; -char **authpriv = NULL; -char *proto = NULL; -char *seclevel = NULL; -char *secname = NULL; -char *authproto = NULL; -char *privproto = NULL; -char *authpasswd = NULL; -char *privpasswd = NULL; -int nulloid = STATE_UNKNOWN; -char **oids = NULL; -size_t oids_size = 0; -char *label; -char *units; -char *port; -char *snmpcmd; -char string_value[MAX_INPUT_BUFFER] = ""; -int invert_search=0; -char **labels = NULL; -char **unitv = NULL; -size_t nlabels = 0; -size_t labels_size = OID_COUNT_STEP; -size_t nunits = 0; -size_t unitv_size = OID_COUNT_STEP; -size_t numoids = 0; -int numauthpriv = 0; -int numcontext = 0; -int verbose = 0; -bool usesnmpgetnext = false; -char *warning_thresholds = NULL; -char *critical_thresholds = NULL; -thresholds **thlds; -size_t thlds_size = OID_COUNT_STEP; -double *response_value; -size_t response_size = OID_COUNT_STEP; -int retries = 0; -int *eval_method; -size_t eval_size = OID_COUNT_STEP; -char *delimiter; -char *output_delim; -char *miblist = NULL; -bool needmibs = false; -int calculate_rate = 0; -double offset = 0.0; -int rate_multiplier = 1; -state_data *previous_state; -double *previous_value; -size_t previous_size = OID_COUNT_STEP; -int perf_labels = 1; -char* ip_version = ""; -double multiplier = 1.0; -char *fmtstr = ""; -bool fmtstr_set = false; -char buffer[DEFAULT_BUFFER_SIZE]; -bool ignore_mib_parsing_errors = false; +static char regex_expect[MAX_INPUT_BUFFER] = ""; +static regex_t preg; +static regmatch_t pmatch[10]; +static char errbuf[MAX_INPUT_BUFFER] = ""; +static char perfstr[MAX_INPUT_BUFFER] = "| "; +static int cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE; +static int eflags = 0; +static int errcode, excode; + +static char *server_address = NULL; +static char *community = NULL; +static char **contextargs = NULL; +static char *context = NULL; +static char **authpriv = NULL; +static char *proto = NULL; +static char *seclevel = NULL; +static char *secname = NULL; +static char *authproto = NULL; +static char *privproto = NULL; +static char *authpasswd = NULL; +static char *privpasswd = NULL; +static int nulloid = STATE_UNKNOWN; +static char **oids = NULL; +static size_t oids_size = 0; +static char *label; +static char *units; +static char *port; +static char *snmpcmd; +static char string_value[MAX_INPUT_BUFFER] = ""; +static int invert_search=0; +static char **labels = NULL; +static char **unitv = NULL; +static size_t nlabels = 0; +static size_t labels_size = OID_COUNT_STEP; +static size_t nunits = 0; +static size_t unitv_size = OID_COUNT_STEP; +static size_t numoids = 0; +static int numauthpriv = 0; +static int numcontext = 0; +static int verbose = 0; +static bool usesnmpgetnext = false; +static char *warning_thresholds = NULL; +static char *critical_thresholds = NULL; +static thresholds **thlds; +static size_t thlds_size = OID_COUNT_STEP; +static double *response_value; +static size_t response_size = OID_COUNT_STEP; +static int retries = 0; +static int *eval_method; +static size_t eval_size = OID_COUNT_STEP; +static char *delimiter; +static char *output_delim; +static char *miblist = NULL; +static bool needmibs = false; +static int calculate_rate = 0; +static double offset = 0.0; +static int rate_multiplier = 1; +static state_data *previous_state; +static double *previous_value; +static size_t previous_size = OID_COUNT_STEP; +static int perf_labels = 1; +static char* ip_version = ""; +static double multiplier = 1.0; +static char *fmtstr = ""; +static bool fmtstr_set = false; +static char buffer[DEFAULT_BUFFER_SIZE]; +static bool ignore_mib_parsing_errors = false; static char *fix_snmp_range(char *th) { @@ -1030,7 +1030,7 @@ selected. -int +static int validate_arguments () { /* check whether to load locally installed MIBS (CPU/disk intensive) */ @@ -1139,7 +1139,7 @@ validate_arguments () /* trim leading whitespace if there is a leading quote, make sure it balances */ -char * +static char * thisarg (char *str) { str += strspn (str, " \t\r\n"); /* trim any leading whitespace */ @@ -1156,7 +1156,7 @@ thisarg (char *str) set the trailing quote to '\x0' if the string continues, advance beyond the comma */ -char * +static char * nextarg (char *str) { if (str[0] == '\'') { @@ -1188,7 +1188,7 @@ nextarg (char *str) /* multiply result (values 0 < n < 1 work as divider) */ -char * +static char * multiply (char *str) { char *endptr; @@ -1225,7 +1225,7 @@ multiply (char *str) } -void +static void print_help (void) { print_revision (progname, NP_VERSION); -- cgit v0.10-9-g596f From b1e96a3bf30d148c33de8715ed30a3df4a829ecd Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Fri, 27 Sep 2024 11:58:42 +0200 Subject: check_snmp: Remove unused PP-macros diff --git a/plugins/check_snmp.c b/plugins/check_snmp.c index bd1940e..90a0402 100644 --- a/plugins/check_snmp.c +++ b/plugins/check_snmp.c @@ -55,8 +55,6 @@ const char *email = "devel@monitoring-plugins.org"; #define CRIT_STRING 2 #define CRIT_REGEX 4 #define WARN_PRESENT 8 -#define WARN_STRING 16 -#define WARN_REGEX 32 #define OID_COUNT_STEP 8 -- cgit v0.10-9-g596f From 7ca72ecace9f74bbd121e6cb604722647cf90701 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Fri, 27 Sep 2024 13:51:21 +0200 Subject: check_disk: Declare global variables static Variables only used in that specific translation unit should be static to actually communicate that fact. Also allows the compiler to detect unused (global) variables. diff --git a/plugins/check_disk.c b/plugins/check_disk.c index 24de2d4..8bfc69b 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -119,44 +119,44 @@ enum #pragma alloca #endif -int process_arguments (int, char **); -void print_path (const char *mypath); -void set_all_thresholds (struct parameter_list *path); -int validate_arguments (uintmax_t, uintmax_t, double, double, double, double, char *); -void print_help (void); +static int process_arguments (int, char **); +static void print_path (const char *mypath); +static void set_all_thresholds (struct parameter_list *path); +static int validate_arguments (uintmax_t, uintmax_t, double, double, double, double, char *); +static void print_help (void); void print_usage (void); -double calculate_percent(uintmax_t, uintmax_t); -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); - -char *exclude_device; -char *units; -uintmax_t mult = 1024 * 1024; -int verbose = 0; -bool erronly = false; -bool display_mntp = false; -bool exact_match = false; -bool ignore_missing = false; -bool freespace_ignore_reserved = false; -bool display_inodes_perfdata = false; -char *warn_freespace_units = NULL; -char *crit_freespace_units = NULL; -char *warn_freespace_percent = NULL; -char *crit_freespace_percent = NULL; -char *warn_usedspace_units = NULL; -char *crit_usedspace_units = NULL; -char *warn_usedspace_percent = NULL; -char *crit_usedspace_percent = NULL; -char *warn_usedinodes_percent = NULL; -char *crit_usedinodes_percent = NULL; -char *warn_freeinodes_percent = NULL; -char *crit_freeinodes_percent = NULL; -bool path_selected = false; -bool path_ignored = false; -char *group = NULL; -struct stat *stat_buf; -struct name_list *seen = NULL; +static double calculate_percent(uintmax_t, uintmax_t); +static bool stat_path (struct parameter_list *p); +static void get_stats (struct parameter_list *p, struct fs_usage *fsp); +static void get_path_stats (struct parameter_list *p, struct fs_usage *fsp); + +static char *exclude_device; +static char *units; +static uintmax_t mult = 1024 * 1024; +static int verbose = 0; +static bool erronly = false; +static bool display_mntp = false; +static bool exact_match = false; +static bool ignore_missing = false; +static bool freespace_ignore_reserved = false; +static bool display_inodes_perfdata = false; +static char *warn_freespace_units = NULL; +static char *crit_freespace_units = NULL; +static char *warn_freespace_percent = NULL; +static char *crit_freespace_percent = NULL; +static char *warn_usedspace_units = NULL; +static char *crit_usedspace_units = NULL; +static char *warn_usedspace_percent = NULL; +static char *crit_usedspace_percent = NULL; +static char *warn_usedinodes_percent = NULL; +static char *crit_usedinodes_percent = NULL; +static char *warn_freeinodes_percent = NULL; +static char *crit_freeinodes_percent = NULL; +static bool path_selected = false; +static bool path_ignored = false; +static char *group = NULL; +static struct stat *stat_buf; +static struct name_list *seen = NULL; int -- cgit v0.10-9-g596f From fb5175aed64bdeb1b5f2725d185ba42576067dda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Fri, 27 Sep 2024 13:53:24 +0200 Subject: check_disk: remove unused variables and functions diff --git a/plugins/check_disk.c b/plugins/check_disk.c index 8bfc69b..b3dd301 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -120,9 +120,7 @@ enum #endif static int process_arguments (int, char **); -static void print_path (const char *mypath); static void set_all_thresholds (struct parameter_list *path); -static int validate_arguments (uintmax_t, uintmax_t, double, double, double, double, char *); static void print_help (void); void print_usage (void); static double calculate_percent(uintmax_t, uintmax_t); @@ -130,7 +128,6 @@ static bool stat_path (struct parameter_list *p); static void get_stats (struct parameter_list *p, struct fs_usage *fsp); static void get_path_stats (struct parameter_list *p, struct fs_usage *fsp); -static char *exclude_device; static char *units; static uintmax_t mult = 1024 * 1024; static int verbose = 0; @@ -899,18 +896,6 @@ process_arguments (int argc, char **argv) return true; } - - -void -print_path (const char *mypath) -{ - if (mypath == NULL) - printf ("\n"); - else - printf (_(" for %s\n"), mypath); -} - - void set_all_thresholds (struct parameter_list *path) { -- cgit v0.10-9-g596f From d7579e42495e2ad83a48d1cea258c6b708aea603 Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Wed, 2 Oct 2024 11:42:22 +0200 Subject: add new github test workflow for debian:testing and fedora:rawhide this workflow runs scheduled once a week, so it does not prevent PRs from being merged but still allows us to notice if anything will go wrong with the next release. Remove rawhide test from the mandatory tests like we did with debian testing already. diff --git a/.github/workflows/test-next.yml b/.github/workflows/test-next.yml new file mode 100644 index 0000000..083bc1e --- /dev/null +++ b/.github/workflows/test-next.yml @@ -0,0 +1,77 @@ +--- +name: Tests Debian:Testing and Fedora:Rawhide + +on: + push: + branches-ignore: + - '*' + schedule: + # Run every week on Monday at 9:00 AM (UTC) + - cron: '0 9 * * 1' + +jobs: + full-test: + name: Running unit and integrationt tests + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + distro: + - 'debian:testing' + include: + - distro: 'debian:testing' + prepare: .github/prepare_debian.sh + steps: + - name: Git clone repository + uses: actions/checkout@v4 + - name: Run the tests on ${{ matrix.distro }} + run: | + docker volume create --driver local --opt type=tmpfs --opt device=tmpfs --opt o=size=100m,uid=1000 tmp-vol + docker run \ + -e NPTEST_ACCEPTDEFAULT=1 \ + -e NPTEST_CACHE="/src/.github/NPTest.cache" \ + -w /src -v ${PWD}:/src \ + --tmpfs /media/ramdisk1 \ + -v /var/run/utmp:/var/run/utmp \ + --mount source=tmp-vol,destination=/src,target=/media/ramdisk2 \ + ${{ matrix.distro }} \ + /bin/sh -c '${{ matrix.prepare }} && \ + tools/setup && \ + ./configure --enable-libtap --with-ipv6=no && \ + make && \ + make test && \ + make dist && \ + tar zxf monitoring-plugins-*.tar.gz && \ + cd monitoring-plugins-*/ && \ + ./configure && \ + make' + docker container prune -f + docker volume prune -f + + build-test: + name: Running rpm build test on ${{ matrix.distro }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - {"distro": "fedora:rawhide", "build": ".github/mock.sh"} + steps: + - name: Git clone repository + uses: actions/checkout@v4 + - name: Run the tests on ${{ matrix.distro }} + run: | + docker volume create --driver local --opt type=tmpfs --opt device=tmpfs --opt o=size=100m,uid=1000 tmp-vol + docker run \ + --privileged=true \ + -e NPTEST_ACCEPTDEFAULT=1 \ + -e NPTEST_CACHE="/src/.github/NPTest.cache" \ + -w /src -v ${PWD}:/src \ + --tmpfs /media/ramdisk1 \ + -v /var/run/utmp:/var/run/utmp \ + --mount source=tmp-vol,destination=/src,target=/media/ramdisk2 \ + ${{ matrix.distro }} \ + /bin/sh -c '${{ matrix.build }} && \ + ls -la' + docker container prune -f + docker volume prune -f diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 33220d6..77ca658 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -54,7 +54,6 @@ jobs: matrix: include: - {"distro": "fedora:latest", "build": ".github/mock.sh"} - - {"distro": "fedora:rawhide", "build": ".github/mock.sh"} - {"distro": "rockylinux:8", "build": ".github/mock.sh"} - {"distro": "almalinux:9", "build": ".github/mock.sh"} # - {"distro": "oraclelinux:9", "build": ".github/mock.sh"} -- cgit v0.10-9-g596f From 2558e488f35334d75f662cb94dc2122f68c7740a Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Wed, 2 Oct 2024 20:59:31 +0200 Subject: add manual workflow trigger diff --git a/.github/workflows/test-next.yml b/.github/workflows/test-next.yml index 083bc1e..8124075 100644 --- a/.github/workflows/test-next.yml +++ b/.github/workflows/test-next.yml @@ -2,6 +2,7 @@ name: Tests Debian:Testing and Fedora:Rawhide on: + workflow_dispatch: {} push: branches-ignore: - '*' -- cgit v0.10-9-g596f From 3b960442485b965d853205bddeaa7f6a6b03253e Mon Sep 17 00:00:00 2001 From: Sven Nierlein Date: Wed, 9 Oct 2024 09:50:39 +0200 Subject: fix check_curl: OpenSSL SSL_read: error:0A000126:SSL routines::unexpected eof while reading, errno 0 using check_curl on a probably embedded device responding as 'Server: GoAhead-Webs' %> check_curl -H ... -S -vvv > GET / HTTP/1.1 Host: ... User-Agent: check_curl/v2.4.0 (monitoring-plugins 2.4.0, libcurl/7.76.1 OpenSSL/3.0.7 zlib/1.2.11 brotli/1.0.9 libidn2/2.3.0 libpsl/0.21.1 (+libidn2/2.3.0) libssh/0.10.4/openssl/zlib nghttp2/1.43.0) Accept: */* Connection: close * Mark bundle as not supporting multiuse * HTTP 1.0, assume close after body < HTTP/1.0 302 Redirect < Server: GoAhead-Webs < Date: Tue Mar 26 17:57:16 2019 < Cache-Control: no-cache, no-store, must-revalidate,private < Pragma: no-cache < Expires: 0 < Content-Type: text/html < X-Frame-Options: sameorigin < X-XSS-Protection: 1; mode=block < X-Content-Type-Options: nosniff < Location: https://... < * OpenSSL SSL_read: error:0A000126:SSL routines::unexpected eof while reading, errno 0 * Closing connection 0 reading the discussion on https://github.com/openssl/openssl/discussions/22690 suggest to set the option SSL_OP_IGNORE_UNEXPECTED_EOF which makes check_curl behave like check_http at this point. Since this is a rather new flag, fencing it in ifdefs. And since there can only be one ssl ctx function, we need to move both tasks into one function. diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 7f45b5a..d3bddac 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -214,6 +214,7 @@ char *client_privkey = NULL; char *ca_cert = NULL; bool verify_peer_and_host = false; bool is_openssl_callback = false; +bool add_sslctx_verify_fun = false; #if defined(HAVE_SSL) && defined(USE_OPENSSL) X509 *cert = NULL; #endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */ @@ -299,7 +300,7 @@ main (int argc, char **argv) int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) { - (void) preverify_ok; + (void) preverify_ok; /* TODO: we get all certificates of the chain, so which ones * should we test? * TODO: is the last certificate always the server certificate? @@ -324,9 +325,18 @@ int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) CURLcode sslctxfun(CURL *curl, SSL_CTX *sslctx, void *parm) { - (void) curl; // ignore unused parameter - (void) parm; // ignore unused parameter - SSL_CTX_set_verify(sslctx, SSL_VERIFY_PEER, verify_callback); + (void) curl; // ignore unused parameter + (void) parm; // ignore unused parameter + if(add_sslctx_verify_fun) { + SSL_CTX_set_verify(sslctx, SSL_VERIFY_PEER, verify_callback); + } + + // workaround for issue: + // OpenSSL SSL_read: error:0A000126:SSL routines::unexpected eof while reading, errno 0 + // see discussion https://github.com/openssl/openssl/discussions/22690 +#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF + SSL_CTX_set_options(sslctx, SSL_OP_IGNORE_UNEXPECTED_EOF); +#endif return CURLE_OK; } @@ -678,9 +688,8 @@ check_http (void) * OpenSSL-style libraries only!) */ #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"); + add_sslctx_verify_fun = true; is_openssl_callback = true; -#else /* USE_OPENSSL */ #endif /* USE_OPENSSL */ /* libcurl is built with OpenSSL, monitoring plugins, so falling * back to manually extracting certificate information */ @@ -713,12 +722,18 @@ check_http (void) #else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */ /* old libcurl, our only hope is OpenSSL, otherwise we are out of luck */ if (ssl_library == CURLHELP_SSL_LIBRARY_OPENSSL || ssl_library == CURLHELP_SSL_LIBRARY_LIBRESSL) - handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION"); + add_sslctx_verify_fun = true; else die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (no CURLOPT_SSL_CTX_FUNCTION, no OpenSSL library or libcurl too old and has no CURLOPT_CERTINFO)\n"); #endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */ } +#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 10, 6) /* required for CURLOPT_SSL_CTX_FUNCTION */ + // ssl ctx function is not available with all ssl backends + if (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, NULL) != CURLE_UNKNOWN_OPTION) + handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION"); +#endif + #endif /* LIBCURL_FEATURE_SSL */ /* set default or user-given user agent identification */ -- cgit v0.10-9-g596f From 0bd0aaa186efeaac815befc4ae32af6b1da74244 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 10 Oct 2024 22:06:33 +0200 Subject: Add clang-format config file diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..c7f0b5e --- /dev/null +++ b/.clang-format @@ -0,0 +1,10 @@ +BasedOnStyle: LLVM +UseTab: ForContinuationAndIndentation +IndentWidth: 4 +TabWidth: 4 +AllowShortIfStatementsOnASingleLine: false +BreakBeforeBraces: Attach +AlignConsecutiveMacros: true +ColumnLimit: 180 +IndentPPDirectives: AfterHash +SortIncludes: Never -- cgit v0.10-9-g596f From 990e48b7119fe547f93a6283db78420dfd30d5bc Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 15 Oct 2024 09:05:00 +0200 Subject: Adapt the hints to coding style in the CODING file diff --git a/CODING b/CODING index 74438e7..d0673e7 100644 --- a/CODING +++ b/CODING @@ -7,33 +7,20 @@ readability in a wide range of environments. 1. C Language Programming -All code should comply with the requirements of the Free Software +All code should comply with most of the requirements of the Free Software Foundation Coding standards (which are currently available at -http://www.gnu.org/prep/standards_toc.html). We also follow most of -the FSF guidelines. Developers may suggest deviations from the FSF +https://www.gnu.org/prep/standards/standards.html ). +We also follow most of the FSF guidelines, with the huge and explicit +exception of the style guidelines. +Developers may suggest deviations from the FSF style recommendations, which will be considered by open discussion on -the Monitoring Plugins devel mailing list. Any such deviations will -apply to the entire code base to ensure consistency. - -Currently, the exceptions to FSF recommendations are roughly equivalent -to GNU indent with invoked as 'indent -ts 2 -br'. Specifically, the -exceptions are as follows: - -a) leading white space for a statement should be formatted as tabs, -with one tab for each code indentation level. - -b) in statement continuation lines, format whitespace up to the column -starting the statement as tabs, format the rest as spaces (this -results in code that is legible regardless of tab-width setting). - -c) with the exception of the above, tabs should generally be avoided - -d) when tab width is 2 spaces, line-length should not exceed 80 -characters - -e) The opening brace of an if or while block is on the same line as -the end of the conditional expression (the '-br' option). +the Monitoring Plugins devel mailing list or the Github Pull Request. +Any such deviations should be +applied to the entire code base to ensure consistency. +The style guideline is the following: +Whatever clang-format does with the configuration file available (.clang-format) +Apart from that, code should naturally be readable and easy to understand. 2. Perl Language Programming -- cgit v0.10-9-g596f From 0d61e6d126817ee38582eea307c9feecf75330f9 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 15 Oct 2024 09:32:09 +0200 Subject: docs: update copyright and remove revision section diff --git a/doc/developer-guidelines.sgml b/doc/developer-guidelines.sgml index 37c963e..edadaad 100644 --- a/doc/developer-guidelines.sgml +++ b/doc/developer-guidelines.sgml @@ -14,15 +14,8 @@ 2013 Monitoring Plugins Development Guidelines - - - 1796 - 2007-09-24 14:51:07 -0400 (Mon, 24 Sep 2007) - - - - 2000 - 2013 + 2000 - 2024 Monitoring Plugins Development Team @@ -34,7 +27,7 @@ the plugin developers and encourage the standardization of the different kind of plugins: C, shell, perl, python, etc. - Monitoring Plugins Development Guidelines Copyright (C) 2000-2013 + Monitoring Plugins Development Guidelines Copyright (C) 2000-2024 (Monitoring Plugins Team) Permission is granted to make and distribute verbatim -- cgit v0.10-9-g596f From 2b1b5c1ce9c70df9853fa4ac01d740d6a7e45d37 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 15 Oct 2024 09:32:28 +0200 Subject: Docs: remove sections about translation This commit removes the sections about translations, because, well, we removed translations a while ago. The documentation should reflect that. diff --git a/doc/developer-guidelines.sgml b/doc/developer-guidelines.sgml index edadaad..4186ed7 100644 --- a/doc/developer-guidelines.sgml +++ b/doc/developer-guidelines.sgml @@ -376,13 +376,6 @@ It is up to third party programs to convert the Monitoring Plugins performance data into graphs. - -
Translations - If possible, use translation tools for all output to respect the user's language - settings. See for guidelines - for the core plugins. - -
System Commands and Auxiliary Files @@ -749,32 +742,6 @@ setup the tests. Run "make test" to run all the tests. All commits will be written to a ChangeLog at release time.
- -
Translations for developers - To make the job easier for translators, please follow these guidelines: - - - Before creating new strings, check the po/monitoring-plugins.pot file to - see if a similar string - already exists - - - For help texts, break into individual options so that these can be reused - between plugins - - Try to avoid linefeeds unless you are working on a block of text - Short help is not translated - Long help has options in English language, but text translated - "Copyright" kept in English - Copyright holder names kept in original text - Debugging output does not need to be translated - -
- -
Translations for translators - To create an up to date list of translatable strings, run: tools/gen_locale.sh -
-
Submission of new plugins and patches -- cgit v0.10-9-g596f From 1b293a4032dfa87b8eeee5695ebe0c74a2b9a413 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 15 Oct 2024 09:33:34 +0200 Subject: Adapted the coding guidelines slightly + typo diff --git a/doc/developer-guidelines.sgml b/doc/developer-guidelines.sgml index 4186ed7..0afa733 100644 --- a/doc/developer-guidelines.sgml +++ b/doc/developer-guidelines.sgml @@ -713,19 +713,18 @@ setup the tests. Run "make test" to run all the tests.
Coding guidelines See GNU - Coding standards for general guidelines. + Coding standards for general guidelines. + Some parts of the guidelines (namely and explicitly the coding style) + are not seen as best practice by us.
C coding - Variables should be declared at the beginning of code blocks and - not inline because of portability with older compilers. - You should use the type "bool" and its values "true" and "false" instead of the "int" type for booleans.
Crediting sources - If you have copied a routine from another source, make sure the licence + If you have copied a routine from another source, make sure the license from your source allows this. Add a comment referencing the ACKNOWLEDGEMENTS file, where you can put more detail about the source. For contributed code, do not add any named credits in the source code -- cgit v0.10-9-g596f From 0caa47a50bae586173f40ca7544d4290de0097a5 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 15 Oct 2024 11:44:28 +0200 Subject: check_icmp: clang-format diff --git a/plugins-root/check_icmp.c b/plugins-root/check_icmp.c index f788d42..5ad1d84 100644 --- a/plugins-root/check_icmp.c +++ b/plugins-root/check_icmp.c @@ -1,40 +1,40 @@ /***************************************************************************** -* -* Monitoring check_icmp plugin -* -* License: GPL -* Copyright (c) 2005-2008 Monitoring Plugins Development Team -* Original Author : Andreas Ericsson -* -* Description: -* -* This file contains the check_icmp plugin -* -* Relevant RFC's: 792 (ICMP), 791 (IP) -* -* This program was modeled somewhat after the check_icmp program, -* which was in turn a hack of fping (www.fping.org) but has been -* completely rewritten since to generate higher precision rta values, -* and support several different modes as well as setting ttl to control. -* redundant routes. The only remainders of fping is currently a few -* function names. -* -* -* 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_icmp plugin + * + * License: GPL + * Copyright (c) 2005-2008 Monitoring Plugins Development Team + * Original Author : Andreas Ericsson + * + * Description: + * + * This file contains the check_icmp plugin + * + * Relevant RFC's: 792 (ICMP), 791 (IP) + * + * This program was modeled somewhat after the check_icmp program, + * which was in turn a hack of fping (www.fping.org) but has been + * completely rewritten since to generate higher precision rta values, + * and support several different modes as well as setting ttl to control. + * redundant routes. The only remainders of fping is currently a few + * function names. + * + * + * 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 . + * + * + *****************************************************************************/ /* progname may change */ /* char *progname = "check_icmp"; */ @@ -48,7 +48,7 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #if HAVE_SYS_SOCKIO_H -#include +# include #endif #include @@ -65,84 +65,83 @@ const char *email = "devel@monitoring-plugins.org"; #include #include - /** sometimes undefined system macros (quite a few, actually) **/ #ifndef MAXTTL -# define MAXTTL 255 +# define MAXTTL 255 #endif #ifndef INADDR_NONE -# define INADDR_NONE (in_addr_t)(-1) +# define INADDR_NONE (in_addr_t)(-1) #endif #ifndef SOL_IP -#define SOL_IP 0 +# define SOL_IP 0 #endif /* we bundle these in one #ifndef, since they're all from BSD * Put individual #ifndef's around those that bother you */ #ifndef ICMP_UNREACH_NET_UNKNOWN -# define ICMP_UNREACH_NET_UNKNOWN 6 -# define ICMP_UNREACH_HOST_UNKNOWN 7 -# define ICMP_UNREACH_ISOLATED 8 -# define ICMP_UNREACH_NET_PROHIB 9 -# define ICMP_UNREACH_HOST_PROHIB 10 -# define ICMP_UNREACH_TOSNET 11 -# define ICMP_UNREACH_TOSHOST 12 +# define ICMP_UNREACH_NET_UNKNOWN 6 +# define ICMP_UNREACH_HOST_UNKNOWN 7 +# define ICMP_UNREACH_ISOLATED 8 +# define ICMP_UNREACH_NET_PROHIB 9 +# define ICMP_UNREACH_HOST_PROHIB 10 +# define ICMP_UNREACH_TOSNET 11 +# define ICMP_UNREACH_TOSHOST 12 #endif /* tru64 has the ones above, but not these */ #ifndef ICMP_UNREACH_FILTER_PROHIB -# define ICMP_UNREACH_FILTER_PROHIB 13 -# define ICMP_UNREACH_HOST_PRECEDENCE 14 -# define ICMP_UNREACH_PRECEDENCE_CUTOFF 15 +# define ICMP_UNREACH_FILTER_PROHIB 13 +# define ICMP_UNREACH_HOST_PRECEDENCE 14 +# define ICMP_UNREACH_PRECEDENCE_CUTOFF 15 #endif -typedef unsigned short range_t; /* type for get_range() -- unimplemented */ +typedef unsigned short range_t; /* type for get_range() -- unimplemented */ typedef struct rta_host { - unsigned short id; /* id in **table, and icmp pkts */ - char *name; /* arg used for adding this host */ - char *msg; /* icmp error message, if any */ - struct sockaddr_storage saddr_in; /* the address of this host */ - struct sockaddr_storage error_addr; /* stores address of error replies */ - unsigned long long time_waited; /* total time waited, in usecs */ + unsigned short id; /* id in **table, and icmp pkts */ + char *name; /* arg used for adding this host */ + char *msg; /* icmp error message, if any */ + struct sockaddr_storage saddr_in; /* the address of this host */ + struct sockaddr_storage error_addr; /* stores address of error replies */ + unsigned long long time_waited; /* total time waited, in usecs */ unsigned int icmp_sent, icmp_recv, icmp_lost; /* counters */ - unsigned char icmp_type, icmp_code; /* type and code from errors */ - unsigned short flags; /* control/status flags */ - double rta; /* measured RTA */ - int rta_status; // check result for RTA checks - double rtmax; /* max rtt */ - double rtmin; /* min rtt */ - double jitter; /* measured jitter */ - int jitter_status; // check result for Jitter checks - double jitter_max; /* jitter rtt maximum */ - double jitter_min; /* jitter rtt minimum */ + unsigned char icmp_type, icmp_code; /* type and code from errors */ + unsigned short flags; /* control/status flags */ + double rta; /* measured RTA */ + int rta_status; // check result for RTA checks + double rtmax; /* max rtt */ + double rtmin; /* min rtt */ + double jitter; /* measured jitter */ + int jitter_status; // check result for Jitter checks + double jitter_max; /* jitter rtt maximum */ + double jitter_min; /* jitter rtt minimum */ double EffectiveLatency; - double mos; /* Mean opnion score */ - int mos_status; // check result for MOS checks - double score; /* score */ - int score_status; // check result for score checks + double mos; /* Mean opnion score */ + int mos_status; // check result for MOS checks + double score; /* score */ + int score_status; // check result for score checks u_int last_tdiff; - u_int last_icmp_seq; /* Last ICMP_SEQ to check out of order pkts */ - unsigned char pl; /* measured packet loss */ - int pl_status; // check result for packet loss checks - struct rta_host *next; /* linked list */ - int order_status; // check result for packet order checks + u_int last_icmp_seq; /* Last ICMP_SEQ to check out of order pkts */ + unsigned char pl; /* measured packet loss */ + int pl_status; // check result for packet loss checks + struct rta_host *next; /* linked list */ + int order_status; // check result for packet order checks } rta_host; -#define FLAG_LOST_CAUSE 0x01 /* decidedly dead target. */ +#define FLAG_LOST_CAUSE 0x01 /* decidedly dead target. */ /* threshold structure. all values are maximum allowed, exclusive */ typedef struct threshold { - unsigned char pl; /* max allowed packet loss in percent */ - unsigned int rta; /* roundtrip time average, microseconds */ - double jitter; /* jitter time average, microseconds */ - double mos; /* MOS */ - double score; /* Score */ + unsigned char pl; /* max allowed packet loss in percent */ + unsigned int rta; /* roundtrip time average, microseconds */ + double jitter; /* jitter time average, microseconds */ + double mos; /* MOS */ + double score; /* Score */ } threshold; /* the data structure */ typedef struct icmp_ping_data { - struct timeval stime; /* timestamp (saved in protocol struct as well) */ + struct timeval stime; /* timestamp (saved in protocol struct as well) */ unsigned short ping_id; } icmp_ping_data; @@ -171,48 +170,42 @@ typedef union icmp_packet { * MODE_ICMP: implement something similar to check_icmp (MODE_RTA without * tcp and udp args does this) */ -#define MODE_RTA 0 +#define MODE_RTA 0 #define MODE_HOSTCHECK 1 -#define MODE_ALL 2 -#define MODE_ICMP 3 +#define MODE_ALL 2 +#define MODE_ICMP 3 -enum enum_threshold_mode { - const_rta_mode, - const_packet_loss_mode, - const_jitter_mode, - const_mos_mode, - const_score_mode -}; +enum enum_threshold_mode { const_rta_mode, const_packet_loss_mode, const_jitter_mode, const_mos_mode, const_score_mode }; typedef enum enum_threshold_mode threshold_mode; /* the different ping types we can do * TODO: investigate ARP ping as well */ #define HAVE_ICMP 1 -#define HAVE_UDP 2 -#define HAVE_TCP 4 -#define HAVE_ARP 8 - -#define MIN_PING_DATA_SIZE sizeof(struct icmp_ping_data) -#define MAX_IP_PKT_SIZE 65536 /* (theoretical) max IP packet size */ -#define IP_HDR_SIZE 20 -#define MAX_PING_DATA (MAX_IP_PKT_SIZE - IP_HDR_SIZE - ICMP_MINLEN) +#define HAVE_UDP 2 +#define HAVE_TCP 4 +#define HAVE_ARP 8 + +#define MIN_PING_DATA_SIZE sizeof(struct icmp_ping_data) +#define MAX_IP_PKT_SIZE 65536 /* (theoretical) max IP packet size */ +#define IP_HDR_SIZE 20 +#define MAX_PING_DATA (MAX_IP_PKT_SIZE - IP_HDR_SIZE - ICMP_MINLEN) #define DEFAULT_PING_DATA_SIZE (MIN_PING_DATA_SIZE + 44) /* various target states */ -#define TSTATE_INACTIVE 0x01 /* don't ping this host anymore */ -#define TSTATE_WAITING 0x02 /* unanswered packets on the wire */ -#define TSTATE_ALIVE 0x04 /* target is alive (has answered something) */ -#define TSTATE_UNREACH 0x08 +#define TSTATE_INACTIVE 0x01 /* don't ping this host anymore */ +#define TSTATE_WAITING 0x02 /* unanswered packets on the wire */ +#define TSTATE_ALIVE 0x04 /* target is alive (has answered something) */ +#define TSTATE_UNREACH 0x08 /** prototypes **/ -void print_help (void); -void print_usage (void); +void print_help(void); +void print_usage(void); static u_int get_timevar(const char *); static u_int get_timevaldiff(struct timeval *, struct timeval *); static in_addr_t get_ip_address(const char *); static int wait_for_reply(int, u_int); -static int recvfrom_wto(int, void *, unsigned int, struct sockaddr *, u_int *, struct timeval*); +static int recvfrom_wto(int, void *, unsigned int, struct sockaddr *, u_int *, struct timeval *); static int send_icmp_ping(int, struct rta_host *); static int get_threshold(char *str, threshold *th); static bool get_threshold2(char *str, size_t length, threshold *, threshold *, threshold_mode mode); @@ -235,20 +228,8 @@ extern char **environ; /** global variables **/ static struct rta_host **table, *cursor, *list; -static threshold crit = { - .pl = 80, - .rta = 500000, - .jitter = 0.0, - .mos = 0.0, - .score = 0.0 -}; -static threshold warn = { - .pl = 40, - .rta = 200000, - .jitter = 0.0, - .mos = 0.0, - .score = 0.0 -}; +static threshold crit = {.pl = 80, .rta = 500000, .jitter = 0.0, .mos = 0.0, .score = 0.0}; +static threshold warn = {.pl = 40, .rta = 200000, .jitter = 0.0, .mos = 0.0, .score = 0.0}; static int mode, protocols, sockets, debug = 0, timeout = 10; static unsigned short icmp_data_size = DEFAULT_PING_DATA_SIZE; @@ -268,17 +249,15 @@ static unsigned int warn_down = 1, crit_down = 1; /* host down threshold values static int min_hosts_alive = -1; float pkt_backoff_factor = 1.5; float target_backoff_factor = 1.5; -bool rta_mode=false; -bool pl_mode=false; -bool jitter_mode=false; -bool score_mode=false; -bool mos_mode=false; -bool order_mode=false; +bool rta_mode = false; +bool pl_mode = false; +bool jitter_mode = false; +bool score_mode = false; +bool mos_mode = false; +bool order_mode = false; /** code start **/ -static void -crash(const char *fmt, ...) -{ +static void crash(const char *fmt, ...) { va_list ap; printf("%s: ", progname); @@ -287,55 +266,100 @@ crash(const char *fmt, ...) vprintf(fmt, ap); va_end(ap); - if(errno) printf(": %s", strerror(errno)); + if (errno) + printf(": %s", strerror(errno)); puts(""); exit(3); } - -static const char * -get_icmp_error_msg(unsigned char icmp_type, unsigned char icmp_code) -{ +static const char *get_icmp_error_msg(unsigned char icmp_type, unsigned char icmp_code) { const char *msg = "unreachable"; - if(debug > 1) printf("get_icmp_error_msg(%u, %u)\n", icmp_type, icmp_code); - switch(icmp_type) { + if (debug > 1) + printf("get_icmp_error_msg(%u, %u)\n", icmp_type, icmp_code); + switch (icmp_type) { case ICMP_UNREACH: - switch(icmp_code) { - case ICMP_UNREACH_NET: msg = "Net unreachable"; break; - case ICMP_UNREACH_HOST: msg = "Host unreachable"; break; - case ICMP_UNREACH_PROTOCOL: msg = "Protocol unreachable (firewall?)"; break; - case ICMP_UNREACH_PORT: msg = "Port unreachable (firewall?)"; break; - case ICMP_UNREACH_NEEDFRAG: msg = "Fragmentation needed"; break; - case ICMP_UNREACH_SRCFAIL: msg = "Source route failed"; break; - case ICMP_UNREACH_ISOLATED: msg = "Source host isolated"; break; - case ICMP_UNREACH_NET_UNKNOWN: msg = "Unknown network"; break; - case ICMP_UNREACH_HOST_UNKNOWN: msg = "Unknown host"; break; - case ICMP_UNREACH_NET_PROHIB: msg = "Network denied (firewall?)"; break; - case ICMP_UNREACH_HOST_PROHIB: msg = "Host denied (firewall?)"; break; - case ICMP_UNREACH_TOSNET: msg = "Bad TOS for network (firewall?)"; break; - case ICMP_UNREACH_TOSHOST: msg = "Bad TOS for host (firewall?)"; break; - case ICMP_UNREACH_FILTER_PROHIB: msg = "Prohibited by filter (firewall)"; break; - case ICMP_UNREACH_HOST_PRECEDENCE: msg = "Host precedence violation"; break; - case ICMP_UNREACH_PRECEDENCE_CUTOFF: msg = "Precedence cutoff"; break; - default: msg = "Invalid code"; break; + switch (icmp_code) { + case ICMP_UNREACH_NET: + msg = "Net unreachable"; + break; + case ICMP_UNREACH_HOST: + msg = "Host unreachable"; + break; + case ICMP_UNREACH_PROTOCOL: + msg = "Protocol unreachable (firewall?)"; + break; + case ICMP_UNREACH_PORT: + msg = "Port unreachable (firewall?)"; + break; + case ICMP_UNREACH_NEEDFRAG: + msg = "Fragmentation needed"; + break; + case ICMP_UNREACH_SRCFAIL: + msg = "Source route failed"; + break; + case ICMP_UNREACH_ISOLATED: + msg = "Source host isolated"; + break; + case ICMP_UNREACH_NET_UNKNOWN: + msg = "Unknown network"; + break; + case ICMP_UNREACH_HOST_UNKNOWN: + msg = "Unknown host"; + break; + case ICMP_UNREACH_NET_PROHIB: + msg = "Network denied (firewall?)"; + break; + case ICMP_UNREACH_HOST_PROHIB: + msg = "Host denied (firewall?)"; + break; + case ICMP_UNREACH_TOSNET: + msg = "Bad TOS for network (firewall?)"; + break; + case ICMP_UNREACH_TOSHOST: + msg = "Bad TOS for host (firewall?)"; + break; + case ICMP_UNREACH_FILTER_PROHIB: + msg = "Prohibited by filter (firewall)"; + break; + case ICMP_UNREACH_HOST_PRECEDENCE: + msg = "Host precedence violation"; + break; + case ICMP_UNREACH_PRECEDENCE_CUTOFF: + msg = "Precedence cutoff"; + break; + default: + msg = "Invalid code"; + break; } break; case ICMP_TIMXCEED: /* really 'out of reach', or non-existent host behind a router serving * two different subnets */ - switch(icmp_code) { - case ICMP_TIMXCEED_INTRANS: msg = "Time to live exceeded in transit"; break; - case ICMP_TIMXCEED_REASS: msg = "Fragment reassembly time exceeded"; break; - default: msg = "Invalid code"; break; + switch (icmp_code) { + case ICMP_TIMXCEED_INTRANS: + msg = "Time to live exceeded in transit"; + break; + case ICMP_TIMXCEED_REASS: + msg = "Fragment reassembly time exceeded"; + break; + default: + msg = "Invalid code"; + break; } break; - case ICMP_SOURCEQUENCH: msg = "Transmitting too fast"; break; - case ICMP_REDIRECT: msg = "Redirect (change route)"; break; - case ICMP_PARAMPROB: msg = "Bad IP header (required option absent)"; break; + case ICMP_SOURCEQUENCH: + msg = "Transmitting too fast"; + break; + case ICMP_REDIRECT: + msg = "Redirect (change route)"; + break; + case ICMP_PARAMPROB: + msg = "Bad IP header (required option absent)"; + break; /* the following aren't error messages, so ignore */ case ICMP_TSTAMP: @@ -344,25 +368,26 @@ get_icmp_error_msg(unsigned char icmp_type, unsigned char icmp_code) case ICMP_IREQREPLY: case ICMP_MASKREQ: case ICMP_MASKREPLY: - default: msg = ""; break; + default: + msg = ""; + break; } return msg; } -static int -handle_random_icmp(unsigned char *packet, struct sockaddr_storage *addr) -{ +static int handle_random_icmp(unsigned char *packet, struct sockaddr_storage *addr) { struct icmp p, sent_icmp; struct rta_host *host = NULL; memcpy(&p, packet, sizeof(p)); - if(p.icmp_type == ICMP_ECHO && ntohs(p.icmp_id) == pid) { + if (p.icmp_type == ICMP_ECHO && ntohs(p.icmp_id) == pid) { /* echo request from us to us (pinging localhost) */ return 0; } - if(debug) printf("handle_random_icmp(%p, %p)\n", (void *)&p, (void *)addr); + if (debug) + printf("handle_random_icmp(%p, %p)\n", (void *)&p, (void *)addr); /* only handle a few types, since others can't possibly be replies to * us in a sane network (if it is anyway, it will be counted as lost @@ -374,44 +399,39 @@ handle_random_icmp(unsigned char *packet, struct sockaddr_storage *addr) * TIMXCEED actually sends a proper icmp response we will have passed * too many hops to have a hope of reaching it later, in which case it * indicates overconfidence in the network, poor routing or both. */ - if(p.icmp_type != ICMP_UNREACH && p.icmp_type != ICMP_TIMXCEED && - p.icmp_type != ICMP_SOURCEQUENCH && p.icmp_type != ICMP_PARAMPROB) - { + if (p.icmp_type != ICMP_UNREACH && p.icmp_type != ICMP_TIMXCEED && p.icmp_type != ICMP_SOURCEQUENCH && p.icmp_type != ICMP_PARAMPROB) { return 0; } /* might be for us. At least it holds the original package (according * to RFC 792). If it isn't, just ignore it */ memcpy(&sent_icmp, packet + 28, sizeof(sent_icmp)); - if(sent_icmp.icmp_type != ICMP_ECHO || ntohs(sent_icmp.icmp_id) != pid || - ntohs(sent_icmp.icmp_seq) >= targets*packets) - { - if(debug) printf("Packet is no response to a packet we sent\n"); + if (sent_icmp.icmp_type != ICMP_ECHO || ntohs(sent_icmp.icmp_id) != pid || ntohs(sent_icmp.icmp_seq) >= targets * packets) { + if (debug) + printf("Packet is no response to a packet we sent\n"); return 0; } /* it is indeed a response for us */ - host = table[ntohs(sent_icmp.icmp_seq)/packets]; - if(debug) { + host = table[ntohs(sent_icmp.icmp_seq) / packets]; + if (debug) { char address[INET6_ADDRSTRLEN]; parse_address(addr, address, sizeof(address)); - printf("Received \"%s\" from %s for ICMP ECHO sent to %s.\n", - get_icmp_error_msg(p.icmp_type, p.icmp_code), - address, host->name); + printf("Received \"%s\" from %s for ICMP ECHO sent to %s.\n", get_icmp_error_msg(p.icmp_type, p.icmp_code), address, host->name); } icmp_lost++; host->icmp_lost++; /* don't spend time on lost hosts any more */ - if(host->flags & FLAG_LOST_CAUSE) return 0; + if (host->flags & FLAG_LOST_CAUSE) + return 0; /* source quench means we're sending too fast, so increase the * interval and mark this packet lost */ - if(p.icmp_type == ICMP_SOURCEQUENCH) { + if (p.icmp_type == ICMP_SOURCEQUENCH) { pkt_interval *= pkt_backoff_factor; target_interval *= target_backoff_factor; - } - else { + } else { targets_down++; host->flags |= FLAG_LOST_CAUSE; } @@ -422,21 +442,18 @@ handle_random_icmp(unsigned char *packet, struct sockaddr_storage *addr) return 0; } -void parse_address(struct sockaddr_storage *addr, char *address, int size) -{ +void parse_address(struct sockaddr_storage *addr, char *address, int size) { switch (address_family) { case AF_INET: inet_ntop(address_family, &((struct sockaddr_in *)addr)->sin_addr, address, size); - break; + break; case AF_INET6: inet_ntop(address_family, &((struct sockaddr_in6 *)addr)->sin6_addr, address, size); - break; + break; } } -int -main(int argc, char **argv) -{ +int main(int argc, char **argv) { int i; char *ptr; long int arg; @@ -450,10 +467,10 @@ main(int argc, char **argv) int on = 1; #endif char *source_ip = NULL; - char * opts_str = "vhVw:c:n:p:t:H:s:i:b:I:l:m:P:R:J:S:M:O64"; - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + char *opts_str = "vhVw:c:n:p:t:H:s:i:b:I:l:m:P:R:J:S:M:O64"; + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* we only need to be setsuid when we get the sockets, so do * that before pointer magic (esp. on network data) */ @@ -465,8 +482,10 @@ main(int argc, char **argv) /* get calling name the old-fashioned way for portability instead * of relying on the glibc-ism __progname */ ptr = strrchr(argv[0], '/'); - if(ptr) progname = &ptr[1]; - else progname = argv[0]; + if (ptr) + progname = &ptr[1]; + else + progname = argv[0]; /* now set defaults. Use progname to set them initially (allows for * superfast check_host program when target host is up */ @@ -478,31 +497,29 @@ main(int argc, char **argv) crit.rta = 500000; crit.pl = 80; crit.jitter = 50; - crit.mos= 3; - crit.score=70; + crit.mos = 3; + crit.score = 70; /* Default warning thresholds */ warn.rta = 200000; warn.pl = 40; warn.jitter = 40; - warn.mos= 3.5; - warn.score=80; + warn.mos = 3.5; + warn.score = 80; protocols = HAVE_ICMP | HAVE_UDP | HAVE_TCP; - pkt_interval = 80000; /* 80 msec packet interval by default */ + pkt_interval = 80000; /* 80 msec packet interval by default */ packets = 5; - if(!strcmp(progname, "check_icmp") || !strcmp(progname, "check_ping")) { + if (!strcmp(progname, "check_icmp") || !strcmp(progname, "check_ping")) { mode = MODE_ICMP; protocols = HAVE_ICMP; - } - else if(!strcmp(progname, "check_host")) { + } else if (!strcmp(progname, "check_host")) { mode = MODE_HOSTCHECK; pkt_interval = 1000000; packets = 5; crit.rta = warn.rta = 1000000; crit.pl = warn.pl = 100; - } - else if(!strcmp(progname, "check_rta_multi")) { + } else if (!strcmp(progname, "check_rta_multi")) { mode = MODE_ALL; target_interval = 0; pkt_interval = 50000; @@ -510,17 +527,17 @@ main(int argc, char **argv) } /* support "--help" and "--version" */ - if(argc == 2) { - if(!strcmp(argv[1], "--help")) + if (argc == 2) { + if (!strcmp(argv[1], "--help")) strcpy(argv[1], "-h"); - if(!strcmp(argv[1], "--version")) + if (!strcmp(argv[1], "--version")) strcpy(argv[1], "-V"); } /* Parse protocol arguments first */ - for(i = 1; i < argc; i++) { - while((arg = getopt(argc, argv, opts_str)) != EOF) { - switch(arg) { + for (i = 1; i < argc; i++) { + while ((arg = getopt(argc, argv, opts_str)) != EOF) { + switch (arg) { case '4': if (address_family != -1) crash("Multiple protocol versions not supported"); @@ -532,7 +549,7 @@ main(int argc, char **argv) crash("Multiple protocol versions not supported"); address_family = AF_INET6; #else - usage (_("IPv6 support not available\n")); + usage(_("IPv6 support not available\n")); #endif break; } @@ -545,22 +562,19 @@ main(int argc, char **argv) unsigned long size; bool err; /* parse the arguments */ - for(i = 1; i < argc; i++) { - while((arg = getopt(argc, argv, opts_str)) != EOF) { - switch(arg) { + for (i = 1; i < argc; i++) { + while ((arg = getopt(argc, argv, opts_str)) != EOF) { + switch (arg) { case 'v': debug++; break; case 'b': - size = strtol(optarg,NULL,0); - if (size >= (sizeof(struct icmp) + sizeof(struct icmp_ping_data)) && - size < MAX_PING_DATA) { + size = strtol(optarg, NULL, 0); + if (size >= (sizeof(struct icmp) + sizeof(struct icmp_ping_data)) && size < MAX_PING_DATA) { icmp_data_size = size; icmp_pkt_size = size + ICMP_MINLEN; } else - usage_va("ICMP data length must be between: %lu and %lu", - sizeof(struct icmp) + sizeof(struct icmp_ping_data), - MAX_PING_DATA - 1); + usage_va("ICMP data length must be between: %lu and %lu", sizeof(struct icmp) + sizeof(struct icmp_ping_data), MAX_PING_DATA - 1); break; case 'i': pkt_interval = get_timevar(optarg); @@ -580,7 +594,8 @@ main(int argc, char **argv) break; case 't': timeout = strtoul(optarg, NULL, 0); - if(!timeout) timeout = 10; + if (!timeout) + timeout = 10; break; case 'H': add_target(optarg); @@ -593,7 +608,7 @@ main(int argc, char **argv) break; case 'd': /* implement later, for cluster checks */ warn_down = (unsigned char)strtoul(optarg, &ptr, 0); - if(ptr) { + if (ptr) { crit_down = (unsigned char)strtoul(ptr + 1, NULL, 0); } break; @@ -601,54 +616,54 @@ main(int argc, char **argv) source_ip = optarg; break; case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); + print_help(); + exit(STATE_UNKNOWN); break; case 'R': /* RTA mode */ err = get_threshold2(optarg, strlen(optarg), &warn, &crit, const_rta_mode); if (!err) { - crash("Failed to parse RTA threshold"); + crash("Failed to parse RTA threshold"); } - rta_mode=true; + rta_mode = true; break; case 'P': /* packet loss mode */ err = get_threshold2(optarg, strlen(optarg), &warn, &crit, const_packet_loss_mode); if (!err) { - crash("Failed to parse packet loss threshold"); + crash("Failed to parse packet loss threshold"); } - pl_mode=true; + pl_mode = true; break; case 'J': /* jitter mode */ err = get_threshold2(optarg, strlen(optarg), &warn, &crit, const_jitter_mode); if (!err) { - crash("Failed to parse jitter threshold"); + crash("Failed to parse jitter threshold"); } - jitter_mode=true; + jitter_mode = true; break; case 'M': /* MOS mode */ err = get_threshold2(optarg, strlen(optarg), &warn, &crit, const_mos_mode); if (!err) { - crash("Failed to parse MOS threshold"); + crash("Failed to parse MOS threshold"); } - mos_mode=true; + mos_mode = true; break; case 'S': /* score mode */ err = get_threshold2(optarg, strlen(optarg), &warn, &crit, const_score_mode); if (!err) { - crash("Failed to parse score threshold"); + crash("Failed to parse score threshold"); } - score_mode=true; + score_mode = true; break; case 'O': /* out of order mode */ - order_mode=true; + order_mode = true; break; } } @@ -663,37 +678,42 @@ main(int argc, char **argv) /* printf("pid = %u\n", pid); */ /* Parse extra opts if any */ - argv=np_extra_opts(&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); argv = &argv[optind]; - while(*argv) { + while (*argv) { add_target(*argv); argv++; } - if(!targets) { + if (!targets) { errno = 0; crash("No hosts to check"); } // add_target might change address_family - switch ( address_family ){ - case AF_INET: icmp_proto = IPPROTO_ICMP; - break; - case AF_INET6: icmp_proto = IPPROTO_ICMPV6; - break; - default: crash("Address family not supported"); + switch (address_family) { + case AF_INET: + icmp_proto = IPPROTO_ICMP; + break; + case AF_INET6: + icmp_proto = IPPROTO_ICMPV6; + break; + default: + crash("Address family not supported"); } - if((icmp_sock = socket(address_family, SOCK_RAW, icmp_proto)) != -1) + if ((icmp_sock = socket(address_family, SOCK_RAW, icmp_proto)) != -1) sockets |= HAVE_ICMP; - else icmp_sockerrno = errno; + else + icmp_sockerrno = errno; - if( source_ip ) + if (source_ip) set_source_ip(source_ip); #ifdef SO_TIMESTAMP - if(setsockopt(icmp_sock, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on))) - if(debug) printf("Warning: no SO_TIMESTAMP support\n"); + if (setsockopt(icmp_sock, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on))) + if (debug) + printf("Warning: no SO_TIMESTAMP support\n"); #endif // SO_TIMESTAMP /* now drop privileges (no effect if not setsuid or geteuid() == 0) */ @@ -702,8 +722,8 @@ main(int argc, char **argv) return 1; } - if(!sockets) { - if(icmp_sock == -1) { + if (!sockets) { + if (icmp_sock == -1) { errno = icmp_sockerrno; crash("Failed to obtain ICMP socket"); return -1; @@ -719,13 +739,16 @@ main(int argc, char **argv) /* return -1; */ /* } */ } - if(!ttl) ttl = 64; + if (!ttl) + ttl = 64; - if(icmp_sock) { + if (icmp_sock) { result = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl)); - if(debug) { - if(result == -1) printf("setsockopt failed\n"); - else printf("ttl set to %u\n", ttl); + if (debug) { + if (result == -1) + printf("setsockopt failed\n"); + else + printf("ttl set to %u\n", ttl); } } @@ -733,85 +756,82 @@ main(int argc, char **argv) * (nothing will break if they do), but some anal plugin maintainer * will probably add some printf() thing here later, so it might be * best to at least show them where to do it. ;) */ - if(warn.pl > crit.pl) warn.pl = crit.pl; - if(warn.rta > crit.rta) warn.rta = crit.rta; - if(warn_down > crit_down) crit_down = warn_down; - if(warn.jitter > crit.jitter) crit.jitter = warn.jitter; - if(warn.mos < crit.mos) warn.mos = crit.mos; - if(warn.score < crit.score) warn.score = crit.score; + if (warn.pl > crit.pl) + warn.pl = crit.pl; + if (warn.rta > crit.rta) + warn.rta = crit.rta; + if (warn_down > crit_down) + crit_down = warn_down; + if (warn.jitter > crit.jitter) + crit.jitter = warn.jitter; + if (warn.mos < crit.mos) + warn.mos = crit.mos; + if (warn.score < crit.score) + warn.score = crit.score; #ifdef HAVE_SIGACTION sig_action.sa_sigaction = NULL; sig_action.sa_handler = finish; sigfillset(&sig_action.sa_mask); - sig_action.sa_flags = SA_NODEFER|SA_RESTART; + sig_action.sa_flags = SA_NODEFER | SA_RESTART; sigaction(SIGINT, &sig_action, NULL); sigaction(SIGHUP, &sig_action, NULL); sigaction(SIGTERM, &sig_action, NULL); sigaction(SIGALRM, &sig_action, NULL); -#else /* HAVE_SIGACTION */ +#else /* HAVE_SIGACTION */ signal(SIGINT, finish); signal(SIGHUP, finish); signal(SIGTERM, finish); signal(SIGALRM, finish); #endif /* HAVE_SIGACTION */ - if(debug) printf("Setting alarm timeout to %u seconds\n", timeout); + if (debug) + printf("Setting alarm timeout to %u seconds\n", timeout); alarm(timeout); /* make sure we don't wait any longer than necessary */ gettimeofday(&prog_start, &tz); - max_completion_time = - ((targets * packets * pkt_interval) + (targets * target_interval)) + - (targets * packets * crit.rta) + crit.rta; + max_completion_time = ((targets * packets * pkt_interval) + (targets * target_interval)) + (targets * packets * crit.rta) + crit.rta; - if(debug) { + if (debug) { printf("packets: %u, targets: %u\n" "target_interval: %0.3f, pkt_interval %0.3f\n" "crit.rta: %0.3f\n" "max_completion_time: %0.3f\n", - packets, targets, - (float)target_interval / 1000, (float)pkt_interval / 1000, - (float)crit.rta / 1000, - (float)max_completion_time / 1000); + packets, targets, (float)target_interval / 1000, (float)pkt_interval / 1000, (float)crit.rta / 1000, (float)max_completion_time / 1000); } - if(debug) { - if(max_completion_time > (u_int)timeout * 1000000) { - printf("max_completion_time: %llu timeout: %u\n", - max_completion_time, timeout); - printf("Timeout must be at least %llu\n", - max_completion_time / 1000000 + 1); + if (debug) { + if (max_completion_time > (u_int)timeout * 1000000) { + printf("max_completion_time: %llu timeout: %u\n", max_completion_time, timeout); + printf("Timeout must be at least %llu\n", max_completion_time / 1000000 + 1); } } - if(debug) { - printf("crit = {%u, %u%%}, warn = {%u, %u%%}\n", - crit.rta, crit.pl, warn.rta, warn.pl); - printf("pkt_interval: %u target_interval: %u retry_interval: %u\n", - pkt_interval, target_interval, retry_interval); - printf("icmp_pkt_size: %u timeout: %u\n", - icmp_pkt_size, timeout); + if (debug) { + printf("crit = {%u, %u%%}, warn = {%u, %u%%}\n", crit.rta, crit.pl, warn.rta, warn.pl); + printf("pkt_interval: %u target_interval: %u retry_interval: %u\n", pkt_interval, target_interval, retry_interval); + printf("icmp_pkt_size: %u timeout: %u\n", icmp_pkt_size, timeout); } - if(packets > 20) { + if (packets > 20) { errno = 0; crash("packets is > 20 (%d)", packets); } - if(min_hosts_alive < -1) { + if (min_hosts_alive < -1) { errno = 0; crash("minimum alive hosts is negative (%i)", min_hosts_alive); } host = list; table = malloc(sizeof(struct rta_host *) * targets); - if(!table) { + if (!table) { crash("main(): malloc failed for host table"); } i = 0; - while(host) { - host->id = i*packets; + while (host) { + host->id = i * packets; table[i] = host; host = host->next; i++; @@ -822,25 +842,24 @@ main(int argc, char **argv) errno = 0; finish(0); - return(0); + return (0); } -static void -run_checks() -{ +static void run_checks() { u_int i, t; u_int final_wait, time_passed; /* this loop might actually violate the pkt_interval or target_interval * settings, but only if there aren't any packets on the wire which * indicates that the target can handle an increased packet rate */ - for(i = 0; i < packets; i++) { - for(t = 0; t < targets; t++) { + for (i = 0; i < packets; i++) { + for (t = 0; t < targets; t++) { /* don't send useless packets */ - if(!targets_alive) finish(0); - if(table[t]->flags & FLAG_LOST_CAUSE) { - if(debug) printf("%s is a lost cause. not sending any more\n", - table[t]->name); + if (!targets_alive) + finish(0); + if (table[t]->flags & FLAG_LOST_CAUSE) { + if (debug) + printf("%s is a lost cause. not sending any more\n", table[t]->name); continue; } @@ -851,28 +870,27 @@ run_checks() wait_for_reply(icmp_sock, pkt_interval * targets); } - if(icmp_pkts_en_route && targets_alive) { + if (icmp_pkts_en_route && targets_alive) { time_passed = get_timevaldiff(NULL, NULL); final_wait = max_completion_time - time_passed; - if(debug) { - printf("time_passed: %u final_wait: %u max_completion_time: %llu\n", - time_passed, final_wait, max_completion_time); + if (debug) { + printf("time_passed: %u final_wait: %u max_completion_time: %llu\n", time_passed, final_wait, max_completion_time); } - if(time_passed > max_completion_time) { - if(debug) printf("Time passed. Finishing up\n"); + if (time_passed > max_completion_time) { + if (debug) + printf("Time passed. Finishing up\n"); finish(0); } /* catch the packets that might come in within the timeframe, but * haven't yet */ - if(debug) printf("Waiting for %u micro-seconds (%0.3f msecs)\n", - final_wait, (float)final_wait / 1000); + if (debug) + printf("Waiting for %u micro-seconds (%0.3f msecs)\n", final_wait, (float)final_wait / 1000); wait_for_reply(icmp_sock, final_wait); } } - /* response structure: * IPv4: * ip header : 20 bytes @@ -883,9 +901,7 @@ run_checks() * both: * icmp echo reply : the rest */ -static int -wait_for_reply(int sock, u_int t) -{ +static int wait_for_reply(int sock, u_int t) { int n, hlen; static unsigned char buf[65536]; struct sockaddr_storage resp_addr; @@ -898,15 +914,14 @@ wait_for_reply(int sock, u_int t) double jitter_tmp; if (!(packet.buf = malloc(icmp_pkt_size))) { - crash("send_icmp_ping(): failed to malloc %d bytes for send buffer", - icmp_pkt_size); - return -1; /* might be reached if we're in debug mode */ + crash("send_icmp_ping(): failed to malloc %d bytes for send buffer", icmp_pkt_size); + return -1; /* might be reached if we're in debug mode */ } memset(packet.buf, 0, icmp_pkt_size); /* if we can't listen or don't have anything to listen to, just return */ - if(!t || !icmp_pkts_en_route) { + if (!t || !icmp_pkts_en_route) { free(packet.buf); return 0; } @@ -915,29 +930,25 @@ wait_for_reply(int sock, u_int t) i = t; per_pkt_wait = t / icmp_pkts_en_route; - while(icmp_pkts_en_route && get_timevaldiff(&wait_start, NULL) < i) { + while (icmp_pkts_en_route && get_timevaldiff(&wait_start, NULL) < i) { t = per_pkt_wait; /* wrap up if all targets are declared dead */ - if(!targets_alive || - get_timevaldiff(&prog_start, NULL) >= max_completion_time || - (mode == MODE_HOSTCHECK && targets_down)) - { + if (!targets_alive || get_timevaldiff(&prog_start, NULL) >= max_completion_time || (mode == MODE_HOSTCHECK && targets_down)) { finish(0); } /* reap responses until we hit a timeout */ - n = recvfrom_wto(sock, buf, sizeof(buf), - (struct sockaddr *)&resp_addr, &t, &now); - if(!n) { - if(debug > 1) { - printf("recvfrom_wto() timed out during a %u usecs wait\n", - per_pkt_wait); + n = recvfrom_wto(sock, buf, sizeof(buf), (struct sockaddr *)&resp_addr, &t, &now); + if (!n) { + if (debug > 1) { + printf("recvfrom_wto() timed out during a %u usecs wait\n", per_pkt_wait); } - continue; /* timeout for this one, so keep trying */ + continue; /* timeout for this one, so keep trying */ } - if(n < 0) { - if(debug) printf("recvfrom_wto() returned errors\n"); + if (n < 0) { + if (debug) + printf("recvfrom_wto() returned errors\n"); free(packet.buf); return n; } @@ -946,31 +957,27 @@ wait_for_reply(int sock, u_int t) if (address_family != AF_INET6) { ip = (union ip_hdr *)buf; - if(debug > 1) { + if (debug > 1) { char address[INET6_ADDRSTRLEN]; parse_address(&resp_addr, address, sizeof(address)); - printf("received %u bytes from %s\n", - address_family == AF_INET6 ? ntohs(ip->ip6.ip6_plen) - : ntohs(ip->ip.ip_len), - address); + printf("received %u bytes from %s\n", address_family == AF_INET6 ? ntohs(ip->ip6.ip6_plen) : ntohs(ip->ip.ip_len), address); } } -/* obsolete. alpha on tru64 provides the necessary defines, but isn't broken */ -/* #if defined( __alpha__ ) && __STDC__ && !defined( __GLIBC__ ) */ + /* obsolete. alpha on tru64 provides the necessary defines, but isn't broken */ + /* #if defined( __alpha__ ) && __STDC__ && !defined( __GLIBC__ ) */ /* alpha headers are decidedly broken. Using an ansi compiler, * they provide ip_vhl instead of ip_hl and ip_v, so we mask * off the bottom 4 bits */ -/* hlen = (ip->ip_vhl & 0x0f) << 2; */ -/* #else */ + /* hlen = (ip->ip_vhl & 0x0f) << 2; */ + /* #else */ hlen = (address_family == AF_INET6) ? 0 : ip->ip.ip_hl << 2; -/* #endif */ + /* #endif */ - if(n < (hlen + ICMP_MINLEN)) { + if (n < (hlen + ICMP_MINLEN)) { char address[INET6_ADDRSTRLEN]; parse_address(&resp_addr, address, sizeof(address)); - crash("received packet too short for ICMP (%d bytes, expected %d) from %s\n", - n, hlen + icmp_pkt_size, address); + crash("received packet too short for ICMP (%d bytes, expected %d) from %s\n", n, hlen + icmp_pkt_size, address); } /* else if(debug) { */ /* printf("ip header size: %u, packet size: %u (expected %u, %u)\n", */ @@ -981,16 +988,14 @@ wait_for_reply(int sock, u_int t) /* check the response */ memcpy(packet.buf, buf + hlen, icmp_pkt_size); -/* address_family == AF_INET6 ? sizeof(struct icmp6_hdr) - : sizeof(struct icmp));*/ - - if( (address_family == PF_INET && - (ntohs(packet.icp->icmp_id) != pid || packet.icp->icmp_type != ICMP_ECHOREPLY - || ntohs(packet.icp->icmp_seq) >= targets * packets)) - || (address_family == PF_INET6 && - (ntohs(packet.icp6->icmp6_id) != pid || packet.icp6->icmp6_type != ICMP6_ECHO_REPLY - || ntohs(packet.icp6->icmp6_seq) >= targets * packets))) { - if(debug > 2) printf("not a proper ICMP_ECHOREPLY\n"); + /* address_family == AF_INET6 ? sizeof(struct icmp6_hdr) + : sizeof(struct icmp));*/ + + if ((address_family == PF_INET && (ntohs(packet.icp->icmp_id) != pid || packet.icp->icmp_type != ICMP_ECHOREPLY || ntohs(packet.icp->icmp_seq) >= targets * packets)) || + (address_family == PF_INET6 && + (ntohs(packet.icp6->icmp6_id) != pid || packet.icp6->icmp6_type != ICMP6_ECHO_REPLY || ntohs(packet.icp6->icmp6_seq) >= targets * packets))) { + if (debug > 2) + printf("not a proper ICMP_ECHOREPLY\n"); handle_random_icmp(buf + hlen, &resp_addr); continue; } @@ -999,22 +1004,20 @@ wait_for_reply(int sock, u_int t) if (address_family == PF_INET) { memcpy(&data, packet.icp->icmp_data, sizeof(data)); if (debug > 2) - printf("ICMP echo-reply of len %lu, id %u, seq %u, cksum 0x%X\n", - (unsigned long)sizeof(data), ntohs(packet.icp->icmp_id), - ntohs(packet.icp->icmp_seq), packet.icp->icmp_cksum); - host = table[ntohs(packet.icp->icmp_seq)/packets]; + printf("ICMP echo-reply of len %lu, id %u, seq %u, cksum 0x%X\n", (unsigned long)sizeof(data), ntohs(packet.icp->icmp_id), ntohs(packet.icp->icmp_seq), + packet.icp->icmp_cksum); + host = table[ntohs(packet.icp->icmp_seq) / packets]; } else { memcpy(&data, &packet.icp6->icmp6_dataun.icmp6_un_data8[4], sizeof(data)); if (debug > 2) - printf("ICMP echo-reply of len %lu, id %u, seq %u, cksum 0x%X\n", - (unsigned long)sizeof(data), ntohs(packet.icp6->icmp6_id), - ntohs(packet.icp6->icmp6_seq), packet.icp6->icmp6_cksum); - host = table[ntohs(packet.icp6->icmp6_seq)/packets]; + printf("ICMP echo-reply of len %lu, id %u, seq %u, cksum 0x%X\n", (unsigned long)sizeof(data), ntohs(packet.icp6->icmp6_id), ntohs(packet.icp6->icmp6_seq), + packet.icp6->icmp6_cksum); + host = table[ntohs(packet.icp6->icmp6_seq) / packets]; } tdiff = get_timevaldiff(&data.stime, &now); - if (host->last_tdiff>0) { + if (host->last_tdiff > 0) { /* Calculate jitter */ if (host->last_tdiff > tdiff) { jitter_tmp = host->last_tdiff - tdiff; @@ -1022,29 +1025,29 @@ wait_for_reply(int sock, u_int t) jitter_tmp = tdiff - host->last_tdiff; } - if (host->jitter==0) { - host->jitter=jitter_tmp; - host->jitter_max=jitter_tmp; - host->jitter_min=jitter_tmp; + if (host->jitter == 0) { + host->jitter = jitter_tmp; + host->jitter_max = jitter_tmp; + host->jitter_min = jitter_tmp; } else { - host->jitter+=jitter_tmp; + host->jitter += jitter_tmp; if (jitter_tmp < host->jitter_min) { - host->jitter_min=jitter_tmp; + host->jitter_min = jitter_tmp; } if (jitter_tmp > host->jitter_max) { - host->jitter_max=jitter_tmp; + host->jitter_max = jitter_tmp; } } /* Check if packets in order */ if (host->last_icmp_seq >= packet.icp->icmp_seq) - host->order_status=STATE_CRITICAL; + host->order_status = STATE_CRITICAL; } - host->last_tdiff=tdiff; + host->last_tdiff = tdiff; - host->last_icmp_seq=packet.icp->icmp_seq; + host->last_icmp_seq = packet.icp->icmp_seq; host->time_waited += tdiff; host->icmp_recv++; @@ -1054,39 +1057,27 @@ wait_for_reply(int sock, u_int t) if (tdiff < (unsigned int)host->rtmin) host->rtmin = tdiff; - if(debug) { + if (debug) { char address[INET6_ADDRSTRLEN]; parse_address(&resp_addr, address, sizeof(address)); - switch(address_family) { - case AF_INET: { - printf("%0.3f ms rtt from %s, outgoing ttl: %u, incoming ttl: %u, max: %0.3f, min: %0.3f\n", - (float)tdiff / 1000, - address, - ttl, - ip->ip.ip_ttl, - (float)host->rtmax / 1000, - (float)host->rtmin / 1000); - break; - }; - case AF_INET6: { - printf("%0.3f ms rtt from %s, outgoing ttl: %u, max: %0.3f, min: %0.3f\n", - (float)tdiff / 1000, - address, - ttl, - (float)host->rtmax / 1000, - (float)host->rtmin / 1000); - }; - } + switch (address_family) { + case AF_INET: { + printf("%0.3f ms rtt from %s, outgoing ttl: %u, incoming ttl: %u, max: %0.3f, min: %0.3f\n", (float)tdiff / 1000, address, ttl, ip->ip.ip_ttl, + (float)host->rtmax / 1000, (float)host->rtmin / 1000); + break; + }; + case AF_INET6: { + printf("%0.3f ms rtt from %s, outgoing ttl: %u, max: %0.3f, min: %0.3f\n", (float)tdiff / 1000, address, ttl, (float)host->rtmax / 1000, (float)host->rtmin / 1000); + }; + } } /* if we're in hostcheck mode, exit with limited printouts */ - if(mode == MODE_HOSTCHECK) { + if (mode == MODE_HOSTCHECK) { printf("OK - %s responds to ICMP. Packet %u, rta %0.3fms|" - "pkt=%u;;;0;%u rta=%0.3f;%0.3f;%0.3f;;\n", - host->name, icmp_recv, (float)tdiff / 1000, - icmp_recv, packets, (float)tdiff / 1000, - (float)warn.rta / 1000, (float)crit.rta / 1000); + "pkt=%u;;;0;%u rta=%0.3f;%0.3f;%0.3f;;\n", + host->name, icmp_recv, (float)tdiff / 1000, icmp_recv, packets, (float)tdiff / 1000, (float)warn.rta / 1000, (float)crit.rta / 1000); exit(STATE_OK); } } @@ -1096,9 +1087,7 @@ wait_for_reply(int sock, u_int t) } /* the ping functions */ -static int -send_icmp_ping(int sock, struct rta_host *host) -{ +static int send_icmp_ping(int sock, struct rta_host *host) { long int len; size_t addrlen; struct icmp_ping_data data; @@ -1107,22 +1096,21 @@ send_icmp_ping(int sock, struct rta_host *host) struct timeval tv; void *buf = NULL; - if(sock == -1) { + if (sock == -1) { errno = 0; crash("Attempt to send on bogus socket"); return -1; } - if(!buf) { + if (!buf) { if (!(buf = malloc(icmp_pkt_size))) { - crash("send_icmp_ping(): failed to malloc %d bytes for send buffer", - icmp_pkt_size); - return -1; /* might be reached if we're in debug mode */ + crash("send_icmp_ping(): failed to malloc %d bytes for send buffer", icmp_pkt_size); + return -1; /* might be reached if we're in debug mode */ } } memset(buf, 0, icmp_pkt_size); - if((gettimeofday(&tv, &tz)) == -1) { + if ((gettimeofday(&tv, &tz)) == -1) { free(buf); return -1; } @@ -1131,7 +1119,7 @@ send_icmp_ping(int sock, struct rta_host *host) memcpy(&data.stime, &tv, sizeof(tv)); if (address_family == AF_INET) { - struct icmp *icp = (struct icmp*)buf; + struct icmp *icp = (struct icmp *)buf; addrlen = sizeof(struct sockaddr_in); memcpy(&icp->icmp_data, &data, sizeof(data)); @@ -1141,14 +1129,13 @@ send_icmp_ping(int sock, struct rta_host *host) icp->icmp_cksum = 0; icp->icmp_id = htons(pid); icp->icmp_seq = htons(host->id++); - icp->icmp_cksum = icmp_checksum((uint16_t*)buf, (size_t)icmp_pkt_size); + icp->icmp_cksum = icmp_checksum((uint16_t *)buf, (size_t)icmp_pkt_size); if (debug > 2) - printf("Sending ICMP echo-request of len %lu, id %u, seq %u, cksum 0x%X to host %s\n", - (unsigned long)sizeof(data), ntohs(icp->icmp_id), ntohs(icp->icmp_seq), icp->icmp_cksum, host->name); - } - else { - struct icmp6_hdr *icp6 = (struct icmp6_hdr*)buf; + printf("Sending ICMP echo-request of len %lu, id %u, seq %u, cksum 0x%X to host %s\n", (unsigned long)sizeof(data), ntohs(icp->icmp_id), ntohs(icp->icmp_seq), + icp->icmp_cksum, host->name); + } else { + struct icmp6_hdr *icp6 = (struct icmp6_hdr *)buf; addrlen = sizeof(struct sockaddr_in6); memcpy(&icp6->icmp6_dataun.icmp6_un_data8[4], &data, sizeof(data)); @@ -1161,9 +1148,8 @@ send_icmp_ping(int sock, struct rta_host *host) // let checksum be calculated automatically if (debug > 2) { - printf("Sending ICMP echo-request of len %lu, id %u, seq %u, cksum 0x%X to host %s\n", - (unsigned long)sizeof(data), ntohs(icp6->icmp6_id), - ntohs(icp6->icmp6_seq), icp6->icmp6_cksum, host->name); + printf("Sending ICMP echo-request of len %lu, id %u, seq %u, cksum 0x%X to host %s\n", (unsigned long)sizeof(data), ntohs(icp6->icmp6_id), ntohs(icp6->icmp6_seq), + icp6->icmp6_cksum, host->name); } } @@ -1188,8 +1174,8 @@ send_icmp_ping(int sock, struct rta_host *host) free(buf); - if(len < 0 || (unsigned int)len != icmp_pkt_size) { - if(debug) { + if (len < 0 || (unsigned int)len != icmp_pkt_size) { + if (debug) { char address[INET6_ADDRSTRLEN]; parse_address((struct sockaddr_storage *)&host->saddr_in, address, sizeof(address)); printf("Failed to send ping to %s: %s\n", address, strerror(errno)); @@ -1204,10 +1190,7 @@ send_icmp_ping(int sock, struct rta_host *host) return 0; } -static int -recvfrom_wto(int sock, void *buf, unsigned int len, struct sockaddr *saddr, - u_int *timo, struct timeval* tv) -{ +static int recvfrom_wto(int sock, void *buf, unsigned int len, struct sockaddr *saddr, u_int *timo, struct timeval *tv) { u_int slen; int n, ret; struct timeval to, then, now; @@ -1218,11 +1201,12 @@ recvfrom_wto(int sock, void *buf, unsigned int len, struct sockaddr *saddr, struct msghdr hdr; struct iovec iov; #ifdef SO_TIMESTAMP - struct cmsghdr* chdr; + struct cmsghdr *chdr; #endif - if(!*timo) { - if(debug) printf("*timo is not\n"); + if (!*timo) { + if (debug) + printf("*timo is not\n"); return 0; } @@ -1235,11 +1219,13 @@ recvfrom_wto(int sock, void *buf, unsigned int len, struct sockaddr *saddr, errno = 0; gettimeofday(&then, &tz); n = select(sock + 1, &rd, &wr, NULL, &to); - if(n < 0) crash("select() in recvfrom_wto"); + if (n < 0) + crash("select() in recvfrom_wto"); gettimeofday(&now, &tz); *timo = get_timevaldiff(&then, &now); - if(!n) return 0; /* timeout */ + if (!n) + return 0; /* timeout */ slen = sizeof(struct sockaddr_storage); @@ -1259,12 +1245,10 @@ recvfrom_wto(int sock, void *buf, unsigned int len, struct sockaddr *saddr, ret = recvmsg(sock, &hdr, 0); #ifdef SO_TIMESTAMP - for(chdr = CMSG_FIRSTHDR(&hdr); chdr; chdr = CMSG_NXTHDR(&hdr, chdr)) { - if(chdr->cmsg_level == SOL_SOCKET - && chdr->cmsg_type == SO_TIMESTAMP - && chdr->cmsg_len >= CMSG_LEN(sizeof(struct timeval))) { + for (chdr = CMSG_FIRSTHDR(&hdr); chdr; chdr = CMSG_NXTHDR(&hdr, chdr)) { + if (chdr->cmsg_level == SOL_SOCKET && chdr->cmsg_type == SO_TIMESTAMP && chdr->cmsg_len >= CMSG_LEN(sizeof(struct timeval))) { memcpy(tv, CMSG_DATA(chdr), sizeof(*tv)); - break ; + break; } } @@ -1274,54 +1258,55 @@ recvfrom_wto(int sock, void *buf, unsigned int len, struct sockaddr *saddr, return (ret); } -static void -finish(int sig) -{ +static void finish(int sig) { u_int i = 0; unsigned char pl; double rta; struct rta_host *host; - const char *status_string[] = - {"OK", "WARNING", "CRITICAL", "UNKNOWN", "DEPENDENT"}; + const char *status_string[] = {"OK", "WARNING", "CRITICAL", "UNKNOWN", "DEPENDENT"}; int hosts_ok = 0; int hosts_warn = 0; int this_status; double R; alarm(0); - if(debug > 1) printf("finish(%d) called\n", sig); - - if(icmp_sock != -1) close(icmp_sock); - if(udp_sock != -1) close(udp_sock); - if(tcp_sock != -1) close(tcp_sock); - - if(debug) { - printf("icmp_sent: %u icmp_recv: %u icmp_lost: %u\n", - icmp_sent, icmp_recv, icmp_lost); + if (debug > 1) + printf("finish(%d) called\n", sig); + + if (icmp_sock != -1) + close(icmp_sock); + if (udp_sock != -1) + close(udp_sock); + if (tcp_sock != -1) + close(tcp_sock); + + if (debug) { + printf("icmp_sent: %u icmp_recv: %u icmp_lost: %u\n", icmp_sent, icmp_recv, icmp_lost); printf("targets: %u targets_alive: %u\n", targets, targets_alive); } /* iterate thrice to calculate values, give output, and print perfparse */ - status=STATE_OK; + status = STATE_OK; host = list; - while(host) { + while (host) { this_status = STATE_OK; - if(!host->icmp_recv) { + if (!host->icmp_recv) { /* rta 0 is ofcourse not entirely correct, but will still show up * conspicuously as missing entries in perfparse and cacti */ pl = 100; rta = 0; status = STATE_CRITICAL; /* up the down counter if not already counted */ - if(!(host->flags & FLAG_LOST_CAUSE) && targets_alive) targets_down++; + if (!(host->flags & FLAG_LOST_CAUSE) && targets_alive) + targets_down++; } else { pl = ((host->icmp_sent - host->icmp_recv) * 100) / host->icmp_sent; rta = (double)host->time_waited / host->icmp_recv; } - if (host->icmp_recv>1) { + if (host->icmp_recv > 1) { /* * This algorithm is probably pretty much blindly copied from * locations like this one: https://www.slac.stanford.edu/comp/net/wan-mon/tutorial.html#mos @@ -1336,19 +1321,19 @@ finish(int sig) * More links: * - https://confluence.slac.stanford.edu/display/IEPM/MOS */ - host->jitter=(host->jitter / (host->icmp_recv - 1)/1000); + host->jitter = (host->jitter / (host->icmp_recv - 1) / 1000); /* * Take the average round trip latency (in milliseconds), add * round trip jitter, but double the impact to latency * then add 10 for protocol latencies (in milliseconds). */ - host->EffectiveLatency = (rta/1000) + host->jitter * 2 + 10; + host->EffectiveLatency = (rta / 1000) + host->jitter * 2 + 10; if (host->EffectiveLatency < 160) { - R = 93.2 - (host->EffectiveLatency / 40); + R = 93.2 - (host->EffectiveLatency / 40); } else { - R = 93.2 - ((host->EffectiveLatency - 120) / 10); + R = 93.2 - ((host->EffectiveLatency - 120) / 10); } // Now, let us deduct 2.5 R values per percentage of packet loss (i.e. a @@ -1360,12 +1345,12 @@ finish(int sig) } host->score = R; - host->mos= 1 + ((0.035) * R) + ((.000007) * R * (R-60) * (100-R)); + host->mos = 1 + ((0.035) * R) + ((.000007) * R * (R - 60) * (100 - R)); } else { - host->jitter=0; - host->jitter_min=0; - host->jitter_max=0; - host->mos=0; + host->jitter = 0; + host->jitter_min = 0; + host->jitter_max = 0; + host->mos = 0; } host->pl = pl; @@ -1379,62 +1364,62 @@ finish(int sig) /* Check which mode is on and do the warn / Crit stuff */ if (rta_mode) { - if(rta >= crit.rta) { + if (rta >= crit.rta) { this_status = STATE_CRITICAL; status = STATE_CRITICAL; - host->rta_status=STATE_CRITICAL; - } else if(status!=STATE_CRITICAL && (rta >= warn.rta)) { + host->rta_status = STATE_CRITICAL; + } else if (status != STATE_CRITICAL && (rta >= warn.rta)) { this_status = (this_status <= STATE_WARNING ? STATE_WARNING : this_status); status = STATE_WARNING; - host->rta_status=STATE_WARNING; + host->rta_status = STATE_WARNING; } } if (pl_mode) { - if(pl >= crit.pl) { + if (pl >= crit.pl) { this_status = STATE_CRITICAL; status = STATE_CRITICAL; - host->pl_status=STATE_CRITICAL; - } else if(status!=STATE_CRITICAL && (pl >= warn.pl)) { + host->pl_status = STATE_CRITICAL; + } else if (status != STATE_CRITICAL && (pl >= warn.pl)) { this_status = (this_status <= STATE_WARNING ? STATE_WARNING : this_status); status = STATE_WARNING; - host->pl_status=STATE_WARNING; + host->pl_status = STATE_WARNING; } } if (jitter_mode) { - if(host->jitter >= crit.jitter) { + if (host->jitter >= crit.jitter) { this_status = STATE_CRITICAL; status = STATE_CRITICAL; - host->jitter_status=STATE_CRITICAL; - } else if(status!=STATE_CRITICAL && (host->jitter >= warn.jitter)) { + host->jitter_status = STATE_CRITICAL; + } else if (status != STATE_CRITICAL && (host->jitter >= warn.jitter)) { this_status = (this_status <= STATE_WARNING ? STATE_WARNING : this_status); status = STATE_WARNING; - host->jitter_status=STATE_WARNING; + host->jitter_status = STATE_WARNING; } } if (mos_mode) { - if(host->mos <= crit.mos) { + if (host->mos <= crit.mos) { this_status = STATE_CRITICAL; status = STATE_CRITICAL; - host->mos_status=STATE_CRITICAL; - } else if(status!=STATE_CRITICAL && (host->mos <= warn.mos)) { + host->mos_status = STATE_CRITICAL; + } else if (status != STATE_CRITICAL && (host->mos <= warn.mos)) { this_status = (this_status <= STATE_WARNING ? STATE_WARNING : this_status); status = STATE_WARNING; - host->mos_status=STATE_WARNING; + host->mos_status = STATE_WARNING; } } if (score_mode) { - if(host->score <= crit.score) { + if (host->score <= crit.score) { this_status = STATE_CRITICAL; status = STATE_CRITICAL; - host->score_status=STATE_CRITICAL; - } else if(status!=STATE_CRITICAL && (host->score <= warn.score)) { + host->score_status = STATE_CRITICAL; + } else if (status != STATE_CRITICAL && (host->score <= warn.score)) { this_status = (this_status <= STATE_WARNING ? STATE_WARNING : this_status); status = STATE_WARNING; - host->score_status=STATE_WARNING; + host->score_status = STATE_WARNING; } } @@ -1447,91 +1432,92 @@ finish(int sig) host = host->next; } - /* this is inevitable */ - if(!targets_alive) status = STATE_CRITICAL; - if(min_hosts_alive > -1) { - if(hosts_ok >= min_hosts_alive) status = STATE_OK; - else if((hosts_ok + hosts_warn) >= min_hosts_alive) status = STATE_WARNING; + if (!targets_alive) + status = STATE_CRITICAL; + if (min_hosts_alive > -1) { + if (hosts_ok >= min_hosts_alive) + status = STATE_OK; + else if ((hosts_ok + hosts_warn) >= min_hosts_alive) + status = STATE_WARNING; } printf("%s - ", status_string[status]); host = list; - while(host) { - - if(debug) puts(""); - if(i) { - if(i < targets) printf(" :: "); - else printf("\n"); + while (host) { + + if (debug) + puts(""); + if (i) { + if (i < targets) + printf(" :: "); + else + printf("\n"); } i++; - if(!host->icmp_recv) { + if (!host->icmp_recv) { status = STATE_CRITICAL; - host->rtmin=0; - host->jitter_min=0; - if(host->flags & FLAG_LOST_CAUSE) { + host->rtmin = 0; + host->jitter_min = 0; + if (host->flags & FLAG_LOST_CAUSE) { char address[INET6_ADDRSTRLEN]; parse_address(&host->error_addr, address, sizeof(address)); - printf("%s: %s @ %s. rta nan, lost %d%%", - host->name, - get_icmp_error_msg(host->icmp_type, host->icmp_code), - address, - 100); + printf("%s: %s @ %s. rta nan, lost %d%%", host->name, get_icmp_error_msg(host->icmp_type, host->icmp_code), address, 100); } else { /* not marked as lost cause, so we have no flags for it */ printf("%s: rta nan, lost 100%%", host->name); } - } else { /* !icmp_recv */ + } else { /* !icmp_recv */ printf("%s", host->name); /* rta text output */ if (rta_mode) { if (status == STATE_OK) printf(" rta %0.3fms", host->rta / 1000); - else if (status==STATE_WARNING && host->rta_status==status) - printf(" rta %0.3fms > %0.3fms", (float)host->rta / 1000, (float)warn.rta/1000); - else if (status==STATE_CRITICAL && host->rta_status==status) - printf(" rta %0.3fms > %0.3fms", (float)host->rta / 1000, (float)crit.rta/1000); + else if (status == STATE_WARNING && host->rta_status == status) + printf(" rta %0.3fms > %0.3fms", (float)host->rta / 1000, (float)warn.rta / 1000); + else if (status == STATE_CRITICAL && host->rta_status == status) + printf(" rta %0.3fms > %0.3fms", (float)host->rta / 1000, (float)crit.rta / 1000); } /* pl text output */ if (pl_mode) { if (status == STATE_OK) printf(" lost %u%%", host->pl); - else if (status==STATE_WARNING && host->pl_status==status) + else if (status == STATE_WARNING && host->pl_status == status) printf(" lost %u%% > %u%%", host->pl, warn.pl); - else if (status==STATE_CRITICAL && host->pl_status==status) + else if (status == STATE_CRITICAL && host->pl_status == status) printf(" lost %u%% > %u%%", host->pl, crit.pl); } /* jitter text output */ if (jitter_mode) { if (status == STATE_OK) printf(" jitter %0.3fms", (float)host->jitter); - else if (status==STATE_WARNING && host->jitter_status==status) + else if (status == STATE_WARNING && host->jitter_status == status) printf(" jitter %0.3fms > %0.3fms", (float)host->jitter, warn.jitter); - else if (status==STATE_CRITICAL && host->jitter_status==status) + else if (status == STATE_CRITICAL && host->jitter_status == status) printf(" jitter %0.3fms > %0.3fms", (float)host->jitter, crit.jitter); } /* mos text output */ if (mos_mode) { if (status == STATE_OK) printf(" MOS %0.1f", (float)host->mos); - else if (status==STATE_WARNING && host->mos_status==status) + else if (status == STATE_WARNING && host->mos_status == status) printf(" MOS %0.1f < %0.1f", (float)host->mos, (float)warn.mos); - else if (status==STATE_CRITICAL && host->mos_status==status) + else if (status == STATE_CRITICAL && host->mos_status == status) printf(" MOS %0.1f < %0.1f", (float)host->mos, (float)crit.mos); } /* score text output */ if (score_mode) { if (status == STATE_OK) printf(" Score %u", (int)host->score); - else if (status==STATE_WARNING && host->score_status==status ) + else if (status == STATE_WARNING && host->score_status == status) printf(" Score %u < %u", (int)host->score, (int)warn.score); - else if (status==STATE_CRITICAL && host->score_status==status ) + else if (status == STATE_CRITICAL && host->score_status == status) printf(" Score %u < %u", (int)host->score, (int)crit.score); } /* order statis text output */ if (order_mode) { if (status == STATE_OK) printf(" Packets in order"); - else if (status==STATE_CRITICAL && host->order_status==status) + else if (status == STATE_CRITICAL && host->order_status == status) printf(" Packets out of order"); } } @@ -1540,25 +1526,21 @@ finish(int sig) /* iterate once more for pretty perfparse output */ if (!(!rta_mode && !pl_mode && !jitter_mode && !score_mode && !mos_mode && order_mode)) { - printf("|"); + printf("|"); } i = 0; host = list; - while(host) { - if(debug) puts(""); + while (host) { + if (debug) + puts(""); if (rta_mode) { - if (host->pl<100) { - printf("%srta=%0.3fms;%0.3f;%0.3f;0; %srtmax=%0.3fms;;;; %srtmin=%0.3fms;;;; ", - (targets > 1) ? host->name : "", - host->rta / 1000, (float)warn.rta / 1000, (float)crit.rta / 1000, - (targets > 1) ? host->name : "", (float)host->rtmax / 1000, - (targets > 1) ? host->name : "", (host->rtmin < INFINITY) ? (float)host->rtmin / 1000 : (float)0); + if (host->pl < 100) { + printf("%srta=%0.3fms;%0.3f;%0.3f;0; %srtmax=%0.3fms;;;; %srtmin=%0.3fms;;;; ", (targets > 1) ? host->name : "", host->rta / 1000, (float)warn.rta / 1000, + (float)crit.rta / 1000, (targets > 1) ? host->name : "", (float)host->rtmax / 1000, (targets > 1) ? host->name : "", + (host->rtmin < INFINITY) ? (float)host->rtmin / 1000 : (float)0); } else { - printf("%srta=U;;;; %srtmax=U;;;; %srtmin=U;;;; ", - (targets > 1) ? host->name : "", - (targets > 1) ? host->name : "", - (targets > 1) ? host->name : ""); + printf("%srta=U;;;; %srtmax=U;;;; %srtmin=U;;;; ", (targets > 1) ? host->name : "", (targets > 1) ? host->name : "", (targets > 1) ? host->name : ""); } } @@ -1567,43 +1549,27 @@ finish(int sig) } if (jitter_mode) { - if (host->pl<100) { - printf("%sjitter_avg=%0.3fms;%0.3f;%0.3f;0; %sjitter_max=%0.3fms;;;; %sjitter_min=%0.3fms;;;; ", - (targets > 1) ? host->name : "", - (float)host->jitter, - (float)warn.jitter, - (float)crit.jitter, - (targets > 1) ? host->name : "", - (float)host->jitter_max / 1000, (targets > 1) ? host->name : "", - (float)host->jitter_min / 1000 - ); + if (host->pl < 100) { + printf("%sjitter_avg=%0.3fms;%0.3f;%0.3f;0; %sjitter_max=%0.3fms;;;; %sjitter_min=%0.3fms;;;; ", (targets > 1) ? host->name : "", (float)host->jitter, + (float)warn.jitter, (float)crit.jitter, (targets > 1) ? host->name : "", (float)host->jitter_max / 1000, (targets > 1) ? host->name : "", + (float)host->jitter_min / 1000); } else { - printf("%sjitter_avg=U;;;; %sjitter_max=U;;;; %sjitter_min=U;;;; ", - (targets > 1) ? host->name : "", - (targets > 1) ? host->name : "", - (targets > 1) ? host->name : ""); + printf("%sjitter_avg=U;;;; %sjitter_max=U;;;; %sjitter_min=U;;;; ", (targets > 1) ? host->name : "", (targets > 1) ? host->name : "", + (targets > 1) ? host->name : ""); } } if (mos_mode) { - if (host->pl<100) { - printf("%smos=%0.1f;%0.1f;%0.1f;0;5 ", - (targets > 1) ? host->name : "", - (float)host->mos, - (float)warn.mos, - (float)crit.mos); + if (host->pl < 100) { + printf("%smos=%0.1f;%0.1f;%0.1f;0;5 ", (targets > 1) ? host->name : "", (float)host->mos, (float)warn.mos, (float)crit.mos); } else { printf("%smos=U;;;; ", (targets > 1) ? host->name : ""); } } if (score_mode) { - if (host->pl<100) { - printf("%sscore=%u;%u;%u;0;100 ", - (targets > 1) ? host->name : "", - (int)host->score, - (int)warn.score, - (int)crit.score); + if (host->pl < 100) { + printf("%sscore=%u;%u;%u;0;100 ", (targets > 1) ? host->name : "", (int)host->score, (int)warn.score, (int)crit.score); } else { printf("%sscore=U;;;; ", (targets > 1) ? host->name : ""); } @@ -1612,35 +1578,34 @@ finish(int sig) host = host->next; } - if(min_hosts_alive > -1) { - if(hosts_ok >= min_hosts_alive) status = STATE_OK; - else if((hosts_ok + hosts_warn) >= min_hosts_alive) status = STATE_WARNING; + if (min_hosts_alive > -1) { + if (hosts_ok >= min_hosts_alive) + status = STATE_OK; + else if ((hosts_ok + hosts_warn) >= min_hosts_alive) + status = STATE_WARNING; } /* finish with an empty line */ puts(""); - if(debug) printf("targets: %u, targets_alive: %u, hosts_ok: %u, hosts_warn: %u, min_hosts_alive: %i\n", - targets, targets_alive, hosts_ok, hosts_warn, min_hosts_alive); + if (debug) + printf("targets: %u, targets_alive: %u, hosts_ok: %u, hosts_warn: %u, min_hosts_alive: %i\n", targets, targets_alive, hosts_ok, hosts_warn, min_hosts_alive); exit(status); } -static u_int -get_timevaldiff(struct timeval *early, struct timeval *later) -{ +static u_int get_timevaldiff(struct timeval *early, struct timeval *later) { u_int ret; struct timeval now; - if(!later) { + if (!later) { gettimeofday(&now, &tz); later = &now; } - if(!early) early = &prog_start; + if (!early) + early = &prog_start; /* if early > later we return 0 so as to indicate a timeout */ - if(early->tv_sec > later->tv_sec || - (early->tv_sec == later->tv_sec && early->tv_usec > later->tv_usec)) - { + if (early->tv_sec > later->tv_sec || (early->tv_sec == later->tv_sec && early->tv_usec > later->tv_usec)) { return 0; } ret = (later->tv_sec - early->tv_sec) * 1000000; @@ -1649,9 +1614,7 @@ get_timevaldiff(struct timeval *early, struct timeval *later) return ret; } -static int -add_target_ip(char *arg, struct sockaddr_storage *in) -{ +static int add_target_ip(char *arg, struct sockaddr_storage *in) { struct rta_host *host; struct sockaddr_in *sin, *host_sin; struct sockaddr_in6 *sin6, *host_sin6; @@ -1661,51 +1624,46 @@ add_target_ip(char *arg, struct sockaddr_storage *in) else sin6 = (struct sockaddr_in6 *)in; - - /* disregard obviously stupid addresses * (I didn't find an ipv6 equivalent to INADDR_NONE) */ - if (((address_family == AF_INET && (sin->sin_addr.s_addr == INADDR_NONE - || sin->sin_addr.s_addr == INADDR_ANY))) - || (address_family == AF_INET6 && (sin6->sin6_addr.s6_addr == in6addr_any.s6_addr))) { + if (((address_family == AF_INET && (sin->sin_addr.s_addr == INADDR_NONE || sin->sin_addr.s_addr == INADDR_ANY))) || + (address_family == AF_INET6 && (sin6->sin6_addr.s6_addr == in6addr_any.s6_addr))) { return -1; } /* no point in adding two identical IP's, so don't. ;) */ host = list; - while(host) { + while (host) { host_sin = (struct sockaddr_in *)&host->saddr_in; host_sin6 = (struct sockaddr_in6 *)&host->saddr_in; - if( (address_family == AF_INET && host_sin->sin_addr.s_addr == sin->sin_addr.s_addr) - || (address_family == AF_INET6 && host_sin6->sin6_addr.s6_addr == sin6->sin6_addr.s6_addr)) { - if(debug) printf("Identical IP already exists. Not adding %s\n", arg); + if ((address_family == AF_INET && host_sin->sin_addr.s_addr == sin->sin_addr.s_addr) || + (address_family == AF_INET6 && host_sin6->sin6_addr.s6_addr == sin6->sin6_addr.s6_addr)) { + if (debug) + printf("Identical IP already exists. Not adding %s\n", arg); return -1; } host = host->next; } /* add the fresh ip */ - host = (struct rta_host*)malloc(sizeof(struct rta_host)); - if(!host) { + host = (struct rta_host *)malloc(sizeof(struct rta_host)); + if (!host) { char straddr[INET6_ADDRSTRLEN]; - parse_address((struct sockaddr_storage*)&in, straddr, sizeof(straddr)); - crash("add_target_ip(%s, %s): malloc(%lu) failed", - arg, straddr, sizeof(struct rta_host)); + parse_address((struct sockaddr_storage *)&in, straddr, sizeof(straddr)); + crash("add_target_ip(%s, %s): malloc(%lu) failed", arg, straddr, sizeof(struct rta_host)); } memset(host, 0, sizeof(struct rta_host)); /* set the values. use calling name for output */ host->name = strdup(arg); - /* fill out the sockaddr_storage struct */ - if(address_family == AF_INET) { + if (address_family == AF_INET) { host_sin = (struct sockaddr_in *)&host->saddr_in; host_sin->sin_family = AF_INET; host_sin->sin_addr.s_addr = sin->sin_addr.s_addr; - } - else { + } else { host_sin6 = (struct sockaddr_in6 *)&host->saddr_in; host_sin6->sin6_family = AF_INET6; memcpy(host_sin6->sin6_addr.s6_addr, sin6->sin6_addr.s6_addr, sizeof host_sin6->sin6_addr.s6_addr); @@ -1714,22 +1672,23 @@ add_target_ip(char *arg, struct sockaddr_storage *in) /* fill out the sockaddr_in struct */ host->rtmin = INFINITY; host->rtmax = 0; - host->jitter=0; - host->jitter_max=0; - host->jitter_min=INFINITY; - host->last_tdiff=0; - host->order_status=STATE_OK; - host->last_icmp_seq=0; - host->rta_status=0; - host->pl_status=0; - host->jitter_status=0; - host->mos_status=0; - host->score_status=0; - host->pl_status=0; - - - if(!list) list = cursor = host; - else cursor->next = host; + host->jitter = 0; + host->jitter_max = 0; + host->jitter_min = INFINITY; + host->last_tdiff = 0; + host->order_status = STATE_OK; + host->last_icmp_seq = 0; + host->rta_status = 0; + host->pl_status = 0; + host->jitter_status = 0; + host->mos_status = 0; + host->score_status = 0; + host->pl_status = 0; + + if (!list) + list = cursor = host; + else + cursor->next = host; cursor = host; targets++; @@ -1738,9 +1697,7 @@ add_target_ip(char *arg, struct sockaddr_storage *in) } /* wrapper for add_target_ip */ -static int -add_target(char *arg) -{ +static int add_target(char *arg) { int error, result = -1; struct sockaddr_storage ip; struct addrinfo hints, *res, *p; @@ -1754,14 +1711,14 @@ add_target(char *arg) sin = (struct sockaddr_in *)&ip; result = inet_pton(address_family, arg, &sin->sin_addr); #ifdef USE_IPV6 - if( result != 1 ){ + if (result != 1) { address_family = AF_INET6; sin6 = (struct sockaddr_in6 *)&ip; result = inet_pton(address_family, arg, &sin6->sin6_addr); } #endif /* If we don't find any valid addresses, we still don't know the address_family */ - if ( result != 1) { + if (result != 1) { address_family = -1; } break; @@ -1773,15 +1730,15 @@ add_target(char *arg) sin6 = (struct sockaddr_in6 *)&ip; result = inet_pton(address_family, arg, &sin6->sin6_addr); break; - default: crash("Address family not supported"); + default: + crash("Address family not supported"); } /* don't resolve if we don't have to */ - if(result == 1) { + if (result == 1) { /* don't add all ip's if we were given a specific one */ return add_target_ip(arg, &ip); - } - else { + } else { errno = 0; memset(&hints, 0, sizeof(hints)); if (address_family == -1) { @@ -1790,7 +1747,7 @@ add_target(char *arg) hints.ai_family = address_family == AF_INET ? PF_INET : PF_INET6; } hints.ai_socktype = SOCK_RAW; - if((error = getaddrinfo(arg, NULL, &hints, &res)) != 0) { + if ((error = getaddrinfo(arg, NULL, &hints, &res)) != 0) { errno = 0; crash("Failed to resolve %s: %s", arg, gai_strerror(error)); return -1; @@ -1799,13 +1756,14 @@ add_target(char *arg) } /* possibly add all the IP's as targets */ - for(p = res; p != NULL; p = p->ai_next) { + for (p = res; p != NULL; p = p->ai_next) { memcpy(&ip, p->ai_addr, p->ai_addrlen); add_target_ip(arg, &ip); /* this is silly, but it works */ - if(mode == MODE_HOSTCHECK || mode == MODE_ALL) { - if(debug > 2) printf("mode: %d\n", mode); + if (mode == MODE_HOSTCHECK || mode == MODE_ALL) { + if (debug > 2) + printf("mode: %d\n", mode); continue; } break; @@ -1815,24 +1773,20 @@ add_target(char *arg) return 0; } -static void -set_source_ip(char *arg) -{ +static void set_source_ip(char *arg) { struct sockaddr_in src; memset(&src, 0, sizeof(src)); src.sin_family = address_family; - if((src.sin_addr.s_addr = inet_addr(arg)) == INADDR_NONE) + if ((src.sin_addr.s_addr = inet_addr(arg)) == INADDR_NONE) src.sin_addr.s_addr = get_ip_address(arg); - if(bind(icmp_sock, (struct sockaddr *)&src, sizeof(src)) == -1) + if (bind(icmp_sock, (struct sockaddr *)&src, sizeof(src)) == -1) crash("Cannot bind to IP address %s", arg); } /* TODO: Move this to netutils.c and also change check_dhcp to use that. */ -static in_addr_t -get_ip_address(const char *ifname) -{ - // TODO: Rewrite this so the function return an error and we exit somewhere else +static in_addr_t get_ip_address(const char *ifname) { + // TODO: Rewrite this so the function return an error and we exit somewhere else struct sockaddr_in ip; ip.sin_addr.s_addr = 0; // Fake initialization to make compiler happy #if defined(SIOCGIFADDR) @@ -1842,12 +1796,12 @@ get_ip_address(const char *ifname) ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0'; - if(ioctl(icmp_sock, SIOCGIFADDR, &ifr) == -1) + if (ioctl(icmp_sock, SIOCGIFADDR, &ifr) == -1) crash("Cannot determine IP address of interface %s", ifname); memcpy(&ip, &ifr.ifr_addr, sizeof(ip)); #else - (void) ifname; + (void)ifname; errno = 0; crash("Cannot get interface IP address on this platform."); #endif @@ -1860,63 +1814,73 @@ get_ip_address(const char *ifname) * s = seconds * return value is in microseconds */ -static u_int -get_timevar(const char *str) -{ +static u_int get_timevar(const char *str) { char p, u, *ptr; size_t len; - u_int i, d; /* integer and decimal, respectively */ - u_int factor = 1000; /* default to milliseconds */ + u_int i, d; /* integer and decimal, respectively */ + u_int factor = 1000; /* default to milliseconds */ - if(!str) return 0; + if (!str) + return 0; len = strlen(str); - if(!len) return 0; + if (!len) + return 0; /* unit might be given as ms|m (millisec), * us|u (microsec) or just plain s, for seconds */ p = '\0'; u = str[len - 1]; - if(len >= 2 && !isdigit((int)str[len - 2])) p = str[len - 2]; - if(p && u == 's') u = p; - else if(!p) p = u; - if(debug > 2) printf("evaluating %s, u: %c, p: %c\n", str, u, p); - - if(u == 'u') factor = 1; /* microseconds */ - else if(u == 'm') factor = 1000; /* milliseconds */ - else if(u == 's') factor = 1000000; /* seconds */ - if(debug > 2) printf("factor is %u\n", factor); + if (len >= 2 && !isdigit((int)str[len - 2])) + p = str[len - 2]; + if (p && u == 's') + u = p; + else if (!p) + p = u; + if (debug > 2) + printf("evaluating %s, u: %c, p: %c\n", str, u, p); + + if (u == 'u') + factor = 1; /* microseconds */ + else if (u == 'm') + factor = 1000; /* milliseconds */ + else if (u == 's') + factor = 1000000; /* seconds */ + if (debug > 2) + printf("factor is %u\n", factor); i = strtoul(str, &ptr, 0); - if(!ptr || *ptr != '.' || strlen(ptr) < 2 || factor == 1) + if (!ptr || *ptr != '.' || strlen(ptr) < 2 || factor == 1) return i * factor; /* time specified in usecs can't have decimal points, so ignore them */ - if(factor == 1) return i; + if (factor == 1) + return i; d = strtoul(ptr + 1, NULL, 0); /* d is decimal, so get rid of excess digits */ - while(d >= factor) d /= 10; + while (d >= factor) + d /= 10; /* the last parenthesis avoids floating point exceptions. */ return ((i * factor) + (d * (factor / 10))); } /* not too good at checking errors, but it'll do (main() should barfe on -1) */ -static int -get_threshold(char *str, threshold *th) -{ +static int get_threshold(char *str, threshold *th) { char *p = NULL, i = 0; - if(!str || !strlen(str) || !th) return -1; + if (!str || !strlen(str) || !th) + return -1; /* pointer magic slims code by 10 lines. i is bof-stop on stupid libc's */ p = &str[strlen(str) - 1]; - while(p != &str[1]) { - if(*p == '%') *p = '\0'; - else if(*p == ',' && i) { - *p = '\0'; /* reset it so get_timevar(str) works nicely later */ - th->pl = (unsigned char)strtoul(p+1, NULL, 0); + while (p != &str[1]) { + if (*p == '%') + *p = '\0'; + else if (*p == ',' && i) { + *p = '\0'; /* reset it so get_timevar(str) works nicely later */ + th->pl = (unsigned char)strtoul(p + 1, NULL, 0); break; } i = 1; @@ -1924,10 +1888,13 @@ get_threshold(char *str, threshold *th) } th->rta = get_timevar(str); - if(!th->rta) return -1; + if (!th->rta) + return -1; - if(th->rta > MAXTTL * 1000000) th->rta = MAXTTL * 1000000; - if(th->pl > 100) th->pl = 100; + if (th->rta > MAXTTL * 1000000) + th->rta = MAXTTL * 1000000; + if (th->pl > 100) + th->pl = 100; return 0; } @@ -1943,8 +1910,8 @@ get_threshold(char *str, threshold *th) * @param[in] mode Determines whether this a threshold for rta, packet_loss, jitter, mos or score (exclusively) */ static bool get_threshold2(char *str, size_t length, threshold *warn, threshold *crit, threshold_mode mode) { - if (!str || !length || !warn || !crit) return false; - + if (!str || !length || !warn || !crit) + return false; // p points to the last char in str char *p = &str[length - 1]; @@ -1952,18 +1919,17 @@ static bool get_threshold2(char *str, size_t length, threshold *warn, threshold // first_iteration is bof-stop on stupid libc's bool first_iteration = true; - while(p != &str[0]) { - if( (*p == 'm') || (*p == '%') ) { + while (p != &str[0]) { + if ((*p == 'm') || (*p == '%')) { *p = '\0'; - } else if(*p == ',' && !first_iteration) { - *p = '\0'; /* reset it so get_timevar(str) works nicely later */ + } else if (*p == ',' && !first_iteration) { + *p = '\0'; /* reset it so get_timevar(str) works nicely later */ char *start_of_value = p + 1; - if (!parse_threshold2_helper(start_of_value, strlen(start_of_value), crit, mode)){ + if (!parse_threshold2_helper(start_of_value, strlen(start_of_value), crit, mode)) { return false; } - } first_iteration = false; p--; @@ -1976,22 +1942,22 @@ static bool parse_threshold2_helper(char *s, size_t length, threshold *thr, thre char *resultChecker = {0}; switch (mode) { - case const_rta_mode: - thr->rta = strtod(s, &resultChecker) * 1000; - break; - case const_packet_loss_mode: - thr->pl = (unsigned char)strtoul(s, &resultChecker, 0); - break; - case const_jitter_mode: - thr->jitter = strtod(s, &resultChecker); + case const_rta_mode: + thr->rta = strtod(s, &resultChecker) * 1000; + break; + case const_packet_loss_mode: + thr->pl = (unsigned char)strtoul(s, &resultChecker, 0); + break; + case const_jitter_mode: + thr->jitter = strtod(s, &resultChecker); - break; - case const_mos_mode: - thr->mos = strtod(s, &resultChecker); - break; - case const_score_mode: - thr->score = strtod(s, &resultChecker); - break; + break; + case const_mos_mode: + thr->mos = strtod(s, &resultChecker); + break; + case const_score_mode: + thr->score = strtod(s, &resultChecker); + break; } if (resultChecker == s) { @@ -2007,123 +1973,116 @@ static bool parse_threshold2_helper(char *s, size_t length, threshold *thr, thre return true; } -unsigned short -icmp_checksum(uint16_t *p, size_t n) -{ +unsigned short icmp_checksum(uint16_t *p, size_t n) { unsigned short cksum; long sum = 0; /* sizeof(uint16_t) == 2 */ - while(n >= 2) { + while (n >= 2) { sum += *(p++); n -= 2; } /* mop up the occasional odd byte */ - if(n == 1) sum += *((uint8_t *)p -1); + if (n == 1) + sum += *((uint8_t *)p - 1); - sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ - sum += (sum >> 16); /* add carry */ - cksum = ~sum; /* ones-complement, trunc to 16 bits */ + sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ + sum += (sum >> 16); /* add carry */ + cksum = ~sum; /* ones-complement, trunc to 16 bits */ return cksum; } -void -print_help(void) -{ +void print_help(void) { /*print_revision (progname);*/ /* FIXME: Why? */ - printf ("Copyright (c) 2005 Andreas Ericsson \n"); - - printf (COPYRIGHT, copyright, email); - - printf ("\n\n"); - - print_usage (); - - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); - - printf (" %s\n", "-H"); - printf (" %s\n", _("specify a target")); - printf (" %s\n", "[-4|-6]"); - printf (" %s\n", _("Use IPv4 (default) or IPv6 to communicate with the targets")); - printf (" %s\n", "-w"); - printf (" %s", _("warning threshold (currently ")); - printf ("%0.3fms,%u%%)\n", (float)warn.rta / 1000, warn.pl); - printf (" %s\n", "-c"); - printf (" %s", _("critical threshold (currently ")); - printf ("%0.3fms,%u%%)\n", (float)crit.rta / 1000, crit.pl); - - printf (" %s\n", "-R"); - printf (" %s\n", _("RTA, round trip average, mode warning,critical, ex. 100ms,200ms unit in ms")); - printf (" %s\n", "-P"); - printf (" %s\n", _("packet loss mode, ex. 40%,50% , unit in %")); - printf (" %s\n", "-J"); - printf (" %s\n", _("jitter mode warning,critical, ex. 40.000ms,50.000ms , unit in ms ")); - printf (" %s\n", "-M"); - printf (" %s\n", _("MOS mode, between 0 and 4.4 warning,critical, ex. 3.5,3.0")); - printf (" %s\n", "-S"); - printf (" %s\n", _("score mode, max value 100 warning,critical, ex. 80,70 ")); - printf (" %s\n", "-O"); - printf (" %s\n", _("detect out of order ICMP packts ")); - printf (" %s\n", "-H"); - printf (" %s\n", _("specify a target")); - printf (" %s\n", "-s"); - printf (" %s\n", _("specify a source IP address or device name")); - printf (" %s\n", "-n"); - printf (" %s", _("number of packets to send (currently ")); - printf ("%u)\n",packets); - printf (" %s\n", "-p"); - printf (" %s", _("number of packets to send (currently ")); - printf ("%u)\n",packets); - printf (" %s\n", "-i"); - printf (" %s", _("max packet interval (currently ")); - printf ("%0.3fms)\n",(float)pkt_interval / 1000); - printf (" %s\n", "-I"); - printf (" %s", _("max target interval (currently ")); - printf ("%0.3fms)\n", (float)target_interval / 1000); - printf (" %s\n", "-m"); - printf (" %s",_("number of alive hosts required for success")); - printf ("\n"); - printf (" %s\n", "-l"); - printf (" %s", _("TTL on outgoing packets (currently ")); - printf ("%u)\n", ttl); - printf (" %s\n", "-t"); - printf (" %s",_("timeout value (seconds, currently ")); - printf ("%u)\n", timeout); - printf (" %s\n", "-b"); - printf (" %s\n", _("Number of icmp data bytes to send")); - printf (" %s %u + %d)\n", _("Packet size will be data bytes + icmp header (currently"),icmp_data_size, ICMP_MINLEN); - printf (" %s\n", "-v"); - printf (" %s\n", _("verbose")); - printf ("\n"); - printf ("%s\n", _("Notes:")); - printf (" %s\n", _("If none of R,P,J,M,S or O is specified, default behavior is -R -P")); - printf (" %s\n", _("The -H switch is optional. Naming a host (or several) to check is not.")); - printf ("\n"); - printf (" %s\n", _("Threshold format for -w and -c is 200.25,60% for 200.25 msec RTA and 60%")); - printf (" %s\n", _("packet loss. The default values should work well for most users.")); - printf (" %s\n", _("You can specify different RTA factors using the standardized abbreviations")); - printf (" %s\n", _("us (microseconds), ms (milliseconds, default) or just plain s for seconds.")); + printf("Copyright (c) 2005 Andreas Ericsson \n"); + + printf(COPYRIGHT, copyright, email); + + printf("\n\n"); + + print_usage(); + + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); + + printf(" %s\n", "-H"); + printf(" %s\n", _("specify a target")); + printf(" %s\n", "[-4|-6]"); + printf(" %s\n", _("Use IPv4 (default) or IPv6 to communicate with the targets")); + printf(" %s\n", "-w"); + printf(" %s", _("warning threshold (currently ")); + printf("%0.3fms,%u%%)\n", (float)warn.rta / 1000, warn.pl); + printf(" %s\n", "-c"); + printf(" %s", _("critical threshold (currently ")); + printf("%0.3fms,%u%%)\n", (float)crit.rta / 1000, crit.pl); + + printf(" %s\n", "-R"); + printf(" %s\n", _("RTA, round trip average, mode warning,critical, ex. 100ms,200ms unit in ms")); + printf(" %s\n", "-P"); + printf(" %s\n", _("packet loss mode, ex. 40%,50% , unit in %")); + printf(" %s\n", "-J"); + printf(" %s\n", _("jitter mode warning,critical, ex. 40.000ms,50.000ms , unit in ms ")); + printf(" %s\n", "-M"); + printf(" %s\n", _("MOS mode, between 0 and 4.4 warning,critical, ex. 3.5,3.0")); + printf(" %s\n", "-S"); + printf(" %s\n", _("score mode, max value 100 warning,critical, ex. 80,70 ")); + printf(" %s\n", "-O"); + printf(" %s\n", _("detect out of order ICMP packts ")); + printf(" %s\n", "-H"); + printf(" %s\n", _("specify a target")); + printf(" %s\n", "-s"); + printf(" %s\n", _("specify a source IP address or device name")); + printf(" %s\n", "-n"); + printf(" %s", _("number of packets to send (currently ")); + printf("%u)\n", packets); + printf(" %s\n", "-p"); + printf(" %s", _("number of packets to send (currently ")); + printf("%u)\n", packets); + printf(" %s\n", "-i"); + printf(" %s", _("max packet interval (currently ")); + printf("%0.3fms)\n", (float)pkt_interval / 1000); + printf(" %s\n", "-I"); + printf(" %s", _("max target interval (currently ")); + printf("%0.3fms)\n", (float)target_interval / 1000); + printf(" %s\n", "-m"); + printf(" %s", _("number of alive hosts required for success")); + printf("\n"); + printf(" %s\n", "-l"); + printf(" %s", _("TTL on outgoing packets (currently ")); + printf("%u)\n", ttl); + printf(" %s\n", "-t"); + printf(" %s", _("timeout value (seconds, currently ")); + printf("%u)\n", timeout); + printf(" %s\n", "-b"); + printf(" %s\n", _("Number of icmp data bytes to send")); + printf(" %s %u + %d)\n", _("Packet size will be data bytes + icmp header (currently"), icmp_data_size, ICMP_MINLEN); + printf(" %s\n", "-v"); + printf(" %s\n", _("verbose")); + printf("\n"); + printf("%s\n", _("Notes:")); + printf(" %s\n", _("If none of R,P,J,M,S or O is specified, default behavior is -R -P")); + printf(" %s\n", _("The -H switch is optional. Naming a host (or several) to check is not.")); + printf("\n"); + printf(" %s\n", _("Threshold format for -w and -c is 200.25,60% for 200.25 msec RTA and 60%")); + printf(" %s\n", _("packet loss. The default values should work well for most users.")); + printf(" %s\n", _("You can specify different RTA factors using the standardized abbreviations")); + printf(" %s\n", _("us (microseconds), ms (milliseconds, default) or just plain s for seconds.")); /* -d not yet implemented */ /* printf ("%s\n", _("Threshold format for -d is warn,crit. 12,14 means WARNING if >= 12 hops")); printf ("%s\n", _("are spent and CRITICAL if >= 14 hops are spent.")); printf ("%s\n\n", _("NOTE: Some systems decrease TTL when forming ICMP_ECHOREPLY, others do not."));*/ - printf ("\n"); - printf (" %s\n", _("The -v switch can be specified several times for increased verbosity.")); + printf("\n"); + printf(" %s\n", _("The -v switch can be specified several times for increased verbosity.")); /* printf ("%s\n", _("Long options are currently unsupported.")); printf ("%s\n", _("Options marked with * require an argument")); */ - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); +void print_usage(void) { + printf("%s\n", _("Usage:")); printf(" %s [options] [-H] host1 host2 hostN\n", progname); } -- cgit v0.10-9-g596f From 85f2e32e276ff92110f56828ac82b28007c72236 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 15 Oct 2024 11:55:08 +0200 Subject: check_icmp: Declare internal variables static diff --git a/plugins-root/check_icmp.c b/plugins-root/check_icmp.c index 5ad1d84..d7e6ca2 100644 --- a/plugins-root/check_icmp.c +++ b/plugins-root/check_icmp.c @@ -247,14 +247,14 @@ static struct timeval prog_start; static unsigned long long max_completion_time = 0; static unsigned int warn_down = 1, crit_down = 1; /* host down threshold values */ static int min_hosts_alive = -1; -float pkt_backoff_factor = 1.5; -float target_backoff_factor = 1.5; -bool rta_mode = false; -bool pl_mode = false; -bool jitter_mode = false; -bool score_mode = false; -bool mos_mode = false; -bool order_mode = false; +static float pkt_backoff_factor = 1.5; +static float target_backoff_factor = 1.5; +static bool rta_mode = false; +static bool pl_mode = false; +static bool jitter_mode = false; +static bool score_mode = false; +static bool mos_mode = false; +static bool order_mode = false; /** code start **/ static void crash(const char *fmt, ...) { -- cgit v0.10-9-g596f From 780909f980809a3798343fb8cf82c33ed284885a Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 15 Oct 2024 11:55:27 +0200 Subject: check_icmp: Properly mark function with void input diff --git a/plugins-root/check_icmp.c b/plugins-root/check_icmp.c index d7e6ca2..e6d4316 100644 --- a/plugins-root/check_icmp.c +++ b/plugins-root/check_icmp.c @@ -845,7 +845,7 @@ int main(int argc, char **argv) { return (0); } -static void run_checks() { +static void run_checks(void) { u_int i, t; u_int final_wait, time_passed; -- cgit v0.10-9-g596f From c0694cc6b52caf924418b636a290b5674a24311a Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 15 Oct 2024 11:56:41 +0200 Subject: check_icmp: Update copyright diff --git a/plugins-root/check_icmp.c b/plugins-root/check_icmp.c index e6d4316..2fd92cd 100644 --- a/plugins-root/check_icmp.c +++ b/plugins-root/check_icmp.c @@ -3,7 +3,7 @@ * Monitoring check_icmp plugin * * License: GPL - * Copyright (c) 2005-2008 Monitoring Plugins Development Team + * Copyright (c) 2005-2024 Monitoring Plugins Development Team * Original Author : Andreas Ericsson * * Description: @@ -39,7 +39,7 @@ /* progname may change */ /* char *progname = "check_icmp"; */ char *progname; -const char *copyright = "2005-2008"; +const char *copyright = "2005-2024"; const char *email = "devel@monitoring-plugins.org"; /** Monitoring Plugins basic includes */ -- cgit v0.10-9-g596f From 3934457c2a531b86d8dd7ceeebf4e0fbb7c83387 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 15 Oct 2024 16:00:07 +0200 Subject: check_dhcp: clang-format diff --git a/plugins-root/check_dhcp.c b/plugins-root/check_dhcp.c index 4b8f5e2..4f50a5c 100644 --- a/plugins-root/check_dhcp.c +++ b/plugins-root/check_dhcp.c @@ -59,45 +59,45 @@ const char *email = "devel@monitoring-plugins.org"; #include #if HAVE_SYS_SOCKIO_H -#include +# include #endif // HAVE_SYS_SOCKIO_H -#if defined( __linux__ ) +#if defined(__linux__) -#include -#include +# include +# include -#elif defined (__bsd__) +#elif defined(__bsd__) -#include -#include -#include -#include +# include +# include +# include +# include #elif defined(__sun__) || defined(__solaris__) || defined(__hpux__) -#define INSAP 22 -#define OUTSAP 24 +# define INSAP 22 +# define OUTSAP 24 -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include -#define bcopy(source, destination, length) memcpy(destination, source, length) +# define bcopy(source, destination, length) memcpy(destination, source, length) -#define AREA_SZ 5000 /* buffer length in bytes */ +# define AREA_SZ 5000 /* buffer length in bytes */ static u_long ctl_area[AREA_SZ]; static u_long dat_area[AREA_SZ]; static struct strbuf ctl = {AREA_SZ, 0, (char *)ctl_area}; static struct strbuf dat = {AREA_SZ, 0, (char *)dat_area}; -#define GOT_CTRL 1 -#define GOT_DATA 2 -#define GOT_BOTH 3 -#define GOT_INTR 4 -#define GOT_ERR 128 +# define GOT_CTRL 1 +# define GOT_DATA 2 +# define GOT_BOTH 3 +# define GOT_INTR 4 +# define GOT_ERR 128 static int get_msg(int); static int check_ctrl(int); @@ -105,178 +105,168 @@ static int put_ctrl(int, int, int); static int put_both(int, int, int, int); static int dl_open(const char *, int, int *); static int dl_bind(int, int, u_char *); -long mac_addr_dlpi( const char *, int, u_char *); +long mac_addr_dlpi(const char *, int, u_char *); #endif // __sun__ || __solaris__ || __hpux - - /**** Common definitions ****/ -#define OK 0 -#define ERROR -1 - +#define OK 0 +#define ERROR -1 /**** DHCP definitions ****/ -#define MAX_DHCP_CHADDR_LENGTH 16 -#define MAX_DHCP_SNAME_LENGTH 64 -#define MAX_DHCP_FILE_LENGTH 128 -#define MAX_DHCP_OPTIONS_LENGTH 312 - - -typedef struct dhcp_packet_struct{ - uint8_t op; /* packet type */ - uint8_t htype; /* type of hardware address for this machine (Ethernet, etc) */ - uint8_t hlen; /* length of hardware address (of this machine) */ - uint8_t hops; /* hops */ - uint32_t xid; /* random transaction id number - chosen by this machine */ - uint16_t secs; /* seconds used in timing */ - uint16_t flags; /* flags */ - struct in_addr ciaddr; /* IP address of this machine (if we already have one) */ - struct in_addr yiaddr; /* IP address of this machine (offered by the DHCP server) */ - struct in_addr siaddr; /* IP address of next server */ - struct in_addr giaddr; /* IP address of DHCP relay */ - unsigned char chaddr [MAX_DHCP_CHADDR_LENGTH]; /* hardware address of this machine */ - char sname [MAX_DHCP_SNAME_LENGTH]; /* name of DHCP server */ - char file [MAX_DHCP_FILE_LENGTH]; /* boot file name (used for diskless booting?) */ - char options[MAX_DHCP_OPTIONS_LENGTH]; /* options */ -}dhcp_packet; - - -typedef struct dhcp_offer_struct{ - struct in_addr server_address; /* address of DHCP server that sent this offer */ - struct in_addr offered_address; /* the IP address that was offered to us */ +#define MAX_DHCP_CHADDR_LENGTH 16 +#define MAX_DHCP_SNAME_LENGTH 64 +#define MAX_DHCP_FILE_LENGTH 128 +#define MAX_DHCP_OPTIONS_LENGTH 312 + +typedef struct dhcp_packet_struct { + uint8_t op; /* packet type */ + uint8_t htype; /* type of hardware address for this machine (Ethernet, etc) */ + uint8_t hlen; /* length of hardware address (of this machine) */ + uint8_t hops; /* hops */ + uint32_t xid; /* random transaction id number - chosen by this machine */ + uint16_t secs; /* seconds used in timing */ + uint16_t flags; /* flags */ + struct in_addr ciaddr; /* IP address of this machine (if we already have one) */ + struct in_addr yiaddr; /* IP address of this machine (offered by the DHCP server) */ + struct in_addr siaddr; /* IP address of next server */ + struct in_addr giaddr; /* IP address of DHCP relay */ + unsigned char chaddr[MAX_DHCP_CHADDR_LENGTH]; /* hardware address of this machine */ + char sname[MAX_DHCP_SNAME_LENGTH]; /* name of DHCP server */ + char file[MAX_DHCP_FILE_LENGTH]; /* boot file name (used for diskless booting?) */ + char options[MAX_DHCP_OPTIONS_LENGTH]; /* options */ +} dhcp_packet; + +typedef struct dhcp_offer_struct { + struct in_addr server_address; /* address of DHCP server that sent this offer */ + struct in_addr offered_address; /* the IP address that was offered to us */ uint32_t lease_time; /* lease time in seconds */ uint32_t renewal_time; /* renewal time in seconds */ uint32_t rebinding_time; /* rebinding time in seconds */ - bool desired; /* is this offer desired (necessary in exclusive mode) */ + bool desired; /* is this offer desired (necessary in exclusive mode) */ struct dhcp_offer_struct *next; -}dhcp_offer; - +} dhcp_offer; -typedef struct requested_server_struct{ +typedef struct requested_server_struct { struct in_addr server_address; bool answered; struct requested_server_struct *next; -}requested_server; - - -#define BOOTREQUEST 1 -#define BOOTREPLY 2 - -#define DHCPDISCOVER 1 -#define DHCPOFFER 2 -#define DHCPREQUEST 3 -#define DHCPDECLINE 4 -#define DHCPACK 5 -#define DHCPNACK 6 -#define DHCPRELEASE 7 - -#define DHCP_OPTION_MESSAGE_TYPE 53 -#define DHCP_OPTION_HOST_NAME 12 -#define DHCP_OPTION_BROADCAST_ADDRESS 28 -#define DHCP_OPTION_REQUESTED_ADDRESS 50 -#define DHCP_OPTION_LEASE_TIME 51 -#define DHCP_OPTION_SERVER_IDENTIFIER 54 -#define DHCP_OPTION_RENEWAL_TIME 58 -#define DHCP_OPTION_REBINDING_TIME 59 -#define DHCP_OPTION_END 255 - -#define DHCP_INFINITE_TIME 0xFFFFFFFF +} requested_server; + +#define BOOTREQUEST 1 +#define BOOTREPLY 2 + +#define DHCPDISCOVER 1 +#define DHCPOFFER 2 +#define DHCPREQUEST 3 +#define DHCPDECLINE 4 +#define DHCPACK 5 +#define DHCPNACK 6 +#define DHCPRELEASE 7 + +#define DHCP_OPTION_MESSAGE_TYPE 53 +#define DHCP_OPTION_HOST_NAME 12 +#define DHCP_OPTION_BROADCAST_ADDRESS 28 +#define DHCP_OPTION_REQUESTED_ADDRESS 50 +#define DHCP_OPTION_LEASE_TIME 51 +#define DHCP_OPTION_SERVER_IDENTIFIER 54 +#define DHCP_OPTION_RENEWAL_TIME 58 +#define DHCP_OPTION_REBINDING_TIME 59 +#define DHCP_OPTION_END 255 + +#define DHCP_INFINITE_TIME 0xFFFFFFFF #define DHCP_BROADCAST_FLAG 32768 -#define DHCP_SERVER_PORT 67 -#define DHCP_CLIENT_PORT 68 +#define DHCP_SERVER_PORT 67 +#define DHCP_CLIENT_PORT 68 -#define ETHERNET_HARDWARE_ADDRESS 1 /* used in htype field of dhcp packet */ -#define ETHERNET_HARDWARE_ADDRESS_LENGTH 6 /* length of Ethernet hardware addresses */ +#define ETHERNET_HARDWARE_ADDRESS 1 /* used in htype field of dhcp packet */ +#define ETHERNET_HARDWARE_ADDRESS_LENGTH 6 /* length of Ethernet hardware addresses */ -bool unicast = false; /* unicast mode: mimic a DHCP relay */ -bool exclusive = false; /* exclusive mode aka "rogue DHCP server detection" */ -struct in_addr my_ip; /* our address (required for relay) */ -struct in_addr dhcp_ip; /* server to query (if in unicast mode) */ -unsigned char client_hardware_address[MAX_DHCP_CHADDR_LENGTH]=""; -unsigned char *user_specified_mac=NULL; +bool unicast = false; /* unicast mode: mimic a DHCP relay */ +bool exclusive = false; /* exclusive mode aka "rogue DHCP server detection" */ +struct in_addr my_ip; /* our address (required for relay) */ +struct in_addr dhcp_ip; /* server to query (if in unicast mode) */ +unsigned char client_hardware_address[MAX_DHCP_CHADDR_LENGTH] = ""; +unsigned char *user_specified_mac = NULL; -char network_interface_name[IFNAMSIZ]="eth0"; +char network_interface_name[IFNAMSIZ] = "eth0"; -uint32_t packet_xid=0; +uint32_t packet_xid = 0; -uint32_t dhcp_lease_time=0; -uint32_t dhcp_renewal_time=0; -uint32_t dhcp_rebinding_time=0; +uint32_t dhcp_lease_time = 0; +uint32_t dhcp_renewal_time = 0; +uint32_t dhcp_rebinding_time = 0; -int dhcpoffer_timeout=2; +int dhcpoffer_timeout = 2; -dhcp_offer *dhcp_offer_list=NULL; -requested_server *requested_server_list=NULL; +dhcp_offer *dhcp_offer_list = NULL; +requested_server *requested_server_list = NULL; -int valid_responses=0; /* number of valid DHCPOFFERs we received */ -int requested_servers=0; -int requested_responses=0; +int valid_responses = 0; /* number of valid DHCPOFFERs we received */ +int requested_servers = 0; +int requested_responses = 0; -bool request_specific_address=false; -bool received_requested_address=false; -int verbose=0; +bool request_specific_address = false; +bool received_requested_address = false; +int verbose = 0; struct in_addr requested_address; - int process_arguments(int, char **); int call_getopt(int, char **); int validate_arguments(int); void print_usage(void); void print_help(void); -void resolve_host(const char *in,struct in_addr *out); +void resolve_host(const char *in, struct in_addr *out); unsigned char *mac_aton(const char *); void print_hardware_address(const unsigned char *); -int get_hardware_address(int,char *); -int get_ip_address(int,char *); +int get_hardware_address(int, char *); +int get_ip_address(int, char *); int send_dhcp_discover(int); int get_dhcp_offer(int); int get_results(void); -int add_dhcp_offer(struct in_addr,dhcp_packet *); +int add_dhcp_offer(struct in_addr, dhcp_packet *); int free_dhcp_offer_list(void); int free_requested_server_list(void); int create_dhcp_socket(void); int close_dhcp_socket(int); -int send_dhcp_packet(void *,int,int,struct sockaddr_in *); -int receive_dhcp_packet(void *,int,int,int,struct sockaddr_in *); - +int send_dhcp_packet(void *, int, int, struct sockaddr_in *); +int receive_dhcp_packet(void *, int, int, int, struct sockaddr_in *); - -int main(int argc, char **argv){ +int main(int argc, char **argv) { int dhcp_socket; int result = STATE_UNKNOWN; - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Parse extra opts if any */ - argv=np_extra_opts(&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if(process_arguments(argc,argv)!=OK){ - usage4 (_("Could not parse arguments")); + if (process_arguments(argc, argv) != OK) { + usage4(_("Could not parse arguments")); } /* create socket for DHCP communications */ - dhcp_socket=create_dhcp_socket(); + dhcp_socket = create_dhcp_socket(); /* get hardware address of client machine */ - if(user_specified_mac!=NULL) - memcpy(client_hardware_address,user_specified_mac,6); + if (user_specified_mac != NULL) + memcpy(client_hardware_address, user_specified_mac, 6); else - get_hardware_address(dhcp_socket,network_interface_name); + get_hardware_address(dhcp_socket, network_interface_name); - if(unicast) /* get IP address of client machine */ - get_ip_address(dhcp_socket,network_interface_name); + if (unicast) /* get IP address of client machine */ + get_ip_address(dhcp_socket, network_interface_name); /* send DHCPDISCOVER packet */ send_dhcp_discover(dhcp_socket); @@ -288,7 +278,7 @@ int main(int argc, char **argv){ close_dhcp_socket(dhcp_socket); /* determine state/plugin output to return */ - result=get_results(); + result = get_results(); /* free allocated memory */ free_dhcp_offer_list(); @@ -297,34 +287,32 @@ int main(int argc, char **argv){ return result; } - - /* determines hardware address on client machine */ -int get_hardware_address(int sock,char *interface_name){ +int get_hardware_address(int sock, char *interface_name) { #if defined(__linux__) struct ifreq ifr; - strncpy((char *)&ifr.ifr_name,interface_name,sizeof(ifr.ifr_name)-1); - ifr.ifr_name[sizeof(ifr.ifr_name)-1]='\0'; + strncpy((char *)&ifr.ifr_name, interface_name, sizeof(ifr.ifr_name) - 1); + ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0'; /* try and grab hardware address of requested interface */ - if(ioctl(sock,SIOCGIFHWADDR,&ifr)<0){ - printf(_("Error: Could not get hardware address of interface '%s'\n"),interface_name); + if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0) { + printf(_("Error: Could not get hardware address of interface '%s'\n"), interface_name); exit(STATE_UNKNOWN); } - memcpy(&client_hardware_address[0],&ifr.ifr_hwaddr.sa_data,6); + memcpy(&client_hardware_address[0], &ifr.ifr_hwaddr.sa_data, 6); #elif defined(__bsd__) /* King 2004 see ACKNOWLEDGEMENTS */ - size_t len; - int mib[6]; - char *buf; - unsigned char *ptr; - struct if_msghdr *ifm; - struct sockaddr_dl *sdl; + size_t len; + int mib[6]; + char *buf; + unsigned char *ptr; + struct if_msghdr *ifm; + struct sockaddr_dl *sdl; mib[0] = CTL_NET; mib[1] = AF_ROUTE; @@ -332,22 +320,22 @@ int get_hardware_address(int sock,char *interface_name){ mib[3] = AF_LINK; mib[4] = NET_RT_IFLIST; - if((mib[5] = if_nametoindex(interface_name)) == 0){ + if ((mib[5] = if_nametoindex(interface_name)) == 0) { printf(_("Error: if_nametoindex error - %s.\n"), strerror(errno)); exit(STATE_UNKNOWN); } - if(sysctl(mib, 6, NULL, &len, NULL, 0) < 0){ + if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { printf(_("Error: Couldn't get hardware address from %s. sysctl 1 error - %s.\n"), interface_name, strerror(errno)); exit(STATE_UNKNOWN); } - if((buf = malloc(len)) == NULL){ + if ((buf = malloc(len)) == NULL) { printf(_("Error: Couldn't get hardware address from interface %s. malloc error - %s.\n"), interface_name, strerror(errno)); exit(4); } - if(sysctl(mib, 6, buf, &len, NULL, 0) < 0){ + if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { printf(_("Error: Couldn't get hardware address from %s. sysctl 2 error - %s.\n"), interface_name, strerror(errno)); exit(STATE_UNKNOWN); } @@ -355,7 +343,7 @@ int get_hardware_address(int sock,char *interface_name){ ifm = (struct if_msghdr *)buf; sdl = (struct sockaddr_dl *)(ifm + 1); ptr = (unsigned char *)LLADDR(sdl); - memcpy(&client_hardware_address[0], ptr, 6) ; + memcpy(&client_hardware_address[0], ptr, 6); /* King 2004 */ #elif defined(__sun__) || defined(__solaris__) @@ -368,22 +356,21 @@ int get_hardware_address(int sock,char *interface_name){ /* get last number from interfacename, eg lnc0, e1000g0*/ int i; - p = interface_name + strlen(interface_name) -1; - for(i = strlen(interface_name) -1; i > 0; p--) { - if(isalpha(*p)) + p = interface_name + strlen(interface_name) - 1; + for (i = strlen(interface_name) - 1; i > 0; p--) { + if (isalpha(*p)) break; } p++; - if( p != interface_name ){ - unit = atoi(p) ; - strncat(dev, interface_name, 6) ; - } - else{ + if (p != interface_name) { + unit = atoi(p); + strncat(dev, interface_name, 6); + } else { printf(_("Error: can't find unit number in interface_name (%s) - expecting TypeNumber eg lnc0.\n"), interface_name); exit(STATE_UNKNOWN); } stat = mac_addr_dlpi(dev, unit, client_hardware_address); - if(stat != 0){ + if (stat != 0) { printf(_("Error: can't read MAC address from DLPI streams interface for device %s unit %d.\n"), dev, unit); exit(STATE_UNKNOWN); } @@ -391,11 +378,11 @@ int get_hardware_address(int sock,char *interface_name){ #elif defined(__hpux__) long stat; - char dev[20] = "/dev/dlpi" ; + char dev[20] = "/dev/dlpi"; int unit = 0; stat = mac_addr_dlpi(dev, unit, client_hardware_address); - if(stat != 0){ + if (stat != 0) { printf(_("Error: can't read MAC address from DLPI streams interface for device %s unit %d.\n"), dev, unit); exit(STATE_UNKNOWN); } @@ -406,68 +393,65 @@ int get_hardware_address(int sock,char *interface_name){ exit(STATE_UNKNOWN); #endif - if(verbose) + if (verbose) print_hardware_address(client_hardware_address); return OK; } /* determines IP address of the client interface */ -int get_ip_address(int sock,char *interface_name){ +int get_ip_address(int sock, char *interface_name) { #if defined(SIOCGIFADDR) struct ifreq ifr; - strncpy((char *)&ifr.ifr_name,interface_name,sizeof(ifr.ifr_name)-1); - ifr.ifr_name[sizeof(ifr.ifr_name)-1]='\0'; + strncpy((char *)&ifr.ifr_name, interface_name, sizeof(ifr.ifr_name) - 1); + ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0'; - if(ioctl(sock,SIOCGIFADDR,&ifr)<0){ - printf(_("Error: Cannot determine IP address of interface %s\n"), - interface_name); + if (ioctl(sock, SIOCGIFADDR, &ifr) < 0) { + printf(_("Error: Cannot determine IP address of interface %s\n"), interface_name); exit(STATE_UNKNOWN); } - my_ip=((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr; + my_ip = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr; #else printf(_("Error: Cannot get interface IP address on this platform.\n")); exit(STATE_UNKNOWN); #endif - if(verbose) - printf(_("Pretending to be relay client %s\n"),inet_ntoa(my_ip)); + if (verbose) + printf(_("Pretending to be relay client %s\n"), inet_ntoa(my_ip)); return OK; } /* sends a DHCPDISCOVER broadcast message in an attempt to find DHCP servers */ -int send_dhcp_discover(int sock){ +int send_dhcp_discover(int sock) { dhcp_packet discover_packet; struct sockaddr_in sockaddr_broadcast; unsigned short opts; - /* clear the packet data structure */ - bzero(&discover_packet,sizeof(discover_packet)); - + bzero(&discover_packet, sizeof(discover_packet)); /* boot request flag (backward compatible with BOOTP servers) */ - discover_packet.op=BOOTREQUEST; + discover_packet.op = BOOTREQUEST; /* hardware address type */ - discover_packet.htype=ETHERNET_HARDWARE_ADDRESS; + discover_packet.htype = ETHERNET_HARDWARE_ADDRESS; /* length of our hardware address */ - discover_packet.hlen=ETHERNET_HARDWARE_ADDRESS_LENGTH; + discover_packet.hlen = ETHERNET_HARDWARE_ADDRESS_LENGTH; /* * transaction ID is supposed to be random. */ - srand(time(NULL)^getpid()); - packet_xid=random(); - discover_packet.xid=htonl(packet_xid); + srand(time(NULL) ^ getpid()); + packet_xid = random(); + discover_packet.xid = htonl(packet_xid); /*discover_packet.secs=htons(65535);*/ - discover_packet.secs=0xFF; + discover_packet.secs = 0xFF; /* * server needs to know if it should broadcast or unicast its response: @@ -476,71 +460,67 @@ int send_dhcp_discover(int sock){ discover_packet.flags = unicast ? 0 : htons(DHCP_BROADCAST_FLAG); /* our hardware address */ - memcpy(discover_packet.chaddr,client_hardware_address,ETHERNET_HARDWARE_ADDRESS_LENGTH); + memcpy(discover_packet.chaddr, client_hardware_address, ETHERNET_HARDWARE_ADDRESS_LENGTH); /* first four bytes of options field is magic cookie (as per RFC 2132) */ - discover_packet.options[0]='\x63'; - discover_packet.options[1]='\x82'; - discover_packet.options[2]='\x53'; - discover_packet.options[3]='\x63'; + discover_packet.options[0] = '\x63'; + discover_packet.options[1] = '\x82'; + discover_packet.options[2] = '\x53'; + discover_packet.options[3] = '\x63'; opts = 4; /* DHCP message type is embedded in options field */ - discover_packet.options[opts++]=DHCP_OPTION_MESSAGE_TYPE; /* DHCP message type option identifier */ - discover_packet.options[opts++]='\x01'; /* DHCP message option length in bytes */ - discover_packet.options[opts++]=DHCPDISCOVER; + discover_packet.options[opts++] = DHCP_OPTION_MESSAGE_TYPE; /* DHCP message type option identifier */ + discover_packet.options[opts++] = '\x01'; /* DHCP message option length in bytes */ + discover_packet.options[opts++] = DHCPDISCOVER; /* the IP address we're requesting */ - if(request_specific_address){ - discover_packet.options[opts++]=DHCP_OPTION_REQUESTED_ADDRESS; - discover_packet.options[opts++]='\x04'; - memcpy(&discover_packet.options[opts],&requested_address,sizeof(requested_address)); + if (request_specific_address) { + discover_packet.options[opts++] = DHCP_OPTION_REQUESTED_ADDRESS; + discover_packet.options[opts++] = '\x04'; + memcpy(&discover_packet.options[opts], &requested_address, sizeof(requested_address)); opts += sizeof(requested_address); } - discover_packet.options[opts++]= (char)DHCP_OPTION_END; + discover_packet.options[opts++] = (char)DHCP_OPTION_END; /* unicast fields */ - if(unicast) + if (unicast) discover_packet.giaddr.s_addr = my_ip.s_addr; /* see RFC 1542, 4.1.1 */ discover_packet.hops = unicast ? 1 : 0; /* send the DHCPDISCOVER packet to broadcast address */ - sockaddr_broadcast.sin_family=AF_INET; - sockaddr_broadcast.sin_port=htons(DHCP_SERVER_PORT); + sockaddr_broadcast.sin_family = AF_INET; + sockaddr_broadcast.sin_port = htons(DHCP_SERVER_PORT); sockaddr_broadcast.sin_addr.s_addr = unicast ? dhcp_ip.s_addr : INADDR_BROADCAST; - bzero(&sockaddr_broadcast.sin_zero,sizeof(sockaddr_broadcast.sin_zero)); - - - if(verbose){ - printf(_("DHCPDISCOVER to %s port %d\n"),inet_ntoa(sockaddr_broadcast.sin_addr),ntohs(sockaddr_broadcast.sin_port)); - printf("DHCPDISCOVER XID: %u (0x%X)\n",ntohl(discover_packet.xid),ntohl(discover_packet.xid)); - printf("DHCDISCOVER ciaddr: %s\n",inet_ntoa(discover_packet.ciaddr)); - printf("DHCDISCOVER yiaddr: %s\n",inet_ntoa(discover_packet.yiaddr)); - printf("DHCDISCOVER siaddr: %s\n",inet_ntoa(discover_packet.siaddr)); - printf("DHCDISCOVER giaddr: %s\n",inet_ntoa(discover_packet.giaddr)); + bzero(&sockaddr_broadcast.sin_zero, sizeof(sockaddr_broadcast.sin_zero)); + + if (verbose) { + printf(_("DHCPDISCOVER to %s port %d\n"), inet_ntoa(sockaddr_broadcast.sin_addr), ntohs(sockaddr_broadcast.sin_port)); + printf("DHCPDISCOVER XID: %u (0x%X)\n", ntohl(discover_packet.xid), ntohl(discover_packet.xid)); + printf("DHCDISCOVER ciaddr: %s\n", inet_ntoa(discover_packet.ciaddr)); + printf("DHCDISCOVER yiaddr: %s\n", inet_ntoa(discover_packet.yiaddr)); + printf("DHCDISCOVER siaddr: %s\n", inet_ntoa(discover_packet.siaddr)); + printf("DHCDISCOVER giaddr: %s\n", inet_ntoa(discover_packet.giaddr)); } /* send the DHCPDISCOVER packet out */ - send_dhcp_packet(&discover_packet,sizeof(discover_packet),sock,&sockaddr_broadcast); + send_dhcp_packet(&discover_packet, sizeof(discover_packet), sock, &sockaddr_broadcast); - if(verbose) + if (verbose) printf("\n\n"); return OK; } - - - /* waits for a DHCPOFFER message from one or more DHCP servers */ -int get_dhcp_offer(int sock){ +int get_dhcp_offer(int sock) { dhcp_packet offer_packet; struct sockaddr_in source; struct sockaddr_in via; - int result=OK; - int responses=0; + int result = OK; + int responses = 0; int x; time_t start_time; time_t current_time; @@ -548,30 +528,29 @@ int get_dhcp_offer(int sock){ time(&start_time); /* receive as many responses as we can */ - for(responses=0,valid_responses=0;;){ + for (responses = 0, valid_responses = 0;;) { time(¤t_time); - if((current_time-start_time)>=dhcpoffer_timeout) + if ((current_time - start_time) >= dhcpoffer_timeout) break; - if(verbose) + if (verbose) printf("\n\n"); - bzero(&source,sizeof(source)); - bzero(&via,sizeof(via)); - bzero(&offer_packet,sizeof(offer_packet)); + bzero(&source, sizeof(source)); + bzero(&via, sizeof(via)); + bzero(&offer_packet, sizeof(offer_packet)); - result=OK; - result=receive_dhcp_packet(&offer_packet,sizeof(offer_packet),sock,dhcpoffer_timeout,&source); + result = OK; + result = receive_dhcp_packet(&offer_packet, sizeof(offer_packet), sock, dhcpoffer_timeout, &source); - if(result!=OK){ - if(verbose) + if (result != OK) { + if (verbose) printf(_("Result=ERROR\n")); continue; - } - else{ - if(verbose) + } else { + if (verbose) printf(_("Result=OK\n")); responses++; @@ -579,85 +558,81 @@ int get_dhcp_offer(int sock){ /* The "source" is either a server or a relay. */ /* Save a copy of "source" into "via" even if it's via itself */ - memcpy(&via,&source,sizeof(source)) ; + memcpy(&via, &source, sizeof(source)); - if(verbose){ - printf(_("DHCPOFFER from IP address %s"),inet_ntoa(source.sin_addr)); - printf(_(" via %s\n"),inet_ntoa(via.sin_addr)); - printf("DHCPOFFER XID: %u (0x%X)\n",ntohl(offer_packet.xid),ntohl(offer_packet.xid)); + if (verbose) { + printf(_("DHCPOFFER from IP address %s"), inet_ntoa(source.sin_addr)); + printf(_(" via %s\n"), inet_ntoa(via.sin_addr)); + printf("DHCPOFFER XID: %u (0x%X)\n", ntohl(offer_packet.xid), ntohl(offer_packet.xid)); } /* check packet xid to see if its the same as the one we used in the discover packet */ - if(ntohl(offer_packet.xid)!=packet_xid){ - if(verbose) - printf(_("DHCPOFFER XID (%u) did not match DHCPDISCOVER XID (%u) - ignoring packet\n"),ntohl(offer_packet.xid),packet_xid); + if (ntohl(offer_packet.xid) != packet_xid) { + if (verbose) + printf(_("DHCPOFFER XID (%u) did not match DHCPDISCOVER XID (%u) - ignoring packet\n"), ntohl(offer_packet.xid), packet_xid); continue; } /* check hardware address */ - result=OK; - if(verbose) + result = OK; + if (verbose) printf("DHCPOFFER chaddr: "); - for(x=0;x %s\n",errno,strerror(errno)); + printf("errno: (%d) -> %s\n", errno, strerror(errno)); } return ERROR; - } - else{ - if(verbose){ - printf(_("receive_dhcp_packet() result: %d\n"),recv_result); - printf(_("receive_dhcp_packet() source: %s\n"),inet_ntoa(source_address.sin_addr)); + } else { + if (verbose) { + printf(_("receive_dhcp_packet() result: %d\n"), recv_result); + printf(_("receive_dhcp_packet() source: %s\n"), inet_ntoa(source_address.sin_addr)); } - memcpy(address,&source_address,sizeof(source_address)); + memcpy(address, &source_address, sizeof(source_address)); return OK; } } @@ -711,172 +684,166 @@ int receive_dhcp_packet(void *buffer, int buffer_size, int sock, int timeout, st return OK; } - /* creates a socket for DHCP communication */ -int create_dhcp_socket(void){ +int create_dhcp_socket(void) { struct sockaddr_in myname; struct ifreq interface; int sock; - int flag=1; + int flag = 1; /* Set up the address we're going to bind to. */ - bzero(&myname,sizeof(myname)); - myname.sin_family=AF_INET; + bzero(&myname, sizeof(myname)); + myname.sin_family = AF_INET; /* listen to DHCP server port if we're in unicast mode */ myname.sin_port = htons(unicast ? DHCP_SERVER_PORT : DHCP_CLIENT_PORT); myname.sin_addr.s_addr = unicast ? my_ip.s_addr : INADDR_ANY; - bzero(&myname.sin_zero,sizeof(myname.sin_zero)); + bzero(&myname.sin_zero, sizeof(myname.sin_zero)); /* create a socket for DHCP communications */ - sock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); - if(sock<0){ + sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (sock < 0) { printf(_("Error: Could not create socket!\n")); exit(STATE_UNKNOWN); } - if(verbose) - printf("DHCP socket: %d\n",sock); + if (verbose) + printf("DHCP socket: %d\n", sock); /* set the reuse address flag so we don't get errors when restarting */ - flag=1; - if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(char *)&flag,sizeof(flag))<0){ + flag = 1; + if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&flag, sizeof(flag)) < 0) { printf(_("Error: Could not set reuse address option on DHCP socket!\n")); exit(STATE_UNKNOWN); } /* set the broadcast option - we need this to listen to DHCP broadcast messages */ - if(!unicast && setsockopt(sock,SOL_SOCKET,SO_BROADCAST,(char *)&flag,sizeof flag)<0){ + if (!unicast && setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&flag, sizeof flag) < 0) { printf(_("Error: Could not set broadcast option on DHCP socket!\n")); exit(STATE_UNKNOWN); } /* bind socket to interface */ #if defined(__linux__) - strncpy(interface.ifr_ifrn.ifrn_name,network_interface_name,IFNAMSIZ-1); - interface.ifr_ifrn.ifrn_name[IFNAMSIZ-1]='\0'; - if(setsockopt(sock,SOL_SOCKET,SO_BINDTODEVICE,(char *)&interface,sizeof(interface))<0){ - printf(_("Error: Could not bind socket to interface %s. Check your privileges...\n"),network_interface_name); + strncpy(interface.ifr_ifrn.ifrn_name, network_interface_name, IFNAMSIZ - 1); + interface.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = '\0'; + if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, (char *)&interface, sizeof(interface)) < 0) { + printf(_("Error: Could not bind socket to interface %s. Check your privileges...\n"), network_interface_name); exit(STATE_UNKNOWN); } #else - strncpy(interface.ifr_name,network_interface_name,IFNAMSIZ-1); - interface.ifr_name[IFNAMSIZ-1]='\0'; + strncpy(interface.ifr_name, network_interface_name, IFNAMSIZ - 1); + interface.ifr_name[IFNAMSIZ - 1] = '\0'; #endif /* bind the socket */ - if(bind(sock,(struct sockaddr *)&myname,sizeof(myname))<0){ - printf(_("Error: Could not bind to DHCP socket (port %d)! Check your privileges...\n"),DHCP_CLIENT_PORT); + if (bind(sock, (struct sockaddr *)&myname, sizeof(myname)) < 0) { + printf(_("Error: Could not bind to DHCP socket (port %d)! Check your privileges...\n"), DHCP_CLIENT_PORT); exit(STATE_UNKNOWN); } return sock; } - /* closes DHCP socket */ -int close_dhcp_socket(int sock){ +int close_dhcp_socket(int sock) { close(sock); return OK; } - /* adds a requested server address to list in memory */ -int add_requested_server(struct in_addr server_address){ +int add_requested_server(struct in_addr server_address) { requested_server *new_server; - new_server=(requested_server *)malloc(sizeof(requested_server)); - if(new_server==NULL) + new_server = (requested_server *)malloc(sizeof(requested_server)); + if (new_server == NULL) return ERROR; - new_server->server_address=server_address; - new_server->answered=false; + new_server->server_address = server_address; + new_server->answered = false; - new_server->next=requested_server_list; - requested_server_list=new_server; + new_server->next = requested_server_list; + requested_server_list = new_server; requested_servers++; - if(verbose) - printf(_("Requested server address: %s\n"),inet_ntoa(new_server->server_address)); + if (verbose) + printf(_("Requested server address: %s\n"), inet_ntoa(new_server->server_address)); return OK; } - - - /* adds a DHCP OFFER to list in memory */ -int add_dhcp_offer(struct in_addr source,dhcp_packet *offer_packet){ +int add_dhcp_offer(struct in_addr source, dhcp_packet *offer_packet) { dhcp_offer *new_offer; int x; unsigned option_type; unsigned option_length; struct in_addr serv_ident = {0}; - if(offer_packet==NULL) + if (offer_packet == NULL) return ERROR; /* process all DHCP options present in the packet */ - for(x=4;xoptions[x]==-1) + if ((int)offer_packet->options[x] == -1) break; /* get option type */ - option_type=offer_packet->options[x++]; + option_type = offer_packet->options[x++]; /* get option length */ - option_length=offer_packet->options[x++]; + option_length = offer_packet->options[x++]; - if(verbose) - printf("Option: %d (0x%02X)\n",option_type,option_length); + if (verbose) + printf("Option: %d (0x%02X)\n", option_type, option_length); /* get option data */ - switch(option_type){ - case DHCP_OPTION_LEASE_TIME: - memcpy(&dhcp_lease_time, &offer_packet->options[x],sizeof(dhcp_lease_time)); - dhcp_lease_time = ntohl(dhcp_lease_time); - break; - case DHCP_OPTION_RENEWAL_TIME: - memcpy(&dhcp_renewal_time, &offer_packet->options[x],sizeof(dhcp_renewal_time)); - dhcp_renewal_time = ntohl(dhcp_renewal_time); - break; - case DHCP_OPTION_REBINDING_TIME: - memcpy(&dhcp_rebinding_time, &offer_packet->options[x],sizeof(dhcp_rebinding_time)); - dhcp_rebinding_time = ntohl(dhcp_rebinding_time); - break; - case DHCP_OPTION_SERVER_IDENTIFIER: - memcpy(&serv_ident.s_addr, &offer_packet->options[x],sizeof(serv_ident.s_addr)); - break; + switch (option_type) { + case DHCP_OPTION_LEASE_TIME: + memcpy(&dhcp_lease_time, &offer_packet->options[x], sizeof(dhcp_lease_time)); + dhcp_lease_time = ntohl(dhcp_lease_time); + break; + case DHCP_OPTION_RENEWAL_TIME: + memcpy(&dhcp_renewal_time, &offer_packet->options[x], sizeof(dhcp_renewal_time)); + dhcp_renewal_time = ntohl(dhcp_renewal_time); + break; + case DHCP_OPTION_REBINDING_TIME: + memcpy(&dhcp_rebinding_time, &offer_packet->options[x], sizeof(dhcp_rebinding_time)); + dhcp_rebinding_time = ntohl(dhcp_rebinding_time); + break; + case DHCP_OPTION_SERVER_IDENTIFIER: + memcpy(&serv_ident.s_addr, &offer_packet->options[x], sizeof(serv_ident.s_addr)); + break; } /* skip option data we're ignoring */ - if(option_type==0) /* "pad" option, see RFC 2132 (3.1) */ - x+=1; + if (option_type == 0) /* "pad" option, see RFC 2132 (3.1) */ + x += 1; else - x+=option_length; + x += option_length; } - if(verbose){ - if(dhcp_lease_time==DHCP_INFINITE_TIME) + if (verbose) { + if (dhcp_lease_time == DHCP_INFINITE_TIME) printf(_("Lease Time: Infinite\n")); else - printf(_("Lease Time: %lu seconds\n"),(unsigned long)dhcp_lease_time); - if(dhcp_renewal_time==DHCP_INFINITE_TIME) + printf(_("Lease Time: %lu seconds\n"), (unsigned long)dhcp_lease_time); + if (dhcp_renewal_time == DHCP_INFINITE_TIME) printf(_("Renewal Time: Infinite\n")); else - printf(_("Renewal Time: %lu seconds\n"),(unsigned long)dhcp_renewal_time); - if(dhcp_rebinding_time==DHCP_INFINITE_TIME) + printf(_("Renewal Time: %lu seconds\n"), (unsigned long)dhcp_renewal_time); + if (dhcp_rebinding_time == DHCP_INFINITE_TIME) printf(_("Rebinding Time: Infinite\n")); - printf(_("Rebinding Time: %lu seconds\n"),(unsigned long)dhcp_rebinding_time); + printf(_("Rebinding Time: %lu seconds\n"), (unsigned long)dhcp_rebinding_time); } - new_offer=(dhcp_offer *)malloc(sizeof(dhcp_offer)); + new_offer = (dhcp_offer *)malloc(sizeof(dhcp_offer)); - if(new_offer==NULL) + if (new_offer == NULL) return ERROR; /* @@ -891,298 +858,286 @@ int add_dhcp_offer(struct in_addr source,dhcp_packet *offer_packet){ * DHCPOFFER from. If 'serv_ident' isn't available for some reason, we * use 'source'. */ - new_offer->server_address=serv_ident.s_addr?serv_ident:source; - new_offer->offered_address=offer_packet->yiaddr; - new_offer->lease_time=dhcp_lease_time; - new_offer->renewal_time=dhcp_renewal_time; - new_offer->rebinding_time=dhcp_rebinding_time; - new_offer->desired=false; /* exclusive mode: we'll check that in get_results */ - - - if(verbose){ - printf(_("Added offer from server @ %s"),inet_ntoa(new_offer->server_address)); - printf(_(" of IP address %s\n"),inet_ntoa(new_offer->offered_address)); + new_offer->server_address = serv_ident.s_addr ? serv_ident : source; + new_offer->offered_address = offer_packet->yiaddr; + new_offer->lease_time = dhcp_lease_time; + new_offer->renewal_time = dhcp_renewal_time; + new_offer->rebinding_time = dhcp_rebinding_time; + new_offer->desired = false; /* exclusive mode: we'll check that in get_results */ + + if (verbose) { + printf(_("Added offer from server @ %s"), inet_ntoa(new_offer->server_address)); + printf(_(" of IP address %s\n"), inet_ntoa(new_offer->offered_address)); } /* add new offer to head of list */ - new_offer->next=dhcp_offer_list; - dhcp_offer_list=new_offer; + new_offer->next = dhcp_offer_list; + dhcp_offer_list = new_offer; return OK; } - /* frees memory allocated to DHCP OFFER list */ -int free_dhcp_offer_list(void){ +int free_dhcp_offer_list(void) { dhcp_offer *this_offer; dhcp_offer *next_offer; - for(this_offer=dhcp_offer_list;this_offer!=NULL;this_offer=next_offer){ - next_offer=this_offer->next; + for (this_offer = dhcp_offer_list; this_offer != NULL; this_offer = next_offer) { + next_offer = this_offer->next; free(this_offer); } return OK; } - /* frees memory allocated to requested server list */ -int free_requested_server_list(void){ +int free_requested_server_list(void) { requested_server *this_server; requested_server *next_server; - for(this_server=requested_server_list;this_server!=NULL;this_server=next_server){ - next_server=this_server->next; + for (this_server = requested_server_list; this_server != NULL; this_server = next_server) { + next_server = this_server->next; free(this_server); } return OK; } - /* gets state and plugin output to return */ -int get_results(void){ - dhcp_offer *temp_offer, *undesired_offer=NULL; +int get_results(void) { + dhcp_offer *temp_offer, *undesired_offer = NULL; requested_server *temp_server; int result; - uint32_t max_lease_time=0; + uint32_t max_lease_time = 0; - received_requested_address=false; + received_requested_address = false; /* checks responses from requested servers */ - requested_responses=0; - if(requested_servers>0){ + requested_responses = 0; + if (requested_servers > 0) { - for(temp_server=requested_server_list;temp_server!=NULL;temp_server=temp_server->next){ + for (temp_server = requested_server_list; temp_server != NULL; temp_server = temp_server->next) { - for(temp_offer=dhcp_offer_list;temp_offer!=NULL;temp_offer=temp_offer->next){ + for (temp_offer = dhcp_offer_list; temp_offer != NULL; temp_offer = temp_offer->next) { /* get max lease time we were offered */ - if(temp_offer->lease_time>max_lease_time || temp_offer->lease_time==DHCP_INFINITE_TIME) - max_lease_time=temp_offer->lease_time; + if (temp_offer->lease_time > max_lease_time || temp_offer->lease_time == DHCP_INFINITE_TIME) + max_lease_time = temp_offer->lease_time; /* see if we got the address we requested */ - if(!memcmp(&requested_address,&temp_offer->offered_address,sizeof(requested_address))) - received_requested_address=true; + if (!memcmp(&requested_address, &temp_offer->offered_address, sizeof(requested_address))) + received_requested_address = true; /* see if the servers we wanted a response from talked to us or not */ - if(!memcmp(&temp_offer->server_address,&temp_server->server_address,sizeof(temp_server->server_address))){ - if(verbose){ - printf(_("DHCP Server Match: Offerer=%s"),inet_ntoa(temp_offer->server_address)); - printf(_(" Requested=%s"),inet_ntoa(temp_server->server_address)); - if(temp_server->answered) + if (!memcmp(&temp_offer->server_address, &temp_server->server_address, sizeof(temp_server->server_address))) { + if (verbose) { + printf(_("DHCP Server Match: Offerer=%s"), inet_ntoa(temp_offer->server_address)); + printf(_(" Requested=%s"), inet_ntoa(temp_server->server_address)); + if (temp_server->answered) printf(_(" (duplicate)")); printf(_("\n")); } - if(!temp_server->answered){ + if (!temp_server->answered) { requested_responses++; - temp_server->answered=true; - temp_offer->desired=true; + temp_server->answered = true; + temp_offer->desired = true; } } } } /* exclusive mode: check for undesired offers */ - for(temp_offer=dhcp_offer_list;temp_offer!=NULL;temp_offer=temp_offer->next) { + for (temp_offer = dhcp_offer_list; temp_offer != NULL; temp_offer = temp_offer->next) { if (!temp_offer->desired) { - undesired_offer=temp_offer; /* Checks only for the first undesired offer */ - break; /* no further checks needed */ + undesired_offer = temp_offer; /* Checks only for the first undesired offer */ + break; /* no further checks needed */ } } } /* else check and see if we got our requested address from any server */ - else{ + else { - for(temp_offer=dhcp_offer_list;temp_offer!=NULL;temp_offer=temp_offer->next){ + for (temp_offer = dhcp_offer_list; temp_offer != NULL; temp_offer = temp_offer->next) { /* get max lease time we were offered */ - if(temp_offer->lease_time>max_lease_time || temp_offer->lease_time==DHCP_INFINITE_TIME) - max_lease_time=temp_offer->lease_time; + if (temp_offer->lease_time > max_lease_time || temp_offer->lease_time == DHCP_INFINITE_TIME) + max_lease_time = temp_offer->lease_time; /* see if we got the address we requested */ - if(!memcmp(&requested_address,&temp_offer->offered_address,sizeof(requested_address))) - received_requested_address=true; + if (!memcmp(&requested_address, &temp_offer->offered_address, sizeof(requested_address))) + received_requested_address = true; } } - result=STATE_OK; - if(valid_responses==0) - result=STATE_CRITICAL; - else if(requested_servers>0 && requested_responses==0) - result=STATE_CRITICAL; - else if(requested_responses 0 && requested_responses == 0) + result = STATE_CRITICAL; + else if (requested_responses < requested_servers) + result = STATE_WARNING; + else if (request_specific_address && !received_requested_address) + result = STATE_WARNING; - if(exclusive && undesired_offer) - result=STATE_CRITICAL; + if (exclusive && undesired_offer) + result = STATE_CRITICAL; - if(result==0) /* garrett honeycutt 2005 */ + if (result == 0) /* garrett honeycutt 2005 */ printf("OK: "); - else if(result==1) + else if (result == 1) printf("WARNING: "); - else if(result==2) + else if (result == 2) printf("CRITICAL: "); - else if(result==3) + else if (result == 3) printf("UNKNOWN: "); /* we didn't receive any DHCPOFFERs */ - if(dhcp_offer_list==NULL){ + if (dhcp_offer_list == NULL) { printf(_("No DHCPOFFERs were received.\n")); return result; } - printf(_("Received %d DHCPOFFER(s)"),valid_responses); - + printf(_("Received %d DHCPOFFER(s)"), valid_responses); - if(exclusive && undesired_offer){ - printf(_(", Rogue DHCP Server detected! Server %s"),inet_ntoa(undesired_offer->server_address)); - printf(_(" offered %s \n"),inet_ntoa(undesired_offer->offered_address)); + if (exclusive && undesired_offer) { + printf(_(", Rogue DHCP Server detected! Server %s"), inet_ntoa(undesired_offer->server_address)); + printf(_(" offered %s \n"), inet_ntoa(undesired_offer->offered_address)); return result; } - if(requested_servers>0) - printf(_(", %s%d of %d requested servers responded"),((requested_responses0)?"only ":"",requested_responses,requested_servers); + if (requested_servers > 0) + printf(_(", %s%d of %d requested servers responded"), ((requested_responses < requested_servers) && requested_responses > 0) ? "only " : "", requested_responses, + requested_servers); - if(request_specific_address) - printf(_(", requested address (%s) was %soffered"),inet_ntoa(requested_address),(received_requested_address)?"":_("not ")); + if (request_specific_address) + printf(_(", requested address (%s) was %soffered"), inet_ntoa(requested_address), (received_requested_address) ? "" : _("not ")); printf(_(", max lease time = ")); - if(max_lease_time==DHCP_INFINITE_TIME) + if (max_lease_time == DHCP_INFINITE_TIME) printf(_("Infinity")); else - printf("%lu sec",(unsigned long)max_lease_time); + printf("%lu sec", (unsigned long)max_lease_time); printf(".\n"); return result; } - /* process command-line arguments */ -int process_arguments(int argc, char **argv){ - if(argc<1) +int process_arguments(int argc, char **argv) { + if (argc < 1) return ERROR; - call_getopt(argc,argv); + call_getopt(argc, argv); return validate_arguments(argc); } - - -int call_getopt(int argc, char **argv){ +int call_getopt(int argc, char **argv) { extern int optind; int option_index = 0; - static struct option long_options[] = - { - {"serverip", required_argument,0,'s'}, - {"requestedip", required_argument,0,'r'}, - {"timeout", required_argument,0,'t'}, - {"interface", required_argument,0,'i'}, - {"mac", required_argument,0,'m'}, - {"unicast", no_argument, 0,'u'}, - {"exclusive", no_argument, 0,'x'}, - {"verbose", no_argument, 0,'v'}, - {"version", no_argument, 0,'V'}, - {"help", no_argument, 0,'h'}, - {0,0,0,0} - }; - - int c=0; - while(true){ - c=getopt_long(argc,argv,"+hVvxt:s:r:t:i:m:u",long_options,&option_index); - - if(c==-1||c==EOF||c==1) + static struct option long_options[] = {{"serverip", required_argument, 0, 's'}, + {"requestedip", required_argument, 0, 'r'}, + {"timeout", required_argument, 0, 't'}, + {"interface", required_argument, 0, 'i'}, + {"mac", required_argument, 0, 'm'}, + {"unicast", no_argument, 0, 'u'}, + {"exclusive", no_argument, 0, 'x'}, + {"verbose", no_argument, 0, 'v'}, + {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {0, 0, 0, 0}}; + + int c = 0; + while (true) { + c = getopt_long(argc, argv, "+hVvxt:s:r:t:i:m:u", long_options, &option_index); + + if (c == -1 || c == EOF || c == 1) break; - switch(c){ - - case 's': /* DHCP server address */ - resolve_host(optarg,&dhcp_ip); - add_requested_server(dhcp_ip); - break; + switch (c) { - case 'r': /* address we are requested from DHCP servers */ - resolve_host(optarg,&requested_address); - request_specific_address=true; - break; + case 's': /* DHCP server address */ + resolve_host(optarg, &dhcp_ip); + add_requested_server(dhcp_ip); + break; - case 't': /* timeout */ + case 'r': /* address we are requested from DHCP servers */ + resolve_host(optarg, &requested_address); + request_specific_address = true; + break; - /* - if(is_intnonneg(optarg)) - */ - if(atoi(optarg)>0) - dhcpoffer_timeout=atoi(optarg); - /* - else - usage("Time interval must be a nonnegative integer\n"); - */ - break; + case 't': /* timeout */ + + /* + if(is_intnonneg(optarg)) + */ + if (atoi(optarg) > 0) + dhcpoffer_timeout = atoi(optarg); + /* + else + usage("Time interval must be a nonnegative integer\n"); + */ + break; - case 'm': /* MAC address */ + case 'm': /* MAC address */ - if((user_specified_mac=mac_aton(optarg)) == NULL) - usage("Cannot parse MAC address.\n"); - if(verbose) - print_hardware_address(user_specified_mac); + if ((user_specified_mac = mac_aton(optarg)) == NULL) + usage("Cannot parse MAC address.\n"); + if (verbose) + print_hardware_address(user_specified_mac); - break; + break; - case 'i': /* interface name */ + case 'i': /* interface name */ - strncpy(network_interface_name,optarg,sizeof(network_interface_name)-1); - network_interface_name[sizeof(network_interface_name)-1]='\x0'; + strncpy(network_interface_name, optarg, sizeof(network_interface_name) - 1); + network_interface_name[sizeof(network_interface_name) - 1] = '\x0'; - break; + break; - case 'u': /* unicast testing */ - unicast=true; - break; - case 'x': /* exclusive testing aka "rogue DHCP server detection" */ - exclusive=true; - break; + case 'u': /* unicast testing */ + unicast = true; + break; + case 'x': /* exclusive testing aka "rogue DHCP server detection" */ + exclusive = true; + break; - case 'V': /* version */ - print_revision(progname, NP_VERSION); - exit(STATE_UNKNOWN); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); - case 'h': /* help */ - print_help(); - exit(STATE_UNKNOWN); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); - case 'v': /* verbose */ - verbose=1; - break; - case '?': /* help */ - usage5 (); - break; + case 'v': /* verbose */ + verbose = 1; + break; + case '?': /* help */ + usage5(); + break; - default: - break; + default: + break; } } return optind; } +int validate_arguments(int argc) { -int validate_arguments(int argc){ - - if(argc - optind > 0) + if (argc - optind > 0) usage(_("Got unexpected non-option argument")); return OK; } - #if defined(__sun__) || defined(__solaris__) || defined(__hpux__) /* Kompf 2000-2003 see ACKNOWLEDGEMENTS */ /* get a message from a stream; return type of message */ -static int get_msg(int fd){ +static int get_msg(int fd) { int flags = 0; int res, ret; ctl_area[0] = 0; @@ -1190,30 +1145,29 @@ static int get_msg(int fd){ ret = 0; res = getmsg(fd, &ctl, &dat, &flags); - if(res < 0){ - if(errno == EINTR){ - return(GOT_INTR); - } - else{ + if (res < 0) { + if (errno == EINTR) { + return (GOT_INTR); + } else { printf("%s\n", "get_msg FAILED."); - return(GOT_ERR); + return (GOT_ERR); } } - if(ctl.len > 0){ + if (ctl.len > 0) { ret |= GOT_CTRL; } - if(dat.len > 0){ + if (dat.len > 0) { ret |= GOT_DATA; } - return(ret); + return (ret); } /* verify that dl_primitive in ctl_area = prim */ -static int check_ctrl(int prim){ +static int check_ctrl(int prim) { dl_error_ack_t *err_ack = (dl_error_ack_t *)ctl_area; - if(err_ack->dl_primitive != prim){ + if (err_ack->dl_primitive != prim) { printf(_("Error: DLPI stream API failed to get MAC in check_ctrl: %s.\n"), strerror(errno)); exit(STATE_UNKNOWN); } @@ -1222,35 +1176,35 @@ static int check_ctrl(int prim){ } /* put a control message on a stream */ -static int put_ctrl(int fd, int len, int pri){ +static int put_ctrl(int fd, int len, int pri) { ctl.len = len; - if(putmsg(fd, &ctl, 0, pri) < 0){ + if (putmsg(fd, &ctl, 0, pri) < 0) { printf(_("Error: DLPI stream API failed to get MAC in put_ctrl/putmsg(): %s.\n"), strerror(errno)); exit(STATE_UNKNOWN); } - return 0; + return 0; } /* put a control + data message on a stream */ -static int put_both(int fd, int clen, int dlen, int pri){ +static int put_both(int fd, int clen, int dlen, int pri) { ctl.len = clen; dat.len = dlen; - if(putmsg(fd, &ctl, &dat, pri) < 0){ + if (putmsg(fd, &ctl, &dat, pri) < 0) { printf(_("Error: DLPI stream API failed to get MAC in put_both/putmsg().\n"), strerror(errno)); exit(STATE_UNKNOWN); } - return 0; + return 0; } /* open file descriptor and attach */ -static int dl_open(const char *dev, int unit, int *fd){ +static int dl_open(const char *dev, int unit, int *fd) { dl_attach_req_t *attach_req = (dl_attach_req_t *)ctl_area; - if((*fd = open(dev, O_RDWR)) == -1){ + if ((*fd = open(dev, O_RDWR)) == -1) { printf(_("Error: DLPI stream API failed to get MAC in dl_attach_req/open(%s..): %s.\n"), dev, strerror(errno)); exit(STATE_UNKNOWN); } @@ -1262,7 +1216,7 @@ static int dl_open(const char *dev, int unit, int *fd){ } /* send DL_BIND_REQ */ -static int dl_bind(int fd, int sap, u_char *addr){ +static int dl_bind(int fd, int sap, u_char *addr) { dl_bind_req_t *bind_req = (dl_bind_req_t *)ctl_area; dl_bind_ack_t *bind_ack = (dl_bind_ack_t *)ctl_area; @@ -1274,12 +1228,11 @@ static int dl_bind(int fd, int sap, u_char *addr){ bind_req->dl_xidtest_flg = 0; put_ctrl(fd, sizeof(dl_bind_req_t), 0); get_msg(fd); - if (GOT_ERR == check_ctrl(DL_BIND_ACK)){ + if (GOT_ERR == check_ctrl(DL_BIND_ACK)) { printf(_("Error: DLPI stream API failed to get MAC in dl_bind/check_ctrl(): %s.\n"), strerror(errno)); exit(STATE_UNKNOWN); } - bcopy((u_char *)bind_ack + bind_ack->dl_addr_offset, addr, - bind_ack->dl_addr_length); + bcopy((u_char *)bind_ack + bind_ack->dl_addr_offset, addr, bind_ack->dl_addr_length); return 0; } @@ -1296,13 +1249,13 @@ static int dl_bind(int fd, int sap, u_char *addr){ * ***********************************************************************/ -long mac_addr_dlpi( const char *dev, int unit, u_char *addr){ +long mac_addr_dlpi(const char *dev, int unit, u_char *addr) { int fd; u_char mac_addr[25]; - if(GOT_ERR != dl_open(dev, unit, &fd)){ - if(GOT_ERR != dl_bind(fd, INSAP, mac_addr)){ - bcopy( mac_addr, addr, 6); + if (GOT_ERR != dl_open(dev, unit, &fd)) { + if (GOT_ERR != dl_bind(fd, INSAP, mac_addr)) { + bcopy(mac_addr, addr, 6); return 0; } } @@ -1314,99 +1267,93 @@ long mac_addr_dlpi( const char *dev, int unit, u_char *addr){ /* Kompf 2000-2003 */ #endif - /* resolve host name or die (TODO: move this to netutils.c!) */ -void resolve_host(const char *in,struct in_addr *out){ +void resolve_host(const char *in, struct in_addr *out) { struct addrinfo hints, *ai; - memset(&hints,0,sizeof(hints)); - hints.ai_family=PF_INET; - if (getaddrinfo(in,NULL,&hints,&ai) != 0) - usage_va(_("Invalid hostname/address - %s"),optarg); + memset(&hints, 0, sizeof(hints)); + hints.ai_family = PF_INET; + if (getaddrinfo(in, NULL, &hints, &ai) != 0) + usage_va(_("Invalid hostname/address - %s"), optarg); - memcpy(out,&((struct sockaddr_in *)ai->ai_addr)->sin_addr,sizeof(*out)); + memcpy(out, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, sizeof(*out)); freeaddrinfo(ai); } - /* parse MAC address string, return 6 bytes (unterminated) or NULL */ -unsigned char *mac_aton(const char *string){ +unsigned char *mac_aton(const char *string) { static unsigned char result[6]; char tmp[3]; unsigned i, j; - for(i=0, j=0; string[i] != '\0' && j < sizeof(result); i++){ + for (i = 0, j = 0; string[i] != '\0' && j < sizeof(result); i++) { /* ignore ':' and any other non-hex character */ - if(!isxdigit(string[i]) || !isxdigit(string[i+1])) + if (!isxdigit(string[i]) || !isxdigit(string[i + 1])) continue; - tmp[0]=string[i]; - tmp[1]=string[i+1]; - tmp[2]='\0'; - result[j]=strtol(tmp,(char **)NULL,16); + tmp[0] = string[i]; + tmp[1] = string[i + 1]; + tmp[2] = '\0'; + result[j] = strtol(tmp, (char **)NULL, 16); i++; j++; } - return (j==6) ? result : NULL; + return (j == 6) ? result : NULL; } - -void print_hardware_address(const unsigned char *address){ +void print_hardware_address(const unsigned char *address) { int i; printf(_("Hardware address: ")); - for (i=0; i<5; i++) + for (i = 0; i < 5; i++) printf("%2.2x:", address[i]); printf("%2.2x", address[i]); putchar('\n'); } - /* print usage help */ -void print_help(void){ +void print_help(void) { print_revision(progname, NP_VERSION); printf("Copyright (c) 2001-2004 Ethan Galstad (nagios@nagios.org)\n"); - printf (COPYRIGHT, copyright, email); + printf(COPYRIGHT, copyright, email); printf("%s\n", _("This plugin tests the availability of DHCP servers on a network.")); - printf ("\n\n"); + printf("\n\n"); print_usage(); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); - - printf (UT_VERBOSE); - - printf (" %s\n", "-s, --serverip=IPADDRESS"); - printf (" %s\n", _("IP address of DHCP server that we must hear from")); - printf (" %s\n", "-r, --requestedip=IPADDRESS"); - printf (" %s\n", _("IP address that should be offered by at least one DHCP server")); - printf (" %s\n", "-t, --timeout=INTEGER"); - printf (" %s\n", _("Seconds to wait for DHCPOFFER before timeout occurs")); - printf (" %s\n", "-i, --interface=STRING"); - printf (" %s\n", _("Interface to to use for listening (i.e. eth0)")); - printf (" %s\n", "-m, --mac=STRING"); - printf (" %s\n", _("MAC address to use in the DHCP request")); - printf (" %s\n", "-u, --unicast"); - printf (" %s\n", _("Unicast testing: mimic a DHCP relay, requires -s")); - printf (" %s\n", "-x, --exclusive"); - printf (" %s\n", _("Only requested DHCP server may response (rogue DHCP server detection), requires -s")); - - printf (UT_SUPPORT); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); + + printf(UT_VERBOSE); + + printf(" %s\n", "-s, --serverip=IPADDRESS"); + printf(" %s\n", _("IP address of DHCP server that we must hear from")); + printf(" %s\n", "-r, --requestedip=IPADDRESS"); + printf(" %s\n", _("IP address that should be offered by at least one DHCP server")); + printf(" %s\n", "-t, --timeout=INTEGER"); + printf(" %s\n", _("Seconds to wait for DHCPOFFER before timeout occurs")); + printf(" %s\n", "-i, --interface=STRING"); + printf(" %s\n", _("Interface to to use for listening (i.e. eth0)")); + printf(" %s\n", "-m, --mac=STRING"); + printf(" %s\n", _("MAC address to use in the DHCP request")); + printf(" %s\n", "-u, --unicast"); + printf(" %s\n", _("Unicast testing: mimic a DHCP relay, requires -s")); + printf(" %s\n", "-x, --exclusive"); + printf(" %s\n", _("Only requested DHCP server may response (rogue DHCP server detection), requires -s")); + + printf(UT_SUPPORT); return; } +void print_usage(void) { -void -print_usage(void){ - - printf ("%s\n", _("Usage:")); - printf (" %s [-v] [-u] [-x] [-s serverip] [-r requestedip] [-t timeout]\n",progname); - printf (" [-i interface] [-m mac]\n"); + printf("%s\n", _("Usage:")); + printf(" %s [-v] [-u] [-x] [-s serverip] [-r requestedip] [-t timeout]\n", progname); + printf(" [-i interface] [-m mac]\n"); return; } -- cgit v0.10-9-g596f From a0e2266c7554fae2ac62f4b57d4b987f339a11cb Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 15 Oct 2024 16:01:27 +0200 Subject: check_dhcp: Update copyright diff --git a/plugins-root/check_dhcp.c b/plugins-root/check_dhcp.c index 4f50a5c..657ddc1 100644 --- a/plugins-root/check_dhcp.c +++ b/plugins-root/check_dhcp.c @@ -4,7 +4,7 @@ * * License: GPL * Copyright (c) 2001-2004 Ethan Galstad (nagios@nagios.org) - * Copyright (c) 2001-2007 Monitoring Plugins Development Team + * Copyright (c) 2001-2023 Monitoring Plugins Development Team * * Description: * @@ -34,7 +34,7 @@ *****************************************************************************/ const char *progname = "check_dhcp"; -const char *copyright = "2001-2023"; +const char *copyright = "2001-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From cd4d59fbd4af00fbc95e35b68e47d194978db2ee Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 15 Oct 2024 16:07:58 +0200 Subject: check_dhcp: Declare internal variables static diff --git a/plugins-root/check_dhcp.c b/plugins-root/check_dhcp.c index 657ddc1..6802232 100644 --- a/plugins-root/check_dhcp.c +++ b/plugins-root/check_dhcp.c @@ -105,7 +105,7 @@ static int put_ctrl(int, int, int); static int put_both(int, int, int, int); static int dl_open(const char *, int, int *); static int dl_bind(int, int, u_char *); -long mac_addr_dlpi(const char *, int, u_char *); +static long mac_addr_dlpi(const char *, int, u_char *); #endif // __sun__ || __solaris__ || __hpux @@ -186,60 +186,60 @@ typedef struct requested_server_struct { #define ETHERNET_HARDWARE_ADDRESS 1 /* used in htype field of dhcp packet */ #define ETHERNET_HARDWARE_ADDRESS_LENGTH 6 /* length of Ethernet hardware addresses */ -bool unicast = false; /* unicast mode: mimic a DHCP relay */ -bool exclusive = false; /* exclusive mode aka "rogue DHCP server detection" */ -struct in_addr my_ip; /* our address (required for relay) */ -struct in_addr dhcp_ip; /* server to query (if in unicast mode) */ -unsigned char client_hardware_address[MAX_DHCP_CHADDR_LENGTH] = ""; -unsigned char *user_specified_mac = NULL; +static bool unicast = false; /* unicast mode: mimic a DHCP relay */ +static bool exclusive = false; /* exclusive mode aka "rogue DHCP server detection" */ +static struct in_addr my_ip; /* our address (required for relay) */ +static struct in_addr dhcp_ip; /* server to query (if in unicast mode) */ +static unsigned char client_hardware_address[MAX_DHCP_CHADDR_LENGTH] = ""; +static unsigned char *user_specified_mac = NULL; -char network_interface_name[IFNAMSIZ] = "eth0"; +static char network_interface_name[IFNAMSIZ] = "eth0"; -uint32_t packet_xid = 0; +static uint32_t packet_xid = 0; -uint32_t dhcp_lease_time = 0; -uint32_t dhcp_renewal_time = 0; -uint32_t dhcp_rebinding_time = 0; +static uint32_t dhcp_lease_time = 0; +static uint32_t dhcp_renewal_time = 0; +static uint32_t dhcp_rebinding_time = 0; -int dhcpoffer_timeout = 2; +static int dhcpoffer_timeout = 2; -dhcp_offer *dhcp_offer_list = NULL; -requested_server *requested_server_list = NULL; +static dhcp_offer *dhcp_offer_list = NULL; +static requested_server *requested_server_list = NULL; -int valid_responses = 0; /* number of valid DHCPOFFERs we received */ -int requested_servers = 0; -int requested_responses = 0; +static int valid_responses = 0; /* number of valid DHCPOFFERs we received */ +static int requested_servers = 0; +static int requested_responses = 0; -bool request_specific_address = false; -bool received_requested_address = false; -int verbose = 0; -struct in_addr requested_address; +static bool request_specific_address = false; +static bool received_requested_address = false; +static int verbose = 0; +static struct in_addr requested_address; -int process_arguments(int, char **); -int call_getopt(int, char **); -int validate_arguments(int); +static int process_arguments(int, char **); +static int call_getopt(int, char **); +static int validate_arguments(int); void print_usage(void); -void print_help(void); +static void print_help(void); -void resolve_host(const char *in, struct in_addr *out); -unsigned char *mac_aton(const char *); -void print_hardware_address(const unsigned char *); -int get_hardware_address(int, char *); -int get_ip_address(int, char *); +static void resolve_host(const char *in, struct in_addr *out); +static unsigned char *mac_aton(const char *); +static void print_hardware_address(const unsigned char *); +static int get_hardware_address(int, char *); +static int get_ip_address(int, char *); -int send_dhcp_discover(int); -int get_dhcp_offer(int); +static int send_dhcp_discover(int); +static int get_dhcp_offer(int); -int get_results(void); +static int get_results(void); -int add_dhcp_offer(struct in_addr, dhcp_packet *); -int free_dhcp_offer_list(void); -int free_requested_server_list(void); +static int add_dhcp_offer(struct in_addr, dhcp_packet *); +static int free_dhcp_offer_list(void); +static int free_requested_server_list(void); -int create_dhcp_socket(void); -int close_dhcp_socket(int); -int send_dhcp_packet(void *, int, int, struct sockaddr_in *); -int receive_dhcp_packet(void *, int, int, int, struct sockaddr_in *); +static int create_dhcp_socket(void); +static int close_dhcp_socket(int); +static int send_dhcp_packet(void *, int, int, struct sockaddr_in *); +static int receive_dhcp_packet(void *, int, int, int, struct sockaddr_in *); int main(int argc, char **argv) { int dhcp_socket; @@ -288,7 +288,7 @@ int main(int argc, char **argv) { } /* determines hardware address on client machine */ -int get_hardware_address(int sock, char *interface_name) { +static int get_hardware_address(int sock, char *interface_name) { #if defined(__linux__) struct ifreq ifr; @@ -400,7 +400,7 @@ int get_hardware_address(int sock, char *interface_name) { } /* determines IP address of the client interface */ -int get_ip_address(int sock, char *interface_name) { +static int get_ip_address(int sock, char *interface_name) { #if defined(SIOCGIFADDR) struct ifreq ifr; @@ -426,7 +426,7 @@ int get_ip_address(int sock, char *interface_name) { } /* sends a DHCPDISCOVER broadcast message in an attempt to find DHCP servers */ -int send_dhcp_discover(int sock) { +static int send_dhcp_discover(int sock) { dhcp_packet discover_packet; struct sockaddr_in sockaddr_broadcast; unsigned short opts; @@ -515,7 +515,7 @@ int send_dhcp_discover(int sock) { } /* waits for a DHCPOFFER message from one or more DHCP servers */ -int get_dhcp_offer(int sock) { +static int get_dhcp_offer(int sock) { dhcp_packet offer_packet; struct sockaddr_in source; struct sockaddr_in via; @@ -617,7 +617,7 @@ int get_dhcp_offer(int sock) { } /* sends a DHCP packet */ -int send_dhcp_packet(void *buffer, int buffer_size, int sock, struct sockaddr_in *dest) { +static int send_dhcp_packet(void *buffer, int buffer_size, int sock, struct sockaddr_in *dest) { int result; result = sendto(sock, (char *)buffer, buffer_size, 0, (struct sockaddr *)dest, sizeof(*dest)); @@ -632,7 +632,7 @@ int send_dhcp_packet(void *buffer, int buffer_size, int sock, struct sockaddr_in } /* receives a DHCP packet */ -int receive_dhcp_packet(void *buffer, int buffer_size, int sock, int timeout, struct sockaddr_in *address) { +static int receive_dhcp_packet(void *buffer, int buffer_size, int sock, int timeout, struct sockaddr_in *address) { struct timeval tv; fd_set readfds; fd_set oobfds; @@ -685,7 +685,7 @@ int receive_dhcp_packet(void *buffer, int buffer_size, int sock, int timeout, st } /* creates a socket for DHCP communication */ -int create_dhcp_socket(void) { +static int create_dhcp_socket(void) { struct sockaddr_in myname; struct ifreq interface; int sock; @@ -746,7 +746,7 @@ int create_dhcp_socket(void) { } /* closes DHCP socket */ -int close_dhcp_socket(int sock) { +static int close_dhcp_socket(int sock) { close(sock); @@ -754,7 +754,7 @@ int close_dhcp_socket(int sock) { } /* adds a requested server address to list in memory */ -int add_requested_server(struct in_addr server_address) { +static int add_requested_server(struct in_addr server_address) { requested_server *new_server; new_server = (requested_server *)malloc(sizeof(requested_server)); @@ -776,7 +776,7 @@ int add_requested_server(struct in_addr server_address) { } /* adds a DHCP OFFER to list in memory */ -int add_dhcp_offer(struct in_addr source, dhcp_packet *offer_packet) { +static int add_dhcp_offer(struct in_addr source, dhcp_packet *offer_packet) { dhcp_offer *new_offer; int x; unsigned option_type; @@ -878,7 +878,7 @@ int add_dhcp_offer(struct in_addr source, dhcp_packet *offer_packet) { } /* frees memory allocated to DHCP OFFER list */ -int free_dhcp_offer_list(void) { +static int free_dhcp_offer_list(void) { dhcp_offer *this_offer; dhcp_offer *next_offer; @@ -891,7 +891,7 @@ int free_dhcp_offer_list(void) { } /* frees memory allocated to requested server list */ -int free_requested_server_list(void) { +static int free_requested_server_list(void) { requested_server *this_server; requested_server *next_server; @@ -904,7 +904,7 @@ int free_requested_server_list(void) { } /* gets state and plugin output to return */ -int get_results(void) { +static int get_results(void) { dhcp_offer *temp_offer, *undesired_offer = NULL; requested_server *temp_server; int result; @@ -1025,7 +1025,7 @@ int get_results(void) { } /* process command-line arguments */ -int process_arguments(int argc, char **argv) { +static int process_arguments(int argc, char **argv) { if (argc < 1) return ERROR; @@ -1033,7 +1033,7 @@ int process_arguments(int argc, char **argv) { return validate_arguments(argc); } -int call_getopt(int argc, char **argv) { +static int call_getopt(int argc, char **argv) { extern int optind; int option_index = 0; static struct option long_options[] = {{"serverip", required_argument, 0, 's'}, @@ -1125,7 +1125,7 @@ int call_getopt(int argc, char **argv) { return optind; } -int validate_arguments(int argc) { +static int validate_arguments(int argc) { if (argc - optind > 0) usage(_("Got unexpected non-option argument")); @@ -1249,7 +1249,7 @@ static int dl_bind(int fd, int sap, u_char *addr) { * ***********************************************************************/ -long mac_addr_dlpi(const char *dev, int unit, u_char *addr) { +static long mac_addr_dlpi(const char *dev, int unit, u_char *addr) { int fd; u_char mac_addr[25]; @@ -1268,7 +1268,7 @@ long mac_addr_dlpi(const char *dev, int unit, u_char *addr) { #endif /* resolve host name or die (TODO: move this to netutils.c!) */ -void resolve_host(const char *in, struct in_addr *out) { +static void resolve_host(const char *in, struct in_addr *out) { struct addrinfo hints, *ai; memset(&hints, 0, sizeof(hints)); @@ -1281,7 +1281,7 @@ void resolve_host(const char *in, struct in_addr *out) { } /* parse MAC address string, return 6 bytes (unterminated) or NULL */ -unsigned char *mac_aton(const char *string) { +static unsigned char *mac_aton(const char *string) { static unsigned char result[6]; char tmp[3]; unsigned i, j; @@ -1301,7 +1301,7 @@ unsigned char *mac_aton(const char *string) { return (j == 6) ? result : NULL; } -void print_hardware_address(const unsigned char *address) { +static void print_hardware_address(const unsigned char *address) { int i; printf(_("Hardware address: ")); @@ -1312,7 +1312,7 @@ void print_hardware_address(const unsigned char *address) { } /* print usage help */ -void print_help(void) { +static void print_help(void) { print_revision(progname, NP_VERSION); -- cgit v0.10-9-g596f From b95e3d7446f33784f0647dc5d60a4b2d0a750a8a Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 15 Oct 2024 16:25:19 +0200 Subject: check_ups: clang-format diff --git a/plugins/check_ups.c b/plugins/check_ups.c index 380ff3b..1d31329 100644 --- a/plugins/check_ups.c +++ b/plugins/check_ups.c @@ -141,7 +141,6 @@ int main(int argc, char **argv) { return STATE_CRITICAL; } - if (supported_options & UPS_STATUS) { ups_status = strdup(""); @@ -151,8 +150,7 @@ int main(int argc, char **argv) { if (config.status & UPSSTATUS_OFF) { xasprintf(&ups_status, "Off"); result = STATE_CRITICAL; - } else if ((config.status & (UPSSTATUS_OB | UPSSTATUS_LB)) == - (UPSSTATUS_OB | UPSSTATUS_LB)) { + } else if ((config.status & (UPSSTATUS_OB | UPSSTATUS_LB)) == (UPSSTATUS_OB | UPSSTATUS_LB)) { xasprintf(&ups_status, _("On Battery, Low Battery")); result = STATE_CRITICAL; } else { @@ -171,8 +169,7 @@ int main(int argc, char **argv) { xasprintf(&ups_status, "%s%s", ups_status, _(", Calibrating")); } if (config.status & UPSSTATUS_RB) { - xasprintf(&ups_status, "%s%s", ups_status, - _(", Replace Battery")); + xasprintf(&ups_status, "%s%s", ups_status, _(", Replace Battery")); result = max_state(result, STATE_WARNING); } if (config.status & UPSSTATUS_BYPASS) { @@ -233,24 +230,16 @@ int main(int argc, char **argv) { } if (config.check_variable == UPS_UTILITY) { - if (config.check_crit && - ups_utility_deviation >= config.critical_value) { + if (config.check_crit && ups_utility_deviation >= config.critical_value) { result = STATE_CRITICAL; - } else if (config.check_warn && - ups_utility_deviation >= config.warning_value) { + } else if (config.check_warn && ups_utility_deviation >= config.warning_value) { result = max_state(result, STATE_WARNING); } xasprintf(&data, "%s", - perfdata("voltage", (long)(1000 * ups_utility_voltage), - "mV", config.check_warn, - (long)(1000 * config.warning_value), - config.check_crit, - (long)(1000 * config.critical_value), true, 0, - false, 0)); + perfdata("voltage", (long)(1000 * ups_utility_voltage), "mV", config.check_warn, (long)(1000 * config.warning_value), config.check_crit, + (long)(1000 * config.critical_value), true, 0, false, 0)); } else { - xasprintf(&data, "%s", - perfdata("voltage", (long)(1000 * ups_utility_voltage), - "mV", false, 0, false, 0, true, 0, false, 0)); + xasprintf(&data, "%s", perfdata("voltage", (long)(1000 * ups_utility_voltage), "mV", false, 0, false, 0, true, 0, false, 0)); } } @@ -268,22 +257,16 @@ int main(int argc, char **argv) { xasprintf(&message, "%sBatt=%3.1f%% ", message, ups_battery_percent); if (config.check_variable == UPS_BATTPCT) { - if (config.check_crit && - ups_battery_percent <= config.critical_value) { + if (config.check_crit && ups_battery_percent <= config.critical_value) { result = STATE_CRITICAL; - } else if (config.check_warn && - ups_battery_percent <= config.warning_value) { + } else if (config.check_warn && ups_battery_percent <= config.warning_value) { result = max_state(result, STATE_WARNING); } xasprintf(&data, "%s %s", data, - perfdata("battery", (long)ups_battery_percent, "%", - config.check_warn, (long)(config.warning_value), - config.check_crit, (long)(config.critical_value), - true, 0, true, 100)); + perfdata("battery", (long)ups_battery_percent, "%", config.check_warn, (long)(config.warning_value), config.check_crit, (long)(config.critical_value), true, + 0, true, 100)); } else { - xasprintf(&data, "%s %s", data, - perfdata("battery", (long)ups_battery_percent, "%", false, - 0, false, 0, true, 0, true, 100)); + xasprintf(&data, "%s %s", data, perfdata("battery", (long)ups_battery_percent, "%", false, 0, false, 0, true, 0, true, 100)); } } @@ -301,22 +284,16 @@ int main(int argc, char **argv) { xasprintf(&message, "%sLoad=%3.1f%% ", message, ups_load_percent); if (config.check_variable == UPS_LOADPCT) { - if (config.check_crit && - ups_load_percent >= config.critical_value) { + if (config.check_crit && ups_load_percent >= config.critical_value) { result = STATE_CRITICAL; - } else if (config.check_warn && - ups_load_percent >= config.warning_value) { + } else if (config.check_warn && ups_load_percent >= config.warning_value) { result = max_state(result, STATE_WARNING); } xasprintf(&data, "%s %s", data, - perfdata("load", (long)ups_load_percent, "%", - config.check_warn, (long)(config.warning_value), - config.check_crit, (long)(config.critical_value), - true, 0, true, 100)); + perfdata("load", (long)ups_load_percent, "%", config.check_warn, (long)(config.warning_value), config.check_crit, (long)(config.critical_value), true, 0, + true, 100)); } else { - xasprintf(&data, "%s %s", data, - perfdata("load", (long)ups_load_percent, "%", false, 0, - false, 0, true, 0, true, 100)); + xasprintf(&data, "%s %s", data, perfdata("load", (long)ups_load_percent, "%", false, 0, false, 0, true, 0, true, 100)); } } @@ -345,19 +322,14 @@ int main(int argc, char **argv) { if (config.check_variable == UPS_TEMP) { if (config.check_crit && ups_temperature >= config.critical_value) { result = STATE_CRITICAL; - } else if (config.check_warn && - ups_temperature >= config.warning_value) { + } else if (config.check_warn && ups_temperature >= config.warning_value) { result = max_state(result, STATE_WARNING); } xasprintf(&data, "%s %s", data, - perfdata("temp", (long)ups_temperature, tunits, - config.check_warn, (long)(config.warning_value), - config.check_crit, (long)(config.critical_value), - true, 0, false, 0)); + perfdata("temp", (long)ups_temperature, tunits, config.check_warn, (long)(config.warning_value), config.check_crit, (long)(config.critical_value), true, 0, + false, 0)); } else { - xasprintf(&data, "%s %s", data, - perfdata("temp", (long)ups_temperature, tunits, false, 0, - false, 0, true, 0, false, 0)); + xasprintf(&data, "%s %s", data, perfdata("temp", (long)ups_temperature, tunits, false, 0, false, 0, true, 0, false, 0)); } } @@ -376,19 +348,14 @@ int main(int argc, char **argv) { if (config.check_variable == UPS_REALPOWER) { if (config.check_crit && ups_realpower >= config.critical_value) { result = STATE_CRITICAL; - } else if (config.check_warn && - ups_realpower >= config.warning_value) { + } else if (config.check_warn && ups_realpower >= config.warning_value) { result = max_state(result, STATE_WARNING); } xasprintf(&data, "%s %s", data, - perfdata("realpower", (long)ups_realpower, "W", - config.check_warn, (long)(config.warning_value), - config.check_crit, (long)(config.critical_value), - true, 0, false, 0)); + perfdata("realpower", (long)ups_realpower, "W", config.check_warn, (long)(config.warning_value), config.check_crit, (long)(config.critical_value), true, 0, + false, 0)); } else { - xasprintf(&data, "%s %s", data, - perfdata("realpower", (long)ups_realpower, "W", false, 0, - false, 0, true, 0, false, 0)); + xasprintf(&data, "%s %s", data, perfdata("realpower", (long)ups_realpower, "W", false, 0, false, 0, true, 0, false, 0)); } } @@ -425,8 +392,7 @@ int determine_status(ups_config *config, int *supported_options) { char temp_buffer[MAX_INPUT_BUFFER]; strcpy(temp_buffer, recv_buffer); - for (char *ptr = (char *)strtok(temp_buffer, " "); ptr != NULL; - ptr = (char *)strtok(NULL, " ")) { + for (char *ptr = (char *)strtok(temp_buffer, " "); ptr != NULL; ptr = (char *)strtok(NULL, " ")) { if (!strcmp(ptr, "OFF")) { config->status |= UPSSTATUS_OFF; } else if (!strcmp(ptr, "OL")) { @@ -467,8 +433,7 @@ int get_ups_variable(const char *varname, char *buf, const ups_config config) { /* create the command string to send to the UPS daemon */ /* Add LOGOUT to avoid read failure logs */ - int res = snprintf(send_buffer, sizeof(send_buffer), - "GET VAR %s %s\nLOGOUT\n", config.ups_name, varname); + int res = snprintf(send_buffer, sizeof(send_buffer), "GET VAR %s %s\nLOGOUT\n", config.ups_name, varname); if ((res > 0) && ((size_t)res >= sizeof(send_buffer))) { printf("%s\n", _("UPS name to long for buffer")); return ERROR; @@ -477,9 +442,7 @@ int get_ups_variable(const char *varname, char *buf, const ups_config config) { char temp_buffer[MAX_INPUT_BUFFER]; /* send the command to the daemon and get a response back */ - if (process_tcp_request(config.server_address, config.server_port, - send_buffer, temp_buffer, - sizeof(temp_buffer)) != STATE_OK) { + if (process_tcp_request(config.server_address, config.server_port, send_buffer, temp_buffer, sizeof(temp_buffer)) != STATE_OK) { printf("%s\n", _("Invalid response received from host")); return ERROR; } @@ -496,8 +459,7 @@ int get_ups_variable(const char *varname, char *buf, const ups_config config) { ptr[len - 1] = 0; } if (strcmp(ptr, "ERR UNKNOWN-UPS") == 0) { - printf(_("CRITICAL - no such UPS '%s' on that host\n"), - config.ups_name); + printf(_("CRITICAL - no such UPS '%s' on that host\n"), config.ups_name); return ERROR; } @@ -694,8 +656,7 @@ void print_help(void) { printf(" %s\n", "-T, --temperature"); printf(" %s\n", _("Output of temperatures in Celsius")); printf(" %s\n", "-v, --variable=STRING"); - printf(" %s %s\n", _("Valid values for STRING are"), - "LINE, TEMP, BATTPCT, LOADPCT or REALPOWER"); + printf(" %s %s\n", _("Valid values for STRING are"), "LINE, TEMP, BATTPCT, LOADPCT or REALPOWER"); printf(UT_WARN_CRIT); @@ -731,8 +692,7 @@ void print_help(void) { "with Russell Kroll's")); printf(" %s\n", _("Network UPS Tools be installed on the remote host. If " "you do not have the")); - printf(" %s\n", - _("package installed on your system, you can download it from")); + printf(" %s\n", _("package installed on your system, you can download it from")); printf(" %s\n", _("http://www.networkupstools.org")); printf(UT_SUPPORT); -- cgit v0.10-9-g596f From 3f7c533ce87c764ff5278e18cec84b06e221b1c5 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Tue, 15 Oct 2024 16:26:21 +0200 Subject: check_ups: Update copyright diff --git a/plugins/check_ups.c b/plugins/check_ups.c index 1d31329..e5badc8 100644 --- a/plugins/check_ups.c +++ b/plugins/check_ups.c @@ -6,7 +6,7 @@ * Copyright (c) 2000 Tom Shields * 2004 Alain Richard * 2004 Arnaud Quette - * Copyright (c) 2002-2023 Monitoring Plugins Development Team + * Copyright (c) 2002-2024 Monitoring Plugins Development Team * * Description: * @@ -33,7 +33,7 @@ *****************************************************************************/ const char *progname = "check_ups"; -const char *copyright = "2000-2023"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From dd649f629e4846313a3dc89fcae72a420f258be4 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Wed, 16 Oct 2024 00:11:17 +0200 Subject: clang-format: Put all enum values in a single line diff --git a/.clang-format b/.clang-format index c7f0b5e..e7869da 100644 --- a/.clang-format +++ b/.clang-format @@ -8,3 +8,4 @@ AlignConsecutiveMacros: true ColumnLimit: 180 IndentPPDirectives: AfterHash SortIncludes: Never +AllowShortEnumsOnASingleLine: false -- cgit v0.10-9-g596f From aa1f9c50118d63f7229523655a1fab28fd0eab24 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Wed, 16 Oct 2024 00:11:39 +0200 Subject: check_icmp: clang-format diff --git a/plugins-root/check_icmp.c b/plugins-root/check_icmp.c index 2fd92cd..6eefeb0 100644 --- a/plugins-root/check_icmp.c +++ b/plugins-root/check_icmp.c @@ -175,7 +175,13 @@ typedef union icmp_packet { #define MODE_ALL 2 #define MODE_ICMP 3 -enum enum_threshold_mode { const_rta_mode, const_packet_loss_mode, const_jitter_mode, const_mos_mode, const_score_mode }; +enum enum_threshold_mode { + const_rta_mode, + const_packet_loss_mode, + const_jitter_mode, + const_mos_mode, + const_score_mode +}; typedef enum enum_threshold_mode threshold_mode; -- cgit v0.10-9-g596f From ee1ba3209993b72e90f5fe30a16ad951f1e2402d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= Date: Thu, 17 Oct 2024 17:57:50 +0200 Subject: lib: clang-format diff --git a/lib/extra_opts.c b/lib/extra_opts.c index 771621d..82460e9 100644 --- a/lib/extra_opts.c +++ b/lib/extra_opts.c @@ -1,24 +1,24 @@ /***************************************************************************** -* -* Monitoring Plugins extra_opts library -* -* License: GPL -* Copyright (c) 2007 Monitoring Plugins Development Team -* -* 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 Plugins extra_opts library + * + * License: GPL + * Copyright (c) 2007 Monitoring Plugins Development Team + * + * 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 . + * + *****************************************************************************/ #include "common.h" #include "utils_base.h" @@ -26,110 +26,115 @@ #include "extra_opts.h" /* FIXME: copied from utils.h; we should move a bunch of libs! */ -bool is_option2 (char *str) -{ +bool is_option2(char *str) { if (!str) return false; - else if (strspn (str, "-") == 1 || strspn (str, "-") == 2) + else if (strspn(str, "-") == 1 || strspn(str, "-") == 2) return true; else return false; } /* this is the externally visible function used by plugins */ -char **np_extra_opts(int *argc, char **argv, const char *plugin_name){ - np_arg_list *extra_args=NULL, *ea1=NULL, *ea_tmp=NULL; - char **argv_new=NULL; - char *argptr=NULL; - int i, j, optfound, argc_new, ea_num=*argc; +char **np_extra_opts(int *argc, char **argv, const char *plugin_name) { + np_arg_list *extra_args = NULL, *ea1 = NULL, *ea_tmp = NULL; + char **argv_new = NULL; + char *argptr = NULL; + int i, j, optfound, argc_new, ea_num = *argc; - if(*argc<2) { + if (*argc < 2) { /* No arguments provided */ return argv; } - for(i=1; i<*argc; i++){ - argptr=NULL; - optfound=0; + for (i = 1; i < *argc; i++) { + argptr = NULL; + optfound = 0; /* Do we have an extra-opts parameter? */ - if(strncmp(argv[i], "--extra-opts=", 13)==0){ + if (strncmp(argv[i], "--extra-opts=", 13) == 0) { /* It is a single argument with value */ - argptr=argv[i]+13; + argptr = argv[i] + 13; /* Delete the extra opts argument */ - for(j=i;j<*argc;j++) argv[j]=argv[j+1]; + for (j = i; j < *argc; j++) + argv[j] = argv[j + 1]; i--; - *argc-=1; - }else if(strcmp(argv[i], "--extra-opts")==0){ - if((i+1<*argc)&&!is_option2(argv[i+1])){ + *argc -= 1; + } else if (strcmp(argv[i], "--extra-opts") == 0) { + if ((i + 1 < *argc) && !is_option2(argv[i + 1])) { /* It is a argument with separate value */ - argptr=argv[i+1]; + argptr = argv[i + 1]; /* Delete the extra-opts argument/value */ - for(j=i;j<*argc-1;j++) argv[j]=argv[j+2]; - i-=2; - *argc-=2; + for (j = i; j < *argc - 1; j++) + argv[j] = argv[j + 2]; + i -= 2; + *argc -= 2; ea_num--; - }else{ + } else { /* It has no value */ - optfound=1; + optfound = 1; /* Delete the extra opts argument */ - for(j=i;j<*argc;j++) argv[j]=argv[j+1]; + for (j = i; j < *argc; j++) + argv[j] = argv[j + 1]; i--; - *argc-=1; + *argc -= 1; } } /* If we found extra-opts, expand them and store them for later*/ - if(argptr||optfound){ + if (argptr || optfound) { /* Process ini section, returning a linked list of arguments */ - ea1=np_get_defaults(argptr, plugin_name); - if(ea1==NULL) { + ea1 = np_get_defaults(argptr, plugin_name); + if (ea1 == NULL) { /* no extra args (empty section)? */ ea_num--; continue; } /* append the list to extra_args */ - if(extra_args==NULL){ - extra_args=ea1; - while((ea1 = ea1->next)) ea_num++; - }else{ - ea_tmp=extra_args; - while(ea_tmp->next) { - ea_tmp=ea_tmp->next; + if (extra_args == NULL) { + extra_args = ea1; + while ((ea1 = ea1->next)) + ea_num++; + } else { + ea_tmp = extra_args; + while (ea_tmp->next) { + ea_tmp = ea_tmp->next; } - ea_tmp->next=ea1; - while((ea1 = ea1->next)) ea_num++; + ea_tmp->next = ea1; + while ((ea1 = ea1->next)) + ea_num++; } - ea1=ea_tmp=NULL; + ea1 = ea_tmp = NULL; } } /* lather, rince, repeat */ - if(ea_num==*argc && extra_args==NULL){ + if (ea_num == *argc && extra_args == NULL) { /* No extra-opts */ return argv; } /* done processing arguments. now create a new argv array... */ - argv_new=(char**)malloc((ea_num+1)*sizeof(char**)); - if(argv_new==NULL) die(STATE_UNKNOWN, _("malloc() failed!\n")); + argv_new = (char **)malloc((ea_num + 1) * sizeof(char **)); + if (argv_new == NULL) + die(STATE_UNKNOWN, _("malloc() failed!\n")); /* starting with program name */ - argv_new[0]=argv[0]; - argc_new=1; + argv_new[0] = argv[0]; + argc_new = 1; /* then parsed ini opts (frying them up in the same run) */ - while(extra_args){ - argv_new[argc_new++]=extra_args->arg; - ea1=extra_args; - extra_args=extra_args->next; + while (extra_args) { + argv_new[argc_new++] = extra_args->arg; + ea1 = extra_args; + extra_args = extra_args->next; free(ea1); } /* finally the rest of the argv array */ - for (i=1; i<*argc; i++) argv_new[argc_new++]=argv[i]; - *argc=argc_new; + for (i = 1; i < *argc; i++) + argv_new[argc_new++] = argv[i]; + *argc = argc_new; /* and terminate. */ - argv_new[argc_new]=NULL; + argv_new[argc_new] = NULL; return argv_new; } - diff --git a/lib/extra_opts.h b/lib/extra_opts.h index 8ff14a1..3f64360 100644 --- a/lib/extra_opts.h +++ b/lib/extra_opts.h @@ -20,4 +20,3 @@ char **np_extra_opts(int *argc, char **argv, const char *plugin_name); #endif /* _EXTRA_OPTS_H_ */ - diff --git a/lib/maxfd.c b/lib/maxfd.c index 529b356..c39d427 100644 --- a/lib/maxfd.c +++ b/lib/maxfd.c @@ -1,7 +1,7 @@ #include "./maxfd.h" #include -long mp_open_max (void) { +long mp_open_max(void) { long maxfd = 0L; /* Try sysconf(_SC_OPEN_MAX) first, as it can be higher than OPEN_MAX. * If that fails and the macro isn't defined, we fall back to an educated @@ -10,17 +10,17 @@ long mp_open_max (void) { #ifdef _SC_OPEN_MAX errno = 0; - if ((maxfd = sysconf (_SC_OPEN_MAX)) < 0) { + if ((maxfd = sysconf(_SC_OPEN_MAX)) < 0) { if (errno == 0) - maxfd = DEFAULT_MAXFD; /* it's indeterminate */ + maxfd = DEFAULT_MAXFD; /* it's indeterminate */ else - die (STATE_UNKNOWN, _("sysconf error for _SC_OPEN_MAX\n")); + die(STATE_UNKNOWN, _("sysconf error for _SC_OPEN_MAX\n")); } #elif defined(OPEN_MAX) return OPEN_MAX -#else /* sysconf macro unavailable, so guess (may be wildly inaccurate) */ +#else /* sysconf macro unavailable, so guess (may be wildly inaccurate) */ return DEFAULT_MAXFD; #endif - return(maxfd); + return (maxfd); } diff --git a/lib/maxfd.h b/lib/maxfd.h index 45218d0..8fcd62d 100644 --- a/lib/maxfd.h +++ b/lib/maxfd.h @@ -1,9 +1,9 @@ #ifndef _MAXFD_ #define _MAXFD_ -#define DEFAULT_MAXFD 256 /* fallback value if no max open files value is set */ -#define MAXFD_LIMIT 8192 /* upper limit of open files */ +#define DEFAULT_MAXFD 256 /* fallback value if no max open files value is set */ +#define MAXFD_LIMIT 8192 /* upper limit of open files */ -long mp_open_max (void); +long mp_open_max(void); #endif // _MAXFD_ diff --git a/lib/parse_ini.c b/lib/parse_ini.c index 09c0dc4..150df7b 100644 --- a/lib/parse_ini.c +++ b/lib/parse_ini.c @@ -1,25 +1,25 @@ /***************************************************************************** -* -* Monitoring Plugins parse_ini library -* -* License: GPL -* Copyright (c) 2007 Monitoring Plugins Development Team -* -* 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 Plugins parse_ini library + * + * License: GPL + * Copyright (c) 2007 Monitoring Plugins Development Team + * + * 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 . + * + * + *****************************************************************************/ #include "common.h" #include "idpriv.h" @@ -40,31 +40,19 @@ typedef struct { char *stanza; } np_ini_info; -static char *default_ini_file_names[] = { - "monitoring-plugins.ini", - "plugins.ini", - "nagios-plugins.ini", - NULL -}; - -static char *default_ini_path_names[] = { - "/usr/local/etc/monitoring-plugins/monitoring-plugins.ini", - "/usr/local/etc/monitoring-plugins.ini", - "/etc/monitoring-plugins/monitoring-plugins.ini", - "/etc/monitoring-plugins.ini", - /* deprecated path names (for backward compatibility): */ - "/etc/nagios/plugins.ini", - "/usr/local/nagios/etc/plugins.ini", - "/usr/local/etc/nagios/plugins.ini", - "/etc/opt/nagios/plugins.ini", - "/etc/nagios-plugins.ini", - "/usr/local/etc/nagios-plugins.ini", - "/etc/opt/nagios-plugins.ini", - NULL -}; +static char *default_ini_file_names[] = {"monitoring-plugins.ini", "plugins.ini", "nagios-plugins.ini", NULL}; + +static char *default_ini_path_names[] = {"/usr/local/etc/monitoring-plugins/monitoring-plugins.ini", "/usr/local/etc/monitoring-plugins.ini", + "/etc/monitoring-plugins/monitoring-plugins.ini", "/etc/monitoring-plugins.ini", + /* deprecated path names (for backward compatibility): */ + "/etc/nagios/plugins.ini", "/usr/local/nagios/etc/plugins.ini", "/usr/local/etc/nagios/plugins.ini", "/etc/opt/nagios/plugins.ini", + "/etc/nagios-plugins.ini", "/usr/local/etc/nagios-plugins.ini", "/etc/opt/nagios-plugins.ini", NULL}; /* eat all characters from a FILE pointer until n is encountered */ -#define GOBBLE_TO(f, c, n) do { (c)=fgetc((f)); } while((c)!=EOF && (c)!=(n)) +#define GOBBLE_TO(f, c, n) \ + do { \ + (c) = fgetc((f)); \ + } while ((c) != EOF && (c) != (n)) /* internal function that returns the constructed defaults options */ static int read_defaults(FILE *f, const char *stanza, np_arg_list **opts); @@ -81,9 +69,7 @@ static char *default_file_in_path(void); * [stanza][@filename] * into its separate parts. */ -static void -parse_locator(const char *locator, const char *def_stanza, np_ini_info *i) -{ +static void parse_locator(const char *locator, const char *def_stanza, np_ini_info *i) { size_t locator_len = 0, stanza_len = 0; /* if locator is NULL we'll use default values */ @@ -96,7 +82,7 @@ parse_locator(const char *locator, const char *def_stanza, np_ini_info *i) i->stanza = malloc(sizeof(char) * (stanza_len + 1)); strncpy(i->stanza, locator, stanza_len); i->stanza[stanza_len] = '\0'; - } else {/* otherwise we use the default stanza */ + } else { /* otherwise we use the default stanza */ i->stanza = strdup(def_stanza); } @@ -105,7 +91,7 @@ parse_locator(const char *locator, const char *def_stanza, np_ini_info *i) /* check whether there's an @file part */ if (stanza_len == locator_len) { - i->file = default_file(); + i->file = default_file(); i->file_string_on_heap = false; } else { i->file = strdup(&(locator[stanza_len + 1])); @@ -113,35 +99,28 @@ parse_locator(const char *locator, const char *def_stanza, np_ini_info *i) } if (i->file == NULL || i->file[0] == '\0') - die(STATE_UNKNOWN, - _("Cannot find config file in any standard location.\n")); + die(STATE_UNKNOWN, _("Cannot find config file in any standard location.\n")); } /* * This is the externally visible function used by extra_opts. */ -np_arg_list * -np_get_defaults(const char *locator, const char *default_section) -{ +np_arg_list *np_get_defaults(const char *locator, const char *default_section) { FILE *inifile = NULL; np_arg_list *defaults = NULL; np_ini_info i; int is_suid_plugin = mp_suid(); if (is_suid_plugin && idpriv_temp_drop() == -1) - die(STATE_UNKNOWN, _("Cannot drop privileges: %s\n"), - strerror(errno)); + die(STATE_UNKNOWN, _("Cannot drop privileges: %s\n"), strerror(errno)); parse_locator(locator, default_section, &i); inifile = strcmp(i.file, "-") == 0 ? stdin : fopen(i.file, "r"); if (inifile == NULL) - die(STATE_UNKNOWN, _("Can't read config file: %s\n"), - strerror(errno)); + die(STATE_UNKNOWN, _("Can't read config file: %s\n"), strerror(errno)); if (!read_defaults(inifile, i.stanza, &defaults)) - die(STATE_UNKNOWN, - _("Invalid section '%s' in config file '%s'\n"), i.stanza, - i.file); + die(STATE_UNKNOWN, _("Invalid section '%s' in config file '%s'\n"), i.stanza, i.file); if (i.file_string_on_heap) { free(i.file); @@ -151,8 +130,7 @@ np_get_defaults(const char *locator, const char *default_section) fclose(inifile); free(i.stanza); if (is_suid_plugin && idpriv_temp_restore() == -1) - die(STATE_UNKNOWN, _("Cannot restore privileges: %s\n"), - strerror(errno)); + die(STATE_UNKNOWN, _("Cannot restore privileges: %s\n"), strerror(errno)); return defaults; } @@ -164,9 +142,7 @@ np_get_defaults(const char *locator, const char *default_section) * be extra careful about user-supplied input (i.e. avoiding possible * format string vulnerabilities, etc). */ -static int -read_defaults(FILE *f, const char *stanza, np_arg_list **opts) -{ +static int read_defaults(FILE *f, const char *stanza, np_arg_list **opts) { int c = 0; bool status = false; size_t i, stanza_len; @@ -217,8 +193,7 @@ read_defaults(FILE *f, const char *stanza, np_arg_list **opts) * we're dealing with a config error */ case NOSTANZA: - die(STATE_UNKNOWN, "%s\n", - _("Config file error")); + die(STATE_UNKNOWN, "%s\n", _("Config file error")); /* we're in a stanza, but for a different plugin */ case WRONGSTANZA: GOBBLE_TO(f, c, '\n'); @@ -227,8 +202,7 @@ read_defaults(FILE *f, const char *stanza, np_arg_list **opts) case RIGHTSTANZA: ungetc(c, f); if (add_option(f, opts)) { - die(STATE_UNKNOWN, "%s\n", - _("Config file error")); + die(STATE_UNKNOWN, "%s\n", _("Config file error")); } status = true; break; @@ -246,9 +220,7 @@ read_defaults(FILE *f, const char *stanza, np_arg_list **opts) * --option[=value] * appending it to the linked list optbuf. */ -static int -add_option(FILE *f, np_arg_list **optlst) -{ +static int add_option(FILE *f, np_arg_list **optlst) { np_arg_list *opttmp = *optlst, *optnew; char *linebuf = NULL, *lineend = NULL, *optptr = NULL, *optend = NULL; char *eqptr = NULL, *valptr = NULL, *valend = NULL; @@ -295,8 +267,7 @@ add_option(FILE *f, np_arg_list **optlst) if (optptr == eqptr) die(STATE_UNKNOWN, "%s\n", _("Config file error")); /* continue from '=' to start of value or EOL */ - for (valptr = eqptr + 1; valptr < lineend && isspace(*valptr); - valptr++) + for (valptr = eqptr + 1; valptr < lineend && isspace(*valptr); valptr++) continue; /* continue to the end of value */ for (valend = valptr; valend < lineend; valend++) @@ -365,13 +336,10 @@ add_option(FILE *f, np_arg_list **optlst) return 0; } -static char * -default_file(void) -{ - char *ini_file; +static char *default_file(void) { + char *ini_file; - if ((ini_file = getenv("MP_CONFIG_FILE")) != NULL || - (ini_file = default_file_in_path()) != NULL) { + if ((ini_file = getenv("MP_CONFIG_FILE")) != NULL || (ini_file = default_file_in_path()) != NULL) { return ini_file; } @@ -383,9 +351,7 @@ default_file(void) return NULL; } -static char * -default_file_in_path(void) -{ +static char *default_file_in_path(void) { char *config_path, **file; char *dir, *ini_file, *tokens; diff --git a/lib/parse_ini.h b/lib/parse_ini.h index e37601b..d17409e 100644 --- a/lib/parse_ini.h +++ b/lib/parse_ini.h @@ -19,4 +19,3 @@ typedef struct np_arg_el { np_arg_list *np_get_defaults(const char *locator, const char *default_section); #endif /* _PARSE_INI_H_ */ - diff --git a/lib/tests/test_base64.c b/lib/tests/test_base64.c index 05dd794..48e5ed6 100644 --- a/lib/tests/test_base64.c +++ b/lib/tests/test_base64.c @@ -1,29 +1,27 @@ /***************************************************************************** -* -* 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 . -* -* -*****************************************************************************/ + * + * 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 . + * + * + *****************************************************************************/ #include "common.h" #include "gl/base64.h" #include "tap.h" -int -main (int argc, char **argv) -{ -#if 0 /* The current base64 function doesn't work on 8bit data */ +int main(int argc, char **argv) { +#if 0 /* The current base64 function doesn't work on 8bit data */ char random[1024] = { 0x8b,0xb0,0xc4,0xe2,0xfc,0x22,0x9f,0x0d,0x85,0xe7,0x2c,0xaa,0x39,0xa1,0x46,0x88, 0x50,0xe6,0x34,0x37,0x0b,0x45,0x4b,0xb8,0xb2,0x86,0x7a,0x3e,0x7f,0x0c,0x40,0x18, @@ -182,168 +180,100 @@ main (int argc, char **argv) #endif char random[1024] = { - 0x0b,0x30,0x44,0x62,0x7c,0x22,0x1f,0x0d,0x05,0x67,0x2c,0x2a,0x39,0x21,0x46,0x08, - 0x50,0x66,0x34,0x37,0x0b,0x45,0x4b,0x38,0x32,0x06,0x7a,0x3e,0x7f,0x0c,0x40,0x18, - 0x6b,0x2d,0x60,0x4c,0x60,0x0c,0x23,0x43,0x3b,0x3e,0x1b,0x16,0x04,0x46,0x58,0x3f, - 0x40,0x6a,0x11,0x05,0x63,0x71,0x14,0x35,0x47,0x79,0x13,0x6f,0x6b,0x27,0x18,0x5b, - 0x48,0x27,0x3e,0x6f,0x15,0x33,0x4f,0x3e,0x5e,0x51,0x73,0x68,0x25,0x0f,0x06,0x5b, - 0x7c,0x72,0x75,0x3e,0x3f,0x1b,0x5c,0x6d,0x6a,0x39,0x7c,0x63,0x63,0x60,0x6c,0x7a, - 0x33,0x76,0x52,0x13,0x25,0x33,0x7d,0x65,0x23,0x27,0x11,0x06,0x06,0x47,0x71,0x1e, - 0x14,0x74,0x63,0x70,0x2d,0x15,0x27,0x18,0x51,0x06,0x05,0x33,0x11,0x2c,0x6b,0x00, - 0x2d,0x77,0x20,0x48,0x0d,0x73,0x51,0x45,0x25,0x7f,0x7f,0x35,0x26,0x2e,0x26,0x53, - 0x24,0x68,0x1e,0x0e,0x58,0x3a,0x59,0x50,0x56,0x37,0x5f,0x66,0x01,0x4c,0x5a,0x64, - 0x32,0x50,0x7b,0x6a,0x20,0x72,0x2b,0x1d,0x7e,0x43,0x7b,0x61,0x42,0x0b,0x61,0x73, - 0x24,0x79,0x3a,0x6b,0x4a,0x79,0x6e,0x09,0x0f,0x27,0x2d,0x0c,0x5e,0x32,0x4b,0x0d, - 0x79,0x46,0x39,0x21,0x0a,0x26,0x5f,0x3a,0x00,0x26,0x3f,0x13,0x2e,0x7e,0x50,0x2b, - 0x67,0x46,0x72,0x3f,0x3b,0x01,0x46,0x1b,0x0b,0x35,0x49,0x39,0x19,0x70,0x3d,0x02, - 0x41,0x0e,0x38,0x05,0x76,0x65,0x4f,0x31,0x6c,0x5e,0x17,0x04,0x15,0x36,0x26,0x64, - 0x34,0x14,0x17,0x7c,0x0e,0x0b,0x5b,0x55,0x53,0x6b,0x00,0x42,0x41,0x4f,0x02,0x5c, - 0x13,0x0a,0x2c,0x2c,0x3e,0x10,0x14,0x33,0x45,0x7c,0x7a,0x5a,0x31,0x61,0x39,0x08, - 0x22,0x6a,0x1e,0x0f,0x6f,0x1b,0x6c,0x13,0x5e,0x79,0x20,0x79,0x50,0x62,0x06,0x2c, - 0x76,0x17,0x04,0x2b,0x2a,0x75,0x1f,0x0c,0x37,0x4e,0x0f,0x7b,0x2d,0x34,0x75,0x60, - 0x31,0x74,0x2e,0x0a,0x4a,0x11,0x6c,0x49,0x25,0x01,0x3a,0x3d,0x22,0x1e,0x6d,0x18, - 0x51,0x78,0x2d,0x62,0x31,0x4c,0x50,0x40,0x17,0x4b,0x6f,0x22,0x00,0x7f,0x61,0x2a, - 0x34,0x3e,0x00,0x5f,0x2f,0x5f,0x2f,0x14,0x2a,0x55,0x27,0x1f,0x46,0x1f,0x12,0x46, - 0x5e,0x1e,0x0c,0x7c,0x38,0x01,0x61,0x64,0x76,0x22,0x6e,0x08,0x20,0x38,0x4f,0x73, - 0x72,0x55,0x12,0x42,0x19,0x50,0x61,0x43,0x77,0x7d,0x41,0x2e,0x35,0x4f,0x3d,0x31, - 0x28,0x58,0x67,0x1b,0x03,0x51,0x20,0x32,0x1c,0x08,0x6e,0x37,0x75,0x37,0x44,0x4f, - 0x68,0x19,0x07,0x64,0x14,0x28,0x25,0x2b,0x69,0x35,0x18,0x27,0x26,0x14,0x13,0x70, - 0x42,0x19,0x12,0x75,0x3e,0x02,0x5d,0x7c,0x13,0x1f,0x16,0x53,0x3b,0x74,0x48,0x3c, - 0x5e,0x39,0x6c,0x1c,0x1c,0x74,0x39,0x1f,0x00,0x1b,0x06,0x0a,0x68,0x3b,0x52,0x4f, - 0x1e,0x6e,0x3c,0x35,0x0c,0x38,0x0e,0x0b,0x3b,0x1a,0x76,0x23,0x29,0x53,0x1e,0x5f, - 0x41,0x0c,0x4b,0x0a,0x65,0x28,0x78,0x67,0x48,0x59,0x26,0x6d,0x31,0x76,0x23,0x70, - 0x61,0x64,0x3b,0x38,0x79,0x66,0x74,0x53,0x2c,0x64,0x64,0x54,0x03,0x54,0x65,0x44, - 0x4c,0x18,0x4f,0x48,0x20,0x4f,0x72,0x10,0x3f,0x0c,0x52,0x2d,0x03,0x14,0x03,0x51, - 0x42,0x10,0x77,0x6a,0x34,0x06,0x32,0x03,0x72,0x14,0x7c,0x08,0x5d,0x52,0x1a,0x62, - 0x7c,0x3e,0x30,0x7e,0x5f,0x7f,0x54,0x0f,0x44,0x49,0x5d,0x5e,0x10,0x6a,0x06,0x2b, - 0x06,0x53,0x10,0x39,0x37,0x32,0x4a,0x4e,0x3d,0x2b,0x65,0x38,0x39,0x07,0x72,0x54, - 0x64,0x4d,0x56,0x6a,0x03,0x22,0x70,0x7b,0x5f,0x60,0x0b,0x2a,0x0b,0x6b,0x10,0x64, - 0x14,0x05,0x22,0x00,0x73,0x40,0x23,0x5b,0x51,0x1f,0x2b,0x1a,0x5d,0x69,0x7a,0x46, - 0x0c,0x5f,0x32,0x4b,0x4a,0x28,0x52,0x79,0x5b,0x12,0x42,0x18,0x00,0x5d,0x27,0x31, - 0x53,0x3c,0x4c,0x36,0x4e,0x38,0x3f,0x72,0x03,0x71,0x02,0x5b,0x36,0x59,0x7f,0x75, - 0x6e,0x08,0x54,0x0d,0x34,0x1c,0x34,0x57,0x5d,0x69,0x48,0x00,0x3b,0x05,0x07,0x6e, - 0x27,0x65,0x6e,0x40,0x3d,0x3a,0x4f,0x72,0x5d,0x39,0x16,0x0f,0x63,0x12,0x12,0x15, - 0x3a,0x70,0x0d,0x57,0x18,0x0d,0x5e,0x3d,0x22,0x68,0x68,0x7c,0x6d,0x4f,0x0c,0x7b, - 0x09,0x2d,0x4a,0x73,0x20,0x47,0x07,0x57,0x75,0x5d,0x53,0x70,0x34,0x21,0x40,0x57, - 0x51,0x5e,0x49,0x44,0x00,0x54,0x27,0x04,0x68,0x7e,0x59,0x56,0x58,0x74,0x14,0x3c, - 0x16,0x33,0x41,0x16,0x4b,0x2f,0x49,0x37,0x0a,0x54,0x08,0x08,0x1f,0x39,0x67,0x76, - 0x28,0x28,0x07,0x1d,0x61,0x47,0x51,0x4d,0x75,0x26,0x52,0x47,0x47,0x0c,0x57,0x58, - 0x74,0x3e,0x62,0x6c,0x58,0x3a,0x44,0x1e,0x16,0x2e,0x21,0x1c,0x73,0x45,0x67,0x74, - 0x4f,0x33,0x66,0x0e,0x74,0x66,0x26,0x1f,0x2e,0x38,0x44,0x40,0x7e,0x2a,0x50,0x52, - 0x5e,0x43,0x01,0x7a,0x38,0x49,0x3c,0x55,0x4d,0x5a,0x44,0x08,0x26,0x59,0x4d,0x45, - 0x0b,0x48,0x0a,0x33,0x5e,0x4a,0x4d,0x75,0x16,0x17,0x63,0x46,0x01,0x2a,0x55,0x7b, - 0x0f,0x02,0x73,0x6a,0x4b,0x7f,0x75,0x65,0x3c,0x4c,0x33,0x39,0x6c,0x74,0x05,0x60, - 0x0f,0x7f,0x2d,0x41,0x4d,0x4d,0x46,0x71,0x09,0x6f,0x4f,0x60,0x15,0x0f,0x46,0x73, - 0x63,0x4c,0x5e,0x74,0x30,0x0d,0x28,0x43,0x08,0x72,0x32,0x04,0x2e,0x31,0x29,0x27, - 0x44,0x6d,0x13,0x17,0x48,0x0f,0x49,0x52,0x10,0x13,0x7f,0x17,0x16,0x62,0x79,0x35, - 0x78,0x3e,0x01,0x7c,0x2e,0x0f,0x76,0x3e,0x5e,0x53,0x6c,0x5b,0x5f,0x7c,0x19,0x41, - 0x02,0x2f,0x17,0x64,0x41,0x75,0x10,0x04,0x47,0x7c,0x3d,0x4b,0x52,0x00,0x10,0x5d, - 0x51,0x4e,0x7a,0x27,0x25,0x55,0x40,0x12,0x35,0x60,0x05,0x1b,0x34,0x2d,0x04,0x7a, - 0x6a,0x69,0x02,0x79,0x03,0x3a,0x2f,0x06,0x0a,0x79,0x7b,0x12,0x5d,0x7c,0x52,0x29, - 0x47,0x58,0x12,0x73,0x3f,0x27,0x56,0x05,0x0c,0x48,0x32,0x58,0x6b,0x57,0x5c,0x03, - 0x64,0x56,0x11,0x52,0x7a,0x30,0x36,0x29,0x17,0x3b,0x68,0x7a,0x7c,0x05,0x6b,0x6b, - 0x13,0x6a,0x24,0x5c,0x68,0x42,0x18,0x32,0x03,0x73,0x6e,0x04,0x21,0x2e,0x01,0x04, - 0x63,0x7d,0x44,0x41,0x12,0x31,0x0b,0x15,0x1f,0x70,0x00,0x2e,0x66,0x14,0x3c,0x7f, - 0x2b,0x00,0x1f,0x0c,0x28,0x59,0x0a,0x16,0x49,0x5a,0x5c,0x64,0x65,0x4b,0x11,0x29, - 0x15,0x36,0x5a,0x65,0x19,0x4f,0x60,0x23,0x3a,0x3a,0x13,0x25,0x02,0x78,0x4c,0x54 - }; - char b64_known[1369] = { - 0x43,0x7a,0x42,0x45,0x59,0x6e,0x77,0x69,0x48,0x77,0x30,0x46,0x5a,0x79,0x77,0x71, - 0x4f,0x53,0x46,0x47,0x43,0x46,0x42,0x6d,0x4e,0x44,0x63,0x4c,0x52,0x55,0x73,0x34, - 0x4d,0x67,0x5a,0x36,0x50,0x6e,0x38,0x4d,0x51,0x42,0x68,0x72,0x4c,0x57,0x42,0x4d, - 0x59,0x41,0x77,0x6a,0x51,0x7a,0x73,0x2b,0x47,0x78,0x59,0x45,0x52,0x6c,0x67,0x2f, - 0x51,0x47,0x6f,0x52,0x42,0x57,0x4e,0x78,0x46,0x44,0x56,0x48,0x65,0x52,0x4e,0x76, - 0x61,0x79,0x63,0x59,0x57,0x30,0x67,0x6e,0x50,0x6d,0x38,0x56,0x4d,0x30,0x38,0x2b, - 0x58,0x6c,0x46,0x7a,0x61,0x43,0x55,0x50,0x42,0x6c,0x74,0x38,0x63,0x6e,0x55,0x2b, - 0x50,0x78,0x74,0x63,0x62,0x57,0x6f,0x35,0x66,0x47,0x4e,0x6a,0x59,0x47,0x78,0x36, - 0x4d,0x33,0x5a,0x53,0x45,0x79,0x55,0x7a,0x66,0x57,0x55,0x6a,0x4a,0x78,0x45,0x47, - 0x42,0x6b,0x64,0x78,0x48,0x68,0x52,0x30,0x59,0x33,0x41,0x74,0x46,0x53,0x63,0x59, - 0x55,0x51,0x59,0x46,0x4d,0x78,0x45,0x73,0x61,0x77,0x41,0x74,0x64,0x79,0x42,0x49, - 0x44,0x58,0x4e,0x52,0x52,0x53,0x56,0x2f,0x66,0x7a,0x55,0x6d,0x4c,0x69,0x5a,0x54, - 0x4a,0x47,0x67,0x65,0x44,0x6c,0x67,0x36,0x57,0x56,0x42,0x57,0x4e,0x31,0x39,0x6d, - 0x41,0x55,0x78,0x61,0x5a,0x44,0x4a,0x51,0x65,0x32,0x6f,0x67,0x63,0x69,0x73,0x64, - 0x66,0x6b,0x4e,0x37,0x59,0x55,0x49,0x4c,0x59,0x58,0x4d,0x6b,0x65,0x54,0x70,0x72, - 0x53,0x6e,0x6c,0x75,0x43,0x51,0x38,0x6e,0x4c,0x51,0x78,0x65,0x4d,0x6b,0x73,0x4e, - 0x65,0x55,0x59,0x35,0x49,0x51,0x6f,0x6d,0x58,0x7a,0x6f,0x41,0x4a,0x6a,0x38,0x54, - 0x4c,0x6e,0x35,0x51,0x4b,0x32,0x64,0x47,0x63,0x6a,0x38,0x37,0x41,0x55,0x59,0x62, - 0x43,0x7a,0x56,0x4a,0x4f,0x52,0x6c,0x77,0x50,0x51,0x4a,0x42,0x44,0x6a,0x67,0x46, - 0x64,0x6d,0x56,0x50,0x4d,0x57,0x78,0x65,0x46,0x77,0x51,0x56,0x4e,0x69,0x5a,0x6b, - 0x4e,0x42,0x51,0x58,0x66,0x41,0x34,0x4c,0x57,0x31,0x56,0x54,0x61,0x77,0x42,0x43, - 0x51,0x55,0x38,0x43,0x58,0x42,0x4d,0x4b,0x4c,0x43,0x77,0x2b,0x45,0x42,0x51,0x7a, - 0x52,0x58,0x78,0x36,0x57,0x6a,0x46,0x68,0x4f,0x51,0x67,0x69,0x61,0x68,0x34,0x50, - 0x62,0x78,0x74,0x73,0x45,0x31,0x35,0x35,0x49,0x48,0x6c,0x51,0x59,0x67,0x59,0x73, - 0x64,0x68,0x63,0x45,0x4b,0x79,0x70,0x31,0x48,0x77,0x77,0x33,0x54,0x67,0x39,0x37, - 0x4c,0x54,0x52,0x31,0x59,0x44,0x46,0x30,0x4c,0x67,0x70,0x4b,0x45,0x57,0x78,0x4a, - 0x4a,0x51,0x45,0x36,0x50,0x53,0x49,0x65,0x62,0x52,0x68,0x52,0x65,0x43,0x31,0x69, - 0x4d,0x55,0x78,0x51,0x51,0x42,0x64,0x4c,0x62,0x79,0x49,0x41,0x66,0x32,0x45,0x71, - 0x4e,0x44,0x34,0x41,0x58,0x79,0x39,0x66,0x4c,0x78,0x51,0x71,0x56,0x53,0x63,0x66, - 0x52,0x68,0x38,0x53,0x52,0x6c,0x34,0x65,0x44,0x48,0x77,0x34,0x41,0x57,0x46,0x6b, - 0x64,0x69,0x4a,0x75,0x43,0x43,0x41,0x34,0x54,0x33,0x4e,0x79,0x56,0x52,0x4a,0x43, - 0x47,0x56,0x42,0x68,0x51,0x33,0x64,0x39,0x51,0x53,0x34,0x31,0x54,0x7a,0x30,0x78, - 0x4b,0x46,0x68,0x6e,0x47,0x77,0x4e,0x52,0x49,0x44,0x49,0x63,0x43,0x47,0x34,0x33, - 0x64,0x54,0x64,0x45,0x54,0x32,0x67,0x5a,0x42,0x32,0x51,0x55,0x4b,0x43,0x55,0x72, - 0x61,0x54,0x55,0x59,0x4a,0x79,0x59,0x55,0x45,0x33,0x42,0x43,0x47,0x52,0x4a,0x31, - 0x50,0x67,0x4a,0x64,0x66,0x42,0x4d,0x66,0x46,0x6c,0x4d,0x37,0x64,0x45,0x67,0x38, - 0x58,0x6a,0x6c,0x73,0x48,0x42,0x78,0x30,0x4f,0x52,0x38,0x41,0x47,0x77,0x59,0x4b, - 0x61,0x44,0x74,0x53,0x54,0x78,0x35,0x75,0x50,0x44,0x55,0x4d,0x4f,0x41,0x34,0x4c, - 0x4f,0x78,0x70,0x32,0x49,0x79,0x6c,0x54,0x48,0x6c,0x39,0x42,0x44,0x45,0x73,0x4b, - 0x5a,0x53,0x68,0x34,0x5a,0x30,0x68,0x5a,0x4a,0x6d,0x30,0x78,0x64,0x69,0x4e,0x77, - 0x59,0x57,0x51,0x37,0x4f,0x48,0x6c,0x6d,0x64,0x46,0x4d,0x73,0x5a,0x47,0x52,0x55, - 0x41,0x31,0x52,0x6c,0x52,0x45,0x77,0x59,0x54,0x30,0x67,0x67,0x54,0x33,0x49,0x51, - 0x50,0x77,0x78,0x53,0x4c,0x51,0x4d,0x55,0x41,0x31,0x46,0x43,0x45,0x48,0x64,0x71, - 0x4e,0x41,0x59,0x79,0x41,0x33,0x49,0x55,0x66,0x41,0x68,0x64,0x55,0x68,0x70,0x69, - 0x66,0x44,0x34,0x77,0x66,0x6c,0x39,0x2f,0x56,0x41,0x39,0x45,0x53,0x56,0x31,0x65, - 0x45,0x47,0x6f,0x47,0x4b,0x77,0x5a,0x54,0x45,0x44,0x6b,0x33,0x4d,0x6b,0x70,0x4f, - 0x50,0x53,0x74,0x6c,0x4f,0x44,0x6b,0x48,0x63,0x6c,0x52,0x6b,0x54,0x56,0x5a,0x71, - 0x41,0x79,0x4a,0x77,0x65,0x31,0x39,0x67,0x43,0x79,0x6f,0x4c,0x61,0x78,0x42,0x6b, - 0x46,0x41,0x55,0x69,0x41,0x48,0x4e,0x41,0x49,0x31,0x74,0x52,0x48,0x79,0x73,0x61, - 0x58,0x57,0x6c,0x36,0x52,0x67,0x78,0x66,0x4d,0x6b,0x74,0x4b,0x4b,0x46,0x4a,0x35, - 0x57,0x78,0x4a,0x43,0x47,0x41,0x42,0x64,0x4a,0x7a,0x46,0x54,0x50,0x45,0x77,0x32, - 0x54,0x6a,0x67,0x2f,0x63,0x67,0x4e,0x78,0x41,0x6c,0x73,0x32,0x57,0x58,0x39,0x31, - 0x62,0x67,0x68,0x55,0x44,0x54,0x51,0x63,0x4e,0x46,0x64,0x64,0x61,0x55,0x67,0x41, - 0x4f,0x77,0x55,0x48,0x62,0x69,0x64,0x6c,0x62,0x6b,0x41,0x39,0x4f,0x6b,0x39,0x79, - 0x58,0x54,0x6b,0x57,0x44,0x32,0x4d,0x53,0x45,0x68,0x55,0x36,0x63,0x41,0x31,0x58, - 0x47,0x41,0x31,0x65,0x50,0x53,0x4a,0x6f,0x61,0x48,0x78,0x74,0x54,0x77,0x78,0x37, - 0x43,0x53,0x31,0x4b,0x63,0x79,0x42,0x48,0x42,0x31,0x64,0x31,0x58,0x56,0x4e,0x77, - 0x4e,0x43,0x46,0x41,0x56,0x31,0x46,0x65,0x53,0x55,0x51,0x41,0x56,0x43,0x63,0x45, - 0x61,0x48,0x35,0x5a,0x56,0x6c,0x68,0x30,0x46,0x44,0x77,0x57,0x4d,0x30,0x45,0x57, - 0x53,0x79,0x39,0x4a,0x4e,0x77,0x70,0x55,0x43,0x41,0x67,0x66,0x4f,0x57,0x64,0x32, - 0x4b,0x43,0x67,0x48,0x48,0x57,0x46,0x48,0x55,0x55,0x31,0x31,0x4a,0x6c,0x4a,0x48, - 0x52,0x77,0x78,0x58,0x57,0x48,0x51,0x2b,0x59,0x6d,0x78,0x59,0x4f,0x6b,0x51,0x65, - 0x46,0x69,0x34,0x68,0x48,0x48,0x4e,0x46,0x5a,0x33,0x52,0x50,0x4d,0x32,0x59,0x4f, - 0x64,0x47,0x59,0x6d,0x48,0x79,0x34,0x34,0x52,0x45,0x42,0x2b,0x4b,0x6c,0x42,0x53, - 0x58,0x6b,0x4d,0x42,0x65,0x6a,0x68,0x4a,0x50,0x46,0x56,0x4e,0x57,0x6b,0x51,0x49, - 0x4a,0x6c,0x6c,0x4e,0x52,0x51,0x74,0x49,0x43,0x6a,0x4e,0x65,0x53,0x6b,0x31,0x31, - 0x46,0x68,0x64,0x6a,0x52,0x67,0x45,0x71,0x56,0x58,0x73,0x50,0x41,0x6e,0x4e,0x71, - 0x53,0x33,0x39,0x31,0x5a,0x54,0x78,0x4d,0x4d,0x7a,0x6c,0x73,0x64,0x41,0x56,0x67, - 0x44,0x33,0x38,0x74,0x51,0x55,0x31,0x4e,0x52,0x6e,0x45,0x4a,0x62,0x30,0x39,0x67, - 0x46,0x51,0x39,0x47,0x63,0x32,0x4e,0x4d,0x58,0x6e,0x51,0x77,0x44,0x53,0x68,0x44, - 0x43,0x48,0x49,0x79,0x42,0x43,0x34,0x78,0x4b,0x53,0x64,0x45,0x62,0x52,0x4d,0x58, - 0x53,0x41,0x39,0x4a,0x55,0x68,0x41,0x54,0x66,0x78,0x63,0x57,0x59,0x6e,0x6b,0x31, - 0x65,0x44,0x34,0x42,0x66,0x43,0x34,0x50,0x64,0x6a,0x35,0x65,0x55,0x32,0x78,0x62, - 0x58,0x33,0x77,0x5a,0x51,0x51,0x49,0x76,0x46,0x32,0x52,0x42,0x64,0x52,0x41,0x45, - 0x52,0x33,0x77,0x39,0x53,0x31,0x49,0x41,0x45,0x46,0x31,0x52,0x54,0x6e,0x6f,0x6e, - 0x4a,0x56,0x56,0x41,0x45,0x6a,0x56,0x67,0x42,0x52,0x73,0x30,0x4c,0x51,0x52,0x36, - 0x61,0x6d,0x6b,0x43,0x65,0x51,0x4d,0x36,0x4c,0x77,0x59,0x4b,0x65,0x58,0x73,0x53, - 0x58,0x58,0x78,0x53,0x4b,0x55,0x64,0x59,0x45,0x6e,0x4d,0x2f,0x4a,0x31,0x59,0x46, - 0x44,0x45,0x67,0x79,0x57,0x47,0x74,0x58,0x58,0x41,0x4e,0x6b,0x56,0x68,0x46,0x53, - 0x65,0x6a,0x41,0x32,0x4b,0x52,0x63,0x37,0x61,0x48,0x70,0x38,0x42,0x57,0x74,0x72, - 0x45,0x32,0x6f,0x6b,0x58,0x47,0x68,0x43,0x47,0x44,0x49,0x44,0x63,0x32,0x34,0x45, - 0x49,0x53,0x34,0x42,0x42,0x47,0x4e,0x39,0x52,0x45,0x45,0x53,0x4d,0x51,0x73,0x56, - 0x48,0x33,0x41,0x41,0x4c,0x6d,0x59,0x55,0x50,0x48,0x38,0x72,0x41,0x42,0x38,0x4d, - 0x4b,0x46,0x6b,0x4b,0x46,0x6b,0x6c,0x61,0x58,0x47,0x52,0x6c,0x53,0x78,0x45,0x70, - 0x46,0x54,0x5a,0x61,0x5a,0x52,0x6c,0x50,0x59,0x43,0x4d,0x36,0x4f,0x68,0x4d,0x6c, - 0x41,0x6e,0x68,0x4d,0x56,0x41,0x3d,0x3d,0x00 - }; + 0x0b, 0x30, 0x44, 0x62, 0x7c, 0x22, 0x1f, 0x0d, 0x05, 0x67, 0x2c, 0x2a, 0x39, 0x21, 0x46, 0x08, 0x50, 0x66, 0x34, 0x37, 0x0b, 0x45, 0x4b, 0x38, 0x32, 0x06, 0x7a, 0x3e, + 0x7f, 0x0c, 0x40, 0x18, 0x6b, 0x2d, 0x60, 0x4c, 0x60, 0x0c, 0x23, 0x43, 0x3b, 0x3e, 0x1b, 0x16, 0x04, 0x46, 0x58, 0x3f, 0x40, 0x6a, 0x11, 0x05, 0x63, 0x71, 0x14, 0x35, + 0x47, 0x79, 0x13, 0x6f, 0x6b, 0x27, 0x18, 0x5b, 0x48, 0x27, 0x3e, 0x6f, 0x15, 0x33, 0x4f, 0x3e, 0x5e, 0x51, 0x73, 0x68, 0x25, 0x0f, 0x06, 0x5b, 0x7c, 0x72, 0x75, 0x3e, + 0x3f, 0x1b, 0x5c, 0x6d, 0x6a, 0x39, 0x7c, 0x63, 0x63, 0x60, 0x6c, 0x7a, 0x33, 0x76, 0x52, 0x13, 0x25, 0x33, 0x7d, 0x65, 0x23, 0x27, 0x11, 0x06, 0x06, 0x47, 0x71, 0x1e, + 0x14, 0x74, 0x63, 0x70, 0x2d, 0x15, 0x27, 0x18, 0x51, 0x06, 0x05, 0x33, 0x11, 0x2c, 0x6b, 0x00, 0x2d, 0x77, 0x20, 0x48, 0x0d, 0x73, 0x51, 0x45, 0x25, 0x7f, 0x7f, 0x35, + 0x26, 0x2e, 0x26, 0x53, 0x24, 0x68, 0x1e, 0x0e, 0x58, 0x3a, 0x59, 0x50, 0x56, 0x37, 0x5f, 0x66, 0x01, 0x4c, 0x5a, 0x64, 0x32, 0x50, 0x7b, 0x6a, 0x20, 0x72, 0x2b, 0x1d, + 0x7e, 0x43, 0x7b, 0x61, 0x42, 0x0b, 0x61, 0x73, 0x24, 0x79, 0x3a, 0x6b, 0x4a, 0x79, 0x6e, 0x09, 0x0f, 0x27, 0x2d, 0x0c, 0x5e, 0x32, 0x4b, 0x0d, 0x79, 0x46, 0x39, 0x21, + 0x0a, 0x26, 0x5f, 0x3a, 0x00, 0x26, 0x3f, 0x13, 0x2e, 0x7e, 0x50, 0x2b, 0x67, 0x46, 0x72, 0x3f, 0x3b, 0x01, 0x46, 0x1b, 0x0b, 0x35, 0x49, 0x39, 0x19, 0x70, 0x3d, 0x02, + 0x41, 0x0e, 0x38, 0x05, 0x76, 0x65, 0x4f, 0x31, 0x6c, 0x5e, 0x17, 0x04, 0x15, 0x36, 0x26, 0x64, 0x34, 0x14, 0x17, 0x7c, 0x0e, 0x0b, 0x5b, 0x55, 0x53, 0x6b, 0x00, 0x42, + 0x41, 0x4f, 0x02, 0x5c, 0x13, 0x0a, 0x2c, 0x2c, 0x3e, 0x10, 0x14, 0x33, 0x45, 0x7c, 0x7a, 0x5a, 0x31, 0x61, 0x39, 0x08, 0x22, 0x6a, 0x1e, 0x0f, 0x6f, 0x1b, 0x6c, 0x13, + 0x5e, 0x79, 0x20, 0x79, 0x50, 0x62, 0x06, 0x2c, 0x76, 0x17, 0x04, 0x2b, 0x2a, 0x75, 0x1f, 0x0c, 0x37, 0x4e, 0x0f, 0x7b, 0x2d, 0x34, 0x75, 0x60, 0x31, 0x74, 0x2e, 0x0a, + 0x4a, 0x11, 0x6c, 0x49, 0x25, 0x01, 0x3a, 0x3d, 0x22, 0x1e, 0x6d, 0x18, 0x51, 0x78, 0x2d, 0x62, 0x31, 0x4c, 0x50, 0x40, 0x17, 0x4b, 0x6f, 0x22, 0x00, 0x7f, 0x61, 0x2a, + 0x34, 0x3e, 0x00, 0x5f, 0x2f, 0x5f, 0x2f, 0x14, 0x2a, 0x55, 0x27, 0x1f, 0x46, 0x1f, 0x12, 0x46, 0x5e, 0x1e, 0x0c, 0x7c, 0x38, 0x01, 0x61, 0x64, 0x76, 0x22, 0x6e, 0x08, + 0x20, 0x38, 0x4f, 0x73, 0x72, 0x55, 0x12, 0x42, 0x19, 0x50, 0x61, 0x43, 0x77, 0x7d, 0x41, 0x2e, 0x35, 0x4f, 0x3d, 0x31, 0x28, 0x58, 0x67, 0x1b, 0x03, 0x51, 0x20, 0x32, + 0x1c, 0x08, 0x6e, 0x37, 0x75, 0x37, 0x44, 0x4f, 0x68, 0x19, 0x07, 0x64, 0x14, 0x28, 0x25, 0x2b, 0x69, 0x35, 0x18, 0x27, 0x26, 0x14, 0x13, 0x70, 0x42, 0x19, 0x12, 0x75, + 0x3e, 0x02, 0x5d, 0x7c, 0x13, 0x1f, 0x16, 0x53, 0x3b, 0x74, 0x48, 0x3c, 0x5e, 0x39, 0x6c, 0x1c, 0x1c, 0x74, 0x39, 0x1f, 0x00, 0x1b, 0x06, 0x0a, 0x68, 0x3b, 0x52, 0x4f, + 0x1e, 0x6e, 0x3c, 0x35, 0x0c, 0x38, 0x0e, 0x0b, 0x3b, 0x1a, 0x76, 0x23, 0x29, 0x53, 0x1e, 0x5f, 0x41, 0x0c, 0x4b, 0x0a, 0x65, 0x28, 0x78, 0x67, 0x48, 0x59, 0x26, 0x6d, + 0x31, 0x76, 0x23, 0x70, 0x61, 0x64, 0x3b, 0x38, 0x79, 0x66, 0x74, 0x53, 0x2c, 0x64, 0x64, 0x54, 0x03, 0x54, 0x65, 0x44, 0x4c, 0x18, 0x4f, 0x48, 0x20, 0x4f, 0x72, 0x10, + 0x3f, 0x0c, 0x52, 0x2d, 0x03, 0x14, 0x03, 0x51, 0x42, 0x10, 0x77, 0x6a, 0x34, 0x06, 0x32, 0x03, 0x72, 0x14, 0x7c, 0x08, 0x5d, 0x52, 0x1a, 0x62, 0x7c, 0x3e, 0x30, 0x7e, + 0x5f, 0x7f, 0x54, 0x0f, 0x44, 0x49, 0x5d, 0x5e, 0x10, 0x6a, 0x06, 0x2b, 0x06, 0x53, 0x10, 0x39, 0x37, 0x32, 0x4a, 0x4e, 0x3d, 0x2b, 0x65, 0x38, 0x39, 0x07, 0x72, 0x54, + 0x64, 0x4d, 0x56, 0x6a, 0x03, 0x22, 0x70, 0x7b, 0x5f, 0x60, 0x0b, 0x2a, 0x0b, 0x6b, 0x10, 0x64, 0x14, 0x05, 0x22, 0x00, 0x73, 0x40, 0x23, 0x5b, 0x51, 0x1f, 0x2b, 0x1a, + 0x5d, 0x69, 0x7a, 0x46, 0x0c, 0x5f, 0x32, 0x4b, 0x4a, 0x28, 0x52, 0x79, 0x5b, 0x12, 0x42, 0x18, 0x00, 0x5d, 0x27, 0x31, 0x53, 0x3c, 0x4c, 0x36, 0x4e, 0x38, 0x3f, 0x72, + 0x03, 0x71, 0x02, 0x5b, 0x36, 0x59, 0x7f, 0x75, 0x6e, 0x08, 0x54, 0x0d, 0x34, 0x1c, 0x34, 0x57, 0x5d, 0x69, 0x48, 0x00, 0x3b, 0x05, 0x07, 0x6e, 0x27, 0x65, 0x6e, 0x40, + 0x3d, 0x3a, 0x4f, 0x72, 0x5d, 0x39, 0x16, 0x0f, 0x63, 0x12, 0x12, 0x15, 0x3a, 0x70, 0x0d, 0x57, 0x18, 0x0d, 0x5e, 0x3d, 0x22, 0x68, 0x68, 0x7c, 0x6d, 0x4f, 0x0c, 0x7b, + 0x09, 0x2d, 0x4a, 0x73, 0x20, 0x47, 0x07, 0x57, 0x75, 0x5d, 0x53, 0x70, 0x34, 0x21, 0x40, 0x57, 0x51, 0x5e, 0x49, 0x44, 0x00, 0x54, 0x27, 0x04, 0x68, 0x7e, 0x59, 0x56, + 0x58, 0x74, 0x14, 0x3c, 0x16, 0x33, 0x41, 0x16, 0x4b, 0x2f, 0x49, 0x37, 0x0a, 0x54, 0x08, 0x08, 0x1f, 0x39, 0x67, 0x76, 0x28, 0x28, 0x07, 0x1d, 0x61, 0x47, 0x51, 0x4d, + 0x75, 0x26, 0x52, 0x47, 0x47, 0x0c, 0x57, 0x58, 0x74, 0x3e, 0x62, 0x6c, 0x58, 0x3a, 0x44, 0x1e, 0x16, 0x2e, 0x21, 0x1c, 0x73, 0x45, 0x67, 0x74, 0x4f, 0x33, 0x66, 0x0e, + 0x74, 0x66, 0x26, 0x1f, 0x2e, 0x38, 0x44, 0x40, 0x7e, 0x2a, 0x50, 0x52, 0x5e, 0x43, 0x01, 0x7a, 0x38, 0x49, 0x3c, 0x55, 0x4d, 0x5a, 0x44, 0x08, 0x26, 0x59, 0x4d, 0x45, + 0x0b, 0x48, 0x0a, 0x33, 0x5e, 0x4a, 0x4d, 0x75, 0x16, 0x17, 0x63, 0x46, 0x01, 0x2a, 0x55, 0x7b, 0x0f, 0x02, 0x73, 0x6a, 0x4b, 0x7f, 0x75, 0x65, 0x3c, 0x4c, 0x33, 0x39, + 0x6c, 0x74, 0x05, 0x60, 0x0f, 0x7f, 0x2d, 0x41, 0x4d, 0x4d, 0x46, 0x71, 0x09, 0x6f, 0x4f, 0x60, 0x15, 0x0f, 0x46, 0x73, 0x63, 0x4c, 0x5e, 0x74, 0x30, 0x0d, 0x28, 0x43, + 0x08, 0x72, 0x32, 0x04, 0x2e, 0x31, 0x29, 0x27, 0x44, 0x6d, 0x13, 0x17, 0x48, 0x0f, 0x49, 0x52, 0x10, 0x13, 0x7f, 0x17, 0x16, 0x62, 0x79, 0x35, 0x78, 0x3e, 0x01, 0x7c, + 0x2e, 0x0f, 0x76, 0x3e, 0x5e, 0x53, 0x6c, 0x5b, 0x5f, 0x7c, 0x19, 0x41, 0x02, 0x2f, 0x17, 0x64, 0x41, 0x75, 0x10, 0x04, 0x47, 0x7c, 0x3d, 0x4b, 0x52, 0x00, 0x10, 0x5d, + 0x51, 0x4e, 0x7a, 0x27, 0x25, 0x55, 0x40, 0x12, 0x35, 0x60, 0x05, 0x1b, 0x34, 0x2d, 0x04, 0x7a, 0x6a, 0x69, 0x02, 0x79, 0x03, 0x3a, 0x2f, 0x06, 0x0a, 0x79, 0x7b, 0x12, + 0x5d, 0x7c, 0x52, 0x29, 0x47, 0x58, 0x12, 0x73, 0x3f, 0x27, 0x56, 0x05, 0x0c, 0x48, 0x32, 0x58, 0x6b, 0x57, 0x5c, 0x03, 0x64, 0x56, 0x11, 0x52, 0x7a, 0x30, 0x36, 0x29, + 0x17, 0x3b, 0x68, 0x7a, 0x7c, 0x05, 0x6b, 0x6b, 0x13, 0x6a, 0x24, 0x5c, 0x68, 0x42, 0x18, 0x32, 0x03, 0x73, 0x6e, 0x04, 0x21, 0x2e, 0x01, 0x04, 0x63, 0x7d, 0x44, 0x41, + 0x12, 0x31, 0x0b, 0x15, 0x1f, 0x70, 0x00, 0x2e, 0x66, 0x14, 0x3c, 0x7f, 0x2b, 0x00, 0x1f, 0x0c, 0x28, 0x59, 0x0a, 0x16, 0x49, 0x5a, 0x5c, 0x64, 0x65, 0x4b, 0x11, 0x29, + 0x15, 0x36, 0x5a, 0x65, 0x19, 0x4f, 0x60, 0x23, 0x3a, 0x3a, 0x13, 0x25, 0x02, 0x78, 0x4c, 0x54}; + char b64_known[1369] = { + 0x43, 0x7a, 0x42, 0x45, 0x59, 0x6e, 0x77, 0x69, 0x48, 0x77, 0x30, 0x46, 0x5a, 0x79, 0x77, 0x71, 0x4f, 0x53, 0x46, 0x47, 0x43, 0x46, 0x42, 0x6d, 0x4e, 0x44, 0x63, 0x4c, + 0x52, 0x55, 0x73, 0x34, 0x4d, 0x67, 0x5a, 0x36, 0x50, 0x6e, 0x38, 0x4d, 0x51, 0x42, 0x68, 0x72, 0x4c, 0x57, 0x42, 0x4d, 0x59, 0x41, 0x77, 0x6a, 0x51, 0x7a, 0x73, 0x2b, + 0x47, 0x78, 0x59, 0x45, 0x52, 0x6c, 0x67, 0x2f, 0x51, 0x47, 0x6f, 0x52, 0x42, 0x57, 0x4e, 0x78, 0x46, 0x44, 0x56, 0x48, 0x65, 0x52, 0x4e, 0x76, 0x61, 0x79, 0x63, 0x59, + 0x57, 0x30, 0x67, 0x6e, 0x50, 0x6d, 0x38, 0x56, 0x4d, 0x30, 0x38, 0x2b, 0x58, 0x6c, 0x46, 0x7a, 0x61, 0x43, 0x55, 0x50, 0x42, 0x6c, 0x74, 0x38, 0x63, 0x6e, 0x55, 0x2b, + 0x50, 0x78, 0x74, 0x63, 0x62, 0x57, 0x6f, 0x35, 0x66, 0x47, 0x4e, 0x6a, 0x59, 0x47, 0x78, 0x36, 0x4d, 0x33, 0x5a, 0x53, 0x45, 0x79, 0x55, 0x7a, 0x66, 0x57, 0x55, 0x6a, + 0x4a, 0x78, 0x45, 0x47, 0x42, 0x6b, 0x64, 0x78, 0x48, 0x68, 0x52, 0x30, 0x59, 0x33, 0x41, 0x74, 0x46, 0x53, 0x63, 0x59, 0x55, 0x51, 0x59, 0x46, 0x4d, 0x78, 0x45, 0x73, + 0x61, 0x77, 0x41, 0x74, 0x64, 0x79, 0x42, 0x49, 0x44, 0x58, 0x4e, 0x52, 0x52, 0x53, 0x56, 0x2f, 0x66, 0x7a, 0x55, 0x6d, 0x4c, 0x69, 0x5a, 0x54, 0x4a, 0x47, 0x67, 0x65, + 0x44, 0x6c, 0x67, 0x36, 0x57, 0x56, 0x42, 0x57, 0x4e, 0x31, 0x39, 0x6d, 0x41, 0x55, 0x78, 0x61, 0x5a, 0x44, 0x4a, 0x51, 0x65, 0x32, 0x6f, 0x67, 0x63, 0x69, 0x73, 0x64, + 0x66, 0x6b, 0x4e, 0x37, 0x59, 0x55, 0x49, 0x4c, 0x59, 0x58, 0x4d, 0x6b, 0x65, 0x54, 0x70, 0x72, 0x53, 0x6e, 0x6c, 0x75, 0x43, 0x51, 0x38, 0x6e, 0x4c, 0x51, 0x78, 0x65, + 0x4d, 0x6b, 0x73, 0x4e, 0x65, 0x55, 0x59, 0x35, 0x49, 0x51, 0x6f, 0x6d, 0x58, 0x7a, 0x6f, 0x41, 0x4a, 0x6a, 0x38, 0x54, 0x4c, 0x6e, 0x35, 0x51, 0x4b, 0x32, 0x64, 0x47, + 0x63, 0x6a, 0x38, 0x37, 0x41, 0x55, 0x59, 0x62, 0x43, 0x7a, 0x56, 0x4a, 0x4f, 0x52, 0x6c, 0x77, 0x50, 0x51, 0x4a, 0x42, 0x44, 0x6a, 0x67, 0x46, 0x64, 0x6d, 0x56, 0x50, + 0x4d, 0x57, 0x78, 0x65, 0x46, 0x77, 0x51, 0x56, 0x4e, 0x69, 0x5a, 0x6b, 0x4e, 0x42, 0x51, 0x58, 0x66, 0x41, 0x34, 0x4c, 0x57, 0x31, 0x56, 0x54, 0x61, 0x77, 0x42, 0x43, + 0x51, 0x55, 0x38, 0x43, 0x58, 0x42, 0x4d, 0x4b, 0x4c, 0x43, 0x77, 0x2b, 0x45, 0x42, 0x51, 0x7a, 0x52, 0x58, 0x78, 0x36, 0x57, 0x6a, 0x46, 0x68, 0x4f, 0x51, 0x67, 0x69, + 0x61, 0x68, 0x34, 0x50, 0x62, 0x78, 0x74, 0x73, 0x45, 0x31, 0x35, 0x35, 0x49, 0x48, 0x6c, 0x51, 0x59, 0x67, 0x59, 0x73, 0x64, 0x68, 0x63, 0x45, 0x4b, 0x79, 0x70, 0x31, + 0x48, 0x77, 0x77, 0x33, 0x54, 0x67, 0x39, 0x37, 0x4c, 0x54, 0x52, 0x31, 0x59, 0x44, 0x46, 0x30, 0x4c, 0x67, 0x70, 0x4b, 0x45, 0x57, 0x78, 0x4a, 0x4a, 0x51, 0x45, 0x36, + 0x50, 0x53, 0x49, 0x65, 0x62, 0x52, 0x68, 0x52, 0x65, 0x43, 0x31, 0x69, 0x4d, 0x55, 0x78, 0x51, 0x51, 0x42, 0x64, 0x4c, 0x62, 0x79, 0x49, 0x41, 0x66, 0x32, 0x45, 0x71, + 0x4e, 0x44, 0x34, 0x41, 0x58, 0x79, 0x39, 0x66, 0x4c, 0x78, 0x51, 0x71, 0x56, 0x53, 0x63, 0x66, 0x52, 0x68, 0x38, 0x53, 0x52, 0x6c, 0x34, 0x65, 0x44, 0x48, 0x77, 0x34, + 0x41, 0x57, 0x46, 0x6b, 0x64, 0x69, 0x4a, 0x75, 0x43, 0x43, 0x41, 0x34, 0x54, 0x33, 0x4e, 0x79, 0x56, 0x52, 0x4a, 0x43, 0x47, 0x56, 0x42, 0x68, 0x51, 0x33, 0x64, 0x39, + 0x51, 0x53, 0x34, 0x31, 0x54, 0x7a, 0x30, 0x78, 0x4b, 0x46, 0x68, 0x6e, 0x47, 0x77, 0x4e, 0x52, 0x49, 0x44, 0x49, 0x63, 0x43, 0x47, 0x34, 0x33, 0x64, 0x54, 0x64, 0x45, + 0x54, 0x32, 0x67, 0x5a, 0x42, 0x32, 0x51, 0x55, 0x4b, 0x43, 0x55, 0x72, 0x61, 0x54, 0x55, 0x59, 0x4a, 0x79, 0x59, 0x55, 0x45, 0x33, 0x42, 0x43, 0x47, 0x52, 0x4a, 0x31, + 0x50, 0x67, 0x4a, 0x64, 0x66, 0x42, 0x4d, 0x66, 0x46, 0x6c, 0x4d, 0x37, 0x64, 0x45, 0x67, 0x38, 0x58, 0x6a, 0x6c, 0x73, 0x48, 0x42, 0x78, 0x30, 0x4f, 0x52, 0x38, 0x41, + 0x47, 0x77, 0x59, 0x4b, 0x61, 0x44, 0x74, 0x53, 0x54, 0x78, 0x35, 0x75, 0x50, 0x44, 0x55, 0x4d, 0x4f, 0x41, 0x34, 0x4c, 0x4f, 0x78, 0x70, 0x32, 0x49, 0x79, 0x6c, 0x54, + 0x48, 0x6c, 0x39, 0x42, 0x44, 0x45, 0x73, 0x4b, 0x5a, 0x53, 0x68, 0x34, 0x5a, 0x30, 0x68, 0x5a, 0x4a, 0x6d, 0x30, 0x78, 0x64, 0x69, 0x4e, 0x77, 0x59, 0x57, 0x51, 0x37, + 0x4f, 0x48, 0x6c, 0x6d, 0x64, 0x46, 0x4d, 0x73, 0x5a, 0x47, 0x52, 0x55, 0x41, 0x31, 0x52, 0x6c, 0x52, 0x45, 0x77, 0x59, 0x54, 0x30, 0x67, 0x67, 0x54, 0x33, 0x49, 0x51, + 0x50, 0x77, 0x78, 0x53, 0x4c, 0x51, 0x4d, 0x55, 0x41, 0x31, 0x46, 0x43, 0x45, 0x48, 0x64, 0x71, 0x4e, 0x41, 0x59, 0x79, 0x41, 0x33, 0x49, 0x55, 0x66, 0x41, 0x68, 0x64, + 0x55, 0x68, 0x70, 0x69, 0x66, 0x44, 0x34, 0x77, 0x66, 0x6c, 0x39, 0x2f, 0x56, 0x41, 0x39, 0x45, 0x53, 0x56, 0x31, 0x65, 0x45, 0x47, 0x6f, 0x47, 0x4b, 0x77, 0x5a, 0x54, + 0x45, 0x44, 0x6b, 0x33, 0x4d, 0x6b, 0x70, 0x4f, 0x50, 0x53, 0x74, 0x6c, 0x4f, 0x44, 0x6b, 0x48, 0x63, 0x6c, 0x52, 0x6b, 0x54, 0x56, 0x5a, 0x71, 0x41, 0x79, 0x4a, 0x77, + 0x65, 0x31, 0x39, 0x67, 0x43, 0x79, 0x6f, 0x4c, 0x61, 0x78, 0x42, 0x6b, 0x46, 0x41, 0x55, 0x69, 0x41, 0x48, 0x4e, 0x41, 0x49, 0x31, 0x74, 0x52, 0x48, 0x79, 0x73, 0x61, + 0x58, 0x57, 0x6c, 0x36, 0x52, 0x67, 0x78, 0x66, 0x4d, 0x6b, 0x74, 0x4b, 0x4b, 0x46, 0x4a, 0x35, 0x57, 0x78, 0x4a, 0x43, 0x47, 0x41, 0x42, 0x64, 0x4a, 0x7a, 0x46, 0x54, + 0x50, 0x45, 0x77, 0x32, 0x54, 0x6a, 0x67, 0x2f, 0x63, 0x67, 0x4e, 0x78, 0x41, 0x6c, 0x73, 0x32, 0x57, 0x58, 0x39, 0x31, 0x62, 0x67, 0x68, 0x55, 0x44, 0x54, 0x51, 0x63, + 0x4e, 0x46, 0x64, 0x64, 0x61, 0x55, 0x67, 0x41, 0x4f, 0x77, 0x55, 0x48, 0x62, 0x69, 0x64, 0x6c, 0x62, 0x6b, 0x41, 0x39, 0x4f, 0x6b, 0x39, 0x79, 0x58, 0x54, 0x6b, 0x57, + 0x44, 0x32, 0x4d, 0x53, 0x45, 0x68, 0x55, 0x36, 0x63, 0x41, 0x31, 0x58, 0x47, 0x41, 0x31, 0x65, 0x50, 0x53, 0x4a, 0x6f, 0x61, 0x48, 0x78, 0x74, 0x54, 0x77, 0x78, 0x37, + 0x43, 0x53, 0x31, 0x4b, 0x63, 0x79, 0x42, 0x48, 0x42, 0x31, 0x64, 0x31, 0x58, 0x56, 0x4e, 0x77, 0x4e, 0x43, 0x46, 0x41, 0x56, 0x31, 0x46, 0x65, 0x53, 0x55, 0x51, 0x41, + 0x56, 0x43, 0x63, 0x45, 0x61, 0x48, 0x35, 0x5a, 0x56, 0x6c, 0x68, 0x30, 0x46, 0x44, 0x77, 0x57, 0x4d, 0x30, 0x45, 0x57, 0x53, 0x79, 0x39, 0x4a, 0x4e, 0x77, 0x70, 0x55, + 0x43, 0x41, 0x67, 0x66, 0x4f, 0x57, 0x64, 0x32, 0x4b, 0x43, 0x67, 0x48, 0x48, 0x57, 0x46, 0x48, 0x55, 0x55, 0x31, 0x31, 0x4a, 0x6c, 0x4a, 0x48, 0x52, 0x77, 0x78, 0x58, + 0x57, 0x48, 0x51, 0x2b, 0x59, 0x6d, 0x78, 0x59, 0x4f, 0x6b, 0x51, 0x65, 0x46, 0x69, 0x34, 0x68, 0x48, 0x48, 0x4e, 0x46, 0x5a, 0x33, 0x52, 0x50, 0x4d, 0x32, 0x59, 0x4f, + 0x64, 0x47, 0x59, 0x6d, 0x48, 0x79, 0x34, 0x34, 0x52, 0x45, 0x42, 0x2b, 0x4b, 0x6c, 0x42, 0x53, 0x58, 0x6b, 0x4d, 0x42, 0x65, 0x6a, 0x68, 0x4a, 0x50, 0x46, 0x56, 0x4e, + 0x57, 0x6b, 0x51, 0x49, 0x4a, 0x6c, 0x6c, 0x4e, 0x52, 0x51, 0x74, 0x49, 0x43, 0x6a, 0x4e, 0x65, 0x53, 0x6b, 0x31, 0x31, 0x46, 0x68, 0x64, 0x6a, 0x52, 0x67, 0x45, 0x71, + 0x56, 0x58, 0x73, 0x50, 0x41, 0x6e, 0x4e, 0x71, 0x53, 0x33, 0x39, 0x31, 0x5a, 0x54, 0x78, 0x4d, 0x4d, 0x7a, 0x6c, 0x73, 0x64, 0x41, 0x56, 0x67, 0x44, 0x33, 0x38, 0x74, + 0x51, 0x55, 0x31, 0x4e, 0x52, 0x6e, 0x45, 0x4a, 0x62, 0x30, 0x39, 0x67, 0x46, 0x51, 0x39, 0x47, 0x63, 0x32, 0x4e, 0x4d, 0x58, 0x6e, 0x51, 0x77, 0x44, 0x53, 0x68, 0x44, + 0x43, 0x48, 0x49, 0x79, 0x42, 0x43, 0x34, 0x78, 0x4b, 0x53, 0x64, 0x45, 0x62, 0x52, 0x4d, 0x58, 0x53, 0x41, 0x39, 0x4a, 0x55, 0x68, 0x41, 0x54, 0x66, 0x78, 0x63, 0x57, + 0x59, 0x6e, 0x6b, 0x31, 0x65, 0x44, 0x34, 0x42, 0x66, 0x43, 0x34, 0x50, 0x64, 0x6a, 0x35, 0x65, 0x55, 0x32, 0x78, 0x62, 0x58, 0x33, 0x77, 0x5a, 0x51, 0x51, 0x49, 0x76, + 0x46, 0x32, 0x52, 0x42, 0x64, 0x52, 0x41, 0x45, 0x52, 0x33, 0x77, 0x39, 0x53, 0x31, 0x49, 0x41, 0x45, 0x46, 0x31, 0x52, 0x54, 0x6e, 0x6f, 0x6e, 0x4a, 0x56, 0x56, 0x41, + 0x45, 0x6a, 0x56, 0x67, 0x42, 0x52, 0x73, 0x30, 0x4c, 0x51, 0x52, 0x36, 0x61, 0x6d, 0x6b, 0x43, 0x65, 0x51, 0x4d, 0x36, 0x4c, 0x77, 0x59, 0x4b, 0x65, 0x58, 0x73, 0x53, + 0x58, 0x58, 0x78, 0x53, 0x4b, 0x55, 0x64, 0x59, 0x45, 0x6e, 0x4d, 0x2f, 0x4a, 0x31, 0x59, 0x46, 0x44, 0x45, 0x67, 0x79, 0x57, 0x47, 0x74, 0x58, 0x58, 0x41, 0x4e, 0x6b, + 0x56, 0x68, 0x46, 0x53, 0x65, 0x6a, 0x41, 0x32, 0x4b, 0x52, 0x63, 0x37, 0x61, 0x48, 0x70, 0x38, 0x42, 0x57, 0x74, 0x72, 0x45, 0x32, 0x6f, 0x6b, 0x58, 0x47, 0x68, 0x43, + 0x47, 0x44, 0x49, 0x44, 0x63, 0x32, 0x34, 0x45, 0x49, 0x53, 0x34, 0x42, 0x42, 0x47, 0x4e, 0x39, 0x52, 0x45, 0x45, 0x53, 0x4d, 0x51, 0x73, 0x56, 0x48, 0x33, 0x41, 0x41, + 0x4c, 0x6d, 0x59, 0x55, 0x50, 0x48, 0x38, 0x72, 0x41, 0x42, 0x38, 0x4d, 0x4b, 0x46, 0x6b, 0x4b, 0x46, 0x6b, 0x6c, 0x61, 0x58, 0x47, 0x52, 0x6c, 0x53, 0x78, 0x45, 0x70, + 0x46, 0x54, 0x5a, 0x61, 0x5a, 0x52, 0x6c, 0x50, 0x59, 0x43, 0x4d, 0x36, 0x4f, 0x68, 0x4d, 0x6c, 0x41, 0x6e, 0x68, 0x4d, 0x56, 0x41, 0x3d, 0x3d, 0x00}; char *b64_test; plan_tests(1); - base64_encode_alloc (random, 1024, &b64_test); + base64_encode_alloc(random, 1024, &b64_test); - ok(strcmp(b64_known, b64_test) == 0, - "Test matching a base64 encoded 1024 bytes random string"); + ok(strcmp(b64_known, b64_test) == 0, "Test matching a base64 encoded 1024 bytes random string"); return exit_status(); } - diff --git a/lib/tests/test_cmd.c b/lib/tests/test_cmd.c index 02ae11f..a60b64e 100644 --- a/lib/tests/test_cmd.c +++ b/lib/tests/test_cmd.c @@ -1,20 +1,20 @@ /***************************************************************************** -* -* 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 . -* -* -*****************************************************************************/ + * + * 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 . + * + * + *****************************************************************************/ #include "common.h" #include "utils_cmd.h" @@ -22,27 +22,23 @@ #include "tap.h" #define COMMAND_LINE 1024 -#define UNSET 65530 +#define UNSET 65530 -char * -get_command (char *const *line) -{ +char *get_command(char *const *line) { char *cmd; int i = 0; - asprintf (&cmd, " %s", line[i++]); + asprintf(&cmd, " %s", line[i++]); while (line[i] != NULL) { - asprintf (&cmd, "%s %s", cmd, line[i]); + asprintf(&cmd, "%s %s", cmd, line[i]); i++; } return cmd; } -int -main (int argc, char **argv) -{ - char **command_line = malloc (sizeof (char *) * COMMAND_LINE); +int main(int argc, char **argv) { + char **command_line = malloc(sizeof(char *) * COMMAND_LINE); char *command = NULL; char *perl; output chld_out, chld_err; @@ -51,183 +47,153 @@ main (int argc, char **argv) plan_tests(51); - diag ("Running plain echo command, set one"); + diag("Running plain echo command, set one"); /* ensure everything is empty before we begin */ - memset (&chld_out, 0, sizeof (output)); - memset (&chld_err, 0, sizeof (output)); - ok (chld_out.lines == 0, "(initialised) Checking stdout is reset"); - ok (chld_err.lines == 0, "(initialised) Checking stderr is reset"); - ok (result == UNSET, "(initialised) Checking exit code is reset"); - - command_line[0] = strdup ("/bin/echo"); - command_line[1] = strdup ("this"); - command_line[2] = strdup ("is"); - command_line[3] = strdup ("test"); - command_line[4] = strdup ("one"); - - command = get_command (command_line); - - result = cmd_run_array (command_line, &chld_out, &chld_err, 0); - ok (chld_out.lines == 1, - "(array) Check for expected number of stdout lines"); - ok (chld_err.lines == 0, - "(array) Check for expected number of stderr lines"); - ok (strcmp (chld_out.line[0], "this is test one") == 0, - "(array) Check for expected stdout output"); - ok (result == 0, "(array) Checking exit code"); + memset(&chld_out, 0, sizeof(output)); + memset(&chld_err, 0, sizeof(output)); + ok(chld_out.lines == 0, "(initialised) Checking stdout is reset"); + ok(chld_err.lines == 0, "(initialised) Checking stderr is reset"); + ok(result == UNSET, "(initialised) Checking exit code is reset"); + + command_line[0] = strdup("/bin/echo"); + command_line[1] = strdup("this"); + command_line[2] = strdup("is"); + command_line[3] = strdup("test"); + command_line[4] = strdup("one"); + + command = get_command(command_line); + + result = cmd_run_array(command_line, &chld_out, &chld_err, 0); + ok(chld_out.lines == 1, "(array) Check for expected number of stdout lines"); + ok(chld_err.lines == 0, "(array) Check for expected number of stderr lines"); + ok(strcmp(chld_out.line[0], "this is test one") == 0, "(array) Check for expected stdout output"); + ok(result == 0, "(array) Checking exit code"); /* ensure everything is empty again */ - memset (&chld_out, 0, sizeof (output)); - memset (&chld_err, 0, sizeof (output)); + memset(&chld_out, 0, sizeof(output)); + memset(&chld_err, 0, sizeof(output)); result = UNSET; - ok (chld_out.lines == 0, "(initialised) Checking stdout is reset"); - ok (chld_err.lines == 0, "(initialised) Checking stderr is reset"); - ok (result == UNSET, "(initialised) Checking exit code is reset"); + ok(chld_out.lines == 0, "(initialised) Checking stdout is reset"); + ok(chld_err.lines == 0, "(initialised) Checking stderr is reset"); + ok(result == UNSET, "(initialised) Checking exit code is reset"); - result = cmd_run (command, &chld_out, &chld_err, 0); + result = cmd_run(command, &chld_out, &chld_err, 0); - ok (chld_out.lines == 1, - "(string) Check for expected number of stdout lines"); - ok (chld_err.lines == 0, - "(string) Check for expected number of stderr lines"); - ok (strcmp (chld_out.line[0], "this is test one") == 0, - "(string) Check for expected stdout output"); - ok (result == 0, "(string) Checking exit code"); + ok(chld_out.lines == 1, "(string) Check for expected number of stdout lines"); + ok(chld_err.lines == 0, "(string) Check for expected number of stderr lines"); + ok(strcmp(chld_out.line[0], "this is test one") == 0, "(string) Check for expected stdout output"); + ok(result == 0, "(string) Checking exit code"); - diag ("Running plain echo command, set two"); + diag("Running plain echo command, set two"); /* ensure everything is empty again */ - memset (&chld_out, 0, sizeof (output)); - memset (&chld_err, 0, sizeof (output)); + memset(&chld_out, 0, sizeof(output)); + memset(&chld_err, 0, sizeof(output)); result = UNSET; - ok (chld_out.lines == 0, "(initialised) Checking stdout is reset"); - ok (chld_err.lines == 0, "(initialised) Checking stderr is reset"); - ok (result == UNSET, "(initialised) Checking exit code is reset"); + ok(chld_out.lines == 0, "(initialised) Checking stdout is reset"); + ok(chld_err.lines == 0, "(initialised) Checking stderr is reset"); + ok(result == UNSET, "(initialised) Checking exit code is reset"); - command_line[0] = strdup ("/bin/echo"); - command_line[1] = strdup ("this is test two"); + command_line[0] = strdup("/bin/echo"); + command_line[1] = strdup("this is test two"); command_line[2] = NULL; command_line[3] = NULL; command_line[4] = NULL; - result = cmd_run_array (command_line, &chld_out, &chld_err, 0); - ok (chld_out.lines == 1, - "(array) Check for expected number of stdout lines"); - ok (chld_err.lines == 0, - "(array) Check for expected number of stderr lines"); - ok (strcmp (chld_out.line[0], "this is test two") == 0, - "(array) Check for expected stdout output"); - ok (result == 0, "(array) Checking exit code"); + result = cmd_run_array(command_line, &chld_out, &chld_err, 0); + ok(chld_out.lines == 1, "(array) Check for expected number of stdout lines"); + ok(chld_err.lines == 0, "(array) Check for expected number of stderr lines"); + ok(strcmp(chld_out.line[0], "this is test two") == 0, "(array) Check for expected stdout output"); + ok(result == 0, "(array) Checking exit code"); /* ensure everything is empty again */ - memset (&chld_out, 0, sizeof (output)); - memset (&chld_err, 0, sizeof (output)); + memset(&chld_out, 0, sizeof(output)); + memset(&chld_err, 0, sizeof(output)); result = UNSET; - ok (chld_out.lines == 0, "(initialised) Checking stdout is reset"); - ok (chld_err.lines == 0, "(initialised) Checking stderr is reset"); - ok (result == UNSET, "(initialised) Checking exit code is reset"); - - result = cmd_run (command, &chld_out, &chld_err, 0); + ok(chld_out.lines == 0, "(initialised) Checking stdout is reset"); + ok(chld_err.lines == 0, "(initialised) Checking stderr is reset"); + ok(result == UNSET, "(initialised) Checking exit code is reset"); - ok (chld_out.lines == 1, - "(string) Check for expected number of stdout lines"); - ok (chld_err.lines == 0, - "(string) Check for expected number of stderr lines"); - ok (strcmp (chld_out.line[0], "this is test one") == 0, - "(string) Check for expected stdout output"); - ok (result == 0, "(string) Checking exit code"); + result = cmd_run(command, &chld_out, &chld_err, 0); + ok(chld_out.lines == 1, "(string) Check for expected number of stdout lines"); + ok(chld_err.lines == 0, "(string) Check for expected number of stderr lines"); + ok(strcmp(chld_out.line[0], "this is test one") == 0, "(string) Check for expected stdout output"); + ok(result == 0, "(string) Checking exit code"); /* ensure everything is empty again */ - memset (&chld_out, 0, sizeof (output)); - memset (&chld_err, 0, sizeof (output)); + memset(&chld_out, 0, sizeof(output)); + memset(&chld_err, 0, sizeof(output)); result = UNSET; - ok (chld_out.lines == 0, "(initialised) Checking stdout is reset"); - ok (chld_err.lines == 0, "(initialised) Checking stderr is reset"); - ok (result == UNSET, "(initialised) Checking exit code is reset"); + ok(chld_out.lines == 0, "(initialised) Checking stdout is reset"); + ok(chld_err.lines == 0, "(initialised) Checking stderr is reset"); + ok(result == UNSET, "(initialised) Checking exit code is reset"); /* Pass linefeeds via parameters through - those should be evaluated by echo to give multi line output */ command_line[0] = strdup("/bin/echo"); command_line[1] = strdup("this is a test via echo\nline two\nit's line 3"); command_line[2] = strdup("and (note space between '3' and 'and') $$ will not get evaluated"); - result = cmd_run_array (command_line, &chld_out, &chld_err, 0); - ok (chld_out.lines == 3, - "(array) Check for expected number of stdout lines"); - ok (chld_err.lines == 0, - "(array) Check for expected number of stderr lines"); - ok (strcmp (chld_out.line[0], "this is a test via echo") == 0, - "(array) Check line 1 for expected stdout output"); - ok (strcmp (chld_out.line[1], "line two") == 0, - "(array) Check line 2 for expected stdout output"); - ok (strcmp (chld_out.line[2], "it's line 3 and (note space between '3' and 'and') $$ will not get evaluated") == 0, - "(array) Check line 3 for expected stdout output"); - ok (result == 0, "(array) Checking exit code"); - - + result = cmd_run_array(command_line, &chld_out, &chld_err, 0); + ok(chld_out.lines == 3, "(array) Check for expected number of stdout lines"); + ok(chld_err.lines == 0, "(array) Check for expected number of stderr lines"); + ok(strcmp(chld_out.line[0], "this is a test via echo") == 0, "(array) Check line 1 for expected stdout output"); + ok(strcmp(chld_out.line[1], "line two") == 0, "(array) Check line 2 for expected stdout output"); + ok(strcmp(chld_out.line[2], "it's line 3 and (note space between '3' and 'and') $$ will not get evaluated") == 0, "(array) Check line 3 for expected stdout output"); + ok(result == 0, "(array) Checking exit code"); /* ensure everything is empty again */ - memset (&chld_out, 0, sizeof (output)); - memset (&chld_err, 0, sizeof (output)); + memset(&chld_out, 0, sizeof(output)); + memset(&chld_err, 0, sizeof(output)); result = UNSET; - ok (chld_out.lines == 0, "(initialised) Checking stdout is reset"); - ok (chld_err.lines == 0, "(initialised) Checking stderr is reset"); - ok (result == UNSET, "(initialised) Checking exit code is reset"); + ok(chld_out.lines == 0, "(initialised) Checking stdout is reset"); + ok(chld_err.lines == 0, "(initialised) Checking stderr is reset"); + ok(result == UNSET, "(initialised) Checking exit code is reset"); command = (char *)malloc(COMMAND_LINE); strcpy(command, "/bin/echo3456 non-existent command"); - result = cmd_run (command, &chld_out, &chld_err, 0); - - ok (chld_out.lines == 0, - "Non existent command, so no output"); - ok (chld_err.lines == 0, - "No stderr either"); - ok (result == 3, "Get return code 3 (?) for non-existent command"); + result = cmd_run(command, &chld_out, &chld_err, 0); + ok(chld_out.lines == 0, "Non existent command, so no output"); + ok(chld_err.lines == 0, "No stderr either"); + ok(result == 3, "Get return code 3 (?) for non-existent command"); /* ensure everything is empty again */ - memset (&chld_out, 0, sizeof (output)); - memset (&chld_err, 0, sizeof (output)); + memset(&chld_out, 0, sizeof(output)); + memset(&chld_err, 0, sizeof(output)); result = UNSET; command = (char *)malloc(COMMAND_LINE); strcpy(command, "/bin/sh non-existent-file"); - result = cmd_run (command, &chld_out, &chld_err, 0); - - ok (chld_out.lines == 0, - "/bin/sh returns no stdout when file is missing..."); - ok (chld_err.lines == 1, - "...but does give an error line"); - ok (strstr(chld_err.line[0],"non-existent-file") != NULL, "And missing filename is in error message"); - ok (result != 0, "Get non-zero return code from /bin/sh"); + result = cmd_run(command, &chld_out, &chld_err, 0); + ok(chld_out.lines == 0, "/bin/sh returns no stdout when file is missing..."); + ok(chld_err.lines == 1, "...but does give an error line"); + ok(strstr(chld_err.line[0], "non-existent-file") != NULL, "And missing filename is in error message"); + ok(result != 0, "Get non-zero return code from /bin/sh"); /* ensure everything is empty again */ result = UNSET; command = (char *)malloc(COMMAND_LINE); - strcpy(command, "/bin/sh -c 'exit 7'"); - result = cmd_run (command, NULL, NULL, 0); - - ok (result == 7, "Get return code 7 from /bin/sh"); + strcpy(command, "/bin/sh -c 'exit 7'"); + result = cmd_run(command, NULL, NULL, 0); + ok(result == 7, "Get return code 7 from /bin/sh"); /* ensure everything is empty again */ - memset (&chld_out, 0, sizeof (output)); - memset (&chld_err, 0, sizeof (output)); + memset(&chld_out, 0, sizeof(output)); + memset(&chld_err, 0, sizeof(output)); result = UNSET; command = (char *)malloc(COMMAND_LINE); strcpy(command, "/bin/non-existent-command"); - result = cmd_run (command, &chld_out, &chld_err, 0); - - ok (chld_out.lines == 0, - "/bin/non-existent-command returns no stdout..."); - ok (chld_err.lines == 0, - "...and no stderr output either"); - ok (result == 3, "Get return code 3 = UNKNOWN when command does not exist"); + result = cmd_run(command, &chld_out, &chld_err, 0); + ok(chld_out.lines == 0, "/bin/non-existent-command returns no stdout..."); + ok(chld_err.lines == 0, "...and no stderr output either"); + ok(result == 3, "Get return code 3 = UNKNOWN when command does not exist"); - return exit_status (); + return exit_status(); } diff --git a/lib/tests/test_disk.c b/lib/tests/test_disk.c index e283fe2..c18db7a 100644 --- a/lib/tests/test_disk.c +++ b/lib/tests/test_disk.c @@ -1,36 +1,31 @@ /***************************************************************************** -* -* 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 . -* -* -*****************************************************************************/ + * + * 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 . + * + * + *****************************************************************************/ #include "common.h" #include "utils_disk.h" #include "tap.h" #include "regex.h" -void np_test_mount_entry_regex (struct mount_entry *dummy_mount_list, - char *regstr, int cflags, int expect, - char *desc); +void np_test_mount_entry_regex(struct mount_entry *dummy_mount_list, char *regstr, int cflags, int expect, char *desc); - -int -main (int argc, char **argv) -{ - struct name_list *exclude_filesystem=NULL; - struct name_list *exclude_fstype=NULL; +int main(int argc, char **argv) { + struct name_list *exclude_filesystem = NULL; + struct name_list *exclude_fstype = NULL; struct name_list *dummy_mountlist = NULL; struct name_list *temp_name; struct parameter_list *paths = NULL; @@ -44,19 +39,19 @@ main (int argc, char **argv) plan_tests(33); - ok( np_find_name(exclude_filesystem, "/var/log") == false, "/var/log not in list"); + ok(np_find_name(exclude_filesystem, "/var/log") == false, "/var/log not in list"); np_add_name(&exclude_filesystem, "/var/log"); - ok( np_find_name(exclude_filesystem, "/var/log") == true, "is in list now"); - ok( np_find_name(exclude_filesystem, "/home") == false, "/home not in list"); + ok(np_find_name(exclude_filesystem, "/var/log") == true, "is in list now"); + ok(np_find_name(exclude_filesystem, "/home") == false, "/home not in list"); np_add_name(&exclude_filesystem, "/home"); - ok( np_find_name(exclude_filesystem, "/home") == true, "is in list now"); - ok( np_find_name(exclude_filesystem, "/var/log") == true, "/var/log still in list"); + ok(np_find_name(exclude_filesystem, "/home") == true, "is in list now"); + ok(np_find_name(exclude_filesystem, "/var/log") == true, "/var/log still in list"); - ok( np_find_name(exclude_fstype, "iso9660") == false, "iso9660 not in list"); + ok(np_find_name(exclude_fstype, "iso9660") == false, "iso9660 not in list"); np_add_name(&exclude_fstype, "iso9660"); - ok( np_find_name(exclude_fstype, "iso9660") == true, "is in list now"); + ok(np_find_name(exclude_fstype, "iso9660") == true, "is in list now"); - ok( np_find_name(exclude_filesystem, "iso9660") == false, "Make sure no clashing in variables"); + ok(np_find_name(exclude_filesystem, "iso9660") == false, "Make sure no clashing in variables"); /* for (temp_name = exclude_filesystem; temp_name; temp_name = temp_name->next) { @@ -64,55 +59,35 @@ main (int argc, char **argv) } */ - me = (struct mount_entry *) malloc(sizeof *me); + me = (struct mount_entry *)malloc(sizeof *me); me->me_devname = strdup("/dev/c0t0d0s0"); me->me_mountdir = strdup("/"); *mtail = me; mtail = &me->me_next; - me = (struct mount_entry *) malloc(sizeof *me); + me = (struct mount_entry *)malloc(sizeof *me); me->me_devname = strdup("/dev/c1t0d1s0"); me->me_mountdir = strdup("/var"); *mtail = me; mtail = &me->me_next; - me = (struct mount_entry *) malloc(sizeof *me); + me = (struct mount_entry *)malloc(sizeof *me); me->me_devname = strdup("/dev/c2t0d0s0"); me->me_mountdir = strdup("/home"); *mtail = me; mtail = &me->me_next; - np_test_mount_entry_regex(dummy_mount_list, strdup("/"), - cflags, 3, strdup("a")); - np_test_mount_entry_regex(dummy_mount_list, strdup("/dev"), - cflags, 3,strdup("regex on dev names:")); - np_test_mount_entry_regex(dummy_mount_list, strdup("/foo"), - cflags, 0, - strdup("regex on non existent dev/path:")); - np_test_mount_entry_regex(dummy_mount_list, strdup("/Foo"), - cflags | REG_ICASE,0, - strdup("regi on non existent dev/path:")); - np_test_mount_entry_regex(dummy_mount_list, strdup("/c.t0"), - cflags, 3, - strdup("partial devname regex match:")); - np_test_mount_entry_regex(dummy_mount_list, strdup("c0t0"), - cflags, 1, - strdup("partial devname regex match:")); - np_test_mount_entry_regex(dummy_mount_list, strdup("C0t0"), - cflags | REG_ICASE, 1, - strdup("partial devname regi match:")); - np_test_mount_entry_regex(dummy_mount_list, strdup("home"), - cflags, 1, - strdup("partial pathname regex match:")); - np_test_mount_entry_regex(dummy_mount_list, strdup("hOme"), - cflags | REG_ICASE, 1, - strdup("partial pathname regi match:")); - np_test_mount_entry_regex(dummy_mount_list, strdup("(/home)|(/var)"), - cflags, 2, - strdup("grouped regex pathname match:")); - np_test_mount_entry_regex(dummy_mount_list, strdup("(/homE)|(/Var)"), - cflags | REG_ICASE, 2, - strdup("grouped regi pathname match:")); + np_test_mount_entry_regex(dummy_mount_list, strdup("/"), cflags, 3, strdup("a")); + np_test_mount_entry_regex(dummy_mount_list, strdup("/dev"), cflags, 3, strdup("regex on dev names:")); + np_test_mount_entry_regex(dummy_mount_list, strdup("/foo"), cflags, 0, strdup("regex on non existent dev/path:")); + np_test_mount_entry_regex(dummy_mount_list, strdup("/Foo"), cflags | REG_ICASE, 0, strdup("regi on non existent dev/path:")); + np_test_mount_entry_regex(dummy_mount_list, strdup("/c.t0"), cflags, 3, strdup("partial devname regex match:")); + np_test_mount_entry_regex(dummy_mount_list, strdup("c0t0"), cflags, 1, strdup("partial devname regex match:")); + np_test_mount_entry_regex(dummy_mount_list, strdup("C0t0"), cflags | REG_ICASE, 1, strdup("partial devname regi match:")); + np_test_mount_entry_regex(dummy_mount_list, strdup("home"), cflags, 1, strdup("partial pathname regex match:")); + np_test_mount_entry_regex(dummy_mount_list, strdup("hOme"), cflags | REG_ICASE, 1, strdup("partial pathname regi match:")); + np_test_mount_entry_regex(dummy_mount_list, strdup("(/home)|(/var)"), cflags, 2, strdup("grouped regex pathname match:")); + np_test_mount_entry_regex(dummy_mount_list, strdup("(/homE)|(/Var)"), cflags | REG_ICASE, 2, strdup("grouped regi pathname match:")); np_add_parameter(&paths, "/home/groups"); np_add_parameter(&paths, "/var"); @@ -124,20 +99,20 @@ main (int argc, char **argv) for (p = paths; p; p = p->name_next) { struct mount_entry *temp_me; temp_me = p->best_match; - if (! strcmp(p->name, "/home/groups")) { - ok( temp_me && !strcmp(temp_me->me_mountdir, "/home"), "/home/groups got right best match: /home"); - } else if (! strcmp(p->name, "/var")) { - ok( temp_me && !strcmp(temp_me->me_mountdir, "/var"), "/var got right best match: /var"); - } else if (! strcmp(p->name, "/tmp")) { - ok( temp_me && !strcmp(temp_me->me_mountdir, "/"), "/tmp got right best match: /"); - } else if (! strcmp(p->name, "/home/tonvoon")) { - ok( temp_me && !strcmp(temp_me->me_mountdir, "/home"), "/home/tonvoon got right best match: /home"); - } else if (! strcmp(p->name, "/dev/c2t0d0s0")) { - ok( temp_me && !strcmp(temp_me->me_devname, "/dev/c2t0d0s0"), "/dev/c2t0d0s0 got right best match: /dev/c2t0d0s0"); + if (!strcmp(p->name, "/home/groups")) { + ok(temp_me && !strcmp(temp_me->me_mountdir, "/home"), "/home/groups got right best match: /home"); + } else if (!strcmp(p->name, "/var")) { + ok(temp_me && !strcmp(temp_me->me_mountdir, "/var"), "/var got right best match: /var"); + } else if (!strcmp(p->name, "/tmp")) { + ok(temp_me && !strcmp(temp_me->me_mountdir, "/"), "/tmp got right best match: /"); + } else if (!strcmp(p->name, "/home/tonvoon")) { + ok(temp_me && !strcmp(temp_me->me_mountdir, "/home"), "/home/tonvoon got right best match: /home"); + } else if (!strcmp(p->name, "/dev/c2t0d0s0")) { + ok(temp_me && !strcmp(temp_me->me_devname, "/dev/c2t0d0s0"), "/dev/c2t0d0s0 got right best match: /dev/c2t0d0s0"); } } - paths = NULL; /* Bad boy - should free, but this is a test suite */ + paths = NULL; /* Bad boy - should free, but this is a test suite */ np_add_parameter(&paths, "/home/groups"); np_add_parameter(&paths, "/var"); np_add_parameter(&paths, "/tmp"); @@ -146,31 +121,31 @@ main (int argc, char **argv) np_set_best_match(paths, dummy_mount_list, true); for (p = paths; p; p = p->name_next) { - if (! strcmp(p->name, "/home/groups")) { - ok( ! p->best_match , "/home/groups correctly not found"); - } else if (! strcmp(p->name, "/var")) { - ok( p->best_match, "/var found"); - } else if (! strcmp(p->name, "/tmp")) { - ok(! p->best_match, "/tmp correctly not found"); - } else if (! strcmp(p->name, "/home/tonvoon")) { - ok(! p->best_match, "/home/tonvoon not found"); - } else if (! strcmp(p->name, "/home")) { - ok( p->best_match, "/home found"); + if (!strcmp(p->name, "/home/groups")) { + ok(!p->best_match, "/home/groups correctly not found"); + } else if (!strcmp(p->name, "/var")) { + ok(p->best_match, "/var found"); + } else if (!strcmp(p->name, "/tmp")) { + ok(!p->best_match, "/tmp correctly not found"); + } else if (!strcmp(p->name, "/home/tonvoon")) { + ok(!p->best_match, "/home/tonvoon not found"); + } else if (!strcmp(p->name, "/home")) { + ok(p->best_match, "/home found"); } } /* test deleting first element in paths */ paths = np_del_parameter(paths, NULL); for (p = paths; p; p = p->name_next) { - if (! strcmp(p->name, "/home/groups")) + if (!strcmp(p->name, "/home/groups")) found = 1; } ok(found == 0, "first element successfully deleted"); found = 0; - p=paths; + p = paths; while (p) { - if (! strcmp(p->name, "/tmp")) + if (!strcmp(p->name, "/tmp")) p = np_del_parameter(p, prev); else { prev = p; @@ -179,7 +154,7 @@ main (int argc, char **argv) } for (p = paths; p; p = p->name_next) { - if (! strcmp(p->name, "/tmp")) + if (!strcmp(p->name, "/tmp")) found = 1; if (p->name_next) prev = p; @@ -190,7 +165,7 @@ main (int argc, char **argv) p = np_del_parameter(last, prev); for (p = paths; p; p = p->name_next) { - if (! strcmp(p->name, "/home")) + if (!strcmp(p->name, "/home")) found = 1; last = p; count++; @@ -198,27 +173,20 @@ main (int argc, char **argv) ok(found == 0, "last (/home) element successfully deleted"); ok(count == 2, "two elements remaining"); - return exit_status(); } - -void -np_test_mount_entry_regex (struct mount_entry *dummy_mount_list, char *regstr, int cflags, int expect, char *desc) -{ +void np_test_mount_entry_regex(struct mount_entry *dummy_mount_list, char *regstr, int cflags, int expect, char *desc) { int matches = 0; regex_t re; struct mount_entry *me; - if (regcomp(&re,regstr, cflags) == 0) { - for (me = dummy_mount_list; me; me= me->me_next) { - if(np_regex_match_mount_entry(me,&re)) + if (regcomp(&re, regstr, cflags) == 0) { + for (me = dummy_mount_list; me; me = me->me_next) { + if (np_regex_match_mount_entry(me, &re)) matches++; } - ok( matches == expect, - "%s '%s' matched %i/3 entries. ok: %i/3", - desc, regstr, expect, matches); + ok(matches == expect, "%s '%s' matched %i/3 entries. ok: %i/3", desc, regstr, expect, matches); } else - ok ( false, "regex '%s' not compilable", regstr); + ok(false, "regex '%s' not compilable", regstr); } - diff --git a/lib/tests/test_ini1.c b/lib/tests/test_ini1.c index 6843bac..711fef9 100644 --- a/lib/tests/test_ini1.c +++ b/lib/tests/test_ini1.c @@ -1,20 +1,20 @@ /***************************************************************************** -* -* 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 . -* -* -*****************************************************************************/ + * + * 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 . + * + * + *****************************************************************************/ #include "common.h" #include "utils_base.h" @@ -29,81 +29,86 @@ void my_free(char *string) { } } -char* -list2str(np_arg_list *optlst) -{ - char *optstr=NULL; +char *list2str(np_arg_list *optlst) { + char *optstr = NULL; np_arg_list *optltmp; /* Put everything as a space-separated string */ asprintf(&optstr, ""); while (optlst) { asprintf(&optstr, "%s%s ", optstr, optlst->arg); - optltmp=optlst; - optlst=optlst->next; + optltmp = optlst; + optlst = optlst->next; free(optltmp); } /* Strip last whitespace */ - if (strlen(optstr)>1) optstr[strlen(optstr)-1]='\0'; + if (strlen(optstr) > 1) + optstr[strlen(optstr) - 1] = '\0'; return optstr; } -int -main (int argc, char **argv) -{ - char *optstr=NULL; +int main(int argc, char **argv) { + char *optstr = NULL; plan_tests(12); - optstr=list2str(np_get_defaults("section@./config-tiny.ini", "check_disk")); - ok( !strcmp(optstr, "--one=two --Foo=Bar --this=Your Mother! --blank"), "config-tiny.ini's section as expected"); + optstr = list2str(np_get_defaults("section@./config-tiny.ini", "check_disk")); + ok(!strcmp(optstr, "--one=two --Foo=Bar --this=Your Mother! --blank"), "config-tiny.ini's section as expected"); my_free(optstr); - optstr=list2str(np_get_defaults("@./config-tiny.ini", "section")); - ok( !strcmp(optstr, "--one=two --Foo=Bar --this=Your Mother! --blank"), "Used default section name, without specific"); + optstr = list2str(np_get_defaults("@./config-tiny.ini", "section")); + ok(!strcmp(optstr, "--one=two --Foo=Bar --this=Your Mother! --blank"), "Used default section name, without specific"); my_free(optstr); - optstr=list2str(np_get_defaults("Section Two@./config-tiny.ini", "check_disk")); - ok( !strcmp(optstr, "--something else=blah --remove=whitespace"), "config-tiny.ini's Section Two as expected"); + optstr = list2str(np_get_defaults("Section Two@./config-tiny.ini", "check_disk")); + ok(!strcmp(optstr, "--something else=blah --remove=whitespace"), "config-tiny.ini's Section Two as expected"); my_free(optstr); - optstr=list2str(np_get_defaults("/path/to/file.txt@./config-tiny.ini", "check_disk")); - ok( !strcmp(optstr, "--this=that"), "config-tiny.ini's filename as section name"); + optstr = list2str(np_get_defaults("/path/to/file.txt@./config-tiny.ini", "check_disk")); + ok(!strcmp(optstr, "--this=that"), "config-tiny.ini's filename as section name"); my_free(optstr); - optstr=list2str(np_get_defaults("section2@./config-tiny.ini", "check_disk")); - ok( !strcmp(optstr, "--this=that"), "config-tiny.ini's section2 with whitespace before section name"); + optstr = list2str(np_get_defaults("section2@./config-tiny.ini", "check_disk")); + ok(!strcmp(optstr, "--this=that"), "config-tiny.ini's section2 with whitespace before section name"); my_free(optstr); - optstr=list2str(np_get_defaults("section3@./config-tiny.ini", "check_disk")); - ok( !strcmp(optstr, "--this=that"), "config-tiny.ini's section3 with whitespace after section name"); + optstr = list2str(np_get_defaults("section3@./config-tiny.ini", "check_disk")); + ok(!strcmp(optstr, "--this=that"), "config-tiny.ini's section3 with whitespace after section name"); my_free(optstr); - optstr=list2str(np_get_defaults("check_mysql@./plugin.ini", "check_disk")); - ok( !strcmp(optstr, "--username=operator --password=secret"), "plugin.ini's check_mysql as expected"); + optstr = list2str(np_get_defaults("check_mysql@./plugin.ini", "check_disk")); + ok(!strcmp(optstr, "--username=operator --password=secret"), "plugin.ini's check_mysql as expected"); my_free(optstr); - optstr=list2str(np_get_defaults("check_mysql2@./plugin.ini", "check_disk")); - ok( !strcmp(optstr, "-u=admin -p=secret"), "plugin.ini's check_mysql2 as expected"); + optstr = list2str(np_get_defaults("check_mysql2@./plugin.ini", "check_disk")); + ok(!strcmp(optstr, "-u=admin -p=secret"), "plugin.ini's check_mysql2 as expected"); my_free(optstr); - optstr=list2str(np_get_defaults("check space_and_flags@./plugin.ini", "check_disk")); - ok( !strcmp(optstr, "--foo=bar -a -b --bar"), "plugin.ini space in stanza and flag arguments"); + optstr = list2str(np_get_defaults("check space_and_flags@./plugin.ini", "check_disk")); + ok(!strcmp(optstr, "--foo=bar -a -b --bar"), "plugin.ini space in stanza and flag arguments"); my_free(optstr); - optstr=list2str(np_get_defaults("Section Two@./config-dos.ini", "check_disk")); - ok( !strcmp(optstr, "--something else=blah --remove=whitespace"), "config-dos.ini's Section Two as expected"); + optstr = list2str(np_get_defaults("Section Two@./config-dos.ini", "check_disk")); + ok(!strcmp(optstr, "--something else=blah --remove=whitespace"), "config-dos.ini's Section Two as expected"); my_free(optstr); - optstr=list2str(np_get_defaults("section_twice@./plugin.ini", "check_disk")); - ok( !strcmp(optstr, "--foo=bar --bar=foo"), "plugin.ini's section_twice defined twice in the file"); + optstr = list2str(np_get_defaults("section_twice@./plugin.ini", "check_disk")); + ok(!strcmp(optstr, "--foo=bar --bar=foo"), "plugin.ini's section_twice defined twice in the file"); my_free(optstr); - optstr=list2str(np_get_defaults("tcp_long_lines@plugins.ini", "check_tcp")); - ok( !strcmp(optstr, "--escape --send=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda --expect=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda --jail"), "Long options"); + optstr = list2str(np_get_defaults("tcp_long_lines@plugins.ini", "check_tcp")); + ok(!strcmp(optstr, + "--escape --send=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " + "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo " + "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " + "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda --expect=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " + "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " + "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo " + "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " + "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda --jail"), + "Long options"); my_free(optstr); return exit_status(); } - diff --git a/lib/tests/test_ini3.c b/lib/tests/test_ini3.c index 8a2a041..2186e4b 100644 --- a/lib/tests/test_ini3.c +++ b/lib/tests/test_ini3.c @@ -1,26 +1,24 @@ /***************************************************************************** -* -* 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 . -* -* -*****************************************************************************/ + * + * 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 . + * + * + *****************************************************************************/ #include "parse_ini.h" -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { /* * This is for testing arguments expected to die. @@ -30,4 +28,3 @@ main (int argc, char **argv) return 0; } - diff --git a/lib/tests/test_opts1.c b/lib/tests/test_opts1.c index 077c5b6..e32115c 100644 --- a/lib/tests/test_opts1.c +++ b/lib/tests/test_opts1.c @@ -1,19 +1,19 @@ /***************************************************************************** -* -* 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 . -* -*****************************************************************************/ + * + * 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 . + * + *****************************************************************************/ #include "common.h" #include "utils_base.h" @@ -40,23 +40,24 @@ void my_free(int *argc, char **newargv, char **argv) { #else void my_free(int *argc, char **newargv, char **argv) { /* Free stuff (and print while we're at it) */ - int i, freeflag=1; - printf (" Arg(%i): ", *argc+1); - printf ("'%s' ", newargv[0]); - for (i=1; i<*argc; i++) { - printf ("'%s' ", newargv[i]); + int i, freeflag = 1; + printf(" Arg(%i): ", *argc + 1); + printf("'%s' ", newargv[0]); + for (i = 1; i < *argc; i++) { + printf("'%s' ", newargv[i]); /* Stop freeing when we get to the start of the original array */ if (freeflag) { if (newargv[i] == argv[1]) - freeflag=0; + freeflag = 0; else free(newargv[i]); } } - printf ("\n"); + printf("\n"); /* Free only if it's a different array */ - if (newargv != argv) free(newargv); - *argc=0; + if (newargv != argv) + free(newargv); + *argc = 0; } #endif @@ -67,9 +68,10 @@ int array_diff(int i1, char **a1, int i2, char **a2) { printf(" Argument count doesn't match!\n"); return 0; } - for (i=0; i<=i1; i++) { - if (a1[i]==NULL && a2[i]==NULL) continue; - if (a1[i]==NULL || a2[i]==NULL) { + for (i = 0; i <= i1; i++) { + if (a1[i] == NULL && a2[i] == NULL) + continue; + if (a1[i] == NULL || a2[i] == NULL) { printf(" Argument # %i null in one array!\n", i); return 0; } @@ -81,59 +83,56 @@ int array_diff(int i1, char **a1, int i2, char **a2) { return 1; } -int -main (int argc, char **argv) -{ - char **argv_new=NULL; +int main(int argc, char **argv) { + char **argv_new = NULL; int i, argc_test; plan_tests(5); { - char *argv_test[] = {"prog_name", (char *) NULL}; - argc_test=1; - char *argv_known[] = {"prog_name", (char *) NULL}; - argv_new=np_extra_opts(&argc_test, argv_test, "check_disk"); + char *argv_test[] = {"prog_name", (char *)NULL}; + argc_test = 1; + char *argv_known[] = {"prog_name", (char *)NULL}; + argv_new = np_extra_opts(&argc_test, argv_test, "check_disk"); ok(array_diff(argc_test, argv_new, 1, argv_known), "No opts, returns correct argv/argc"); my_free(&argc_test, argv_new, argv_test); } { - char *argv_test[] = {"prog_name", "arg1", "--arg2=val1", "--arg3", "val2", (char *) NULL}; - argc_test=5; - char *argv_known[] = {"prog_name", "arg1", "--arg2=val1", "--arg3", "val2", (char *) NULL}; - argv_new=np_extra_opts(&argc_test, argv_test, "check_disk"); + char *argv_test[] = {"prog_name", "arg1", "--arg2=val1", "--arg3", "val2", (char *)NULL}; + argc_test = 5; + char *argv_known[] = {"prog_name", "arg1", "--arg2=val1", "--arg3", "val2", (char *)NULL}; + argv_new = np_extra_opts(&argc_test, argv_test, "check_disk"); ok(array_diff(argc_test, argv_new, 5, argv_known), "No extra opts, verbatim copy of argv"); my_free(&argc_test, argv_new, argv_test); } { - char *argv_test[] = {"prog_name", "--extra-opts=@./config-opts.ini", (char *) NULL}; - argc_test=2; - char *argv_known[] = {"prog_name", "--foo=Bar", "--this=Your Mother!", "--blank", (char *) NULL}; - argv_new=np_extra_opts(&argc_test, argv_test, "check_disk"); + char *argv_test[] = {"prog_name", "--extra-opts=@./config-opts.ini", (char *)NULL}; + argc_test = 2; + char *argv_known[] = {"prog_name", "--foo=Bar", "--this=Your Mother!", "--blank", (char *)NULL}; + argv_new = np_extra_opts(&argc_test, argv_test, "check_disk"); ok(array_diff(argc_test, argv_new, 4, argv_known), "Only extra opts using default section"); my_free(&argc_test, argv_new, argv_test); } { - char *argv_test[] = {"prog_name", "--extra-opts=sect1@./config-opts.ini", "--extra-opts", "sect2@./config-opts.ini", (char *) NULL}; - argc_test=4; - char *argv_known[] = {"prog_name", "--one=two", "--something else=oops", "--this=that", (char *) NULL}; - argv_new=np_extra_opts(&argc_test, argv_test, "check_disk"); + char *argv_test[] = {"prog_name", "--extra-opts=sect1@./config-opts.ini", "--extra-opts", "sect2@./config-opts.ini", (char *)NULL}; + argc_test = 4; + char *argv_known[] = {"prog_name", "--one=two", "--something else=oops", "--this=that", (char *)NULL}; + argv_new = np_extra_opts(&argc_test, argv_test, "check_disk"); ok(array_diff(argc_test, argv_new, 4, argv_known), "Only extra opts specified twice"); my_free(&argc_test, argv_new, argv_test); } { - char *argv_test[] = {"prog_name", "--arg1=val1", "--extra-opts=@./config-opts.ini", "--extra-opts", "sect1@./config-opts.ini", "--arg2", (char *) NULL}; - argc_test=6; - char *argv_known[] = {"prog_name", "--foo=Bar", "--this=Your Mother!", "--blank", "--one=two", "--arg1=val1", "--arg2", (char *) NULL}; - argv_new=np_extra_opts(&argc_test, argv_test, "check_disk"); + char *argv_test[] = {"prog_name", "--arg1=val1", "--extra-opts=@./config-opts.ini", "--extra-opts", "sect1@./config-opts.ini", "--arg2", (char *)NULL}; + argc_test = 6; + char *argv_known[] = {"prog_name", "--foo=Bar", "--this=Your Mother!", "--blank", "--one=two", "--arg1=val1", "--arg2", (char *)NULL}; + argv_new = np_extra_opts(&argc_test, argv_test, "check_disk"); ok(array_diff(argc_test, argv_new, 7, argv_known), "twice extra opts using two sections"); my_free(&argc_test, argv_new, argv_test); } return exit_status(); } - diff --git a/lib/tests/test_opts2.c b/lib/tests/test_opts2.c index 780220e..95c6505 100644 --- a/lib/tests/test_opts2.c +++ b/lib/tests/test_opts2.c @@ -1,19 +1,19 @@ /***************************************************************************** -* -* 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 . -* -*****************************************************************************/ + * + * 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 . + * + *****************************************************************************/ #include "common.h" #include "utils_base.h" @@ -23,23 +23,24 @@ void my_free(int *argc, char **newargv, char **argv) { /* Free stuff (and print while we're at it) */ - int i, freeflag=1; - printf (" Arg(%i): ", *argc+1); - printf ("'%s' ", newargv[0]); - for (i=1; i<*argc; i++) { - printf ("'%s' ", newargv[i]); + int i, freeflag = 1; + printf(" Arg(%i): ", *argc + 1); + printf("'%s' ", newargv[0]); + for (i = 1; i < *argc; i++) { + printf("'%s' ", newargv[i]); /* Stop freeing when we get to the start of the original array */ if (freeflag) { if (newargv[i] == argv[1]) - freeflag=0; + freeflag = 0; else free(newargv[i]); } } - printf ("\n"); + printf("\n"); /* Free only if it's a different array */ - if (newargv != argv) free(newargv); - *argc=0; + if (newargv != argv) + free(newargv); + *argc = 0; } int array_diff(int i1, char **a1, int i2, char **a2) { @@ -49,9 +50,10 @@ int array_diff(int i1, char **a1, int i2, char **a2) { printf(" Argument count doesn't match!\n"); return 0; } - for (i=0; i<=i1; i++) { - if (a1[i]==NULL && a2[i]==NULL) continue; - if (a1[i]==NULL || a2[i]==NULL) { + for (i = 0; i <= i1; i++) { + if (a1[i] == NULL && a2[i] == NULL) + continue; + if (a1[i] == NULL || a2[i] == NULL) { printf(" Argument # %i null in one array!\n", i); return 0; } @@ -63,59 +65,69 @@ int array_diff(int i1, char **a1, int i2, char **a2) { return 1; } -int -main (int argc, char **argv) -{ - char **argv_new=NULL; +int main(int argc, char **argv) { + char **argv_new = NULL; int i, argc_test; plan_tests(5); { - char *argv_test[] = {"prog_name", "arg1", "--extra-opts", "--arg3", "val2", (char *) NULL}; - argc_test=5; - char *argv_known[] = {"prog_name", "--foo=bar", "arg1", "--arg3", "val2", (char *) NULL}; - argv_new=np_extra_opts(&argc_test, argv_test, "check_disk"); + char *argv_test[] = {"prog_name", "arg1", "--extra-opts", "--arg3", "val2", (char *)NULL}; + argc_test = 5; + char *argv_known[] = {"prog_name", "--foo=bar", "arg1", "--arg3", "val2", (char *)NULL}; + argv_new = np_extra_opts(&argc_test, argv_test, "check_disk"); ok(array_diff(argc_test, argv_new, 5, argv_known), "Default section 1"); my_free(&argc_test, argv_new, argv_test); } { - char *argv_test[] = {"prog_name", "--extra-opts", (char *) NULL}; - argc_test=2; - char *argv_known[] = {"prog_name", "--foo=bar", (char *) NULL}; - argv_new=np_extra_opts(&argc_test, argv_test, "check_disk"); + char *argv_test[] = {"prog_name", "--extra-opts", (char *)NULL}; + argc_test = 2; + char *argv_known[] = {"prog_name", "--foo=bar", (char *)NULL}; + argv_new = np_extra_opts(&argc_test, argv_test, "check_disk"); ok(array_diff(argc_test, argv_new, 2, argv_known), "Default section 2"); my_free(&argc_test, argv_new, argv_test); } { - char *argv_test[] = {"prog_name", "arg1", "--extra-opts=section1", "--arg3", "val2", (char *) NULL}; - argc_test=5; - char *argv_known[] = {"prog_name", "--foobar=baz", "arg1", "--arg3", "val2", (char *) NULL}; - argv_new=np_extra_opts(&argc_test, argv_test, "check_disk"); + char *argv_test[] = {"prog_name", "arg1", "--extra-opts=section1", "--arg3", "val2", (char *)NULL}; + argc_test = 5; + char *argv_known[] = {"prog_name", "--foobar=baz", "arg1", "--arg3", "val2", (char *)NULL}; + argv_new = np_extra_opts(&argc_test, argv_test, "check_disk"); ok(array_diff(argc_test, argv_new, 5, argv_known), "Default section 3"); my_free(&argc_test, argv_new, argv_test); } { - char *argv_test[] = {"prog_name", "arg1", "--extra-opts", "-arg3", "val2", (char *) NULL}; - argc_test=5; - char *argv_known[] = {"prog_name", "--foo=bar", "arg1", "-arg3", "val2", (char *) NULL}; - argv_new=np_extra_opts(&argc_test, argv_test, "check_disk"); + char *argv_test[] = {"prog_name", "arg1", "--extra-opts", "-arg3", "val2", (char *)NULL}; + argc_test = 5; + char *argv_known[] = {"prog_name", "--foo=bar", "arg1", "-arg3", "val2", (char *)NULL}; + argv_new = np_extra_opts(&argc_test, argv_test, "check_disk"); ok(array_diff(argc_test, argv_new, 5, argv_known), "Default section 4"); my_free(&argc_test, argv_new, argv_test); } { - char *argv_test[] = {"check_tcp", "--extra-opts", "--extra-opts=tcp_long_lines", (char *) NULL}; - argc_test=3; - char *argv_known[] = {"check_tcp", "--timeout=10", "--escape", "--send=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda", "--expect=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda", "--jail", (char *) NULL}; - argv_new=np_extra_opts(&argc_test, argv_test, "check_tcp"); + char *argv_test[] = {"check_tcp", "--extra-opts", "--extra-opts=tcp_long_lines", (char *)NULL}; + argc_test = 3; + char *argv_known[] = {"check_tcp", + "--timeout=10", + "--escape", + "--send=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda " + "yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " + "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar " + "BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda", + "--expect=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda " + "yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " + "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar " + "BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo " + "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda", + "--jail", + (char *)NULL}; + argv_new = np_extra_opts(&argc_test, argv_test, "check_tcp"); ok(array_diff(argc_test, argv_new, 6, argv_known), "Long lines test"); my_free(&argc_test, argv_new, argv_test); } return exit_status(); } - diff --git a/lib/tests/test_opts3.c b/lib/tests/test_opts3.c index b64270d..cecea43 100644 --- a/lib/tests/test_opts3.c +++ b/lib/tests/test_opts3.c @@ -1,31 +1,28 @@ /***************************************************************************** -* -* 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 . -* -*****************************************************************************/ + * + * 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 . + * + *****************************************************************************/ #include "extra_opts.h" -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { /* * This is for testing arguments expected to die. */ - argv=np_extra_opts(&argc, argv, argv[0]); + argv = np_extra_opts(&argc, argv, argv[0]); return 0; } - diff --git a/lib/tests/test_tcp.c b/lib/tests/test_tcp.c index 1954b0f..b09c005 100644 --- a/lib/tests/test_tcp.c +++ b/lib/tests/test_tcp.c @@ -1,58 +1,46 @@ /***************************************************************************** -* -* 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 . -* -* -*****************************************************************************/ + * + * 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 . + * + * + *****************************************************************************/ #include "common.h" #include "utils_tcp.h" #include "tap.h" -int -main(void) -{ +int main(void) { char **server_expect; int server_expect_count = 3; plan_tests(9); - server_expect = malloc(sizeof(char*) * server_expect_count); + server_expect = malloc(sizeof(char *) * server_expect_count); server_expect[0] = strdup("AA"); server_expect[1] = strdup("bb"); server_expect[2] = strdup("CC"); - ok(np_expect_match("AA bb CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_SUCCESS, - "Test matching any string at the beginning (first expect string)"); - ok(np_expect_match("bb AA CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_SUCCESS, - "Test matching any string at the beginning (second expect string)"); - ok(np_expect_match("b", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_RETRY, - "Test matching any string at the beginning (substring match)"); - ok(np_expect_match("XX bb AA CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_FAILURE, - "Test with strings not matching at the beginning"); - ok(np_expect_match("XX CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_FAILURE, - "Test matching any string"); - ok(np_expect_match("XX", server_expect, server_expect_count, 0) == NP_MATCH_RETRY, - "Test not matching any string"); - ok(np_expect_match("XX AA bb CC XX", server_expect, server_expect_count, NP_MATCH_ALL) == NP_MATCH_SUCCESS, - "Test matching all strings"); - ok(np_expect_match("XX bb CC XX", server_expect, server_expect_count, NP_MATCH_ALL) == NP_MATCH_RETRY, - "Test not matching all strings"); - ok(np_expect_match("XX XX", server_expect, server_expect_count, NP_MATCH_ALL) == NP_MATCH_RETRY, - "Test not matching any string (testing all)"); - + ok(np_expect_match("AA bb CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_SUCCESS, "Test matching any string at the beginning (first expect string)"); + ok(np_expect_match("bb AA CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_SUCCESS, "Test matching any string at the beginning (second expect string)"); + ok(np_expect_match("b", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_RETRY, "Test matching any string at the beginning (substring match)"); + ok(np_expect_match("XX bb AA CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_FAILURE, "Test with strings not matching at the beginning"); + ok(np_expect_match("XX CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_FAILURE, "Test matching any string"); + ok(np_expect_match("XX", server_expect, server_expect_count, 0) == NP_MATCH_RETRY, "Test not matching any string"); + ok(np_expect_match("XX AA bb CC XX", server_expect, server_expect_count, NP_MATCH_ALL) == NP_MATCH_SUCCESS, "Test matching all strings"); + ok(np_expect_match("XX bb CC XX", server_expect, server_expect_count, NP_MATCH_ALL) == NP_MATCH_RETRY, "Test not matching all strings"); + ok(np_expect_match("XX XX", server_expect, server_expect_count, NP_MATCH_ALL) == NP_MATCH_RETRY, "Test not matching any string (testing all)"); return exit_status(); } diff --git a/lib/tests/test_utils.c b/lib/tests/test_utils.c index 01afacd..901e0cc 100644 --- a/lib/tests/test_utils.c +++ b/lib/tests/test_utils.c @@ -1,20 +1,20 @@ /***************************************************************************** -* -* 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 . -* -* -*****************************************************************************/ + * + * 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 . + * + * + *****************************************************************************/ #include "common.h" #include "utils_base.h" @@ -27,331 +27,323 @@ #include "utils_base.c" -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { char state_path[1024]; - range *range; - double temp; + range *range; + double temp; thresholds *thresholds = NULL; - int i, rc; - char *temp_string; + int i, rc; + char *temp_string; state_key *temp_state_key = NULL; state_data *temp_state_data; - time_t current_time; + time_t current_time; plan_tests(185); - ok( this_monitoring_plugin==NULL, "monitoring_plugin not initialised"); + ok(this_monitoring_plugin == NULL, "monitoring_plugin not initialised"); - np_init( "check_test", argc, argv ); + np_init("check_test", argc, argv); - ok( this_monitoring_plugin!=NULL, "monitoring_plugin now initialised"); - ok( !strcmp(this_monitoring_plugin->plugin_name, "check_test"), "plugin name initialised" ); + ok(this_monitoring_plugin != NULL, "monitoring_plugin now initialised"); + ok(!strcmp(this_monitoring_plugin->plugin_name, "check_test"), "plugin name initialised"); - ok( this_monitoring_plugin->argc==argc, "Argc set" ); - ok( this_monitoring_plugin->argv==argv, "Argv set" ); + ok(this_monitoring_plugin->argc == argc, "Argc set"); + ok(this_monitoring_plugin->argv == argv, "Argv set"); - np_set_args(0,0); + np_set_args(0, 0); - ok( this_monitoring_plugin->argc==0, "argc changed" ); - ok( this_monitoring_plugin->argv==0, "argv changed" ); + ok(this_monitoring_plugin->argc == 0, "argc changed"); + ok(this_monitoring_plugin->argv == 0, "argv changed"); np_set_args(argc, argv); range = parse_range_string("6"); - ok( range != NULL, "'6' is valid range"); - ok( range->start == 0, "Start correct"); - ok( range->start_infinity == false, "Not using negative infinity"); - ok( range->end == 6, "End correct"); - ok( range->end_infinity == false, "Not using infinity"); + ok(range != NULL, "'6' is valid range"); + ok(range->start == 0, "Start correct"); + ok(range->start_infinity == false, "Not using negative infinity"); + ok(range->end == 6, "End correct"); + ok(range->end_infinity == false, "Not using infinity"); free(range); range = parse_range_string("1:12%%"); - ok( range != NULL, "'1:12%%' is valid - percentages are ignored"); - ok( range->start == 1, "Start correct"); - ok( range->start_infinity == false, "Not using negative infinity"); - ok( range->end == 12, "End correct"); - ok( range->end_infinity == false, "Not using infinity"); + ok(range != NULL, "'1:12%%' is valid - percentages are ignored"); + ok(range->start == 1, "Start correct"); + ok(range->start_infinity == false, "Not using negative infinity"); + ok(range->end == 12, "End correct"); + ok(range->end_infinity == false, "Not using infinity"); free(range); range = parse_range_string("-7:23"); - ok( range != NULL, "'-7:23' is valid range"); - ok( range->start == -7, "Start correct"); - ok( range->start_infinity == false, "Not using negative infinity"); - ok( range->end == 23, "End correct"); - ok( range->end_infinity == false, "Not using infinity"); + ok(range != NULL, "'-7:23' is valid range"); + ok(range->start == -7, "Start correct"); + ok(range->start_infinity == false, "Not using negative infinity"); + ok(range->end == 23, "End correct"); + ok(range->end_infinity == false, "Not using infinity"); free(range); range = parse_range_string(":5.75"); - ok( range != NULL, "':5.75' is valid range"); - ok( range->start == 0, "Start correct"); - ok( range->start_infinity == false, "Not using negative infinity"); - ok( range->end == 5.75, "End correct"); - ok( range->end_infinity == false, "Not using infinity"); + ok(range != NULL, "':5.75' is valid range"); + ok(range->start == 0, "Start correct"); + ok(range->start_infinity == false, "Not using negative infinity"); + ok(range->end == 5.75, "End correct"); + ok(range->end_infinity == false, "Not using infinity"); free(range); range = parse_range_string("~:-95.99"); - ok( range != NULL, "~:-95.99' is valid range"); - ok( range->start_infinity == true, "Using negative infinity"); - ok( range->end == -95.99, "End correct (with rounding errors)"); - ok( range->end_infinity == false, "Not using infinity"); + ok(range != NULL, "~:-95.99' is valid range"); + ok(range->start_infinity == true, "Using negative infinity"); + ok(range->end == -95.99, "End correct (with rounding errors)"); + ok(range->end_infinity == false, "Not using infinity"); free(range); range = parse_range_string("12345678901234567890:"); - temp = atof("12345678901234567890"); /* Can't just use this because number too large */ - ok( range != NULL, "'12345678901234567890:' is valid range"); - ok( range->start == temp, "Start correct"); - ok( range->start_infinity == false, "Not using negative infinity"); - ok( range->end_infinity == true, "Using infinity"); + temp = atof("12345678901234567890"); /* Can't just use this because number too large */ + ok(range != NULL, "'12345678901234567890:' is valid range"); + ok(range->start == temp, "Start correct"); + ok(range->start_infinity == false, "Not using negative infinity"); + ok(range->end_infinity == true, "Using infinity"); /* Cannot do a "-1" on temp, as it appears to be same value */ - ok( check_range(temp/1.1, range) == true, "12345678901234567890/1.1 - alert"); - ok( check_range(temp, range) == false, "12345678901234567890 - no alert"); - ok( check_range(temp*2, range) == false, "12345678901234567890*2 - no alert"); + ok(check_range(temp / 1.1, range) == true, "12345678901234567890/1.1 - alert"); + ok(check_range(temp, range) == false, "12345678901234567890 - no alert"); + ok(check_range(temp * 2, range) == false, "12345678901234567890*2 - no alert"); free(range); range = parse_range_string("~:0"); - ok( range != NULL, "'~:0' is valid range"); - ok( range->start_infinity == true, "Using negative infinity"); - ok( range->end == 0, "End correct"); - ok( range->end_infinity == false, "Not using infinity"); - ok( range->alert_on == OUTSIDE, "Will alert on outside of this range"); - ok( check_range(0.5, range) == true, "0.5 - alert"); - ok( check_range(-10, range) == false, "-10 - no alert"); - ok( check_range(0, range) == false, "0 - no alert"); + ok(range != NULL, "'~:0' is valid range"); + ok(range->start_infinity == true, "Using negative infinity"); + ok(range->end == 0, "End correct"); + ok(range->end_infinity == false, "Not using infinity"); + ok(range->alert_on == OUTSIDE, "Will alert on outside of this range"); + ok(check_range(0.5, range) == true, "0.5 - alert"); + ok(check_range(-10, range) == false, "-10 - no alert"); + ok(check_range(0, range) == false, "0 - no alert"); free(range); range = parse_range_string("@0:657.8210567"); - ok( range != 0, "@0:657.8210567' is a valid range"); - ok( range->start == 0, "Start correct"); - ok( range->start_infinity == false, "Not using negative infinity"); - ok( range->end == 657.8210567, "End correct"); - ok( range->end_infinity == false, "Not using infinity"); - ok( range->alert_on == INSIDE, "Will alert on inside of this range" ); - ok( check_range(32.88, range) == true, "32.88 - alert"); - ok( check_range(-2, range) == false, "-2 - no alert"); - ok( check_range(657.8210567, range) == true, "657.8210567 - alert"); - ok( check_range(0, range) == true, "0 - alert"); + ok(range != 0, "@0:657.8210567' is a valid range"); + ok(range->start == 0, "Start correct"); + ok(range->start_infinity == false, "Not using negative infinity"); + ok(range->end == 657.8210567, "End correct"); + ok(range->end_infinity == false, "Not using infinity"); + ok(range->alert_on == INSIDE, "Will alert on inside of this range"); + ok(check_range(32.88, range) == true, "32.88 - alert"); + ok(check_range(-2, range) == false, "-2 - no alert"); + ok(check_range(657.8210567, range) == true, "657.8210567 - alert"); + ok(check_range(0, range) == true, "0 - alert"); free(range); range = parse_range_string("@1:1"); - ok( range != NULL, "'@1:1' is a valid range"); - ok( range->start == 1, "Start correct"); - ok( range->start_infinity == false, "Not using negative infinity"); - ok( range->end == 1, "End correct"); - ok( range->end_infinity == false, "Not using infinity"); - ok( range->alert_on == INSIDE, "Will alert on inside of this range" ); - ok( check_range(0.5, range) == false, "0.5 - no alert"); - ok( check_range(1, range) == true, "1 - alert"); - ok( check_range(5.2, range) == false, "5.2 - no alert"); + ok(range != NULL, "'@1:1' is a valid range"); + ok(range->start == 1, "Start correct"); + ok(range->start_infinity == false, "Not using negative infinity"); + ok(range->end == 1, "End correct"); + ok(range->end_infinity == false, "Not using infinity"); + ok(range->alert_on == INSIDE, "Will alert on inside of this range"); + ok(check_range(0.5, range) == false, "0.5 - no alert"); + ok(check_range(1, range) == true, "1 - alert"); + ok(check_range(5.2, range) == false, "5.2 - no alert"); free(range); range = parse_range_string("1:1"); - ok( range != NULL, "'1:1' is a valid range"); - ok( range->start == 1, "Start correct"); - ok( range->start_infinity == false, "Not using negative infinity"); - ok( range->end == 1, "End correct"); - ok( range->end_infinity == false, "Not using infinity"); - ok( check_range(0.5, range) == true, "0.5 - alert"); - ok( check_range(1, range) == false, "1 - no alert"); - ok( check_range(5.2, range) == true, "5.2 - alert"); + ok(range != NULL, "'1:1' is a valid range"); + ok(range->start == 1, "Start correct"); + ok(range->start_infinity == false, "Not using negative infinity"); + ok(range->end == 1, "End correct"); + ok(range->end_infinity == false, "Not using infinity"); + ok(check_range(0.5, range) == true, "0.5 - alert"); + ok(check_range(1, range) == false, "1 - no alert"); + ok(check_range(5.2, range) == true, "5.2 - alert"); free(range); range = parse_range_string("2:1"); - ok( range == NULL, "'2:1' rejected"); + ok(range == NULL, "'2:1' rejected"); rc = _set_thresholds(&thresholds, NULL, NULL); - ok( rc == 0, "Thresholds (NULL, NULL) set"); - ok( thresholds->warning == NULL, "Warning not set"); - ok( thresholds->critical == NULL, "Critical not set"); + ok(rc == 0, "Thresholds (NULL, NULL) set"); + ok(thresholds->warning == NULL, "Warning not set"); + ok(thresholds->critical == NULL, "Critical not set"); rc = _set_thresholds(&thresholds, NULL, "80"); - ok( rc == 0, "Thresholds (NULL, '80') set"); - ok( thresholds->warning == NULL, "Warning not set"); - ok( thresholds->critical->end == 80, "Critical set correctly"); + ok(rc == 0, "Thresholds (NULL, '80') set"); + ok(thresholds->warning == NULL, "Warning not set"); + ok(thresholds->critical->end == 80, "Critical set correctly"); rc = _set_thresholds(&thresholds, "5:33", NULL); - ok( rc == 0, "Thresholds ('5:33', NULL) set"); - ok( thresholds->warning->start == 5, "Warning start set"); - ok( thresholds->warning->end == 33, "Warning end set"); - ok( thresholds->critical == NULL, "Critical not set"); + ok(rc == 0, "Thresholds ('5:33', NULL) set"); + ok(thresholds->warning->start == 5, "Warning start set"); + ok(thresholds->warning->end == 33, "Warning end set"); + ok(thresholds->critical == NULL, "Critical not set"); rc = _set_thresholds(&thresholds, "30", "60"); - ok( rc == 0, "Thresholds ('30', '60') set"); - ok( thresholds->warning->end == 30, "Warning set correctly"); - ok( thresholds->critical->end == 60, "Critical set correctly"); - ok( get_status(15.3, thresholds) == STATE_OK, "15.3 - ok"); - ok( get_status(30.0001, thresholds) == STATE_WARNING, "30.0001 - warning"); - ok( get_status(69, thresholds) == STATE_CRITICAL, "69 - critical"); + ok(rc == 0, "Thresholds ('30', '60') set"); + ok(thresholds->warning->end == 30, "Warning set correctly"); + ok(thresholds->critical->end == 60, "Critical set correctly"); + ok(get_status(15.3, thresholds) == STATE_OK, "15.3 - ok"); + ok(get_status(30.0001, thresholds) == STATE_WARNING, "30.0001 - warning"); + ok(get_status(69, thresholds) == STATE_CRITICAL, "69 - critical"); rc = _set_thresholds(&thresholds, "-10:-2", "-30:20"); - ok( rc == 0, "Thresholds ('-30:20', '-10:-2') set"); - ok( thresholds->warning->start == -10, "Warning start set correctly"); - ok( thresholds->warning->end == -2, "Warning end set correctly"); - ok( thresholds->critical->start == -30, "Critical start set correctly"); - ok( thresholds->critical->end == 20, "Critical end set correctly"); - ok( get_status(-31, thresholds) == STATE_CRITICAL, "-31 - critical"); - ok( get_status(-29, thresholds) == STATE_WARNING, "-29 - warning"); - ok( get_status(-11, thresholds) == STATE_WARNING, "-11 - warning"); - ok( get_status(-10, thresholds) == STATE_OK, "-10 - ok"); - ok( get_status(-2, thresholds) == STATE_OK, "-2 - ok"); - ok( get_status(-1, thresholds) == STATE_WARNING, "-1 - warning"); - ok( get_status(19, thresholds) == STATE_WARNING, "19 - warning"); - ok( get_status(21, thresholds) == STATE_CRITICAL, "21 - critical"); + ok(rc == 0, "Thresholds ('-30:20', '-10:-2') set"); + ok(thresholds->warning->start == -10, "Warning start set correctly"); + ok(thresholds->warning->end == -2, "Warning end set correctly"); + ok(thresholds->critical->start == -30, "Critical start set correctly"); + ok(thresholds->critical->end == 20, "Critical end set correctly"); + ok(get_status(-31, thresholds) == STATE_CRITICAL, "-31 - critical"); + ok(get_status(-29, thresholds) == STATE_WARNING, "-29 - warning"); + ok(get_status(-11, thresholds) == STATE_WARNING, "-11 - warning"); + ok(get_status(-10, thresholds) == STATE_OK, "-10 - ok"); + ok(get_status(-2, thresholds) == STATE_OK, "-2 - ok"); + ok(get_status(-1, thresholds) == STATE_WARNING, "-1 - warning"); + ok(get_status(19, thresholds) == STATE_WARNING, "19 - warning"); + ok(get_status(21, thresholds) == STATE_CRITICAL, "21 - critical"); char *test; test = np_escaped_string("bob\\n"); - ok( strcmp(test, "bob\n") == 0, "bob\\n ok"); + ok(strcmp(test, "bob\n") == 0, "bob\\n ok"); free(test); test = np_escaped_string("rhuba\\rb"); - ok( strcmp(test, "rhuba\rb") == 0, "rhuba\\rb okay"); + ok(strcmp(test, "rhuba\rb") == 0, "rhuba\\rb okay"); free(test); test = np_escaped_string("ba\\nge\\r"); - ok( strcmp(test, "ba\nge\r") == 0, "ba\\nge\\r okay"); + ok(strcmp(test, "ba\nge\r") == 0, "ba\\nge\\r okay"); free(test); test = np_escaped_string("\\rabbi\\t"); - ok( strcmp(test, "\rabbi\t") == 0, "\\rabbi\\t okay"); + ok(strcmp(test, "\rabbi\t") == 0, "\\rabbi\\t okay"); free(test); test = np_escaped_string("and\\\\or"); - ok( strcmp(test, "and\\or") == 0, "and\\\\or okay"); + ok(strcmp(test, "and\\or") == 0, "and\\\\or okay"); free(test); test = np_escaped_string("bo\\gus"); - ok( strcmp(test, "bogus") == 0, "bo\\gus okay"); + ok(strcmp(test, "bogus") == 0, "bo\\gus okay"); free(test); test = np_escaped_string("everything"); - ok( strcmp(test, "everything") == 0, "everything okay"); + ok(strcmp(test, "everything") == 0, "everything okay"); /* np_extract_ntpvar tests (23) */ - test=np_extract_ntpvar("foo=bar, bar=foo, foobar=barfoo\n", "foo"); + test = np_extract_ntpvar("foo=bar, bar=foo, foobar=barfoo\n", "foo"); ok(test && !strcmp(test, "bar"), "1st test as expected"); free(test); - test=np_extract_ntpvar("foo=bar,bar=foo,foobar=barfoo\n", "bar"); + test = np_extract_ntpvar("foo=bar,bar=foo,foobar=barfoo\n", "bar"); ok(test && !strcmp(test, "foo"), "2nd test as expected"); free(test); - test=np_extract_ntpvar("foo=bar, bar=foo, foobar=barfoo\n", "foobar"); + test = np_extract_ntpvar("foo=bar, bar=foo, foobar=barfoo\n", "foobar"); ok(test && !strcmp(test, "barfoo"), "3rd test as expected"); free(test); - test=np_extract_ntpvar("foo=bar\n", "foo"); + test = np_extract_ntpvar("foo=bar\n", "foo"); ok(test && !strcmp(test, "bar"), "Single test as expected"); free(test); - test=np_extract_ntpvar("foo=bar, bar=foo, foobar=barfooi\n", "abcd"); + test = np_extract_ntpvar("foo=bar, bar=foo, foobar=barfooi\n", "abcd"); ok(!test, "Key not found 1"); - test=np_extract_ntpvar("foo=bar\n", "abcd"); + test = np_extract_ntpvar("foo=bar\n", "abcd"); ok(!test, "Key not found 2"); - test=np_extract_ntpvar("foo=bar=foobar", "foo"); + test = np_extract_ntpvar("foo=bar=foobar", "foo"); ok(test && !strcmp(test, "bar=foobar"), "Strange string 1"); free(test); - test=np_extract_ntpvar("foo", "foo"); + test = np_extract_ntpvar("foo", "foo"); ok(!test, "Malformed string 1"); - test=np_extract_ntpvar("foo,", "foo"); + test = np_extract_ntpvar("foo,", "foo"); ok(!test, "Malformed string 2"); - test=np_extract_ntpvar("foo=", "foo"); + test = np_extract_ntpvar("foo=", "foo"); ok(!test, "Malformed string 3"); - test=np_extract_ntpvar("foo=,bar=foo", "foo"); + test = np_extract_ntpvar("foo=,bar=foo", "foo"); ok(!test, "Malformed string 4"); - test=np_extract_ntpvar(",foo", "foo"); + test = np_extract_ntpvar(",foo", "foo"); ok(!test, "Malformed string 5"); - test=np_extract_ntpvar("=foo", "foo"); + test = np_extract_ntpvar("=foo", "foo"); ok(!test, "Malformed string 6"); - test=np_extract_ntpvar("=foo,", "foo"); + test = np_extract_ntpvar("=foo,", "foo"); ok(!test, "Malformed string 7"); - test=np_extract_ntpvar(",,,", "foo"); + test = np_extract_ntpvar(",,,", "foo"); ok(!test, "Malformed string 8"); - test=np_extract_ntpvar("===", "foo"); + test = np_extract_ntpvar("===", "foo"); ok(!test, "Malformed string 9"); - test=np_extract_ntpvar(",=,=,", "foo"); + test = np_extract_ntpvar(",=,=,", "foo"); ok(!test, "Malformed string 10"); - test=np_extract_ntpvar("=,=,=", "foo"); + test = np_extract_ntpvar("=,=,=", "foo"); ok(!test, "Malformed string 11"); - test=np_extract_ntpvar(" foo=bar ,\n bar=foo\n , foobar=barfoo \n ", "foo"); + test = np_extract_ntpvar(" foo=bar ,\n bar=foo\n , foobar=barfoo \n ", "foo"); ok(test && !strcmp(test, "bar"), "Random spaces and newlines 1"); free(test); - test=np_extract_ntpvar(" foo=bar ,\n bar=foo\n , foobar=barfoo \n ", "bar"); + test = np_extract_ntpvar(" foo=bar ,\n bar=foo\n , foobar=barfoo \n ", "bar"); ok(test && !strcmp(test, "foo"), "Random spaces and newlines 2"); free(test); - test=np_extract_ntpvar(" foo=bar ,\n bar=foo\n , foobar=barfoo \n ", "foobar"); + test = np_extract_ntpvar(" foo=bar ,\n bar=foo\n , foobar=barfoo \n ", "foobar"); ok(test && !strcmp(test, "barfoo"), "Random spaces and newlines 3"); free(test); - test=np_extract_ntpvar(" foo=bar ,\n bar\n \n= \n foo\n , foobar=barfoo \n ", "bar"); + test = np_extract_ntpvar(" foo=bar ,\n bar\n \n= \n foo\n , foobar=barfoo \n ", "bar"); ok(test && !strcmp(test, "foo"), "Random spaces and newlines 4"); free(test); - test=np_extract_ntpvar("", "foo"); + test = np_extract_ntpvar("", "foo"); ok(!test, "Empty string return NULL"); - /* This is the result of running ./test_utils */ - temp_string = (char *) _np_state_generate_key(); - ok(!strcmp(temp_string, "e2d17f995fd4c020411b85e3e3d0ff7306d4147e"), "Got hash with exe and no parameters" ) || - diag( "You are probably running in wrong directory. Must run as ./test_utils" ); - + temp_string = (char *)_np_state_generate_key(); + ok(!strcmp(temp_string, "e2d17f995fd4c020411b85e3e3d0ff7306d4147e"), "Got hash with exe and no parameters") || + diag("You are probably running in wrong directory. Must run as ./test_utils"); - this_monitoring_plugin->argc=4; + this_monitoring_plugin->argc = 4; this_monitoring_plugin->argv[0] = "./test_utils"; this_monitoring_plugin->argv[1] = "here"; this_monitoring_plugin->argv[2] = "--and"; this_monitoring_plugin->argv[3] = "now"; - temp_string = (char *) _np_state_generate_key(); - ok(!strcmp(temp_string, "bd72da9f78ff1419fad921ea5e43ce56508aef6c"), "Got based on expected argv" ); + temp_string = (char *)_np_state_generate_key(); + ok(!strcmp(temp_string, "bd72da9f78ff1419fad921ea5e43ce56508aef6c"), "Got based on expected argv"); unsetenv("MP_STATE_PATH"); - temp_string = (char *) _np_state_calculate_location_prefix(); - ok(!strcmp(temp_string, NP_STATE_DIR_PREFIX), "Got default directory" ); + temp_string = (char *)_np_state_calculate_location_prefix(); + ok(!strcmp(temp_string, NP_STATE_DIR_PREFIX), "Got default directory"); setenv("MP_STATE_PATH", "", 1); - temp_string = (char *) _np_state_calculate_location_prefix(); - ok(!strcmp(temp_string, NP_STATE_DIR_PREFIX), "Got default directory even with empty string" ); + temp_string = (char *)_np_state_calculate_location_prefix(); + ok(!strcmp(temp_string, NP_STATE_DIR_PREFIX), "Got default directory even with empty string"); setenv("MP_STATE_PATH", "/usr/local/nagios/var", 1); - temp_string = (char *) _np_state_calculate_location_prefix(); - ok(!strcmp(temp_string, "/usr/local/nagios/var"), "Got default directory" ); - + temp_string = (char *)_np_state_calculate_location_prefix(); + ok(!strcmp(temp_string, "/usr/local/nagios/var"), "Got default directory"); + ok(temp_state_key == NULL, "temp_state_key initially empty"); - ok(temp_state_key==NULL, "temp_state_key initially empty"); - - this_monitoring_plugin->argc=1; + this_monitoring_plugin->argc = 1; this_monitoring_plugin->argv[0] = "./test_utils"; np_enable_state(NULL, 51); temp_state_key = this_monitoring_plugin->state; - ok( !strcmp(temp_state_key->plugin_name, "check_test"), "Got plugin name" ); - ok( !strcmp(temp_state_key->name, "e2d17f995fd4c020411b85e3e3d0ff7306d4147e"), "Got generated filename" ); - + ok(!strcmp(temp_state_key->plugin_name, "check_test"), "Got plugin name"); + ok(!strcmp(temp_state_key->name, "e2d17f995fd4c020411b85e3e3d0ff7306d4147e"), "Got generated filename"); np_enable_state("allowedchars_in_keyname", 77); temp_state_key = this_monitoring_plugin->state; sprintf(state_path, "/usr/local/nagios/var/%lu/check_test/allowedchars_in_keyname", (unsigned long)geteuid()); - ok( !strcmp(temp_state_key->plugin_name, "check_test"), "Got plugin name" ); - ok( !strcmp(temp_state_key->name, "allowedchars_in_keyname"), "Got key name with valid chars" ); - ok( !strcmp(temp_state_key->_filename, state_path), "Got internal filename" ); - + ok(!strcmp(temp_state_key->plugin_name, "check_test"), "Got plugin name"); + ok(!strcmp(temp_state_key->name, "allowedchars_in_keyname"), "Got key name with valid chars"); + ok(!strcmp(temp_state_key->_filename, state_path), "Got internal filename"); /* Don't do this test just yet. Will die */ /* @@ -363,73 +355,64 @@ main (int argc, char **argv) np_enable_state("funnykeyname", 54); temp_state_key = this_monitoring_plugin->state; sprintf(state_path, "/usr/local/nagios/var/%lu/check_test/funnykeyname", (unsigned long)geteuid()); - ok( !strcmp(temp_state_key->plugin_name, "check_test"), "Got plugin name" ); - ok( !strcmp(temp_state_key->name, "funnykeyname"), "Got key name" ); + ok(!strcmp(temp_state_key->plugin_name, "check_test"), "Got plugin name"); + ok(!strcmp(temp_state_key->name, "funnykeyname"), "Got key name"); - - - ok( !strcmp(temp_state_key->_filename, state_path), "Got internal filename" ); - ok( temp_state_key->data_version==54, "Version set" ); + ok(!strcmp(temp_state_key->_filename, state_path), "Got internal filename"); + ok(temp_state_key->data_version == 54, "Version set"); temp_state_data = np_state_read(); - ok( temp_state_data==NULL, "Got no state data as file does not exist" ); - + ok(temp_state_data == NULL, "Got no state data as file does not exist"); -/* - temp_fp = fopen("var/statefile", "r"); - if (temp_fp==NULL) - printf("Error opening. errno=%d\n", errno); - printf("temp_fp=%s\n", temp_fp); - ok( _np_state_read_file(temp_fp) == true, "Can read state file" ); - fclose(temp_fp); -*/ + /* + temp_fp = fopen("var/statefile", "r"); + if (temp_fp==NULL) + printf("Error opening. errno=%d\n", errno); + printf("temp_fp=%s\n", temp_fp); + ok( _np_state_read_file(temp_fp) == true, "Can read state file" ); + fclose(temp_fp); + */ - temp_state_key->_filename="var/statefile"; + temp_state_key->_filename = "var/statefile"; temp_state_data = np_state_read(); - ok( this_monitoring_plugin->state->state_data!=NULL, "Got state data now" ) || diag("Are you running in right directory? Will get coredump next if not"); - ok( this_monitoring_plugin->state->state_data->time==1234567890, "Got time" ); - ok( !strcmp((char *)this_monitoring_plugin->state->state_data->data, "String to read"), "Data as expected" ); + ok(this_monitoring_plugin->state->state_data != NULL, "Got state data now") || diag("Are you running in right directory? Will get coredump next if not"); + ok(this_monitoring_plugin->state->state_data->time == 1234567890, "Got time"); + ok(!strcmp((char *)this_monitoring_plugin->state->state_data->data, "String to read"), "Data as expected"); - temp_state_key->data_version=53; + temp_state_key->data_version = 53; temp_state_data = np_state_read(); - ok( temp_state_data==NULL, "Older data version gives NULL" ); - temp_state_key->data_version=54; + ok(temp_state_data == NULL, "Older data version gives NULL"); + temp_state_key->data_version = 54; - temp_state_key->_filename="var/nonexistent"; + temp_state_key->_filename = "var/nonexistent"; temp_state_data = np_state_read(); - ok( temp_state_data==NULL, "Missing file gives NULL" ); - ok( this_monitoring_plugin->state->state_data==NULL, "No state information" ); + ok(temp_state_data == NULL, "Missing file gives NULL"); + ok(this_monitoring_plugin->state->state_data == NULL, "No state information"); - temp_state_key->_filename="var/oldformat"; + temp_state_key->_filename = "var/oldformat"; temp_state_data = np_state_read(); - ok( temp_state_data==NULL, "Old file format gives NULL" ); + ok(temp_state_data == NULL, "Old file format gives NULL"); - temp_state_key->_filename="var/baddate"; + temp_state_key->_filename = "var/baddate"; temp_state_data = np_state_read(); - ok( temp_state_data==NULL, "Bad date gives NULL" ); + ok(temp_state_data == NULL, "Bad date gives NULL"); - temp_state_key->_filename="var/missingdataline"; + temp_state_key->_filename = "var/missingdataline"; temp_state_data = np_state_read(); - ok( temp_state_data==NULL, "Missing data line gives NULL" ); - - - + ok(temp_state_data == NULL, "Missing data line gives NULL"); unlink("var/generated"); - temp_state_key->_filename="var/generated"; - current_time=1234567890; + temp_state_key->_filename = "var/generated"; + current_time = 1234567890; np_state_write_string(current_time, "String to read"); - ok(system("cmp var/generated var/statefile")==0, "Generated file same as expected"); - - - + ok(system("cmp var/generated var/statefile") == 0, "Generated file same as expected"); unlink("var/generated_directory/statefile"); unlink("var/generated_directory"); - temp_state_key->_filename="var/generated_directory/statefile"; - current_time=1234567890; + temp_state_key->_filename = "var/generated_directory/statefile"; + current_time = 1234567890; np_state_write_string(current_time, "String to read"); - ok(system("cmp var/generated_directory/statefile var/statefile")==0, "Have created directory"); + ok(system("cmp var/generated_directory/statefile var/statefile") == 0, "Have created directory"); /* This test to check cannot write to dir - can't automate yet */ /* @@ -438,15 +421,13 @@ main (int argc, char **argv) np_state_write_string(current_time, "String to read"); */ - - temp_state_key->_filename="var/generated"; + temp_state_key->_filename = "var/generated"; time(¤t_time); np_state_write_string(0, "String to read"); temp_state_data = np_state_read(); /* Check time is set to current_time */ - ok(system("cmp var/generated var/statefile > /dev/null")!=0, "Generated file should be different this time"); - ok(this_monitoring_plugin->state->state_data->time-current_time<=1, "Has time generated from current time"); - + ok(system("cmp var/generated var/statefile > /dev/null") != 0, "Generated file should be different this time"); + ok(this_monitoring_plugin->state->state_data->time - current_time <= 1, "Has time generated from current time"); /* Don't know how to automatically test this. Need to be able to redefine die and catch the error */ /* @@ -454,23 +435,16 @@ main (int argc, char **argv) np_state_write_string(0, "Bad file"); */ - np_cleanup(); - ok(this_monitoring_plugin==NULL, "Free'd this_monitoring_plugin"); + ok(this_monitoring_plugin == NULL, "Free'd this_monitoring_plugin"); ok(mp_suid() == false, "Test aren't suid"); /* base states with random case */ - char *states[] = { - "Ok", - "wArnINg", - "cRiTIcaL", - "UnKNoWN", - NULL - }; - - for (i=0; states[i]!=NULL; i++) { + char *states[] = {"Ok", "wArnINg", "cRiTIcaL", "UnKNoWN", NULL}; + + for (i = 0; states[i] != NULL; i++) { /* out of the random case states, create the lower and upper versions + numeric string one */ char *statelower = strdup(states[i]); char *stateupper = strdup(states[i]); @@ -488,23 +462,23 @@ main (int argc, char **argv) char testname[64] = "Translate state string: "; int tlen = strlen(testname); - strcpy(testname+tlen, states[i]); - ok(i==mp_translate_state(states[i]), testname); + strcpy(testname + tlen, states[i]); + ok(i == mp_translate_state(states[i]), testname); - strcpy(testname+tlen, statelower); - ok(i==mp_translate_state(statelower), testname); + strcpy(testname + tlen, statelower); + ok(i == mp_translate_state(statelower), testname); - strcpy(testname+tlen, stateupper); - ok(i==mp_translate_state(stateupper), testname); + strcpy(testname + tlen, stateupper); + ok(i == mp_translate_state(stateupper), testname); - strcpy(testname+tlen, statenum); - ok(i==mp_translate_state(statenum), testname); + strcpy(testname + tlen, statenum); + ok(i == mp_translate_state(statenum), testname); } - ok(ERROR==mp_translate_state("warningfewgw"), "Translate state string with garbage"); - ok(ERROR==mp_translate_state("00"), "Translate state string: bad numeric string 1"); - ok(ERROR==mp_translate_state("01"), "Translate state string: bad numeric string 2"); - ok(ERROR==mp_translate_state("10"), "Translate state string: bad numeric string 3"); - ok(ERROR==mp_translate_state(""), "Translate state string: empty string"); + ok(ERROR == mp_translate_state("warningfewgw"), "Translate state string with garbage"); + ok(ERROR == mp_translate_state("00"), "Translate state string: bad numeric string 1"); + ok(ERROR == mp_translate_state("01"), "Translate state string: bad numeric string 2"); + ok(ERROR == mp_translate_state("10"), "Translate state string: bad numeric string 3"); + ok(ERROR == mp_translate_state(""), "Translate state string: empty string"); return exit_status(); } diff --git a/lib/utils_base.c b/lib/utils_base.c index f8592f4..cd13583 100644 --- a/lib/utils_base.c +++ b/lib/utils_base.c @@ -1,28 +1,28 @@ /***************************************************************************** -* -* utils_base.c -* -* License: GPL -* Copyright (c) 2006 Monitoring Plugins Development Team -* -* Library of useful functions for plugins -* -* -* 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 . -* -* -*****************************************************************************/ + * + * utils_base.c + * + * License: GPL + * Copyright (c) 2006 Monitoring Plugins Development Team + * + * Library of useful functions for plugins + * + * + * 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 . + * + * + *****************************************************************************/ #include "../plugins/common.h" #include @@ -33,43 +33,47 @@ #include #include -#define np_free(ptr) { if(ptr) { free(ptr); ptr = NULL; } } +#define np_free(ptr) \ + { \ + if (ptr) { \ + free(ptr); \ + ptr = NULL; \ + } \ + } -monitoring_plugin *this_monitoring_plugin=NULL; +monitoring_plugin *this_monitoring_plugin = NULL; int timeout_state = STATE_CRITICAL; unsigned int timeout_interval = DEFAULT_SOCKET_TIMEOUT; bool _np_state_read_file(FILE *); -void np_init( char *plugin_name, int argc, char **argv ) { - if (this_monitoring_plugin==NULL) { +void np_init(char *plugin_name, int argc, char **argv) { + if (this_monitoring_plugin == NULL) { this_monitoring_plugin = calloc(1, sizeof(monitoring_plugin)); - if (this_monitoring_plugin==NULL) { - die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), - strerror(errno)); + if (this_monitoring_plugin == NULL) { + die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), strerror(errno)); } this_monitoring_plugin->plugin_name = strdup(plugin_name); - if (this_monitoring_plugin->plugin_name==NULL) + if (this_monitoring_plugin->plugin_name == NULL) die(STATE_UNKNOWN, _("Cannot execute strdup: %s"), strerror(errno)); this_monitoring_plugin->argc = argc; this_monitoring_plugin->argv = argv; } } -void np_set_args( int argc, char **argv ) { - if (this_monitoring_plugin==NULL) +void np_set_args(int argc, char **argv) { + if (this_monitoring_plugin == NULL) die(STATE_UNKNOWN, _("This requires np_init to be called")); this_monitoring_plugin->argc = argc; this_monitoring_plugin->argv = argv; } - void np_cleanup() { - if (this_monitoring_plugin!=NULL) { - if(this_monitoring_plugin->state!=NULL) { - if(this_monitoring_plugin->state->state_data) { + if (this_monitoring_plugin != NULL) { + if (this_monitoring_plugin->state != NULL) { + if (this_monitoring_plugin->state->state_data) { np_free(this_monitoring_plugin->state->state_data->data); np_free(this_monitoring_plugin->state->state_data); } @@ -79,48 +83,43 @@ void np_cleanup() { np_free(this_monitoring_plugin->plugin_name); np_free(this_monitoring_plugin); } - this_monitoring_plugin=NULL; + this_monitoring_plugin = NULL; } /* Hidden function to get a pointer to this_monitoring_plugin for testing */ -void _get_monitoring_plugin( monitoring_plugin **pointer ){ - *pointer = this_monitoring_plugin; -} +void _get_monitoring_plugin(monitoring_plugin **pointer) { *pointer = this_monitoring_plugin; } -void -die (int result, const char *fmt, ...) -{ - if(fmt!=NULL) { +void die(int result, const char *fmt, ...) { + if (fmt != NULL) { va_list ap; - va_start (ap, fmt); - vprintf (fmt, ap); - va_end (ap); + va_start(ap, fmt); + vprintf(fmt, ap); + va_end(ap); } - if(this_monitoring_plugin!=NULL) { + if (this_monitoring_plugin != NULL) { np_cleanup(); } - exit (result); + exit(result); } -void set_range_start (range *this, double value) { +void set_range_start(range *this, double value) { this->start = value; this->start_infinity = false; } -void set_range_end (range *this, double value) { +void set_range_end(range *this, double value) { this->end = value; this->end_infinity = false; } -range -*parse_range_string (char *str) { +range *parse_range_string(char *str) { range *temp_range; double start; double end; char *end_str; - temp_range = (range *) calloc(1, sizeof(range)); + temp_range = (range *)calloc(1, sizeof(range)); /* Set defaults */ temp_range->start = 0; @@ -140,10 +139,10 @@ range if (str[0] == '~') { temp_range->start_infinity = true; } else { - start = strtod(str, NULL); /* Will stop at the ':' */ + start = strtod(str, NULL); /* Will stop at the ':' */ set_range_start(temp_range, start); } - end_str++; /* Move past the ':' */ + end_str++; /* Move past the ':' */ } else { end_str = str; } @@ -152,9 +151,7 @@ range set_range_end(temp_range, end); } - if (temp_range->start_infinity == true || - temp_range->end_infinity == true || - temp_range->start <= temp_range->end) { + if (temp_range->start_infinity == true || temp_range->end_infinity == true || temp_range->start <= temp_range->end) { return temp_range; } free(temp_range); @@ -162,14 +159,11 @@ range } /* returns 0 if okay, otherwise 1 */ -int -_set_thresholds(thresholds **my_thresholds, char *warn_string, char *critical_string) -{ +int _set_thresholds(thresholds **my_thresholds, char *warn_string, char *critical_string) { thresholds *temp_thresholds = NULL; if ((temp_thresholds = calloc(1, sizeof(thresholds))) == NULL) - die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), - strerror(errno)); + die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), strerror(errno)); temp_thresholds->warning = NULL; temp_thresholds->critical = NULL; @@ -190,9 +184,7 @@ _set_thresholds(thresholds **my_thresholds, char *warn_string, char *critical_st return 0; } -void -set_thresholds(thresholds **my_thresholds, char *warn_string, char *critical_string) -{ +void set_thresholds(thresholds **my_thresholds, char *warn_string, char *critical_string) { switch (_set_thresholds(my_thresholds, warn_string, critical_string)) { case 0: return; @@ -206,7 +198,7 @@ set_thresholds(thresholds **my_thresholds, char *warn_string, char *critical_str void print_thresholds(const char *threshold_name, thresholds *my_threshold) { printf("%s - ", threshold_name); - if (! my_threshold) { + if (!my_threshold) { printf("Threshold not set"); } else { if (my_threshold->warning) { @@ -224,8 +216,7 @@ void print_thresholds(const char *threshold_name, thresholds *my_threshold) { } /* Returns true if alert should be raised based on the range */ -bool check_range(double value, range *my_range) -{ +bool check_range(double value, range *my_range) { bool no = false; bool yes = true; @@ -258,9 +249,7 @@ bool check_range(double value, range *my_range) } /* Returns status */ -int -get_status(double value, thresholds *my_thresholds) -{ +int get_status(double value, thresholds *my_thresholds) { if (my_thresholds->critical != NULL) { if (check_range(value, my_thresholds->critical) == true) { return STATE_CRITICAL; @@ -274,27 +263,27 @@ get_status(double value, thresholds *my_thresholds) return STATE_OK; } -char *np_escaped_string (const char *string) { +char *np_escaped_string(const char *string) { char *data; - int i, j=0; + int i, j = 0; data = strdup(string); - for (i=0; data[i]; i++) { + for (i = 0; data[i]; i++) { if (data[i] == '\\') { - switch(data[++i]) { - case 'n': - data[j++] = '\n'; - break; - case 'r': - data[j++] = '\r'; - break; - case 't': - data[j++] = '\t'; - break; - case '\\': - data[j++] = '\\'; - break; - default: - data[j++] = data[i]; + switch (data[++i]) { + case 'n': + data[j++] = '\n'; + break; + case 'r': + data[j++] = '\r'; + break; + case 't': + data[j++] = '\t'; + break; + case '\\': + data[j++] = '\\'; + break; + default: + data[j++] = data[i]; } } else { data[j++] = data[i]; @@ -313,33 +302,38 @@ int np_check_if_root(void) { return (geteuid() == 0); } * data strings. */ char *np_extract_value(const char *varlist, const char *name, char sep) { - char *tmp=NULL, *value=NULL; + char *tmp = NULL, *value = NULL; int i; while (1) { /* Strip any leading space */ - for (; isspace(varlist[0]); varlist++); + for (; isspace(varlist[0]); varlist++) + ; if (strncmp(name, varlist, strlen(name)) == 0) { varlist += strlen(name); /* strip trailing spaces */ - for (; isspace(varlist[0]); varlist++); + for (; isspace(varlist[0]); varlist++) + ; if (varlist[0] == '=') { /* We matched the key, go past the = sign */ varlist++; /* strip leading spaces */ - for (; isspace(varlist[0]); varlist++); + for (; isspace(varlist[0]); varlist++) + ; if ((tmp = index(varlist, sep))) { /* Value is delimited by a comma */ - if (tmp-varlist == 0) continue; - value = (char *)calloc(1, tmp-varlist+1); - strncpy(value, varlist, tmp-varlist); - value[tmp-varlist] = '\0'; + if (tmp - varlist == 0) + continue; + value = (char *)calloc(1, tmp - varlist + 1); + strncpy(value, varlist, tmp - varlist); + value[tmp - varlist] = '\0'; } else { /* Value is delimited by a \0 */ - if (strlen(varlist) == 0) continue; + if (strlen(varlist) == 0) + continue; value = (char *)calloc(1, strlen(varlist) + 1); strncpy(value, varlist, strlen(varlist)); value[strlen(varlist)] = '\0'; @@ -357,14 +351,14 @@ char *np_extract_value(const char *varlist, const char *name, char sep) { } /* Clean-up trailing spaces/newlines */ - if (value) for (i=strlen(value)-1; isspace(value[i]); i--) value[i] = '\0'; + if (value) + for (i = strlen(value) - 1; isspace(value[i]); i--) + value[i] = '\0'; return value; } -const char * -state_text (int result) -{ +const char *state_text(int result) { switch (result) { case STATE_OK: return "OK"; @@ -383,14 +377,14 @@ state_text (int result) * Read a string representing a state (ok, warning... or numeric: 0, 1) and * return the corresponding STATE_ value or ERROR) */ -int mp_translate_state (char *state_text) { - if (!strcasecmp(state_text,"OK") || !strcmp(state_text,"0")) +int mp_translate_state(char *state_text) { + if (!strcasecmp(state_text, "OK") || !strcmp(state_text, "0")) return STATE_OK; - if (!strcasecmp(state_text,"WARNING") || !strcmp(state_text,"1")) + if (!strcasecmp(state_text, "WARNING") || !strcmp(state_text, "1")) return STATE_WARNING; - if (!strcasecmp(state_text,"CRITICAL") || !strcmp(state_text,"2")) + if (!strcasecmp(state_text, "CRITICAL") || !strcmp(state_text, "2")) return STATE_CRITICAL; - if (!strcasecmp(state_text,"UNKNOWN") || !strcmp(state_text,"3")) + if (!strcasecmp(state_text, "UNKNOWN") || !strcmp(state_text, "3")) return STATE_UNKNOWN; return ERROR; } @@ -404,7 +398,7 @@ char *_np_state_generate_key() { int i; char **argv = this_monitoring_plugin->argv; char keyname[41]; - char *p=NULL; + char *p = NULL; unsigned char result[256]; @@ -418,7 +412,7 @@ char *_np_state_generate_key() { EVP_DigestInit(ctx, EVP_sha256()); - for(i=0; iargc; i++) { + for (i = 0; i < this_monitoring_plugin->argc; i++) { EVP_DigestUpdate(ctx, argv[i], strlen(argv[i])); } @@ -427,28 +421,28 @@ char *_np_state_generate_key() { struct sha256_ctx ctx; - for(i=0; iargc; i++) { + for (i = 0; i < this_monitoring_plugin->argc; i++) { sha256_process_bytes(argv[i], strlen(argv[i]), &ctx); } sha256_finish_ctx(&ctx, result); #endif // FOUNDOPENSSL - for (i=0; i<20; ++i) { - sprintf(&keyname[2*i], "%02x", result[i]); + for (i = 0; i < 20; ++i) { + sprintf(&keyname[2 * i], "%02x", result[i]); } - keyname[40]='\0'; + keyname[40] = '\0'; p = strdup(keyname); - if(p==NULL) { + if (p == NULL) { die(STATE_UNKNOWN, _("Cannot execute strdup: %s"), strerror(errno)); } return p; } void _cleanup_state_data() { - if (this_monitoring_plugin->state->state_data!=NULL) { + if (this_monitoring_plugin->state->state_data != NULL) { np_free(this_monitoring_plugin->state->state_data->data); np_free(this_monitoring_plugin->state->state_data); } @@ -459,18 +453,18 @@ void _cleanup_state_data() { * envvar NAGIOS_PLUGIN_STATE_DIRECTORY * statically compiled shared state directory */ -char* _np_state_calculate_location_prefix(){ +char *_np_state_calculate_location_prefix() { char *env_dir; /* Do not allow passing MP_STATE_PATH in setuid plugins * for security reasons */ if (!mp_suid()) { env_dir = getenv("MP_STATE_PATH"); - if(env_dir && env_dir[0] != '\0') + if (env_dir && env_dir[0] != '\0') return env_dir; /* This is the former ENV, for backward-compatibility */ env_dir = getenv("NAGIOS_PLUGIN_STATE_DIRECTORY"); - if(env_dir && env_dir[0] != '\0') + if (env_dir && env_dir[0] != '\0') return env_dir; } @@ -486,46 +480,42 @@ void np_enable_state(char *keyname, int expected_data_version) { state_key *this_state = NULL; char *temp_filename = NULL; char *temp_keyname = NULL; - char *p=NULL; + char *p = NULL; int ret; - if(this_monitoring_plugin==NULL) + if (this_monitoring_plugin == NULL) die(STATE_UNKNOWN, _("This requires np_init to be called")); - this_state = (state_key *) calloc(1, sizeof(state_key)); - if(this_state==NULL) - die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), - strerror(errno)); + this_state = (state_key *)calloc(1, sizeof(state_key)); + if (this_state == NULL) + die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), strerror(errno)); - if(keyname==NULL) { + if (keyname == NULL) { temp_keyname = _np_state_generate_key(); } else { temp_keyname = strdup(keyname); - if(temp_keyname==NULL) + if (temp_keyname == NULL) die(STATE_UNKNOWN, _("Cannot execute strdup: %s"), strerror(errno)); } /* Die if invalid characters used for keyname */ p = temp_keyname; - while(*p!='\0') { - if(! (isalnum(*p) || *p == '_')) { + while (*p != '\0') { + if (!(isalnum(*p) || *p == '_')) { die(STATE_UNKNOWN, _("Invalid character for keyname - only alphanumerics or '_'")); } p++; } - this_state->name=temp_keyname; - this_state->plugin_name=this_monitoring_plugin->plugin_name; - this_state->data_version=expected_data_version; - this_state->state_data=NULL; + this_state->name = temp_keyname; + this_state->plugin_name = this_monitoring_plugin->plugin_name; + this_state->data_version = expected_data_version; + this_state->state_data = NULL; /* Calculate filename */ - ret = asprintf(&temp_filename, "%s/%lu/%s/%s", - _np_state_calculate_location_prefix(), (unsigned long)geteuid(), - this_monitoring_plugin->plugin_name, this_state->name); + ret = asprintf(&temp_filename, "%s/%lu/%s/%s", _np_state_calculate_location_prefix(), (unsigned long)geteuid(), this_monitoring_plugin->plugin_name, this_state->name); if (ret < 0) - die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), - strerror(errno)); + die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), strerror(errno)); - this_state->_filename=temp_filename; + this_state->_filename = temp_filename; this_monitoring_plugin->state = this_state; } @@ -538,23 +528,22 @@ void np_enable_state(char *keyname, int expected_data_version) { * if exceptional error. */ state_data *np_state_read() { - state_data *this_state_data=NULL; + state_data *this_state_data = NULL; FILE *statefile; bool rc = false; - if(this_monitoring_plugin==NULL) + if (this_monitoring_plugin == NULL) die(STATE_UNKNOWN, _("This requires np_init to be called")); /* Open file. If this fails, no previous state found */ - statefile = fopen( this_monitoring_plugin->state->_filename, "r" ); - if(statefile!=NULL) { + statefile = fopen(this_monitoring_plugin->state->_filename, "r"); + if (statefile != NULL) { - this_state_data = (state_data *) calloc(1, sizeof(state_data)); - if(this_state_data==NULL) - die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), - strerror(errno)); + this_state_data = (state_data *)calloc(1, sizeof(state_data)); + if (this_state_data == NULL) + die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), strerror(errno)); - this_state_data->data=NULL; + this_state_data->data = NULL; this_monitoring_plugin->state->state_data = this_state_data; rc = _np_state_read_file(statefile); @@ -562,7 +551,7 @@ state_data *np_state_read() { fclose(statefile); } - if(!rc) { + if (!rc) { _cleanup_state_data(); } @@ -577,60 +566,59 @@ bool _np_state_read_file(FILE *f) { size_t pos; char *line; int i; - int failure=0; + int failure = 0; time_t current_time, data_time; - enum { STATE_FILE_VERSION, STATE_DATA_VERSION, STATE_DATA_TIME, STATE_DATA_TEXT, STATE_DATA_END } expected=STATE_FILE_VERSION; + enum { STATE_FILE_VERSION, STATE_DATA_VERSION, STATE_DATA_TIME, STATE_DATA_TEXT, STATE_DATA_END } expected = STATE_FILE_VERSION; time(¤t_time); /* Note: This introduces a limit of 1024 bytes in the string data */ - line = (char *) calloc(1, 1024); - if(line==NULL) - die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), - strerror(errno)); - - while(!failure && (fgets(line,1024,f))!=NULL){ - pos=strlen(line); - if(line[pos-1]=='\n') { - line[pos-1]='\0'; + line = (char *)calloc(1, 1024); + if (line == NULL) + die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), strerror(errno)); + + while (!failure && (fgets(line, 1024, f)) != NULL) { + pos = strlen(line); + if (line[pos - 1] == '\n') { + line[pos - 1] = '\0'; } - if(line[0] == '#') continue; + if (line[0] == '#') + continue; - switch(expected) { - case STATE_FILE_VERSION: - i=atoi(line); - if(i!=NP_STATE_FORMAT_VERSION) - failure++; - else - expected=STATE_DATA_VERSION; - break; - case STATE_DATA_VERSION: - i=atoi(line); - if(i != this_monitoring_plugin->state->data_version) - failure++; - else - expected=STATE_DATA_TIME; - break; - case STATE_DATA_TIME: - /* If time > now, error */ - data_time=strtoul(line,NULL,10); - if(data_time > current_time) - failure++; - else { - this_monitoring_plugin->state->state_data->time = data_time; - expected=STATE_DATA_TEXT; - } - break; - case STATE_DATA_TEXT: - this_monitoring_plugin->state->state_data->data = strdup(line); - if(this_monitoring_plugin->state->state_data->data==NULL) - die(STATE_UNKNOWN, _("Cannot execute strdup: %s"), strerror(errno)); - expected=STATE_DATA_END; - status=true; - break; - case STATE_DATA_END: - ; + switch (expected) { + case STATE_FILE_VERSION: + i = atoi(line); + if (i != NP_STATE_FORMAT_VERSION) + failure++; + else + expected = STATE_DATA_VERSION; + break; + case STATE_DATA_VERSION: + i = atoi(line); + if (i != this_monitoring_plugin->state->data_version) + failure++; + else + expected = STATE_DATA_TIME; + break; + case STATE_DATA_TIME: + /* If time > now, error */ + data_time = strtoul(line, NULL, 10); + if (data_time > current_time) + failure++; + else { + this_monitoring_plugin->state->state_data->time = data_time; + expected = STATE_DATA_TEXT; + } + break; + case STATE_DATA_TEXT: + this_monitoring_plugin->state->state_data->data = strdup(line); + if (this_monitoring_plugin->state->state_data->data == NULL) + die(STATE_UNKNOWN, _("Cannot execute strdup: %s"), strerror(errno)); + expected = STATE_DATA_END; + status = true; + break; + case STATE_DATA_END:; } } @@ -647,77 +635,75 @@ bool _np_state_read_file(FILE *f) { */ void np_state_write_string(time_t data_time, char *data_string) { FILE *fp; - char *temp_file=NULL; - int fd=0, result=0; + char *temp_file = NULL; + int fd = 0, result = 0; time_t current_time; - char *directories=NULL; - char *p=NULL; + char *directories = NULL; + char *p = NULL; - if(data_time==0) + if (data_time == 0) time(¤t_time); else - current_time=data_time; + current_time = data_time; /* If file doesn't currently exist, create directories */ - if(access(this_monitoring_plugin->state->_filename,F_OK)!=0) { + if (access(this_monitoring_plugin->state->_filename, F_OK) != 0) { result = asprintf(&directories, "%s", this_monitoring_plugin->state->_filename); - if(result < 0) - die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), - strerror(errno)); - - for(p=directories+1; *p; p++) { - if(*p=='/') { - *p='\0'; - if((access(directories,F_OK)!=0) && (mkdir(directories, S_IRWXU)!=0)) { + if (result < 0) + die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), strerror(errno)); + + for (p = directories + 1; *p; p++) { + if (*p == '/') { + *p = '\0'; + if ((access(directories, F_OK) != 0) && (mkdir(directories, S_IRWXU) != 0)) { /* Can't free this! Otherwise error message is wrong! */ /* np_free(directories); */ die(STATE_UNKNOWN, _("Cannot create directory: %s"), directories); } - *p='/'; + *p = '/'; } } np_free(directories); } - result = asprintf(&temp_file,"%s.XXXXXX",this_monitoring_plugin->state->_filename); - if(result < 0) - die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), - strerror(errno)); + result = asprintf(&temp_file, "%s.XXXXXX", this_monitoring_plugin->state->_filename); + if (result < 0) + die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), strerror(errno)); - if((fd=mkstemp(temp_file))==-1) { + if ((fd = mkstemp(temp_file)) == -1) { np_free(temp_file); die(STATE_UNKNOWN, _("Cannot create temporary filename")); } - fp=(FILE *)fdopen(fd,"w"); - if(fp==NULL) { + fp = (FILE *)fdopen(fd, "w"); + if (fp == NULL) { close(fd); unlink(temp_file); np_free(temp_file); die(STATE_UNKNOWN, _("Unable to open temporary state file")); } - fprintf(fp,"# NP State file\n"); - fprintf(fp,"%d\n",NP_STATE_FORMAT_VERSION); - fprintf(fp,"%d\n",this_monitoring_plugin->state->data_version); - fprintf(fp,"%lu\n",current_time); - fprintf(fp,"%s\n",data_string); + fprintf(fp, "# NP State file\n"); + fprintf(fp, "%d\n", NP_STATE_FORMAT_VERSION); + fprintf(fp, "%d\n", this_monitoring_plugin->state->data_version); + fprintf(fp, "%lu\n", current_time); + fprintf(fp, "%s\n", data_string); fchmod(fd, S_IRUSR | S_IWUSR | S_IRGRP); fflush(fp); - result=fclose(fp); + result = fclose(fp); fsync(fd); - if(result!=0) { + if (result != 0) { unlink(temp_file); np_free(temp_file); die(STATE_UNKNOWN, _("Error writing temp file")); } - if(rename(temp_file, this_monitoring_plugin->state->_filename)!=0) { + if (rename(temp_file, this_monitoring_plugin->state->_filename) != 0) { unlink(temp_file); np_free(temp_file); die(STATE_UNKNOWN, _("Cannot rename state temp file")); diff --git a/lib/utils_base.h b/lib/utils_base.h index 9d4dffe..a209cb6 100644 --- a/lib/utils_base.h +++ b/lib/utils_base.h @@ -3,7 +3,7 @@ /* Header file for Monitoring Plugins utils_base.c */ #ifndef USE_OPENSSL -# include "sha256.h" +# include "sha256.h" #endif /* This file holds header information for thresholds - use this in preference to @@ -20,44 +20,43 @@ #define INSIDE 1 typedef struct range_struct { - double start; + double start; bool start_infinity; - double end; - int end_infinity; - int alert_on; /* OUTSIDE (default) or INSIDE */ - char* text; /* original unparsed text input */ - } range; + double end; + int end_infinity; + int alert_on; /* OUTSIDE (default) or INSIDE */ + char *text; /* original unparsed text input */ +} range; typedef struct thresholds_struct { - range *warning; - range *critical; - } thresholds; + range *warning; + range *critical; +} thresholds; #define NP_STATE_FORMAT_VERSION 1 typedef struct state_data_struct { - time_t time; - void *data; - int length; /* Of binary data */ - } state_data; - + time_t time; + void *data; + int length; /* Of binary data */ +} state_data; typedef struct state_key_struct { - char *name; - char *plugin_name; - int data_version; - char *_filename; + char *name; + char *plugin_name; + int data_version; + char *_filename; state_data *state_data; - } state_key; +} state_key; typedef struct np_struct { - char *plugin_name; + char *plugin_name; state_key *state; - int argc; - char **argv; - } monitoring_plugin; + int argc; + char **argv; +} monitoring_plugin; -range *parse_range_string (char *); +range *parse_range_string(char *); int _set_thresholds(thresholds **, char *, char *); void set_thresholds(thresholds **, char *, char *); void print_thresholds(const char *, thresholds *); @@ -71,13 +70,13 @@ extern unsigned int timeout_interval; /* All possible characters in a threshold range */ #define NP_THRESHOLDS_CHARS "-0123456789.:@~" -char *np_escaped_string (const char *); +char *np_escaped_string(const char *); -void die (int, const char *, ...) __attribute__((noreturn,format(printf, 2, 3))); +void die(int, const char *, ...) __attribute__((noreturn, format(printf, 2, 3))); /* Return codes for _set_thresholds */ #define NP_RANGE_UNPARSEABLE 1 -#define NP_WARN_WITHIN_CRIT 2 +#define NP_WARN_WITHIN_CRIT 2 /* a simple check to see if we're running as root. * returns zero on failure, nonzero on success */ @@ -93,7 +92,7 @@ int np_check_if_root(void); * This function can be used to parse NTP control packet data and performance * data strings. */ -char *np_extract_value(const char*, const char*, char); +char *np_extract_value(const char *, const char *, char); /* * Same as np_extract_value with separator suitable for NTP control packet @@ -105,7 +104,7 @@ char *np_extract_value(const char*, const char*, char); * Read a string representing a state (ok, warning... or numeric: 0, 1) and * return the corresponding NP_STATE or ERROR) */ -int mp_translate_state (char *); +int mp_translate_state(char *); void np_enable_state(char *, int); state_data *np_state_read(); @@ -114,6 +113,6 @@ void np_state_write_string(time_t, char *); void np_init(char *, int argc, char **argv); void np_set_args(int argc, char **argv); void np_cleanup(); -const char *state_text (int); +const char *state_text(int); #endif /* _UTILS_BASE_ */ diff --git a/lib/utils_cmd.c b/lib/utils_cmd.c index 7957ec1..25d5678 100644 --- a/lib/utils_cmd.c +++ b/lib/utils_cmd.c @@ -1,40 +1,40 @@ /***************************************************************************** -* -* Monitoring run command utilities -* -* License: GPL -* Copyright (c) 2005-2006 Monitoring Plugins Development Team -* -* Description : -* -* A simple interface to executing programs from other programs, using an -* optimized and safe popen()-like implementation. It is considered safe -* in that no shell needs to be spawned and the environment passed to the -* execve()'d program is essentially empty. -* -* The code in this file is a derivative of popen.c which in turn was taken -* from "Advanced Programming for the Unix Environment" by W. Richard Stevens. -* -* Care has been taken to make sure the functions are async-safe. The one -* function which isn't is cmd_init() which it doesn't make sense to -* call twice anyway, so the api as a whole should be considered async-safe. -* -* -* 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 run command utilities + * + * License: GPL + * Copyright (c) 2005-2006 Monitoring Plugins Development Team + * + * Description : + * + * A simple interface to executing programs from other programs, using an + * optimized and safe popen()-like implementation. It is considered safe + * in that no shell needs to be spawned and the environment passed to the + * execve()'d program is essentially empty. + * + * The code in this file is a derivative of popen.c which in turn was taken + * from "Advanced Programming for the Unix Environment" by W. Richard Stevens. + * + * Care has been taken to make sure the functions are async-safe. The one + * function which isn't is cmd_init() which it doesn't make sense to + * call twice anyway, so the api as a whole should be considered async-safe. + * + * + * 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 . + * + * + *****************************************************************************/ #define NAGIOSPLUG_API_C 1 @@ -59,7 +59,7 @@ static pid_t *_cmd_pids = NULL; #include #ifdef HAVE_SYS_WAIT_H -# include +# include #endif /* used in _cmd_open to pass the environment to commands */ @@ -67,57 +67,48 @@ extern char **environ; /** macros **/ #ifndef WEXITSTATUS -# define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8) +# define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8) #endif #ifndef WIFEXITED -# define WIFEXITED(stat_val) (((stat_val) & 255) == 0) +# define WIFEXITED(stat_val) (((stat_val)&255) == 0) #endif /* 4.3BSD Reno doesn't define SIG_ERR */ #if defined(SIG_IGN) && !defined(SIG_ERR) -# define SIG_ERR ((Sigfunc *)-1) +# define SIG_ERR ((Sigfunc *)-1) #endif /** prototypes **/ -static int _cmd_open (char *const *, int *, int *) - __attribute__ ((__nonnull__ (1, 2, 3))); +static int _cmd_open(char *const *, int *, int *) __attribute__((__nonnull__(1, 2, 3))); -static int _cmd_fetch_output (int, output *, int) - __attribute__ ((__nonnull__ (2))); +static int _cmd_fetch_output(int, output *, int) __attribute__((__nonnull__(2))); -static int _cmd_close (int); +static int _cmd_close(int); /* prototype imported from utils.h */ -extern void die (int, const char *, ...) - __attribute__ ((__noreturn__, __format__ (__printf__, 2, 3))); - +extern void die(int, const char *, ...) __attribute__((__noreturn__, __format__(__printf__, 2, 3))); /* this function is NOT async-safe. It is exported so multithreaded * plugins (or other apps) can call it prior to running any commands * through this api and thus achieve async-safeness throughout the api */ -void -cmd_init (void) -{ +void cmd_init(void) { long maxfd = mp_open_max(); /* if maxfd is unnaturally high, we force it to a lower value * ( e.g. on SunOS, when ulimit is set to unlimited: 2147483647 this would cause * a segfault when following calloc is called ... ) */ - if ( maxfd > MAXFD_LIMIT ) { + if (maxfd > MAXFD_LIMIT) { maxfd = MAXFD_LIMIT; } if (!_cmd_pids) - _cmd_pids = calloc (maxfd, sizeof (pid_t)); + _cmd_pids = calloc(maxfd, sizeof(pid_t)); } - /* Start running a command, array style */ -static int -_cmd_open (char *const *argv, int *pfd, int *pfderr) -{ +static int _cmd_open(char *const *argv, int *pfd, int *pfderr) { pid_t pid; #ifdef RLIMIT_CORE struct rlimit limit; @@ -130,26 +121,26 @@ _cmd_open (char *const *argv, int *pfd, int *pfderr) setenv("LC_ALL", "C", 1); - if (pipe (pfd) < 0 || pipe (pfderr) < 0 || (pid = fork ()) < 0) - return -1; /* errno set by the failing function */ + if (pipe(pfd) < 0 || pipe(pfderr) < 0 || (pid = fork()) < 0) + return -1; /* errno set by the failing function */ /* child runs exceve() and _exit. */ if (pid == 0) { -#ifdef RLIMIT_CORE +#ifdef RLIMIT_CORE /* the program we execve shouldn't leave core files */ - getrlimit (RLIMIT_CORE, &limit); + getrlimit(RLIMIT_CORE, &limit); limit.rlim_cur = 0; - setrlimit (RLIMIT_CORE, &limit); + setrlimit(RLIMIT_CORE, &limit); #endif - close (pfd[0]); + close(pfd[0]); if (pfd[1] != STDOUT_FILENO) { - dup2 (pfd[1], STDOUT_FILENO); - close (pfd[1]); + dup2(pfd[1], STDOUT_FILENO); + close(pfd[1]); } - close (pfderr[0]); + close(pfderr[0]); if (pfderr[1] != STDERR_FILENO) { - dup2 (pfderr[1], STDERR_FILENO); - close (pfderr[1]); + dup2(pfderr[1], STDERR_FILENO); + close(pfderr[1]); } /* close all descriptors in _cmd_pids[] @@ -158,16 +149,16 @@ _cmd_open (char *const *argv, int *pfd, int *pfderr) long maxfd = mp_open_max(); for (i = 0; i < maxfd; i++) if (_cmd_pids[i] > 0) - close (i); + close(i); - execve (argv[0], argv, environ); - _exit (STATE_UNKNOWN); + execve(argv[0], argv, environ); + _exit(STATE_UNKNOWN); } /* parent picks up execution here */ /* close children descriptors in our address space */ - close (pfd[1]); - close (pfderr[1]); + close(pfd[1]); + close(pfderr[1]); /* tag our file's entry in the pid-list and return it */ _cmd_pids[pfd[0]] = pid; @@ -175,9 +166,7 @@ _cmd_open (char *const *argv, int *pfd, int *pfderr) return pfd[0]; } -static int -_cmd_close (int fd) -{ +static int _cmd_close(int fd) { int status; pid_t pid; @@ -187,40 +176,37 @@ _cmd_close (int fd) return -1; _cmd_pids[fd] = 0; - if (close (fd) == -1) + if (close(fd) == -1) return -1; /* EINTR is ok (sort of), everything else is bad */ - while (waitpid (pid, &status, 0) < 0) + while (waitpid(pid, &status, 0) < 0) if (errno != EINTR) return -1; /* return child's termination status */ - return (WIFEXITED (status)) ? WEXITSTATUS (status) : -1; + return (WIFEXITED(status)) ? WEXITSTATUS(status) : -1; } - -static int -_cmd_fetch_output (int fd, output * op, int flags) -{ +static int _cmd_fetch_output(int fd, output *op, int flags) { size_t len = 0, i = 0, lineno = 0; - size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */ + size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */ char *buf = NULL; int ret; char tmpbuf[4096]; op->buf = NULL; op->buflen = 0; - while ((ret = read (fd, tmpbuf, sizeof (tmpbuf))) > 0) { - len = (size_t) ret; - op->buf = realloc (op->buf, op->buflen + len + 1); - memcpy (op->buf + op->buflen, tmpbuf, len); + while ((ret = read(fd, tmpbuf, sizeof(tmpbuf))) > 0) { + len = (size_t)ret; + op->buf = realloc(op->buf, op->buflen + len + 1); + memcpy(op->buf + op->buflen, tmpbuf, len); op->buflen += len; i++; } if (ret < 0) { - printf ("read() returned %d: %s\n", ret, strerror (errno)); + printf("read() returned %d: %s\n", ret, strerror(errno)); return ret; } @@ -231,10 +217,9 @@ _cmd_fetch_output (int fd, output * op, int flags) /* and some may want both */ if (flags & CMD_NO_ASSOC) { - buf = malloc (op->buflen); - memcpy (buf, op->buf, op->buflen); - } - else + buf = malloc(op->buflen); + memcpy(buf, op->buf, op->buflen); + } else buf = op->buf; op->line = NULL; @@ -248,8 +233,8 @@ _cmd_fetch_output (int fd, output * op, int flags) ary_size = op->buflen >> --rsf; } while (!ary_size); - op->line = realloc (op->line, ary_size * sizeof (char *)); - op->lens = realloc (op->lens, ary_size * sizeof (size_t)); + op->line = realloc(op->line, ary_size * sizeof(char *)); + op->lens = realloc(op->lens, ary_size * sizeof(size_t)); } /* set the pointer to the string */ @@ -261,7 +246,7 @@ _cmd_fetch_output (int fd, output * op, int flags) buf[i] = '\0'; /* calculate the string length using pointer difference */ - op->lens[lineno] = (size_t) & buf[i] - (size_t) op->line[lineno]; + op->lens[lineno] = (size_t)&buf[i] - (size_t)op->line[lineno]; lineno++; i++; @@ -270,10 +255,7 @@ _cmd_fetch_output (int fd, output * op, int flags) return lineno; } - -int -cmd_run (const char *cmdstring, output * out, output * err, int flags) -{ +int cmd_run(const char *cmdstring, output *out, output *err, int flags) { int i = 0, argc; size_t cmdlen; char **argv = NULL; @@ -285,120 +267,114 @@ cmd_run (const char *cmdstring, output * out, output * err, int flags) /* initialize the structs */ if (out) - memset (out, 0, sizeof (output)); + memset(out, 0, sizeof(output)); if (err) - memset (err, 0, sizeof (output)); + memset(err, 0, sizeof(output)); /* make copy of command string so strtok() doesn't silently modify it */ /* (the calling program may want to access it later) */ - cmdlen = strlen (cmdstring); - if ((cmd = malloc (cmdlen + 1)) == NULL) + cmdlen = strlen(cmdstring); + if ((cmd = malloc(cmdlen + 1)) == NULL) return -1; - memcpy (cmd, cmdstring, cmdlen); + memcpy(cmd, cmdstring, cmdlen); cmd[cmdlen] = '\0'; /* This is not a shell, so we don't handle "???" */ - if (strstr (cmdstring, "\"")) return -1; + if (strstr(cmdstring, "\"")) + return -1; /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */ - if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''")) + if (strstr(cmdstring, " ' ") || strstr(cmdstring, "'''")) return -1; /* each arg must be whitespace-separated, so args can be a maximum * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */ argc = (cmdlen >> 1) + 2; - argv = calloc (sizeof (char *), argc); + argv = calloc(sizeof(char *), argc); if (argv == NULL) { - printf ("%s\n", _("Could not malloc argv array in popen()")); + printf("%s\n", _("Could not malloc argv array in popen()")); return -1; } /* get command arguments (stupidly, but fairly quickly) */ while (cmd) { str = cmd; - str += strspn (str, " \t\r\n"); /* trim any leading whitespace */ + str += strspn(str, " \t\r\n"); /* trim any leading whitespace */ - if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */ + if (strstr(str, "'") == str) { /* handle SIMPLE quoted strings */ str++; - if (!strstr (str, "'")) - return -1; /* balanced? */ - cmd = 1 + strstr (str, "'"); - str[strcspn (str, "'")] = 0; - } - else { - if (strpbrk (str, " \t\r\n")) { - cmd = 1 + strpbrk (str, " \t\r\n"); - str[strcspn (str, " \t\r\n")] = 0; - } - else { + if (!strstr(str, "'")) + return -1; /* balanced? */ + cmd = 1 + strstr(str, "'"); + str[strcspn(str, "'")] = 0; + } else { + if (strpbrk(str, " \t\r\n")) { + cmd = 1 + strpbrk(str, " \t\r\n"); + str[strcspn(str, " \t\r\n")] = 0; + } else { cmd = NULL; } } - if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n")) + if (cmd && strlen(cmd) == strspn(cmd, " \t\r\n")) cmd = NULL; argv[i++] = str; } - return cmd_run_array (argv, out, err, flags); + return cmd_run_array(argv, out, err, flags); } -int -cmd_run_array (char *const *argv, output * out, output * err, int flags) -{ +int cmd_run_array(char *const *argv, output *out, output *err, int flags) { int fd, pfd_out[2], pfd_err[2]; /* initialize the structs */ if (out) - memset (out, 0, sizeof (output)); + memset(out, 0, sizeof(output)); if (err) - memset (err, 0, sizeof (output)); + memset(err, 0, sizeof(output)); - if ((fd = _cmd_open (argv, pfd_out, pfd_err)) == -1) - die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), argv[0]); + if ((fd = _cmd_open(argv, pfd_out, pfd_err)) == -1) + die(STATE_UNKNOWN, _("Could not open pipe: %s\n"), argv[0]); if (out) - out->lines = _cmd_fetch_output (pfd_out[0], out, flags); + out->lines = _cmd_fetch_output(pfd_out[0], out, flags); if (err) - err->lines = _cmd_fetch_output (pfd_err[0], err, flags); + err->lines = _cmd_fetch_output(pfd_err[0], err, flags); - return _cmd_close (fd); + return _cmd_close(fd); } -int -cmd_file_read ( char *filename, output *out, int flags) -{ +int cmd_file_read(char *filename, output *out, int flags) { int fd; - if(out) - memset (out, 0, sizeof(output)); + if (out) + memset(out, 0, sizeof(output)); if ((fd = open(filename, O_RDONLY)) == -1) { - die( STATE_UNKNOWN, _("Error opening %s: %s"), filename, strerror(errno) ); + die(STATE_UNKNOWN, _("Error opening %s: %s"), filename, strerror(errno)); } - if(out) - out->lines = _cmd_fetch_output (fd, out, flags); + if (out) + out->lines = _cmd_fetch_output(fd, out, flags); if (close(fd) == -1) - die( STATE_UNKNOWN, _("Error closing %s: %s"), filename, strerror(errno) ); + die(STATE_UNKNOWN, _("Error closing %s: %s"), filename, strerror(errno)); return 0; } -void -timeout_alarm_handler (int signo) -{ +void timeout_alarm_handler(int signo) { if (signo == SIGALRM) { - printf (_("%s - Plugin timed out after %d seconds\n"), - state_text(timeout_state), timeout_interval); + printf(_("%s - Plugin timed out after %d seconds\n"), state_text(timeout_state), timeout_interval); long maxfd = mp_open_max(); - if(_cmd_pids) for(long int i = 0; i < maxfd; i++) { - if(_cmd_pids[i] != 0) kill(_cmd_pids[i], SIGKILL); - } + if (_cmd_pids) + for (long int i = 0; i < maxfd; i++) { + if (_cmd_pids[i] != 0) + kill(_cmd_pids[i], SIGKILL); + } - exit (timeout_state); + exit(timeout_state); } } diff --git a/lib/utils_cmd.h b/lib/utils_cmd.h index 061f5d4..0fc0917 100644 --- a/lib/utils_cmd.h +++ b/lib/utils_cmd.h @@ -8,8 +8,7 @@ */ /** types **/ -struct output -{ +struct output { char *buf; /* output buffer */ size_t buflen; /* output buffer content length */ char **line; /* array of lines (points to buf) */ @@ -20,20 +19,18 @@ struct output typedef struct output output; /** prototypes **/ -int cmd_run (const char *, output *, output *, int); -int cmd_run_array (char *const *, output *, output *, int); -int cmd_file_read (char *, output *, int); +int cmd_run(const char *, output *, output *, int); +int cmd_run_array(char *const *, output *, output *, int); +int cmd_file_read(char *, output *, int); /* only multi-threaded plugins need to bother with this */ -void cmd_init (void); +void cmd_init(void); #define CMD_INIT cmd_init() /* possible flags for cmd_run()'s fourth argument */ -#define CMD_NO_ARRAYS 0x01 /* don't populate arrays at all */ -#define CMD_NO_ASSOC 0x02 /* output.line won't point to buf */ - - -void timeout_alarm_handler (int); +#define CMD_NO_ARRAYS 0x01 /* don't populate arrays at all */ +#define CMD_NO_ASSOC 0x02 /* output.line won't point to buf */ +void timeout_alarm_handler(int); #endif /* _UTILS_CMD_ */ diff --git a/lib/utils_disk.c b/lib/utils_disk.c index 483be06..a317f7d 100644 --- a/lib/utils_disk.c +++ b/lib/utils_disk.c @@ -1,44 +1,42 @@ /***************************************************************************** -* -* Library for check_disk -* -* License: GPL -* Copyright (c) 1999-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains utilities for check_disk. These are tested by libtap -* -* -* 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 . -* -* -*****************************************************************************/ + * + * Library for check_disk + * + * License: GPL + * Copyright (c) 1999-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains utilities for check_disk. These are tested by libtap + * + * + * 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 . + * + * + *****************************************************************************/ #include "common.h" #include "utils_disk.h" #include "gl/fsusage.h" #include -void -np_add_name (struct name_list **list, const char *name) -{ - struct name_list *new_entry; - new_entry = (struct name_list *) malloc (sizeof *new_entry); - new_entry->name = (char *) name; - new_entry->next = *list; - *list = new_entry; +void np_add_name(struct name_list **list, const char *name) { + struct name_list *new_entry; + new_entry = (struct name_list *)malloc(sizeof *new_entry); + new_entry->name = (char *)name; + new_entry->next = *list; + *list = new_entry; } /* @brief Initialises a new regex at the begin of list via regcomp(3) @@ -50,17 +48,14 @@ np_add_name (struct name_list **list, const char *name) * @param regex the string containing the regex which should be inserted into the list * @param clags the cflags parameter for regcomp(3) */ -int -np_add_regex (struct regex_list **list, const char *regex, int cflags) -{ - struct regex_list *new_entry = (struct regex_list *) malloc (sizeof *new_entry); +int np_add_regex(struct regex_list **list, const char *regex, int cflags) { + struct regex_list *new_entry = (struct regex_list *)malloc(sizeof *new_entry); if (new_entry == NULL) { - die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), - strerror(errno)); + die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), strerror(errno)); } - int regcomp_result = regcomp(&new_entry->regex, regex, cflags); + int regcomp_result = regcomp(&new_entry->regex, regex, cflags); if (!regcomp_result) { // regcomp succeeded @@ -74,197 +69,186 @@ np_add_regex (struct regex_list **list, const char *regex, int cflags) return regcomp_result; } - } /* Initialises a new parameter at the end of list */ -struct parameter_list * -np_add_parameter(struct parameter_list **list, const char *name) -{ - struct parameter_list *current = *list; - struct parameter_list *new_path; - new_path = (struct parameter_list *) malloc (sizeof *new_path); - new_path->name = (char *) malloc(strlen(name) + 1); - new_path->best_match = NULL; - new_path->name_next = NULL; - new_path->name_prev = NULL; - new_path->freespace_bytes = NULL; - new_path->freespace_units = NULL; - new_path->freespace_percent = NULL; - new_path->usedspace_bytes = NULL; - new_path->usedspace_units = NULL; - new_path->usedspace_percent = NULL; - new_path->usedinodes_percent = NULL; - new_path->freeinodes_percent = NULL; - new_path->group = NULL; - new_path->dfree_pct = -1; - new_path->dused_pct = -1; - new_path->total = 0; - new_path->available = 0; - new_path->available_to_root = 0; - new_path->used = 0; - new_path->dused_units = 0; - new_path->dfree_units = 0; - new_path->dtotal_units = 0; - new_path->inodes_total = 0; - new_path->inodes_free = 0; - new_path->inodes_free_to_root = 0; - new_path->inodes_used = 0; - new_path->dused_inodes_percent = 0; - new_path->dfree_inodes_percent = 0; - - strcpy(new_path->name, name); - - if (current == NULL) { - *list = new_path; - new_path->name_prev = NULL; - } else { - while (current->name_next) { - current = current->name_next; - } - current->name_next = new_path; - new_path->name_prev = current; - } - return new_path; +struct parameter_list *np_add_parameter(struct parameter_list **list, const char *name) { + struct parameter_list *current = *list; + struct parameter_list *new_path; + new_path = (struct parameter_list *)malloc(sizeof *new_path); + new_path->name = (char *)malloc(strlen(name) + 1); + new_path->best_match = NULL; + new_path->name_next = NULL; + new_path->name_prev = NULL; + new_path->freespace_bytes = NULL; + new_path->freespace_units = NULL; + new_path->freespace_percent = NULL; + new_path->usedspace_bytes = NULL; + new_path->usedspace_units = NULL; + new_path->usedspace_percent = NULL; + new_path->usedinodes_percent = NULL; + new_path->freeinodes_percent = NULL; + new_path->group = NULL; + new_path->dfree_pct = -1; + new_path->dused_pct = -1; + new_path->total = 0; + new_path->available = 0; + new_path->available_to_root = 0; + new_path->used = 0; + new_path->dused_units = 0; + new_path->dfree_units = 0; + new_path->dtotal_units = 0; + new_path->inodes_total = 0; + new_path->inodes_free = 0; + new_path->inodes_free_to_root = 0; + new_path->inodes_used = 0; + new_path->dused_inodes_percent = 0; + new_path->dfree_inodes_percent = 0; + + strcpy(new_path->name, name); + + if (current == NULL) { + *list = new_path; + new_path->name_prev = NULL; + } else { + while (current->name_next) { + current = current->name_next; + } + current->name_next = new_path; + new_path->name_prev = current; + } + return new_path; } /* Delete a given parameter from list and return pointer to next element*/ -struct parameter_list * -np_del_parameter(struct parameter_list *item, struct parameter_list *prev) -{ - if (item == NULL) { - return NULL; - } - struct parameter_list *next; - - if (item->name_next) - next = item->name_next; - else - next = NULL; - - if (next) - next->name_prev = prev; - - if (prev) - prev->name_next = next; - - if (item->name) { - free(item->name); - } - free(item); - - return next; -} +struct parameter_list *np_del_parameter(struct parameter_list *item, struct parameter_list *prev) { + if (item == NULL) { + return NULL; + } + struct parameter_list *next; + + if (item->name_next) + next = item->name_next; + else + next = NULL; + + if (next) + next->name_prev = prev; + if (prev) + prev->name_next = next; + + if (item->name) { + free(item->name); + } + free(item); + + return next; +} /* returns a pointer to the struct found in the list */ -struct parameter_list * -np_find_parameter(struct parameter_list *list, const char *name) -{ - struct parameter_list *temp_list; - for (temp_list = list; temp_list; temp_list = temp_list->name_next) { - if (! strcmp(temp_list->name, name)) - return temp_list; - } - - return NULL; +struct parameter_list *np_find_parameter(struct parameter_list *list, const char *name) { + struct parameter_list *temp_list; + for (temp_list = list; temp_list; temp_list = temp_list->name_next) { + if (!strcmp(temp_list->name, name)) + return temp_list; + } + + return NULL; } void np_set_best_match(struct parameter_list *desired, struct mount_entry *mount_list, bool exact) { - struct parameter_list *d; - for (d = desired; d; d= d->name_next) { - if (! d->best_match) { - struct mount_entry *me; - size_t name_len = strlen(d->name); - size_t best_match_len = 0; - struct mount_entry *best_match = NULL; - struct fs_usage fsp; - - /* set best match if path name exactly matches a mounted device name */ - for (me = mount_list; me; me = me->me_next) { - if (strcmp(me->me_devname, d->name)==0) { - if (get_fs_usage(me->me_mountdir, me->me_devname, &fsp) >= 0) { - best_match = me; - } - } - } - - /* set best match by directory name if no match was found by devname */ - if (! best_match) { - for (me = mount_list; me; me = me->me_next) { - size_t len = strlen (me->me_mountdir); - if ((!exact && (best_match_len <= len && len <= name_len && - (len == 1 || strncmp (me->me_mountdir, d->name, len) == 0))) - || (exact && strcmp(me->me_mountdir, d->name)==0)) - { - if (get_fs_usage(me->me_mountdir, me->me_devname, &fsp) >= 0) { - best_match = me; - best_match_len = len; - } - } - } - } - - if (best_match) { - d->best_match = best_match; - } else { - d->best_match = NULL; /* Not sure why this is needed as it should be null on initialisation */ - } - } - } + struct parameter_list *d; + for (d = desired; d; d = d->name_next) { + if (!d->best_match) { + struct mount_entry *me; + size_t name_len = strlen(d->name); + size_t best_match_len = 0; + struct mount_entry *best_match = NULL; + struct fs_usage fsp; + + /* set best match if path name exactly matches a mounted device name */ + for (me = mount_list; me; me = me->me_next) { + if (strcmp(me->me_devname, d->name) == 0) { + if (get_fs_usage(me->me_mountdir, me->me_devname, &fsp) >= 0) { + best_match = me; + } + } + } + + /* set best match by directory name if no match was found by devname */ + if (!best_match) { + for (me = mount_list; me; me = me->me_next) { + size_t len = strlen(me->me_mountdir); + if ((!exact && (best_match_len <= len && len <= name_len && (len == 1 || strncmp(me->me_mountdir, d->name, len) == 0))) || + (exact && strcmp(me->me_mountdir, d->name) == 0)) { + if (get_fs_usage(me->me_mountdir, me->me_devname, &fsp) >= 0) { + best_match = me; + best_match_len = len; + } + } + } + } + + if (best_match) { + d->best_match = best_match; + } else { + d->best_match = NULL; /* Not sure why this is needed as it should be null on initialisation */ + } + } + } } /* Returns true if name is in list */ -bool np_find_name (struct name_list *list, const char *name) { - const struct name_list *n; - - if (list == NULL || name == NULL) { - return false; - } - for (n = list; n; n = n->next) { - if (!strcmp(name, n->name)) { - return true; - } - } - return false; +bool np_find_name(struct name_list *list, const char *name) { + const struct name_list *n; + + if (list == NULL || name == NULL) { + return false; + } + for (n = list; n; n = n->next) { + if (!strcmp(name, n->name)) { + return true; + } + } + return false; } /* Returns true if name is in list */ -bool np_find_regmatch (struct regex_list *list, const char *name) { - int len; - regmatch_t m; +bool np_find_regmatch(struct regex_list *list, const char *name) { + int len; + regmatch_t m; - if (name == NULL) { - return false; - } + if (name == NULL) { + return false; + } - len = strlen(name); + len = strlen(name); - for (; list; list = list->next) { - /* Emulate a full match as if surrounded with ^( )$ - by checking whether the match spans the whole name */ - if (!regexec(&list->regex, name, 1, &m, 0) && m.rm_so == 0 && m.rm_eo == len) { - return true; - } - } + for (; list; list = list->next) { + /* Emulate a full match as if surrounded with ^( )$ + by checking whether the match spans the whole name */ + if (!regexec(&list->regex, name, 1, &m, 0) && m.rm_so == 0 && m.rm_eo == len) { + return true; + } + } - return false; + return false; } bool np_seen_name(struct name_list *list, const char *name) { - const struct name_list *s; - for (s = list; s; s=s->next) { - if (!strcmp(s->name, name)) { - return true; - } - } - return false; + const struct name_list *s; + for (s = list; s; s = s->next) { + if (!strcmp(s->name, name)) { + return true; + } + } + return false; } -bool np_regex_match_mount_entry (struct mount_entry* me, regex_t* re) { - if (regexec(re, me->me_devname, (size_t) 0, NULL, 0) == 0 || - regexec(re, me->me_mountdir, (size_t) 0, NULL, 0) == 0 ) { - return true; - } +bool np_regex_match_mount_entry(struct mount_entry *me, regex_t *re) { + if (regexec(re, me->me_devname, (size_t)0, NULL, 0) == 0 || regexec(re, me->me_mountdir, (size_t)0, NULL, 0) == 0) { + return true; + } return false; } diff --git a/lib/utils_disk.h b/lib/utils_disk.h index 5b2caf2..c5e81dc 100644 --- a/lib/utils_disk.h +++ b/lib/utils_disk.h @@ -4,49 +4,45 @@ #include "utils_base.h" #include "regex.h" -struct name_list -{ - char *name; - struct name_list *next; +struct name_list { + char *name; + struct name_list *next; }; -struct regex_list -{ - regex_t regex; - struct regex_list *next; +struct regex_list { + regex_t regex; + struct regex_list *next; }; -struct parameter_list -{ - char *name; - thresholds *freespace_bytes; - thresholds *freespace_units; - thresholds *freespace_percent; - thresholds *usedspace_bytes; - thresholds *usedspace_units; - thresholds *usedspace_percent; - thresholds *usedinodes_percent; - thresholds *freeinodes_percent; - char *group; - struct mount_entry *best_match; - struct parameter_list *name_next; - struct parameter_list *name_prev; - uintmax_t total, available, available_to_root, used, - inodes_free, inodes_free_to_root, inodes_used, inodes_total; - double dfree_pct, dused_pct; - uint64_t dused_units, dfree_units, dtotal_units; - double dused_inodes_percent, dfree_inodes_percent; +struct parameter_list { + char *name; + thresholds *freespace_bytes; + thresholds *freespace_units; + thresholds *freespace_percent; + thresholds *usedspace_bytes; + thresholds *usedspace_units; + thresholds *usedspace_percent; + thresholds *usedinodes_percent; + thresholds *freeinodes_percent; + char *group; + struct mount_entry *best_match; + struct parameter_list *name_next; + struct parameter_list *name_prev; + uintmax_t total, available, available_to_root, used, inodes_free, inodes_free_to_root, inodes_used, inodes_total; + double dfree_pct, dused_pct; + uint64_t dused_units, dfree_units, dtotal_units; + double dused_inodes_percent, dfree_inodes_percent; }; -void np_add_name (struct name_list **list, const char *name); -bool np_find_name (struct name_list *list, const char *name); -bool np_seen_name (struct name_list *list, const char *name); -int np_add_regex (struct regex_list **list, const char *regex, int cflags); -bool np_find_regmatch (struct regex_list *list, const char *name); +void np_add_name(struct name_list **list, const char *name); +bool np_find_name(struct name_list *list, const char *name); +bool np_seen_name(struct name_list *list, const char *name); +int np_add_regex(struct regex_list **list, const char *regex, int cflags); +bool np_find_regmatch(struct regex_list *list, const char *name); struct parameter_list *np_add_parameter(struct parameter_list **list, const char *name); struct parameter_list *np_find_parameter(struct parameter_list *list, const char *name); struct parameter_list *np_del_parameter(struct parameter_list *item, struct parameter_list *prev); -int search_parameter_list (struct parameter_list *list, const char *name); +int search_parameter_list(struct parameter_list *list, const char *name); void np_set_best_match(struct parameter_list *desired, struct mount_entry *mount_list, bool exact); -bool np_regex_match_mount_entry (struct mount_entry* me, regex_t* re); +bool np_regex_match_mount_entry(struct mount_entry *me, regex_t *re); diff --git a/lib/utils_tcp.c b/lib/utils_tcp.c index 23ee4a9..ffb351e 100644 --- a/lib/utils_tcp.c +++ b/lib/utils_tcp.c @@ -1,51 +1,46 @@ /***************************************************************************** -* -* Library for check_tcp -* -* License: GPL -* Copyright (c) 1999-2013 Monitoring Plugins Development Team -* -* Description: -* -* This file contains utilities for check_tcp. These are tested by libtap -* -* -* 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 . -* -* -*****************************************************************************/ + * + * Library for check_tcp + * + * License: GPL + * Copyright (c) 1999-2013 Monitoring Plugins Development Team + * + * Description: + * + * This file contains utilities for check_tcp. These are tested by libtap + * + * + * 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 . + * + * + *****************************************************************************/ #include "common.h" #include "utils_tcp.h" -#define VERBOSE(message) \ - do { \ - if (flags & NP_MATCH_VERBOSE) \ - puts(message); \ +#define VERBOSE(message) \ + do { \ + if (flags & NP_MATCH_VERBOSE) \ + puts(message); \ } while (0) -enum np_match_result -np_expect_match(char *status, char **server_expect, int expect_count, int flags) -{ +enum np_match_result np_expect_match(char *status, char **server_expect, int expect_count, int flags) { int i, match = 0, partial = 0; for (i = 0; i < expect_count; i++) { if (flags & NP_MATCH_VERBOSE) - printf("looking for [%s] %s [%s]\n", server_expect[i], - (flags & NP_MATCH_EXACT) ? - "in beginning of" : "anywhere in", - status); + printf("looking for [%s] %s [%s]\n", server_expect[i], (flags & NP_MATCH_EXACT) ? "in beginning of" : "anywhere in", status); if (flags & NP_MATCH_EXACT) { if (strncmp(status, server_expect[i], strlen(server_expect[i])) == 0) { @@ -58,15 +53,14 @@ np_expect_match(char *status, char **server_expect, int expect_count, int flags) continue; } } else if (strstr(status, server_expect[i]) != NULL) { - VERBOSE("found it"); - match++; - continue; + VERBOSE("found it"); + match++; + continue; } VERBOSE("couldn't find it"); } - if ((flags & NP_MATCH_ALL && match == expect_count) || - (!(flags & NP_MATCH_ALL) && match >= 1)) + if ((flags & NP_MATCH_ALL && match == expect_count) || (!(flags & NP_MATCH_ALL) && match >= 1)) return NP_MATCH_SUCCESS; else if (partial > 0 || !(flags & NP_MATCH_EXACT)) return NP_MATCH_RETRY; diff --git a/lib/utils_tcp.h b/lib/utils_tcp.h index 0328a9c..6543377 100644 --- a/lib/utils_tcp.h +++ b/lib/utils_tcp.h @@ -1,8 +1,8 @@ /* Header file for utils_tcp */ -#define NP_MATCH_ALL 0x1 -#define NP_MATCH_EXACT 0x2 -#define NP_MATCH_VERBOSE 0x4 +#define NP_MATCH_ALL 0x1 +#define NP_MATCH_EXACT 0x2 +#define NP_MATCH_VERBOSE 0x4 /* * The NP_MATCH_RETRY state indicates that matching might succeed if @@ -10,13 +10,6 @@ * caller to decide whether it makes sense to wait for additional data from the * server. */ -enum np_match_result { - NP_MATCH_FAILURE, - NP_MATCH_SUCCESS, - NP_MATCH_RETRY -}; +enum np_match_result { NP_MATCH_FAILURE, NP_MATCH_SUCCESS, NP_MATCH_RETRY }; -enum np_match_result np_expect_match(char *status, - char **server_expect, - int server_expect_count, - int flags); +enum np_match_result np_expect_match(char *status, char **server_expect, int server_expect_count, int flags); -- cgit v0.10-9-g596f From 9462819774ed2e3f51c75fffda59724428205c0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= Date: Thu, 17 Oct 2024 18:01:49 +0200 Subject: lib: Update copyright diff --git a/lib/extra_opts.c b/lib/extra_opts.c index 82460e9..8878733 100644 --- a/lib/extra_opts.c +++ b/lib/extra_opts.c @@ -3,7 +3,7 @@ * Monitoring Plugins extra_opts library * * License: GPL - * Copyright (c) 2007 Monitoring Plugins Development Team + * Copyright (c) 2007 - 2024 Monitoring Plugins Development Team * * 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 diff --git a/lib/maxfd.c b/lib/maxfd.c index c39d427..ca5b6e5 100644 --- a/lib/maxfd.c +++ b/lib/maxfd.c @@ -1,3 +1,23 @@ +/***************************************************************************** + * + * License: GPL + * Copyright (c) 2024 Monitoring Plugins Development Team + * + * 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 . + * + *****************************************************************************/ + #include "./maxfd.h" #include diff --git a/lib/parse_ini.c b/lib/parse_ini.c index 150df7b..873ee8c 100644 --- a/lib/parse_ini.c +++ b/lib/parse_ini.c @@ -3,7 +3,7 @@ * Monitoring Plugins parse_ini library * * License: GPL - * Copyright (c) 2007 Monitoring Plugins Development Team + * Copyright (c) 2007 - 2024 Monitoring Plugins Development Team * * 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 diff --git a/lib/utils_base.c b/lib/utils_base.c index cd13583..6d6954e 100644 --- a/lib/utils_base.c +++ b/lib/utils_base.c @@ -3,7 +3,7 @@ * utils_base.c * * License: GPL - * Copyright (c) 2006 Monitoring Plugins Development Team + * Copyright (c) 2006 - 2024 Monitoring Plugins Development Team * * Library of useful functions for plugins * diff --git a/lib/utils_cmd.c b/lib/utils_cmd.c index 25d5678..416cf82 100644 --- a/lib/utils_cmd.c +++ b/lib/utils_cmd.c @@ -3,7 +3,7 @@ * Monitoring run command utilities * * License: GPL - * Copyright (c) 2005-2006 Monitoring Plugins Development Team + * Copyright (c) 2005-2024 Monitoring Plugins Development Team * * Description : * diff --git a/lib/utils_cmd.h b/lib/utils_cmd.h index 0fc0917..d00069c 100644 --- a/lib/utils_cmd.h +++ b/lib/utils_cmd.h @@ -4,7 +4,6 @@ /* * Header file for Monitoring Plugins utils_cmd.c * - * */ /** types **/ diff --git a/lib/utils_disk.c b/lib/utils_disk.c index a317f7d..c87090e 100644 --- a/lib/utils_disk.c +++ b/lib/utils_disk.c @@ -3,7 +3,7 @@ * Library for check_disk * * License: GPL - * Copyright (c) 1999-2007 Monitoring Plugins Development Team + * Copyright (c) 1999-2024 Monitoring Plugins Development Team * * Description: * diff --git a/lib/utils_tcp.c b/lib/utils_tcp.c index ffb351e..440eb9b 100644 --- a/lib/utils_tcp.c +++ b/lib/utils_tcp.c @@ -3,7 +3,7 @@ * Library for check_tcp * * License: GPL - * Copyright (c) 1999-2013 Monitoring Plugins Development Team + * Copyright (c) 1999-2024 Monitoring Plugins Development Team * * Description: * -- cgit v0.10-9-g596f From c0a3bd07057f7e6b000d477088424cf71f89e3e7 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Sat, 19 Oct 2024 01:21:02 +0200 Subject: clang format config: line lenght 180 -> 140, no base style diff --git a/.clang-format b/.clang-format index c7f0b5e..a7d1949 100644 --- a/.clang-format +++ b/.clang-format @@ -1,10 +1,10 @@ -BasedOnStyle: LLVM UseTab: ForContinuationAndIndentation IndentWidth: 4 TabWidth: 4 AllowShortIfStatementsOnASingleLine: false BreakBeforeBraces: Attach AlignConsecutiveMacros: true -ColumnLimit: 180 +ColumnLimit: 140 IndentPPDirectives: AfterHash SortIncludes: Never +BinPackArguments: false -- cgit v0.10-9-g596f From 4541b2b3571fd7806313187aa852bfe7c2ad5235 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Sat, 19 Oct 2024 01:21:22 +0200 Subject: check_ups: clang-format again diff --git a/plugins/check_ups.c b/plugins/check_ups.c index e5badc8..c2451ab 100644 --- a/plugins/check_ups.c +++ b/plugins/check_ups.c @@ -235,9 +235,19 @@ int main(int argc, char **argv) { } else if (config.check_warn && ups_utility_deviation >= config.warning_value) { result = max_state(result, STATE_WARNING); } - xasprintf(&data, "%s", - perfdata("voltage", (long)(1000 * ups_utility_voltage), "mV", config.check_warn, (long)(1000 * config.warning_value), config.check_crit, - (long)(1000 * config.critical_value), true, 0, false, 0)); + xasprintf(&data, + "%s", + perfdata("voltage", + (long)(1000 * ups_utility_voltage), + "mV", + config.check_warn, + (long)(1000 * config.warning_value), + config.check_crit, + (long)(1000 * config.critical_value), + true, + 0, + false, + 0)); } else { xasprintf(&data, "%s", perfdata("voltage", (long)(1000 * ups_utility_voltage), "mV", false, 0, false, 0, true, 0, false, 0)); } @@ -262,9 +272,20 @@ int main(int argc, char **argv) { } else if (config.check_warn && ups_battery_percent <= config.warning_value) { result = max_state(result, STATE_WARNING); } - xasprintf(&data, "%s %s", data, - perfdata("battery", (long)ups_battery_percent, "%", config.check_warn, (long)(config.warning_value), config.check_crit, (long)(config.critical_value), true, - 0, true, 100)); + xasprintf(&data, + "%s %s", + data, + perfdata("battery", + (long)ups_battery_percent, + "%", + config.check_warn, + (long)(config.warning_value), + config.check_crit, + (long)(config.critical_value), + true, + 0, + true, + 100)); } else { xasprintf(&data, "%s %s", data, perfdata("battery", (long)ups_battery_percent, "%", false, 0, false, 0, true, 0, true, 100)); } @@ -289,9 +310,20 @@ int main(int argc, char **argv) { } else if (config.check_warn && ups_load_percent >= config.warning_value) { result = max_state(result, STATE_WARNING); } - xasprintf(&data, "%s %s", data, - perfdata("load", (long)ups_load_percent, "%", config.check_warn, (long)(config.warning_value), config.check_crit, (long)(config.critical_value), true, 0, - true, 100)); + xasprintf(&data, + "%s %s", + data, + perfdata("load", + (long)ups_load_percent, + "%", + config.check_warn, + (long)(config.warning_value), + config.check_crit, + (long)(config.critical_value), + true, + 0, + true, + 100)); } else { xasprintf(&data, "%s %s", data, perfdata("load", (long)ups_load_percent, "%", false, 0, false, 0, true, 0, true, 100)); } @@ -325,9 +357,20 @@ int main(int argc, char **argv) { } else if (config.check_warn && ups_temperature >= config.warning_value) { result = max_state(result, STATE_WARNING); } - xasprintf(&data, "%s %s", data, - perfdata("temp", (long)ups_temperature, tunits, config.check_warn, (long)(config.warning_value), config.check_crit, (long)(config.critical_value), true, 0, - false, 0)); + xasprintf(&data, + "%s %s", + data, + perfdata("temp", + (long)ups_temperature, + tunits, + config.check_warn, + (long)(config.warning_value), + config.check_crit, + (long)(config.critical_value), + true, + 0, + false, + 0)); } else { xasprintf(&data, "%s %s", data, perfdata("temp", (long)ups_temperature, tunits, false, 0, false, 0, true, 0, false, 0)); } @@ -351,9 +394,20 @@ int main(int argc, char **argv) { } else if (config.check_warn && ups_realpower >= config.warning_value) { result = max_state(result, STATE_WARNING); } - xasprintf(&data, "%s %s", data, - perfdata("realpower", (long)ups_realpower, "W", config.check_warn, (long)(config.warning_value), config.check_crit, (long)(config.critical_value), true, 0, - false, 0)); + xasprintf(&data, + "%s %s", + data, + perfdata("realpower", + (long)ups_realpower, + "W", + config.check_warn, + (long)(config.warning_value), + config.check_crit, + (long)(config.critical_value), + true, + 0, + false, + 0)); } else { xasprintf(&data, "%s %s", data, perfdata("realpower", (long)ups_realpower, "W", false, 0, false, 0, true, 0, false, 0)); } @@ -635,10 +689,12 @@ void print_help(void) { printf("Copyright (c) 2004 Arnaud Quette \n"); printf(COPYRIGHT, copyright, email); - printf("%s\n", _("This plugin tests the UPS service on the specified host. " - "Network UPS Tools")); - printf("%s\n", _("from www.networkupstools.org must be running for this " - "plugin to work.")); + printf("%s\n", + _("This plugin tests the UPS service on the specified host. " + "Network UPS Tools")); + printf("%s\n", + _("from www.networkupstools.org must be running for this " + "plugin to work.")); printf("\n\n"); @@ -667,31 +723,41 @@ void print_help(void) { /* printf (UT_VERBOSE); */ printf("\n"); - printf("%s\n", _("This plugin attempts to determine the status of a UPS " - "(Uninterruptible Power")); - printf("%s\n", _("Supply) on a local or remote host. If the UPS is online " - "or calibrating, the")); - printf("%s\n", _("plugin will return an OK state. If the battery is on it " - "will return a WARNING")); - printf("%s\n", _("state. If the UPS is off or has a low battery the plugin " - "will return a CRITICAL")); + printf("%s\n", + _("This plugin attempts to determine the status of a UPS " + "(Uninterruptible Power")); + printf("%s\n", + _("Supply) on a local or remote host. If the UPS is online " + "or calibrating, the")); + printf("%s\n", + _("plugin will return an OK state. If the battery is on it " + "will return a WARNING")); + printf("%s\n", + _("state. If the UPS is off or has a low battery the plugin " + "will return a CRITICAL")); printf("%s\n", _("state.")); printf("\n"); printf("%s\n", _("Notes:")); - printf(" %s\n", _("You may also specify a variable to check (such as " - "temperature, utility voltage,")); - printf(" %s\n", _("battery load, etc.) as well as warning and critical " - "thresholds for the value")); - printf(" %s\n", _("of that variable. If the remote host has multiple UPS " - "that are being monitored")); - printf(" %s\n", _("you will have to use the --ups option to specify which " - "UPS to check.")); + printf(" %s\n", + _("You may also specify a variable to check (such as " + "temperature, utility voltage,")); + printf(" %s\n", + _("battery load, etc.) as well as warning and critical " + "thresholds for the value")); + printf(" %s\n", + _("of that variable. If the remote host has multiple UPS " + "that are being monitored")); + printf(" %s\n", + _("you will have to use the --ups option to specify which " + "UPS to check.")); printf("\n"); - printf(" %s\n", _("This plugin requires that the UPSD daemon distributed " - "with Russell Kroll's")); - printf(" %s\n", _("Network UPS Tools be installed on the remote host. If " - "you do not have the")); + printf(" %s\n", + _("This plugin requires that the UPSD daemon distributed " + "with Russell Kroll's")); + printf(" %s\n", + _("Network UPS Tools be installed on the remote host. If " + "you do not have the")); printf(" %s\n", _("package installed on your system, you can download it from")); printf(" %s\n", _("http://www.networkupstools.org")); -- cgit v0.10-9-g596f From 39705a8c1f7b8ecba29b1e3e5abb906d9c2e6b5b Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Fri, 25 Oct 2024 11:45:48 +0200 Subject: clang-format options: set BinPack to true diff --git a/.clang-format b/.clang-format index a7d1949..f29680a 100644 --- a/.clang-format +++ b/.clang-format @@ -7,4 +7,4 @@ AlignConsecutiveMacros: true ColumnLimit: 140 IndentPPDirectives: AfterHash SortIncludes: Never -BinPackArguments: false +BinPackArguments: true -- cgit v0.10-9-g596f From 05ad606c09325ae9ae7d4607a55236245dcad47a Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Fri, 25 Oct 2024 11:45:58 +0200 Subject: check_ups: clang-format again diff --git a/plugins/check_ups.c b/plugins/check_ups.c index c2451ab..f60c0e9 100644 --- a/plugins/check_ups.c +++ b/plugins/check_ups.c @@ -235,19 +235,9 @@ int main(int argc, char **argv) { } else if (config.check_warn && ups_utility_deviation >= config.warning_value) { result = max_state(result, STATE_WARNING); } - xasprintf(&data, - "%s", - perfdata("voltage", - (long)(1000 * ups_utility_voltage), - "mV", - config.check_warn, - (long)(1000 * config.warning_value), - config.check_crit, - (long)(1000 * config.critical_value), - true, - 0, - false, - 0)); + xasprintf(&data, "%s", + perfdata("voltage", (long)(1000 * ups_utility_voltage), "mV", config.check_warn, (long)(1000 * config.warning_value), + config.check_crit, (long)(1000 * config.critical_value), true, 0, false, 0)); } else { xasprintf(&data, "%s", perfdata("voltage", (long)(1000 * ups_utility_voltage), "mV", false, 0, false, 0, true, 0, false, 0)); } @@ -272,20 +262,9 @@ int main(int argc, char **argv) { } else if (config.check_warn && ups_battery_percent <= config.warning_value) { result = max_state(result, STATE_WARNING); } - xasprintf(&data, - "%s %s", - data, - perfdata("battery", - (long)ups_battery_percent, - "%", - config.check_warn, - (long)(config.warning_value), - config.check_crit, - (long)(config.critical_value), - true, - 0, - true, - 100)); + xasprintf(&data, "%s %s", data, + perfdata("battery", (long)ups_battery_percent, "%", config.check_warn, (long)(config.warning_value), + config.check_crit, (long)(config.critical_value), true, 0, true, 100)); } else { xasprintf(&data, "%s %s", data, perfdata("battery", (long)ups_battery_percent, "%", false, 0, false, 0, true, 0, true, 100)); } @@ -310,20 +289,9 @@ int main(int argc, char **argv) { } else if (config.check_warn && ups_load_percent >= config.warning_value) { result = max_state(result, STATE_WARNING); } - xasprintf(&data, - "%s %s", - data, - perfdata("load", - (long)ups_load_percent, - "%", - config.check_warn, - (long)(config.warning_value), - config.check_crit, - (long)(config.critical_value), - true, - 0, - true, - 100)); + xasprintf(&data, "%s %s", data, + perfdata("load", (long)ups_load_percent, "%", config.check_warn, (long)(config.warning_value), config.check_crit, + (long)(config.critical_value), true, 0, true, 100)); } else { xasprintf(&data, "%s %s", data, perfdata("load", (long)ups_load_percent, "%", false, 0, false, 0, true, 0, true, 100)); } @@ -357,20 +325,9 @@ int main(int argc, char **argv) { } else if (config.check_warn && ups_temperature >= config.warning_value) { result = max_state(result, STATE_WARNING); } - xasprintf(&data, - "%s %s", - data, - perfdata("temp", - (long)ups_temperature, - tunits, - config.check_warn, - (long)(config.warning_value), - config.check_crit, - (long)(config.critical_value), - true, - 0, - false, - 0)); + xasprintf(&data, "%s %s", data, + perfdata("temp", (long)ups_temperature, tunits, config.check_warn, (long)(config.warning_value), config.check_crit, + (long)(config.critical_value), true, 0, false, 0)); } else { xasprintf(&data, "%s %s", data, perfdata("temp", (long)ups_temperature, tunits, false, 0, false, 0, true, 0, false, 0)); } @@ -394,20 +351,9 @@ int main(int argc, char **argv) { } else if (config.check_warn && ups_realpower >= config.warning_value) { result = max_state(result, STATE_WARNING); } - xasprintf(&data, - "%s %s", - data, - perfdata("realpower", - (long)ups_realpower, - "W", - config.check_warn, - (long)(config.warning_value), - config.check_crit, - (long)(config.critical_value), - true, - 0, - false, - 0)); + xasprintf(&data, "%s %s", data, + perfdata("realpower", (long)ups_realpower, "W", config.check_warn, (long)(config.warning_value), config.check_crit, + (long)(config.critical_value), true, 0, false, 0)); } else { xasprintf(&data, "%s %s", data, perfdata("realpower", (long)ups_realpower, "W", false, 0, false, 0, true, 0, false, 0)); } @@ -689,12 +635,10 @@ void print_help(void) { printf("Copyright (c) 2004 Arnaud Quette \n"); printf(COPYRIGHT, copyright, email); - printf("%s\n", - _("This plugin tests the UPS service on the specified host. " - "Network UPS Tools")); - printf("%s\n", - _("from www.networkupstools.org must be running for this " - "plugin to work.")); + printf("%s\n", _("This plugin tests the UPS service on the specified host. " + "Network UPS Tools")); + printf("%s\n", _("from www.networkupstools.org must be running for this " + "plugin to work.")); printf("\n\n"); @@ -723,41 +667,31 @@ void print_help(void) { /* printf (UT_VERBOSE); */ printf("\n"); - printf("%s\n", - _("This plugin attempts to determine the status of a UPS " - "(Uninterruptible Power")); - printf("%s\n", - _("Supply) on a local or remote host. If the UPS is online " - "or calibrating, the")); - printf("%s\n", - _("plugin will return an OK state. If the battery is on it " - "will return a WARNING")); - printf("%s\n", - _("state. If the UPS is off or has a low battery the plugin " - "will return a CRITICAL")); + printf("%s\n", _("This plugin attempts to determine the status of a UPS " + "(Uninterruptible Power")); + printf("%s\n", _("Supply) on a local or remote host. If the UPS is online " + "or calibrating, the")); + printf("%s\n", _("plugin will return an OK state. If the battery is on it " + "will return a WARNING")); + printf("%s\n", _("state. If the UPS is off or has a low battery the plugin " + "will return a CRITICAL")); printf("%s\n", _("state.")); printf("\n"); printf("%s\n", _("Notes:")); - printf(" %s\n", - _("You may also specify a variable to check (such as " - "temperature, utility voltage,")); - printf(" %s\n", - _("battery load, etc.) as well as warning and critical " - "thresholds for the value")); - printf(" %s\n", - _("of that variable. If the remote host has multiple UPS " - "that are being monitored")); - printf(" %s\n", - _("you will have to use the --ups option to specify which " - "UPS to check.")); + printf(" %s\n", _("You may also specify a variable to check (such as " + "temperature, utility voltage,")); + printf(" %s\n", _("battery load, etc.) as well as warning and critical " + "thresholds for the value")); + printf(" %s\n", _("of that variable. If the remote host has multiple UPS " + "that are being monitored")); + printf(" %s\n", _("you will have to use the --ups option to specify which " + "UPS to check.")); printf("\n"); - printf(" %s\n", - _("This plugin requires that the UPSD daemon distributed " - "with Russell Kroll's")); - printf(" %s\n", - _("Network UPS Tools be installed on the remote host. If " - "you do not have the")); + printf(" %s\n", _("This plugin requires that the UPSD daemon distributed " + "with Russell Kroll's")); + printf(" %s\n", _("Network UPS Tools be installed on the remote host. If " + "you do not have the")); printf(" %s\n", _("package installed on your system, you can download it from")); printf(" %s\n", _("http://www.networkupstools.org")); -- cgit v0.10-9-g596f From 903773eb9c3cc2079187dc99c7b48662148ff679 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Fri, 25 Oct 2024 12:02:14 +0200 Subject: Add sanity options to test prepare scripts diff --git a/.github/mock.sh b/.github/mock.sh index 7fbe690..8da147e 100755 --- a/.github/mock.sh +++ b/.github/mock.sh @@ -2,6 +2,8 @@ set -x +set -euo pipefail + export DEBIAN_FRONTEND=noninteractive BASE_PATH="/src" diff --git a/.github/prepare_debian.sh b/.github/prepare_debian.sh index 3f4674a..c38d241 100755 --- a/.github/prepare_debian.sh +++ b/.github/prepare_debian.sh @@ -1,7 +1,7 @@ #!/bin/bash set -x -set -e +set -euo pipefail export DEBIAN_FRONTEND=noninteractive -- cgit v0.10-9-g596f From d996f6560065950393c186cb6c39d94ea9025ac1 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Fri, 25 Oct 2024 12:21:16 +0200 Subject: github/mock.sh: Improve readability and generel shellcheck stuff diff --git a/.github/mock.sh b/.github/mock.sh index 8da147e..0b91364 100755 --- a/.github/mock.sh +++ b/.github/mock.sh @@ -20,7 +20,11 @@ SPEC_FILE="${SPEC_DIR}monitoring-plugins.spec" cd ${BASE_PATH} dnf -y --setopt="tsflags=nodocs" update && \ - if [ ${distro_id} != "fedora" ]; then dnf -y --setopt="tsflags=nodocs" install epel-release; else platform_id="$(echo ${platform_id} | sed s/^f/fc/)"; fi && \ + if [ "${distro_id}" != "fedora" ]; then + dnf -y --setopt="tsflags=nodocs" install epel-release; + else + platform_id="$(echo "${platform_id}" | sed s/^f/fc/)"; + fi && \ case ${distro_id} in ol) case ${platform_id} in @@ -34,19 +38,27 @@ dnf -y --setopt="tsflags=nodocs" update && \ ;; esac dnf -y --setopt="tsflags=nodocs" install mock rpm-build git-core && \ - usermod -a -G mock $(whoami) + usermod -a -G mock "$(whoami)" + SRC_RPM="monitoring-plugins-*-1.${platform_id}.src.rpm" + if command -v git > /dev/null 2>&1; then git config --global --add safe.directory ${BASE_PATH} SHA="$(git rev-parse HEAD)" sed "s/^%global commit.*/%global commit ${SHA}/" ${SPEC_FILE} > ${SPEC_DIR}monitoring-plugins-git.spec sed -i "s/^%global fromgit.*/%global fromgit 1/" ${SPEC_DIR}monitoring-plugins-git.spec SPEC_FILE="${SPEC_DIR}monitoring-plugins-git.spec" - SRC_RPM="monitoring-plugins-*git.$(echo ${SHA:0:7})*.${platform_id}.src.rpm" + SRC_RPM="monitoring-plugins-*git.${SHA:0:7}*.${platform_id}.src.rpm" fi + mkdir -p "${SRCRPM_DIR}" "${RPM_DIR}" #rpmbuild --undefine=_disable_source_fetch --define "_sourcedir ${SOURCE_DIR}" -ba ${SPEC_FILE} -dnf -y --setopt="tsflags=nodocs" install rpmdevtools && spectool -g -C ${SOURCE_DIR} ${SPEC_FILE} && \ -mock --dnf --clean --spec ${SPEC_FILE} --sources=${SOURCE_DIR} --result=${SRCRPM_DIR} --build || { cat ${SRCRPM_DIR}/{root,build}.log; exit 1; } -mock --dnf --clean --sources=${SOURCE_DIR} --result=${RPM_DIR} --rebuild ${SRCRPM_DIR}/${SRC_RPM} || { cat ${RPM_DIR}/{root,build}.log; exit 1; } +dnf -y --setopt="tsflags=nodocs" install rpmdevtools && \ + spectool -g -C ${SOURCE_DIR} ${SPEC_FILE} && \ + { mock --dnf --clean --spec ${SPEC_FILE} --sources=${SOURCE_DIR} --result=${SRCRPM_DIR} --build || \ + { cat ${SRCRPM_DIR}/{root,build}.log; exit 1; } } + +mock --dnf --clean --sources=${SOURCE_DIR} --result=${RPM_DIR} --rebuild "${SRCRPM_DIR}/${SRC_RPM}" || \ + { cat ${RPM_DIR}/{root,build}.log; exit 1; } + ls -la ${SOURCE_DIR} ${SRCRPM_DIR} ${RPM_DIR} -- cgit v0.10-9-g596f From 78246e904ddfc9c0a88e9f47797dc38c1693abbb Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Fri, 25 Oct 2024 12:30:19 +0200 Subject: prepare_debian.sh: Fix typo diff --git a/.github/prepare_debian.sh b/.github/prepare_debian.sh index c38d241..3640e50 100755 --- a/.github/prepare_debian.sh +++ b/.github/prepare_debian.sh @@ -127,5 +127,5 @@ sed "/NP_HOST_TLS_CERT/s/.*/'NP_HOST_TLS_CERT' => '$(hostname)',/" -i /src/.gith # create some test files to lower inodes for i in $(seq 10); do - touch /media/ramdisk2/test.$1 + touch /media/ramdisk2/test.$i done -- cgit v0.10-9-g596f From 54162dbaf689d560656e3eb6c3313840ebc0513a Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Fri, 25 Oct 2024 12:52:32 +0200 Subject: mock.sh: remove some quotting to allow pathname expansion again diff --git a/.github/mock.sh b/.github/mock.sh index 0b91364..87543ce 100755 --- a/.github/mock.sh +++ b/.github/mock.sh @@ -58,7 +58,7 @@ dnf -y --setopt="tsflags=nodocs" install rpmdevtools && \ { mock --dnf --clean --spec ${SPEC_FILE} --sources=${SOURCE_DIR} --result=${SRCRPM_DIR} --build || \ { cat ${SRCRPM_DIR}/{root,build}.log; exit 1; } } -mock --dnf --clean --sources=${SOURCE_DIR} --result=${RPM_DIR} --rebuild "${SRCRPM_DIR}/${SRC_RPM}" || \ +mock --dnf --clean --sources=${SOURCE_DIR} --result=${RPM_DIR} --rebuild "${SRCRPM_DIR}"/${SRC_RPM} || \ { cat ${RPM_DIR}/{root,build}.log; exit 1; } ls -la ${SOURCE_DIR} ${SRCRPM_DIR} ${RPM_DIR} -- cgit v0.10-9-g596f From de6e3c45f3f0889a5b4aada623cbefbd9fcb434d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= Date: Wed, 30 Oct 2024 17:12:19 +0100 Subject: check_icmp: Apply clang-format again diff --git a/plugins-root/check_icmp.c b/plugins-root/check_icmp.c index 6eefeb0..960ab8f 100644 --- a/plugins-root/check_icmp.c +++ b/plugins-root/check_icmp.c @@ -580,7 +580,8 @@ int main(int argc, char **argv) { icmp_data_size = size; icmp_pkt_size = size + ICMP_MINLEN; } else - usage_va("ICMP data length must be between: %lu and %lu", sizeof(struct icmp) + sizeof(struct icmp_ping_data), MAX_PING_DATA - 1); + usage_va("ICMP data length must be between: %lu and %lu", sizeof(struct icmp) + sizeof(struct icmp_ping_data), + MAX_PING_DATA - 1); break; case 'i': pkt_interval = get_timevar(optarg); @@ -803,7 +804,8 @@ int main(int argc, char **argv) { "target_interval: %0.3f, pkt_interval %0.3f\n" "crit.rta: %0.3f\n" "max_completion_time: %0.3f\n", - packets, targets, (float)target_interval / 1000, (float)pkt_interval / 1000, (float)crit.rta / 1000, (float)max_completion_time / 1000); + packets, targets, (float)target_interval / 1000, (float)pkt_interval / 1000, (float)crit.rta / 1000, + (float)max_completion_time / 1000); } if (debug) { @@ -997,9 +999,10 @@ static int wait_for_reply(int sock, u_int t) { /* address_family == AF_INET6 ? sizeof(struct icmp6_hdr) : sizeof(struct icmp));*/ - if ((address_family == PF_INET && (ntohs(packet.icp->icmp_id) != pid || packet.icp->icmp_type != ICMP_ECHOREPLY || ntohs(packet.icp->icmp_seq) >= targets * packets)) || - (address_family == PF_INET6 && - (ntohs(packet.icp6->icmp6_id) != pid || packet.icp6->icmp6_type != ICMP6_ECHO_REPLY || ntohs(packet.icp6->icmp6_seq) >= targets * packets))) { + if ((address_family == PF_INET && (ntohs(packet.icp->icmp_id) != pid || packet.icp->icmp_type != ICMP_ECHOREPLY || + ntohs(packet.icp->icmp_seq) >= targets * packets)) || + (address_family == PF_INET6 && (ntohs(packet.icp6->icmp6_id) != pid || packet.icp6->icmp6_type != ICMP6_ECHO_REPLY || + ntohs(packet.icp6->icmp6_seq) >= targets * packets))) { if (debug > 2) printf("not a proper ICMP_ECHOREPLY\n"); handle_random_icmp(buf + hlen, &resp_addr); @@ -1010,14 +1013,14 @@ static int wait_for_reply(int sock, u_int t) { if (address_family == PF_INET) { memcpy(&data, packet.icp->icmp_data, sizeof(data)); if (debug > 2) - printf("ICMP echo-reply of len %lu, id %u, seq %u, cksum 0x%X\n", (unsigned long)sizeof(data), ntohs(packet.icp->icmp_id), ntohs(packet.icp->icmp_seq), - packet.icp->icmp_cksum); + printf("ICMP echo-reply of len %lu, id %u, seq %u, cksum 0x%X\n", (unsigned long)sizeof(data), ntohs(packet.icp->icmp_id), + ntohs(packet.icp->icmp_seq), packet.icp->icmp_cksum); host = table[ntohs(packet.icp->icmp_seq) / packets]; } else { memcpy(&data, &packet.icp6->icmp6_dataun.icmp6_un_data8[4], sizeof(data)); if (debug > 2) - printf("ICMP echo-reply of len %lu, id %u, seq %u, cksum 0x%X\n", (unsigned long)sizeof(data), ntohs(packet.icp6->icmp6_id), ntohs(packet.icp6->icmp6_seq), - packet.icp6->icmp6_cksum); + printf("ICMP echo-reply of len %lu, id %u, seq %u, cksum 0x%X\n", (unsigned long)sizeof(data), ntohs(packet.icp6->icmp6_id), + ntohs(packet.icp6->icmp6_seq), packet.icp6->icmp6_cksum); host = table[ntohs(packet.icp6->icmp6_seq) / packets]; } @@ -1069,12 +1072,13 @@ static int wait_for_reply(int sock, u_int t) { switch (address_family) { case AF_INET: { - printf("%0.3f ms rtt from %s, outgoing ttl: %u, incoming ttl: %u, max: %0.3f, min: %0.3f\n", (float)tdiff / 1000, address, ttl, ip->ip.ip_ttl, - (float)host->rtmax / 1000, (float)host->rtmin / 1000); + printf("%0.3f ms rtt from %s, outgoing ttl: %u, incoming ttl: %u, max: %0.3f, min: %0.3f\n", (float)tdiff / 1000, address, + ttl, ip->ip.ip_ttl, (float)host->rtmax / 1000, (float)host->rtmin / 1000); break; }; case AF_INET6: { - printf("%0.3f ms rtt from %s, outgoing ttl: %u, max: %0.3f, min: %0.3f\n", (float)tdiff / 1000, address, ttl, (float)host->rtmax / 1000, (float)host->rtmin / 1000); + printf("%0.3f ms rtt from %s, outgoing ttl: %u, max: %0.3f, min: %0.3f\n", (float)tdiff / 1000, address, ttl, + (float)host->rtmax / 1000, (float)host->rtmin / 1000); }; } } @@ -1083,7 +1087,8 @@ static int wait_for_reply(int sock, u_int t) { if (mode == MODE_HOSTCHECK) { printf("OK - %s responds to ICMP. Packet %u, rta %0.3fms|" "pkt=%u;;;0;%u rta=%0.3f;%0.3f;%0.3f;;\n", - host->name, icmp_recv, (float)tdiff / 1000, icmp_recv, packets, (float)tdiff / 1000, (float)warn.rta / 1000, (float)crit.rta / 1000); + host->name, icmp_recv, (float)tdiff / 1000, icmp_recv, packets, (float)tdiff / 1000, (float)warn.rta / 1000, + (float)crit.rta / 1000); exit(STATE_OK); } } @@ -1138,8 +1143,8 @@ static int send_icmp_ping(int sock, struct rta_host *host) { icp->icmp_cksum = icmp_checksum((uint16_t *)buf, (size_t)icmp_pkt_size); if (debug > 2) - printf("Sending ICMP echo-request of len %lu, id %u, seq %u, cksum 0x%X to host %s\n", (unsigned long)sizeof(data), ntohs(icp->icmp_id), ntohs(icp->icmp_seq), - icp->icmp_cksum, host->name); + printf("Sending ICMP echo-request of len %lu, id %u, seq %u, cksum 0x%X to host %s\n", (unsigned long)sizeof(data), + ntohs(icp->icmp_id), ntohs(icp->icmp_seq), icp->icmp_cksum, host->name); } else { struct icmp6_hdr *icp6 = (struct icmp6_hdr *)buf; addrlen = sizeof(struct sockaddr_in6); @@ -1154,8 +1159,8 @@ static int send_icmp_ping(int sock, struct rta_host *host) { // let checksum be calculated automatically if (debug > 2) { - printf("Sending ICMP echo-request of len %lu, id %u, seq %u, cksum 0x%X to host %s\n", (unsigned long)sizeof(data), ntohs(icp6->icmp6_id), ntohs(icp6->icmp6_seq), - icp6->icmp6_cksum, host->name); + printf("Sending ICMP echo-request of len %lu, id %u, seq %u, cksum 0x%X to host %s\n", (unsigned long)sizeof(data), + ntohs(icp6->icmp6_id), ntohs(icp6->icmp6_seq), icp6->icmp6_cksum, host->name); } } @@ -1542,11 +1547,13 @@ static void finish(int sig) { if (rta_mode) { if (host->pl < 100) { - printf("%srta=%0.3fms;%0.3f;%0.3f;0; %srtmax=%0.3fms;;;; %srtmin=%0.3fms;;;; ", (targets > 1) ? host->name : "", host->rta / 1000, (float)warn.rta / 1000, - (float)crit.rta / 1000, (targets > 1) ? host->name : "", (float)host->rtmax / 1000, (targets > 1) ? host->name : "", + printf("%srta=%0.3fms;%0.3f;%0.3f;0; %srtmax=%0.3fms;;;; %srtmin=%0.3fms;;;; ", (targets > 1) ? host->name : "", + host->rta / 1000, (float)warn.rta / 1000, (float)crit.rta / 1000, (targets > 1) ? host->name : "", + (float)host->rtmax / 1000, (targets > 1) ? host->name : "", (host->rtmin < INFINITY) ? (float)host->rtmin / 1000 : (float)0); } else { - printf("%srta=U;;;; %srtmax=U;;;; %srtmin=U;;;; ", (targets > 1) ? host->name : "", (targets > 1) ? host->name : "", (targets > 1) ? host->name : ""); + printf("%srta=U;;;; %srtmax=U;;;; %srtmin=U;;;; ", (targets > 1) ? host->name : "", (targets > 1) ? host->name : "", + (targets > 1) ? host->name : ""); } } @@ -1556,12 +1563,13 @@ static void finish(int sig) { if (jitter_mode) { if (host->pl < 100) { - printf("%sjitter_avg=%0.3fms;%0.3f;%0.3f;0; %sjitter_max=%0.3fms;;;; %sjitter_min=%0.3fms;;;; ", (targets > 1) ? host->name : "", (float)host->jitter, - (float)warn.jitter, (float)crit.jitter, (targets > 1) ? host->name : "", (float)host->jitter_max / 1000, (targets > 1) ? host->name : "", + printf("%sjitter_avg=%0.3fms;%0.3f;%0.3f;0; %sjitter_max=%0.3fms;;;; %sjitter_min=%0.3fms;;;; ", + (targets > 1) ? host->name : "", (float)host->jitter, (float)warn.jitter, (float)crit.jitter, + (targets > 1) ? host->name : "", (float)host->jitter_max / 1000, (targets > 1) ? host->name : "", (float)host->jitter_min / 1000); } else { - printf("%sjitter_avg=U;;;; %sjitter_max=U;;;; %sjitter_min=U;;;; ", (targets > 1) ? host->name : "", (targets > 1) ? host->name : "", - (targets > 1) ? host->name : ""); + printf("%sjitter_avg=U;;;; %sjitter_max=U;;;; %sjitter_min=U;;;; ", (targets > 1) ? host->name : "", + (targets > 1) ? host->name : "", (targets > 1) ? host->name : ""); } } @@ -1594,7 +1602,8 @@ static void finish(int sig) { /* finish with an empty line */ puts(""); if (debug) - printf("targets: %u, targets_alive: %u, hosts_ok: %u, hosts_warn: %u, min_hosts_alive: %i\n", targets, targets_alive, hosts_ok, hosts_warn, min_hosts_alive); + printf("targets: %u, targets_alive: %u, hosts_ok: %u, hosts_warn: %u, min_hosts_alive: %i\n", targets, targets_alive, hosts_ok, + hosts_warn, min_hosts_alive); exit(status); } -- cgit v0.10-9-g596f From 880e57271d66b34240b58bdbeaf9d53a08958eb2 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 01:30:50 +0100 Subject: lib: clang-format diff --git a/lib/parse_ini.c b/lib/parse_ini.c index 873ee8c..1289aae 100644 --- a/lib/parse_ini.c +++ b/lib/parse_ini.c @@ -42,16 +42,17 @@ typedef struct { static char *default_ini_file_names[] = {"monitoring-plugins.ini", "plugins.ini", "nagios-plugins.ini", NULL}; -static char *default_ini_path_names[] = {"/usr/local/etc/monitoring-plugins/monitoring-plugins.ini", "/usr/local/etc/monitoring-plugins.ini", - "/etc/monitoring-plugins/monitoring-plugins.ini", "/etc/monitoring-plugins.ini", - /* deprecated path names (for backward compatibility): */ - "/etc/nagios/plugins.ini", "/usr/local/nagios/etc/plugins.ini", "/usr/local/etc/nagios/plugins.ini", "/etc/opt/nagios/plugins.ini", - "/etc/nagios-plugins.ini", "/usr/local/etc/nagios-plugins.ini", "/etc/opt/nagios-plugins.ini", NULL}; +static char *default_ini_path_names[] = { + "/usr/local/etc/monitoring-plugins/monitoring-plugins.ini", "/usr/local/etc/monitoring-plugins.ini", + "/etc/monitoring-plugins/monitoring-plugins.ini", "/etc/monitoring-plugins.ini", + /* deprecated path names (for backward compatibility): */ + "/etc/nagios/plugins.ini", "/usr/local/nagios/etc/plugins.ini", "/usr/local/etc/nagios/plugins.ini", "/etc/opt/nagios/plugins.ini", + "/etc/nagios-plugins.ini", "/usr/local/etc/nagios-plugins.ini", "/etc/opt/nagios-plugins.ini", NULL}; /* eat all characters from a FILE pointer until n is encountered */ -#define GOBBLE_TO(f, c, n) \ - do { \ - (c) = fgetc((f)); \ +#define GOBBLE_TO(f, c, n) \ + do { \ + (c) = fgetc((f)); \ } while ((c) != EOF && (c) != (n)) /* internal function that returns the constructed defaults options */ @@ -146,7 +147,11 @@ static int read_defaults(FILE *f, const char *stanza, np_arg_list **opts) { int c = 0; bool status = false; size_t i, stanza_len; - enum { NOSTANZA, WRONGSTANZA, RIGHTSTANZA } stanzastate = NOSTANZA; + enum { + NOSTANZA, + WRONGSTANZA, + RIGHTSTANZA + } stanzastate = NOSTANZA; stanza_len = strlen(stanza); diff --git a/lib/tests/test_base64.c b/lib/tests/test_base64.c index 48e5ed6..94cb5aa 100644 --- a/lib/tests/test_base64.c +++ b/lib/tests/test_base64.c @@ -180,93 +180,117 @@ int main(int argc, char **argv) { #endif char random[1024] = { - 0x0b, 0x30, 0x44, 0x62, 0x7c, 0x22, 0x1f, 0x0d, 0x05, 0x67, 0x2c, 0x2a, 0x39, 0x21, 0x46, 0x08, 0x50, 0x66, 0x34, 0x37, 0x0b, 0x45, 0x4b, 0x38, 0x32, 0x06, 0x7a, 0x3e, - 0x7f, 0x0c, 0x40, 0x18, 0x6b, 0x2d, 0x60, 0x4c, 0x60, 0x0c, 0x23, 0x43, 0x3b, 0x3e, 0x1b, 0x16, 0x04, 0x46, 0x58, 0x3f, 0x40, 0x6a, 0x11, 0x05, 0x63, 0x71, 0x14, 0x35, - 0x47, 0x79, 0x13, 0x6f, 0x6b, 0x27, 0x18, 0x5b, 0x48, 0x27, 0x3e, 0x6f, 0x15, 0x33, 0x4f, 0x3e, 0x5e, 0x51, 0x73, 0x68, 0x25, 0x0f, 0x06, 0x5b, 0x7c, 0x72, 0x75, 0x3e, - 0x3f, 0x1b, 0x5c, 0x6d, 0x6a, 0x39, 0x7c, 0x63, 0x63, 0x60, 0x6c, 0x7a, 0x33, 0x76, 0x52, 0x13, 0x25, 0x33, 0x7d, 0x65, 0x23, 0x27, 0x11, 0x06, 0x06, 0x47, 0x71, 0x1e, - 0x14, 0x74, 0x63, 0x70, 0x2d, 0x15, 0x27, 0x18, 0x51, 0x06, 0x05, 0x33, 0x11, 0x2c, 0x6b, 0x00, 0x2d, 0x77, 0x20, 0x48, 0x0d, 0x73, 0x51, 0x45, 0x25, 0x7f, 0x7f, 0x35, - 0x26, 0x2e, 0x26, 0x53, 0x24, 0x68, 0x1e, 0x0e, 0x58, 0x3a, 0x59, 0x50, 0x56, 0x37, 0x5f, 0x66, 0x01, 0x4c, 0x5a, 0x64, 0x32, 0x50, 0x7b, 0x6a, 0x20, 0x72, 0x2b, 0x1d, - 0x7e, 0x43, 0x7b, 0x61, 0x42, 0x0b, 0x61, 0x73, 0x24, 0x79, 0x3a, 0x6b, 0x4a, 0x79, 0x6e, 0x09, 0x0f, 0x27, 0x2d, 0x0c, 0x5e, 0x32, 0x4b, 0x0d, 0x79, 0x46, 0x39, 0x21, - 0x0a, 0x26, 0x5f, 0x3a, 0x00, 0x26, 0x3f, 0x13, 0x2e, 0x7e, 0x50, 0x2b, 0x67, 0x46, 0x72, 0x3f, 0x3b, 0x01, 0x46, 0x1b, 0x0b, 0x35, 0x49, 0x39, 0x19, 0x70, 0x3d, 0x02, - 0x41, 0x0e, 0x38, 0x05, 0x76, 0x65, 0x4f, 0x31, 0x6c, 0x5e, 0x17, 0x04, 0x15, 0x36, 0x26, 0x64, 0x34, 0x14, 0x17, 0x7c, 0x0e, 0x0b, 0x5b, 0x55, 0x53, 0x6b, 0x00, 0x42, - 0x41, 0x4f, 0x02, 0x5c, 0x13, 0x0a, 0x2c, 0x2c, 0x3e, 0x10, 0x14, 0x33, 0x45, 0x7c, 0x7a, 0x5a, 0x31, 0x61, 0x39, 0x08, 0x22, 0x6a, 0x1e, 0x0f, 0x6f, 0x1b, 0x6c, 0x13, - 0x5e, 0x79, 0x20, 0x79, 0x50, 0x62, 0x06, 0x2c, 0x76, 0x17, 0x04, 0x2b, 0x2a, 0x75, 0x1f, 0x0c, 0x37, 0x4e, 0x0f, 0x7b, 0x2d, 0x34, 0x75, 0x60, 0x31, 0x74, 0x2e, 0x0a, - 0x4a, 0x11, 0x6c, 0x49, 0x25, 0x01, 0x3a, 0x3d, 0x22, 0x1e, 0x6d, 0x18, 0x51, 0x78, 0x2d, 0x62, 0x31, 0x4c, 0x50, 0x40, 0x17, 0x4b, 0x6f, 0x22, 0x00, 0x7f, 0x61, 0x2a, - 0x34, 0x3e, 0x00, 0x5f, 0x2f, 0x5f, 0x2f, 0x14, 0x2a, 0x55, 0x27, 0x1f, 0x46, 0x1f, 0x12, 0x46, 0x5e, 0x1e, 0x0c, 0x7c, 0x38, 0x01, 0x61, 0x64, 0x76, 0x22, 0x6e, 0x08, - 0x20, 0x38, 0x4f, 0x73, 0x72, 0x55, 0x12, 0x42, 0x19, 0x50, 0x61, 0x43, 0x77, 0x7d, 0x41, 0x2e, 0x35, 0x4f, 0x3d, 0x31, 0x28, 0x58, 0x67, 0x1b, 0x03, 0x51, 0x20, 0x32, - 0x1c, 0x08, 0x6e, 0x37, 0x75, 0x37, 0x44, 0x4f, 0x68, 0x19, 0x07, 0x64, 0x14, 0x28, 0x25, 0x2b, 0x69, 0x35, 0x18, 0x27, 0x26, 0x14, 0x13, 0x70, 0x42, 0x19, 0x12, 0x75, - 0x3e, 0x02, 0x5d, 0x7c, 0x13, 0x1f, 0x16, 0x53, 0x3b, 0x74, 0x48, 0x3c, 0x5e, 0x39, 0x6c, 0x1c, 0x1c, 0x74, 0x39, 0x1f, 0x00, 0x1b, 0x06, 0x0a, 0x68, 0x3b, 0x52, 0x4f, - 0x1e, 0x6e, 0x3c, 0x35, 0x0c, 0x38, 0x0e, 0x0b, 0x3b, 0x1a, 0x76, 0x23, 0x29, 0x53, 0x1e, 0x5f, 0x41, 0x0c, 0x4b, 0x0a, 0x65, 0x28, 0x78, 0x67, 0x48, 0x59, 0x26, 0x6d, - 0x31, 0x76, 0x23, 0x70, 0x61, 0x64, 0x3b, 0x38, 0x79, 0x66, 0x74, 0x53, 0x2c, 0x64, 0x64, 0x54, 0x03, 0x54, 0x65, 0x44, 0x4c, 0x18, 0x4f, 0x48, 0x20, 0x4f, 0x72, 0x10, - 0x3f, 0x0c, 0x52, 0x2d, 0x03, 0x14, 0x03, 0x51, 0x42, 0x10, 0x77, 0x6a, 0x34, 0x06, 0x32, 0x03, 0x72, 0x14, 0x7c, 0x08, 0x5d, 0x52, 0x1a, 0x62, 0x7c, 0x3e, 0x30, 0x7e, - 0x5f, 0x7f, 0x54, 0x0f, 0x44, 0x49, 0x5d, 0x5e, 0x10, 0x6a, 0x06, 0x2b, 0x06, 0x53, 0x10, 0x39, 0x37, 0x32, 0x4a, 0x4e, 0x3d, 0x2b, 0x65, 0x38, 0x39, 0x07, 0x72, 0x54, - 0x64, 0x4d, 0x56, 0x6a, 0x03, 0x22, 0x70, 0x7b, 0x5f, 0x60, 0x0b, 0x2a, 0x0b, 0x6b, 0x10, 0x64, 0x14, 0x05, 0x22, 0x00, 0x73, 0x40, 0x23, 0x5b, 0x51, 0x1f, 0x2b, 0x1a, - 0x5d, 0x69, 0x7a, 0x46, 0x0c, 0x5f, 0x32, 0x4b, 0x4a, 0x28, 0x52, 0x79, 0x5b, 0x12, 0x42, 0x18, 0x00, 0x5d, 0x27, 0x31, 0x53, 0x3c, 0x4c, 0x36, 0x4e, 0x38, 0x3f, 0x72, - 0x03, 0x71, 0x02, 0x5b, 0x36, 0x59, 0x7f, 0x75, 0x6e, 0x08, 0x54, 0x0d, 0x34, 0x1c, 0x34, 0x57, 0x5d, 0x69, 0x48, 0x00, 0x3b, 0x05, 0x07, 0x6e, 0x27, 0x65, 0x6e, 0x40, - 0x3d, 0x3a, 0x4f, 0x72, 0x5d, 0x39, 0x16, 0x0f, 0x63, 0x12, 0x12, 0x15, 0x3a, 0x70, 0x0d, 0x57, 0x18, 0x0d, 0x5e, 0x3d, 0x22, 0x68, 0x68, 0x7c, 0x6d, 0x4f, 0x0c, 0x7b, - 0x09, 0x2d, 0x4a, 0x73, 0x20, 0x47, 0x07, 0x57, 0x75, 0x5d, 0x53, 0x70, 0x34, 0x21, 0x40, 0x57, 0x51, 0x5e, 0x49, 0x44, 0x00, 0x54, 0x27, 0x04, 0x68, 0x7e, 0x59, 0x56, - 0x58, 0x74, 0x14, 0x3c, 0x16, 0x33, 0x41, 0x16, 0x4b, 0x2f, 0x49, 0x37, 0x0a, 0x54, 0x08, 0x08, 0x1f, 0x39, 0x67, 0x76, 0x28, 0x28, 0x07, 0x1d, 0x61, 0x47, 0x51, 0x4d, - 0x75, 0x26, 0x52, 0x47, 0x47, 0x0c, 0x57, 0x58, 0x74, 0x3e, 0x62, 0x6c, 0x58, 0x3a, 0x44, 0x1e, 0x16, 0x2e, 0x21, 0x1c, 0x73, 0x45, 0x67, 0x74, 0x4f, 0x33, 0x66, 0x0e, - 0x74, 0x66, 0x26, 0x1f, 0x2e, 0x38, 0x44, 0x40, 0x7e, 0x2a, 0x50, 0x52, 0x5e, 0x43, 0x01, 0x7a, 0x38, 0x49, 0x3c, 0x55, 0x4d, 0x5a, 0x44, 0x08, 0x26, 0x59, 0x4d, 0x45, - 0x0b, 0x48, 0x0a, 0x33, 0x5e, 0x4a, 0x4d, 0x75, 0x16, 0x17, 0x63, 0x46, 0x01, 0x2a, 0x55, 0x7b, 0x0f, 0x02, 0x73, 0x6a, 0x4b, 0x7f, 0x75, 0x65, 0x3c, 0x4c, 0x33, 0x39, - 0x6c, 0x74, 0x05, 0x60, 0x0f, 0x7f, 0x2d, 0x41, 0x4d, 0x4d, 0x46, 0x71, 0x09, 0x6f, 0x4f, 0x60, 0x15, 0x0f, 0x46, 0x73, 0x63, 0x4c, 0x5e, 0x74, 0x30, 0x0d, 0x28, 0x43, - 0x08, 0x72, 0x32, 0x04, 0x2e, 0x31, 0x29, 0x27, 0x44, 0x6d, 0x13, 0x17, 0x48, 0x0f, 0x49, 0x52, 0x10, 0x13, 0x7f, 0x17, 0x16, 0x62, 0x79, 0x35, 0x78, 0x3e, 0x01, 0x7c, - 0x2e, 0x0f, 0x76, 0x3e, 0x5e, 0x53, 0x6c, 0x5b, 0x5f, 0x7c, 0x19, 0x41, 0x02, 0x2f, 0x17, 0x64, 0x41, 0x75, 0x10, 0x04, 0x47, 0x7c, 0x3d, 0x4b, 0x52, 0x00, 0x10, 0x5d, - 0x51, 0x4e, 0x7a, 0x27, 0x25, 0x55, 0x40, 0x12, 0x35, 0x60, 0x05, 0x1b, 0x34, 0x2d, 0x04, 0x7a, 0x6a, 0x69, 0x02, 0x79, 0x03, 0x3a, 0x2f, 0x06, 0x0a, 0x79, 0x7b, 0x12, - 0x5d, 0x7c, 0x52, 0x29, 0x47, 0x58, 0x12, 0x73, 0x3f, 0x27, 0x56, 0x05, 0x0c, 0x48, 0x32, 0x58, 0x6b, 0x57, 0x5c, 0x03, 0x64, 0x56, 0x11, 0x52, 0x7a, 0x30, 0x36, 0x29, - 0x17, 0x3b, 0x68, 0x7a, 0x7c, 0x05, 0x6b, 0x6b, 0x13, 0x6a, 0x24, 0x5c, 0x68, 0x42, 0x18, 0x32, 0x03, 0x73, 0x6e, 0x04, 0x21, 0x2e, 0x01, 0x04, 0x63, 0x7d, 0x44, 0x41, - 0x12, 0x31, 0x0b, 0x15, 0x1f, 0x70, 0x00, 0x2e, 0x66, 0x14, 0x3c, 0x7f, 0x2b, 0x00, 0x1f, 0x0c, 0x28, 0x59, 0x0a, 0x16, 0x49, 0x5a, 0x5c, 0x64, 0x65, 0x4b, 0x11, 0x29, - 0x15, 0x36, 0x5a, 0x65, 0x19, 0x4f, 0x60, 0x23, 0x3a, 0x3a, 0x13, 0x25, 0x02, 0x78, 0x4c, 0x54}; + 0x0b, 0x30, 0x44, 0x62, 0x7c, 0x22, 0x1f, 0x0d, 0x05, 0x67, 0x2c, 0x2a, 0x39, 0x21, 0x46, 0x08, 0x50, 0x66, 0x34, 0x37, 0x0b, 0x45, + 0x4b, 0x38, 0x32, 0x06, 0x7a, 0x3e, 0x7f, 0x0c, 0x40, 0x18, 0x6b, 0x2d, 0x60, 0x4c, 0x60, 0x0c, 0x23, 0x43, 0x3b, 0x3e, 0x1b, 0x16, + 0x04, 0x46, 0x58, 0x3f, 0x40, 0x6a, 0x11, 0x05, 0x63, 0x71, 0x14, 0x35, 0x47, 0x79, 0x13, 0x6f, 0x6b, 0x27, 0x18, 0x5b, 0x48, 0x27, + 0x3e, 0x6f, 0x15, 0x33, 0x4f, 0x3e, 0x5e, 0x51, 0x73, 0x68, 0x25, 0x0f, 0x06, 0x5b, 0x7c, 0x72, 0x75, 0x3e, 0x3f, 0x1b, 0x5c, 0x6d, + 0x6a, 0x39, 0x7c, 0x63, 0x63, 0x60, 0x6c, 0x7a, 0x33, 0x76, 0x52, 0x13, 0x25, 0x33, 0x7d, 0x65, 0x23, 0x27, 0x11, 0x06, 0x06, 0x47, + 0x71, 0x1e, 0x14, 0x74, 0x63, 0x70, 0x2d, 0x15, 0x27, 0x18, 0x51, 0x06, 0x05, 0x33, 0x11, 0x2c, 0x6b, 0x00, 0x2d, 0x77, 0x20, 0x48, + 0x0d, 0x73, 0x51, 0x45, 0x25, 0x7f, 0x7f, 0x35, 0x26, 0x2e, 0x26, 0x53, 0x24, 0x68, 0x1e, 0x0e, 0x58, 0x3a, 0x59, 0x50, 0x56, 0x37, + 0x5f, 0x66, 0x01, 0x4c, 0x5a, 0x64, 0x32, 0x50, 0x7b, 0x6a, 0x20, 0x72, 0x2b, 0x1d, 0x7e, 0x43, 0x7b, 0x61, 0x42, 0x0b, 0x61, 0x73, + 0x24, 0x79, 0x3a, 0x6b, 0x4a, 0x79, 0x6e, 0x09, 0x0f, 0x27, 0x2d, 0x0c, 0x5e, 0x32, 0x4b, 0x0d, 0x79, 0x46, 0x39, 0x21, 0x0a, 0x26, + 0x5f, 0x3a, 0x00, 0x26, 0x3f, 0x13, 0x2e, 0x7e, 0x50, 0x2b, 0x67, 0x46, 0x72, 0x3f, 0x3b, 0x01, 0x46, 0x1b, 0x0b, 0x35, 0x49, 0x39, + 0x19, 0x70, 0x3d, 0x02, 0x41, 0x0e, 0x38, 0x05, 0x76, 0x65, 0x4f, 0x31, 0x6c, 0x5e, 0x17, 0x04, 0x15, 0x36, 0x26, 0x64, 0x34, 0x14, + 0x17, 0x7c, 0x0e, 0x0b, 0x5b, 0x55, 0x53, 0x6b, 0x00, 0x42, 0x41, 0x4f, 0x02, 0x5c, 0x13, 0x0a, 0x2c, 0x2c, 0x3e, 0x10, 0x14, 0x33, + 0x45, 0x7c, 0x7a, 0x5a, 0x31, 0x61, 0x39, 0x08, 0x22, 0x6a, 0x1e, 0x0f, 0x6f, 0x1b, 0x6c, 0x13, 0x5e, 0x79, 0x20, 0x79, 0x50, 0x62, + 0x06, 0x2c, 0x76, 0x17, 0x04, 0x2b, 0x2a, 0x75, 0x1f, 0x0c, 0x37, 0x4e, 0x0f, 0x7b, 0x2d, 0x34, 0x75, 0x60, 0x31, 0x74, 0x2e, 0x0a, + 0x4a, 0x11, 0x6c, 0x49, 0x25, 0x01, 0x3a, 0x3d, 0x22, 0x1e, 0x6d, 0x18, 0x51, 0x78, 0x2d, 0x62, 0x31, 0x4c, 0x50, 0x40, 0x17, 0x4b, + 0x6f, 0x22, 0x00, 0x7f, 0x61, 0x2a, 0x34, 0x3e, 0x00, 0x5f, 0x2f, 0x5f, 0x2f, 0x14, 0x2a, 0x55, 0x27, 0x1f, 0x46, 0x1f, 0x12, 0x46, + 0x5e, 0x1e, 0x0c, 0x7c, 0x38, 0x01, 0x61, 0x64, 0x76, 0x22, 0x6e, 0x08, 0x20, 0x38, 0x4f, 0x73, 0x72, 0x55, 0x12, 0x42, 0x19, 0x50, + 0x61, 0x43, 0x77, 0x7d, 0x41, 0x2e, 0x35, 0x4f, 0x3d, 0x31, 0x28, 0x58, 0x67, 0x1b, 0x03, 0x51, 0x20, 0x32, 0x1c, 0x08, 0x6e, 0x37, + 0x75, 0x37, 0x44, 0x4f, 0x68, 0x19, 0x07, 0x64, 0x14, 0x28, 0x25, 0x2b, 0x69, 0x35, 0x18, 0x27, 0x26, 0x14, 0x13, 0x70, 0x42, 0x19, + 0x12, 0x75, 0x3e, 0x02, 0x5d, 0x7c, 0x13, 0x1f, 0x16, 0x53, 0x3b, 0x74, 0x48, 0x3c, 0x5e, 0x39, 0x6c, 0x1c, 0x1c, 0x74, 0x39, 0x1f, + 0x00, 0x1b, 0x06, 0x0a, 0x68, 0x3b, 0x52, 0x4f, 0x1e, 0x6e, 0x3c, 0x35, 0x0c, 0x38, 0x0e, 0x0b, 0x3b, 0x1a, 0x76, 0x23, 0x29, 0x53, + 0x1e, 0x5f, 0x41, 0x0c, 0x4b, 0x0a, 0x65, 0x28, 0x78, 0x67, 0x48, 0x59, 0x26, 0x6d, 0x31, 0x76, 0x23, 0x70, 0x61, 0x64, 0x3b, 0x38, + 0x79, 0x66, 0x74, 0x53, 0x2c, 0x64, 0x64, 0x54, 0x03, 0x54, 0x65, 0x44, 0x4c, 0x18, 0x4f, 0x48, 0x20, 0x4f, 0x72, 0x10, 0x3f, 0x0c, + 0x52, 0x2d, 0x03, 0x14, 0x03, 0x51, 0x42, 0x10, 0x77, 0x6a, 0x34, 0x06, 0x32, 0x03, 0x72, 0x14, 0x7c, 0x08, 0x5d, 0x52, 0x1a, 0x62, + 0x7c, 0x3e, 0x30, 0x7e, 0x5f, 0x7f, 0x54, 0x0f, 0x44, 0x49, 0x5d, 0x5e, 0x10, 0x6a, 0x06, 0x2b, 0x06, 0x53, 0x10, 0x39, 0x37, 0x32, + 0x4a, 0x4e, 0x3d, 0x2b, 0x65, 0x38, 0x39, 0x07, 0x72, 0x54, 0x64, 0x4d, 0x56, 0x6a, 0x03, 0x22, 0x70, 0x7b, 0x5f, 0x60, 0x0b, 0x2a, + 0x0b, 0x6b, 0x10, 0x64, 0x14, 0x05, 0x22, 0x00, 0x73, 0x40, 0x23, 0x5b, 0x51, 0x1f, 0x2b, 0x1a, 0x5d, 0x69, 0x7a, 0x46, 0x0c, 0x5f, + 0x32, 0x4b, 0x4a, 0x28, 0x52, 0x79, 0x5b, 0x12, 0x42, 0x18, 0x00, 0x5d, 0x27, 0x31, 0x53, 0x3c, 0x4c, 0x36, 0x4e, 0x38, 0x3f, 0x72, + 0x03, 0x71, 0x02, 0x5b, 0x36, 0x59, 0x7f, 0x75, 0x6e, 0x08, 0x54, 0x0d, 0x34, 0x1c, 0x34, 0x57, 0x5d, 0x69, 0x48, 0x00, 0x3b, 0x05, + 0x07, 0x6e, 0x27, 0x65, 0x6e, 0x40, 0x3d, 0x3a, 0x4f, 0x72, 0x5d, 0x39, 0x16, 0x0f, 0x63, 0x12, 0x12, 0x15, 0x3a, 0x70, 0x0d, 0x57, + 0x18, 0x0d, 0x5e, 0x3d, 0x22, 0x68, 0x68, 0x7c, 0x6d, 0x4f, 0x0c, 0x7b, 0x09, 0x2d, 0x4a, 0x73, 0x20, 0x47, 0x07, 0x57, 0x75, 0x5d, + 0x53, 0x70, 0x34, 0x21, 0x40, 0x57, 0x51, 0x5e, 0x49, 0x44, 0x00, 0x54, 0x27, 0x04, 0x68, 0x7e, 0x59, 0x56, 0x58, 0x74, 0x14, 0x3c, + 0x16, 0x33, 0x41, 0x16, 0x4b, 0x2f, 0x49, 0x37, 0x0a, 0x54, 0x08, 0x08, 0x1f, 0x39, 0x67, 0x76, 0x28, 0x28, 0x07, 0x1d, 0x61, 0x47, + 0x51, 0x4d, 0x75, 0x26, 0x52, 0x47, 0x47, 0x0c, 0x57, 0x58, 0x74, 0x3e, 0x62, 0x6c, 0x58, 0x3a, 0x44, 0x1e, 0x16, 0x2e, 0x21, 0x1c, + 0x73, 0x45, 0x67, 0x74, 0x4f, 0x33, 0x66, 0x0e, 0x74, 0x66, 0x26, 0x1f, 0x2e, 0x38, 0x44, 0x40, 0x7e, 0x2a, 0x50, 0x52, 0x5e, 0x43, + 0x01, 0x7a, 0x38, 0x49, 0x3c, 0x55, 0x4d, 0x5a, 0x44, 0x08, 0x26, 0x59, 0x4d, 0x45, 0x0b, 0x48, 0x0a, 0x33, 0x5e, 0x4a, 0x4d, 0x75, + 0x16, 0x17, 0x63, 0x46, 0x01, 0x2a, 0x55, 0x7b, 0x0f, 0x02, 0x73, 0x6a, 0x4b, 0x7f, 0x75, 0x65, 0x3c, 0x4c, 0x33, 0x39, 0x6c, 0x74, + 0x05, 0x60, 0x0f, 0x7f, 0x2d, 0x41, 0x4d, 0x4d, 0x46, 0x71, 0x09, 0x6f, 0x4f, 0x60, 0x15, 0x0f, 0x46, 0x73, 0x63, 0x4c, 0x5e, 0x74, + 0x30, 0x0d, 0x28, 0x43, 0x08, 0x72, 0x32, 0x04, 0x2e, 0x31, 0x29, 0x27, 0x44, 0x6d, 0x13, 0x17, 0x48, 0x0f, 0x49, 0x52, 0x10, 0x13, + 0x7f, 0x17, 0x16, 0x62, 0x79, 0x35, 0x78, 0x3e, 0x01, 0x7c, 0x2e, 0x0f, 0x76, 0x3e, 0x5e, 0x53, 0x6c, 0x5b, 0x5f, 0x7c, 0x19, 0x41, + 0x02, 0x2f, 0x17, 0x64, 0x41, 0x75, 0x10, 0x04, 0x47, 0x7c, 0x3d, 0x4b, 0x52, 0x00, 0x10, 0x5d, 0x51, 0x4e, 0x7a, 0x27, 0x25, 0x55, + 0x40, 0x12, 0x35, 0x60, 0x05, 0x1b, 0x34, 0x2d, 0x04, 0x7a, 0x6a, 0x69, 0x02, 0x79, 0x03, 0x3a, 0x2f, 0x06, 0x0a, 0x79, 0x7b, 0x12, + 0x5d, 0x7c, 0x52, 0x29, 0x47, 0x58, 0x12, 0x73, 0x3f, 0x27, 0x56, 0x05, 0x0c, 0x48, 0x32, 0x58, 0x6b, 0x57, 0x5c, 0x03, 0x64, 0x56, + 0x11, 0x52, 0x7a, 0x30, 0x36, 0x29, 0x17, 0x3b, 0x68, 0x7a, 0x7c, 0x05, 0x6b, 0x6b, 0x13, 0x6a, 0x24, 0x5c, 0x68, 0x42, 0x18, 0x32, + 0x03, 0x73, 0x6e, 0x04, 0x21, 0x2e, 0x01, 0x04, 0x63, 0x7d, 0x44, 0x41, 0x12, 0x31, 0x0b, 0x15, 0x1f, 0x70, 0x00, 0x2e, 0x66, 0x14, + 0x3c, 0x7f, 0x2b, 0x00, 0x1f, 0x0c, 0x28, 0x59, 0x0a, 0x16, 0x49, 0x5a, 0x5c, 0x64, 0x65, 0x4b, 0x11, 0x29, 0x15, 0x36, 0x5a, 0x65, + 0x19, 0x4f, 0x60, 0x23, 0x3a, 0x3a, 0x13, 0x25, 0x02, 0x78, 0x4c, 0x54}; char b64_known[1369] = { - 0x43, 0x7a, 0x42, 0x45, 0x59, 0x6e, 0x77, 0x69, 0x48, 0x77, 0x30, 0x46, 0x5a, 0x79, 0x77, 0x71, 0x4f, 0x53, 0x46, 0x47, 0x43, 0x46, 0x42, 0x6d, 0x4e, 0x44, 0x63, 0x4c, - 0x52, 0x55, 0x73, 0x34, 0x4d, 0x67, 0x5a, 0x36, 0x50, 0x6e, 0x38, 0x4d, 0x51, 0x42, 0x68, 0x72, 0x4c, 0x57, 0x42, 0x4d, 0x59, 0x41, 0x77, 0x6a, 0x51, 0x7a, 0x73, 0x2b, - 0x47, 0x78, 0x59, 0x45, 0x52, 0x6c, 0x67, 0x2f, 0x51, 0x47, 0x6f, 0x52, 0x42, 0x57, 0x4e, 0x78, 0x46, 0x44, 0x56, 0x48, 0x65, 0x52, 0x4e, 0x76, 0x61, 0x79, 0x63, 0x59, - 0x57, 0x30, 0x67, 0x6e, 0x50, 0x6d, 0x38, 0x56, 0x4d, 0x30, 0x38, 0x2b, 0x58, 0x6c, 0x46, 0x7a, 0x61, 0x43, 0x55, 0x50, 0x42, 0x6c, 0x74, 0x38, 0x63, 0x6e, 0x55, 0x2b, - 0x50, 0x78, 0x74, 0x63, 0x62, 0x57, 0x6f, 0x35, 0x66, 0x47, 0x4e, 0x6a, 0x59, 0x47, 0x78, 0x36, 0x4d, 0x33, 0x5a, 0x53, 0x45, 0x79, 0x55, 0x7a, 0x66, 0x57, 0x55, 0x6a, - 0x4a, 0x78, 0x45, 0x47, 0x42, 0x6b, 0x64, 0x78, 0x48, 0x68, 0x52, 0x30, 0x59, 0x33, 0x41, 0x74, 0x46, 0x53, 0x63, 0x59, 0x55, 0x51, 0x59, 0x46, 0x4d, 0x78, 0x45, 0x73, - 0x61, 0x77, 0x41, 0x74, 0x64, 0x79, 0x42, 0x49, 0x44, 0x58, 0x4e, 0x52, 0x52, 0x53, 0x56, 0x2f, 0x66, 0x7a, 0x55, 0x6d, 0x4c, 0x69, 0x5a, 0x54, 0x4a, 0x47, 0x67, 0x65, - 0x44, 0x6c, 0x67, 0x36, 0x57, 0x56, 0x42, 0x57, 0x4e, 0x31, 0x39, 0x6d, 0x41, 0x55, 0x78, 0x61, 0x5a, 0x44, 0x4a, 0x51, 0x65, 0x32, 0x6f, 0x67, 0x63, 0x69, 0x73, 0x64, - 0x66, 0x6b, 0x4e, 0x37, 0x59, 0x55, 0x49, 0x4c, 0x59, 0x58, 0x4d, 0x6b, 0x65, 0x54, 0x70, 0x72, 0x53, 0x6e, 0x6c, 0x75, 0x43, 0x51, 0x38, 0x6e, 0x4c, 0x51, 0x78, 0x65, - 0x4d, 0x6b, 0x73, 0x4e, 0x65, 0x55, 0x59, 0x35, 0x49, 0x51, 0x6f, 0x6d, 0x58, 0x7a, 0x6f, 0x41, 0x4a, 0x6a, 0x38, 0x54, 0x4c, 0x6e, 0x35, 0x51, 0x4b, 0x32, 0x64, 0x47, - 0x63, 0x6a, 0x38, 0x37, 0x41, 0x55, 0x59, 0x62, 0x43, 0x7a, 0x56, 0x4a, 0x4f, 0x52, 0x6c, 0x77, 0x50, 0x51, 0x4a, 0x42, 0x44, 0x6a, 0x67, 0x46, 0x64, 0x6d, 0x56, 0x50, - 0x4d, 0x57, 0x78, 0x65, 0x46, 0x77, 0x51, 0x56, 0x4e, 0x69, 0x5a, 0x6b, 0x4e, 0x42, 0x51, 0x58, 0x66, 0x41, 0x34, 0x4c, 0x57, 0x31, 0x56, 0x54, 0x61, 0x77, 0x42, 0x43, - 0x51, 0x55, 0x38, 0x43, 0x58, 0x42, 0x4d, 0x4b, 0x4c, 0x43, 0x77, 0x2b, 0x45, 0x42, 0x51, 0x7a, 0x52, 0x58, 0x78, 0x36, 0x57, 0x6a, 0x46, 0x68, 0x4f, 0x51, 0x67, 0x69, - 0x61, 0x68, 0x34, 0x50, 0x62, 0x78, 0x74, 0x73, 0x45, 0x31, 0x35, 0x35, 0x49, 0x48, 0x6c, 0x51, 0x59, 0x67, 0x59, 0x73, 0x64, 0x68, 0x63, 0x45, 0x4b, 0x79, 0x70, 0x31, - 0x48, 0x77, 0x77, 0x33, 0x54, 0x67, 0x39, 0x37, 0x4c, 0x54, 0x52, 0x31, 0x59, 0x44, 0x46, 0x30, 0x4c, 0x67, 0x70, 0x4b, 0x45, 0x57, 0x78, 0x4a, 0x4a, 0x51, 0x45, 0x36, - 0x50, 0x53, 0x49, 0x65, 0x62, 0x52, 0x68, 0x52, 0x65, 0x43, 0x31, 0x69, 0x4d, 0x55, 0x78, 0x51, 0x51, 0x42, 0x64, 0x4c, 0x62, 0x79, 0x49, 0x41, 0x66, 0x32, 0x45, 0x71, - 0x4e, 0x44, 0x34, 0x41, 0x58, 0x79, 0x39, 0x66, 0x4c, 0x78, 0x51, 0x71, 0x56, 0x53, 0x63, 0x66, 0x52, 0x68, 0x38, 0x53, 0x52, 0x6c, 0x34, 0x65, 0x44, 0x48, 0x77, 0x34, - 0x41, 0x57, 0x46, 0x6b, 0x64, 0x69, 0x4a, 0x75, 0x43, 0x43, 0x41, 0x34, 0x54, 0x33, 0x4e, 0x79, 0x56, 0x52, 0x4a, 0x43, 0x47, 0x56, 0x42, 0x68, 0x51, 0x33, 0x64, 0x39, - 0x51, 0x53, 0x34, 0x31, 0x54, 0x7a, 0x30, 0x78, 0x4b, 0x46, 0x68, 0x6e, 0x47, 0x77, 0x4e, 0x52, 0x49, 0x44, 0x49, 0x63, 0x43, 0x47, 0x34, 0x33, 0x64, 0x54, 0x64, 0x45, - 0x54, 0x32, 0x67, 0x5a, 0x42, 0x32, 0x51, 0x55, 0x4b, 0x43, 0x55, 0x72, 0x61, 0x54, 0x55, 0x59, 0x4a, 0x79, 0x59, 0x55, 0x45, 0x33, 0x42, 0x43, 0x47, 0x52, 0x4a, 0x31, - 0x50, 0x67, 0x4a, 0x64, 0x66, 0x42, 0x4d, 0x66, 0x46, 0x6c, 0x4d, 0x37, 0x64, 0x45, 0x67, 0x38, 0x58, 0x6a, 0x6c, 0x73, 0x48, 0x42, 0x78, 0x30, 0x4f, 0x52, 0x38, 0x41, - 0x47, 0x77, 0x59, 0x4b, 0x61, 0x44, 0x74, 0x53, 0x54, 0x78, 0x35, 0x75, 0x50, 0x44, 0x55, 0x4d, 0x4f, 0x41, 0x34, 0x4c, 0x4f, 0x78, 0x70, 0x32, 0x49, 0x79, 0x6c, 0x54, - 0x48, 0x6c, 0x39, 0x42, 0x44, 0x45, 0x73, 0x4b, 0x5a, 0x53, 0x68, 0x34, 0x5a, 0x30, 0x68, 0x5a, 0x4a, 0x6d, 0x30, 0x78, 0x64, 0x69, 0x4e, 0x77, 0x59, 0x57, 0x51, 0x37, - 0x4f, 0x48, 0x6c, 0x6d, 0x64, 0x46, 0x4d, 0x73, 0x5a, 0x47, 0x52, 0x55, 0x41, 0x31, 0x52, 0x6c, 0x52, 0x45, 0x77, 0x59, 0x54, 0x30, 0x67, 0x67, 0x54, 0x33, 0x49, 0x51, - 0x50, 0x77, 0x78, 0x53, 0x4c, 0x51, 0x4d, 0x55, 0x41, 0x31, 0x46, 0x43, 0x45, 0x48, 0x64, 0x71, 0x4e, 0x41, 0x59, 0x79, 0x41, 0x33, 0x49, 0x55, 0x66, 0x41, 0x68, 0x64, - 0x55, 0x68, 0x70, 0x69, 0x66, 0x44, 0x34, 0x77, 0x66, 0x6c, 0x39, 0x2f, 0x56, 0x41, 0x39, 0x45, 0x53, 0x56, 0x31, 0x65, 0x45, 0x47, 0x6f, 0x47, 0x4b, 0x77, 0x5a, 0x54, - 0x45, 0x44, 0x6b, 0x33, 0x4d, 0x6b, 0x70, 0x4f, 0x50, 0x53, 0x74, 0x6c, 0x4f, 0x44, 0x6b, 0x48, 0x63, 0x6c, 0x52, 0x6b, 0x54, 0x56, 0x5a, 0x71, 0x41, 0x79, 0x4a, 0x77, - 0x65, 0x31, 0x39, 0x67, 0x43, 0x79, 0x6f, 0x4c, 0x61, 0x78, 0x42, 0x6b, 0x46, 0x41, 0x55, 0x69, 0x41, 0x48, 0x4e, 0x41, 0x49, 0x31, 0x74, 0x52, 0x48, 0x79, 0x73, 0x61, - 0x58, 0x57, 0x6c, 0x36, 0x52, 0x67, 0x78, 0x66, 0x4d, 0x6b, 0x74, 0x4b, 0x4b, 0x46, 0x4a, 0x35, 0x57, 0x78, 0x4a, 0x43, 0x47, 0x41, 0x42, 0x64, 0x4a, 0x7a, 0x46, 0x54, - 0x50, 0x45, 0x77, 0x32, 0x54, 0x6a, 0x67, 0x2f, 0x63, 0x67, 0x4e, 0x78, 0x41, 0x6c, 0x73, 0x32, 0x57, 0x58, 0x39, 0x31, 0x62, 0x67, 0x68, 0x55, 0x44, 0x54, 0x51, 0x63, - 0x4e, 0x46, 0x64, 0x64, 0x61, 0x55, 0x67, 0x41, 0x4f, 0x77, 0x55, 0x48, 0x62, 0x69, 0x64, 0x6c, 0x62, 0x6b, 0x41, 0x39, 0x4f, 0x6b, 0x39, 0x79, 0x58, 0x54, 0x6b, 0x57, - 0x44, 0x32, 0x4d, 0x53, 0x45, 0x68, 0x55, 0x36, 0x63, 0x41, 0x31, 0x58, 0x47, 0x41, 0x31, 0x65, 0x50, 0x53, 0x4a, 0x6f, 0x61, 0x48, 0x78, 0x74, 0x54, 0x77, 0x78, 0x37, - 0x43, 0x53, 0x31, 0x4b, 0x63, 0x79, 0x42, 0x48, 0x42, 0x31, 0x64, 0x31, 0x58, 0x56, 0x4e, 0x77, 0x4e, 0x43, 0x46, 0x41, 0x56, 0x31, 0x46, 0x65, 0x53, 0x55, 0x51, 0x41, - 0x56, 0x43, 0x63, 0x45, 0x61, 0x48, 0x35, 0x5a, 0x56, 0x6c, 0x68, 0x30, 0x46, 0x44, 0x77, 0x57, 0x4d, 0x30, 0x45, 0x57, 0x53, 0x79, 0x39, 0x4a, 0x4e, 0x77, 0x70, 0x55, - 0x43, 0x41, 0x67, 0x66, 0x4f, 0x57, 0x64, 0x32, 0x4b, 0x43, 0x67, 0x48, 0x48, 0x57, 0x46, 0x48, 0x55, 0x55, 0x31, 0x31, 0x4a, 0x6c, 0x4a, 0x48, 0x52, 0x77, 0x78, 0x58, - 0x57, 0x48, 0x51, 0x2b, 0x59, 0x6d, 0x78, 0x59, 0x4f, 0x6b, 0x51, 0x65, 0x46, 0x69, 0x34, 0x68, 0x48, 0x48, 0x4e, 0x46, 0x5a, 0x33, 0x52, 0x50, 0x4d, 0x32, 0x59, 0x4f, - 0x64, 0x47, 0x59, 0x6d, 0x48, 0x79, 0x34, 0x34, 0x52, 0x45, 0x42, 0x2b, 0x4b, 0x6c, 0x42, 0x53, 0x58, 0x6b, 0x4d, 0x42, 0x65, 0x6a, 0x68, 0x4a, 0x50, 0x46, 0x56, 0x4e, - 0x57, 0x6b, 0x51, 0x49, 0x4a, 0x6c, 0x6c, 0x4e, 0x52, 0x51, 0x74, 0x49, 0x43, 0x6a, 0x4e, 0x65, 0x53, 0x6b, 0x31, 0x31, 0x46, 0x68, 0x64, 0x6a, 0x52, 0x67, 0x45, 0x71, - 0x56, 0x58, 0x73, 0x50, 0x41, 0x6e, 0x4e, 0x71, 0x53, 0x33, 0x39, 0x31, 0x5a, 0x54, 0x78, 0x4d, 0x4d, 0x7a, 0x6c, 0x73, 0x64, 0x41, 0x56, 0x67, 0x44, 0x33, 0x38, 0x74, - 0x51, 0x55, 0x31, 0x4e, 0x52, 0x6e, 0x45, 0x4a, 0x62, 0x30, 0x39, 0x67, 0x46, 0x51, 0x39, 0x47, 0x63, 0x32, 0x4e, 0x4d, 0x58, 0x6e, 0x51, 0x77, 0x44, 0x53, 0x68, 0x44, - 0x43, 0x48, 0x49, 0x79, 0x42, 0x43, 0x34, 0x78, 0x4b, 0x53, 0x64, 0x45, 0x62, 0x52, 0x4d, 0x58, 0x53, 0x41, 0x39, 0x4a, 0x55, 0x68, 0x41, 0x54, 0x66, 0x78, 0x63, 0x57, - 0x59, 0x6e, 0x6b, 0x31, 0x65, 0x44, 0x34, 0x42, 0x66, 0x43, 0x34, 0x50, 0x64, 0x6a, 0x35, 0x65, 0x55, 0x32, 0x78, 0x62, 0x58, 0x33, 0x77, 0x5a, 0x51, 0x51, 0x49, 0x76, - 0x46, 0x32, 0x52, 0x42, 0x64, 0x52, 0x41, 0x45, 0x52, 0x33, 0x77, 0x39, 0x53, 0x31, 0x49, 0x41, 0x45, 0x46, 0x31, 0x52, 0x54, 0x6e, 0x6f, 0x6e, 0x4a, 0x56, 0x56, 0x41, - 0x45, 0x6a, 0x56, 0x67, 0x42, 0x52, 0x73, 0x30, 0x4c, 0x51, 0x52, 0x36, 0x61, 0x6d, 0x6b, 0x43, 0x65, 0x51, 0x4d, 0x36, 0x4c, 0x77, 0x59, 0x4b, 0x65, 0x58, 0x73, 0x53, - 0x58, 0x58, 0x78, 0x53, 0x4b, 0x55, 0x64, 0x59, 0x45, 0x6e, 0x4d, 0x2f, 0x4a, 0x31, 0x59, 0x46, 0x44, 0x45, 0x67, 0x79, 0x57, 0x47, 0x74, 0x58, 0x58, 0x41, 0x4e, 0x6b, - 0x56, 0x68, 0x46, 0x53, 0x65, 0x6a, 0x41, 0x32, 0x4b, 0x52, 0x63, 0x37, 0x61, 0x48, 0x70, 0x38, 0x42, 0x57, 0x74, 0x72, 0x45, 0x32, 0x6f, 0x6b, 0x58, 0x47, 0x68, 0x43, - 0x47, 0x44, 0x49, 0x44, 0x63, 0x32, 0x34, 0x45, 0x49, 0x53, 0x34, 0x42, 0x42, 0x47, 0x4e, 0x39, 0x52, 0x45, 0x45, 0x53, 0x4d, 0x51, 0x73, 0x56, 0x48, 0x33, 0x41, 0x41, - 0x4c, 0x6d, 0x59, 0x55, 0x50, 0x48, 0x38, 0x72, 0x41, 0x42, 0x38, 0x4d, 0x4b, 0x46, 0x6b, 0x4b, 0x46, 0x6b, 0x6c, 0x61, 0x58, 0x47, 0x52, 0x6c, 0x53, 0x78, 0x45, 0x70, - 0x46, 0x54, 0x5a, 0x61, 0x5a, 0x52, 0x6c, 0x50, 0x59, 0x43, 0x4d, 0x36, 0x4f, 0x68, 0x4d, 0x6c, 0x41, 0x6e, 0x68, 0x4d, 0x56, 0x41, 0x3d, 0x3d, 0x00}; + 0x43, 0x7a, 0x42, 0x45, 0x59, 0x6e, 0x77, 0x69, 0x48, 0x77, 0x30, 0x46, 0x5a, 0x79, 0x77, 0x71, 0x4f, 0x53, 0x46, 0x47, 0x43, 0x46, + 0x42, 0x6d, 0x4e, 0x44, 0x63, 0x4c, 0x52, 0x55, 0x73, 0x34, 0x4d, 0x67, 0x5a, 0x36, 0x50, 0x6e, 0x38, 0x4d, 0x51, 0x42, 0x68, 0x72, + 0x4c, 0x57, 0x42, 0x4d, 0x59, 0x41, 0x77, 0x6a, 0x51, 0x7a, 0x73, 0x2b, 0x47, 0x78, 0x59, 0x45, 0x52, 0x6c, 0x67, 0x2f, 0x51, 0x47, + 0x6f, 0x52, 0x42, 0x57, 0x4e, 0x78, 0x46, 0x44, 0x56, 0x48, 0x65, 0x52, 0x4e, 0x76, 0x61, 0x79, 0x63, 0x59, 0x57, 0x30, 0x67, 0x6e, + 0x50, 0x6d, 0x38, 0x56, 0x4d, 0x30, 0x38, 0x2b, 0x58, 0x6c, 0x46, 0x7a, 0x61, 0x43, 0x55, 0x50, 0x42, 0x6c, 0x74, 0x38, 0x63, 0x6e, + 0x55, 0x2b, 0x50, 0x78, 0x74, 0x63, 0x62, 0x57, 0x6f, 0x35, 0x66, 0x47, 0x4e, 0x6a, 0x59, 0x47, 0x78, 0x36, 0x4d, 0x33, 0x5a, 0x53, + 0x45, 0x79, 0x55, 0x7a, 0x66, 0x57, 0x55, 0x6a, 0x4a, 0x78, 0x45, 0x47, 0x42, 0x6b, 0x64, 0x78, 0x48, 0x68, 0x52, 0x30, 0x59, 0x33, + 0x41, 0x74, 0x46, 0x53, 0x63, 0x59, 0x55, 0x51, 0x59, 0x46, 0x4d, 0x78, 0x45, 0x73, 0x61, 0x77, 0x41, 0x74, 0x64, 0x79, 0x42, 0x49, + 0x44, 0x58, 0x4e, 0x52, 0x52, 0x53, 0x56, 0x2f, 0x66, 0x7a, 0x55, 0x6d, 0x4c, 0x69, 0x5a, 0x54, 0x4a, 0x47, 0x67, 0x65, 0x44, 0x6c, + 0x67, 0x36, 0x57, 0x56, 0x42, 0x57, 0x4e, 0x31, 0x39, 0x6d, 0x41, 0x55, 0x78, 0x61, 0x5a, 0x44, 0x4a, 0x51, 0x65, 0x32, 0x6f, 0x67, + 0x63, 0x69, 0x73, 0x64, 0x66, 0x6b, 0x4e, 0x37, 0x59, 0x55, 0x49, 0x4c, 0x59, 0x58, 0x4d, 0x6b, 0x65, 0x54, 0x70, 0x72, 0x53, 0x6e, + 0x6c, 0x75, 0x43, 0x51, 0x38, 0x6e, 0x4c, 0x51, 0x78, 0x65, 0x4d, 0x6b, 0x73, 0x4e, 0x65, 0x55, 0x59, 0x35, 0x49, 0x51, 0x6f, 0x6d, + 0x58, 0x7a, 0x6f, 0x41, 0x4a, 0x6a, 0x38, 0x54, 0x4c, 0x6e, 0x35, 0x51, 0x4b, 0x32, 0x64, 0x47, 0x63, 0x6a, 0x38, 0x37, 0x41, 0x55, + 0x59, 0x62, 0x43, 0x7a, 0x56, 0x4a, 0x4f, 0x52, 0x6c, 0x77, 0x50, 0x51, 0x4a, 0x42, 0x44, 0x6a, 0x67, 0x46, 0x64, 0x6d, 0x56, 0x50, + 0x4d, 0x57, 0x78, 0x65, 0x46, 0x77, 0x51, 0x56, 0x4e, 0x69, 0x5a, 0x6b, 0x4e, 0x42, 0x51, 0x58, 0x66, 0x41, 0x34, 0x4c, 0x57, 0x31, + 0x56, 0x54, 0x61, 0x77, 0x42, 0x43, 0x51, 0x55, 0x38, 0x43, 0x58, 0x42, 0x4d, 0x4b, 0x4c, 0x43, 0x77, 0x2b, 0x45, 0x42, 0x51, 0x7a, + 0x52, 0x58, 0x78, 0x36, 0x57, 0x6a, 0x46, 0x68, 0x4f, 0x51, 0x67, 0x69, 0x61, 0x68, 0x34, 0x50, 0x62, 0x78, 0x74, 0x73, 0x45, 0x31, + 0x35, 0x35, 0x49, 0x48, 0x6c, 0x51, 0x59, 0x67, 0x59, 0x73, 0x64, 0x68, 0x63, 0x45, 0x4b, 0x79, 0x70, 0x31, 0x48, 0x77, 0x77, 0x33, + 0x54, 0x67, 0x39, 0x37, 0x4c, 0x54, 0x52, 0x31, 0x59, 0x44, 0x46, 0x30, 0x4c, 0x67, 0x70, 0x4b, 0x45, 0x57, 0x78, 0x4a, 0x4a, 0x51, + 0x45, 0x36, 0x50, 0x53, 0x49, 0x65, 0x62, 0x52, 0x68, 0x52, 0x65, 0x43, 0x31, 0x69, 0x4d, 0x55, 0x78, 0x51, 0x51, 0x42, 0x64, 0x4c, + 0x62, 0x79, 0x49, 0x41, 0x66, 0x32, 0x45, 0x71, 0x4e, 0x44, 0x34, 0x41, 0x58, 0x79, 0x39, 0x66, 0x4c, 0x78, 0x51, 0x71, 0x56, 0x53, + 0x63, 0x66, 0x52, 0x68, 0x38, 0x53, 0x52, 0x6c, 0x34, 0x65, 0x44, 0x48, 0x77, 0x34, 0x41, 0x57, 0x46, 0x6b, 0x64, 0x69, 0x4a, 0x75, + 0x43, 0x43, 0x41, 0x34, 0x54, 0x33, 0x4e, 0x79, 0x56, 0x52, 0x4a, 0x43, 0x47, 0x56, 0x42, 0x68, 0x51, 0x33, 0x64, 0x39, 0x51, 0x53, + 0x34, 0x31, 0x54, 0x7a, 0x30, 0x78, 0x4b, 0x46, 0x68, 0x6e, 0x47, 0x77, 0x4e, 0x52, 0x49, 0x44, 0x49, 0x63, 0x43, 0x47, 0x34, 0x33, + 0x64, 0x54, 0x64, 0x45, 0x54, 0x32, 0x67, 0x5a, 0x42, 0x32, 0x51, 0x55, 0x4b, 0x43, 0x55, 0x72, 0x61, 0x54, 0x55, 0x59, 0x4a, 0x79, + 0x59, 0x55, 0x45, 0x33, 0x42, 0x43, 0x47, 0x52, 0x4a, 0x31, 0x50, 0x67, 0x4a, 0x64, 0x66, 0x42, 0x4d, 0x66, 0x46, 0x6c, 0x4d, 0x37, + 0x64, 0x45, 0x67, 0x38, 0x58, 0x6a, 0x6c, 0x73, 0x48, 0x42, 0x78, 0x30, 0x4f, 0x52, 0x38, 0x41, 0x47, 0x77, 0x59, 0x4b, 0x61, 0x44, + 0x74, 0x53, 0x54, 0x78, 0x35, 0x75, 0x50, 0x44, 0x55, 0x4d, 0x4f, 0x41, 0x34, 0x4c, 0x4f, 0x78, 0x70, 0x32, 0x49, 0x79, 0x6c, 0x54, + 0x48, 0x6c, 0x39, 0x42, 0x44, 0x45, 0x73, 0x4b, 0x5a, 0x53, 0x68, 0x34, 0x5a, 0x30, 0x68, 0x5a, 0x4a, 0x6d, 0x30, 0x78, 0x64, 0x69, + 0x4e, 0x77, 0x59, 0x57, 0x51, 0x37, 0x4f, 0x48, 0x6c, 0x6d, 0x64, 0x46, 0x4d, 0x73, 0x5a, 0x47, 0x52, 0x55, 0x41, 0x31, 0x52, 0x6c, + 0x52, 0x45, 0x77, 0x59, 0x54, 0x30, 0x67, 0x67, 0x54, 0x33, 0x49, 0x51, 0x50, 0x77, 0x78, 0x53, 0x4c, 0x51, 0x4d, 0x55, 0x41, 0x31, + 0x46, 0x43, 0x45, 0x48, 0x64, 0x71, 0x4e, 0x41, 0x59, 0x79, 0x41, 0x33, 0x49, 0x55, 0x66, 0x41, 0x68, 0x64, 0x55, 0x68, 0x70, 0x69, + 0x66, 0x44, 0x34, 0x77, 0x66, 0x6c, 0x39, 0x2f, 0x56, 0x41, 0x39, 0x45, 0x53, 0x56, 0x31, 0x65, 0x45, 0x47, 0x6f, 0x47, 0x4b, 0x77, + 0x5a, 0x54, 0x45, 0x44, 0x6b, 0x33, 0x4d, 0x6b, 0x70, 0x4f, 0x50, 0x53, 0x74, 0x6c, 0x4f, 0x44, 0x6b, 0x48, 0x63, 0x6c, 0x52, 0x6b, + 0x54, 0x56, 0x5a, 0x71, 0x41, 0x79, 0x4a, 0x77, 0x65, 0x31, 0x39, 0x67, 0x43, 0x79, 0x6f, 0x4c, 0x61, 0x78, 0x42, 0x6b, 0x46, 0x41, + 0x55, 0x69, 0x41, 0x48, 0x4e, 0x41, 0x49, 0x31, 0x74, 0x52, 0x48, 0x79, 0x73, 0x61, 0x58, 0x57, 0x6c, 0x36, 0x52, 0x67, 0x78, 0x66, + 0x4d, 0x6b, 0x74, 0x4b, 0x4b, 0x46, 0x4a, 0x35, 0x57, 0x78, 0x4a, 0x43, 0x47, 0x41, 0x42, 0x64, 0x4a, 0x7a, 0x46, 0x54, 0x50, 0x45, + 0x77, 0x32, 0x54, 0x6a, 0x67, 0x2f, 0x63, 0x67, 0x4e, 0x78, 0x41, 0x6c, 0x73, 0x32, 0x57, 0x58, 0x39, 0x31, 0x62, 0x67, 0x68, 0x55, + 0x44, 0x54, 0x51, 0x63, 0x4e, 0x46, 0x64, 0x64, 0x61, 0x55, 0x67, 0x41, 0x4f, 0x77, 0x55, 0x48, 0x62, 0x69, 0x64, 0x6c, 0x62, 0x6b, + 0x41, 0x39, 0x4f, 0x6b, 0x39, 0x79, 0x58, 0x54, 0x6b, 0x57, 0x44, 0x32, 0x4d, 0x53, 0x45, 0x68, 0x55, 0x36, 0x63, 0x41, 0x31, 0x58, + 0x47, 0x41, 0x31, 0x65, 0x50, 0x53, 0x4a, 0x6f, 0x61, 0x48, 0x78, 0x74, 0x54, 0x77, 0x78, 0x37, 0x43, 0x53, 0x31, 0x4b, 0x63, 0x79, + 0x42, 0x48, 0x42, 0x31, 0x64, 0x31, 0x58, 0x56, 0x4e, 0x77, 0x4e, 0x43, 0x46, 0x41, 0x56, 0x31, 0x46, 0x65, 0x53, 0x55, 0x51, 0x41, + 0x56, 0x43, 0x63, 0x45, 0x61, 0x48, 0x35, 0x5a, 0x56, 0x6c, 0x68, 0x30, 0x46, 0x44, 0x77, 0x57, 0x4d, 0x30, 0x45, 0x57, 0x53, 0x79, + 0x39, 0x4a, 0x4e, 0x77, 0x70, 0x55, 0x43, 0x41, 0x67, 0x66, 0x4f, 0x57, 0x64, 0x32, 0x4b, 0x43, 0x67, 0x48, 0x48, 0x57, 0x46, 0x48, + 0x55, 0x55, 0x31, 0x31, 0x4a, 0x6c, 0x4a, 0x48, 0x52, 0x77, 0x78, 0x58, 0x57, 0x48, 0x51, 0x2b, 0x59, 0x6d, 0x78, 0x59, 0x4f, 0x6b, + 0x51, 0x65, 0x46, 0x69, 0x34, 0x68, 0x48, 0x48, 0x4e, 0x46, 0x5a, 0x33, 0x52, 0x50, 0x4d, 0x32, 0x59, 0x4f, 0x64, 0x47, 0x59, 0x6d, + 0x48, 0x79, 0x34, 0x34, 0x52, 0x45, 0x42, 0x2b, 0x4b, 0x6c, 0x42, 0x53, 0x58, 0x6b, 0x4d, 0x42, 0x65, 0x6a, 0x68, 0x4a, 0x50, 0x46, + 0x56, 0x4e, 0x57, 0x6b, 0x51, 0x49, 0x4a, 0x6c, 0x6c, 0x4e, 0x52, 0x51, 0x74, 0x49, 0x43, 0x6a, 0x4e, 0x65, 0x53, 0x6b, 0x31, 0x31, + 0x46, 0x68, 0x64, 0x6a, 0x52, 0x67, 0x45, 0x71, 0x56, 0x58, 0x73, 0x50, 0x41, 0x6e, 0x4e, 0x71, 0x53, 0x33, 0x39, 0x31, 0x5a, 0x54, + 0x78, 0x4d, 0x4d, 0x7a, 0x6c, 0x73, 0x64, 0x41, 0x56, 0x67, 0x44, 0x33, 0x38, 0x74, 0x51, 0x55, 0x31, 0x4e, 0x52, 0x6e, 0x45, 0x4a, + 0x62, 0x30, 0x39, 0x67, 0x46, 0x51, 0x39, 0x47, 0x63, 0x32, 0x4e, 0x4d, 0x58, 0x6e, 0x51, 0x77, 0x44, 0x53, 0x68, 0x44, 0x43, 0x48, + 0x49, 0x79, 0x42, 0x43, 0x34, 0x78, 0x4b, 0x53, 0x64, 0x45, 0x62, 0x52, 0x4d, 0x58, 0x53, 0x41, 0x39, 0x4a, 0x55, 0x68, 0x41, 0x54, + 0x66, 0x78, 0x63, 0x57, 0x59, 0x6e, 0x6b, 0x31, 0x65, 0x44, 0x34, 0x42, 0x66, 0x43, 0x34, 0x50, 0x64, 0x6a, 0x35, 0x65, 0x55, 0x32, + 0x78, 0x62, 0x58, 0x33, 0x77, 0x5a, 0x51, 0x51, 0x49, 0x76, 0x46, 0x32, 0x52, 0x42, 0x64, 0x52, 0x41, 0x45, 0x52, 0x33, 0x77, 0x39, + 0x53, 0x31, 0x49, 0x41, 0x45, 0x46, 0x31, 0x52, 0x54, 0x6e, 0x6f, 0x6e, 0x4a, 0x56, 0x56, 0x41, 0x45, 0x6a, 0x56, 0x67, 0x42, 0x52, + 0x73, 0x30, 0x4c, 0x51, 0x52, 0x36, 0x61, 0x6d, 0x6b, 0x43, 0x65, 0x51, 0x4d, 0x36, 0x4c, 0x77, 0x59, 0x4b, 0x65, 0x58, 0x73, 0x53, + 0x58, 0x58, 0x78, 0x53, 0x4b, 0x55, 0x64, 0x59, 0x45, 0x6e, 0x4d, 0x2f, 0x4a, 0x31, 0x59, 0x46, 0x44, 0x45, 0x67, 0x79, 0x57, 0x47, + 0x74, 0x58, 0x58, 0x41, 0x4e, 0x6b, 0x56, 0x68, 0x46, 0x53, 0x65, 0x6a, 0x41, 0x32, 0x4b, 0x52, 0x63, 0x37, 0x61, 0x48, 0x70, 0x38, + 0x42, 0x57, 0x74, 0x72, 0x45, 0x32, 0x6f, 0x6b, 0x58, 0x47, 0x68, 0x43, 0x47, 0x44, 0x49, 0x44, 0x63, 0x32, 0x34, 0x45, 0x49, 0x53, + 0x34, 0x42, 0x42, 0x47, 0x4e, 0x39, 0x52, 0x45, 0x45, 0x53, 0x4d, 0x51, 0x73, 0x56, 0x48, 0x33, 0x41, 0x41, 0x4c, 0x6d, 0x59, 0x55, + 0x50, 0x48, 0x38, 0x72, 0x41, 0x42, 0x38, 0x4d, 0x4b, 0x46, 0x6b, 0x4b, 0x46, 0x6b, 0x6c, 0x61, 0x58, 0x47, 0x52, 0x6c, 0x53, 0x78, + 0x45, 0x70, 0x46, 0x54, 0x5a, 0x61, 0x5a, 0x52, 0x6c, 0x50, 0x59, 0x43, 0x4d, 0x36, 0x4f, 0x68, 0x4d, 0x6c, 0x41, 0x6e, 0x68, 0x4d, + 0x56, 0x41, 0x3d, 0x3d, 0x00}; char *b64_test; plan_tests(1); diff --git a/lib/tests/test_cmd.c b/lib/tests/test_cmd.c index a60b64e..c8867df 100644 --- a/lib/tests/test_cmd.c +++ b/lib/tests/test_cmd.c @@ -140,7 +140,8 @@ int main(int argc, char **argv) { ok(chld_err.lines == 0, "(array) Check for expected number of stderr lines"); ok(strcmp(chld_out.line[0], "this is a test via echo") == 0, "(array) Check line 1 for expected stdout output"); ok(strcmp(chld_out.line[1], "line two") == 0, "(array) Check line 2 for expected stdout output"); - ok(strcmp(chld_out.line[2], "it's line 3 and (note space between '3' and 'and') $$ will not get evaluated") == 0, "(array) Check line 3 for expected stdout output"); + ok(strcmp(chld_out.line[2], "it's line 3 and (note space between '3' and 'and') $$ will not get evaluated") == 0, + "(array) Check line 3 for expected stdout output"); ok(result == 0, "(array) Checking exit code"); /* ensure everything is empty again */ diff --git a/lib/tests/test_generic_output b/lib/tests/test_generic_output new file mode 100755 index 0000000..51e299a Binary files /dev/null and b/lib/tests/test_generic_output differ diff --git a/lib/tests/test_ini1.c b/lib/tests/test_ini1.c index 711fef9..246c125 100644 --- a/lib/tests/test_ini1.c +++ b/lib/tests/test_ini1.c @@ -98,15 +98,22 @@ int main(int argc, char **argv) { my_free(optstr); optstr = list2str(np_get_defaults("tcp_long_lines@plugins.ini", "check_tcp")); - ok(!strcmp(optstr, - "--escape --send=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " - "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo " - "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " - "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda --expect=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " - "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " - "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo " - "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " - "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda --jail"), + ok(!strcmp(optstr, "--escape --send=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar " + "BAZ yadda yadda yadda Foo bar BAZ yadda yadda " + "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda " + "yadda yadda Foo bar BAZ yadda yadda yadda Foo " + "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " + "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " + "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda --expect=Foo bar BAZ yadda yadda " + "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " + "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo " + "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " + "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda " + "yadda yadda Foo bar BAZ yadda yadda yadda Foo " + "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " + "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " + "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo " + "bar BAZ yadda yadda yadda --jail"), "Long options"); my_free(optstr); diff --git a/lib/tests/test_opts1.c b/lib/tests/test_opts1.c index e32115c..984183d 100644 --- a/lib/tests/test_opts1.c +++ b/lib/tests/test_opts1.c @@ -126,9 +126,11 @@ int main(int argc, char **argv) { } { - char *argv_test[] = {"prog_name", "--arg1=val1", "--extra-opts=@./config-opts.ini", "--extra-opts", "sect1@./config-opts.ini", "--arg2", (char *)NULL}; + char *argv_test[] = {"prog_name", "--arg1=val1", "--extra-opts=@./config-opts.ini", "--extra-opts", "sect1@./config-opts.ini", + "--arg2", (char *)NULL}; argc_test = 6; - char *argv_known[] = {"prog_name", "--foo=Bar", "--this=Your Mother!", "--blank", "--one=two", "--arg1=val1", "--arg2", (char *)NULL}; + char *argv_known[] = {"prog_name", "--foo=Bar", "--this=Your Mother!", "--blank", "--one=two", + "--arg1=val1", "--arg2", (char *)NULL}; argv_new = np_extra_opts(&argc_test, argv_test, "check_disk"); ok(array_diff(argc_test, argv_new, 7, argv_known), "twice extra opts using two sections"); my_free(&argc_test, argv_new, argv_test); diff --git a/lib/tests/test_opts2.c b/lib/tests/test_opts2.c index 95c6505..2349661 100644 --- a/lib/tests/test_opts2.c +++ b/lib/tests/test_opts2.c @@ -110,20 +110,28 @@ int main(int argc, char **argv) { { char *argv_test[] = {"check_tcp", "--extra-opts", "--extra-opts=tcp_long_lines", (char *)NULL}; argc_test = 3; - char *argv_known[] = {"check_tcp", - "--timeout=10", - "--escape", - "--send=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda " - "yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " - "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar " - "BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda", - "--expect=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda " - "yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " - "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar " - "BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo " - "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda", - "--jail", - (char *)NULL}; + char *argv_known[] = { + "check_tcp", + "--timeout=10", + "--escape", + "--send=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " + "yadda Foo bar BAZ yadda " + "yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " + "yadda Foo bar BAZ " + "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda " + "yadda yadda Foo bar " + "BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda", + "--expect=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " + "yadda Foo bar BAZ yadda " + "yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " + "yadda Foo bar BAZ " + "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda " + "yadda yadda Foo bar " + "BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " + "yadda yadda yadda Foo " + "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda", + "--jail", + (char *)NULL}; argv_new = np_extra_opts(&argc_test, argv_test, "check_tcp"); ok(array_diff(argc_test, argv_new, 6, argv_known), "Long lines test"); my_free(&argc_test, argv_new, argv_test); diff --git a/lib/tests/test_tcp.c b/lib/tests/test_tcp.c index b09c005..1b3003e 100644 --- a/lib/tests/test_tcp.c +++ b/lib/tests/test_tcp.c @@ -32,15 +32,21 @@ int main(void) { server_expect[1] = strdup("bb"); server_expect[2] = strdup("CC"); - ok(np_expect_match("AA bb CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_SUCCESS, "Test matching any string at the beginning (first expect string)"); - ok(np_expect_match("bb AA CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_SUCCESS, "Test matching any string at the beginning (second expect string)"); - ok(np_expect_match("b", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_RETRY, "Test matching any string at the beginning (substring match)"); - ok(np_expect_match("XX bb AA CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_FAILURE, "Test with strings not matching at the beginning"); + ok(np_expect_match("AA bb CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_SUCCESS, + "Test matching any string at the beginning (first expect string)"); + ok(np_expect_match("bb AA CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_SUCCESS, + "Test matching any string at the beginning (second expect string)"); + ok(np_expect_match("b", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_RETRY, + "Test matching any string at the beginning (substring match)"); + ok(np_expect_match("XX bb AA CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_FAILURE, + "Test with strings not matching at the beginning"); ok(np_expect_match("XX CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_FAILURE, "Test matching any string"); ok(np_expect_match("XX", server_expect, server_expect_count, 0) == NP_MATCH_RETRY, "Test not matching any string"); - ok(np_expect_match("XX AA bb CC XX", server_expect, server_expect_count, NP_MATCH_ALL) == NP_MATCH_SUCCESS, "Test matching all strings"); + ok(np_expect_match("XX AA bb CC XX", server_expect, server_expect_count, NP_MATCH_ALL) == NP_MATCH_SUCCESS, + "Test matching all strings"); ok(np_expect_match("XX bb CC XX", server_expect, server_expect_count, NP_MATCH_ALL) == NP_MATCH_RETRY, "Test not matching all strings"); - ok(np_expect_match("XX XX", server_expect, server_expect_count, NP_MATCH_ALL) == NP_MATCH_RETRY, "Test not matching any string (testing all)"); + ok(np_expect_match("XX XX", server_expect, server_expect_count, NP_MATCH_ALL) == NP_MATCH_RETRY, + "Test not matching any string (testing all)"); return exit_status(); } diff --git a/lib/tests/test_utils.c b/lib/tests/test_utils.c index 901e0cc..c3150f0 100644 --- a/lib/tests/test_utils.c +++ b/lib/tests/test_utils.c @@ -375,7 +375,8 @@ int main(int argc, char **argv) { temp_state_key->_filename = "var/statefile"; temp_state_data = np_state_read(); - ok(this_monitoring_plugin->state->state_data != NULL, "Got state data now") || diag("Are you running in right directory? Will get coredump next if not"); + ok(this_monitoring_plugin->state->state_data != NULL, "Got state data now") || + diag("Are you running in right directory? Will get coredump next if not"); ok(this_monitoring_plugin->state->state_data->time == 1234567890, "Got time"); ok(!strcmp((char *)this_monitoring_plugin->state->state_data->data, "String to read"), "Data as expected"); diff --git a/lib/utils_base.c b/lib/utils_base.c index 6d6954e..90a4aaa 100644 --- a/lib/utils_base.c +++ b/lib/utils_base.c @@ -33,12 +33,12 @@ #include #include -#define np_free(ptr) \ - { \ - if (ptr) { \ - free(ptr); \ - ptr = NULL; \ - } \ +#define np_free(ptr) \ + { \ + if (ptr) { \ + free(ptr); \ + ptr = NULL; \ + } \ } monitoring_plugin *this_monitoring_plugin = NULL; @@ -511,7 +511,8 @@ void np_enable_state(char *keyname, int expected_data_version) { this_state->state_data = NULL; /* Calculate filename */ - ret = asprintf(&temp_filename, "%s/%lu/%s/%s", _np_state_calculate_location_prefix(), (unsigned long)geteuid(), this_monitoring_plugin->plugin_name, this_state->name); + ret = asprintf(&temp_filename, "%s/%lu/%s/%s", _np_state_calculate_location_prefix(), (unsigned long)geteuid(), + this_monitoring_plugin->plugin_name, this_state->name); if (ret < 0) die(STATE_UNKNOWN, _("Cannot allocate memory: %s"), strerror(errno)); @@ -568,7 +569,13 @@ bool _np_state_read_file(FILE *f) { int i; int failure = 0; time_t current_time, data_time; - enum { STATE_FILE_VERSION, STATE_DATA_VERSION, STATE_DATA_TIME, STATE_DATA_TEXT, STATE_DATA_END } expected = STATE_FILE_VERSION; + enum { + STATE_FILE_VERSION, + STATE_DATA_VERSION, + STATE_DATA_TIME, + STATE_DATA_TEXT, + STATE_DATA_END + } expected = STATE_FILE_VERSION; time(¤t_time); diff --git a/lib/utils_disk.c b/lib/utils_disk.c index c87090e..2b761f5 100644 --- a/lib/utils_disk.c +++ b/lib/utils_disk.c @@ -180,7 +180,8 @@ void np_set_best_match(struct parameter_list *desired, struct mount_entry *mount if (!best_match) { for (me = mount_list; me; me = me->me_next) { size_t len = strlen(me->me_mountdir); - if ((!exact && (best_match_len <= len && len <= name_len && (len == 1 || strncmp(me->me_mountdir, d->name, len) == 0))) || + if ((!exact && + (best_match_len <= len && len <= name_len && (len == 1 || strncmp(me->me_mountdir, d->name, len) == 0))) || (exact && strcmp(me->me_mountdir, d->name) == 0)) { if (get_fs_usage(me->me_mountdir, me->me_devname, &fsp) >= 0) { best_match = me; diff --git a/lib/utils_tcp.c b/lib/utils_tcp.c index 440eb9b..daae1d5 100644 --- a/lib/utils_tcp.c +++ b/lib/utils_tcp.c @@ -29,10 +29,10 @@ #include "common.h" #include "utils_tcp.h" -#define VERBOSE(message) \ - do { \ - if (flags & NP_MATCH_VERBOSE) \ - puts(message); \ +#define VERBOSE(message) \ + do { \ + if (flags & NP_MATCH_VERBOSE) \ + puts(message); \ } while (0) enum np_match_result np_expect_match(char *status, char **server_expect, int expect_count, int flags) { -- cgit v0.10-9-g596f From 7d90b8200f709d125df19fa6aedf633c64b88ad4 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 01:31:59 +0100 Subject: lib: clang-format for headers too diff --git a/lib/utils_tcp.h b/lib/utils_tcp.h index 6543377..d5999e9 100644 --- a/lib/utils_tcp.h +++ b/lib/utils_tcp.h @@ -10,6 +10,10 @@ * caller to decide whether it makes sense to wait for additional data from the * server. */ -enum np_match_result { NP_MATCH_FAILURE, NP_MATCH_SUCCESS, NP_MATCH_RETRY }; +enum np_match_result { + NP_MATCH_FAILURE, + NP_MATCH_SUCCESS, + NP_MATCH_RETRY +}; enum np_match_result np_expect_match(char *status, char **server_expect, int server_expect_count, int flags); -- cgit v0.10-9-g596f From 9f1ec43ce1637b41117d03b8456af8c0829a54f2 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:43:12 +0100 Subject: check_by_ssh: clang-format diff --git a/plugins/check_by_ssh.c b/plugins/check_by_ssh.c index 2a23b39..35aa1b8 100644 --- a/plugins/check_by_ssh.c +++ b/plugins/check_by_ssh.c @@ -1,30 +1,30 @@ /***************************************************************************** -* -* Monitoring check_by_ssh plugin -* -* License: GPL -* Copyright (c) 2000-2008 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_by_ssh plugin -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_by_ssh plugin + * + * License: GPL + * Copyright (c) 2000-2008 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_by_ssh plugin + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "check_by_ssh"; const char *copyright = "2000-2008"; @@ -36,14 +36,14 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils_cmd.h" #ifndef NP_MAXARGS -#define NP_MAXARGS 1024 +# define NP_MAXARGS 1024 #endif -int process_arguments (int, char **); -int validate_arguments (void); -void comm_append (const char *); -void print_help (void); -void print_usage (void); +int process_arguments(int, char **); +int validate_arguments(void); +void comm_append(const char *); +void print_help(void); +void print_usage(void); unsigned int commands = 0; unsigned int services = 0; @@ -61,9 +61,7 @@ char **service; bool passive = false; bool verbose = false; -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { char *status_text; int cresult; @@ -75,43 +73,42 @@ main (int argc, char **argv) remotecmd = ""; comm_append(SSH_COMMAND); - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); /* process arguments */ - if (process_arguments (argc, argv) == ERROR) + if (process_arguments(argc, argv) == ERROR) usage_va(_("Could not parse arguments")); /* Set signal handling and alarm timeout */ - if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) { + if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR) { usage_va(_("Cannot catch SIGALRM")); } - alarm (timeout_interval); + alarm(timeout_interval); /* run the command */ if (verbose) { - printf ("Command: %s\n", commargv[0]); + printf("Command: %s\n", commargv[0]); for (int i = 1; i < commargc; i++) - printf ("Argument %i: %s\n", i, commargv[i]); + printf("Argument %i: %s\n", i, commargv[i]); } - result = cmd_run_array (commargv, &chld_out, &chld_err, 0); + result = cmd_run_array(commargv, &chld_out, &chld_err, 0); /* SSH returns 255 if connection attempt fails; include the first line of error output */ if (result == 255 && unknown_timeout) { - printf (_("SSH connection failed: %s\n"), - chld_err.lines > 0 ? chld_err.line[0] : "(no error output)"); + printf(_("SSH connection failed: %s\n"), chld_err.lines > 0 ? chld_err.line[0] : "(no error output)"); return STATE_UNKNOWN; } if (verbose) { - for(size_t i = 0; i < chld_out.lines; i++) + for (size_t i = 0; i < chld_out.lines; i++) printf("stdout: %s\n", chld_out.line[i]); - for(size_t i = 0; i < chld_err.lines; i++) + for (size_t i = 0; i < chld_err.lines; i++) printf("stderr: %s\n", chld_err.line[i]); } @@ -121,10 +118,9 @@ main (int argc, char **argv) skip_stderr = chld_err.lines; /* UNKNOWN or worse if (non-skipped) output found on stderr */ - if(chld_err.lines > (size_t)skip_stderr) { - printf (_("Remote command execution failed: %s\n"), - chld_err.line[skip_stderr]); - if ( warn_on_stderr ) + if (chld_err.lines > (size_t)skip_stderr) { + printf(_("Remote command execution failed: %s\n"), chld_err.line[skip_stderr]); + if (warn_on_stderr) return max_state_alt(result, STATE_WARNING); else return max_state_alt(result, STATE_UNKNOWN); @@ -132,144 +128,134 @@ main (int argc, char **argv) /* this is simple if we're not supposed to be passive. * Wrap up quickly and keep the tricks below */ - if(!passive) { + if (!passive) { if (chld_out.lines > (size_t)skip_stdout) for (size_t i = skip_stdout; i < chld_out.lines; i++) - puts (chld_out.line[i]); + puts(chld_out.line[i]); else - printf (_("%s - check_by_ssh: Remote command '%s' returned status %d\n"), - state_text(result), remotecmd, result); - return result; /* return error status from remote command */ + printf(_("%s - check_by_ssh: Remote command '%s' returned status %d\n"), state_text(result), remotecmd, result); + return result; /* return error status from remote command */ } - /* * Passive mode */ /* process output */ - if (!(fp = fopen (outputfile, "a"))) { - printf (_("SSH WARNING: could not open %s\n"), outputfile); - exit (STATE_UNKNOWN); + if (!(fp = fopen(outputfile, "a"))) { + printf(_("SSH WARNING: could not open %s\n"), outputfile); + exit(STATE_UNKNOWN); } - local_time = time (NULL); + local_time = time(NULL); commands = 0; - for(size_t i = skip_stdout; i < chld_out.lines; i++) { + for (size_t i = skip_stdout; i < chld_out.lines; i++) { status_text = chld_out.line[i++]; - if (i == chld_out.lines || strstr (chld_out.line[i], "STATUS CODE: ") == NULL) - die (STATE_UNKNOWN, _("%s: Error parsing output\n"), progname); - - if (service[commands] && status_text - && sscanf (chld_out.line[i], "STATUS CODE: %d", &cresult) == 1) - { - fprintf (fp, "[%d] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%d;%s\n", - (int) local_time, host_shortname, service[commands++], - cresult, status_text); + if (i == chld_out.lines || strstr(chld_out.line[i], "STATUS CODE: ") == NULL) + die(STATE_UNKNOWN, _("%s: Error parsing output\n"), progname); + + if (service[commands] && status_text && sscanf(chld_out.line[i], "STATUS CODE: %d", &cresult) == 1) { + fprintf(fp, "[%d] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%d;%s\n", (int)local_time, host_shortname, service[commands++], cresult, + status_text); } } - + /* Multiple commands and passive checking should always return OK */ return result; } /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ +int process_arguments(int argc, char **argv) { int c; char *p1, *p2; int option = 0; - static struct option longopts[] = { - {"version", no_argument, 0, 'V'}, - {"help", no_argument, 0, 'h'}, - {"verbose", no_argument, 0, 'v'}, - {"fork", no_argument, 0, 'f'}, - {"timeout", required_argument, 0, 't'}, - {"unknown-timeout", no_argument, 0, 'U'}, - {"host", required_argument, 0, 'H'}, /* backward compatibility */ - {"hostname", required_argument, 0, 'H'}, - {"port", required_argument,0,'p'}, - {"output", required_argument, 0, 'O'}, - {"name", required_argument, 0, 'n'}, - {"services", required_argument, 0, 's'}, - {"identity", required_argument, 0, 'i'}, - {"user", required_argument, 0, 'u'}, - {"logname", required_argument, 0, 'l'}, - {"command", required_argument, 0, 'C'}, - {"skip", optional_argument, 0, 'S'}, /* backwards compatibility */ - {"skip-stdout", optional_argument, 0, 'S'}, - {"skip-stderr", optional_argument, 0, 'E'}, - {"warn-on-stderr", no_argument, 0, 'W'}, - {"proto1", no_argument, 0, '1'}, - {"proto2", no_argument, 0, '2'}, - {"use-ipv4", no_argument, 0, '4'}, - {"use-ipv6", no_argument, 0, '6'}, - {"ssh-option", required_argument, 0, 'o'}, - {"quiet", no_argument, 0, 'q'}, - {"configfile", optional_argument, 0, 'F'}, - {0, 0, 0, 0} - }; + static struct option longopts[] = {{"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {"verbose", no_argument, 0, 'v'}, + {"fork", no_argument, 0, 'f'}, + {"timeout", required_argument, 0, 't'}, + {"unknown-timeout", no_argument, 0, 'U'}, + {"host", required_argument, 0, 'H'}, /* backward compatibility */ + {"hostname", required_argument, 0, 'H'}, + {"port", required_argument, 0, 'p'}, + {"output", required_argument, 0, 'O'}, + {"name", required_argument, 0, 'n'}, + {"services", required_argument, 0, 's'}, + {"identity", required_argument, 0, 'i'}, + {"user", required_argument, 0, 'u'}, + {"logname", required_argument, 0, 'l'}, + {"command", required_argument, 0, 'C'}, + {"skip", optional_argument, 0, 'S'}, /* backwards compatibility */ + {"skip-stdout", optional_argument, 0, 'S'}, + {"skip-stderr", optional_argument, 0, 'E'}, + {"warn-on-stderr", no_argument, 0, 'W'}, + {"proto1", no_argument, 0, '1'}, + {"proto2", no_argument, 0, '2'}, + {"use-ipv4", no_argument, 0, '4'}, + {"use-ipv6", no_argument, 0, '6'}, + {"ssh-option", required_argument, 0, 'o'}, + {"quiet", no_argument, 0, 'q'}, + {"configfile", optional_argument, 0, 'F'}, + {0, 0, 0, 0}}; if (argc < 2) return ERROR; for (c = 1; c < argc; c++) - if (strcmp ("-to", argv[c]) == 0) - strcpy (argv[c], "-t"); + if (strcmp("-to", argv[c]) == 0) + strcpy(argv[c], "-t"); while (1) { - c = getopt_long (argc, argv, "Vvh1246fqt:UH:O:p:i:u:l:C:S::E::n:s:o:F:", longopts, - &option); + c = getopt_long(argc, argv, "Vvh1246fqt:UH:O:p:i:u:l:C:S::E::n:s:o:F:", longopts, &option); if (c == -1 || c == EOF) break; switch (c) { - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case 'v': /* help */ + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case 'v': /* help */ verbose = true; break; - case 't': /* timeout period */ - if (!is_integer (optarg)) + case 't': /* timeout period */ + if (!is_integer(optarg)) usage_va(_("Timeout interval must be a positive integer")); else - timeout_interval = atoi (optarg); + timeout_interval = atoi(optarg); break; case 'U': unknown_timeout = true; break; - case 'H': /* host */ + case 'H': /* host */ hostname = optarg; break; case 'p': /* port number */ - if (!is_integer (optarg)) + if (!is_integer(optarg)) usage_va(_("Port must be a positive integer")); comm_append("-p"); comm_append(optarg); break; - case 'O': /* output file */ + case 'O': /* output file */ outputfile = optarg; passive = true; break; - case 's': /* description of service to check */ + case 's': /* description of service to check */ p1 = optarg; - service = realloc (service, (++services) * sizeof(char *)); - while ((p2 = index (p1, ':'))) { + service = realloc(service, (++services) * sizeof(char *)); + while ((p2 = index(p1, ':'))) { *p2 = '\0'; service[services - 1] = p1; - service = realloc (service, (++services) * sizeof(char *)); + service = realloc(service, (++services) * sizeof(char *)); p1 = p2 + 1; } service[services - 1] = p1; break; - case 'n': /* short name of host in the monitoring configuration */ + case 'n': /* short name of host in the monitoring configuration */ host_shortname = optarg; break; @@ -277,67 +263,67 @@ process_arguments (int argc, char **argv) comm_append("-l"); comm_append(optarg); break; - case 'l': /* login name */ + case 'l': /* login name */ comm_append("-l"); comm_append(optarg); break; - case 'i': /* identity */ + case 'i': /* identity */ comm_append("-i"); comm_append(optarg); break; - case '1': /* Pass these switches directly to ssh */ + case '1': /* Pass these switches directly to ssh */ comm_append("-1"); break; - case '2': /* 1 to force version 1, 2 to force version 2 */ + case '2': /* 1 to force version 1, 2 to force version 2 */ comm_append("-2"); break; - case '4': /* -4 for IPv4 */ + case '4': /* -4 for IPv4 */ comm_append("-4"); break; - case '6': /* -6 for IPv6 */ + case '6': /* -6 for IPv6 */ comm_append("-6"); break; - case 'f': /* fork to background */ + case 'f': /* fork to background */ comm_append("-f"); break; - case 'C': /* Command for remote machine */ + case 'C': /* Command for remote machine */ commands++; if (commands > 1) - xasprintf (&remotecmd, "%s;echo STATUS CODE: $?;", remotecmd); - xasprintf (&remotecmd, "%s%s", remotecmd, optarg); + xasprintf(&remotecmd, "%s;echo STATUS CODE: $?;", remotecmd); + xasprintf(&remotecmd, "%s%s", remotecmd, optarg); break; - case 'S': /* skip n (or all) lines on stdout */ + case 'S': /* skip n (or all) lines on stdout */ if (optarg == NULL) skip_stdout = -1; /* skip all output on stdout */ - else if (!is_integer (optarg)) + else if (!is_integer(optarg)) usage_va(_("skip-stdout argument must be an integer")); else - skip_stdout = atoi (optarg); + skip_stdout = atoi(optarg); break; - case 'E': /* skip n (or all) lines on stderr */ + case 'E': /* skip n (or all) lines on stderr */ if (optarg == NULL) skip_stderr = -1; /* skip all output on stderr */ - else if (!is_integer (optarg)) + else if (!is_integer(optarg)) usage_va(_("skip-stderr argument must be an integer")); else - skip_stderr = atoi (optarg); + skip_stderr = atoi(optarg); break; - case 'W': /* exit with warning if there is an output on stderr */ + case 'W': /* exit with warning if there is an output on stderr */ warn_on_stderr = 1; break; - case 'o': /* Extra options for the ssh command */ + case 'o': /* Extra options for the ssh command */ comm_append("-o"); comm_append(optarg); break; - case 'q': /* Tell the ssh command to be quiet */ + case 'q': /* Tell the ssh command to be quiet */ comm_append("-q"); break; - case 'F': /* ssh configfile */ + case 'F': /* ssh configfile */ comm_append("-F"); comm_append(optarg); break; - default: /* help */ + default: /* help */ usage5(); } } @@ -345,7 +331,7 @@ process_arguments (int argc, char **argv) c = optind; if (hostname == NULL) { if (c <= argc) { - die (STATE_UNKNOWN, _("%s: You must provide a host name\n"), progname); + die(STATE_UNKNOWN, _("%s: You must provide a host name\n"), progname); } hostname = argv[c++]; } @@ -353,143 +339,130 @@ process_arguments (int argc, char **argv) if (strlen(remotecmd) == 0) { for (; c < argc; c++) if (strlen(remotecmd) > 0) - xasprintf (&remotecmd, "%s %s", remotecmd, argv[c]); + xasprintf(&remotecmd, "%s %s", remotecmd, argv[c]); else - xasprintf (&remotecmd, "%s", argv[c]); + xasprintf(&remotecmd, "%s", argv[c]); } if (commands > 1 || passive) - xasprintf (&remotecmd, "%s;echo STATUS CODE: $?;", remotecmd); + xasprintf(&remotecmd, "%s;echo STATUS CODE: $?;", remotecmd); - if (remotecmd == NULL || strlen (remotecmd) <= 1) + if (remotecmd == NULL || strlen(remotecmd) <= 1) usage_va(_("No remotecmd")); comm_append(hostname); comm_append(remotecmd); - return validate_arguments (); + return validate_arguments(); } - -void -comm_append (const char *str) -{ +void comm_append(const char *str) { if (++commargc > NP_MAXARGS) die(STATE_UNKNOWN, _("%s: Argument limit of %d exceeded\n"), progname, NP_MAXARGS); - if ((commargv = (char **)realloc(commargv, (commargc+1) * sizeof(char *))) == NULL) + if ((commargv = (char **)realloc(commargv, (commargc + 1) * sizeof(char *))) == NULL) die(STATE_UNKNOWN, _("Can not (re)allocate 'commargv' buffer\n")); - commargv[commargc-1] = strdup(str); + commargv[commargc - 1] = strdup(str); commargv[commargc] = NULL; - } -int -validate_arguments (void) -{ +int validate_arguments(void) { if (remotecmd == NULL || hostname == NULL) return ERROR; if (passive && commands != services) - die (STATE_UNKNOWN, _("%s: In passive mode, you must provide a service name for each command.\n"), progname); + die(STATE_UNKNOWN, _("%s: In passive mode, you must provide a service name for each command.\n"), progname); if (passive && host_shortname == NULL) - die (STATE_UNKNOWN, _("%s: In passive mode, you must provide the host short name from the monitoring configs.\n"), progname); + die(STATE_UNKNOWN, _("%s: In passive mode, you must provide the host short name from the monitoring configs.\n"), progname); return OK; } - -void -print_help (void) -{ - print_revision (progname, NP_VERSION); - - printf ("Copyright (c) 1999 Karl DeBisschop \n"); - printf (COPYRIGHT, copyright, email); - - printf (_("This plugin uses SSH to execute commands on a remote host")); - - printf ("\n\n"); - - print_usage (); - - printf (UT_HELP_VRSN); - - printf (UT_EXTRA_OPTS); - - printf (UT_HOST_PORT, 'p', "none"); - - printf (UT_IPv46); - - printf (" %s\n", "-1, --proto1"); - printf (" %s\n", _("tell ssh to use Protocol 1 [optional]")); - printf (" %s\n", "-2, --proto2"); - printf (" %s\n", _("tell ssh to use Protocol 2 [optional]")); - printf (" %s\n", "-S, --skip-stdout[=n]"); - printf (" %s\n", _("Ignore all or (if specified) first n lines on STDOUT [optional]")); - printf (" %s\n", "-E, --skip-stderr[=n]"); - printf (" %s\n", _("Ignore all or (if specified) first n lines on STDERR [optional]")); - printf (" %s\n", "-W, --warn-on-stderr]"); - printf (" %s\n", _("Exit with an warning, if there is an output on STDERR")); - printf (" %s\n", "-f"); - printf (" %s\n", _("tells ssh to fork rather than create a tty [optional]. This will always return OK if ssh is executed")); - printf (" %s\n","-C, --command='COMMAND STRING'"); - printf (" %s\n", _("command to execute on the remote machine")); - printf (" %s\n","-l, --logname=USERNAME"); - printf (" %s\n", _("SSH user name on remote host [optional]")); - printf (" %s\n","-i, --identity=KEYFILE"); - printf (" %s\n", _("identity of an authorized key [optional]")); - printf (" %s\n","-O, --output=FILE"); - printf (" %s\n", _("external command file for monitoring [optional]")); - printf (" %s\n","-s, --services=LIST"); - printf (" %s\n", _("list of monitoring service names, separated by ':' [optional]")); - printf (" %s\n","-n, --name=NAME"); - printf (" %s\n", _("short name of host in the monitoring configuration [optional]")); - printf (" %s\n","-o, --ssh-option=OPTION"); - printf (" %s\n", _("Call ssh with '-o OPTION' (may be used multiple times) [optional]")); - printf (" %s\n","-F, --configfile"); - printf (" %s\n", _("Tell ssh to use this configfile [optional]")); - printf (" %s\n","-q, --quiet"); - printf (" %s\n", _("Tell ssh to suppress warning and diagnostic messages [optional]")); - printf (UT_WARN_CRIT); - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - printf (" %s\n","-U, --unknown-timeout"); - printf (" %s\n", _("Make connection problems return UNKNOWN instead of CRITICAL")); - printf (UT_VERBOSE); +void print_help(void) { + print_revision(progname, NP_VERSION); + + printf("Copyright (c) 1999 Karl DeBisschop \n"); + printf(COPYRIGHT, copyright, email); + + printf(_("This plugin uses SSH to execute commands on a remote host")); + + printf("\n\n"); + + print_usage(); + + printf(UT_HELP_VRSN); + + printf(UT_EXTRA_OPTS); + + printf(UT_HOST_PORT, 'p', "none"); + + printf(UT_IPv46); + + printf(" %s\n", "-1, --proto1"); + printf(" %s\n", _("tell ssh to use Protocol 1 [optional]")); + printf(" %s\n", "-2, --proto2"); + printf(" %s\n", _("tell ssh to use Protocol 2 [optional]")); + printf(" %s\n", "-S, --skip-stdout[=n]"); + printf(" %s\n", _("Ignore all or (if specified) first n lines on STDOUT [optional]")); + printf(" %s\n", "-E, --skip-stderr[=n]"); + printf(" %s\n", _("Ignore all or (if specified) first n lines on STDERR [optional]")); + printf(" %s\n", "-W, --warn-on-stderr]"); + printf(" %s\n", _("Exit with an warning, if there is an output on STDERR")); + printf(" %s\n", "-f"); + printf(" %s\n", _("tells ssh to fork rather than create a tty [optional]. This will always return OK if ssh is executed")); + printf(" %s\n", "-C, --command='COMMAND STRING'"); + printf(" %s\n", _("command to execute on the remote machine")); + printf(" %s\n", "-l, --logname=USERNAME"); + printf(" %s\n", _("SSH user name on remote host [optional]")); + printf(" %s\n", "-i, --identity=KEYFILE"); + printf(" %s\n", _("identity of an authorized key [optional]")); + printf(" %s\n", "-O, --output=FILE"); + printf(" %s\n", _("external command file for monitoring [optional]")); + printf(" %s\n", "-s, --services=LIST"); + printf(" %s\n", _("list of monitoring service names, separated by ':' [optional]")); + printf(" %s\n", "-n, --name=NAME"); + printf(" %s\n", _("short name of host in the monitoring configuration [optional]")); + printf(" %s\n", "-o, --ssh-option=OPTION"); + printf(" %s\n", _("Call ssh with '-o OPTION' (may be used multiple times) [optional]")); + printf(" %s\n", "-F, --configfile"); + printf(" %s\n", _("Tell ssh to use this configfile [optional]")); + printf(" %s\n", "-q, --quiet"); + printf(" %s\n", _("Tell ssh to suppress warning and diagnostic messages [optional]")); + printf(UT_WARN_CRIT); + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + printf(" %s\n", "-U, --unknown-timeout"); + printf(" %s\n", _("Make connection problems return UNKNOWN instead of CRITICAL")); + printf(UT_VERBOSE); + printf("\n"); + printf(" %s\n", _("The most common mode of use is to refer to a local identity file with")); + printf(" %s\n", _("the '-i' option. In this mode, the identity pair should have a null")); + printf(" %s\n", _("passphrase and the public key should be listed in the authorized_keys")); + printf(" %s\n", _("file of the remote host. Usually the key will be restricted to running")); + printf(" %s\n", _("only one command on the remote server. If the remote SSH server tracks")); + printf(" %s\n", _("invocation arguments, the one remote program may be an agent that can")); + printf(" %s\n", _("execute additional commands as proxy")); + printf("\n"); + printf(" %s\n", _("To use passive mode, provide multiple '-C' options, and provide")); + printf(" %s\n", _("all of -O, -s, and -n options (servicelist order must match '-C'options)")); printf("\n"); - printf (" %s\n", _("The most common mode of use is to refer to a local identity file with")); - printf (" %s\n", _("the '-i' option. In this mode, the identity pair should have a null")); - printf (" %s\n", _("passphrase and the public key should be listed in the authorized_keys")); - printf (" %s\n", _("file of the remote host. Usually the key will be restricted to running")); - printf (" %s\n", _("only one command on the remote server. If the remote SSH server tracks")); - printf (" %s\n", _("invocation arguments, the one remote program may be an agent that can")); - printf (" %s\n", _("execute additional commands as proxy")); - printf("\n"); - printf (" %s\n", _("To use passive mode, provide multiple '-C' options, and provide")); - printf (" %s\n", _("all of -O, -s, and -n options (servicelist order must match '-C'options)")); - printf ("\n"); - printf ("%s\n", _("Examples:")); - printf (" %s\n", "$ check_by_ssh -H localhost -n lh -s c1:c2:c3 -C uptime -C uptime -C uptime -O /tmp/foo"); - printf (" %s\n", "$ cat /tmp/foo"); - printf (" %s\n", "[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c1;0; up 2 days"); - printf (" %s\n", "[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c2;0; up 2 days"); - printf (" %s\n", "[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c3;0; up 2 days"); + printf("%s\n", _("Examples:")); + printf(" %s\n", "$ check_by_ssh -H localhost -n lh -s c1:c2:c3 -C uptime -C uptime -C uptime -O /tmp/foo"); + printf(" %s\n", "$ cat /tmp/foo"); + printf(" %s\n", "[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c1;0; up 2 days"); + printf(" %s\n", "[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c2;0; up 2 days"); + printf(" %s\n", "[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c3;0; up 2 days"); printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf (" %s -H -C [-fqvU] [-1|-2] [-4|-6]\n" - " [-S [lines]] [-E [lines]] [-W] [-t timeout] [-i identity]\n" - " [-l user] [-n name] [-s servicelist] [-O outputfile]\n" - " [-p port] [-o ssh-option] [-F configfile]\n", - progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf(" %s -H -C [-fqvU] [-1|-2] [-4|-6]\n" + " [-S [lines]] [-E [lines]] [-W] [-t timeout] [-i identity]\n" + " [-l user] [-n name] [-s servicelist] [-O outputfile]\n" + " [-p port] [-o ssh-option] [-F configfile]\n", + progname); } -- cgit v0.10-9-g596f From 744568f1f804f6676358a4ad654e4319598cebdf Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:44:09 +0100 Subject: check_by_ssh: Copyright update diff --git a/plugins/check_by_ssh.c b/plugins/check_by_ssh.c index 35aa1b8..4bcac00 100644 --- a/plugins/check_by_ssh.c +++ b/plugins/check_by_ssh.c @@ -3,7 +3,7 @@ * Monitoring check_by_ssh plugin * * License: GPL - * Copyright (c) 2000-2008 Monitoring Plugins Development Team + * Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -27,7 +27,7 @@ *****************************************************************************/ const char *progname = "check_by_ssh"; -const char *copyright = "2000-2008"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From ba47cca3ef026209868da044741554cbb6c2bb3b Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:45:58 +0100 Subject: check_by_ssh: do not export local symbols diff --git a/plugins/check_by_ssh.c b/plugins/check_by_ssh.c index 4bcac00..598e046 100644 --- a/plugins/check_by_ssh.c +++ b/plugins/check_by_ssh.c @@ -39,27 +39,27 @@ const char *email = "devel@monitoring-plugins.org"; # define NP_MAXARGS 1024 #endif -int process_arguments(int, char **); -int validate_arguments(void); -void comm_append(const char *); -void print_help(void); +static int process_arguments(int, char **); +static int validate_arguments(void); +static void comm_append(const char *); +static void print_help(void); void print_usage(void); -unsigned int commands = 0; -unsigned int services = 0; -int skip_stdout = 0; -int skip_stderr = 0; -int warn_on_stderr = 0; -bool unknown_timeout = false; -char *remotecmd = NULL; -char **commargv = NULL; -int commargc = 0; -char *hostname = NULL; -char *outputfile = NULL; -char *host_shortname = NULL; -char **service; -bool passive = false; -bool verbose = false; +static unsigned int commands = 0; +static unsigned int services = 0; +static int skip_stdout = 0; +static int skip_stderr = 0; +static int warn_on_stderr = 0; +static bool unknown_timeout = false; +static char *remotecmd = NULL; +static char **commargv = NULL; +static int commargc = 0; +static char *hostname = NULL; +static char *outputfile = NULL; +static char *host_shortname = NULL; +static char **service; +static bool passive = false; +static bool verbose = false; int main(int argc, char **argv) { -- cgit v0.10-9-g596f From 060bd01d89a6da0a5a7c3c1779c98a2b2c8c0c53 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:50:34 +0100 Subject: check_by_ssh: linter fixes diff --git a/plugins/check_by_ssh.c b/plugins/check_by_ssh.c index 598e046..905b239 100644 --- a/plugins/check_by_ssh.c +++ b/plugins/check_by_ssh.c @@ -39,9 +39,9 @@ const char *email = "devel@monitoring-plugins.org"; # define NP_MAXARGS 1024 #endif -static int process_arguments(int, char **); +static int process_arguments(int /*argc*/, char ** /*argv*/); static int validate_arguments(void); -static void comm_append(const char *); +static void comm_append(const char * /*str*/); static void print_help(void); void print_usage(void); @@ -67,8 +67,9 @@ int main(int argc, char **argv) { int cresult; int result = STATE_UNKNOWN; time_t local_time; - FILE *fp = NULL; - output chld_out, chld_err; + FILE *file_pointer = NULL; + output chld_out; + output chld_err; remotecmd = ""; comm_append(SSH_COMMAND); @@ -122,8 +123,7 @@ int main(int argc, char **argv) { printf(_("Remote command execution failed: %s\n"), chld_err.line[skip_stderr]); if (warn_on_stderr) return max_state_alt(result, STATE_WARNING); - else - return max_state_alt(result, STATE_UNKNOWN); + return max_state_alt(result, STATE_UNKNOWN); } /* this is simple if we're not supposed to be passive. @@ -142,7 +142,7 @@ int main(int argc, char **argv) { */ /* process output */ - if (!(fp = fopen(outputfile, "a"))) { + if (!(file_pointer = fopen(outputfile, "a"))) { printf(_("SSH WARNING: could not open %s\n"), outputfile); exit(STATE_UNKNOWN); } @@ -155,8 +155,8 @@ int main(int argc, char **argv) { die(STATE_UNKNOWN, _("%s: Error parsing output\n"), progname); if (service[commands] && status_text && sscanf(chld_out.line[i], "STATUS CODE: %d", &cresult) == 1) { - fprintf(fp, "[%d] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%d;%s\n", (int)local_time, host_shortname, service[commands++], cresult, - status_text); + fprintf(file_pointer, "[%d] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%d;%s\n", (int)local_time, host_shortname, service[commands++], + cresult, status_text); } } @@ -167,7 +167,8 @@ int main(int argc, char **argv) { /* process command-line arguments */ int process_arguments(int argc, char **argv) { int c; - char *p1, *p2; + char *p1; + char *p2; int option = 0; static struct option longopts[] = {{"version", no_argument, 0, 'V'}, -- cgit v0.10-9-g596f From 80ec3f0f046384399d4850b06806815cbc5cc7c9 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:51:49 +0100 Subject: check_cluster: clang-format diff --git a/plugins/check_cluster.c b/plugins/check_cluster.c index e1ede9f..aa55528 100644 --- a/plugins/check_cluster.c +++ b/plugins/check_cluster.c @@ -1,26 +1,26 @@ /***************************************************************************** -* -* check_cluster.c - Host and Service Cluster Plugin for Monitoring -* -* License: GPL -* Copyright (c) 2000-2004 Ethan Galstad (nagios@nagios.org) -* Copyright (c) 2007 Monitoring Plugins Development Team -* -* 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 . -* -* -*****************************************************************************/ + * + * check_cluster.c - Host and Service Cluster Plugin for Monitoring + * + * License: GPL + * Copyright (c) 2000-2004 Ethan Galstad (nagios@nagios.org) + * Copyright (c) 2007 Monitoring Plugins Development Team + * + * 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_cluster"; const char *copyright = "2000-2007"; @@ -30,63 +30,61 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #include "utils_base.h" -#define CHECK_SERVICES 1 -#define CHECK_HOSTS 2 +#define CHECK_SERVICES 1 +#define CHECK_HOSTS 2 -void print_help (void); -void print_usage (void); +void print_help(void); +void print_usage(void); -int total_services_ok=0; -int total_services_warning=0; -int total_services_unknown=0; -int total_services_critical=0; +int total_services_ok = 0; +int total_services_warning = 0; +int total_services_unknown = 0; +int total_services_critical = 0; -int total_hosts_up=0; -int total_hosts_down=0; -int total_hosts_unreachable=0; +int total_hosts_up = 0; +int total_hosts_down = 0; +int total_hosts_unreachable = 0; char *warn_threshold; char *crit_threshold; -int check_type=CHECK_SERVICES; +int check_type = CHECK_SERVICES; -char *data_vals=NULL; -char *label=NULL; +char *data_vals = NULL; +char *label = NULL; -int verbose=0; +int verbose = 0; -int process_arguments(int,char **); +int process_arguments(int, char **); - - -int main(int argc, char **argv){ +int main(int argc, char **argv) { char *ptr; int data_val; - int return_code=STATE_OK; + int return_code = STATE_OK; thresholds *thresholds = NULL; - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Parse extra opts if any */ - argv=np_extra_opts(&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if(process_arguments(argc,argv)==ERROR) + if (process_arguments(argc, argv) == ERROR) usage(_("Could not parse arguments")); /* Initialize the thresholds */ set_thresholds(&thresholds, warn_threshold, crit_threshold); - if(verbose) + if (verbose) print_thresholds("check_cluster", thresholds); /* check the data values */ - for(ptr=strtok(data_vals,",");ptr!=NULL;ptr=strtok(NULL,",")){ + for (ptr = strtok(data_vals, ","); ptr != NULL; ptr = strtok(NULL, ",")) { - data_val=atoi(ptr); + data_val = atoi(ptr); - if(check_type==CHECK_SERVICES){ - switch(data_val){ + if (check_type == CHECK_SERVICES) { + switch (data_val) { case 0: total_services_ok++; break; @@ -101,10 +99,9 @@ int main(int argc, char **argv){ break; default: break; - } - } - else{ - switch(data_val){ + } + } else { + switch (data_val) { case 0: total_hosts_up++; break; @@ -116,67 +113,54 @@ int main(int argc, char **argv){ break; default: break; - } - } - } - + } + } + } /* return the status of the cluster */ - if(check_type==CHECK_SERVICES){ - return_code=get_status(total_services_warning+total_services_unknown+total_services_critical, thresholds); - printf("CLUSTER %s: %s: %d ok, %d warning, %d unknown, %d critical\n", - state_text(return_code), (label==NULL)?"Service cluster":label, - total_services_ok,total_services_warning, - total_services_unknown,total_services_critical); - } - else{ - return_code=get_status(total_hosts_down+total_hosts_unreachable, thresholds); - printf("CLUSTER %s: %s: %d up, %d down, %d unreachable\n", - state_text(return_code), (label==NULL)?"Host cluster":label, - total_hosts_up,total_hosts_down,total_hosts_unreachable); + if (check_type == CHECK_SERVICES) { + return_code = get_status(total_services_warning + total_services_unknown + total_services_critical, thresholds); + printf("CLUSTER %s: %s: %d ok, %d warning, %d unknown, %d critical\n", state_text(return_code), + (label == NULL) ? "Service cluster" : label, total_services_ok, total_services_warning, total_services_unknown, + total_services_critical); + } else { + return_code = get_status(total_hosts_down + total_hosts_unreachable, thresholds); + printf("CLUSTER %s: %s: %d up, %d down, %d unreachable\n", state_text(return_code), (label == NULL) ? "Host cluster" : label, + total_hosts_up, total_hosts_down, total_hosts_unreachable); } return return_code; } - - -int process_arguments(int argc, char **argv){ +int process_arguments(int argc, char **argv) { int c; char *ptr; - int option=0; - static struct option longopts[]={ - {"data", required_argument,0,'d'}, - {"warning", required_argument,0,'w'}, - {"critical", required_argument,0,'c'}, - {"label", required_argument,0,'l'}, - {"host", no_argument, 0,'h'}, - {"service", no_argument, 0,'s'}, - {"verbose", no_argument, 0,'v'}, - {"version", no_argument, 0,'V'}, - {"help", no_argument, 0,'H'}, - {0,0,0,0} - }; + int option = 0; + static struct option longopts[] = {{"data", required_argument, 0, 'd'}, {"warning", required_argument, 0, 'w'}, + {"critical", required_argument, 0, 'c'}, {"label", required_argument, 0, 'l'}, + {"host", no_argument, 0, 'h'}, {"service", no_argument, 0, 's'}, + {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'H'}, {0, 0, 0, 0}}; /* no options were supplied */ - if(argc<2) + if (argc < 2) return ERROR; - while(1){ + while (1) { - c=getopt_long(argc,argv,"hHsvVw:c:d:l:",longopts,&option); + c = getopt_long(argc, argv, "hHsvVw:c:d:l:", longopts, &option); - if(c==-1 || c==EOF || c==1) + if (c == -1 || c == EOF || c == 1) break; - switch(c){ + switch (c) { case 'h': /* host cluster */ - check_type=CHECK_HOSTS; + check_type = CHECK_HOSTS; break; case 's': /* service cluster */ - check_type=CHECK_SERVICES; + check_type = CHECK_SERVICES; break; case 'w': /* warning threshold */ @@ -188,20 +172,20 @@ int process_arguments(int argc, char **argv){ break; case 'd': /* data values */ - data_vals=(char *)strdup(optarg); + data_vals = (char *)strdup(optarg); /* validate data */ - for (ptr=data_vals;ptr!=NULL;ptr+=2){ - if (ptr[0]<'0' || ptr[0]>'3') + for (ptr = data_vals; ptr != NULL; ptr += 2) { + if (ptr[0] < '0' || ptr[0] > '3') return ERROR; - if (ptr[1]=='\0') + if (ptr[1] == '\0') break; - if (ptr[1]!=',') + if (ptr[1] != ',') return ERROR; } break; case 'l': /* text label */ - label=(char *)strdup(optarg); + label = (char *)strdup(optarg); break; case 'v': /* verbose */ @@ -209,8 +193,8 @@ int process_arguments(int argc, char **argv){ break; case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); break; case 'H': /* help */ @@ -221,20 +205,18 @@ int process_arguments(int argc, char **argv){ default: return ERROR; break; - } + } } - if(data_vals==NULL) + if (data_vals == NULL) return ERROR; return OK; } -void -print_help(void) -{ +void print_help(void) { print_revision(progname, NP_VERSION); - printf ("Copyright (c) 2000-2004 Ethan Galstad (nagios@nagios.org)\n"); + printf("Copyright (c) 2000-2004 Ethan Galstad (nagios@nagios.org)\n"); printf(COPYRIGHT, copyright, email); printf(_("Host/Service Cluster Plugin for Monitoring")); @@ -245,21 +227,21 @@ print_help(void) printf("\n"); printf("%s\n", _("Options:")); printf(UT_EXTRA_OPTS); - printf (" %s\n", "-s, --service"); - printf (" %s\n", _("Check service cluster status")); - printf (" %s\n", "-h, --host"); - printf (" %s\n", _("Check host cluster status")); - printf (" %s\n", "-l, --label=STRING"); - printf (" %s\n", _("Optional prepended text output (i.e. \"Host cluster\")")); - printf (" %s\n", "-w, --warning=THRESHOLD"); - printf (" %s\n", _("Specifies the range of hosts or services in cluster that must be in a")); - printf (" %s\n", _("non-OK state in order to return a WARNING status level")); - printf (" %s\n", "-c, --critical=THRESHOLD"); - printf (" %s\n", _("Specifies the range of hosts or services in cluster that must be in a")); - printf (" %s\n", _("non-OK state in order to return a CRITICAL status level")); - printf (" %s\n", "-d, --data=LIST"); - printf (" %s\n", _("The status codes of the hosts or services in the cluster, separated by")); - printf (" %s\n", _("commas")); + printf(" %s\n", "-s, --service"); + printf(" %s\n", _("Check service cluster status")); + printf(" %s\n", "-h, --host"); + printf(" %s\n", _("Check host cluster status")); + printf(" %s\n", "-l, --label=STRING"); + printf(" %s\n", _("Optional prepended text output (i.e. \"Host cluster\")")); + printf(" %s\n", "-w, --warning=THRESHOLD"); + printf(" %s\n", _("Specifies the range of hosts or services in cluster that must be in a")); + printf(" %s\n", _("non-OK state in order to return a WARNING status level")); + printf(" %s\n", "-c, --critical=THRESHOLD"); + printf(" %s\n", _("Specifies the range of hosts or services in cluster that must be in a")); + printf(" %s\n", _("non-OK state in order to return a CRITICAL status level")); + printf(" %s\n", "-d, --data=LIST"); + printf(" %s\n", _("The status codes of the hosts or services in the cluster, separated by")); + printf(" %s\n", _("commas")); printf(UT_VERBOSE); @@ -267,23 +249,18 @@ print_help(void) printf("%s\n", _("Notes:")); printf(UT_THRESHOLDS_NOTES); - printf ("\n"); - printf ("%s\n", _("Examples:")); - printf (" %s\n", "check_cluster -s -d 2,0,2,0 -c @3:"); - printf (" %s\n", _("Will alert critical if there are 3 or more service data points in a non-OK") ); - printf (" %s\n", _("state.") ); + printf("\n"); + printf("%s\n", _("Examples:")); + printf(" %s\n", "check_cluster -s -d 2,0,2,0 -c @3:"); + printf(" %s\n", _("Will alert critical if there are 3 or more service data points in a non-OK")); + printf(" %s\n", _("state.")); printf(UT_SUPPORT); } - -void -print_usage(void) -{ +void print_usage(void) { printf("%s\n", _("Usage:")); printf(" %s (-s | -h) -d val1[,val2,...,valn] [-l label]\n", progname); printf("[-w threshold] [-c threshold] [-v] [--help]\n"); - } - -- cgit v0.10-9-g596f From a30f0c6c08f90de8abe6ca277e98102aa4d6950c Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:53:01 +0100 Subject: check_cluster: Copyright update diff --git a/plugins/check_cluster.c b/plugins/check_cluster.c index aa55528..6ca43c6 100644 --- a/plugins/check_cluster.c +++ b/plugins/check_cluster.c @@ -4,7 +4,7 @@ * * License: GPL * Copyright (c) 2000-2004 Ethan Galstad (nagios@nagios.org) - * Copyright (c) 2007 Monitoring Plugins Development Team + * Copyright (c) 2007-2024 Monitoring Plugins Development Team * * 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 @@ -23,7 +23,7 @@ *****************************************************************************/ const char *progname = "check_cluster"; -const char *copyright = "2000-2007"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From ebb453f55ef6e64033ac50341963eb49cf457796 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:54:48 +0100 Subject: check_cluster: do not export local symbols diff --git a/plugins/check_cluster.c b/plugins/check_cluster.c index 6ca43c6..0afb3f4 100644 --- a/plugins/check_cluster.c +++ b/plugins/check_cluster.c @@ -33,29 +33,29 @@ const char *email = "devel@monitoring-plugins.org"; #define CHECK_SERVICES 1 #define CHECK_HOSTS 2 -void print_help(void); +static void print_help(void); void print_usage(void); -int total_services_ok = 0; -int total_services_warning = 0; -int total_services_unknown = 0; -int total_services_critical = 0; +static int total_services_ok = 0; +static int total_services_warning = 0; +static int total_services_unknown = 0; +static int total_services_critical = 0; -int total_hosts_up = 0; -int total_hosts_down = 0; -int total_hosts_unreachable = 0; +static int total_hosts_up = 0; +static int total_hosts_down = 0; +static int total_hosts_unreachable = 0; -char *warn_threshold; -char *crit_threshold; +static char *warn_threshold; +static char *crit_threshold; -int check_type = CHECK_SERVICES; +static int check_type = CHECK_SERVICES; -char *data_vals = NULL; -char *label = NULL; +static char *data_vals = NULL; +static char *label = NULL; -int verbose = 0; +static int verbose = 0; -int process_arguments(int, char **); +static int process_arguments(int, char **); int main(int argc, char **argv) { char *ptr; -- cgit v0.10-9-g596f From 289f07d754554191d202684b7664f9012c662f10 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:57:07 +0100 Subject: check_cluster: linter fixes diff --git a/plugins/check_cluster.c b/plugins/check_cluster.c index 0afb3f4..b40c38c 100644 --- a/plugins/check_cluster.c +++ b/plugins/check_cluster.c @@ -30,8 +30,10 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #include "utils_base.h" -#define CHECK_SERVICES 1 -#define CHECK_HOSTS 2 +enum { + CHECK_SERVICES = 1, + CHECK_HOSTS = 2 +}; static void print_help(void); void print_usage(void); @@ -55,7 +57,7 @@ static char *label = NULL; static int verbose = 0; -static int process_arguments(int, char **); +static int process_arguments(int /*argc*/, char ** /*argv*/); int main(int argc, char **argv) { char *ptr; -- cgit v0.10-9-g596f From 80f07ff92b73d24614c0d3d15021f115bf85b152 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:58:41 +0100 Subject: check_curl: clang-format diff --git a/plugins/check_curl.c b/plugins/check_curl.c index d3bddac..8936110 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -1,37 +1,37 @@ /***************************************************************************** -* -* Monitoring check_curl plugin -* -* License: GPL -* Copyright (c) 1999-2019 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_curl 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 plugin uses functions from the curl library, see -* http://curl.haxx.se -* -* 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_curl plugin + * + * License: GPL + * Copyright (c) 1999-2019 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_curl 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 plugin uses functions from the curl library, see + * http://curl.haxx.se + * + * 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_curl"; const char *copyright = "2006-2019"; @@ -44,7 +44,7 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #ifndef LIBCURL_PROTOCOL_HTTP -#error libcurl compiled without HTTP support, compiling check_curl plugin does not makes a lot of sense +# error libcurl compiled without HTTP support, compiling check_curl plugin does not makes a lot of sense #endif #include "curl/curl.h" @@ -58,7 +58,7 @@ const char *email = "devel@monitoring-plugins.org"; #include #if defined(HAVE_SSL) && defined(USE_OPENSSL) -#include +# include #endif #include @@ -66,66 +66,66 @@ const char *email = "devel@monitoring-plugins.org"; #define MAKE_LIBCURL_VERSION(major, minor, patch) ((major)*0x10000 + (minor)*0x100 + (patch)) #define DEFAULT_BUFFER_SIZE 2048 -#define DEFAULT_SERVER_URL "/" -#define HTTP_EXPECT "HTTP/" -#define INET_ADDR_MAX_SIZE INET6_ADDRSTRLEN +#define DEFAULT_SERVER_URL "/" +#define HTTP_EXPECT "HTTP/" +#define INET_ADDR_MAX_SIZE INET6_ADDRSTRLEN enum { - MAX_IPV4_HOSTLENGTH = 255, - HTTP_PORT = 80, - HTTPS_PORT = 443, - MAX_PORT = 65535, - DEFAULT_MAX_REDIRS = 15 + MAX_IPV4_HOSTLENGTH = 255, + HTTP_PORT = 80, + HTTPS_PORT = 443, + MAX_PORT = 65535, + DEFAULT_MAX_REDIRS = 15 }; enum { - STICKY_NONE = 0, - STICKY_HOST = 1, - STICKY_PORT = 2 + STICKY_NONE = 0, + STICKY_HOST = 1, + STICKY_PORT = 2 }; enum { - FOLLOW_HTTP_CURL = 0, - FOLLOW_LIBCURL = 1 + FOLLOW_HTTP_CURL = 0, + FOLLOW_LIBCURL = 1 }; /* for buffers for header and body */ typedef struct { - char *buf; - size_t buflen; - size_t bufsize; + char *buf; + size_t buflen; + size_t bufsize; } curlhelp_write_curlbuf; /* for buffering the data sent in PUT */ typedef struct { - char *buf; - size_t buflen; - off_t pos; + char *buf; + size_t buflen; + off_t pos; } curlhelp_read_curlbuf; /* for parsing the HTTP status line */ typedef struct { - int http_major; /* major version of the protocol, always 1 (HTTP/0.9 - * never reached the big internet most likely) */ - int http_minor; /* minor version of the protocol, usually 0 or 1 */ - int http_code; /* HTTP return code as in RFC 2145 */ - int http_subcode; /* Microsoft IIS extension, HTTP subcodes, see - * http://support.microsoft.com/kb/318380/en-us */ - const char *msg; /* the human readable message */ - char *first_line; /* a copy of the first line */ + int http_major; /* major version of the protocol, always 1 (HTTP/0.9 + * never reached the big internet most likely) */ + int http_minor; /* minor version of the protocol, usually 0 or 1 */ + int http_code; /* HTTP return code as in RFC 2145 */ + int http_subcode; /* Microsoft IIS extension, HTTP subcodes, see + * http://support.microsoft.com/kb/318380/en-us */ + const char *msg; /* the human readable message */ + char *first_line; /* a copy of the first line */ } curlhelp_statusline; /* to know the underlying SSL library used by libcurl */ typedef enum curlhelp_ssl_library { - CURLHELP_SSL_LIBRARY_UNKNOWN, - CURLHELP_SSL_LIBRARY_OPENSSL, - CURLHELP_SSL_LIBRARY_LIBRESSL, - CURLHELP_SSL_LIBRARY_GNUTLS, - CURLHELP_SSL_LIBRARY_NSS + CURLHELP_SSL_LIBRARY_UNKNOWN, + CURLHELP_SSL_LIBRARY_OPENSSL, + CURLHELP_SSL_LIBRARY_LIBRESSL, + CURLHELP_SSL_LIBRARY_GNUTLS, + CURLHELP_SSL_LIBRARY_NSS } curlhelp_ssl_library; enum { - REGS = 2, - MAX_RE_SIZE = 1024 + REGS = 2, + MAX_RE_SIZE = 1024 }; #include "regex.h" regex_t preg; @@ -204,8 +204,8 @@ 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; + struct curl_slist *to_info; + struct curl_certinfo *to_certinfo; } cert_ptr_union; cert_ptr_union cert_ptr; int ssl_version = CURL_SSLVERSION_DEFAULT; @@ -227,946 +227,889 @@ bool automatic_decompression = false; char *cookie_jar_file = NULL; bool haproxy_protocol = false; -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*); -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); -void print_curl_version (void); -int curlhelp_initwritebuffer (curlhelp_write_curlbuf*); -size_t curlhelp_buffer_write_callback(void*, size_t , size_t , void*); -void curlhelp_freewritebuffer (curlhelp_write_curlbuf*); -int curlhelp_initreadbuffer (curlhelp_read_curlbuf *, const char *, size_t); -size_t curlhelp_buffer_read_callback(void *, size_t , size_t , void *); -void curlhelp_freereadbuffer (curlhelp_read_curlbuf *); -curlhelp_ssl_library curlhelp_get_ssl_library (); -const char* curlhelp_get_ssl_library_string (curlhelp_ssl_library); -int net_noopenssl_check_certificate (cert_ptr_union*, int, int); - -int curlhelp_parse_statusline (const char*, curlhelp_statusline *); -void curlhelp_free_statusline (curlhelp_statusline *); -char *get_header_value (const struct phr_header* headers, const size_t nof_headers, const char* header); -int check_document_dates (const curlhelp_write_curlbuf *, char (*msg)[DEFAULT_BUFFER_SIZE]); -int get_content_length (const curlhelp_write_curlbuf* header_buf, const curlhelp_write_curlbuf* body_buf); +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 *); +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); +void print_curl_version(void); +int curlhelp_initwritebuffer(curlhelp_write_curlbuf *); +size_t curlhelp_buffer_write_callback(void *, size_t, size_t, void *); +void curlhelp_freewritebuffer(curlhelp_write_curlbuf *); +int curlhelp_initreadbuffer(curlhelp_read_curlbuf *, const char *, size_t); +size_t curlhelp_buffer_read_callback(void *, size_t, size_t, void *); +void curlhelp_freereadbuffer(curlhelp_read_curlbuf *); +curlhelp_ssl_library curlhelp_get_ssl_library(); +const char *curlhelp_get_ssl_library_string(curlhelp_ssl_library); +int net_noopenssl_check_certificate(cert_ptr_union *, int, int); + +int curlhelp_parse_statusline(const char *, curlhelp_statusline *); +void curlhelp_free_statusline(curlhelp_statusline *); +char *get_header_value(const struct phr_header *headers, const size_t nof_headers, const char *header); +int check_document_dates(const curlhelp_write_curlbuf *, char (*msg)[DEFAULT_BUFFER_SIZE]); +int get_content_length(const curlhelp_write_curlbuf *header_buf, const curlhelp_write_curlbuf *body_buf); #if defined(HAVE_SSL) && defined(USE_OPENSSL) int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int days_till_exp_crit); #endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */ -void remove_newlines (char *); -void test_file (char *); +void remove_newlines(char *); +void test_file(char *); -int -main (int argc, char **argv) -{ - int result = STATE_UNKNOWN; +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); - /* Parse extra opts if any */ - argv = np_extra_opts (&argc, argv, progname); + /* Parse extra opts if any */ + argv = np_extra_opts(&argc, argv, progname); - /* set defaults */ - snprintf( user_agent, DEFAULT_BUFFER_SIZE, "%s/v%s (monitoring-plugins %s, %s)", - progname, NP_VERSION, VERSION, curl_version()); + /* set defaults */ + snprintf(user_agent, DEFAULT_BUFFER_SIZE, "%s/v%s (monitoring-plugins %s, %s)", progname, NP_VERSION, VERSION, curl_version()); - /* parse arguments */ - if (process_arguments (argc, argv) == false) - usage4 (_("Could not parse arguments")); + /* parse arguments */ + if (process_arguments(argc, argv) == false) + usage4(_("Could not parse arguments")); - if (display_html) - printf ("", - use_ssl ? "https" : "http", - host_name ? host_name : server_address, - virtual_port ? virtual_port : server_port, - server_url); + if (display_html) + printf("", use_ssl ? "https" : "http", host_name ? host_name : server_address, + virtual_port ? virtual_port : server_port, server_url); - result = check_http (); - return result; + result = check_http(); + return result; } #ifdef HAVE_SSL -#ifdef USE_OPENSSL - -int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) -{ - (void) preverify_ok; - /* TODO: we get all certificates of the chain, so which ones - * should we test? - * TODO: is the last certificate always the server certificate? - */ - cert = X509_STORE_CTX_get_current_cert(x509_ctx); -#if OPENSSL_VERSION_NUMBER >= 0x10100000L - X509_up_ref(cert); -#endif - if (verbose>=2) { - puts("* SSL verify callback with certificate:"); - X509_NAME *subject, *issuer; - printf("* issuer:\n"); - issuer = X509_get_issuer_name( cert ); - X509_NAME_print_ex_fp(stdout, issuer, 5, XN_FLAG_MULTILINE); - printf("* curl verify_callback:\n* subject:\n"); - subject = X509_get_subject_name( cert ); - X509_NAME_print_ex_fp(stdout, subject, 5, XN_FLAG_MULTILINE); - puts(""); - } - return 1; +# ifdef USE_OPENSSL + +int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) { + (void)preverify_ok; + /* TODO: we get all certificates of the chain, so which ones + * should we test? + * TODO: is the last certificate always the server certificate? + */ + cert = X509_STORE_CTX_get_current_cert(x509_ctx); +# if OPENSSL_VERSION_NUMBER >= 0x10100000L + X509_up_ref(cert); +# endif + if (verbose >= 2) { + puts("* SSL verify callback with certificate:"); + X509_NAME *subject, *issuer; + printf("* issuer:\n"); + issuer = X509_get_issuer_name(cert); + X509_NAME_print_ex_fp(stdout, issuer, 5, XN_FLAG_MULTILINE); + printf("* curl verify_callback:\n* subject:\n"); + subject = X509_get_subject_name(cert); + X509_NAME_print_ex_fp(stdout, subject, 5, XN_FLAG_MULTILINE); + puts(""); + } + return 1; } -CURLcode sslctxfun(CURL *curl, SSL_CTX *sslctx, void *parm) -{ - (void) curl; // ignore unused parameter - (void) parm; // ignore unused parameter - if(add_sslctx_verify_fun) { - SSL_CTX_set_verify(sslctx, SSL_VERIFY_PEER, verify_callback); - } - - // workaround for issue: - // OpenSSL SSL_read: error:0A000126:SSL routines::unexpected eof while reading, errno 0 - // see discussion https://github.com/openssl/openssl/discussions/22690 -#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF - SSL_CTX_set_options(sslctx, SSL_OP_IGNORE_UNEXPECTED_EOF); -#endif +CURLcode sslctxfun(CURL *curl, SSL_CTX *sslctx, void *parm) { + (void)curl; // ignore unused parameter + (void)parm; // ignore unused parameter + if (add_sslctx_verify_fun) { + SSL_CTX_set_verify(sslctx, SSL_VERIFY_PEER, verify_callback); + } + + // workaround for issue: + // OpenSSL SSL_read: error:0A000126:SSL routines::unexpected eof while reading, errno 0 + // see discussion https://github.com/openssl/openssl/discussions/22690 +# ifdef SSL_OP_IGNORE_UNEXPECTED_EOF + SSL_CTX_set_options(sslctx, SSL_OP_IGNORE_UNEXPECTED_EOF); +# endif - return CURLE_OK; + return CURLE_OK; } -#endif /* USE_OPENSSL */ -#endif /* HAVE_SSL */ +# endif /* USE_OPENSSL */ +#endif /* HAVE_SSL */ /* returns a string "HTTP/1.x" or "HTTP/2" */ -static char *string_statuscode (int major, int minor) -{ - static char buf[10]; - - switch (major) { - case 1: - snprintf (buf, sizeof (buf), "HTTP/%d.%d", major, minor); - break; - case 2: - case 3: - snprintf (buf, sizeof (buf), "HTTP/%d", major); - break; - default: - /* assuming here HTTP/N with N>=4 */ - snprintf (buf, sizeof (buf), "HTTP/%d", major); - break; - } - - return buf; +static char *string_statuscode(int major, int minor) { + static char buf[10]; + + switch (major) { + case 1: + snprintf(buf, sizeof(buf), "HTTP/%d.%d", major, minor); + break; + case 2: + case 3: + snprintf(buf, sizeof(buf), "HTTP/%d", major); + break; + default: + /* assuming here HTTP/N with N>=4 */ + snprintf(buf, sizeof(buf), "HTTP/%d", major); + break; + } + + return buf; } /* Checks if the server 'reply' is one of the expected 'statuscodes' */ -static int -expected_statuscode (const char *reply, const char *statuscodes) -{ - char *expected, *code; - int result = 0; - - 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) { - result = 1; - break; - } - - free (expected); - return result; +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")); + + for (code = strtok(expected, ","); code != NULL; code = strtok(NULL, ",")) + if (strstr(reply, code) != NULL) { + result = 1; + break; + } + + free(expected); + return result; } -void -handle_curl_option_return_code (CURLcode res, const char* option) -{ - if (res != CURLE_OK) { - snprintf (msg, - DEFAULT_BUFFER_SIZE, - _("Error while setting cURL option '%s': cURL returned %d - %s"), - option, - res, - curl_easy_strerror(res)); - die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); - } +void handle_curl_option_return_code(CURLcode res, const char *option) { + if (res != CURLE_OK) { + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Error while setting cURL option '%s': cURL returned %d - %s"), option, res, + curl_easy_strerror(res)); + die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); + } } -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 = { 0 }; - size_t buflen_remaining = buflen - 1; - - memset (&hints, 0, sizeof (hints)); - hints.ai_family = address_family; - hints.ai_socktype = SOCK_STREAM; - hints.ai_flags |= AI_CANONNAME; - - errcode = getaddrinfo (host, NULL, &hints, &result); - if (errcode != 0) - return errcode; - - strcpy(buf, ""); - res = result; - - while (res) { - switch (res->ai_family) { - case AF_INET: - ptr = &((struct sockaddr_in *) res->ai_addr)->sin_addr; - break; - case AF_INET6: - ptr = &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr; - break; - } - - inet_ntop (res->ai_family, ptr, addrstr, 100); - if (verbose >= 1) { - printf ("* getaddrinfo IPv%d address: %s\n", - res->ai_family == PF_INET6 ? 6 : 4, addrstr); - } - - // Append all IPs to buf as a comma-separated string - addrstr_len = strlen(addrstr); - if (buflen_remaining > addrstr_len + 1) { - if (buf[0] != '\0') { - strncat(buf, ",", buflen_remaining); - buflen_remaining -= 1; - } - strncat(buf, addrstr, buflen_remaining); - buflen_remaining -= addrstr_len; - } - - res = res->ai_next; - } - - freeaddrinfo(result); - - return 0; +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 = {0}; + size_t buflen_remaining = buflen - 1; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = address_family; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags |= AI_CANONNAME; + + errcode = getaddrinfo(host, NULL, &hints, &result); + if (errcode != 0) + return errcode; + + strcpy(buf, ""); + res = result; + + while (res) { + switch (res->ai_family) { + case AF_INET: + ptr = &((struct sockaddr_in *)res->ai_addr)->sin_addr; + break; + case AF_INET6: + ptr = &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr; + break; + } + + inet_ntop(res->ai_family, ptr, addrstr, 100); + if (verbose >= 1) { + printf("* getaddrinfo IPv%d address: %s\n", res->ai_family == PF_INET6 ? 6 : 4, addrstr); + } + + // Append all IPs to buf as a comma-separated string + addrstr_len = strlen(addrstr); + if (buflen_remaining > addrstr_len + 1) { + if (buf[0] != '\0') { + strncat(buf, ",", buflen_remaining); + buflen_remaining -= 1; + } + strncat(buf, addrstr, buflen_remaining); + buflen_remaining -= addrstr_len; + } + + res = res->ai_next; + } + + freeaddrinfo(result); + + return 0; } -static void -cleanup (void) -{ - if (status_line_initialized) curlhelp_free_statusline(&status_line); - status_line_initialized = false; - if (curl_easy_initialized) curl_easy_cleanup (curl); - curl_easy_initialized = false; - if (curl_global_initialized) curl_global_cleanup (); - curl_global_initialized = false; - if (body_buf_initialized) curlhelp_freewritebuffer (&body_buf); - body_buf_initialized = false; - if (header_buf_initialized) curlhelp_freewritebuffer (&header_buf); - header_buf_initialized = false; - if (put_buf_initialized) curlhelp_freereadbuffer (&put_buf); - put_buf_initialized = false; +static void cleanup(void) { + if (status_line_initialized) + curlhelp_free_statusline(&status_line); + status_line_initialized = false; + if (curl_easy_initialized) + curl_easy_cleanup(curl); + curl_easy_initialized = false; + if (curl_global_initialized) + curl_global_cleanup(); + curl_global_initialized = false; + if (body_buf_initialized) + curlhelp_freewritebuffer(&body_buf); + body_buf_initialized = false; + if (header_buf_initialized) + curlhelp_freewritebuffer(&header_buf); + header_buf_initialized = false; + if (put_buf_initialized) + curlhelp_freereadbuffer(&put_buf); + put_buf_initialized = false; } -int -check_http (void) -{ - int result = STATE_OK; - int result_ssl = STATE_OK; - int page_len = 0; - int i; - char *force_host_header = NULL; - struct curl_slist *host = NULL; - char addrstr[DEFAULT_BUFFER_SIZE/2]; - char dnscache[DEFAULT_BUFFER_SIZE]; - - /* initialize curl */ - if (curl_global_init (CURL_GLOBAL_DEFAULT) != CURLE_OK) - die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_global_init failed\n"); - curl_global_initialized = true; - - if ((curl = curl_easy_init()) == NULL) { - die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_easy_init failed\n"); - } - 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, 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"); - - if (automatic_decompression) +int check_http(void) { + int result = STATE_OK; + int result_ssl = STATE_OK; + int page_len = 0; + int i; + char *force_host_header = NULL; + struct curl_slist *host = NULL; + char addrstr[DEFAULT_BUFFER_SIZE / 2]; + char dnscache[DEFAULT_BUFFER_SIZE]; + + /* initialize curl */ + if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK) + die(STATE_UNKNOWN, "HTTP UNKNOWN - curl_global_init failed\n"); + curl_global_initialized = true; + + if ((curl = curl_easy_init()) == NULL) { + die(STATE_UNKNOWN, "HTTP UNKNOWN - curl_easy_init failed\n"); + } + 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, 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"); + + if (automatic_decompression) #if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 21, 6) - handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, ""), "CURLOPT_ACCEPT_ENCODING"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, ""), "CURLOPT_ACCEPT_ENCODING"); #else - handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_ENCODING, ""), "CURLOPT_ENCODING"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_ENCODING, ""), "CURLOPT_ENCODING"); #endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 21, 6) */ - /* initialize buffer for body of the answer */ - if (curlhelp_initwritebuffer(&body_buf) < 0) - die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for body\n"); - 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 = 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"); - - /* set the error buffer */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_ERRORBUFFER, errbuf), "CURLOPT_ERRORBUFFER"); - - /* set timeouts */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CONNECTTIMEOUT, socket_timeout), "CURLOPT_CONNECTTIMEOUT"); - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_TIMEOUT, socket_timeout), "CURLOPT_TIMEOUT"); - - /* enable haproxy protocol */ - if (haproxy_protocol) { - handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_HAPROXYPROTOCOL, 1L), "CURLOPT_HAPROXYPROTOCOL"); - } - - // 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, 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); - } - snprintf (dnscache, DEFAULT_BUFFER_SIZE, "%s:%d:%s", host_name, server_port, addrstr); - host = curl_slist_append(NULL, dnscache); - curl_easy_setopt(curl, CURLOPT_RESOLVE, host); - if (verbose>=1) - printf ("* curl CURLOPT_RESOLVE: %s\n", dnscache); - } - - // If server_address is an IPv6 address it must be surround by square brackets - struct in6_addr tmp_in_addr; - if (inet_pton(AF_INET6, server_address, &tmp_in_addr) == 1) { - char *new_server_address = malloc(strlen(server_address) + 3); - if (new_server_address == NULL) { - die(STATE_UNKNOWN, "HTTP UNKNOWN - Unable to allocate memory\n"); - } - snprintf(new_server_address, strlen(server_address)+3, "[%s]", server_address); - free(server_address); - server_address = new_server_address; - } - - /* compose URL: use the address we want to connect to, set Host: header later */ - snprintf (url, DEFAULT_BUFFER_SIZE, "%s://%s:%d%s", - use_ssl ? "https" : "http", - ( use_ssl & ( host_name != NULL ) ) ? host_name : server_address, - server_port, - server_url - ); - - if (verbose>=1) - printf ("* curl CURLOPT_URL: %s\n", url); - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_URL, url), "CURLOPT_URL"); - - /* extract proxy information for legacy proxy https requests */ - if (!strcmp(http_method, "CONNECT") || strstr(server_url, "http") == server_url) { - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_PROXY, server_address), "CURLOPT_PROXY"); - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_PROXYPORT, (long)server_port), "CURLOPT_PROXYPORT"); - if (verbose>=2) - printf ("* curl CURLOPT_PROXY: %s:%d\n", server_address, server_port); - http_method = "GET"; - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_URL, server_url), "CURLOPT_URL"); - } - - /* disable body for HEAD request */ - if (http_method && !strcmp (http_method, "HEAD" )) { - no_body = true; - } - - /* set HTTP protocol version */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_HTTP_VERSION, curl_http_version), "CURLOPT_HTTP_VERSION"); - - /* set HTTP method */ - if (http_method) { - if (!strcmp(http_method, "POST")) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_POST, 1), "CURLOPT_POST"); - else if (!strcmp(http_method, "PUT")) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_UPLOAD, 1), "CURLOPT_UPLOAD"); - else - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CUSTOMREQUEST, http_method), "CURLOPT_CUSTOMREQUEST"); - } - - /* check if Host header is explicitly set in options */ - if (http_opt_headers_count) { - 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]; - } - } - } - - /* set hostname (virtual hosts), not needed if CURLOPT_CONNECT_TO is used, but left in anyway */ - if(host_name != NULL && force_host_header == NULL) { - if((virtual_port != HTTP_PORT && !use_ssl) || (virtual_port != HTTPS_PORT && use_ssl)) { - snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s:%d", host_name, virtual_port); - } else { - snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s", host_name); - } - header_list = curl_slist_append (header_list, http_header); - } - - /* always close connection, be nice to servers */ - snprintf (http_header, DEFAULT_BUFFER_SIZE, "Connection: close"); - header_list = curl_slist_append (header_list, http_header); - - /* attach additional headers supplied by the user */ - /* optionally send any other header tag */ - if (http_opt_headers_count) { - for (i = 0; i < http_opt_headers_count ; i++) { - header_list = curl_slist_append (header_list, http_opt_headers[i]); - } - /* This cannot be free'd here because a redirection will then try to access this and segfault */ - /* Covered in a testcase in tests/check_http.t */ - /* free(http_opt_headers); */ - } - - /* set HTTP headers */ - handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_HTTPHEADER, header_list ), "CURLOPT_HTTPHEADER"); + /* 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 = 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 = 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"); + + /* set the error buffer */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf), "CURLOPT_ERRORBUFFER"); + + /* set timeouts */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, socket_timeout), "CURLOPT_CONNECTTIMEOUT"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_TIMEOUT, socket_timeout), "CURLOPT_TIMEOUT"); + + /* enable haproxy protocol */ + if (haproxy_protocol) { + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_HAPROXYPROTOCOL, 1L), "CURLOPT_HAPROXYPROTOCOL"); + } + + // 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, 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); + } + snprintf(dnscache, DEFAULT_BUFFER_SIZE, "%s:%d:%s", host_name, server_port, addrstr); + host = curl_slist_append(NULL, dnscache); + curl_easy_setopt(curl, CURLOPT_RESOLVE, host); + if (verbose >= 1) + printf("* curl CURLOPT_RESOLVE: %s\n", dnscache); + } + + // If server_address is an IPv6 address it must be surround by square brackets + struct in6_addr tmp_in_addr; + if (inet_pton(AF_INET6, server_address, &tmp_in_addr) == 1) { + char *new_server_address = malloc(strlen(server_address) + 3); + if (new_server_address == NULL) { + die(STATE_UNKNOWN, "HTTP UNKNOWN - Unable to allocate memory\n"); + } + snprintf(new_server_address, strlen(server_address) + 3, "[%s]", server_address); + free(server_address); + server_address = new_server_address; + } + + /* compose URL: use the address we want to connect to, set Host: header later */ + snprintf(url, DEFAULT_BUFFER_SIZE, "%s://%s:%d%s", use_ssl ? "https" : "http", + (use_ssl & (host_name != NULL)) ? host_name : server_address, server_port, server_url); + + if (verbose >= 1) + printf("* curl CURLOPT_URL: %s\n", url); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_URL, url), "CURLOPT_URL"); + + /* extract proxy information for legacy proxy https requests */ + if (!strcmp(http_method, "CONNECT") || strstr(server_url, "http") == server_url) { + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_PROXY, server_address), "CURLOPT_PROXY"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_PROXYPORT, (long)server_port), "CURLOPT_PROXYPORT"); + if (verbose >= 2) + printf("* curl CURLOPT_PROXY: %s:%d\n", server_address, server_port); + http_method = "GET"; + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_URL, server_url), "CURLOPT_URL"); + } + + /* disable body for HEAD request */ + if (http_method && !strcmp(http_method, "HEAD")) { + no_body = true; + } + + /* set HTTP protocol version */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, curl_http_version), "CURLOPT_HTTP_VERSION"); + + /* set HTTP method */ + if (http_method) { + if (!strcmp(http_method, "POST")) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_POST, 1), "CURLOPT_POST"); + else if (!strcmp(http_method, "PUT")) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_UPLOAD, 1), "CURLOPT_UPLOAD"); + else + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, http_method), "CURLOPT_CUSTOMREQUEST"); + } + + /* check if Host header is explicitly set in options */ + if (http_opt_headers_count) { + 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]; + } + } + } + + /* set hostname (virtual hosts), not needed if CURLOPT_CONNECT_TO is used, but left in anyway */ + if (host_name != NULL && force_host_header == NULL) { + if ((virtual_port != HTTP_PORT && !use_ssl) || (virtual_port != HTTPS_PORT && use_ssl)) { + snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s:%d", host_name, virtual_port); + } else { + snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s", host_name); + } + header_list = curl_slist_append(header_list, http_header); + } + + /* always close connection, be nice to servers */ + snprintf(http_header, DEFAULT_BUFFER_SIZE, "Connection: close"); + header_list = curl_slist_append(header_list, http_header); + + /* attach additional headers supplied by the user */ + /* optionally send any other header tag */ + if (http_opt_headers_count) { + for (i = 0; i < http_opt_headers_count; i++) { + header_list = curl_slist_append(header_list, http_opt_headers[i]); + } + /* This cannot be free'd here because a redirection will then try to access this and segfault */ + /* Covered in a testcase in tests/check_http.t */ + /* free(http_opt_headers); */ + } + + /* set HTTP headers */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list), "CURLOPT_HTTPHEADER"); #ifdef LIBCURL_FEATURE_SSL - /* set SSL version, warn about insecure or unsupported versions */ - if (use_ssl) { - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLVERSION, ssl_version), "CURLOPT_SSLVERSION"); - } - - /* client certificate and key to present to server (SSL) */ - if (client_cert) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLCERT, client_cert), "CURLOPT_SSLCERT"); - if (client_privkey) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLKEY, client_privkey), "CURLOPT_SSLKEY"); - if (ca_cert) { - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CAINFO, ca_cert), "CURLOPT_CAINFO"); - } - if (ca_cert || verify_peer_and_host) { - /* per default if we have a CA verify both the peer and the - * hostname in the certificate, can be switched off later */ - handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_SSL_VERIFYPEER, 1), "CURLOPT_SSL_VERIFYPEER"); - handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_SSL_VERIFYHOST, 2), "CURLOPT_SSL_VERIFYHOST"); - } else { - /* backward-compatible behaviour, be tolerant in checks - * TODO: depending on more options have aspects we want - * to be less tolerant about ssl verfications - */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSL_VERIFYPEER, 0), "CURLOPT_SSL_VERIFYPEER"); - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSL_VERIFYHOST, 0), "CURLOPT_SSL_VERIFYHOST"); - } - - /* detect SSL library used by libcurl */ - ssl_library = curlhelp_get_ssl_library (); - - /* try hard to get a stack of certificates to verify against */ - if (check_cert) { -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) - /* inform curl to report back certificates */ - switch (ssl_library) { - case CURLHELP_SSL_LIBRARY_OPENSSL: - case CURLHELP_SSL_LIBRARY_LIBRESSL: - /* set callback to extract certificate with OpenSSL context function (works with - * OpenSSL-style libraries only!) */ -#ifdef USE_OPENSSL - /* libcurl and monitoring plugins built with OpenSSL, good */ - add_sslctx_verify_fun = true; - is_openssl_callback = true; -#endif /* USE_OPENSSL */ - /* libcurl is built with OpenSSL, monitoring plugins, so falling - * back to manually extracting certificate information */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO"); - break; - - case CURLHELP_SSL_LIBRARY_NSS: -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) - /* NSS: support for CERTINFO is implemented since 7.34.0 */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO"); -#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ - die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (libcurl linked with SSL library '%s' is too old)\n", curlhelp_get_ssl_library_string (ssl_library)); -#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ - break; - - case CURLHELP_SSL_LIBRARY_GNUTLS: -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) - /* GnuTLS: support for CERTINFO is implemented since 7.42.0 */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO"); -#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */ - die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (libcurl linked with SSL library '%s' is too old)\n", curlhelp_get_ssl_library_string (ssl_library)); -#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */ - break; - - case CURLHELP_SSL_LIBRARY_UNKNOWN: - default: - die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (unknown SSL library '%s', must implement first)\n", curlhelp_get_ssl_library_string (ssl_library)); - break; - } -#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */ - /* old libcurl, our only hope is OpenSSL, otherwise we are out of luck */ - if (ssl_library == CURLHELP_SSL_LIBRARY_OPENSSL || ssl_library == CURLHELP_SSL_LIBRARY_LIBRESSL) - add_sslctx_verify_fun = true; - else - die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (no CURLOPT_SSL_CTX_FUNCTION, no OpenSSL library or libcurl too old and has no CURLOPT_CERTINFO)\n"); -#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */ - } - -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 10, 6) /* required for CURLOPT_SSL_CTX_FUNCTION */ - // ssl ctx function is not available with all ssl backends - if (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, NULL) != CURLE_UNKNOWN_OPTION) - handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION"); -#endif + /* set SSL version, warn about insecure or unsupported versions */ + if (use_ssl) { + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSLVERSION, ssl_version), "CURLOPT_SSLVERSION"); + } + + /* client certificate and key to present to server (SSL) */ + if (client_cert) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSLCERT, client_cert), "CURLOPT_SSLCERT"); + if (client_privkey) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSLKEY, client_privkey), "CURLOPT_SSLKEY"); + if (ca_cert) { + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CAINFO, ca_cert), "CURLOPT_CAINFO"); + } + if (ca_cert || verify_peer_and_host) { + /* per default if we have a CA verify both the peer and the + * hostname in the certificate, can be switched off later */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1), "CURLOPT_SSL_VERIFYPEER"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2), "CURLOPT_SSL_VERIFYHOST"); + } else { + /* backward-compatible behaviour, be tolerant in checks + * TODO: depending on more options have aspects we want + * to be less tolerant about ssl verfications + */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0), "CURLOPT_SSL_VERIFYPEER"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0), "CURLOPT_SSL_VERIFYHOST"); + } + + /* detect SSL library used by libcurl */ + ssl_library = curlhelp_get_ssl_library(); + + /* try hard to get a stack of certificates to verify against */ + if (check_cert) { +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) + /* inform curl to report back certificates */ + switch (ssl_library) { + case CURLHELP_SSL_LIBRARY_OPENSSL: + case CURLHELP_SSL_LIBRARY_LIBRESSL: + /* set callback to extract certificate with OpenSSL context function (works with + * OpenSSL-style libraries only!) */ +# ifdef USE_OPENSSL + /* libcurl and monitoring plugins built with OpenSSL, good */ + add_sslctx_verify_fun = true; + is_openssl_callback = true; +# endif /* USE_OPENSSL */ + /* libcurl is built with OpenSSL, monitoring plugins, so falling + * back to manually extracting certificate information */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO"); + break; + + case CURLHELP_SSL_LIBRARY_NSS: +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) + /* NSS: support for CERTINFO is implemented since 7.34.0 */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO"); +# else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ + die(STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (libcurl linked with SSL library '%s' is too old)\n", + curlhelp_get_ssl_library_string(ssl_library)); +# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ + break; + + case CURLHELP_SSL_LIBRARY_GNUTLS: +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) + /* GnuTLS: support for CERTINFO is implemented since 7.42.0 */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO"); +# else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */ + die(STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (libcurl linked with SSL library '%s' is too old)\n", + curlhelp_get_ssl_library_string(ssl_library)); +# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */ + break; + + case CURLHELP_SSL_LIBRARY_UNKNOWN: + default: + die(STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (unknown SSL library '%s', must implement first)\n", + curlhelp_get_ssl_library_string(ssl_library)); + break; + } +# else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */ + /* old libcurl, our only hope is OpenSSL, otherwise we are out of luck */ + if (ssl_library == CURLHELP_SSL_LIBRARY_OPENSSL || ssl_library == CURLHELP_SSL_LIBRARY_LIBRESSL) + add_sslctx_verify_fun = true; + else + die(STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (no CURLOPT_SSL_CTX_FUNCTION, no OpenSSL library or libcurl " + "too old and has no CURLOPT_CERTINFO)\n"); +# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */ + } + +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 10, 6) /* required for CURLOPT_SSL_CTX_FUNCTION */ + // ssl ctx function is not available with all ssl backends + if (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, NULL) != CURLE_UNKNOWN_OPTION) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION"); +# endif #endif /* LIBCURL_FEATURE_SSL */ - /* set default or user-given user agent identification */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_USERAGENT, user_agent), "CURLOPT_USERAGENT"); - - /* proxy-authentication */ - if (strcmp(proxy_auth, "")) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_PROXYUSERPWD, proxy_auth), "CURLOPT_PROXYUSERPWD"); - - /* authentication */ - if (strcmp(user_auth, "")) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_USERPWD, user_auth), "CURLOPT_USERPWD"); - - /* TODO: parameter auth method, bitfield of following methods: - * CURLAUTH_BASIC (default) - * CURLAUTH_DIGEST - * CURLAUTH_DIGEST_IE - * CURLAUTH_NEGOTIATE - * CURLAUTH_NTLM - * CURLAUTH_NTLM_WB - * - * convenience tokens for typical sets of methods: - * CURLAUTH_ANYSAFE: most secure, without BASIC - * or CURLAUTH_ANY: most secure, even BASIC if necessary - * - * handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_DIGEST ), "CURLOPT_HTTPAUTH"); - */ - - /* handle redirections */ - if (onredirect == STATE_DEPENDENT) { - if( followmethod == FOLLOW_LIBCURL ) { - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_FOLLOWLOCATION, 1), "CURLOPT_FOLLOWLOCATION"); - - /* default -1 is infinite, not good, could lead to zombie plugins! - Setting it to one bigger than maximal limit to handle errors nicely below - */ - 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) */ + /* set default or user-given user agent identification */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent), "CURLOPT_USERAGENT"); + + /* proxy-authentication */ + if (strcmp(proxy_auth, "")) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, proxy_auth), "CURLOPT_PROXYUSERPWD"); + + /* authentication */ + if (strcmp(user_auth, "")) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_USERPWD, user_auth), "CURLOPT_USERPWD"); + + /* TODO: parameter auth method, bitfield of following methods: + * CURLAUTH_BASIC (default) + * CURLAUTH_DIGEST + * CURLAUTH_DIGEST_IE + * CURLAUTH_NEGOTIATE + * CURLAUTH_NTLM + * CURLAUTH_NTLM_WB + * + * convenience tokens for typical sets of methods: + * CURLAUTH_ANYSAFE: most secure, without BASIC + * or CURLAUTH_ANY: most secure, even BASIC if necessary + * + * handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_DIGEST ), "CURLOPT_HTTPAUTH"); + */ + + /* handle redirections */ + if (onredirect == STATE_DEPENDENT) { + if (followmethod == FOLLOW_LIBCURL) { + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1), "CURLOPT_FOLLOWLOCATION"); + + /* default -1 is infinite, not good, could lead to zombie plugins! + Setting it to one bigger than maximal limit to handle errors nicely below + */ + 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"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR, "http,https"), + "CURLOPT_REDIR_PROTOCOLS_STR"); #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"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS), + "CURLOPT_REDIRECT_PROTOCOLS"); #endif - /* TODO: handle the following aspects of redirection, make them - * command line options too later: - CURLOPT_POSTREDIR: method switch - CURLINFO_REDIRECT_URL: custom redirect option - CURLOPT_REDIRECT_PROTOCOLS: allow people to step outside safe protocols - CURLINFO_REDIRECT_COUNT: get the number of redirects, print it, maybe a range option here is nice like for expected page size? - */ - } else { - /* old style redirection is handled below */ - } - } - - /* no-body */ - if (no_body) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_NOBODY, 1), "CURLOPT_NOBODY"); - - /* IPv4 or IPv6 forced DNS resolution */ - if (address_family == AF_UNSPEC) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_WHATEVER)"); - else if (address_family == AF_INET) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V4)"); -#if defined (USE_IPV6) && defined (LIBCURL_FEATURE_IPV6) - else if (address_family == AF_INET6) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V6)"); + /* TODO: handle the following aspects of redirection, make them + * command line options too later: + CURLOPT_POSTREDIR: method switch + CURLINFO_REDIRECT_URL: custom redirect option + CURLOPT_REDIRECT_PROTOCOLS: allow people to step outside safe protocols + CURLINFO_REDIRECT_COUNT: get the number of redirects, print it, maybe a range option here is nice like for expected page size? + */ + } else { + /* old style redirection is handled below */ + } + } + + /* no-body */ + if (no_body) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_NOBODY, 1), "CURLOPT_NOBODY"); + + /* IPv4 or IPv6 forced DNS resolution */ + if (address_family == AF_UNSPEC) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER), + "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_WHATEVER)"); + else if (address_family == AF_INET) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4), + "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V4)"); +#if defined(USE_IPV6) && defined(LIBCURL_FEATURE_IPV6) + else if (address_family == AF_INET6) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6), + "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V6)"); #endif - /* either send http POST data (any data, not only POST)*/ - if (!strcmp(http_method, "POST") ||!strcmp(http_method, "PUT")) { - /* set content of payload for POST and PUT */ - if (http_content_type) { - snprintf (http_header, DEFAULT_BUFFER_SIZE, "Content-Type: %s", http_content_type); - header_list = curl_slist_append (header_list, http_header); - } - /* NULL indicates "HTTP Continue" in libcurl, provide an empty string - * in case of no POST/PUT data */ - if (!http_post_data) - http_post_data = ""; - if (!strcmp(http_method, "POST")) { - /* POST method, set payload with CURLOPT_POSTFIELDS */ - 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"); - 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 = 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"); - } - } - - /* 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"); - } - - /* do the request */ - res = curl_easy_perform(curl); - - if (verbose>=2 && http_post_data) - printf ("**** REQUEST CONTENT ****\n%s\n", http_post_data); - - /* 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) { - snprintf (msg, - DEFAULT_BUFFER_SIZE, - _("Invalid HTTP response received from host on port %d: cURL returned %d - %s"), - server_port, - res, - errbuf[0] ? errbuf : curl_easy_strerror(res)); - die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); - } - - /* certificate checks */ + /* either send http POST data (any data, not only POST)*/ + if (!strcmp(http_method, "POST") || !strcmp(http_method, "PUT")) { + /* set content of payload for POST and PUT */ + if (http_content_type) { + snprintf(http_header, DEFAULT_BUFFER_SIZE, "Content-Type: %s", http_content_type); + header_list = curl_slist_append(header_list, http_header); + } + /* NULL indicates "HTTP Continue" in libcurl, provide an empty string + * in case of no POST/PUT data */ + if (!http_post_data) + http_post_data = ""; + if (!strcmp(http_method, "POST")) { + /* POST method, set payload with CURLOPT_POSTFIELDS */ + 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"); + 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 = 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"); + } + } + + /* 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"); + } + + /* do the request */ + res = curl_easy_perform(curl); + + if (verbose >= 2 && http_post_data) + printf("**** REQUEST CONTENT ****\n%s\n", http_post_data); + + /* 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) { + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host on port %d: cURL returned %d - %s"), server_port, + res, errbuf[0] ? errbuf : curl_easy_strerror(res)); + die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); + } + + /* certificate checks */ #ifdef LIBCURL_FEATURE_SSL - 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_ssl = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit); - if (!continue_after_check_cert) { - return result_ssl; - } -#else /* USE_OPENSSL */ - die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates - OpenSSL callback used and not linked against OpenSSL\n"); -#endif /* USE_OPENSSL */ - } else { - int i; - struct curl_slist *slist; - - cert_ptr.to_info = NULL; - res = curl_easy_getinfo (curl, CURLINFO_CERTINFO, &cert_ptr.to_info); - if (!res && cert_ptr.to_info) { -#ifdef USE_OPENSSL - /* We have no OpenSSL in libcurl, but we can use OpenSSL for X509 cert parsing - * We only check the first certificate and assume it's the one of the server - */ - const char* raw_cert = NULL; - for (i = 0; i < cert_ptr.to_certinfo->num_of_certs; i++) { - for (slist = cert_ptr.to_certinfo->certinfo[i]; slist; slist = slist->next) { - if (verbose >= 2) - printf ("%d ** %s\n", i, slist->data); - if (strncmp (slist->data, "Cert:", 5) == 0) { - raw_cert = &slist->data[5]; - goto GOT_FIRST_CERT; - } - } - } -GOT_FIRST_CERT: - if (!raw_cert) { - snprintf (msg, - DEFAULT_BUFFER_SIZE, - _("Cannot retrieve certificates from CERTINFO information - certificate data was empty")); - die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); - } - BIO* cert_BIO = BIO_new (BIO_s_mem()); - BIO_write (cert_BIO, raw_cert, strlen(raw_cert)); - cert = PEM_read_bio_X509 (cert_BIO, NULL, NULL, NULL); - if (!cert) { - snprintf (msg, - DEFAULT_BUFFER_SIZE, - _("Cannot read certificate from CERTINFO information - BIO error")); - die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); - } - BIO_free (cert_BIO); - result_ssl = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit); - if (!continue_after_check_cert) { - return result_ssl; - } -#else /* USE_OPENSSL */ - /* We assume we don't have OpenSSL and np_net_ssl_check_certificate at our disposal, - * so we use the libcurl CURLINFO data - */ - result_ssl = net_noopenssl_check_certificate(&cert_ptr, days_till_exp_warn, days_till_exp_crit); - if (!continue_after_check_cert) { - return result_ssl; - } -#endif /* USE_OPENSSL */ - } else { - snprintf (msg, - DEFAULT_BUFFER_SIZE, - _("Cannot retrieve certificates - cURL returned %d - %s"), - res, - curl_easy_strerror(res)); - die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); - } - } - } - } + 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_ssl = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit); + if (!continue_after_check_cert) { + return result_ssl; + } +# else /* USE_OPENSSL */ + die(STATE_CRITICAL, + "HTTP CRITICAL - Cannot retrieve certificates - OpenSSL callback used and not linked against OpenSSL\n"); +# endif /* USE_OPENSSL */ + } else { + int i; + struct curl_slist *slist; + + cert_ptr.to_info = NULL; + res = curl_easy_getinfo(curl, CURLINFO_CERTINFO, &cert_ptr.to_info); + if (!res && cert_ptr.to_info) { +# ifdef USE_OPENSSL + /* We have no OpenSSL in libcurl, but we can use OpenSSL for X509 cert parsing + * We only check the first certificate and assume it's the one of the server + */ + const char *raw_cert = NULL; + for (i = 0; i < cert_ptr.to_certinfo->num_of_certs; i++) { + for (slist = cert_ptr.to_certinfo->certinfo[i]; slist; slist = slist->next) { + if (verbose >= 2) + printf("%d ** %s\n", i, slist->data); + if (strncmp(slist->data, "Cert:", 5) == 0) { + raw_cert = &slist->data[5]; + goto GOT_FIRST_CERT; + } + } + } + GOT_FIRST_CERT: + if (!raw_cert) { + snprintf(msg, DEFAULT_BUFFER_SIZE, + _("Cannot retrieve certificates from CERTINFO information - certificate data was empty")); + die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); + } + BIO *cert_BIO = BIO_new(BIO_s_mem()); + BIO_write(cert_BIO, raw_cert, strlen(raw_cert)); + cert = PEM_read_bio_X509(cert_BIO, NULL, NULL, NULL); + if (!cert) { + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Cannot read certificate from CERTINFO information - BIO error")); + die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); + } + BIO_free(cert_BIO); + result_ssl = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit); + if (!continue_after_check_cert) { + return result_ssl; + } +# else /* USE_OPENSSL */ + /* We assume we don't have OpenSSL and np_net_ssl_check_certificate at our disposal, + * so we use the libcurl CURLINFO data + */ + result_ssl = net_noopenssl_check_certificate(&cert_ptr, days_till_exp_warn, days_till_exp_crit); + if (!continue_after_check_cert) { + return result_ssl; + } +# endif /* USE_OPENSSL */ + } else { + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Cannot retrieve certificates - cURL returned %d - %s"), res, + curl_easy_strerror(res)); + die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); + } + } + } + } #endif /* LIBCURL_FEATURE_SSL */ - /* we got the data and we executed the request in a given time, so we can append - * performance data to the answer always - */ - handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_TOTAL_TIME, &total_time), "CURLINFO_TOTAL_TIME"); - page_len = get_content_length(&header_buf, &body_buf); - if(show_extended_perfdata) { - handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &time_connect), "CURLINFO_CONNECT_TIME"); - handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_APPCONNECT_TIME, &time_appconnect), "CURLINFO_APPCONNECT_TIME"); - handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &time_headers), "CURLINFO_PRETRANSFER_TIME"); - handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_STARTTRANSFER_TIME, &time_firstbyte), "CURLINFO_STARTTRANSFER_TIME"); - snprintf(perfstring, DEFAULT_BUFFER_SIZE, "%s %s %s %s %s %s %s", - perfd_time(total_time), - perfd_size(page_len), - perfd_time_connect(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) - ); - } else { - snprintf(perfstring, DEFAULT_BUFFER_SIZE, "%s %s", - perfd_time(total_time), - perfd_size(page_len) - ); - } - - /* return a CRITICAL status if we couldn't read any data */ - if (strlen(header_buf.buf) == 0 && strlen(body_buf.buf) == 0) - die (STATE_CRITICAL, _("HTTP CRITICAL - No header received from host\n")); - - /* get status line of answer, check sanity of HTTP code */ - if (curlhelp_parse_statusline (header_buf.buf, &status_line) < 0) { - snprintf (msg, - DEFAULT_BUFFER_SIZE, - "Unparsable status line in %.3g seconds response time|%s\n", - total_time, - perfstring); - /* 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 = true; - - /* get result code from cURL */ - handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &code), "CURLINFO_RESPONSE_CODE"); - if (verbose>=2) - printf ("* curl CURLINFO_RESPONSE_CODE is %ld\n", code); - - /* print status line, header, body if verbose */ - if (verbose >= 2) { - printf ("**** HEADER ****\n%s\n**** CONTENT ****\n%s\n", header_buf.buf, - (no_body ? " [[ skipped ]]" : body_buf.buf)); - } - - /* make sure the status line matches the response we are looking for */ - if (!expected_statuscode(status_line.first_line, server_expect)) { - if (server_port == HTTP_PORT) - snprintf(msg, - DEFAULT_BUFFER_SIZE, - _("Invalid HTTP response received from host: %s\n"), - status_line.first_line); - else - snprintf(msg, - DEFAULT_BUFFER_SIZE, - _("Invalid HTTP response received from host on port %d: %s\n"), - server_port, - status_line.first_line); - die (STATE_CRITICAL, "HTTP CRITICAL - %s%s%s", msg, - show_body ? "\n" : "", - show_body ? body_buf.buf : ""); - } - - if( server_expect_yn ) { - snprintf(msg, DEFAULT_BUFFER_SIZE, _("Status line output matched \"%s\" - "), server_expect); - if (verbose) - printf ("%s\n",msg); - result = STATE_OK; - } - else { - /* illegal return codes result in a critical state */ - if (code >= 600 || code < 100) { - die (STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status (%d, %.40s)\n"), status_line.http_code, status_line.msg); - /* server errors result in a critical state */ - } else if (code >= 500) { - result = STATE_CRITICAL; - /* client errors result in a warning state */ - } else if (code >= 400) { - result = STATE_WARNING; - /* check redirected page if specified */ - } else if (code >= 300) { - if (onredirect == STATE_DEPENDENT) { - if( followmethod == FOLLOW_LIBCURL ) { - code = status_line.http_code; - } else { - /* old check_http style redirection, if we come - * back here, we are in the same status as with - * the libcurl method - */ - redir (&header_buf); - } - } else { - /* this is a specific code in the command line to - * be returned when a redirection is encountered - */ - } - result = max_state_alt (onredirect, result); - /* all other codes are considered ok */ - } else { - result = STATE_OK; - } - } - - /* libcurl redirection internally, handle error states here */ - if( followmethod == FOLLOW_LIBCURL ) { - handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_REDIRECT_COUNT, &redir_depth), "CURLINFO_REDIRECT_COUNT"); - if (verbose >= 2) - printf(_("* curl LIBINFO_REDIRECT_COUNT is %d\n"), redir_depth); - if (redir_depth > max_depth) { - snprintf (msg, DEFAULT_BUFFER_SIZE, "maximum redirection depth %d exceeded in libcurl", - max_depth); - die (STATE_WARNING, "HTTP WARNING - %s", msg); - } - } - - /* check status codes, set exit status accordingly */ - if( status_line.http_code != code ) { - die (STATE_CRITICAL, _("HTTP CRITICAL %s %d %s - different HTTP codes (cUrl has %ld)\n"), - string_statuscode (status_line.http_major, status_line.http_minor), - status_line.http_code, status_line.msg, code); - } - - if (maximum_age >= 0) { - result = max_state_alt(check_document_dates(&header_buf, &msg), result); - } - - /* Page and Header content checks go here */ - - if (strlen (header_expect)) { - if (!strstr (header_buf.buf, 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); - } + /* we got the data and we executed the request in a given time, so we can append + * performance data to the answer always + */ + handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time), "CURLINFO_TOTAL_TIME"); + page_len = get_content_length(&header_buf, &body_buf); + if (show_extended_perfdata) { + handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &time_connect), "CURLINFO_CONNECT_TIME"); + handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_APPCONNECT_TIME, &time_appconnect), "CURLINFO_APPCONNECT_TIME"); + handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &time_headers), "CURLINFO_PRETRANSFER_TIME"); + handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_STARTTRANSFER_TIME, &time_firstbyte), + "CURLINFO_STARTTRANSFER_TIME"); + snprintf(perfstring, DEFAULT_BUFFER_SIZE, "%s %s %s %s %s %s %s", perfd_time(total_time), perfd_size(page_len), + perfd_time_connect(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)); + } else { + snprintf(perfstring, DEFAULT_BUFFER_SIZE, "%s %s", perfd_time(total_time), perfd_size(page_len)); + } - char tmp[DEFAULT_BUFFER_SIZE]; + /* return a CRITICAL status if we couldn't read any data */ + if (strlen(header_buf.buf) == 0 && strlen(body_buf.buf) == 0) + die(STATE_CRITICAL, _("HTTP CRITICAL - No header received from host\n")); - snprintf (tmp, - DEFAULT_BUFFER_SIZE, - _("%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); + /* get status line of answer, check sanity of HTTP code */ + if (curlhelp_parse_statusline(header_buf.buf, &status_line) < 0) { + snprintf(msg, DEFAULT_BUFFER_SIZE, "Unparsable status line in %.3g seconds response time|%s\n", total_time, perfstring); + /* 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 = true; - strcpy(msg, tmp); + /* get result code from cURL */ + handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code), "CURLINFO_RESPONSE_CODE"); + if (verbose >= 2) + printf("* curl CURLINFO_RESPONSE_CODE is %ld\n", code); + + /* print status line, header, body if verbose */ + if (verbose >= 2) { + printf("**** HEADER ****\n%s\n**** CONTENT ****\n%s\n", header_buf.buf, (no_body ? " [[ skipped ]]" : body_buf.buf)); + } + + /* make sure the status line matches the response we are looking for */ + if (!expected_statuscode(status_line.first_line, server_expect)) { + if (server_port == HTTP_PORT) + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host: %s\n"), status_line.first_line); + else + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host on port %d: %s\n"), server_port, + status_line.first_line); + die(STATE_CRITICAL, "HTTP CRITICAL - %s%s%s", msg, show_body ? "\n" : "", show_body ? body_buf.buf : ""); + } + + if (server_expect_yn) { + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Status line output matched \"%s\" - "), server_expect); + if (verbose) + printf("%s\n", msg); + result = STATE_OK; + } else { + /* illegal return codes result in a critical state */ + if (code >= 600 || code < 100) { + die(STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status (%d, %.40s)\n"), status_line.http_code, status_line.msg); + /* server errors result in a critical state */ + } else if (code >= 500) { + result = STATE_CRITICAL; + /* client errors result in a warning state */ + } else if (code >= 400) { + result = STATE_WARNING; + /* check redirected page if specified */ + } else if (code >= 300) { + if (onredirect == STATE_DEPENDENT) { + if (followmethod == FOLLOW_LIBCURL) { + code = status_line.http_code; + } else { + /* old check_http style redirection, if we come + * back here, we are in the same status as with + * the libcurl method + */ + redir(&header_buf); + } + } else { + /* this is a specific code in the command line to + * be returned when a redirection is encountered + */ + } + result = max_state_alt(onredirect, result); + /* all other codes are considered ok */ + } else { + result = STATE_OK; + } + } - result = STATE_CRITICAL; - } - } + /* libcurl redirection internally, handle error states here */ + if (followmethod == FOLLOW_LIBCURL) { + handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_REDIRECT_COUNT, &redir_depth), "CURLINFO_REDIRECT_COUNT"); + if (verbose >= 2) + printf(_("* curl LIBINFO_REDIRECT_COUNT is %d\n"), redir_depth); + if (redir_depth > max_depth) { + snprintf(msg, DEFAULT_BUFFER_SIZE, "maximum redirection depth %d exceeded in libcurl", max_depth); + die(STATE_WARNING, "HTTP WARNING - %s", msg); + } + } - if (strlen (string_expect)) { - if (!strstr (body_buf.buf, string_expect)) { + /* check status codes, set exit status accordingly */ + if (status_line.http_code != code) { + die(STATE_CRITICAL, _("HTTP CRITICAL %s %d %s - different HTTP codes (cUrl has %ld)\n"), + string_statuscode(status_line.http_major, status_line.http_minor), status_line.http_code, status_line.msg, code); + } - strncpy(&output_string_search[0],string_expect,sizeof(output_string_search)); + if (maximum_age >= 0) { + result = max_state_alt(check_document_dates(&header_buf, &msg), result); + } - if(output_string_search[sizeof(output_string_search)-1]!='\0') { - bcopy("...",&output_string_search[sizeof(output_string_search)-4],4); - } + /* Page and Header content checks go here */ + + if (strlen(header_expect)) { + if (!strstr(header_buf.buf, 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); + } char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, - DEFAULT_BUFFER_SIZE, - _("%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); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%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); strcpy(msg, tmp); result = STATE_CRITICAL; - } - } - - if (strlen (regexp)) { - errcode = regexec (&preg, body_buf.buf, REGS, pmatch, 0); - 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) || (errcode == 0 && invert_regex)) { + } + } + + if (strlen(string_expect)) { + if (!strstr(body_buf.buf, 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); + } + + char tmp[DEFAULT_BUFFER_SIZE]; + + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%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); + + strcpy(msg, tmp); + + result = STATE_CRITICAL; + } + } + + if (strlen(regexp)) { + errcode = regexec(&preg, body_buf.buf, REGS, pmatch, 0); + 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) || (errcode == 0 && invert_regex)) { if (!invert_regex) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%spattern not found, "), msg); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%spattern not found, "), msg); strcpy(msg, tmp); } else { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%spattern found, "), msg); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%spattern found, "), msg); strcpy(msg, tmp); - } result = state_regex; } else { - regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); + regerror(errcode, &preg, errbuf, MAX_INPUT_BUFFER); char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%sExecute Error: %s, "), msg, errbuf); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sExecute Error: %s, "), msg, errbuf); strcpy(msg, tmp); result = STATE_UNKNOWN; } - } + } - /* make sure the page is of an appropriate size */ + /* make sure the page is of an appropriate size */ if ((max_page_len > 0) && (page_len > max_page_len)) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%spage size %d too large, "), msg, page_len); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%spage size %d too large, "), msg, page_len); strcpy(msg, tmp); @@ -1175,1281 +1118,1239 @@ GOT_FIRST_CERT: } else if ((min_page_len > 0) && (page_len < min_page_len)) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%spage size %d too small, "), msg, page_len); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%spage size %d too small, "), msg, page_len); strcpy(msg, tmp); result = max_state_alt(STATE_WARNING, result); } - /* -w, -c: check warning and critical level */ - result = max_state_alt(get_status(total_time, thlds), result); - - /* Cut-off trailing characters */ - if (strlen(msg) >= 2) { - if(msg[strlen(msg)-2] == ',') - msg[strlen(msg)-2] = '\0'; - else - msg[strlen(msg)-3] = '\0'; - } - - /* TODO: separate _() msg and status code: die (result, "HTTP %s: %s\n", state_text(result), msg); */ - die (max_state_alt(result, result_ssl), "HTTP %s: %s %d %s%s%s - %d bytes in %.3f second response time %s|%s\n%s%s", - state_text(result), string_statuscode (status_line.http_major, status_line.http_minor), - status_line.http_code, status_line.msg, - strlen(msg) > 0 ? " - " : "", - msg, page_len, total_time, - (display_html ? "" : ""), - perfstring, - (show_body ? body_buf.buf : ""), - (show_body ? "\n" : "") ); - - return max_state_alt(result, result_ssl); + /* -w, -c: check warning and critical level */ + result = max_state_alt(get_status(total_time, thlds), result); + + /* Cut-off trailing characters */ + if (strlen(msg) >= 2) { + if (msg[strlen(msg) - 2] == ',') + msg[strlen(msg) - 2] = '\0'; + else + msg[strlen(msg) - 3] = '\0'; + } + + /* TODO: separate _() msg and status code: die (result, "HTTP %s: %s\n", state_text(result), msg); */ + die(max_state_alt(result, result_ssl), "HTTP %s: %s %d %s%s%s - %d bytes in %.3f second response time %s|%s\n%s%s", state_text(result), + string_statuscode(status_line.http_major, status_line.http_minor), status_line.http_code, status_line.msg, + strlen(msg) > 0 ? " - " : "", msg, page_len, total_time, (display_html ? "" : ""), perfstring, (show_body ? body_buf.buf : ""), + (show_body ? "\n" : "")); + + return max_state_alt(result, result_ssl); } -int -uri_strcmp (const UriTextRangeA range, const char* s) -{ - if (!range.first) return -1; - if ( (size_t)(range.afterLast - range.first) < strlen (s) ) return -1; - return strncmp (s, range.first, min( (size_t)(range.afterLast - range.first), strlen (s))); +int uri_strcmp(const UriTextRangeA range, const char *s) { + if (!range.first) + return -1; + if ((size_t)(range.afterLast - range.first) < strlen(s)) + return -1; + return strncmp(s, range.first, min((size_t)(range.afterLast - range.first), strlen(s))); } -char* -uri_string (const UriTextRangeA range, char* buf, size_t buflen) -{ - if (!range.first) return "(null)"; - strncpy (buf, range.first, max (buflen-1, (size_t)(range.afterLast - range.first))); - buf[max (buflen-1, (size_t)(range.afterLast - range.first))] = '\0'; - buf[range.afterLast - range.first] = '\0'; - return buf; +char *uri_string(const UriTextRangeA range, char *buf, size_t buflen) { + if (!range.first) + return "(null)"; + strncpy(buf, range.first, max(buflen - 1, (size_t)(range.afterLast - range.first))); + buf[max(buflen - 1, (size_t)(range.afterLast - range.first))] = '\0'; + buf[range.afterLast - range.first] = '\0'; + return buf; } -void -redir (curlhelp_write_curlbuf* header_buf) -{ - char *location = NULL; - curlhelp_statusline status_line; - struct phr_header headers[255]; - size_t nof_headers = 255; - size_t msglen; - char buf[DEFAULT_BUFFER_SIZE]; - char ipstr[INET_ADDR_MAX_SIZE]; - int new_port; - char *new_host; - char *new_url; - - int res = phr_parse_response (header_buf->buf, header_buf->buflen, - &status_line.http_major, &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen, - headers, &nof_headers, 0); +void redir(curlhelp_write_curlbuf *header_buf) { + char *location = NULL; + curlhelp_statusline status_line; + struct phr_header headers[255]; + size_t nof_headers = 255; + size_t msglen; + char buf[DEFAULT_BUFFER_SIZE]; + char ipstr[INET_ADDR_MAX_SIZE]; + int new_port; + char *new_host; + char *new_url; + + int res = phr_parse_response(header_buf->buf, header_buf->buflen, &status_line.http_major, &status_line.http_minor, + &status_line.http_code, &status_line.msg, &msglen, headers, &nof_headers, 0); if (res == -1) { - die (STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n")); - } - - location = get_header_value (headers, nof_headers, "location"); - - if (verbose >= 2) - printf(_("* Seen redirect location %s\n"), location); - - if (++redir_depth > max_depth) - die (STATE_WARNING, - _("HTTP WARNING - maximum redirection depth %d exceeded - %s%s\n"), - max_depth, location, (display_html ? "" : "")); - - UriParserStateA state; - UriUriA uri; - state.uri = &uri; - if (uriParseUriA (&state, location) != URI_SUCCESS) { - if (state.errorCode == URI_ERROR_SYNTAX) { - die (STATE_UNKNOWN, - _("HTTP UNKNOWN - Could not parse redirect location '%s'%s\n"), - location, (display_html ? "" : "")); - } else if (state.errorCode == URI_ERROR_MALLOC) { - die (STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n")); - } - } - - if (verbose >= 2) { - printf (_("** scheme: %s\n"), - uri_string (uri.scheme, buf, DEFAULT_BUFFER_SIZE)); - printf (_("** host: %s\n"), - uri_string (uri.hostText, buf, DEFAULT_BUFFER_SIZE)); - printf (_("** port: %s\n"), - uri_string (uri.portText, buf, DEFAULT_BUFFER_SIZE)); - if (uri.hostData.ip4) { - inet_ntop (AF_INET, uri.hostData.ip4->data, ipstr, sizeof (ipstr)); - printf (_("** IPv4: %s\n"), ipstr); - } - if (uri.hostData.ip6) { - inet_ntop (AF_INET, uri.hostData.ip6->data, ipstr, sizeof (ipstr)); - printf (_("** IPv6: %s\n"), ipstr); - } - if (uri.pathHead) { - printf (_("** path: ")); - const UriPathSegmentA* p = uri.pathHead; - for (; p; p = p->next) { - printf ("/%s", uri_string (p->text, buf, DEFAULT_BUFFER_SIZE)); - } - puts (""); - } - if (uri.query.first) { - printf (_("** query: %s\n"), - uri_string (uri.query, buf, DEFAULT_BUFFER_SIZE)); - } - if (uri.fragment.first) { - printf (_("** fragment: %s\n"), - uri_string (uri.fragment, buf, DEFAULT_BUFFER_SIZE)); - } - } - - if (uri.scheme.first) { - 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 - */ - if (uri.portText.first) { - new_port = atoi (uri_string (uri.portText, buf, DEFAULT_BUFFER_SIZE)); - } else { - new_port = HTTP_PORT; - if (use_ssl) - new_port = HTTPS_PORT; - } - if (new_port > MAX_PORT) - die (STATE_UNKNOWN, - _("HTTP UNKNOWN - Redirection to port above %d - %s%s\n"), - MAX_PORT, location, display_html ? "" : ""); - - /* by RFC 7231 relative URLs in Location should be taken relative to - * the original URL, so we try to form a new absolute URL here - */ - if (!uri.scheme.first && !uri.hostText.first) { - new_host = strdup (host_name ? host_name : server_address); - new_port = server_port; - if(use_ssl) - uri_string (uri.scheme, "https", DEFAULT_BUFFER_SIZE); - } else { - new_host = strdup (uri_string (uri.hostText, buf, DEFAULT_BUFFER_SIZE)); - } - - /* compose new path */ - /* TODO: handle fragments and query part of URL */ - new_url = (char *)calloc( 1, DEFAULT_BUFFER_SIZE); - if (uri.pathHead) { - const UriPathSegmentA* p = uri.pathHead; - for (; p; p = p->next) { - strncat (new_url, "/", DEFAULT_BUFFER_SIZE); - strncat (new_url, uri_string (p->text, buf, DEFAULT_BUFFER_SIZE), DEFAULT_BUFFER_SIZE-1); - } - } - - if (server_port==new_port && - !strncmp(server_address, new_host, MAX_IPV4_HOSTLENGTH) && - (host_name && !strncmp(host_name, new_host, MAX_IPV4_HOSTLENGTH)) && - !strcmp(server_url, new_url)) - die (STATE_CRITICAL, - _("HTTP CRITICAL - redirection creates an infinite loop - %s://%s:%d%s%s\n"), - use_ssl ? "https" : "http", new_host, new_port, new_url, (display_html ? "" : "")); - - /* set new values for redirected request */ - - if (!(followsticky & STICKY_HOST)) { - free (server_address); - server_address = strndup (new_host, MAX_IPV4_HOSTLENGTH); - } - if (!(followsticky & STICKY_PORT)) { - server_port = (unsigned short)new_port; - } - - free (host_name); - host_name = strndup (new_host, MAX_IPV4_HOSTLENGTH); - - /* reset virtual port */ - virtual_port = server_port; - - free(new_host); - free (server_url); - server_url = new_url; - - uriFreeUriMembersA (&uri); - - if (verbose) - printf (_("Redirection to %s://%s:%d%s\n"), use_ssl ? "https" : "http", - host_name ? host_name : server_address, server_port, server_url); - - /* TODO: the hash component MUST be taken from the original URL and - * attached to the URL in Location - */ - - cleanup (); - check_http (); + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n")); + } + + location = get_header_value(headers, nof_headers, "location"); + + if (verbose >= 2) + printf(_("* Seen redirect location %s\n"), location); + + if (++redir_depth > max_depth) + die(STATE_WARNING, _("HTTP WARNING - maximum redirection depth %d exceeded - %s%s\n"), max_depth, location, + (display_html ? "" : "")); + + UriParserStateA state; + UriUriA uri; + state.uri = &uri; + if (uriParseUriA(&state, location) != URI_SUCCESS) { + if (state.errorCode == URI_ERROR_SYNTAX) { + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Could not parse redirect location '%s'%s\n"), location, (display_html ? "" : "")); + } else if (state.errorCode == URI_ERROR_MALLOC) { + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n")); + } + } + + if (verbose >= 2) { + printf(_("** scheme: %s\n"), uri_string(uri.scheme, buf, DEFAULT_BUFFER_SIZE)); + printf(_("** host: %s\n"), uri_string(uri.hostText, buf, DEFAULT_BUFFER_SIZE)); + printf(_("** port: %s\n"), uri_string(uri.portText, buf, DEFAULT_BUFFER_SIZE)); + if (uri.hostData.ip4) { + inet_ntop(AF_INET, uri.hostData.ip4->data, ipstr, sizeof(ipstr)); + printf(_("** IPv4: %s\n"), ipstr); + } + if (uri.hostData.ip6) { + inet_ntop(AF_INET, uri.hostData.ip6->data, ipstr, sizeof(ipstr)); + printf(_("** IPv6: %s\n"), ipstr); + } + if (uri.pathHead) { + printf(_("** path: ")); + const UriPathSegmentA *p = uri.pathHead; + for (; p; p = p->next) { + printf("/%s", uri_string(p->text, buf, DEFAULT_BUFFER_SIZE)); + } + puts(""); + } + if (uri.query.first) { + printf(_("** query: %s\n"), uri_string(uri.query, buf, DEFAULT_BUFFER_SIZE)); + } + if (uri.fragment.first) { + printf(_("** fragment: %s\n"), uri_string(uri.fragment, buf, DEFAULT_BUFFER_SIZE)); + } + } + + if (uri.scheme.first) { + 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 + */ + if (uri.portText.first) { + new_port = atoi(uri_string(uri.portText, buf, DEFAULT_BUFFER_SIZE)); + } else { + new_port = HTTP_PORT; + if (use_ssl) + new_port = HTTPS_PORT; + } + if (new_port > MAX_PORT) + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Redirection to port above %d - %s%s\n"), MAX_PORT, location, display_html ? "" : ""); + + /* by RFC 7231 relative URLs in Location should be taken relative to + * the original URL, so we try to form a new absolute URL here + */ + if (!uri.scheme.first && !uri.hostText.first) { + new_host = strdup(host_name ? host_name : server_address); + new_port = server_port; + if (use_ssl) + uri_string(uri.scheme, "https", DEFAULT_BUFFER_SIZE); + } else { + new_host = strdup(uri_string(uri.hostText, buf, DEFAULT_BUFFER_SIZE)); + } + + /* compose new path */ + /* TODO: handle fragments and query part of URL */ + new_url = (char *)calloc(1, DEFAULT_BUFFER_SIZE); + if (uri.pathHead) { + const UriPathSegmentA *p = uri.pathHead; + for (; p; p = p->next) { + strncat(new_url, "/", DEFAULT_BUFFER_SIZE); + strncat(new_url, uri_string(p->text, buf, DEFAULT_BUFFER_SIZE), DEFAULT_BUFFER_SIZE - 1); + } + } + + if (server_port == new_port && !strncmp(server_address, new_host, MAX_IPV4_HOSTLENGTH) && + (host_name && !strncmp(host_name, new_host, MAX_IPV4_HOSTLENGTH)) && !strcmp(server_url, new_url)) + die(STATE_CRITICAL, _("HTTP CRITICAL - redirection creates an infinite loop - %s://%s:%d%s%s\n"), use_ssl ? "https" : "http", + new_host, new_port, new_url, (display_html ? "" : "")); + + /* set new values for redirected request */ + + if (!(followsticky & STICKY_HOST)) { + free(server_address); + server_address = strndup(new_host, MAX_IPV4_HOSTLENGTH); + } + if (!(followsticky & STICKY_PORT)) { + server_port = (unsigned short)new_port; + } + + free(host_name); + host_name = strndup(new_host, MAX_IPV4_HOSTLENGTH); + + /* reset virtual port */ + virtual_port = server_port; + + free(new_host); + free(server_url); + server_url = new_url; + + uriFreeUriMembersA(&uri); + + if (verbose) + printf(_("Redirection to %s://%s:%d%s\n"), use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port, + server_url); + + /* TODO: the hash component MUST be taken from the original URL and + * attached to the URL in Location + */ + + cleanup(); + check_http(); } /* check whether a file exists */ -void -test_file (char *path) -{ - if (access(path, R_OK) == 0) - return; - usage2 (_("file does not exist or is not readable"), path); +void test_file(char *path) { + if (access(path, R_OK) == 0) + return; + usage2(_("file does not exist or is not readable"), path); } -bool -process_arguments (int argc, char **argv) -{ - char *p; - int c = 1; - char *temp; - - enum { - INVERT_REGEX = CHAR_MAX + 1, - SNI_OPTION, - MAX_REDIRS_OPTION, - CONTINUE_AFTER_CHECK_CERT, - CA_CERT_OPTION, - HTTP_VERSION_OPTION, - AUTOMATIC_DECOMPRESSION, - COOKIE_JAR, - HAPROXY_PROTOCOL, - STATE_REGEX - }; - - int option = 0; - int got_plus = 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'}, - {"ca-cert", required_argument, 0, CA_CERT_OPTION}, - {"verify-cert", no_argument, 0, 'D'}, - {"continue-after-certificate", no_argument, 0, CONTINUE_AFTER_CHECK_CERT}, - {"useragent", required_argument, 0, 'A'}, - {"header", required_argument, 0, 'k'}, - {"no-body", no_argument, 0, 'N'}, - {"max-age", required_argument, 0, 'M'}, - {"content-type", required_argument, 0, 'T'}, - {"pagesize", required_argument, 0, 'm'}, - {"invert-regex", no_argument, NULL, INVERT_REGEX}, - {"state-regex", required_argument, 0, STATE_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}, - {"http-version", required_argument, 0, HTTP_VERSION_OPTION}, - {"enable-automatic-decompression", no_argument, 0, AUTOMATIC_DECOMPRESSION}, - {"cookie-jar", required_argument, 0, COOKIE_JAR}, - {"haproxy-protocol", no_argument, 0, HAPROXY_PROTOCOL}, - {0, 0, 0, 0} - }; - - if (argc < 2) - return false; - - /* support check_http compatible arguments */ - 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"); - } - - server_url = strdup(DEFAULT_SERVER_URL); - - while (1) { - c = getopt_long (argc, argv, "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:d:e:p:s:R:r:u:f:C:J:K:DnlLS::m:M:NEB", longopts, &option); - if (c == -1 || c == EOF || c == 1) - break; - - switch (c) { - case 'h': - print_help(); - exit(STATE_UNKNOWN); - break; - case 'V': - print_revision(progname, NP_VERSION); - print_curl_version(); - exit(STATE_UNKNOWN); - break; - case 'v': - verbose++; - break; - case 't': /* timeout period */ - if (!is_intnonneg (optarg)) - usage2 (_("Timeout interval must be a positive integer"), optarg); - else - socket_timeout = (int)strtol (optarg, NULL, 10); - break; - case 'c': /* critical time threshold */ - critical_thresholds = optarg; - break; - case 'w': /* warning time threshold */ - warning_thresholds = optarg; - break; - case 'H': /* virtual host */ - host_name = strdup (optarg); - if (host_name[0] == '[') { - 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); - } - } 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); - } - break; - case 'I': /* internet address */ - server_address = strdup (optarg); - break; - case 'u': /* URL path */ - server_url = strdup (optarg); - break; - case 'p': /* Server port */ - if (!is_intnonneg (optarg)) - usage2 (_("Invalid port number, expecting a non-negative number"), optarg); - else { - 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; - } - break; - case 'a': /* authorization info */ - 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); - 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) - http_method = strdup("POST"); - break; - case 'j': /* Set HTTP method */ - if (http_method) - free(http_method); - http_method = strdup (optarg); - break; - case 'A': /* useragent */ - strncpy (user_agent, optarg, DEFAULT_BUFFER_SIZE); - user_agent[DEFAULT_BUFFER_SIZE-1] = '\0'; - break; - case 'k': /* Additional headers */ - if (http_opt_headers_count == 0) - 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[http_opt_headers_count - 1] = optarg; - break; - case 'L': /* show html link */ - display_html = true; - break; - case 'n': /* do not show html link */ - display_html = false; - break; - case 'C': /* Check SSL cert validity */ +bool process_arguments(int argc, char **argv) { + char *p; + int c = 1; + char *temp; + + enum { + INVERT_REGEX = CHAR_MAX + 1, + SNI_OPTION, + MAX_REDIRS_OPTION, + CONTINUE_AFTER_CHECK_CERT, + CA_CERT_OPTION, + HTTP_VERSION_OPTION, + AUTOMATIC_DECOMPRESSION, + COOKIE_JAR, + HAPROXY_PROTOCOL, + STATE_REGEX + }; + + int option = 0; + int got_plus = 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'}, + {"ca-cert", required_argument, 0, CA_CERT_OPTION}, + {"verify-cert", no_argument, 0, 'D'}, + {"continue-after-certificate", no_argument, 0, CONTINUE_AFTER_CHECK_CERT}, + {"useragent", required_argument, 0, 'A'}, + {"header", required_argument, 0, 'k'}, + {"no-body", no_argument, 0, 'N'}, + {"max-age", required_argument, 0, 'M'}, + {"content-type", required_argument, 0, 'T'}, + {"pagesize", required_argument, 0, 'm'}, + {"invert-regex", no_argument, NULL, INVERT_REGEX}, + {"state-regex", required_argument, 0, STATE_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}, + {"http-version", required_argument, 0, HTTP_VERSION_OPTION}, + {"enable-automatic-decompression", no_argument, 0, AUTOMATIC_DECOMPRESSION}, + {"cookie-jar", required_argument, 0, COOKIE_JAR}, + {"haproxy-protocol", no_argument, 0, HAPROXY_PROTOCOL}, + {0, 0, 0, 0}}; + + if (argc < 2) + return false; + + /* support check_http compatible arguments */ + 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"); + } + + server_url = strdup(DEFAULT_SERVER_URL); + + while (1) { + c = getopt_long(argc, argv, "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:d:e:p:s:R:r:u:f:C:J:K:DnlLS::m:M:NEB", longopts, &option); + if (c == -1 || c == EOF || c == 1) + break; + + switch (c) { + case 'h': + print_help(); + exit(STATE_UNKNOWN); + break; + case 'V': + print_revision(progname, NP_VERSION); + print_curl_version(); + exit(STATE_UNKNOWN); + break; + case 'v': + verbose++; + break; + case 't': /* timeout period */ + if (!is_intnonneg(optarg)) + usage2(_("Timeout interval must be a positive integer"), optarg); + else + socket_timeout = (int)strtol(optarg, NULL, 10); + break; + case 'c': /* critical time threshold */ + critical_thresholds = optarg; + break; + case 'w': /* warning time threshold */ + warning_thresholds = optarg; + break; + case 'H': /* virtual host */ + host_name = strdup(optarg); + if (host_name[0] == '[') { + 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); + } + } 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); + } + break; + case 'I': /* internet address */ + server_address = strdup(optarg); + break; + case 'u': /* URL path */ + server_url = strdup(optarg); + break; + case 'p': /* Server port */ + if (!is_intnonneg(optarg)) + usage2(_("Invalid port number, expecting a non-negative number"), optarg); + else { + 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; + } + break; + case 'a': /* authorization info */ + 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); + 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) + http_method = strdup("POST"); + break; + case 'j': /* Set HTTP method */ + if (http_method) + free(http_method); + http_method = strdup(optarg); + break; + case 'A': /* useragent */ + strncpy(user_agent, optarg, DEFAULT_BUFFER_SIZE); + user_agent[DEFAULT_BUFFER_SIZE - 1] = '\0'; + break; + case 'k': /* Additional headers */ + if (http_opt_headers_count == 0) + 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[http_opt_headers_count - 1] = optarg; + break; + case 'L': /* show html link */ + display_html = true; + break; + case 'n': /* do not show html link */ + display_html = false; + break; + case 'C': /* Check SSL cert validity */ #ifdef LIBCURL_FEATURE_SSL - 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++; - 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; + 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++; + 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; + continue_after_check_cert = true; + break; #endif - case 'J': /* use client certificate */ + case 'J': /* use client certificate */ #ifdef LIBCURL_FEATURE_SSL - test_file(optarg); - client_cert = optarg; - goto enable_ssl; + test_file(optarg); + client_cert = optarg; + goto enable_ssl; #endif - case 'K': /* use client private key */ + case 'K': /* use client private key */ #ifdef LIBCURL_FEATURE_SSL - test_file(optarg); - client_privkey = optarg; - goto enable_ssl; + test_file(optarg); + client_privkey = optarg; + goto enable_ssl; #endif #ifdef LIBCURL_FEATURE_SSL - case CA_CERT_OPTION: /* use CA chain file */ - test_file(optarg); - ca_cert = optarg; - goto enable_ssl; + case CA_CERT_OPTION: /* use CA chain file */ + test_file(optarg); + ca_cert = optarg; + goto enable_ssl; #endif #ifdef LIBCURL_FEATURE_SSL - case 'D': /* verify peer certificate & host */ - verify_peer_and_host = true; - break; + case 'D': /* verify peer certificate & host */ + verify_peer_and_host = true; + break; #endif - case 'S': /* use SSL */ + case 'S': /* use SSL */ #ifdef LIBCURL_FEATURE_SSL - enable_ssl: - 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 */ - ssl_version = CURL_SSLVERSION_DEFAULT; - if (c=='S' && optarg != NULL) { - char *plus_ptr = strchr(optarg, '+'); - if (plus_ptr) { - got_plus = 1; - *plus_ptr = '\0'; - } - - if (optarg[0] == '2') - ssl_version = CURL_SSLVERSION_SSLv2; - else if (optarg[0] == '3') - ssl_version = CURL_SSLVERSION_SSLv3; - else if (!strcmp (optarg, "1") || !strcmp (optarg, "1.0")) -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) - ssl_version = CURL_SSLVERSION_TLSv1_0; -#else - ssl_version = CURL_SSLVERSION_DEFAULT; -#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ - else if (!strcmp (optarg, "1.1")) -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) - ssl_version = CURL_SSLVERSION_TLSv1_1; -#else - ssl_version = CURL_SSLVERSION_DEFAULT; -#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ - else if (!strcmp (optarg, "1.2")) -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) - ssl_version = CURL_SSLVERSION_TLSv1_2; -#else - ssl_version = CURL_SSLVERSION_DEFAULT; -#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ - else if (!strcmp (optarg, "1.3")) -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0) - ssl_version = CURL_SSLVERSION_TLSv1_3; -#else - ssl_version = CURL_SSLVERSION_DEFAULT; -#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0) */ - else - usage4 (_("Invalid option - Valid SSL/TLS versions: 2, 3, 1, 1.1, 1.2, 1.3 (with optional '+' suffix)")); - } -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0) - if (got_plus) { - switch (ssl_version) { - case CURL_SSLVERSION_TLSv1_3: - ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3; - break; - case CURL_SSLVERSION_TLSv1_2: - case CURL_SSLVERSION_TLSv1_1: - case CURL_SSLVERSION_TLSv1_0: - ssl_version |= CURL_SSLVERSION_MAX_DEFAULT; - break; - } - } else { - switch (ssl_version) { - case CURL_SSLVERSION_TLSv1_3: - ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3; - break; - case CURL_SSLVERSION_TLSv1_2: - ssl_version |= CURL_SSLVERSION_MAX_TLSv1_2; - break; - case CURL_SSLVERSION_TLSv1_1: - ssl_version |= CURL_SSLVERSION_MAX_TLSv1_1; - break; - case CURL_SSLVERSION_TLSv1_0: - ssl_version |= CURL_SSLVERSION_MAX_TLSv1_0; - break; - } - } -#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) - 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; - break; + enable_ssl: + 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 */ + ssl_version = CURL_SSLVERSION_DEFAULT; + if (c == 'S' && optarg != NULL) { + char *plus_ptr = strchr(optarg, '+'); + if (plus_ptr) { + got_plus = 1; + *plus_ptr = '\0'; + } + + if (optarg[0] == '2') + ssl_version = CURL_SSLVERSION_SSLv2; + else if (optarg[0] == '3') + ssl_version = CURL_SSLVERSION_SSLv3; + else if (!strcmp(optarg, "1") || !strcmp(optarg, "1.0")) +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) + ssl_version = CURL_SSLVERSION_TLSv1_0; +# else + ssl_version = CURL_SSLVERSION_DEFAULT; +# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ + else if (!strcmp(optarg, "1.1")) +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) + ssl_version = CURL_SSLVERSION_TLSv1_1; +# else + ssl_version = CURL_SSLVERSION_DEFAULT; +# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ + else if (!strcmp(optarg, "1.2")) +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) + ssl_version = CURL_SSLVERSION_TLSv1_2; +# else + ssl_version = CURL_SSLVERSION_DEFAULT; +# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ + else if (!strcmp(optarg, "1.3")) +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0) + ssl_version = CURL_SSLVERSION_TLSv1_3; +# else + ssl_version = CURL_SSLVERSION_DEFAULT; +# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0) */ + else + usage4(_("Invalid option - Valid SSL/TLS versions: 2, 3, 1, 1.1, 1.2, 1.3 (with optional '+' suffix)")); + } +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0) + if (got_plus) { + switch (ssl_version) { + case CURL_SSLVERSION_TLSv1_3: + ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3; + break; + case CURL_SSLVERSION_TLSv1_2: + case CURL_SSLVERSION_TLSv1_1: + case CURL_SSLVERSION_TLSv1_0: + ssl_version |= CURL_SSLVERSION_MAX_DEFAULT; + break; + } + } else { + switch (ssl_version) { + case CURL_SSLVERSION_TLSv1_3: + ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3; + break; + case CURL_SSLVERSION_TLSv1_2: + ssl_version |= CURL_SSLVERSION_MAX_TLSv1_2; + break; + case CURL_SSLVERSION_TLSv1_1: + ssl_version |= CURL_SSLVERSION_MAX_TLSv1_1; + break; + case CURL_SSLVERSION_TLSv1_0: + ssl_version |= CURL_SSLVERSION_MAX_TLSv1_0; + break; + } + } +# 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) + 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; + break; #endif /* LIBCURL_FEATURE_SSL */ - case MAX_REDIRS_OPTION: - if (!is_intnonneg (optarg)) - usage2 (_("Invalid max_redirs count"), optarg); - else { - max_depth = atoi (optarg); - } - break; - case 'f': /* onredirect */ - if (!strcmp (optarg, "ok")) - onredirect = STATE_OK; - else if (!strcmp (optarg, "warning")) - onredirect = STATE_WARNING; - else if (!strcmp (optarg, "critical")) - onredirect = STATE_CRITICAL; - else if (!strcmp (optarg, "unknown")) - onredirect = STATE_UNKNOWN; - else if (!strcmp (optarg, "follow")) - onredirect = STATE_DEPENDENT; - else if (!strcmp (optarg, "stickyport")) - onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_HOST|STICKY_PORT; - else if (!strcmp (optarg, "sticky")) - onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_HOST; - else if (!strcmp (optarg, "follow")) - onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_NONE; - else if (!strcmp (optarg, "curl")) - onredirect = STATE_DEPENDENT, followmethod = FOLLOW_LIBCURL; - else usage2 (_("Invalid onredirect option"), optarg); - if (verbose >= 2) - printf(_("* Following redirects set to %s\n"), state_text(onredirect)); - break; - case 'd': /* string or substring */ - 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); - string_expect[MAX_INPUT_BUFFER - 1] = 0; - break; - case 'e': /* string or substring */ - strncpy (server_expect, optarg, MAX_INPUT_BUFFER - 1); - server_expect[MAX_INPUT_BUFFER - 1] = 0; - server_expect_yn = 1; - break; - case 'T': /* Content-type */ - http_content_type = strdup (optarg); - break; - case 'l': /* linespan */ - cflags &= ~REG_NEWLINE; - break; - case 'R': /* regex */ - cflags |= REG_ICASE; + case MAX_REDIRS_OPTION: + if (!is_intnonneg(optarg)) + usage2(_("Invalid max_redirs count"), optarg); + else { + max_depth = atoi(optarg); + } + break; + case 'f': /* onredirect */ + if (!strcmp(optarg, "ok")) + onredirect = STATE_OK; + else if (!strcmp(optarg, "warning")) + onredirect = STATE_WARNING; + else if (!strcmp(optarg, "critical")) + onredirect = STATE_CRITICAL; + else if (!strcmp(optarg, "unknown")) + onredirect = STATE_UNKNOWN; + else if (!strcmp(optarg, "follow")) + onredirect = STATE_DEPENDENT; + else if (!strcmp(optarg, "stickyport")) + onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_HOST | STICKY_PORT; + else if (!strcmp(optarg, "sticky")) + onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_HOST; + else if (!strcmp(optarg, "follow")) + onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_NONE; + else if (!strcmp(optarg, "curl")) + onredirect = STATE_DEPENDENT, followmethod = FOLLOW_LIBCURL; + else + usage2(_("Invalid onredirect option"), optarg); + if (verbose >= 2) + printf(_("* Following redirects set to %s\n"), state_text(onredirect)); + break; + case 'd': /* string or substring */ + 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); + string_expect[MAX_INPUT_BUFFER - 1] = 0; + break; + case 'e': /* string or substring */ + strncpy(server_expect, optarg, MAX_INPUT_BUFFER - 1); + server_expect[MAX_INPUT_BUFFER - 1] = 0; + server_expect_yn = 1; + break; + case 'T': /* Content-type */ + http_content_type = strdup(optarg); + break; + case 'l': /* linespan */ + cflags &= ~REG_NEWLINE; + break; + case 'R': /* regex */ + cflags |= REG_ICASE; // fall through - case 'r': /* regex */ - strncpy (regexp, optarg, MAX_RE_SIZE - 1); - regexp[MAX_RE_SIZE - 1] = 0; - errcode = regcomp (&preg, regexp, cflags); - if (errcode != 0) { - (void) regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); - printf (_("Could Not Compile Regular Expression: %s"), errbuf); - return false; - } - break; - case INVERT_REGEX: - invert_regex = true; - break; - case STATE_REGEX: - if (!strcasecmp (optarg, "critical")) - state_regex = STATE_CRITICAL; - else if (!strcasecmp (optarg, "warning")) - state_regex = STATE_WARNING; - else usage2 (_("Invalid state-regex option"), optarg); - break; - case '4': - address_family = AF_INET; - break; - case '6': -#if defined (USE_IPV6) && defined (LIBCURL_FEATURE_IPV6) - address_family = AF_INET6; + case 'r': /* regex */ + strncpy(regexp, optarg, MAX_RE_SIZE - 1); + regexp[MAX_RE_SIZE - 1] = 0; + errcode = regcomp(&preg, regexp, cflags); + if (errcode != 0) { + (void)regerror(errcode, &preg, errbuf, MAX_INPUT_BUFFER); + printf(_("Could Not Compile Regular Expression: %s"), errbuf); + return false; + } + break; + case INVERT_REGEX: + invert_regex = true; + break; + case STATE_REGEX: + if (!strcasecmp(optarg, "critical")) + state_regex = STATE_CRITICAL; + else if (!strcasecmp(optarg, "warning")) + state_regex = STATE_WARNING; + else + usage2(_("Invalid state-regex option"), optarg); + break; + case '4': + address_family = AF_INET; + break; + case '6': +#if defined(USE_IPV6) && defined(LIBCURL_FEATURE_IPV6) + address_family = AF_INET6; #else - usage4 (_("IPv6 support not available")); + usage4(_("IPv6 support not available")); #endif - 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); - } else - min_page_len = atoi(tmp); - - tmp = strtok(NULL, ":"); - if (tmp == NULL) { - printf("Bad format: try \"-m min:max\"\n"); - exit (STATE_WARNING); - } else - max_page_len = atoi(tmp); - } else - 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); - } - if (verbose >= 2) - printf ("* Maximal age of document set to %d seconds\n", maximum_age); - } - break; - case 'E': /* show extended perfdata */ - show_extended_perfdata = true; - break; - case 'B': /* print body content after status line */ - show_body = true; - break; - case HTTP_VERSION_OPTION: - curl_http_version = CURL_HTTP_VERSION_NONE; - if (strcmp (optarg, "1.0") == 0) { - curl_http_version = CURL_HTTP_VERSION_1_0; - } else if (strcmp (optarg, "1.1") == 0) { - curl_http_version = CURL_HTTP_VERSION_1_1; - } else if ((strcmp (optarg, "2.0") == 0) || (strcmp (optarg, "2") == 0)) { + 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); + } else + min_page_len = atoi(tmp); + + tmp = strtok(NULL, ":"); + if (tmp == NULL) { + printf("Bad format: try \"-m min:max\"\n"); + exit(STATE_WARNING); + } else + max_page_len = atoi(tmp); + } else + 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); + } + if (verbose >= 2) + printf("* Maximal age of document set to %d seconds\n", maximum_age); + } break; + case 'E': /* show extended perfdata */ + show_extended_perfdata = true; + break; + case 'B': /* print body content after status line */ + show_body = true; + break; + case HTTP_VERSION_OPTION: + curl_http_version = CURL_HTTP_VERSION_NONE; + if (strcmp(optarg, "1.0") == 0) { + curl_http_version = CURL_HTTP_VERSION_1_0; + } else if (strcmp(optarg, "1.1") == 0) { + curl_http_version = CURL_HTTP_VERSION_1_1; + } else if ((strcmp(optarg, "2.0") == 0) || (strcmp(optarg, "2") == 0)) { #if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 33, 0) - curl_http_version = CURL_HTTP_VERSION_2_0; + curl_http_version = CURL_HTTP_VERSION_2_0; #else - curl_http_version = CURL_HTTP_VERSION_NONE; + curl_http_version = CURL_HTTP_VERSION_NONE; #endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 33, 0) */ - } else { - fprintf (stderr, "unknown http-version parameter: %s\n", optarg); - exit (STATE_WARNING); - } - break; - case AUTOMATIC_DECOMPRESSION: - automatic_decompression = true; - break; - case COOKIE_JAR: - cookie_jar_file = optarg; - break; - case HAPROXY_PROTOCOL: - haproxy_protocol = true; - break; - case '?': - /* print short usage statement if args not parsable */ - usage5 (); - break; - } - } - - c = optind; - - if (server_address == NULL && c < argc) - server_address = strdup (argv[c++]); - - if (host_name == NULL && c < argc) - host_name = strdup (argv[c++]); - - if (server_address == NULL) { - if (host_name == NULL) - usage4 (_("You must specify a server address or host name")); - else - server_address = strdup (host_name); - } - - set_thresholds(&thlds, warning_thresholds, critical_thresholds); - - if (critical_thresholds && thlds->critical->end>(double)socket_timeout) - socket_timeout = (int)thlds->critical->end + 1; - if (verbose >= 2) - printf ("* Socket timeout set to %ld seconds\n", socket_timeout); - - if (http_method == NULL) - http_method = strdup ("GET"); - - if (client_cert && !client_privkey) - usage4 (_("If you use a client certificate you must also specify a private key file")); - - if (virtual_port == 0) - virtual_port = server_port; - else { - if ((use_ssl && server_port == HTTPS_PORT) || (!use_ssl && server_port == HTTP_PORT)) - if(!specify_port) - server_port = virtual_port; - } - - return true; + } else { + fprintf(stderr, "unknown http-version parameter: %s\n", optarg); + exit(STATE_WARNING); + } + break; + case AUTOMATIC_DECOMPRESSION: + automatic_decompression = true; + break; + case COOKIE_JAR: + cookie_jar_file = optarg; + break; + case HAPROXY_PROTOCOL: + haproxy_protocol = true; + break; + case '?': + /* print short usage statement if args not parsable */ + usage5(); + break; + } + } + + c = optind; + + if (server_address == NULL && c < argc) + server_address = strdup(argv[c++]); + + if (host_name == NULL && c < argc) + host_name = strdup(argv[c++]); + + if (server_address == NULL) { + if (host_name == NULL) + usage4(_("You must specify a server address or host name")); + else + server_address = strdup(host_name); + } + + set_thresholds(&thlds, warning_thresholds, critical_thresholds); + + if (critical_thresholds && thlds->critical->end > (double)socket_timeout) + socket_timeout = (int)thlds->critical->end + 1; + if (verbose >= 2) + printf("* Socket timeout set to %ld seconds\n", socket_timeout); + + if (http_method == NULL) + http_method = strdup("GET"); + + if (client_cert && !client_privkey) + usage4(_("If you use a client certificate you must also specify a private key file")); + + if (virtual_port == 0) + virtual_port = server_port; + else { + if ((use_ssl && server_port == HTTPS_PORT) || (!use_ssl && server_port == HTTP_PORT)) + if (!specify_port) + server_port = virtual_port; + } + + 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); +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 ("\n"); - printf ("%s\n", _("It makes use of libcurl to do so. It tries to be as compatible to check_http")); - printf ("%s\n", _("as possible.")); + 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"); + printf("%s\n", _("It makes use of libcurl to do so. It tries to be as compatible to check_http")); + printf("%s\n", _("as possible.")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - 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 LIBCURL_FEATURE_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, 1.3 = TLSv1.3). With a '+' suffix, newer versions are also accepted.")); - printf (" %s\n", _("Note: SSLv2 and SSLv3 are deprecated and are usually disabled in libcurl")); - printf (" %s\n", "--sni"); - printf (" %s\n", _("Enable SSL/TLS hostname extension support (SNI)")); -#if LIBCURL_VERSION_NUM >= 0x071801 - printf (" %s\n", _("Note: --sni is the default in libcurl as SSLv2 and SSLV3 are deprecated and")); - printf (" %s\n", _(" SNI only really works since TLSv1.0")); -#else - printf (" %s\n", _("Note: SNI is not supported in libcurl before 7.18.1")); -#endif - printf (" %s\n", "-C, --certificate=INTEGER[,INTEGER]"); - printf (" %s\n", _("Minimum number of days a certificate has to be valid. Port defaults to 443.")); - printf (" %s\n", _("A STATE_WARNING is returned if the certificate has a validity less than the")); - printf (" %s\n", _("first agument's value. If there is a second argument and the certificate's")); - printf (" %s\n", _("validity is less than its value, a STATE_CRITICAL is returned.")); - 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", "--ca-cert=FILE"); - printf (" %s\n", _("CA certificate file to verify peer against")); - printf (" %s\n", "-D, --verify-cert"); - printf (" %s\n", _("Verify the peer's SSL certificate and hostname")); + 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, 1.3 = TLSv1.3). With a '+' suffix, newer versions are also accepted.")); + printf(" %s\n", _("Note: SSLv2 and SSLv3 are deprecated and are usually disabled in libcurl")); + printf(" %s\n", "--sni"); + printf(" %s\n", _("Enable SSL/TLS hostname extension support (SNI)")); +# if LIBCURL_VERSION_NUM >= 0x071801 + printf(" %s\n", _("Note: --sni is the default in libcurl as SSLv2 and SSLV3 are deprecated and")); + printf(" %s\n", _(" SNI only really works since TLSv1.0")); +# else + printf(" %s\n", _("Note: SNI is not supported in libcurl before 7.18.1")); +# endif + printf(" %s\n", "-C, --certificate=INTEGER[,INTEGER]"); + printf(" %s\n", _("Minimum number of days a certificate has to be valid. Port defaults to 443.")); + printf(" %s\n", _("A STATE_WARNING is returned if the certificate has a validity less than the")); + printf(" %s\n", _("first agument's value. If there is a second argument and the certificate's")); + printf(" %s\n", _("validity is less than its value, a STATE_CRITICAL is returned.")); + 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", "--ca-cert=FILE"); + printf(" %s\n", _("CA certificate file to verify peer against")); + printf(" %s\n", "-D, --verify-cert"); + printf(" %s\n", _("Verify the peer's SSL certificate and hostname")); #endif - printf (" %s\n", "-e, --expect=STRING"); - 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 decoded http POST data")); - printf (" %s\n", "-j, --method=STRING (for example: HEAD, OPTIONS, TRACE, PUT, DELETE, CONNECT)"); - 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 STATE if found, OK if not (STATE is CRITICAL, per default)")); - printf (" %s\n", _("can be changed with --state--regex)")); - printf (" %s\n", "--state-regex=STATE"); - printf (" %s\n", _("Return STATE if regex is found, OK if not. STATE can be one of \"critical\",\"warning\"")); - 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", _("follow uses the old redirection algorithm of check_http.")); - printf (" %s\n", _("curl uses CURL_FOLLOWLOCATION built into libcurl.")); - printf (" %s\n", "--max-redirs=INTEGER"); - printf (" %s", _("Maximal number of redirects (default: ")); - printf ("%d)\n", DEFAULT_MAX_REDIRS); - printf (" %s\n", "-m, --pagesize=INTEGER<:INTEGER>"); - printf (" %s\n", _("Minimum page size required (bytes) : Maximum page size required (bytes)")); - printf ("\n"); - printf (" %s\n", "--http-version=VERSION"); - printf (" %s\n", _("Connect via specific HTTP protocol.")); - printf (" %s\n", _("1.0 = HTTP/1.0, 1.1 = HTTP/1.1, 2.0 = HTTP/2 (HTTP/2 will fail without -S)")); - printf (" %s\n", "--enable-automatic-decompression"); - printf (" %s\n", _("Enable automatic decompression of body (CURLOPT_ACCEPT_ENCODING).")); - printf(" %s\n", "--haproxy-protocol"); - printf(" %s\n", _("Send HAProxy proxy protocol v1 header (CURLOPT_HAPROXYPROTOCOL).")); - 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); - - 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 decoded http POST data")); + printf(" %s\n", "-j, --method=STRING (for example: HEAD, OPTIONS, TRACE, PUT, DELETE, CONNECT)"); + 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 STATE if found, OK if not (STATE is CRITICAL, per default)")); + printf(" %s\n", _("can be changed with --state--regex)")); + printf(" %s\n", "--state-regex=STATE"); + printf(" %s\n", _("Return STATE if regex is found, OK if not. STATE can be one of \"critical\",\"warning\"")); + 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", _("follow uses the old redirection algorithm of check_http.")); + printf(" %s\n", _("curl uses CURL_FOLLOWLOCATION built into libcurl.")); + printf(" %s\n", "--max-redirs=INTEGER"); + printf(" %s", _("Maximal number of redirects (default: ")); + printf("%d)\n", DEFAULT_MAX_REDIRS); + printf(" %s\n", "-m, --pagesize=INTEGER<:INTEGER>"); + printf(" %s\n", _("Minimum page size required (bytes) : Maximum page size required (bytes)")); + printf("\n"); + printf(" %s\n", "--http-version=VERSION"); + printf(" %s\n", _("Connect via specific HTTP protocol.")); + printf(" %s\n", _("1.0 = HTTP/1.0, 1.1 = HTTP/1.1, 2.0 = HTTP/2 (HTTP/2 will fail without -S)")); + printf(" %s\n", "--enable-automatic-decompression"); + printf(" %s\n", _("Enable automatic decompression of body (CURLOPT_ACCEPT_ENCODING).")); + printf(" %s\n", "--haproxy-protocol"); + printf(" %s\n", _("Send HAProxy proxy protocol v1 header (CURLOPT_HAPROXYPROTOCOL).")); + 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); + + 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 LIBCURL_FEATURE_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_curl -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_curl -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_curl -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("\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_curl -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_curl -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_curl -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")); #endif - printf ("\n %s\n", "CHECK WEBSERVER CONTENT VIA PROXY:"); - printf (" %s\n", _("It is recommended to use an environment proxy like:")); - printf (" %s\n", _("http_proxy=http://192.168.100.35:3128 ./check_curl -H www.monitoring-plugins.org")); - printf (" %s\n", _("legacy proxy requests in check_http style still work:")); - printf (" %s\n", _("check_curl -I 192.168.100.35 -p 3128 -u http://www.monitoring-plugins.org/ -H www.monitoring-plugins.org")); + printf("\n %s\n", "CHECK WEBSERVER CONTENT VIA PROXY:"); + printf(" %s\n", _("It is recommended to use an environment proxy like:")); + printf(" %s\n", _("http_proxy=http://192.168.100.35:3128 ./check_curl -H www.monitoring-plugins.org")); + printf(" %s\n", _("legacy proxy requests in check_http style still work:")); + printf(" %s\n", _("check_curl -I 192.168.100.35 -p 3128 -u http://www.monitoring-plugins.org/ -H www.monitoring-plugins.org")); #ifdef LIBCURL_FEATURE_SSL - printf ("\n %s\n", "CHECK SSL WEBSERVER CONTENT VIA PROXY USING HTTP 1.1 CONNECT: "); - printf (" %s\n", _("It is recommended to use an environment proxy like:")); - printf (" %s\n", _("https_proxy=http://192.168.100.35:3128 ./check_curl -H www.verisign.com -S")); - printf (" %s\n", _("legacy proxy requests in check_http style still work:")); - printf (" %s\n", _("check_curl -I 192.168.100.35 -p 3128 -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.")); + printf("\n %s\n", "CHECK SSL WEBSERVER CONTENT VIA PROXY USING HTTP 1.1 CONNECT: "); + printf(" %s\n", _("It is recommended to use an environment proxy like:")); + printf(" %s\n", _("https_proxy=http://192.168.100.35:3128 ./check_curl -H www.verisign.com -S")); + printf(" %s\n", _("legacy proxy requests in check_http style still work:")); + printf(" %s\n", _("check_curl -I 192.168.100.35 -p 3128 -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.")); #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 ] [--ca-cert ] [-D]\n"); - printf (" [-w ] [-c ] [-t ] [-L] [-E] [-a auth]\n"); - printf (" [-b proxy_auth] [-f ]\n"); - printf (" [-e ] [-d string] [-s string] [-l] [-r | -R ]\n"); - printf (" [-P string] [-m :] [-4|-6] [-N] [-M ]\n"); - printf (" [-A string] [-k string] [-S ] [--sni] [--haproxy-protocol]\n"); - printf (" [-T ] [-j method]\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"); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf(" %s -H | -I [-u ] [-p ]\n", progname); + printf(" [-J ] [-K ] [--ca-cert ] [-D]\n"); + printf(" [-w ] [-c ] [-t ] [-L] [-E] [-a auth]\n"); + printf(" [-b proxy_auth] [-f ]\n"); + printf(" [-e ] [-d string] [-s string] [-l] [-r | -R ]\n"); + printf(" [-P string] [-m :] [-4|-6] [-N] [-M ]\n"); + printf(" [-A string] [-k string] [-S ] [--sni] [--haproxy-protocol]\n"); + printf(" [-T ] [-j method]\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"); #ifdef LIBCURL_FEATURE_SSL - printf ("%s\n", _("In the first form, make an HTTP request.")); - printf ("%s\n\n", _("In the second form, connect to the server and check the TLS certificate.")); + printf("%s\n", _("In the first form, make an HTTP request.")); + printf("%s\n\n", _("In the second form, connect to the server and check the TLS certificate.")); #endif } -void -print_curl_version (void) -{ - printf( "%s\n", curl_version()); -} +void print_curl_version(void) { printf("%s\n", curl_version()); } -int -curlhelp_initwritebuffer (curlhelp_write_curlbuf *buf) -{ - buf->bufsize = DEFAULT_BUFFER_SIZE; - buf->buflen = 0; - buf->buf = (char *)malloc ((size_t)buf->bufsize); - if (buf->buf == NULL) return -1; - return 0; +int curlhelp_initwritebuffer(curlhelp_write_curlbuf *buf) { + buf->bufsize = DEFAULT_BUFFER_SIZE; + buf->buflen = 0; + buf->buf = (char *)malloc((size_t)buf->bufsize); + if (buf->buf == NULL) + return -1; + return 0; } -size_t curlhelp_buffer_write_callback (void *buffer, size_t size, size_t nmemb, void *stream) -{ - curlhelp_write_curlbuf *buf = (curlhelp_write_curlbuf *)stream; +size_t curlhelp_buffer_write_callback(void *buffer, size_t size, size_t nmemb, void *stream) { + curlhelp_write_curlbuf *buf = (curlhelp_write_curlbuf *)stream; - while (buf->bufsize < buf->buflen + size * nmemb + 1) { - buf->bufsize = buf->bufsize * 2; - buf->buf = (char *)realloc (buf->buf, buf->bufsize); - if (buf->buf == NULL) { - fprintf(stderr, "malloc failed (%d) %s\n", errno, strerror(errno)); - return -1; - } - } + while (buf->bufsize < buf->buflen + size * nmemb + 1) { + buf->bufsize = buf->bufsize * 2; + buf->buf = (char *)realloc(buf->buf, buf->bufsize); + if (buf->buf == NULL) { + fprintf(stderr, "malloc failed (%d) %s\n", errno, strerror(errno)); + return -1; + } + } - memcpy (buf->buf + buf->buflen, buffer, size * nmemb); - buf->buflen += size * nmemb; - buf->buf[buf->buflen] = '\0'; + memcpy(buf->buf + buf->buflen, buffer, size * nmemb); + buf->buflen += size * nmemb; + buf->buf[buf->buflen] = '\0'; - return (int)(size * nmemb); + return (int)(size * nmemb); } -size_t curlhelp_buffer_read_callback(void *buffer, size_t size, size_t nmemb, void *stream) -{ - curlhelp_read_curlbuf *buf = (curlhelp_read_curlbuf *)stream; +size_t curlhelp_buffer_read_callback(void *buffer, size_t size, size_t nmemb, void *stream) { + curlhelp_read_curlbuf *buf = (curlhelp_read_curlbuf *)stream; - size_t n = min (nmemb * size, buf->buflen - buf->pos); + size_t n = min(nmemb * size, buf->buflen - buf->pos); - memcpy (buffer, buf->buf + buf->pos, n); - buf->pos += n; + memcpy(buffer, buf->buf + buf->pos, n); + buf->pos += n; - return (int)n; + return (int)n; } -void -curlhelp_freewritebuffer (curlhelp_write_curlbuf *buf) -{ - free (buf->buf); - buf->buf = NULL; +void curlhelp_freewritebuffer(curlhelp_write_curlbuf *buf) { + free(buf->buf); + buf->buf = NULL; } -int -curlhelp_initreadbuffer (curlhelp_read_curlbuf *buf, const char *data, size_t datalen) -{ - buf->buflen = datalen; - buf->buf = (char *)malloc ((size_t)buf->buflen); - if (buf->buf == NULL) return -1; - memcpy (buf->buf, data, datalen); - buf->pos = 0; - return 0; +int curlhelp_initreadbuffer(curlhelp_read_curlbuf *buf, const char *data, size_t datalen) { + buf->buflen = datalen; + buf->buf = (char *)malloc((size_t)buf->buflen); + if (buf->buf == NULL) + return -1; + memcpy(buf->buf, data, datalen); + buf->pos = 0; + return 0; } -void -curlhelp_freereadbuffer (curlhelp_read_curlbuf *buf) -{ - free (buf->buf); - buf->buf = NULL; +void curlhelp_freereadbuffer(curlhelp_read_curlbuf *buf) { + free(buf->buf); + buf->buf = NULL; } /* TODO: where to put this, it's actually part of sstrings2 (logically)? */ -const char* -strrstr2(const char *haystack, const char *needle) -{ - int counter; - size_t len; - const char *prev_pos; - const char *pos; - - if (haystack == NULL || needle == NULL) - return NULL; - - if (haystack[0] == '\0' || needle[0] == '\0') - return NULL; - - counter = 0; - prev_pos = NULL; - pos = haystack; - len = strlen (needle); - for (;;) { - pos = strstr (pos, needle); - if (pos == NULL) { - if (counter == 0) - return NULL; - else - return prev_pos; - } - counter++; - prev_pos = pos; - pos += len; - if (*pos == '\0') return prev_pos; - } +const char *strrstr2(const char *haystack, const char *needle) { + int counter; + size_t len; + const char *prev_pos; + const char *pos; + + if (haystack == NULL || needle == NULL) + return NULL; + + if (haystack[0] == '\0' || needle[0] == '\0') + return NULL; + + counter = 0; + prev_pos = NULL; + pos = haystack; + len = strlen(needle); + for (;;) { + pos = strstr(pos, needle); + if (pos == NULL) { + if (counter == 0) + return NULL; + else + return prev_pos; + } + counter++; + prev_pos = pos; + pos += len; + if (*pos == '\0') + return prev_pos; + } } -int -curlhelp_parse_statusline (const char *buf, curlhelp_statusline *status_line) -{ - char *first_line_end; - char *p; - size_t first_line_len; - char *pp; - const char *start; - char *first_line_buf; - - /* find last start of a new header */ - start = strrstr2 (buf, "\r\nHTTP/"); - if (start != NULL) { - start += 2; - buf = start; - } - - first_line_end = strstr(buf, "\r\n"); - if (first_line_end == NULL) return -1; - - first_line_len = (size_t)(first_line_end - buf); - status_line->first_line = (char *)malloc (first_line_len + 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'; - first_line_buf = strdup( status_line->first_line ); - - /* protocol and version: "HTTP/x.x" SP or "HTTP/2" SP */ - - p = strtok(first_line_buf, "/"); - if( p == NULL ) { free( first_line_buf ); return -1; } - if( strcmp( p, "HTTP" ) != 0 ) { free( first_line_buf ); return -1; } - - p = strtok( NULL, " " ); - if( p == NULL ) { free( first_line_buf ); return -1; } - if( strchr( p, '.' ) != NULL ) { - - /* HTTP 1.x case */ - strtok( p, "." ); - status_line->http_major = (int)strtol( p, &pp, 10 ); - if( *pp != '\0' ) { free( first_line_buf ); return -1; } - strtok( NULL, " " ); - status_line->http_minor = (int)strtol( p, &pp, 10 ); - if( *pp != '\0' ) { free( first_line_buf ); return -1; } - p += 4; /* 1.x SP */ - } else { - /* HTTP 2 case */ - status_line->http_major = (int)strtol( p, &pp, 10 ); - status_line->http_minor = 0; - p += 2; /* 2 SP */ - } - - /* status code: "404" or "404.1", then SP */ - - p = strtok( p, " " ); - if( p == NULL ) { free( first_line_buf ); return -1; } - if( strchr( p, '.' ) != NULL ) { - char *ppp; - ppp = strtok( p, "." ); - status_line->http_code = (int)strtol( ppp, &pp, 10 ); - if( *pp != '\0' ) { free( first_line_buf ); return -1; } - ppp = strtok( NULL, "" ); - status_line->http_subcode = (int)strtol( ppp, &pp, 10 ); - if( *pp != '\0' ) { free( first_line_buf ); return -1; } - p += 6; /* 400.1 SP */ - } else { - status_line->http_code = (int)strtol( p, &pp, 10 ); - status_line->http_subcode = -1; - if( *pp != '\0' ) { free( first_line_buf ); return -1; } - p += 4; /* 400 SP */ - } - - /* Human readable message: "Not Found" CRLF */ - - p = strtok( p, "" ); - if( p == NULL ) { status_line->msg = ""; return 0; } - status_line->msg = status_line->first_line + ( p - first_line_buf ); - free( first_line_buf ); - - return 0; -} +int curlhelp_parse_statusline(const char *buf, curlhelp_statusline *status_line) { + char *first_line_end; + char *p; + size_t first_line_len; + char *pp; + const char *start; + char *first_line_buf; + + /* find last start of a new header */ + start = strrstr2(buf, "\r\nHTTP/"); + if (start != NULL) { + start += 2; + buf = start; + } + + first_line_end = strstr(buf, "\r\n"); + if (first_line_end == NULL) + return -1; + + first_line_len = (size_t)(first_line_end - buf); + status_line->first_line = (char *)malloc(first_line_len + 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'; + first_line_buf = strdup(status_line->first_line); + + /* protocol and version: "HTTP/x.x" SP or "HTTP/2" SP */ + + p = strtok(first_line_buf, "/"); + if (p == NULL) { + free(first_line_buf); + return -1; + } + if (strcmp(p, "HTTP") != 0) { + free(first_line_buf); + return -1; + } + + p = strtok(NULL, " "); + if (p == NULL) { + free(first_line_buf); + return -1; + } + if (strchr(p, '.') != NULL) { + + /* HTTP 1.x case */ + strtok(p, "."); + status_line->http_major = (int)strtol(p, &pp, 10); + if (*pp != '\0') { + free(first_line_buf); + return -1; + } + strtok(NULL, " "); + status_line->http_minor = (int)strtol(p, &pp, 10); + if (*pp != '\0') { + free(first_line_buf); + return -1; + } + p += 4; /* 1.x SP */ + } else { + /* HTTP 2 case */ + status_line->http_major = (int)strtol(p, &pp, 10); + status_line->http_minor = 0; + p += 2; /* 2 SP */ + } -void -curlhelp_free_statusline (curlhelp_statusline *status_line) -{ - free (status_line->first_line); + /* status code: "404" or "404.1", then SP */ + + p = strtok(p, " "); + if (p == NULL) { + free(first_line_buf); + return -1; + } + if (strchr(p, '.') != NULL) { + char *ppp; + ppp = strtok(p, "."); + status_line->http_code = (int)strtol(ppp, &pp, 10); + if (*pp != '\0') { + free(first_line_buf); + return -1; + } + ppp = strtok(NULL, ""); + status_line->http_subcode = (int)strtol(ppp, &pp, 10); + if (*pp != '\0') { + free(first_line_buf); + return -1; + } + p += 6; /* 400.1 SP */ + } else { + status_line->http_code = (int)strtol(p, &pp, 10); + status_line->http_subcode = -1; + if (*pp != '\0') { + free(first_line_buf); + return -1; + } + p += 4; /* 400 SP */ + } + + /* Human readable message: "Not Found" CRLF */ + + p = strtok(p, ""); + if (p == NULL) { + status_line->msg = ""; + return 0; + } + status_line->msg = status_line->first_line + (p - first_line_buf); + free(first_line_buf); + + return 0; } -void -remove_newlines (char *s) -{ - char *p; +void curlhelp_free_statusline(curlhelp_statusline *status_line) { free(status_line->first_line); } - for (p = s; *p != '\0'; p++) - if (*p == '\r' || *p == '\n') - *p = ' '; +void remove_newlines(char *s) { + char *p; + + for (p = s; *p != '\0'; p++) + if (*p == '\r' || *p == '\n') + *p = ' '; } -char * -get_header_value (const struct phr_header* headers, const size_t nof_headers, const char* header) -{ - for(size_t i = 0; i < nof_headers; i++ ) { - if(headers[i].name != NULL && strncasecmp( header, headers[i].name, max( headers[i].name_len, 4 ) ) == 0 ) { - return strndup( headers[i].value, headers[i].value_len ); - } - } - return NULL; +char *get_header_value(const struct phr_header *headers, const size_t nof_headers, const char *header) { + for (size_t i = 0; i < nof_headers; i++) { + if (headers[i].name != NULL && strncasecmp(header, headers[i].name, max(headers[i].name_len, 4)) == 0) { + return strndup(headers[i].value, headers[i].value_len); + } + } + return NULL; } -int -check_document_dates (const curlhelp_write_curlbuf *header_buf, char (*msg)[DEFAULT_BUFFER_SIZE]) -{ - char *server_date = NULL; - char *document_date = NULL; - int date_result = STATE_OK; - curlhelp_statusline status_line; - struct phr_header headers[255]; - size_t nof_headers = 255; - size_t msglen; - - int res = phr_parse_response (header_buf->buf, header_buf->buflen, - &status_line.http_major, &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen, - headers, &nof_headers, 0); +int check_document_dates(const curlhelp_write_curlbuf *header_buf, char (*msg)[DEFAULT_BUFFER_SIZE]) { + char *server_date = NULL; + char *document_date = NULL; + int date_result = STATE_OK; + curlhelp_statusline status_line; + struct phr_header headers[255]; + size_t nof_headers = 255; + size_t msglen; + + int res = phr_parse_response(header_buf->buf, header_buf->buflen, &status_line.http_major, &status_line.http_minor, + &status_line.http_code, &status_line.msg, &msglen, headers, &nof_headers, 0); if (res == -1) { - die (STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n")); + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n")); } - server_date = get_header_value (headers, nof_headers, "date"); - document_date = get_header_value (headers, nof_headers, "last-modified"); + server_date = get_header_value(headers, nof_headers, "date"); + document_date = get_header_value(headers, nof_headers, "last-modified"); if (!server_date || !*server_date) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%sServer date unknown, "), *msg); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sServer date unknown, "), *msg); strcpy(*msg, tmp); date_result = max_state_alt(STATE_UNKNOWN, date_result); @@ -2457,34 +2358,34 @@ check_document_dates (const curlhelp_write_curlbuf *header_buf, char (*msg)[DEFA } else if (!document_date || !*document_date) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%sDocument modification date unknown, "), *msg); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sDocument modification date unknown, "), *msg); strcpy(*msg, tmp); date_result = max_state_alt(STATE_CRITICAL, date_result); - } else { - time_t srv_data = curl_getdate (server_date, NULL); - time_t doc_data = curl_getdate (document_date, NULL); - if (verbose >= 2) - printf ("* server date: '%s' (%d), doc_date: '%s' (%d)\n", server_date, (int)srv_data, document_date, (int)doc_data); + } else { + time_t srv_data = curl_getdate(server_date, NULL); + time_t doc_data = curl_getdate(document_date, NULL); + if (verbose >= 2) + printf("* server date: '%s' (%d), doc_date: '%s' (%d)\n", server_date, (int)srv_data, document_date, (int)doc_data); if (srv_data <= 0) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%sServer date \"%100s\" unparsable, "), *msg, server_date); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sServer date \"%100s\" unparsable, "), *msg, server_date); strcpy(*msg, tmp); date_result = max_state_alt(STATE_CRITICAL, date_result); } else if (doc_data <= 0) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%sDocument date \"%100s\" unparsable, "), *msg, document_date); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sDocument date \"%100s\" unparsable, "), *msg, document_date); strcpy(*msg, tmp); date_result = max_state_alt(STATE_CRITICAL, date_result); } else if (doc_data > srv_data + 30) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%sDocument is %d seconds in the future, "), *msg, (int)doc_data - (int)srv_data); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sDocument is %d seconds in the future, "), *msg, (int)doc_data - (int)srv_data); strcpy(*msg, tmp); date_result = max_state_alt(STATE_CRITICAL, date_result); @@ -2493,14 +2394,14 @@ check_document_dates (const curlhelp_write_curlbuf *header_buf, char (*msg)[DEFA if (n > (60 * 60 * 24 * 2)) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%sLast modified %.1f days ago, "), *msg, ((float) n) / (60 * 60 * 24)); - strcpy(*msg, tmp); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sLast modified %.1f days ago, "), *msg, ((float)n) / (60 * 60 * 24)); + strcpy(*msg, tmp); date_result = max_state_alt(STATE_CRITICAL, date_result); } else { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%sLast modified %d:%02d:%02d ago, "), *msg, n / (60 * 60), (n / 60) % 60, n % 60); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sLast modified %d:%02d:%02d ago, "), *msg, n / (60 * 60), (n / 60) % 60, n % 60); strcpy(*msg, tmp); date_result = max_state_alt(STATE_CRITICAL, date_result); @@ -2508,132 +2409,128 @@ check_document_dates (const curlhelp_write_curlbuf *header_buf, char (*msg)[DEFA } } - if (server_date) free (server_date); - if (document_date) free (document_date); + if (server_date) + free(server_date); + if (document_date) + free(document_date); - return date_result; + return date_result; } +int get_content_length(const curlhelp_write_curlbuf *header_buf, const curlhelp_write_curlbuf *body_buf) { + size_t content_length = 0; + struct phr_header headers[255]; + size_t nof_headers = 255; + size_t msglen; + char *content_length_s = NULL; + curlhelp_statusline status_line; -int -get_content_length (const curlhelp_write_curlbuf* header_buf, const curlhelp_write_curlbuf* body_buf) -{ - size_t content_length = 0; - struct phr_header headers[255]; - size_t nof_headers = 255; - size_t msglen; - char *content_length_s = NULL; - curlhelp_statusline status_line; - - int res = phr_parse_response (header_buf->buf, header_buf->buflen, - &status_line.http_major, &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen, - headers, &nof_headers, 0); + int res = phr_parse_response(header_buf->buf, header_buf->buflen, &status_line.http_major, &status_line.http_minor, + &status_line.http_code, &status_line.msg, &msglen, headers, &nof_headers, 0); if (res == -1) { - die (STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n")); + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n")); } - content_length_s = get_header_value (headers, nof_headers, "content-length"); - if (!content_length_s) { - return header_buf->buflen + body_buf->buflen; - } - content_length_s += strspn (content_length_s, " \t"); - content_length = atoi (content_length_s); - if (content_length != body_buf->buflen) { - /* TODO: should we warn if the actual and the reported body length don't match? */ - } + content_length_s = get_header_value(headers, nof_headers, "content-length"); + if (!content_length_s) { + return header_buf->buflen + body_buf->buflen; + } + content_length_s += strspn(content_length_s, " \t"); + content_length = atoi(content_length_s); + if (content_length != body_buf->buflen) { + /* TODO: should we warn if the actual and the reported body length don't match? */ + } - if (content_length_s) free (content_length_s); + if (content_length_s) + free(content_length_s); - return header_buf->buflen + body_buf->buflen; + return header_buf->buflen + body_buf->buflen; } /* TODO: is there a better way in libcurl to check for the SSL library? */ -curlhelp_ssl_library -curlhelp_get_ssl_library () -{ - curl_version_info_data* version_data; - char *ssl_version; - char *library; - curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN; - - version_data = curl_version_info (CURLVERSION_NOW); - if (version_data == NULL) return CURLHELP_SSL_LIBRARY_UNKNOWN; - - ssl_version = strdup (version_data->ssl_version); - if (ssl_version == NULL ) return CURLHELP_SSL_LIBRARY_UNKNOWN; - - library = strtok (ssl_version, "/"); - if (library == NULL) return CURLHELP_SSL_LIBRARY_UNKNOWN; - - if (strcmp (library, "OpenSSL") == 0) - ssl_library = CURLHELP_SSL_LIBRARY_OPENSSL; - else if (strcmp (library, "LibreSSL") == 0) - ssl_library = CURLHELP_SSL_LIBRARY_LIBRESSL; - else if (strcmp (library, "GnuTLS") == 0) - ssl_library = CURLHELP_SSL_LIBRARY_GNUTLS; - else if (strcmp (library, "NSS") == 0) - ssl_library = CURLHELP_SSL_LIBRARY_NSS; - - if (verbose >= 2) - printf ("* SSL library string is : %s %s (%d)\n", version_data->ssl_version, library, ssl_library); - - free (ssl_version); - - return ssl_library; +curlhelp_ssl_library curlhelp_get_ssl_library() { + curl_version_info_data *version_data; + char *ssl_version; + char *library; + curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN; + + version_data = curl_version_info(CURLVERSION_NOW); + if (version_data == NULL) + return CURLHELP_SSL_LIBRARY_UNKNOWN; + + ssl_version = strdup(version_data->ssl_version); + if (ssl_version == NULL) + return CURLHELP_SSL_LIBRARY_UNKNOWN; + + library = strtok(ssl_version, "/"); + if (library == NULL) + return CURLHELP_SSL_LIBRARY_UNKNOWN; + + if (strcmp(library, "OpenSSL") == 0) + ssl_library = CURLHELP_SSL_LIBRARY_OPENSSL; + else if (strcmp(library, "LibreSSL") == 0) + ssl_library = CURLHELP_SSL_LIBRARY_LIBRESSL; + else if (strcmp(library, "GnuTLS") == 0) + ssl_library = CURLHELP_SSL_LIBRARY_GNUTLS; + else if (strcmp(library, "NSS") == 0) + ssl_library = CURLHELP_SSL_LIBRARY_NSS; + + if (verbose >= 2) + printf("* SSL library string is : %s %s (%d)\n", version_data->ssl_version, library, ssl_library); + + free(ssl_version); + + return ssl_library; } -const char* -curlhelp_get_ssl_library_string (curlhelp_ssl_library ssl_library) -{ - switch (ssl_library) { - case CURLHELP_SSL_LIBRARY_OPENSSL: - return "OpenSSL"; - case CURLHELP_SSL_LIBRARY_LIBRESSL: - return "LibreSSL"; - case CURLHELP_SSL_LIBRARY_GNUTLS: - return "GnuTLS"; - case CURLHELP_SSL_LIBRARY_NSS: - return "NSS"; - case CURLHELP_SSL_LIBRARY_UNKNOWN: - default: - return "unknown"; - } +const char *curlhelp_get_ssl_library_string(curlhelp_ssl_library ssl_library) { + switch (ssl_library) { + case CURLHELP_SSL_LIBRARY_OPENSSL: + return "OpenSSL"; + case CURLHELP_SSL_LIBRARY_LIBRESSL: + return "LibreSSL"; + case CURLHELP_SSL_LIBRARY_GNUTLS: + return "GnuTLS"; + case CURLHELP_SSL_LIBRARY_NSS: + return "NSS"; + case CURLHELP_SSL_LIBRARY_UNKNOWN: + default: + return "unknown"; + } } #ifdef LIBCURL_FEATURE_SSL -#ifndef USE_OPENSSL -time_t -parse_cert_date (const char *s) -{ - struct tm tm; - time_t date; - char *res; - - if (!s) return -1; - - /* Jan 17 14:25:12 2020 GMT */ - res = strptime (s, "%Y-%m-%d %H:%M:%S GMT", &tm); - /* Sep 11 12:00:00 2020 GMT */ - if (res == NULL) strptime (s, "%Y %m %d %H:%M:%S GMT", &tm); - date = mktime (&tm); - - return date; +# ifndef USE_OPENSSL +time_t parse_cert_date(const char *s) { + struct tm tm; + time_t date; + char *res; + + if (!s) + return -1; + + /* Jan 17 14:25:12 2020 GMT */ + res = strptime(s, "%Y-%m-%d %H:%M:%S GMT", &tm); + /* Sep 11 12:00:00 2020 GMT */ + if (res == NULL) + strptime(s, "%Y %m %d %H:%M:%S GMT", &tm); + date = mktime(&tm); + + return date; } /* TODO: this needs cleanup in the sslutils.c, maybe we the #else case to * OpenSSL could be this function */ -int -net_noopenssl_check_certificate (cert_ptr_union* cert_ptr, int days_till_exp_warn, int days_till_exp_crit) -{ - int i; - struct curl_slist* slist; - int cname_found = 0; - char* start_date_str = NULL; - char* end_date_str = NULL; - time_t start_date; - time_t end_date; +int net_noopenssl_check_certificate(cert_ptr_union *cert_ptr, int days_till_exp_warn, int days_till_exp_crit) { + int i; + struct curl_slist *slist; + int cname_found = 0; + char *start_date_str = NULL; + char *end_date_str = NULL; + time_t start_date; + time_t end_date; char *tz; float time_left; int days_left; @@ -2641,66 +2538,64 @@ net_noopenssl_check_certificate (cert_ptr_union* cert_ptr, int days_till_exp_war char timestamp[50] = ""; int status = STATE_UNKNOWN; - if (verbose >= 2) - printf ("**** REQUEST CERTIFICATES ****\n"); - - for (i = 0; i < cert_ptr->to_certinfo->num_of_certs; i++) { - for (slist = cert_ptr->to_certinfo->certinfo[i]; slist; slist = slist->next) { - /* find first common name in subject, - * TODO: check alternative subjects for - * TODO: have a decent parser here and not a hack - * multi-host certificate, check wildcards - */ - if (strncasecmp (slist->data, "Subject:", 8) == 0) { - int d = 3; - char* p = strstr (slist->data, "CN="); - if (p == NULL) { - d = 5; - p = strstr (slist->data, "CN = "); - } - if (p != NULL) { - if (strncmp (host_name, p+d, strlen (host_name)) == 0) { - cname_found = 1; - } - } - } else if (strncasecmp (slist->data, "Start Date:", 11) == 0) { - start_date_str = &slist->data[11]; - } else if (strncasecmp (slist->data, "Expire Date:", 12) == 0) { - end_date_str = &slist->data[12]; - } else if (strncasecmp (slist->data, "Cert:", 5) == 0) { - goto HAVE_FIRST_CERT; - } - if (verbose >= 2) - printf ("%d ** %s\n", i, slist->data); - } - } + if (verbose >= 2) + printf("**** REQUEST CERTIFICATES ****\n"); + + for (i = 0; i < cert_ptr->to_certinfo->num_of_certs; i++) { + for (slist = cert_ptr->to_certinfo->certinfo[i]; slist; slist = slist->next) { + /* find first common name in subject, + * TODO: check alternative subjects for + * TODO: have a decent parser here and not a hack + * multi-host certificate, check wildcards + */ + if (strncasecmp(slist->data, "Subject:", 8) == 0) { + int d = 3; + char *p = strstr(slist->data, "CN="); + if (p == NULL) { + d = 5; + p = strstr(slist->data, "CN = "); + } + if (p != NULL) { + if (strncmp(host_name, p + d, strlen(host_name)) == 0) { + cname_found = 1; + } + } + } else if (strncasecmp(slist->data, "Start Date:", 11) == 0) { + start_date_str = &slist->data[11]; + } else if (strncasecmp(slist->data, "Expire Date:", 12) == 0) { + end_date_str = &slist->data[12]; + } else if (strncasecmp(slist->data, "Cert:", 5) == 0) { + goto HAVE_FIRST_CERT; + } + if (verbose >= 2) + printf("%d ** %s\n", i, slist->data); + } + } HAVE_FIRST_CERT: - if (verbose >= 2) - printf ("**** REQUEST CERTIFICATES ****\n"); + if (verbose >= 2) + printf("**** REQUEST CERTIFICATES ****\n"); - if (!cname_found) { - printf("%s\n",_("CRITICAL - Cannot retrieve certificate subject.")); + if (!cname_found) { + printf("%s\n", _("CRITICAL - Cannot retrieve certificate subject.")); return STATE_CRITICAL; - } - - start_date = parse_cert_date (start_date_str); - if (start_date <= 0) { - snprintf (msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Start Date' in certificate: '%s'"), - start_date_str); - puts (msg); - return STATE_WARNING; - } - - end_date = parse_cert_date (end_date_str); - if (end_date <= 0) { - snprintf (msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Expire Date' in certificate: '%s'"), - start_date_str); - puts (msg); - return STATE_WARNING; - } - - time_left = difftime (end_date, time(NULL)); + } + + start_date = parse_cert_date(start_date_str); + if (start_date <= 0) { + snprintf(msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Start Date' in certificate: '%s'"), start_date_str); + puts(msg); + return STATE_WARNING; + } + + end_date = parse_cert_date(end_date_str); + if (end_date <= 0) { + snprintf(msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Expire Date' in certificate: '%s'"), start_date_str); + puts(msg); + return STATE_WARNING; + } + + time_left = difftime(end_date, time(NULL)); days_left = time_left / 86400; tz = getenv("TZ"); setenv("TZ", "GMT", 1); @@ -2713,30 +2608,31 @@ HAVE_FIRST_CERT: tzset(); if (days_left > 0 && days_left <= days_till_exp_warn) { - printf (_("%s - Certificate '%s' expires in %d day(s) (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", host_name, days_left, timestamp); + printf(_("%s - Certificate '%s' expires in %d day(s) (%s).\n"), (days_left > days_till_exp_crit) ? "WARNING" : "CRITICAL", + host_name, days_left, timestamp); if (days_left > days_till_exp_crit) status = STATE_WARNING; else status = STATE_CRITICAL; } else if (days_left == 0 && time_left > 0) { if (time_left >= 3600) - time_remaining = (int) time_left / 3600; + time_remaining = (int)time_left / 3600; else - time_remaining = (int) time_left / 60; + time_remaining = (int)time_left / 60; - printf (_("%s - Certificate '%s' expires in %u %s (%s)\n"), - (days_left>days_till_exp_crit) ? "WARNING" : "CRITICAL", host_name, time_remaining, - time_left >= 3600 ? "hours" : "minutes", timestamp); + printf(_("%s - Certificate '%s' expires in %u %s (%s)\n"), (days_left > days_till_exp_crit) ? "WARNING" : "CRITICAL", host_name, + time_remaining, time_left >= 3600 ? "hours" : "minutes", timestamp); - if ( days_left > days_till_exp_crit) + if (days_left > days_till_exp_crit) status = STATE_WARNING; else status = STATE_CRITICAL; } else if (time_left < 0) { printf(_("CRITICAL - Certificate '%s' expired on %s.\n"), host_name, timestamp); - status=STATE_CRITICAL; + status = STATE_CRITICAL; } else if (days_left == 0) { - printf (_("%s - Certificate '%s' just expired (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", host_name, timestamp); + printf(_("%s - Certificate '%s' just expired (%s).\n"), (days_left > days_till_exp_crit) ? "WARNING" : "CRITICAL", host_name, + timestamp); if (days_left > days_till_exp_crit) status = STATE_WARNING; else @@ -2747,5 +2643,5 @@ HAVE_FIRST_CERT: } return status; } -#endif /* USE_OPENSSL */ -#endif /* LIBCURL_FEATURE_SSL */ +# endif /* USE_OPENSSL */ +#endif /* LIBCURL_FEATURE_SSL */ -- cgit v0.10-9-g596f From 367c4f89c1417aba29d2421e157817994a049f87 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:59:49 +0100 Subject: check_curl: Update copyright diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 8936110..8277f5e 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -3,7 +3,7 @@ * Monitoring check_curl plugin * * License: GPL - * Copyright (c) 1999-2019 Monitoring Plugins Development Team + * Copyright (c) 1999-2024 Monitoring Plugins Development Team * * Description: * @@ -34,7 +34,7 @@ *****************************************************************************/ const char *progname = "check_curl"; -const char *copyright = "2006-2019"; +const char *copyright = "2006-2024"; const char *email = "devel@monitoring-plugins.org"; #include -- cgit v0.10-9-g596f From 7334812a929768aa310557ae823b91df79b32f51 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:05:43 +0100 Subject: check_curl: do not export local variables and remove unused ones diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 8277f5e..06fc6d6 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -128,141 +128,138 @@ enum { MAX_RE_SIZE = 1024 }; #include "regex.h" -regex_t preg; -regmatch_t pmatch[REGS]; -char regexp[MAX_RE_SIZE]; -int cflags = REG_NOSUB | REG_EXTENDED | REG_NEWLINE; -int errcode; -bool invert_regex = false; -int state_regex = STATE_CRITICAL; - -char *server_address = NULL; -char *host_name = NULL; -char *server_url = 0; -char server_ip[DEFAULT_BUFFER_SIZE]; -struct curl_slist *server_ips = NULL; -bool specify_port = false; -unsigned short server_port = HTTP_PORT; -unsigned short virtual_port = 0; -int host_name_length; -char output_header_search[30] = ""; -char output_string_search[30] = ""; -char *warning_thresholds = NULL; -char *critical_thresholds = NULL; -int days_till_exp_warn, days_till_exp_crit; -thresholds *thlds; -char user_agent[DEFAULT_BUFFER_SIZE]; -int verbose = 0; -bool show_extended_perfdata = false; -bool show_body = false; -int min_page_len = 0; -int max_page_len = 0; -int redir_depth = 0; -int max_depth = DEFAULT_MAX_REDIRS; -char *http_method = NULL; -char *http_post_data = NULL; -char *http_content_type = NULL; -CURL *curl; -bool curl_global_initialized = false; -bool curl_easy_initialized = false; -struct curl_slist *header_list = NULL; -bool body_buf_initialized = false; -curlhelp_write_curlbuf body_buf; -bool header_buf_initialized = false; -curlhelp_write_curlbuf header_buf; -bool status_line_initialized = false; -curlhelp_statusline status_line; -bool put_buf_initialized = false; -curlhelp_read_curlbuf put_buf; -char http_header[DEFAULT_BUFFER_SIZE]; -long code; -long socket_timeout = DEFAULT_SOCKET_TIMEOUT; -double total_time; -double time_connect; -double time_appconnect; -double time_headers; -double time_firstbyte; -char errbuf[MAX_INPUT_BUFFER]; -CURLcode res; -char url[DEFAULT_BUFFER_SIZE]; -char msg[DEFAULT_BUFFER_SIZE]; -char perfstring[DEFAULT_BUFFER_SIZE]; -char header_expect[MAX_INPUT_BUFFER] = ""; -char string_expect[MAX_INPUT_BUFFER] = ""; -char server_expect[MAX_INPUT_BUFFER] = HTTP_EXPECT; -int server_expect_yn = 0; -char user_auth[MAX_INPUT_BUFFER] = ""; -char proxy_auth[MAX_INPUT_BUFFER] = ""; -char **http_opt_headers; -int http_opt_headers_count = 0; -bool display_html = false; -int onredirect = STATE_OK; -int followmethod = FOLLOW_HTTP_CURL; -int followsticky = STICKY_NONE; -bool use_ssl = false; -bool use_sni = true; -bool check_cert = false; -bool continue_after_check_cert = false; +static regex_t preg; +static regmatch_t pmatch[REGS]; +static char regexp[MAX_RE_SIZE]; +static int cflags = REG_NOSUB | REG_EXTENDED | REG_NEWLINE; +static int errcode; +static bool invert_regex = false; +static int state_regex = STATE_CRITICAL; + +static char *server_address = NULL; +static char *host_name = NULL; +static char *server_url = 0; +static struct curl_slist *server_ips = NULL; +static bool specify_port = false; +static unsigned short server_port = HTTP_PORT; +static unsigned short virtual_port = 0; +static int host_name_length; +static char output_header_search[30] = ""; +static char output_string_search[30] = ""; +static char *warning_thresholds = NULL; +static char *critical_thresholds = NULL; +static int days_till_exp_warn, days_till_exp_crit; +static thresholds *thlds; +static char user_agent[DEFAULT_BUFFER_SIZE]; +static int verbose = 0; +static bool show_extended_perfdata = false; +static bool show_body = false; +static int min_page_len = 0; +static int max_page_len = 0; +static int redir_depth = 0; +static int max_depth = DEFAULT_MAX_REDIRS; +static char *http_method = NULL; +static char *http_post_data = NULL; +static char *http_content_type = NULL; +static CURL *curl; +static bool curl_global_initialized = false; +static bool curl_easy_initialized = false; +static struct curl_slist *header_list = NULL; +static bool body_buf_initialized = false; +static curlhelp_write_curlbuf body_buf; +static bool header_buf_initialized = false; +static curlhelp_write_curlbuf header_buf; +static bool status_line_initialized = false; +static curlhelp_statusline status_line; +static bool put_buf_initialized = false; +static curlhelp_read_curlbuf put_buf; +static char http_header[DEFAULT_BUFFER_SIZE]; +static long code; +static long socket_timeout = DEFAULT_SOCKET_TIMEOUT; +static double total_time; +static double time_connect; +static double time_appconnect; +static double time_headers; +static double time_firstbyte; +static char errbuf[MAX_INPUT_BUFFER]; +static CURLcode res; +static char url[DEFAULT_BUFFER_SIZE]; +static char msg[DEFAULT_BUFFER_SIZE]; +static char perfstring[DEFAULT_BUFFER_SIZE]; +static char header_expect[MAX_INPUT_BUFFER] = ""; +static char string_expect[MAX_INPUT_BUFFER] = ""; +static char server_expect[MAX_INPUT_BUFFER] = HTTP_EXPECT; +static int server_expect_yn = 0; +static char user_auth[MAX_INPUT_BUFFER] = ""; +static char proxy_auth[MAX_INPUT_BUFFER] = ""; +static char **http_opt_headers; +static int http_opt_headers_count = 0; +static bool display_html = false; +static int onredirect = STATE_OK; +static int followmethod = FOLLOW_HTTP_CURL; +static int followsticky = STICKY_NONE; +static bool use_ssl = false; +static bool check_cert = false; +static bool continue_after_check_cert = false; typedef union { struct curl_slist *to_info; struct curl_certinfo *to_certinfo; } cert_ptr_union; -cert_ptr_union cert_ptr; -int ssl_version = CURL_SSLVERSION_DEFAULT; -char *client_cert = NULL; -char *client_privkey = NULL; -char *ca_cert = NULL; -bool verify_peer_and_host = false; -bool is_openssl_callback = false; -bool add_sslctx_verify_fun = false; +static cert_ptr_union cert_ptr; +static int ssl_version = CURL_SSLVERSION_DEFAULT; +static char *client_cert = NULL; +static char *client_privkey = NULL; +static char *ca_cert = NULL; +static bool verify_peer_and_host = false; +static bool is_openssl_callback = false; +static bool add_sslctx_verify_fun = false; #if defined(HAVE_SSL) && defined(USE_OPENSSL) -X509 *cert = NULL; +static X509 *cert = NULL; #endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */ -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; -bool automatic_decompression = false; -char *cookie_jar_file = NULL; -bool haproxy_protocol = false; - -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 *); -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); +static bool no_body = false; +static int maximum_age = -1; +static int address_family = AF_UNSPEC; +static curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN; +static int curl_http_version = CURL_HTTP_VERSION_NONE; +static bool automatic_decompression = false; +static char *cookie_jar_file = NULL; +static bool haproxy_protocol = false; + +static bool process_arguments(int, char **); +static void handle_curl_option_return_code(CURLcode res, const char *option); +static int check_http(void); +static void redir(curlhelp_write_curlbuf *); +static char *perfd_time(double microsec); +static char *perfd_time_connect(double microsec); +static char *perfd_time_ssl(double microsec); +static char *perfd_time_firstbyte(double microsec); +static char *perfd_time_headers(double microsec); +static char *perfd_time_transfer(double microsec); +static char *perfd_size(int page_len); +static void print_help(void); void print_usage(void); -void print_curl_version(void); -int curlhelp_initwritebuffer(curlhelp_write_curlbuf *); -size_t curlhelp_buffer_write_callback(void *, size_t, size_t, void *); -void curlhelp_freewritebuffer(curlhelp_write_curlbuf *); -int curlhelp_initreadbuffer(curlhelp_read_curlbuf *, const char *, size_t); -size_t curlhelp_buffer_read_callback(void *, size_t, size_t, void *); -void curlhelp_freereadbuffer(curlhelp_read_curlbuf *); -curlhelp_ssl_library curlhelp_get_ssl_library(); -const char *curlhelp_get_ssl_library_string(curlhelp_ssl_library); +static void print_curl_version(void); +static int curlhelp_initwritebuffer(curlhelp_write_curlbuf *); +static size_t curlhelp_buffer_write_callback(void *, size_t, size_t, void *); +static void curlhelp_freewritebuffer(curlhelp_write_curlbuf *); +static int curlhelp_initreadbuffer(curlhelp_read_curlbuf *, const char *, size_t); +static size_t curlhelp_buffer_read_callback(void *, size_t, size_t, void *); +static void curlhelp_freereadbuffer(curlhelp_read_curlbuf *); +static curlhelp_ssl_library curlhelp_get_ssl_library(); +static const char *curlhelp_get_ssl_library_string(curlhelp_ssl_library); int net_noopenssl_check_certificate(cert_ptr_union *, int, int); -int curlhelp_parse_statusline(const char *, curlhelp_statusline *); -void curlhelp_free_statusline(curlhelp_statusline *); -char *get_header_value(const struct phr_header *headers, const size_t nof_headers, const char *header); -int check_document_dates(const curlhelp_write_curlbuf *, char (*msg)[DEFAULT_BUFFER_SIZE]); -int get_content_length(const curlhelp_write_curlbuf *header_buf, const curlhelp_write_curlbuf *body_buf); +static int curlhelp_parse_statusline(const char *, curlhelp_statusline *); +static void curlhelp_free_statusline(curlhelp_statusline *); +static char *get_header_value(const struct phr_header *headers, const size_t nof_headers, const char *header); +static int check_document_dates(const curlhelp_write_curlbuf *, char (*msg)[DEFAULT_BUFFER_SIZE]); +static int get_content_length(const curlhelp_write_curlbuf *header_buf, const curlhelp_write_curlbuf *body_buf); #if defined(HAVE_SSL) && defined(USE_OPENSSL) int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int days_till_exp_crit); #endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */ -void remove_newlines(char *); -void test_file(char *); +static void test_file(char *); int main(int argc, char **argv) { int result = STATE_UNKNOWN; @@ -2311,14 +2308,6 @@ int curlhelp_parse_statusline(const char *buf, curlhelp_statusline *status_line) void curlhelp_free_statusline(curlhelp_statusline *status_line) { free(status_line->first_line); } -void remove_newlines(char *s) { - char *p; - - for (p = s; *p != '\0'; p++) - if (*p == '\r' || *p == '\n') - *p = ' '; -} - char *get_header_value(const struct phr_header *headers, const size_t nof_headers, const char *header) { for (size_t i = 0; i < nof_headers; i++) { if (headers[i].name != NULL && strncasecmp(header, headers[i].name, max(headers[i].name_len, 4)) == 0) { -- cgit v0.10-9-g596f From fde8e9c77b094ccec536d05c634d9d8f1f0e3abc Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:10:57 +0100 Subject: check_curl: Linter fixes diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 06fc6d6..1d27da2 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -225,41 +225,41 @@ static bool automatic_decompression = false; static char *cookie_jar_file = NULL; static bool haproxy_protocol = false; -static bool process_arguments(int, char **); +static bool process_arguments(int /*argc*/, char ** /*argv*/); static void handle_curl_option_return_code(CURLcode res, const char *option); static int check_http(void); -static void redir(curlhelp_write_curlbuf *); -static char *perfd_time(double microsec); -static char *perfd_time_connect(double microsec); -static char *perfd_time_ssl(double microsec); -static char *perfd_time_firstbyte(double microsec); -static char *perfd_time_headers(double microsec); -static char *perfd_time_transfer(double microsec); +static void redir(curlhelp_write_curlbuf * /*header_buf*/); +static char *perfd_time(double elapsed_time); +static char *perfd_time_connect(double elapsed_time_connect); +static char *perfd_time_ssl(double elapsed_time_ssl); +static char *perfd_time_firstbyte(double elapsed_time_firstbyte); +static char *perfd_time_headers(double elapsed_time_headers); +static char *perfd_time_transfer(double elapsed_time_transfer); static char *perfd_size(int page_len); static void print_help(void); void print_usage(void); static void print_curl_version(void); -static int curlhelp_initwritebuffer(curlhelp_write_curlbuf *); -static size_t curlhelp_buffer_write_callback(void *, size_t, size_t, void *); -static void curlhelp_freewritebuffer(curlhelp_write_curlbuf *); -static int curlhelp_initreadbuffer(curlhelp_read_curlbuf *, const char *, size_t); -static size_t curlhelp_buffer_read_callback(void *, size_t, size_t, void *); -static void curlhelp_freereadbuffer(curlhelp_read_curlbuf *); -static curlhelp_ssl_library curlhelp_get_ssl_library(); -static const char *curlhelp_get_ssl_library_string(curlhelp_ssl_library); +static int curlhelp_initwritebuffer(curlhelp_write_curlbuf * /*buf*/); +static size_t curlhelp_buffer_write_callback(void * /*buffer*/, size_t /*size*/, size_t /*nmemb*/, void * /*stream*/); +static void curlhelp_freewritebuffer(curlhelp_write_curlbuf * /*buf*/); +static int curlhelp_initreadbuffer(curlhelp_read_curlbuf * /*buf*/, const char * /*data*/, size_t /*datalen*/); +static size_t curlhelp_buffer_read_callback(void * /*buffer*/, size_t /*size*/, size_t /*nmemb*/, void * /*stream*/); +static void curlhelp_freereadbuffer(curlhelp_read_curlbuf * /*buf*/); +static curlhelp_ssl_library curlhelp_get_ssl_library(void); +static const char *curlhelp_get_ssl_library_string(curlhelp_ssl_library /*ssl_library*/); int net_noopenssl_check_certificate(cert_ptr_union *, int, int); -static int curlhelp_parse_statusline(const char *, curlhelp_statusline *); -static void curlhelp_free_statusline(curlhelp_statusline *); -static char *get_header_value(const struct phr_header *headers, const size_t nof_headers, const char *header); -static int check_document_dates(const curlhelp_write_curlbuf *, char (*msg)[DEFAULT_BUFFER_SIZE]); +static int curlhelp_parse_statusline(const char * /*buf*/, curlhelp_statusline * /*status_line*/); +static void curlhelp_free_statusline(curlhelp_statusline * /*status_line*/); +static char *get_header_value(const struct phr_header *headers, size_t nof_headers, const char *header); +static int check_document_dates(const curlhelp_write_curlbuf * /*header_buf*/, char (*msg)[DEFAULT_BUFFER_SIZE]); static int get_content_length(const curlhelp_write_curlbuf *header_buf, const curlhelp_write_curlbuf *body_buf); #if defined(HAVE_SSL) && defined(USE_OPENSSL) int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int days_till_exp_crit); #endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */ -static void test_file(char *); +static void test_file(char * /*path*/); int main(int argc, char **argv) { int result = STATE_UNKNOWN; @@ -301,7 +301,8 @@ int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) { # endif if (verbose >= 2) { puts("* SSL verify callback with certificate:"); - X509_NAME *subject, *issuer; + X509_NAME *subject; + X509_NAME *issuer; printf("* issuer:\n"); issuer = X509_get_issuer_name(cert); X509_NAME_print_ex_fp(stdout, issuer, 5, XN_FLAG_MULTILINE); @@ -356,7 +357,8 @@ static char *string_statuscode(int major, int minor) { /* Checks if the server 'reply' is one of the expected 'statuscodes' */ static int expected_statuscode(const char *reply, const char *statuscodes) { - char *expected, *code; + char *expected; + char *code; int result = 0; if ((expected = strdup(statuscodes)) == NULL) @@ -523,7 +525,7 @@ int check_http(void) { // use the host_name later on to make SNI happy if (use_ssl && host_name != NULL) { 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, + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Unable to lookup IP address for '%s': getaddrinfo returned %d - %d"), server_address, res, gai_strerror(res)); die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); } @@ -2183,8 +2185,7 @@ const char *strrstr2(const char *haystack, const char *needle) { if (pos == NULL) { if (counter == 0) return NULL; - else - return prev_pos; + return prev_pos; } counter++; prev_pos = pos; @@ -2438,7 +2439,7 @@ int get_content_length(const curlhelp_write_curlbuf *header_buf, const curlhelp_ } /* TODO: is there a better way in libcurl to check for the SSL library? */ -curlhelp_ssl_library curlhelp_get_ssl_library() { +curlhelp_ssl_library curlhelp_get_ssl_library(void) { curl_version_info_data *version_data; char *ssl_version; char *library; -- cgit v0.10-9-g596f From c413037aa8041daccb61d4bef77e34553e3c5fb7 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:11:54 +0100 Subject: check_dbi: clang-format diff --git a/plugins/check_dbi.c b/plugins/check_dbi.c index 29c8520..0c0ed6d 100644 --- a/plugins/check_dbi.c +++ b/plugins/check_dbi.c @@ -1,33 +1,33 @@ /***************************************************************************** -* -* Monitoring check_dbi plugin -* -* License: GPL -* Copyright (c) 2011 Monitoring Plugins Development Team -* Author: Sebastian 'tokkee' Harl -* -* Description: -* -* This file contains the check_dbi plugin -* -* Runs an arbitrary (SQL) command and checks the result. -* -* -* 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_dbi plugin + * + * License: GPL + * Copyright (c) 2011 Monitoring Plugins Development Team + * Author: Sebastian 'tokkee' Harl + * + * Description: + * + * This file contains the check_dbi plugin + * + * Runs an arbitrary (SQL) command and checks the result. + * + * + * 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_dbi"; const char *copyright = "2011"; @@ -43,7 +43,7 @@ const char *email = "devel@monitoring-plugins.org"; /* required for NAN */ #ifndef _ISOC99_SOURCE -#define _ISOC99_SOURCE +# define _ISOC99_SOURCE #endif #include @@ -92,20 +92,18 @@ int np_dbi_options_num = 0; char *np_dbi_database = NULL; char *np_dbi_query = NULL; -int process_arguments (int, char **); -int validate_arguments (void); -void print_usage (void); -void print_help (void); +int process_arguments(int, char **); +int validate_arguments(void); +void print_usage(void); +void print_help(void); -double timediff (struct timeval, struct timeval); +double timediff(struct timeval, struct timeval); -void np_dbi_print_error (dbi_conn, char *, ...); +void np_dbi_print_error(dbi_conn, char *, ...); -int do_query (dbi_conn, const char **, double *, double *); +int do_query(dbi_conn, const char **, double *, double *); -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { int status = STATE_UNKNOWN; dbi_driver driver; @@ -122,59 +120,58 @@ main (int argc, char **argv) int i; - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Parse extra opts if any */ - argv = np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if (process_arguments (argc, argv) == ERROR) - usage4 (_("Could not parse arguments")); + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments")); /* Set signal handling and alarm */ - if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) { - usage4 (_("Cannot catch SIGALRM")); + if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR) { + usage4(_("Cannot catch SIGALRM")); } - alarm (timeout_interval); + alarm(timeout_interval); if (verbose > 2) - printf ("Initializing DBI\n"); + printf("Initializing DBI\n"); - dbi_inst *instance_p = { 0 }; + dbi_inst *instance_p = {0}; if (dbi_initialize_r(NULL, instance_p) < 0) { - printf ("UNKNOWN - failed to initialize DBI; possibly you don't have any drivers installed.\n"); + printf("UNKNOWN - failed to initialize DBI; possibly you don't have any drivers installed.\n"); return STATE_UNKNOWN; } if (instance_p == NULL) { - printf ("UNKNOWN - failed to initialize DBI.\n"); + printf("UNKNOWN - failed to initialize DBI.\n"); return STATE_UNKNOWN; } if (verbose) - printf ("Opening DBI driver '%s'\n", np_dbi_driver); + printf("Opening DBI driver '%s'\n", np_dbi_driver); driver = dbi_driver_open_r(np_dbi_driver, instance_p); - if (! driver) { - printf ("UNKNOWN - failed to open DBI driver '%s'; possibly it's not installed.\n", - np_dbi_driver); + if (!driver) { + printf("UNKNOWN - failed to open DBI driver '%s'; possibly it's not installed.\n", np_dbi_driver); - printf ("Known drivers:\n"); + printf("Known drivers:\n"); for (driver = dbi_driver_list_r(NULL, instance_p); driver; driver = dbi_driver_list_r(driver, instance_p)) { - printf (" - %s\n", dbi_driver_get_name (driver)); + printf(" - %s\n", dbi_driver_get_name(driver)); } return STATE_UNKNOWN; } /* make a connection to the database */ - gettimeofday (&start_timeval, NULL); + gettimeofday(&start_timeval, NULL); - conn = dbi_conn_open (driver); - if (! conn) { - printf ("UNKNOWN - failed top open connection object.\n"); - dbi_conn_close (conn); + conn = dbi_conn_open(driver); + if (!conn) { + printf("UNKNOWN - failed top open connection object.\n"); + dbi_conn_close(conn); return STATE_UNKNOWN; } @@ -182,210 +179,189 @@ main (int argc, char **argv) const char *opt; if (verbose > 1) - printf ("Setting DBI driver option '%s' to '%s'\n", - np_dbi_options[i].key, np_dbi_options[i].value); + printf("Setting DBI driver option '%s' to '%s'\n", np_dbi_options[i].key, np_dbi_options[i].value); - if (! dbi_conn_set_option (conn, np_dbi_options[i].key, np_dbi_options[i].value)) + if (!dbi_conn_set_option(conn, np_dbi_options[i].key, np_dbi_options[i].value)) continue; /* else: status != 0 */ - np_dbi_print_error (conn, "UNKNOWN - failed to set option '%s' to '%s'", - np_dbi_options[i].key, np_dbi_options[i].value); - printf ("Known driver options:\n"); + np_dbi_print_error(conn, "UNKNOWN - failed to set option '%s' to '%s'", np_dbi_options[i].key, np_dbi_options[i].value); + printf("Known driver options:\n"); - for (opt = dbi_conn_get_option_list (conn, NULL); opt; - opt = dbi_conn_get_option_list (conn, opt)) { - printf (" - %s\n", opt); + for (opt = dbi_conn_get_option_list(conn, NULL); opt; opt = dbi_conn_get_option_list(conn, opt)) { + printf(" - %s\n", opt); } - dbi_conn_close (conn); + dbi_conn_close(conn); return STATE_UNKNOWN; } if (host) { if (verbose > 1) - printf ("Setting DBI driver option 'host' to '%s'\n", host); - dbi_conn_set_option (conn, "host", host); + printf("Setting DBI driver option 'host' to '%s'\n", host); + dbi_conn_set_option(conn, "host", host); } if (verbose) { const char *dbname, *host; - dbname = dbi_conn_get_option (conn, "dbname"); - host = dbi_conn_get_option (conn, "host"); + dbname = dbi_conn_get_option(conn, "dbname"); + host = dbi_conn_get_option(conn, "host"); - if (! dbname) + if (!dbname) dbname = ""; - if (! host) + if (!host) host = ""; - printf ("Connecting to database '%s' at host '%s'\n", - dbname, host); + printf("Connecting to database '%s' at host '%s'\n", dbname, host); } - if (dbi_conn_connect (conn) < 0) { - np_dbi_print_error (conn, "UNKNOWN - failed to connect to database"); + if (dbi_conn_connect(conn) < 0) { + np_dbi_print_error(conn, "UNKNOWN - failed to connect to database"); return STATE_UNKNOWN; } - gettimeofday (&end_timeval, NULL); - conn_time = timediff (start_timeval, end_timeval); + gettimeofday(&end_timeval, NULL); + conn_time = timediff(start_timeval, end_timeval); - server_version = dbi_conn_get_engine_version (conn); + server_version = dbi_conn_get_engine_version(conn); if (verbose) - printf ("Connected to server version %u\n", server_version); + printf("Connected to server version %u\n", server_version); if (metric == METRIC_SERVER_VERSION) - status = get_status (server_version, dbi_thresholds); + status = get_status(server_version, dbi_thresholds); if (verbose) - printf ("Time elapsed: %f\n", conn_time); + printf("Time elapsed: %f\n", conn_time); if (metric == METRIC_CONN_TIME) - status = get_status (conn_time, dbi_thresholds); + status = get_status(conn_time, dbi_thresholds); /* select a database */ if (np_dbi_database) { if (verbose > 1) - printf ("Selecting database '%s'\n", np_dbi_database); + printf("Selecting database '%s'\n", np_dbi_database); - if (dbi_conn_select_db (conn, np_dbi_database)) { - np_dbi_print_error (conn, "UNKNOWN - failed to select database '%s'", - np_dbi_database); + if (dbi_conn_select_db(conn, np_dbi_database)) { + np_dbi_print_error(conn, "UNKNOWN - failed to select database '%s'", np_dbi_database); return STATE_UNKNOWN; } } if (np_dbi_query) { /* execute query */ - status = do_query (conn, &query_val_str, &query_val, &query_time); + status = do_query(conn, &query_val_str, &query_val, &query_time); if (status != STATE_OK) /* do_query prints an error message in this case */ return status; if (metric == METRIC_QUERY_RESULT) { if (expect) { - if ((! query_val_str) || strcmp (query_val_str, expect)) + if ((!query_val_str) || strcmp(query_val_str, expect)) status = STATE_CRITICAL; else status = STATE_OK; - } - else if (expect_re_str) { + } else if (expect_re_str) { int err; - err = regexec (&expect_re, query_val_str, 0, NULL, /* flags = */ 0); - if (! err) + err = regexec(&expect_re, query_val_str, 0, NULL, /* flags = */ 0); + if (!err) status = STATE_OK; else if (err == REG_NOMATCH) status = STATE_CRITICAL; else { char errmsg[1024]; - regerror (err, &expect_re, errmsg, sizeof (errmsg)); - printf ("ERROR - failed to execute regular expression: %s\n", - errmsg); + regerror(err, &expect_re, errmsg, sizeof(errmsg)); + printf("ERROR - failed to execute regular expression: %s\n", errmsg); status = STATE_CRITICAL; } - } - else - status = get_status (query_val, dbi_thresholds); - } - else if (metric == METRIC_QUERY_TIME) - status = get_status (query_time, dbi_thresholds); + } else + status = get_status(query_val, dbi_thresholds); + } else if (metric == METRIC_QUERY_TIME) + status = get_status(query_time, dbi_thresholds); } if (verbose) printf("Closing connection\n"); - dbi_conn_close (conn); + dbi_conn_close(conn); /* In case of METRIC_QUERY_RESULT, isnan(query_val) indicates an error * which should have been reported and handled (abort) before * ... unless we expected a string to be returned */ - assert ((metric != METRIC_QUERY_RESULT) || (! isnan (query_val)) - || (type == TYPE_STRING)); + assert((metric != METRIC_QUERY_RESULT) || (!isnan(query_val)) || (type == TYPE_STRING)); - assert ((type != TYPE_STRING) || (expect || expect_re_str)); + assert((type != TYPE_STRING) || (expect || expect_re_str)); - printf ("%s - connection time: %fs", state_text (status), conn_time); + printf("%s - connection time: %fs", state_text(status), conn_time); if (np_dbi_query) { if (type == TYPE_STRING) { - assert (expect || expect_re_str); - printf (", '%s' returned '%s' in %fs", np_dbi_query, - query_val_str ? query_val_str : "", query_time); + assert(expect || expect_re_str); + printf(", '%s' returned '%s' in %fs", np_dbi_query, query_val_str ? query_val_str : "", query_time); if (status != STATE_OK) { if (expect) - printf (" (expected '%s')", expect); + printf(" (expected '%s')", expect); else if (expect_re_str) - printf (" (expected regex /%s/%s)", expect_re_str, - ((expect_re_cflags & REG_ICASE) ? "i" : "")); + printf(" (expected regex /%s/%s)", expect_re_str, ((expect_re_cflags & REG_ICASE) ? "i" : "")); } - } - else if (isnan (query_val)) - printf (", '%s' query execution time: %fs", np_dbi_query, query_time); + } else if (isnan(query_val)) + printf(", '%s' query execution time: %fs", np_dbi_query, query_time); else - printf (", '%s' returned %f in %fs", np_dbi_query, query_val, query_time); + printf(", '%s' returned %f in %fs", np_dbi_query, query_val, query_time); } - printf (" | conntime=%fs;%s;%s;0; server_version=%u;%s;%s;0;", conn_time, - ((metric == METRIC_CONN_TIME) && warning_range) ? warning_range : "", - ((metric == METRIC_CONN_TIME) && critical_range) ? critical_range : "", - server_version, - ((metric == METRIC_SERVER_VERSION) && warning_range) ? warning_range : "", - ((metric == METRIC_SERVER_VERSION) && critical_range) ? critical_range : ""); + printf(" | conntime=%fs;%s;%s;0; server_version=%u;%s;%s;0;", conn_time, + ((metric == METRIC_CONN_TIME) && warning_range) ? warning_range : "", + ((metric == METRIC_CONN_TIME) && critical_range) ? critical_range : "", server_version, + ((metric == METRIC_SERVER_VERSION) && warning_range) ? warning_range : "", + ((metric == METRIC_SERVER_VERSION) && critical_range) ? critical_range : ""); if (np_dbi_query) { - if (! isnan (query_val)) /* this is also true when -e is used */ - printf (" query=%f;%s;%s;;", query_val, - ((metric == METRIC_QUERY_RESULT) && warning_range) ? warning_range : "", - ((metric == METRIC_QUERY_RESULT) && critical_range) ? critical_range : ""); - printf (" querytime=%fs;%s;%s;0;", query_time, - ((metric == METRIC_QUERY_TIME) && warning_range) ? warning_range : "", - ((metric == METRIC_QUERY_TIME) && critical_range) ? critical_range : ""); + if (!isnan(query_val)) /* this is also true when -e is used */ + printf(" query=%f;%s;%s;;", query_val, ((metric == METRIC_QUERY_RESULT) && warning_range) ? warning_range : "", + ((metric == METRIC_QUERY_RESULT) && critical_range) ? critical_range : ""); + printf(" querytime=%fs;%s;%s;0;", query_time, ((metric == METRIC_QUERY_TIME) && warning_range) ? warning_range : "", + ((metric == METRIC_QUERY_TIME) && critical_range) ? critical_range : ""); } - printf ("\n"); + printf("\n"); return status; } /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ +int process_arguments(int argc, char **argv) { int c; int option = 0; - static struct option longopts[] = { - STD_LONG_OPTS, - - {"expect", required_argument, 0, 'e'}, - {"regex", required_argument, 0, 'r'}, - {"regexi", required_argument, 0, 'R'}, - {"metric", required_argument, 0, 'm'}, - {"driver", required_argument, 0, 'd'}, - {"option", required_argument, 0, 'o'}, - {"query", required_argument, 0, 'q'}, - {"database", required_argument, 0, 'D'}, - {0, 0, 0, 0} - }; + static struct option longopts[] = {STD_LONG_OPTS, + + {"expect", required_argument, 0, 'e'}, + {"regex", required_argument, 0, 'r'}, + {"regexi", required_argument, 0, 'R'}, + {"metric", required_argument, 0, 'm'}, + {"driver", required_argument, 0, 'd'}, + {"option", required_argument, 0, 'o'}, + {"query", required_argument, 0, 'q'}, + {"database", required_argument, 0, 'D'}, + {0, 0, 0, 0}}; while (1) { - c = getopt_long (argc, argv, "Vvht:c:w:e:r:R:m:H:d:o:q:D:", - longopts, &option); + c = getopt_long(argc, argv, "Vvht:c:w:e:r:R:m:H:d:o:q:D:", longopts, &option); if (c == EOF) break; switch (c) { - case '?': /* usage */ - usage5 (); - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - - case 'c': /* critical range */ + case '?': /* usage */ + usage5(); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + + case 'c': /* critical range */ critical_range = optarg; type = TYPE_NUMERIC; break; - case 'w': /* warning range */ + case 'w': /* warning range */ warning_range = optarg; type = TYPE_NUMERIC; break; @@ -396,47 +372,45 @@ process_arguments (int argc, char **argv) case 'R': expect_re_cflags = REG_ICASE; /* fall through */ - case 'r': - { - int err; + case 'r': { + int err; - expect_re_cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE; - expect_re_str = optarg; - type = TYPE_STRING; + expect_re_cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE; + expect_re_str = optarg; + type = TYPE_STRING; - err = regcomp (&expect_re, expect_re_str, expect_re_cflags); - if (err) { - char errmsg[1024]; - regerror (err, &expect_re, errmsg, sizeof (errmsg)); - printf ("ERROR - failed to compile regular expression: %s\n", - errmsg); - return ERROR; - } - break; + err = regcomp(&expect_re, expect_re_str, expect_re_cflags); + if (err) { + char errmsg[1024]; + regerror(err, &expect_re, errmsg, sizeof(errmsg)); + printf("ERROR - failed to compile regular expression: %s\n", errmsg); + return ERROR; } + break; + } case 'm': - if (! strcasecmp (optarg, "CONN_TIME")) + if (!strcasecmp(optarg, "CONN_TIME")) metric = METRIC_CONN_TIME; - else if (! strcasecmp (optarg, "SERVER_VERSION")) + else if (!strcasecmp(optarg, "SERVER_VERSION")) metric = METRIC_SERVER_VERSION; - else if (! strcasecmp (optarg, "QUERY_RESULT")) + else if (!strcasecmp(optarg, "QUERY_RESULT")) metric = METRIC_QUERY_RESULT; - else if (! strcasecmp (optarg, "QUERY_TIME")) + else if (!strcasecmp(optarg, "QUERY_TIME")) metric = METRIC_QUERY_TIME; else - usage2 (_("Invalid metric"), optarg); + usage2(_("Invalid metric"), optarg); break; - case 't': /* timeout */ - if (!is_intnonneg (optarg)) - usage2 (_("Timeout interval must be a positive integer"), optarg); + case 't': /* timeout */ + if (!is_intnonneg(optarg)) + usage2(_("Timeout interval must be a positive integer"), optarg); else - timeout_interval = atoi (optarg); + timeout_interval = atoi(optarg); break; - case 'H': /* host */ - if (!is_host (optarg)) - usage2 (_("Invalid hostname/address"), optarg); + case 'H': /* host */ + if (!is_host(optarg)) + usage2(_("Invalid hostname/address"), optarg); else host = optarg; break; @@ -447,36 +421,33 @@ process_arguments (int argc, char **argv) case 'd': np_dbi_driver = optarg; break; - case 'o': - { - driver_option_t *new; + case 'o': { + driver_option_t *new; - char *k, *v; + char *k, *v; - k = optarg; - v = strchr (k, (int)'='); + k = optarg; + v = strchr(k, (int)'='); - if (! v) - usage2 (_("Option must be '='"), optarg); + if (!v) + usage2(_("Option must be '='"), optarg); - *v = '\0'; - ++v; + *v = '\0'; + ++v; - new = realloc (np_dbi_options, - (np_dbi_options_num + 1) * sizeof (*new)); - if (! new) { - printf ("UNKNOWN - failed to reallocate memory\n"); - exit (STATE_UNKNOWN); - } + new = realloc(np_dbi_options, (np_dbi_options_num + 1) * sizeof(*new)); + if (!new) { + printf("UNKNOWN - failed to reallocate memory\n"); + exit(STATE_UNKNOWN); + } - np_dbi_options = new; - new = np_dbi_options + np_dbi_options_num; - ++np_dbi_options_num; + np_dbi_options = new; + new = np_dbi_options + np_dbi_options_num; + ++np_dbi_options_num; - new->key = k; - new->value = v; - } - break; + new->key = k; + new->value = v; + } break; case 'q': np_dbi_query = optarg; break; @@ -486,341 +457,312 @@ process_arguments (int argc, char **argv) } } - set_thresholds (&dbi_thresholds, warning_range, critical_range); + set_thresholds(&dbi_thresholds, warning_range, critical_range); - return validate_arguments (); + return validate_arguments(); } -int -validate_arguments () -{ - if (! np_dbi_driver) - usage ("Must specify a DBI driver"); +int validate_arguments() { + if (!np_dbi_driver) + usage("Must specify a DBI driver"); - if (((metric == METRIC_QUERY_RESULT) || (metric == METRIC_QUERY_TIME)) - && (! np_dbi_query)) - usage ("Must specify a query to execute (metric == QUERY_RESULT)"); + if (((metric == METRIC_QUERY_RESULT) || (metric == METRIC_QUERY_TIME)) && (!np_dbi_query)) + usage("Must specify a query to execute (metric == QUERY_RESULT)"); - if ((metric != METRIC_CONN_TIME) - && (metric != METRIC_SERVER_VERSION) - && (metric != METRIC_QUERY_RESULT) - && (metric != METRIC_QUERY_TIME)) - usage ("Invalid metric specified"); + if ((metric != METRIC_CONN_TIME) && (metric != METRIC_SERVER_VERSION) && (metric != METRIC_QUERY_RESULT) && + (metric != METRIC_QUERY_TIME)) + usage("Invalid metric specified"); if (expect && (warning_range || critical_range || expect_re_str)) - usage ("Do not mix -e and -w/-c/-r/-R"); + usage("Do not mix -e and -w/-c/-r/-R"); if (expect_re_str && (warning_range || critical_range || expect)) - usage ("Do not mix -r/-R and -w/-c/-e"); + usage("Do not mix -r/-R and -w/-c/-e"); if (expect && (metric != METRIC_QUERY_RESULT)) - usage ("Option -e requires metric QUERY_RESULT"); + usage("Option -e requires metric QUERY_RESULT"); if (expect_re_str && (metric != METRIC_QUERY_RESULT)) - usage ("Options -r/-R require metric QUERY_RESULT"); + usage("Options -r/-R require metric QUERY_RESULT"); return OK; } -void -print_help (void) -{ - print_revision (progname, NP_VERSION); +void print_help(void) { + print_revision(progname, NP_VERSION); - printf (COPYRIGHT, copyright, email); + printf(COPYRIGHT, copyright, email); - printf (_("This program connects to an (SQL) database using DBI and checks the\n" - "specified metric against threshold levels. The default metric is\n" - "the result of the specified query.\n")); + printf(_("This program connects to an (SQL) database using DBI and checks the\n" + "specified metric against threshold levels. The default metric is\n" + "the result of the specified query.\n")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (UT_HELP_VRSN); + printf(UT_HELP_VRSN); /* include this conditionally to avoid 'zero-length printf format string' * compiler warnings */ #ifdef NP_EXTRA_OPTS - printf (UT_EXTRA_OPTS); + printf(UT_EXTRA_OPTS); #endif - printf ("\n"); - - printf (" %s\n", "-d, --driver=STRING"); - printf (" %s\n", _("DBI driver to use")); - printf (" %s\n", "-o, --option=STRING"); - printf (" %s\n", _("DBI driver options")); - printf (" %s\n", "-q, --query=STRING"); - printf (" %s\n", _("query to execute")); - printf ("\n"); - - printf (UT_WARN_CRIT_RANGE); - printf (" %s\n", "-e, --expect=STRING"); - printf (" %s\n", _("String to expect as query result")); - printf (" %s\n", _("Do not mix with -w, -c, -r, or -R!")); - printf (" %s\n", "-r, --regex=REGEX"); - printf (" %s\n", _("Extended POSIX regular expression to check query result against")); - printf (" %s\n", _("Do not mix with -w, -c, -e, or -R!")); - printf (" %s\n", "-R, --regexi=REGEX"); - printf (" %s\n", _("Case-insensitive extended POSIX regex to check query result against")); - printf (" %s\n", _("Do not mix with -w, -c, -e, or -r!")); - printf (" %s\n", "-m, --metric=METRIC"); - printf (" %s\n", _("Metric to check thresholds against. Available metrics:")); - printf (" CONN_TIME - %s\n", _("time used for setting up the database connection")); - printf (" QUERY_RESULT - %s\n", _("result (first column of first row) of the query")); - printf (" QUERY_TIME - %s\n", _("time used to execute the query")); - printf (" %s\n", _("(ignore the query result)")); - printf ("\n"); - - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - - printf (UT_VERBOSE); - - printf ("\n"); - printf (" %s\n", _("A DBI driver (-d option) is required. If the specified metric operates")); - printf (" %s\n\n", _("on a query, one has to be specified (-q option).")); - - printf (" %s\n", _("This plugin connects to an (SQL) database using libdbi and, optionally,")); - printf (" %s\n", _("executes the specified query. The first column of the first row of the")); - printf (" %s\n", _("result will be parsed and, in QUERY_RESULT mode, compared with the")); - printf (" %s\n", _("warning and critical ranges. The result from the query has to be numeric")); - printf (" %s\n\n", _("(strings representing numbers are fine).")); - - printf (" %s\n", _("The number and type of required DBI driver options depends on the actual")); - printf (" %s\n", _("driver. See its documentation at http://libdbi-drivers.sourceforge.net/")); - printf (" %s\n\n", _("for details.")); - - printf (" %s\n", _("Examples:")); - printf (" check_dbi -d pgsql -o username=postgres -m QUERY_RESULT \\\n"); - printf (" -q 'SELECT COUNT(*) FROM pg_stat_activity' -w 5 -c 10\n"); - printf (" Warning if more than five connections; critical if more than ten.\n\n"); - - printf (" check_dbi -d mysql -H localhost -o username=user -o password=secret \\\n"); - printf (" -q 'SELECT COUNT(*) FROM logged_in_users -w 5:20 -c 0:50\n"); - printf (" Warning if less than 5 or more than 20 users are logged in; critical\n"); - printf (" if more than 50 users.\n\n"); - - printf (" check_dbi -d firebird -o username=user -o password=secret -o dbname=foo \\\n"); - printf (" -m CONN_TIME -w 0.5 -c 2\n"); - printf (" Warning if connecting to the database takes more than half of a second;\n"); - printf (" critical if it takes more than 2 seconds.\n\n"); - - printf (" check_dbi -d mysql -H localhost -o username=user \\\n"); - printf (" -q 'SELECT concat(@@version, \" \", @@version_comment)' \\\n"); - printf (" -r '^5\\.[01].*MySQL Enterprise Server'\n"); - printf (" Critical if the database server is not a MySQL enterprise server in either\n"); - printf (" version 5.0.x or 5.1.x.\n\n"); - - printf (" check_dbi -d pgsql -u username=user -m SERVER_VERSION \\\n"); - printf (" -w 090000:090099 -c 090000:090199\n"); - printf (" Warn if the PostgreSQL server version is not 9.0.x; critical if the version\n"); - printf (" is less than 9.x or higher than 9.1.x.\n"); - - printf (UT_SUPPORT); + printf("\n"); + + printf(" %s\n", "-d, --driver=STRING"); + printf(" %s\n", _("DBI driver to use")); + printf(" %s\n", "-o, --option=STRING"); + printf(" %s\n", _("DBI driver options")); + printf(" %s\n", "-q, --query=STRING"); + printf(" %s\n", _("query to execute")); + printf("\n"); + + printf(UT_WARN_CRIT_RANGE); + printf(" %s\n", "-e, --expect=STRING"); + printf(" %s\n", _("String to expect as query result")); + printf(" %s\n", _("Do not mix with -w, -c, -r, or -R!")); + printf(" %s\n", "-r, --regex=REGEX"); + printf(" %s\n", _("Extended POSIX regular expression to check query result against")); + printf(" %s\n", _("Do not mix with -w, -c, -e, or -R!")); + printf(" %s\n", "-R, --regexi=REGEX"); + printf(" %s\n", _("Case-insensitive extended POSIX regex to check query result against")); + printf(" %s\n", _("Do not mix with -w, -c, -e, or -r!")); + printf(" %s\n", "-m, --metric=METRIC"); + printf(" %s\n", _("Metric to check thresholds against. Available metrics:")); + printf(" CONN_TIME - %s\n", _("time used for setting up the database connection")); + printf(" QUERY_RESULT - %s\n", _("result (first column of first row) of the query")); + printf(" QUERY_TIME - %s\n", _("time used to execute the query")); + printf(" %s\n", _("(ignore the query result)")); + printf("\n"); + + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + + printf(UT_VERBOSE); + + printf("\n"); + printf(" %s\n", _("A DBI driver (-d option) is required. If the specified metric operates")); + printf(" %s\n\n", _("on a query, one has to be specified (-q option).")); + + printf(" %s\n", _("This plugin connects to an (SQL) database using libdbi and, optionally,")); + printf(" %s\n", _("executes the specified query. The first column of the first row of the")); + printf(" %s\n", _("result will be parsed and, in QUERY_RESULT mode, compared with the")); + printf(" %s\n", _("warning and critical ranges. The result from the query has to be numeric")); + printf(" %s\n\n", _("(strings representing numbers are fine).")); + + printf(" %s\n", _("The number and type of required DBI driver options depends on the actual")); + printf(" %s\n", _("driver. See its documentation at http://libdbi-drivers.sourceforge.net/")); + printf(" %s\n\n", _("for details.")); + + printf(" %s\n", _("Examples:")); + printf(" check_dbi -d pgsql -o username=postgres -m QUERY_RESULT \\\n"); + printf(" -q 'SELECT COUNT(*) FROM pg_stat_activity' -w 5 -c 10\n"); + printf(" Warning if more than five connections; critical if more than ten.\n\n"); + + printf(" check_dbi -d mysql -H localhost -o username=user -o password=secret \\\n"); + printf(" -q 'SELECT COUNT(*) FROM logged_in_users -w 5:20 -c 0:50\n"); + printf(" Warning if less than 5 or more than 20 users are logged in; critical\n"); + printf(" if more than 50 users.\n\n"); + + printf(" check_dbi -d firebird -o username=user -o password=secret -o dbname=foo \\\n"); + printf(" -m CONN_TIME -w 0.5 -c 2\n"); + printf(" Warning if connecting to the database takes more than half of a second;\n"); + printf(" critical if it takes more than 2 seconds.\n\n"); + + printf(" check_dbi -d mysql -H localhost -o username=user \\\n"); + printf(" -q 'SELECT concat(@@version, \" \", @@version_comment)' \\\n"); + printf(" -r '^5\\.[01].*MySQL Enterprise Server'\n"); + printf(" Critical if the database server is not a MySQL enterprise server in either\n"); + printf(" version 5.0.x or 5.1.x.\n\n"); + + printf(" check_dbi -d pgsql -u username=user -m SERVER_VERSION \\\n"); + printf(" -w 090000:090099 -c 090000:090199\n"); + printf(" Warn if the PostgreSQL server version is not 9.0.x; critical if the version\n"); + printf(" is less than 9.x or higher than 9.1.x.\n"); + + printf(UT_SUPPORT); } -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s -d [-o [...]] [-q ]\n", progname); - printf (" [-H ] [-c ] [-w ] [-m ]\n"); - printf (" [-e ] [-r|-R ]\n"); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s -d [-o [...]] [-q ]\n", progname); + printf(" [-H ] [-c ] [-w ] [-m ]\n"); + printf(" [-e ] [-r|-R ]\n"); } -#define CHECK_IGNORE_ERROR(s) \ - do { \ - if (metric != METRIC_QUERY_RESULT) \ - return (s); \ +#define CHECK_IGNORE_ERROR(s) \ + do { \ + if (metric != METRIC_QUERY_RESULT) \ + return (s); \ } while (0) -const char * -get_field_str (dbi_conn conn, dbi_result res, unsigned short field_type) -{ +const char *get_field_str(dbi_conn conn, dbi_result res, unsigned short field_type) { const char *str; if (field_type != DBI_TYPE_STRING) { - printf ("CRITICAL - result value is not a string\n"); + printf("CRITICAL - result value is not a string\n"); return NULL; } - str = dbi_result_get_string_idx (res, 1); - if ((! str) || (strcmp (str, "ERROR") == 0)) { - CHECK_IGNORE_ERROR (NULL); - np_dbi_print_error (conn, "CRITICAL - failed to fetch string value"); + str = dbi_result_get_string_idx(res, 1); + if ((!str) || (strcmp(str, "ERROR") == 0)) { + CHECK_IGNORE_ERROR(NULL); + np_dbi_print_error(conn, "CRITICAL - failed to fetch string value"); return NULL; } if ((verbose && (type == TYPE_STRING)) || (verbose > 2)) - printf ("Query returned string '%s'\n", str); + printf("Query returned string '%s'\n", str); return str; } -double -get_field (dbi_conn conn, dbi_result res, unsigned short *field_type) -{ +double get_field(dbi_conn conn, dbi_result res, unsigned short *field_type) { double val = NAN; if (*field_type == DBI_TYPE_INTEGER) { - val = (double)dbi_result_get_longlong_idx (res, 1); - } - else if (*field_type == DBI_TYPE_DECIMAL) { - val = dbi_result_get_double_idx (res, 1); - } - else if (*field_type == DBI_TYPE_STRING) { + val = (double)dbi_result_get_longlong_idx(res, 1); + } else if (*field_type == DBI_TYPE_DECIMAL) { + val = dbi_result_get_double_idx(res, 1); + } else if (*field_type == DBI_TYPE_STRING) { const char *val_str; char *endptr = NULL; - val_str = get_field_str (conn, res, *field_type); - if (! val_str) { - CHECK_IGNORE_ERROR (NAN); + val_str = get_field_str(conn, res, *field_type); + if (!val_str) { + CHECK_IGNORE_ERROR(NAN); *field_type = DBI_TYPE_ERROR; return NAN; } - val = strtod (val_str, &endptr); + val = strtod(val_str, &endptr); if (endptr == val_str) { - CHECK_IGNORE_ERROR (NAN); - printf ("CRITICAL - result value is not a numeric: %s\n", val_str); + CHECK_IGNORE_ERROR(NAN); + printf("CRITICAL - result value is not a numeric: %s\n", val_str); *field_type = DBI_TYPE_ERROR; return NAN; - } - else if ((endptr != NULL) && (*endptr != '\0')) { + } else if ((endptr != NULL) && (*endptr != '\0')) { if (verbose) - printf ("Garbage after value: %s\n", endptr); + printf("Garbage after value: %s\n", endptr); } - } - else { - CHECK_IGNORE_ERROR (NAN); - printf ("CRITICAL - cannot parse value of type %s (%i)\n", - (*field_type == DBI_TYPE_BINARY) - ? "BINARY" - : (*field_type == DBI_TYPE_DATETIME) - ? "DATETIME" - : "", - *field_type); + } else { + CHECK_IGNORE_ERROR(NAN); + printf("CRITICAL - cannot parse value of type %s (%i)\n", + (*field_type == DBI_TYPE_BINARY) ? "BINARY" + : (*field_type == DBI_TYPE_DATETIME) ? "DATETIME" + : "", + *field_type); *field_type = DBI_TYPE_ERROR; return NAN; } return val; } -double -get_query_result (dbi_conn conn, dbi_result res, const char **res_val_str, double *res_val) -{ +double get_query_result(dbi_conn conn, dbi_result res, const char **res_val_str, double *res_val) { unsigned short field_type; double val = NAN; - if (dbi_result_get_numrows (res) == DBI_ROW_ERROR) { - CHECK_IGNORE_ERROR (STATE_OK); - np_dbi_print_error (conn, "CRITICAL - failed to fetch rows"); + if (dbi_result_get_numrows(res) == DBI_ROW_ERROR) { + CHECK_IGNORE_ERROR(STATE_OK); + np_dbi_print_error(conn, "CRITICAL - failed to fetch rows"); return STATE_CRITICAL; } - if (dbi_result_get_numrows (res) < 1) { - CHECK_IGNORE_ERROR (STATE_OK); - printf ("WARNING - no rows returned\n"); + if (dbi_result_get_numrows(res) < 1) { + CHECK_IGNORE_ERROR(STATE_OK); + printf("WARNING - no rows returned\n"); return STATE_WARNING; } - if (dbi_result_get_numfields (res) == DBI_FIELD_ERROR) { - CHECK_IGNORE_ERROR (STATE_OK); - np_dbi_print_error (conn, "CRITICAL - failed to fetch fields"); + if (dbi_result_get_numfields(res) == DBI_FIELD_ERROR) { + CHECK_IGNORE_ERROR(STATE_OK); + np_dbi_print_error(conn, "CRITICAL - failed to fetch fields"); return STATE_CRITICAL; } - if (dbi_result_get_numfields (res) < 1) { - CHECK_IGNORE_ERROR (STATE_OK); - printf ("WARNING - no fields returned\n"); + if (dbi_result_get_numfields(res) < 1) { + CHECK_IGNORE_ERROR(STATE_OK); + printf("WARNING - no fields returned\n"); return STATE_WARNING; } - if (dbi_result_first_row (res) != 1) { - CHECK_IGNORE_ERROR (STATE_OK); - np_dbi_print_error (conn, "CRITICAL - failed to fetch first row"); + if (dbi_result_first_row(res) != 1) { + CHECK_IGNORE_ERROR(STATE_OK); + np_dbi_print_error(conn, "CRITICAL - failed to fetch first row"); return STATE_CRITICAL; } - field_type = dbi_result_get_field_type_idx (res, 1); + field_type = dbi_result_get_field_type_idx(res, 1); if (field_type != DBI_TYPE_ERROR) { if (type == TYPE_STRING) /* the value will be freed in dbi_result_free */ - *res_val_str = strdup (get_field_str (conn, res, field_type)); + *res_val_str = strdup(get_field_str(conn, res, field_type)); else - val = get_field (conn, res, &field_type); + val = get_field(conn, res, &field_type); } *res_val = val; if (field_type == DBI_TYPE_ERROR) { - CHECK_IGNORE_ERROR (STATE_OK); - np_dbi_print_error (conn, "CRITICAL - failed to fetch data"); + CHECK_IGNORE_ERROR(STATE_OK); + np_dbi_print_error(conn, "CRITICAL - failed to fetch data"); return STATE_CRITICAL; } - dbi_result_free (res); + dbi_result_free(res); return STATE_OK; } #undef CHECK_IGNORE_ERROR -int -do_query (dbi_conn conn, const char **res_val_str, double *res_val, double *res_time) -{ +int do_query(dbi_conn conn, const char **res_val_str, double *res_val, double *res_time) { dbi_result res; struct timeval timeval_start, timeval_end; int status = STATE_OK; - assert (np_dbi_query); + assert(np_dbi_query); if (verbose) - printf ("Executing query '%s'\n", np_dbi_query); + printf("Executing query '%s'\n", np_dbi_query); - gettimeofday (&timeval_start, NULL); + gettimeofday(&timeval_start, NULL); - res = dbi_conn_query (conn, np_dbi_query); - if (! res) { - np_dbi_print_error (conn, "CRITICAL - failed to execute query '%s'", np_dbi_query); + res = dbi_conn_query(conn, np_dbi_query); + if (!res) { + np_dbi_print_error(conn, "CRITICAL - failed to execute query '%s'", np_dbi_query); return STATE_CRITICAL; } - status = get_query_result (conn, res, res_val_str, res_val); + status = get_query_result(conn, res, res_val_str, res_val); - gettimeofday (&timeval_end, NULL); - *res_time = timediff (timeval_start, timeval_end); + gettimeofday(&timeval_end, NULL); + *res_time = timediff(timeval_start, timeval_end); if (verbose) - printf ("Time elapsed: %f\n", *res_time); + printf("Time elapsed: %f\n", *res_time); return status; } -double -timediff (struct timeval start, struct timeval end) -{ +double timediff(struct timeval start, struct timeval end) { double diff; while (start.tv_usec > end.tv_usec) { --end.tv_sec; end.tv_usec += 1000000; } - diff = (double)(end.tv_sec - start.tv_sec) - + (double)(end.tv_usec - start.tv_usec) / 1000000.0; + diff = (double)(end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000.0; return diff; } -void -np_dbi_print_error (dbi_conn conn, char *fmt, ...) -{ +void np_dbi_print_error(dbi_conn conn, char *fmt, ...) { const char *errmsg = NULL; va_list ap; - va_start (ap, fmt); + va_start(ap, fmt); - dbi_conn_error (conn, &errmsg); - vprintf (fmt, ap); - printf (": %s\n", errmsg); + dbi_conn_error(conn, &errmsg); + vprintf(fmt, ap); + printf(": %s\n", errmsg); - va_end (ap); + va_end(ap); } - -- cgit v0.10-9-g596f From 267c6689813d6acac60a8cb4dce1e58055f8471d Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:13:07 +0100 Subject: check_dbi: Update copyright diff --git a/plugins/check_dbi.c b/plugins/check_dbi.c index 0c0ed6d..cb7c881 100644 --- a/plugins/check_dbi.c +++ b/plugins/check_dbi.c @@ -3,8 +3,8 @@ * Monitoring check_dbi plugin * * License: GPL - * Copyright (c) 2011 Monitoring Plugins Development Team - * Author: Sebastian 'tokkee' Harl + * Copyright (c) 2011-2024 Monitoring Plugins Development Team + * Original Author: Sebastian 'tokkee' Harl * * Description: * @@ -30,7 +30,7 @@ *****************************************************************************/ const char *progname = "check_dbi"; -const char *copyright = "2011"; +const char *copyright = "2011-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 981f1d562990d96001a88ea1227bc047561879c7 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:15:12 +0100 Subject: check_dbi: do not export local symbols diff --git a/plugins/check_dbi.c b/plugins/check_dbi.c index cb7c881..e896448 100644 --- a/plugins/check_dbi.c +++ b/plugins/check_dbi.c @@ -70,38 +70,38 @@ typedef struct { char *value; } driver_option_t; -char *host = NULL; -int verbose = 0; +static char *host = NULL; +static int verbose = 0; -char *warning_range = NULL; -char *critical_range = NULL; -thresholds *dbi_thresholds = NULL; +static char *warning_range = NULL; +static char *critical_range = NULL; +static thresholds *dbi_thresholds = NULL; -char *expect = NULL; +static char *expect = NULL; -regex_t expect_re; -char *expect_re_str = NULL; -int expect_re_cflags = 0; +static regex_t expect_re; +static char *expect_re_str = NULL; +static int expect_re_cflags = 0; -np_dbi_metric_t metric = METRIC_QUERY_RESULT; -np_dbi_type_t type = TYPE_NUMERIC; +static np_dbi_metric_t metric = METRIC_QUERY_RESULT; +static np_dbi_type_t type = TYPE_NUMERIC; -char *np_dbi_driver = NULL; -driver_option_t *np_dbi_options = NULL; -int np_dbi_options_num = 0; -char *np_dbi_database = NULL; -char *np_dbi_query = NULL; +static char *np_dbi_driver = NULL; +static driver_option_t *np_dbi_options = NULL; +static int np_dbi_options_num = 0; +static char *np_dbi_database = NULL; +static char *np_dbi_query = NULL; -int process_arguments(int, char **); -int validate_arguments(void); +static int process_arguments(int, char **); +static int validate_arguments(void); void print_usage(void); -void print_help(void); +static void print_help(void); -double timediff(struct timeval, struct timeval); +static double timediff(struct timeval, struct timeval); -void np_dbi_print_error(dbi_conn, char *, ...); +static void np_dbi_print_error(dbi_conn, char *, ...); -int do_query(dbi_conn, const char **, double *, double *); +static int do_query(dbi_conn, const char **, double *, double *); int main(int argc, char **argv) { int status = STATE_UNKNOWN; -- cgit v0.10-9-g596f From 79d7f401612d390d3a4975139da524043bdc43a7 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:17:20 +0100 Subject: check_dbi: linter fixes diff --git a/plugins/check_dbi.c b/plugins/check_dbi.c index e896448..9657567 100644 --- a/plugins/check_dbi.c +++ b/plugins/check_dbi.c @@ -111,7 +111,8 @@ int main(int argc, char **argv) { unsigned int server_version; - struct timeval start_timeval, end_timeval; + struct timeval start_timeval; + struct timeval end_timeval; double conn_time = 0.0; double query_time = 0.0; @@ -202,7 +203,8 @@ int main(int argc, char **argv) { } if (verbose) { - const char *dbname, *host; + const char *dbname; + const char *host; dbname = dbi_conn_get_option(conn, "dbname"); host = dbi_conn_get_option(conn, "host"); @@ -424,7 +426,8 @@ int process_arguments(int argc, char **argv) { case 'o': { driver_option_t *new; - char *k, *v; + char *k; + char *v; k = optarg; v = strchr(k, (int)'='); @@ -462,7 +465,7 @@ int process_arguments(int argc, char **argv) { return validate_arguments(); } -int validate_arguments() { +int validate_arguments(void) { if (!np_dbi_driver) usage("Must specify a DBI driver"); @@ -639,7 +642,8 @@ double get_field(dbi_conn conn, dbi_result res, unsigned short *field_type) { printf("CRITICAL - result value is not a numeric: %s\n", val_str); *field_type = DBI_TYPE_ERROR; return NAN; - } else if ((endptr != NULL) && (*endptr != '\0')) { + } + if ((endptr != NULL) && (*endptr != '\0')) { if (verbose) printf("Garbage after value: %s\n", endptr); } @@ -716,7 +720,8 @@ double get_query_result(dbi_conn conn, dbi_result res, const char **res_val_str, int do_query(dbi_conn conn, const char **res_val_str, double *res_val, double *res_time) { dbi_result res; - struct timeval timeval_start, timeval_end; + struct timeval timeval_start; + struct timeval timeval_end; int status = STATE_OK; assert(np_dbi_query); -- cgit v0.10-9-g596f From 904d1ef78dabae2e9fb1f57dfb7d43ecdf294fd3 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:19:50 +0100 Subject: check_dig: clang-format diff --git a/plugins/check_dig.c b/plugins/check_dig.c index be7a610..37e0e24 100644 --- a/plugins/check_dig.c +++ b/plugins/check_dig.c @@ -1,30 +1,30 @@ /***************************************************************************** -* -* Monitoring check_dig plugin -* -* License: GPL -* Copyright (c) 2002-2008 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_dig plugin -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_dig plugin + * + * License: GPL + * Copyright (c) 2002-2008 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_dig plugin + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ /* Hackers note: * There are typecasts to (char *) from _("foo bar") in this file. @@ -41,13 +41,13 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #include "runcmd.h" -int process_arguments (int, char **); -int validate_arguments (void); -void print_help (void); -void print_usage (void); +int process_arguments(int, char **); +int validate_arguments(void); +void print_help(void); +void print_usage(void); -#define UNDEFINED 0 -#define DEFAULT_PORT 53 +#define UNDEFINED 0 +#define DEFAULT_PORT 53 #define DEFAULT_TRIES 2 char *query_address = NULL; @@ -63,318 +63,290 @@ double warning_interval = UNDEFINED; double critical_interval = UNDEFINED; struct timeval tv; -int -main (int argc, char **argv) -{ - char *command_line; - output chld_out, chld_err; - char *msg = NULL; - size_t i; - char *t; - long microsec; - double elapsed_time; - int result = STATE_UNKNOWN; - int timeout_interval_dig; - - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); - - /* Set signal handling and alarm */ - if (signal (SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) - usage_va(_("Cannot catch SIGALRM")); - - /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); - - if (process_arguments (argc, argv) == ERROR) - usage_va(_("Could not parse arguments")); - - /* dig applies the timeout to each try, so we need to work around this */ - timeout_interval_dig = timeout_interval / number_tries + number_tries; - - /* get the command to run */ - xasprintf (&command_line, "%s %s %s -p %d @%s %s %s +retry=%d +time=%d", - PATH_TO_DIG, dig_args, query_transport, server_port, dns_server, query_address, record_type, number_tries, timeout_interval_dig); - - alarm (timeout_interval); - gettimeofday (&tv, NULL); - - if (verbose) { - printf ("%s\n", command_line); - if(expected_address != NULL) { - printf (_("Looking for: '%s'\n"), expected_address); - } else { - printf (_("Looking for: '%s'\n"), query_address); - } - } - - /* run the command */ - if(np_runcmd(command_line, &chld_out, &chld_err, 0) != 0) { - result = STATE_WARNING; - msg = (char *)_("dig returned an error status"); - } - - for(i = 0; i < chld_out.lines; i++) { - /* the server is responding, we just got the host name... */ - if (strstr (chld_out.line[i], ";; ANSWER SECTION:")) { - - /* loop through the whole 'ANSWER SECTION' */ - for(; i < chld_out.lines; i++) { - /* get the host address */ - if (verbose) - printf ("%s\n", chld_out.line[i]); - - if (strcasestr (chld_out.line[i], (expected_address == NULL ? query_address : expected_address)) != NULL) { - msg = chld_out.line[i]; - result = STATE_OK; - - /* Translate output TAB -> SPACE */ - t = msg; - while ((t = strchr(t, '\t')) != NULL) *t = ' '; - break; - } - } - - if (result == STATE_UNKNOWN) { - msg = (char *)_("Server not found in ANSWER SECTION"); - result = STATE_WARNING; - } - - /* we found the answer section, so break out of the loop */ - break; - } - } - - if (result == STATE_UNKNOWN) { - msg = (char *)_("No ANSWER SECTION found"); - result = STATE_CRITICAL; - } - - /* If we get anything on STDERR, at least set warning */ - if(chld_err.buflen > 0) { - result = max_state(result, STATE_WARNING); - if(!msg) for(i = 0; i < chld_err.lines; i++) { - msg = strchr(chld_err.line[0], ':'); - if(msg) { - msg++; - break; - } - } - } - - microsec = deltime (tv); - elapsed_time = (double)microsec / 1.0e6; - - if (critical_interval > UNDEFINED && elapsed_time > critical_interval) - result = STATE_CRITICAL; - - else if (warning_interval > UNDEFINED && elapsed_time > warning_interval) - result = STATE_WARNING; - - printf ("DNS %s - %.3f seconds response time (%s)|%s\n", - state_text (result), elapsed_time, - msg ? msg : _("Probably a non-existent host/domain"), - fperfdata("time", elapsed_time, "s", - (warning_interval>UNDEFINED ? true:false), - warning_interval, - (critical_interval>UNDEFINED ? true:false), - critical_interval, - true, 0, false, 0)); - return result; +int main(int argc, char **argv) { + char *command_line; + output chld_out, chld_err; + char *msg = NULL; + size_t i; + char *t; + long microsec; + double elapsed_time; + int result = STATE_UNKNOWN; + int timeout_interval_dig; + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + + /* Set signal handling and alarm */ + if (signal(SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) + usage_va(_("Cannot catch SIGALRM")); + + /* Parse extra opts if any */ + argv = np_extra_opts(&argc, argv, progname); + + if (process_arguments(argc, argv) == ERROR) + usage_va(_("Could not parse arguments")); + + /* dig applies the timeout to each try, so we need to work around this */ + timeout_interval_dig = timeout_interval / number_tries + number_tries; + + /* get the command to run */ + xasprintf(&command_line, "%s %s %s -p %d @%s %s %s +retry=%d +time=%d", PATH_TO_DIG, dig_args, query_transport, server_port, dns_server, + query_address, record_type, number_tries, timeout_interval_dig); + + alarm(timeout_interval); + gettimeofday(&tv, NULL); + + if (verbose) { + printf("%s\n", command_line); + if (expected_address != NULL) { + printf(_("Looking for: '%s'\n"), expected_address); + } else { + printf(_("Looking for: '%s'\n"), query_address); + } + } + + /* run the command */ + if (np_runcmd(command_line, &chld_out, &chld_err, 0) != 0) { + result = STATE_WARNING; + msg = (char *)_("dig returned an error status"); + } + + for (i = 0; i < chld_out.lines; i++) { + /* the server is responding, we just got the host name... */ + if (strstr(chld_out.line[i], ";; ANSWER SECTION:")) { + + /* loop through the whole 'ANSWER SECTION' */ + for (; i < chld_out.lines; i++) { + /* get the host address */ + if (verbose) + printf("%s\n", chld_out.line[i]); + + if (strcasestr(chld_out.line[i], (expected_address == NULL ? query_address : expected_address)) != NULL) { + msg = chld_out.line[i]; + result = STATE_OK; + + /* Translate output TAB -> SPACE */ + t = msg; + while ((t = strchr(t, '\t')) != NULL) + *t = ' '; + break; + } + } + + if (result == STATE_UNKNOWN) { + msg = (char *)_("Server not found in ANSWER SECTION"); + result = STATE_WARNING; + } + + /* we found the answer section, so break out of the loop */ + break; + } + } + + if (result == STATE_UNKNOWN) { + msg = (char *)_("No ANSWER SECTION found"); + result = STATE_CRITICAL; + } + + /* If we get anything on STDERR, at least set warning */ + if (chld_err.buflen > 0) { + result = max_state(result, STATE_WARNING); + if (!msg) + for (i = 0; i < chld_err.lines; i++) { + msg = strchr(chld_err.line[0], ':'); + if (msg) { + msg++; + break; + } + } + } + + microsec = deltime(tv); + elapsed_time = (double)microsec / 1.0e6; + + if (critical_interval > UNDEFINED && elapsed_time > critical_interval) + result = STATE_CRITICAL; + + else if (warning_interval > UNDEFINED && elapsed_time > warning_interval) + result = STATE_WARNING; + + printf("DNS %s - %.3f seconds response time (%s)|%s\n", state_text(result), elapsed_time, + msg ? msg : _("Probably a non-existent host/domain"), + fperfdata("time", elapsed_time, "s", (warning_interval > UNDEFINED ? true : false), warning_interval, + (critical_interval > UNDEFINED ? true : false), critical_interval, true, 0, false, 0)); + return result; } - - /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ - int c; - - int option = 0; - static struct option longopts[] = { - {"hostname", required_argument, 0, 'H'}, - {"query_address", required_argument, 0, 'l'}, - {"warning", required_argument, 0, 'w'}, - {"critical", required_argument, 0, 'c'}, - {"timeout", required_argument, 0, 't'}, - {"dig-arguments", required_argument, 0, 'A'}, - {"verbose", no_argument, 0, 'v'}, - {"version", no_argument, 0, 'V'}, - {"help", no_argument, 0, 'h'}, - {"record_type", required_argument, 0, 'T'}, - {"expected_address", required_argument, 0, 'a'}, - {"port", required_argument, 0, 'p'}, - {"use-ipv4", no_argument, 0, '4'}, - {"use-ipv6", no_argument, 0, '6'}, - {0, 0, 0, 0} - }; - - if (argc < 2) - return ERROR; - - while (1) { - c = getopt_long (argc, argv, "hVvt:l:H:w:c:T:p:a:A:46", longopts, &option); - - if (c == -1 || c == EOF) - break; - - switch (c) { - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'H': /* hostname */ - host_or_die(optarg); - dns_server = optarg; - break; - case 'p': /* server port */ - if (is_intpos (optarg)) { - server_port = atoi (optarg); - } - else { - usage_va(_("Port must be a positive integer - %s"), optarg); - } - break; - case 'l': /* address to lookup */ - query_address = optarg; - break; - case 'w': /* warning */ - if (is_nonnegative (optarg)) { - warning_interval = strtod (optarg, NULL); - } - else { - usage_va(_("Warning interval must be a positive integer - %s"), optarg); - } - break; - case 'c': /* critical */ - if (is_nonnegative (optarg)) { - critical_interval = strtod (optarg, NULL); - } - else { - usage_va(_("Critical interval must be a positive integer - %s"), optarg); - } - break; - case 't': /* timeout */ - if (is_intnonneg (optarg)) { - timeout_interval = atoi (optarg); - } - else { - usage_va(_("Timeout interval must be a positive integer - %s"), optarg); - } - break; - case 'A': /* dig arguments */ - dig_args = strdup(optarg); - break; - case 'v': /* verbose */ - verbose = true; - break; - case 'T': - record_type = optarg; - break; - case 'a': - expected_address = optarg; - break; - case '4': - query_transport = "-4"; - break; - case '6': - query_transport = "-6"; - break; - default: /* usage5 */ - usage5(); - } - } - - c = optind; - if (dns_server == NULL) { - if (c < argc) { - host_or_die(argv[c]); - dns_server = argv[c]; - } - else { - if (strcmp(query_transport,"-6") == 0) - dns_server = strdup("::1"); - else - dns_server = strdup ("127.0.0.1"); - } - } - - return validate_arguments (); +int process_arguments(int argc, char **argv) { + int c; + + int option = 0; + static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, + {"query_address", required_argument, 0, 'l'}, + {"warning", required_argument, 0, 'w'}, + {"critical", required_argument, 0, 'c'}, + {"timeout", required_argument, 0, 't'}, + {"dig-arguments", required_argument, 0, 'A'}, + {"verbose", no_argument, 0, 'v'}, + {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {"record_type", required_argument, 0, 'T'}, + {"expected_address", required_argument, 0, 'a'}, + {"port", required_argument, 0, 'p'}, + {"use-ipv4", no_argument, 0, '4'}, + {"use-ipv6", no_argument, 0, '6'}, + {0, 0, 0, 0}}; + + if (argc < 2) + return ERROR; + + while (1) { + c = getopt_long(argc, argv, "hVvt:l:H:w:c:T:p:a:A:46", longopts, &option); + + if (c == -1 || c == EOF) + break; + + switch (c) { + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'H': /* hostname */ + host_or_die(optarg); + dns_server = optarg; + break; + case 'p': /* server port */ + if (is_intpos(optarg)) { + server_port = atoi(optarg); + } else { + usage_va(_("Port must be a positive integer - %s"), optarg); + } + break; + case 'l': /* address to lookup */ + query_address = optarg; + break; + case 'w': /* warning */ + if (is_nonnegative(optarg)) { + warning_interval = strtod(optarg, NULL); + } else { + usage_va(_("Warning interval must be a positive integer - %s"), optarg); + } + break; + case 'c': /* critical */ + if (is_nonnegative(optarg)) { + critical_interval = strtod(optarg, NULL); + } else { + usage_va(_("Critical interval must be a positive integer - %s"), optarg); + } + break; + case 't': /* timeout */ + if (is_intnonneg(optarg)) { + timeout_interval = atoi(optarg); + } else { + usage_va(_("Timeout interval must be a positive integer - %s"), optarg); + } + break; + case 'A': /* dig arguments */ + dig_args = strdup(optarg); + break; + case 'v': /* verbose */ + verbose = true; + break; + case 'T': + record_type = optarg; + break; + case 'a': + expected_address = optarg; + break; + case '4': + query_transport = "-4"; + break; + case '6': + query_transport = "-6"; + break; + default: /* usage5 */ + usage5(); + } + } + + c = optind; + if (dns_server == NULL) { + if (c < argc) { + host_or_die(argv[c]); + dns_server = argv[c]; + } else { + if (strcmp(query_transport, "-6") == 0) + dns_server = strdup("::1"); + else + dns_server = strdup("127.0.0.1"); + } + } + + return validate_arguments(); } - - -int -validate_arguments (void) -{ - if (query_address != NULL) - return OK; - else - return ERROR; +int validate_arguments(void) { + if (query_address != NULL) + return OK; + else + return ERROR; } +void print_help(void) { + char *myport; + xasprintf(&myport, "%d", DEFAULT_PORT); -void -print_help (void) -{ - char *myport; + print_revision(progname, NP_VERSION); - xasprintf (&myport, "%d", DEFAULT_PORT); + printf("Copyright (c) 2000 Karl DeBisschop \n"); + printf(COPYRIGHT, copyright, email); - print_revision (progname, NP_VERSION); + printf(_("This plugin tests the DNS service on the specified host using dig")); - printf ("Copyright (c) 2000 Karl DeBisschop \n"); - printf (COPYRIGHT, copyright, email); + printf("\n\n"); - printf (_("This plugin tests the DNS service on the specified host using dig")); + print_usage(); - printf ("\n\n"); + printf(UT_HELP_VRSN); - print_usage (); + printf(UT_EXTRA_OPTS); - printf (UT_HELP_VRSN); + printf(UT_HOST_PORT, 'p', myport); - printf (UT_EXTRA_OPTS); + printf(" %s\n", "-4, --use-ipv4"); + printf(" %s\n", _("Force dig to only use IPv4 query transport")); + printf(" %s\n", "-6, --use-ipv6"); + printf(" %s\n", _("Force dig to only use IPv6 query transport")); + printf(" %s\n", "-l, --query_address=STRING"); + printf(" %s\n", _("Machine name to lookup")); + printf(" %s\n", "-T, --record_type=STRING"); + printf(" %s\n", _("Record type to lookup (default: A)")); + printf(" %s\n", "-a, --expected_address=STRING"); + printf(" %s\n", _("An address expected to be in the answer section. If not set, uses whatever")); + printf(" %s\n", _("was in -l")); + printf(" %s\n", "-A, --dig-arguments=STRING"); + printf(" %s\n", _("Pass STRING as argument(s) to dig")); + printf(UT_WARN_CRIT); + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + printf(UT_VERBOSE); - printf (UT_HOST_PORT, 'p', myport); + printf("\n"); + printf("%s\n", _("Examples:")); + printf(" %s\n", "check_dig -H DNSSERVER -l www.example.com -A \"+tcp\""); + printf(" %s\n", "This will send a tcp query to DNSSERVER for www.example.com"); - printf (" %s\n","-4, --use-ipv4"); - printf (" %s\n",_("Force dig to only use IPv4 query transport")); - printf (" %s\n","-6, --use-ipv6"); - printf (" %s\n",_("Force dig to only use IPv6 query transport")); - printf (" %s\n","-l, --query_address=STRING"); - printf (" %s\n",_("Machine name to lookup")); - printf (" %s\n","-T, --record_type=STRING"); - printf (" %s\n",_("Record type to lookup (default: A)")); - printf (" %s\n","-a, --expected_address=STRING"); - printf (" %s\n",_("An address expected to be in the answer section. If not set, uses whatever")); - printf (" %s\n",_("was in -l")); - printf (" %s\n","-A, --dig-arguments=STRING"); - printf (" %s\n",_("Pass STRING as argument(s) to dig")); - printf (UT_WARN_CRIT); - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - printf (UT_VERBOSE); - - printf ("\n"); - printf ("%s\n", _("Examples:")); - printf (" %s\n", "check_dig -H DNSSERVER -l www.example.com -A \"+tcp\""); - printf (" %s\n", "This will send a tcp query to DNSSERVER for www.example.com"); - - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s -l [-H ] [-p ]\n", progname); - printf (" [-T ] [-w ] [-c ]\n"); - printf (" [-t ] [-a ] [-v]\n"); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s -l [-H ] [-p ]\n", progname); + printf(" [-T ] [-w ] [-c ]\n"); + printf(" [-t ] [-a ] [-v]\n"); } -- cgit v0.10-9-g596f From f0d780384219dabb5b7ad569a7dfb3576b199230 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:21:37 +0100 Subject: check_dig: do not export local symbols diff --git a/plugins/check_dig.c b/plugins/check_dig.c index 37e0e24..e5f9993 100644 --- a/plugins/check_dig.c +++ b/plugins/check_dig.c @@ -41,27 +41,27 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #include "runcmd.h" -int process_arguments(int, char **); -int validate_arguments(void); -void print_help(void); +static int process_arguments(int /*argc*/, char ** /*argv*/); +static int validate_arguments(void); +static void print_help(void); void print_usage(void); #define UNDEFINED 0 #define DEFAULT_PORT 53 #define DEFAULT_TRIES 2 -char *query_address = NULL; -char *record_type = "A"; -char *expected_address = NULL; -char *dns_server = NULL; -char *dig_args = ""; -char *query_transport = ""; -bool verbose = false; -int server_port = DEFAULT_PORT; -int number_tries = DEFAULT_TRIES; -double warning_interval = UNDEFINED; -double critical_interval = UNDEFINED; -struct timeval tv; +static char *query_address = NULL; +static char *record_type = "A"; +static char *expected_address = NULL; +static char *dns_server = NULL; +static char *dig_args = ""; +static char *query_transport = ""; +static bool verbose = false; +static int server_port = DEFAULT_PORT; +static int number_tries = DEFAULT_TRIES; +static double warning_interval = UNDEFINED; +static double critical_interval = UNDEFINED; +static struct timeval tv; int main(int argc, char **argv) { char *command_line; -- cgit v0.10-9-g596f From acb19fe8f7acaeccb3fe0c1cb11e8ab5fd5e8a1b Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:22:43 +0100 Subject: check_dig: Linter fixes diff --git a/plugins/check_dig.c b/plugins/check_dig.c index e5f9993..4d89ca8 100644 --- a/plugins/check_dig.c +++ b/plugins/check_dig.c @@ -65,7 +65,8 @@ static struct timeval tv; int main(int argc, char **argv) { char *command_line; - output chld_out, chld_err; + output chld_out; + output chld_err; char *msg = NULL; size_t i; char *t; @@ -293,8 +294,7 @@ int process_arguments(int argc, char **argv) { int validate_arguments(void) { if (query_address != NULL) return OK; - else - return ERROR; + return ERROR; } void print_help(void) { -- cgit v0.10-9-g596f From 25e0c67b0972b9bef426ebf6ca11ee191df74cff Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:24:02 +0100 Subject: check_disk: clang-format diff --git a/plugins/check_disk.c b/plugins/check_disk.c index b3dd301..fc4039f 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -1,43 +1,42 @@ /***************************************************************************** -* -* Monitoring check_disk plugin -* -* License: GPL -* Copyright (c) 1999-2008 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_disk plugin -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_disk plugin + * + * License: GPL + * Copyright (c) 1999-2008 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_disk plugin + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "check_disk"; -const char *program_name = "check_disk"; /* Required for coreutils libs */ +const char *program_name = "check_disk"; /* Required for coreutils libs */ const char *copyright = "1999-2008"; const char *email = "devel@monitoring-plugins.org"; - #include "common.h" #ifdef HAVE_SYS_STAT_H -# include +# include #endif #if HAVE_INTTYPES_H -# include +# include #endif #include #include "popen.h" @@ -48,14 +47,14 @@ const char *email = "devel@monitoring-plugins.org"; #include "mountlist.h" #include #if HAVE_LIMITS_H -# include +# include #endif #include "regex.h" #ifdef __CYGWIN__ -# include -# undef ERROR -# define ERROR -1 +# include +# undef ERROR +# define ERROR -1 #endif /* If nonzero, show even filesystems with zero size or @@ -108,25 +107,24 @@ static struct mount_entry *mount_list; /* For long options that have no equivalent short option, use a non-character as a pseudo short option, starting with CHAR_MAX + 1. */ -enum -{ - SYNC_OPTION = CHAR_MAX + 1, - NO_SYNC_OPTION, - BLOCK_SIZE_OPTION +enum { + SYNC_OPTION = CHAR_MAX + 1, + NO_SYNC_OPTION, + BLOCK_SIZE_OPTION }; #ifdef _AIX -#pragma alloca +# pragma alloca #endif -static int process_arguments (int, char **); -static void set_all_thresholds (struct parameter_list *path); -static void print_help (void); -void print_usage (void); +static int process_arguments(int, char **); +static void set_all_thresholds(struct parameter_list *path); +static void print_help(void); +void print_usage(void); static double calculate_percent(uintmax_t, uintmax_t); -static bool stat_path (struct parameter_list *p); -static void get_stats (struct parameter_list *p, struct fs_usage *fsp); -static void get_path_stats (struct parameter_list *p, struct fs_usage *fsp); +static bool stat_path(struct parameter_list *p); +static void get_stats(struct parameter_list *p, struct fs_usage *fsp); +static void get_path_stats(struct parameter_list *p, struct fs_usage *fsp); static char *units; static uintmax_t mult = 1024 * 1024; @@ -155,992 +153,955 @@ static char *group = NULL; static struct stat *stat_buf; static struct name_list *seen = NULL; - -int -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 = " - free space:"; - char *ignored_preamble = " - ignored paths:"; - char *flag_header; - int temp_result; - - struct mount_entry *me; - struct fs_usage fsp; - struct parameter_list *temp_list, *path; +int 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 = " - free space:"; + char *ignored_preamble = " - ignored paths:"; + char *flag_header; + int temp_result; + + struct mount_entry *me; + struct fs_usage fsp; + struct parameter_list *temp_list, *path; #ifdef __CYGWIN__ - char mountdir[32]; + char mountdir[32]; #endif - output = strdup (""); - ignored = strdup (""); - details = strdup (""); - perf = strdup (""); - perf_ilabel = strdup (""); - stat_buf = malloc(sizeof *stat_buf); - - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); - - mount_list = read_file_system_list (0); - - /* Parse extra opts if any */ - argv = np_extra_opts (&argc, argv, progname); - - if (process_arguments (argc, argv) == ERROR) - usage4 (_("Could not parse arguments")); - - /* 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) { - 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); - } - path->best_match = me; - path->group = group; - set_all_thresholds(path); - } - } - - 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 (path_select_list) { - 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; - } - /* 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; - - if (! path_select_list && ignore_missing == true) { - result = STATE_OK; - if (verbose >= 2) { - printf ("None of the provided paths were found\n"); - } - } - - /* Process for every path in list */ - for (path = path_select_list; path; path=path->name_next) { - if (verbose >= 3 && path->freespace_percent->warning != NULL && path->freespace_percent->critical != NULL) - printf("Thresholds(pct) for %s warn: %f crit %f\n", - path->name, - path->freespace_percent->warning->end, - path->freespace_percent->critical->end); - - if (verbose >= 3 && path->group != NULL) - printf("Group of %s: %s\n",path->name,path->group); - - /* reset disk result */ - disk_result = STATE_UNKNOWN; - - me = path->best_match; - - if (!me) { - continue; - } + output = strdup(""); + ignored = strdup(""); + details = strdup(""); + perf = strdup(""); + perf_ilabel = strdup(""); + stat_buf = malloc(sizeof *stat_buf); + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + + mount_list = read_file_system_list(0); + + /* Parse extra opts if any */ + argv = np_extra_opts(&argc, argv, progname); + + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments")); + + /* 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) { + 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); + } + path->best_match = me; + path->group = group; + set_all_thresholds(path); + } + } + + 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 (path_select_list) { + 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; + } + /* 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; + + if (!path_select_list && ignore_missing == true) { + result = STATE_OK; + if (verbose >= 2) { + printf("None of the provided paths were found\n"); + } + } + + /* Process for every path in list */ + for (path = path_select_list; path; path = path->name_next) { + if (verbose >= 3 && path->freespace_percent->warning != NULL && path->freespace_percent->critical != NULL) + printf("Thresholds(pct) for %s warn: %f crit %f\n", path->name, path->freespace_percent->warning->end, + path->freespace_percent->critical->end); + + if (verbose >= 3 && path->group != NULL) + printf("Group of %s: %s\n", path->name, path->group); + + /* reset disk result */ + disk_result = STATE_UNKNOWN; + + me = path->best_match; + + if (!me) { + continue; + } #ifdef __CYGWIN__ - if (strncmp(path->name, "/cygdrive/", 10) != 0 || strlen(path->name) > 11) - continue; - snprintf(mountdir, sizeof(mountdir), "%s:\\", me->me_mountdir + 10); - if (GetDriveType(mountdir) != DRIVE_FIXED) - me->me_remote = 1; + if (strncmp(path->name, "/cygdrive/", 10) != 0 || strlen(path->name) > 11) + continue; + snprintf(mountdir, sizeof(mountdir), "%s:\\", me->me_mountdir + 10); + if (GetDriveType(mountdir) != DRIVE_FIXED) + me->me_remote = 1; #endif - /* Filters */ - - /* Remove filesystems already seen */ - if (np_seen_name(seen, me->me_mountdir)) { - continue; - } - np_add_name(&seen, me->me_mountdir); - - 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) { - if (!stat_path(path) && ignore_missing == true) { - 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) { - continue; - /* Skip excluded fstypes */ - } else if (fs_exclude_list && np_find_regmatch (fs_exclude_list, me->me_type)) { - continue; - /* Skip excluded fs's */ - } else if (dp_exclude_list && - (np_find_name (dp_exclude_list, me->me_devname) || - np_find_name (dp_exclude_list, me->me_mountdir))) { - continue; - /* Skip not included fstypes */ - } else if (fs_include_list && !np_find_regmatch(fs_include_list, me->me_type)) { - continue; - } - } - - if (!stat_path(path)) { - if (ignore_missing == true) { - 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)) { - get_stats (path, &fsp); - - if (verbose >= 3) { - printf ("For %s, used_pct=%f free_pct=%f used_units=%lu free_units=%lu total_units=%lu used_inodes_pct=%f free_inodes_pct=%f fsp.fsu_blocksize=%lu mult=%lu\n", - me->me_mountdir, - path->dused_pct, - path->dfree_pct, - path->dused_units, - path->dfree_units, - path->dtotal_units, - path->dused_inodes_percent, - path->dfree_inodes_percent, - fsp.fsu_blocksize, - mult); - } - - /* Threshold comparisons */ - - temp_result = get_status(path->dfree_units, path->freespace_units); - if (verbose >=3) printf("Freespace_units result=%d\n", temp_result); - disk_result = max_state( disk_result, temp_result ); - - temp_result = get_status(path->dfree_pct, path->freespace_percent); - if (verbose >=3) printf("Freespace%% result=%d\n", temp_result); - disk_result = max_state( disk_result, temp_result ); - - temp_result = get_status(path->dused_units, path->usedspace_units); - if (verbose >=3) printf("Usedspace_units result=%d\n", temp_result); - disk_result = max_state( disk_result, temp_result ); - - temp_result = get_status(path->dused_pct, path->usedspace_percent); - if (verbose >=3) printf("Usedspace_percent result=%d\n", temp_result); - disk_result = max_state( disk_result, temp_result ); - - temp_result = get_status(path->dused_inodes_percent, path->usedinodes_percent); - if (verbose >=3) printf("Usedinodes_percent result=%d\n", temp_result); - disk_result = max_state( disk_result, temp_result ); - - temp_result = get_status(path->dfree_inodes_percent, path->freeinodes_percent); - if (verbose >=3) printf("Freeinodes_percent result=%d\n", temp_result); - disk_result = max_state( disk_result, temp_result ); - - result = max_state(result, disk_result); - - /* What a mess of units. The output shows free space, the perf data shows used space. Yikes! - Hack here. Trying to get warn/crit levels from freespace_(units|percent) for perf - data. Assumption that start=0. Roll on new syntax... - */ - - /* *_high_tide must be reinitialized at each run */ - uint64_t warning_high_tide = UINT64_MAX; - - if (path->freespace_units->warning != NULL) { - warning_high_tide = (path->dtotal_units - path->freespace_units->warning->end) * mult; - } - if (path->freespace_percent->warning != NULL) { - warning_high_tide = min( warning_high_tide, (uint64_t)((1.0 - path->freespace_percent->warning->end/100) * (path->dtotal_units * mult)) ); - } - - uint64_t critical_high_tide = UINT64_MAX; - - if (path->freespace_units->critical != NULL) { - critical_high_tide = (path->dtotal_units - path->freespace_units->critical->end) * mult; - } - if (path->freespace_percent->critical != NULL) { - critical_high_tide = min( critical_high_tide, (uint64_t)((1.0 - path->freespace_percent->critical->end/100) * (path->dtotal_units * mult)) ); - } - - /* Nb: *_high_tide are unset when == UINT64_MAX */ - xasprintf (&perf, "%s %s", perf, - perfdata_uint64 ( - (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, - path->dused_units * mult, "B", - (warning_high_tide == UINT64_MAX ? false : true), warning_high_tide, - (critical_high_tide == UINT64_MAX ? false : true), critical_high_tide, - true, 0, - true, path->dtotal_units * mult)); - - if (display_inodes_perfdata) { - /* *_high_tide must be reinitialized at each run */ - warning_high_tide = UINT64_MAX; - critical_high_tide = UINT64_MAX; - - if (path->freeinodes_percent->warning != NULL) { - warning_high_tide = (uint64_t) fabs( min( (double) warning_high_tide, (double) (1.0 - path->freeinodes_percent->warning->end/100)*path->inodes_total )); - } - if (path->freeinodes_percent->critical != NULL) { - critical_high_tide = (uint64_t) fabs( min( (double) critical_high_tide, (double) (1.0 - path->freeinodes_percent->critical->end/100)*path->inodes_total )); - } - - xasprintf (&perf_ilabel, "%s (inodes)", (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir); - /* Nb: *_high_tide are unset when == UINT64_MAX */ - xasprintf (&perf, "%s %s", perf, - perfdata_uint64 (perf_ilabel, - path->inodes_used, "", - (warning_high_tide != UINT64_MAX ? true : false), warning_high_tide, - (critical_high_tide != UINT64_MAX ? true : false), critical_high_tide, - true, 0, - true, path->inodes_total)); - } - - if (disk_result==STATE_OK && erronly && !verbose) - continue; - - if(disk_result && verbose >= 1) { - xasprintf(&flag_header, " %s [", state_text (disk_result)); - } else { - xasprintf(&flag_header, ""); - } - xasprintf (&output, "%s%s %s %llu%s (%.1f%%", - output, flag_header, - (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, - path->dfree_units, - units, - path->dfree_pct); - if (path->dused_inodes_percent < 0) { - xasprintf(&output, "%s inode=-)%s;", output, (disk_result ? "]" : "")); - } else { - xasprintf(&output, "%s inode=%.0f%%)%s;", output, path->dfree_inodes_percent, ((disk_result && verbose >= 1) ? "]" : "")); - } - free(flag_header); - } - } - - if (verbose >= 2) - xasprintf (&output, "%s%s", output, details); - - if (strcmp(output, "") == 0 && ! erronly) { - preamble = ""; - 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); - return result; -} + /* Filters */ + + /* Remove filesystems already seen */ + if (np_seen_name(seen, me->me_mountdir)) { + continue; + } + np_add_name(&seen, me->me_mountdir); + + 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) { + if (!stat_path(path) && ignore_missing == true) { + 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) { + continue; + /* Skip excluded fstypes */ + } else if (fs_exclude_list && np_find_regmatch(fs_exclude_list, me->me_type)) { + continue; + /* Skip excluded fs's */ + } else if (dp_exclude_list && + (np_find_name(dp_exclude_list, me->me_devname) || np_find_name(dp_exclude_list, me->me_mountdir))) { + continue; + /* Skip not included fstypes */ + } else if (fs_include_list && !np_find_regmatch(fs_include_list, me->me_type)) { + continue; + } + } + + if (!stat_path(path)) { + if (ignore_missing == true) { + 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)) { + get_stats(path, &fsp); + + if (verbose >= 3) { + printf("For %s, used_pct=%f free_pct=%f used_units=%lu free_units=%lu total_units=%lu used_inodes_pct=%f " + "free_inodes_pct=%f fsp.fsu_blocksize=%lu mult=%lu\n", + me->me_mountdir, path->dused_pct, path->dfree_pct, path->dused_units, path->dfree_units, path->dtotal_units, + path->dused_inodes_percent, path->dfree_inodes_percent, fsp.fsu_blocksize, mult); + } + + /* Threshold comparisons */ + + temp_result = get_status(path->dfree_units, path->freespace_units); + if (verbose >= 3) + printf("Freespace_units result=%d\n", temp_result); + disk_result = max_state(disk_result, temp_result); + + temp_result = get_status(path->dfree_pct, path->freespace_percent); + if (verbose >= 3) + printf("Freespace%% result=%d\n", temp_result); + disk_result = max_state(disk_result, temp_result); + + temp_result = get_status(path->dused_units, path->usedspace_units); + if (verbose >= 3) + printf("Usedspace_units result=%d\n", temp_result); + disk_result = max_state(disk_result, temp_result); + + temp_result = get_status(path->dused_pct, path->usedspace_percent); + if (verbose >= 3) + printf("Usedspace_percent result=%d\n", temp_result); + disk_result = max_state(disk_result, temp_result); + + temp_result = get_status(path->dused_inodes_percent, path->usedinodes_percent); + if (verbose >= 3) + printf("Usedinodes_percent result=%d\n", temp_result); + disk_result = max_state(disk_result, temp_result); + + temp_result = get_status(path->dfree_inodes_percent, path->freeinodes_percent); + if (verbose >= 3) + printf("Freeinodes_percent result=%d\n", temp_result); + disk_result = max_state(disk_result, temp_result); + + result = max_state(result, disk_result); + + /* What a mess of units. The output shows free space, the perf data shows used space. Yikes! + Hack here. Trying to get warn/crit levels from freespace_(units|percent) for perf + data. Assumption that start=0. Roll on new syntax... + */ + + /* *_high_tide must be reinitialized at each run */ + uint64_t warning_high_tide = UINT64_MAX; + + if (path->freespace_units->warning != NULL) { + warning_high_tide = (path->dtotal_units - path->freespace_units->warning->end) * mult; + } + if (path->freespace_percent->warning != NULL) { + warning_high_tide = + min(warning_high_tide, (uint64_t)((1.0 - path->freespace_percent->warning->end / 100) * (path->dtotal_units * mult))); + } + + uint64_t critical_high_tide = UINT64_MAX; + + if (path->freespace_units->critical != NULL) { + critical_high_tide = (path->dtotal_units - path->freespace_units->critical->end) * mult; + } + if (path->freespace_percent->critical != NULL) { + critical_high_tide = + min(critical_high_tide, (uint64_t)((1.0 - path->freespace_percent->critical->end / 100) * (path->dtotal_units * mult))); + } + + /* Nb: *_high_tide are unset when == UINT64_MAX */ + xasprintf(&perf, "%s %s", perf, + perfdata_uint64((!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, + path->dused_units * mult, "B", (warning_high_tide == UINT64_MAX ? false : true), warning_high_tide, + (critical_high_tide == UINT64_MAX ? false : true), critical_high_tide, true, 0, true, + path->dtotal_units * mult)); + + if (display_inodes_perfdata) { + /* *_high_tide must be reinitialized at each run */ + warning_high_tide = UINT64_MAX; + critical_high_tide = UINT64_MAX; + + if (path->freeinodes_percent->warning != NULL) { + warning_high_tide = (uint64_t)fabs( + min((double)warning_high_tide, (double)(1.0 - path->freeinodes_percent->warning->end / 100) * path->inodes_total)); + } + if (path->freeinodes_percent->critical != NULL) { + critical_high_tide = (uint64_t)fabs(min( + (double)critical_high_tide, (double)(1.0 - path->freeinodes_percent->critical->end / 100) * path->inodes_total)); + } + + xasprintf(&perf_ilabel, "%s (inodes)", + (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir); + /* Nb: *_high_tide are unset when == UINT64_MAX */ + xasprintf(&perf, "%s %s", perf, + perfdata_uint64(perf_ilabel, path->inodes_used, "", (warning_high_tide != UINT64_MAX ? true : false), + warning_high_tide, (critical_high_tide != UINT64_MAX ? true : false), critical_high_tide, true, 0, + true, path->inodes_total)); + } + + if (disk_result == STATE_OK && erronly && !verbose) + continue; + + if (disk_result && verbose >= 1) { + xasprintf(&flag_header, " %s [", state_text(disk_result)); + } else { + xasprintf(&flag_header, ""); + } + xasprintf(&output, "%s%s %s %llu%s (%.1f%%", output, flag_header, + (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, path->dfree_units, units, + path->dfree_pct); + if (path->dused_inodes_percent < 0) { + xasprintf(&output, "%s inode=-)%s;", output, (disk_result ? "]" : "")); + } else { + xasprintf(&output, "%s inode=%.0f%%)%s;", output, path->dfree_inodes_percent, ((disk_result && verbose >= 1) ? "]" : "")); + } + free(flag_header); + } + } + + if (verbose >= 2) + xasprintf(&output, "%s%s", output, details); + if (strcmp(output, "") == 0 && !erronly) { + preamble = ""; + 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); + return result; +} double calculate_percent(uintmax_t value, uintmax_t total) { - double pct = -1; - if(value <= DBL_MAX && total != 0) { - pct = (double)value / total * 100.0; - } - return pct; + double pct = -1; + if (value <= DBL_MAX && total != 0) { + pct = (double)value / total * 100.0; + } + return pct; } /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ - int c, err; - struct parameter_list *se; - struct parameter_list *temp_list = NULL, *previous = NULL; - struct mount_entry *me; - regex_t re; - int cflags = REG_NOSUB | REG_EXTENDED; - int default_cflags = cflags; - char errbuf[MAX_INPUT_BUFFER]; - int fnd = 0; - - int option = 0; - static struct option longopts[] = { - {"timeout", required_argument, 0, 't'}, - {"warning", required_argument, 0, 'w'}, - {"critical", required_argument, 0, 'c'}, - {"iwarning", required_argument, 0, 'W'}, - /* Dang, -C is taken. We might want to reshuffle this. */ - {"icritical", required_argument, 0, 'K'}, - {"kilobytes", no_argument, 0, 'k'}, - {"megabytes", no_argument, 0, 'm'}, - {"units", required_argument, 0, 'u'}, - {"path", required_argument, 0, 'p'}, - {"partition", required_argument, 0, 'p'}, - {"exclude_device", required_argument, 0, 'x'}, - {"exclude-type", required_argument, 0, 'X'}, - {"include-type", required_argument, 0, 'N'}, - {"group", required_argument, 0, 'g'}, - {"eregi-path", required_argument, 0, 'R'}, - {"eregi-partition", required_argument, 0, 'R'}, - {"ereg-path", required_argument, 0, 'r'}, - {"ereg-partition", required_argument, 0, 'r'}, - {"freespace-ignore-reserved", no_argument, 0, 'f'}, - {"ignore-ereg-path", required_argument, 0, 'i'}, - {"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, 'n'}, - {"local", no_argument, 0, 'l'}, - {"stat-remote-fs", no_argument, 0, 'L'}, - {"iperfdata", no_argument, 0, 'P'}, - {"mountpoint", no_argument, 0, 'M'}, - {"errors-only", no_argument, 0, 'e'}, - {"exact-match", no_argument, 0, 'E'}, - {"all", no_argument, 0, 'A'}, - {"verbose", no_argument, 0, 'v'}, - {"quiet", no_argument, 0, 'q'}, - {"clear", no_argument, 0, 'C'}, - {"version", no_argument, 0, 'V'}, - {"help", no_argument, 0, 'h'}, - {0, 0, 0, 0} - }; - - if (argc < 2) - return ERROR; - - np_add_regex(&fs_exclude_list, "iso9660", REG_EXTENDED); - - for (c = 1; c < argc; c++) - if (strcmp ("-to", argv[c]) == 0) - strcpy (argv[c], "-t"); - - while (1) { - c = getopt_long (argc, argv, "+?VqhvefCt:c:w:K:W:u:p:x:X:N:mklLPg:R:r:i:I:MEAn", longopts, &option); - - if (c == -1 || c == EOF) - break; - - switch (c) { - case 't': /* timeout period */ - if (is_integer (optarg)) { - timeout_interval = atoi (optarg); - break; - } - else { - usage2 (_("Timeout interval must be a positive integer"), optarg); - } - - /* See comments for 'c' */ - case 'w': /* warning threshold */ +int process_arguments(int argc, char **argv) { + int c, err; + struct parameter_list *se; + struct parameter_list *temp_list = NULL, *previous = NULL; + struct mount_entry *me; + regex_t re; + int cflags = REG_NOSUB | REG_EXTENDED; + int default_cflags = cflags; + char errbuf[MAX_INPUT_BUFFER]; + int fnd = 0; + + int option = 0; + static struct option longopts[] = {{"timeout", required_argument, 0, 't'}, + {"warning", required_argument, 0, 'w'}, + {"critical", required_argument, 0, 'c'}, + {"iwarning", required_argument, 0, 'W'}, + /* Dang, -C is taken. We might want to reshuffle this. */ + {"icritical", required_argument, 0, 'K'}, + {"kilobytes", no_argument, 0, 'k'}, + {"megabytes", no_argument, 0, 'm'}, + {"units", required_argument, 0, 'u'}, + {"path", required_argument, 0, 'p'}, + {"partition", required_argument, 0, 'p'}, + {"exclude_device", required_argument, 0, 'x'}, + {"exclude-type", required_argument, 0, 'X'}, + {"include-type", required_argument, 0, 'N'}, + {"group", required_argument, 0, 'g'}, + {"eregi-path", required_argument, 0, 'R'}, + {"eregi-partition", required_argument, 0, 'R'}, + {"ereg-path", required_argument, 0, 'r'}, + {"ereg-partition", required_argument, 0, 'r'}, + {"freespace-ignore-reserved", no_argument, 0, 'f'}, + {"ignore-ereg-path", required_argument, 0, 'i'}, + {"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, 'n'}, + {"local", no_argument, 0, 'l'}, + {"stat-remote-fs", no_argument, 0, 'L'}, + {"iperfdata", no_argument, 0, 'P'}, + {"mountpoint", no_argument, 0, 'M'}, + {"errors-only", no_argument, 0, 'e'}, + {"exact-match", no_argument, 0, 'E'}, + {"all", no_argument, 0, 'A'}, + {"verbose", no_argument, 0, 'v'}, + {"quiet", no_argument, 0, 'q'}, + {"clear", no_argument, 0, 'C'}, + {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {0, 0, 0, 0}}; + + if (argc < 2) + return ERROR; + + np_add_regex(&fs_exclude_list, "iso9660", REG_EXTENDED); + + for (c = 1; c < argc; c++) + if (strcmp("-to", argv[c]) == 0) + strcpy(argv[c], "-t"); + + while (1) { + c = getopt_long(argc, argv, "+?VqhvefCt:c:w:K:W:u:p:x:X:N:mklLPg:R:r:i:I:MEAn", longopts, &option); + + if (c == -1 || c == EOF) + break; + + switch (c) { + case 't': /* timeout period */ + if (is_integer(optarg)) { + timeout_interval = atoi(optarg); + break; + } else { + usage2(_("Timeout interval must be a positive integer"), optarg); + } + + /* See comments for 'c' */ + case 'w': /* warning threshold */ if (!is_percentage_expression(optarg) && !is_numeric(optarg)) { - die(STATE_UNKNOWN, "Argument for --warning invalid or missing: %s\n", optarg); + die(STATE_UNKNOWN, "Argument for --warning invalid or missing: %s\n", optarg); } - if (strstr(optarg, "%")) { - if (*optarg == '@') { - warn_freespace_percent = optarg; - } else { - xasprintf(&warn_freespace_percent, "@%s", optarg); - } - } else { - if (*optarg == '@') { - warn_freespace_units = optarg; - } else { - xasprintf(&warn_freespace_units, "@%s", optarg); - } - } - break; - - /* Awful mistake where the range values do not make sense. Normally, - you alert if the value is within the range, but since we are using - freespace, we have to alert if outside the range. Thus we artificially - force @ at the beginning of the range, so that it is backwards compatible - */ - case 'c': /* critical threshold */ + if (strstr(optarg, "%")) { + if (*optarg == '@') { + warn_freespace_percent = optarg; + } else { + xasprintf(&warn_freespace_percent, "@%s", optarg); + } + } else { + if (*optarg == '@') { + warn_freespace_units = optarg; + } else { + xasprintf(&warn_freespace_units, "@%s", optarg); + } + } + break; + + /* Awful mistake where the range values do not make sense. Normally, + you alert if the value is within the range, but since we are using + freespace, we have to alert if outside the range. Thus we artificially + force @ at the beginning of the range, so that it is backwards compatible + */ + case 'c': /* critical threshold */ if (!is_percentage_expression(optarg) && !is_numeric(optarg)) { - die(STATE_UNKNOWN, "Argument for --critical invalid or missing: %s\n", optarg); + die(STATE_UNKNOWN, "Argument for --critical invalid or missing: %s\n", optarg); } - if (strstr(optarg, "%")) { - if (*optarg == '@') { - crit_freespace_percent = optarg; - } else { - xasprintf(&crit_freespace_percent, "@%s", optarg); - } - } else { - if (*optarg == '@') { - crit_freespace_units = optarg; - } else { - xasprintf(&crit_freespace_units, "@%s", optarg); - } - } - break; - - case 'W': /* warning inode threshold */ - if (*optarg == '@') { - warn_freeinodes_percent = optarg; - } else { - xasprintf(&warn_freeinodes_percent, "@%s", optarg); - } - break; - case 'K': /* critical inode threshold */ - if (*optarg == '@') { - crit_freeinodes_percent = optarg; - } else { - xasprintf(&crit_freeinodes_percent, "@%s", optarg); - } - break; - case 'u': - if (units) - free(units); - if (! strcasecmp (optarg, "bytes")) { - mult = (uintmax_t)1; - units = strdup ("B"); - } else if (!strcmp(optarg, "KiB")) { - mult = (uintmax_t)1024; - units = strdup ("KiB"); - } else if (! strcmp (optarg, "kB")) { - mult = (uintmax_t)1000; - units = strdup ("kB"); - } else if (!strcmp(optarg, "MiB")) { - mult = (uintmax_t)1024 * 1024; - units = strdup ("MiB"); - } else if (! strcmp (optarg, "MB")) { - mult = (uintmax_t)1000 * 1000; - units = strdup ("MB"); - } else if (!strcmp(optarg, "GiB")) { - mult = (uintmax_t)1024 * 1024 * 1024; - units = strdup ("GiB"); - } else if (! strcmp (optarg, "GB")){ - mult = (uintmax_t)1000 * 1000 * 1000; - units = strdup ("GB"); - } else if (!strcmp(optarg, "TiB")) { - mult = (uintmax_t)1024 * 1024 * 1024 * 1024; - units = strdup ("TiB"); - } else if (! strcmp (optarg, "TB")) { - mult = (uintmax_t)1000 * 1000 * 1000 * 1000; - units = strdup ("TB"); - } else if (!strcmp(optarg, "PiB")) { - mult = (uintmax_t)1024 * 1024 * 1024 * 1024 * 1024; - units = strdup ("PiB"); - } else if (! strcmp (optarg, "PB")){ - mult = (uintmax_t)1000 * 1000 * 1000 * 1000 * 1000; - units = strdup ("PB"); - } else { - die (STATE_UNKNOWN, _("unit type %s not known\n"), optarg); - } - if (units == NULL) - die (STATE_UNKNOWN, _("failed allocating storage for '%s'\n"), "units"); - break; - case 'k': /* display mountpoint */ - mult = 1024; - if (units) - free(units); - units = strdup ("kiB"); - break; - case 'm': /* display mountpoint */ - mult = 1024 * 1024; - if (units) - free(units); - units = strdup ("MiB"); - break; - case 'L': - stat_remote_fs = 1; - /* fallthrough */ - case 'l': - show_local_fs = 1; - break; - case 'P': - display_inodes_perfdata = 1; - break; - case 'p': /* select path */ - if (! (warn_freespace_units || crit_freespace_units || warn_freespace_percent || - crit_freespace_percent || warn_usedspace_units || crit_usedspace_units || - warn_usedspace_percent || crit_usedspace_percent || warn_usedinodes_percent || - crit_usedinodes_percent || warn_freeinodes_percent || crit_freeinodes_percent )) { - die (STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set a threshold value before using -p\n")); - } - - /* 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 == true) { - 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 */ - 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 */ - mount_list = read_file_system_list (0); - np_set_best_match(se, mount_list, exact_match); - - path_selected = true; - break; - case 'x': /* exclude path or partition */ - np_add_name(&dp_exclude_list, optarg); - break; - case 'X': /* exclude file system type */ - err = np_add_regex(&fs_exclude_list, optarg, REG_EXTENDED); - if (err != 0) { - regerror (err, &fs_exclude_list->regex, errbuf, MAX_INPUT_BUFFER); - die (STATE_UNKNOWN, "DISK %s: %s - %s\n",_("UNKNOWN"), _("Could not compile regular expression"), errbuf); - } - break; - case 'N': /* include file system type */ - err = np_add_regex(&fs_include_list, optarg, REG_EXTENDED); - if (err != 0) { - regerror (err, &fs_exclude_list->regex, errbuf, MAX_INPUT_BUFFER); - die (STATE_UNKNOWN, "DISK %s: %s - %s\n",_("UNKNOWN"), _("Could not compile regular expression"), errbuf); - } - break; - case 'v': /* verbose */ - verbose++; - break; - case 'q': /* TODO: this function should eventually go away (removed 2007-09-20) */ - /* verbose--; **replaced by line below**. -q was only a broken way of implementing -e */ - erronly = true; - break; - case 'e': - erronly = true; - break; - case 'E': - if (path_selected) - die (STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set -E before selecting paths\n")); - exact_match = true; - break; - case 'f': - freespace_ignore_reserved = true; - break; - case 'g': - if (path_selected) - die (STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set group value before selecting paths\n")); - group = optarg; - break; - case 'I': - cflags |= REG_ICASE; - // Intentional fallthrough - case 'i': - if (!path_selected) - die (STATE_UNKNOWN, "DISK %s: %s\n", _("UNKNOWN"), _("Paths need to be selected before using -i/-I. Use -A to select all paths explicitly")); - err = regcomp(&re, optarg, cflags); - if (err != 0) { - regerror (err, &re, errbuf, MAX_INPUT_BUFFER); - die (STATE_UNKNOWN, "DISK %s: %s - %s\n",_("UNKNOWN"), _("Could not compile regular expression"), errbuf); - } - - temp_list = path_select_list; - - previous = NULL; - while (temp_list) { - if (temp_list->best_match) { - if (np_regex_match_mount_entry(temp_list->best_match, &re)) { - - if (verbose >=3) - printf("ignoring %s matching regex\n", temp_list->name); - - temp_list = np_del_parameter(temp_list, previous); - /* pointer to first element needs to be updated if first item gets deleted */ - if (previous == NULL) - path_select_list = temp_list; - } else { - previous = temp_list; - temp_list = temp_list->name_next; - } - } else { - previous = temp_list; - temp_list = temp_list->name_next; - } - } - - - cflags = default_cflags; - break; - - case 'n': - ignore_missing = true; - break; - case 'A': - optarg = strdup(".*"); - // Intentional fallthrough - case 'R': - cflags |= REG_ICASE; - // Intentional fallthrough - case 'r': - if (! (warn_freespace_units || crit_freespace_units || warn_freespace_percent || - crit_freespace_percent || warn_usedspace_units || crit_usedspace_units || - warn_usedspace_percent || crit_usedspace_percent || warn_usedinodes_percent || - crit_usedinodes_percent || warn_freeinodes_percent || crit_freeinodes_percent )) { - die (STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set a threshold value before using -r/-R/-A (--ereg-path/--eregi-path/--all)\n")); - } - - err = regcomp(&re, optarg, cflags); - if (err != 0) { - regerror (err, &re, errbuf, MAX_INPUT_BUFFER); - die (STATE_UNKNOWN, "DISK %s: %s - %s\n",_("UNKNOWN"), _("Could not compile regular expression"), errbuf); - } - - for (me = mount_list; me; me = me->me_next) { - if (np_regex_match_mount_entry(me, &re)) { - fnd = true; - if (verbose >= 3) - printf("%s %s matching expression %s\n", me->me_devname, me->me_mountdir, optarg); - - /* add parameter if not found. overwrite thresholds if path has already been added */ - if (! (se = np_find_parameter(path_select_list, me->me_mountdir))) { - se = np_add_parameter(&path_select_list, me->me_mountdir); - } - se->group = group; - set_all_thresholds(se); - } - } - - if (!fnd && ignore_missing == true) { - 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); - - fnd = false; - path_selected = true; - np_set_best_match(path_select_list, mount_list, exact_match); - cflags = default_cflags; - - break; - case 'M': /* display mountpoint */ - display_mntp = true; - break; - case 'C': - /* add all mount entries to path_select list if no partitions have been explicitly defined using -p */ - if (path_selected == false) { - struct parameter_list *path; - 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); - path->best_match = me; - path->group = group; - set_all_thresholds(path); - } - } - warn_freespace_units = NULL; - crit_freespace_units = NULL; - warn_usedspace_units = NULL; - crit_usedspace_units = NULL; - warn_freespace_percent = NULL; - crit_freespace_percent = NULL; - warn_usedspace_percent = NULL; - crit_usedspace_percent = NULL; - warn_usedinodes_percent = NULL; - crit_usedinodes_percent = NULL; - warn_freeinodes_percent = NULL; - crit_freeinodes_percent = NULL; - - path_selected = false; - group = NULL; - break; - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case '?': /* help */ - usage (_("Unknown argument")); - } - } - - /* Support for "check_disk warn crit [fs]" with thresholds at used% level */ - c = optind; - if (warn_usedspace_percent == NULL && argc > c && is_intnonneg (argv[c])) - warn_usedspace_percent = argv[c++]; - - if (crit_usedspace_percent == NULL && argc > c && is_intnonneg (argv[c])) - crit_usedspace_percent = argv[c++]; - - if (argc > c) { - se = np_add_parameter(&path_select_list, strdup(argv[c++])); - path_selected = true; - set_all_thresholds(se); - } - - if (units == NULL) { - units = strdup ("MiB"); - mult = (uintmax_t)1024 * 1024; - } - - return true; -} + if (strstr(optarg, "%")) { + if (*optarg == '@') { + crit_freespace_percent = optarg; + } else { + xasprintf(&crit_freespace_percent, "@%s", optarg); + } + } else { + if (*optarg == '@') { + crit_freespace_units = optarg; + } else { + xasprintf(&crit_freespace_units, "@%s", optarg); + } + } + break; -void -set_all_thresholds (struct parameter_list *path) -{ - if (path->freespace_units != NULL) free(path->freespace_units); - set_thresholds(&path->freespace_units, warn_freespace_units, crit_freespace_units); - if (path->freespace_percent != NULL) free (path->freespace_percent); - set_thresholds(&path->freespace_percent, warn_freespace_percent, crit_freespace_percent); - if (path->usedspace_units != NULL) free (path->usedspace_units); - set_thresholds(&path->usedspace_units, warn_usedspace_units, crit_usedspace_units); - if (path->usedspace_percent != NULL) free (path->usedspace_percent); - set_thresholds(&path->usedspace_percent, warn_usedspace_percent, crit_usedspace_percent); - if (path->usedinodes_percent != NULL) free (path->usedinodes_percent); - set_thresholds(&path->usedinodes_percent, warn_usedinodes_percent, crit_usedinodes_percent); - if (path->freeinodes_percent != NULL) free (path->freeinodes_percent); - set_thresholds(&path->freeinodes_percent, warn_freeinodes_percent, crit_freeinodes_percent); -} + case 'W': /* warning inode threshold */ + if (*optarg == '@') { + warn_freeinodes_percent = optarg; + } else { + xasprintf(&warn_freeinodes_percent, "@%s", optarg); + } + break; + case 'K': /* critical inode threshold */ + if (*optarg == '@') { + crit_freeinodes_percent = optarg; + } else { + xasprintf(&crit_freeinodes_percent, "@%s", optarg); + } + break; + case 'u': + if (units) + free(units); + if (!strcasecmp(optarg, "bytes")) { + mult = (uintmax_t)1; + units = strdup("B"); + } else if (!strcmp(optarg, "KiB")) { + mult = (uintmax_t)1024; + units = strdup("KiB"); + } else if (!strcmp(optarg, "kB")) { + mult = (uintmax_t)1000; + units = strdup("kB"); + } else if (!strcmp(optarg, "MiB")) { + mult = (uintmax_t)1024 * 1024; + units = strdup("MiB"); + } else if (!strcmp(optarg, "MB")) { + mult = (uintmax_t)1000 * 1000; + units = strdup("MB"); + } else if (!strcmp(optarg, "GiB")) { + mult = (uintmax_t)1024 * 1024 * 1024; + units = strdup("GiB"); + } else if (!strcmp(optarg, "GB")) { + mult = (uintmax_t)1000 * 1000 * 1000; + units = strdup("GB"); + } else if (!strcmp(optarg, "TiB")) { + mult = (uintmax_t)1024 * 1024 * 1024 * 1024; + units = strdup("TiB"); + } else if (!strcmp(optarg, "TB")) { + mult = (uintmax_t)1000 * 1000 * 1000 * 1000; + units = strdup("TB"); + } else if (!strcmp(optarg, "PiB")) { + mult = (uintmax_t)1024 * 1024 * 1024 * 1024 * 1024; + units = strdup("PiB"); + } else if (!strcmp(optarg, "PB")) { + mult = (uintmax_t)1000 * 1000 * 1000 * 1000 * 1000; + units = strdup("PB"); + } else { + die(STATE_UNKNOWN, _("unit type %s not known\n"), optarg); + } + if (units == NULL) + die(STATE_UNKNOWN, _("failed allocating storage for '%s'\n"), "units"); + break; + case 'k': /* display mountpoint */ + mult = 1024; + if (units) + free(units); + units = strdup("kiB"); + break; + case 'm': /* display mountpoint */ + mult = 1024 * 1024; + if (units) + free(units); + units = strdup("MiB"); + break; + case 'L': + stat_remote_fs = 1; + /* fallthrough */ + case 'l': + show_local_fs = 1; + break; + case 'P': + display_inodes_perfdata = 1; + break; + case 'p': /* select path */ + if (!(warn_freespace_units || crit_freespace_units || warn_freespace_percent || crit_freespace_percent || + warn_usedspace_units || crit_usedspace_units || warn_usedspace_percent || crit_usedspace_percent || + warn_usedinodes_percent || crit_usedinodes_percent || warn_freeinodes_percent || crit_freeinodes_percent)) { + die(STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set a threshold value before using -p\n")); + } -void -print_help (void) -{ - print_revision (progname, NP_VERSION); - - printf ("Copyright (c) 1999 Ethan Galstad \n"); - printf (COPYRIGHT, copyright, email); - - printf ("%s\n", _("This plugin checks the amount of used disk space on a mounted file system")); - printf ("%s\n", _("and generates an alert if free space is less than one of the threshold values")); - - printf ("\n\n"); - - print_usage (); - - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); - - printf (" %s\n", "-w, --warning=INTEGER"); - printf (" %s\n", _("Exit with WARNING status if less than INTEGER units of disk are free")); - printf (" %s\n", "-w, --warning=PERCENT%"); - printf (" %s\n", _("Exit with WARNING status if less than PERCENT of disk space is free")); - printf (" %s\n", "-c, --critical=INTEGER"); - printf (" %s\n", _("Exit with CRITICAL status if less than INTEGER units of disk are free")); - printf (" %s\n", "-c, --critical=PERCENT%"); - printf (" %s\n", _("Exit with CRITICAL status if less than PERCENT of disk space is free")); - printf (" %s\n", "-W, --iwarning=PERCENT%"); - printf (" %s\n", _("Exit with WARNING status if less than PERCENT of inode space is free")); - printf (" %s\n", "-K, --icritical=PERCENT%"); - printf (" %s\n", _("Exit with CRITICAL status if less than PERCENT of inode space is free")); - printf (" %s\n", "-p, --path=PATH, --partition=PARTITION"); - printf (" %s\n", _("Mount point or block device as emitted by the mount(8) command (may be repeated)")); - printf (" %s\n", "-x, --exclude_device=PATH "); - printf (" %s\n", _("Ignore device (only works if -p unspecified)")); - printf (" %s\n", "-C, --clear"); - printf (" %s\n", _("Clear thresholds")); - printf (" %s\n", "-E, --exact-match"); - printf (" %s\n", _("For paths or partitions specified with -p, only check for exact paths")); - printf (" %s\n", "-e, --errors-only"); - printf (" %s\n", _("Display only devices/mountpoints with errors")); - printf (" %s\n", "-f, --freespace-ignore-reserved"); - printf (" %s\n", _("Don't account root-reserved blocks into freespace in perfdata")); - printf (" %s\n", "-P, --iperfdata"); - printf (" %s\n", _("Display inode usage in perfdata")); - printf (" %s\n", "-g, --group=NAME"); - printf (" %s\n", _("Group paths. Thresholds apply to (free-)space of all partitions together")); - printf (" %s\n", "-k, --kilobytes"); - printf (" %s\n", _("Same as '--units kB'")); - printf (" %s\n", "-l, --local"); - printf (" %s\n", _("Only check local filesystems")); - printf (" %s\n", "-L, --stat-remote-fs"); - printf (" %s\n", _("Only check local filesystems against thresholds. Yet call stat on remote filesystems")); - printf (" %s\n", _("to test if they are accessible (e.g. to detect Stale NFS Handles)")); - printf (" %s\n", "-M, --mountpoint"); - printf (" %s\n", _("Display the (block) device instead of the mount point")); - printf (" %s\n", "-m, --megabytes"); - printf (" %s\n", _("Same as '--units MB'")); - printf (" %s\n", "-A, --all"); - printf (" %s\n", _("Explicitly select all paths. This is equivalent to -R '.*'")); - printf (" %s\n", "-R, --eregi-path=PATH, --eregi-partition=PARTITION"); - printf (" %s\n", _("Case insensitive regular expression for path/partition (may be repeated)")); - printf (" %s\n", "-r, --ereg-path=PATH, --ereg-partition=PARTITION"); - printf (" %s\n", _("Regular expression for path or partition (may be repeated)")); - printf (" %s\n", "-I, --ignore-eregi-path=PATH, --ignore-eregi-partition=PARTITION"); - 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", "-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 -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)")); - printf (UT_VERBOSE); - printf (" %s\n", "-X, --exclude-type=TYPE_REGEX"); - printf (" %s\n", _("Ignore all filesystems of types matching given regex(7) (may be repeated)")); - printf (" %s\n", "-N, --include-type=TYPE_REGEX"); - printf (" %s\n", _("Check only filesystems where the type matches this given regex(7) (may be repeated)")); - - printf ("\n"); - printf ("%s\n", _("General usage hints:")); - printf (" %s\n", _("- Arguments are positional! \"-w 5 -c 1 -p /foo -w6 -c2 -p /bar\" is not the same as")); - printf (" %s\n", _("\"-w 5 -c 1 -p /bar w6 -c2 -p /foo\".")); - printf (" %s\n", _("- The syntax is broadly: \"{thresholds a} {paths a} -C {thresholds b} {thresholds b} ...\"")); - - - - printf ("\n"); - printf ("%s\n", _("Examples:")); - printf (" %s\n", "check_disk -w 10% -c 5% -p /tmp -p /var -C -w 100000 -c 50000 -p /"); - printf (" %s\n\n", _("Checks /tmp and /var at 10% and 5%, and / at 100MB and 50MB")); - printf (" %s\n", "check_disk -w 100 -c 50 -C -w 1000 -c 500 -g sidDATA -r '^/oracle/SID/data.*$'"); - printf (" %s\n", _("Checks all filesystems not matching -r at 100M and 50M. The fs matching the -r regex")); - printf (" %s\n\n", _("are grouped which means the freespace thresholds are applied to all disks together")); - printf (" %s\n", "check_disk -w 100 -c 50 -C -w 1000 -c 500 -p /foo -C -w 5% -c 3% -p /bar"); - printf (" %s\n", _("Checks /foo for 1000M/500M and /bar for 5/3%. All remaining volumes use 100M/50M")); - - printf (UT_SUPPORT); -} + /* 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 == true) { + 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 */ + 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 */ + mount_list = read_file_system_list(0); + np_set_best_match(se, mount_list, exact_match); + + path_selected = true; + break; + case 'x': /* exclude path or partition */ + np_add_name(&dp_exclude_list, optarg); + break; + case 'X': /* exclude file system type */ + err = np_add_regex(&fs_exclude_list, optarg, REG_EXTENDED); + if (err != 0) { + regerror(err, &fs_exclude_list->regex, errbuf, MAX_INPUT_BUFFER); + die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"), _("Could not compile regular expression"), errbuf); + } + break; + case 'N': /* include file system type */ + err = np_add_regex(&fs_include_list, optarg, REG_EXTENDED); + if (err != 0) { + regerror(err, &fs_exclude_list->regex, errbuf, MAX_INPUT_BUFFER); + die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"), _("Could not compile regular expression"), errbuf); + } + break; + case 'v': /* verbose */ + verbose++; + break; + case 'q': /* TODO: this function should eventually go away (removed 2007-09-20) */ + /* verbose--; **replaced by line below**. -q was only a broken way of implementing -e */ + erronly = true; + break; + case 'e': + erronly = true; + break; + case 'E': + if (path_selected) + die(STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set -E before selecting paths\n")); + exact_match = true; + break; + case 'f': + freespace_ignore_reserved = true; + break; + case 'g': + if (path_selected) + die(STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set group value before selecting paths\n")); + group = optarg; + break; + case 'I': + cflags |= REG_ICASE; + // Intentional fallthrough + case 'i': + if (!path_selected) + die(STATE_UNKNOWN, "DISK %s: %s\n", _("UNKNOWN"), + _("Paths need to be selected before using -i/-I. Use -A to select all paths explicitly")); + err = regcomp(&re, optarg, cflags); + if (err != 0) { + regerror(err, &re, errbuf, MAX_INPUT_BUFFER); + die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"), _("Could not compile regular expression"), errbuf); + } + + temp_list = path_select_list; + + previous = NULL; + while (temp_list) { + if (temp_list->best_match) { + if (np_regex_match_mount_entry(temp_list->best_match, &re)) { + + if (verbose >= 3) + printf("ignoring %s matching regex\n", temp_list->name); + + temp_list = np_del_parameter(temp_list, previous); + /* pointer to first element needs to be updated if first item gets deleted */ + if (previous == NULL) + path_select_list = temp_list; + } else { + previous = temp_list; + temp_list = temp_list->name_next; + } + } else { + previous = temp_list; + temp_list = temp_list->name_next; + } + } + + cflags = default_cflags; + break; + + case 'n': + ignore_missing = true; + break; + case 'A': + optarg = strdup(".*"); + // Intentional fallthrough + case 'R': + cflags |= REG_ICASE; + // Intentional fallthrough + case 'r': + if (!(warn_freespace_units || crit_freespace_units || warn_freespace_percent || crit_freespace_percent || + warn_usedspace_units || crit_usedspace_units || warn_usedspace_percent || crit_usedspace_percent || + warn_usedinodes_percent || crit_usedinodes_percent || warn_freeinodes_percent || crit_freeinodes_percent)) { + die(STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), + _("Must set a threshold value before using -r/-R/-A (--ereg-path/--eregi-path/--all)\n")); + } + + err = regcomp(&re, optarg, cflags); + if (err != 0) { + regerror(err, &re, errbuf, MAX_INPUT_BUFFER); + die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"), _("Could not compile regular expression"), errbuf); + } + for (me = mount_list; me; me = me->me_next) { + if (np_regex_match_mount_entry(me, &re)) { + fnd = true; + if (verbose >= 3) + printf("%s %s matching expression %s\n", me->me_devname, me->me_mountdir, optarg); + + /* add parameter if not found. overwrite thresholds if path has already been added */ + if (!(se = np_find_parameter(path_select_list, me->me_mountdir))) { + se = np_add_parameter(&path_select_list, me->me_mountdir); + } + se->group = group; + set_all_thresholds(se); + } + } + if (!fnd && ignore_missing == true) { + 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); + + fnd = false; + path_selected = true; + np_set_best_match(path_select_list, mount_list, exact_match); + cflags = default_cflags; + + break; + case 'M': /* display mountpoint */ + display_mntp = true; + break; + case 'C': + /* add all mount entries to path_select list if no partitions have been explicitly defined using -p */ + if (path_selected == false) { + struct parameter_list *path; + 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); + path->best_match = me; + path->group = group; + set_all_thresholds(path); + } + } + warn_freespace_units = NULL; + crit_freespace_units = NULL; + warn_usedspace_units = NULL; + crit_usedspace_units = NULL; + warn_freespace_percent = NULL; + crit_freespace_percent = NULL; + warn_usedspace_percent = NULL; + crit_usedspace_percent = NULL; + warn_usedinodes_percent = NULL; + crit_usedinodes_percent = NULL; + warn_freeinodes_percent = NULL; + crit_freeinodes_percent = NULL; + + path_selected = false; + group = NULL; + break; + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case '?': /* help */ + usage(_("Unknown argument")); + } + } + + /* Support for "check_disk warn crit [fs]" with thresholds at used% level */ + c = optind; + if (warn_usedspace_percent == NULL && argc > c && is_intnonneg(argv[c])) + warn_usedspace_percent = argv[c++]; + + if (crit_usedspace_percent == NULL && argc > c && is_intnonneg(argv[c])) + crit_usedspace_percent = argv[c++]; + + if (argc > c) { + se = np_add_parameter(&path_select_list, strdup(argv[c++])); + path_selected = true; + set_all_thresholds(se); + } + + if (units == NULL) { + units = strdup("MiB"); + mult = (uintmax_t)1024 * 1024; + } + + return true; +} -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - 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_regex] [-N type]\n"); +void set_all_thresholds(struct parameter_list *path) { + if (path->freespace_units != NULL) + free(path->freespace_units); + set_thresholds(&path->freespace_units, warn_freespace_units, crit_freespace_units); + if (path->freespace_percent != NULL) + free(path->freespace_percent); + set_thresholds(&path->freespace_percent, warn_freespace_percent, crit_freespace_percent); + if (path->usedspace_units != NULL) + free(path->usedspace_units); + set_thresholds(&path->usedspace_units, warn_usedspace_units, crit_usedspace_units); + if (path->usedspace_percent != NULL) + free(path->usedspace_percent); + set_thresholds(&path->usedspace_percent, warn_usedspace_percent, crit_usedspace_percent); + if (path->usedinodes_percent != NULL) + free(path->usedinodes_percent); + set_thresholds(&path->usedinodes_percent, warn_usedinodes_percent, crit_usedinodes_percent); + if (path->freeinodes_percent != NULL) + free(path->freeinodes_percent); + set_thresholds(&path->freeinodes_percent, warn_freeinodes_percent, crit_freeinodes_percent); } -bool -stat_path (struct parameter_list *p) -{ - /* Stat entry to check that dir exists and is accessible */ - if (verbose >= 3) - printf("calling stat on %s\n", p->name); - if (stat (p->name, &stat_buf[0])) { - if (verbose >= 3) - printf("stat failed on %s\n", p->name); - if (ignore_missing == true) { - return false; - } else { - printf("DISK %s - ", _("CRITICAL")); - die (STATE_CRITICAL, _("%s %s: %s\n"), p->name, _("is not accessible"), strerror(errno)); - } - } - return true; +void print_help(void) { + print_revision(progname, NP_VERSION); + + printf("Copyright (c) 1999 Ethan Galstad \n"); + printf(COPYRIGHT, copyright, email); + + printf("%s\n", _("This plugin checks the amount of used disk space on a mounted file system")); + printf("%s\n", _("and generates an alert if free space is less than one of the threshold values")); + + printf("\n\n"); + + print_usage(); + + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); + + printf(" %s\n", "-w, --warning=INTEGER"); + printf(" %s\n", _("Exit with WARNING status if less than INTEGER units of disk are free")); + printf(" %s\n", "-w, --warning=PERCENT%"); + printf(" %s\n", _("Exit with WARNING status if less than PERCENT of disk space is free")); + printf(" %s\n", "-c, --critical=INTEGER"); + printf(" %s\n", _("Exit with CRITICAL status if less than INTEGER units of disk are free")); + printf(" %s\n", "-c, --critical=PERCENT%"); + printf(" %s\n", _("Exit with CRITICAL status if less than PERCENT of disk space is free")); + printf(" %s\n", "-W, --iwarning=PERCENT%"); + printf(" %s\n", _("Exit with WARNING status if less than PERCENT of inode space is free")); + printf(" %s\n", "-K, --icritical=PERCENT%"); + printf(" %s\n", _("Exit with CRITICAL status if less than PERCENT of inode space is free")); + printf(" %s\n", "-p, --path=PATH, --partition=PARTITION"); + printf(" %s\n", _("Mount point or block device as emitted by the mount(8) command (may be repeated)")); + printf(" %s\n", "-x, --exclude_device=PATH "); + printf(" %s\n", _("Ignore device (only works if -p unspecified)")); + printf(" %s\n", "-C, --clear"); + printf(" %s\n", _("Clear thresholds")); + printf(" %s\n", "-E, --exact-match"); + printf(" %s\n", _("For paths or partitions specified with -p, only check for exact paths")); + printf(" %s\n", "-e, --errors-only"); + printf(" %s\n", _("Display only devices/mountpoints with errors")); + printf(" %s\n", "-f, --freespace-ignore-reserved"); + printf(" %s\n", _("Don't account root-reserved blocks into freespace in perfdata")); + printf(" %s\n", "-P, --iperfdata"); + printf(" %s\n", _("Display inode usage in perfdata")); + printf(" %s\n", "-g, --group=NAME"); + printf(" %s\n", _("Group paths. Thresholds apply to (free-)space of all partitions together")); + printf(" %s\n", "-k, --kilobytes"); + printf(" %s\n", _("Same as '--units kB'")); + printf(" %s\n", "-l, --local"); + printf(" %s\n", _("Only check local filesystems")); + printf(" %s\n", "-L, --stat-remote-fs"); + printf(" %s\n", _("Only check local filesystems against thresholds. Yet call stat on remote filesystems")); + printf(" %s\n", _("to test if they are accessible (e.g. to detect Stale NFS Handles)")); + printf(" %s\n", "-M, --mountpoint"); + printf(" %s\n", _("Display the (block) device instead of the mount point")); + printf(" %s\n", "-m, --megabytes"); + printf(" %s\n", _("Same as '--units MB'")); + printf(" %s\n", "-A, --all"); + printf(" %s\n", _("Explicitly select all paths. This is equivalent to -R '.*'")); + printf(" %s\n", "-R, --eregi-path=PATH, --eregi-partition=PARTITION"); + printf(" %s\n", _("Case insensitive regular expression for path/partition (may be repeated)")); + printf(" %s\n", "-r, --ereg-path=PATH, --ereg-partition=PARTITION"); + printf(" %s\n", _("Regular expression for path or partition (may be repeated)")); + printf(" %s\n", "-I, --ignore-eregi-path=PATH, --ignore-eregi-partition=PARTITION"); + 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", "-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 -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)")); + printf(UT_VERBOSE); + printf(" %s\n", "-X, --exclude-type=TYPE_REGEX"); + printf(" %s\n", _("Ignore all filesystems of types matching given regex(7) (may be repeated)")); + printf(" %s\n", "-N, --include-type=TYPE_REGEX"); + printf(" %s\n", _("Check only filesystems where the type matches this given regex(7) (may be repeated)")); + + printf("\n"); + printf("%s\n", _("General usage hints:")); + printf(" %s\n", _("- Arguments are positional! \"-w 5 -c 1 -p /foo -w6 -c2 -p /bar\" is not the same as")); + printf(" %s\n", _("\"-w 5 -c 1 -p /bar w6 -c2 -p /foo\".")); + printf(" %s\n", _("- The syntax is broadly: \"{thresholds a} {paths a} -C {thresholds b} {thresholds b} ...\"")); + + printf("\n"); + printf("%s\n", _("Examples:")); + printf(" %s\n", "check_disk -w 10% -c 5% -p /tmp -p /var -C -w 100000 -c 50000 -p /"); + printf(" %s\n\n", _("Checks /tmp and /var at 10% and 5%, and / at 100MB and 50MB")); + printf(" %s\n", "check_disk -w 100 -c 50 -C -w 1000 -c 500 -g sidDATA -r '^/oracle/SID/data.*$'"); + printf(" %s\n", _("Checks all filesystems not matching -r at 100M and 50M. The fs matching the -r regex")); + printf(" %s\n\n", _("are grouped which means the freespace thresholds are applied to all disks together")); + printf(" %s\n", "check_disk -w 100 -c 50 -C -w 1000 -c 500 -p /foo -C -w 5% -c 3% -p /bar"); + printf(" %s\n", _("Checks /foo for 1000M/500M and /bar for 5/3%. All remaining volumes use 100M/50M")); + + printf(UT_SUPPORT); } +void print_usage(void) { + printf("%s\n", _("Usage:")); + 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_regex] [-N type]\n"); +} -void -get_stats (struct parameter_list *p, struct fs_usage *fsp) { - struct parameter_list *p_list; - struct fs_usage tmpfsp; - int first = 1; +bool stat_path(struct parameter_list *p) { + /* Stat entry to check that dir exists and is accessible */ + if (verbose >= 3) + printf("calling stat on %s\n", p->name); + if (stat(p->name, &stat_buf[0])) { + if (verbose >= 3) + printf("stat failed on %s\n", p->name); + if (ignore_missing == true) { + return false; + } else { + printf("DISK %s - ", _("CRITICAL")); + die(STATE_CRITICAL, _("%s %s: %s\n"), p->name, _("is not accessible"), strerror(errno)); + } + } + return true; +} + +void get_stats(struct parameter_list *p, struct fs_usage *fsp) { + struct parameter_list *p_list; + struct fs_usage tmpfsp; + int first = 1; - if (p->group == NULL) { - get_path_stats(p,fsp); - } else { - /* find all group members */ - for (p_list = path_select_list; p_list; p_list=p_list->name_next) { + if (p->group == NULL) { + get_path_stats(p, fsp); + } else { + /* find all group members */ + for (p_list = path_select_list; p_list; p_list = p_list->name_next) { #ifdef __CYGWIN__ - if (strncmp(p_list->name, "/cygdrive/", 10) != 0) - continue; + if (strncmp(p_list->name, "/cygdrive/", 10) != 0) + continue; #endif - if (p_list->group && ! (strcmp(p_list->group, p->group))) { - 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) - printf("Group %s: adding %lu blocks sized %lu, (%s) used_units=%lu free_units=%lu total_units=%lu mult=%lu\n", - p_list->group, - tmpfsp.fsu_blocks, - tmpfsp.fsu_blocksize, - p_list->best_match->me_mountdir, - p_list->dused_units, - p_list->dfree_units, - p_list->dtotal_units, - mult); - - /* prevent counting the first FS of a group twice since its parameter_list entry - * is used to carry the information of all file systems of the entire group */ - if (! first) { - p->total += p_list->total; - p->available += p_list->available; - p->available_to_root += p_list->available_to_root; - p->used += p_list->used; - - p->dused_units += p_list->dused_units; - p->dfree_units += p_list->dfree_units; - p->dtotal_units += p_list->dtotal_units; - p->inodes_total += p_list->inodes_total; - p->inodes_free += p_list->inodes_free; - p->inodes_free_to_root += p_list->inodes_free_to_root; - p->inodes_used += p_list->inodes_used; - } - first = 0; - } - if (verbose >= 3) - printf("Group %s now has: used_units=%lu free_units=%lu total_units=%lu fsu_blocksize=%lu mult=%lu\n", - p->group, - p->dused_units, - p->dfree_units, - p->dtotal_units, - tmpfsp.fsu_blocksize, - mult); - } - /* modify devname and mountdir for output */ - p->best_match->me_mountdir = p->best_match->me_devname = p->group; - } - /* finally calculate percentages for either plain FS or summed up group */ - p->dused_pct = calculate_percent( p->used, p->used + p->available ); /* used + available can never be > uintmax */ - p->dfree_pct = 100.0 - p->dused_pct; - p->dused_inodes_percent = calculate_percent(p->inodes_total - p->inodes_free, p->inodes_total); - p->dfree_inodes_percent = 100 - p->dused_inodes_percent; - + if (p_list->group && !(strcmp(p_list->group, p->group))) { + 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) + printf("Group %s: adding %lu blocks sized %lu, (%s) used_units=%lu free_units=%lu total_units=%lu mult=%lu\n", + p_list->group, tmpfsp.fsu_blocks, tmpfsp.fsu_blocksize, p_list->best_match->me_mountdir, p_list->dused_units, + p_list->dfree_units, p_list->dtotal_units, mult); + + /* prevent counting the first FS of a group twice since its parameter_list entry + * is used to carry the information of all file systems of the entire group */ + if (!first) { + p->total += p_list->total; + p->available += p_list->available; + p->available_to_root += p_list->available_to_root; + p->used += p_list->used; + + p->dused_units += p_list->dused_units; + p->dfree_units += p_list->dfree_units; + p->dtotal_units += p_list->dtotal_units; + p->inodes_total += p_list->inodes_total; + p->inodes_free += p_list->inodes_free; + p->inodes_free_to_root += p_list->inodes_free_to_root; + p->inodes_used += p_list->inodes_used; + } + first = 0; + } + if (verbose >= 3) + printf("Group %s now has: used_units=%lu free_units=%lu total_units=%lu fsu_blocksize=%lu mult=%lu\n", p->group, + p->dused_units, p->dfree_units, p->dtotal_units, tmpfsp.fsu_blocksize, mult); + } + /* modify devname and mountdir for output */ + p->best_match->me_mountdir = p->best_match->me_devname = p->group; + } + /* finally calculate percentages for either plain FS or summed up group */ + p->dused_pct = calculate_percent(p->used, p->used + p->available); /* used + available can never be > uintmax */ + p->dfree_pct = 100.0 - p->dused_pct; + p->dused_inodes_percent = calculate_percent(p->inodes_total - p->inodes_free, p->inodes_total); + p->dfree_inodes_percent = 100 - p->dused_inodes_percent; } -void -get_path_stats (struct parameter_list *p, struct fs_usage *fsp) { - p->available = fsp->fsu_bavail; - p->available_to_root = fsp->fsu_bfree; - p->used = fsp->fsu_blocks - fsp->fsu_bfree; - if (freespace_ignore_reserved) { - /* option activated : we subtract the root-reserved space from the total */ - p->total = fsp->fsu_blocks - p->available_to_root + p->available; - } else { - /* default behaviour : take all the blocks into account */ - p->total = fsp->fsu_blocks; - } - - p->dused_units = p->used*fsp->fsu_blocksize/mult; - p->dfree_units = p->available*fsp->fsu_blocksize/mult; - p->dtotal_units = p->total*fsp->fsu_blocksize/mult; - /* Free file nodes. Not sure the workaround is required, but in case...*/ - 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) { - /* option activated : we subtract the root-reserved inodes from the total */ - /* not all OS report fsp->fsu_favail, only the ones with statvfs syscall */ - /* for others, fsp->fsu_ffree == fsp->fsu_favail */ - p->inodes_total = fsp->fsu_files - p->inodes_free_to_root + p->inodes_free; - } else { - /* default behaviour : take all the inodes into account */ - p->inodes_total = fsp->fsu_files; - } - np_add_name(&seen, p->best_match->me_mountdir); +void get_path_stats(struct parameter_list *p, struct fs_usage *fsp) { + p->available = fsp->fsu_bavail; + p->available_to_root = fsp->fsu_bfree; + p->used = fsp->fsu_blocks - fsp->fsu_bfree; + if (freespace_ignore_reserved) { + /* option activated : we subtract the root-reserved space from the total */ + p->total = fsp->fsu_blocks - p->available_to_root + p->available; + } else { + /* default behaviour : take all the blocks into account */ + p->total = fsp->fsu_blocks; + } + + p->dused_units = p->used * fsp->fsu_blocksize / mult; + p->dfree_units = p->available * fsp->fsu_blocksize / mult; + p->dtotal_units = p->total * fsp->fsu_blocksize / mult; + /* Free file nodes. Not sure the workaround is required, but in case...*/ + 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) { + /* option activated : we subtract the root-reserved inodes from the total */ + /* not all OS report fsp->fsu_favail, only the ones with statvfs syscall */ + /* for others, fsp->fsu_ffree == fsp->fsu_favail */ + p->inodes_total = fsp->fsu_files - p->inodes_free_to_root + p->inodes_free; + } else { + /* default behaviour : take all the inodes into account */ + p->inodes_total = fsp->fsu_files; + } + np_add_name(&seen, p->best_match->me_mountdir); } -- cgit v0.10-9-g596f From 78aa69150556f83d335ec417c290c617b6f6b5df Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:25:04 +0100 Subject: check_disk: Update copyright diff --git a/plugins/check_disk.c b/plugins/check_disk.c index fc4039f..873b17b 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -3,7 +3,7 @@ * Monitoring check_disk plugin * * License: GPL - * Copyright (c) 1999-2008 Monitoring Plugins Development Team + * Copyright (c) 1999-2024 Monitoring Plugins Development Team * * Description: * @@ -28,7 +28,7 @@ const char *progname = "check_disk"; const char *program_name = "check_disk"; /* Required for coreutils libs */ -const char *copyright = "1999-2008"; +const char *copyright = "1999-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From e57e86aedb91ea8c973b1e751cf233dc1aa0465b Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:26:07 +0100 Subject: check_dig: Update copyright diff --git a/plugins/check_dig.c b/plugins/check_dig.c index 4d89ca8..2bbd1e0 100644 --- a/plugins/check_dig.c +++ b/plugins/check_dig.c @@ -3,7 +3,7 @@ * Monitoring check_dig plugin * * License: GPL - * Copyright (c) 2002-2008 Monitoring Plugins Development Team + * Copyright (c) 2002-2024 Monitoring Plugins Development Team * * Description: * @@ -33,7 +33,7 @@ * because on some architectures those strings are in non-writable memory */ const char *progname = "check_dig"; -const char *copyright = "2002-2008"; +const char *copyright = "2002-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 08526fd07f99895f198db1e58ad92e52b9b809bb Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:28:27 +0100 Subject: check_disk: Linter fixes diff --git a/plugins/check_disk.c b/plugins/check_disk.c index 873b17b..d1d1b92 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -117,7 +117,7 @@ enum { # pragma alloca #endif -static int process_arguments(int, char **); +static int process_arguments(int /*argc*/, char ** /*argv*/); static void set_all_thresholds(struct parameter_list *path); static void print_help(void); void print_usage(void); @@ -168,7 +168,8 @@ int main(int argc, char **argv) { struct mount_entry *me; struct fs_usage fsp; - struct parameter_list *temp_list, *path; + struct parameter_list *temp_list; + struct parameter_list *path; #ifdef __CYGWIN__ char mountdir[32]; @@ -286,17 +287,20 @@ int main(int argc, char **argv) { } continue; /* Skip pseudo fs's if we haven't asked for all fs's */ - } else if (me->me_dummy && !show_all_fs) { + } + if (me->me_dummy && !show_all_fs) { continue; /* Skip excluded fstypes */ - } else if (fs_exclude_list && np_find_regmatch(fs_exclude_list, me->me_type)) { + } + if (fs_exclude_list && np_find_regmatch(fs_exclude_list, me->me_type)) { continue; /* Skip excluded fs's */ - } else if (dp_exclude_list && - (np_find_name(dp_exclude_list, me->me_devname) || np_find_name(dp_exclude_list, me->me_mountdir))) { + } + if (dp_exclude_list && (np_find_name(dp_exclude_list, me->me_devname) || np_find_name(dp_exclude_list, me->me_mountdir))) { continue; /* Skip not included fstypes */ - } else if (fs_include_list && !np_find_regmatch(fs_include_list, me->me_type)) { + } + if (fs_include_list && !np_find_regmatch(fs_include_list, me->me_type)) { continue; } } @@ -453,9 +457,11 @@ double calculate_percent(uintmax_t value, uintmax_t total) { /* process command-line arguments */ int process_arguments(int argc, char **argv) { - int c, err; + int c; + int err; struct parameter_list *se; - struct parameter_list *temp_list = NULL, *previous = NULL; + struct parameter_list *temp_list = NULL; + struct parameter_list *previous = NULL; struct mount_entry *me; regex_t re; int cflags = REG_NOSUB | REG_EXTENDED; @@ -803,7 +809,8 @@ int process_arguments(int argc, char **argv) { path_ignored = true; path_selected = true; break; - } else if (!fnd) + } + if (!fnd) die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"), _("Regular expression did not match any path or disk"), optarg); fnd = false; @@ -1011,10 +1018,9 @@ bool stat_path(struct parameter_list *p) { printf("stat failed on %s\n", p->name); if (ignore_missing == true) { return false; - } else { - printf("DISK %s - ", _("CRITICAL")); - die(STATE_CRITICAL, _("%s %s: %s\n"), p->name, _("is not accessible"), strerror(errno)); } + printf("DISK %s - ", _("CRITICAL")); + die(STATE_CRITICAL, _("%s %s: %s\n"), p->name, _("is not accessible"), strerror(errno)); } return true; } -- cgit v0.10-9-g596f From 499c0a07ae42ef48b3a1f25031fb933c3c59e327 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:29:32 +0100 Subject: check_dns: clang-format diff --git a/plugins/check_dns.c b/plugins/check_dns.c index 468bc95..7cd2316 100644 --- a/plugins/check_dns.c +++ b/plugins/check_dns.c @@ -1,33 +1,33 @@ /***************************************************************************** -* -* Monitoring check_dns plugin -* -* License: GPL -* Copyright (c) 2000-2008 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_dns plugin -* -* LIMITATION: nslookup on Solaris 7 can return output over 2 lines, which -* will not be picked up by this plugin -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_dns plugin + * + * License: GPL + * Copyright (c) 2000-2008 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_dns plugin + * + * LIMITATION: nslookup on Solaris 7 can return output over 2 lines, which + * will not be picked up by this plugin + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "check_dns"; const char *copyright = "2000-2008"; @@ -39,13 +39,13 @@ const char *email = "devel@monitoring-plugins.org"; #include "netutils.h" #include "runcmd.h" -int process_arguments (int, char **); -int validate_arguments (void); -int error_scan (char *, bool *); +int process_arguments(int, char **); +int validate_arguments(void); +int error_scan(char *, bool *); bool ip_match_cidr(const char *, const char *); unsigned long ip2long(const char *); -void print_help (void); -void print_usage (void); +void print_help(void); +void print_usage(void); #define ADDRESS_LENGTH 256 char query_address[ADDRESS_LENGTH] = ""; @@ -60,558 +60,509 @@ bool expect_authority = false; bool all_match = false; thresholds *time_thresholds = NULL; -static int -qstrcmp(const void *p1, const void *p2) -{ +static int qstrcmp(const void *p1, const void *p2) { /* The actual arguments to this function are "pointers to pointers to char", but strcmp() arguments are "pointers to char", hence the following cast plus dereference */ - return strcmp(* (char * const *) p1, * (char * const *) p2); + return strcmp(*(char *const *)p1, *(char *const *)p2); } +int main(int argc, char **argv) { + char *command_line = NULL; + char input_buffer[MAX_INPUT_BUFFER]; + char *address = NULL; /* comma separated str with addrs/ptrs (sorted) */ + char **addresses = NULL; + int n_addresses = 0; + char *msg = NULL; + char *temp_buffer = NULL; + bool non_authoritative = false; + int result = STATE_UNKNOWN; + double elapsed_time; + long microsec; + struct timeval tv; + bool parse_address = false; /* This flag scans for Address: but only after Name: */ + output chld_out, chld_err; + bool is_nxdomain = false; + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + + /* Set signal handling and alarm */ + if (signal(SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) { + usage_va(_("Cannot catch SIGALRM")); + } + + /* Parse extra opts if any */ + argv = np_extra_opts(&argc, argv, progname); + + if (process_arguments(argc, argv) == ERROR) { + usage_va(_("Could not parse arguments")); + } + + /* get the command to run */ + xasprintf(&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server); + + alarm(timeout_interval); + gettimeofday(&tv, NULL); + + if (verbose) + printf("%s\n", command_line); + + /* run the command */ + if ((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) { + msg = (char *)_("nslookup returned an error status"); + result = STATE_WARNING; + } + + /* scan stdout */ + for (size_t i = 0; i < chld_out.lines; i++) { + if (addresses == NULL) + addresses = malloc(sizeof(*addresses) * 10); + else if (!(n_addresses % 10)) + addresses = realloc(addresses, sizeof(*addresses) * (n_addresses + 10)); + + if (verbose) + puts(chld_out.line[i]); + + if (strcasestr(chld_out.line[i], ".in-addr.arpa") || strcasestr(chld_out.line[i], ".ip6.arpa")) { + if ((temp_buffer = strstr(chld_out.line[i], "name = "))) + addresses[n_addresses++] = strdup(temp_buffer + 7); + else { + msg = (char *)_("Warning plugin error"); + result = STATE_WARNING; + } + } + + /* bug ID: 2946553 - Older versions of bind will use all available dns + servers, we have to match the one specified */ + if (strstr(chld_out.line[i], "Server:") && strlen(dns_server) > 0) { + temp_buffer = strchr(chld_out.line[i], ':'); + temp_buffer++; + + /* Strip leading tabs */ + for (; *temp_buffer != '\0' && *temp_buffer == '\t'; temp_buffer++) + /* NOOP */; + + strip(temp_buffer); + if (temp_buffer == NULL || strlen(temp_buffer) == 0) { + die(STATE_CRITICAL, _("DNS CRITICAL - '%s' returned empty server string\n"), NSLOOKUP_COMMAND); + } + + if (strcmp(temp_buffer, dns_server) != 0) { + die(STATE_CRITICAL, _("DNS CRITICAL - No response from DNS %s\n"), dns_server); + } + } + + /* the server is responding, we just got the host name... */ + if (strstr(chld_out.line[i], "Name:")) + parse_address = true; + else if (parse_address && (strstr(chld_out.line[i], "Address:") || strstr(chld_out.line[i], "Addresses:"))) { + temp_buffer = index(chld_out.line[i], ':'); + temp_buffer++; + + /* Strip leading spaces */ + while (*temp_buffer == ' ') + temp_buffer++; + + strip(temp_buffer); + if (temp_buffer == NULL || strlen(temp_buffer) == 0) { + die(STATE_CRITICAL, _("DNS CRITICAL - '%s' returned empty host name string\n"), NSLOOKUP_COMMAND); + } + + addresses[n_addresses++] = strdup(temp_buffer); + } else if (strstr(chld_out.line[i], _("Non-authoritative answer:"))) { + non_authoritative = true; + } + + result = error_scan(chld_out.line[i], &is_nxdomain); + if (result != STATE_OK) { + msg = strchr(chld_out.line[i], ':'); + if (msg) + msg++; + break; + } + } + + /* scan stderr */ + for (size_t i = 0; i < chld_err.lines; i++) { + if (verbose) + puts(chld_err.line[i]); + + if (error_scan(chld_err.line[i], &is_nxdomain) != STATE_OK) { + result = max_state(result, error_scan(chld_err.line[i], &is_nxdomain)); + msg = strchr(input_buffer, ':'); + if (msg) + msg++; + else + msg = input_buffer; + } + } + + if (is_nxdomain && !expect_nxdomain) { + die(STATE_CRITICAL, _("Domain '%s' was not found by the server\n"), query_address); + } -int -main (int argc, char **argv) -{ - char *command_line = NULL; - char input_buffer[MAX_INPUT_BUFFER]; - char *address = NULL; /* comma separated str with addrs/ptrs (sorted) */ - char **addresses = NULL; - int n_addresses = 0; - char *msg = NULL; - char *temp_buffer = NULL; - bool non_authoritative = false; - int result = STATE_UNKNOWN; - double elapsed_time; - long microsec; - struct timeval tv; - bool parse_address = false; /* This flag scans for Address: but only after Name: */ - output chld_out, chld_err; - bool is_nxdomain = false; - - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); - - /* Set signal handling and alarm */ - if (signal (SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) { - usage_va(_("Cannot catch SIGALRM")); - } - - /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); - - if (process_arguments (argc, argv) == ERROR) { - usage_va(_("Could not parse arguments")); - } - - /* get the command to run */ - xasprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server); - - alarm (timeout_interval); - gettimeofday (&tv, NULL); - - if (verbose) - printf ("%s\n", command_line); - - /* run the command */ - if((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) { - msg = (char *)_("nslookup returned an error status"); - result = STATE_WARNING; - } - - /* scan stdout */ - for(size_t i = 0; i < chld_out.lines; i++) { - if (addresses == NULL) - addresses = malloc(sizeof(*addresses)*10); - else if (!(n_addresses % 10)) - addresses = realloc(addresses,sizeof(*addresses) * (n_addresses + 10)); - - if (verbose) - puts(chld_out.line[i]); - - if (strcasestr (chld_out.line[i], ".in-addr.arpa") || strcasestr (chld_out.line[i], ".ip6.arpa")) { - if ((temp_buffer = strstr (chld_out.line[i], "name = "))) - addresses[n_addresses++] = strdup (temp_buffer + 7); - else { - msg = (char *)_("Warning plugin error"); - result = STATE_WARNING; - } - } - - /* bug ID: 2946553 - Older versions of bind will use all available dns - servers, we have to match the one specified */ - if (strstr (chld_out.line[i], "Server:") && strlen(dns_server) > 0) { - temp_buffer = strchr (chld_out.line[i], ':'); - temp_buffer++; - - /* Strip leading tabs */ - for (; *temp_buffer != '\0' && *temp_buffer == '\t'; temp_buffer++) - /* NOOP */; - - strip(temp_buffer); - if (temp_buffer==NULL || strlen(temp_buffer)==0) { - die (STATE_CRITICAL, - _("DNS CRITICAL - '%s' returned empty server string\n"), - NSLOOKUP_COMMAND); - } - - if (strcmp(temp_buffer, dns_server) != 0) { - die (STATE_CRITICAL, _("DNS CRITICAL - No response from DNS %s\n"), dns_server); - } - } - - /* the server is responding, we just got the host name... */ - if (strstr (chld_out.line[i], "Name:")) - parse_address = true; - else if (parse_address && (strstr (chld_out.line[i], "Address:") || - strstr (chld_out.line[i], "Addresses:"))) { - temp_buffer = index (chld_out.line[i], ':'); - temp_buffer++; - - /* Strip leading spaces */ - while (*temp_buffer == ' ') - temp_buffer++; - - strip(temp_buffer); - if (temp_buffer==NULL || strlen(temp_buffer)==0) { - die (STATE_CRITICAL, - _("DNS CRITICAL - '%s' returned empty host name string\n"), - NSLOOKUP_COMMAND); - } - - addresses[n_addresses++] = strdup(temp_buffer); - } - else if (strstr (chld_out.line[i], _("Non-authoritative answer:"))) { - non_authoritative = true; - } - - - result = error_scan (chld_out.line[i], &is_nxdomain); - if (result != STATE_OK) { - msg = strchr (chld_out.line[i], ':'); - if(msg) msg++; - break; - } - } - - /* scan stderr */ - for(size_t i = 0; i < chld_err.lines; i++) { - if (verbose) - puts(chld_err.line[i]); - - if (error_scan (chld_err.line[i], &is_nxdomain) != STATE_OK) { - result = max_state (result, error_scan (chld_err.line[i], &is_nxdomain)); - msg = strchr(input_buffer, ':'); - if(msg) - msg++; - else - msg = input_buffer; - } - } - - if (is_nxdomain && !expect_nxdomain) { - die (STATE_CRITICAL, _("Domain '%s' was not found by the server\n"), query_address); - } - - if (addresses) { - int i,slen; - char *adrp; - qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp); - for(i=0, slen=1; i < n_addresses; i++) { - slen += strlen(addresses[i])+1; - } - adrp = address = malloc(slen); - for(i=0; i < n_addresses; i++) { - if (i) *adrp++ = ','; - strcpy(adrp, addresses[i]); - adrp += strlen(addresses[i]); - } - *adrp = 0; - } else - die (STATE_CRITICAL, - _("DNS CRITICAL - '%s' msg parsing exited with no address\n"), - NSLOOKUP_COMMAND); - - /* compare to expected address */ - if (result == STATE_OK && expected_address_cnt > 0) { - result = STATE_CRITICAL; - temp_buffer = ""; - unsigned long expect_match = (1 << expected_address_cnt) - 1; - unsigned long addr_match = (1 << n_addresses) - 1; - - for (int i=0; iwarning != NULL) && (time_thresholds->critical != NULL)) { - printf ("|%s\n", fperfdata ("time", elapsed_time, "s", - true, time_thresholds->warning->end, - true, time_thresholds->critical->end, - true, 0, false, 0)); - } else if ((time_thresholds->warning == NULL) && (time_thresholds->critical != NULL)) { - printf ("|%s\n", fperfdata ("time", elapsed_time, "s", - false, 0, - true, time_thresholds->critical->end, - true, 0, false, 0)); - } else if ((time_thresholds->warning != NULL) && (time_thresholds->critical == NULL)) { - printf ("|%s\n", fperfdata ("time", elapsed_time, "s", - true, time_thresholds->warning->end, - false, 0, - true, 0, false, 0)); - } else - printf ("|%s\n", fperfdata ("time", elapsed_time, "s", false, 0, false, 0, true, 0, false, 0)); - } - else if (result == STATE_WARNING) - printf (_("DNS WARNING - %s\n"), - !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg); - else if (result == STATE_CRITICAL) - printf (_("DNS CRITICAL - %s\n"), - !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg); - else - printf (_("DNS UNKNOWN - %s\n"), - !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg); - - return result; + if (addresses) { + int i, slen; + char *adrp; + qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp); + for (i = 0, slen = 1; i < n_addresses; i++) { + slen += strlen(addresses[i]) + 1; + } + adrp = address = malloc(slen); + for (i = 0; i < n_addresses; i++) { + if (i) + *adrp++ = ','; + strcpy(adrp, addresses[i]); + adrp += strlen(addresses[i]); + } + *adrp = 0; + } else + die(STATE_CRITICAL, _("DNS CRITICAL - '%s' msg parsing exited with no address\n"), NSLOOKUP_COMMAND); + + /* compare to expected address */ + if (result == STATE_OK && expected_address_cnt > 0) { + result = STATE_CRITICAL; + temp_buffer = ""; + unsigned long expect_match = (1 << expected_address_cnt) - 1; + unsigned long addr_match = (1 << n_addresses) - 1; + + for (int i = 0; i < expected_address_cnt; i++) { + int j; + /* check if we get a match on 'raw' ip or cidr */ + for (j = 0; j < n_addresses; j++) { + if (strcmp(addresses[j], expected_address[i]) == 0 || ip_match_cidr(addresses[j], expected_address[i])) { + result = STATE_OK; + addr_match &= ~(1 << j); + expect_match &= ~(1 << i); + } + } + + /* prepare an error string */ + xasprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]); + } + /* check if expected_address must cover all in addresses and none may be missing */ + if (all_match && (expect_match != 0 || addr_match != 0)) + result = STATE_CRITICAL; + if (result == STATE_CRITICAL) { + /* Strip off last semicolon... */ + temp_buffer[strlen(temp_buffer) - 2] = '\0'; + xasprintf(&msg, _("expected '%s' but got '%s'"), temp_buffer, address); + } + } + + if (expect_nxdomain) { + if (!is_nxdomain) { + result = STATE_CRITICAL; + xasprintf(&msg, _("Domain '%s' was found by the server: '%s'\n"), query_address, address); + } else { + if (address != NULL) + free(address); + address = "NXDOMAIN"; + } + } + + /* check if authoritative */ + if (result == STATE_OK && expect_authority && non_authoritative) { + result = STATE_CRITICAL; + xasprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address); + } + + microsec = deltime(tv); + elapsed_time = (double)microsec / 1.0e6; + + if (result == STATE_OK) { + result = get_status(elapsed_time, time_thresholds); + if (result == STATE_OK) { + printf("DNS %s: ", _("OK")); + } else if (result == STATE_WARNING) { + printf("DNS %s: ", _("WARNING")); + } else if (result == STATE_CRITICAL) { + printf("DNS %s: ", _("CRITICAL")); + } + printf(ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time), elapsed_time); + printf(_(". %s returns %s"), query_address, address); + if ((time_thresholds->warning != NULL) && (time_thresholds->critical != NULL)) { + printf("|%s\n", fperfdata("time", elapsed_time, "s", true, time_thresholds->warning->end, true, time_thresholds->critical->end, + true, 0, false, 0)); + } else if ((time_thresholds->warning == NULL) && (time_thresholds->critical != NULL)) { + printf("|%s\n", fperfdata("time", elapsed_time, "s", false, 0, true, time_thresholds->critical->end, true, 0, false, 0)); + } else if ((time_thresholds->warning != NULL) && (time_thresholds->critical == NULL)) { + printf("|%s\n", fperfdata("time", elapsed_time, "s", true, time_thresholds->warning->end, false, 0, true, 0, false, 0)); + } else + printf("|%s\n", fperfdata("time", elapsed_time, "s", false, 0, false, 0, true, 0, false, 0)); + } else if (result == STATE_WARNING) + printf(_("DNS WARNING - %s\n"), !strcmp(msg, "") ? _(" Probably a non-existent host/domain") : msg); + else if (result == STATE_CRITICAL) + printf(_("DNS CRITICAL - %s\n"), !strcmp(msg, "") ? _(" Probably a non-existent host/domain") : msg); + else + printf(_("DNS UNKNOWN - %s\n"), !strcmp(msg, "") ? _(" Probably a non-existent host/domain") : msg); + + return result; } bool ip_match_cidr(const char *addr, const char *cidr_ro) { - char *subnet, *mask_c, *cidr = strdup(cidr_ro); - int mask; - subnet = strtok(cidr, "/"); - mask_c = strtok(NULL, "\0"); - if (!subnet || !mask_c) { - return false; + char *subnet, *mask_c, *cidr = strdup(cidr_ro); + int mask; + subnet = strtok(cidr, "/"); + mask_c = strtok(NULL, "\0"); + if (!subnet || !mask_c) { + return false; } - mask = atoi(mask_c); + mask = atoi(mask_c); - /* https://www.cryptobells.com/verifying-ips-in-a-subnet-in-php/ */ - return (ip2long(addr) & ~((1 << (32 - mask)) - 1)) == (ip2long(subnet) >> (32 - mask)) << (32 - mask); + /* https://www.cryptobells.com/verifying-ips-in-a-subnet-in-php/ */ + return (ip2long(addr) & ~((1 << (32 - mask)) - 1)) == (ip2long(subnet) >> (32 - mask)) << (32 - mask); } -unsigned long -ip2long(const char* src) { - unsigned long ip[4]; - /* http://computer-programming-forum.com/47-c-language/1376ffb92a12c471.htm */ - return (sscanf(src, "%3lu.%3lu.%3lu.%3lu", - &ip[0], &ip[1], &ip[2], &ip[3]) == 4 && - ip[0] < 256 && ip[1] < 256 && - ip[2] < 256 && ip[3] < 256) - ? ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3] - : 0; +unsigned long ip2long(const char *src) { + unsigned long ip[4]; + /* http://computer-programming-forum.com/47-c-language/1376ffb92a12c471.htm */ + return (sscanf(src, "%3lu.%3lu.%3lu.%3lu", &ip[0], &ip[1], &ip[2], &ip[3]) == 4 && ip[0] < 256 && ip[1] < 256 && ip[2] < 256 && + ip[3] < 256) + ? ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3] + : 0; } -int -error_scan (char *input_buffer, bool *is_nxdomain) -{ - - const int nxdomain = strstr (input_buffer, "Non-existent") || - strstr (input_buffer, "** server can't find") || - strstr (input_buffer, "** Can't find") || - strstr (input_buffer, "NXDOMAIN"); - if (nxdomain) *is_nxdomain = true; - - /* the DNS lookup timed out */ - if (strstr (input_buffer, _("Note: nslookup is deprecated and may be removed from future releases.")) || - strstr (input_buffer, _("Consider using the `dig' or `host' programs instead. Run nslookup with")) || - strstr (input_buffer, _("the `-sil[ent]' option to prevent this message from appearing."))) - return STATE_OK; - - /* DNS server is not running... */ - else if (strstr (input_buffer, "No response from server")) - die (STATE_CRITICAL, _("No response from DNS %s\n"), dns_server); - else if (strstr (input_buffer, "no servers could be reached")) - die (STATE_CRITICAL, _("No response from DNS %s\n"), dns_server); - - /* Host name is valid, but server doesn't have records... */ - else if (strstr (input_buffer, "No records")) - die (STATE_CRITICAL, _("DNS %s has no records\n"), dns_server); - - /* Connection was refused */ - else if (strstr (input_buffer, "Connection refused") || - strstr (input_buffer, "Couldn't find server") || - strstr (input_buffer, "Refused") || - (strstr (input_buffer, "** server can't find") && - strstr (input_buffer, ": REFUSED"))) - die (STATE_CRITICAL, _("Connection to DNS %s was refused\n"), dns_server); - - /* Query refused (usually by an ACL in the namserver) */ - else if (strstr (input_buffer, "Query refused")) - die (STATE_CRITICAL, _("Query was refused by DNS server at %s\n"), dns_server); - - /* No information (e.g. nameserver IP has two PTR records) */ - else if (strstr (input_buffer, "No information")) - die (STATE_CRITICAL, _("No information returned by DNS server at %s\n"), dns_server); - - /* Network is unreachable */ - else if (strstr (input_buffer, "Network is unreachable")) - die (STATE_CRITICAL, _("Network is unreachable\n")); - - /* Internal server failure */ - else if (strstr (input_buffer, "Server failure")) - die (STATE_CRITICAL, _("DNS failure for %s\n"), dns_server); - - /* Request error or the DNS lookup timed out */ - else if (strstr (input_buffer, "Format error") || - strstr (input_buffer, "Timed out")) - return STATE_WARNING; - - return STATE_OK; +int error_scan(char *input_buffer, bool *is_nxdomain) { -} + const int nxdomain = strstr(input_buffer, "Non-existent") || strstr(input_buffer, "** server can't find") || + strstr(input_buffer, "** Can't find") || strstr(input_buffer, "NXDOMAIN"); + if (nxdomain) + *is_nxdomain = true; + + /* the DNS lookup timed out */ + if (strstr(input_buffer, _("Note: nslookup is deprecated and may be removed from future releases.")) || + strstr(input_buffer, _("Consider using the `dig' or `host' programs instead. Run nslookup with")) || + strstr(input_buffer, _("the `-sil[ent]' option to prevent this message from appearing."))) + return STATE_OK; + + /* DNS server is not running... */ + else if (strstr(input_buffer, "No response from server")) + die(STATE_CRITICAL, _("No response from DNS %s\n"), dns_server); + else if (strstr(input_buffer, "no servers could be reached")) + die(STATE_CRITICAL, _("No response from DNS %s\n"), dns_server); + + /* Host name is valid, but server doesn't have records... */ + else if (strstr(input_buffer, "No records")) + die(STATE_CRITICAL, _("DNS %s has no records\n"), dns_server); + + /* Connection was refused */ + else if (strstr(input_buffer, "Connection refused") || strstr(input_buffer, "Couldn't find server") || + strstr(input_buffer, "Refused") || (strstr(input_buffer, "** server can't find") && strstr(input_buffer, ": REFUSED"))) + die(STATE_CRITICAL, _("Connection to DNS %s was refused\n"), dns_server); + + /* Query refused (usually by an ACL in the namserver) */ + else if (strstr(input_buffer, "Query refused")) + die(STATE_CRITICAL, _("Query was refused by DNS server at %s\n"), dns_server); + + /* No information (e.g. nameserver IP has two PTR records) */ + else if (strstr(input_buffer, "No information")) + die(STATE_CRITICAL, _("No information returned by DNS server at %s\n"), dns_server); + + /* Network is unreachable */ + else if (strstr(input_buffer, "Network is unreachable")) + die(STATE_CRITICAL, _("Network is unreachable\n")); + + /* Internal server failure */ + else if (strstr(input_buffer, "Server failure")) + die(STATE_CRITICAL, _("DNS failure for %s\n"), dns_server); + /* Request error or the DNS lookup timed out */ + else if (strstr(input_buffer, "Format error") || strstr(input_buffer, "Timed out")) + return STATE_WARNING; + + return STATE_OK; +} /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ - int c; - char *warning = NULL; - char *critical = NULL; - - int opt_index = 0; - static struct option long_opts[] = { - {"help", no_argument, 0, 'h'}, - {"version", no_argument, 0, 'V'}, - {"verbose", no_argument, 0, 'v'}, - {"timeout", required_argument, 0, 't'}, - {"hostname", required_argument, 0, 'H'}, - {"server", required_argument, 0, 's'}, - {"reverse-server", required_argument, 0, 'r'}, - {"expected-address", required_argument, 0, 'a'}, - {"expect-nxdomain", no_argument, 0, 'n'}, - {"expect-authority", no_argument, 0, 'A'}, - {"all", no_argument, 0, 'L'}, - {"warning", required_argument, 0, 'w'}, - {"critical", required_argument, 0, 'c'}, - {0, 0, 0, 0} - }; - - if (argc < 2) - return ERROR; - - for (c = 1; c < argc; c++) - if (strcmp ("-to", argv[c]) == 0) - strcpy (argv[c], "-t"); - - while (1) { - c = getopt_long (argc, argv, "hVvALnt:H:s:r:a:w:c:", long_opts, &opt_index); - - if (c == -1 || c == EOF) - break; - - switch (c) { - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'v': /* version */ - verbose = true; - break; - case 't': /* timeout period */ - timeout_interval = atoi (optarg); - break; - case 'H': /* hostname */ - if (strlen (optarg) >= ADDRESS_LENGTH) - die (STATE_UNKNOWN, _("Input buffer overflow\n")); - strcpy (query_address, optarg); - break; - case 's': /* server name */ - /* TODO: this host_or_die check is probably unnecessary. - * Better to confirm nslookup response matches */ - host_or_die(optarg); - if (strlen (optarg) >= ADDRESS_LENGTH) - die (STATE_UNKNOWN, _("Input buffer overflow\n")); - strcpy (dns_server, optarg); - break; - case 'r': /* reverse server name */ - /* TODO: Is this host_or_die necessary? */ - host_or_die(optarg); - if (strlen (optarg) >= ADDRESS_LENGTH) - die (STATE_UNKNOWN, _("Input buffer overflow\n")); - strcpy (ptr_server, optarg); - break; - case 'a': /* expected address */ - if (strlen (optarg) >= ADDRESS_LENGTH) - die (STATE_UNKNOWN, _("Input buffer overflow\n")); - if (strchr(optarg, ',') != NULL) { - char *comma = strchr(optarg, ','); - while (comma != NULL) { - expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**)); - expected_address[expected_address_cnt] = strndup(optarg, comma - optarg); - expected_address_cnt++; - optarg = comma + 1; - comma = strchr(optarg, ','); +int process_arguments(int argc, char **argv) { + int c; + char *warning = NULL; + char *critical = NULL; + + int opt_index = 0; + static struct option long_opts[] = {{"help", no_argument, 0, 'h'}, + {"version", no_argument, 0, 'V'}, + {"verbose", no_argument, 0, 'v'}, + {"timeout", required_argument, 0, 't'}, + {"hostname", required_argument, 0, 'H'}, + {"server", required_argument, 0, 's'}, + {"reverse-server", required_argument, 0, 'r'}, + {"expected-address", required_argument, 0, 'a'}, + {"expect-nxdomain", no_argument, 0, 'n'}, + {"expect-authority", no_argument, 0, 'A'}, + {"all", no_argument, 0, 'L'}, + {"warning", required_argument, 0, 'w'}, + {"critical", required_argument, 0, 'c'}, + {0, 0, 0, 0}}; + + if (argc < 2) + return ERROR; + + for (c = 1; c < argc; c++) + if (strcmp("-to", argv[c]) == 0) + strcpy(argv[c], "-t"); + + while (1) { + c = getopt_long(argc, argv, "hVvALnt:H:s:r:a:w:c:", long_opts, &opt_index); + + if (c == -1 || c == EOF) + break; + + switch (c) { + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'v': /* version */ + verbose = true; + break; + case 't': /* timeout period */ + timeout_interval = atoi(optarg); + break; + case 'H': /* hostname */ + if (strlen(optarg) >= ADDRESS_LENGTH) + die(STATE_UNKNOWN, _("Input buffer overflow\n")); + strcpy(query_address, optarg); + break; + case 's': /* server name */ + /* TODO: this host_or_die check is probably unnecessary. + * Better to confirm nslookup response matches */ + host_or_die(optarg); + if (strlen(optarg) >= ADDRESS_LENGTH) + die(STATE_UNKNOWN, _("Input buffer overflow\n")); + strcpy(dns_server, optarg); + break; + case 'r': /* reverse server name */ + /* TODO: Is this host_or_die necessary? */ + host_or_die(optarg); + if (strlen(optarg) >= ADDRESS_LENGTH) + die(STATE_UNKNOWN, _("Input buffer overflow\n")); + strcpy(ptr_server, optarg); + break; + case 'a': /* expected address */ + if (strlen(optarg) >= ADDRESS_LENGTH) + die(STATE_UNKNOWN, _("Input buffer overflow\n")); + if (strchr(optarg, ',') != NULL) { + char *comma = strchr(optarg, ','); + while (comma != NULL) { + expected_address = (char **)realloc(expected_address, (expected_address_cnt + 1) * sizeof(char **)); + expected_address[expected_address_cnt] = strndup(optarg, comma - optarg); + expected_address_cnt++; + optarg = comma + 1; + comma = strchr(optarg, ','); + } + expected_address = (char **)realloc(expected_address, (expected_address_cnt + 1) * sizeof(char **)); + expected_address[expected_address_cnt] = strdup(optarg); + expected_address_cnt++; + } else { + expected_address = (char **)realloc(expected_address, (expected_address_cnt + 1) * sizeof(char **)); + expected_address[expected_address_cnt] = strdup(optarg); + expected_address_cnt++; + } + break; + case 'n': /* expect NXDOMAIN */ + expect_nxdomain = true; + break; + case 'A': /* expect authority */ + expect_authority = true; + break; + case 'L': /* all must match */ + all_match = true; + break; + case 'w': + warning = optarg; + break; + case 'c': + critical = optarg; + break; + default: /* args not parsable */ + usage5(); + } } - expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**)); - expected_address[expected_address_cnt] = strdup(optarg); - expected_address_cnt++; - } else { - expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**)); - expected_address[expected_address_cnt] = strdup(optarg); - expected_address_cnt++; - } - break; - case 'n': /* expect NXDOMAIN */ - expect_nxdomain = true; - break; - case 'A': /* expect authority */ - expect_authority = true; - break; - case 'L': /* all must match */ - all_match = true; - break; - case 'w': - warning = optarg; - break; - case 'c': - critical = optarg; - break; - default: /* args not parsable */ - usage5(); - } - } - - c = optind; - if (strlen(query_address)==0 && c=ADDRESS_LENGTH) - die (STATE_UNKNOWN, _("Input buffer overflow\n")); - strcpy (query_address, argv[c++]); - } - - if (strlen(dns_server)==0 && c= ADDRESS_LENGTH) - die (STATE_UNKNOWN, _("Input buffer overflow\n")); - strcpy (dns_server, argv[c++]); - } - - set_thresholds(&time_thresholds, warning, critical); - - return validate_arguments (); -} + c = optind; + if (strlen(query_address) == 0 && c < argc) { + if (strlen(argv[c]) >= ADDRESS_LENGTH) + die(STATE_UNKNOWN, _("Input buffer overflow\n")); + strcpy(query_address, argv[c++]); + } -int -validate_arguments () -{ - if (query_address[0] == 0) { - printf ("missing --host argument\n"); - return ERROR; - } + if (strlen(dns_server) == 0 && c < argc) { + /* TODO: See -s option */ + host_or_die(argv[c]); + if (strlen(argv[c]) >= ADDRESS_LENGTH) + die(STATE_UNKNOWN, _("Input buffer overflow\n")); + strcpy(dns_server, argv[c++]); + } - if (expected_address_cnt > 0 && expect_nxdomain) { - printf ("--expected-address and --expect-nxdomain cannot be combined\n"); - return ERROR; - } + set_thresholds(&time_thresholds, warning, critical); - return OK; + return validate_arguments(); } +int validate_arguments() { + if (query_address[0] == 0) { + printf("missing --host argument\n"); + return ERROR; + } + + if (expected_address_cnt > 0 && expect_nxdomain) { + printf("--expected-address and --expect-nxdomain cannot be combined\n"); + return ERROR; + } -void -print_help (void) -{ - print_revision (progname, NP_VERSION); - - printf ("Copyright (c) 1999 Ethan Galstad \n"); - printf (COPYRIGHT, copyright, email); - - printf ("%s\n", _("This plugin uses the nslookup program to obtain the IP address for the given host/domain query.")); - printf ("%s\n", _("An optional DNS server to use may be specified.")); - printf ("%s\n", _("If no DNS server is specified, the default server(s) specified in /etc/resolv.conf will be used.")); - - printf ("\n\n"); - - print_usage (); - - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); - - printf (" -H, --hostname=HOST\n"); - printf (" %s\n", _("The name or address you want to query")); - printf (" -s, --server=HOST\n"); - printf (" %s\n", _("Optional DNS server you want to use for the lookup")); - printf (" -a, --expected-address=IP-ADDRESS|CIDR|HOST\n"); - printf (" %s\n", _("Optional IP-ADDRESS/CIDR you expect the DNS server to return. HOST must end")); - printf (" %s\n", _("with a dot (.). This option can be repeated multiple times (Returns OK if any")); - printf (" %s\n", _("value matches).")); - printf (" -n, --expect-nxdomain\n"); - printf (" %s\n", _("Expect the DNS server to return NXDOMAIN (i.e. the domain was not found)")); - printf (" %s\n", _("Cannot be used together with -a")); - printf (" -A, --expect-authority\n"); - printf (" %s\n", _("Optionally expect the DNS server to be authoritative for the lookup")); - printf (" -w, --warning=seconds\n"); - printf (" %s\n", _("Return warning if elapsed time exceeds value. Default off")); - printf (" -c, --critical=seconds\n"); - printf (" %s\n", _("Return critical if elapsed time exceeds value. Default off")); - printf (" -L, --all\n"); - printf (" %s\n", _("Return critical if the list of expected addresses does not match all addresses")); - printf (" %s\n", _("returned. Default off")); - - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - - printf (UT_SUPPORT); + return OK; } +void print_help(void) { + print_revision(progname, NP_VERSION); + + printf("Copyright (c) 1999 Ethan Galstad \n"); + printf(COPYRIGHT, copyright, email); + + printf("%s\n", _("This plugin uses the nslookup program to obtain the IP address for the given host/domain query.")); + printf("%s\n", _("An optional DNS server to use may be specified.")); + printf("%s\n", _("If no DNS server is specified, the default server(s) specified in /etc/resolv.conf will be used.")); + + printf("\n\n"); + + print_usage(); + + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); + + printf(" -H, --hostname=HOST\n"); + printf(" %s\n", _("The name or address you want to query")); + printf(" -s, --server=HOST\n"); + printf(" %s\n", _("Optional DNS server you want to use for the lookup")); + printf(" -a, --expected-address=IP-ADDRESS|CIDR|HOST\n"); + printf(" %s\n", _("Optional IP-ADDRESS/CIDR you expect the DNS server to return. HOST must end")); + printf(" %s\n", _("with a dot (.). This option can be repeated multiple times (Returns OK if any")); + printf(" %s\n", _("value matches).")); + printf(" -n, --expect-nxdomain\n"); + printf(" %s\n", _("Expect the DNS server to return NXDOMAIN (i.e. the domain was not found)")); + printf(" %s\n", _("Cannot be used together with -a")); + printf(" -A, --expect-authority\n"); + printf(" %s\n", _("Optionally expect the DNS server to be authoritative for the lookup")); + printf(" -w, --warning=seconds\n"); + printf(" %s\n", _("Return warning if elapsed time exceeds value. Default off")); + printf(" -c, --critical=seconds\n"); + printf(" %s\n", _("Return critical if elapsed time exceeds value. Default off")); + printf(" -L, --all\n"); + printf(" %s\n", _("Return critical if the list of expected addresses does not match all addresses")); + printf(" %s\n", _("returned. Default off")); + + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + + printf(UT_SUPPORT); +} -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s -H host [-s server] [-a expected-address] [-n] [-A] [-t timeout] [-w warn] [-c crit] [-L]\n", progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s -H host [-s server] [-a expected-address] [-n] [-A] [-t timeout] [-w warn] [-c crit] [-L]\n", progname); } -- cgit v0.10-9-g596f From 702dc596a4a6ed124751c55cbd5c62f96ae8a157 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:30:42 +0100 Subject: check_dns: do not export local variables diff --git a/plugins/check_dns.c b/plugins/check_dns.c index 7cd2316..911853b 100644 --- a/plugins/check_dns.c +++ b/plugins/check_dns.c @@ -39,26 +39,26 @@ const char *email = "devel@monitoring-plugins.org"; #include "netutils.h" #include "runcmd.h" -int process_arguments(int, char **); -int validate_arguments(void); -int error_scan(char *, bool *); -bool ip_match_cidr(const char *, const char *); -unsigned long ip2long(const char *); -void print_help(void); +static int process_arguments(int, char **); +static int validate_arguments(void); +static int error_scan(char *, bool *); +static bool ip_match_cidr(const char *, const char *); +static unsigned long ip2long(const char *); +static void print_help(void); void print_usage(void); #define ADDRESS_LENGTH 256 -char query_address[ADDRESS_LENGTH] = ""; -char dns_server[ADDRESS_LENGTH] = ""; -char ptr_server[ADDRESS_LENGTH] = ""; -bool verbose = false; -char **expected_address = NULL; -int expected_address_cnt = 0; -bool expect_nxdomain = false; - -bool expect_authority = false; -bool all_match = false; -thresholds *time_thresholds = NULL; +static char query_address[ADDRESS_LENGTH] = ""; +static char dns_server[ADDRESS_LENGTH] = ""; +static char ptr_server[ADDRESS_LENGTH] = ""; +static bool verbose = false; +static char **expected_address = NULL; +static int expected_address_cnt = 0; +static bool expect_nxdomain = false; + +static bool expect_authority = false; +static bool all_match = false; +static thresholds *time_thresholds = NULL; static int qstrcmp(const void *p1, const void *p2) { /* The actual arguments to this function are "pointers to -- cgit v0.10-9-g596f From 4f34506c81484673bf3623d1c3a8100dc1761e8c Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:33:10 +0100 Subject: check_dns: Linter fixes diff --git a/plugins/check_dns.c b/plugins/check_dns.c index 911853b..e5ca581 100644 --- a/plugins/check_dns.c +++ b/plugins/check_dns.c @@ -39,11 +39,11 @@ const char *email = "devel@monitoring-plugins.org"; #include "netutils.h" #include "runcmd.h" -static int process_arguments(int, char **); +static int process_arguments(int /*argc*/, char ** /*argv*/); static int validate_arguments(void); -static int error_scan(char *, bool *); -static bool ip_match_cidr(const char *, const char *); -static unsigned long ip2long(const char *); +static int error_scan(char * /*input_buffer*/, bool *); +static bool ip_match_cidr(const char * /*addr*/, const char * /*cidr_ro*/); +static unsigned long ip2long(const char * /*src*/); static void print_help(void); void print_usage(void); @@ -81,7 +81,8 @@ int main(int argc, char **argv) { long microsec; struct timeval tv; bool parse_address = false; /* This flag scans for Address: but only after Name: */ - output chld_out, chld_err; + output chld_out; + output chld_err; bool is_nxdomain = false; setlocale(LC_ALL, ""); @@ -204,7 +205,8 @@ int main(int argc, char **argv) { } if (addresses) { - int i, slen; + int i; + int slen; char *adrp; qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp); for (i = 0, slen = 1; i < n_addresses; i++) { @@ -303,7 +305,9 @@ int main(int argc, char **argv) { } bool ip_match_cidr(const char *addr, const char *cidr_ro) { - char *subnet, *mask_c, *cidr = strdup(cidr_ro); + char *subnet; + char *mask_c; + char *cidr = strdup(cidr_ro); int mask; subnet = strtok(cidr, "/"); mask_c = strtok(NULL, "\0"); @@ -505,7 +509,7 @@ int process_arguments(int argc, char **argv) { return validate_arguments(); } -int validate_arguments() { +int validate_arguments(void) { if (query_address[0] == 0) { printf("missing --host argument\n"); return ERROR; -- cgit v0.10-9-g596f From 078e9b96adce9a9ae10535e496a743288eb8c9f2 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:33:51 +0100 Subject: check_dns: update copyright diff --git a/plugins/check_dns.c b/plugins/check_dns.c index e5ca581..e1e7c00 100644 --- a/plugins/check_dns.c +++ b/plugins/check_dns.c @@ -3,7 +3,7 @@ * Monitoring check_dns plugin * * License: GPL - * Copyright (c) 2000-2008 Monitoring Plugins Development Team + * Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -30,7 +30,7 @@ *****************************************************************************/ const char *progname = "check_dns"; -const char *copyright = "2000-2008"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 31133c789c609f510a8490032633b4be822060fc Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:34:46 +0100 Subject: check_dummy: clang-format diff --git a/plugins/check_dummy.c b/plugins/check_dummy.c index 212a134..1d9d2ab 100644 --- a/plugins/check_dummy.c +++ b/plugins/check_dummy.c @@ -1,32 +1,32 @@ /***************************************************************************** -* -* Monitoring check_dummy plugin -* -* License: GPL -* Copyright (c) 1999-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_dummy plugin -* -* This plugin will simply return the state corresponding to the numeric value -* -* -* 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_dummy plugin + * + * License: GPL + * Copyright (c) 1999-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_dummy plugin + * + * This plugin will simply return the state corresponding to the numeric value + * + * + * 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_dummy"; const char *copyright = "1999-2007"; @@ -35,90 +35,77 @@ const char *email = "devel@monitoring-plugins.org"; #include "common.h" #include "utils.h" -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); - - if (argc < 2) - usage4 (_("Could not parse arguments")); - else if (strcmp (argv[1], "-V") == 0 || strcmp (argv[1], "--version") == 0) { - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - } - else if (strcmp (argv[1], "-h") == 0 || strcmp (argv[1], "--help") == 0) { - print_help (); - exit (STATE_UNKNOWN); - } - else if (!is_integer (argv[1])) - usage4 (_("Arguments to check_dummy must be an integer")); - else - result = atoi (argv[1]); - - switch (result) { - case STATE_OK: - printf (_("OK")); - break; - case STATE_WARNING: - printf (_("WARNING")); - break; - case STATE_CRITICAL: - printf (_("CRITICAL")); - break; - case STATE_UNKNOWN: - printf (_("UNKNOWN")); - break; - default: - printf (_("UNKNOWN")); - printf (": "); - printf (_("Status %d is not a supported error state\n"), result); - return STATE_UNKNOWN; - } - - if (argc >= 3) - printf (": %s", argv[2]); - - printf("\n"); - - return result; +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); + + if (argc < 2) + usage4(_("Could not parse arguments")); + else if (strcmp(argv[1], "-V") == 0 || strcmp(argv[1], "--version") == 0) { + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + } else if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) { + print_help(); + exit(STATE_UNKNOWN); + } else if (!is_integer(argv[1])) + usage4(_("Arguments to check_dummy must be an integer")); + else + result = atoi(argv[1]); + + switch (result) { + case STATE_OK: + printf(_("OK")); + break; + case STATE_WARNING: + printf(_("WARNING")); + break; + case STATE_CRITICAL: + printf(_("CRITICAL")); + break; + case STATE_UNKNOWN: + printf(_("UNKNOWN")); + break; + default: + printf(_("UNKNOWN")); + printf(": "); + printf(_("Status %d is not a supported error state\n"), result); + return STATE_UNKNOWN; + } + + if (argc >= 3) + printf(": %s", argv[2]); + + printf("\n"); + + return result; } +void print_help(void) { + print_revision(progname, NP_VERSION); + printf("Copyright (c) 1999 Ethan Galstad \n"); + printf(COPYRIGHT, copyright, email); -void -print_help (void) -{ - print_revision (progname, NP_VERSION); + printf("%s\n", _("This plugin will simply return the state corresponding to the numeric value")); - printf ("Copyright (c) 1999 Ethan Galstad \n"); - printf (COPYRIGHT, copyright, email); + printf("%s\n", _("of the argument with optional text")); - printf ("%s\n", _("This plugin will simply return the state corresponding to the numeric value")); + printf("\n\n"); - printf ("%s\n", _("of the argument with optional text")); + print_usage(); - printf ("\n\n"); + printf(UT_HELP_VRSN); - print_usage (); - - printf (UT_HELP_VRSN); - - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf (" %s [optional text]\n", progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf(" %s [optional text]\n", progname); } -- cgit v0.10-9-g596f From 1633fd73bde6f2a2899b2f20d2e07683d5ea13ce Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:35:18 +0100 Subject: check_dummy: update copyright diff --git a/plugins/check_dummy.c b/plugins/check_dummy.c index 1d9d2ab..9262238 100644 --- a/plugins/check_dummy.c +++ b/plugins/check_dummy.c @@ -3,7 +3,7 @@ * Monitoring check_dummy plugin * * License: GPL - * Copyright (c) 1999-2007 Monitoring Plugins Development Team + * Copyright (c) 1999-2024 Monitoring Plugins Development Team * * Description: * @@ -29,7 +29,7 @@ *****************************************************************************/ const char *progname = "check_dummy"; -const char *copyright = "1999-2007"; +const char *copyright = "1999-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 5f2ae6d5e5240570de28a344fea2e822e1fa0bf4 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:36:00 +0100 Subject: check_dummy: do not export local symbols diff --git a/plugins/check_dummy.c b/plugins/check_dummy.c index 9262238..19f6c04 100644 --- a/plugins/check_dummy.c +++ b/plugins/check_dummy.c @@ -35,7 +35,7 @@ const char *email = "devel@monitoring-plugins.org"; #include "common.h" #include "utils.h" -void print_help(void); +static void print_help(void); void print_usage(void); int main(int argc, char **argv) { -- cgit v0.10-9-g596f From 82975ac988cad3f555fb381da98fc3b018a5769f Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:36:59 +0100 Subject: check_fping: clang-format diff --git a/plugins/check_fping.c b/plugins/check_fping.c index 70d6f9f..ec15114 100644 --- a/plugins/check_fping.c +++ b/plugins/check_fping.c @@ -1,33 +1,33 @@ /***************************************************************************** -* -* Monitoring check_fping plugin -* -* License: GPL -* Copyright (c) 2000-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_disk plugin -* -* This plugin will use the fping command to ping the specified host for a -* fast check -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_fping plugin + * + * License: GPL + * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_disk plugin + * + * This plugin will use the fping command to ping the specified host for a + * fast check + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "check_fping"; const char *copyright = "2000-2007"; @@ -40,17 +40,17 @@ const char *email = "devel@monitoring-plugins.org"; #include enum { - PACKET_COUNT = 1, - PACKET_SIZE = 56, - PL = 0, - RTA = 1 + PACKET_COUNT = 1, + PACKET_SIZE = 56, + PL = 0, + RTA = 1 }; -int textscan (char *buf); -int process_arguments (int, char **); -int get_threshold (char *arg, char *rv[2]); -void print_help (void); -void print_usage (void); +int textscan(char *buf); +int process_arguments(int, char **); +int get_threshold(char *arg, char *rv[2]); +void print_help(void); +void print_usage(void); char *server_name = NULL; char *sourceip = NULL; @@ -70,458 +70,419 @@ bool alive_p = false; bool crta_p = false; bool wrta_p = false; -int -main (int argc, char **argv) -{ -/* normally should be int result = STATE_UNKNOWN; */ - - int status = STATE_UNKNOWN; - int result = 0; - char *fping_prog = NULL; - char *server = NULL; - char *command_line = NULL; - char *input_buffer = NULL; - char *option_string = ""; - input_buffer = malloc (MAX_INPUT_BUFFER); - - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); - - /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); - - if (process_arguments (argc, argv) == ERROR) - usage4 (_("Could not parse arguments")); - - server = strscpy (server, server_name); - - /* compose the command */ - if (target_timeout) - xasprintf(&option_string, "%s-t %d ", option_string, target_timeout); - if (packet_interval) - xasprintf(&option_string, "%s-p %d ", option_string, packet_interval); - if (sourceip) - xasprintf(&option_string, "%s-S %s ", option_string, sourceip); - if (sourceif) - xasprintf(&option_string, "%s-I %s ", option_string, sourceif); +int main(int argc, char **argv) { + /* normally should be int result = STATE_UNKNOWN; */ + + int status = STATE_UNKNOWN; + int result = 0; + char *fping_prog = NULL; + char *server = NULL; + char *command_line = NULL; + char *input_buffer = NULL; + char *option_string = ""; + input_buffer = malloc(MAX_INPUT_BUFFER); + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + + /* Parse extra opts if any */ + argv = np_extra_opts(&argc, argv, progname); + + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments")); + + server = strscpy(server, server_name); + + /* compose the command */ + if (target_timeout) + xasprintf(&option_string, "%s-t %d ", option_string, target_timeout); + if (packet_interval) + xasprintf(&option_string, "%s-p %d ", option_string, packet_interval); + if (sourceip) + xasprintf(&option_string, "%s-S %s ", option_string, sourceip); + if (sourceif) + xasprintf(&option_string, "%s-I %s ", option_string, sourceif); #ifdef PATH_TO_FPING6 - if (address_family != AF_INET && is_inet6_addr(server)) - fping_prog = strdup(PATH_TO_FPING6); - else - fping_prog = strdup(PATH_TO_FPING); + if (address_family != AF_INET && is_inet6_addr(server)) + fping_prog = strdup(PATH_TO_FPING6); + else + fping_prog = strdup(PATH_TO_FPING); #else - fping_prog = strdup(PATH_TO_FPING); + fping_prog = strdup(PATH_TO_FPING); #endif - xasprintf (&command_line, "%s %s-b %d -c %d %s", fping_prog, - option_string, packet_size, packet_count, server); - - if (verbose) - printf ("%s\n", command_line); - - /* run the command */ - child_process = spopen (command_line); - if (child_process == NULL) { - printf (_("Could not open pipe: %s\n"), command_line); - return STATE_UNKNOWN; - } - - child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r"); - if (child_stderr == NULL) { - printf (_("Could not open stderr for %s\n"), command_line); - } - - while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) { - if (verbose) - printf ("%s", input_buffer); - status = max_state (status, textscan (input_buffer)); - } - - /* If we get anything on STDERR, at least set warning */ - while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) { - status = max_state (status, STATE_WARNING); - if (verbose) - printf ("%s", input_buffer); - status = max_state (status, textscan (input_buffer)); - } - (void) fclose (child_stderr); - - /* close the pipe */ - result = spclose (child_process); - if (result) { - /* need to use max_state not max */ - status = max_state (status, STATE_WARNING); - } - - if (result > 1 ) { - status = max_state (status, STATE_UNKNOWN); - if (result == 2) { - die (STATE_UNKNOWN, _("FPING UNKNOWN - IP address not found\n")); - } - if (result == 3) { - die (STATE_UNKNOWN, _("FPING UNKNOWN - invalid commandline argument\n")); - } - if (result == 4) { - die (STATE_UNKNOWN, _("FPING UNKNOWN - failed system call\n")); - } - - } - - printf ("FPING %s - %s\n", state_text (status), server_name); - - return status; + xasprintf(&command_line, "%s %s-b %d -c %d %s", fping_prog, option_string, packet_size, packet_count, server); + + if (verbose) + printf("%s\n", command_line); + + /* run the command */ + child_process = spopen(command_line); + if (child_process == NULL) { + printf(_("Could not open pipe: %s\n"), command_line); + return STATE_UNKNOWN; + } + + child_stderr = fdopen(child_stderr_array[fileno(child_process)], "r"); + if (child_stderr == NULL) { + printf(_("Could not open stderr for %s\n"), command_line); + } + + while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process)) { + if (verbose) + printf("%s", input_buffer); + status = max_state(status, textscan(input_buffer)); + } + + /* If we get anything on STDERR, at least set warning */ + while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) { + status = max_state(status, STATE_WARNING); + if (verbose) + printf("%s", input_buffer); + status = max_state(status, textscan(input_buffer)); + } + (void)fclose(child_stderr); + + /* close the pipe */ + result = spclose(child_process); + if (result) { + /* need to use max_state not max */ + status = max_state(status, STATE_WARNING); + } + + if (result > 1) { + status = max_state(status, STATE_UNKNOWN); + if (result == 2) { + die(STATE_UNKNOWN, _("FPING UNKNOWN - IP address not found\n")); + } + if (result == 3) { + die(STATE_UNKNOWN, _("FPING UNKNOWN - invalid commandline argument\n")); + } + if (result == 4) { + die(STATE_UNKNOWN, _("FPING UNKNOWN - failed system call\n")); + } + } + + printf("FPING %s - %s\n", state_text(status), server_name); + + return status; } - -int textscan (char *buf) { - char *rtastr = NULL; - char *losstr = NULL; - char *xmtstr = NULL; - double loss; - double rta; - double xmt; - int status = STATE_UNKNOWN; - - /* stops testing after the first successful reply. */ - if (alive_p && strstr(buf, "avg, 0% loss)")) { - rtastr = strstr (buf, "ms ("); - rtastr = 1 + index(rtastr, '('); - rta = strtod(rtastr, NULL); - loss=strtod("0",NULL); - die (STATE_OK, - _("FPING %s - %s (rta=%f ms)|%s\n"), - state_text (STATE_OK), server_name,rta, - /* No loss since we only waited for the first reply - perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, true, 0, true, 100), */ - fperfdata ("rta", rta/1.0e3, "s", wrta_p, wrta/1.0e3, crta_p, crta/1.0e3, true, 0, false, 0)); - } - - if (strstr (buf, "not found")) { - die (STATE_CRITICAL, _("FPING UNKNOWN - %s not found\n"), server_name); - - } - else if (strstr (buf, "is unreachable") || strstr (buf, "Unreachable")) { - die (STATE_CRITICAL, _("FPING CRITICAL - %s is unreachable\n"), - "host"); - - } - else if (strstr (buf, "Operation not permitted") || strstr (buf, "No such device") ) { - die (STATE_UNKNOWN, _("FPING UNKNOWN - %s parameter error\n"), - "host"); - } - else if (strstr (buf, "is down")) { - die (STATE_CRITICAL, _("FPING CRITICAL - %s is down\n"), server_name); - - } - else if (strstr (buf, "is alive")) { - status = STATE_OK; - - } - else if (strstr (buf, "xmt/rcv/%loss") && strstr (buf, "min/avg/max")) { - losstr = strstr (buf, "="); - losstr = 1 + strstr (losstr, "/"); - losstr = 1 + strstr (losstr, "/"); - rtastr = strstr (buf, "min/avg/max"); - rtastr = strstr (rtastr, "="); - rtastr = 1 + index (rtastr, '/'); - loss = strtod (losstr, NULL); - rta = strtod (rtastr, NULL); - if (cpl_p && loss > cpl) - status = STATE_CRITICAL; - else if (crta_p && rta > crta) - status = STATE_CRITICAL; - else if (wpl_p && loss > wpl) - status = STATE_WARNING; - else if (wrta_p && rta > wrta) - status = STATE_WARNING; - else - status = STATE_OK; - die (status, - _("FPING %s - %s (loss=%.0f%%, rta=%f ms)|%s %s\n"), - state_text (status), server_name, loss, rta, - perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, true, 0, true, 100), - fperfdata ("rta", rta/1.0e3, "s", wrta_p, wrta/1.0e3, crta_p, crta/1.0e3, true, 0, false, 0)); - - } - else if(strstr (buf, "xmt/rcv/%loss") ) { - /* no min/max/avg if host was unreachable in fping v2.2.b1 */ - /* in v2.4b2: 10.99.0.1 : xmt/rcv/%loss = 0/0/0% */ - losstr = strstr (buf, "="); - xmtstr = 1 + losstr; - xmt = strtod (xmtstr, NULL); - if(xmt == 0) - die (STATE_CRITICAL, _("FPING CRITICAL - %s is down\n"), server_name); - losstr = 1 + strstr (losstr, "/"); - losstr = 1 + strstr (losstr, "/"); - loss = strtod (losstr, NULL); - if (atoi(losstr) == 100) - status = STATE_CRITICAL; - else if (cpl_p && loss > cpl) - status = STATE_CRITICAL; - else if (wpl_p && loss > wpl) - status = STATE_WARNING; - else - status = STATE_OK; - /* loss=%.0f%%;%d;%d;0;100 */ - die (status, _("FPING %s - %s (loss=%.0f%% )|%s\n"), - state_text (status), server_name, loss , - perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, true, 0, true, 100)); - - } - else { - status = max_state (status, STATE_WARNING); - } - - return status; +int textscan(char *buf) { + char *rtastr = NULL; + char *losstr = NULL; + char *xmtstr = NULL; + double loss; + double rta; + double xmt; + int status = STATE_UNKNOWN; + + /* stops testing after the first successful reply. */ + if (alive_p && strstr(buf, "avg, 0% loss)")) { + rtastr = strstr(buf, "ms ("); + rtastr = 1 + index(rtastr, '('); + rta = strtod(rtastr, NULL); + loss = strtod("0", NULL); + die(STATE_OK, _("FPING %s - %s (rta=%f ms)|%s\n"), state_text(STATE_OK), server_name, rta, + /* No loss since we only waited for the first reply + perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, true, 0, true, 100), */ + fperfdata("rta", rta / 1.0e3, "s", wrta_p, wrta / 1.0e3, crta_p, crta / 1.0e3, true, 0, false, 0)); + } + + if (strstr(buf, "not found")) { + die(STATE_CRITICAL, _("FPING UNKNOWN - %s not found\n"), server_name); + + } else if (strstr(buf, "is unreachable") || strstr(buf, "Unreachable")) { + die(STATE_CRITICAL, _("FPING CRITICAL - %s is unreachable\n"), "host"); + + } else if (strstr(buf, "Operation not permitted") || strstr(buf, "No such device")) { + die(STATE_UNKNOWN, _("FPING UNKNOWN - %s parameter error\n"), "host"); + } else if (strstr(buf, "is down")) { + die(STATE_CRITICAL, _("FPING CRITICAL - %s is down\n"), server_name); + + } else if (strstr(buf, "is alive")) { + status = STATE_OK; + + } else if (strstr(buf, "xmt/rcv/%loss") && strstr(buf, "min/avg/max")) { + losstr = strstr(buf, "="); + losstr = 1 + strstr(losstr, "/"); + losstr = 1 + strstr(losstr, "/"); + rtastr = strstr(buf, "min/avg/max"); + rtastr = strstr(rtastr, "="); + rtastr = 1 + index(rtastr, '/'); + loss = strtod(losstr, NULL); + rta = strtod(rtastr, NULL); + if (cpl_p && loss > cpl) + status = STATE_CRITICAL; + else if (crta_p && rta > crta) + status = STATE_CRITICAL; + else if (wpl_p && loss > wpl) + status = STATE_WARNING; + else if (wrta_p && rta > wrta) + status = STATE_WARNING; + else + status = STATE_OK; + die(status, _("FPING %s - %s (loss=%.0f%%, rta=%f ms)|%s %s\n"), state_text(status), server_name, loss, rta, + perfdata("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, true, 0, true, 100), + fperfdata("rta", rta / 1.0e3, "s", wrta_p, wrta / 1.0e3, crta_p, crta / 1.0e3, true, 0, false, 0)); + + } else if (strstr(buf, "xmt/rcv/%loss")) { + /* no min/max/avg if host was unreachable in fping v2.2.b1 */ + /* in v2.4b2: 10.99.0.1 : xmt/rcv/%loss = 0/0/0% */ + losstr = strstr(buf, "="); + xmtstr = 1 + losstr; + xmt = strtod(xmtstr, NULL); + if (xmt == 0) + die(STATE_CRITICAL, _("FPING CRITICAL - %s is down\n"), server_name); + losstr = 1 + strstr(losstr, "/"); + losstr = 1 + strstr(losstr, "/"); + loss = strtod(losstr, NULL); + if (atoi(losstr) == 100) + status = STATE_CRITICAL; + else if (cpl_p && loss > cpl) + status = STATE_CRITICAL; + else if (wpl_p && loss > wpl) + status = STATE_WARNING; + else + status = STATE_OK; + /* loss=%.0f%%;%d;%d;0;100 */ + die(status, _("FPING %s - %s (loss=%.0f%% )|%s\n"), state_text(status), server_name, loss, + perfdata("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, true, 0, true, 100)); + + } else { + status = max_state(status, STATE_WARNING); + } + + return status; } - - /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ - int c; - char *rv[2]; - - int option = 0; - static struct option longopts[] = { - {"hostname", required_argument, 0, 'H'}, - {"sourceip", required_argument, 0, 'S'}, - {"sourceif", required_argument, 0, 'I'}, - {"critical", required_argument, 0, 'c'}, - {"warning", required_argument, 0, 'w'}, - {"alive", no_argument, 0, 'a'}, - {"bytes", required_argument, 0, 'b'}, - {"number", required_argument, 0, 'n'}, - {"target-timeout", required_argument, 0, 'T'}, - {"interval", required_argument, 0, 'i'}, - {"verbose", no_argument, 0, 'v'}, - {"version", no_argument, 0, 'V'}, - {"help", no_argument, 0, 'h'}, - {"use-ipv4", no_argument, 0, '4'}, - {"use-ipv6", no_argument, 0, '6'}, - {0, 0, 0, 0} - }; - - rv[PL] = NULL; - rv[RTA] = NULL; - - if (argc < 2) - return ERROR; - - if (!is_option (argv[1])) { - server_name = argv[1]; - argv[1] = argv[0]; - argv = &argv[1]; - argc--; - } - - while (1) { - c = getopt_long (argc, argv, "+hVvaH:S:c:w:b:n:T:i:I:46", longopts, &option); - - if (c == -1 || c == EOF || c == 1) - break; - - switch (c) { - case '?': /* print short usage statement if args not parsable */ - usage5 (); - case 'a': /* host alive mode */ - alive_p = true; - break; - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'v': /* verbose mode */ - verbose = true; - break; - case 'H': /* hostname */ - if (is_host (optarg) == false) { - usage2 (_("Invalid hostname/address"), optarg); - } - server_name = strscpy (server_name, optarg); - break; - case 'S': /* sourceip */ - if (is_host (optarg) == false) { - usage2 (_("Invalid hostname/address"), optarg); - } - sourceip = strscpy (sourceip, optarg); - break; - case 'I': /* sourceip */ - sourceif = strscpy (sourceif, optarg); +int process_arguments(int argc, char **argv) { + int c; + char *rv[2]; + + int option = 0; + static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, + {"sourceip", required_argument, 0, 'S'}, + {"sourceif", required_argument, 0, 'I'}, + {"critical", required_argument, 0, 'c'}, + {"warning", required_argument, 0, 'w'}, + {"alive", no_argument, 0, 'a'}, + {"bytes", required_argument, 0, 'b'}, + {"number", required_argument, 0, 'n'}, + {"target-timeout", required_argument, 0, 'T'}, + {"interval", required_argument, 0, 'i'}, + {"verbose", no_argument, 0, 'v'}, + {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {"use-ipv4", no_argument, 0, '4'}, + {"use-ipv6", no_argument, 0, '6'}, + {0, 0, 0, 0}}; + + rv[PL] = NULL; + rv[RTA] = NULL; + + if (argc < 2) + return ERROR; + + if (!is_option(argv[1])) { + server_name = argv[1]; + argv[1] = argv[0]; + argv = &argv[1]; + argc--; + } + + while (1) { + c = getopt_long(argc, argv, "+hVvaH:S:c:w:b:n:T:i:I:46", longopts, &option); + + if (c == -1 || c == EOF || c == 1) + break; + + switch (c) { + case '?': /* print short usage statement if args not parsable */ + usage5(); + case 'a': /* host alive mode */ + alive_p = true; + break; + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'v': /* verbose mode */ + verbose = true; + break; + case 'H': /* hostname */ + if (is_host(optarg) == false) { + usage2(_("Invalid hostname/address"), optarg); + } + server_name = strscpy(server_name, optarg); break; - case '4': /* IPv4 only */ - address_family = AF_INET; - break; - case '6': /* IPv6 only */ + case 'S': /* sourceip */ + if (is_host(optarg) == false) { + usage2(_("Invalid hostname/address"), optarg); + } + sourceip = strscpy(sourceip, optarg); + break; + case 'I': /* sourceip */ + sourceif = strscpy(sourceif, optarg); + break; + case '4': /* IPv4 only */ + address_family = AF_INET; + break; + case '6': /* IPv6 only */ #ifdef USE_IPV6 - address_family = AF_INET6; + address_family = AF_INET6; #else - usage (_("IPv6 support not available\n")); + usage(_("IPv6 support not available\n")); #endif - break; - case 'c': - get_threshold (optarg, rv); - if (rv[RTA]) { - crta = strtod (rv[RTA], NULL); - crta_p = true; - rv[RTA] = NULL; - } - if (rv[PL]) { - cpl = atoi (rv[PL]); - cpl_p = true; - rv[PL] = NULL; - } - break; - case 'w': - get_threshold (optarg, rv); - if (rv[RTA]) { - wrta = strtod (rv[RTA], NULL); - wrta_p = true; - rv[RTA] = NULL; - } - if (rv[PL]) { - wpl = atoi (rv[PL]); - wpl_p = true; - rv[PL] = NULL; - } - break; - case 'b': /* bytes per packet */ - if (is_intpos (optarg)) - packet_size = atoi (optarg); - else - usage (_("Packet size must be a positive integer")); - break; - case 'n': /* number of packets */ - if (is_intpos (optarg)) - packet_count = atoi (optarg); - else - usage (_("Packet count must be a positive integer")); - break; - case 'T': /* timeout in msec */ - if (is_intpos (optarg)) - target_timeout = atoi (optarg); - else - usage (_("Target timeout must be a positive integer")); - break; - case 'i': /* interval in msec */ - if (is_intpos (optarg)) - packet_interval = atoi (optarg); - else - usage (_("Interval must be a positive integer")); - break; - } - } - - if (server_name == NULL) - usage4 (_("Hostname was not supplied")); - - return OK; -} + break; + case 'c': + get_threshold(optarg, rv); + if (rv[RTA]) { + crta = strtod(rv[RTA], NULL); + crta_p = true; + rv[RTA] = NULL; + } + if (rv[PL]) { + cpl = atoi(rv[PL]); + cpl_p = true; + rv[PL] = NULL; + } + break; + case 'w': + get_threshold(optarg, rv); + if (rv[RTA]) { + wrta = strtod(rv[RTA], NULL); + wrta_p = true; + rv[RTA] = NULL; + } + if (rv[PL]) { + wpl = atoi(rv[PL]); + wpl_p = true; + rv[PL] = NULL; + } + break; + case 'b': /* bytes per packet */ + if (is_intpos(optarg)) + packet_size = atoi(optarg); + else + usage(_("Packet size must be a positive integer")); + break; + case 'n': /* number of packets */ + if (is_intpos(optarg)) + packet_count = atoi(optarg); + else + usage(_("Packet count must be a positive integer")); + break; + case 'T': /* timeout in msec */ + if (is_intpos(optarg)) + target_timeout = atoi(optarg); + else + usage(_("Target timeout must be a positive integer")); + break; + case 'i': /* interval in msec */ + if (is_intpos(optarg)) + packet_interval = atoi(optarg); + else + usage(_("Interval must be a positive integer")); + break; + } + } + if (server_name == NULL) + usage4(_("Hostname was not supplied")); -int -get_threshold (char *arg, char *rv[2]) -{ - char *arg1 = NULL; - char *arg2 = NULL; - - arg1 = strscpy (arg1, arg); - if (strpbrk (arg1, ",:")) - arg2 = 1 + strpbrk (arg1, ",:"); - - if (arg2) { - arg1[strcspn (arg1, ",:")] = 0; - if (strstr (arg1, "%") && strstr (arg2, "%")) - die (STATE_UNKNOWN, - _("%s: Only one threshold may be packet loss (%s)\n"), progname, - arg); - if (!strstr (arg1, "%") && !strstr (arg2, "%")) - die (STATE_UNKNOWN, - _("%s: Only one threshold must be packet loss (%s)\n"), - progname, arg); - } - - if (arg2 && strstr (arg2, "%")) { - rv[PL] = arg2; - rv[RTA] = arg1; - } - else if (arg2) { - rv[PL] = arg1; - rv[RTA] = arg2; - } - else if (strstr (arg1, "%")) { - rv[PL] = arg1; - } - else { - rv[RTA] = arg1; - } - - return OK; + return OK; } +int get_threshold(char *arg, char *rv[2]) { + char *arg1 = NULL; + char *arg2 = NULL; + + arg1 = strscpy(arg1, arg); + if (strpbrk(arg1, ",:")) + arg2 = 1 + strpbrk(arg1, ",:"); + + if (arg2) { + arg1[strcspn(arg1, ",:")] = 0; + if (strstr(arg1, "%") && strstr(arg2, "%")) + die(STATE_UNKNOWN, _("%s: Only one threshold may be packet loss (%s)\n"), progname, arg); + if (!strstr(arg1, "%") && !strstr(arg2, "%")) + die(STATE_UNKNOWN, _("%s: Only one threshold must be packet loss (%s)\n"), progname, arg); + } + + if (arg2 && strstr(arg2, "%")) { + rv[PL] = arg2; + rv[RTA] = arg1; + } else if (arg2) { + rv[PL] = arg1; + rv[RTA] = arg2; + } else if (strstr(arg1, "%")) { + rv[PL] = arg1; + } else { + rv[RTA] = arg1; + } + + return OK; +} -void print_help (void) { +void print_help(void) { - print_revision (progname, NP_VERSION); + print_revision(progname, NP_VERSION); - printf ("Copyright (c) 1999 Didi Rieder \n"); - printf (COPYRIGHT, copyright, email); + printf("Copyright (c) 1999 Didi Rieder \n"); + printf(COPYRIGHT, copyright, email); - printf ("%s\n", _("This plugin will use the fping command to ping the specified host for a fast check")); + printf("%s\n", _("This plugin will use the fping command to ping the specified host for a fast check")); - printf ("%s\n", _("Note that it is necessary to set the suid flag on fping.")); + printf("%s\n", _("Note that it is necessary to set the suid flag on fping.")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); - printf (UT_IPv46); + printf(UT_IPv46); - printf (" %s\n", "-H, --hostname=HOST"); - printf (" %s\n", _("name or IP Address of host to ping (IP Address bypasses name lookup, reducing system load)")); - printf (" %s\n", "-w, --warning=THRESHOLD"); - printf (" %s\n", _("warning threshold pair")); - printf (" %s\n", "-c, --critical=THRESHOLD"); - printf (" %s\n", _("critical threshold pair")); - printf (" %s\n", "-a, --alive"); - 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"); - printf (" %s (default: %d)\n", _("number of ICMP packets to send"),PACKET_COUNT); - printf (" %s\n", "-T, --target-timeout=INTEGER"); - printf (" %s (default: fping's default for -t)\n", _("Target timeout (ms)")); - printf (" %s\n", "-i, --interval=INTEGER"); - printf (" %s (default: fping's default for -p)\n", _("Interval (ms) between sending packets")); - printf (" %s\n", "-S, --sourceip=HOST"); - printf (" %s\n", _("name or IP Address of sourceip")); - printf (" %s\n", "-I, --sourceif=IF"); - printf (" %s\n", _("source interface name")); - printf (UT_VERBOSE); - printf ("\n"); - printf (" %s\n", _("THRESHOLD is ,%% where is the round trip average travel time (ms)")); - printf (" %s\n", _("which triggers a WARNING or CRITICAL state, and is the percentage of")); - printf (" %s\n", _("packet loss to trigger an alarm state.")); + printf(" %s\n", "-H, --hostname=HOST"); + printf(" %s\n", _("name or IP Address of host to ping (IP Address bypasses name lookup, reducing system load)")); + printf(" %s\n", "-w, --warning=THRESHOLD"); + printf(" %s\n", _("warning threshold pair")); + printf(" %s\n", "-c, --critical=THRESHOLD"); + printf(" %s\n", _("critical threshold pair")); + printf(" %s\n", "-a, --alive"); + 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"); + printf(" %s (default: %d)\n", _("number of ICMP packets to send"), PACKET_COUNT); + printf(" %s\n", "-T, --target-timeout=INTEGER"); + printf(" %s (default: fping's default for -t)\n", _("Target timeout (ms)")); + printf(" %s\n", "-i, --interval=INTEGER"); + printf(" %s (default: fping's default for -p)\n", _("Interval (ms) between sending packets")); + printf(" %s\n", "-S, --sourceip=HOST"); + printf(" %s\n", _("name or IP Address of sourceip")); + printf(" %s\n", "-I, --sourceif=IF"); + printf(" %s\n", _("source interface name")); + printf(UT_VERBOSE); + printf("\n"); + printf(" %s\n", _("THRESHOLD is ,%% where is the round trip average travel time (ms)")); + printf(" %s\n", _("which triggers a WARNING or CRITICAL state, and is the percentage of")); + printf(" %s\n", _("packet loss to trigger an alarm state.")); - printf ("\n"); - printf (" %s\n", _("IPv4 is used by default. Specify -6 to use IPv6.")); + printf("\n"); + printf(" %s\n", _("IPv4 is used by default. Specify -6 to use IPv6.")); - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf (" %s -w limit -c limit [-b size] [-n number] [-T number] [-i number]\n", progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf(" %s -w limit -c limit [-b size] [-n number] [-T number] [-i number]\n", progname); } -- cgit v0.10-9-g596f From 5490729f1ff8fd65ba408906cf1552331938424b Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:37:38 +0100 Subject: check_fping: update copyright diff --git a/plugins/check_fping.c b/plugins/check_fping.c index ec15114..b11508a 100644 --- a/plugins/check_fping.c +++ b/plugins/check_fping.c @@ -3,7 +3,7 @@ * Monitoring check_fping plugin * * License: GPL - * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -30,7 +30,7 @@ *****************************************************************************/ const char *progname = "check_fping"; -const char *copyright = "2000-2007"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From f3ed9c6038eb960efcdaff7f58cae7934dd20a3e Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:38:44 +0100 Subject: check_fping: do not export local symbols diff --git a/plugins/check_fping.c b/plugins/check_fping.c index b11508a..79d672c 100644 --- a/plugins/check_fping.c +++ b/plugins/check_fping.c @@ -46,29 +46,29 @@ enum { RTA = 1 }; -int textscan(char *buf); -int process_arguments(int, char **); -int get_threshold(char *arg, char *rv[2]); -void print_help(void); +static int textscan(char *buf); +static int process_arguments(int, char **); +static int get_threshold(char *arg, char *rv[2]); +static void print_help(void); void print_usage(void); -char *server_name = NULL; -char *sourceip = NULL; -char *sourceif = NULL; -int packet_size = PACKET_SIZE; -int packet_count = PACKET_COUNT; -int target_timeout = 0; -int packet_interval = 0; -bool verbose = false; -int cpl; -int wpl; -double crta; -double wrta; -bool cpl_p = false; -bool wpl_p = false; -bool alive_p = false; -bool crta_p = false; -bool wrta_p = false; +static char *server_name = NULL; +static char *sourceip = NULL; +static char *sourceif = NULL; +static int packet_size = PACKET_SIZE; +static int packet_count = PACKET_COUNT; +static int target_timeout = 0; +static int packet_interval = 0; +static bool verbose = false; +static int cpl; +static int wpl; +static double crta; +static double wrta; +static bool cpl_p = false; +static bool wpl_p = false; +static bool alive_p = false; +static bool crta_p = false; +static bool wrta_p = false; int main(int argc, char **argv) { /* normally should be int result = STATE_UNKNOWN; */ -- cgit v0.10-9-g596f From 1d0f532750f24b2208846c139927fb8ed50ff1d3 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:39:38 +0100 Subject: check_fping: Linter fixes diff --git a/plugins/check_fping.c b/plugins/check_fping.c index 79d672c..49235e2 100644 --- a/plugins/check_fping.c +++ b/plugins/check_fping.c @@ -47,7 +47,7 @@ enum { }; static int textscan(char *buf); -static int process_arguments(int, char **); +static int process_arguments(int /*argc*/, char ** /*argv*/); static int get_threshold(char *arg, char *rv[2]); static void print_help(void); void print_usage(void); -- cgit v0.10-9-g596f From 11a5ab2b8d1ae2c21e2831dd8f6fc4097775dbf7 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:40:12 +0100 Subject: check_game: clang-format diff --git a/plugins/check_game.c b/plugins/check_game.c index ca12697..843c558 100644 --- a/plugins/check_game.c +++ b/plugins/check_game.c @@ -1,33 +1,33 @@ /***************************************************************************** -* -* Monitoring check_game plugin -* -* License: GPL -* Copyright (c) 2002-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_game plugin -* -* This plugin tests game server connections with the specified host. -* using the qstat program -* -* -* 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_game plugin + * + * License: GPL + * Copyright (c) 2002-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_game plugin + * + * This plugin tests game server connections with the specified host. + * using the qstat program + * + * + * 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_game"; const char *copyright = "2002-2007"; @@ -37,16 +37,16 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #include "runcmd.h" -int process_arguments (int, char **); -int validate_arguments (void); -void print_help (void); -void print_usage (void); +int process_arguments(int, char **); +int validate_arguments(void); +void print_help(void); +void print_usage(void); -#define QSTAT_DATA_DELIMITER "," +#define QSTAT_DATA_DELIMITER "," -#define QSTAT_HOST_ERROR "ERROR" -#define QSTAT_HOST_DOWN "DOWN" -#define QSTAT_HOST_TIMEOUT "TIMEOUT" +#define QSTAT_HOST_ERROR "ERROR" +#define QSTAT_HOST_DOWN "DOWN" +#define QSTAT_HOST_TIMEOUT "TIMEOUT" #define QSTAT_MAX_RETURN_ARGS 12 char *server_ip; @@ -61,275 +61,247 @@ int qstat_game_field = -1; int qstat_map_field = -1; int qstat_ping_field = -1; - -int -main (int argc, char **argv) -{ - char *command_line; - int result = STATE_UNKNOWN; - char *p, *ret[QSTAT_MAX_RETURN_ARGS]; - size_t i = 0; - output chld_out; - - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); - - /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); - - if (process_arguments (argc, argv) == ERROR) - usage_va(_("Could not parse arguments")); - - result = STATE_OK; - - /* create the command line to execute */ - xasprintf (&command_line, "%s -raw %s -%s %s", - PATH_TO_QSTAT, QSTAT_DATA_DELIMITER, game_type, server_ip); - - if (port) - xasprintf (&command_line, "%s:%-d", command_line, port); - - if (verbose) - printf ("%s\n", command_line); - - /* run the command. historically, this plugin ignores output on stderr, - * as well as return status of the qstat program */ - (void)np_runcmd(command_line, &chld_out, NULL, 0); - - /* sanity check */ - /* was thinking about running qstat without any options, capturing the - -default line, parsing it & making an array of all know server types - but thought this would be too much hassle considering this is a tool - for intelligent sysadmins (ha). Could put a static array of known - server types in a header file but then we'd be limiting ourselves - - In the end, I figured I'd simply let an error occur & then trap it - */ - - if (!strncmp (chld_out.line[0], "unknown option", 14)) { - printf (_("CRITICAL - Host type parameter incorrect!\n")); - result = STATE_CRITICAL; - return result; - } - - p = (char *) strtok (chld_out.line[0], QSTAT_DATA_DELIMITER); - while (p != NULL) { - ret[i] = p; - p = (char *) strtok (NULL, QSTAT_DATA_DELIMITER); - i++; - if (i >= QSTAT_MAX_RETURN_ARGS) - break; - } - - if (strstr (ret[2], QSTAT_HOST_ERROR)) { - printf (_("CRITICAL - Host not found\n")); - result = STATE_CRITICAL; - } - else if (strstr (ret[2], QSTAT_HOST_DOWN)) { - printf (_("CRITICAL - Game server down or unavailable\n")); - result = STATE_CRITICAL; - } - else if (strstr (ret[2], QSTAT_HOST_TIMEOUT)) { - printf (_("CRITICAL - Game server timeout\n")); - result = STATE_CRITICAL; - } - else { - printf ("OK: %s/%s %s (%s), Ping: %s ms|%s %s\n", - ret[qstat_game_players], - ret[qstat_game_players_max], - ret[qstat_game_field], - ret[qstat_map_field], - ret[qstat_ping_field], - perfdata ("players", atol(ret[qstat_game_players]), "", - false, 0, false, 0, - true, 0, true, atol(ret[qstat_game_players_max])), - fperfdata ("ping", strtod(ret[qstat_ping_field], NULL), "", - false, 0, false, 0, - true, 0, false, 0)); - } - - return result; +int main(int argc, char **argv) { + char *command_line; + int result = STATE_UNKNOWN; + char *p, *ret[QSTAT_MAX_RETURN_ARGS]; + size_t i = 0; + output chld_out; + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + + /* Parse extra opts if any */ + argv = np_extra_opts(&argc, argv, progname); + + if (process_arguments(argc, argv) == ERROR) + usage_va(_("Could not parse arguments")); + + result = STATE_OK; + + /* create the command line to execute */ + xasprintf(&command_line, "%s -raw %s -%s %s", PATH_TO_QSTAT, QSTAT_DATA_DELIMITER, game_type, server_ip); + + if (port) + xasprintf(&command_line, "%s:%-d", command_line, port); + + if (verbose) + printf("%s\n", command_line); + + /* run the command. historically, this plugin ignores output on stderr, + * as well as return status of the qstat program */ + (void)np_runcmd(command_line, &chld_out, NULL, 0); + + /* sanity check */ + /* was thinking about running qstat without any options, capturing the + -default line, parsing it & making an array of all know server types + but thought this would be too much hassle considering this is a tool + for intelligent sysadmins (ha). Could put a static array of known + server types in a header file but then we'd be limiting ourselves + + In the end, I figured I'd simply let an error occur & then trap it + */ + + if (!strncmp(chld_out.line[0], "unknown option", 14)) { + printf(_("CRITICAL - Host type parameter incorrect!\n")); + result = STATE_CRITICAL; + return result; + } + + p = (char *)strtok(chld_out.line[0], QSTAT_DATA_DELIMITER); + while (p != NULL) { + ret[i] = p; + p = (char *)strtok(NULL, QSTAT_DATA_DELIMITER); + i++; + if (i >= QSTAT_MAX_RETURN_ARGS) + break; + } + + if (strstr(ret[2], QSTAT_HOST_ERROR)) { + printf(_("CRITICAL - Host not found\n")); + result = STATE_CRITICAL; + } else if (strstr(ret[2], QSTAT_HOST_DOWN)) { + printf(_("CRITICAL - Game server down or unavailable\n")); + result = STATE_CRITICAL; + } else if (strstr(ret[2], QSTAT_HOST_TIMEOUT)) { + printf(_("CRITICAL - Game server timeout\n")); + result = STATE_CRITICAL; + } else { + printf("OK: %s/%s %s (%s), Ping: %s ms|%s %s\n", ret[qstat_game_players], ret[qstat_game_players_max], ret[qstat_game_field], + ret[qstat_map_field], ret[qstat_ping_field], + perfdata("players", atol(ret[qstat_game_players]), "", false, 0, false, 0, true, 0, true, atol(ret[qstat_game_players_max])), + fperfdata("ping", strtod(ret[qstat_ping_field], NULL), "", false, 0, false, 0, true, 0, false, 0)); + } + + return result; } - -int -process_arguments (int argc, char **argv) -{ - int c; - - int opt_index = 0; - static struct option long_opts[] = { - {"help", no_argument, 0, 'h'}, - {"version", no_argument, 0, 'V'}, - {"verbose", no_argument, 0, 'v'}, - {"timeout", required_argument, 0, 't'}, - {"hostname", required_argument, 0, 'H'}, - {"port", required_argument, 0, 'P'}, - {"game-type", required_argument, 0, 'G'}, - {"map-field", required_argument, 0, 'm'}, - {"ping-field", required_argument, 0, 'p'}, - {"game-field", required_argument, 0, 'g'}, - {"players-field", required_argument, 0, 129}, - {"max-players-field", required_argument, 0, 130}, - {0, 0, 0, 0} - }; - - if (argc < 2) - return ERROR; - - for (c = 1; c < argc; c++) { - if (strcmp ("-mf", argv[c]) == 0) - strcpy (argv[c], "-m"); - else if (strcmp ("-pf", argv[c]) == 0) - strcpy (argv[c], "-p"); - else if (strcmp ("-gf", argv[c]) == 0) - strcpy (argv[c], "-g"); - } - - while (1) { - c = getopt_long (argc, argv, "hVvt:H:P:G:g:p:m:", long_opts, &opt_index); - - if (c == -1 || c == EOF) - break; - - switch (c) { - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'v': /* version */ - verbose = true; - break; - case 't': /* timeout period */ - timeout_interval = atoi (optarg); - break; - case 'H': /* hostname */ - if (strlen (optarg) >= MAX_HOST_ADDRESS_LENGTH) - die (STATE_UNKNOWN, _("Input buffer overflow\n")); - server_ip = optarg; - break; - case 'P': /* port */ - port = atoi (optarg); - break; - case 'G': /* hostname */ - if (strlen (optarg) >= MAX_INPUT_BUFFER) - die (STATE_UNKNOWN, _("Input buffer overflow\n")); - game_type = optarg; - break; - case 'p': /* index of ping field */ - qstat_ping_field = atoi (optarg); - if (qstat_ping_field < 0 || qstat_ping_field > QSTAT_MAX_RETURN_ARGS) - return ERROR; - break; - case 'm': /* index on map field */ - qstat_map_field = atoi (optarg); - if (qstat_map_field < 0 || qstat_map_field > QSTAT_MAX_RETURN_ARGS) - return ERROR; - break; - case 'g': /* index of game field */ - qstat_game_field = atoi (optarg); - if (qstat_game_field < 0 || qstat_game_field > QSTAT_MAX_RETURN_ARGS) - return ERROR; - break; - case 129: /* index of player count field */ - qstat_game_players = atoi (optarg); - if (qstat_game_players_max == 0) - qstat_game_players_max = qstat_game_players - 1; - if (qstat_game_players < 0 || qstat_game_players > QSTAT_MAX_RETURN_ARGS) - return ERROR; - break; - case 130: /* index of max players field */ - qstat_game_players_max = atoi (optarg); - if (qstat_game_players_max < 0 || qstat_game_players_max > QSTAT_MAX_RETURN_ARGS) - return ERROR; - break; - default: /* args not parsable */ - usage5(); - } - } - - c = optind; - /* first option is the game type */ - if (!game_type && c= MAX_HOST_ADDRESS_LENGTH) + die(STATE_UNKNOWN, _("Input buffer overflow\n")); + server_ip = optarg; + break; + case 'P': /* port */ + port = atoi(optarg); + break; + case 'G': /* hostname */ + if (strlen(optarg) >= MAX_INPUT_BUFFER) + die(STATE_UNKNOWN, _("Input buffer overflow\n")); + game_type = optarg; + break; + case 'p': /* index of ping field */ + qstat_ping_field = atoi(optarg); + if (qstat_ping_field < 0 || qstat_ping_field > QSTAT_MAX_RETURN_ARGS) + return ERROR; + break; + case 'm': /* index on map field */ + qstat_map_field = atoi(optarg); + if (qstat_map_field < 0 || qstat_map_field > QSTAT_MAX_RETURN_ARGS) + return ERROR; + break; + case 'g': /* index of game field */ + qstat_game_field = atoi(optarg); + if (qstat_game_field < 0 || qstat_game_field > QSTAT_MAX_RETURN_ARGS) + return ERROR; + break; + case 129: /* index of player count field */ + qstat_game_players = atoi(optarg); + if (qstat_game_players_max == 0) + qstat_game_players_max = qstat_game_players - 1; + if (qstat_game_players < 0 || qstat_game_players > QSTAT_MAX_RETURN_ARGS) + return ERROR; + break; + case 130: /* index of max players field */ + qstat_game_players_max = atoi(optarg); + if (qstat_game_players_max < 0 || qstat_game_players_max > QSTAT_MAX_RETURN_ARGS) + return ERROR; + break; + default: /* args not parsable */ + usage5(); + } + } + + c = optind; + /* first option is the game type */ + if (!game_type && c < argc) + game_type = strdup(argv[c++]); + + /* Second option is the server name */ + if (!server_ip && c < argc) + server_ip = strdup(argv[c++]); + + return validate_arguments(); } +int validate_arguments(void) { + if (qstat_game_players_max < 0) + qstat_game_players_max = 4; -int -validate_arguments (void) -{ - if (qstat_game_players_max < 0) - qstat_game_players_max = 4; + if (qstat_game_players < 0) + qstat_game_players = 5; - if (qstat_game_players < 0) - qstat_game_players = 5; + if (qstat_game_field < 0) + qstat_game_field = 2; - if (qstat_game_field < 0) - qstat_game_field = 2; + if (qstat_map_field < 0) + qstat_map_field = 3; - if (qstat_map_field < 0) - qstat_map_field = 3; + if (qstat_ping_field < 0) + qstat_ping_field = 5; - if (qstat_ping_field < 0) - qstat_ping_field = 5; - - return OK; + return OK; } +void print_help(void) { + print_revision(progname, NP_VERSION); -void -print_help (void) -{ - print_revision (progname, NP_VERSION); - - printf ("Copyright (c) 1999 Ian Cass, Knowledge Matters Limited\n"); - printf (COPYRIGHT, copyright, email); + printf("Copyright (c) 1999 Ian Cass, Knowledge Matters Limited\n"); + printf(COPYRIGHT, copyright, email); - printf (_("This plugin tests game server connections with the specified host.")); + printf(_("This plugin tests game server connections with the specified host.")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); - printf (" %s\n", "-p"); - printf (" %s\n", _("Optional port of which to connect")); - printf (" %s\n", "gf"); - printf (" %s\n", _("Field number in raw qstat output that contains game name")); - printf (" %s\n", "-mf"); - printf (" %s\n", _("Field number in raw qstat output that contains map name")); - printf (" %s\n", "-pf"); - printf (" %s\n", _("Field number in raw qstat output that contains ping time")); + printf(" %s\n", "-p"); + printf(" %s\n", _("Optional port of which to connect")); + printf(" %s\n", "gf"); + printf(" %s\n", _("Field number in raw qstat output that contains game name")); + printf(" %s\n", "-mf"); + printf(" %s\n", _("Field number in raw qstat output that contains map name")); + printf(" %s\n", "-pf"); + printf(" %s\n", _("Field number in raw qstat output that contains ping time")); - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - printf ("\n"); - printf ("%s\n", _("Notes:")); - printf (" %s\n", _("This plugin uses the 'qstat' command, the popular game server status query tool.")); - printf (" %s\n", _("If you don't have the package installed, you will need to download it from")); - printf (" %s\n", _("https://github.com/multiplay/qstat before you can use this plugin.")); + printf("\n"); + printf("%s\n", _("Notes:")); + printf(" %s\n", _("This plugin uses the 'qstat' command, the popular game server status query tool.")); + printf(" %s\n", _("If you don't have the package installed, you will need to download it from")); + printf(" %s\n", _("https://github.com/multiplay/qstat before you can use this plugin.")); - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf (" %s [-hvV] [-P port] [-t timeout] [-g game_field] [-m map_field] [-p ping_field] [-G game-time] [-H hostname] \n", progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf(" %s [-hvV] [-P port] [-t timeout] [-g game_field] [-m map_field] [-p ping_field] [-G game-time] [-H hostname] " + "\n", + progname); } /****************************************************************************** -- cgit v0.10-9-g596f From aa143390f5ee7ca43958312e3142b25df6653e9a Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:41:06 +0100 Subject: check_game: update copyright diff --git a/plugins/check_game.c b/plugins/check_game.c index 843c558..b372cf1 100644 --- a/plugins/check_game.c +++ b/plugins/check_game.c @@ -3,7 +3,7 @@ * Monitoring check_game plugin * * License: GPL - * Copyright (c) 2002-2007 Monitoring Plugins Development Team + * Copyright (c) 2002-2024 Monitoring Plugins Development Team * * Description: * @@ -30,7 +30,7 @@ *****************************************************************************/ const char *progname = "check_game"; -const char *copyright = "2002-2007"; +const char *copyright = "2002-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 8355b9db407f2ca763467efb509de7564f8016a4 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:42:06 +0100 Subject: check_game: do not export local symbols diff --git a/plugins/check_game.c b/plugins/check_game.c index b372cf1..80a90e4 100644 --- a/plugins/check_game.c +++ b/plugins/check_game.c @@ -37,9 +37,9 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #include "runcmd.h" -int process_arguments(int, char **); -int validate_arguments(void); -void print_help(void); +static int process_arguments(int, char **); +static int validate_arguments(void); +static void print_help(void); void print_usage(void); #define QSTAT_DATA_DELIMITER "," @@ -49,17 +49,17 @@ void print_usage(void); #define QSTAT_HOST_TIMEOUT "TIMEOUT" #define QSTAT_MAX_RETURN_ARGS 12 -char *server_ip; -char *game_type; -int port = 0; +static char *server_ip; +static char *game_type; +static int port = 0; -bool verbose = false; +static bool verbose = false; -int qstat_game_players_max = -1; -int qstat_game_players = -1; -int qstat_game_field = -1; -int qstat_map_field = -1; -int qstat_ping_field = -1; +static int qstat_game_players_max = -1; +static int qstat_game_players = -1; +static int qstat_game_field = -1; +static int qstat_map_field = -1; +static int qstat_ping_field = -1; int main(int argc, char **argv) { char *command_line; -- cgit v0.10-9-g596f From 0e0c517b19c7a97cb4efec0731c40caf57d1a340 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:44:06 +0100 Subject: check_game: linter fixes diff --git a/plugins/check_game.c b/plugins/check_game.c index 80a90e4..619277e 100644 --- a/plugins/check_game.c +++ b/plugins/check_game.c @@ -37,7 +37,7 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #include "runcmd.h" -static int process_arguments(int, char **); +static int process_arguments(int /*argc*/, char ** /*argv*/); static int validate_arguments(void); static void print_help(void); void print_usage(void); @@ -64,7 +64,8 @@ static int qstat_ping_field = -1; int main(int argc, char **argv) { char *command_line; int result = STATE_UNKNOWN; - char *p, *ret[QSTAT_MAX_RETURN_ARGS]; + char *p; + char *ret[QSTAT_MAX_RETURN_ARGS]; size_t i = 0; output chld_out; -- cgit v0.10-9-g596f From 80fcc8dfacba565881bc552f1f5515d7ea5ffbed Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:45:03 +0100 Subject: check_hpjd: clang-format diff --git a/plugins/check_hpjd.c b/plugins/check_hpjd.c index c34bb08..836bf95 100644 --- a/plugins/check_hpjd.c +++ b/plugins/check_hpjd.c @@ -1,33 +1,33 @@ /***************************************************************************** -* -* Monitoring check_hpjd plugin -* -* License: GPL -* Copyright (c) 2000-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_hpjd plugin -* -* This plugin tests the STATUS of an HP printer with a JetDirect card. -* Net-SNMP must be installed on the computer running the plugin. -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_hpjd plugin + * + * License: GPL + * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_hpjd plugin + * + * This plugin tests the STATUS of an HP printer with a JetDirect card. + * Net-SNMP must be installed on the computer running the plugin. + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "check_hpjd"; const char *copyright = "2000-2007"; @@ -39,7 +39,7 @@ const char *email = "devel@monitoring-plugins.org"; #include "netutils.h" #define DEFAULT_COMMUNITY "public" -#define DEFAULT_PORT "161" +#define DEFAULT_PORT "161" const char *option_summary = "-H host [-C community]\n"; @@ -56,22 +56,20 @@ const char *option_summary = "-H host [-C community]\n"; #define HPJD_GD_PAPER_OUTPUT ".1.3.6.1.4.1.11.2.3.9.1.1.2.19" #define HPJD_GD_STATUS_DISPLAY ".1.3.6.1.4.1.11.2.3.9.1.1.3" -#define ONLINE 0 -#define OFFLINE 1 +#define ONLINE 0 +#define OFFLINE 1 -int process_arguments (int, char **); -int validate_arguments (void); -void print_help (void); -void print_usage (void); +int process_arguments(int, char **); +int validate_arguments(void); +void print_help(void); +void print_usage(void); char *community = NULL; char *address = NULL; unsigned int port = 0; -int check_paper_out = 1; +int check_paper_out = 1; -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { char command_line[1024]; int result = STATE_UNKNOWN; int line; @@ -94,116 +92,99 @@ main (int argc, char **argv) errmsg = malloc(MAX_INPUT_BUFFER); - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if (process_arguments (argc, argv) == ERROR) - usage4 (_("Could not parse arguments")); + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments")); /* removed ' 2>1' at end of command 10/27/1999 - EG */ /* create the query string */ - sprintf - (query_string, - "%s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0", - HPJD_LINE_STATUS, - HPJD_PAPER_STATUS, - HPJD_INTERVENTION_REQUIRED, - HPJD_GD_PERIPHERAL_ERROR, - HPJD_GD_PAPER_JAM, - HPJD_GD_PAPER_OUT, - HPJD_GD_TONER_LOW, - HPJD_GD_PAGE_PUNT, - HPJD_GD_MEMORY_OUT, - HPJD_GD_DOOR_OPEN, HPJD_GD_PAPER_OUTPUT, HPJD_GD_STATUS_DISPLAY); + sprintf(query_string, "%s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0", HPJD_LINE_STATUS, HPJD_PAPER_STATUS, + HPJD_INTERVENTION_REQUIRED, HPJD_GD_PERIPHERAL_ERROR, HPJD_GD_PAPER_JAM, HPJD_GD_PAPER_OUT, HPJD_GD_TONER_LOW, + HPJD_GD_PAGE_PUNT, HPJD_GD_MEMORY_OUT, HPJD_GD_DOOR_OPEN, HPJD_GD_PAPER_OUTPUT, HPJD_GD_STATUS_DISPLAY); /* get the command to run */ - sprintf (command_line, "%s -OQa -m : -v 1 -c %s %s:%u %s", - PATH_TO_SNMPGET, - community, - address, - port, - query_string); + sprintf(command_line, "%s -OQa -m : -v 1 -c %s %s:%u %s", PATH_TO_SNMPGET, community, address, port, query_string); /* run the command */ - child_process = spopen (command_line); + child_process = spopen(command_line); if (child_process == NULL) { - printf (_("Could not open pipe: %s\n"), command_line); + printf(_("Could not open pipe: %s\n"), command_line); return STATE_UNKNOWN; } - child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r"); + child_stderr = fdopen(child_stderr_array[fileno(child_process)], "r"); if (child_stderr == NULL) { - printf (_("Could not open stderr for %s\n"), command_line); + printf(_("Could not open stderr for %s\n"), command_line); } result = STATE_OK; line = 0; - while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) { + while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process)) { /* strip the newline character from the end of the input */ - if (input_buffer[strlen (input_buffer) - 1] == '\n') - input_buffer[strlen (input_buffer) - 1] = 0; + if (input_buffer[strlen(input_buffer) - 1] == '\n') + input_buffer[strlen(input_buffer) - 1] = 0; line++; - temp_buffer = strtok (input_buffer, "="); - temp_buffer = strtok (NULL, "="); + temp_buffer = strtok(input_buffer, "="); + temp_buffer = strtok(NULL, "="); if (temp_buffer == NULL && line < 13) { - result = STATE_UNKNOWN; - strcpy (errmsg, input_buffer); + result = STATE_UNKNOWN; + strcpy(errmsg, input_buffer); } else { switch (line) { - case 1: /* 1st line should contain the line status */ - line_status = atoi (temp_buffer); + case 1: /* 1st line should contain the line status */ + line_status = atoi(temp_buffer); break; - case 2: /* 2nd line should contain the paper status */ - paper_status = atoi (temp_buffer); + case 2: /* 2nd line should contain the paper status */ + paper_status = atoi(temp_buffer); break; - case 3: /* 3rd line should be intervention required */ - intervention_required = atoi (temp_buffer); + case 3: /* 3rd line should be intervention required */ + intervention_required = atoi(temp_buffer); break; - case 4: /* 4th line should be peripheral error */ - peripheral_error = atoi (temp_buffer); + case 4: /* 4th line should be peripheral error */ + peripheral_error = atoi(temp_buffer); break; - case 5: /* 5th line should contain the paper jam status */ - paper_jam = atoi (temp_buffer); + case 5: /* 5th line should contain the paper jam status */ + paper_jam = atoi(temp_buffer); break; - case 6: /* 6th line should contain the paper out status */ - paper_out = atoi (temp_buffer); + case 6: /* 6th line should contain the paper out status */ + paper_out = atoi(temp_buffer); break; - case 7: /* 7th line should contain the toner low status */ - toner_low = atoi (temp_buffer); + case 7: /* 7th line should contain the toner low status */ + toner_low = atoi(temp_buffer); break; - case 8: /* did data come too slow for engine */ - page_punt = atoi (temp_buffer); + case 8: /* did data come too slow for engine */ + page_punt = atoi(temp_buffer); break; - case 9: /* did we run out of memory */ - memory_out = atoi (temp_buffer); + case 9: /* did we run out of memory */ + memory_out = atoi(temp_buffer); break; - case 10: /* is there a door open */ - door_open = atoi (temp_buffer); + case 10: /* is there a door open */ + door_open = atoi(temp_buffer); break; - case 11: /* is output tray full */ - paper_output = atoi (temp_buffer); + case 11: /* is output tray full */ + paper_output = atoi(temp_buffer); break; - case 12: /* display panel message */ - strcpy (display_message, temp_buffer + 1); + case 12: /* display panel message */ + strcpy(display_message, temp_buffer + 1); break; - default: /* fold multiline message */ - strncat (display_message, input_buffer, - sizeof (display_message) - strlen (display_message) - 1); + default: /* fold multiline message */ + strncat(display_message, input_buffer, sizeof(display_message) - strlen(display_message) - 1); } - } /* break out of the read loop if we encounter an error */ @@ -212,29 +193,27 @@ main (int argc, char **argv) } /* WARNING if output found on stderr */ - if (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) { - result = max_state (result, STATE_WARNING); + if (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) { + result = max_state(result, STATE_WARNING); /* remove CRLF */ - if (input_buffer[strlen (input_buffer) - 1] == '\n') - input_buffer[strlen (input_buffer) - 1] = 0; - sprintf (errmsg, "%s", input_buffer ); - + if (input_buffer[strlen(input_buffer) - 1] == '\n') + input_buffer[strlen(input_buffer) - 1] = 0; + sprintf(errmsg, "%s", input_buffer); } /* close stderr */ - (void) fclose (child_stderr); + (void)fclose(child_stderr); /* close the pipe */ - if (spclose (child_process)) - result = max_state (result, STATE_WARNING); + if (spclose(child_process)) + result = max_state(result, STATE_WARNING); /* if there wasn't any output, display an error */ if (line == 0) { /* might not be the problem, but most likely is. */ - result = STATE_UNKNOWN ; - xasprintf (&errmsg, "%s : Timeout from host %s\n", errmsg, address ); - + result = STATE_UNKNOWN; + xasprintf(&errmsg, "%s : Timeout from host %s\n", errmsg, address); } /* if we had no read errors, check the printer status results... */ @@ -242,201 +221,171 @@ main (int argc, char **argv) if (paper_jam) { result = STATE_WARNING; - strcpy (errmsg, _("Paper Jam")); - } - else if (paper_out) { + strcpy(errmsg, _("Paper Jam")); + } else if (paper_out) { if (check_paper_out) result = STATE_WARNING; - strcpy (errmsg, _("Out of Paper")); - } - else if (line_status == OFFLINE) { - if (strcmp (errmsg, "POWERSAVE ON") != 0) { + strcpy(errmsg, _("Out of Paper")); + } else if (line_status == OFFLINE) { + if (strcmp(errmsg, "POWERSAVE ON") != 0) { result = STATE_WARNING; - strcpy (errmsg, _("Printer Offline")); + strcpy(errmsg, _("Printer Offline")); } - } - else if (peripheral_error) { + } else if (peripheral_error) { result = STATE_WARNING; - strcpy (errmsg, _("Peripheral Error")); - } - else if (intervention_required) { + strcpy(errmsg, _("Peripheral Error")); + } else if (intervention_required) { result = STATE_WARNING; - strcpy (errmsg, _("Intervention Required")); - } - else if (toner_low) { + strcpy(errmsg, _("Intervention Required")); + } else if (toner_low) { result = STATE_WARNING; - strcpy (errmsg, _("Toner Low")); - } - else if (memory_out) { + strcpy(errmsg, _("Toner Low")); + } else if (memory_out) { result = STATE_WARNING; - strcpy (errmsg, _("Insufficient Memory")); - } - else if (door_open) { + strcpy(errmsg, _("Insufficient Memory")); + } else if (door_open) { result = STATE_WARNING; - strcpy (errmsg, _("A Door is Open")); - } - else if (paper_output) { + strcpy(errmsg, _("A Door is Open")); + } else if (paper_output) { result = STATE_WARNING; - strcpy (errmsg, _("Output Tray is Full")); - } - else if (page_punt) { + strcpy(errmsg, _("Output Tray is Full")); + } else if (page_punt) { result = STATE_WARNING; - strcpy (errmsg, _("Data too Slow for Engine")); - } - else if (paper_status) { + strcpy(errmsg, _("Data too Slow for Engine")); + } else if (paper_status) { result = STATE_WARNING; - strcpy (errmsg, _("Unknown Paper Error")); + strcpy(errmsg, _("Unknown Paper Error")); } } if (result == STATE_OK) - printf (_("Printer ok - (%s)\n"), display_message); + printf(_("Printer ok - (%s)\n"), display_message); else if (result == STATE_UNKNOWN) { - printf ("%s\n", errmsg); + printf("%s\n", errmsg); /* if printer could not be reached, escalate to critical */ - if (strstr (errmsg, "Timeout")) + if (strstr(errmsg, "Timeout")) result = STATE_CRITICAL; } else if (result == STATE_WARNING) - printf ("%s (%s)\n", errmsg, display_message); + printf("%s (%s)\n", errmsg, display_message); return result; } - /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ +int process_arguments(int argc, char **argv) { int c; int option = 0; - static struct option longopts[] = { - {"hostname", required_argument, 0, 'H'}, - {"community", required_argument, 0, 'C'}, -/* {"critical", required_argument,0,'c'}, */ -/* {"warning", required_argument,0,'w'}, */ - {"port", required_argument,0,'p'}, - {"version", no_argument, 0, 'V'}, - {"help", no_argument, 0, 'h'}, - {0, 0, 0, 0} - }; + static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, + {"community", required_argument, 0, 'C'}, + /* {"critical", required_argument,0,'c'}, */ + /* {"warning", required_argument,0,'w'}, */ + {"port", required_argument, 0, 'p'}, + {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {0, 0, 0, 0}}; if (argc < 2) return ERROR; - while (1) { - c = getopt_long (argc, argv, "+hVH:C:p:D", longopts, &option); + c = getopt_long(argc, argv, "+hVH:C:p:D", longopts, &option); if (c == -1 || c == EOF || c == 1) break; switch (c) { - case 'H': /* hostname */ - if (is_host (optarg)) { - address = strscpy(address, optarg) ; - } - else { - usage2 (_("Invalid hostname/address"), optarg); + case 'H': /* hostname */ + if (is_host(optarg)) { + address = strscpy(address, optarg); + } else { + usage2(_("Invalid hostname/address"), optarg); } break; - case 'C': /* community */ - community = strscpy (community, optarg); + case 'C': /* community */ + community = strscpy(community, optarg); break; case 'p': if (!is_intpos(optarg)) - usage2 (_("Port must be a positive short integer"), optarg); + usage2(_("Port must be a positive short integer"), optarg); else port = atoi(optarg); break; - case 'D': /* disable paper out check*/ + case 'D': /* disable paper out check*/ check_paper_out = 0; break; - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case '?': /* help */ - usage5 (); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case '?': /* help */ + usage5(); } } c = optind; if (address == NULL) { - if (is_host (argv[c])) { + if (is_host(argv[c])) { address = argv[c++]; - } - else { - usage2 (_("Invalid hostname/address"), argv[c]); + } else { + usage2(_("Invalid hostname/address"), argv[c]); } } if (community == NULL) { - if (argv[c] != NULL ) + if (argv[c] != NULL) community = argv[c]; else - community = strdup (DEFAULT_COMMUNITY); + community = strdup(DEFAULT_COMMUNITY); } if (port == 0) { port = atoi(DEFAULT_PORT); } - return validate_arguments (); + return validate_arguments(); } +int validate_arguments(void) { return OK; } -int -validate_arguments (void) -{ - return OK; -} - - -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 STATUS of an HP printer with a JetDirect card.")); - printf ("%s\n", _("Net-snmp must be installed on the computer running the plugin.")); + printf("%s\n", _("This plugin tests the STATUS of an HP printer with a JetDirect card.")); + printf("%s\n", _("Net-snmp must be installed on the computer running the plugin.")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); - printf (" %s\n", "-C, --community=STRING"); - printf (" %s", _("The SNMP community name ")); - printf (_("(default=%s)"), DEFAULT_COMMUNITY); - printf ("\n"); - printf (" %s\n", "-p, --port=STRING"); - printf (" %s", _("Specify the port to check ")); - printf (_("(default=%s)"), DEFAULT_PORT); - printf ("\n"); - printf (" %s\n", "-D"); - printf (" %s", _("Disable paper check ")); + printf(" %s\n", "-C, --community=STRING"); + printf(" %s", _("The SNMP community name ")); + printf(_("(default=%s)"), DEFAULT_COMMUNITY); + printf("\n"); + printf(" %s\n", "-p, --port=STRING"); + printf(" %s", _("Specify the port to check ")); + printf(_("(default=%s)"), DEFAULT_PORT); + printf("\n"); + printf(" %s\n", "-D"); + printf(" %s", _("Disable paper check ")); - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s -H host [-C community] [-p port] [-D]\n", progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s -H host [-C community] [-p port] [-D]\n", progname); } -- cgit v0.10-9-g596f From a4b3386657625fa8d24ca25993560895694ad9c8 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:45:50 +0100 Subject: check_hpjd: update copyright diff --git a/plugins/check_hpjd.c b/plugins/check_hpjd.c index 836bf95..713b108 100644 --- a/plugins/check_hpjd.c +++ b/plugins/check_hpjd.c @@ -3,7 +3,7 @@ * Monitoring check_hpjd plugin * * License: GPL - * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -30,7 +30,7 @@ *****************************************************************************/ const char *progname = "check_hpjd"; -const char *copyright = "2000-2007"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From f33412e50acbb57c3c02a412a3e9574639576f83 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:47:03 +0100 Subject: check_hpjd: do not export local symbols diff --git a/plugins/check_hpjd.c b/plugins/check_hpjd.c index 713b108..6e4ddcb 100644 --- a/plugins/check_hpjd.c +++ b/plugins/check_hpjd.c @@ -41,8 +41,6 @@ const char *email = "devel@monitoring-plugins.org"; #define DEFAULT_COMMUNITY "public" #define DEFAULT_PORT "161" -const char *option_summary = "-H host [-C community]\n"; - #define HPJD_LINE_STATUS ".1.3.6.1.4.1.11.2.3.9.1.1.2.1" #define HPJD_PAPER_STATUS ".1.3.6.1.4.1.11.2.3.9.1.1.2.2" #define HPJD_INTERVENTION_REQUIRED ".1.3.6.1.4.1.11.2.3.9.1.1.2.3" @@ -59,15 +57,15 @@ const char *option_summary = "-H host [-C community]\n"; #define ONLINE 0 #define OFFLINE 1 -int process_arguments(int, char **); -int validate_arguments(void); -void print_help(void); +static int process_arguments(int, char **); +static int validate_arguments(void); +static void print_help(void); void print_usage(void); -char *community = NULL; -char *address = NULL; -unsigned int port = 0; -int check_paper_out = 1; +static char *community = NULL; +static char *address = NULL; +static unsigned int port = 0; +static int check_paper_out = 1; int main(int argc, char **argv) { char command_line[1024]; -- cgit v0.10-9-g596f From e03fb9904ba91e44023ea56758f438b0005f8972 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:47:51 +0100 Subject: check_hpjd: linter fixes diff --git a/plugins/check_hpjd.c b/plugins/check_hpjd.c index 6e4ddcb..b39bccf 100644 --- a/plugins/check_hpjd.c +++ b/plugins/check_hpjd.c @@ -57,7 +57,7 @@ const char *email = "devel@monitoring-plugins.org"; #define ONLINE 0 #define OFFLINE 1 -static int process_arguments(int, char **); +static int process_arguments(int /*argc*/, char ** /*argv*/); static int validate_arguments(void); static void print_help(void); void print_usage(void); -- cgit v0.10-9-g596f From 536d8e700267432dc7b3ab0504d80a9071972a22 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:48:28 +0100 Subject: check_ide_smart: clang-format diff --git a/plugins/check_ide_smart.c b/plugins/check_ide_smart.c index 3872e34..00d9eb3 100644 --- a/plugins/check_ide_smart.c +++ b/plugins/check_ide_smart.c @@ -1,112 +1,105 @@ /***************************************************************************** -* -* Monitoring check_ide_smart plugin -* ide-smart 1.3 - IDE S.M.A.R.T. checking tool -* -* License: GPL -* Copyright (C) 1998-1999 Ragnar Hojland Espinosa -* 1998 Gadi Oxman -* Copyright (c) 2000 Robert Dale -* Copyright (c) 2000-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_ide_smart plugin -* -* This plugin checks a local hard drive with the (Linux specific) SMART -* interface -* -* -* 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_ide_smart plugin + * ide-smart 1.3 - IDE S.M.A.R.T. checking tool + * + * License: GPL + * Copyright (C) 1998-1999 Ragnar Hojland Espinosa + * 1998 Gadi Oxman + * Copyright (c) 2000 Robert Dale + * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_ide_smart plugin + * + * This plugin checks a local hard drive with the (Linux specific) SMART + * interface + * + * + * 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_ide_smart"; const char *copyright = "1998-2007"; const char *email = "devel@monitoring-plugins.org"; - + #include "common.h" #include "utils.h" -void print_help (void); -void print_usage (void); +void print_help(void); +void print_usage(void); #include #include #include #ifdef __linux__ -#include -#include +# include +# include -#define OPEN_MODE O_RDONLY +# define OPEN_MODE O_RDONLY #endif /* __linux__ */ #ifdef __NetBSD__ -#include -#include -#include -#include /* for __u8 and friends */ -#include -#include -#include -#include - -#define SMART_ENABLE WDSM_ENABLE_OPS -#define SMART_DISABLE WDSM_DISABLE_OPS -#define SMART_IMMEDIATE_OFFLINE WDSM_EXEC_OFFL_IMM -#define SMART_AUTO_OFFLINE 0xdb /* undefined in NetBSD headers */ - -#define OPEN_MODE O_RDWR +# include +# include +# include +# include /* for __u8 and friends */ +# include +# include +# include +# include + +# define SMART_ENABLE WDSM_ENABLE_OPS +# define SMART_DISABLE WDSM_DISABLE_OPS +# define SMART_IMMEDIATE_OFFLINE WDSM_EXEC_OFFL_IMM +# define SMART_AUTO_OFFLINE 0xdb /* undefined in NetBSD headers */ + +# define OPEN_MODE O_RDWR #endif /* __NetBSD__ */ #include - -#define NR_ATTRIBUTES 30 - -#define PREFAILURE 2 -#define ADVISORY 1 + +#define NR_ATTRIBUTES 30 + +#define PREFAILURE 2 +#define ADVISORY 1 #define OPERATIONAL 0 -#define UNKNOWN -1 +#define UNKNOWN -1 -typedef struct threshold_s -{ +typedef struct threshold_s { __u8 id; __u8 threshold; __u8 reserved[10]; -} -__attribute__ ((packed)) threshold_t; +} __attribute__((packed)) threshold_t; -typedef struct thresholds_s -{ +typedef struct thresholds_s { __u16 revision; threshold_t thresholds[NR_ATTRIBUTES]; __u8 reserved[18]; __u8 vendor[131]; __u8 checksum; -} -__attribute__ ((packed)) thresholds_t; +} __attribute__((packed)) thresholds_t; -typedef struct value_s -{ +typedef struct value_s { __u8 id; __u16 status; __u8 value; __u8 vendor[8]; -} -__attribute__ ((packed)) value_t; +} __attribute__((packed)) value_t; -typedef struct values_s -{ +typedef struct values_s { __u16 revision; value_t values[NR_ATTRIBUTES]; __u8 offline_status; @@ -118,60 +111,43 @@ typedef struct values_s __u8 reserved[16]; __u8 vendor[125]; __u8 checksum; -} -__attribute__ ((packed)) values_t; +} __attribute__((packed)) values_t; -struct -{ +struct { __u8 value; char *text; } -offline_status_text[] = - { - {0x00, "NeverStarted"}, - {0x02, "Completed"}, - {0x04, "Suspended"}, - {0x05, "Aborted"}, - {0x06, "Failed"}, - {0, 0} - }; - -struct -{ +offline_status_text[] = {{0x00, "NeverStarted"}, {0x02, "Completed"}, {0x04, "Suspended"}, {0x05, "Aborted"}, {0x06, "Failed"}, {0, 0}}; + +struct { __u8 value; char *text; } -smart_command[] = - { - {SMART_ENABLE, "SMART_ENABLE"}, - {SMART_DISABLE, "SMART_DISABLE"}, - {SMART_IMMEDIATE_OFFLINE, "SMART_IMMEDIATE_OFFLINE"}, - {SMART_AUTO_OFFLINE, "SMART_AUTO_OFFLINE"} - }; - - -/* Index to smart_command table, keep in order */ -enum SmartCommand - { SMART_CMD_ENABLE, - SMART_CMD_DISABLE, - SMART_CMD_IMMEDIATE_OFFLINE, - SMART_CMD_AUTO_OFFLINE - }; - -char *get_offline_text (int); -int smart_read_values (int, values_t *); -int nagios (values_t *, thresholds_t *); -void print_value (value_t *, threshold_t *); -void print_values (values_t *, thresholds_t *); -int smart_cmd_simple (int, enum SmartCommand, __u8, bool); -int smart_read_thresholds (int, thresholds_t *); +smart_command[] = {{SMART_ENABLE, "SMART_ENABLE"}, + {SMART_DISABLE, "SMART_DISABLE"}, + {SMART_IMMEDIATE_OFFLINE, "SMART_IMMEDIATE_OFFLINE"}, + {SMART_AUTO_OFFLINE, "SMART_AUTO_OFFLINE"}}; + +/* Index to smart_command table, keep in order */ +enum SmartCommand { + SMART_CMD_ENABLE, + SMART_CMD_DISABLE, + SMART_CMD_IMMEDIATE_OFFLINE, + SMART_CMD_AUTO_OFFLINE +}; + +char *get_offline_text(int); +int smart_read_values(int, values_t *); +int nagios(values_t *, thresholds_t *); +void print_value(value_t *, threshold_t *); +void print_values(values_t *, thresholds_t *); +int smart_cmd_simple(int, enum SmartCommand, __u8, bool); +int smart_read_thresholds(int, thresholds_t *); bool verbose = false; -int -main (int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { char *device = NULL; int o, longindex; int retval = 0; @@ -180,28 +156,26 @@ main (int argc, char *argv[]) values_t values; int fd; - static struct option longopts[] = { - {"device", required_argument, 0, 'd'}, - {"immediate", no_argument, 0, 'i'}, - {"quiet-check", no_argument, 0, 'q'}, - {"auto-on", no_argument, 0, '1'}, - {"auto-off", no_argument, 0, '0'}, - {"nagios", no_argument, 0, 'n'}, /* DEPRECATED, but we still accept it */ - {"help", no_argument, 0, 'h'}, - {"version", no_argument, 0, 'V'}, - {0, 0, 0, 0} - }; + static struct option longopts[] = {{"device", required_argument, 0, 'd'}, + {"immediate", no_argument, 0, 'i'}, + {"quiet-check", no_argument, 0, 'q'}, + {"auto-on", no_argument, 0, '1'}, + {"auto-off", no_argument, 0, '0'}, + {"nagios", no_argument, 0, 'n'}, /* DEPRECATED, but we still accept it */ + {"help", no_argument, 0, 'h'}, + {"version", no_argument, 0, 'V'}, + {0, 0, 0, 0}}; /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); while (true) { - - o = getopt_long (argc, argv, "+d:iq10nhVv", longopts, &longindex); + + o = getopt_long(argc, argv, "+d:iq10nhVv", longopts, &longindex); if (o == -1 || o == EOF || o == 1) break; @@ -211,30 +185,30 @@ main (int argc, char *argv[]) device = optarg; break; case 'q': - fprintf (stderr, "%s\n", _("DEPRECATION WARNING: the -q switch (quiet output) is no longer \"quiet\".")); - fprintf (stderr, "%s\n", _("Nagios-compatible output is now always returned.")); + fprintf(stderr, "%s\n", _("DEPRECATION WARNING: the -q switch (quiet output) is no longer \"quiet\".")); + fprintf(stderr, "%s\n", _("Nagios-compatible output is now always returned.")); break; case 'i': case '1': case '0': - printf ("%s\n", _("SMART commands are broken and have been disabled (See Notes in --help).")); + printf("%s\n", _("SMART commands are broken and have been disabled (See Notes in --help).")); return STATE_CRITICAL; break; case 'n': - fprintf (stderr, "%s\n", _("DEPRECATION WARNING: the -n switch (Nagios-compatible output) is now the")); - fprintf (stderr, "%s\n", _("default and will be removed from future releases.")); + fprintf(stderr, "%s\n", _("DEPRECATION WARNING: the -n switch (Nagios-compatible output) is now the")); + fprintf(stderr, "%s\n", _("default and will be removed from future releases.")); break; case 'v': /* verbose */ verbose = true; break; case 'h': - print_help (); + print_help(); return STATE_UNKNOWN; case 'V': - print_revision (progname, NP_VERSION); + print_revision(progname, NP_VERSION); return STATE_UNKNOWN; default: - usage5 (); + usage5(); } } @@ -243,36 +217,33 @@ main (int argc, char *argv[]) } if (!device) { - print_help (); + print_help(); return STATE_UNKNOWN; } - fd = open (device, OPEN_MODE); + fd = open(device, OPEN_MODE); if (fd < 0) { - printf (_("CRITICAL - Couldn't open device %s: %s\n"), device, strerror (errno)); + printf(_("CRITICAL - Couldn't open device %s: %s\n"), device, strerror(errno)); return STATE_CRITICAL; } - if (smart_cmd_simple (fd, SMART_CMD_ENABLE, 0, false)) { - printf (_("CRITICAL - SMART_CMD_ENABLE\n")); + if (smart_cmd_simple(fd, SMART_CMD_ENABLE, 0, false)) { + printf(_("CRITICAL - SMART_CMD_ENABLE\n")); return STATE_CRITICAL; } - smart_read_values (fd, &values); - smart_read_thresholds (fd, &thresholds); - retval = nagios (&values, &thresholds); - if (verbose) print_values (&values, &thresholds); + smart_read_values(fd, &values); + smart_read_thresholds(fd, &thresholds); + retval = nagios(&values, &thresholds); + if (verbose) + print_values(&values, &thresholds); - close (fd); + close(fd); return retval; } - - -char * -get_offline_text (int status) -{ +char *get_offline_text(int status) { int i; for (i = 0; offline_status_text[i].text; i++) { if (offline_status_text[i].value == status) { @@ -282,11 +253,7 @@ get_offline_text (int status) return "UNKNOWN"; } - - -int -smart_read_values (int fd, values_t * values) -{ +int smart_read_values(int fd, values_t *values) { #ifdef __linux__ int e; __u8 args[4 + 512]; @@ -294,12 +261,12 @@ smart_read_values (int fd, values_t * values) args[1] = 0; args[2] = SMART_READ_VALUES; args[3] = 1; - if (ioctl (fd, HDIO_DRIVE_CMD, &args)) { + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) { e = errno; - printf (_("CRITICAL - SMART_READ_VALUES: %s\n"), strerror (errno)); + printf(_("CRITICAL - SMART_READ_VALUES: %s\n"), strerror(errno)); return e; } - memcpy (values, args + 4, 512); + memcpy(values, args + 4, 512); #endif /* __linux__ */ #ifdef __NetBSD__ struct atareq req; @@ -323,7 +290,7 @@ smart_read_values (int fd, values_t * values) if (errno != 0) { int e = errno; - printf (_("CRITICAL - SMART_READ_VALUES: %s\n"), strerror (errno)); + printf(_("CRITICAL - SMART_READ_VALUES: %s\n"), strerror(errno)); return e; } @@ -332,13 +299,9 @@ smart_read_values (int fd, values_t * values) return 0; } - - -int -nagios (values_t * p, thresholds_t * t) -{ - value_t * value = p->values; - threshold_t * threshold = t->thresholds; +int nagios(values_t *p, thresholds_t *t) { + value_t *value = p->values; + threshold_t *threshold = t->thresholds; int status = OPERATIONAL; int prefailure = 0; int advisory = 0; @@ -353,13 +316,11 @@ nagios (values_t * p, thresholds_t * t) if (value->status & 1) { status = PREFAILURE; ++prefailure; - } - else { + } else { status = ADVISORY; ++advisory; } - } - else { + } else { ++passed; } ++total; @@ -369,81 +330,49 @@ nagios (values_t * p, thresholds_t * t) } switch (status) { case PREFAILURE: - printf (_("CRITICAL - %d Harddrive PreFailure%cDetected! %d/%d tests failed.\n"), - prefailure, - prefailure > 1 ? 's' : ' ', - failed, - total); - status=STATE_CRITICAL; + printf(_("CRITICAL - %d Harddrive PreFailure%cDetected! %d/%d tests failed.\n"), prefailure, prefailure > 1 ? 's' : ' ', failed, + total); + status = STATE_CRITICAL; break; case ADVISORY: - printf (_("WARNING - %d Harddrive Advisor%s Detected. %d/%d tests failed.\n"), - advisory, - advisory > 1 ? "ies" : "y", - failed, - total); - status=STATE_WARNING; + printf(_("WARNING - %d Harddrive Advisor%s Detected. %d/%d tests failed.\n"), advisory, advisory > 1 ? "ies" : "y", failed, total); + status = STATE_WARNING; break; case OPERATIONAL: - printf (_("OK - Operational (%d/%d tests passed)\n"), passed, total); - status=STATE_OK; + printf(_("OK - Operational (%d/%d tests passed)\n"), passed, total); + status = STATE_OK; break; default: - printf (_("ERROR - Status '%d' unknown. %d/%d tests passed\n"), status, - passed, total); + printf(_("ERROR - Status '%d' unknown. %d/%d tests passed\n"), status, passed, total); status = STATE_UNKNOWN; break; } return status; } - - -void -print_value (value_t * p, threshold_t * t) -{ - printf ("Id=%3d, Status=%2d {%s , %s}, Value=%3d, Threshold=%3d, %s\n", - p->id, p->status, p->status & 1 ? "PreFailure" : "Advisory ", - p->status & 2 ? "OnLine " : "OffLine", p->value, t->threshold, - p->value >= t->threshold ? "Passed" : "Failed"); +void print_value(value_t *p, threshold_t *t) { + printf("Id=%3d, Status=%2d {%s , %s}, Value=%3d, Threshold=%3d, %s\n", p->id, p->status, p->status & 1 ? "PreFailure" : "Advisory ", + p->status & 2 ? "OnLine " : "OffLine", p->value, t->threshold, p->value >= t->threshold ? "Passed" : "Failed"); } - - -void -print_values (values_t * p, thresholds_t * t) -{ - value_t * value = p->values; - threshold_t * threshold = t->thresholds; +void print_values(values_t *p, thresholds_t *t) { + value_t *value = p->values; + threshold_t *threshold = t->thresholds; int i; for (i = 0; i < NR_ATTRIBUTES; i++) { if (value->id && threshold->id && value->id == threshold->id) { - print_value (value++, threshold++); + print_value(value++, threshold++); } } - printf - (_("OffLineStatus=%d {%s}, AutoOffLine=%s, OffLineTimeout=%d minutes\n"), - p->offline_status, - get_offline_text (p->offline_status & 0x7f), - (p->offline_status & 0x80 ? "Yes" : "No"), - p->offline_timeout / 60); - printf - (_("OffLineCapability=%d {%s %s %s}\n"), - p->offline_capability, - p->offline_capability & 1 ? "Immediate" : "", - p->offline_capability & 2 ? "Auto" : "", - p->offline_capability & 4 ? "AbortOnCmd" : "SuspendOnCmd"); - printf - (_("SmartRevision=%d, CheckSum=%d, SmartCapability=%d {%s %s}\n"), - p->revision, - p->checksum, - p->smart_capability, - p->smart_capability & 1 ? "SaveOnStandBy" : "", - p->smart_capability & 2 ? "AutoSave" : ""); + printf(_("OffLineStatus=%d {%s}, AutoOffLine=%s, OffLineTimeout=%d minutes\n"), p->offline_status, + get_offline_text(p->offline_status & 0x7f), (p->offline_status & 0x80 ? "Yes" : "No"), p->offline_timeout / 60); + printf(_("OffLineCapability=%d {%s %s %s}\n"), p->offline_capability, p->offline_capability & 1 ? "Immediate" : "", + p->offline_capability & 2 ? "Auto" : "", p->offline_capability & 4 ? "AbortOnCmd" : "SuspendOnCmd"); + printf(_("SmartRevision=%d, CheckSum=%d, SmartCapability=%d {%s %s}\n"), p->revision, p->checksum, p->smart_capability, + p->smart_capability & 1 ? "SaveOnStandBy" : "", p->smart_capability & 2 ? "AutoSave" : ""); } - -int smart_cmd_simple (int fd, enum SmartCommand command, __u8 val0, bool show_error) { +int smart_cmd_simple(int fd, enum SmartCommand command, __u8 val0, bool show_error) { int e = STATE_UNKNOWN; #ifdef __linux__ __u8 args[4]; @@ -451,14 +380,14 @@ int smart_cmd_simple (int fd, enum SmartCommand command, __u8 val0, bool show_er args[1] = val0; args[2] = smart_command[command].value; args[3] = 0; - if (ioctl (fd, HDIO_DRIVE_CMD, &args)) { + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) { e = STATE_CRITICAL; if (show_error) - printf (_("CRITICAL - %s: %s\n"), smart_command[command].text, strerror (errno)); + printf(_("CRITICAL - %s: %s\n"), smart_command[command].text, strerror(errno)); } else { e = STATE_OK; if (show_error) - printf (_("OK - Command sent (%s)\n"), smart_command[command].text); + printf(_("OK - Command sent (%s)\n"), smart_command[command].text); } #endif /* __linux__ */ @@ -483,35 +412,31 @@ int smart_cmd_simple (int fd, enum SmartCommand command, __u8 val0, bool show_er if (errno != 0) { e = STATE_CRITICAL; if (show_error) - printf (_("CRITICAL - %s: %s\n"), smart_command[command].text, strerror (errno)); + printf(_("CRITICAL - %s: %s\n"), smart_command[command].text, strerror(errno)); } else { e = STATE_OK; if (show_error) - printf (_("OK - Command sent (%s)\n"), smart_command[command].text); + printf(_("OK - Command sent (%s)\n"), smart_command[command].text); } #endif /* __NetBSD__ */ return e; } - - -int -smart_read_thresholds (int fd, thresholds_t * thresholds) -{ +int smart_read_thresholds(int fd, thresholds_t *thresholds) { #ifdef __linux__ int e; __u8 args[4 + 512]; args[0] = WIN_SMART; - args[1] = 0; - args[2] = SMART_READ_THRESHOLDS; - args[3] = 1; - if (ioctl (fd, HDIO_DRIVE_CMD, &args)) { + args[1] = 0; + args[2] = SMART_READ_THRESHOLDS; + args[3] = 1; + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) { e = errno; - printf (_("CRITICAL - SMART_READ_THRESHOLDS: %s\n"), strerror (errno)); + printf(_("CRITICAL - SMART_READ_THRESHOLDS: %s\n"), strerror(errno)); return e; } - memcpy (thresholds, args + 4, 512); + memcpy(thresholds, args + 4, 512); #endif /* __linux__ */ #ifdef __NetBSD__ struct atareq req; @@ -535,7 +460,7 @@ smart_read_thresholds (int fd, thresholds_t * thresholds) if (errno != 0) { int e = errno; - printf (_("CRITICAL - SMART_READ_THRESHOLDS: %s\n"), strerror (errno)); + printf(_("CRITICAL - SMART_READ_THRESHOLDS: %s\n"), strerror(errno)); return e; } @@ -544,45 +469,43 @@ smart_read_thresholds (int fd, thresholds_t * thresholds) return 0; } +void print_help(void) { + print_revision(progname, NP_VERSION); -void -print_help (void) -{ - print_revision (progname, NP_VERSION); + printf("(C) 1999 Ragnar Hojland Espinosa \n"); + printf("Plugin implementation - 1999 Robert Dale \n"); + printf(COPYRIGHT, copyright, email); - printf ("(C) 1999 Ragnar Hojland Espinosa \n"); - printf ("Plugin implementation - 1999 Robert Dale \n"); - printf (COPYRIGHT, copyright, email); + printf(_("This plugin checks a local hard drive with the (Linux specific) SMART interface " + "[http://smartlinux.sourceforge.net/smart/index.php].")); - printf (_("This plugin checks a local hard drive with the (Linux specific) SMART interface [http://smartlinux.sourceforge.net/smart/index.php].")); + printf("\n\n"); - printf ("\n\n"); + print_usage(); - print_usage (); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); + printf(" %s\n", "-d, --device=DEVICE"); + printf(" %s\n", _("Select device DEVICE")); + printf(" %s\n", _("Note: if the device is specified without this option, any further option will")); + printf(" %s\n", _("be ignored.")); - printf (" %s\n", "-d, --device=DEVICE"); - printf (" %s\n", _("Select device DEVICE")); - printf (" %s\n", _("Note: if the device is specified without this option, any further option will")); - printf (" %s\n", _("be ignored.")); + printf(UT_VERBOSE); - printf (UT_VERBOSE); + printf("\n"); + printf("%s\n", _("Notes:")); + printf(" %s\n", _("The SMART command modes (-i/--immediate, -0/--auto-off and -1/--auto-on) were")); + printf(" %s\n", _("broken in an underhand manner and have been disabled. You can use smartctl")); + printf(" %s\n", _("instead:")); + printf(" %s\n", _("-0/--auto-off: use \"smartctl --offlineauto=off\"")); + printf(" %s\n", _("-1/--auto-on: use \"smartctl --offlineauto=on\"")); + printf(" %s\n", _("-i/--immediate: use \"smartctl --test=offline\"")); - printf ("\n"); - printf ("%s\n", _("Notes:")); - printf (" %s\n", _("The SMART command modes (-i/--immediate, -0/--auto-off and -1/--auto-on) were")); - printf (" %s\n", _("broken in an underhand manner and have been disabled. You can use smartctl")); - printf (" %s\n", _("instead:")); - printf (" %s\n", _("-0/--auto-off: use \"smartctl --offlineauto=off\"")); - printf (" %s\n", _("-1/--auto-on: use \"smartctl --offlineauto=on\"")); - printf (" %s\n", _("-i/--immediate: use \"smartctl --test=offline\"")); - - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - /* todo : add to the long nanual as example +/* todo : add to the long nanual as example * * Run with: check_ide-smart --nagios [-d] * Where DRIVE is an IDE drive, ie. /dev/hda, /dev/hdb, /dev/hdc @@ -593,10 +516,7 @@ print_help (void) * - Returns -1 not too often */ - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s [-d ] [-v]", progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s [-d ] [-v]", progname); } -- cgit v0.10-9-g596f From c16bc4024caed74a3ceb9168c7e50ce3ad09dacb Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:49:17 +0100 Subject: check_ide_smart: update copyright diff --git a/plugins/check_ide_smart.c b/plugins/check_ide_smart.c index 00d9eb3..550cd98 100644 --- a/plugins/check_ide_smart.c +++ b/plugins/check_ide_smart.c @@ -7,7 +7,7 @@ * Copyright (C) 1998-1999 Ragnar Hojland Espinosa * 1998 Gadi Oxman * Copyright (c) 2000 Robert Dale - * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -34,7 +34,7 @@ *****************************************************************************/ const char *progname = "check_ide_smart"; -const char *copyright = "1998-2007"; +const char *copyright = "1998-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 5c6d79dac31b55d78fcbb10c48ab357574307bc0 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:51:37 +0100 Subject: check_ide_smart: do not export local symbols diff --git a/plugins/check_ide_smart.c b/plugins/check_ide_smart.c index 550cd98..fc75e53 100644 --- a/plugins/check_ide_smart.c +++ b/plugins/check_ide_smart.c @@ -40,7 +40,7 @@ const char *email = "devel@monitoring-plugins.org"; #include "common.h" #include "utils.h" -void print_help(void); +static void print_help(void); void print_usage(void); #include @@ -118,14 +118,12 @@ struct { char *text; } -offline_status_text[] = {{0x00, "NeverStarted"}, {0x02, "Completed"}, {0x04, "Suspended"}, {0x05, "Aborted"}, {0x06, "Failed"}, {0, 0}}; +static offline_status_text[] = {{0x00, "NeverStarted"}, {0x02, "Completed"}, {0x04, "Suspended"}, {0x05, "Aborted"}, {0x06, "Failed"}, {0, 0}}; -struct { +static struct { __u8 value; char *text; -} - -smart_command[] = {{SMART_ENABLE, "SMART_ENABLE"}, +} smart_command[] = {{SMART_ENABLE, "SMART_ENABLE"}, {SMART_DISABLE, "SMART_DISABLE"}, {SMART_IMMEDIATE_OFFLINE, "SMART_IMMEDIATE_OFFLINE"}, {SMART_AUTO_OFFLINE, "SMART_AUTO_OFFLINE"}}; @@ -138,14 +136,14 @@ enum SmartCommand { SMART_CMD_AUTO_OFFLINE }; -char *get_offline_text(int); -int smart_read_values(int, values_t *); -int nagios(values_t *, thresholds_t *); -void print_value(value_t *, threshold_t *); -void print_values(values_t *, thresholds_t *); -int smart_cmd_simple(int, enum SmartCommand, __u8, bool); -int smart_read_thresholds(int, thresholds_t *); -bool verbose = false; +static char *get_offline_text(int); +static int smart_read_values(int, values_t *); +static int nagios(values_t *, thresholds_t *); +static void print_value(value_t *, threshold_t *); +static void print_values(values_t *, thresholds_t *); +static int smart_cmd_simple(int, enum SmartCommand, __u8, bool); +static int smart_read_thresholds(int, thresholds_t *); +static bool verbose = false; int main(int argc, char *argv[]) { char *device = NULL; -- cgit v0.10-9-g596f From 4db8808a5120778004b8ade834f30d0f4b3db914 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:52:36 +0100 Subject: check_ide_smart: linter fixes diff --git a/plugins/check_ide_smart.c b/plugins/check_ide_smart.c index fc75e53..cfc7908 100644 --- a/plugins/check_ide_smart.c +++ b/plugins/check_ide_smart.c @@ -147,7 +147,8 @@ static bool verbose = false; int main(int argc, char *argv[]) { char *device = NULL; - int o, longindex; + int o; + int longindex; int retval = 0; thresholds_t thresholds; -- cgit v0.10-9-g596f From cc45c9772b4a7df9cd2231fa8f36c33ca09495a7 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 12:15:15 +0100 Subject: check_mrtg: clang-format diff --git a/plugins/check_mrtg.c b/plugins/check_mrtg.c index 826b77e..e4d3243 100644 --- a/plugins/check_mrtg.c +++ b/plugins/check_mrtg.c @@ -1,33 +1,33 @@ /***************************************************************************** -* -* Monitoring check_mrtg plugin -* -* License: GPL -* Copyright (c) 1999-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_mrtg plugin -* -* This plugin will check either the average or maximum value of one of the -* two variables recorded in an MRTG log file. -* -* -* 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_mrtg plugin + * + * License: GPL + * Copyright (c) 1999-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_mrtg plugin + * + * This plugin will check either the average or maximum value of one of the + * two variables recorded in an MRTG log file. + * + * + * 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_mrtg"; const char *copyright = "1999-2007"; @@ -36,10 +36,10 @@ const char *email = "devel@monitoring-plugins.org"; #include "common.h" #include "utils.h" -int process_arguments (int, char **); -int validate_arguments (void); -void print_help (void); -void print_usage (void); +int process_arguments(int, char **); +int validate_arguments(void); +void print_help(void); +void print_usage(void); char *log_file = NULL; int expire_minutes = 0; @@ -50,9 +50,7 @@ unsigned long value_critical_threshold = 0L; char *label; char *units; -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { int result = STATE_OK; FILE *fp; int line; @@ -64,25 +62,25 @@ main (int argc, char **argv) unsigned long maximum_value_rate = 0L; unsigned long rate = 0L; - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if (process_arguments (argc, argv) == ERROR) - usage4 (_("Could not parse arguments\n")); + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments\n")); /* open the MRTG log file for reading */ - fp = fopen (log_file, "r"); + fp = fopen(log_file, "r"); if (fp == NULL) { - printf (_("Unable to open MRTG log file\n")); + printf(_("Unable to open MRTG log file\n")); return STATE_UNKNOWN; } line = 0; - while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) { + while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, fp)) { line++; @@ -95,45 +93,43 @@ main (int argc, char **argv) break; /* grab the timestamp */ - temp_buffer = strtok (input_buffer, " "); - timestamp = strtoul (temp_buffer, NULL, 10); + temp_buffer = strtok(input_buffer, " "); + timestamp = strtoul(temp_buffer, NULL, 10); /* grab the average value 1 rate */ - temp_buffer = strtok (NULL, " "); + temp_buffer = strtok(NULL, " "); if (variable_number == 1) - average_value_rate = strtoul (temp_buffer, NULL, 10); + average_value_rate = strtoul(temp_buffer, NULL, 10); /* grab the average value 2 rate */ - temp_buffer = strtok (NULL, " "); + temp_buffer = strtok(NULL, " "); if (variable_number == 2) - average_value_rate = strtoul (temp_buffer, NULL, 10); + average_value_rate = strtoul(temp_buffer, NULL, 10); /* grab the maximum value 1 rate */ - temp_buffer = strtok (NULL, " "); + temp_buffer = strtok(NULL, " "); if (variable_number == 1) - maximum_value_rate = strtoul (temp_buffer, NULL, 10); + maximum_value_rate = strtoul(temp_buffer, NULL, 10); /* grab the maximum value 2 rate */ - temp_buffer = strtok (NULL, " "); + temp_buffer = strtok(NULL, " "); if (variable_number == 2) - maximum_value_rate = strtoul (temp_buffer, NULL, 10); + maximum_value_rate = strtoul(temp_buffer, NULL, 10); } /* close the log file */ - fclose (fp); + fclose(fp); /* if we couldn't read enough data, return an unknown error */ if (line <= 2) { - printf (_("Unable to process MRTG log file\n")); + printf(_("Unable to process MRTG log file\n")); return STATE_UNKNOWN; } /* make sure the MRTG data isn't too old */ - time (¤t_time); - if (expire_minutes > 0 - && (current_time - timestamp) > (expire_minutes * 60)) { - printf (_("MRTG data has expired (%d minutes old)\n"), - (int) ((current_time - timestamp) / 60)); + time(¤t_time); + if (expire_minutes > 0 && (current_time - timestamp) > (expire_minutes * 60)) { + printf(_("MRTG data has expired (%d minutes old)\n"), (int)((current_time - timestamp) / 60)); return STATE_WARNING; } @@ -148,98 +144,80 @@ main (int argc, char **argv) else if (rate > value_warning_threshold) result = STATE_WARNING; - printf("%s. %s = %lu %s|%s\n", - (use_average) ? _("Avg") : _("Max"), - label, rate, units, - perfdata(label, (long) rate, units, - (int) value_warning_threshold, (long) value_warning_threshold, - (int) value_critical_threshold, (long) value_critical_threshold, - 0, 0, 0, 0)); + printf("%s. %s = %lu %s|%s\n", (use_average) ? _("Avg") : _("Max"), label, rate, units, + perfdata(label, (long)rate, units, (int)value_warning_threshold, (long)value_warning_threshold, (int)value_critical_threshold, + (long)value_critical_threshold, 0, 0, 0, 0)); return result; } - - /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ +int process_arguments(int argc, char **argv) { int c; int option = 0; static struct option longopts[] = { - {"logfile", required_argument, 0, 'F'}, - {"expires", required_argument, 0, 'e'}, - {"aggregation", required_argument, 0, 'a'}, - {"variable", required_argument, 0, 'v'}, - {"critical", required_argument, 0, 'c'}, - {"warning", required_argument, 0, 'w'}, - {"label", required_argument, 0, 'l'}, - {"units", required_argument, 0, 'u'}, - {"variable", required_argument, 0, 'v'}, - {"version", no_argument, 0, 'V'}, - {"help", no_argument, 0, 'h'}, - {0, 0, 0, 0} - }; + {"logfile", required_argument, 0, 'F'}, {"expires", required_argument, 0, 'e'}, {"aggregation", required_argument, 0, 'a'}, + {"variable", required_argument, 0, 'v'}, {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, + {"label", required_argument, 0, 'l'}, {"units", required_argument, 0, 'u'}, {"variable", required_argument, 0, 'v'}, + {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0}}; if (argc < 2) return ERROR; for (c = 1; c < argc; c++) { - if (strcmp ("-to", argv[c]) == 0) - strcpy (argv[c], "-t"); - else if (strcmp ("-wt", argv[c]) == 0) - strcpy (argv[c], "-w"); - else if (strcmp ("-ct", argv[c]) == 0) - strcpy (argv[c], "-c"); + if (strcmp("-to", argv[c]) == 0) + strcpy(argv[c], "-t"); + else if (strcmp("-wt", argv[c]) == 0) + strcpy(argv[c], "-w"); + else if (strcmp("-ct", argv[c]) == 0) + strcpy(argv[c], "-c"); } while (1) { - c = getopt_long (argc, argv, "hVF:e:a:v:c:w:l:u:", longopts, - &option); + c = getopt_long(argc, argv, "hVF:e:a:v:c:w:l:u:", longopts, &option); if (c == -1 || c == EOF) break; switch (c) { - case 'F': /* input file */ + case 'F': /* input file */ log_file = optarg; break; - case 'e': /* ups name */ - expire_minutes = atoi (optarg); + case 'e': /* ups name */ + expire_minutes = atoi(optarg); break; - case 'a': /* port */ - if (!strcmp (optarg, "MAX")) + case 'a': /* port */ + if (!strcmp(optarg, "MAX")) use_average = false; else use_average = true; break; case 'v': - variable_number = atoi (optarg); + variable_number = atoi(optarg); if (variable_number < 1 || variable_number > 2) - usage4 (_("Invalid variable number")); + usage4(_("Invalid variable number")); break; - case 'w': /* critical time threshold */ - value_warning_threshold = strtoul (optarg, NULL, 10); + case 'w': /* critical time threshold */ + value_warning_threshold = strtoul(optarg, NULL, 10); break; - case 'c': /* warning time threshold */ - value_critical_threshold = strtoul (optarg, NULL, 10); + case 'c': /* warning time threshold */ + value_critical_threshold = strtoul(optarg, NULL, 10); break; - case 'l': /* label */ + case 'l': /* label */ label = optarg; break; - case 'u': /* timeout */ + case 'u': /* timeout */ units = optarg; break; - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case '?': /* help */ - usage5 (); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case '?': /* help */ + usage5(); } } @@ -249,137 +227,124 @@ process_arguments (int argc, char **argv) } if (expire_minutes <= 0 && argc > c) { - if (is_intpos (argv[c])) - expire_minutes = atoi (argv[c++]); + if (is_intpos(argv[c])) + expire_minutes = atoi(argv[c++]); else - die (STATE_UNKNOWN, - _("%s is not a valid expiration time\nUse '%s -h' for additional help\n"), - argv[c], progname); + die(STATE_UNKNOWN, _("%s is not a valid expiration time\nUse '%s -h' for additional help\n"), argv[c], progname); } - if (argc > c && strcmp (argv[c], "MAX") == 0) { + if (argc > c && strcmp(argv[c], "MAX") == 0) { use_average = false; c++; - } - else if (argc > c && strcmp (argv[c], "AVG") == 0) { + } else if (argc > c && strcmp(argv[c], "AVG") == 0) { use_average = true; c++; } if (argc > c && variable_number == -1) { - variable_number = atoi (argv[c++]); + variable_number = atoi(argv[c++]); if (variable_number < 1 || variable_number > 2) { - printf ("%s :", argv[c]); - usage (_("Invalid variable number\n")); + printf("%s :", argv[c]); + usage(_("Invalid variable number\n")); } } if (argc > c && value_warning_threshold == 0) { - value_warning_threshold = strtoul (argv[c++], NULL, 10); + value_warning_threshold = strtoul(argv[c++], NULL, 10); } if (argc > c && value_critical_threshold == 0) { - value_critical_threshold = strtoul (argv[c++], NULL, 10); + value_critical_threshold = strtoul(argv[c++], NULL, 10); } - if (argc > c && strlen (label) == 0) { + if (argc > c && strlen(label) == 0) { label = argv[c++]; } - if (argc > c && strlen (units) == 0) { + if (argc > c && strlen(units) == 0) { units = argv[c++]; } - return validate_arguments (); + return validate_arguments(); } -int -validate_arguments (void) -{ +int validate_arguments(void) { if (variable_number == -1) - usage4 (_("You must supply the variable number")); + usage4(_("You must supply the variable number")); if (label == NULL) - label = strdup ("value"); + label = strdup("value"); if (units == NULL) - units = strdup (""); + units = strdup(""); return OK; } - - -void -print_help (void) -{ - print_revision (progname, NP_VERSION); - - printf ("Copyright (c) 1999 Ethan Galstad \n"); - printf (COPYRIGHT, copyright, email); - - printf ("%s\n", _("This plugin will check either the average or maximum value of one of the")); - printf ("%s\n", _("two variables recorded in an MRTG log file.")); - - printf ("\n\n"); - - print_usage (); - - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); - - printf (" %s\n", "-F, --logfile=FILE"); - printf (" %s\n", _("The MRTG log file containing the data you want to monitor")); - printf (" %s\n", "-e, --expires=MINUTES"); - printf (" %s\n", _("Minutes before MRTG data is considered to be too old")); - printf (" %s\n", "-a, --aggregation=AVG|MAX"); - printf (" %s\n", _("Should we check average or maximum values?")); - printf (" %s\n", "-v, --variable=INTEGER"); - printf (" %s\n", _("Which variable set should we inspect? (1 or 2)")); - printf (" %s\n", "-w, --warning=INTEGER"); - printf (" %s\n", _("Threshold value for data to result in WARNING status")); - printf (" %s\n", "-c, --critical=INTEGER"); - printf (" %s\n", _("Threshold value for data to result in CRITICAL status")); - printf (" %s\n", "-l, --label=STRING"); - printf (" %s\n", _("Type label for data (Examples: Conns, \"Processor Load\", In, Out)")); - printf (" %s\n", "-u, --units=STRING"); - printf (" %s\n", _("Option units label for data (Example: Packets/Sec, Errors/Sec,")); - printf (" %s\n", _("\"Bytes Per Second\", \"%% Utilization\")")); - - printf ("\n"); - printf (" %s\n", _("If the value exceeds the threshold, a WARNING status is returned. If")); - printf (" %s\n", _("the value exceeds the threshold, a CRITICAL status is returned. If")); - printf (" %s\n", _("the data in the log file is older than old, a WARNING")); - printf (" %s\n", _("status is returned and a warning message is printed.")); - - printf ("\n"); - printf (" %s\n", _("This plugin is useful for monitoring MRTG data that does not correspond to")); - printf (" %s\n", _("bandwidth usage. (Use the check_mrtgtraf plugin for monitoring bandwidth).")); - printf (" %s\n", _("It can be used to monitor any kind of data that MRTG is monitoring - errors,")); - printf (" %s\n", _("packets/sec, etc. I use MRTG in conjunction with the Novell NLM that allows")); - printf (" %s\n", _("me to track processor utilization, user connections, drive space, etc and")); - printf (" %s\n\n", _("this plugin works well for monitoring that kind of data as well.")); - - printf ("%s\n", _("Notes:")); - printf (" %s\n", _("- This plugin only monitors one of the two variables stored in the MRTG log")); - printf (" %s\n", _("file. If you want to monitor both values you will have to define two")); - printf (" %s\n", _("commands with different values for the argument. Of course,")); - printf (" %s\n", _("you can always hack the code to make this plugin work for you...")); - printf (" %s\n", _("- MRTG stands for the Multi Router Traffic Grapher. It can be downloaded from")); - printf (" %s\n", "http://ee-staff.ethz.ch/~oetiker/webtools/mrtg/mrtg.html"); - - printf (UT_SUPPORT); +void print_help(void) { + print_revision(progname, NP_VERSION); + + printf("Copyright (c) 1999 Ethan Galstad \n"); + printf(COPYRIGHT, copyright, email); + + printf("%s\n", _("This plugin will check either the average or maximum value of one of the")); + printf("%s\n", _("two variables recorded in an MRTG log file.")); + + printf("\n\n"); + + print_usage(); + + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); + + printf(" %s\n", "-F, --logfile=FILE"); + printf(" %s\n", _("The MRTG log file containing the data you want to monitor")); + printf(" %s\n", "-e, --expires=MINUTES"); + printf(" %s\n", _("Minutes before MRTG data is considered to be too old")); + printf(" %s\n", "-a, --aggregation=AVG|MAX"); + printf(" %s\n", _("Should we check average or maximum values?")); + printf(" %s\n", "-v, --variable=INTEGER"); + printf(" %s\n", _("Which variable set should we inspect? (1 or 2)")); + printf(" %s\n", "-w, --warning=INTEGER"); + printf(" %s\n", _("Threshold value for data to result in WARNING status")); + printf(" %s\n", "-c, --critical=INTEGER"); + printf(" %s\n", _("Threshold value for data to result in CRITICAL status")); + printf(" %s\n", "-l, --label=STRING"); + printf(" %s\n", _("Type label for data (Examples: Conns, \"Processor Load\", In, Out)")); + printf(" %s\n", "-u, --units=STRING"); + printf(" %s\n", _("Option units label for data (Example: Packets/Sec, Errors/Sec,")); + printf(" %s\n", _("\"Bytes Per Second\", \"%% Utilization\")")); + + printf("\n"); + printf(" %s\n", _("If the value exceeds the threshold, a WARNING status is returned. If")); + printf(" %s\n", _("the value exceeds the threshold, a CRITICAL status is returned. If")); + printf(" %s\n", _("the data in the log file is older than old, a WARNING")); + printf(" %s\n", _("status is returned and a warning message is printed.")); + + printf("\n"); + printf(" %s\n", _("This plugin is useful for monitoring MRTG data that does not correspond to")); + printf(" %s\n", _("bandwidth usage. (Use the check_mrtgtraf plugin for monitoring bandwidth).")); + printf(" %s\n", _("It can be used to monitor any kind of data that MRTG is monitoring - errors,")); + printf(" %s\n", _("packets/sec, etc. I use MRTG in conjunction with the Novell NLM that allows")); + printf(" %s\n", _("me to track processor utilization, user connections, drive space, etc and")); + printf(" %s\n\n", _("this plugin works well for monitoring that kind of data as well.")); + + printf("%s\n", _("Notes:")); + printf(" %s\n", _("- This plugin only monitors one of the two variables stored in the MRTG log")); + printf(" %s\n", _("file. If you want to monitor both values you will have to define two")); + printf(" %s\n", _("commands with different values for the argument. Of course,")); + printf(" %s\n", _("you can always hack the code to make this plugin work for you...")); + printf(" %s\n", _("- MRTG stands for the Multi Router Traffic Grapher. It can be downloaded from")); + printf(" %s\n", "http://ee-staff.ethz.ch/~oetiker/webtools/mrtg/mrtg.html"); + + printf(UT_SUPPORT); } - - /* original command line: -@@ ******************************************************************************/ - - -int -validate_arguments () -{ - return OK; -} +int validate_arguments() { return OK; } /** @@ -437,10 +403,8 @@ should be added. -@@ ******************************************************************************/ - - -bool is_pg_logname (char *username) { - if (strlen (username) > NAMEDATALEN - 1) +bool is_pg_logname(char *username) { + if (strlen(username) > NAMEDATALEN - 1) return (false); return (true); } @@ -453,108 +417,98 @@ bool is_pg_logname (char *username) { -@@ ******************************************************************************/ - - -void -print_help (void) -{ +void print_help(void) { char *myport; - xasprintf (&myport, "%d", DEFAULT_PORT); + xasprintf(&myport, "%d", DEFAULT_PORT); - print_revision (progname, NP_VERSION); + print_revision(progname, NP_VERSION); - printf (COPYRIGHT, copyright, email); + printf(COPYRIGHT, copyright, email); - printf (_("Test whether a PostgreSQL Database is accepting connections.")); + printf(_("Test whether a PostgreSQL Database is accepting connections.")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); - printf (UT_HOST_PORT, 'P', myport); + printf(UT_HOST_PORT, 'P', myport); - printf (" %s\n", "-d, --database=STRING"); - printf (" %s", _("Database to check ")); - printf (_("(default: %s)\n"), DEFAULT_DB); - printf (" %s\n", "-l, --logname = STRING"); - printf (" %s\n", _("Login name of user")); - printf (" %s\n", "-p, --password = STRING"); - printf (" %s\n", _("Password (BIG SECURITY ISSUE)")); - printf (" %s\n", "-o, --option = STRING"); - printf (" %s\n", _("Connection parameters (keyword = value), see below")); + printf(" %s\n", "-d, --database=STRING"); + printf(" %s", _("Database to check ")); + printf(_("(default: %s)\n"), DEFAULT_DB); + printf(" %s\n", "-l, --logname = STRING"); + printf(" %s\n", _("Login name of user")); + printf(" %s\n", "-p, --password = STRING"); + printf(" %s\n", _("Password (BIG SECURITY ISSUE)")); + printf(" %s\n", "-o, --option = STRING"); + printf(" %s\n", _("Connection parameters (keyword = value), see below")); - printf (UT_WARN_CRIT); + printf(UT_WARN_CRIT); - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - printf (" %s\n", "-q, --query=STRING"); - printf (" %s\n", _("SQL query to run. Only first column in first row will be read")); - printf (" %s\n", "--queryname=STRING"); - printf (" %s\n", _("A name for the query, this string is used instead of the query")); - printf (" %s\n", _("in the long output of the plugin")); - printf (" %s\n", "-W, --query-warning=RANGE"); - printf (" %s\n", _("SQL query value to result in warning status (double)")); - printf (" %s\n", "-C, --query-critical=RANGE"); - printf (" %s\n", _("SQL query value to result in critical status (double)")); + printf(" %s\n", "-q, --query=STRING"); + printf(" %s\n", _("SQL query to run. Only first column in first row will be read")); + printf(" %s\n", "--queryname=STRING"); + printf(" %s\n", _("A name for the query, this string is used instead of the query")); + printf(" %s\n", _("in the long output of the plugin")); + printf(" %s\n", "-W, --query-warning=RANGE"); + printf(" %s\n", _("SQL query value to result in warning status (double)")); + printf(" %s\n", "-C, --query-critical=RANGE"); + printf(" %s\n", _("SQL query value to result in critical status (double)")); - printf (UT_VERBOSE); + printf(UT_VERBOSE); - printf ("\n"); - printf (" %s\n", _("All parameters are optional.")); - printf (" %s\n", _("This plugin tests a PostgreSQL DBMS to determine whether it is active and")); - printf (" %s\n", _("accepting queries. In its current operation, it simply connects to the")); - printf (" %s\n", _("specified database, and then disconnects. If no database is specified, it")); - printf (" %s\n", _("connects to the template1 database, which is present in every functioning")); - printf (" %s\n\n", _("PostgreSQL DBMS.")); + printf("\n"); + printf(" %s\n", _("All parameters are optional.")); + printf(" %s\n", _("This plugin tests a PostgreSQL DBMS to determine whether it is active and")); + printf(" %s\n", _("accepting queries. In its current operation, it simply connects to the")); + printf(" %s\n", _("specified database, and then disconnects. If no database is specified, it")); + printf(" %s\n", _("connects to the template1 database, which is present in every functioning")); + printf(" %s\n\n", _("PostgreSQL DBMS.")); - printf (" %s\n", _("If a query is specified using the -q option, it will be executed after")); - printf (" %s\n", _("connecting to the server. The result from the query has to be numeric.")); - printf (" %s\n", _("Multiple SQL commands, separated by semicolon, are allowed but the result ")); - printf (" %s\n", _("of the last command is taken into account only. The value of the first")); - printf (" %s\n", _("column in the first row is used as the check result. If a second column is")); - printf (" %s\n", _("present in the result set, this is added to the plugin output with a")); - printf (" %s\n", _("prefix of \"Extra Info:\". This information can be displayed in the system")); - printf (" %s\n\n", _("executing the plugin.")); + printf(" %s\n", _("If a query is specified using the -q option, it will be executed after")); + printf(" %s\n", _("connecting to the server. The result from the query has to be numeric.")); + printf(" %s\n", _("Multiple SQL commands, separated by semicolon, are allowed but the result ")); + printf(" %s\n", _("of the last command is taken into account only. The value of the first")); + printf(" %s\n", _("column in the first row is used as the check result. If a second column is")); + printf(" %s\n", _("present in the result set, this is added to the plugin output with a")); + printf(" %s\n", _("prefix of \"Extra Info:\". This information can be displayed in the system")); + printf(" %s\n\n", _("executing the plugin.")); - printf (" %s\n", _("See the chapter \"Monitoring Database Activity\" of the PostgreSQL manual")); - printf (" %s\n\n", _("for details about how to access internal statistics of the database server.")); + printf(" %s\n", _("See the chapter \"Monitoring Database Activity\" of the PostgreSQL manual")); + printf(" %s\n\n", _("for details about how to access internal statistics of the database server.")); - printf (" %s\n", _("For a list of available connection parameters which may be used with the -o")); - printf (" %s\n", _("command line option, see the documentation for PQconnectdb() in the chapter")); - printf (" %s\n", _("\"libpq - C Library\" of the PostgreSQL manual. For example, this may be")); - printf (" %s\n", _("used to specify a service name in pg_service.conf to be used for additional")); - printf (" %s\n", _("connection parameters: -o 'service=' or to specify the SSL mode:")); - printf (" %s\n\n", _("-o 'sslmode=require'.")); + printf(" %s\n", _("For a list of available connection parameters which may be used with the -o")); + printf(" %s\n", _("command line option, see the documentation for PQconnectdb() in the chapter")); + printf(" %s\n", _("\"libpq - C Library\" of the PostgreSQL manual. For example, this may be")); + printf(" %s\n", _("used to specify a service name in pg_service.conf to be used for additional")); + printf(" %s\n", _("connection parameters: -o 'service=' or to specify the SSL mode:")); + printf(" %s\n\n", _("-o 'sslmode=require'.")); - printf (" %s\n", _("The plugin will connect to a local postmaster if no host is specified. To")); - printf (" %s\n", _("connect to a remote host, be sure that the remote postmaster accepts TCP/IP")); - printf (" %s\n\n", _("connections (start the postmaster with the -i option).")); + printf(" %s\n", _("The plugin will connect to a local postmaster if no host is specified. To")); + printf(" %s\n", _("connect to a remote host, be sure that the remote postmaster accepts TCP/IP")); + printf(" %s\n\n", _("connections (start the postmaster with the -i option).")); - printf (" %s\n", _("Typically, the monitoring user (unless the --logname option is used) should be")); - printf (" %s\n", _("able to connect to the database without a password. The plugin can also send")); - printf (" %s\n", _("a password, but no effort is made to obscure or encrypt the password.")); + printf(" %s\n", _("Typically, the monitoring user (unless the --logname option is used) should be")); + printf(" %s\n", _("able to connect to the database without a password. The plugin can also send")); + printf(" %s\n", _("a password, but no effort is made to obscure or encrypt the password.")); - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s [-H ] [-P ] [-c ] [-w ]\n", progname); - printf (" [-t ] [-d ] [-l ] [-p ]\n" - "[-q ] [-C ] [-W ]\n"); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s [-H ] [-P ] [-c ] [-w ]\n", progname); + printf(" [-t ] [-d ] [-l ] [-p ]\n" + "[-q ] [-C ] [-W ]\n"); } -int -do_query (PGconn *conn, char *query) -{ +int do_query(PGconn *conn, char *query) { PGresult *res; char *val_str; @@ -566,69 +520,59 @@ do_query (PGconn *conn, char *query) int my_status = STATE_UNKNOWN; if (verbose) - printf ("Executing SQL query \"%s\".\n", query); - res = PQexec (conn, query); + printf("Executing SQL query \"%s\".\n", query); + res = PQexec(conn, query); - if (PGRES_TUPLES_OK != PQresultStatus (res)) { - printf (_("QUERY %s - %s: %s.\n"), _("CRITICAL"), _("Error with query"), - PQerrorMessage (conn)); + if (PGRES_TUPLES_OK != PQresultStatus(res)) { + printf(_("QUERY %s - %s: %s.\n"), _("CRITICAL"), _("Error with query"), PQerrorMessage(conn)); return STATE_CRITICAL; } - if (PQntuples (res) < 1) { - printf ("QUERY %s - %s.\n", _("WARNING"), _("No rows returned")); + if (PQntuples(res) < 1) { + printf("QUERY %s - %s.\n", _("WARNING"), _("No rows returned")); return STATE_WARNING; } - if (PQnfields (res) < 1) { - printf ("QUERY %s - %s.\n", _("WARNING"), _("No columns returned")); + if (PQnfields(res) < 1) { + printf("QUERY %s - %s.\n", _("WARNING"), _("No columns returned")); return STATE_WARNING; } - val_str = PQgetvalue (res, 0, 0); - if (! val_str) { - printf ("QUERY %s - %s.\n", _("CRITICAL"), _("No data returned")); + val_str = PQgetvalue(res, 0, 0); + if (!val_str) { + printf("QUERY %s - %s.\n", _("CRITICAL"), _("No data returned")); return STATE_CRITICAL; } - value = strtod (val_str, &endptr); + value = strtod(val_str, &endptr); if (verbose) - printf ("Query result: %f\n", value); + printf("Query result: %f\n", value); if (endptr == val_str) { - printf ("QUERY %s - %s: %s\n", _("CRITICAL"), _("Is not a numeric"), val_str); + printf("QUERY %s - %s: %s\n", _("CRITICAL"), _("Is not a numeric"), val_str); return STATE_CRITICAL; - } - else if ((endptr != NULL) && (*endptr != '\0')) { + } else if ((endptr != NULL) && (*endptr != '\0')) { if (verbose) - printf ("Garbage after value: %s.\n", endptr); + printf("Garbage after value: %s.\n", endptr); } - my_status = get_status (value, qthresholds); - printf ("QUERY %s - ", - (my_status == STATE_OK) - ? _("OK") - : (my_status == STATE_WARNING) - ? _("WARNING") - : (my_status == STATE_CRITICAL) - ? _("CRITICAL") - : _("UNKNOWN")); - if(pgqueryname) { - printf (_("%s returned %f"), pgqueryname, value); - } - else { - printf (_("'%s' returned %f"), query, value); + my_status = get_status(value, qthresholds); + printf("QUERY %s - ", (my_status == STATE_OK) ? _("OK") + : (my_status == STATE_WARNING) ? _("WARNING") + : (my_status == STATE_CRITICAL) ? _("CRITICAL") + : _("UNKNOWN")); + if (pgqueryname) { + printf(_("%s returned %f"), pgqueryname, value); + } else { + printf(_("'%s' returned %f"), query, value); } - printf ("|query=%f;%s;%s;;\n", value, - query_warning ? query_warning : "", - query_critical ? query_critical : ""); - if (PQnfields (res) > 1) { - extra_info = PQgetvalue (res, 0, 1); + printf("|query=%f;%s;%s;;\n", value, query_warning ? query_warning : "", query_critical ? query_critical : ""); + if (PQnfields(res) > 1) { + extra_info = PQgetvalue(res, 0, 1); if (extra_info != NULL) { - printf ("Extra Info: %s\n", extra_info); + printf("Extra Info: %s\n", extra_info); } } return my_status; } - -- cgit v0.10-9-g596f From cc63bc669977ed29fe2c457218ac51cdd3e121dd Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 13:25:30 +0100 Subject: check_pgsql: update copyright diff --git a/plugins/check_pgsql.c b/plugins/check_pgsql.c index 3ca3d20..76ed183 100644 --- a/plugins/check_pgsql.c +++ b/plugins/check_pgsql.c @@ -3,7 +3,7 @@ * Monitoring check_pgsql plugin * * License: GPL - * Copyright (c) 1999-2011 Monitoring Plugins Development Team + * Copyright (c) 1999-2024 Monitoring Plugins Development Team * * Description: * @@ -29,7 +29,7 @@ *****************************************************************************/ const char *progname = "check_pgsql"; -const char *copyright = "1999-2011"; +const char *copyright = "1999-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From daf37fbd6700cb67cb15ce5267d370423d3815ea Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 13:26:56 +0100 Subject: check_pgsql: do not export local variables diff --git a/plugins/check_pgsql.c b/plugins/check_pgsql.c index 76ed183..a6411a5 100644 --- a/plugins/check_pgsql.c +++ b/plugins/check_pgsql.c @@ -59,31 +59,31 @@ enum { DEFAULT_CRIT = 8 }; -int process_arguments(int, char **); -int validate_arguments(void); -void print_usage(void); -void print_help(void); -bool is_pg_logname(char *); -int do_query(PGconn *, char *); - -char *pghost = NULL; /* host name of the backend server */ -char *pgport = NULL; /* port of the backend server */ -int default_port = DEFAULT_PORT; -char *pgoptions = NULL; -char *pgtty = NULL; -char dbName[NAMEDATALEN] = DEFAULT_DB; -char *pguser = NULL; -char *pgpasswd = NULL; -char *pgparams = NULL; -double twarn = (double)DEFAULT_WARN; -double tcrit = (double)DEFAULT_CRIT; -char *pgquery = NULL; +static int process_arguments(int, char **); +static int validate_arguments(void); +static void print_usage(void); +static void print_help(void); +static bool is_pg_logname(char *); +static int do_query(PGconn *, char *); + +static char *pghost = NULL; /* host name of the backend server */ +static char *pgport = NULL; /* port of the backend server */ +static char *pgoptions = NULL; +static char *pgtty = NULL; +static char dbName[NAMEDATALEN] = DEFAULT_DB; +static char *pguser = NULL; +static char *pgpasswd = NULL; +static char *pgparams = NULL; +static double twarn = (double)DEFAULT_WARN; +static double tcrit = (double)DEFAULT_CRIT; +static char *pgquery = NULL; +static char *pgqueryname = NULL; +static char *query_warning = NULL; +static char *query_critical = NULL; +static thresholds *qthresholds = NULL; +static int verbose = 0; + #define OPTID_QUERYNAME -1000 -char *pgqueryname = NULL; -char *query_warning = NULL; -char *query_critical = NULL; -thresholds *qthresholds = NULL; -int verbose = 0; /****************************************************************************** -- cgit v0.10-9-g596f From 0a3fcf0d97896b66a0263daa6d96bf2a87511611 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 13:33:31 +0100 Subject: check_pgsql: diverse style fixes diff --git a/plugins/check_pgsql.c b/plugins/check_pgsql.c index a6411a5..1e35a4c 100644 --- a/plugins/check_pgsql.c +++ b/plugins/check_pgsql.c @@ -59,12 +59,11 @@ enum { DEFAULT_CRIT = 8 }; -static int process_arguments(int, char **); -static int validate_arguments(void); +static int process_arguments(int /*argc*/, char ** /*argv*/); static void print_usage(void); static void print_help(void); -static bool is_pg_logname(char *); -static int do_query(PGconn *, char *); +static bool is_pg_logname(char * /*username*/); +static int do_query(PGconn * /*conn*/, char * /*query*/); static char *pghost = NULL; /* host name of the backend server */ static char *pgport = NULL; /* port of the backend server */ @@ -136,14 +135,9 @@ Please note that all tags must be lowercase to use the DocBook XML DTD. ******************************************************************************/ int main(int argc, char **argv) { - PGconn *conn; - char *conninfo = NULL; - - struct timeval start_timeval; - struct timeval end_timeval; - double elapsed_time; - int status = STATE_UNKNOWN; - int query_status = STATE_UNKNOWN; + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* begin, by setting the parameters for a backend connection if the * parameters are null, then the system will try to use reasonable @@ -153,10 +147,6 @@ int main(int argc, char **argv) { pgoptions = NULL; /* special options to start up the backend server */ pgtty = NULL; /* debugging tty for the backend server */ - setlocale(LC_ALL, ""); - bindtextdomain(PACKAGE, LOCALEDIR); - textdomain(PACKAGE); - /* Parse extra opts if any */ argv = np_extra_opts(&argc, argv, progname); @@ -171,6 +161,7 @@ int main(int argc, char **argv) { } alarm(timeout_interval); + char *conninfo = NULL; if (pgparams) asprintf(&conninfo, "%s ", pgparams); @@ -192,15 +183,18 @@ int main(int argc, char **argv) { asprintf(&conninfo, "%s password = '%s'", conninfo, pgpasswd); /* make a connection to the database */ + struct timeval start_timeval; gettimeofday(&start_timeval, NULL); - conn = PQconnectdb(conninfo); + PGconn *conn = PQconnectdb(conninfo); + struct timeval end_timeval; gettimeofday(&end_timeval, NULL); while (start_timeval.tv_usec > end_timeval.tv_usec) { --end_timeval.tv_sec; end_timeval.tv_usec += 1000000; } - elapsed_time = (double)(end_timeval.tv_sec - start_timeval.tv_sec) + (double)(end_timeval.tv_usec - start_timeval.tv_usec) / 1000000.0; + double elapsed_time = + (double)(end_timeval.tv_sec - start_timeval.tv_sec) + (double)(end_timeval.tv_usec - start_timeval.tv_usec) / 1000000.0; if (verbose) printf("Time elapsed: %f\n", elapsed_time); @@ -212,7 +206,10 @@ int main(int argc, char **argv) { printf(_("CRITICAL - no connection to '%s' (%s).\n"), dbName, PQerrorMessage(conn)); PQfinish(conn); return STATE_CRITICAL; - } else if (elapsed_time > tcrit) { + } + + int status = STATE_UNKNOWN; + if (elapsed_time > tcrit) { status = STATE_CRITICAL; } else if (elapsed_time > twarn) { status = STATE_WARNING; @@ -234,6 +231,7 @@ int main(int argc, char **argv) { printf(_(" %s - database %s (%f sec.)|%s\n"), state_text(status), dbName, elapsed_time, fperfdata("time", elapsed_time, "s", !!(twarn > 0.0), twarn, !!(tcrit > 0.0), tcrit, true, 0, false, 0)); + int query_status = STATE_UNKNOWN; if (pgquery) query_status = do_query(conn, pgquery); @@ -245,9 +243,6 @@ int main(int argc, char **argv) { /* process command-line arguments */ int process_arguments(int argc, char **argv) { - int c; - - int option = 0; static struct option longopts[] = {{"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'}, {"timeout", required_argument, 0, 't'}, @@ -267,13 +262,14 @@ int process_arguments(int argc, char **argv) { {"verbose", no_argument, 0, 'v'}, {0, 0, 0, 0}}; - while (1) { - c = getopt_long(argc, argv, "hVt:c:w:H:P:d:l:p:a:o:q:C:W:v", longopts, &option); + while (true) { + int option = 0; + int option_char = getopt_long(argc, argv, "hVt:c:w:H:P:d:l:p:a:o:q:C:W:v", longopts, &option); - if (c == EOF) + if (option_char == EOF) break; - switch (c) { + switch (option_char) { case '?': /* usage */ usage5(); case 'h': /* help */ @@ -354,31 +350,9 @@ int process_arguments(int argc, char **argv) { set_thresholds(&qthresholds, query_warning, query_critical); - return validate_arguments(); + return OK; } -/****************************************************************************** - -@@- - -validate_arguments - -&PROTO_validate_arguments; - -Given a database name, this function returns true if the string -is a valid PostgreSQL database name, and returns false if it is -not. - -Valid PostgreSQL database names are less than &NAMEDATALEN; -characters long and consist of letters, numbers, and underscores. The -first character cannot be a number, however. - - --@@ -******************************************************************************/ - -int validate_arguments() { return OK; } - /** the tango program should eventually create an entity here based on the @@ -509,19 +483,9 @@ void print_usage(void) { } int do_query(PGconn *conn, char *query) { - PGresult *res; - - char *val_str; - char *extra_info; - double value; - - char *endptr = NULL; - - int my_status = STATE_UNKNOWN; - if (verbose) printf("Executing SQL query \"%s\".\n", query); - res = PQexec(conn, query); + PGresult *res = PQexec(conn, query); if (PGRES_TUPLES_OK != PQresultStatus(res)) { printf(_("QUERY %s - %s: %s.\n"), _("CRITICAL"), _("Error with query"), PQerrorMessage(conn)); @@ -538,25 +502,28 @@ int do_query(PGconn *conn, char *query) { return STATE_WARNING; } - val_str = PQgetvalue(res, 0, 0); + char *val_str = PQgetvalue(res, 0, 0); if (!val_str) { printf("QUERY %s - %s.\n", _("CRITICAL"), _("No data returned")); return STATE_CRITICAL; } - value = strtod(val_str, &endptr); + char *endptr = NULL; + double value = strtod(val_str, &endptr); if (verbose) printf("Query result: %f\n", value); if (endptr == val_str) { printf("QUERY %s - %s: %s\n", _("CRITICAL"), _("Is not a numeric"), val_str); return STATE_CRITICAL; - } else if ((endptr != NULL) && (*endptr != '\0')) { + } + + if ((endptr != NULL) && (*endptr != '\0')) { if (verbose) printf("Garbage after value: %s.\n", endptr); } - my_status = get_status(value, qthresholds); + int my_status = get_status(value, qthresholds); printf("QUERY %s - ", (my_status == STATE_OK) ? _("OK") : (my_status == STATE_WARNING) ? _("WARNING") : (my_status == STATE_CRITICAL) ? _("CRITICAL") @@ -569,7 +536,7 @@ int do_query(PGconn *conn, char *query) { printf("|query=%f;%s;%s;;\n", value, query_warning ? query_warning : "", query_critical ? query_critical : ""); if (PQnfields(res) > 1) { - extra_info = PQgetvalue(res, 0, 1); + char *extra_info = PQgetvalue(res, 0, 1); if (extra_info != NULL) { printf("Extra Info: %s\n", extra_info); } -- cgit v0.10-9-g596f From 8eb68605783b2d651c94c133d84faacefee83a99 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 13:34:11 +0100 Subject: check_ping: clang-format diff --git a/plugins/check_ping.c b/plugins/check_ping.c index 6e162e6..1977546 100644 --- a/plugins/check_ping.c +++ b/plugins/check_ping.c @@ -1,32 +1,32 @@ /***************************************************************************** -* -* Monitoring check_ping plugin -* -* License: GPL -* Copyright (c) 2000-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_ping plugin -* -* Use the ping program to check connection statistics for a remote host. -* -* -* 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_ping plugin + * + * License: GPL + * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_ping plugin + * + * Use the ping program to check connection statistics for a remote host. + * + * + * 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_ping"; const char *copyright = "2000-2007"; @@ -39,21 +39,21 @@ const char *email = "devel@monitoring-plugins.org"; #include -#define WARN_DUPLICATES "DUPLICATES FOUND! " -#define UNKNOWN_TRIP_TIME -1.0 /* -1 seconds */ +#define WARN_DUPLICATES "DUPLICATES FOUND! " +#define UNKNOWN_TRIP_TIME -1.0 /* -1 seconds */ enum { - UNKNOWN_PACKET_LOSS = 200, /* 200% */ - DEFAULT_MAX_PACKETS = 5 /* default no. of ICMP ECHO packets */ + UNKNOWN_PACKET_LOSS = 200, /* 200% */ + DEFAULT_MAX_PACKETS = 5 /* default no. of ICMP ECHO packets */ }; -int process_arguments (int, char **); -int get_threshold (char *, float *, int *); -int validate_arguments (void); -int run_ping (const char *cmd, const char *addr); -int error_scan (char buf[MAX_INPUT_BUFFER], const char *addr); -void print_usage (void); -void print_help (void); +int process_arguments(int, char **); +int get_threshold(char *, float *, int *); +int validate_arguments(void); +int run_ping(const char *cmd, const char *addr); +int error_scan(char buf[MAX_INPUT_BUFFER], const char *addr); +void print_usage(void); +void print_help(void); bool display_html = false; int wpl = UNKNOWN_PACKET_LOSS; @@ -71,45 +71,41 @@ int pl = UNKNOWN_PACKET_LOSS; char *warn_text; - - -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { char *cmd = NULL; char *rawcmd = NULL; int result = STATE_UNKNOWN; int this_result = STATE_UNKNOWN; int i; - setlocale (LC_ALL, ""); - setlocale (LC_NUMERIC, "C"); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + setlocale(LC_NUMERIC, "C"); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); - addresses = malloc (sizeof(char*) * max_addr); + addresses = malloc(sizeof(char *) * max_addr); addresses[0] = NULL; /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if (process_arguments (argc, argv) == ERROR) - usage4 (_("Could not parse arguments")); + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments")); /* Set signal handling and alarm */ - if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) { - usage4 (_("Cannot catch SIGALRM")); + if (signal(SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) { + usage4(_("Cannot catch SIGALRM")); } /* If ./configure finds ping has timeout values, set plugin alarm slightly * higher so that we can use response from command line ping */ #if defined(PING_PACKETS_FIRST) && defined(PING_HAS_TIMEOUT) - alarm (timeout_interval + 1); + alarm(timeout_interval + 1); #else - alarm (timeout_interval); + alarm(timeout_interval); #endif - for (i = 0 ; i < n_addresses ; i++) { + for (i = 0; i < n_addresses; i++) { #ifdef PING6_COMMAND if (address_family != AF_INET && is_inet6_addr(addresses[i])) @@ -120,27 +116,26 @@ main (int argc, char **argv) rawcmd = strdup(PING_COMMAND); #endif - /* does the host address of number of packets argument come first? */ + /* does the host address of number of packets argument come first? */ #ifdef PING_PACKETS_FIRST -# ifdef PING_HAS_TIMEOUT - xasprintf (&cmd, rawcmd, timeout_interval, max_packets, addresses[i]); -# else - xasprintf (&cmd, rawcmd, max_packets, addresses[i]); -# endif +# ifdef PING_HAS_TIMEOUT + xasprintf(&cmd, rawcmd, timeout_interval, max_packets, addresses[i]); +# else + xasprintf(&cmd, rawcmd, max_packets, addresses[i]); +# endif #else - xasprintf (&cmd, rawcmd, addresses[i], max_packets); + xasprintf(&cmd, rawcmd, addresses[i], max_packets); #endif if (verbose >= 2) - printf ("CMD: %s\n", cmd); + printf("CMD: %s\n", cmd); /* run the command */ - this_result = run_ping (cmd, addresses[i]); + this_result = run_ping(cmd, addresses[i]); if (pl == UNKNOWN_PACKET_LOSS || rta < 0.0) { - printf ("%s\n", cmd); - die (STATE_UNKNOWN, - _("CRITICAL - Could not interpret output from ping command\n")); + printf("%s\n", cmd); + die(STATE_UNKNOWN, _("CRITICAL - Could not interpret output from ping command\n")); } if (pl >= cpl || rta >= crta || rta < 0) @@ -148,267 +143,241 @@ main (int argc, char **argv) else if (pl >= wpl || rta >= wrta) this_result = STATE_WARNING; else if (pl >= 0 && rta >= 0) - this_result = max_state (STATE_OK, this_result); + this_result = max_state(STATE_OK, this_result); if (n_addresses > 1 && this_result != STATE_UNKNOWN) - die (STATE_OK, "%s is alive\n", addresses[i]); + die(STATE_OK, "%s is alive\n", addresses[i]); if (display_html == true) - printf ("", CGIURL, addresses[i]); + printf("", CGIURL, addresses[i]); if (pl == 100) - printf (_("PING %s - %sPacket loss = %d%%"), state_text (this_result), warn_text, - pl); + printf(_("PING %s - %sPacket loss = %d%%"), state_text(this_result), warn_text, pl); else - printf (_("PING %s - %sPacket loss = %d%%, RTA = %2.2f ms"), - state_text (this_result), warn_text, pl, rta); + printf(_("PING %s - %sPacket loss = %d%%, RTA = %2.2f ms"), state_text(this_result), warn_text, pl, rta); if (display_html == true) - printf (""); + printf(""); /* Print performance data */ if (pl != 100) { - printf("|%s", fperfdata ("rta", (double) rta, "ms", - wrta>0?true:false, wrta, - crta>0?true:false, crta, - true, 0, false, 0)); + printf("|%s", + fperfdata("rta", (double)rta, "ms", wrta > 0 ? true : false, wrta, crta > 0 ? true : false, crta, true, 0, false, 0)); } else { printf("| rta=U;%f;%f;;", wrta, crta); } - printf(" %s\n", perfdata ("pl", (long) pl, "%", - wpl>0?true:false, wpl, - cpl>0?true:false, cpl, - true, 0, false, 0)); + printf(" %s\n", perfdata("pl", (long)pl, "%", wpl > 0 ? true : false, wpl, cpl > 0 ? true : false, cpl, true, 0, false, 0)); if (verbose >= 2) - printf ("%f:%d%% %f:%d%%\n", wrta, wpl, crta, cpl); + printf("%f:%d%% %f:%d%%\n", wrta, wpl, crta, cpl); - result = max_state (result, this_result); - free (rawcmd); - free (cmd); + result = max_state(result, this_result); + free(rawcmd); + free(cmd); } return result; } - - /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ +int process_arguments(int argc, char **argv) { int c = 1; char *ptr; int option = 0; - static struct option longopts[] = { - STD_LONG_OPTS, - {"packets", required_argument, 0, 'p'}, - {"nohtml", no_argument, 0, 'n'}, - {"link", no_argument, 0, 'L'}, - {"use-ipv4", no_argument, 0, '4'}, - {"use-ipv6", no_argument, 0, '6'}, - {0, 0, 0, 0} - }; + static struct option longopts[] = {STD_LONG_OPTS, + {"packets", required_argument, 0, 'p'}, + {"nohtml", no_argument, 0, 'n'}, + {"link", no_argument, 0, 'L'}, + {"use-ipv4", no_argument, 0, '4'}, + {"use-ipv6", no_argument, 0, '6'}, + {0, 0, 0, 0}}; if (argc < 2) return ERROR; for (c = 1; c < argc; c++) { - if (strcmp ("-to", argv[c]) == 0) - strcpy (argv[c], "-t"); - if (strcmp ("-nohtml", argv[c]) == 0) - strcpy (argv[c], "-n"); + if (strcmp("-to", argv[c]) == 0) + strcpy(argv[c], "-t"); + if (strcmp("-nohtml", argv[c]) == 0) + strcpy(argv[c], "-n"); } while (1) { - c = getopt_long (argc, argv, "VvhnL46t:c:w:H:p:", longopts, &option); + c = getopt_long(argc, argv, "VvhnL46t:c:w:H:p:", longopts, &option); if (c == -1 || c == EOF) break; switch (c) { - case '?': /* usage */ - usage5 (); - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); + case '?': /* usage */ + usage5(); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); break; - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); break; - case 't': /* timeout period */ - timeout_interval = atoi (optarg); + case 't': /* timeout period */ + timeout_interval = atoi(optarg); break; - case 'v': /* verbose mode */ + case 'v': /* verbose mode */ verbose++; break; - case '4': /* IPv4 only */ + case '4': /* IPv4 only */ address_family = AF_INET; break; - case '6': /* IPv6 only */ + case '6': /* IPv6 only */ #ifdef USE_IPV6 address_family = AF_INET6; #else - usage (_("IPv6 support not available\n")); + usage(_("IPv6 support not available\n")); #endif break; - case 'H': /* hostname */ - ptr=optarg; + case 'H': /* hostname */ + ptr = optarg; while (1) { n_addresses++; if (n_addresses > max_addr) { max_addr *= 2; - addresses = realloc (addresses, sizeof(char*) * max_addr); + addresses = realloc(addresses, sizeof(char *) * max_addr); if (addresses == NULL) - die (STATE_UNKNOWN, _("Could not realloc() addresses\n")); + die(STATE_UNKNOWN, _("Could not realloc() addresses\n")); } - addresses[n_addresses-1] = ptr; - if ((ptr = index (ptr, ','))) { - strcpy (ptr, ""); + addresses[n_addresses - 1] = ptr; + if ((ptr = index(ptr, ','))) { + strcpy(ptr, ""); ptr += sizeof(char); } else { break; } } break; - case 'p': /* number of packets to send */ - if (is_intnonneg (optarg)) - max_packets = atoi (optarg); + case 'p': /* number of packets to send */ + if (is_intnonneg(optarg)) + max_packets = atoi(optarg); else - usage2 (_(" (%s) must be a non-negative number\n"), optarg); + usage2(_(" (%s) must be a non-negative number\n"), optarg); break; - case 'n': /* no HTML */ + case 'n': /* no HTML */ display_html = false; break; - case 'L': /* show HTML */ + case 'L': /* show HTML */ display_html = true; break; case 'c': - get_threshold (optarg, &crta, &cpl); + get_threshold(optarg, &crta, &cpl); break; case 'w': - get_threshold (optarg, &wrta, &wpl); + get_threshold(optarg, &wrta, &wpl); break; } } c = optind; if (c == argc) - return validate_arguments (); + return validate_arguments(); if (addresses[0] == NULL) { - if (!is_host (argv[c])) { - usage2 (_("Invalid hostname/address"), argv[c]); + if (!is_host(argv[c])) { + usage2(_("Invalid hostname/address"), argv[c]); } else { addresses[0] = argv[c++]; n_addresses++; if (c == argc) - return validate_arguments (); + return validate_arguments(); } } if (wpl == UNKNOWN_PACKET_LOSS) { - if (!is_intpercent (argv[c])) { - printf (_(" (%s) must be an integer percentage\n"), argv[c]); + if (!is_intpercent(argv[c])) { + printf(_(" (%s) must be an integer percentage\n"), argv[c]); return ERROR; } else { - wpl = atoi (argv[c++]); + wpl = atoi(argv[c++]); if (c == argc) - return validate_arguments (); + return validate_arguments(); } } if (cpl == UNKNOWN_PACKET_LOSS) { - if (!is_intpercent (argv[c])) { - printf (_(" (%s) must be an integer percentage\n"), argv[c]); + if (!is_intpercent(argv[c])) { + printf(_(" (%s) must be an integer percentage\n"), argv[c]); return ERROR; } else { - cpl = atoi (argv[c++]); + cpl = atoi(argv[c++]); if (c == argc) - return validate_arguments (); + return validate_arguments(); } } if (wrta < 0.0) { - if (is_negative (argv[c])) { - printf (_(" (%s) must be a non-negative number\n"), argv[c]); + if (is_negative(argv[c])) { + printf(_(" (%s) must be a non-negative number\n"), argv[c]); return ERROR; } else { - wrta = atof (argv[c++]); + wrta = atof(argv[c++]); if (c == argc) - return validate_arguments (); + return validate_arguments(); } } if (crta < 0.0) { - if (is_negative (argv[c])) { - printf (_(" (%s) must be a non-negative number\n"), argv[c]); + if (is_negative(argv[c])) { + printf(_(" (%s) must be a non-negative number\n"), argv[c]); return ERROR; } else { - crta = atof (argv[c++]); + crta = atof(argv[c++]); if (c == argc) - return validate_arguments (); + return validate_arguments(); } } if (max_packets == -1) { - if (is_intnonneg (argv[c])) { - max_packets = atoi (argv[c++]); + if (is_intnonneg(argv[c])) { + max_packets = atoi(argv[c++]); } else { - printf (_(" (%s) must be a non-negative number\n"), argv[c]); + printf(_(" (%s) must be a non-negative number\n"), argv[c]); return ERROR; } } - return validate_arguments (); + return validate_arguments(); } - - -int -get_threshold (char *arg, float *trta, int *tpl) -{ - if (is_intnonneg (arg) && sscanf (arg, "%f", trta) == 1) +int get_threshold(char *arg, float *trta, int *tpl) { + if (is_intnonneg(arg) && sscanf(arg, "%f", trta) == 1) return OK; - else if (strpbrk (arg, ",:") && strstr (arg, "%") && sscanf (arg, "%f%*[:,]%d%%", trta, tpl) == 2) + else if (strpbrk(arg, ",:") && strstr(arg, "%") && sscanf(arg, "%f%*[:,]%d%%", trta, tpl) == 2) return OK; - else if (strstr (arg, "%") && sscanf (arg, "%d%%", tpl) == 1) + else if (strstr(arg, "%") && sscanf(arg, "%d%%", tpl) == 1) return OK; - usage2 (_("%s: Warning threshold must be integer or percentage!\n\n"), arg); + usage2(_("%s: Warning threshold must be integer or percentage!\n\n"), arg); return STATE_UNKNOWN; } - - -int -validate_arguments () -{ +int validate_arguments() { float max_seconds; int i; if (wrta < 0.0) { - printf (_(" was not set\n")); + printf(_(" was not set\n")); return ERROR; - } - else if (crta < 0.0) { - printf (_(" was not set\n")); + } else if (crta < 0.0) { + printf(_(" was not set\n")); return ERROR; - } - else if (wpl == UNKNOWN_PACKET_LOSS) { - printf (_(" was not set\n")); + } else if (wpl == UNKNOWN_PACKET_LOSS) { + printf(_(" was not set\n")); return ERROR; - } - else if (cpl == UNKNOWN_PACKET_LOSS) { - printf (_(" was not set\n")); + } else if (cpl == UNKNOWN_PACKET_LOSS) { + printf(_(" was not set\n")); return ERROR; - } - else if (wrta > crta) { - printf (_(" (%f) cannot be larger than (%f)\n"), wrta, crta); + } else if (wrta > crta) { + printf(_(" (%f) cannot be larger than (%f)\n"), wrta, crta); return ERROR; - } - else if (wpl > cpl) { - printf (_(" (%d) cannot be larger than (%d)\n"), wpl, cpl); + } else if (wpl > cpl) { + printf(_(" (%d) cannot be larger than (%d)\n"), wpl, cpl); return ERROR; } @@ -419,68 +388,61 @@ validate_arguments () if (max_seconds > timeout_interval) timeout_interval = (int)max_seconds; - for (i=0; i= 3) printf("Output: %s", buf); - result = max_state (result, error_scan (buf, addr)); + result = max_state(result, error_scan(buf, addr)); /* get the percent loss statistics */ match = 0; - if((sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d errors, %d%% packet loss%n",&pl,&match) && match) || - (sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d duplicates, %d%% packet loss%n",&pl,&match) && match) || - (sscanf(buf,"%*d packets transmitted, %*d received, +%*d duplicates, %d%% packet loss%n",&pl,&match) && match) || - (sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% packet loss%n",&pl,&match) && match) || - (sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% loss, time%n",&pl,&match) && match) || - (sscanf(buf,"%*d packets transmitted, %*d received, %d%% loss, time%n",&pl,&match) && match) || - (sscanf(buf,"%*d packets transmitted, %*d received, %d%% packet loss, time%n",&pl,&match) && match) || - (sscanf(buf,"%*d packets transmitted, %*d received, +%*d errors, %d%% packet loss%n",&pl,&match) && match) || - (sscanf(buf,"%*d packets transmitted %*d received, +%*d errors, %d%% packet loss%n",&pl,&match) && match) || - (sscanf(buf,"%*[^(](%d%% %*[^)])%n",&pl,&match) && match) - ) + if ((sscanf(buf, "%*d packets transmitted, %*d packets received, +%*d errors, %d%% packet loss%n", &pl, &match) && match) || + (sscanf(buf, "%*d packets transmitted, %*d packets received, +%*d duplicates, %d%% packet loss%n", &pl, &match) && match) || + (sscanf(buf, "%*d packets transmitted, %*d received, +%*d duplicates, %d%% packet loss%n", &pl, &match) && match) || + (sscanf(buf, "%*d packets transmitted, %*d packets received, %d%% packet loss%n", &pl, &match) && match) || + (sscanf(buf, "%*d packets transmitted, %*d packets received, %d%% loss, time%n", &pl, &match) && match) || + (sscanf(buf, "%*d packets transmitted, %*d received, %d%% loss, time%n", &pl, &match) && match) || + (sscanf(buf, "%*d packets transmitted, %*d received, %d%% packet loss, time%n", &pl, &match) && match) || + (sscanf(buf, "%*d packets transmitted, %*d received, +%*d errors, %d%% packet loss%n", &pl, &match) && match) || + (sscanf(buf, "%*d packets transmitted %*d received, +%*d errors, %d%% packet loss%n", &pl, &match) && match) || + (sscanf(buf, "%*[^(](%d%% %*[^)])%n", &pl, &match) && match)) continue; /* get the round trip average */ - else - if((sscanf(buf,"round-trip min/avg/max = %*f/%f/%*f%n",&rta,&match) && match) || - (sscanf(buf,"round-trip min/avg/max/mdev = %*f/%f/%*f/%*f%n",&rta,&match) && match) || - (sscanf(buf,"round-trip min/avg/max/sdev = %*f/%f/%*f/%*f%n",&rta,&match) && match) || - (sscanf(buf,"round-trip min/avg/max/stddev = %*f/%f/%*f/%*f%n",&rta,&match) && match) || - (sscanf(buf,"round-trip min/avg/max/std-dev = %*f/%f/%*f/%*f%n",&rta,&match) && match) || - (sscanf(buf,"round-trip (ms) min/avg/max = %*f/%f/%*f%n",&rta,&match) && match) || - (sscanf(buf,"round-trip (ms) min/avg/max/stddev = %*f/%f/%*f/%*f%n",&rta,&match) && match) || - (sscanf(buf,"rtt min/avg/max/mdev = %*f/%f/%*f/%*f ms%n",&rta,&match) && match) || - (sscanf(buf, "%*[^=] = %*fms, %*[^=] = %*fms, %*[^=] = %fms%n", &rta, &match) && match) - ) + else if ((sscanf(buf, "round-trip min/avg/max = %*f/%f/%*f%n", &rta, &match) && match) || + (sscanf(buf, "round-trip min/avg/max/mdev = %*f/%f/%*f/%*f%n", &rta, &match) && match) || + (sscanf(buf, "round-trip min/avg/max/sdev = %*f/%f/%*f/%*f%n", &rta, &match) && match) || + (sscanf(buf, "round-trip min/avg/max/stddev = %*f/%f/%*f/%*f%n", &rta, &match) && match) || + (sscanf(buf, "round-trip min/avg/max/std-dev = %*f/%f/%*f/%*f%n", &rta, &match) && match) || + (sscanf(buf, "round-trip (ms) min/avg/max = %*f/%f/%*f%n", &rta, &match) && match) || + (sscanf(buf, "round-trip (ms) min/avg/max/stddev = %*f/%f/%*f/%*f%n", &rta, &match) && match) || + (sscanf(buf, "rtt min/avg/max/mdev = %*f/%f/%*f/%*f ms%n", &rta, &match) && match) || + (sscanf(buf, "%*[^=] = %*fms, %*[^=] = %*fms, %*[^=] = %fms%n", &rta, &match) && match)) continue; } @@ -490,16 +452,14 @@ run_ping (const char *cmd, const char *addr) /* check stderr, setting at least WARNING if there is output here */ /* Add warning into warn_text */ - while (fgets (buf, MAX_INPUT_BUFFER - 1, child_stderr)) { - if ( - ! strstr(buf,"WARNING - no SO_TIMESTAMP support, falling back to SIOCGSTAMP") - && ! strstr(buf,"Warning: time of day goes back") + while (fgets(buf, MAX_INPUT_BUFFER - 1, child_stderr)) { + if (!strstr(buf, "WARNING - no SO_TIMESTAMP support, falling back to SIOCGSTAMP") && !strstr(buf, "Warning: time of day goes back") ) { if (verbose >= 3) { printf("Got stderr: %s", buf); } - if ((result=error_scan(buf, addr)) == STATE_OK) { + if ((result = error_scan(buf, addr)) == STATE_OK) { result = STATE_WARNING; if (warn_text == NULL) { warn_text = strdup(_("System call sent warnings to stderr ")); @@ -510,10 +470,9 @@ run_ping (const char *cmd, const char *addr) } } - (void) fclose (child_stderr); + (void)fclose(child_stderr); - - spclose (child_process); + spclose(child_process); if (warn_text == NULL) warn_text = strdup(""); @@ -521,100 +480,86 @@ run_ping (const char *cmd, const char *addr) return result; } - - -int -error_scan (char buf[MAX_INPUT_BUFFER], const char *addr) -{ - if (strstr (buf, "Network is unreachable") || - strstr (buf, "Destination Net Unreachable") || - strstr (buf, "No route") - ) - die (STATE_CRITICAL, _("CRITICAL - Network Unreachable (%s)\n"), addr); - else if (strstr (buf, "Destination Host Unreachable") || strstr(buf, "Address unreachable")) - die (STATE_CRITICAL, _("CRITICAL - Host Unreachable (%s)\n"), addr); - else if (strstr (buf, "Destination Port Unreachable") || strstr(buf, "Port unreachable")) - die (STATE_CRITICAL, _("CRITICAL - Bogus ICMP: Port Unreachable (%s)\n"), addr); - else if (strstr (buf, "Destination Protocol Unreachable")) - die (STATE_CRITICAL, _("CRITICAL - Bogus ICMP: Protocol Unreachable (%s)\n"), addr); - else if (strstr (buf, "Destination Net Prohibited")) - die (STATE_CRITICAL, _("CRITICAL - Network Prohibited (%s)\n"), addr); - else if (strstr (buf, "Destination Host Prohibited")) - die (STATE_CRITICAL, _("CRITICAL - Host Prohibited (%s)\n"), addr); - else if (strstr (buf, "Packet filtered") || strstr(buf, "Administratively prohibited")) - die (STATE_CRITICAL, _("CRITICAL - Packet Filtered (%s)\n"), addr); - else if (strstr (buf, "unknown host" )) - die (STATE_CRITICAL, _("CRITICAL - Host not found (%s)\n"), addr); - else if (strstr (buf, "Time to live exceeded") || strstr(buf, "Time exceeded")) - die (STATE_CRITICAL, _("CRITICAL - Time to live exceeded (%s)\n"), addr); - else if (strstr (buf, "Destination unreachable: ")) - die (STATE_CRITICAL, _("CRITICAL - Destination Unreachable (%s)\n"), addr); - - if (strstr (buf, "(DUP!)") || strstr (buf, "DUPLICATES FOUND")) { +int error_scan(char buf[MAX_INPUT_BUFFER], const char *addr) { + if (strstr(buf, "Network is unreachable") || strstr(buf, "Destination Net Unreachable") || strstr(buf, "No route")) + die(STATE_CRITICAL, _("CRITICAL - Network Unreachable (%s)\n"), addr); + else if (strstr(buf, "Destination Host Unreachable") || strstr(buf, "Address unreachable")) + die(STATE_CRITICAL, _("CRITICAL - Host Unreachable (%s)\n"), addr); + else if (strstr(buf, "Destination Port Unreachable") || strstr(buf, "Port unreachable")) + die(STATE_CRITICAL, _("CRITICAL - Bogus ICMP: Port Unreachable (%s)\n"), addr); + else if (strstr(buf, "Destination Protocol Unreachable")) + die(STATE_CRITICAL, _("CRITICAL - Bogus ICMP: Protocol Unreachable (%s)\n"), addr); + else if (strstr(buf, "Destination Net Prohibited")) + die(STATE_CRITICAL, _("CRITICAL - Network Prohibited (%s)\n"), addr); + else if (strstr(buf, "Destination Host Prohibited")) + die(STATE_CRITICAL, _("CRITICAL - Host Prohibited (%s)\n"), addr); + else if (strstr(buf, "Packet filtered") || strstr(buf, "Administratively prohibited")) + die(STATE_CRITICAL, _("CRITICAL - Packet Filtered (%s)\n"), addr); + else if (strstr(buf, "unknown host")) + die(STATE_CRITICAL, _("CRITICAL - Host not found (%s)\n"), addr); + else if (strstr(buf, "Time to live exceeded") || strstr(buf, "Time exceeded")) + die(STATE_CRITICAL, _("CRITICAL - Time to live exceeded (%s)\n"), addr); + else if (strstr(buf, "Destination unreachable: ")) + die(STATE_CRITICAL, _("CRITICAL - Destination Unreachable (%s)\n"), addr); + + if (strstr(buf, "(DUP!)") || strstr(buf, "DUPLICATES FOUND")) { if (warn_text == NULL) - warn_text = strdup (_(WARN_DUPLICATES)); - else if (! strstr (warn_text, _(WARN_DUPLICATES)) && - xasprintf (&warn_text, "%s %s", warn_text, _(WARN_DUPLICATES)) == -1) - die (STATE_UNKNOWN, _("Unable to realloc warn_text\n")); + warn_text = strdup(_(WARN_DUPLICATES)); + else if (!strstr(warn_text, _(WARN_DUPLICATES)) && xasprintf(&warn_text, "%s %s", warn_text, _(WARN_DUPLICATES)) == -1) + die(STATE_UNKNOWN, _("Unable to realloc warn_text\n")); return (STATE_WARNING); } return (STATE_OK); } +void print_help(void) { + print_revision(progname, NP_VERSION); + printf("Copyright (c) 1999 Ethan Galstad \n"); + printf(COPYRIGHT, copyright, email); -void -print_help (void) -{ - print_revision (progname, NP_VERSION); - - printf ("Copyright (c) 1999 Ethan Galstad \n"); - printf (COPYRIGHT, copyright, email); - - printf (_("Use ping to check connection statistics for a remote host.")); + printf(_("Use ping to check connection statistics for a remote host.")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); - printf (UT_IPv46); + printf(UT_IPv46); - printf (" %s\n", "-H, --hostname=HOST"); - printf (" %s\n", _("host to ping")); - printf (" %s\n", "-w, --warning=THRESHOLD"); - printf (" %s\n", _("warning threshold pair")); - printf (" %s\n", "-c, --critical=THRESHOLD"); - printf (" %s\n", _("critical threshold pair")); - printf (" %s\n", "-p, --packets=INTEGER"); - printf (" %s ", _("number of ICMP ECHO packets to send")); - printf (_("(Default: %d)\n"), DEFAULT_MAX_PACKETS); - printf (" %s\n", "-L, --link"); - printf (" %s\n", _("show HTML in the plugin output (obsoleted by urlize)")); + printf(" %s\n", "-H, --hostname=HOST"); + printf(" %s\n", _("host to ping")); + printf(" %s\n", "-w, --warning=THRESHOLD"); + printf(" %s\n", _("warning threshold pair")); + printf(" %s\n", "-c, --critical=THRESHOLD"); + printf(" %s\n", _("critical threshold pair")); + printf(" %s\n", "-p, --packets=INTEGER"); + printf(" %s ", _("number of ICMP ECHO packets to send")); + printf(_("(Default: %d)\n"), DEFAULT_MAX_PACKETS); + printf(" %s\n", "-L, --link"); + printf(" %s\n", _("show HTML in the plugin output (obsoleted by urlize)")); - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - printf ("\n"); - printf ("%s\n", _("THRESHOLD is ,% where is the round trip average travel")); - printf ("%s\n", _("time (ms) which triggers a WARNING or CRITICAL state, and is the")); - printf ("%s\n", _("percentage of packet loss to trigger an alarm state.")); + printf("\n"); + printf("%s\n", _("THRESHOLD is ,% where is the round trip average travel")); + printf("%s\n", _("time (ms) which triggers a WARNING or CRITICAL state, and is the")); + printf("%s\n", _("percentage of packet loss to trigger an alarm state.")); - printf ("\n"); - printf ("%s\n", _("This plugin uses the ping command to probe the specified host for packet loss")); - printf ("%s\n", _("(percentage) and round trip average (milliseconds). It can produce HTML output")); - printf ("%s\n", _("linking to a traceroute CGI contributed by Ian Cass. The CGI can be found in")); - printf ("%s\n", _("the contrib area of the downloads section at http://www.nagios.org/")); + printf("\n"); + printf("%s\n", _("This plugin uses the ping command to probe the specified host for packet loss")); + printf("%s\n", _("(percentage) and round trip average (milliseconds). It can produce HTML output")); + printf("%s\n", _("linking to a traceroute CGI contributed by Ian Cass. The CGI can be found in")); + printf("%s\n", _("the contrib area of the downloads section at http://www.nagios.org/")); - printf (UT_SUPPORT); + printf(UT_SUPPORT); } -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s -H -w ,%% -c ,%%\n", progname); - printf (" [-p packets] [-t timeout] [-4|-6]\n"); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s -H -w ,%% -c ,%%\n", progname); + printf(" [-p packets] [-t timeout] [-4|-6]\n"); } -- cgit v0.10-9-g596f From f60f83a522a7d1552d787630455c1b30ce31764a Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 13:35:48 +0100 Subject: check_pgsql: print_usage must be exported diff --git a/plugins/check_pgsql.c b/plugins/check_pgsql.c index 1e35a4c..6613634 100644 --- a/plugins/check_pgsql.c +++ b/plugins/check_pgsql.c @@ -60,10 +60,10 @@ enum { }; static int process_arguments(int /*argc*/, char ** /*argv*/); -static void print_usage(void); static void print_help(void); static bool is_pg_logname(char * /*username*/); static int do_query(PGconn * /*conn*/, char * /*query*/); +void print_usage(void); static char *pghost = NULL; /* host name of the backend server */ static char *pgport = NULL; /* port of the backend server */ -- cgit v0.10-9-g596f From bf53f05ebfa10641a70e85a998928aad8ce8c4b7 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 13:39:22 +0100 Subject: check_ping: update copyright diff --git a/plugins/check_ping.c b/plugins/check_ping.c index 1977546..3fff341 100644 --- a/plugins/check_ping.c +++ b/plugins/check_ping.c @@ -3,7 +3,7 @@ * Monitoring check_ping plugin * * License: GPL - * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -29,7 +29,7 @@ *****************************************************************************/ const char *progname = "check_ping"; -const char *copyright = "2000-2007"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 6d4e76680c96d21b00d565fa0128e6956d0be8a3 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 13:39:35 +0100 Subject: check_ping: do not export local symbols diff --git a/plugins/check_ping.c b/plugins/check_ping.c index 3fff341..6dfb6b6 100644 --- a/plugins/check_ping.c +++ b/plugins/check_ping.c @@ -47,29 +47,29 @@ enum { DEFAULT_MAX_PACKETS = 5 /* default no. of ICMP ECHO packets */ }; -int process_arguments(int, char **); -int get_threshold(char *, float *, int *); -int validate_arguments(void); -int run_ping(const char *cmd, const char *addr); -int error_scan(char buf[MAX_INPUT_BUFFER], const char *addr); +static int process_arguments(int, char **); +static int get_threshold(char *, float *, int *); +static int validate_arguments(void); +static int run_ping(const char *cmd, const char *addr); +static int error_scan(char buf[MAX_INPUT_BUFFER], const char *addr); +static void print_help(void); void print_usage(void); -void print_help(void); - -bool display_html = false; -int wpl = UNKNOWN_PACKET_LOSS; -int cpl = UNKNOWN_PACKET_LOSS; -float wrta = UNKNOWN_TRIP_TIME; -float crta = UNKNOWN_TRIP_TIME; -char **addresses = NULL; -int n_addresses = 0; -int max_addr = 1; -int max_packets = -1; -int verbose = 0; - -float rta = UNKNOWN_TRIP_TIME; -int pl = UNKNOWN_PACKET_LOSS; - -char *warn_text; + +static bool display_html = false; +static int wpl = UNKNOWN_PACKET_LOSS; +static int cpl = UNKNOWN_PACKET_LOSS; +static float wrta = UNKNOWN_TRIP_TIME; +static float crta = UNKNOWN_TRIP_TIME; +static char **addresses = NULL; +static int n_addresses = 0; +static int max_addr = 1; +static int max_packets = -1; +static int verbose = 0; + +static float rta = UNKNOWN_TRIP_TIME; +static int pl = UNKNOWN_PACKET_LOSS; + +static char *warn_text; int main(int argc, char **argv) { char *cmd = NULL; -- cgit v0.10-9-g596f From b227a9f85498e724bd82b4d6bd9fccc02f64763a Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 13:42:06 +0100 Subject: check_ping: linter fixes diff --git a/plugins/check_ping.c b/plugins/check_ping.c index 6dfb6b6..4aafaf4 100644 --- a/plugins/check_ping.c +++ b/plugins/check_ping.c @@ -47,8 +47,8 @@ enum { DEFAULT_MAX_PACKETS = 5 /* default no. of ICMP ECHO packets */ }; -static int process_arguments(int, char **); -static int get_threshold(char *, float *, int *); +static int process_arguments(int /*argc*/, char ** /*argv*/); +static int get_threshold(char * /*arg*/, float * /*trta*/, int * /*tpl*/); static int validate_arguments(void); static int run_ping(const char *cmd, const char *addr); static int error_scan(char buf[MAX_INPUT_BUFFER], const char *addr); -- cgit v0.10-9-g596f From 5b3c12025bf7a2eee43301a634a63dfac6507a7e Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 13:43:05 +0100 Subject: check_real: clang-format diff --git a/plugins/check_real.c b/plugins/check_real.c index 15e035b..03ed655 100644 --- a/plugins/check_real.c +++ b/plugins/check_real.c @@ -1,32 +1,32 @@ /***************************************************************************** -* -* Monitoring check_real plugin -* -* License: GPL -* Copyright (c) 2000-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_real plugin -* -* This plugin tests the REAL service on the specified host. -* -* -* 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_real plugin + * + * License: GPL + * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_real plugin + * + * This plugin tests the REAL service on the specified host. + * + * + * 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_real"; const char *copyright = "2000-2007"; @@ -37,16 +37,16 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" enum { - PORT = 554 + PORT = 554 }; -#define EXPECT "RTSP/1." -#define URL "" +#define EXPECT "RTSP/1." +#define URL "" -int process_arguments (int, char **); -int validate_arguments (void); -void print_help (void); -void print_usage (void); +int process_arguments(int, char **); +int validate_arguments(void); +void print_help(void); +void print_usage(void); int server_port = PORT; char *server_address; @@ -59,99 +59,92 @@ int critical_time = 0; bool check_critical_time = false; bool verbose = false; - - -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { int sd; int result = STATE_UNKNOWN; char buffer[MAX_INPUT_BUFFER]; char *status_line = NULL; - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if (process_arguments (argc, argv) == ERROR) - usage4 (_("Could not parse arguments")); + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments")); /* initialize alarm signal handling */ - signal (SIGALRM, socket_timeout_alarm_handler); + signal(SIGALRM, socket_timeout_alarm_handler); /* set socket timeout */ - alarm (socket_timeout); - time (&start_time); + alarm(socket_timeout); + time(&start_time); /* try to connect to the host at the given port number */ - if (my_tcp_connect (server_address, server_port, &sd) != STATE_OK) - die (STATE_CRITICAL, _("Unable to connect to %s on port %d\n"), - server_address, server_port); + if (my_tcp_connect(server_address, server_port, &sd) != STATE_OK) + die(STATE_CRITICAL, _("Unable to connect to %s on port %d\n"), server_address, server_port); /* Part I - Server Check */ /* send the OPTIONS request */ - sprintf (buffer, "OPTIONS rtsp://%s:%d RTSP/1.0\r\n", host_name, server_port); - result = send (sd, buffer, strlen (buffer), 0); + sprintf(buffer, "OPTIONS rtsp://%s:%d RTSP/1.0\r\n", host_name, server_port); + result = send(sd, buffer, strlen(buffer), 0); /* send the header sync */ - sprintf (buffer, "CSeq: 1\r\n"); - result = send (sd, buffer, strlen (buffer), 0); + sprintf(buffer, "CSeq: 1\r\n"); + result = send(sd, buffer, strlen(buffer), 0); /* send a newline so the server knows we're done with the request */ - sprintf (buffer, "\r\n"); - result = send (sd, buffer, strlen (buffer), 0); + sprintf(buffer, "\r\n"); + result = send(sd, buffer, strlen(buffer), 0); /* watch for the REAL connection string */ - result = recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0); + result = recv(sd, buffer, MAX_INPUT_BUFFER - 1, 0); /* return a CRITICAL status if we couldn't read any data */ if (result == -1) - die (STATE_CRITICAL, _("No data received from %s\n"), host_name); + die(STATE_CRITICAL, _("No data received from %s\n"), host_name); /* make sure we find the response we are looking for */ - if (!strstr (buffer, server_expect)) { + if (!strstr(buffer, server_expect)) { if (server_port == PORT) - printf ("%s\n", _("Invalid REAL response received from host")); + printf("%s\n", _("Invalid REAL response received from host")); else - printf (_("Invalid REAL response received from host on port %d\n"), - server_port); - } - else { + printf(_("Invalid REAL response received from host on port %d\n"), server_port); + } else { /* else we got the REAL string, so check the return code */ - time (&end_time); + time(&end_time); result = STATE_OK; - status_line = (char *) strtok (buffer, "\n"); + status_line = (char *)strtok(buffer, "\n"); - if (strstr (status_line, "200")) + if (strstr(status_line, "200")) result = STATE_OK; /* client errors result in a warning state */ - else if (strstr (status_line, "400")) + else if (strstr(status_line, "400")) result = STATE_WARNING; - else if (strstr (status_line, "401")) + else if (strstr(status_line, "401")) result = STATE_WARNING; - else if (strstr (status_line, "402")) + else if (strstr(status_line, "402")) result = STATE_WARNING; - else if (strstr (status_line, "403")) + else if (strstr(status_line, "403")) result = STATE_WARNING; - else if (strstr (status_line, "404")) + else if (strstr(status_line, "404")) result = STATE_WARNING; /* server errors result in a critical state */ - else if (strstr (status_line, "500")) + else if (strstr(status_line, "500")) result = STATE_CRITICAL; - else if (strstr (status_line, "501")) + else if (strstr(status_line, "501")) result = STATE_CRITICAL; - else if (strstr (status_line, "502")) + else if (strstr(status_line, "502")) result = STATE_CRITICAL; - else if (strstr (status_line, "503")) + else if (strstr(status_line, "503")) result = STATE_CRITICAL; else @@ -159,74 +152,70 @@ main (int argc, char **argv) } /* Part II - Check stream exists and is ok */ - if ((result == STATE_OK )&& (server_url != NULL) ) { + if ((result == STATE_OK) && (server_url != NULL)) { /* Part I - Server Check */ /* send the DESCRIBE request */ - sprintf (buffer, "DESCRIBE rtsp://%s:%d%s RTSP/1.0\r\n", host_name, - server_port, server_url); - result = send (sd, buffer, strlen (buffer), 0); + sprintf(buffer, "DESCRIBE rtsp://%s:%d%s RTSP/1.0\r\n", host_name, server_port, server_url); + result = send(sd, buffer, strlen(buffer), 0); /* send the header sync */ - sprintf (buffer, "CSeq: 2\r\n"); - result = send (sd, buffer, strlen (buffer), 0); + sprintf(buffer, "CSeq: 2\r\n"); + result = send(sd, buffer, strlen(buffer), 0); /* send a newline so the server knows we're done with the request */ - sprintf (buffer, "\r\n"); - result = send (sd, buffer, strlen (buffer), 0); + sprintf(buffer, "\r\n"); + result = send(sd, buffer, strlen(buffer), 0); /* watch for the REAL connection string */ - result = recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0); + result = recv(sd, buffer, MAX_INPUT_BUFFER - 1, 0); buffer[result] = '\0'; /* null terminate received buffer */ /* return a CRITICAL status if we couldn't read any data */ if (result == -1) { - printf (_("No data received from host\n")); + printf(_("No data received from host\n")); result = STATE_CRITICAL; - } - else { + } else { /* make sure we find the response we are looking for */ - if (!strstr (buffer, server_expect)) { + if (!strstr(buffer, server_expect)) { if (server_port == PORT) - printf ("%s\n", _("Invalid REAL response received from host")); + printf("%s\n", _("Invalid REAL response received from host")); else - printf (_("Invalid REAL response received from host on port %d\n"), - server_port); - } - else { + printf(_("Invalid REAL response received from host on port %d\n"), server_port); + } else { /* else we got the REAL string, so check the return code */ - time (&end_time); + time(&end_time); result = STATE_OK; - status_line = (char *) strtok (buffer, "\n"); + status_line = (char *)strtok(buffer, "\n"); - if (strstr (status_line, "200")) + if (strstr(status_line, "200")) result = STATE_OK; /* client errors result in a warning state */ - else if (strstr (status_line, "400")) + else if (strstr(status_line, "400")) result = STATE_WARNING; - else if (strstr (status_line, "401")) + else if (strstr(status_line, "401")) result = STATE_WARNING; - else if (strstr (status_line, "402")) + else if (strstr(status_line, "402")) result = STATE_WARNING; - else if (strstr (status_line, "403")) + else if (strstr(status_line, "403")) result = STATE_WARNING; - else if (strstr (status_line, "404")) + else if (strstr(status_line, "404")) result = STATE_WARNING; /* server errors result in a critical state */ - else if (strstr (status_line, "500")) + else if (strstr(status_line, "500")) result = STATE_CRITICAL; - else if (strstr (status_line, "501")) + else if (strstr(status_line, "501")) result = STATE_CRITICAL; - else if (strstr (status_line, "502")) + else if (strstr(status_line, "502")) result = STATE_CRITICAL; - else if (strstr (status_line, "503")) + else if (strstr(status_line, "503")) result = STATE_CRITICAL; else @@ -238,217 +227,180 @@ main (int argc, char **argv) /* Return results */ if (result == STATE_OK) { - if (check_critical_time - && (end_time - start_time) > critical_time) result = STATE_CRITICAL; - else if (check_warning_time - && (end_time - start_time) > warning_time) result = - STATE_WARNING; + if (check_critical_time && (end_time - start_time) > critical_time) + result = STATE_CRITICAL; + else if (check_warning_time && (end_time - start_time) > warning_time) + result = STATE_WARNING; /* Put some HTML in here to create a dynamic link */ - printf (_("REAL %s - %d second response time\n"), - state_text (result), - (int) (end_time - start_time)); - } - else - printf ("%s\n", status_line); + printf(_("REAL %s - %d second response time\n"), state_text(result), (int)(end_time - start_time)); + } else + printf("%s\n", status_line); /* close the connection */ - close (sd); + close(sd); /* reset the alarm */ - alarm (0); + alarm(0); return result; } - - /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ +int process_arguments(int argc, char **argv) { int c; int option = 0; - static struct option longopts[] = { - {"hostname", required_argument, 0, 'H'}, - {"IPaddress", required_argument, 0, 'I'}, - {"expect", required_argument, 0, 'e'}, - {"url", required_argument, 0, 'u'}, - {"port", required_argument, 0, 'p'}, - {"critical", required_argument, 0, 'c'}, - {"warning", required_argument, 0, 'w'}, - {"timeout", required_argument, 0, 't'}, - {"verbose", no_argument, 0, 'v'}, - {"version", no_argument, 0, 'V'}, - {"help", no_argument, 0, 'h'}, - {0, 0, 0, 0} - }; + static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, {"IPaddress", required_argument, 0, 'I'}, + {"expect", required_argument, 0, 'e'}, {"url", required_argument, 0, 'u'}, + {"port", required_argument, 0, 'p'}, {"critical", required_argument, 0, 'c'}, + {"warning", required_argument, 0, 'w'}, {"timeout", required_argument, 0, 't'}, + {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, {0, 0, 0, 0}}; if (argc < 2) return ERROR; for (c = 1; c < argc; c++) { - if (strcmp ("-to", argv[c]) == 0) - strcpy (argv[c], "-t"); - else if (strcmp ("-wt", argv[c]) == 0) - strcpy (argv[c], "-w"); - else if (strcmp ("-ct", argv[c]) == 0) - strcpy (argv[c], "-c"); + if (strcmp("-to", argv[c]) == 0) + strcpy(argv[c], "-t"); + else if (strcmp("-wt", argv[c]) == 0) + strcpy(argv[c], "-w"); + else if (strcmp("-ct", argv[c]) == 0) + strcpy(argv[c], "-c"); } while (1) { - c = getopt_long (argc, argv, "+hvVI:H:e:u:p:w:c:t:", longopts, - &option); + c = getopt_long(argc, argv, "+hvVI:H:e:u:p:w:c:t:", longopts, &option); if (c == -1 || c == EOF) break; switch (c) { - case 'I': /* hostname */ - case 'H': /* hostname */ + case 'I': /* hostname */ + case 'H': /* hostname */ if (server_address) break; - else if (is_host (optarg)) + else if (is_host(optarg)) server_address = optarg; else - usage2 (_("Invalid hostname/address"), optarg); + usage2(_("Invalid hostname/address"), optarg); break; - case 'e': /* string to expect in response header */ + case 'e': /* string to expect in response header */ server_expect = optarg; break; - case 'u': /* server URL */ + case 'u': /* server URL */ server_url = optarg; break; - case 'p': /* port */ - if (is_intpos (optarg)) { - server_port = atoi (optarg); - } - else { - usage4 (_("Port must be a positive integer")); + case 'p': /* port */ + if (is_intpos(optarg)) { + server_port = atoi(optarg); + } else { + usage4(_("Port must be a positive integer")); } break; - case 'w': /* warning time threshold */ - if (is_intnonneg (optarg)) { - warning_time = atoi (optarg); + case 'w': /* warning time threshold */ + if (is_intnonneg(optarg)) { + warning_time = atoi(optarg); check_warning_time = true; - } - else { - usage4 (_("Warning time must be a positive integer")); + } else { + usage4(_("Warning time must be a positive integer")); } break; - case 'c': /* critical time threshold */ - if (is_intnonneg (optarg)) { - critical_time = atoi (optarg); + case 'c': /* critical time threshold */ + if (is_intnonneg(optarg)) { + critical_time = atoi(optarg); check_critical_time = true; - } - else { - usage4 (_("Critical time must be a positive integer")); + } else { + usage4(_("Critical time must be a positive integer")); } break; - case 'v': /* verbose */ + case 'v': /* verbose */ verbose = true; break; - case 't': /* timeout */ - if (is_intnonneg (optarg)) { - socket_timeout = atoi (optarg); - } - else { - usage4 (_("Timeout interval must be a positive integer")); + case 't': /* timeout */ + if (is_intnonneg(optarg)) { + socket_timeout = atoi(optarg); + } else { + usage4(_("Timeout interval must be a positive integer")); } break; - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case '?': /* usage */ - usage5 (); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case '?': /* usage */ + usage5(); } } c = optind; - if (server_address==NULL && argc>c) { - if (is_host (argv[c])) { + if (server_address == NULL && argc > c) { + if (is_host(argv[c])) { server_address = argv[c++]; - } - else { - usage2 (_("Invalid hostname/address"), argv[c]); + } else { + usage2(_("Invalid hostname/address"), argv[c]); } } - if (server_address==NULL) - usage4 (_("You must provide a server to check")); + if (server_address == NULL) + usage4(_("You must provide a server to check")); - if (host_name==NULL) - host_name = strdup (server_address); + if (host_name == NULL) + host_name = strdup(server_address); if (server_expect == NULL) server_expect = strdup(EXPECT); - return validate_arguments (); + return validate_arguments(); } +int validate_arguments(void) { return OK; } - -int -validate_arguments (void) -{ - return OK; -} - - - -void -print_help (void) -{ +void print_help(void) { char *myport; - xasprintf (&myport, "%d", PORT); + xasprintf(&myport, "%d", PORT); - print_revision (progname, NP_VERSION); + print_revision(progname, NP_VERSION); - printf ("Copyright (c) 1999 Pedro Leite \n"); - printf (COPYRIGHT, copyright, email); + printf("Copyright (c) 1999 Pedro Leite \n"); + printf(COPYRIGHT, copyright, email); - printf ("%s\n", _("This plugin tests the REAL service on the specified host.")); + printf("%s\n", _("This plugin tests the REAL service on the specified host.")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); - printf (UT_HOST_PORT, 'p', myport); + printf(UT_HOST_PORT, 'p', myport); - printf (" %s\n", "-u, --url=STRING"); - printf (" %s\n", _("Connect to this url")); - printf (" %s\n", "-e, --expect=STRING"); - printf (_("String to expect in first line of server response (default: %s)\n"), - EXPECT); + printf(" %s\n", "-u, --url=STRING"); + printf(" %s\n", _("Connect to this url")); + printf(" %s\n", "-e, --expect=STRING"); + printf(_("String to expect in first line of server response (default: %s)\n"), EXPECT); - printf (UT_WARN_CRIT); + printf(UT_WARN_CRIT); - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - printf (UT_VERBOSE); + printf(UT_VERBOSE); - printf ("\n"); - printf ("%s\n", _("This plugin will attempt to open an RTSP connection with the host.")); - printf ("%s\n", _("Successful connects return STATE_OK, refusals and timeouts return")); - printf ("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful connects,")); - printf ("%s\n", _("but incorrect response messages from the host result in STATE_WARNING return")); - printf ("%s\n", _("values.")); + printf("\n"); + printf("%s\n", _("This plugin will attempt to open an RTSP connection with the host.")); + printf("%s\n", _("Successful connects return STATE_OK, refusals and timeouts return")); + printf("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful connects,")); + printf("%s\n", _("but incorrect response messages from the host result in STATE_WARNING return")); + printf("%s\n", _("values.")); - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s -H host [-e expect] [-p port] [-w warn] [-c crit] [-t timeout] [-v]\n", progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s -H host [-e expect] [-p port] [-w warn] [-c crit] [-t timeout] [-v]\n", progname); } -- cgit v0.10-9-g596f From 5dcd63f11019d55f0de58ead32cbc01741dd2f1c Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 13:47:20 +0100 Subject: check_real: style and linter fixes diff --git a/plugins/check_real.c b/plugins/check_real.c index 03ed655..cfab26f 100644 --- a/plugins/check_real.c +++ b/plugins/check_real.c @@ -43,28 +43,22 @@ enum { #define EXPECT "RTSP/1." #define URL "" -int process_arguments(int, char **); -int validate_arguments(void); -void print_help(void); +static int process_arguments(int, char **); +static void print_help(void); void print_usage(void); -int server_port = PORT; -char *server_address; -char *host_name; -char *server_url = NULL; -char *server_expect; -int warning_time = 0; -bool check_warning_time = false; -int critical_time = 0; -bool check_critical_time = false; -bool verbose = false; +static int server_port = PORT; +static char *server_address; +static char *host_name; +static char *server_url = NULL; +static char *server_expect; +static int warning_time = 0; +static bool check_warning_time = false; +static int critical_time = 0; +static bool check_critical_time = false; +static bool verbose = false; int main(int argc, char **argv) { - int sd; - int result = STATE_UNKNOWN; - char buffer[MAX_INPUT_BUFFER]; - char *status_line = NULL; - setlocale(LC_ALL, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); @@ -83,30 +77,33 @@ int main(int argc, char **argv) { time(&start_time); /* try to connect to the host at the given port number */ - if (my_tcp_connect(server_address, server_port, &sd) != STATE_OK) + int socket; + if (my_tcp_connect(server_address, server_port, &socket) != STATE_OK) die(STATE_CRITICAL, _("Unable to connect to %s on port %d\n"), server_address, server_port); /* Part I - Server Check */ /* send the OPTIONS request */ + char buffer[MAX_INPUT_BUFFER]; sprintf(buffer, "OPTIONS rtsp://%s:%d RTSP/1.0\r\n", host_name, server_port); - result = send(sd, buffer, strlen(buffer), 0); + int result = send(socket, buffer, strlen(buffer), 0); /* send the header sync */ sprintf(buffer, "CSeq: 1\r\n"); - result = send(sd, buffer, strlen(buffer), 0); + result = send(socket, buffer, strlen(buffer), 0); /* send a newline so the server knows we're done with the request */ sprintf(buffer, "\r\n"); - result = send(sd, buffer, strlen(buffer), 0); + result = send(socket, buffer, strlen(buffer), 0); /* watch for the REAL connection string */ - result = recv(sd, buffer, MAX_INPUT_BUFFER - 1, 0); + result = recv(socket, buffer, MAX_INPUT_BUFFER - 1, 0); /* return a CRITICAL status if we couldn't read any data */ if (result == -1) die(STATE_CRITICAL, _("No data received from %s\n"), host_name); + char *status_line = NULL; /* make sure we find the response we are looking for */ if (!strstr(buffer, server_expect)) { if (server_port == PORT) @@ -158,18 +155,18 @@ int main(int argc, char **argv) { /* send the DESCRIBE request */ sprintf(buffer, "DESCRIBE rtsp://%s:%d%s RTSP/1.0\r\n", host_name, server_port, server_url); - result = send(sd, buffer, strlen(buffer), 0); + result = send(socket, buffer, strlen(buffer), 0); /* send the header sync */ sprintf(buffer, "CSeq: 2\r\n"); - result = send(sd, buffer, strlen(buffer), 0); + result = send(socket, buffer, strlen(buffer), 0); /* send a newline so the server knows we're done with the request */ sprintf(buffer, "\r\n"); - result = send(sd, buffer, strlen(buffer), 0); + result = send(socket, buffer, strlen(buffer), 0); /* watch for the REAL connection string */ - result = recv(sd, buffer, MAX_INPUT_BUFFER - 1, 0); + result = recv(socket, buffer, MAX_INPUT_BUFFER - 1, 0); buffer[result] = '\0'; /* null terminate received buffer */ /* return a CRITICAL status if we couldn't read any data */ @@ -238,7 +235,7 @@ int main(int argc, char **argv) { printf("%s\n", status_line); /* close the connection */ - close(sd); + close(socket); /* reset the alarm */ alarm(0); @@ -248,9 +245,6 @@ int main(int argc, char **argv) { /* process command-line arguments */ int process_arguments(int argc, char **argv) { - int c; - - int option = 0; static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, {"IPaddress", required_argument, 0, 'I'}, {"expect", required_argument, 0, 'e'}, {"url", required_argument, 0, 'u'}, {"port", required_argument, 0, 'p'}, {"critical", required_argument, 0, 'c'}, @@ -261,22 +255,24 @@ int process_arguments(int argc, char **argv) { if (argc < 2) return ERROR; - for (c = 1; c < argc; c++) { - if (strcmp("-to", argv[c]) == 0) - strcpy(argv[c], "-t"); - else if (strcmp("-wt", argv[c]) == 0) - strcpy(argv[c], "-w"); - else if (strcmp("-ct", argv[c]) == 0) - strcpy(argv[c], "-c"); + for (int i = 1; i < argc; i++) { + if (strcmp("-to", argv[i]) == 0) + strcpy(argv[i], "-t"); + else if (strcmp("-wt", argv[i]) == 0) + strcpy(argv[i], "-w"); + else if (strcmp("-ct", argv[i]) == 0) + strcpy(argv[i], "-c"); } - while (1) { - c = getopt_long(argc, argv, "+hvVI:H:e:u:p:w:c:t:", longopts, &option); + int option_char; + while (true) { + int option = 0; + option_char = getopt_long(argc, argv, "+hvVI:H:e:u:p:w:c:t:", longopts, &option); - if (c == -1 || c == EOF) + if (option_char == -1 || option_char == EOF) break; - switch (c) { + switch (option_char) { case 'I': /* hostname */ case 'H': /* hostname */ if (server_address) @@ -336,12 +332,12 @@ int process_arguments(int argc, char **argv) { } } - c = optind; - if (server_address == NULL && argc > c) { - if (is_host(argv[c])) { - server_address = argv[c++]; + option_char = optind; + if (server_address == NULL && argc > option_char) { + if (is_host(argv[option_char])) { + server_address = argv[option_char++]; } else { - usage2(_("Invalid hostname/address"), argv[c]); + usage2(_("Invalid hostname/address"), argv[option_char]); } } @@ -354,11 +350,9 @@ int process_arguments(int argc, char **argv) { if (server_expect == NULL) server_expect = strdup(EXPECT); - return validate_arguments(); + return OK; } -int validate_arguments(void) { return OK; } - void print_help(void) { char *myport; xasprintf(&myport, "%d", PORT); -- cgit v0.10-9-g596f From b033e670c6adf4073428f644e76e8d1c77fe0198 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 13:47:49 +0100 Subject: check_real: update copyright diff --git a/plugins/check_real.c b/plugins/check_real.c index cfab26f..369a88b 100644 --- a/plugins/check_real.c +++ b/plugins/check_real.c @@ -3,7 +3,7 @@ * Monitoring check_real plugin * * License: GPL - * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -29,7 +29,7 @@ *****************************************************************************/ const char *progname = "check_real"; -const char *copyright = "2000-2007"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 50f6ae2c6433d954027e7102f4f3982ba1cf048d Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 13:56:00 +0100 Subject: check_snmp: clang-format diff --git a/plugins/check_snmp.c b/plugins/check_snmp.c index 90a0402..2bfdcfe 100644 --- a/plugins/check_snmp.c +++ b/plugins/check_snmp.c @@ -1,32 +1,32 @@ /***************************************************************************** -* -* 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 . -* -* -*****************************************************************************/ + * + * 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"; const char *copyright = "1999-2007"; @@ -37,60 +37,68 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #include "utils_cmd.h" -#define DEFAULT_COMMUNITY "public" -#define DEFAULT_PORT "161" -#define DEFAULT_MIBLIST "ALL" -#define DEFAULT_PROTOCOL "1" -#define DEFAULT_RETRIES 5 -#define DEFAULT_AUTH_PROTOCOL "MD5" -#define DEFAULT_PRIV_PROTOCOL "DES" -#define DEFAULT_DELIMITER "=" +#define DEFAULT_COMMUNITY "public" +#define DEFAULT_PORT "161" +#define DEFAULT_MIBLIST "ALL" +#define DEFAULT_PROTOCOL "1" +#define DEFAULT_RETRIES 5 +#define DEFAULT_AUTH_PROTOCOL "MD5" +#define DEFAULT_PRIV_PROTOCOL "DES" +#define DEFAULT_DELIMITER "=" #define DEFAULT_OUTPUT_DELIMITER " " -#define DEFAULT_BUFFER_SIZE 100 +#define DEFAULT_BUFFER_SIZE 100 -#define mark(a) ((a)!=0?"*":"") +#define mark(a) ((a) != 0 ? "*" : "") -#define CHECK_UNDEF 0 +#define CHECK_UNDEF 0 #define CRIT_PRESENT 1 -#define CRIT_STRING 2 -#define CRIT_REGEX 4 +#define CRIT_STRING 2 +#define CRIT_REGEX 4 #define WARN_PRESENT 8 #define OID_COUNT_STEP 8 /* Longopts only arguments */ -#define L_CALCULATE_RATE CHAR_MAX+1 -#define L_RATE_MULTIPLIER CHAR_MAX+2 -#define L_INVERT_SEARCH CHAR_MAX+3 -#define L_OFFSET CHAR_MAX+4 -#define L_IGNORE_MIB_PARSING_ERRORS CHAR_MAX+5 +#define L_CALCULATE_RATE CHAR_MAX + 1 +#define L_RATE_MULTIPLIER CHAR_MAX + 2 +#define L_INVERT_SEARCH CHAR_MAX + 3 +#define L_OFFSET CHAR_MAX + 4 +#define L_IGNORE_MIB_PARSING_ERRORS CHAR_MAX + 5 /* Gobble to string - stop incrementing c when c[0] match one of the * characters in s */ -#define GOBBLE_TOS(c, s) while(c[0]!='\0' && strchr(s, c[0])==NULL) { c++; } +#define GOBBLE_TOS(c, s) \ + while (c[0] != '\0' && strchr(s, c[0]) == NULL) { \ + c++; \ + } /* Given c, keep track of backslashes (bk) and double-quotes (dq) * from c[0] */ -#define COUNT_SEQ(c, bk, dq) switch(c[0]) {\ - case '\\': \ - if (bk) bk--; \ - else bk++; \ - break; \ - case '"': \ - if (!dq) { dq++; } \ - else if(!bk) { dq--; } \ - else { bk--; } \ - break; \ +#define COUNT_SEQ(c, bk, dq) \ + switch (c[0]) { \ + case '\\': \ + if (bk) \ + bk--; \ + else \ + bk++; \ + break; \ + case '"': \ + if (!dq) { \ + dq++; \ + } else if (!bk) { \ + dq--; \ + } else { \ + bk--; \ + } \ + break; \ } - - -static int process_arguments (int, char **); -static int validate_arguments (void); -static char *thisarg (char *str); -static char *nextarg (char *str); -void print_usage (void); -static void print_help (void); -static char *multiply (char *str); +static int process_arguments(int, char **); +static int validate_arguments(void); +static char *thisarg(char *str); +static char *nextarg(char *str); +void print_usage(void); +static void print_help(void); +static char *multiply(char *str); #include "regex.h" static char regex_expect[MAX_INPUT_BUFFER] = ""; @@ -122,7 +130,7 @@ static char *units; static char *port; static char *snmpcmd; static char string_value[MAX_INPUT_BUFFER] = ""; -static int invert_search=0; +static int invert_search = 0; static char **labels = NULL; static char **unitv = NULL; static size_t nlabels = 0; @@ -154,15 +162,14 @@ static state_data *previous_state; static double *previous_value; static size_t previous_size = OID_COUNT_STEP; static int perf_labels = 1; -static char* ip_version = ""; +static char *ip_version = ""; static double multiplier = 1.0; static char *fmtstr = ""; static bool fmtstr_set = false; static char buffer[DEFAULT_BUFFER_SIZE]; static bool ignore_mib_parsing_errors = false; -static char *fix_snmp_range(char *th) -{ +static char *fix_snmp_range(char *th) { double left, right; char *colon, *ret; @@ -182,9 +189,7 @@ static char *fix_snmp_range(char *th) return ret; } -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { int len, total_oids; size_t line; unsigned int bk_count = 0, dq_count = 0; @@ -200,80 +205,80 @@ main (int argc, char **argv) char *outbuff; char *ptr = NULL; char *show = NULL; - char *th_warn=NULL; - char *th_crit=NULL; + char *th_warn = NULL; + char *th_crit = NULL; char type[8] = ""; output chld_out, chld_err; - char *previous_string=NULL; - char *ap=NULL; - char *state_string=NULL; + char *previous_string = NULL; + char *ap = NULL; + char *state_string = NULL; size_t response_length, current_length, string_length; - char *temp_string=NULL; - char *quote_string=NULL; + char *temp_string = NULL; + char *quote_string = NULL; time_t current_time; double temp_double; time_t duration; char *conv = "12345678"; - int is_counter=0; - - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); - - labels = malloc (labels_size * sizeof(*labels)); - unitv = malloc (unitv_size * sizeof(*unitv)); - thlds = malloc (thlds_size * sizeof(*thlds)); - response_value = malloc (response_size * sizeof(*response_value)); - previous_value = malloc (previous_size * sizeof(*previous_value)); - eval_method = calloc (eval_size, sizeof(*eval_method)); - oids = calloc(oids_size, sizeof (char *)); - - label = strdup ("SNMP"); - units = strdup (""); - port = strdup (DEFAULT_PORT); - outbuff = strdup (""); - delimiter = strdup (" = "); - output_delim = strdup (DEFAULT_OUTPUT_DELIMITER); + int is_counter = 0; + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + + labels = malloc(labels_size * sizeof(*labels)); + unitv = malloc(unitv_size * sizeof(*unitv)); + thlds = malloc(thlds_size * sizeof(*thlds)); + response_value = malloc(response_size * sizeof(*response_value)); + previous_value = malloc(previous_size * sizeof(*previous_value)); + eval_method = calloc(eval_size, sizeof(*eval_method)); + oids = calloc(oids_size, sizeof(char *)); + + label = strdup("SNMP"); + units = strdup(""); + port = strdup(DEFAULT_PORT); + outbuff = strdup(""); + delimiter = strdup(" = "); + output_delim = strdup(DEFAULT_OUTPUT_DELIMITER); timeout_interval = DEFAULT_SOCKET_TIMEOUT; retries = DEFAULT_RETRIES; - np_init( (char *) progname, argc, argv ); + np_init((char *)progname, argc, argv); /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); np_set_args(argc, argv); time(¤t_time); - if (process_arguments (argc, argv) == ERROR) - usage4 (_("Could not parse arguments")); + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments")); - if(calculate_rate) { + if (calculate_rate) { if (!strcmp(label, "SNMP")) label = strdup("SNMP RATE"); size_t i = 0; previous_state = np_state_read(); - if(previous_state!=NULL) { + if (previous_state != NULL) { /* Split colon separated values */ - previous_string = strdup((char *) previous_state->data); - while((ap = strsep(&previous_string, ":")) != NULL) { - if(verbose>2) + previous_string = strdup((char *)previous_state->data); + while ((ap = strsep(&previous_string, ":")) != NULL) { + if (verbose > 2) printf("State for %zd=%s\n", i, ap); while (i >= previous_size) { previous_size += OID_COUNT_STEP; previous_value = realloc(previous_value, previous_size * sizeof(*previous_value)); } - previous_value[i++]=strtod(ap,NULL); + previous_value[i++] = strtod(ap, NULL); } } } /* Populate the thresholds */ - th_warn=warning_thresholds; - th_crit=critical_thresholds; + th_warn = warning_thresholds; + th_crit = critical_thresholds; for (size_t i = 0; i < numoids; i++) { char *w = th_warn ? strndup(th_warn, strcspn(th_warn, ",")) : NULL; char *c = th_crit ? strndup(th_crit, strcspn(th_crit, ",")) : NULL; @@ -287,53 +292,52 @@ main (int argc, char **argv) } /* Skip empty thresholds, while avoiding segfault */ - set_thresholds(&thlds[i], - w ? strpbrk(w, NP_THRESHOLDS_CHARS) : NULL, - c ? strpbrk(c, NP_THRESHOLDS_CHARS) : NULL); + set_thresholds(&thlds[i], w ? strpbrk(w, NP_THRESHOLDS_CHARS) : NULL, c ? strpbrk(c, NP_THRESHOLDS_CHARS) : NULL); if (w) { - th_warn=strchr(th_warn, ','); - if (th_warn) th_warn++; + th_warn = strchr(th_warn, ','); + if (th_warn) + th_warn++; free(w); } if (c) { - th_crit=strchr(th_crit, ','); - if (th_crit) th_crit++; + th_crit = strchr(th_crit, ','); + if (th_crit) + th_crit++; free(c); } } /* Create the command array to execute */ - if(usesnmpgetnext) { - snmpcmd = strdup (PATH_TO_SNMPGETNEXT); - }else{ - snmpcmd = strdup (PATH_TO_SNMPGET); + if (usesnmpgetnext) { + snmpcmd = strdup(PATH_TO_SNMPGETNEXT); + } else { + snmpcmd = strdup(PATH_TO_SNMPGET); } /* 10 arguments to pass before context and authpriv options + 1 for host and numoids. Add one for terminating NULL */ unsigned index = 0; - command_line = calloc (11 + numcontext + numauthpriv + 1 + numoids + 1, sizeof (char *)); + command_line = calloc(11 + numcontext + numauthpriv + 1 + numoids + 1, sizeof(char *)); command_line[index++] = snmpcmd; - command_line[index++] = strdup ("-Le"); - command_line[index++] = strdup ("-t"); - xasprintf (&command_line[index++], "%d", timeout_interval); - command_line[index++] = strdup ("-r"); - xasprintf (&command_line[index++], "%d", retries); - command_line[index++] = strdup ("-m"); - command_line[index++] = strdup (miblist); + command_line[index++] = strdup("-Le"); + command_line[index++] = strdup("-t"); + xasprintf(&command_line[index++], "%d", timeout_interval); + command_line[index++] = strdup("-r"); + xasprintf(&command_line[index++], "%d", retries); + command_line[index++] = strdup("-m"); + command_line[index++] = strdup(miblist); command_line[index++] = "-v"; - command_line[index++] = strdup (proto); + command_line[index++] = strdup(proto); - xasprintf(&cl_hidden_auth, "%s -Le -t %d -r %d -m %s -v %s", - snmpcmd, timeout_interval, retries, strlen(miblist) ? miblist : "''", proto); + xasprintf(&cl_hidden_auth, "%s -Le -t %d -r %d -m %s -v %s", snmpcmd, timeout_interval, retries, strlen(miblist) ? miblist : "''", + proto); if (ignore_mib_parsing_errors) { command_line[index++] = "-Pe"; xasprintf(&cl_hidden_auth, "%s -Pe", cl_hidden_auth); } - for (int i = 0; i < numcontext; i++) { command_line[index++] = contextargs[i]; } @@ -342,12 +346,9 @@ main (int argc, char **argv) command_line[index++] = authpriv[i]; } - xasprintf (&command_line[index++], "%s:%s", server_address, port); + xasprintf(&command_line[index++], "%s:%s", server_address, port); - xasprintf(&cl_hidden_auth, "%s [context] [authpriv] %s:%s", - cl_hidden_auth, - server_address, - port); + xasprintf(&cl_hidden_auth, "%s [context] [authpriv] %s:%s", cl_hidden_auth, server_address, port); for (size_t i = 0; i < numoids; i++) { command_line[index++] = oids[i]; @@ -357,17 +358,17 @@ main (int argc, char **argv) command_line[index++] = NULL; if (verbose) { - printf ("%s\n", cl_hidden_auth); + printf("%s\n", cl_hidden_auth); } /* Set signal handling and alarm */ - if (signal (SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) { - usage4 (_("Cannot catch SIGALRM")); + if (signal(SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) { + usage4(_("Cannot catch SIGALRM")); } alarm(timeout_interval * retries + 5); /* Run the command */ - return_code = cmd_run_array (command_line, &chld_out, &chld_err, 0); + return_code = cmd_run_array(command_line, &chld_out, &chld_err, 0); /* disable alarm again */ alarm(0); @@ -377,80 +378,74 @@ main (int argc, char **argv) Do this way so that if there is stderr, will get added to output, which helps problem diagnosis */ if (return_code != 0) - external_error=1; + external_error = 1; if (chld_out.lines == 0) - external_error=1; + external_error = 1; if (external_error) { if (chld_err.lines > 0) { - printf (_("External command error: %s\n"), chld_err.line[0]); + printf(_("External command error: %s\n"), chld_err.line[0]); for (size_t i = 1; i < chld_err.lines; i++) { - printf ("%s\n", chld_err.line[i]); + printf("%s\n", chld_err.line[i]); } } else { printf(_("External command error with no output (return code: %d)\n"), return_code); } - exit (STATE_UNKNOWN); + exit(STATE_UNKNOWN); } if (verbose) { for (size_t i = 0; i < chld_out.lines; i++) { - printf ("%s\n", chld_out.line[i]); + printf("%s\n", chld_out.line[i]); } } line = 0; total_oids = 0; - for (size_t i = 0; line < chld_out.lines && i < numoids ; line++, i++, total_oids++) { - if(calculate_rate) + for (size_t i = 0; line < chld_out.lines && i < numoids; line++, i++, total_oids++) { + if (calculate_rate) conv = "%.10g"; else conv = "%.0f"; ptr = chld_out.line[line]; - oidname = strpcpy (oidname, ptr, delimiter); - response = strstr (ptr, delimiter); + oidname = strpcpy(oidname, ptr, delimiter); + response = strstr(ptr, delimiter); if (response == NULL) break; if (verbose > 2) { - printf("Processing oid %zi (line %zi)\n oidname: %s\n response: %s\n", i+1, line+1, oidname, response); + printf("Processing oid %zi (line %zi)\n oidname: %s\n response: %s\n", i + 1, line + 1, oidname, response); } /* Clean up type array - Sol10 does not necessarily zero it out */ bzero(type, sizeof(type)); - is_counter=0; + is_counter = 0; /* We strip out the datatype indicator for PHBs */ - if (strstr (response, "Gauge: ")) { - show = multiply (strstr (response, "Gauge: ") + 7); - } - else if (strstr (response, "Gauge32: ")) { - show = multiply (strstr (response, "Gauge32: ") + 9); - } - else if (strstr (response, "Counter32: ")) { - show = strstr (response, "Counter32: ") + 11; - is_counter=1; - if(!calculate_rate) + if (strstr(response, "Gauge: ")) { + show = multiply(strstr(response, "Gauge: ") + 7); + } else if (strstr(response, "Gauge32: ")) { + show = multiply(strstr(response, "Gauge32: ") + 9); + } else if (strstr(response, "Counter32: ")) { + show = strstr(response, "Counter32: ") + 11; + is_counter = 1; + if (!calculate_rate) strcpy(type, "c"); - } - else if (strstr (response, "Counter64: ")) { - show = strstr (response, "Counter64: ") + 11; - is_counter=1; - if(!calculate_rate) + } else if (strstr(response, "Counter64: ")) { + show = strstr(response, "Counter64: ") + 11; + is_counter = 1; + if (!calculate_rate) strcpy(type, "c"); - } - else if (strstr (response, "INTEGER: ")) { - show = multiply (strstr (response, "INTEGER: ") + 9); + } else if (strstr(response, "INTEGER: ")) { + show = multiply(strstr(response, "INTEGER: ") + 9); if (fmtstr_set) { conv = fmtstr; } - } - else if (strstr (response, "OID: ")) { - show = strstr (response, "OID: ") + 5; - } - else if (strstr (response, "STRING: ")) { - show = strstr (response, "STRING: ") + 8; + } else if (strstr(response, "OID: ")) { + show = strstr(response, "OID: ") + 5; + } else if (strstr(response, "STRING: ")) { + show = strstr(response, "STRING: ") + 8; conv = "%.10g"; /* Get the rest of the string on multi-line strings */ @@ -464,15 +459,17 @@ main (int argc, char **argv) if (dq_count) { /* unfinished line */ /* copy show verbatim first */ - if (!mult_resp) mult_resp = strdup(""); - xasprintf (&mult_resp, "%s%s:\n%s\n", mult_resp, oids[i], show); + if (!mult_resp) + mult_resp = strdup(""); + xasprintf(&mult_resp, "%s%s:\n%s\n", mult_resp, oids[i], show); /* then strip out unmatched double-quote from single-line output */ - if (show[0] == '"') show++; + if (show[0] == '"') + show++; /* Keep reading until we match end of double-quoted string */ for (line++; line < chld_out.lines; line++) { ptr = chld_out.line[line]; - xasprintf (&mult_resp, "%s%s\n", mult_resp, ptr); + xasprintf(&mult_resp, "%s%s\n", mult_resp, ptr); COUNT_SEQ(ptr, bk_count, dq_count) while (dq_count && ptr[0] != '\n' && ptr[0] != '\0') { @@ -481,15 +478,14 @@ main (int argc, char **argv) COUNT_SEQ(ptr, bk_count, dq_count) } /* Break for loop before next line increment when done */ - if (!dq_count) break; + if (!dq_count) + break; } } - } - else if (strstr (response, "Timeticks: ")) { - show = strstr (response, "Timeticks: "); - } - else + } else if (strstr(response, "Timeticks: ")) { + show = strstr(response, "Timeticks: "); + } else show = response + 3; iresult = STATE_DEPENDENT; @@ -500,68 +496,67 @@ main (int argc, char **argv) if (verbose > 2) { print_thresholds(" thresholds", thlds[i]); } - ptr = strpbrk (show, "-0123456789"); - if (ptr == NULL){ + ptr = strpbrk(show, "-0123456789"); + if (ptr == NULL) { if (nulloid == 3) - die (STATE_UNKNOWN,_("No valid data returned (%s)\n"), show); + die(STATE_UNKNOWN, _("No valid data returned (%s)\n"), show); else if (nulloid == 0) - die (STATE_OK,_("No valid data returned (%s)\n"), show); + die(STATE_OK, _("No valid data returned (%s)\n"), show); else if (nulloid == 1) - die (STATE_WARNING,_("No valid data returned (%s)\n"), show); + die(STATE_WARNING, _("No valid data returned (%s)\n"), show); else if (nulloid == 2) - die (STATE_CRITICAL,_("No valid data returned (%s)\n"), show); + die(STATE_CRITICAL, _("No valid data returned (%s)\n"), show); } while (i >= response_size) { response_size += OID_COUNT_STEP; response_value = realloc(response_value, response_size * sizeof(*response_value)); } - response_value[i] = strtod (ptr, NULL) + offset; - - if(calculate_rate) { - if (previous_state!=NULL) { - duration = current_time-previous_state->time; - if(duration<=0) - die(STATE_UNKNOWN,_("Time duration between plugin calls is invalid")); - temp_double = response_value[i]-previous_value[i]; + response_value[i] = strtod(ptr, NULL) + offset; + + if (calculate_rate) { + if (previous_state != NULL) { + duration = current_time - previous_state->time; + if (duration <= 0) + die(STATE_UNKNOWN, _("Time duration between plugin calls is invalid")); + temp_double = response_value[i] - previous_value[i]; /* Simple overflow catcher (same as in rrdtool, rrd_update.c) */ - if(is_counter) { - if(temp_double<(double)0.0) - temp_double+=(double)4294967296.0; /* 2^32 */ - if(temp_double<(double)0.0) - temp_double+=(double)18446744069414584320.0; /* 2^64-2^32 */; + if (is_counter) { + if (temp_double < (double)0.0) + temp_double += (double)4294967296.0; /* 2^32 */ + if (temp_double < (double)0.0) + temp_double += (double)18446744069414584320.0; /* 2^64-2^32 */ + ; } /* Convert to per second, then use multiplier */ - temp_double = temp_double/duration*rate_multiplier; + temp_double = temp_double / duration * rate_multiplier; iresult = get_status(temp_double, thlds[i]); - xasprintf (&show, conv, temp_double); + xasprintf(&show, conv, temp_double); } } else { iresult = get_status(response_value[i], thlds[i]); - xasprintf (&show, conv, response_value[i]); + xasprintf(&show, conv, response_value[i]); } } /* Process this block for string matching */ else if (eval_size > i && eval_method[i] & CRIT_STRING) { - if (strcmp (show, string_value)) - iresult = (invert_search==0) ? STATE_CRITICAL : STATE_OK; + if (strcmp(show, string_value)) + iresult = (invert_search == 0) ? STATE_CRITICAL : STATE_OK; else - iresult = (invert_search==0) ? STATE_OK : STATE_CRITICAL; + iresult = (invert_search == 0) ? STATE_OK : STATE_CRITICAL; } /* Process this block for regex matching */ else if (eval_size > i && eval_method[i] & CRIT_REGEX) { - excode = regexec (&preg, response, 10, pmatch, eflags); + excode = regexec(&preg, response, 10, pmatch, eflags); if (excode == 0) { - iresult = (invert_search==0) ? STATE_OK : STATE_CRITICAL; - } - else if (excode != REG_NOMATCH) { - regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER); - printf (_("Execute Error: %s\n"), errbuf); - exit (STATE_CRITICAL); - } - else { - iresult = (invert_search==0) ? STATE_CRITICAL : STATE_OK; + iresult = (invert_search == 0) ? STATE_OK : STATE_CRITICAL; + } else if (excode != REG_NOMATCH) { + regerror(excode, &preg, errbuf, MAX_INPUT_BUFFER); + printf(_("Execute Error: %s\n"), errbuf); + exit(STATE_CRITICAL); + } else { + iresult = (invert_search == 0) ? STATE_CRITICAL : STATE_OK; } } @@ -577,294 +572,285 @@ main (int argc, char **argv) } /* Result is the worst outcome of all the OIDs tested */ - result = max_state (result, iresult); + result = max_state(result, iresult); /* Prepend a label for this OID if there is one */ if (nlabels >= (size_t)1 && (size_t)i < nlabels && labels[i] != NULL) - xasprintf (&outbuff, "%s%s%s %s%s%s", outbuff, - (i == 0) ? " " : output_delim, - labels[i], mark (iresult), show, mark (iresult)); + xasprintf(&outbuff, "%s%s%s %s%s%s", outbuff, (i == 0) ? " " : output_delim, labels[i], mark(iresult), show, mark(iresult)); else - xasprintf (&outbuff, "%s%s%s%s%s", outbuff, (i == 0) ? " " : output_delim, - mark (iresult), show, mark (iresult)); + xasprintf(&outbuff, "%s%s%s%s%s", outbuff, (i == 0) ? " " : output_delim, mark(iresult), show, mark(iresult)); /* Append a unit string for this OID if there is one */ if (nunits > (size_t)0 && (size_t)i < nunits && unitv[i] != NULL) - xasprintf (&outbuff, "%s %s", outbuff, unitv[i]); + xasprintf(&outbuff, "%s %s", outbuff, unitv[i]); /* Write perfdata with whatever can be parsed by strtod, if possible */ ptr = NULL; strtod(show, &ptr); if (ptr > show) { if (perf_labels && nlabels >= (size_t)1 && (size_t)i < nlabels && labels[i] != NULL) - temp_string=labels[i]; + temp_string = labels[i]; else - temp_string=oidname; - if (strpbrk (temp_string, " ='\"") == NULL) { - strncat(perfstr, temp_string, sizeof(perfstr)-strlen(perfstr)-1); + temp_string = oidname; + if (strpbrk(temp_string, " ='\"") == NULL) { + strncat(perfstr, temp_string, sizeof(perfstr) - strlen(perfstr) - 1); } else { - if (strpbrk (temp_string, "'") == NULL) { - quote_string="'"; + if (strpbrk(temp_string, "'") == NULL) { + quote_string = "'"; } else { - quote_string="\""; + quote_string = "\""; } - strncat(perfstr, quote_string, sizeof(perfstr)-strlen(perfstr)-1); - strncat(perfstr, temp_string, sizeof(perfstr)-strlen(perfstr)-1); - strncat(perfstr, quote_string, sizeof(perfstr)-strlen(perfstr)-1); + strncat(perfstr, quote_string, sizeof(perfstr) - strlen(perfstr) - 1); + strncat(perfstr, temp_string, sizeof(perfstr) - strlen(perfstr) - 1); + strncat(perfstr, quote_string, sizeof(perfstr) - strlen(perfstr) - 1); } - strncat(perfstr, "=", sizeof(perfstr)-strlen(perfstr)-1); - len = sizeof(perfstr)-strlen(perfstr)-1; - strncat(perfstr, show, len>ptr-show ? ptr-show : len); + strncat(perfstr, "=", sizeof(perfstr) - strlen(perfstr) - 1); + len = sizeof(perfstr) - strlen(perfstr) - 1; + strncat(perfstr, show, len > ptr - show ? ptr - show : len); if (strcmp(type, "") != 0) { - strncat(perfstr, type, sizeof(perfstr)-strlen(perfstr)-1); + strncat(perfstr, type, sizeof(perfstr) - strlen(perfstr) - 1); } if (warning_thresholds) { - strncat(perfstr, ";", sizeof(perfstr)-strlen(perfstr)-1); - if(thlds[i]->warning && thlds[i]->warning->text) - strncat(perfstr, thlds[i]->warning->text, sizeof(perfstr)-strlen(perfstr)-1); + strncat(perfstr, ";", sizeof(perfstr) - strlen(perfstr) - 1); + if (thlds[i]->warning && thlds[i]->warning->text) + strncat(perfstr, thlds[i]->warning->text, sizeof(perfstr) - strlen(perfstr) - 1); } if (critical_thresholds) { if (!warning_thresholds) - strncat(perfstr, ";", sizeof(perfstr)-strlen(perfstr)-1); - strncat(perfstr, ";", sizeof(perfstr)-strlen(perfstr)-1); - if(thlds[i]->critical && thlds[i]->critical->text) - strncat(perfstr, thlds[i]->critical->text, sizeof(perfstr)-strlen(perfstr)-1); + strncat(perfstr, ";", sizeof(perfstr) - strlen(perfstr) - 1); + strncat(perfstr, ";", sizeof(perfstr) - strlen(perfstr) - 1); + if (thlds[i]->critical && thlds[i]->critical->text) + strncat(perfstr, thlds[i]->critical->text, sizeof(perfstr) - strlen(perfstr) - 1); } - strncat(perfstr, " ", sizeof(perfstr)-strlen(perfstr)-1); + strncat(perfstr, " ", sizeof(perfstr) - strlen(perfstr) - 1); } } /* Save state data, as all data collected now */ - if(calculate_rate) { - string_length=1024; - state_string=malloc(string_length); - if(state_string==NULL) + if (calculate_rate) { + string_length = 1024; + state_string = malloc(string_length); + if (state_string == NULL) die(STATE_UNKNOWN, _("Cannot malloc")); - current_length=0; - for(int i = 0; i < total_oids; i++) { - xasprintf(&temp_string,"%.0f",response_value[i]); - if(temp_string==NULL) - die(STATE_UNKNOWN,_("Cannot asprintf()")); + current_length = 0; + for (int i = 0; i < total_oids; i++) { + xasprintf(&temp_string, "%.0f", response_value[i]); + if (temp_string == NULL) + die(STATE_UNKNOWN, _("Cannot asprintf()")); response_length = strlen(temp_string); - if(current_length+response_length>string_length) { - string_length=current_length+1024; - state_string=realloc(state_string,string_length); - if(state_string==NULL) + if (current_length + response_length > string_length) { + string_length = current_length + 1024; + state_string = realloc(state_string, string_length); + if (state_string == NULL) die(STATE_UNKNOWN, _("Cannot realloc()")); } - strcpy(&state_string[current_length],temp_string); - current_length=current_length+response_length; - state_string[current_length]=':'; + strcpy(&state_string[current_length], temp_string); + current_length = current_length + response_length; + state_string[current_length] = ':'; current_length++; free(temp_string); } - state_string[--current_length]='\0'; + state_string[--current_length] = '\0'; if (verbose > 2) - printf("State string=%s\n",state_string); + 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) { + np_state_write_string(current_time, state_string); + if (previous_state == NULL) { /* Or should this be highest state? */ - die( STATE_OK, _("No previous data to calculate rate - assume okay" ) ); + die(STATE_OK, _("No previous data to calculate rate - assume okay")); } } - printf ("%s %s -%s %s\n", label, state_text (result), outbuff, perfstr); - if (mult_resp) printf ("%s", mult_resp); + printf("%s %s -%s %s\n", label, state_text(result), outbuff, perfstr); + if (mult_resp) + printf("%s", mult_resp); return result; } - - /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ +int process_arguments(int argc, char **argv) { char *ptr; int c = 1; size_t j = 0, jj = 0; int option = 0; - static struct option longopts[] = { - STD_LONG_OPTS, - {"community", required_argument, 0, 'C'}, - {"oid", required_argument, 0, 'o'}, - {"object", required_argument, 0, 'o'}, - {"delimiter", required_argument, 0, 'd'}, - {"nulloid", required_argument, 0, 'z'}, - {"output-delimiter", required_argument, 0, 'D'}, - {"string", required_argument, 0, 's'}, - {"timeout", required_argument, 0, 't'}, - {"regex", required_argument, 0, 'r'}, - {"ereg", required_argument, 0, 'r'}, - {"eregi", required_argument, 0, 'R'}, - {"label", required_argument, 0, 'l'}, - {"units", required_argument, 0, 'u'}, - {"port", required_argument, 0, 'p'}, - {"retries", required_argument, 0, 'e'}, - {"miblist", required_argument, 0, 'm'}, - {"protocol", required_argument, 0, 'P'}, - {"context", required_argument, 0, 'N'}, - {"seclevel", required_argument, 0, 'L'}, - {"secname", required_argument, 0, 'U'}, - {"authproto", required_argument, 0, 'a'}, - {"privproto", required_argument, 0, 'x'}, - {"authpasswd", required_argument, 0, 'A'}, - {"privpasswd", required_argument, 0, 'X'}, - {"next", no_argument, 0, 'n'}, - {"rate", no_argument, 0, L_CALCULATE_RATE}, - {"rate-multiplier", required_argument, 0, L_RATE_MULTIPLIER}, - {"offset", required_argument, 0, L_OFFSET}, - {"invert-search", no_argument, 0, L_INVERT_SEARCH}, - {"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'}, - {"ignore-mib-parsing-errors", no_argument, false, L_IGNORE_MIB_PARSING_ERRORS}, - {0, 0, 0, 0} - }; + static struct option longopts[] = {STD_LONG_OPTS, + {"community", required_argument, 0, 'C'}, + {"oid", required_argument, 0, 'o'}, + {"object", required_argument, 0, 'o'}, + {"delimiter", required_argument, 0, 'd'}, + {"nulloid", required_argument, 0, 'z'}, + {"output-delimiter", required_argument, 0, 'D'}, + {"string", required_argument, 0, 's'}, + {"timeout", required_argument, 0, 't'}, + {"regex", required_argument, 0, 'r'}, + {"ereg", required_argument, 0, 'r'}, + {"eregi", required_argument, 0, 'R'}, + {"label", required_argument, 0, 'l'}, + {"units", required_argument, 0, 'u'}, + {"port", required_argument, 0, 'p'}, + {"retries", required_argument, 0, 'e'}, + {"miblist", required_argument, 0, 'm'}, + {"protocol", required_argument, 0, 'P'}, + {"context", required_argument, 0, 'N'}, + {"seclevel", required_argument, 0, 'L'}, + {"secname", required_argument, 0, 'U'}, + {"authproto", required_argument, 0, 'a'}, + {"privproto", required_argument, 0, 'x'}, + {"authpasswd", required_argument, 0, 'A'}, + {"privpasswd", required_argument, 0, 'X'}, + {"next", no_argument, 0, 'n'}, + {"rate", no_argument, 0, L_CALCULATE_RATE}, + {"rate-multiplier", required_argument, 0, L_RATE_MULTIPLIER}, + {"offset", required_argument, 0, L_OFFSET}, + {"invert-search", no_argument, 0, L_INVERT_SEARCH}, + {"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'}, + {"ignore-mib-parsing-errors", no_argument, false, L_IGNORE_MIB_PARSING_ERRORS}, + {0, 0, 0, 0}}; if (argc < 2) return ERROR; /* reverse compatibility for very old non-POSIX usage forms */ for (c = 1; c < argc; c++) { - if (strcmp ("-to", argv[c]) == 0) - strcpy (argv[c], "-t"); - if (strcmp ("-wv", argv[c]) == 0) - strcpy (argv[c], "-w"); - if (strcmp ("-cv", argv[c]) == 0) - strcpy (argv[c], "-c"); + if (strcmp("-to", argv[c]) == 0) + strcpy(argv[c], "-t"); + if (strcmp("-wv", argv[c]) == 0) + strcpy(argv[c], "-w"); + if (strcmp("-cv", argv[c]) == 0) + strcpy(argv[c], "-c"); } 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:M:f:z:", - longopts, &option); + 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) break; switch (c) { - case '?': /* usage */ - usage5 (); - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); + case '?': /* usage */ + usage5(); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); case 'v': /* verbose */ verbose++; break; - /* Connection info */ - case 'C': /* group or community */ + /* Connection info */ + case 'C': /* group or community */ community = optarg; break; - case 'H': /* Host or server */ + case 'H': /* Host or server */ server_address = optarg; break; - case 'p': /* TCP port number */ + case 'p': /* TCP port number */ port = optarg; break; - case 'm': /* List of MIBS */ + case 'm': /* List of MIBS */ miblist = optarg; break; - case 'n': /* usesnmpgetnext */ + case 'n': /* usesnmpgetnext */ usesnmpgetnext = true; break; - case 'P': /* SNMP protocol version */ + case 'P': /* SNMP protocol version */ proto = optarg; break; - case 'N': /* SNMPv3 context */ + case 'N': /* SNMPv3 context */ context = optarg; break; - case 'L': /* security level */ + case 'L': /* security level */ seclevel = optarg; break; - case 'U': /* security username */ + case 'U': /* security username */ secname = optarg; break; - case 'a': /* auth protocol */ + case 'a': /* auth protocol */ authproto = optarg; break; - case 'x': /* priv protocol */ + case 'x': /* priv protocol */ privproto = optarg; break; - case 'A': /* auth passwd */ + case 'A': /* auth passwd */ authpasswd = optarg; break; - case 'X': /* priv passwd */ + case 'X': /* priv passwd */ privpasswd = optarg; break; - case 't': /* timeout period */ - if (!is_integer (optarg)) - usage2 (_("Timeout interval must be a positive integer"), optarg); + case 't': /* timeout period */ + if (!is_integer(optarg)) + usage2(_("Timeout interval must be a positive integer"), optarg); else - timeout_interval = atoi (optarg); + timeout_interval = atoi(optarg); break; - /* Test parameters */ - case 'c': /* critical threshold */ + /* Test parameters */ + case 'c': /* critical threshold */ critical_thresholds = optarg; break; - case 'w': /* warning threshold */ + case 'w': /* warning threshold */ warning_thresholds = optarg; break; case 'e': /* PRELIMINARY - may change */ case 'E': /* PRELIMINARY - may change */ - if (!is_integer (optarg)) - usage2 (_("Retries interval must be a positive integer"), optarg); + if (!is_integer(optarg)) + usage2(_("Retries interval must be a positive integer"), optarg); else retries = atoi(optarg); break; - case 'o': /* object identifier */ - if ( strspn( optarg, "0123456789.," ) != strlen( optarg ) ) { - /* - * we have something other than digits, periods and comas, - * so we have a mib variable, rather than just an SNMP OID, - * so we have to actually read the mib files - */ - needmibs = true; + case 'o': /* object identifier */ + if (strspn(optarg, "0123456789.,") != strlen(optarg)) { + /* + * we have something other than digits, periods and comas, + * so we have a mib variable, rather than just an SNMP OID, + * so we have to actually read the mib files + */ + needmibs = true; } for (ptr = strtok(optarg, ", "); ptr != NULL; ptr = strtok(NULL, ", "), j++) { while (j >= oids_size) { oids_size += OID_COUNT_STEP; - oids = realloc(oids, oids_size * sizeof (*oids)); + oids = realloc(oids, oids_size * sizeof(*oids)); } oids[j] = strdup(ptr); } numoids = j; if (c == 'E' || c == 'e') { jj++; - while (j+1 >= eval_size) { + while (j + 1 >= eval_size) { eval_size += OID_COUNT_STEP; eval_method = realloc(eval_method, eval_size * sizeof(*eval_method)); memset(eval_method + eval_size - OID_COUNT_STEP, 0, 8); } if (c == 'E') - eval_method[j+1] |= WARN_PRESENT; + eval_method[j + 1] |= WARN_PRESENT; else if (c == 'e') - eval_method[j+1] |= CRIT_PRESENT; + eval_method[j + 1] |= CRIT_PRESENT; } break; - case 'z': /* Null OID Return Check */ - if (!is_integer (optarg)) - usage2 (_("Exit status must be a positive integer"), optarg); + case 'z': /* Null OID Return Check */ + if (!is_integer(optarg)) + usage2(_("Exit status must be a positive integer"), optarg); else nulloid = atoi(optarg); break; - case 's': /* string or substring */ - strncpy (string_value, optarg, sizeof (string_value) - 1); - string_value[sizeof (string_value) - 1] = 0; + case 's': /* string or substring */ + strncpy(string_value, optarg, sizeof(string_value) - 1); + string_value[sizeof(string_value) - 1] = 0; while (jj >= eval_size) { eval_size += OID_COUNT_STEP; eval_method = realloc(eval_method, eval_size * sizeof(*eval_method)); @@ -872,17 +858,17 @@ process_arguments (int argc, char **argv) } eval_method[jj++] = CRIT_STRING; break; - case 'R': /* regex */ + case 'R': /* regex */ cflags = REG_ICASE; // fall through - case 'r': /* regex */ + case 'r': /* regex */ cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE; - strncpy (regex_expect, optarg, sizeof (regex_expect) - 1); - regex_expect[sizeof (regex_expect) - 1] = 0; - errcode = regcomp (&preg, regex_expect, cflags); + strncpy(regex_expect, optarg, sizeof(regex_expect) - 1); + regex_expect[sizeof(regex_expect) - 1] = 0; + errcode = regcomp(&preg, regex_expect, cflags); if (errcode != 0) { - regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); - printf (_("Could Not Compile Regular Expression")); + regerror(errcode, &preg, errbuf, MAX_INPUT_BUFFER); + printf(_("Could Not Compile Regular Expression")); return ERROR; } while (jj >= eval_size) { @@ -893,64 +879,64 @@ process_arguments (int argc, char **argv) eval_method[jj++] = CRIT_REGEX; break; - /* Format */ - case 'd': /* delimiter */ - delimiter = strscpy (delimiter, optarg); + /* Format */ + case 'd': /* delimiter */ + delimiter = strscpy(delimiter, optarg); break; - case 'D': /* output-delimiter */ - output_delim = strscpy (output_delim, optarg); + case 'D': /* output-delimiter */ + output_delim = strscpy(output_delim, optarg); break; - case 'l': /* label */ + case 'l': /* label */ nlabels++; if (nlabels > labels_size) { labels_size += 8; - labels = realloc (labels, labels_size * sizeof(*labels)); + labels = realloc(labels, labels_size * sizeof(*labels)); if (labels == NULL) - die (STATE_UNKNOWN, _("Could not reallocate labels[%d]"), (int)nlabels); + die(STATE_UNKNOWN, _("Could not reallocate labels[%d]"), (int)nlabels); } labels[nlabels - 1] = optarg; - ptr = thisarg (optarg); + ptr = thisarg(optarg); labels[nlabels - 1] = ptr; if (ptr[0] == '\'') labels[nlabels - 1] = ptr + 1; - while (ptr && (ptr = nextarg (ptr))) { + while (ptr && (ptr = nextarg(ptr))) { nlabels++; if (nlabels > labels_size) { labels_size += 8; - labels = realloc (labels, labels_size * sizeof(*labels)); + labels = realloc(labels, labels_size * sizeof(*labels)); if (labels == NULL) - die (STATE_UNKNOWN, _("Could not reallocate labels\n")); + die(STATE_UNKNOWN, _("Could not reallocate labels\n")); } - ptr = thisarg (ptr); + ptr = thisarg(ptr); if (ptr[0] == '\'') labels[nlabels - 1] = ptr + 1; else labels[nlabels - 1] = ptr; } break; - case 'u': /* units */ + case 'u': /* units */ units = optarg; nunits++; if (nunits > unitv_size) { unitv_size += 8; - unitv = realloc (unitv, unitv_size * sizeof(*unitv)); + unitv = realloc(unitv, unitv_size * sizeof(*unitv)); if (unitv == NULL) - die (STATE_UNKNOWN, _("Could not reallocate units [%d]\n"), (int)nunits); + die(STATE_UNKNOWN, _("Could not reallocate units [%d]\n"), (int)nunits); } unitv[nunits - 1] = optarg; - ptr = thisarg (optarg); + ptr = thisarg(optarg); unitv[nunits - 1] = ptr; if (ptr[0] == '\'') unitv[nunits - 1] = ptr + 1; - while (ptr && (ptr = nextarg (ptr))) { + while (ptr && (ptr = nextarg(ptr))) { if (nunits > unitv_size) { unitv_size += 8; - unitv = realloc (unitv, unitv_size * sizeof(*unitv)); + unitv = realloc(unitv, unitv_size * sizeof(*unitv)); if (units == NULL) - die (STATE_UNKNOWN, _("Could not realloc() units\n")); + die(STATE_UNKNOWN, _("Could not realloc() units\n")); } nunits++; - ptr = thisarg (ptr); + ptr = thisarg(ptr); if (ptr[0] == '\'') unitv[nunits - 1] = ptr + 1; else @@ -958,38 +944,38 @@ process_arguments (int argc, char **argv) } break; case L_CALCULATE_RATE: - if(calculate_rate==0) + if (calculate_rate == 0) np_enable_state(NULL, 1); calculate_rate = 1; break; case L_RATE_MULTIPLIER: - if(!is_integer(optarg)||((rate_multiplier=atoi(optarg))<=0)) - usage2(_("Rate multiplier must be a positive integer"),optarg); + if (!is_integer(optarg) || ((rate_multiplier = atoi(optarg)) <= 0)) + usage2(_("Rate multiplier must be a positive integer"), optarg); break; case L_OFFSET: - offset=strtod(optarg,NULL); + offset = strtod(optarg, NULL); break; case L_INVERT_SEARCH: - invert_search=1; + invert_search = 1; break; case 'O': - perf_labels=0; + perf_labels = 0; break; case '4': break; case '6': xasprintf(&ip_version, "udp6:"); - if(verbose>2) + 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); + if (strspn(optarg, "0123456789.,") == strlen(optarg)) { + multiplier = strtod(optarg, NULL); } break; case 'f': if (multiplier != 1.0) { - fmtstr=optarg; + fmtstr = optarg; fmtstr_set = true; } break; @@ -1002,12 +988,11 @@ process_arguments (int argc, char **argv) server_address = argv[optind]; if (community == NULL) - community = strdup (DEFAULT_COMMUNITY); + community = strdup(DEFAULT_COMMUNITY); - return validate_arguments (); + return validate_arguments(); } - /****************************************************************************** @@- @@ -1026,17 +1011,13 @@ selected. -@@ ******************************************************************************/ - - -static int -validate_arguments () -{ +static int validate_arguments() { /* check whether to load locally installed MIBS (CPU/disk intensive) */ if (miblist == NULL) { if (needmibs) { - miblist = strdup (DEFAULT_MIBLIST); - }else{ - miblist = ""; /* don't read any mib files for numeric oids */ + miblist = strdup(DEFAULT_MIBLIST); + } else { + miblist = ""; /* don't read any mib files for numeric oids */ } } @@ -1051,18 +1032,17 @@ validate_arguments () if (proto == NULL) xasprintf(&proto, DEFAULT_PROTOCOL); - if ((strcmp(proto,"1") == 0) || (strcmp(proto, "2c")==0)) { /* snmpv1 or snmpv2c */ + if ((strcmp(proto, "1") == 0) || (strcmp(proto, "2c") == 0)) { /* snmpv1 or snmpv2c */ numauthpriv = 2; - authpriv = calloc (numauthpriv, sizeof (char *)); - authpriv[0] = strdup ("-c"); - authpriv[1] = strdup (community); - } - else if ( strcmp (proto, "3") == 0 ) { /* snmpv3 args */ + authpriv = calloc(numauthpriv, sizeof(char *)); + authpriv[0] = strdup("-c"); + authpriv[1] = strdup(community); + } else if (strcmp(proto, "3") == 0) { /* snmpv3 args */ if (!(context == NULL)) { numcontext = 2; - contextargs = calloc (numcontext, sizeof (char *)); - contextargs[0] = strdup ("-n"); - contextargs[1] = strdup (context); + contextargs = calloc(numcontext, sizeof(char *)); + contextargs[0] = strdup("-n"); + contextargs[1] = strdup(context); } if (seclevel == NULL) @@ -1073,138 +1053,123 @@ validate_arguments () if (strcmp(seclevel, "noAuthNoPriv") == 0) { numauthpriv = 4; - authpriv = calloc (numauthpriv, sizeof (char *)); - authpriv[0] = strdup ("-l"); - authpriv[1] = strdup ("noAuthNoPriv"); - authpriv[2] = strdup ("-u"); - authpriv[3] = strdup (secname); + authpriv = calloc(numauthpriv, sizeof(char *)); + authpriv[0] = strdup("-l"); + authpriv[1] = strdup("noAuthNoPriv"); + authpriv[2] = strdup("-u"); + authpriv[3] = strdup(secname); } else { - if (! ( (strcmp(seclevel, "authNoPriv")==0) || (strcmp(seclevel, "authPriv")==0) ) ) { - usage2 (_("Invalid seclevel"), seclevel); + if (!((strcmp(seclevel, "authNoPriv") == 0) || (strcmp(seclevel, "authPriv") == 0))) { + usage2(_("Invalid seclevel"), seclevel); } - if (authproto == NULL ) + if (authproto == NULL) xasprintf(&authproto, DEFAULT_AUTH_PROTOCOL); if (authpasswd == NULL) die(STATE_UNKNOWN, _("Required parameter: %s\n"), "authpasswd"); - if ( strcmp(seclevel, "authNoPriv") == 0 ) { + if (strcmp(seclevel, "authNoPriv") == 0) { numauthpriv = 8; - authpriv = calloc (numauthpriv, sizeof (char *)); - authpriv[0] = strdup ("-l"); - authpriv[1] = strdup ("authNoPriv"); - authpriv[2] = strdup ("-a"); - authpriv[3] = strdup (authproto); - authpriv[4] = strdup ("-u"); - authpriv[5] = strdup (secname); - authpriv[6] = strdup ("-A"); - authpriv[7] = strdup (authpasswd); - } else if ( strcmp(seclevel, "authPriv") == 0 ) { - if (privproto == NULL ) + authpriv = calloc(numauthpriv, sizeof(char *)); + authpriv[0] = strdup("-l"); + authpriv[1] = strdup("authNoPriv"); + authpriv[2] = strdup("-a"); + authpriv[3] = strdup(authproto); + authpriv[4] = strdup("-u"); + authpriv[5] = strdup(secname); + authpriv[6] = strdup("-A"); + authpriv[7] = strdup(authpasswd); + } else if (strcmp(seclevel, "authPriv") == 0) { + if (privproto == NULL) xasprintf(&privproto, DEFAULT_PRIV_PROTOCOL); if (privpasswd == NULL) die(STATE_UNKNOWN, _("Required parameter: %s\n"), "privpasswd"); numauthpriv = 12; - authpriv = calloc (numauthpriv, sizeof (char *)); - authpriv[0] = strdup ("-l"); - authpriv[1] = strdup ("authPriv"); - authpriv[2] = strdup ("-a"); - authpriv[3] = strdup (authproto); - authpriv[4] = strdup ("-u"); - authpriv[5] = strdup (secname); - authpriv[6] = strdup ("-A"); - authpriv[7] = strdup (authpasswd); - authpriv[8] = strdup ("-x"); - authpriv[9] = strdup (privproto); - authpriv[10] = strdup ("-X"); - authpriv[11] = strdup (privpasswd); + authpriv = calloc(numauthpriv, sizeof(char *)); + authpriv[0] = strdup("-l"); + authpriv[1] = strdup("authPriv"); + authpriv[2] = strdup("-a"); + authpriv[3] = strdup(authproto); + authpriv[4] = strdup("-u"); + authpriv[5] = strdup(secname); + authpriv[6] = strdup("-A"); + authpriv[7] = strdup(authpasswd); + authpriv[8] = strdup("-x"); + authpriv[9] = strdup(privproto); + authpriv[10] = strdup("-X"); + authpriv[11] = strdup(privpasswd); } } - } - else { - usage2 (_("Invalid SNMP version"), proto); + } else { + usage2(_("Invalid SNMP version"), proto); } return OK; } - - /* trim leading whitespace if there is a leading quote, make sure it balances */ -static char * -thisarg (char *str) -{ - str += strspn (str, " \t\r\n"); /* trim any leading whitespace */ - if (str[0] == '\'') { /* handle SIMPLE quoted strings */ - if (strlen (str) == 1 || !strstr (str + 1, "'")) - die (STATE_UNKNOWN, _("Unbalanced quotes\n")); +static char *thisarg(char *str) { + str += strspn(str, " \t\r\n"); /* trim any leading whitespace */ + if (str[0] == '\'') { /* handle SIMPLE quoted strings */ + if (strlen(str) == 1 || !strstr(str + 1, "'")) + die(STATE_UNKNOWN, _("Unbalanced quotes\n")); } return str; } - - /* if there's a leading quote, advance to the trailing quote set the trailing quote to '\x0' if the string continues, advance beyond the comma */ -static char * -nextarg (char *str) -{ +static char *nextarg(char *str) { if (str[0] == '\'') { str[0] = 0; - if (strlen (str) > 1) { - str = strstr (str + 1, "'"); + if (strlen(str) > 1) { + str = strstr(str + 1, "'"); return (++str); - } - else { + } else { return NULL; } } if (str[0] == ',') { str[0] = 0; - if (strlen (str) > 1) { + if (strlen(str) > 1) { return (++str); - } - else { + } else { return NULL; } } - if ((str = strstr (str, ",")) && strlen (str) > 1) { + if ((str = strstr(str, ",")) && strlen(str) > 1) { str[0] = 0; return (++str); } return NULL; } - - /* multiply result (values 0 < n < 1 work as divider) */ -static char * -multiply (char *str) -{ +static char *multiply(char *str) { char *endptr; double val; char *conv = "%f"; - if(multiplier == 1) - return(str); + if (multiplier == 1) + return (str); - if(verbose>2) + if (verbose > 2) printf(" multiply input: %s\n", str); - val = strtod (str, &endptr); + val = strtod(str, &endptr); if ((val == 0.0) && (endptr == str)) { die(STATE_UNKNOWN, _("multiplier set (%.1f), but input is not a number: %s"), multiplier, str); } - if(verbose>2) + if (verbose > 2) printf(" multiply extracted double: %f\n", val); val *= multiplier; if (fmtstr_set) { @@ -1213,144 +1178,142 @@ multiply (char *str) if (val == (int)val) { snprintf(buffer, DEFAULT_BUFFER_SIZE, "%.0f", val); } else { - if(verbose>2) + if (verbose > 2) printf(" multiply using format: %s\n", conv); snprintf(buffer, DEFAULT_BUFFER_SIZE, conv, val); } - if(verbose>2) + if (verbose > 2) printf(" multiply result: %s\n", buffer); return buffer; } +static void print_help(void) { + print_revision(progname, NP_VERSION); -static void -print_help (void) -{ - print_revision (progname, NP_VERSION); - - printf (COPYRIGHT, copyright, email); + printf(COPYRIGHT, copyright, email); - printf ("%s\n", _("Check status of remote machines and obtain system information via SNMP")); + printf("%s\n", _("Check status of remote machines and obtain system information via SNMP")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); - printf (UT_IPv46); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); + printf(UT_IPv46); - printf (UT_HOST_PORT, 'p', DEFAULT_PORT); + printf(UT_HOST_PORT, 'p', DEFAULT_PORT); /* SNMP and Authentication Protocol */ - printf (" %s\n", "-n, --next"); - printf (" %s\n", _("Use SNMP GETNEXT instead of SNMP GET")); - printf (" %s\n", "-P, --protocol=[1|2c|3]"); - printf (" %s\n", _("SNMP protocol version")); - printf (" %s\n", "-N, --context=CONTEXT"); - printf (" %s\n", _("SNMPv3 context")); - printf (" %s\n", "-L, --seclevel=[noAuthNoPriv|authNoPriv|authPriv]"); - printf (" %s\n", _("SNMPv3 securityLevel")); - printf (" %s\n", "-a, --authproto=AUTHENTICATION_PROTOCOL"); - printf (" %s\n", _("SNMPv3 authentication protocol (default MD5), available options depend on the specific version of the net-snmp tools")); - printf (" %s\n", _("if < 5.8 SHA (1) and MD5 should be available, if >= 5.8 additionally SHA-224, SHA-256, SHA-384 and SHA-512")); - printf (" %s\n", "-x, --privproto=PRIVACY_PROTOCOL"); - printf (" %s\n", _("SNMPv3 privacy protocol (default DES), available options depend on the specific version of the net-snmp tools")); - printf (" %s\n", _("if < 5.8 DES and AES should be available, if >= 5.8 additionally AES-192 and AES-256")); + printf(" %s\n", "-n, --next"); + printf(" %s\n", _("Use SNMP GETNEXT instead of SNMP GET")); + printf(" %s\n", "-P, --protocol=[1|2c|3]"); + printf(" %s\n", _("SNMP protocol version")); + printf(" %s\n", "-N, --context=CONTEXT"); + printf(" %s\n", _("SNMPv3 context")); + printf(" %s\n", "-L, --seclevel=[noAuthNoPriv|authNoPriv|authPriv]"); + printf(" %s\n", _("SNMPv3 securityLevel")); + printf(" %s\n", "-a, --authproto=AUTHENTICATION_PROTOCOL"); + printf(" %s\n", + _("SNMPv3 authentication protocol (default MD5), available options depend on the specific version of the net-snmp tools")); + printf(" %s\n", _("if < 5.8 SHA (1) and MD5 should be available, if >= 5.8 additionally SHA-224, SHA-256, SHA-384 and SHA-512")); + printf(" %s\n", "-x, --privproto=PRIVACY_PROTOCOL"); + printf(" %s\n", _("SNMPv3 privacy protocol (default DES), available options depend on the specific version of the net-snmp tools")); + printf(" %s\n", _("if < 5.8 DES and AES should be available, if >= 5.8 additionally AES-192 and AES-256")); /* Authentication Tokens*/ - printf (" %s\n", "-C, --community=STRING"); - printf (" %s ", _("Optional community string for SNMP communication")); - printf ("(%s \"%s\")\n", _("default is") ,DEFAULT_COMMUNITY); - printf (" %s\n", "-U, --secname=USERNAME"); - printf (" %s\n", _("SNMPv3 username")); - printf (" %s\n", "-A, --authpasswd=PASSWORD"); - printf (" %s\n", _("SNMPv3 authentication password")); - printf (" %s\n", "-X, --privpasswd=PASSWORD"); - printf (" %s\n", _("SNMPv3 privacy password")); + printf(" %s\n", "-C, --community=STRING"); + printf(" %s ", _("Optional community string for SNMP communication")); + printf("(%s \"%s\")\n", _("default is"), DEFAULT_COMMUNITY); + printf(" %s\n", "-U, --secname=USERNAME"); + printf(" %s\n", _("SNMPv3 username")); + printf(" %s\n", "-A, --authpasswd=PASSWORD"); + printf(" %s\n", _("SNMPv3 authentication password")); + printf(" %s\n", "-X, --privpasswd=PASSWORD"); + printf(" %s\n", _("SNMPv3 privacy password")); /* OID Stuff */ - printf (" %s\n", "-o, --oid=OID(s)"); - printf (" %s\n", _("Object identifier(s) or SNMP variables whose value you wish to query")); - printf (" %s\n", "-m, --miblist=STRING"); - printf (" %s\n", _("List of MIBS to be loaded (default = none if using numeric OIDs or 'ALL'")); - printf (" %s\n", _("for symbolic OIDs.)")); - printf (" %s\n", "-d, --delimiter=STRING"); - printf (" %s \"%s\"\n", _("Delimiter to use when parsing returned data. Default is"), DEFAULT_DELIMITER); - printf (" %s\n", _("Any data on the right hand side of the delimiter is considered")); - printf (" %s\n", _("to be the data that should be used in the evaluation.")); - printf (" %s\n", "-z, --nulloid=#"); - printf (" %s\n", _("If the check returns a 0 length string or NULL value")); - printf (" %s\n", _("This option allows you to choose what status you want it to exit")); - printf (" %s\n", _("Excluding this option renders the default exit of 3(STATE_UNKNOWN)")); - printf (" %s\n", _("0 = OK")); - printf (" %s\n", _("1 = WARNING")); - printf (" %s\n", _("2 = CRITICAL")); - printf (" %s\n", _("3 = UNKNOWN")); + printf(" %s\n", "-o, --oid=OID(s)"); + printf(" %s\n", _("Object identifier(s) or SNMP variables whose value you wish to query")); + printf(" %s\n", "-m, --miblist=STRING"); + printf(" %s\n", _("List of MIBS to be loaded (default = none if using numeric OIDs or 'ALL'")); + printf(" %s\n", _("for symbolic OIDs.)")); + printf(" %s\n", "-d, --delimiter=STRING"); + printf(" %s \"%s\"\n", _("Delimiter to use when parsing returned data. Default is"), DEFAULT_DELIMITER); + printf(" %s\n", _("Any data on the right hand side of the delimiter is considered")); + printf(" %s\n", _("to be the data that should be used in the evaluation.")); + printf(" %s\n", "-z, --nulloid=#"); + printf(" %s\n", _("If the check returns a 0 length string or NULL value")); + printf(" %s\n", _("This option allows you to choose what status you want it to exit")); + printf(" %s\n", _("Excluding this option renders the default exit of 3(STATE_UNKNOWN)")); + printf(" %s\n", _("0 = OK")); + printf(" %s\n", _("1 = WARNING")); + printf(" %s\n", _("2 = CRITICAL")); + printf(" %s\n", _("3 = UNKNOWN")); /* Tests Against Integers */ - printf (" %s\n", "-w, --warning=THRESHOLD(s)"); - printf (" %s\n", _("Warning threshold range(s)")); - printf (" %s\n", "-c, --critical=THRESHOLD(s)"); - printf (" %s\n", _("Critical threshold range(s)")); - printf (" %s\n", "--rate"); - printf (" %s\n", _("Enable rate calculation. See 'Rate Calculation' below")); - printf (" %s\n", "--rate-multiplier"); - printf (" %s\n", _("Converts rate per second. For example, set to 60 to convert to per minute")); - printf (" %s\n", "--offset=OFFSET"); - printf (" %s\n", _("Add/subtract the specified OFFSET to numeric sensor data")); + printf(" %s\n", "-w, --warning=THRESHOLD(s)"); + printf(" %s\n", _("Warning threshold range(s)")); + printf(" %s\n", "-c, --critical=THRESHOLD(s)"); + printf(" %s\n", _("Critical threshold range(s)")); + printf(" %s\n", "--rate"); + printf(" %s\n", _("Enable rate calculation. See 'Rate Calculation' below")); + printf(" %s\n", "--rate-multiplier"); + printf(" %s\n", _("Converts rate per second. For example, set to 60 to convert to per minute")); + printf(" %s\n", "--offset=OFFSET"); + printf(" %s\n", _("Add/subtract the specified OFFSET to numeric sensor data")); /* Tests Against Strings */ - printf (" %s\n", "-s, --string=STRING"); - printf (" %s\n", _("Return OK state (for that OID) if STRING is an exact match")); - printf (" %s\n", "-r, --ereg=REGEX"); - printf (" %s\n", _("Return OK state (for that OID) if extended regular expression REGEX matches")); - printf (" %s\n", "-R, --eregi=REGEX"); - printf (" %s\n", _("Return OK state (for that OID) if case-insensitive extended REGEX matches")); - printf (" %s\n", "--invert-search"); - printf (" %s\n", _("Invert search result (CRITICAL if found)")); + printf(" %s\n", "-s, --string=STRING"); + printf(" %s\n", _("Return OK state (for that OID) if STRING is an exact match")); + printf(" %s\n", "-r, --ereg=REGEX"); + printf(" %s\n", _("Return OK state (for that OID) if extended regular expression REGEX matches")); + printf(" %s\n", "-R, --eregi=REGEX"); + printf(" %s\n", _("Return OK state (for that OID) if case-insensitive extended REGEX matches")); + printf(" %s\n", "--invert-search"); + printf(" %s\n", _("Invert search result (CRITICAL if found)")); /* Output Formatting */ - printf (" %s\n", "-l, --label=STRING"); - printf (" %s\n", _("Prefix label for output from plugin")); - printf (" %s\n", "-u, --units=STRING"); - 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")); - printf (" %s\n", "-e, --retries=INTEGER"); - printf (" %s%i\n", _("Number of retries to be used in the requests, default: "), DEFAULT_RETRIES); - - printf (" %s\n", "-O, --perf-oids"); - printf (" %s\n", _("Label performance data with OIDs instead of --label's")); - - printf (" %s\n", "--ignore-mib-parsing-errors"); - printf (" %s\n", _("Tell snmpget to not print errors encountered when parsing MIB files")); - - printf (UT_VERBOSE); - - printf ("\n"); - printf ("%s\n", _("This plugin uses the 'snmpget' command included with the NET-SNMP package.")); - printf ("%s\n", _("if you don't have the package installed, you will need to download it from")); - printf ("%s\n", _("http://net-snmp.sourceforge.net before you can use this plugin.")); - - printf ("\n"); - printf ("%s\n", _("Notes:")); - printf (" %s\n", _("- Multiple OIDs (and labels) may be indicated by a comma or space-delimited ")); - printf (" %s\n", _("list (lists with internal spaces must be quoted).")); + printf(" %s\n", "-l, --label=STRING"); + printf(" %s\n", _("Prefix label for output from plugin")); + printf(" %s\n", "-u, --units=STRING"); + 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")); + printf(" %s\n", "-e, --retries=INTEGER"); + printf(" %s%i\n", _("Number of retries to be used in the requests, default: "), DEFAULT_RETRIES); + + printf(" %s\n", "-O, --perf-oids"); + printf(" %s\n", _("Label performance data with OIDs instead of --label's")); + + printf(" %s\n", "--ignore-mib-parsing-errors"); + printf(" %s\n", _("Tell snmpget to not print errors encountered when parsing MIB files")); + + printf(UT_VERBOSE); + + printf("\n"); + printf("%s\n", _("This plugin uses the 'snmpget' command included with the NET-SNMP package.")); + printf("%s\n", _("if you don't have the package installed, you will need to download it from")); + printf("%s\n", _("http://net-snmp.sourceforge.net before you can use this plugin.")); + + printf("\n"); + printf("%s\n", _("Notes:")); + printf(" %s\n", _("- Multiple OIDs (and labels) may be indicated by a comma or space-delimited ")); + printf(" %s\n", _("list (lists with internal spaces must be quoted).")); printf(" -%s", UT_THRESHOLDS_NOTES); - printf (" %s\n", _("- When checking multiple OIDs, separate ranges by commas like '-w 1:10,1:,:20'")); - printf (" %s\n", _("- Note that only one string and one regex may be checked at present")); - printf (" %s\n", _("- All evaluation methods other than PR, STR, and SUBSTR expect that the value")); - printf (" %s\n", _("returned from the SNMP query is an unsigned integer.")); + printf(" %s\n", _("- When checking multiple OIDs, separate ranges by commas like '-w 1:10,1:,:20'")); + printf(" %s\n", _("- Note that only one string and one regex may be checked at present")); + printf(" %s\n", _("- All evaluation methods other than PR, STR, and SUBSTR expect that the value")); + printf(" %s\n", _("returned from the SNMP query is an unsigned integer.")); printf("\n"); printf("%s\n", _("Rate Calculation:")); @@ -1362,19 +1325,15 @@ print_help (void) printf(" %s\n", _("The state is uniquely determined by the arguments to the plugin, so")); printf(" %s\n", _("changing the arguments will create a new state file.")); - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s -H -o [-w warn_range] [-c crit_range]\n",progname); - printf ("[-C community] [-s string] [-r regex] [-R regexi] [-t timeout] [-e retries]\n"); - 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"); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s -H -o [-w warn_range] [-c crit_range]\n", progname); + printf("[-C community] [-s string] [-r regex] [-R regexi] [-t timeout] [-e retries]\n"); + 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"); } -- cgit v0.10-9-g596f From 04471ba48d5cf2bb422b8bc1fec9cfdac2fbad5f Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 13:56:28 +0100 Subject: check_snmp: update copyright diff --git a/plugins/check_snmp.c b/plugins/check_snmp.c index 2bfdcfe..0adf3be 100644 --- a/plugins/check_snmp.c +++ b/plugins/check_snmp.c @@ -3,7 +3,7 @@ * Monitoring check_snmp plugin * * License: GPL - * Copyright (c) 1999-2007 Monitoring Plugins Development Team + * Copyright (c) 1999-2024 Monitoring Plugins Development Team * * Description: * @@ -29,7 +29,7 @@ *****************************************************************************/ const char *progname = "check_snmp"; -const char *copyright = "1999-2007"; +const char *copyright = "1999-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From b6d920da5576b712fe998abc04dbf4cb23245106 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:01:12 +0100 Subject: check_snmp: style + linter fixes diff --git a/plugins/check_snmp.c b/plugins/check_snmp.c index 0adf3be..c1d8e2d 100644 --- a/plugins/check_snmp.c +++ b/plugins/check_snmp.c @@ -170,8 +170,10 @@ static char buffer[DEFAULT_BUFFER_SIZE]; static bool ignore_mib_parsing_errors = false; static char *fix_snmp_range(char *th) { - double left, right; - char *colon, *ret; + double left; + double right; + char *colon; + char *ret; if ((colon = strchr(th, ':')) == NULL || *(colon + 1) == '\0') return th; @@ -190,9 +192,11 @@ static char *fix_snmp_range(char *th) { } int main(int argc, char **argv) { - int len, total_oids; + int len; + int total_oids; size_t line; - unsigned int bk_count = 0, dq_count = 0; + unsigned int bk_count = 0; + unsigned int dq_count = 0; int iresult = STATE_UNKNOWN; int result = STATE_UNKNOWN; int return_code = 0; @@ -208,11 +212,14 @@ int main(int argc, char **argv) { char *th_warn = NULL; char *th_crit = NULL; char type[8] = ""; - output chld_out, chld_err; + output chld_out; + output chld_err; char *previous_string = NULL; char *ap = NULL; char *state_string = NULL; - size_t response_length, current_length, string_length; + size_t response_length; + size_t current_length; + size_t string_length; char *temp_string = NULL; char *quote_string = NULL; time_t current_time; @@ -676,11 +683,6 @@ int main(int argc, char **argv) { /* process command-line arguments */ int process_arguments(int argc, char **argv) { - char *ptr; - int c = 1; - size_t j = 0, jj = 0; - - int option = 0; static struct option longopts[] = {STD_LONG_OPTS, {"community", required_argument, 0, 'C'}, {"oid", required_argument, 0, 'o'}, @@ -723,7 +725,7 @@ int process_arguments(int argc, char **argv) { return ERROR; /* reverse compatibility for very old non-POSIX usage forms */ - for (c = 1; c < argc; c++) { + for (int c = 1; c < argc; c++) { if (strcmp("-to", argv[c]) == 0) strcpy(argv[c], "-t"); if (strcmp("-wv", argv[c]) == 0) @@ -732,13 +734,16 @@ int process_arguments(int argc, char **argv) { strcpy(argv[c], "-c"); } - 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:M:f:z:", longopts, &option); + size_t j = 0; + size_t jj = 0; + while (true) { + int option = 0; + int option_char = 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) + if (option_char == -1 || option_char == EOF) break; - switch (c) { + switch (option_char) { case '?': /* usage */ usage5(); case 'h': /* help */ @@ -821,7 +826,7 @@ int process_arguments(int argc, char **argv) { */ needmibs = true; } - for (ptr = strtok(optarg, ", "); ptr != NULL; ptr = strtok(NULL, ", "), j++) { + for (char *ptr = strtok(optarg, ", "); ptr != NULL; ptr = strtok(NULL, ", "), j++) { while (j >= oids_size) { oids_size += OID_COUNT_STEP; oids = realloc(oids, oids_size * sizeof(*oids)); @@ -829,16 +834,16 @@ int process_arguments(int argc, char **argv) { oids[j] = strdup(ptr); } numoids = j; - if (c == 'E' || c == 'e') { + if (option_char == 'E' || option_char == 'e') { jj++; while (j + 1 >= eval_size) { eval_size += OID_COUNT_STEP; eval_method = realloc(eval_method, eval_size * sizeof(*eval_method)); memset(eval_method + eval_size - OID_COUNT_STEP, 0, 8); } - if (c == 'E') + if (option_char == 'E') eval_method[j + 1] |= WARN_PRESENT; - else if (c == 'e') + else if (option_char == 'e') eval_method[j + 1] |= CRIT_PRESENT; } break; @@ -895,7 +900,7 @@ int process_arguments(int argc, char **argv) { die(STATE_UNKNOWN, _("Could not reallocate labels[%d]"), (int)nlabels); } labels[nlabels - 1] = optarg; - ptr = thisarg(optarg); + char *ptr = thisarg(optarg); labels[nlabels - 1] = ptr; if (ptr[0] == '\'') labels[nlabels - 1] = ptr + 1; @@ -1154,24 +1159,23 @@ static char *nextarg(char *str) { /* multiply result (values 0 < n < 1 work as divider) */ static char *multiply(char *str) { - char *endptr; - double val; - char *conv = "%f"; - if (multiplier == 1) return (str); if (verbose > 2) printf(" multiply input: %s\n", str); - val = strtod(str, &endptr); + char *endptr; + double val = strtod(str, &endptr); if ((val == 0.0) && (endptr == str)) { die(STATE_UNKNOWN, _("multiplier set (%.1f), but input is not a number: %s"), multiplier, str); } if (verbose > 2) printf(" multiply extracted double: %f\n", val); + val *= multiplier; + char *conv = "%f"; if (fmtstr_set) { conv = fmtstr; } -- cgit v0.10-9-g596f From 0be4dede6e546234684b807618d930c1aa50fe31 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:02:13 +0100 Subject: check_tcp: clang-format diff --git a/plugins/check_tcp.c b/plugins/check_tcp.c index 01dd35e..78dcbd4 100644 --- a/plugins/check_tcp.c +++ b/plugins/check_tcp.c @@ -1,31 +1,31 @@ /***************************************************************************** -* -* Monitoring check_tcp plugin -* -* License: GPL -* Copyright (c) 1999-2013 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_tcp plugin -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* $Id$ -* -*****************************************************************************/ + * + * Monitoring check_tcp plugin + * + * License: GPL + * Copyright (c) 1999-2013 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_tcp plugin + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * $Id$ + * + *****************************************************************************/ /* progname "check_tcp" changes depending on symlink called */ char *progname; @@ -43,17 +43,17 @@ const char *email = "devel@monitoring-plugins.org"; #ifdef HAVE_SSL static bool check_cert = false; static int days_till_exp_warn, days_till_exp_crit; -# define my_recv(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_read(buf, len) : read(sd, buf, len)) -# define my_send(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0)) +# define my_recv(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_read(buf, len) : read(sd, buf, len)) +# define my_send(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0)) #else -# 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 /* int my_recv(char *, size_t); */ -static int process_arguments (int, char **); -void print_help (void); -void print_usage (void); +static int process_arguments(int, char **); +void print_help(void); +void print_usage(void); #define EXPECT server_expect[0] static char *SERVICE = "TCP"; @@ -91,16 +91,14 @@ static char *sni = NULL; static bool sni_specified = false; #endif -#define FLAG_SSL 0x01 -#define FLAG_VERBOSE 0x02 -#define FLAG_TIME_WARN 0x04 -#define FLAG_TIME_CRIT 0x08 +#define FLAG_SSL 0x01 +#define FLAG_VERBOSE 0x02 +#define FLAG_TIME_WARN 0x04 +#define FLAG_TIME_CRIT 0x08 #define FLAG_HIDE_OUTPUT 0x10 static size_t flags; -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { int result = STATE_UNKNOWN; char *status = NULL; struct timeval tv; @@ -110,19 +108,21 @@ main (int argc, char **argv) FD_ZERO(&rfds); - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* determine program- and service-name quickly */ progname = strrchr(argv[0], '/'); - if(progname != NULL) progname++; - else progname = argv[0]; + if (progname != NULL) + progname++; + else + progname = argv[0]; size_t prog_name_len = strlen(progname); - if(prog_name_len > 6 && !memcmp(progname, "check_", 6)) { + if (prog_name_len > 6 && !memcmp(progname, "check_", 6)) { SERVICE = strdup(progname + 6); - for(size_t i = 0; i < prog_name_len - 6; i++) + for (size_t i = 0; i < prog_name_len - 6; i++) SERVICE[i] = toupper(SERVICE[i]); } @@ -133,23 +133,19 @@ main (int argc, char **argv) /* determine defaults for this service's protocol */ if (!strncmp(SERVICE, "UDP", 3)) { PROTOCOL = IPPROTO_UDP; - } - else if (!strncmp(SERVICE, "FTP", 3)) { + } else if (!strncmp(SERVICE, "FTP", 3)) { EXPECT = "220"; QUIT = "QUIT\r\n"; PORT = 21; - } - else if (!strncmp(SERVICE, "POP", 3) || !strncmp(SERVICE, "POP3", 4)) { + } else if (!strncmp(SERVICE, "POP", 3) || !strncmp(SERVICE, "POP3", 4)) { EXPECT = "+OK"; QUIT = "QUIT\r\n"; PORT = 110; - } - else if (!strncmp(SERVICE, "SMTP", 4)) { + } else if (!strncmp(SERVICE, "SMTP", 4)) { EXPECT = "220"; QUIT = "QUIT\r\n"; PORT = 25; - } - else if (!strncmp(SERVICE, "IMAP", 4)) { + } else if (!strncmp(SERVICE, "IMAP", 4)) { EXPECT = "* OK"; QUIT = "a1 LOGOUT\r\n"; PORT = 143; @@ -160,27 +156,23 @@ main (int argc, char **argv) QUIT = "a1 LOGOUT\r\n"; flags |= FLAG_SSL; PORT = 993; - } - else if (!strncmp(SERVICE, "SPOP", 4)) { + } else if (!strncmp(SERVICE, "SPOP", 4)) { EXPECT = "+OK"; QUIT = "QUIT\r\n"; flags |= FLAG_SSL; PORT = 995; - } - else if (!strncmp(SERVICE, "SSMTP", 5)) { + } else if (!strncmp(SERVICE, "SSMTP", 5)) { EXPECT = "220"; QUIT = "QUIT\r\n"; flags |= FLAG_SSL; PORT = 465; - } - else if (!strncmp(SERVICE, "JABBER", 6)) { + } else if (!strncmp(SERVICE, "JABBER", 6)) { SEND = "\n"; EXPECT = "\n"; flags |= FLAG_HIDE_OUTPUT; PORT = 5222; - } - else if (!strncmp (SERVICE, "NNTPS", 5)) { + } else if (!strncmp(SERVICE, "NNTPS", 5)) { server_expect_count = 2; server_expect[0] = "200"; server_expect[1] = "201"; @@ -189,23 +181,22 @@ main (int argc, char **argv) PORT = 563; } #endif - else if (!strncmp (SERVICE, "NNTP", 4)) { + else if (!strncmp(SERVICE, "NNTP", 4)) { server_expect_count = 2; server_expect = malloc(sizeof(char *) * server_expect_count); server_expect[0] = strdup("200"); server_expect[1] = strdup("201"); QUIT = "QUIT\r\n"; PORT = 119; - } - else if (!strncmp(SERVICE, "CLAMD", 5)) { + } else if (!strncmp(SERVICE, "CLAMD", 5)) { SEND = "PING"; EXPECT = "PONG"; QUIT = NULL; PORT = 3310; } /* fallthrough check, so it's supposed to use reverse matching */ - else if (strcmp (SERVICE, "TCP")) - usage (_("CRITICAL - Generic check_tcp called with unknown service\n")); + else if (strcmp(SERVICE, "TCP")) + usage(_("CRITICAL - Generic check_tcp called with unknown service\n")); server_address = "127.0.0.1"; server_port = PORT; @@ -214,58 +205,60 @@ main (int argc, char **argv) status = NULL; /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if (process_arguments (argc, argv) == ERROR) - usage4 (_("Could not parse arguments")); + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments")); - if(flags & FLAG_VERBOSE) { + if (flags & FLAG_VERBOSE) { printf("Using service %s\n", SERVICE); printf("Port: %d\n", server_port); printf("flags: 0x%x\n", (int)flags); } - if(EXPECT && !server_expect_count) + if (EXPECT && !server_expect_count) server_expect_count++; - if(PROTOCOL==IPPROTO_UDP && !(server_expect_count && server_send)){ + if (PROTOCOL == IPPROTO_UDP && !(server_expect_count && server_send)) { usage(_("With UDP checks, a send/expect string must be specified.")); } /* set up the timer */ - signal (SIGALRM, socket_timeout_alarm_handler); - alarm (socket_timeout); + signal(SIGALRM, socket_timeout_alarm_handler); + alarm(socket_timeout); /* try to connect to the host at the given port number */ - gettimeofday (&tv, NULL); + gettimeofday(&tv, NULL); - result = np_net_connect (server_address, server_port, &sd, PROTOCOL); - if (result == STATE_CRITICAL) return econn_refuse_state; + result = np_net_connect(server_address, server_port, &sd, PROTOCOL); + if (result == STATE_CRITICAL) + return econn_refuse_state; #ifdef HAVE_SSL - if (flags & FLAG_SSL){ + if (flags & FLAG_SSL) { result = np_net_ssl_init_with_hostname(sd, (sni_specified ? sni : NULL)); if (result == STATE_OK && check_cert) { result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit); } } - if(result != STATE_OK){ - if(sd) close(sd); + if (result != STATE_OK) { + if (sd) + close(sd); np_net_ssl_cleanup(); return result; } #endif /* HAVE_SSL */ - if (server_send != NULL) { /* Something to send? */ + if (server_send != NULL) { /* Something to send? */ my_send(server_send, strlen(server_send)); } if (delay > 0) { tv.tv_sec += delay; - sleep (delay); + sleep(delay); } - if(flags & FLAG_VERBOSE) { + if (flags & FLAG_VERBOSE) { if (server_send) { printf("Send string: %s\n", server_send); } @@ -273,7 +266,7 @@ main (int argc, char **argv) printf("Quit string: %s\n", server_quit); } printf("server_expect_count: %d\n", (int)server_expect_count); - for(size_t i = 0; i < server_expect_count; i++) + for (size_t i = 0; i < server_expect_count; i++) printf("\t%zd: %s\n", i, server_expect[i]); } @@ -294,17 +287,14 @@ main (int argc, char **argv) if (maxbytes && len >= maxbytes) break; - if ((match = np_expect_match(status, - server_expect, - server_expect_count, - match_flags)) != NP_MATCH_RETRY) + if ((match = np_expect_match(status, server_expect, server_expect_count, match_flags)) != NP_MATCH_RETRY) break; /* some protocols wait for further input, so make sure we don't wait forever */ FD_SET(sd, &rfds); - timeout.tv_sec = READ_TIMEOUT; + timeout.tv_sec = READ_TIMEOUT; timeout.tv_usec = 0; - if(select(sd + 1, &rfds, NULL, NULL, &timeout) <= 0) + if (select(sd + 1, &rfds, NULL, NULL, &timeout) <= 0) break; } @@ -313,26 +303,26 @@ main (int argc, char **argv) /* no data when expected, so return critical */ if (len == 0) - die (STATE_CRITICAL, _("No data received from host\n")); + die(STATE_CRITICAL, _("No data received from host\n")); /* print raw output if we're debugging */ - if(flags & FLAG_VERBOSE) - printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n", - (int)len + 1, status); + if (flags & FLAG_VERBOSE) + printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n", (int)len + 1, status); /* strip whitespace from end of output */ - while(--len > 0 && isspace(status[len])) + while (--len > 0 && isspace(status[len])) status[len] = '\0'; } if (server_quit != NULL) { my_send(server_quit, strlen(server_quit)); } - if (sd) close (sd); + if (sd) + close(sd); #ifdef HAVE_SSL np_net_ssl_cleanup(); #endif - microsec = deltime (tv); + microsec = deltime(tv); elapsed_time = (double)microsec / 1.0e6; if (flags & FLAG_TIME_CRIT && elapsed_time > critical_time) @@ -341,66 +331,52 @@ main (int argc, char **argv) result = STATE_WARNING; /* did we get the response we hoped? */ - if(match == NP_MATCH_FAILURE && result != STATE_CRITICAL) + if (match == NP_MATCH_FAILURE && result != STATE_CRITICAL) result = expect_mismatch_state; /* reset the alarm */ - alarm (0); + alarm(0); /* this is a bit stupid, because we don't want to print the * response time (which can look ok to the user) if we didn't get * the response we were looking for. if-else */ printf("%s %s - ", SERVICE, state_text(result)); - if(match == NP_MATCH_FAILURE && len && !(flags & FLAG_HIDE_OUTPUT)) + if (match == NP_MATCH_FAILURE && len && !(flags & FLAG_HIDE_OUTPUT)) printf("Unexpected response from host/socket: %s", status); else { - if(match == NP_MATCH_FAILURE) + if (match == NP_MATCH_FAILURE) printf("Unexpected response from host/socket on "); else printf("%.3f second response time on ", elapsed_time); - if(server_address[0] != '/') { + if (server_address[0] != '/') { if (host_specified) - printf("%s port %d", - server_address, server_port); + printf("%s port %d", server_address, server_port); else printf("port %d", server_port); - } - else + } else printf("socket %s", server_address); } if (match != NP_MATCH_FAILURE && !(flags & FLAG_HIDE_OUTPUT) && len) - printf (" [%s]", status); + printf(" [%s]", status); /* perf-data doesn't apply when server doesn't talk properly, * so print all zeroes on warn and crit. Use fperfdata since * localisation settings can make different outputs */ - if(match == NP_MATCH_FAILURE) - printf ("|%s", - fperfdata ("time", elapsed_time, "s", - (flags & FLAG_TIME_WARN ? true : false), 0, - (flags & FLAG_TIME_CRIT ? true : false), 0, - true, 0, - true, socket_timeout) - ); + if (match == NP_MATCH_FAILURE) + printf("|%s", fperfdata("time", elapsed_time, "s", (flags & FLAG_TIME_WARN ? true : false), 0, + (flags & FLAG_TIME_CRIT ? true : false), 0, true, 0, true, socket_timeout)); else - printf("|%s", - fperfdata ("time", elapsed_time, "s", - (flags & FLAG_TIME_WARN ? true : false), warning_time, - (flags & FLAG_TIME_CRIT ? true : false), critical_time, - true, 0, - true, socket_timeout) - ); + printf("|%s", fperfdata("time", elapsed_time, "s", (flags & FLAG_TIME_WARN ? true : false), warning_time, + (flags & FLAG_TIME_CRIT ? true : false), critical_time, true, 0, true, socket_timeout)); putchar('\n'); return result; } - - /* process command-line arguments */ -static int process_arguments (int argc, char **argv) { +static int process_arguments(int argc, char **argv) { int c; bool escape = false; char *temp; @@ -410,50 +386,48 @@ static int process_arguments (int argc, char **argv) { }; int option = 0; - static struct option longopts[] = { - {"hostname", required_argument, 0, 'H'}, - {"critical", required_argument, 0, 'c'}, - {"warning", required_argument, 0, 'w'}, - {"critical-codes", required_argument, 0, 'C'}, - {"warning-codes", required_argument, 0, 'W'}, - {"timeout", required_argument, 0, 't'}, - {"protocol", required_argument, 0, 'P'}, /* FIXME: Unhandled */ - {"port", required_argument, 0, 'p'}, - {"escape", no_argument, 0, 'E'}, - {"all", no_argument, 0, 'A'}, - {"send", required_argument, 0, 's'}, - {"expect", required_argument, 0, 'e'}, - {"maxbytes", required_argument, 0, 'm'}, - {"quit", required_argument, 0, 'q'}, - {"jail", no_argument, 0, 'j'}, - {"delay", required_argument, 0, 'd'}, - {"refuse", required_argument, 0, 'r'}, - {"mismatch", required_argument, 0, 'M'}, - {"use-ipv4", no_argument, 0, '4'}, - {"use-ipv6", no_argument, 0, '6'}, - {"verbose", no_argument, 0, 'v'}, - {"version", no_argument, 0, 'V'}, - {"help", no_argument, 0, 'h'}, - {"ssl", no_argument, 0, 'S'}, - {"sni", required_argument, 0, SNI_OPTION}, - {"certificate", required_argument, 0, 'D'}, - {0, 0, 0, 0} - }; + static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, + {"critical", required_argument, 0, 'c'}, + {"warning", required_argument, 0, 'w'}, + {"critical-codes", required_argument, 0, 'C'}, + {"warning-codes", required_argument, 0, 'W'}, + {"timeout", required_argument, 0, 't'}, + {"protocol", required_argument, 0, 'P'}, /* FIXME: Unhandled */ + {"port", required_argument, 0, 'p'}, + {"escape", no_argument, 0, 'E'}, + {"all", no_argument, 0, 'A'}, + {"send", required_argument, 0, 's'}, + {"expect", required_argument, 0, 'e'}, + {"maxbytes", required_argument, 0, 'm'}, + {"quit", required_argument, 0, 'q'}, + {"jail", no_argument, 0, 'j'}, + {"delay", required_argument, 0, 'd'}, + {"refuse", required_argument, 0, 'r'}, + {"mismatch", required_argument, 0, 'M'}, + {"use-ipv4", no_argument, 0, '4'}, + {"use-ipv6", no_argument, 0, '6'}, + {"verbose", no_argument, 0, 'v'}, + {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {"ssl", no_argument, 0, 'S'}, + {"sni", required_argument, 0, SNI_OPTION}, + {"certificate", required_argument, 0, 'D'}, + {0, 0, 0, 0}}; if (argc < 2) - usage4 (_("No arguments found")); + usage4(_("No arguments found")); /* backwards compatibility */ for (c = 1; c < argc; c++) { - if (strcmp ("-to", argv[c]) == 0) - strcpy (argv[c], "-t"); - else if (strcmp ("-wt", argv[c]) == 0) - strcpy (argv[c], "-w"); - else if (strcmp ("-ct", argv[c]) == 0) - strcpy (argv[c], "-c"); + if (strcmp("-to", argv[c]) == 0) + strcpy(argv[c], "-t"); + else if (strcmp("-wt", argv[c]) == 0) + strcpy(argv[c], "-w"); + else if (strcmp("-ct", argv[c]) == 0) + strcpy(argv[c], "-c"); } - if (!is_option (argv[1])) { + if (!is_option(argv[1])) { server_address = argv[1]; argv[1] = argv[0]; argv = &argv[1]; @@ -461,22 +435,21 @@ static int process_arguments (int argc, char **argv) { } while (1) { - c = getopt_long (argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:", - longopts, &option); + c = getopt_long(argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:", longopts, &option); if (c == -1 || c == EOF || c == 1) break; switch (c) { - case '?': /* print short usage statement if args not parsable */ - usage5 (); - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'v': /* verbose mode */ + case '?': /* print short usage statement if args not parsable */ + usage5(); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'v': /* verbose mode */ flags |= FLAG_VERBOSE; match_flags |= NP_MATCH_VERBOSE; break; @@ -487,43 +460,43 @@ static int 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 'H': /* hostname */ + case 'H': /* hostname */ host_specified = true; server_address = optarg; break; - case 'c': /* critical */ - critical_time = strtod (optarg, NULL); + case 'c': /* critical */ + critical_time = strtod(optarg, NULL); flags |= FLAG_TIME_CRIT; break; - case 'j': /* hide output */ + case 'j': /* hide output */ flags |= FLAG_HIDE_OUTPUT; break; - case 'w': /* warning */ - warning_time = strtod (optarg, NULL); + case 'w': /* warning */ + warning_time = strtod(optarg, NULL); flags |= FLAG_TIME_WARN; break; case 'C': - crit_codes = realloc (crit_codes, ++crit_codes_count); + crit_codes = realloc(crit_codes, ++crit_codes_count); crit_codes[crit_codes_count - 1] = optarg; break; case 'W': - warn_codes = realloc (warn_codes, ++warn_codes_count); + warn_codes = realloc(warn_codes, ++warn_codes_count); warn_codes[warn_codes_count - 1] = optarg; break; - case 't': /* timeout */ - if (!is_intpos (optarg)) - usage4 (_("Timeout interval must be a positive integer")); + case 't': /* timeout */ + if (!is_intpos(optarg)) + usage4(_("Timeout interval must be a positive integer")); else - socket_timeout = atoi (optarg); + socket_timeout = atoi(optarg); break; - case 'p': /* port */ - if (!is_intpos (optarg)) - usage4 (_("Port must be a positive integer")); + case 'p': /* port */ + if (!is_intpos(optarg)) + usage4(_("Port must be a positive integer")); else - server_port = atoi (optarg); + server_port = atoi(optarg); break; case 'E': escape = true; @@ -537,16 +510,16 @@ static int process_arguments (int argc, char **argv) { case 'e': /* expect string (may be repeated) */ match_flags &= ~NP_MATCH_EXACT; if (server_expect_count == 0) - server_expect = malloc (sizeof (char *) * (++server_expect_count)); + server_expect = malloc(sizeof(char *) * (++server_expect_count)); else - server_expect = realloc (server_expect, sizeof (char *) * (++server_expect_count)); + server_expect = realloc(server_expect, sizeof(char *) * (++server_expect_count)); server_expect[server_expect_count - 1] = optarg; break; case 'm': - if (!is_intpos (optarg)) - usage4 (_("Maxbytes must be a positive integer")); + if (!is_intpos(optarg)) + usage4(_("Maxbytes must be a positive integer")); else - maxbytes = strtol (optarg, NULL, 0); + maxbytes = strtol(optarg, NULL, 0); break; case 'q': if (escape) @@ -555,62 +528,61 @@ static int process_arguments (int argc, char **argv) { xasprintf(&server_quit, "%s\r\n", optarg); break; case 'r': - if (!strncmp(optarg,"ok",2)) + if (!strncmp(optarg, "ok", 2)) econn_refuse_state = STATE_OK; - else if (!strncmp(optarg,"warn",4)) + else if (!strncmp(optarg, "warn", 4)) econn_refuse_state = STATE_WARNING; - else if (!strncmp(optarg,"crit",4)) + else if (!strncmp(optarg, "crit", 4)) econn_refuse_state = STATE_CRITICAL; else - usage4 (_("Refuse must be one of ok, warn, crit")); + usage4(_("Refuse must be one of ok, warn, crit")); break; case 'M': - if (!strncmp(optarg,"ok",2)) + if (!strncmp(optarg, "ok", 2)) expect_mismatch_state = STATE_OK; - else if (!strncmp(optarg,"warn",4)) + else if (!strncmp(optarg, "warn", 4)) expect_mismatch_state = STATE_WARNING; - else if (!strncmp(optarg,"crit",4)) + else if (!strncmp(optarg, "crit", 4)) expect_mismatch_state = STATE_CRITICAL; else - usage4 (_("Mismatch must be one of ok, warn, crit")); + usage4(_("Mismatch must be one of ok, warn, crit")); break; case 'd': - if (is_intpos (optarg)) - delay = atoi (optarg); + if (is_intpos(optarg)) + delay = atoi(optarg); else - usage4 (_("Delay must be a positive integer")); + usage4(_("Delay must be a positive integer")); break; case 'D': /* Check SSL cert validity - days 'til certificate expiration */ #ifdef HAVE_SSL -# ifdef USE_OPENSSL /* XXX */ - 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++; - 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); +# ifdef USE_OPENSSL /* XXX */ + 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++; + 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; flags |= FLAG_SSL; break; -# endif /* USE_OPENSSL */ +# endif /* USE_OPENSSL */ #endif /* fallthrough if we don't have ssl */ case 'S': #ifdef HAVE_SSL flags |= FLAG_SSL; #else - die (STATE_UNKNOWN, _("Invalid option - SSL is not available")); + die(STATE_UNKNOWN, _("Invalid option - SSL is not available")); #endif break; case SNI_OPTION: @@ -619,7 +591,7 @@ static int process_arguments (int argc, char **argv) { sni_specified = true; sni = optarg; #else - die (STATE_UNKNOWN, _("Invalid option - SSL is not available")); + die(STATE_UNKNOWN, _("Invalid option - SSL is not available")); #endif break; case 'A': @@ -629,86 +601,80 @@ static int process_arguments (int argc, char **argv) { } c = optind; - if(!host_specified && c < argc) - server_address = strdup (argv[c++]); + if (!host_specified && c < argc) + server_address = strdup(argv[c++]); if (server_address == NULL) - usage4 (_("You must provide a server address")); + usage4(_("You must provide a server address")); else if (server_address[0] != '/' && !is_host(server_address)) - die (STATE_CRITICAL, "%s %s - %s: %s\n", SERVICE, state_text(STATE_CRITICAL), _("Invalid hostname, address or socket"), server_address); + die(STATE_CRITICAL, "%s %s - %s: %s\n", SERVICE, state_text(STATE_CRITICAL), _("Invalid hostname, address or socket"), + server_address); return OK; } - -void -print_help (void) -{ - print_revision (progname, NP_VERSION); - - printf ("Copyright (c) 1999 Ethan Galstad \n"); - printf (COPYRIGHT, copyright, email); - - printf (_("This plugin tests %s connections with the specified host (or unix socket).\n\n"), - SERVICE); - - print_usage (); - - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); - - printf (UT_HOST_PORT, 'p', "none"); - - printf (UT_IPv46); - - printf (" %s\n", "-E, --escape"); - printf (" %s\n", _("Can use \\n, \\r, \\t or \\\\ in send or quit string. Must come before send or quit option")); - printf (" %s\n", _("Default: nothing added to send, \\r\\n added to end of quit")); - printf (" %s\n", "-s, --send=STRING"); - printf (" %s\n", _("String to send to the server")); - printf (" %s\n", "-e, --expect=STRING"); - printf (" %s %s\n", _("String to expect in server response"), _("(may be repeated)")); - printf (" %s\n", "-A, --all"); - printf (" %s\n", _("All expect strings need to occur in server response. Default is any")); - printf (" %s\n", "-q, --quit=STRING"); - printf (" %s\n", _("String to send server to initiate a clean close of the connection")); - printf (" %s\n", "-r, --refuse=ok|warn|crit"); - printf (" %s\n", _("Accept TCP refusals with states ok, warn, crit (default: crit)")); - printf (" %s\n", "-M, --mismatch=ok|warn|crit"); - printf (" %s\n", _("Accept expected string mismatches with states ok, warn, crit (default: warn)")); - printf (" %s\n", "-j, --jail"); - printf (" %s\n", _("Hide output from TCP socket")); - printf (" %s\n", "-m, --maxbytes=INTEGER"); - printf (" %s\n", _("Close connection once more than this number of bytes are received")); - printf (" %s\n", "-d, --delay=INTEGER"); - printf (" %s\n", _("Seconds to wait between sending string and polling for response")); +void print_help(void) { + print_revision(progname, NP_VERSION); + + printf("Copyright (c) 1999 Ethan Galstad \n"); + printf(COPYRIGHT, copyright, email); + + printf(_("This plugin tests %s connections with the specified host (or unix socket).\n\n"), SERVICE); + + print_usage(); + + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); + + printf(UT_HOST_PORT, 'p', "none"); + + printf(UT_IPv46); + + printf(" %s\n", "-E, --escape"); + printf(" %s\n", _("Can use \\n, \\r, \\t or \\\\ in send or quit string. Must come before send or quit option")); + printf(" %s\n", _("Default: nothing added to send, \\r\\n added to end of quit")); + printf(" %s\n", "-s, --send=STRING"); + printf(" %s\n", _("String to send to the server")); + printf(" %s\n", "-e, --expect=STRING"); + printf(" %s %s\n", _("String to expect in server response"), _("(may be repeated)")); + printf(" %s\n", "-A, --all"); + printf(" %s\n", _("All expect strings need to occur in server response. Default is any")); + printf(" %s\n", "-q, --quit=STRING"); + printf(" %s\n", _("String to send server to initiate a clean close of the connection")); + printf(" %s\n", "-r, --refuse=ok|warn|crit"); + printf(" %s\n", _("Accept TCP refusals with states ok, warn, crit (default: crit)")); + printf(" %s\n", "-M, --mismatch=ok|warn|crit"); + printf(" %s\n", _("Accept expected string mismatches with states ok, warn, crit (default: warn)")); + printf(" %s\n", "-j, --jail"); + printf(" %s\n", _("Hide output from TCP socket")); + printf(" %s\n", "-m, --maxbytes=INTEGER"); + printf(" %s\n", _("Close connection once more than this number of bytes are received")); + printf(" %s\n", "-d, --delay=INTEGER"); + printf(" %s\n", _("Seconds to wait between sending string and polling for response")); #ifdef HAVE_SSL - printf (" %s\n", "-D, --certificate=INTEGER[,INTEGER]"); - printf (" %s\n", _("Minimum number of days a certificate has to be valid.")); - printf (" %s\n", _("1st is #days for warning, 2nd is critical (if not specified - 0).")); - printf (" %s\n", "-S, --ssl"); - printf (" %s\n", _("Use SSL for the connection.")); - printf (" %s\n", "--sni=STRING"); - printf (" %s\n", _("SSL server_name")); + printf(" %s\n", "-D, --certificate=INTEGER[,INTEGER]"); + printf(" %s\n", _("Minimum number of days a certificate has to be valid.")); + printf(" %s\n", _("1st is #days for warning, 2nd is critical (if not specified - 0).")); + printf(" %s\n", "-S, --ssl"); + printf(" %s\n", _("Use SSL for the connection.")); + printf(" %s\n", "--sni=STRING"); + printf(" %s\n", _("SSL server_name")); #endif - printf (UT_WARN_CRIT); + printf(UT_WARN_CRIT); - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - printf (UT_VERBOSE); + printf(UT_VERBOSE); - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s -H host -p port [-w ] [-c ] [-s ]\n",progname); - printf ("[-e ] [-q ][-m ] [-d ]\n"); - printf ("[-t ] [-r ] [-M ] [-v] [-4|-6] [-j]\n"); - printf ("[-D [,]] [-S ] [-E]\n"); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s -H host -p port [-w ] [-c ] [-s ]\n", progname); + printf("[-e ] [-q ][-m ] [-d ]\n"); + printf("[-t ] [-r ] [-M ] [-v] [-4|-6] [-j]\n"); + printf("[-D [,]] [-S ] [-E]\n"); } -- cgit v0.10-9-g596f From ec70b396727570c21465f8d94fb64105a80ae958 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:02:57 +0100 Subject: check_tcp: update_copyright diff --git a/plugins/check_tcp.c b/plugins/check_tcp.c index 78dcbd4..af31885 100644 --- a/plugins/check_tcp.c +++ b/plugins/check_tcp.c @@ -3,7 +3,7 @@ * Monitoring check_tcp plugin * * License: GPL - * Copyright (c) 1999-2013 Monitoring Plugins Development Team + * Copyright (c) 1999-2024 Monitoring Plugins Development Team * * Description: * @@ -29,7 +29,7 @@ /* progname "check_tcp" changes depending on symlink called */ char *progname; -const char *copyright = "1999-2008"; +const char *copyright = "1999-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From c1f337c6537110d87b4cf2e63454889f910c3fa2 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:07:54 +0100 Subject: check_tcp: style + linter fixes diff --git a/plugins/check_tcp.c b/plugins/check_tcp.c index af31885..c13ac76 100644 --- a/plugins/check_tcp.c +++ b/plugins/check_tcp.c @@ -51,8 +51,8 @@ static int days_till_exp_warn, days_till_exp_crit; #endif /* int my_recv(char *, size_t); */ -static int process_arguments(int, char **); -void print_help(void); +static int process_arguments(int /*argc*/, char ** /*argv*/); +static void print_help(void); void print_usage(void); #define EXPECT server_expect[0] @@ -99,15 +99,6 @@ static bool sni_specified = false; static size_t flags; int main(int argc, char **argv) { - int result = STATE_UNKNOWN; - char *status = NULL; - struct timeval tv; - struct timeval timeout; - int match = -1; - fd_set rfds; - - FD_ZERO(&rfds); - setlocale(LC_ALL, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); @@ -202,7 +193,7 @@ int main(int argc, char **argv) { server_port = PORT; server_send = SEND; server_quit = QUIT; - status = NULL; + char *status = NULL; /* Parse extra opts if any */ argv = np_extra_opts(&argc, argv, progname); @@ -228,8 +219,10 @@ int main(int argc, char **argv) { alarm(socket_timeout); /* try to connect to the host at the given port number */ + struct timeval tv; gettimeofday(&tv, NULL); + int result = STATE_UNKNOWN; result = np_net_connect(server_address, server_port, &sd, PROTOCOL); if (result == STATE_CRITICAL) return econn_refuse_state; @@ -273,6 +266,10 @@ int main(int argc, char **argv) { /* if(len) later on, we know we have a non-NULL response */ ssize_t len = 0; + int match = -1; + struct timeval timeout; + fd_set rfds; + FD_ZERO(&rfds); if (server_expect_count) { ssize_t received = 0; @@ -377,15 +374,10 @@ int main(int argc, char **argv) { /* process command-line arguments */ static int process_arguments(int argc, char **argv) { - int c; - bool escape = false; - char *temp; - enum { SNI_OPTION = CHAR_MAX + 1 }; - int option = 0; static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, @@ -418,13 +410,13 @@ static int process_arguments(int argc, char **argv) { usage4(_("No arguments found")); /* backwards compatibility */ - for (c = 1; c < argc; c++) { - if (strcmp("-to", argv[c]) == 0) - strcpy(argv[c], "-t"); - else if (strcmp("-wt", argv[c]) == 0) - strcpy(argv[c], "-w"); - else if (strcmp("-ct", argv[c]) == 0) - strcpy(argv[c], "-c"); + for (int i = 1; i < argc; i++) { + if (strcmp("-to", argv[i]) == 0) + strcpy(argv[i], "-t"); + else if (strcmp("-wt", argv[i]) == 0) + strcpy(argv[i], "-w"); + else if (strcmp("-ct", argv[i]) == 0) + strcpy(argv[i], "-c"); } if (!is_option(argv[1])) { @@ -434,13 +426,16 @@ static int process_arguments(int argc, char **argv) { argc--; } - while (1) { - c = getopt_long(argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:", longopts, &option); + int option_char; + bool escape = false; + while (true) { + int option = 0; + option_char = getopt_long(argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:", longopts, &option); - if (c == -1 || c == EOF || c == 1) + if (option_char == -1 || option_char == EOF || option_char == 1) break; - switch (c) { + switch (option_char) { case '?': /* print short usage statement if args not parsable */ usage5(); case 'h': /* help */ @@ -553,9 +548,10 @@ static int process_arguments(int argc, char **argv) { else usage4(_("Delay must be a positive integer")); break; - case 'D': /* Check SSL cert validity - days 'til certificate expiration */ + case 'D': { /* Check SSL cert validity - days 'til certificate expiration */ #ifdef HAVE_SSL # ifdef USE_OPENSSL /* XXX */ + char *temp; if ((temp = strchr(optarg, ',')) != NULL) { *temp = '\0'; if (!is_intnonneg(optarg)) @@ -574,7 +570,7 @@ static int process_arguments(int argc, char **argv) { } check_cert = true; flags |= FLAG_SSL; - break; + } break; # endif /* USE_OPENSSL */ #endif /* fallthrough if we don't have ssl */ @@ -600,9 +596,9 @@ static int process_arguments(int argc, char **argv) { } } - c = optind; - if (!host_specified && c < argc) - server_address = strdup(argv[c++]); + option_char = optind; + if (!host_specified && option_char < argc) + server_address = strdup(argv[option_char++]); if (server_address == NULL) usage4(_("You must provide a server address")); -- cgit v0.10-9-g596f From e4e7c00647c44901eca531f0209d7211725f8b86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:09:45 +0100 Subject: check_time: clang-format diff --git a/plugins/check_time.c b/plugins/check_time.c index f50ea42..41d2c49 100644 --- a/plugins/check_time.c +++ b/plugins/check_time.c @@ -1,32 +1,32 @@ /***************************************************************************** -* -* Monitoring check_time plugin -* -* License: GPL -* Copyright (c) 1999-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_time plugin -* -* This plugin will check the time difference with the specified host. -* -* -* 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_time plugin + * + * License: GPL + * Copyright (c) 1999-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_time plugin + * + * This plugin will check the time difference with the specified host. + * + * + * 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_time"; const char *copyright = "1999-2007"; @@ -40,7 +40,7 @@ enum { TIME_PORT = 37 }; -#define UNIX_EPOCH 2208988800UL +#define UNIX_EPOCH 2208988800UL uint32_t raw_server_time; unsigned long server_time, diff_time; @@ -56,39 +56,37 @@ int server_port = TIME_PORT; char *server_address = NULL; bool use_udp = false; -int process_arguments (int, char **); -void print_help (void); -void print_usage (void); +int process_arguments(int, char **); +void print_help(void); +void print_usage(void); -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { int sd; int result = STATE_UNKNOWN; time_t conntime; - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if (process_arguments (argc, argv) == ERROR) - usage4 (_("Could not parse arguments")); + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments")); /* initialize alarm signal handling */ - signal (SIGALRM, socket_timeout_alarm_handler); + signal(SIGALRM, socket_timeout_alarm_handler); /* set socket timeout */ - alarm (socket_timeout); - time (&start_time); + alarm(socket_timeout); + time(&start_time); /* try to connect to the host at the given port number */ if (use_udp) { - result = my_udp_connect (server_address, server_port, &sd); + result = my_udp_connect(server_address, server_port, &sd); } else { - result = my_tcp_connect (server_address, server_port, &sd); + result = my_tcp_connect(server_address, server_port, &sd); } if (result != STATE_OK) { @@ -98,34 +96,30 @@ main (int argc, char **argv) result = STATE_WARNING; else result = STATE_UNKNOWN; - die (result, - _("TIME UNKNOWN - could not connect to server %s, port %d\n"), - server_address, server_port); + die(result, _("TIME UNKNOWN - could not connect to server %s, port %d\n"), server_address, server_port); } if (use_udp) { - if (send (sd, "", 0, 0) < 0) { + if (send(sd, "", 0, 0) < 0) { if (check_critical_time) result = STATE_CRITICAL; else if (check_warning_time) result = STATE_WARNING; else result = STATE_UNKNOWN; - die (result, - _("TIME UNKNOWN - could not send UDP request to server %s, port %d\n"), - server_address, server_port); + die(result, _("TIME UNKNOWN - could not send UDP request to server %s, port %d\n"), server_address, server_port); } } /* watch for the connection string */ - result = recv (sd, (void *)&raw_server_time, sizeof (raw_server_time), 0); + result = recv(sd, (void *)&raw_server_time, sizeof(raw_server_time), 0); /* close the connection */ - close (sd); + close(sd); /* reset the alarm */ - time (&end_time); - alarm (0); + time(&end_time); + alarm(0); /* return a WARNING status if we couldn't read any data */ if (result <= 0) { @@ -135,175 +129,150 @@ main (int argc, char **argv) result = STATE_WARNING; else result = STATE_UNKNOWN; - die (result, - _("TIME UNKNOWN - no data received from server %s, port %d\n"), - server_address, server_port); + die(result, _("TIME UNKNOWN - no data received from server %s, port %d\n"), server_address, server_port); } result = STATE_OK; conntime = (end_time - start_time); - if (check_critical_time&& conntime > critical_time) + if (check_critical_time && conntime > critical_time) result = STATE_CRITICAL; else if (check_warning_time && conntime > warning_time) result = STATE_WARNING; if (result != STATE_OK) - die (result, _("TIME %s - %d second response time|%s\n"), - state_text (result), (int)conntime, - perfdata ("time", (long)conntime, "s", - check_warning_time, (long)warning_time, - check_critical_time, (long)critical_time, - true, 0, false, 0)); - - server_time = ntohl (raw_server_time) - UNIX_EPOCH; + die(result, _("TIME %s - %d second response time|%s\n"), state_text(result), (int)conntime, + perfdata("time", (long)conntime, "s", check_warning_time, (long)warning_time, check_critical_time, (long)critical_time, true, 0, + false, 0)); + + server_time = ntohl(raw_server_time) - UNIX_EPOCH; if (server_time > (unsigned long)end_time) diff_time = server_time - (unsigned long)end_time; else diff_time = (unsigned long)end_time - server_time; - if (check_critical_diff&& diff_time > critical_diff) + if (check_critical_diff && diff_time > critical_diff) result = STATE_CRITICAL; - else if (check_warning_diff&& diff_time > warning_diff) + else if (check_warning_diff && diff_time > warning_diff) result = STATE_WARNING; - printf (_("TIME %s - %lu second time difference|%s %s\n"), - state_text (result), diff_time, - perfdata ("time", (long)conntime, "s", - check_warning_time, (long)warning_time, - check_critical_time, (long)critical_time, - true, 0, false, 0), - perfdata ("offset", diff_time, "s", - check_warning_diff, warning_diff, - check_critical_diff, critical_diff, - true, 0, false, 0)); + printf(_("TIME %s - %lu second time difference|%s %s\n"), state_text(result), diff_time, + perfdata("time", (long)conntime, "s", check_warning_time, (long)warning_time, check_critical_time, (long)critical_time, true, 0, + false, 0), + perfdata("offset", diff_time, "s", check_warning_diff, warning_diff, check_critical_diff, critical_diff, true, 0, false, 0)); return result; } - - /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ +int process_arguments(int argc, char **argv) { int c; int option = 0; - static struct option longopts[] = { - {"hostname", required_argument, 0, 'H'}, - {"warning-variance", required_argument, 0, 'w'}, - {"critical-variance", required_argument, 0, 'c'}, - {"warning-connect", required_argument, 0, 'W'}, - {"critical-connect", required_argument, 0, 'C'}, - {"port", required_argument, 0, 'p'}, - {"udp", no_argument, 0, 'u'}, - {"timeout", required_argument, 0, 't'}, - {"version", no_argument, 0, 'V'}, - {"help", no_argument, 0, 'h'}, - {0, 0, 0, 0} - }; + static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, + {"warning-variance", required_argument, 0, 'w'}, + {"critical-variance", required_argument, 0, 'c'}, + {"warning-connect", required_argument, 0, 'W'}, + {"critical-connect", required_argument, 0, 'C'}, + {"port", required_argument, 0, 'p'}, + {"udp", no_argument, 0, 'u'}, + {"timeout", required_argument, 0, 't'}, + {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {0, 0, 0, 0}}; if (argc < 2) - usage ("\n"); + usage("\n"); for (c = 1; c < argc; c++) { - if (strcmp ("-to", argv[c]) == 0) - strcpy (argv[c], "-t"); - else if (strcmp ("-wd", argv[c]) == 0) - strcpy (argv[c], "-w"); - else if (strcmp ("-cd", argv[c]) == 0) - strcpy (argv[c], "-c"); - else if (strcmp ("-wt", argv[c]) == 0) - strcpy (argv[c], "-W"); - else if (strcmp ("-ct", argv[c]) == 0) - strcpy (argv[c], "-C"); + if (strcmp("-to", argv[c]) == 0) + strcpy(argv[c], "-t"); + else if (strcmp("-wd", argv[c]) == 0) + strcpy(argv[c], "-w"); + else if (strcmp("-cd", argv[c]) == 0) + strcpy(argv[c], "-c"); + else if (strcmp("-wt", argv[c]) == 0) + strcpy(argv[c], "-W"); + else if (strcmp("-ct", argv[c]) == 0) + strcpy(argv[c], "-C"); } while (true) { - c = getopt_long (argc, argv, "hVH:w:c:W:C:p:t:u", longopts, - &option); + c = getopt_long(argc, argv, "hVH:w:c:W:C:p:t:u", longopts, &option); if (c == -1 || c == EOF) break; switch (c) { - case '?': /* print short usage statement if args not parsable */ - usage5 (); - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'H': /* hostname */ - if (!is_host (optarg)) - usage2 (_("Invalid hostname/address"), optarg); + case '?': /* print short usage statement if args not parsable */ + usage5(); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'H': /* hostname */ + if (!is_host(optarg)) + usage2(_("Invalid hostname/address"), optarg); server_address = optarg; break; - case 'w': /* warning-variance */ - if (is_intnonneg (optarg)) { - warning_diff = strtoul (optarg, NULL, 10); + case 'w': /* warning-variance */ + if (is_intnonneg(optarg)) { + warning_diff = strtoul(optarg, NULL, 10); check_warning_diff = true; - } - else if (strspn (optarg, "0123456789:,") > 0) { - if (sscanf (optarg, "%lu%*[:,]%d", &warning_diff, &warning_time) == 2) { + } else if (strspn(optarg, "0123456789:,") > 0) { + if (sscanf(optarg, "%lu%*[:,]%d", &warning_diff, &warning_time) == 2) { check_warning_diff = true; check_warning_time = true; + } else { + usage4(_("Warning thresholds must be a positive integer")); } - else { - usage4 (_("Warning thresholds must be a positive integer")); - } - } - else { - usage4 (_("Warning threshold must be a positive integer")); + } else { + usage4(_("Warning threshold must be a positive integer")); } break; - case 'c': /* critical-variance */ - if (is_intnonneg (optarg)) { - critical_diff = strtoul (optarg, NULL, 10); + case 'c': /* critical-variance */ + if (is_intnonneg(optarg)) { + critical_diff = strtoul(optarg, NULL, 10); check_critical_diff = true; - } - else if (strspn (optarg, "0123456789:,") > 0) { - if (sscanf (optarg, "%lu%*[:,]%d", &critical_diff, &critical_time) == - 2) { + } else if (strspn(optarg, "0123456789:,") > 0) { + if (sscanf(optarg, "%lu%*[:,]%d", &critical_diff, &critical_time) == 2) { check_critical_diff = true; check_critical_time = true; + } else { + usage4(_("Critical thresholds must be a positive integer")); } - else { - usage4 (_("Critical thresholds must be a positive integer")); - } - } - else { - usage4 (_("Critical threshold must be a positive integer")); + } else { + usage4(_("Critical threshold must be a positive integer")); } break; - case 'W': /* warning-connect */ - if (!is_intnonneg (optarg)) - usage4 (_("Warning threshold must be a positive integer")); + case 'W': /* warning-connect */ + if (!is_intnonneg(optarg)) + usage4(_("Warning threshold must be a positive integer")); else - warning_time = atoi (optarg); + warning_time = atoi(optarg); check_warning_time = true; break; - case 'C': /* critical-connect */ - if (!is_intnonneg (optarg)) - usage4 (_("Critical threshold must be a positive integer")); + case 'C': /* critical-connect */ + if (!is_intnonneg(optarg)) + usage4(_("Critical threshold must be a positive integer")); else - critical_time = atoi (optarg); + critical_time = atoi(optarg); check_critical_time = true; break; - case 'p': /* port */ - if (!is_intnonneg (optarg)) - usage4 (_("Port must be a positive integer")); + case 'p': /* port */ + if (!is_intnonneg(optarg)) + usage4(_("Port must be a positive integer")); else - server_port = atoi (optarg); + server_port = atoi(optarg); break; - case 't': /* timeout */ - if (!is_intnonneg (optarg)) - usage2 (_("Timeout interval must be a positive integer"), optarg); + case 't': /* timeout */ + if (!is_intnonneg(optarg)) + usage2(_("Timeout interval must be a positive integer"), optarg); else - socket_timeout = atoi (optarg); + socket_timeout = atoi(optarg); break; - case 'u': /* udp */ + case 'u': /* udp */ use_udp = true; } } @@ -311,64 +280,55 @@ process_arguments (int argc, char **argv) c = optind; if (server_address == NULL) { if (argc > c) { - if (!is_host (argv[c])) - usage2 (_("Invalid hostname/address"), optarg); + if (!is_host(argv[c])) + usage2(_("Invalid hostname/address"), optarg); server_address = argv[c]; - } - else { - usage4 (_("Hostname was not supplied")); + } else { + usage4(_("Hostname was not supplied")); } } return OK; } - - -void -print_help (void) -{ +void print_help(void) { char *myport; - xasprintf (&myport, "%d", TIME_PORT); + xasprintf(&myport, "%d", TIME_PORT); - print_revision (progname, NP_VERSION); + 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 will check the time on the specified host.")); + printf("%s\n", _("This plugin will check the time on the specified host.")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); - printf (UT_HOST_PORT, 'p', myport); + printf(UT_HOST_PORT, 'p', myport); - printf (" %s\n", "-u, --udp"); - printf (" %s\n", _("Use UDP to connect, not TCP")); - printf (" %s\n", "-w, --warning-variance=INTEGER"); - printf (" %s\n", _("Time difference (sec.) necessary to result in a warning status")); - printf (" %s\n", "-c, --critical-variance=INTEGER"); - printf (" %s\n", _("Time difference (sec.) necessary to result in a critical status")); - printf (" %s\n", "-W, --warning-connect=INTEGER"); - printf (" %s\n", _("Response time (sec.) necessary to result in warning status")); - printf (" %s\n", "-C, --critical-connect=INTEGER"); - printf (" %s\n", _("Response time (sec.) necessary to result in critical status")); + printf(" %s\n", "-u, --udp"); + printf(" %s\n", _("Use UDP to connect, not TCP")); + printf(" %s\n", "-w, --warning-variance=INTEGER"); + printf(" %s\n", _("Time difference (sec.) necessary to result in a warning status")); + printf(" %s\n", "-c, --critical-variance=INTEGER"); + printf(" %s\n", _("Time difference (sec.) necessary to result in a critical status")); + printf(" %s\n", "-W, --warning-connect=INTEGER"); + printf(" %s\n", _("Response time (sec.) necessary to result in warning status")); + printf(" %s\n", "-C, --critical-connect=INTEGER"); + printf(" %s\n", _("Response time (sec.) necessary to result in critical status")); - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s -H [-p port] [-u] [-w variance] [-c variance]\n",progname); - printf (" [-W connect_time] [-C connect_time] [-t timeout]\n"); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s -H [-p port] [-u] [-w variance] [-c variance]\n", progname); + printf(" [-W connect_time] [-C connect_time] [-t timeout]\n"); } -- cgit v0.10-9-g596f From a54dd508958449d4205a2ae6b1033ce44d7507e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:10:27 +0100 Subject: check_time: do not export local variables diff --git a/plugins/check_time.c b/plugins/check_time.c index 41d2c49..cf17b22 100644 --- a/plugins/check_time.c +++ b/plugins/check_time.c @@ -42,22 +42,22 @@ enum { #define UNIX_EPOCH 2208988800UL -uint32_t raw_server_time; -unsigned long server_time, diff_time; -int warning_time = 0; -bool check_warning_time = false; -int critical_time = 0; -bool check_critical_time = false; -unsigned long warning_diff = 0; -bool check_warning_diff = false; -unsigned long critical_diff = 0; -bool check_critical_diff = false; -int server_port = TIME_PORT; -char *server_address = NULL; -bool use_udp = false; - -int process_arguments(int, char **); -void print_help(void); +static uint32_t raw_server_time; +static unsigned long server_time, diff_time; +static int warning_time = 0; +static bool check_warning_time = false; +static int critical_time = 0; +static bool check_critical_time = false; +static unsigned long warning_diff = 0; +static bool check_warning_diff = false; +static unsigned long critical_diff = 0; +static bool check_critical_diff = false; +static int server_port = TIME_PORT; +static char *server_address = NULL; +static bool use_udp = false; + +static int process_arguments(int, char **); +static void print_help(void); void print_usage(void); int main(int argc, char **argv) { -- cgit v0.10-9-g596f From eca51d0787c073900efe723a7ad03467a057197e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:12:27 +0100 Subject: check_time: style + linter fixes diff --git a/plugins/check_time.c b/plugins/check_time.c index cf17b22..7d0cc2e 100644 --- a/plugins/check_time.c +++ b/plugins/check_time.c @@ -61,10 +61,6 @@ static void print_help(void); void print_usage(void); int main(int argc, char **argv) { - int sd; - int result = STATE_UNKNOWN; - time_t conntime; - setlocale(LC_ALL, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); @@ -82,11 +78,13 @@ int main(int argc, char **argv) { alarm(socket_timeout); time(&start_time); + int socket; + int result = STATE_UNKNOWN; /* try to connect to the host at the given port number */ if (use_udp) { - result = my_udp_connect(server_address, server_port, &sd); + result = my_udp_connect(server_address, server_port, &socket); } else { - result = my_tcp_connect(server_address, server_port, &sd); + result = my_tcp_connect(server_address, server_port, &socket); } if (result != STATE_OK) { @@ -100,7 +98,7 @@ int main(int argc, char **argv) { } if (use_udp) { - if (send(sd, "", 0, 0) < 0) { + if (send(socket, "", 0, 0) < 0) { if (check_critical_time) result = STATE_CRITICAL; else if (check_warning_time) @@ -112,10 +110,10 @@ int main(int argc, char **argv) { } /* watch for the connection string */ - result = recv(sd, (void *)&raw_server_time, sizeof(raw_server_time), 0); + result = recv(socket, (void *)&raw_server_time, sizeof(raw_server_time), 0); /* close the connection */ - close(sd); + close(socket); /* reset the alarm */ time(&end_time); @@ -134,7 +132,7 @@ int main(int argc, char **argv) { result = STATE_OK; - conntime = (end_time - start_time); + time_t conntime = (end_time - start_time); if (check_critical_time && conntime > critical_time) result = STATE_CRITICAL; else if (check_warning_time && conntime > warning_time) @@ -165,9 +163,6 @@ int main(int argc, char **argv) { /* process command-line arguments */ int process_arguments(int argc, char **argv) { - int c; - - int option = 0; static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, {"warning-variance", required_argument, 0, 'w'}, {"critical-variance", required_argument, 0, 'c'}, @@ -183,26 +178,28 @@ int process_arguments(int argc, char **argv) { if (argc < 2) usage("\n"); - for (c = 1; c < argc; c++) { - if (strcmp("-to", argv[c]) == 0) - strcpy(argv[c], "-t"); - else if (strcmp("-wd", argv[c]) == 0) - strcpy(argv[c], "-w"); - else if (strcmp("-cd", argv[c]) == 0) - strcpy(argv[c], "-c"); - else if (strcmp("-wt", argv[c]) == 0) - strcpy(argv[c], "-W"); - else if (strcmp("-ct", argv[c]) == 0) - strcpy(argv[c], "-C"); + for (int i = 1; i < argc; i++) { + if (strcmp("-to", argv[i]) == 0) + strcpy(argv[i], "-t"); + else if (strcmp("-wd", argv[i]) == 0) + strcpy(argv[i], "-w"); + else if (strcmp("-cd", argv[i]) == 0) + strcpy(argv[i], "-c"); + else if (strcmp("-wt", argv[i]) == 0) + strcpy(argv[i], "-W"); + else if (strcmp("-ct", argv[i]) == 0) + strcpy(argv[i], "-C"); } + int option_char; while (true) { - c = getopt_long(argc, argv, "hVH:w:c:W:C:p:t:u", longopts, &option); + int option = 0; + option_char = getopt_long(argc, argv, "hVH:w:c:W:C:p:t:u", longopts, &option); - if (c == -1 || c == EOF) + if (option_char == -1 || option_char == EOF) break; - switch (c) { + switch (option_char) { case '?': /* print short usage statement if args not parsable */ usage5(); case 'h': /* help */ @@ -277,12 +274,12 @@ int process_arguments(int argc, char **argv) { } } - c = optind; + option_char = optind; if (server_address == NULL) { - if (argc > c) { - if (!is_host(argv[c])) + if (argc > option_char) { + if (!is_host(argv[option_char])) usage2(_("Invalid hostname/address"), optarg); - server_address = argv[c]; + server_address = argv[option_char]; } else { usage4(_("Hostname was not supplied")); } -- cgit v0.10-9-g596f From 6dd03aff71357712c2ff09667da7b7506d9b7e7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:13:00 +0100 Subject: check_time: update copyright diff --git a/plugins/check_time.c b/plugins/check_time.c index 7d0cc2e..d1f5068 100644 --- a/plugins/check_time.c +++ b/plugins/check_time.c @@ -3,7 +3,7 @@ * Monitoring check_time plugin * * License: GPL - * Copyright (c) 1999-2007 Monitoring Plugins Development Team + * Copyright (c) 1999-2024 Monitoring Plugins Development Team * * Description: * @@ -29,7 +29,7 @@ *****************************************************************************/ const char *progname = "check_time"; -const char *copyright = "1999-2007"; +const char *copyright = "1999-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 35723950547b06a359bac9a767d2a6f1520926b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:13:43 +0100 Subject: check_ups: clang-format diff --git a/plugins/check_ups.c b/plugins/check_ups.c index f60c0e9..adb7ab8 100644 --- a/plugins/check_ups.c +++ b/plugins/check_ups.c @@ -40,7 +40,9 @@ const char *email = "devel@monitoring-plugins.org"; #include "netutils.h" #include "utils.h" -enum { PORT = 3493 }; +enum { + PORT = 3493 +}; #define UPS_NONE 0 /* no supported options */ #define UPS_UTILITY 1 /* supports utility line */ @@ -66,7 +68,9 @@ enum { PORT = 3493 }; #define UPSSTATUS_UNKNOWN 4096 #define UPSSTATUS_ALARM 8192 -enum { NOSUCHVAR = ERROR - 1 }; +enum { + NOSUCHVAR = ERROR - 1 +}; typedef struct ups_config { unsigned int server_port; -- cgit v0.10-9-g596f From 92d18a18d1250f74505790639ddcde6ff9b212cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:14:31 +0100 Subject: check_users: clang-format diff --git a/plugins/check_users.c b/plugins/check_users.c index 89b9536..1ff7fe6 100644 --- a/plugins/check_users.c +++ b/plugins/check_users.c @@ -1,34 +1,34 @@ /***************************************************************************** -* -* Monitoring check_users plugin -* -* License: GPL -* Copyright (c) 2000-2012 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_users plugin -* -* This plugin checks the number of users currently logged in on the local -* system and generates an error if the number exceeds the thresholds -* specified. -* -* -* 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_users plugin + * + * License: GPL + * Copyright (c) 2000-2012 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_users plugin + * + * This plugin checks the number of users currently logged in on the local + * system and generates an error if the number exceeds the thresholds + * specified. + * + * + * 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_users"; const char *copyright = "2000-2007"; @@ -38,34 +38,32 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #if HAVE_WTSAPI32_H -# include -# include -# undef ERROR -# define ERROR -1 +# include +# include +# undef ERROR +# define ERROR -1 #elif HAVE_UTMPX_H -# include +# include #else -# include "popen.h" +# include "popen.h" #endif #ifdef HAVE_LIBSYSTEMD -#include -#include +# include +# include #endif -#define possibly_set(a,b) ((a) == 0 ? (b) : 0) +#define possibly_set(a, b) ((a) == 0 ? (b) : 0) -int process_arguments (int, char **); -void print_help (void); -void print_usage (void); +int process_arguments(int, char **); +void print_help(void); +void print_usage(void); char *warning_range = NULL; char *critical_range = NULL; thresholds *thlds = NULL; -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { int users = -1; int result = STATE_UNKNOWN; #if HAVE_WTSAPI32_H @@ -78,74 +76,71 @@ main (int argc, char **argv) char input_buffer[MAX_INPUT_BUFFER]; #endif - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Parse extra opts if any */ - argv = np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if (process_arguments (argc, argv) == ERROR) - usage4 (_("Could not parse arguments")); + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments")); users = 0; #ifdef HAVE_LIBSYSTEMD - if (sd_booted () > 0) - users = sd_get_sessions (NULL); + if (sd_booted() > 0) + users = sd_get_sessions(NULL); else { #endif #if HAVE_WTSAPI32_H - if (!WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, - 0, 1, &wtsinfo, &wtscount)) { - printf(_("Could not enumerate RD sessions: %d\n"), GetLastError()); - return STATE_UNKNOWN; - } + if (!WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &wtsinfo, &wtscount)) { + printf(_("Could not enumerate RD sessions: %d\n"), GetLastError()); + return STATE_UNKNOWN; + } - for (index = 0; index < wtscount; index++) { - LPTSTR username; - DWORD size; - int len; + for (index = 0; index < wtscount; index++) { + LPTSTR username; + DWORD size; + int len; - if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, - wtsinfo[index].SessionId, WTSUserName, &username, &size)) - continue; + if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, wtsinfo[index].SessionId, WTSUserName, &username, &size)) + continue; - len = lstrlen(username); + len = lstrlen(username); - WTSFreeMemory(username); + WTSFreeMemory(username); - if (len == 0) - continue; + if (len == 0) + continue; - if (wtsinfo[index].State == WTSActive || - wtsinfo[index].State == WTSDisconnected) - users++; - } + if (wtsinfo[index].State == WTSActive || wtsinfo[index].State == WTSDisconnected) + users++; + } - WTSFreeMemory(wtsinfo); + WTSFreeMemory(wtsinfo); #elif HAVE_UTMPX_H /* get currently logged users from utmpx */ - setutxent (); + setutxent(); - while ((putmpx = getutxent ()) != NULL) + while ((putmpx = getutxent()) != NULL) if (putmpx->ut_type == USER_PROCESS) users++; - endutxent (); + endutxent(); #else /* run the command */ - child_process = spopen (WHO_COMMAND); + child_process = spopen(WHO_COMMAND); if (child_process == NULL) { - printf (_("Could not open pipe: %s\n"), WHO_COMMAND); + printf(_("Could not open pipe: %s\n"), WHO_COMMAND); return STATE_UNKNOWN; } - child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r"); + child_stderr = fdopen(child_stderr_array[fileno(child_process)], "r"); if (child_stderr == NULL) - printf (_("Could not open stderr for %s\n"), WHO_COMMAND); + printf(_("Could not open stderr for %s\n"), WHO_COMMAND); - while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) { + while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process)) { /* increment 'users' on all lines except total user count */ if (input_buffer[0] != '#') { users++; @@ -153,18 +148,18 @@ main (int argc, char **argv) } /* get total logged in users */ - if (sscanf (input_buffer, _("# users=%d"), &users) == 1) + if (sscanf(input_buffer, _("# users=%d"), &users) == 1) break; } /* check STDERR */ - if (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) - result = possibly_set (result, STATE_UNKNOWN); - (void) fclose (child_stderr); + if (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) + result = possibly_set(result, STATE_UNKNOWN); + (void)fclose(child_stderr); /* close the pipe */ - if (spclose (child_process)) - result = possibly_set (result, STATE_UNKNOWN); + if (spclose(child_process)) + result = possibly_set(result, STATE_UNKNOWN); #endif #ifdef HAVE_LIBSYSTEMD } @@ -174,53 +169,47 @@ main (int argc, char **argv) result = get_status((double)users, thlds); if (result == STATE_UNKNOWN) - printf ("%s\n", _("Unable to read output")); + printf("%s\n", _("Unable to read output")); else { - printf (_("USERS %s - %d users currently logged in |%s\n"), - state_text(result), users, - sperfdata_int("users", users, "", warning_range, - critical_range, true, 0, false, 0)); + printf(_("USERS %s - %d users currently logged in |%s\n"), state_text(result), users, + sperfdata_int("users", users, "", warning_range, critical_range, true, 0, false, 0)); } return result; } /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ +int process_arguments(int argc, char **argv) { int c; int option = 0; - static struct option longopts[] = { - {"critical", required_argument, 0, 'c'}, - {"warning", required_argument, 0, 'w'}, - {"version", no_argument, 0, 'V'}, - {"help", no_argument, 0, 'h'}, - {0, 0, 0, 0} - }; + static struct option longopts[] = {{"critical", required_argument, 0, 'c'}, + {"warning", required_argument, 0, 'w'}, + {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {0, 0, 0, 0}}; if (argc < 2) - usage ("\n"); + usage("\n"); while (true) { - c = getopt_long (argc, argv, "+hVvc:w:", longopts, &option); + c = getopt_long(argc, argv, "+hVvc:w:", longopts, &option); if (c == -1 || c == EOF || c == 1) break; switch (c) { - case '?': /* print short usage statement if args not parsable */ - usage5 (); - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'c': /* critical */ + case '?': /* print short usage statement if args not parsable */ + usage5(); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'c': /* critical */ critical_range = optarg; break; - case 'w': /* warning */ + case 'w': /* warning */ warning_range = optarg; break; } @@ -235,48 +224,44 @@ process_arguments (int argc, char **argv) critical_range = argv[c++]; /* this will abort in case of invalid ranges */ - set_thresholds (&thlds, warning_range, critical_range); + set_thresholds(&thlds, warning_range, critical_range); if (!thlds->warning) { - usage4 (_("Warning threshold must be a valid range expression")); + usage4(_("Warning threshold must be a valid range expression")); } if (!thlds->critical) { - usage4 (_("Critical threshold must be a valid range expression")); + usage4(_("Critical threshold must be a valid range expression")); } return OK; } -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 checks the number of users currently logged in on the local")); - printf ("%s\n", _("system and generates an error if the number exceeds the thresholds specified.")); + printf("%s\n", _("This plugin checks the number of users currently logged in on the local")); + printf("%s\n", _("system and generates an error if the number exceeds the thresholds specified.")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); - printf (" %s\n", "-w, --warning=RANGE_EXPRESSION"); - printf (" %s\n", _("Set WARNING status if number of logged in users violates RANGE_EXPRESSION")); - printf (" %s\n", "-c, --critical=RANGE_EXPRESSION"); - printf (" %s\n", _("Set CRITICAL status if number of logged in users violates RANGE_EXPRESSION")); + printf(" %s\n", "-w, --warning=RANGE_EXPRESSION"); + printf(" %s\n", _("Set WARNING status if number of logged in users violates RANGE_EXPRESSION")); + printf(" %s\n", "-c, --critical=RANGE_EXPRESSION"); + printf(" %s\n", _("Set CRITICAL status if number of logged in users violates RANGE_EXPRESSION")); - printf (UT_SUPPORT); + printf(UT_SUPPORT); } -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s -w -c \n", progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s -w -c \n", progname); } -- cgit v0.10-9-g596f From 61f569e6d3493e2cd648c3c17f4eb7c82f1070f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:16:13 +0100 Subject: check_users: update copyright diff --git a/plugins/check_users.c b/plugins/check_users.c index 1ff7fe6..885c0dc 100644 --- a/plugins/check_users.c +++ b/plugins/check_users.c @@ -3,7 +3,7 @@ * Monitoring check_users plugin * * License: GPL - * Copyright (c) 2000-2012 Monitoring Plugins Development Team + * Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -31,7 +31,7 @@ *****************************************************************************/ const char *progname = "check_users"; -const char *copyright = "2000-2007"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 7185547291299ce9d32dc95054c35dcabf184e3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:16:34 +0100 Subject: check_users: do not export local variables + style fixes diff --git a/plugins/check_users.c b/plugins/check_users.c index 885c0dc..f1e1c39 100644 --- a/plugins/check_users.c +++ b/plugins/check_users.c @@ -55,13 +55,13 @@ const char *email = "devel@monitoring-plugins.org"; #define possibly_set(a, b) ((a) == 0 ? (b) : 0) -int process_arguments(int, char **); -void print_help(void); +static int process_arguments(int, char **); +static void print_help(void); void print_usage(void); -char *warning_range = NULL; -char *critical_range = NULL; -thresholds *thlds = NULL; +static char *warning_range = NULL; +static char *critical_range = NULL; +static thresholds *thlds = NULL; int main(int argc, char **argv) { int users = -1; @@ -180,8 +180,6 @@ int main(int argc, char **argv) { /* process command-line arguments */ int process_arguments(int argc, char **argv) { - int c; - int option = 0; static struct option longopts[] = {{"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, {"version", no_argument, 0, 'V'}, @@ -191,13 +189,15 @@ int process_arguments(int argc, char **argv) { if (argc < 2) usage("\n"); + int option_char; while (true) { - c = getopt_long(argc, argv, "+hVvc:w:", longopts, &option); + int option = 0; + option_char = getopt_long(argc, argv, "+hVvc:w:", longopts, &option); - if (c == -1 || c == EOF || c == 1) + if (option_char == -1 || option_char == EOF || option_char == 1) break; - switch (c) { + switch (option_char) { case '?': /* print short usage statement if args not parsable */ usage5(); case 'h': /* help */ @@ -215,13 +215,13 @@ int process_arguments(int argc, char **argv) { } } - c = optind; + option_char = optind; - if (warning_range == NULL && argc > c) - warning_range = argv[c++]; + if (warning_range == NULL && argc > option_char) + warning_range = argv[option_char++]; - if (critical_range == NULL && argc > c) - critical_range = argv[c++]; + if (critical_range == NULL && argc > option_char) + critical_range = argv[option_char++]; /* this will abort in case of invalid ranges */ set_thresholds(&thlds, warning_range, critical_range); -- cgit v0.10-9-g596f From e191544a17e1758d5bd256df5b0f3785fb105e1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:17:46 +0100 Subject: negate: clang-format diff --git a/plugins/negate.c b/plugins/negate.c index c5fe7e1..ee497cd 100644 --- a/plugins/negate.c +++ b/plugins/negate.c @@ -1,33 +1,33 @@ /***************************************************************************** -* -* Monitoring negate plugin -* -* License: GPL -* Copyright (c) 2002-2008 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the negate plugin -* -* Negates the status of a plugin (returns OK for CRITICAL, and vice-versa). -* Can also perform custom state switching. -* -* -* 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 negate plugin + * + * License: GPL + * Copyright (c) 2002-2008 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the negate plugin + * + * Negates the status of a plugin (returns OK for CRITICAL, and vice-versa). + * Can also perform custom state switching. + * + * + * 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 = "negate"; const char *copyright = "2002-2008"; @@ -43,10 +43,10 @@ const char *email = "devel@monitoring-plugins.org"; /* char *command_line; */ -static const char **process_arguments (int, char **); -void validate_arguments (char **); -void print_help (void); -void print_usage (void); +static const char **process_arguments(int, char **); +void validate_arguments(char **); +void print_help(void); +void print_usage(void); bool subst_text = false; static int state[4] = { @@ -56,185 +56,167 @@ static int state[4] = { STATE_UNKNOWN, }; -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { int result = STATE_UNKNOWN; char *sub; char **command_line; output chld_out, chld_err; - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); timeout_interval = DEFAULT_TIMEOUT; - command_line = (char **) process_arguments (argc, argv); + command_line = (char **)process_arguments(argc, argv); /* Set signal handling and alarm */ - if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) - die (STATE_UNKNOWN, _("Cannot catch SIGALRM")); + if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR) + die(STATE_UNKNOWN, _("Cannot catch SIGALRM")); - (void) alarm ((unsigned) timeout_interval); + (void)alarm((unsigned)timeout_interval); /* catch when the command is quoted */ - if(command_line[1] == NULL) { - result = cmd_run (command_line[0], &chld_out, &chld_err, 0); + if (command_line[1] == NULL) { + result = cmd_run(command_line[0], &chld_out, &chld_err, 0); } else { - result = cmd_run_array (command_line, &chld_out, &chld_err, 0); + result = cmd_run_array(command_line, &chld_out, &chld_err, 0); } if (chld_err.lines > 0) { for (size_t i = 0; i < chld_err.lines; i++) { - fprintf (stderr, "%s\n", chld_err.line[i]); + fprintf(stderr, "%s\n", chld_err.line[i]); } } /* Return UNKNOWN or worse if no output is returned */ if (chld_out.lines == 0) - die (max_state_alt (result, STATE_UNKNOWN), _("No data returned from command\n")); + die(max_state_alt(result, STATE_UNKNOWN), _("No data returned from command\n")); for (size_t i = 0; i < chld_out.lines; i++) { - if (subst_text && result >= 0 && result <= 4 && result != state[result]) { + if (subst_text && result >= 0 && result <= 4 && result != state[result]) { /* Loop over each match found */ - while ((sub = strstr (chld_out.line[i], state_text (result)))) { + while ((sub = strstr(chld_out.line[i], state_text(result)))) { /* Terminate the first part and skip over the string we'll substitute */ *sub = '\0'; - sub += strlen (state_text (result)); + sub += strlen(state_text(result)); /* then put everything back together */ - xasprintf (&chld_out.line[i], "%s%s%s", chld_out.line[i], state_text (state[result]), sub); + xasprintf(&chld_out.line[i], "%s%s%s", chld_out.line[i], state_text(state[result]), sub); } } - printf ("%s\n", chld_out.line[i]); + printf("%s\n", chld_out.line[i]); } if (result >= 0 && result <= 4) { - exit (state[result]); + exit(state[result]); } else { - exit (result); + exit(result); } } - /* process command-line arguments */ -static const char ** -process_arguments (int argc, char **argv) -{ +static const char **process_arguments(int argc, char **argv) { int c; bool permute = true; int option = 0; - static struct option longopts[] = { - {"help", no_argument, 0, 'h'}, - {"version", no_argument, 0, 'V'}, - {"timeout", required_argument, 0, 't'}, - {"timeout-result", required_argument, 0, 'T'}, - {"ok", required_argument, 0, 'o'}, - {"warning", required_argument, 0, 'w'}, - {"critical", required_argument, 0, 'c'}, - {"unknown", required_argument, 0, 'u'}, - {"substitute", no_argument, 0, 's'}, - {0, 0, 0, 0} - }; + static struct option longopts[] = {{"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'}, + {"timeout", required_argument, 0, 't'}, {"timeout-result", required_argument, 0, 'T'}, + {"ok", required_argument, 0, 'o'}, {"warning", required_argument, 0, 'w'}, + {"critical", required_argument, 0, 'c'}, {"unknown", required_argument, 0, 'u'}, + {"substitute", no_argument, 0, 's'}, {0, 0, 0, 0}}; while (1) { - c = getopt_long (argc, argv, "+hVt:T:o:w:c:u:s", longopts, &option); + c = getopt_long(argc, argv, "+hVt:T:o:w:c:u:s", longopts, &option); if (c == -1 || c == EOF) break; switch (c) { - case '?': /* help */ - usage5 (); + case '?': /* help */ + usage5(); break; - case 'h': /* help */ - print_help (); - exit (EXIT_SUCCESS); + case 'h': /* help */ + print_help(); + exit(EXIT_SUCCESS); break; - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (EXIT_SUCCESS); - case 't': /* timeout period */ - if (!is_integer (optarg)) - usage2 (_("Timeout interval must be a positive integer"), optarg); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(EXIT_SUCCESS); + case 't': /* timeout period */ + if (!is_integer(optarg)) + usage2(_("Timeout interval must be a positive integer"), optarg); else - timeout_interval = atoi (optarg); + timeout_interval = atoi(optarg); break; - case 'T': /* Result to return on timeouts */ + case 'T': /* Result to return on timeouts */ if ((timeout_state = mp_translate_state(optarg)) == ERROR) - usage4 (_("Timeout result must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); + usage4(_("Timeout result must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); break; - case 'o': /* replacement for OK */ + case 'o': /* replacement for OK */ if ((state[STATE_OK] = mp_translate_state(optarg)) == ERROR) - usage4 (_("Ok must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); + usage4(_("Ok must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); permute = false; break; - case 'w': /* replacement for WARNING */ + case 'w': /* replacement for WARNING */ if ((state[STATE_WARNING] = mp_translate_state(optarg)) == ERROR) - usage4 (_("Warning must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); + usage4(_("Warning must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); permute = false; break; - case 'c': /* replacement for CRITICAL */ + case 'c': /* replacement for CRITICAL */ if ((state[STATE_CRITICAL] = mp_translate_state(optarg)) == ERROR) - usage4 (_("Critical must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); + usage4(_("Critical must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); permute = false; break; - case 'u': /* replacement for UNKNOWN */ + case 'u': /* replacement for UNKNOWN */ if ((state[STATE_UNKNOWN] = mp_translate_state(optarg)) == ERROR) - usage4 (_("Unknown must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); + usage4(_("Unknown must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); permute = false; break; - case 's': /* Substitute status text */ + case 's': /* Substitute status text */ subst_text = true; break; } } - validate_arguments (&argv[optind]); + validate_arguments(&argv[optind]); if (permute) { /* No [owcu] switch specified, default to this */ state[STATE_OK] = STATE_CRITICAL; state[STATE_CRITICAL] = STATE_OK; } - return (const char **) &argv[optind]; + return (const char **)&argv[optind]; } - -void -validate_arguments (char **command_line) -{ +void validate_arguments(char **command_line) { if (command_line[0] == NULL) - usage4 (_("Could not parse arguments")); + usage4(_("Could not parse arguments")); - if (strncmp(command_line[0],"/",1) != 0 && strncmp(command_line[0],"./",2) != 0) - usage4 (_("Require path to command")); + if (strncmp(command_line[0], "/", 1) != 0 && strncmp(command_line[0], "./", 2) != 0) + usage4(_("Require path to command")); } +void print_help(void) { + print_revision(progname, NP_VERSION); -void -print_help (void) -{ - print_revision (progname, NP_VERSION); - - printf (COPYRIGHT, copyright, email); + printf(COPYRIGHT, copyright, email); - printf ("%s\n", _("Negates only the return code of a plugin (returns OK for CRITICAL and vice-versa) by default.")); - printf ("%s\n", _("Additional switches can be used to control:\n")); - printf ("\t - which state becomes what\n"); - printf ("\t - changing the plugin output text to match the return code"); + printf("%s\n", _("Negates only the return code of a plugin (returns OK for CRITICAL and vice-versa) by default.")); + printf("%s\n", _("Additional switches can be used to control:\n")); + printf("\t - which state becomes what\n"); + printf("\t - changing the plugin output text to match the return code"); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (UT_HELP_VRSN); + printf(UT_HELP_VRSN); - printf (UT_PLUG_TIMEOUT, timeout_interval); - printf (" %s\n", _("Keep timeout longer than the plugin timeout to retain CRITICAL status.")); - printf (" -T, --timeout-result=STATUS\n"); - printf (" %s\n", _("Custom result on Negate timeouts; see below for STATUS definition\n")); + printf(UT_PLUG_TIMEOUT, timeout_interval); + printf(" %s\n", _("Keep timeout longer than the plugin timeout to retain CRITICAL status.")); + printf(" -T, --timeout-result=STATUS\n"); + printf(" %s\n", _("Custom result on Negate timeouts; see below for STATUS definition\n")); printf(" -o, --ok=STATUS\n"); printf(" -w, --warning=STATUS\n"); @@ -246,31 +228,27 @@ print_help (void) printf(" -s, --substitute\n"); printf(_(" Substitute output text as well. Will only substitute text in CAPITALS\n")); - printf ("\n"); - printf ("%s\n", _("Examples:")); - printf (" %s\n", "negate /usr/local/nagios/libexec/check_ping -H host"); - printf (" %s\n", _("Run check_ping and invert result. Must use full path to plugin")); - printf (" %s\n", "negate -w OK -c UNKNOWN /usr/local/nagios/libexec/check_procs -a 'vi negate.c'"); - printf (" %s\n", _("This will return OK instead of WARNING and UNKNOWN instead of CRITICAL")); - printf ("\n"); - printf ("%s\n", _("Notes:")); - printf (" %s\n", _("This plugin is a wrapper to take the output of another plugin and invert it.")); - printf (" %s\n", _("The full path of the plugin must be provided.")); - printf (" %s\n", _("If the wrapped plugin returns OK, the wrapper will return CRITICAL.")); - printf (" %s\n", _("If the wrapped plugin returns CRITICAL, the wrapper will return OK.")); - printf (" %s\n", _("Otherwise, the output state of the wrapped plugin is unchanged.")); - printf ("\n"); - printf (" %s\n", _("Using timeout-result, it is possible to override the timeout behaviour or a")); - printf (" %s\n", _("plugin by setting the negate timeout a bit lower.")); - - printf (UT_SUPPORT); + printf("\n"); + printf("%s\n", _("Examples:")); + printf(" %s\n", "negate /usr/local/nagios/libexec/check_ping -H host"); + printf(" %s\n", _("Run check_ping and invert result. Must use full path to plugin")); + printf(" %s\n", "negate -w OK -c UNKNOWN /usr/local/nagios/libexec/check_procs -a 'vi negate.c'"); + printf(" %s\n", _("This will return OK instead of WARNING and UNKNOWN instead of CRITICAL")); + printf("\n"); + printf("%s\n", _("Notes:")); + printf(" %s\n", _("This plugin is a wrapper to take the output of another plugin and invert it.")); + printf(" %s\n", _("The full path of the plugin must be provided.")); + printf(" %s\n", _("If the wrapped plugin returns OK, the wrapper will return CRITICAL.")); + printf(" %s\n", _("If the wrapped plugin returns CRITICAL, the wrapper will return OK.")); + printf(" %s\n", _("Otherwise, the output state of the wrapped plugin is unchanged.")); + printf("\n"); + printf(" %s\n", _("Using timeout-result, it is possible to override the timeout behaviour or a")); + printf(" %s\n", _("plugin by setting the negate timeout a bit lower.")); + + printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s [-t timeout] [-Towcu STATE] [-s] \n", progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s [-t timeout] [-Towcu STATE] [-s] \n", progname); } -- cgit v0.10-9-g596f From 733d7257191cfe5b77d6374257a1435ec14fd625 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:18:24 +0100 Subject: negate: update copyright diff --git a/plugins/negate.c b/plugins/negate.c index ee497cd..e8f7c01 100644 --- a/plugins/negate.c +++ b/plugins/negate.c @@ -3,7 +3,7 @@ * Monitoring negate plugin * * License: GPL - * Copyright (c) 2002-2008 Monitoring Plugins Development Team + * Copyright (c) 2002-2024 Monitoring Plugins Development Team * * Description: * @@ -30,7 +30,7 @@ *****************************************************************************/ const char *progname = "negate"; -const char *copyright = "2002-2008"; +const char *copyright = "2002-2024"; const char *email = "devel@monitoring-plugins.org"; #define DEFAULT_TIMEOUT 11 -- cgit v0.10-9-g596f From ab5a037d66b970fd4c7d7bb67495c38e38664da0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:19:05 +0100 Subject: negate: do not export local variables diff --git a/plugins/negate.c b/plugins/negate.c index e8f7c01..82a5548 100644 --- a/plugins/negate.c +++ b/plugins/negate.c @@ -44,10 +44,10 @@ const char *email = "devel@monitoring-plugins.org"; /* char *command_line; */ static const char **process_arguments(int, char **); -void validate_arguments(char **); -void print_help(void); +static void validate_arguments(char **); +static void print_help(void); void print_usage(void); -bool subst_text = false; +static bool subst_text = false; static int state[4] = { STATE_OK, -- cgit v0.10-9-g596f From c6e09500c82fccec09527ec375f314cf24fdef8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:21:55 +0100 Subject: negate: style + linter fixes diff --git a/plugins/negate.c b/plugins/negate.c index 82a5548..7e52fe6 100644 --- a/plugins/negate.c +++ b/plugins/negate.c @@ -41,10 +41,8 @@ const char *email = "devel@monitoring-plugins.org"; #include -/* char *command_line; */ - -static const char **process_arguments(int, char **); -static void validate_arguments(char **); +static const char **process_arguments(int /*argc*/, char ** /*argv*/); +static void validate_arguments(char ** /*command_line*/); static void print_help(void); void print_usage(void); static bool subst_text = false; @@ -57,18 +55,13 @@ static int state[4] = { }; int main(int argc, char **argv) { - int result = STATE_UNKNOWN; - char *sub; - char **command_line; - output chld_out, chld_err; - setlocale(LC_ALL, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); timeout_interval = DEFAULT_TIMEOUT; - command_line = (char **)process_arguments(argc, argv); + char **command_line = (char **)process_arguments(argc, argv); /* Set signal handling and alarm */ if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR) @@ -76,6 +69,10 @@ int main(int argc, char **argv) { (void)alarm((unsigned)timeout_interval); + int result = STATE_UNKNOWN; + output chld_out; + output chld_err; + /* catch when the command is quoted */ if (command_line[1] == NULL) { result = cmd_run(command_line[0], &chld_out, &chld_err, 0); @@ -92,6 +89,7 @@ int main(int argc, char **argv) { if (chld_out.lines == 0) die(max_state_alt(result, STATE_UNKNOWN), _("No data returned from command\n")); + char *sub; for (size_t i = 0; i < chld_out.lines; i++) { if (subst_text && result >= 0 && result <= 4 && result != state[result]) { /* Loop over each match found */ @@ -115,23 +113,21 @@ int main(int argc, char **argv) { /* process command-line arguments */ static const char **process_arguments(int argc, char **argv) { - int c; - bool permute = true; - - int option = 0; static struct option longopts[] = {{"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'}, {"timeout", required_argument, 0, 't'}, {"timeout-result", required_argument, 0, 'T'}, {"ok", required_argument, 0, 'o'}, {"warning", required_argument, 0, 'w'}, {"critical", required_argument, 0, 'c'}, {"unknown", required_argument, 0, 'u'}, {"substitute", no_argument, 0, 's'}, {0, 0, 0, 0}}; - while (1) { - c = getopt_long(argc, argv, "+hVt:T:o:w:c:u:s", longopts, &option); + bool permute = true; + while (true) { + int option = 0; + int option_char = getopt_long(argc, argv, "+hVt:T:o:w:c:u:s", longopts, &option); - if (c == -1 || c == EOF) + if (option_char == -1 || option_char == EOF) break; - switch (c) { + switch (option_char) { case '?': /* help */ usage5(); break; -- cgit v0.10-9-g596f From f0f767f8caf481ab575ed089b715c3963b0e6e12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:22:25 +0100 Subject: popen.c: clang-format diff --git a/plugins/popen.c b/plugins/popen.c index 54e63bc..32c9ea4 100644 --- a/plugins/popen.c +++ b/plugins/popen.c @@ -1,42 +1,42 @@ /***************************************************************************** -* -* Monitoring Plugins popen -* -* License: GPL -* Copyright (c) 2005-2007 Monitoring Plugins Development Team -* -* Description: -* -* A safe alternative to popen -* -* Provides spopen and spclose -* -* FILE * spopen(const char *); -* int spclose(FILE *); -* -* Code taken with little modification from "Advanced Programming for the Unix -* Environment" by W. Richard Stevens -* -* This is considered safe in that no shell is spawned, and the environment -* and path passed to the exec'd program are essentially empty. (popen create -* a shell and passes the environment to it). -* -* -* 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 Plugins popen + * + * License: GPL + * Copyright (c) 2005-2007 Monitoring Plugins Development Team + * + * Description: + * + * A safe alternative to popen + * + * Provides spopen and spclose + * + * FILE * spopen(const char *); + * int spclose(FILE *); + * + * Code taken with little modification from "Advanced Programming for the Unix + * Environment" by W. Richard Stevens + * + * This is considered safe in that no shell is spawned, and the environment + * and path passed to the exec'd program are essentially empty. (popen create + * a shell and passes the environment to it). + * + * + * 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 . + * + * + *****************************************************************************/ #include "./common.h" #include "./utils.h" @@ -47,46 +47,43 @@ extern pid_t *childpid; extern int *child_stderr_array; extern FILE *child_process; -FILE *spopen (const char *); -int spclose (FILE *); +FILE *spopen(const char *); +int spclose(FILE *); #ifdef REDHAT_SPOPEN_ERROR -void popen_sigchld_handler (int); +void popen_sigchld_handler(int); #endif -void popen_timeout_alarm_handler (int); +void popen_timeout_alarm_handler(int); -#include /* ANSI C header file */ +#include /* ANSI C header file */ #include #include #include #ifdef HAVE_SYS_WAIT_H -#include +# include #endif #ifndef WEXITSTATUS -# define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8) +# define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8) #endif #ifndef WIFEXITED -# define WIFEXITED(stat_val) (((stat_val) & 255) == 0) +# define WIFEXITED(stat_val) (((stat_val)&255) == 0) #endif /* 4.3BSD Reno doesn't define SIG_ERR */ #if defined(SIG_IGN) && !defined(SIG_ERR) -#define SIG_ERR ((Sigfunc *)-1) +# define SIG_ERR ((Sigfunc *)-1) #endif - -char *pname = NULL; /* caller can set this from argv[0] */ +char *pname = NULL; /* caller can set this from argv[0] */ #ifdef REDHAT_SPOPEN_ERROR static volatile int childtermd = 0; #endif -FILE * -spopen (const char *cmdstring) -{ +FILE *spopen(const char *cmdstring) { char *env[2]; char *cmd = NULL; char **argv = NULL; @@ -96,12 +93,12 @@ spopen (const char *cmdstring) int i = 0, pfd[2], pfderr[2]; pid_t pid; -#ifdef RLIMIT_CORE +#ifdef RLIMIT_CORE /* do not leave core files */ struct rlimit limit; - getrlimit (RLIMIT_CORE, &limit); + getrlimit(RLIMIT_CORE, &limit); limit.rlim_cur = 0; - setrlimit (RLIMIT_CORE, &limit); + setrlimit(RLIMIT_CORE, &limit); #endif env[0] = strdup("LC_ALL=C"); @@ -113,182 +110,173 @@ spopen (const char *cmdstring) /* make copy of command string so strtok() doesn't silently modify it */ /* (the calling program may want to access it later) */ - cmd = malloc (strlen (cmdstring) + 1); + cmd = malloc(strlen(cmdstring) + 1); if (cmd == NULL) return NULL; - strcpy (cmd, cmdstring); + strcpy(cmd, cmdstring); /* This is not a shell, so we don't handle "???" */ - if (strstr (cmdstring, "\"")) + if (strstr(cmdstring, "\"")) return NULL; /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */ - if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''")) + if (strstr(cmdstring, " ' ") || strstr(cmdstring, "'''")) return NULL; /* there cannot be more args than characters */ - argc = strlen (cmdstring) + 1; /* add 1 for NULL termination */ - argv = malloc (sizeof(char*)*argc); + argc = strlen(cmdstring) + 1; /* add 1 for NULL termination */ + argv = malloc(sizeof(char *) * argc); if (argv == NULL) { - printf ("%s\n", _("Could not malloc argv array in popen()")); + printf("%s\n", _("Could not malloc argv array in popen()")); return NULL; } /* loop to get arguments to command */ while (cmd) { str = cmd; - str += strspn (str, " \t\r\n"); /* trim any leading whitespace */ + str += strspn(str, " \t\r\n"); /* trim any leading whitespace */ if (i >= argc - 2) { - printf ("%s\n",_("CRITICAL - You need more args!!!")); + printf("%s\n", _("CRITICAL - You need more args!!!")); return (NULL); } - if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */ + if (strstr(str, "'") == str) { /* handle SIMPLE quoted strings */ str++; - if (!strstr (str, "'")) - return NULL; /* balanced? */ - cmd = 1 + strstr (str, "'"); - str[strcspn (str, "'")] = 0; - } - else if (strcspn(str,"'") < strcspn (str, " \t\r\n")) { - /* handle --option='foo bar' strings */ + if (!strstr(str, "'")) + return NULL; /* balanced? */ + cmd = 1 + strstr(str, "'"); + str[strcspn(str, "'")] = 0; + } else if (strcspn(str, "'") < strcspn(str, " \t\r\n")) { + /* handle --option='foo bar' strings */ tmp = str + strcspn(str, "'") + 1; - if (!strstr (tmp, "'")) - return NULL; /* balanced? */ - tmp += strcspn(tmp,"'") + 1; + if (!strstr(tmp, "'")) + return NULL; /* balanced? */ + tmp += strcspn(tmp, "'") + 1; *tmp = 0; cmd = tmp + 1; } else { - if (strpbrk (str, " \t\r\n")) { - cmd = 1 + strpbrk (str, " \t\r\n"); - str[strcspn (str, " \t\r\n")] = 0; - } - else { + if (strpbrk(str, " \t\r\n")) { + cmd = 1 + strpbrk(str, " \t\r\n"); + str[strcspn(str, " \t\r\n")] = 0; + } else { cmd = NULL; } } - if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n")) + if (cmd && strlen(cmd) == strspn(cmd, " \t\r\n")) cmd = NULL; argv[i++] = str; - } argv[i] = NULL; long maxfd = mp_open_max(); - if (childpid == NULL) { /* first time through */ - if ((childpid = calloc ((size_t)maxfd, sizeof (pid_t))) == NULL) + if (childpid == NULL) { /* first time through */ + if ((childpid = calloc((size_t)maxfd, sizeof(pid_t))) == NULL) return (NULL); } - if (child_stderr_array == NULL) { /* first time through */ - if ((child_stderr_array = calloc ((size_t)maxfd, sizeof (int))) == NULL) + if (child_stderr_array == NULL) { /* first time through */ + if ((child_stderr_array = calloc((size_t)maxfd, sizeof(int))) == NULL) return (NULL); } - if (pipe (pfd) < 0) - return (NULL); /* errno set by pipe() */ + if (pipe(pfd) < 0) + return (NULL); /* errno set by pipe() */ - if (pipe (pfderr) < 0) - return (NULL); /* errno set by pipe() */ + if (pipe(pfderr) < 0) + return (NULL); /* errno set by pipe() */ #ifdef REDHAT_SPOPEN_ERROR - if (signal (SIGCHLD, popen_sigchld_handler) == SIG_ERR) { - usage4 (_("Cannot catch SIGCHLD")); + if (signal(SIGCHLD, popen_sigchld_handler) == SIG_ERR) { + usage4(_("Cannot catch SIGCHLD")); } #endif - if ((pid = fork ()) < 0) - return (NULL); /* errno set by fork() */ - else if (pid == 0) { /* child */ - close (pfd[0]); + if ((pid = fork()) < 0) + return (NULL); /* errno set by fork() */ + else if (pid == 0) { /* child */ + close(pfd[0]); if (pfd[1] != STDOUT_FILENO) { - dup2 (pfd[1], STDOUT_FILENO); - close (pfd[1]); + dup2(pfd[1], STDOUT_FILENO); + close(pfd[1]); } - close (pfderr[0]); + close(pfderr[0]); if (pfderr[1] != STDERR_FILENO) { - dup2 (pfderr[1], STDERR_FILENO); - close (pfderr[1]); + dup2(pfderr[1], STDERR_FILENO); + close(pfderr[1]); } /* close all descriptors in childpid[] */ for (i = 0; i < maxfd; i++) if (childpid[i] > 0) - close (i); + close(i); - execve (argv[0], argv, env); - _exit (0); + execve(argv[0], argv, env); + _exit(0); } - close (pfd[1]); /* parent */ - if ((child_process = fdopen (pfd[0], "r")) == NULL) + close(pfd[1]); /* parent */ + if ((child_process = fdopen(pfd[0], "r")) == NULL) return (NULL); - close (pfderr[1]); + close(pfderr[1]); - childpid[fileno (child_process)] = pid; /* remember child pid for this fd */ - child_stderr_array[fileno (child_process)] = pfderr[0]; /* remember STDERR */ + childpid[fileno(child_process)] = pid; /* remember child pid for this fd */ + child_stderr_array[fileno(child_process)] = pfderr[0]; /* remember STDERR */ return (child_process); } -int -spclose (FILE * fp) -{ +int spclose(FILE *fp) { int fd, status; pid_t pid; if (childpid == NULL) - return (1); /* popen() has never been called */ + return (1); /* popen() has never been called */ - fd = fileno (fp); + fd = fileno(fp); if ((pid = childpid[fd]) == 0) - return (1); /* fp wasn't opened by popen() */ + return (1); /* fp wasn't opened by popen() */ childpid[fd] = 0; - if (fclose (fp) == EOF) + if (fclose(fp) == EOF) return (1); #ifdef REDHAT_SPOPEN_ERROR - while (!childtermd); /* wait until SIGCHLD */ + while (!childtermd) + ; /* wait until SIGCHLD */ #endif - while (waitpid (pid, &status, 0) < 0) + while (waitpid(pid, &status, 0) < 0) if (errno != EINTR) - return (1); /* error other than EINTR from waitpid() */ + return (1); /* error other than EINTR from waitpid() */ - if (WIFEXITED (status)) - return (WEXITSTATUS (status)); /* return child's termination status */ + if (WIFEXITED(status)) + return (WEXITSTATUS(status)); /* return child's termination status */ return (1); } #ifdef REDHAT_SPOPEN_ERROR -void -popen_sigchld_handler (int signo) -{ +void popen_sigchld_handler(int signo) { if (signo == SIGCHLD) childtermd = 1; } #endif -void -popen_timeout_alarm_handler (int signo) -{ +void popen_timeout_alarm_handler(int signo) { int fh; if (signo == SIGALRM) { if (child_process != NULL) { - fh=fileno (child_process); - if(fh >= 0){ - kill (childpid[fh], SIGKILL); + fh = fileno(child_process); + if (fh >= 0) { + kill(childpid[fh], SIGKILL); } - printf (_("CRITICAL - Plugin timed out after %d seconds\n"), - timeout_interval); + printf(_("CRITICAL - Plugin timed out after %d seconds\n"), timeout_interval); } else { - printf ("%s\n", _("CRITICAL - popen timeout received, but no child process")); + printf("%s\n", _("CRITICAL - popen timeout received, but no child process")); } - exit (STATE_CRITICAL); + exit(STATE_CRITICAL); } } -- cgit v0.10-9-g596f From baa2208a1daa3bf12c6bd7f9bc3646fcff36121f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:23:05 +0100 Subject: popen.c: update copyright diff --git a/plugins/popen.c b/plugins/popen.c index 32c9ea4..7aa18bf 100644 --- a/plugins/popen.c +++ b/plugins/popen.c @@ -3,7 +3,7 @@ * Monitoring Plugins popen * * License: GPL - * Copyright (c) 2005-2007 Monitoring Plugins Development Team + * Copyright (c) 2005-2024 Monitoring Plugins Development Team * * Description: * -- cgit v0.10-9-g596f From fc90673afcdc6e4107161391d9ad62d40d4b558f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:27:16 +0100 Subject: popen.c: style + linter fixes diff --git a/plugins/popen.c b/plugins/popen.c index 7aa18bf..2b9824b 100644 --- a/plugins/popen.c +++ b/plugins/popen.c @@ -47,12 +47,12 @@ extern pid_t *childpid; extern int *child_stderr_array; extern FILE *child_process; -FILE *spopen(const char *); -int spclose(FILE *); +FILE *spopen(const char * /*cmdstring*/); +int spclose(FILE * /*fp*/); #ifdef REDHAT_SPOPEN_ERROR void popen_sigchld_handler(int); #endif -void popen_timeout_alarm_handler(int); +void popen_timeout_alarm_handler(int /*signo*/); #include /* ANSI C header file */ #include @@ -84,15 +84,6 @@ static volatile int childtermd = 0; #endif FILE *spopen(const char *cmdstring) { - char *env[2]; - char *cmd = NULL; - char **argv = NULL; - char *str, *tmp; - int argc; - - int i = 0, pfd[2], pfderr[2]; - pid_t pid; - #ifdef RLIMIT_CORE /* do not leave core files */ struct rlimit limit; @@ -101,6 +92,7 @@ FILE *spopen(const char *cmdstring) { setrlimit(RLIMIT_CORE, &limit); #endif + char *env[2]; env[0] = strdup("LC_ALL=C"); env[1] = NULL; @@ -108,6 +100,7 @@ FILE *spopen(const char *cmdstring) { if (cmdstring == NULL) return (NULL); + char *cmd = NULL; /* make copy of command string so strtok() doesn't silently modify it */ /* (the calling program may want to access it later) */ cmd = malloc(strlen(cmdstring) + 1); @@ -123,6 +116,8 @@ FILE *spopen(const char *cmdstring) { if (strstr(cmdstring, " ' ") || strstr(cmdstring, "'''")) return NULL; + int argc; + char **argv = NULL; /* there cannot be more args than characters */ argc = strlen(cmdstring) + 1; /* add 1 for NULL termination */ argv = malloc(sizeof(char *) * argc); @@ -132,6 +127,8 @@ FILE *spopen(const char *cmdstring) { return NULL; } + int i = 0; + char *str; /* loop to get arguments to command */ while (cmd) { str = cmd; @@ -150,7 +147,7 @@ FILE *spopen(const char *cmdstring) { str[strcspn(str, "'")] = 0; } else if (strcspn(str, "'") < strcspn(str, " \t\r\n")) { /* handle --option='foo bar' strings */ - tmp = str + strcspn(str, "'") + 1; + char *tmp = str + strcspn(str, "'") + 1; if (!strstr(tmp, "'")) return NULL; /* balanced? */ tmp += strcspn(tmp, "'") + 1; @@ -184,9 +181,11 @@ FILE *spopen(const char *cmdstring) { return (NULL); } + int pfd[2]; if (pipe(pfd) < 0) return (NULL); /* errno set by pipe() */ + int pfderr[2]; if (pipe(pfderr) < 0) return (NULL); /* errno set by pipe() */ @@ -196,9 +195,11 @@ FILE *spopen(const char *cmdstring) { } #endif + pid_t pid; if ((pid = fork()) < 0) - return (NULL); /* errno set by fork() */ - else if (pid == 0) { /* child */ + return (NULL); /* errno set by fork() */ + + if (pid == 0) { /* child */ close(pfd[0]); if (pfd[1] != STDOUT_FILENO) { dup2(pfd[1], STDOUT_FILENO); @@ -229,13 +230,11 @@ FILE *spopen(const char *cmdstring) { } int spclose(FILE *fp) { - int fd, status; - pid_t pid; - if (childpid == NULL) return (1); /* popen() has never been called */ - fd = fileno(fp); + pid_t pid; + int fd = fileno(fp); if ((pid = childpid[fd]) == 0) return (1); /* fp wasn't opened by popen() */ @@ -248,6 +247,7 @@ int spclose(FILE *fp) { ; /* wait until SIGCHLD */ #endif + int status; while (waitpid(pid, &status, 0) < 0) if (errno != EINTR) return (1); /* error other than EINTR from waitpid() */ @@ -266,10 +266,9 @@ void popen_sigchld_handler(int signo) { #endif void popen_timeout_alarm_handler(int signo) { - int fh; if (signo == SIGALRM) { if (child_process != NULL) { - fh = fileno(child_process); + int fh = fileno(child_process); if (fh >= 0) { kill(childpid[fh], SIGKILL); } -- cgit v0.10-9-g596f From c7691ddf4be137e262521f83f9efb4888190c623 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:28:12 +0100 Subject: picohttpparser: clang-format diff --git a/plugins/picohttpparser/picohttpparser.c b/plugins/picohttpparser/picohttpparser.c index d0bfac6..2ae92d6 100644 --- a/plugins/picohttpparser/picohttpparser.c +++ b/plugins/picohttpparser/picohttpparser.c @@ -28,623 +28,610 @@ #include #include #ifdef __SSE4_2__ -#ifdef _MSC_VER -#include -#else -#include -#endif +# ifdef _MSC_VER +# include +# else +# include +# endif #endif #include "picohttpparser.h" #if __GNUC__ >= 3 -#define likely(x) __builtin_expect(!!(x), 1) -#define unlikely(x) __builtin_expect(!!(x), 0) +# define likely(x) __builtin_expect(!!(x), 1) +# define unlikely(x) __builtin_expect(!!(x), 0) #else -#define likely(x) (x) -#define unlikely(x) (x) +# define likely(x) (x) +# define unlikely(x) (x) #endif #ifdef _MSC_VER -#define ALIGNED(n) _declspec(align(n)) +# define ALIGNED(n) _declspec(align(n)) #else -#define ALIGNED(n) __attribute__((aligned(n))) +# define ALIGNED(n) __attribute__((aligned(n))) #endif #define IS_PRINTABLE_ASCII(c) ((unsigned char)(c)-040u < 0137u) -#define CHECK_EOF() \ - if (buf == buf_end) { \ - *ret = -2; \ - return NULL; \ - } - -#define EXPECT_CHAR_NO_CHECK(ch) \ - if (*buf++ != ch) { \ - *ret = -1; \ - return NULL; \ - } - -#define EXPECT_CHAR(ch) \ - CHECK_EOF(); \ - EXPECT_CHAR_NO_CHECK(ch); - -#define ADVANCE_TOKEN(tok, toklen) \ - do { \ - const char *tok_start = buf; \ - static const char ALIGNED(16) ranges2[16] = "\000\040\177\177"; \ - int found2; \ - buf = findchar_fast(buf, buf_end, ranges2, 4, &found2); \ - if (!found2) { \ - CHECK_EOF(); \ - } \ - while (1) { \ - if (*buf == ' ') { \ - break; \ - } else if (unlikely(!IS_PRINTABLE_ASCII(*buf))) { \ - if ((unsigned char)*buf < '\040' || *buf == '\177') { \ - *ret = -1; \ - return NULL; \ - } \ - } \ - ++buf; \ - CHECK_EOF(); \ - } \ - tok = tok_start; \ - toklen = buf - tok_start; \ - } while (0) +#define CHECK_EOF() \ + if (buf == buf_end) { \ + *ret = -2; \ + return NULL; \ + } + +#define EXPECT_CHAR_NO_CHECK(ch) \ + if (*buf++ != ch) { \ + *ret = -1; \ + return NULL; \ + } + +#define EXPECT_CHAR(ch) \ + CHECK_EOF(); \ + EXPECT_CHAR_NO_CHECK(ch); + +#define ADVANCE_TOKEN(tok, toklen) \ + do { \ + const char *tok_start = buf; \ + static const char ALIGNED(16) ranges2[16] = "\000\040\177\177"; \ + int found2; \ + buf = findchar_fast(buf, buf_end, ranges2, 4, &found2); \ + if (!found2) { \ + CHECK_EOF(); \ + } \ + while (1) { \ + if (*buf == ' ') { \ + break; \ + } else if (unlikely(!IS_PRINTABLE_ASCII(*buf))) { \ + if ((unsigned char)*buf < '\040' || *buf == '\177') { \ + *ret = -1; \ + return NULL; \ + } \ + } \ + ++buf; \ + CHECK_EOF(); \ + } \ + tok = tok_start; \ + toklen = buf - tok_start; \ + } while (0) static const char *token_char_map = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" - "\0\1\0\1\1\1\1\1\0\0\1\1\0\1\1\0\1\1\1\1\1\1\1\1\1\1\0\0\0\0\0\0" - "\0\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\0\0\1\1" - "\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\1\0\1\0" - "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" - "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" - "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" - "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; - -static const char *findchar_fast(const char *buf, const char *buf_end, const char *ranges, size_t ranges_size, int *found) -{ - *found = 0; + "\0\1\0\1\1\1\1\1\0\0\1\1\0\1\1\0\1\1\1\1\1\1\1\1\1\1\0\0\0\0\0\0" + "\0\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\0\0\1\1" + "\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\1\0\1\0" + "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" + "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" + "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" + "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; + +static const char *findchar_fast(const char *buf, const char *buf_end, const char *ranges, size_t ranges_size, int *found) { + *found = 0; #if __SSE4_2__ - if (likely(buf_end - buf >= 16)) { - __m128i ranges16 = _mm_loadu_si128((const __m128i *)ranges); - - size_t left = (buf_end - buf) & ~15; - do { - __m128i b16 = _mm_loadu_si128((const __m128i *)buf); - int r = _mm_cmpestri(ranges16, ranges_size, b16, 16, _SIDD_LEAST_SIGNIFICANT | _SIDD_CMP_RANGES | _SIDD_UBYTE_OPS); - if (unlikely(r != 16)) { - buf += r; - *found = 1; - break; - } - buf += 16; - left -= 16; - } while (likely(left != 0)); - } + if (likely(buf_end - buf >= 16)) { + __m128i ranges16 = _mm_loadu_si128((const __m128i *)ranges); + + size_t left = (buf_end - buf) & ~15; + do { + __m128i b16 = _mm_loadu_si128((const __m128i *)buf); + int r = _mm_cmpestri(ranges16, ranges_size, b16, 16, _SIDD_LEAST_SIGNIFICANT | _SIDD_CMP_RANGES | _SIDD_UBYTE_OPS); + if (unlikely(r != 16)) { + buf += r; + *found = 1; + break; + } + buf += 16; + left -= 16; + } while (likely(left != 0)); + } #else - /* suppress unused parameter warning */ - (void)buf_end; - (void)ranges; - (void)ranges_size; + /* suppress unused parameter warning */ + (void)buf_end; + (void)ranges; + (void)ranges_size; #endif - return buf; + return buf; } -static const char *get_token_to_eol(const char *buf, const char *buf_end, const char **token, size_t *token_len, int *ret) -{ - const char *token_start = buf; +static const char *get_token_to_eol(const char *buf, const char *buf_end, const char **token, size_t *token_len, int *ret) { + const char *token_start = buf; #ifdef __SSE4_2__ - static const char ALIGNED(16) ranges1[16] = "\0\010" /* allow HT */ - "\012\037" /* allow SP and up to but not including DEL */ - "\177\177"; /* allow chars w. MSB set */ - int found; - buf = findchar_fast(buf, buf_end, ranges1, 6, &found); - if (found) - goto FOUND_CTL; + static const char ALIGNED(16) ranges1[16] = "\0\010" /* allow HT */ + "\012\037" /* allow SP and up to but not including DEL */ + "\177\177"; /* allow chars w. MSB set */ + int found; + buf = findchar_fast(buf, buf_end, ranges1, 6, &found); + if (found) + goto FOUND_CTL; #else - /* find non-printable char within the next 8 bytes, this is the hottest code; manually inlined */ - while (likely(buf_end - buf >= 8)) { -#define DOIT() \ - do { \ - if (unlikely(!IS_PRINTABLE_ASCII(*buf))) \ - goto NonPrintable; \ - ++buf; \ - } while (0) - DOIT(); - DOIT(); - DOIT(); - DOIT(); - DOIT(); - DOIT(); - DOIT(); - DOIT(); -#undef DOIT - continue; - NonPrintable: - if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) || unlikely(*buf == '\177')) { - goto FOUND_CTL; - } - ++buf; - } + /* find non-printable char within the next 8 bytes, this is the hottest code; manually inlined */ + while (likely(buf_end - buf >= 8)) { +# define DOIT() \ + do { \ + if (unlikely(!IS_PRINTABLE_ASCII(*buf))) \ + goto NonPrintable; \ + ++buf; \ + } while (0) + DOIT(); + DOIT(); + DOIT(); + DOIT(); + DOIT(); + DOIT(); + DOIT(); + DOIT(); +# undef DOIT + continue; + NonPrintable: + if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) || unlikely(*buf == '\177')) { + goto FOUND_CTL; + } + ++buf; + } #endif - for (;; ++buf) { - CHECK_EOF(); - if (unlikely(!IS_PRINTABLE_ASCII(*buf))) { - if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) || unlikely(*buf == '\177')) { - goto FOUND_CTL; - } - } - } + for (;; ++buf) { + CHECK_EOF(); + if (unlikely(!IS_PRINTABLE_ASCII(*buf))) { + if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) || unlikely(*buf == '\177')) { + goto FOUND_CTL; + } + } + } FOUND_CTL: - if (likely(*buf == '\015')) { - ++buf; - EXPECT_CHAR('\012'); - *token_len = buf - 2 - token_start; - } else if (*buf == '\012') { - *token_len = buf - token_start; - ++buf; - } else { - *ret = -1; - return NULL; - } - *token = token_start; - - return buf; + if (likely(*buf == '\015')) { + ++buf; + EXPECT_CHAR('\012'); + *token_len = buf - 2 - token_start; + } else if (*buf == '\012') { + *token_len = buf - token_start; + ++buf; + } else { + *ret = -1; + return NULL; + } + *token = token_start; + + return buf; } -static const char *is_complete(const char *buf, const char *buf_end, size_t last_len, int *ret) -{ - int ret_cnt = 0; - buf = last_len < 3 ? buf : buf + last_len - 3; - - while (1) { - CHECK_EOF(); - if (*buf == '\015') { - ++buf; - CHECK_EOF(); - EXPECT_CHAR('\012'); - ++ret_cnt; - } else if (*buf == '\012') { - ++buf; - ++ret_cnt; - } else { - ++buf; - ret_cnt = 0; - } - if (ret_cnt == 2) { - return buf; - } - } - - *ret = -2; - return NULL; +static const char *is_complete(const char *buf, const char *buf_end, size_t last_len, int *ret) { + int ret_cnt = 0; + buf = last_len < 3 ? buf : buf + last_len - 3; + + while (1) { + CHECK_EOF(); + if (*buf == '\015') { + ++buf; + CHECK_EOF(); + EXPECT_CHAR('\012'); + ++ret_cnt; + } else if (*buf == '\012') { + ++buf; + ++ret_cnt; + } else { + ++buf; + ret_cnt = 0; + } + if (ret_cnt == 2) { + return buf; + } + } + + *ret = -2; + return NULL; } -#define PARSE_INT(valp_, mul_) \ - if (*buf < '0' || '9' < *buf) { \ - buf++; \ - *ret = -1; \ - return NULL; \ - } \ - *(valp_) = (mul_) * (*buf++ - '0'); - -#define PARSE_INT_3(valp_) \ - do { \ - int res_ = 0; \ - PARSE_INT(&res_, 100) \ - *valp_ = res_; \ - PARSE_INT(&res_, 10) \ - *valp_ += res_; \ - PARSE_INT(&res_, 1) \ - *valp_ += res_; \ - } while (0) +#define PARSE_INT(valp_, mul_) \ + if (*buf < '0' || '9' < *buf) { \ + buf++; \ + *ret = -1; \ + return NULL; \ + } \ + *(valp_) = (mul_) * (*buf++ - '0'); + +#define PARSE_INT_3(valp_) \ + do { \ + int res_ = 0; \ + PARSE_INT(&res_, 100) \ + *valp_ = res_; \ + PARSE_INT(&res_, 10) \ + *valp_ += res_; \ + PARSE_INT(&res_, 1) \ + *valp_ += res_; \ + } while (0) /* returned pointer is always within [buf, buf_end), or null */ -static const char *parse_http_version(const char *buf, const char *buf_end, int *major_version, int *minor_version, int *ret) -{ - /* we want at least [HTTP/1.] to try to parse */ - if (buf_end - buf < 9) { - *ret = -2; - return NULL; - } - EXPECT_CHAR_NO_CHECK('H'); - EXPECT_CHAR_NO_CHECK('T'); - EXPECT_CHAR_NO_CHECK('T'); - EXPECT_CHAR_NO_CHECK('P'); - EXPECT_CHAR_NO_CHECK('/'); - PARSE_INT(major_version, 1); - if (*major_version == 1) { - EXPECT_CHAR_NO_CHECK('.'); - PARSE_INT(minor_version, 1); - } else { - *minor_version = 0; - } - return buf; +static const char *parse_http_version(const char *buf, const char *buf_end, int *major_version, int *minor_version, int *ret) { + /* we want at least [HTTP/1.] to try to parse */ + if (buf_end - buf < 9) { + *ret = -2; + return NULL; + } + EXPECT_CHAR_NO_CHECK('H'); + EXPECT_CHAR_NO_CHECK('T'); + EXPECT_CHAR_NO_CHECK('T'); + EXPECT_CHAR_NO_CHECK('P'); + EXPECT_CHAR_NO_CHECK('/'); + PARSE_INT(major_version, 1); + if (*major_version == 1) { + EXPECT_CHAR_NO_CHECK('.'); + PARSE_INT(minor_version, 1); + } else { + *minor_version = 0; + } + return buf; } -static const char *parse_headers(const char *buf, const char *buf_end, struct phr_header *headers, size_t *num_headers, - size_t max_headers, int *ret) -{ - for (;; ++*num_headers) { - CHECK_EOF(); - if (*buf == '\015') { - ++buf; - EXPECT_CHAR('\012'); - break; - } else if (*buf == '\012') { - ++buf; - break; - } - if (*num_headers == max_headers) { - *ret = -1; - return NULL; - } - if (!(*num_headers != 0 && (*buf == ' ' || *buf == '\t'))) { - /* parsing name, but do not discard SP before colon, see - * http://www.mozilla.org/security/announce/2006/mfsa2006-33.html */ - headers[*num_headers].name = buf; - static const char ALIGNED(16) ranges1[] = "\x00 " /* control chars and up to SP */ - "\"\"" /* 0x22 */ - "()" /* 0x28,0x29 */ - ",," /* 0x2c */ - "//" /* 0x2f */ - ":@" /* 0x3a-0x40 */ - "[]" /* 0x5b-0x5d */ - "{\377"; /* 0x7b-0xff */ - int found; - buf = findchar_fast(buf, buf_end, ranges1, sizeof(ranges1) - 1, &found); - if (!found) { - CHECK_EOF(); - } - while (1) { - if (*buf == ':') { - break; - } else if (!token_char_map[(unsigned char)*buf]) { - *ret = -1; - return NULL; - } - ++buf; - CHECK_EOF(); - } - if ((headers[*num_headers].name_len = buf - headers[*num_headers].name) == 0) { - *ret = -1; - return NULL; - } - ++buf; - for (;; ++buf) { - CHECK_EOF(); - if (!(*buf == ' ' || *buf == '\t')) { - break; - } - } - } else { - headers[*num_headers].name = NULL; - headers[*num_headers].name_len = 0; - } - const char *value; - size_t value_len; - if ((buf = get_token_to_eol(buf, buf_end, &value, &value_len, ret)) == NULL) { - return NULL; - } - /* remove trailing SPs and HTABs */ - const char *value_end = value + value_len; - for (; value_end != value; --value_end) { - const char c = *(value_end - 1); - if (!(c == ' ' || c == '\t')) { - break; - } - } - headers[*num_headers].value = value; - headers[*num_headers].value_len = value_end - value; - } - return buf; +static const char *parse_headers(const char *buf, const char *buf_end, struct phr_header *headers, size_t *num_headers, size_t max_headers, + int *ret) { + for (;; ++*num_headers) { + CHECK_EOF(); + if (*buf == '\015') { + ++buf; + EXPECT_CHAR('\012'); + break; + } else if (*buf == '\012') { + ++buf; + break; + } + if (*num_headers == max_headers) { + *ret = -1; + return NULL; + } + if (!(*num_headers != 0 && (*buf == ' ' || *buf == '\t'))) { + /* parsing name, but do not discard SP before colon, see + * http://www.mozilla.org/security/announce/2006/mfsa2006-33.html */ + headers[*num_headers].name = buf; + static const char ALIGNED(16) ranges1[] = "\x00 " /* control chars and up to SP */ + "\"\"" /* 0x22 */ + "()" /* 0x28,0x29 */ + ",," /* 0x2c */ + "//" /* 0x2f */ + ":@" /* 0x3a-0x40 */ + "[]" /* 0x5b-0x5d */ + "{\377"; /* 0x7b-0xff */ + int found; + buf = findchar_fast(buf, buf_end, ranges1, sizeof(ranges1) - 1, &found); + if (!found) { + CHECK_EOF(); + } + while (1) { + if (*buf == ':') { + break; + } else if (!token_char_map[(unsigned char)*buf]) { + *ret = -1; + return NULL; + } + ++buf; + CHECK_EOF(); + } + if ((headers[*num_headers].name_len = buf - headers[*num_headers].name) == 0) { + *ret = -1; + return NULL; + } + ++buf; + for (;; ++buf) { + CHECK_EOF(); + if (!(*buf == ' ' || *buf == '\t')) { + break; + } + } + } else { + headers[*num_headers].name = NULL; + headers[*num_headers].name_len = 0; + } + const char *value; + size_t value_len; + if ((buf = get_token_to_eol(buf, buf_end, &value, &value_len, ret)) == NULL) { + return NULL; + } + /* remove trailing SPs and HTABs */ + const char *value_end = value + value_len; + for (; value_end != value; --value_end) { + const char c = *(value_end - 1); + if (!(c == ' ' || c == '\t')) { + break; + } + } + headers[*num_headers].value = value; + headers[*num_headers].value_len = value_end - value; + } + return buf; } static const char *parse_request(const char *buf, const char *buf_end, const char **method, size_t *method_len, const char **path, - size_t *path_len, int *major_version, int *minor_version, struct phr_header *headers, size_t *num_headers, - size_t max_headers, int *ret) -{ - /* skip first empty line (some clients add CRLF after POST content) */ - CHECK_EOF(); - if (*buf == '\015') { - ++buf; - EXPECT_CHAR('\012'); - } else if (*buf == '\012') { - ++buf; - } - - /* parse request line */ - ADVANCE_TOKEN(*method, *method_len); - do { - ++buf; - } while (*buf == ' '); - ADVANCE_TOKEN(*path, *path_len); - do { - ++buf; - } while (*buf == ' '); - if (*method_len == 0 || *path_len == 0) { - *ret = -1; - return NULL; - } - if ((buf = parse_http_version(buf, buf_end, major_version, minor_version, ret)) == NULL) { - return NULL; - } - if (*buf == '\015') { - ++buf; - EXPECT_CHAR('\012'); - } else if (*buf == '\012') { - ++buf; - } else { - *ret = -1; - return NULL; - } - - return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret); + size_t *path_len, int *major_version, int *minor_version, struct phr_header *headers, size_t *num_headers, + size_t max_headers, int *ret) { + /* skip first empty line (some clients add CRLF after POST content) */ + CHECK_EOF(); + if (*buf == '\015') { + ++buf; + EXPECT_CHAR('\012'); + } else if (*buf == '\012') { + ++buf; + } + + /* parse request line */ + ADVANCE_TOKEN(*method, *method_len); + do { + ++buf; + } while (*buf == ' '); + ADVANCE_TOKEN(*path, *path_len); + do { + ++buf; + } while (*buf == ' '); + if (*method_len == 0 || *path_len == 0) { + *ret = -1; + return NULL; + } + if ((buf = parse_http_version(buf, buf_end, major_version, minor_version, ret)) == NULL) { + return NULL; + } + if (*buf == '\015') { + ++buf; + EXPECT_CHAR('\012'); + } else if (*buf == '\012') { + ++buf; + } else { + *ret = -1; + return NULL; + } + + return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret); } -int phr_parse_request(const char *buf_start, size_t len, const char **method, size_t *method_len, const char **path, - size_t *path_len, int *major_version, int *minor_version, struct phr_header *headers, size_t *num_headers, size_t last_len) -{ - const char *buf = buf_start, *buf_end = buf_start + len; - size_t max_headers = *num_headers; - int r; - - *method = NULL; - *method_len = 0; - *path = NULL; - *path_len = 0; - *major_version = -1; - *minor_version = -1; - *num_headers = 0; - - /* if last_len != 0, check if the request is complete (a fast countermeasure - against slowloris */ - if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) { - return r; - } - - if ((buf = parse_request(buf, buf_end, method, method_len, path, path_len, major_version, minor_version, headers, num_headers, max_headers, - &r)) == NULL) { - return r; - } - - return (int)(buf - buf_start); +int phr_parse_request(const char *buf_start, size_t len, const char **method, size_t *method_len, const char **path, size_t *path_len, + int *major_version, int *minor_version, struct phr_header *headers, size_t *num_headers, size_t last_len) { + const char *buf = buf_start, *buf_end = buf_start + len; + size_t max_headers = *num_headers; + int r; + + *method = NULL; + *method_len = 0; + *path = NULL; + *path_len = 0; + *major_version = -1; + *minor_version = -1; + *num_headers = 0; + + /* if last_len != 0, check if the request is complete (a fast countermeasure + against slowloris */ + if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) { + return r; + } + + if ((buf = parse_request(buf, buf_end, method, method_len, path, path_len, major_version, minor_version, headers, num_headers, + max_headers, &r)) == NULL) { + return r; + } + + return (int)(buf - buf_start); } -static const char *parse_response(const char *buf, const char *buf_end, int *major_version, int *minor_version, int *status, const char **msg, - size_t *msg_len, struct phr_header *headers, size_t *num_headers, size_t max_headers, int *ret) -{ - /* parse "HTTP/1.x" */ - if ((buf = parse_http_version(buf, buf_end, major_version, minor_version, ret)) == NULL) { - return NULL; - } - /* skip space */ - if (*buf != ' ') { - *ret = -1; - return NULL; - } - do { - ++buf; - } while (*buf == ' '); - /* parse status code, we want at least [:digit:][:digit:][:digit:] to try to parse */ - if (buf_end - buf < 4) { - *ret = -2; - return NULL; - } - PARSE_INT_3(status); - - /* get message including preceding space */ - if ((buf = get_token_to_eol(buf, buf_end, msg, msg_len, ret)) == NULL) { - return NULL; - } - if (*msg_len == 0) { - /* ok */ - } else if (**msg == ' ') { - /* remove preceding space */ - do { - ++*msg; - --*msg_len; - } while (**msg == ' '); - } else { - /* garbage found after status code */ - *ret = -1; - return NULL; - } - - return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret); +static const char *parse_response(const char *buf, const char *buf_end, int *major_version, int *minor_version, int *status, + const char **msg, size_t *msg_len, struct phr_header *headers, size_t *num_headers, size_t max_headers, + int *ret) { + /* parse "HTTP/1.x" */ + if ((buf = parse_http_version(buf, buf_end, major_version, minor_version, ret)) == NULL) { + return NULL; + } + /* skip space */ + if (*buf != ' ') { + *ret = -1; + return NULL; + } + do { + ++buf; + } while (*buf == ' '); + /* parse status code, we want at least [:digit:][:digit:][:digit:] to try to parse */ + if (buf_end - buf < 4) { + *ret = -2; + return NULL; + } + PARSE_INT_3(status); + + /* get message including preceding space */ + if ((buf = get_token_to_eol(buf, buf_end, msg, msg_len, ret)) == NULL) { + return NULL; + } + if (*msg_len == 0) { + /* ok */ + } else if (**msg == ' ') { + /* remove preceding space */ + do { + ++*msg; + --*msg_len; + } while (**msg == ' '); + } else { + /* garbage found after status code */ + *ret = -1; + return NULL; + } + + return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret); } -int phr_parse_response(const char *buf_start, size_t len, int *major_version, int *minor_version, int *status, const char **msg, size_t *msg_len, - struct phr_header *headers, size_t *num_headers, size_t last_len) -{ - const char *buf = buf_start, *buf_end = buf + len; - size_t max_headers = *num_headers; - int r; - - *major_version = -1; - *minor_version = -1; - *status = 0; - *msg = NULL; - *msg_len = 0; - *num_headers = 0; - - /* if last_len != 0, check if the response is complete (a fast countermeasure - against slowloris */ - if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) { - return r; - } - - if ((buf = parse_response(buf, buf_end, major_version, minor_version, status, msg, msg_len, headers, num_headers, max_headers, &r)) == NULL) { - return r; - } - - return (int)(buf - buf_start); +int phr_parse_response(const char *buf_start, size_t len, int *major_version, int *minor_version, int *status, const char **msg, + size_t *msg_len, struct phr_header *headers, size_t *num_headers, size_t last_len) { + const char *buf = buf_start, *buf_end = buf + len; + size_t max_headers = *num_headers; + int r; + + *major_version = -1; + *minor_version = -1; + *status = 0; + *msg = NULL; + *msg_len = 0; + *num_headers = 0; + + /* if last_len != 0, check if the response is complete (a fast countermeasure + against slowloris */ + if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) { + return r; + } + + if ((buf = parse_response(buf, buf_end, major_version, minor_version, status, msg, msg_len, headers, num_headers, max_headers, &r)) == + NULL) { + return r; + } + + return (int)(buf - buf_start); } -int phr_parse_headers(const char *buf_start, size_t len, struct phr_header *headers, size_t *num_headers, size_t last_len) -{ - const char *buf = buf_start, *buf_end = buf + len; - size_t max_headers = *num_headers; - int r; +int phr_parse_headers(const char *buf_start, size_t len, struct phr_header *headers, size_t *num_headers, size_t last_len) { + const char *buf = buf_start, *buf_end = buf + len; + size_t max_headers = *num_headers; + int r; - *num_headers = 0; + *num_headers = 0; - /* if last_len != 0, check if the response is complete (a fast countermeasure - against slowloris */ - if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) { - return r; - } + /* if last_len != 0, check if the response is complete (a fast countermeasure + against slowloris */ + if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) { + return r; + } - if ((buf = parse_headers(buf, buf_end, headers, num_headers, max_headers, &r)) == NULL) { - return r; - } + if ((buf = parse_headers(buf, buf_end, headers, num_headers, max_headers, &r)) == NULL) { + return r; + } - return (int)(buf - buf_start); + return (int)(buf - buf_start); } enum { - CHUNKED_IN_CHUNK_SIZE, - CHUNKED_IN_CHUNK_EXT, - CHUNKED_IN_CHUNK_DATA, - CHUNKED_IN_CHUNK_CRLF, - CHUNKED_IN_TRAILERS_LINE_HEAD, - CHUNKED_IN_TRAILERS_LINE_MIDDLE + CHUNKED_IN_CHUNK_SIZE, + CHUNKED_IN_CHUNK_EXT, + CHUNKED_IN_CHUNK_DATA, + CHUNKED_IN_CHUNK_CRLF, + CHUNKED_IN_TRAILERS_LINE_HEAD, + CHUNKED_IN_TRAILERS_LINE_MIDDLE }; -static int decode_hex(int ch) -{ - if ('0' <= ch && ch <= '9') { - return ch - '0'; - } else if ('A' <= ch && ch <= 'F') { - return ch - 'A' + 0xa; - } else if ('a' <= ch && ch <= 'f') { - return ch - 'a' + 0xa; - } else { - return -1; - } +static int decode_hex(int ch) { + if ('0' <= ch && ch <= '9') { + return ch - '0'; + } else if ('A' <= ch && ch <= 'F') { + return ch - 'A' + 0xa; + } else if ('a' <= ch && ch <= 'f') { + return ch - 'a' + 0xa; + } else { + return -1; + } } -ssize_t phr_decode_chunked(struct phr_chunked_decoder *decoder, char *buf, size_t *_bufsz) -{ - size_t dst = 0, src = 0, bufsz = *_bufsz; - ssize_t ret = -2; /* incomplete */ - - while (1) { - switch (decoder->_state) { - case CHUNKED_IN_CHUNK_SIZE: - for (;; ++src) { - int v; - if (src == bufsz) - goto Exit; - if ((v = decode_hex(buf[src])) == -1) { - if (decoder->_hex_count == 0) { - ret = -1; - goto Exit; - } - break; - } - if (decoder->_hex_count == sizeof(size_t) * 2) { - ret = -1; - goto Exit; - } - decoder->bytes_left_in_chunk = decoder->bytes_left_in_chunk * 16 + v; - ++decoder->_hex_count; - } - decoder->_hex_count = 0; - decoder->_state = CHUNKED_IN_CHUNK_EXT; - /* fallthru */ - case CHUNKED_IN_CHUNK_EXT: - /* RFC 7230 A.2 "Line folding in chunk extensions is disallowed" */ - for (;; ++src) { - if (src == bufsz) - goto Exit; - if (buf[src] == '\012') - break; - } - ++src; - if (decoder->bytes_left_in_chunk == 0) { - if (decoder->consume_trailer) { - decoder->_state = CHUNKED_IN_TRAILERS_LINE_HEAD; - break; - } else { - goto Complete; - } - } - decoder->_state = CHUNKED_IN_CHUNK_DATA; - /* fallthru */ - case CHUNKED_IN_CHUNK_DATA: { - size_t avail = bufsz - src; - if (avail < decoder->bytes_left_in_chunk) { - if (dst != src) - memmove(buf + dst, buf + src, avail); - src += avail; - dst += avail; - decoder->bytes_left_in_chunk -= avail; - goto Exit; - } - if (dst != src) - memmove(buf + dst, buf + src, decoder->bytes_left_in_chunk); - src += decoder->bytes_left_in_chunk; - dst += decoder->bytes_left_in_chunk; - decoder->bytes_left_in_chunk = 0; - decoder->_state = CHUNKED_IN_CHUNK_CRLF; - } - /* fallthru */ - case CHUNKED_IN_CHUNK_CRLF: - for (;; ++src) { - if (src == bufsz) - goto Exit; - if (buf[src] != '\015') - break; - } - if (buf[src] != '\012') { - ret = -1; - goto Exit; - } - ++src; - decoder->_state = CHUNKED_IN_CHUNK_SIZE; - break; - case CHUNKED_IN_TRAILERS_LINE_HEAD: - for (;; ++src) { - if (src == bufsz) - goto Exit; - if (buf[src] != '\015') - break; - } - if (buf[src++] == '\012') - goto Complete; - decoder->_state = CHUNKED_IN_TRAILERS_LINE_MIDDLE; - /* fallthru */ - case CHUNKED_IN_TRAILERS_LINE_MIDDLE: - for (;; ++src) { - if (src == bufsz) - goto Exit; - if (buf[src] == '\012') - break; - } - ++src; - decoder->_state = CHUNKED_IN_TRAILERS_LINE_HEAD; - break; - default: - assert(!"decoder is corrupt"); - } - } +ssize_t phr_decode_chunked(struct phr_chunked_decoder *decoder, char *buf, size_t *_bufsz) { + size_t dst = 0, src = 0, bufsz = *_bufsz; + ssize_t ret = -2; /* incomplete */ + + while (1) { + switch (decoder->_state) { + case CHUNKED_IN_CHUNK_SIZE: + for (;; ++src) { + int v; + if (src == bufsz) + goto Exit; + if ((v = decode_hex(buf[src])) == -1) { + if (decoder->_hex_count == 0) { + ret = -1; + goto Exit; + } + break; + } + if (decoder->_hex_count == sizeof(size_t) * 2) { + ret = -1; + goto Exit; + } + decoder->bytes_left_in_chunk = decoder->bytes_left_in_chunk * 16 + v; + ++decoder->_hex_count; + } + decoder->_hex_count = 0; + decoder->_state = CHUNKED_IN_CHUNK_EXT; + /* fallthru */ + case CHUNKED_IN_CHUNK_EXT: + /* RFC 7230 A.2 "Line folding in chunk extensions is disallowed" */ + for (;; ++src) { + if (src == bufsz) + goto Exit; + if (buf[src] == '\012') + break; + } + ++src; + if (decoder->bytes_left_in_chunk == 0) { + if (decoder->consume_trailer) { + decoder->_state = CHUNKED_IN_TRAILERS_LINE_HEAD; + break; + } else { + goto Complete; + } + } + decoder->_state = CHUNKED_IN_CHUNK_DATA; + /* fallthru */ + case CHUNKED_IN_CHUNK_DATA: { + size_t avail = bufsz - src; + if (avail < decoder->bytes_left_in_chunk) { + if (dst != src) + memmove(buf + dst, buf + src, avail); + src += avail; + dst += avail; + decoder->bytes_left_in_chunk -= avail; + goto Exit; + } + if (dst != src) + memmove(buf + dst, buf + src, decoder->bytes_left_in_chunk); + src += decoder->bytes_left_in_chunk; + dst += decoder->bytes_left_in_chunk; + decoder->bytes_left_in_chunk = 0; + decoder->_state = CHUNKED_IN_CHUNK_CRLF; + } + /* fallthru */ + case CHUNKED_IN_CHUNK_CRLF: + for (;; ++src) { + if (src == bufsz) + goto Exit; + if (buf[src] != '\015') + break; + } + if (buf[src] != '\012') { + ret = -1; + goto Exit; + } + ++src; + decoder->_state = CHUNKED_IN_CHUNK_SIZE; + break; + case CHUNKED_IN_TRAILERS_LINE_HEAD: + for (;; ++src) { + if (src == bufsz) + goto Exit; + if (buf[src] != '\015') + break; + } + if (buf[src++] == '\012') + goto Complete; + decoder->_state = CHUNKED_IN_TRAILERS_LINE_MIDDLE; + /* fallthru */ + case CHUNKED_IN_TRAILERS_LINE_MIDDLE: + for (;; ++src) { + if (src == bufsz) + goto Exit; + if (buf[src] == '\012') + break; + } + ++src; + decoder->_state = CHUNKED_IN_TRAILERS_LINE_HEAD; + break; + default: + assert(!"decoder is corrupt"); + } + } Complete: - ret = bufsz - src; + ret = bufsz - src; Exit: - if (dst != src) - memmove(buf + dst, buf + src, bufsz - src); - *_bufsz = dst; - return ret; + if (dst != src) + memmove(buf + dst, buf + src, bufsz - src); + *_bufsz = dst; + return ret; } -int phr_decode_chunked_is_in_data(struct phr_chunked_decoder *decoder) -{ - return decoder->_state == CHUNKED_IN_CHUNK_DATA; -} +int phr_decode_chunked_is_in_data(struct phr_chunked_decoder *decoder) { return decoder->_state == CHUNKED_IN_CHUNK_DATA; } #undef CHECK_EOF #undef EXPECT_CHAR -- cgit v0.10-9-g596f From 629571aac3a8f5953fa52403516d16bd73069f87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:28:36 +0100 Subject: runcmd.c: clang-format diff --git a/plugins/runcmd.c b/plugins/runcmd.c index ed49bb9..9474835 100644 --- a/plugins/runcmd.c +++ b/plugins/runcmd.c @@ -1,63 +1,63 @@ /***************************************************************************** -* -* Monitoring run command utilities -* -* License: GPL -* Copyright (c) 2005-2006 Monitoring Plugins Development Team -* -* Description : -* -* A simple interface to executing programs from other programs, using an -* optimized and safe popen()-like implementation. It is considered safe -* in that no shell needs to be spawned and the environment passed to the -* execve()'d program is essentially empty. -* -* The code in this file is a derivative of popen.c which in turn was taken -* from "Advanced Programming for the Unix Environment" by W. Richard Stevens. -* -* Care has been taken to make sure the functions are async-safe. The one -* function which isn't is np_runcmd_init() which it doesn't make sense to -* call twice anyway, so the api as a whole should be considered async-safe. -* -* -* 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 run command utilities + * + * License: GPL + * Copyright (c) 2005-2006 Monitoring Plugins Development Team + * + * Description : + * + * A simple interface to executing programs from other programs, using an + * optimized and safe popen()-like implementation. It is considered safe + * in that no shell needs to be spawned and the environment passed to the + * execve()'d program is essentially empty. + * + * The code in this file is a derivative of popen.c which in turn was taken + * from "Advanced Programming for the Unix Environment" by W. Richard Stevens. + * + * Care has been taken to make sure the functions are async-safe. The one + * function which isn't is np_runcmd_init() which it doesn't make sense to + * call twice anyway, so the api as a whole should be considered async-safe. + * + * + * 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 . + * + * + *****************************************************************************/ #define NAGIOSPLUG_API_C 1 /** includes **/ #include "runcmd.h" #ifdef HAVE_SYS_WAIT_H -# include +# include #endif #include "./utils.h" /** macros **/ #ifndef WEXITSTATUS -# define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8) +# define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8) #endif #ifndef WIFEXITED -# define WIFEXITED(stat_val) (((stat_val) & 255) == 0) +# define WIFEXITED(stat_val) (((stat_val)&255) == 0) #endif /* 4.3BSD Reno doesn't define SIG_ERR */ #if defined(SIG_IGN) && !defined(SIG_ERR) -# define SIG_ERR ((Sigfunc *)-1) +# define SIG_ERR ((Sigfunc *)-1) #endif #include "../lib/maxfd.h" @@ -72,33 +72,26 @@ static pid_t *np_pids = NULL; /** prototypes **/ -static int np_runcmd_open(const char *, int *, int *) - __attribute__((__nonnull__(1, 2, 3))); +static int np_runcmd_open(const char *, int *, int *) __attribute__((__nonnull__(1, 2, 3))); -static int np_fetch_output(int, output *, int) - __attribute__((__nonnull__(2))); +static int np_fetch_output(int, output *, int) __attribute__((__nonnull__(2))); static int np_runcmd_close(int); /* prototype imported from utils.h */ -extern void die (int, const char *, ...) - __attribute__((__noreturn__,__format__(__printf__, 2, 3))); - +extern void die(int, const char *, ...) __attribute__((__noreturn__, __format__(__printf__, 2, 3))); /* this function is NOT async-safe. It is exported so multithreaded * plugins (or other apps) can call it prior to running any commands * through this api and thus achieve async-safeness throughout the api */ -void np_runcmd_init(void) -{ - long maxfd = mp_open_max(); - if(!np_pids) np_pids = calloc(maxfd, sizeof(pid_t)); +void np_runcmd_init(void) { + long maxfd = mp_open_max(); + if (!np_pids) + np_pids = calloc(maxfd, sizeof(pid_t)); } - /* Start running a command */ -static int -np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr) -{ +static int np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr) { char *env[2]; char *cmd = NULL; char **argv = NULL; @@ -112,7 +105,8 @@ np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr) int i = 0; - if(!np_pids) NP_RUNCMD_INIT; + if (!np_pids) + NP_RUNCMD_INIT; env[0] = strdup("LC_ALL=C"); env[1] = NULL; @@ -120,15 +114,17 @@ np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr) /* make copy of command string so strtok() doesn't silently modify it */ /* (the calling program may want to access it later) */ cmdlen = strlen(cmdstring); - if((cmd = malloc(cmdlen + 1)) == NULL) return -1; + if ((cmd = malloc(cmdlen + 1)) == NULL) + return -1; memcpy(cmd, cmdstring, cmdlen); cmd[cmdlen] = '\0'; /* This is not a shell, so we don't handle "???" */ - if (strstr (cmdstring, "\"")) return -1; + if (strstr(cmdstring, "\"")) + return -1; /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */ - if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''")) + if (strstr(cmdstring, " ' ") || strstr(cmdstring, "'''")) return -1; /* each arg must be whitespace-separated, so args can be a maximum @@ -137,32 +133,31 @@ np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr) argv = calloc(sizeof(char *), argc); if (argv == NULL) { - printf ("%s\n", _("Could not malloc argv array in popen()")); + printf("%s\n", _("Could not malloc argv array in popen()")); return -1; } /* get command arguments (stupidly, but fairly quickly) */ while (cmd) { str = cmd; - str += strspn (str, " \t\r\n"); /* trim any leading whitespace */ + str += strspn(str, " \t\r\n"); /* trim any leading whitespace */ - if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */ + if (strstr(str, "'") == str) { /* handle SIMPLE quoted strings */ str++; - if (!strstr (str, "'")) return -1; /* balanced? */ - cmd = 1 + strstr (str, "'"); - str[strcspn (str, "'")] = 0; - } - else { - if (strpbrk (str, " \t\r\n")) { - cmd = 1 + strpbrk (str, " \t\r\n"); - str[strcspn (str, " \t\r\n")] = 0; - } - else { + if (!strstr(str, "'")) + return -1; /* balanced? */ + cmd = 1 + strstr(str, "'"); + str[strcspn(str, "'")] = 0; + } else { + if (strpbrk(str, " \t\r\n")) { + cmd = 1 + strpbrk(str, " \t\r\n"); + str[strcspn(str, " \t\r\n")] = 0; + } else { cmd = NULL; } } - if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n")) + if (cmd && strlen(cmd) == strspn(cmd, " \t\r\n")) cmd = NULL; argv[i++] = str; @@ -173,33 +168,33 @@ np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr) /* child runs exceve() and _exit. */ if (pid == 0) { -#ifdef RLIMIT_CORE +#ifdef RLIMIT_CORE /* the program we execve shouldn't leave core files */ - getrlimit (RLIMIT_CORE, &limit); + getrlimit(RLIMIT_CORE, &limit); limit.rlim_cur = 0; - setrlimit (RLIMIT_CORE, &limit); + setrlimit(RLIMIT_CORE, &limit); #endif - close (pfd[0]); + close(pfd[0]); if (pfd[1] != STDOUT_FILENO) { - dup2 (pfd[1], STDOUT_FILENO); - close (pfd[1]); + dup2(pfd[1], STDOUT_FILENO); + close(pfd[1]); } - close (pfderr[0]); + close(pfderr[0]); if (pfderr[1] != STDERR_FILENO) { - dup2 (pfderr[1], STDERR_FILENO); - close (pfderr[1]); + dup2(pfderr[1], STDERR_FILENO); + close(pfderr[1]); } /* close all descriptors in np_pids[] * This is executed in a separate address space (pure child), * so we don't have to worry about async safety */ - long maxfd = mp_open_max(); + long maxfd = mp_open_max(); for (i = 0; i < maxfd; i++) - if(np_pids[i] > 0) - close (i); + if (np_pids[i] > 0) + close(i); - execve (argv[0], argv, env); - _exit (STATE_UNKNOWN); + execve(argv[0], argv, env); + _exit(STATE_UNKNOWN); } /* parent picks up execution here */ @@ -213,49 +208,44 @@ np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr) return pfd[0]; } - -static int -np_runcmd_close(int fd) -{ +static int np_runcmd_close(int fd) { int status; pid_t pid; /* make sure this fd was opened by popen() */ - long maxfd = mp_open_max(); - if(fd < 0 || fd > maxfd || !np_pids || (pid = np_pids[fd]) == 0) + long maxfd = mp_open_max(); + if (fd < 0 || fd > maxfd || !np_pids || (pid = np_pids[fd]) == 0) return -1; np_pids[fd] = 0; - if (close (fd) == -1) return -1; + if (close(fd) == -1) + return -1; /* EINTR is ok (sort of), everything else is bad */ - while (waitpid (pid, &status, 0) < 0) - if (errno != EINTR) return -1; + while (waitpid(pid, &status, 0) < 0) + if (errno != EINTR) + return -1; /* return child's termination status */ return (WIFEXITED(status)) ? WEXITSTATUS(status) : -1; } - -void -runcmd_timeout_alarm_handler (int signo) -{ +void runcmd_timeout_alarm_handler(int signo) { if (signo == SIGALRM) puts(_("CRITICAL - Plugin timed out while executing system call")); - long maxfd = mp_open_max(); - if(np_pids) for(long int i = 0; i < maxfd; i++) { - if(np_pids[i] != 0) kill(np_pids[i], SIGKILL); - } + long maxfd = mp_open_max(); + if (np_pids) + for (long int i = 0; i < maxfd; i++) { + if (np_pids[i] != 0) + kill(np_pids[i], SIGKILL); + } - exit (STATE_CRITICAL); + exit(STATE_CRITICAL); } - -static int -np_fetch_output(int fd, output *op, int flags) -{ +static int np_fetch_output(int fd, output *op, int flags) { size_t len = 0, i = 0, lineno = 0; size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */ char *buf = NULL; @@ -264,7 +254,7 @@ np_fetch_output(int fd, output *op, int flags) op->buf = NULL; op->buflen = 0; - while((ret = read(fd, tmpbuf, sizeof(tmpbuf))) > 0) { + while ((ret = read(fd, tmpbuf, sizeof(tmpbuf))) > 0) { len = (size_t)ret; op->buf = realloc(op->buf, op->buflen + len + 1); memcpy(op->buf + op->buflen, tmpbuf, len); @@ -272,33 +262,33 @@ np_fetch_output(int fd, output *op, int flags) i++; } - if(ret < 0) { + if (ret < 0) { printf("read() returned %d: %s\n", ret, strerror(errno)); return ret; } /* some plugins may want to keep output unbroken, and some commands * will yield no output, so return here for those */ - if(flags & RUNCMD_NO_ARRAYS || !op->buf || !op->buflen) + if (flags & RUNCMD_NO_ARRAYS || !op->buf || !op->buflen) return op->buflen; /* and some may want both */ - if(flags & RUNCMD_NO_ASSOC) { + if (flags & RUNCMD_NO_ASSOC) { buf = malloc(op->buflen); memcpy(buf, op->buf, op->buflen); - } - else buf = op->buf; + } else + buf = op->buf; op->line = NULL; op->lens = NULL; i = 0; - while(i < op->buflen) { + while (i < op->buflen) { /* make sure we have enough memory */ - if(lineno >= ary_size) { + if (lineno >= ary_size) { /* ary_size must never be zero */ do { ary_size = op->buflen >> --rsf; - } while(!ary_size); + } while (!ary_size); op->line = realloc(op->line, ary_size * sizeof(char *)); op->lens = realloc(op->lens, ary_size * sizeof(size_t)); @@ -308,7 +298,8 @@ np_fetch_output(int fd, output *op, int flags) op->line[lineno] = &buf[i]; /* hop to next newline or end of buffer */ - while(buf[i] != '\n' && i < op->buflen) i++; + while (buf[i] != '\n' && i < op->buflen) + i++; buf[i] = '\0'; /* calculate the string length using pointer difference */ @@ -321,21 +312,22 @@ np_fetch_output(int fd, output *op, int flags) return lineno; } - -int -np_runcmd(const char *cmd, output *out, output *err, int flags) -{ +int np_runcmd(const char *cmd, output *out, output *err, int flags) { int fd, pfd_out[2], pfd_err[2]; /* initialize the structs */ - if(out) memset(out, 0, sizeof(output)); - if(err) memset(err, 0, sizeof(output)); - - if((fd = np_runcmd_open(cmd, pfd_out, pfd_err)) == -1) - die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd); - - if(out) out->lines = np_fetch_output(pfd_out[0], out, flags); - if(err) err->lines = np_fetch_output(pfd_err[0], err, flags); + if (out) + memset(out, 0, sizeof(output)); + if (err) + memset(err, 0, sizeof(output)); + + if ((fd = np_runcmd_open(cmd, pfd_out, pfd_err)) == -1) + die(STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd); + + if (out) + out->lines = np_fetch_output(pfd_out[0], out, flags); + if (err) + err->lines = np_fetch_output(pfd_err[0], err, flags); return np_runcmd_close(fd); } -- cgit v0.10-9-g596f From 4ca5696a19df55962fd55e223dea9fd4e801f0e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:29:13 +0100 Subject: runcmd.c: update copyright diff --git a/plugins/runcmd.c b/plugins/runcmd.c index 9474835..2e53dc0 100644 --- a/plugins/runcmd.c +++ b/plugins/runcmd.c @@ -3,7 +3,7 @@ * Monitoring run command utilities * * License: GPL - * Copyright (c) 2005-2006 Monitoring Plugins Development Team + * Copyright (c) 2005-2024 Monitoring Plugins Development Team * * Description : * -- cgit v0.10-9-g596f From daecd2f6f845336a65a8ad479ff4c0fe3e8558ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:30:10 +0100 Subject: netuils.c: clang-format diff --git a/plugins/netutils.c b/plugins/netutils.c index c6af248..fdfef32 100644 --- a/plugins/netutils.c +++ b/plugins/netutils.c @@ -1,31 +1,31 @@ /***************************************************************************** -* -* Monitoring Plugins network utilities -* -* License: GPL -* Copyright (c) 1999 Ethan Galstad (nagios@nagios.org) -* Copyright (c) 2003-2008 Monitoring Plugins Development Team -* -* Description: -* -* This file contains commons functions used in many of the plugins. -* -* -* 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 Plugins network utilities + * + * License: GPL + * Copyright (c) 1999 Ethan Galstad (nagios@nagios.org) + * Copyright (c) 2003-2008 Monitoring Plugins Development Team + * + * Description: + * + * This file contains commons functions used in many of the plugins. + * + * + * 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 . + * + * + *****************************************************************************/ #include "common.h" #include "netutils.h" @@ -42,25 +42,19 @@ int address_family = AF_INET; #endif /* handles socket timeouts */ -void -socket_timeout_alarm_handler (int sig) -{ +void socket_timeout_alarm_handler(int sig) { if (sig == SIGALRM) - printf (_("%s - Socket timeout after %d seconds\n"), state_text(socket_timeout_state), socket_timeout); + printf(_("%s - Socket timeout after %d seconds\n"), state_text(socket_timeout_state), socket_timeout); else - printf (_("%s - Abnormal timeout after %d seconds\n"), state_text(socket_timeout_state), socket_timeout); + printf(_("%s - Abnormal timeout after %d seconds\n"), state_text(socket_timeout_state), socket_timeout); - exit (socket_timeout_state); + exit(socket_timeout_state); } - /* connects to a host on a specified tcp port, sends a string, and gets a response. loops on select-recv until timeout or eof to get all of a multi-packet answer */ -int -process_tcp_request2 (const char *server_address, int server_port, - const char *send_buffer, char *recv_buffer, int recv_size) -{ +int process_tcp_request2(const char *server_address, int server_port, const char *send_buffer, char *recv_buffer, int recv_size) { int result; int send_result; @@ -70,13 +64,13 @@ process_tcp_request2 (const char *server_address, int server_port, fd_set readfds; int recv_length = 0; - result = np_net_connect (server_address, server_port, &sd, IPPROTO_TCP); + result = np_net_connect(server_address, server_port, &sd, IPPROTO_TCP); if (result != STATE_OK) return STATE_CRITICAL; - send_result = send (sd, send_buffer, strlen (send_buffer), 0); - if (send_result<0 || (size_t)send_result!=strlen(send_buffer)) { - printf ("%s\n", _("Send failed")); + send_result = send(sd, send_buffer, strlen(send_buffer), 0); + if (send_result < 0 || (size_t)send_result != strlen(send_buffer)) { + printf("%s\n", _("Send failed")); result = STATE_WARNING; } @@ -85,38 +79,32 @@ process_tcp_request2 (const char *server_address, int server_port, minus one for data from the host */ tv.tv_sec = socket_timeout - 1; tv.tv_usec = 0; - FD_ZERO (&readfds); - FD_SET (sd, &readfds); - select (sd + 1, &readfds, NULL, NULL, &tv); + FD_ZERO(&readfds); + FD_SET(sd, &readfds); + select(sd + 1, &readfds, NULL, NULL, &tv); /* make sure some data has arrived */ - if (!FD_ISSET (sd, &readfds)) { /* it hasn't */ + if (!FD_ISSET(sd, &readfds)) { /* it hasn't */ if (!recv_length) { - strcpy (recv_buffer, ""); - printf ("%s\n", _("No data was received from host!")); + strcpy(recv_buffer, ""); + printf("%s\n", _("No data was received from host!")); result = STATE_WARNING; - } - else { /* this one failed, but previous ones worked */ + } else { /* this one failed, but previous ones worked */ recv_buffer[recv_length] = 0; } break; - } - else { /* it has */ - recv_result = - recv (sd, recv_buffer + recv_length, - (size_t)recv_size - recv_length - 1, 0); + } else { /* it has */ + recv_result = recv(sd, recv_buffer + recv_length, (size_t)recv_size - recv_length - 1, 0); if (recv_result == -1) { /* recv failed, bail out */ - strcpy (recv_buffer + recv_length, ""); + strcpy(recv_buffer + recv_length, ""); result = STATE_WARNING; break; - } - else if (recv_result == 0) { + } else if (recv_result == 0) { /* end of file ? */ recv_buffer[recv_length] = 0; break; - } - else { /* we got data! */ + } else { /* we got data! */ recv_length += recv_result; if (recv_length >= recv_size - 1) { /* buffer full, we're done */ @@ -129,42 +117,35 @@ process_tcp_request2 (const char *server_address, int server_port, } /* end while(1) */ - close (sd); + close(sd); return result; } - /* connects to a host on a specified port, sends a string, and gets a response */ -int -process_request (const char *server_address, int server_port, int proto, - const char *send_buffer, char *recv_buffer, int recv_size) -{ +int process_request(const char *server_address, int server_port, int proto, const char *send_buffer, char *recv_buffer, int recv_size) { int result; int sd; result = STATE_OK; - result = np_net_connect (server_address, server_port, &sd, proto); + result = np_net_connect(server_address, server_port, &sd, proto); if (result != STATE_OK) return STATE_CRITICAL; - result = send_request (sd, proto, send_buffer, recv_buffer, recv_size); + result = send_request(sd, proto, send_buffer, recv_buffer, recv_size); - close (sd); + close(sd); return result; } - /* opens a tcp or udp connection to a remote host or local socket */ -int -np_net_connect (const char *host_name, int port, int *sd, int proto) -{ - /* send back STATE_UNKOWN if there's an error - send back STATE_OK if we connect - send back STATE_CRITICAL if we can't connect. - Let upstream figure out what to send to the user. */ +int np_net_connect(const char *host_name, int port, int *sd, int proto) { + /* send back STATE_UNKOWN if there's an error + send back STATE_OK if we connect + send back STATE_CRITICAL if we can't connect. + Let upstream figure out what to send to the user. */ struct addrinfo hints; struct addrinfo *r, *res; struct sockaddr_un su; @@ -176,13 +157,13 @@ np_net_connect (const char *host_name, int port, int *sd, int proto) socktype = (proto == IPPROTO_UDP) ? SOCK_DGRAM : SOCK_STREAM; /* as long as it doesn't start with a '/', it's assumed a host or ip */ - if (!is_socket){ - memset (&hints, 0, sizeof (hints)); + if (!is_socket) { + memset(&hints, 0, sizeof(hints)); hints.ai_family = address_family; hints.ai_protocol = proto; hints.ai_socktype = socktype; - len = strlen (host_name); + len = strlen(host_name); /* check for an [IPv6] address (and strip the brackets) */ if (len >= 2 && host_name[0] == '[' && host_name[len - 1] == ']') { host_name++; @@ -190,29 +171,29 @@ np_net_connect (const char *host_name, int port, int *sd, int proto) } if (len >= sizeof(host)) return STATE_UNKNOWN; - memcpy (host, host_name, len); + memcpy(host, host_name, len); host[len] = '\0'; - snprintf (port_str, sizeof (port_str), "%d", port); - result = getaddrinfo (host, port_str, &hints, &res); + snprintf(port_str, sizeof(port_str), "%d", port); + result = getaddrinfo(host, port_str, &hints, &res); if (result != 0) { - printf ("%s\n", gai_strerror (result)); + printf("%s\n", gai_strerror(result)); return STATE_UNKNOWN; } r = res; while (r) { /* attempt to create a socket */ - *sd = socket (r->ai_family, socktype, r->ai_protocol); + *sd = socket(r->ai_family, socktype, r->ai_protocol); if (*sd < 0) { - printf ("%s\n", _("Socket creation failed")); - freeaddrinfo (r); + printf("%s\n", _("Socket creation failed")); + freeaddrinfo(r); return STATE_UNKNOWN; } /* attempt to open a connection */ - result = connect (*sd, r->ai_addr, r->ai_addrlen); + result = connect(*sd, r->ai_addr, r->ai_addrlen); if (result == 0) { was_refused = false; @@ -227,21 +208,21 @@ np_net_connect (const char *host_name, int port, int *sd, int proto) } } - close (*sd); + close(*sd); r = r->ai_next; } - freeaddrinfo (res); + freeaddrinfo(res); } /* else the hostname is interpreted as a path to a unix socket */ else { - if(strlen(host_name) >= UNIX_PATH_MAX){ + if (strlen(host_name) >= UNIX_PATH_MAX) { die(STATE_UNKNOWN, _("Supplied path too long unix domain socket")); } memset(&su, 0, sizeof(su)); su.sun_family = AF_UNIX; strncpy(su.sun_path, host_name, UNIX_PATH_MAX); *sd = socket(PF_UNIX, SOCK_STREAM, 0); - if(*sd < 0){ + if (*sd < 0) { die(STATE_UNKNOWN, _("Socket creation failed")); } result = connect(*sd, (struct sockaddr *)&su, sizeof(su)); @@ -259,37 +240,32 @@ np_net_connect (const char *host_name, int port, int *sd, int proto) if (is_socket) printf("connect to file socket %s: %s\n", host_name, strerror(errno)); else - printf("connect to address %s and port %d: %s\n", - host_name, port, strerror(errno)); + printf("connect to address %s and port %d: %s\n", host_name, port, strerror(errno)); return STATE_CRITICAL; break; default: /* it's a logic error if we do not end up in STATE_(OK|WARNING|CRITICAL) */ return STATE_UNKNOWN; break; } - } - else { + } else { if (is_socket) printf("connect to file socket %s: %s\n", host_name, strerror(errno)); else - printf("connect to address %s and port %d: %s\n", - host_name, port, strerror(errno)); + printf("connect to address %s and port %d: %s\n", host_name, port, strerror(errno)); return STATE_CRITICAL; } } -int -send_request (int sd, int proto, const char *send_buffer, char *recv_buffer, int recv_size) -{ +int send_request(int sd, int proto, const char *send_buffer, char *recv_buffer, int recv_size) { int result = STATE_OK; int send_result; int recv_result; struct timeval tv; fd_set readfds; - send_result = send (sd, send_buffer, strlen (send_buffer), 0); - if (send_result<0 || (size_t)send_result!=strlen(send_buffer)) { - printf ("%s\n", _("Send failed")); + send_result = send(sd, send_buffer, strlen(send_buffer), 0); + if (send_result < 0 || (size_t)send_result != strlen(send_buffer)) { + printf("%s\n", _("Send failed")); result = STATE_WARNING; } @@ -297,26 +273,25 @@ send_request (int sd, int proto, const char *send_buffer, char *recv_buffer, int for data from the host */ tv.tv_sec = socket_timeout - 1; tv.tv_usec = 0; - FD_ZERO (&readfds); - FD_SET (sd, &readfds); - select (sd + 1, &readfds, NULL, NULL, &tv); + FD_ZERO(&readfds); + FD_SET(sd, &readfds); + select(sd + 1, &readfds, NULL, NULL, &tv); /* make sure some data has arrived */ - if (!FD_ISSET (sd, &readfds)) { - strcpy (recv_buffer, ""); - printf ("%s\n", _("No data was received from host!")); + if (!FD_ISSET(sd, &readfds)) { + strcpy(recv_buffer, ""); + printf("%s\n", _("No data was received from host!")); result = STATE_WARNING; } else { - recv_result = recv (sd, recv_buffer, (size_t)recv_size - 1, 0); + recv_result = recv(sd, recv_buffer, (size_t)recv_size - 1, 0); if (recv_result == -1) { - strcpy (recv_buffer, ""); + strcpy(recv_buffer, ""); if (proto != IPPROTO_TCP) - printf ("%s\n", _("Receive failed")); + printf("%s\n", _("Receive failed")); result = STATE_WARNING; - } - else + } else recv_buffer[recv_result] = 0; /* die returned string */ @@ -325,51 +300,46 @@ send_request (int sd, int proto, const char *send_buffer, char *recv_buffer, int return result; } - -bool is_host (const char *address) { - if (is_addr (address) || is_hostname (address)) +bool is_host(const char *address) { + if (is_addr(address) || is_hostname(address)) return (true); return (false); } -void -host_or_die(const char *str) -{ - if(!str || (!is_addr(str) && !is_hostname(str))) +void host_or_die(const char *str) { + if (!str || (!is_addr(str) && !is_hostname(str))) usage_va(_("Invalid hostname/address - %s"), str); } -bool is_addr (const char *address) { +bool is_addr(const char *address) { #ifdef USE_IPV6 - if (address_family == AF_INET && is_inet_addr (address)) + if (address_family == AF_INET && is_inet_addr(address)) return true; - else if (address_family == AF_INET6 && is_inet6_addr (address)) + else if (address_family == AF_INET6 && is_inet6_addr(address)) return true; #else - if (is_inet_addr (address)) + if (is_inet_addr(address)) return (true); #endif return (false); } -int -dns_lookup (const char *in, struct sockaddr_storage *ss, int family) -{ +int dns_lookup(const char *in, struct sockaddr_storage *ss, int family) { struct addrinfo hints; struct addrinfo *res; int retval; - memset (&hints, 0, sizeof(struct addrinfo)); + memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = family; - retval = getaddrinfo (in, NULL, &hints, &res); + retval = getaddrinfo(in, NULL, &hints, &res); if (retval != 0) return false; if (ss != NULL) - memcpy (ss, res->ai_addr, res->ai_addrlen); - freeaddrinfo (res); + memcpy(ss, res->ai_addr, res->ai_addrlen); + freeaddrinfo(res); return true; } -- cgit v0.10-9-g596f From e353337d08b7cc778f01ef94301af73539e8266c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:30:43 +0100 Subject: netutils.c: update copyright diff --git a/plugins/netutils.c b/plugins/netutils.c index fdfef32..ee81912 100644 --- a/plugins/netutils.c +++ b/plugins/netutils.c @@ -4,7 +4,7 @@ * * License: GPL * Copyright (c) 1999 Ethan Galstad (nagios@nagios.org) - * Copyright (c) 2003-2008 Monitoring Plugins Development Team + * Copyright (c) 2003-2024 Monitoring Plugins Development Team * * Description: * -- cgit v0.10-9-g596f From 8c937fbfac89e632d86dcde9c6b8e5f7d6790902 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:32:03 +0100 Subject: sslutils.c: clang-format diff --git a/plugins/sslutils.c b/plugins/sslutils.c index 6bc0ba8..b8cbc7c 100644 --- a/plugins/sslutils.c +++ b/plugins/sslutils.c @@ -1,46 +1,42 @@ /***************************************************************************** -* -* Monitoring Plugins SSL utilities -* -* License: GPL -* Copyright (c) 2005-2010 Monitoring Plugins Development Team -* -* Description: -* -* This file contains common functions for plugins that require SSL. -* -* -* 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 Plugins SSL utilities + * + * License: GPL + * Copyright (c) 2005-2010 Monitoring Plugins Development Team + * + * Description: + * + * This file contains common functions for plugins that require SSL. + * + * + * 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 . + * + * + *****************************************************************************/ #define MAX_CN_LENGTH 256 #include "common.h" #include "netutils.h" #ifdef HAVE_SSL -static SSL_CTX *ctx=NULL; -static SSL *s=NULL; +static SSL_CTX *ctx = NULL; +static SSL *s = NULL; -int np_net_ssl_init(int sd) { - return np_net_ssl_init_with_hostname(sd, NULL); -} +int np_net_ssl_init(int sd) { return np_net_ssl_init_with_hostname(sd, NULL); } -int np_net_ssl_init_with_hostname(int sd, char *host_name) { - return np_net_ssl_init_with_hostname_and_version(sd, host_name, 0); -} +int np_net_ssl_init_with_hostname(int sd, char *host_name) { return np_net_ssl_init_with_hostname_and_version(sd, host_name, 0); } int np_net_ssl_init_with_hostname_and_version(int sd, char *host_name, int version) { return np_net_ssl_init_with_hostname_version_and_cert(sd, host_name, version, NULL, NULL); @@ -59,145 +55,141 @@ int np_net_ssl_init_with_hostname_version_and_cert(int sd, char *host_name, int printf("%s\n", _("UNKNOWN - SSL protocol version 2 is not supported by your SSL library.")); return STATE_UNKNOWN; case MP_SSLv3: /* SSLv3 protocol */ -#if defined(OPENSSL_NO_SSL3) +# if defined(OPENSSL_NO_SSL3) printf("%s\n", _("UNKNOWN - SSL protocol version 3 is not supported by your SSL library.")); return STATE_UNKNOWN; -#else +# else SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION); SSL_CTX_set_max_proto_version(ctx, SSL3_VERSION); break; -#endif +# endif case MP_TLSv1: /* TLSv1 protocol */ -#if defined(OPENSSL_NO_TLS1) +# if defined(OPENSSL_NO_TLS1) printf("%s\n", _("UNKNOWN - TLS protocol version 1 is not supported by your SSL library.")); return STATE_UNKNOWN; -#else +# else SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION); SSL_CTX_set_max_proto_version(ctx, TLS1_VERSION); break; -#endif +# endif case MP_TLSv1_1: /* TLSv1.1 protocol */ -#if !defined(SSL_OP_NO_TLSv1_1) +# if !defined(SSL_OP_NO_TLSv1_1) printf("%s\n", _("UNKNOWN - TLS protocol version 1.1 is not supported by your SSL library.")); return STATE_UNKNOWN; -#else +# else SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION); SSL_CTX_set_max_proto_version(ctx, TLS1_1_VERSION); break; -#endif +# endif case MP_TLSv1_2: /* TLSv1.2 protocol */ -#if !defined(SSL_OP_NO_TLSv1_2) +# if !defined(SSL_OP_NO_TLSv1_2) printf("%s\n", _("UNKNOWN - TLS protocol version 1.2 is not supported by your SSL library.")); return STATE_UNKNOWN; -#else +# else SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION); SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION); break; -#endif +# endif case MP_TLSv1_2_OR_NEWER: -#if !defined(SSL_OP_NO_TLSv1_1) +# if !defined(SSL_OP_NO_TLSv1_1) printf("%s\n", _("UNKNOWN - Disabling TLSv1.1 is not supported by your SSL library.")); return STATE_UNKNOWN; -#else +# else SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION); break; -#endif +# endif case MP_TLSv1_1_OR_NEWER: -#if !defined(SSL_OP_NO_TLSv1) +# if !defined(SSL_OP_NO_TLSv1) printf("%s\n", _("UNKNOWN - Disabling TLSv1 is not supported by your SSL library.")); return STATE_UNKNOWN; -#else +# else SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION); break; -#endif +# endif case MP_TLSv1_OR_NEWER: -#if defined(SSL_OP_NO_SSLv3) +# if defined(SSL_OP_NO_SSLv3) SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION); break; -#endif +# endif case MP_SSLv3_OR_NEWER: -#if defined(SSL_OP_NO_SSLv2) +# if defined(SSL_OP_NO_SSLv2) SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION); break; -#endif +# endif } if (cert && privkey) { -#ifdef USE_OPENSSL +# ifdef USE_OPENSSL if (!SSL_CTX_use_certificate_chain_file(ctx, cert)) { -#elif USE_GNUTLS +# elif USE_GNUTLS if (!SSL_CTX_use_certificate_file(ctx, cert, SSL_FILETYPE_PEM)) { -#else -#error Unported for unknown SSL library -#endif - printf ("%s\n", _("CRITICAL - Unable to open certificate chain file!\n")); +# else +# error Unported for unknown SSL library +# endif + printf("%s\n", _("CRITICAL - Unable to open certificate chain file!\n")); return STATE_CRITICAL; } SSL_CTX_use_PrivateKey_file(ctx, privkey, SSL_FILETYPE_PEM); -#ifdef USE_OPENSSL +# ifdef USE_OPENSSL if (!SSL_CTX_check_private_key(ctx)) { - printf ("%s\n", _("CRITICAL - Private key does not seem to match certificate!\n")); + printf("%s\n", _("CRITICAL - Private key does not seem to match certificate!\n")); return STATE_CRITICAL; } -#endif +# endif } -#ifdef SSL_OP_NO_TICKET +# ifdef SSL_OP_NO_TICKET options |= SSL_OP_NO_TICKET; -#endif +# endif SSL_CTX_set_options(ctx, options); SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY); if ((s = SSL_new(ctx)) != NULL) { -#ifdef SSL_set_tlsext_host_name +# ifdef SSL_set_tlsext_host_name if (host_name != NULL) SSL_set_tlsext_host_name(s, host_name); -#endif +# endif SSL_set_fd(s, sd); if (SSL_connect(s) == 1) { return OK; } else { printf("%s\n", _("CRITICAL - Cannot make SSL connection.")); -# ifdef USE_OPENSSL /* XXX look into ERR_error_string */ +# ifdef USE_OPENSSL /* XXX look into ERR_error_string */ ERR_print_errors_fp(stdout); -# endif /* USE_OPENSSL */ +# endif /* USE_OPENSSL */ } } else { - printf("%s\n", _("CRITICAL - Cannot initiate SSL handshake.")); + printf("%s\n", _("CRITICAL - Cannot initiate SSL handshake.")); } return STATE_CRITICAL; } void np_net_ssl_cleanup() { if (s) { -#ifdef SSL_set_tlsext_host_name +# ifdef SSL_set_tlsext_host_name SSL_set_tlsext_host_name(s, NULL); -#endif +# endif SSL_shutdown(s); SSL_free(s); if (ctx) { SSL_CTX_free(ctx); - ctx=NULL; + ctx = NULL; } - s=NULL; + s = NULL; } } -int np_net_ssl_write(const void *buf, int num) { - return SSL_write(s, buf, num); -} +int np_net_ssl_write(const void *buf, int num) { return SSL_write(s, buf, num); } -int np_net_ssl_read(void *buf, int num) { - return SSL_read(s, buf, num); -} +int np_net_ssl_read(void *buf, int num) { return SSL_read(s, buf, num); } -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; +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; char timestamp[50] = ""; - char cn[MAX_CN_LENGTH]= ""; + char cn[MAX_CN_LENGTH] = ""; char *tz; - int cnlen =-1; - int status=STATE_UNKNOWN; + int cnlen = -1; + int status = STATE_UNKNOWN; ASN1_STRING *tm; int offset; @@ -208,15 +200,15 @@ int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int time_t tm_t; if (!certificate) { - printf("%s\n",_("CRITICAL - Cannot retrieve server certificate.")); + printf("%s\n", _("CRITICAL - Cannot retrieve server certificate.")); return STATE_CRITICAL; } /* Extract CN from certificate subject */ - subj=X509_get_subject_name(certificate); + subj = X509_get_subject_name(certificate); if (!subj) { - printf("%s\n",_("CRITICAL - Cannot retrieve certificate subject.")); + printf("%s\n", _("CRITICAL - Cannot retrieve certificate subject.")); return STATE_CRITICAL; } cnlen = X509_NAME_get_text_by_NID(subj, NID_commonName, cn, sizeof(cn)); @@ -242,23 +234,16 @@ int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int printf("%s\n", _("CRITICAL - Wrong time format in certificate.")); return STATE_CRITICAL; } else { - stamp.tm_year = - (tm->data[0] - '0') * 1000 + (tm->data[1] - '0') * 100 + - (tm->data[2] - '0') * 10 + (tm->data[3] - '0'); + stamp.tm_year = (tm->data[0] - '0') * 1000 + (tm->data[1] - '0') * 100 + (tm->data[2] - '0') * 10 + (tm->data[3] - '0'); stamp.tm_year -= 1900; offset = 2; } } - stamp.tm_mon = - (tm->data[2 + offset] - '0') * 10 + (tm->data[3 + offset] - '0') - 1; - stamp.tm_mday = - (tm->data[4 + offset] - '0') * 10 + (tm->data[5 + offset] - '0'); - stamp.tm_hour = - (tm->data[6 + offset] - '0') * 10 + (tm->data[7 + offset] - '0'); - stamp.tm_min = - (tm->data[8 + offset] - '0') * 10 + (tm->data[9 + offset] - '0'); - stamp.tm_sec = - (tm->data[10 + offset] - '0') * 10 + (tm->data[11 + offset] - '0'); + stamp.tm_mon = (tm->data[2 + offset] - '0') * 10 + (tm->data[3 + offset] - '0') - 1; + stamp.tm_mday = (tm->data[4 + offset] - '0') * 10 + (tm->data[5 + offset] - '0'); + stamp.tm_hour = (tm->data[6 + offset] - '0') * 10 + (tm->data[7 + offset] - '0'); + stamp.tm_min = (tm->data[8 + offset] - '0') * 10 + (tm->data[9 + offset] - '0'); + stamp.tm_sec = (tm->data[10 + offset] - '0') * 10 + (tm->data[11 + offset] - '0'); stamp.tm_isdst = -1; tm_t = timegm(&stamp); @@ -275,30 +260,30 @@ int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int tzset(); if (days_left > 0 && days_left <= days_till_exp_warn) { - printf (_("%s - Certificate '%s' expires in %d day(s) (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", cn, days_left, timestamp); + printf(_("%s - Certificate '%s' expires in %d day(s) (%s).\n"), (days_left > days_till_exp_crit) ? "WARNING" : "CRITICAL", cn, + days_left, timestamp); if (days_left > days_till_exp_crit) status = STATE_WARNING; else status = STATE_CRITICAL; } else if (days_left == 0 && time_left > 0) { if (time_left >= 3600) - time_remaining = (int) time_left / 3600; + time_remaining = (int)time_left / 3600; else - time_remaining = (int) time_left / 60; + time_remaining = (int)time_left / 60; - printf (_("%s - Certificate '%s' expires in %u %s (%s)\n"), - (days_left>days_till_exp_crit) ? "WARNING" : "CRITICAL", cn, time_remaining, - time_left >= 3600 ? "hours" : "minutes", timestamp); + printf(_("%s - Certificate '%s' expires in %u %s (%s)\n"), (days_left > days_till_exp_crit) ? "WARNING" : "CRITICAL", cn, + time_remaining, time_left >= 3600 ? "hours" : "minutes", timestamp); - if ( days_left > days_till_exp_crit) + if (days_left > days_till_exp_crit) status = STATE_WARNING; else status = STATE_CRITICAL; } else if (time_left < 0) { printf(_("CRITICAL - Certificate '%s' expired on %s.\n"), cn, timestamp); - status=STATE_CRITICAL; + status = STATE_CRITICAL; } else if (days_left == 0) { - printf (_("%s - Certificate '%s' just expired (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", cn, timestamp); + printf(_("%s - Certificate '%s' just expired (%s).\n"), (days_left > days_till_exp_crit) ? "WARNING" : "CRITICAL", cn, timestamp); if (days_left > days_till_exp_crit) status = STATE_WARNING; else @@ -309,22 +294,21 @@ int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int } X509_free(certificate); return status; -# else /* ifndef USE_OPENSSL */ +# else /* ifndef USE_OPENSSL */ printf("%s\n", _("WARNING - Plugin does not support checking certificates.")); return STATE_WARNING; -# endif /* USE_OPENSSL */ +# endif /* USE_OPENSSL */ } -int np_net_ssl_check_cert(int days_till_exp_warn, int days_till_exp_crit){ -# ifdef 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 */ + 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 /* USE_OPENSSL */ } - #endif /* HAVE_SSL */ -- cgit v0.10-9-g596f From d32adb6697a8c8c8b9df235a382316f8302df87a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:32:43 +0100 Subject: sslutils.c: update copyright diff --git a/plugins/sslutils.c b/plugins/sslutils.c index b8cbc7c..3c92841 100644 --- a/plugins/sslutils.c +++ b/plugins/sslutils.c @@ -3,7 +3,7 @@ * Monitoring Plugins SSL utilities * * License: GPL - * Copyright (c) 2005-2010 Monitoring Plugins Development Team + * Copyright (c) 2005-2024 Monitoring Plugins Development Team * * Description: * -- cgit v0.10-9-g596f From cadc94074bba0c181ddda678e989ca3b8be8dce5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:33:04 +0100 Subject: urlize.c: clang-format diff --git a/plugins/urlize.c b/plugins/urlize.c index 6fda72d..b9cc1c8 100644 --- a/plugins/urlize.c +++ b/plugins/urlize.c @@ -1,33 +1,33 @@ /***************************************************************************** -* -* Monitoring urlize plugin -* -* License: GPL -* Copyright (c) 2000-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the urlize plugin -* -* This plugin wraps the text output of another command (plugin) in HTML -* tags. This plugin returns the status of the invoked plugin. -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring urlize plugin + * + * License: GPL + * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the urlize plugin + * + * This plugin wraps the text output of another command (plugin) in HTML + * tags. This plugin returns the status of the invoked plugin. + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "urlize"; const char *copyright = "2000-2006"; @@ -37,15 +37,13 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #include "popen.h" -#define PERF_CHARACTER "|" +#define PERF_CHARACTER "|" #define NEWLINE_CHARACTER '\n' -void print_help (void); -void print_usage (void); +void print_help(void); +void print_usage(void); -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { int found = 0, result = STATE_UNKNOWN; char *url = NULL; char *cmd; @@ -56,79 +54,72 @@ main (int argc, char **argv) int c; int option = 0; static struct option longopts[] = { - {"help", no_argument, 0, 'h'}, - {"version", no_argument, 0, 'V'}, - {"url", required_argument, 0, 'u'}, - {0, 0, 0, 0} - }; + {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'}, {"url", required_argument, 0, 'u'}, {0, 0, 0, 0}}; - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Need at least 2 args */ if (argc < 3) { print_help(); - exit (STATE_UNKNOWN); + exit(STATE_UNKNOWN); } while (1) { - c = getopt_long (argc, argv, "+hVu:", longopts, &option); + c = getopt_long(argc, argv, "+hVu:", longopts, &option); if (c == -1 || c == EOF) break; switch (c) { - case 'h': /* help */ - print_help (); - exit (EXIT_SUCCESS); + case 'h': /* help */ + print_help(); + exit(EXIT_SUCCESS); break; - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (EXIT_SUCCESS); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(EXIT_SUCCESS); break; case 'u': - url = strdup (argv[optind]); + url = strdup(argv[optind]); break; case '?': default: - usage5 (); + usage5(); } } if (url == NULL) - url = strdup (argv[optind++]); + url = strdup(argv[optind++]); - cmd = strdup (argv[optind++]); + cmd = strdup(argv[optind++]); for (c = optind; c < argc; c++) { - xasprintf (&cmd, "%s %s", cmd, argv[c]); + xasprintf(&cmd, "%s %s", cmd, argv[c]); } - child_process = spopen (cmd); + child_process = spopen(cmd); if (child_process == NULL) { - printf (_("Could not open pipe: %s\n"), cmd); - exit (STATE_UNKNOWN); + printf(_("Could not open pipe: %s\n"), cmd); + exit(STATE_UNKNOWN); } - child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r"); + child_stderr = fdopen(child_stderr_array[fileno(child_process)], "r"); if (child_stderr == NULL) { - printf (_("Could not open stderr for %s\n"), cmd); + printf(_("Could not open stderr for %s\n"), cmd); } bzero(tstr, sizeof(tstr)); buf = malloc(MAX_INPUT_BUFFER); - printf ("", argv[1]); - while (fgets (buf, MAX_INPUT_BUFFER - 1, child_process)) { + printf("", argv[1]); + while (fgets(buf, MAX_INPUT_BUFFER - 1, child_process)) { found++; /* Collect the string in temp str so we can tokenize */ strcat(tstr, buf); } if (!found) - die (STATE_UNKNOWN, - _("%s UNKNOWN - No data received from host\nCMD: %s\n"), - argv[0], cmd); - + die(STATE_UNKNOWN, _("%s UNKNOWN - No data received from host\nCMD: %s\n"), argv[0], cmd); /* chop the newline character */ if ((nstr = strchr(tstr, NEWLINE_CHARACTER)) != NULL) @@ -136,63 +127,55 @@ main (int argc, char **argv) /* tokenize the string for Perfdata if there is some */ nstr = strtok(tstr, PERF_CHARACTER); - printf ("%s", nstr); - printf (""); + printf("%s", nstr); + printf(""); nstr = strtok(NULL, PERF_CHARACTER); if (nstr != NULL) - printf (" | %s", nstr); + printf(" | %s", nstr); /* close the pipe */ - result = spclose (child_process); + result = spclose(child_process); /* WARNING if output found on stderr */ - if (fgets (buf, MAX_INPUT_BUFFER - 1, child_stderr)) - result = max_state (result, STATE_WARNING); + if (fgets(buf, MAX_INPUT_BUFFER - 1, child_stderr)) + result = max_state(result, STATE_WARNING); /* close stderr */ - (void) fclose (child_stderr); + (void)fclose(child_stderr); return result; } +void print_help(void) { + print_revision(progname, NP_VERSION); + printf("Copyright (c) 2000 Karl DeBisschop \n"); + printf(COPYRIGHT, copyright, email); -void -print_help (void) -{ - print_revision (progname, NP_VERSION); - - printf ("Copyright (c) 2000 Karl DeBisschop \n"); - printf (COPYRIGHT, copyright, email); - - printf ("%s\n", _("This plugin wraps the text output of another command (plugin) in HTML ")); - printf ("%s\n", _("tags, thus displaying the child plugin's output as a clickable link in compatible")); - printf ("%s\n", _("monitoring status screen. This plugin returns the status of the invoked plugin.")); + printf("%s\n", _("This plugin wraps the text output of another command (plugin) in HTML ")); + printf("%s\n", _("tags, thus displaying the child plugin's output as a clickable link in compatible")); + printf("%s\n", _("monitoring status screen. This plugin returns the status of the invoked plugin.")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (UT_HELP_VRSN); + printf(UT_HELP_VRSN); - printf ("\n"); - printf ("%s\n", _("Examples:")); - printf ("%s\n", _("Pay close attention to quoting to ensure that the shell passes the expected")); - printf ("%s\n\n", _("data to the plugin. For example, in:")); - printf (" %s\n\n", _("urlize http://example.com/ check_http -H example.com -r 'two words'")); - printf (" %s\n", _("the shell will remove the single quotes and urlize will see:")); - printf (" %s\n\n", _("urlize http://example.com/ check_http -H example.com -r two words")); - printf (" %s\n\n", _("You probably want:")); - printf (" %s\n", _("urlize http://example.com/ \"check_http -H example.com -r 'two words'\"")); + printf("\n"); + printf("%s\n", _("Examples:")); + printf("%s\n", _("Pay close attention to quoting to ensure that the shell passes the expected")); + printf("%s\n\n", _("data to the plugin. For example, in:")); + printf(" %s\n\n", _("urlize http://example.com/ check_http -H example.com -r 'two words'")); + printf(" %s\n", _("the shell will remove the single quotes and urlize will see:")); + printf(" %s\n\n", _("urlize http://example.com/ check_http -H example.com -r two words")); + printf(" %s\n\n", _("You probably want:")); + printf(" %s\n", _("urlize http://example.com/ \"check_http -H example.com -r 'two words'\"")); - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s ... \n", progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s ... \n", progname); } -- cgit v0.10-9-g596f From 9c9d7a0d43e4271ad701f080bb4e25a38d6556d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:33:47 +0100 Subject: urlize.c: update copyright diff --git a/plugins/urlize.c b/plugins/urlize.c index b9cc1c8..218233f 100644 --- a/plugins/urlize.c +++ b/plugins/urlize.c @@ -3,7 +3,7 @@ * Monitoring urlize plugin * * License: GPL - * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * -- cgit v0.10-9-g596f From dde0e519ff69a4c6b17c17d62df8f90be70b86ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:34:06 +0100 Subject: plugins/utils.c: clang-format diff --git a/plugins/utils.c b/plugins/utils.c index 77d6a6f..1b88fa7 100644 --- a/plugins/utils.c +++ b/plugins/utils.c @@ -1,26 +1,26 @@ /***************************************************************************** -* -* Library of useful functions for plugins -* -* License: GPL -* Copyright (c) 2000 Karl DeBisschop (karl@debisschop.net) -* Copyright (c) 2002-2007 Monitoring Plugins Development Team -* -* 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 . -* -* -*****************************************************************************/ + * + * Library of useful functions for plugins + * + * License: GPL + * Copyright (c) 2000 Karl DeBisschop (karl@debisschop.net) + * Copyright (c) 2002-2007 Monitoring Plugins Development Team + * + * 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 . + * + * + *****************************************************************************/ #include "common.h" #include "./utils.h" @@ -34,7 +34,7 @@ #include -extern void print_usage (void); +extern void print_usage(void); extern const char *progname; #define STRLEN 64 @@ -50,9 +50,7 @@ time_t start_time, end_time; * Note that numerically the above does not hold ****************************************************************************/ -int -max_state (int a, int b) -{ +int max_state(int a, int b) { if (a == STATE_CRITICAL || b == STATE_CRITICAL) return STATE_CRITICAL; else if (a == STATE_WARNING || b == STATE_WARNING) @@ -64,7 +62,7 @@ max_state (int a, int b) else if (a == STATE_DEPENDENT || b == STATE_DEPENDENT) return STATE_DEPENDENT; else - return max (a, b); + return max(a, b); } /* ************************************************************************** @@ -77,9 +75,7 @@ max_state (int a, int b) * non-OK state. ****************************************************************************/ -int -max_state_alt (int a, int b) -{ +int max_state_alt(int a, int b) { if (a == STATE_CRITICAL || b == STATE_CRITICAL) return STATE_CRITICAL; else if (a == STATE_WARNING || b == STATE_WARNING) @@ -91,124 +87,112 @@ max_state_alt (int a, int b) else if (a == STATE_OK || b == STATE_OK) return STATE_OK; else - return max (a, b); + return max(a, b); } -void usage (const char *msg) -{ - printf ("%s\n", msg); - print_usage (); - exit (STATE_UNKNOWN); +void usage(const char *msg) { + printf("%s\n", msg); + print_usage(); + exit(STATE_UNKNOWN); } -void usage_va (const char *fmt, ...) -{ +void usage_va(const char *fmt, ...) { va_list ap; printf("%s: ", progname); va_start(ap, fmt); vprintf(fmt, ap); va_end(ap); printf("\n"); - exit (STATE_UNKNOWN); + exit(STATE_UNKNOWN); } -void usage2(const char *msg, const char *arg) -{ - printf ("%s: %s - %s\n", progname, msg, arg?arg:"(null)" ); - print_usage (); - exit (STATE_UNKNOWN); +void usage2(const char *msg, const char *arg) { + printf("%s: %s - %s\n", progname, msg, arg ? arg : "(null)"); + print_usage(); + exit(STATE_UNKNOWN); } -void -usage3 (const char *msg, int arg) -{ - printf ("%s: %s - %c\n", progname, msg, arg); +void usage3(const char *msg, int arg) { + printf("%s: %s - %c\n", progname, msg, arg); print_usage(); - exit (STATE_UNKNOWN); + exit(STATE_UNKNOWN); } -void -usage4 (const char *msg) -{ - printf ("%s: %s\n", progname, msg); +void usage4(const char *msg) { + printf("%s: %s\n", progname, msg); print_usage(); - exit (STATE_UNKNOWN); + exit(STATE_UNKNOWN); } -void -usage5 (void) -{ +void usage5(void) { print_usage(); - exit (STATE_UNKNOWN); + exit(STATE_UNKNOWN); } -void -print_revision (const char *command_name, const char *revision) -{ - printf ("%s v%s (%s %s)\n", - command_name, revision, PACKAGE, VERSION); +void print_revision(const char *command_name, const char *revision) { + printf("%s v%s (%s %s)\n", command_name, revision, PACKAGE, VERSION); } -bool is_numeric (char *number) { +bool is_numeric(char *number) { char tmp[1]; float x; if (!number) return false; - else if (sscanf (number, "%f%c", &x, tmp) == 1) + else if (sscanf(number, "%f%c", &x, tmp) == 1) return true; else return false; } -bool is_positive (char *number) { - if (is_numeric (number) && atof (number) > 0.0) +bool is_positive(char *number) { + if (is_numeric(number) && atof(number) > 0.0) return true; else return false; } -bool is_negative (char *number) { - if (is_numeric (number) && atof (number) < 0.0) +bool is_negative(char *number) { + if (is_numeric(number) && atof(number) < 0.0) return true; else return false; } -bool is_nonnegative (char *number) { - if (is_numeric (number) && atof (number) >= 0.0) +bool is_nonnegative(char *number) { + if (is_numeric(number) && atof(number) >= 0.0) return true; else return false; } -bool is_percentage (char *number) { +bool is_percentage(char *number) { int x; - if (is_numeric (number) && (x = atof (number)) >= 0 && x <= 100) + if (is_numeric(number) && (x = atof(number)) >= 0 && x <= 100) return true; else return false; } -bool is_percentage_expression (const char str[]) { +bool is_percentage_expression(const char str[]) { if (!str) { return false; } size_t len = strlen(str); - if (str[len-1] != '%') { + if (str[len - 1] != '%') { return false; } char *foo = calloc(sizeof(char), len + 1); if (!foo) { - die (STATE_UNKNOWN, _("calloc failed \n")); + die(STATE_UNKNOWN, _("calloc failed \n")); } strcpy(foo, str); - foo[len-1] = '\0'; + foo[len - 1] = '\0'; bool result = is_numeric(foo); @@ -217,13 +201,13 @@ bool is_percentage_expression (const char str[]) { return result; } -bool is_integer (char *number) { +bool is_integer(char *number) { long int n; - if (!number || (strspn (number, "-0123456789 ") != strlen (number))) + if (!number || (strspn(number, "-0123456789 ") != strlen(number))) return false; - n = strtol (number, NULL, 10); + n = strtol(number, NULL, 10); if (errno != ERANGE && n >= INT_MIN && n <= INT_MAX) return true; @@ -231,22 +215,22 @@ bool is_integer (char *number) { return false; } -bool is_intpos (char *number) { - if (is_integer (number) && atoi (number) > 0) +bool is_intpos(char *number) { + if (is_integer(number) && atoi(number) > 0) return true; else return false; } -bool is_intneg (char *number) { - if (is_integer (number) && atoi (number) < 0) +bool is_intneg(char *number) { + if (is_integer(number) && atoi(number) < 0) return true; else return false; } -bool is_intnonneg (char *number) { - if (is_integer (number) && atoi (number) >= 0) +bool is_intnonneg(char *number) { + if (is_integer(number) && atoi(number) >= 0) return true; else return false; @@ -259,7 +243,7 @@ bool is_intnonneg (char *number) { */ bool is_int64(char *number, int64_t *target) { errno = 0; - char *endptr = { 0 }; + char *endptr = {0}; int64_t tmp = strtoll(number, &endptr, 10); if (errno != 0) { @@ -287,7 +271,7 @@ bool is_int64(char *number, int64_t *target) { */ bool is_uint64(char *number, uint64_t *target) { errno = 0; - char *endptr = { 0 }; + char *endptr = {0}; unsigned long long tmp = strtoull(number, &endptr, 10); if (errno != 0) { @@ -309,66 +293,50 @@ bool is_uint64(char *number, uint64_t *target) { return true; } -bool is_intpercent (char *number) { +bool is_intpercent(char *number) { int i; - if (is_integer (number) && (i = atoi (number)) >= 0 && i <= 100) + if (is_integer(number) && (i = atoi(number)) >= 0 && i <= 100) return true; else return false; } -bool is_option (char *str) { +bool is_option(char *str) { if (!str) return false; - else if (strspn (str, "-") == 1 || strspn (str, "-") == 2) + else if (strspn(str, "-") == 1 || strspn(str, "-") == 2) return true; else return false; } #ifdef NEED_GETTIMEOFDAY -int -gettimeofday (struct timeval *tv, struct timezone *tz) -{ +int gettimeofday(struct timeval *tv, struct timezone *tz) { tv->tv_usec = 0; - tv->tv_sec = (long) time ((time_t) 0); + tv->tv_sec = (long)time((time_t)0); } #endif - - -double -delta_time (struct timeval tv) -{ +double delta_time(struct timeval tv) { struct timeval now; - gettimeofday (&now, NULL); + gettimeofday(&now, NULL); return ((double)(now.tv_sec - tv.tv_sec) + (double)(now.tv_usec - tv.tv_usec) / (double)1000000); } - - -long -deltime (struct timeval tv) -{ +long deltime(struct timeval tv) { struct timeval now; - gettimeofday (&now, NULL); - return (now.tv_sec - tv.tv_sec)*1000000 + now.tv_usec - tv.tv_usec; + gettimeofday(&now, NULL); + return (now.tv_sec - tv.tv_sec) * 1000000 + now.tv_usec - tv.tv_usec; } - - - -void -strip (char *buffer) -{ +void strip(char *buffer) { size_t x; int i; - for (x = strlen (buffer); x >= 1; x--) { + for (x = strlen(buffer); x >= 1; x--) { i = x - 1; - if (buffer[i] == ' ' || - buffer[i] == '\r' || buffer[i] == '\n' || buffer[i] == '\t') + if (buffer[i] == ' ' || buffer[i] == '\r' || buffer[i] == '\n' || buffer[i] == '\t') buffer[i] = '\0'; else break; @@ -376,7 +344,6 @@ strip (char *buffer) return; } - /****************************************************************************** * * Copies one string to another. Any previously existing data in @@ -389,19 +356,15 @@ strip (char *buffer) * *****************************************************************************/ -char * -strscpy (char *dest, const char *src) -{ +char *strscpy(char *dest, const char *src) { if (src == NULL) return NULL; - xasprintf (&dest, "%s", src); + xasprintf(&dest, "%s", src); return dest; } - - /****************************************************************************** * * Returns a pointer to the next line of a multiline string buffer @@ -418,7 +381,7 @@ strscpy (char *dest, const char *src) * This * is * a - * + * * multiline string buffer * ============================== * @@ -431,7 +394,7 @@ strscpy (char *dest, const char *src) * printf("%d %s",i++,firstword(ptr)); * ptr = strnl(ptr); * } - * + * * Produces the following: * * 1 This @@ -452,25 +415,22 @@ strscpy (char *dest, const char *src) * *****************************************************************************/ -char * -strnl (char *str) -{ +char *strnl(char *str) { size_t len; if (str == NULL) return NULL; - str = strpbrk (str, "\r\n"); + str = strpbrk(str, "\r\n"); if (str == NULL) return NULL; - len = strspn (str, "\r\n"); + len = strspn(str, "\r\n"); if (str[len] == '\0') return NULL; str += len; - if (strlen (str) == 0) + if (strlen(str) == 0) return NULL; return str; } - /****************************************************************************** * * Like strscpy, except only the portion of the source string up to @@ -487,29 +447,25 @@ strnl (char *str) * *****************************************************************************/ -char * -strpcpy (char *dest, const char *src, const char *str) -{ +char *strpcpy(char *dest, const char *src, const char *str) { size_t len; if (src) - len = strcspn (src, str); + len = strcspn(src, str); else return NULL; - if (dest == NULL || strlen (dest) < len) - dest = realloc (dest, len + 1); + if (dest == NULL || strlen(dest) < len) + dest = realloc(dest, len + 1); if (dest == NULL) - die (STATE_UNKNOWN, _("failed realloc in strpcpy\n")); + die(STATE_UNKNOWN, _("failed realloc in strpcpy\n")); - strncpy (dest, src, len); + strncpy(dest, src, len); dest[len] = '\0'; return dest; } - - /****************************************************************************** * * Like strscat, except only the portion of the source string up to @@ -518,62 +474,54 @@ strpcpy (char *dest, const char *src, const char *str) * str = strpcpy(str,"This is a line of text with no trailing newline","x"); * str = strpcat(str,"This is a line of text with no trailing newline","x"); * printf("%s\n",str); - * + * *This is a line of texThis is a line of tex * *****************************************************************************/ -char * -strpcat (char *dest, const char *src, const char *str) -{ +char *strpcat(char *dest, const char *src, const char *str) { size_t len, l2; if (dest) - len = strlen (dest); + len = strlen(dest); else len = 0; if (src) { - l2 = strcspn (src, str); - } - else { + l2 = strcspn(src, str); + } else { return dest; } - dest = realloc (dest, len + l2 + 1); + dest = realloc(dest, len + l2 + 1); if (dest == NULL) - die (STATE_UNKNOWN, _("failed malloc in strscat\n")); + die(STATE_UNKNOWN, _("failed malloc in strscat\n")); - strncpy (dest + len, src, l2); + strncpy(dest + len, src, l2); dest[len + l2] = '\0'; return dest; } - /****************************************************************************** * * asprintf, but die on failure * ******************************************************************************/ -int -xvasprintf (char **strp, const char *fmt, va_list ap) -{ - int result = vasprintf (strp, fmt, ap); +int xvasprintf(char **strp, const char *fmt, va_list ap) { + int result = vasprintf(strp, fmt, ap); if (result == -1 || *strp == NULL) - die (STATE_UNKNOWN, _("failed malloc in xvasprintf\n")); + die(STATE_UNKNOWN, _("failed malloc in xvasprintf\n")); return result; } -int -xasprintf (char **strp, const char *fmt, ...) -{ +int xasprintf(char **strp, const char *fmt, ...) { va_list ap; int result; - va_start (ap, fmt); - result = xvasprintf (strp, fmt, ap); - va_end (ap); + va_start(ap, fmt); + result = xvasprintf(strp, fmt, ap); + va_end(ap); return result; } @@ -583,247 +531,192 @@ xasprintf (char **strp, const char *fmt, ...) * ******************************************************************************/ -char *perfdata (const char *label, - long int val, - const char *uom, - int warnp, - long int warn, - int critp, - long int crit, - int minp, - long int minv, - int maxp, - long int maxv) -{ +char *perfdata(const char *label, long int val, const char *uom, int warnp, long int warn, int critp, long int crit, int minp, + long int minv, int maxp, long int maxv) { char *data = NULL; - if (strpbrk (label, "'= ")) - xasprintf (&data, "'%s'=%ld%s;", label, val, uom); + if (strpbrk(label, "'= ")) + xasprintf(&data, "'%s'=%ld%s;", label, val, uom); else - xasprintf (&data, "%s=%ld%s;", label, val, uom); + xasprintf(&data, "%s=%ld%s;", label, val, uom); if (warnp) - xasprintf (&data, "%s%ld;", data, warn); + xasprintf(&data, "%s%ld;", data, warn); else - xasprintf (&data, "%s;", data); + xasprintf(&data, "%s;", data); if (critp) - xasprintf (&data, "%s%ld;", data, crit); + xasprintf(&data, "%s%ld;", data, crit); else - xasprintf (&data, "%s;", data); + xasprintf(&data, "%s;", data); if (minp) - xasprintf (&data, "%s%ld;", data, minv); + xasprintf(&data, "%s%ld;", data, minv); else - xasprintf (&data, "%s;", data); + xasprintf(&data, "%s;", data); if (maxp) - xasprintf (&data, "%s%ld", data, maxv); + xasprintf(&data, "%s%ld", data, maxv); return data; } - -char *perfdata_uint64 (const char *label, - uint64_t val, - const char *uom, - int warnp, /* Warning present */ - uint64_t warn, - int critp, /* Critical present */ - uint64_t crit, - int minp, /* Minimum present */ - uint64_t minv, - int maxp, /* Maximum present */ - uint64_t maxv) -{ +char *perfdata_uint64(const char *label, uint64_t val, const char *uom, int warnp, /* Warning present */ + uint64_t warn, int critp, /* Critical present */ + uint64_t crit, int minp, /* Minimum present */ + uint64_t minv, int maxp, /* Maximum present */ + uint64_t maxv) { char *data = NULL; - if (strpbrk (label, "'= ")) - xasprintf (&data, "'%s'=%" PRIu64 "%s;", label, val, uom); + if (strpbrk(label, "'= ")) + xasprintf(&data, "'%s'=%" PRIu64 "%s;", label, val, uom); else - xasprintf (&data, "%s=%" PRIu64 "%s;", label, val, uom); + xasprintf(&data, "%s=%" PRIu64 "%s;", label, val, uom); if (warnp) - xasprintf (&data, "%s%" PRIu64 ";", data, warn); + xasprintf(&data, "%s%" PRIu64 ";", data, warn); else - xasprintf (&data, "%s;", data); + xasprintf(&data, "%s;", data); if (critp) - xasprintf (&data, "%s%" PRIu64 ";", data, crit); + xasprintf(&data, "%s%" PRIu64 ";", data, crit); else - xasprintf (&data, "%s;", data); + xasprintf(&data, "%s;", data); if (minp) - xasprintf (&data, "%s%" PRIu64 ";", data, minv); + xasprintf(&data, "%s%" PRIu64 ";", data, minv); else - xasprintf (&data, "%s;", data); + xasprintf(&data, "%s;", data); if (maxp) - xasprintf (&data, "%s%" PRIu64, data, maxv); + xasprintf(&data, "%s%" PRIu64, data, maxv); return data; } - -char *perfdata_int64 (const char *label, - int64_t val, - const char *uom, - int warnp, /* Warning present */ - int64_t warn, - int critp, /* Critical present */ - int64_t crit, - int minp, /* Minimum present */ - int64_t minv, - int maxp, /* Maximum present */ - int64_t maxv) -{ +char *perfdata_int64(const char *label, int64_t val, const char *uom, int warnp, /* Warning present */ + int64_t warn, int critp, /* Critical present */ + int64_t crit, int minp, /* Minimum present */ + int64_t minv, int maxp, /* Maximum present */ + int64_t maxv) { char *data = NULL; - if (strpbrk (label, "'= ")) - xasprintf (&data, "'%s'=%" PRId64 "%s;", label, val, uom); + if (strpbrk(label, "'= ")) + xasprintf(&data, "'%s'=%" PRId64 "%s;", label, val, uom); else - xasprintf (&data, "%s=%" PRId64 "%s;", label, val, uom); + xasprintf(&data, "%s=%" PRId64 "%s;", label, val, uom); if (warnp) - xasprintf (&data, "%s%" PRId64 ";", data, warn); + xasprintf(&data, "%s%" PRId64 ";", data, warn); else - xasprintf (&data, "%s;", data); + xasprintf(&data, "%s;", data); if (critp) - xasprintf (&data, "%s%" PRId64 ";", data, crit); + xasprintf(&data, "%s%" PRId64 ";", data, crit); else - xasprintf (&data, "%s;", data); + xasprintf(&data, "%s;", data); if (minp) - xasprintf (&data, "%s%" PRId64 ";", data, minv); + xasprintf(&data, "%s%" PRId64 ";", data, minv); else - xasprintf (&data, "%s;", data); + xasprintf(&data, "%s;", data); if (maxp) - xasprintf (&data, "%s%" PRId64, data, maxv); + xasprintf(&data, "%s%" PRId64, data, maxv); return data; } - -char *fperfdata (const char *label, - double val, - const char *uom, - int warnp, - double warn, - int critp, - double crit, - int minp, - double minv, - int maxp, - double maxv) -{ +char *fperfdata(const char *label, double val, const char *uom, int warnp, double warn, int critp, double crit, int minp, double minv, + int maxp, double maxv) { char *data = NULL; - if (strpbrk (label, "'= ")) - xasprintf (&data, "'%s'=", label); + if (strpbrk(label, "'= ")) + xasprintf(&data, "'%s'=", label); else - xasprintf (&data, "%s=", label); + xasprintf(&data, "%s=", label); - xasprintf (&data, "%s%f", data, val); - xasprintf (&data, "%s%s;", data, uom); + xasprintf(&data, "%s%f", data, val); + xasprintf(&data, "%s%s;", data, uom); if (warnp) - xasprintf (&data, "%s%f", data, warn); + xasprintf(&data, "%s%f", data, warn); - xasprintf (&data, "%s;", data); + xasprintf(&data, "%s;", data); if (critp) - xasprintf (&data, "%s%f", data, crit); + xasprintf(&data, "%s%f", data, crit); - xasprintf (&data, "%s;", data); + xasprintf(&data, "%s;", data); if (minp) - xasprintf (&data, "%s%f", data, minv); + xasprintf(&data, "%s%f", data, minv); if (maxp) { - xasprintf (&data, "%s;", data); - xasprintf (&data, "%s%f", data, maxv); + xasprintf(&data, "%s;", data); + xasprintf(&data, "%s%f", data, maxv); } return data; } -char *sperfdata (const char *label, - double val, - const char *uom, - char *warn, - char *crit, - int minp, - double minv, - int maxp, - double maxv) -{ +char *sperfdata(const char *label, double val, const char *uom, char *warn, char *crit, int minp, double minv, int maxp, double maxv) { char *data = NULL; - if (strpbrk (label, "'= ")) - xasprintf (&data, "'%s'=", label); + if (strpbrk(label, "'= ")) + xasprintf(&data, "'%s'=", label); else - xasprintf (&data, "%s=", label); + xasprintf(&data, "%s=", label); - xasprintf (&data, "%s%f", data, val); - xasprintf (&data, "%s%s;", data, uom); + xasprintf(&data, "%s%f", data, val); + xasprintf(&data, "%s%s;", data, uom); - if (warn!=NULL) - xasprintf (&data, "%s%s", data, warn); + if (warn != NULL) + xasprintf(&data, "%s%s", data, warn); - xasprintf (&data, "%s;", data); + xasprintf(&data, "%s;", data); - if (crit!=NULL) - xasprintf (&data, "%s%s", data, crit); + if (crit != NULL) + xasprintf(&data, "%s%s", data, crit); - xasprintf (&data, "%s;", data); + xasprintf(&data, "%s;", data); if (minp) - xasprintf (&data, "%s%f", data, minv); + xasprintf(&data, "%s%f", data, minv); if (maxp) { - xasprintf (&data, "%s;", data); - xasprintf (&data, "%s%f", data, maxv); + xasprintf(&data, "%s;", data); + xasprintf(&data, "%s%f", data, maxv); } return data; } -char *sperfdata_int (const char *label, - int val, - const char *uom, - char *warn, - char *crit, - int minp, - int minv, - int maxp, - int maxv) -{ +char *sperfdata_int(const char *label, int val, const char *uom, char *warn, char *crit, int minp, int minv, int maxp, int maxv) { char *data = NULL; - if (strpbrk (label, "'= ")) - xasprintf (&data, "'%s'=", label); + if (strpbrk(label, "'= ")) + xasprintf(&data, "'%s'=", label); else - xasprintf (&data, "%s=", label); + xasprintf(&data, "%s=", label); - xasprintf (&data, "%s%d", data, val); - xasprintf (&data, "%s%s;", data, uom); + xasprintf(&data, "%s%d", data, val); + xasprintf(&data, "%s%s;", data, uom); - if (warn!=NULL) - xasprintf (&data, "%s%s", data, warn); + if (warn != NULL) + xasprintf(&data, "%s%s", data, warn); - xasprintf (&data, "%s;", data); + xasprintf(&data, "%s;", data); - if (crit!=NULL) - xasprintf (&data, "%s%s", data, crit); + if (crit != NULL) + xasprintf(&data, "%s%s", data, crit); - xasprintf (&data, "%s;", data); + xasprintf(&data, "%s;", data); if (minp) - xasprintf (&data, "%s%d", data, minv); + xasprintf(&data, "%s%d", data, minv); if (maxp) { - xasprintf (&data, "%s;", data); - xasprintf (&data, "%s%d", data, maxv); + xasprintf(&data, "%s;", data); + xasprintf(&data, "%s%d", data, maxv); } return data; -- cgit v0.10-9-g596f From 08d9932c137301aa2bdb6f6f30ff7cbeacaccbb3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:35:09 +0100 Subject: plugins/utils.c: update copyright diff --git a/plugins/utils.c b/plugins/utils.c index 1b88fa7..f11db73 100644 --- a/plugins/utils.c +++ b/plugins/utils.c @@ -4,7 +4,7 @@ * * License: GPL * Copyright (c) 2000 Karl DeBisschop (karl@debisschop.net) - * Copyright (c) 2002-2007 Monitoring Plugins Development Team + * Copyright (c) 2002-2024 Monitoring Plugins Development Team * * 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 -- cgit v0.10-9-g596f From bb6e5dac7bccc1ff6b40fdcaf9dea4f11fe4b797 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:35:42 +0100 Subject: check_ide_smart: clang-format again diff --git a/plugins/check_ide_smart.c b/plugins/check_ide_smart.c index cfc7908..381dbd8 100644 --- a/plugins/check_ide_smart.c +++ b/plugins/check_ide_smart.c @@ -118,15 +118,16 @@ struct { char *text; } -static offline_status_text[] = {{0x00, "NeverStarted"}, {0x02, "Completed"}, {0x04, "Suspended"}, {0x05, "Aborted"}, {0x06, "Failed"}, {0, 0}}; +static offline_status_text[] = {{0x00, "NeverStarted"}, {0x02, "Completed"}, {0x04, "Suspended"}, + {0x05, "Aborted"}, {0x06, "Failed"}, {0, 0}}; static struct { __u8 value; char *text; } smart_command[] = {{SMART_ENABLE, "SMART_ENABLE"}, - {SMART_DISABLE, "SMART_DISABLE"}, - {SMART_IMMEDIATE_OFFLINE, "SMART_IMMEDIATE_OFFLINE"}, - {SMART_AUTO_OFFLINE, "SMART_AUTO_OFFLINE"}}; + {SMART_DISABLE, "SMART_DISABLE"}, + {SMART_IMMEDIATE_OFFLINE, "SMART_IMMEDIATE_OFFLINE"}, + {SMART_AUTO_OFFLINE, "SMART_AUTO_OFFLINE"}}; /* Index to smart_command table, keep in order */ enum SmartCommand { -- cgit v0.10-9-g596f From e3348570d177e333f79e6dc56389ec4871f95cba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:38:33 +0100 Subject: check_nwstat: clang-format diff --git a/plugins/check_nwstat.c b/plugins/check_nwstat.c index 10c493b..cb708df 100644 --- a/plugins/check_nwstat.c +++ b/plugins/check_nwstat.c @@ -1,33 +1,33 @@ /***************************************************************************** -* -* Monitoring check_nwstat plugin -* -* License: GPL -* Copyright (c) 2000-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_nwstat plugin -* -* This plugin attempts to contact the MRTGEXT NLM running on a -* Novell server to gather the requested system information. -* -* -* 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_nwstat plugin + * + * License: GPL + * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_nwstat plugin + * + * This plugin attempts to contact the MRTGEXT NLM running on a + * Novell server to gather the requested system information. + * + * + * 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_nwstat"; const char *copyright = "2000-2007"; @@ -44,10 +44,10 @@ enum checkvar { LOAD15, /* check 15 minute CPU load */ CONNS, /* check number of connections */ VPF, /* check % free space on volume */ - VMF, /* check MB free space on volume */ - VMU, /* check MB used space on volume */ - VPU, /* check % used space on volume */ - VMP, /* check MB purgeable space on volume */ + VMF, /* check MB free space on volume */ + VMU, /* check MB used space on volume */ + VPU, /* check % used space on volume */ + VMP, /* check MB purgeable space on volume */ VKF, /* check KB free space on volume */ LTCH, /* check long-term cache hit percentage */ CBUFF, /* check total cache buffers */ @@ -55,7 +55,7 @@ enum checkvar { LRUM, /* check LRU sitting time in minutes */ DSDB, /* check to see if DS Database is open */ LOGINS, /* check to see if logins are enabled */ - NRMH, /* check to see NRM Health Status */ + NRMH, /* check to see NRM Health Status */ PUPRB, /* check % of used packet receive buffers */ UPRB, /* check used packet receive buffers */ SAPENTRIES, /* check SAP entries */ @@ -73,8 +73,8 @@ enum checkvar { DSVER, /* check NDS version */ UPTIME, /* check server uptime */ NLM, /* check NLM loaded */ - NRMP, /* check NRM Process Values */ - NRMM, /* check NRM Memory Values */ + NRMP, /* check NRM Process Values */ + NRMM, /* check NRM Memory Values */ NRMS, /* check NRM Values */ NSS1, /* check Statistics from _Admin:Manage_NSS\GeneralStats.xml */ NSS2, /* check Statistics from _Admin:Manage_NSS\BufferCache.xml */ @@ -89,1652 +89,1439 @@ enum { PORT = 9999 }; -char *server_address=NULL; -char *volume_name=NULL; -char *nlm_name=NULL; -char *nrmp_name=NULL; -char *nrmm_name=NULL; -char *nrms_name=NULL; -char *nss1_name=NULL; -char *nss2_name=NULL; -char *nss3_name=NULL; -char *nss4_name=NULL; -char *nss5_name=NULL; -char *nss6_name=NULL; -char *nss7_name=NULL; -int server_port=PORT; -unsigned long warning_value=0L; -unsigned long critical_value=0L; +char *server_address = NULL; +char *volume_name = NULL; +char *nlm_name = NULL; +char *nrmp_name = NULL; +char *nrmm_name = NULL; +char *nrms_name = NULL; +char *nss1_name = NULL; +char *nss2_name = NULL; +char *nss3_name = NULL; +char *nss4_name = NULL; +char *nss5_name = NULL; +char *nss6_name = NULL; +char *nss7_name = NULL; +int server_port = PORT; +unsigned long warning_value = 0L; +unsigned long critical_value = 0L; bool check_warning_value = false; bool check_critical_value = false; bool check_netware_version = false; enum checkvar vars_to_check = NONE; -int sap_number=-1; +int sap_number = -1; int process_arguments(int, char **); void print_help(void); void print_usage(void); - - -int -main(int argc, char **argv) { +int main(int argc, char **argv) { int result = STATE_UNKNOWN; int sd; - char *send_buffer=NULL; + char *send_buffer = NULL; char recv_buffer[MAX_INPUT_BUFFER]; - char *output_message=NULL; - char *temp_buffer=NULL; - char *netware_version=NULL; - - int time_sync_status=0; - int nrm_health_status=0; - unsigned long total_cache_buffers=0; - unsigned long dirty_cache_buffers=0; - unsigned long open_files=0; - unsigned long abended_threads=0; - unsigned long max_service_processes=0; - unsigned long current_service_processes=0; - unsigned long free_disk_space=0L; - unsigned long nrmp_value=0L; - unsigned long nrmm_value=0L; - unsigned long nrms_value=0L; - unsigned long nss1_value=0L; - unsigned long nss2_value=0L; - unsigned long nss3_value=0L; - unsigned long nss4_value=0L; - unsigned long nss5_value=0L; - unsigned long nss6_value=0L; - unsigned long nss7_value=0L; - unsigned long total_disk_space=0L; - unsigned long used_disk_space=0L; - unsigned long percent_used_disk_space=0L; - unsigned long purgeable_disk_space=0L; - unsigned long non_purgeable_disk_space=0L; - unsigned long percent_free_space=0; - unsigned long percent_purgeable_space=0; - unsigned long percent_non_purgeable_space=0; - unsigned long current_connections=0L; - unsigned long utilization=0L; - unsigned long cache_hits=0; - unsigned long cache_buffers=0L; - unsigned long lru_time=0L; - unsigned long max_packet_receive_buffers=0; - unsigned long used_packet_receive_buffers=0; - unsigned long percent_used_packet_receive_buffers=0L; - unsigned long sap_entries=0; + char *output_message = NULL; + char *temp_buffer = NULL; + char *netware_version = NULL; + + int time_sync_status = 0; + int nrm_health_status = 0; + unsigned long total_cache_buffers = 0; + unsigned long dirty_cache_buffers = 0; + unsigned long open_files = 0; + unsigned long abended_threads = 0; + unsigned long max_service_processes = 0; + unsigned long current_service_processes = 0; + unsigned long free_disk_space = 0L; + unsigned long nrmp_value = 0L; + unsigned long nrmm_value = 0L; + unsigned long nrms_value = 0L; + unsigned long nss1_value = 0L; + unsigned long nss2_value = 0L; + unsigned long nss3_value = 0L; + unsigned long nss4_value = 0L; + unsigned long nss5_value = 0L; + unsigned long nss6_value = 0L; + unsigned long nss7_value = 0L; + unsigned long total_disk_space = 0L; + unsigned long used_disk_space = 0L; + unsigned long percent_used_disk_space = 0L; + unsigned long purgeable_disk_space = 0L; + unsigned long non_purgeable_disk_space = 0L; + unsigned long percent_free_space = 0; + unsigned long percent_purgeable_space = 0; + unsigned long percent_non_purgeable_space = 0; + unsigned long current_connections = 0L; + unsigned long utilization = 0L; + unsigned long cache_hits = 0; + unsigned long cache_buffers = 0L; + unsigned long lru_time = 0L; + unsigned long max_packet_receive_buffers = 0; + unsigned long used_packet_receive_buffers = 0; + unsigned long percent_used_packet_receive_buffers = 0L; + unsigned long sap_entries = 0; char uptime[MAX_INPUT_BUFFER]; - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Parse extra opts if any */ - argv=np_extra_opts(&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if (process_arguments(argc,argv) == ERROR) - usage4 (_("Could not parse arguments")); + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments")); /* initialize alarm signal handling */ - signal(SIGALRM,socket_timeout_alarm_handler); + signal(SIGALRM, socket_timeout_alarm_handler); /* set socket timeout */ alarm(socket_timeout); /* open connection */ - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); /* get OS version string */ if (check_netware_version) { - send_buffer = strdup ("S19\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + send_buffer = strdup("S19\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) + if (!strcmp(recv_buffer, "-1\n")) netware_version = strdup(""); else { - recv_buffer[strlen(recv_buffer)-1]=0; - xasprintf (&netware_version,_("NetWare %s: "),recv_buffer); + recv_buffer[strlen(recv_buffer) - 1] = 0; + xasprintf(&netware_version, _("NetWare %s: "), recv_buffer); } } else netware_version = strdup(""); - /* check CPU load */ - if (vars_to_check==LOAD1 || vars_to_check==LOAD5 || vars_to_check==LOAD15) { + if (vars_to_check == LOAD1 || vars_to_check == LOAD5 || vars_to_check == LOAD15) { - switch(vars_to_check) { + switch (vars_to_check) { case LOAD1: - temp_buffer = strdup ("1"); + temp_buffer = strdup("1"); break; case LOAD5: - temp_buffer = strdup ("5"); + temp_buffer = strdup("5"); break; default: - temp_buffer = strdup ("15"); + temp_buffer = strdup("15"); break; } close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"UTIL%s\r\n",temp_buffer); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "UTIL%s\r\n", temp_buffer); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - utilization=strtoul(recv_buffer,NULL,10); + utilization = strtoul(recv_buffer, NULL, 10); close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - send_buffer = strdup ("UPTIME\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + send_buffer = strdup("UPTIME\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - recv_buffer[strlen(recv_buffer)-1]=0; - sprintf(uptime,_("Up %s,"),recv_buffer); + recv_buffer[strlen(recv_buffer) - 1] = 0; + sprintf(uptime, _("Up %s,"), recv_buffer); if (check_critical_value && utilization >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && utilization >= warning_value) - result=STATE_WARNING; - - xasprintf (&output_message, - _("Load %s - %s %s-min load average = %lu%%|load%s=%lu;%lu;%lu;0;100"), - state_text(result), - uptime, - temp_buffer, - utilization, - temp_buffer, - utilization, - warning_value, - critical_value); + result = STATE_WARNING; + + xasprintf(&output_message, _("Load %s - %s %s-min load average = %lu%%|load%s=%lu;%lu;%lu;0;100"), state_text(result), uptime, + temp_buffer, utilization, temp_buffer, utilization, warning_value, critical_value); /* check number of user connections */ - } else if (vars_to_check==CONNS) { + } else if (vars_to_check == CONNS) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - send_buffer = strdup ("CONNECT\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + send_buffer = strdup("CONNECT\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - current_connections=strtoul(recv_buffer,NULL,10); + current_connections = strtoul(recv_buffer, NULL, 10); if (check_critical_value && current_connections >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && current_connections >= warning_value) - result=STATE_WARNING; + result = STATE_WARNING; - xasprintf (&output_message, - _("Conns %s - %lu current connections|Conns=%lu;%lu;%lu;;"), - state_text(result), - current_connections, - current_connections, - warning_value, - critical_value); + xasprintf(&output_message, _("Conns %s - %lu current connections|Conns=%lu;%lu;%lu;;"), state_text(result), current_connections, + current_connections, warning_value, critical_value); /* check % long term cache hits */ - } else if (vars_to_check==LTCH) { + } else if (vars_to_check == LTCH) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - send_buffer = strdup ("S1\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + send_buffer = strdup("S1\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - cache_hits=atoi(recv_buffer); + cache_hits = atoi(recv_buffer); if (check_critical_value && cache_hits <= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && cache_hits <= warning_value) - result=STATE_WARNING; + result = STATE_WARNING; - xasprintf (&output_message, - _("%s: Long term cache hits = %lu%%"), - state_text(result), - cache_hits); + xasprintf(&output_message, _("%s: Long term cache hits = %lu%%"), state_text(result), cache_hits); /* check cache buffers */ - } else if (vars_to_check==CBUFF) { + } else if (vars_to_check == CBUFF) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - send_buffer = strdup ("S2\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + send_buffer = strdup("S2\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - cache_buffers=strtoul(recv_buffer,NULL,10); + cache_buffers = strtoul(recv_buffer, NULL, 10); if (check_critical_value && cache_buffers <= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && cache_buffers <= warning_value) - result=STATE_WARNING; + result = STATE_WARNING; - xasprintf (&output_message, - _("%s: Total cache buffers = %lu|Cachebuffers=%lu;%lu;%lu;;"), - state_text(result), - cache_buffers, - cache_buffers, - warning_value, - critical_value); + xasprintf(&output_message, _("%s: Total cache buffers = %lu|Cachebuffers=%lu;%lu;%lu;;"), state_text(result), cache_buffers, + cache_buffers, warning_value, critical_value); /* check dirty cache buffers */ - } else if (vars_to_check==CDBUFF) { + } else if (vars_to_check == CDBUFF) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - send_buffer = strdup ("S3\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + send_buffer = strdup("S3\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - cache_buffers=strtoul(recv_buffer,NULL,10); + cache_buffers = strtoul(recv_buffer, NULL, 10); if (check_critical_value && cache_buffers >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && cache_buffers >= warning_value) - result=STATE_WARNING; + result = STATE_WARNING; - xasprintf (&output_message, - _("%s: Dirty cache buffers = %lu|Dirty-Cache-Buffers=%lu;%lu;%lu;;"), - state_text(result), - cache_buffers, - cache_buffers, - warning_value, - critical_value); + xasprintf(&output_message, _("%s: Dirty cache buffers = %lu|Dirty-Cache-Buffers=%lu;%lu;%lu;;"), state_text(result), cache_buffers, + cache_buffers, warning_value, critical_value); /* check LRU sitting time in minutes */ - } else if (vars_to_check==LRUM) { + } else if (vars_to_check == LRUM) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - send_buffer = strdup ("S5\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + send_buffer = strdup("S5\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - lru_time=strtoul(recv_buffer,NULL,10); + lru_time = strtoul(recv_buffer, NULL, 10); if (check_critical_value && lru_time <= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && lru_time <= warning_value) - result=STATE_WARNING; - - xasprintf (&output_message, - _("%s: LRU sitting time = %lu minutes"), - state_text(result), - lru_time); + result = STATE_WARNING; + xasprintf(&output_message, _("%s: LRU sitting time = %lu minutes"), state_text(result), lru_time); /* check KB free space on volume */ - } else if (vars_to_check==VKF) { + } else if (vars_to_check == VKF) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"VKF%s\r\n",volume_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "VKF%s\r\n", volume_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { - xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name); - result=STATE_CRITICAL; - } else { - free_disk_space=strtoul(recv_buffer,NULL,10); + if (!strcmp(recv_buffer, "-1\n")) { + xasprintf(&output_message, _("CRITICAL - Volume '%s' does not exist!"), volume_name); + result = STATE_CRITICAL; + } else { + free_disk_space = strtoul(recv_buffer, NULL, 10); if (check_critical_value && free_disk_space <= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && free_disk_space <= warning_value) - result=STATE_WARNING; - xasprintf (&output_message, - _("%s%lu KB free on volume %s|KBFree%s=%lu;%lu;%lu;;"), - (result==STATE_OK)?"":_("Only "), - free_disk_space, - volume_name, - volume_name, - free_disk_space, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("%s%lu KB free on volume %s|KBFree%s=%lu;%lu;%lu;;"), (result == STATE_OK) ? "" : _("Only "), + free_disk_space, volume_name, volume_name, free_disk_space, warning_value, critical_value); } /* check MB free space on volume */ - } else if (vars_to_check==VMF) { + } else if (vars_to_check == VMF) { - xasprintf (&send_buffer,"VMF%s\r\n",volume_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "VMF%s\r\n", volume_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { - xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name); - result=STATE_CRITICAL; - } else { - free_disk_space=strtoul(recv_buffer,NULL,10); + if (!strcmp(recv_buffer, "-1\n")) { + xasprintf(&output_message, _("CRITICAL - Volume '%s' does not exist!"), volume_name); + result = STATE_CRITICAL; + } else { + free_disk_space = strtoul(recv_buffer, NULL, 10); if (check_critical_value && free_disk_space <= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && free_disk_space <= warning_value) - result=STATE_WARNING; - xasprintf (&output_message, - _("%s%lu MB free on volume %s|MBFree%s=%lu;%lu;%lu;;"), - (result==STATE_OK)?"":_("Only "), - free_disk_space, - volume_name, - volume_name, - free_disk_space, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("%s%lu MB free on volume %s|MBFree%s=%lu;%lu;%lu;;"), (result == STATE_OK) ? "" : _("Only "), + free_disk_space, volume_name, volume_name, free_disk_space, warning_value, critical_value); } /* check MB used space on volume */ - } else if (vars_to_check==VMU) { + } else if (vars_to_check == VMU) { - xasprintf (&send_buffer,"VMU%s\r\n",volume_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "VMU%s\r\n", volume_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { - xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name); - result=STATE_CRITICAL; - } else { - free_disk_space=strtoul(recv_buffer,NULL,10); + if (!strcmp(recv_buffer, "-1\n")) { + xasprintf(&output_message, _("CRITICAL - Volume '%s' does not exist!"), volume_name); + result = STATE_CRITICAL; + } else { + free_disk_space = strtoul(recv_buffer, NULL, 10); if (check_critical_value && free_disk_space <= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && free_disk_space <= warning_value) - result=STATE_WARNING; - xasprintf (&output_message, - _("%s%lu MB used on volume %s|MBUsed%s=%lu;%lu;%lu;;"), - (result==STATE_OK)?"":_("Only "), - free_disk_space, - volume_name, - volume_name, - free_disk_space, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("%s%lu MB used on volume %s|MBUsed%s=%lu;%lu;%lu;;"), (result == STATE_OK) ? "" : _("Only "), + free_disk_space, volume_name, volume_name, free_disk_space, warning_value, critical_value); } /* check % used space on volume */ - } else if (vars_to_check==VPU) { + } else if (vars_to_check == VPU) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - asprintf (&send_buffer,"VMU%s\r\n",volume_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); + asprintf(&send_buffer, "VMU%s\r\n", volume_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); - if (result!=STATE_OK) + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { - asprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name); - result=STATE_CRITICAL; + if (!strcmp(recv_buffer, "-1\n")) { + asprintf(&output_message, _("CRITICAL - Volume '%s' does not exist!"), volume_name); + result = STATE_CRITICAL; } else { - used_disk_space=strtoul(recv_buffer,NULL,10); + used_disk_space = strtoul(recv_buffer, NULL, 10); close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); /* get total volume in MB */ - asprintf (&send_buffer,"VMS%s\r\n",volume_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + asprintf(&send_buffer, "VMS%s\r\n", volume_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - total_disk_space=strtoul(recv_buffer,NULL,10); + total_disk_space = strtoul(recv_buffer, NULL, 10); /* calculate percent used on volume */ - percent_used_disk_space=(unsigned long)(((double)used_disk_space/(double)total_disk_space)*100.0); + percent_used_disk_space = (unsigned long)(((double)used_disk_space / (double)total_disk_space) * 100.0); if (check_critical_value && percent_used_disk_space >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && percent_used_disk_space >= warning_value) - result=STATE_WARNING; - - asprintf (&output_message,_("%lu MB (%lu%%) used on volume %s - total %lu MB|Used space in percent on %s=%lu;%lu;%lu;0;100"), - used_disk_space, - percent_used_disk_space, - volume_name, - total_disk_space, - volume_name, - percent_used_disk_space, - warning_value, - critical_value - ); + result = STATE_WARNING; + + asprintf(&output_message, _("%lu MB (%lu%%) used on volume %s - total %lu MB|Used space in percent on %s=%lu;%lu;%lu;0;100"), + used_disk_space, percent_used_disk_space, volume_name, total_disk_space, volume_name, percent_used_disk_space, + warning_value, critical_value); } /* check % free space on volume */ - } else if (vars_to_check==VPF) { + } else if (vars_to_check == VPF) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"VKF%s\r\n",volume_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "VKF%s\r\n", volume_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { + if (!strcmp(recv_buffer, "-1\n")) { - xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name); - result=STATE_CRITICAL; + xasprintf(&output_message, _("CRITICAL - Volume '%s' does not exist!"), volume_name); + result = STATE_CRITICAL; } else { - free_disk_space=strtoul(recv_buffer,NULL,10); + free_disk_space = strtoul(recv_buffer, NULL, 10); close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"VKS%s\r\n",volume_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "VKS%s\r\n", volume_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - total_disk_space=strtoul(recv_buffer,NULL,10); + total_disk_space = strtoul(recv_buffer, NULL, 10); - percent_free_space=(unsigned long)(((double)free_disk_space/(double)total_disk_space)*100.0); + percent_free_space = (unsigned long)(((double)free_disk_space / (double)total_disk_space) * 100.0); if (check_critical_value && percent_free_space <= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && percent_free_space <= warning_value) - result=STATE_WARNING; - free_disk_space/=1024; - total_disk_space/=1024; - xasprintf (&output_message,_("%lu MB (%lu%%) free on volume %s - total %lu MB|FreeMB%s=%lu;%lu;%lu;0;100"), - free_disk_space, - percent_free_space, - volume_name, - total_disk_space, - volume_name, - percent_free_space, - warning_value, - critical_value - ); + result = STATE_WARNING; + free_disk_space /= 1024; + total_disk_space /= 1024; + xasprintf(&output_message, _("%lu MB (%lu%%) free on volume %s - total %lu MB|FreeMB%s=%lu;%lu;%lu;0;100"), free_disk_space, + percent_free_space, volume_name, total_disk_space, volume_name, percent_free_space, warning_value, critical_value); } /* check to see if DS Database is open or closed */ - } else if (vars_to_check==DSDB) { + } else if (vars_to_check == DSDB) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - send_buffer = strdup ("S11\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + send_buffer = strdup("S11\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (atoi(recv_buffer)==1) - result=STATE_OK; + if (atoi(recv_buffer) == 1) + result = STATE_OK; else - result=STATE_WARNING; + result = STATE_WARNING; close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - send_buffer = strdup ("S13\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - temp_buffer=strtok(recv_buffer,"\r\n"); + send_buffer = strdup("S13\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + temp_buffer = strtok(recv_buffer, "\r\n"); - xasprintf (&output_message,_("Directory Services Database is %s (DS version %s)"),(result==STATE_OK)?"open":"closed",temp_buffer); + xasprintf(&output_message, _("Directory Services Database is %s (DS version %s)"), (result == STATE_OK) ? "open" : "closed", + temp_buffer); /* check to see if logins are enabled */ - } else if (vars_to_check==LOGINS) { + } else if (vars_to_check == LOGINS) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - send_buffer = strdup ("S12\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + send_buffer = strdup("S12\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (atoi(recv_buffer)==1) - result=STATE_OK; + if (atoi(recv_buffer) == 1) + result = STATE_OK; else - result=STATE_WARNING; - - xasprintf (&output_message,_("Logins are %s"),(result==STATE_OK)?_("enabled"):_("disabled")); + result = STATE_WARNING; + xasprintf(&output_message, _("Logins are %s"), (result == STATE_OK) ? _("enabled") : _("disabled")); /* check NRM Health Status Summary*/ - } else if (vars_to_check==NRMH) { + } else if (vars_to_check == NRMH) { - xasprintf (&send_buffer,"NRMH\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "NRMH\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - nrm_health_status=atoi(recv_buffer); + nrm_health_status = atoi(recv_buffer); - if (nrm_health_status==2) { - result=STATE_OK; - xasprintf (&output_message,_("CRITICAL - NRM Status is bad!")); - } - else { - if (nrm_health_status==1) { - result=STATE_WARNING; - xasprintf (&output_message,_("Warning - NRM Status is suspect!")); + if (nrm_health_status == 2) { + result = STATE_OK; + xasprintf(&output_message, _("CRITICAL - NRM Status is bad!")); + } else { + if (nrm_health_status == 1) { + result = STATE_WARNING; + xasprintf(&output_message, _("Warning - NRM Status is suspect!")); } - xasprintf (&output_message,_("OK - NRM Status is good!")); + xasprintf(&output_message, _("OK - NRM Status is good!")); } - - /* check packet receive buffers */ - } else if (vars_to_check==UPRB || vars_to_check==PUPRB) { + } else if (vars_to_check == UPRB || vars_to_check == PUPRB) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"S15\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "S15\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - used_packet_receive_buffers=atoi(recv_buffer); + used_packet_receive_buffers = atoi(recv_buffer); close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"S16\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "S16\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - max_packet_receive_buffers=atoi(recv_buffer); + max_packet_receive_buffers = atoi(recv_buffer); - percent_used_packet_receive_buffers=(unsigned long)(((double)used_packet_receive_buffers/(double)max_packet_receive_buffers)*100.0); + percent_used_packet_receive_buffers = + (unsigned long)(((double)used_packet_receive_buffers / (double)max_packet_receive_buffers) * 100.0); - if (vars_to_check==UPRB) { + if (vars_to_check == UPRB) { if (check_critical_value && used_packet_receive_buffers >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && used_packet_receive_buffers >= warning_value) - result=STATE_WARNING; + result = STATE_WARNING; } else { if (check_critical_value && percent_used_packet_receive_buffers >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && percent_used_packet_receive_buffers >= warning_value) - result=STATE_WARNING; + result = STATE_WARNING; } - xasprintf (&output_message,_("%lu of %lu (%lu%%) packet receive buffers used"),used_packet_receive_buffers,max_packet_receive_buffers,percent_used_packet_receive_buffers); + xasprintf(&output_message, _("%lu of %lu (%lu%%) packet receive buffers used"), used_packet_receive_buffers, + max_packet_receive_buffers, percent_used_packet_receive_buffers); /* check SAP table entries */ - } else if (vars_to_check==SAPENTRIES) { + } else if (vars_to_check == SAPENTRIES) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - if (sap_number==-1) - xasprintf (&send_buffer,"S9\r\n"); + if (sap_number == -1) + xasprintf(&send_buffer, "S9\r\n"); else - xasprintf (&send_buffer,"S9.%d\r\n",sap_number); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "S9.%d\r\n", sap_number); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - sap_entries=atoi(recv_buffer); + sap_entries = atoi(recv_buffer); if (check_critical_value && sap_entries >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && sap_entries >= warning_value) - result=STATE_WARNING; + result = STATE_WARNING; - if (sap_number==-1) - xasprintf (&output_message,_("%lu entries in SAP table"),sap_entries); + if (sap_number == -1) + xasprintf(&output_message, _("%lu entries in SAP table"), sap_entries); else - xasprintf (&output_message,_("%lu entries in SAP table for SAP type %d"),sap_entries,sap_number); + xasprintf(&output_message, _("%lu entries in SAP table for SAP type %d"), sap_entries, sap_number); /* check KB purgeable space on volume */ - } else if (vars_to_check==VKP) { + } else if (vars_to_check == VKP) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"VKP%s\r\n",volume_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "VKP%s\r\n", volume_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { - xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name); - result=STATE_CRITICAL; + if (!strcmp(recv_buffer, "-1\n")) { + xasprintf(&output_message, _("CRITICAL - Volume '%s' does not exist!"), volume_name); + result = STATE_CRITICAL; } else { - purgeable_disk_space=strtoul(recv_buffer,NULL,10); + purgeable_disk_space = strtoul(recv_buffer, NULL, 10); if (check_critical_value && purgeable_disk_space >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && purgeable_disk_space >= warning_value) - result=STATE_WARNING; - xasprintf (&output_message,_("%s%lu KB purgeable on volume %s|Purge%s=%lu;%lu;%lu;;"), - (result==STATE_OK)?"":_("Only "), - purgeable_disk_space, - volume_name, - volume_name, - purgeable_disk_space, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("%s%lu KB purgeable on volume %s|Purge%s=%lu;%lu;%lu;;"), (result == STATE_OK) ? "" : _("Only "), + purgeable_disk_space, volume_name, volume_name, purgeable_disk_space, warning_value, critical_value); } /* check MB purgeable space on volume */ - } else if (vars_to_check==VMP) { + } else if (vars_to_check == VMP) { - xasprintf (&send_buffer,"VMP%s\r\n",volume_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "VMP%s\r\n", volume_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { - xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name); - result=STATE_CRITICAL; + if (!strcmp(recv_buffer, "-1\n")) { + xasprintf(&output_message, _("CRITICAL - Volume '%s' does not exist!"), volume_name); + result = STATE_CRITICAL; } else { - purgeable_disk_space=strtoul(recv_buffer,NULL,10); + purgeable_disk_space = strtoul(recv_buffer, NULL, 10); if (check_critical_value && purgeable_disk_space >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && purgeable_disk_space >= warning_value) - result=STATE_WARNING; - xasprintf (&output_message,_("%s%lu MB purgeable on volume %s|Purge%s=%lu;%lu;%lu;;"), - (result==STATE_OK)?"":_("Only "), - purgeable_disk_space, - volume_name, - volume_name, - purgeable_disk_space, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("%s%lu MB purgeable on volume %s|Purge%s=%lu;%lu;%lu;;"), (result == STATE_OK) ? "" : _("Only "), + purgeable_disk_space, volume_name, volume_name, purgeable_disk_space, warning_value, critical_value); } /* check % purgeable space on volume */ - } else if (vars_to_check==VPP) { + } else if (vars_to_check == VPP) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"VKP%s\r\n",volume_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "VKP%s\r\n", volume_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { + if (!strcmp(recv_buffer, "-1\n")) { - xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name); - result=STATE_CRITICAL; + xasprintf(&output_message, _("CRITICAL - Volume '%s' does not exist!"), volume_name); + result = STATE_CRITICAL; } else { - purgeable_disk_space=strtoul(recv_buffer,NULL,10); + purgeable_disk_space = strtoul(recv_buffer, NULL, 10); close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"VKS%s\r\n",volume_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "VKS%s\r\n", volume_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - total_disk_space=strtoul(recv_buffer,NULL,10); + total_disk_space = strtoul(recv_buffer, NULL, 10); - percent_purgeable_space=(unsigned long)(((double)purgeable_disk_space/(double)total_disk_space)*100.0); + percent_purgeable_space = (unsigned long)(((double)purgeable_disk_space / (double)total_disk_space) * 100.0); if (check_critical_value && percent_purgeable_space >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && percent_purgeable_space >= warning_value) - result=STATE_WARNING; - purgeable_disk_space/=1024; - xasprintf (&output_message,_("%lu MB (%lu%%) purgeable on volume %s|Purgeable%s=%lu;%lu;%lu;0;100"), - purgeable_disk_space, - percent_purgeable_space, - volume_name, - volume_name, - percent_purgeable_space, - warning_value, - critical_value - ); + result = STATE_WARNING; + purgeable_disk_space /= 1024; + xasprintf(&output_message, _("%lu MB (%lu%%) purgeable on volume %s|Purgeable%s=%lu;%lu;%lu;0;100"), purgeable_disk_space, + percent_purgeable_space, volume_name, volume_name, percent_purgeable_space, warning_value, critical_value); } /* check KB not yet purgeable space on volume */ - } else if (vars_to_check==VKNP) { + } else if (vars_to_check == VKNP) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"VKNP%s\r\n",volume_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "VKNP%s\r\n", volume_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { - xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name); - result=STATE_CRITICAL; + if (!strcmp(recv_buffer, "-1\n")) { + xasprintf(&output_message, _("CRITICAL - Volume '%s' does not exist!"), volume_name); + result = STATE_CRITICAL; } else { - non_purgeable_disk_space=strtoul(recv_buffer,NULL,10); + non_purgeable_disk_space = strtoul(recv_buffer, NULL, 10); if (check_critical_value && non_purgeable_disk_space >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && non_purgeable_disk_space >= warning_value) - result=STATE_WARNING; - xasprintf (&output_message,_("%s%lu KB not yet purgeable on volume %s"),(result==STATE_OK)?"":_("Only "),non_purgeable_disk_space,volume_name); + result = STATE_WARNING; + xasprintf(&output_message, _("%s%lu KB not yet purgeable on volume %s"), (result == STATE_OK) ? "" : _("Only "), + non_purgeable_disk_space, volume_name); } /* check % not yet purgeable space on volume */ - } else if (vars_to_check==VPNP) { + } else if (vars_to_check == VPNP) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"VKNP%s\r\n",volume_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "VKNP%s\r\n", volume_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { + if (!strcmp(recv_buffer, "-1\n")) { - xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name); - result=STATE_CRITICAL; + xasprintf(&output_message, _("CRITICAL - Volume '%s' does not exist!"), volume_name); + result = STATE_CRITICAL; } else { - non_purgeable_disk_space=strtoul(recv_buffer,NULL,10); + non_purgeable_disk_space = strtoul(recv_buffer, NULL, 10); close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"VKS%s\r\n",volume_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "VKS%s\r\n", volume_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - total_disk_space=strtoul(recv_buffer,NULL,10); + total_disk_space = strtoul(recv_buffer, NULL, 10); - percent_non_purgeable_space=(unsigned long)(((double)non_purgeable_disk_space/(double)total_disk_space)*100.0); + percent_non_purgeable_space = (unsigned long)(((double)non_purgeable_disk_space / (double)total_disk_space) * 100.0); if (check_critical_value && percent_non_purgeable_space >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && percent_non_purgeable_space >= warning_value) - result=STATE_WARNING; - purgeable_disk_space/=1024; - xasprintf (&output_message,_("%lu MB (%lu%%) not yet purgeable on volume %s"),non_purgeable_disk_space,percent_non_purgeable_space,volume_name); + result = STATE_WARNING; + purgeable_disk_space /= 1024; + xasprintf(&output_message, _("%lu MB (%lu%%) not yet purgeable on volume %s"), non_purgeable_disk_space, + percent_non_purgeable_space, volume_name); } /* check # of open files */ - } else if (vars_to_check==OFILES) { + } else if (vars_to_check == OFILES) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"S18\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "S18\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - open_files=atoi(recv_buffer); + open_files = atoi(recv_buffer); if (check_critical_value && open_files >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && open_files >= warning_value) - result=STATE_WARNING; - - xasprintf (&output_message,_("%lu open files|Openfiles=%lu;%lu;%lu;0,0"), - open_files, - open_files, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("%lu open files|Openfiles=%lu;%lu;%lu;0,0"), open_files, open_files, warning_value, critical_value); /* check # of abended threads (Netware > 5.x only) */ - } else if (vars_to_check==ABENDS) { + } else if (vars_to_check == ABENDS) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"S17\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "S17\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - abended_threads=atoi(recv_buffer); + abended_threads = atoi(recv_buffer); if (check_critical_value && abended_threads >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && abended_threads >= warning_value) - result=STATE_WARNING; + result = STATE_WARNING; - xasprintf (&output_message,_("%lu abended threads|Abends=%lu;%lu;%lu;;"), - abended_threads, - abended_threads, - warning_value, - critical_value); + xasprintf(&output_message, _("%lu abended threads|Abends=%lu;%lu;%lu;;"), abended_threads, abended_threads, warning_value, + critical_value); /* check # of current service processes (Netware 5.x only) */ - } else if (vars_to_check==CSPROCS) { + } else if (vars_to_check == CSPROCS) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"S20\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "S20\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - max_service_processes=atoi(recv_buffer); + max_service_processes = atoi(recv_buffer); close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"S21\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "S21\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - current_service_processes=atoi(recv_buffer); + current_service_processes = atoi(recv_buffer); if (check_critical_value && current_service_processes >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && current_service_processes >= warning_value) - result=STATE_WARNING; + result = STATE_WARNING; - xasprintf (&output_message, - _("%lu current service processes (%lu max)|Processes=%lu;%lu;%lu;0;%lu"), - current_service_processes, - max_service_processes, - current_service_processes, - warning_value, - critical_value, - max_service_processes); + xasprintf(&output_message, _("%lu current service processes (%lu max)|Processes=%lu;%lu;%lu;0;%lu"), current_service_processes, + max_service_processes, current_service_processes, warning_value, critical_value, max_service_processes); /* check # Timesync Status */ - } else if (vars_to_check==TSYNC) { + } else if (vars_to_check == TSYNC) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"S22\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "S22\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - time_sync_status=atoi(recv_buffer); + time_sync_status = atoi(recv_buffer); - if (time_sync_status==0) { - result=STATE_CRITICAL; - xasprintf (&output_message,_("CRITICAL - Time not in sync with network!")); - } - else { - xasprintf (&output_message,_("OK - Time in sync with network!")); + if (time_sync_status == 0) { + result = STATE_CRITICAL; + xasprintf(&output_message, _("CRITICAL - Time not in sync with network!")); + } else { + xasprintf(&output_message, _("OK - Time in sync with network!")); } - - - - /* check LRU sitting time in secondss */ - } else if (vars_to_check==LRUS) { + } else if (vars_to_check == LRUS) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - send_buffer = strdup ("S4\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + send_buffer = strdup("S4\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - lru_time=strtoul(recv_buffer,NULL,10); + lru_time = strtoul(recv_buffer, NULL, 10); if (check_critical_value && lru_time <= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && lru_time <= warning_value) - result=STATE_WARNING; - xasprintf (&output_message,_("LRU sitting time = %lu seconds"),lru_time); - + result = STATE_WARNING; + xasprintf(&output_message, _("LRU sitting time = %lu seconds"), lru_time); /* check % dirty cacheobuffers as a percentage of the total*/ - } else if (vars_to_check==DCB) { + } else if (vars_to_check == DCB) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - send_buffer = strdup ("S6\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + send_buffer = strdup("S6\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - dirty_cache_buffers=atoi(recv_buffer); + dirty_cache_buffers = atoi(recv_buffer); if (check_critical_value && dirty_cache_buffers <= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && dirty_cache_buffers <= warning_value) - result=STATE_WARNING; - xasprintf (&output_message,_("Dirty cache buffers = %lu%% of the total|DCB=%lu;%lu;%lu;0;100"), - dirty_cache_buffers, - dirty_cache_buffers, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("Dirty cache buffers = %lu%% of the total|DCB=%lu;%lu;%lu;0;100"), dirty_cache_buffers, + dirty_cache_buffers, warning_value, critical_value); /* check % total cache buffers as a percentage of the original*/ - } else if (vars_to_check==TCB) { + } else if (vars_to_check == TCB) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - send_buffer = strdup ("S7\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + send_buffer = strdup("S7\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - total_cache_buffers=atoi(recv_buffer); + total_cache_buffers = atoi(recv_buffer); if (check_critical_value && total_cache_buffers <= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && total_cache_buffers <= warning_value) - result=STATE_WARNING; - xasprintf (&output_message,_("Total cache buffers = %lu%% of the original|TCB=%lu;%lu;%lu;0;100"), - total_cache_buffers, - total_cache_buffers, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("Total cache buffers = %lu%% of the original|TCB=%lu;%lu;%lu;0;100"), total_cache_buffers, + total_cache_buffers, warning_value, critical_value); - } else if (vars_to_check==DSVER) { + } else if (vars_to_check == DSVER) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"S13\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "S13\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - recv_buffer[strlen(recv_buffer)-1]=0; + recv_buffer[strlen(recv_buffer) - 1] = 0; - xasprintf (&output_message,_("NDS Version %s"),recv_buffer); + xasprintf(&output_message, _("NDS Version %s"), recv_buffer); - } else if (vars_to_check==UPTIME) { + } else if (vars_to_check == UPTIME) { close(sd); - my_tcp_connect (server_address, server_port, &sd); - - xasprintf (&send_buffer,"UPTIME\r\n"); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) - return result; + my_tcp_connect(server_address, server_port, &sd); + xasprintf(&send_buffer, "UPTIME\r\n"); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) + return result; - recv_buffer[sizeof(recv_buffer)-1]=0; - recv_buffer[strlen(recv_buffer)-1]=0; + recv_buffer[sizeof(recv_buffer) - 1] = 0; + recv_buffer[strlen(recv_buffer) - 1] = 0; - xasprintf (&output_message,_("Up %s"),recv_buffer); + xasprintf(&output_message, _("Up %s"), recv_buffer); - } else if (vars_to_check==NLM) { + } else if (vars_to_check == NLM) { close(sd); - my_tcp_connect (server_address, server_port, &sd); + my_tcp_connect(server_address, server_port, &sd); - xasprintf (&send_buffer,"S24:%s\r\n",nlm_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "S24:%s\r\n", nlm_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - recv_buffer[strlen(recv_buffer)-1]=0; - if (strcmp(recv_buffer,"-1")) { - xasprintf (&output_message,_("Module %s version %s is loaded"),nlm_name,recv_buffer); + recv_buffer[strlen(recv_buffer) - 1] = 0; + if (strcmp(recv_buffer, "-1")) { + xasprintf(&output_message, _("Module %s version %s is loaded"), nlm_name, recv_buffer); } else { - result=STATE_CRITICAL; - xasprintf (&output_message,_("Module %s is not loaded"),nlm_name); - - } - } else if (vars_to_check==NRMP) { + result = STATE_CRITICAL; + xasprintf(&output_message, _("Module %s is not loaded"), nlm_name); + } + } else if (vars_to_check == NRMP) { - xasprintf (&send_buffer,"NRMP:%s\r\n",nrmp_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "NRMP:%s\r\n", nrmp_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { - xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nrmp_name); - result=STATE_CRITICAL; - } else { - nrmp_value=strtoul(recv_buffer,NULL,10); + if (!strcmp(recv_buffer, "-1\n")) { + xasprintf(&output_message, _("CRITICAL - Value '%s' does not exist!"), nrmp_name); + result = STATE_CRITICAL; + } else { + nrmp_value = strtoul(recv_buffer, NULL, 10); if (check_critical_value && nrmp_value <= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && nrmp_value <= warning_value) - result=STATE_WARNING; - xasprintf (&output_message, - _("%s is %lu|%s=%lu;%lu;%lu;;"), - nrmp_name, - nrmp_value, - nrmp_name, - nrmp_value, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("%s is %lu|%s=%lu;%lu;%lu;;"), nrmp_name, nrmp_value, nrmp_name, nrmp_value, warning_value, + critical_value); } - } else if (vars_to_check==NRMM) { + } else if (vars_to_check == NRMM) { - xasprintf (&send_buffer,"NRMM:%s\r\n",nrmm_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "NRMM:%s\r\n", nrmm_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { - xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nrmm_name); - result=STATE_CRITICAL; - } else { - nrmm_value=strtoul(recv_buffer,NULL,10); + if (!strcmp(recv_buffer, "-1\n")) { + xasprintf(&output_message, _("CRITICAL - Value '%s' does not exist!"), nrmm_name); + result = STATE_CRITICAL; + } else { + nrmm_value = strtoul(recv_buffer, NULL, 10); if (check_critical_value && nrmm_value <= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && nrmm_value <= warning_value) - result=STATE_WARNING; - xasprintf (&output_message, - _("%s is %lu|%s=%lu;%lu;%lu;;"), - nrmm_name, - nrmm_value, - nrmm_name, - nrmm_value, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("%s is %lu|%s=%lu;%lu;%lu;;"), nrmm_name, nrmm_value, nrmm_name, nrmm_value, warning_value, + critical_value); } - } else if (vars_to_check==NRMS) { + } else if (vars_to_check == NRMS) { - xasprintf (&send_buffer,"NRMS:%s\r\n",nrms_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "NRMS:%s\r\n", nrms_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { - xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nrms_name); - result=STATE_CRITICAL; - } else { - nrms_value=strtoul(recv_buffer,NULL,10); + if (!strcmp(recv_buffer, "-1\n")) { + xasprintf(&output_message, _("CRITICAL - Value '%s' does not exist!"), nrms_name); + result = STATE_CRITICAL; + } else { + nrms_value = strtoul(recv_buffer, NULL, 10); if (check_critical_value && nrms_value >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && nrms_value >= warning_value) - result=STATE_WARNING; - xasprintf (&output_message, - _("%s is %lu|%s=%lu;%lu;%lu;;"), - nrms_name, - nrms_value, - nrms_name, - nrms_value, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("%s is %lu|%s=%lu;%lu;%lu;;"), nrms_name, nrms_value, nrms_name, nrms_value, warning_value, + critical_value); } - } else if (vars_to_check==NSS1) { + } else if (vars_to_check == NSS1) { - xasprintf (&send_buffer,"NSS1:%s\r\n",nss1_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "NSS1:%s\r\n", nss1_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { - xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss1_name); - result=STATE_CRITICAL; - } else { - nss1_value=strtoul(recv_buffer,NULL,10); + if (!strcmp(recv_buffer, "-1\n")) { + xasprintf(&output_message, _("CRITICAL - Value '%s' does not exist!"), nss1_name); + result = STATE_CRITICAL; + } else { + nss1_value = strtoul(recv_buffer, NULL, 10); if (check_critical_value && nss1_value >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && nss1_value >= warning_value) - result=STATE_WARNING; - xasprintf (&output_message, - _("%s is %lu|%s=%lu;%lu;%lu;;"), - nss1_name, - nss1_value, - nss1_name, - nss1_value, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("%s is %lu|%s=%lu;%lu;%lu;;"), nss1_name, nss1_value, nss1_name, nss1_value, warning_value, + critical_value); } - } else if (vars_to_check==NSS2) { + } else if (vars_to_check == NSS2) { - xasprintf (&send_buffer,"NSS2:%s\r\n",nss2_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "NSS2:%s\r\n", nss2_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { - xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss2_name); - result=STATE_CRITICAL; - } else { - nss2_value=strtoul(recv_buffer,NULL,10); + if (!strcmp(recv_buffer, "-1\n")) { + xasprintf(&output_message, _("CRITICAL - Value '%s' does not exist!"), nss2_name); + result = STATE_CRITICAL; + } else { + nss2_value = strtoul(recv_buffer, NULL, 10); if (check_critical_value && nss2_value >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && nss2_value >= warning_value) - result=STATE_WARNING; - xasprintf (&output_message, - _("%s is %lu|%s=%lu;%lu;%lu;;"), - nss2_name, - nss2_value, - nss2_name, - nss2_value, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("%s is %lu|%s=%lu;%lu;%lu;;"), nss2_name, nss2_value, nss2_name, nss2_value, warning_value, + critical_value); } - } else if (vars_to_check==NSS3) { + } else if (vars_to_check == NSS3) { - xasprintf (&send_buffer,"NSS3:%s\r\n",nss3_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "NSS3:%s\r\n", nss3_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { - xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss3_name); - result=STATE_CRITICAL; - } else { - nss3_value=strtoul(recv_buffer,NULL,10); + if (!strcmp(recv_buffer, "-1\n")) { + xasprintf(&output_message, _("CRITICAL - Value '%s' does not exist!"), nss3_name); + result = STATE_CRITICAL; + } else { + nss3_value = strtoul(recv_buffer, NULL, 10); if (check_critical_value && nss3_value >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && nss3_value >= warning_value) - result=STATE_WARNING; - xasprintf (&output_message, - _("%s is %lu|%s=%lu;%lu;%lu;;"), - nss3_name, - nss3_value, - nss3_name, - nss3_value, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("%s is %lu|%s=%lu;%lu;%lu;;"), nss3_name, nss3_value, nss3_name, nss3_value, warning_value, + critical_value); } - } else if (vars_to_check==NSS4) { + } else if (vars_to_check == NSS4) { - xasprintf (&send_buffer,"NSS4:%s\r\n",nss4_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "NSS4:%s\r\n", nss4_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { - xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss4_name); - result=STATE_CRITICAL; - } else { - nss4_value=strtoul(recv_buffer,NULL,10); + if (!strcmp(recv_buffer, "-1\n")) { + xasprintf(&output_message, _("CRITICAL - Value '%s' does not exist!"), nss4_name); + result = STATE_CRITICAL; + } else { + nss4_value = strtoul(recv_buffer, NULL, 10); if (check_critical_value && nss4_value >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && nss4_value >= warning_value) - result=STATE_WARNING; - xasprintf (&output_message, - _("%s is %lu|%s=%lu;%lu;%lu;;"), - nss4_name, - nss4_value, - nss4_name, - nss4_value, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("%s is %lu|%s=%lu;%lu;%lu;;"), nss4_name, nss4_value, nss4_name, nss4_value, warning_value, + critical_value); } - } else if (vars_to_check==NSS5) { + } else if (vars_to_check == NSS5) { - xasprintf (&send_buffer,"NSS5:%s\r\n",nss5_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "NSS5:%s\r\n", nss5_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { - xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss5_name); - result=STATE_CRITICAL; - } else { - nss5_value=strtoul(recv_buffer,NULL,10); + if (!strcmp(recv_buffer, "-1\n")) { + xasprintf(&output_message, _("CRITICAL - Value '%s' does not exist!"), nss5_name); + result = STATE_CRITICAL; + } else { + nss5_value = strtoul(recv_buffer, NULL, 10); if (check_critical_value && nss5_value >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && nss5_value >= warning_value) - result=STATE_WARNING; - xasprintf (&output_message, - _("%s is %lu|%s=%lu;%lu;%lu;;"), - nss5_name, - nss5_value, - nss5_name, - nss5_value, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("%s is %lu|%s=%lu;%lu;%lu;;"), nss5_name, nss5_value, nss5_name, nss5_value, warning_value, + critical_value); } - } else if (vars_to_check==NSS6) { + } else if (vars_to_check == NSS6) { - xasprintf (&send_buffer,"NSS6:%s\r\n",nss6_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "NSS6:%s\r\n", nss6_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { - xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss6_name); - result=STATE_CRITICAL; - } else { - nss6_value=strtoul(recv_buffer,NULL,10); + if (!strcmp(recv_buffer, "-1\n")) { + xasprintf(&output_message, _("CRITICAL - Value '%s' does not exist!"), nss6_name); + result = STATE_CRITICAL; + } else { + nss6_value = strtoul(recv_buffer, NULL, 10); if (check_critical_value && nss6_value >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && nss6_value >= warning_value) - result=STATE_WARNING; - xasprintf (&output_message, - _("%s is %lu|%s=%lu;%lu;%lu;;"), - nss6_name, - nss6_value, - nss6_name, - nss6_value, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("%s is %lu|%s=%lu;%lu;%lu;;"), nss6_name, nss6_value, nss6_name, nss6_value, warning_value, + critical_value); } - } else if (vars_to_check==NSS7) { + } else if (vars_to_check == NSS7) { - xasprintf (&send_buffer,"NSS7:%s\r\n",nss7_name); - result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer)); - if (result!=STATE_OK) + xasprintf(&send_buffer, "NSS7:%s\r\n", nss7_name); + result = send_tcp_request(sd, send_buffer, recv_buffer, sizeof(recv_buffer)); + if (result != STATE_OK) return result; - if (!strcmp(recv_buffer,"-1\n")) { - xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss7_name); - result=STATE_CRITICAL; - } else { - nss7_value=strtoul(recv_buffer,NULL,10); + if (!strcmp(recv_buffer, "-1\n")) { + xasprintf(&output_message, _("CRITICAL - Value '%s' does not exist!"), nss7_name); + result = STATE_CRITICAL; + } else { + nss7_value = strtoul(recv_buffer, NULL, 10); if (check_critical_value && nss7_value >= critical_value) - result=STATE_CRITICAL; + result = STATE_CRITICAL; else if (check_warning_value && nss7_value >= warning_value) - result=STATE_WARNING; - xasprintf (&output_message, - _("%s is %lu|%s=%lu;%lu;%lu;;"), - nss7_name, - nss7_value, - nss7_name, - nss7_value, - warning_value, - critical_value); + result = STATE_WARNING; + xasprintf(&output_message, _("%s is %lu|%s=%lu;%lu;%lu;;"), nss7_name, nss7_value, nss7_name, nss7_value, warning_value, + critical_value); } + } else { -} - else { - - output_message = strdup (_("Nothing to check!\n")); - result=STATE_UNKNOWN; - + output_message = strdup(_("Nothing to check!\n")); + result = STATE_UNKNOWN; } - close (sd); + close(sd); /* reset timeout */ alarm(0); - printf("%s%s\n",netware_version,output_message); + printf("%s%s\n", netware_version, output_message); return result; } - - /* process command-line arguments */ int process_arguments(int argc, char **argv) { int c; int option = 0; - static struct option longopts[] = - { - {"port", required_argument,0,'p'}, - {"timeout", required_argument,0,'t'}, - {"critical", required_argument,0,'c'}, - {"warning", required_argument,0,'w'}, - {"variable", required_argument,0,'v'}, - {"hostname", required_argument,0,'H'}, - {"osversion",no_argument, 0,'o'}, - {"version", no_argument, 0,'V'}, - {"help", no_argument, 0,'h'}, - {0,0,0,0} - }; + static struct option longopts[] = {{"port", required_argument, 0, 'p'}, {"timeout", required_argument, 0, 't'}, + {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, + {"variable", required_argument, 0, 'v'}, {"hostname", required_argument, 0, 'H'}, + {"osversion", no_argument, 0, 'o'}, {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, {0, 0, 0, 0}}; /* no options were supplied */ - if (argc<2) return ERROR; + if (argc < 2) + return ERROR; /* backwards compatibility */ - if (! is_option(argv[1])) { - server_address=argv[1]; - argv[1]=argv[0]; - argv=&argv[1]; + if (!is_option(argv[1])) { + server_address = argv[1]; + argv[1] = argv[0]; + argv = &argv[1]; argc--; } - for (c=1;c 10) + sap_number = atoi(optarg + 10); else - die(STATE_UNKNOWN,_("Server port an integer\n")); - break; - case 'v': - if (strlen(optarg)<3) - return ERROR; - if (!strcmp(optarg,"LOAD1")) - vars_to_check=LOAD1; - else if (!strcmp(optarg,"LOAD5")) - vars_to_check=LOAD5; - else if (!strcmp(optarg,"LOAD15")) - vars_to_check=LOAD15; - else if (!strcmp(optarg,"CONNS")) - vars_to_check=CONNS; - else if (!strcmp(optarg,"LTCH")) - vars_to_check=LTCH; - else if (!strcmp(optarg,"DCB")) - vars_to_check=DCB; - else if (!strcmp(optarg,"TCB")) - vars_to_check=TCB; - else if (!strcmp(optarg,"CBUFF")) - vars_to_check=CBUFF; - else if (!strcmp(optarg,"CDBUFF")) - vars_to_check=CDBUFF; - else if (!strcmp(optarg,"LRUM")) - vars_to_check=LRUM; - else if (!strcmp(optarg,"LRUS")) - vars_to_check=LRUS; - else if (strncmp(optarg,"VPF",3)==0) { - vars_to_check=VPF; - volume_name = strdup (optarg+3); - if (!strcmp(volume_name,"")) - volume_name = strdup ("SYS"); - } - else if (strncmp(optarg,"VKF",3)==0) { - vars_to_check=VKF; - volume_name = strdup (optarg+3); - if (!strcmp(volume_name,"")) - volume_name = strdup ("SYS"); - } - else if (strncmp(optarg,"VMF",3)==0) { - vars_to_check=VMF; - volume_name = strdup (optarg+3); - if (!strcmp(volume_name,"")) - volume_name = strdup ("SYS"); - } - else if (!strcmp(optarg,"DSDB")) - vars_to_check=DSDB; - else if (!strcmp(optarg,"LOGINS")) - vars_to_check=LOGINS; - else if (!strcmp(optarg,"NRMH")) - vars_to_check=NRMH; - else if (!strcmp(optarg,"UPRB")) - vars_to_check=UPRB; - else if (!strcmp(optarg,"PUPRB")) - vars_to_check=PUPRB; - else if (!strncmp(optarg,"SAPENTRIES",10)) { - vars_to_check=SAPENTRIES; - if (strlen(optarg)>10) - sap_number=atoi(optarg+10); - else - sap_number=-1; - } - else if (!strcmp(optarg,"OFILES")) - vars_to_check=OFILES; - else if (strncmp(optarg,"VKP",3)==0) { - vars_to_check=VKP; - volume_name = strdup (optarg+3); - if (!strcmp(volume_name,"")) - volume_name = strdup ("SYS"); - } - else if (strncmp(optarg,"VMP",3)==0) { - vars_to_check=VMP; - volume_name = strdup (optarg+3); - if (!strcmp(volume_name,"")) - volume_name = strdup ("SYS"); - } - else if (strncmp(optarg,"VMU",3)==0) { - vars_to_check=VMU; - volume_name = strdup (optarg+3); - if (!strcmp(volume_name,"")) - volume_name = strdup ("SYS"); - } - else if (strncmp(optarg,"VPU",3)==0) { - vars_to_check=VPU; - volume_name = strdup (optarg+3); - if (!strcmp(volume_name,"")) - volume_name = strdup ("SYS"); - } - else if (strncmp(optarg,"VPP",3)==0) { - vars_to_check=VPP; - volume_name = strdup (optarg+3); - if (!strcmp(volume_name,"")) - volume_name = strdup ("SYS"); - } - else if (strncmp(optarg,"VKNP",4)==0) { - vars_to_check=VKNP; - volume_name = strdup (optarg+4); - if (!strcmp(volume_name,"")) - volume_name = strdup ("SYS"); - } - else if (strncmp(optarg,"VPNP",4)==0) { - vars_to_check=VPNP; - volume_name = strdup (optarg+4); - if (!strcmp(volume_name,"")) - volume_name = strdup("SYS"); - } - else if (!strcmp(optarg,"ABENDS")) - vars_to_check=ABENDS; - else if (!strcmp(optarg,"CSPROCS")) - vars_to_check=CSPROCS; - else if (!strcmp(optarg,"TSYNC")) - vars_to_check=TSYNC; - else if (!strcmp(optarg,"DSVER")) - vars_to_check=DSVER; - else if (!strcmp(optarg,"UPTIME")) { - vars_to_check=UPTIME; - } - else if (strncmp(optarg,"NLM:",4)==0) { - vars_to_check=NLM; - nlm_name=strdup (optarg+4); - } - else if (strncmp(optarg,"NRMP",4)==0) { - vars_to_check=NRMP; - nrmp_name = strdup (optarg+4); - if (!strcmp(nrmp_name,"")) - nrmp_name = strdup ("AVAILABLE_MEMORY"); - } - else if (strncmp(optarg,"NRMM",4)==0) { - vars_to_check=NRMM; - nrmm_name = strdup (optarg+4); - if (!strcmp(nrmm_name,"")) - nrmm_name = strdup ("AVAILABLE_CACHE_MEMORY"); - - } - - else if (strncmp(optarg,"NRMS",4)==0) { - vars_to_check=NRMS; - nrms_name = strdup (optarg+4); - if (!strcmp(nrms_name,"")) - nrms_name = strdup ("USED_SWAP_SPACE"); - - } - - else if (strncmp(optarg,"NSS1",4)==0) { - vars_to_check=NSS1; - nss1_name = strdup (optarg+4); - if (!strcmp(nss1_name,"")) - nss1_name = strdup ("CURRENTBUFFERCACHESIZE"); - - } - - else if (strncmp(optarg,"NSS2",4)==0) { - vars_to_check=NSS2; - nss2_name = strdup (optarg+4); - if (!strcmp(nss2_name,"")) - nss2_name = strdup ("CACHEHITS"); - - } - - else if (strncmp(optarg,"NSS3",4)==0) { - vars_to_check=NSS3; - nss3_name = strdup (optarg+4); - if (!strcmp(nss3_name,"")) - nss3_name = strdup ("CACHEGITPERCENT"); - - } - - else if (strncmp(optarg,"NSS4",4)==0) { - vars_to_check=NSS4; - nss4_name = strdup (optarg+4); - if (!strcmp(nss4_name,"")) - nss4_name = strdup ("CURRENTOPENCOUNT"); - - } - - else if (strncmp(optarg,"NSS5",4)==0) { - vars_to_check=NSS5; - nss5_name = strdup (optarg+4); - if (!strcmp(nss5_name,"")) - nss5_name = strdup ("CACHEMISSES"); - - } - - - else if (strncmp(optarg,"NSS6",4)==0) { - vars_to_check=NSS6; - nss6_name = strdup (optarg+4); - if (!strcmp(nss6_name,"")) - nss6_name = strdup ("PENDINGWORKSCOUNT"); - - } - - - else if (strncmp(optarg,"NSS7",4)==0) { - vars_to_check=NSS7; - nss7_name = strdup (optarg+4); - if (!strcmp(nss7_name,"")) - nss7_name = strdup ("CACHESIZE"); - - } + sap_number = -1; + } else if (!strcmp(optarg, "OFILES")) + vars_to_check = OFILES; + else if (strncmp(optarg, "VKP", 3) == 0) { + vars_to_check = VKP; + volume_name = strdup(optarg + 3); + if (!strcmp(volume_name, "")) + volume_name = strdup("SYS"); + } else if (strncmp(optarg, "VMP", 3) == 0) { + vars_to_check = VMP; + volume_name = strdup(optarg + 3); + if (!strcmp(volume_name, "")) + volume_name = strdup("SYS"); + } else if (strncmp(optarg, "VMU", 3) == 0) { + vars_to_check = VMU; + volume_name = strdup(optarg + 3); + if (!strcmp(volume_name, "")) + volume_name = strdup("SYS"); + } else if (strncmp(optarg, "VPU", 3) == 0) { + vars_to_check = VPU; + volume_name = strdup(optarg + 3); + if (!strcmp(volume_name, "")) + volume_name = strdup("SYS"); + } else if (strncmp(optarg, "VPP", 3) == 0) { + vars_to_check = VPP; + volume_name = strdup(optarg + 3); + if (!strcmp(volume_name, "")) + volume_name = strdup("SYS"); + } else if (strncmp(optarg, "VKNP", 4) == 0) { + vars_to_check = VKNP; + volume_name = strdup(optarg + 4); + if (!strcmp(volume_name, "")) + volume_name = strdup("SYS"); + } else if (strncmp(optarg, "VPNP", 4) == 0) { + vars_to_check = VPNP; + volume_name = strdup(optarg + 4); + if (!strcmp(volume_name, "")) + volume_name = strdup("SYS"); + } else if (!strcmp(optarg, "ABENDS")) + vars_to_check = ABENDS; + else if (!strcmp(optarg, "CSPROCS")) + vars_to_check = CSPROCS; + else if (!strcmp(optarg, "TSYNC")) + vars_to_check = TSYNC; + else if (!strcmp(optarg, "DSVER")) + vars_to_check = DSVER; + else if (!strcmp(optarg, "UPTIME")) { + vars_to_check = UPTIME; + } else if (strncmp(optarg, "NLM:", 4) == 0) { + vars_to_check = NLM; + nlm_name = strdup(optarg + 4); + } else if (strncmp(optarg, "NRMP", 4) == 0) { + vars_to_check = NRMP; + nrmp_name = strdup(optarg + 4); + if (!strcmp(nrmp_name, "")) + nrmp_name = strdup("AVAILABLE_MEMORY"); + } else if (strncmp(optarg, "NRMM", 4) == 0) { + vars_to_check = NRMM; + nrmm_name = strdup(optarg + 4); + if (!strcmp(nrmm_name, "")) + nrmm_name = strdup("AVAILABLE_CACHE_MEMORY"); + } + + else if (strncmp(optarg, "NRMS", 4) == 0) { + vars_to_check = NRMS; + nrms_name = strdup(optarg + 4); + if (!strcmp(nrms_name, "")) + nrms_name = strdup("USED_SWAP_SPACE"); - else - return ERROR; - break; - case 'w': /* warning threshold */ - warning_value=strtoul(optarg,NULL,10); - check_warning_value = true; - break; - case 'c': /* critical threshold */ - critical_value=strtoul(optarg,NULL,10); - check_critical_value = true; - break; - case 't': /* timeout */ - socket_timeout=atoi(optarg); - if (socket_timeout<=0) - return ERROR; } + else if (strncmp(optarg, "NSS1", 4) == 0) { + vars_to_check = NSS1; + nss1_name = strdup(optarg + 4); + if (!strcmp(nss1_name, "")) + nss1_name = strdup("CURRENTBUFFERCACHESIZE"); + + } + + else if (strncmp(optarg, "NSS2", 4) == 0) { + vars_to_check = NSS2; + nss2_name = strdup(optarg + 4); + if (!strcmp(nss2_name, "")) + nss2_name = strdup("CACHEHITS"); + + } + + else if (strncmp(optarg, "NSS3", 4) == 0) { + vars_to_check = NSS3; + nss3_name = strdup(optarg + 4); + if (!strcmp(nss3_name, "")) + nss3_name = strdup("CACHEGITPERCENT"); + + } + + else if (strncmp(optarg, "NSS4", 4) == 0) { + vars_to_check = NSS4; + nss4_name = strdup(optarg + 4); + if (!strcmp(nss4_name, "")) + nss4_name = strdup("CURRENTOPENCOUNT"); + + } + + else if (strncmp(optarg, "NSS5", 4) == 0) { + vars_to_check = NSS5; + nss5_name = strdup(optarg + 4); + if (!strcmp(nss5_name, "")) + nss5_name = strdup("CACHEMISSES"); + + } + + else if (strncmp(optarg, "NSS6", 4) == 0) { + vars_to_check = NSS6; + nss6_name = strdup(optarg + 4); + if (!strcmp(nss6_name, "")) + nss6_name = strdup("PENDINGWORKSCOUNT"); + + } + + else if (strncmp(optarg, "NSS7", 4) == 0) { + vars_to_check = NSS7; + nss7_name = strdup(optarg + 4); + if (!strcmp(nss7_name, "")) + nss7_name = strdup("CACHESIZE"); + + } + + else + return ERROR; + break; + case 'w': /* warning threshold */ + warning_value = strtoul(optarg, NULL, 10); + check_warning_value = true; + break; + case 'c': /* critical threshold */ + critical_value = strtoul(optarg, NULL, 10); + check_critical_value = true; + break; + case 't': /* timeout */ + socket_timeout = atoi(optarg); + if (socket_timeout <= 0) + return ERROR; + } } return OK; } - - -void print_help(void) -{ +void print_help(void) { char *myport; - xasprintf (&myport, "%d", PORT); + xasprintf(&myport, "%d", PORT); - print_revision (progname, NP_VERSION); + 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 attempts to contact the MRTGEXT NLM running on a")); - printf ("%s\n", _("Novell server to gather the requested system information.")); + printf("%s\n", _("This plugin attempts to contact the MRTGEXT NLM running on a")); + printf("%s\n", _("Novell server to gather the requested system information.")); - printf ("\n\n"); + printf("\n\n"); print_usage(); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); - - printf (UT_HOST_PORT, 'p', myport); - - printf (" %s\n", "-v, --variable=STRING"); - printf (" %s\n", _("Variable to check. Valid variables include:")); - printf (" %s\n", _("LOAD1 = 1 minute average CPU load")); - printf (" %s\n", _("LOAD5 = 5 minute average CPU load")); - printf (" %s\n", _("LOAD15 = 15 minute average CPU load")); - printf (" %s\n", _("CSPROCS = number of current service processes (NW 5.x only)")); - printf (" %s\n", _("ABENDS = number of abended threads (NW 5.x only)")); - printf (" %s\n", _("UPTIME = server uptime")); - printf (" %s\n", _("LTCH = percent long term cache hits")); - printf (" %s\n", _("CBUFF = current number of cache buffers")); - printf (" %s\n", _("CDBUFF = current number of dirty cache buffers")); - printf (" %s\n", _("DCB = dirty cache buffers as a percentage of the total")); - printf (" %s\n", _("TCB = dirty cache buffers as a percentage of the original")); - printf (" %s\n", _("OFILES = number of open files")); - printf (" %s\n", _(" VMF = MB of free space on Volume ")); - printf (" %s\n", _(" VMU = MB used space on Volume ")); - printf (" %s\n", _(" VPU = percent used space on Volume ")); - printf (" %s\n", _(" VMP = MB of purgeable space on Volume ")); - printf (" %s\n", _(" VPF = percent free space on volume ")); - printf (" %s\n", _(" VKF = KB of free space on volume ")); - printf (" %s\n", _(" VPP = percent purgeable space on volume ")); - printf (" %s\n", _(" VKP = KB of purgeable space on volume ")); - printf (" %s\n", _(" VPNP = percent not yet purgeable space on volume ")); - printf (" %s\n", _(" VKNP = KB of not yet purgeable space on volume ")); - printf (" %s\n", _(" LRUM = LRU sitting time in minutes")); - printf (" %s\n", _(" LRUS = LRU sitting time in seconds")); - printf (" %s\n", _(" DSDB = check to see if DS Database is open")); - printf (" %s\n", _(" DSVER = NDS version")); - printf (" %s\n", _(" UPRB = used packet receive buffers")); - printf (" %s\n", _(" PUPRB = percent (of max) used packet receive buffers")); - printf (" %s\n", _(" SAPENTRIES = number of entries in the SAP table")); - printf (" %s\n", _(" SAPENTRIES = number of entries in the SAP table for SAP type ")); - printf (" %s\n", _(" TSYNC = timesync status")); - printf (" %s\n", _(" LOGINS = check to see if logins are enabled")); - printf (" %s\n", _(" CONNS = number of currently licensed connections")); - printf (" %s\n", _(" NRMH = NRM Summary Status")); - printf (" %s\n", _(" NRMP = Returns the current value for a NRM health item")); - printf (" %s\n", _(" NRMM = Returns the current memory stats from NRM")); - printf (" %s\n", _(" NRMS = Returns the current Swapfile stats from NRM")); - printf (" %s\n", _(" NSS1 = Statistics from _Admin:Manage_NSS\\GeneralStats.xml")); - printf (" %s\n", _(" NSS3 = Statistics from _Admin:Manage_NSS\\NameCache.xml")); - printf (" %s\n", _(" NSS4 = Statistics from _Admin:Manage_NSS\\FileStats.xml")); - printf (" %s\n", _(" NSS5 = Statistics from _Admin:Manage_NSS\\ObjectCache.xml")); - printf (" %s\n", _(" NSS6 = Statistics from _Admin:Manage_NSS\\Thread.xml")); - printf (" %s\n", _(" NSS7 = Statistics from _Admin:Manage_NSS\\AuthorizationCache.xml")); - printf (" %s\n", _(" NLM: = check if NLM is loaded and report version")); - printf (" %s\n", _(" (e.g. NLM:TSANDS.NLM)")); - printf ("\n"); - printf (" %s\n", "-w, --warning=INTEGER"); - printf (" %s\n", _("Threshold which will result in a warning status")); - printf (" %s\n", "-c, --critical=INTEGER"); - printf (" %s\n", _("Threshold which will result in a critical status")); - printf (" %s\n", "-o, --osversion"); - printf (" %s\n", _("Include server version string in results")); - - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - - printf ("\n"); - printf ("%s\n", _("Notes:")); - printf (" %s\n", _("- This plugin requires that the MRTGEXT.NLM file from James Drews' MRTG")); - printf (" %s\n", _(" extension for NetWare be loaded on the Novell servers you wish to check.")); - printf (" %s\n", _(" (available from http://www.engr.wisc.edu/~drews/mrtg/)")); - printf (" %s\n", _("- Values for critical thresholds should be lower than warning thresholds")); - printf (" %s\n", _(" when the following variables are checked: VPF, VKF, LTCH, CBUFF, DCB, ")); - printf (" %s\n", _(" TCB, LRUS and LRUM.")); - - printf (UT_SUPPORT); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); + + printf(UT_HOST_PORT, 'p', myport); + + printf(" %s\n", "-v, --variable=STRING"); + printf(" %s\n", _("Variable to check. Valid variables include:")); + printf(" %s\n", _("LOAD1 = 1 minute average CPU load")); + printf(" %s\n", _("LOAD5 = 5 minute average CPU load")); + printf(" %s\n", _("LOAD15 = 15 minute average CPU load")); + printf(" %s\n", _("CSPROCS = number of current service processes (NW 5.x only)")); + printf(" %s\n", _("ABENDS = number of abended threads (NW 5.x only)")); + printf(" %s\n", _("UPTIME = server uptime")); + printf(" %s\n", _("LTCH = percent long term cache hits")); + printf(" %s\n", _("CBUFF = current number of cache buffers")); + printf(" %s\n", _("CDBUFF = current number of dirty cache buffers")); + printf(" %s\n", _("DCB = dirty cache buffers as a percentage of the total")); + printf(" %s\n", _("TCB = dirty cache buffers as a percentage of the original")); + printf(" %s\n", _("OFILES = number of open files")); + printf(" %s\n", _(" VMF = MB of free space on Volume ")); + printf(" %s\n", _(" VMU = MB used space on Volume ")); + printf(" %s\n", _(" VPU = percent used space on Volume ")); + printf(" %s\n", _(" VMP = MB of purgeable space on Volume ")); + printf(" %s\n", _(" VPF = percent free space on volume ")); + printf(" %s\n", _(" VKF = KB of free space on volume ")); + printf(" %s\n", _(" VPP = percent purgeable space on volume ")); + printf(" %s\n", _(" VKP = KB of purgeable space on volume ")); + printf(" %s\n", _(" VPNP = percent not yet purgeable space on volume ")); + printf(" %s\n", _(" VKNP = KB of not yet purgeable space on volume ")); + printf(" %s\n", _(" LRUM = LRU sitting time in minutes")); + printf(" %s\n", _(" LRUS = LRU sitting time in seconds")); + printf(" %s\n", _(" DSDB = check to see if DS Database is open")); + printf(" %s\n", _(" DSVER = NDS version")); + printf(" %s\n", _(" UPRB = used packet receive buffers")); + printf(" %s\n", _(" PUPRB = percent (of max) used packet receive buffers")); + printf(" %s\n", _(" SAPENTRIES = number of entries in the SAP table")); + printf(" %s\n", _(" SAPENTRIES = number of entries in the SAP table for SAP type ")); + printf(" %s\n", _(" TSYNC = timesync status")); + printf(" %s\n", _(" LOGINS = check to see if logins are enabled")); + printf(" %s\n", _(" CONNS = number of currently licensed connections")); + printf(" %s\n", _(" NRMH = NRM Summary Status")); + printf(" %s\n", _(" NRMP = Returns the current value for a NRM health item")); + printf(" %s\n", _(" NRMM = Returns the current memory stats from NRM")); + printf(" %s\n", _(" NRMS = Returns the current Swapfile stats from NRM")); + printf(" %s\n", _(" NSS1 = Statistics from _Admin:Manage_NSS\\GeneralStats.xml")); + printf(" %s\n", _(" NSS3 = Statistics from _Admin:Manage_NSS\\NameCache.xml")); + printf(" %s\n", _(" NSS4 = Statistics from _Admin:Manage_NSS\\FileStats.xml")); + printf(" %s\n", _(" NSS5 = Statistics from _Admin:Manage_NSS\\ObjectCache.xml")); + printf(" %s\n", _(" NSS6 = Statistics from _Admin:Manage_NSS\\Thread.xml")); + printf(" %s\n", _(" NSS7 = Statistics from _Admin:Manage_NSS\\AuthorizationCache.xml")); + printf(" %s\n", _(" NLM: = check if NLM is loaded and report version")); + printf(" %s\n", _(" (e.g. NLM:TSANDS.NLM)")); + printf("\n"); + printf(" %s\n", "-w, --warning=INTEGER"); + printf(" %s\n", _("Threshold which will result in a warning status")); + printf(" %s\n", "-c, --critical=INTEGER"); + printf(" %s\n", _("Threshold which will result in a critical status")); + printf(" %s\n", "-o, --osversion"); + printf(" %s\n", _("Include server version string in results")); + + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + + printf("\n"); + printf("%s\n", _("Notes:")); + printf(" %s\n", _("- This plugin requires that the MRTGEXT.NLM file from James Drews' MRTG")); + printf(" %s\n", _(" extension for NetWare be loaded on the Novell servers you wish to check.")); + printf(" %s\n", _(" (available from http://www.engr.wisc.edu/~drews/mrtg/)")); + printf(" %s\n", _("- Values for critical thresholds should be lower than warning thresholds")); + printf(" %s\n", _(" when the following variables are checked: VPF, VKF, LTCH, CBUFF, DCB, ")); + printf(" %s\n", _(" TCB, LRUS and LRUM.")); + + printf(UT_SUPPORT); } - - -void print_usage(void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s -H host [-p port] [-v variable] [-w warning] [-c critical] [-t timeout]\n",progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s -H host [-p port] [-v variable] [-w warning] [-c critical] [-t timeout]\n", progname); } -- cgit v0.10-9-g596f From ac3cb0b7025b5661ffc385df5999b3c908797922 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:39:05 +0100 Subject: check_nwstat: update copyright diff --git a/plugins/check_nwstat.c b/plugins/check_nwstat.c index cb708df..3af6360 100644 --- a/plugins/check_nwstat.c +++ b/plugins/check_nwstat.c @@ -3,7 +3,7 @@ * Monitoring check_nwstat plugin * * License: GPL - * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -30,7 +30,7 @@ *****************************************************************************/ const char *progname = "check_nwstat"; -const char *copyright = "2000-2007"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 3b1ffd9264b232438be6965c398ecf3a6651b52c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:39:19 +0100 Subject: check_overcr: clang-format diff --git a/plugins/check_overcr.c b/plugins/check_overcr.c index 5165c82..21991db 100644 --- a/plugins/check_overcr.c +++ b/plugins/check_overcr.c @@ -1,33 +1,33 @@ /***************************************************************************** -* -* Monitoring check_overcr plugin -* -* License: GPL -* Copyright (c) 2000-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_overcr plugin -* -* This plugin attempts to contact the Over-CR collector daemon running on the -* remote UNIX server in order to gather the requested system information. -* -* -* 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_overcr plugin + * + * License: GPL + * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_overcr plugin + * + * This plugin attempts to contact the Over-CR collector daemon running on the + * remote UNIX server in order to gather the requested system information. + * + * + * 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_overcr"; const char *copyright = "2000-2007"; @@ -66,13 +66,11 @@ char *disk_name = NULL; char *process_name = NULL; char send_buffer[MAX_INPUT_BUFFER]; -int process_arguments (int, char **); -void print_usage (void); -void print_help (void); +int process_arguments(int, char **); +void print_usage(void); +void print_help(void); -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { int result = STATE_UNKNOWN; char recv_buffer[MAX_INPUT_BUFFER]; char temp_buffer[MAX_INPUT_BUFFER]; @@ -91,66 +89,62 @@ main (int argc, char **argv) int uptime_hours = 0; int uptime_minutes = 0; - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if (process_arguments (argc, argv) == ERROR) - usage4 (_("Could not parse arguments")); + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments")); /* initialize alarm signal handling */ - signal (SIGALRM, socket_timeout_alarm_handler); + signal(SIGALRM, socket_timeout_alarm_handler); /* set socket timeout */ - alarm (socket_timeout); + alarm(socket_timeout); - result = process_tcp_request2 (server_address, - server_port, - send_buffer, - recv_buffer, - sizeof (recv_buffer)); + result = process_tcp_request2(server_address, server_port, send_buffer, recv_buffer, sizeof(recv_buffer)); switch (vars_to_check) { case LOAD1: case LOAD5: case LOAD15: - + if (result != STATE_OK) - die (result, _("Unknown error fetching load data\n")); + die(result, _("Unknown error fetching load data\n")); - temp_ptr = (char *) strtok (recv_buffer, "\r\n"); + temp_ptr = (char *)strtok(recv_buffer, "\r\n"); if (temp_ptr == NULL) - die (STATE_CRITICAL, _("Invalid response from server - no load information\n")); + die(STATE_CRITICAL, _("Invalid response from server - no load information\n")); else - load_1min = strtod (temp_ptr, NULL); + load_1min = strtod(temp_ptr, NULL); - temp_ptr = (char *) strtok (NULL, "\r\n"); + temp_ptr = (char *)strtok(NULL, "\r\n"); if (temp_ptr == NULL) - die (STATE_CRITICAL, _("Invalid response from server after load 1\n")); + die(STATE_CRITICAL, _("Invalid response from server after load 1\n")); else - load_5min = strtod (temp_ptr, NULL); + load_5min = strtod(temp_ptr, NULL); - temp_ptr = (char *) strtok (NULL, "\r\n"); + temp_ptr = (char *)strtok(NULL, "\r\n"); if (temp_ptr == NULL) - die (STATE_CRITICAL, _("Invalid response from server after load 5\n")); + die(STATE_CRITICAL, _("Invalid response from server after load 5\n")); else - load_15min = strtod (temp_ptr, NULL); + load_15min = strtod(temp_ptr, NULL); switch (vars_to_check) { case LOAD1: - strcpy (temp_buffer, "1"); + strcpy(temp_buffer, "1"); load = load_1min; break; case LOAD5: - strcpy (temp_buffer, "5"); + strcpy(temp_buffer, "5"); load = load_5min; break; default: - strcpy (temp_buffer, "15"); + strcpy(temp_buffer, "15"); load = load_15min; break; } @@ -160,98 +154,82 @@ main (int argc, char **argv) else if (check_warning_value && (load >= warning_value)) result = STATE_WARNING; - die (result, - _("Load %s - %s-min load average = %0.2f"), - state_text(result), - temp_buffer, - load); + die(result, _("Load %s - %s-min load average = %0.2f"), state_text(result), temp_buffer, load); - break; + break; case DPU: if (result != STATE_OK) - die (result, _("Unknown error fetching disk data\n")); + die(result, _("Unknown error fetching disk data\n")); - for (temp_ptr = (char *) strtok (recv_buffer, " "); - temp_ptr != NULL; - temp_ptr = (char *) strtok (NULL, " ")) { + for (temp_ptr = (char *)strtok(recv_buffer, " "); temp_ptr != NULL; temp_ptr = (char *)strtok(NULL, " ")) { - if (!strcmp (temp_ptr, disk_name)) { + if (!strcmp(temp_ptr, disk_name)) { found_disk = true; - temp_ptr = (char *) strtok (NULL, "%"); + temp_ptr = (char *)strtok(NULL, "%"); if (temp_ptr == NULL) - die (STATE_CRITICAL, _("Invalid response from server\n")); + die(STATE_CRITICAL, _("Invalid response from server\n")); else - percent_used_disk_space = strtoul (temp_ptr, NULL, 10); + percent_used_disk_space = strtoul(temp_ptr, NULL, 10); break; } - temp_ptr = (char *) strtok (NULL, "\r\n"); + temp_ptr = (char *)strtok(NULL, "\r\n"); } /* error if we couldn't find the info for the disk */ if (!found_disk) - die (STATE_CRITICAL, - "CRITICAL - Disk '%s' non-existent or not mounted", - disk_name); + die(STATE_CRITICAL, "CRITICAL - Disk '%s' non-existent or not mounted", disk_name); if (check_critical_value && (percent_used_disk_space >= critical_value)) result = STATE_CRITICAL; else if (check_warning_value && (percent_used_disk_space >= warning_value)) result = STATE_WARNING; - die (result, "Disk %s - %lu%% used on %s", state_text(result), percent_used_disk_space, disk_name); + die(result, "Disk %s - %lu%% used on %s", state_text(result), percent_used_disk_space, disk_name); break; case NETSTAT: if (result != STATE_OK) - die (result, _("Unknown error fetching network status\n")); + die(result, _("Unknown error fetching network status\n")); else - port_connections = strtod (recv_buffer, NULL); + port_connections = strtod(recv_buffer, NULL); if (check_critical_value && (port_connections >= critical_value)) result = STATE_CRITICAL; else if (check_warning_value && (port_connections >= warning_value)) result = STATE_WARNING; - die (result, - _("Net %s - %d connection%s on port %d"), - state_text(result), - port_connections, - (port_connections == 1) ? "" : "s", - netstat_port); + die(result, _("Net %s - %d connection%s on port %d"), state_text(result), port_connections, (port_connections == 1) ? "" : "s", + netstat_port); break; case PROCS: if (result != STATE_OK) - die (result, _("Unknown error fetching process status\n")); + die(result, _("Unknown error fetching process status\n")); - temp_ptr = (char *) strtok (recv_buffer, "("); + temp_ptr = (char *)strtok(recv_buffer, "("); if (temp_ptr == NULL) - die (STATE_CRITICAL, _("Invalid response from server\n")); + die(STATE_CRITICAL, _("Invalid response from server\n")); - temp_ptr = (char *) strtok (NULL, ")"); + temp_ptr = (char *)strtok(NULL, ")"); if (temp_ptr == NULL) - die (STATE_CRITICAL, _("Invalid response from server\n")); + die(STATE_CRITICAL, _("Invalid response from server\n")); else - processes = strtod (temp_ptr, NULL); + processes = strtod(temp_ptr, NULL); if (check_critical_value && (processes >= critical_value)) result = STATE_CRITICAL; else if (check_warning_value && (processes >= warning_value)) result = STATE_WARNING; - die (result, - _("Process %s - %d instance%s of %s running"), - state_text(result), - processes, - (processes == 1) ? "" : "s", - process_name); + die(result, _("Process %s - %d instance%s of %s running"), state_text(result), processes, (processes == 1) ? "" : "s", + process_name); break; case UPTIME: @@ -259,8 +237,8 @@ main (int argc, char **argv) if (result != STATE_OK) return result; - uptime_raw_hours = strtod (recv_buffer, NULL); - uptime_raw_minutes = (unsigned long) (uptime_raw_hours * 60.0); + uptime_raw_hours = strtod(recv_buffer, NULL); + uptime_raw_minutes = (unsigned long)(uptime_raw_hours * 60.0); if (check_critical_value && (uptime_raw_minutes <= critical_value)) result = STATE_CRITICAL; @@ -273,46 +251,31 @@ main (int argc, char **argv) uptime_raw_minutes %= 60; uptime_minutes = uptime_raw_minutes; - die (result, - _("Uptime %s - Up %d days %d hours %d minutes"), - state_text(result), - uptime_days, - uptime_hours, - uptime_minutes); + die(result, _("Uptime %s - Up %d days %d hours %d minutes"), state_text(result), uptime_days, uptime_hours, uptime_minutes); break; default: - die (STATE_UNKNOWN, _("Nothing to check!\n")); + die(STATE_UNKNOWN, _("Nothing to check!\n")); break; } } - /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ +int process_arguments(int argc, char **argv) { int c; int option = 0; static struct option longopts[] = { - {"port", required_argument, 0, 'p'}, - {"timeout", required_argument, 0, 't'}, - {"critical", required_argument, 0, 'c'}, - {"warning", required_argument, 0, 'w'}, - {"variable", required_argument, 0, 'v'}, - {"hostname", required_argument, 0, 'H'}, - {"version", no_argument, 0, 'V'}, - {"help", no_argument, 0, 'h'}, - {0, 0, 0, 0} - }; + {"port", required_argument, 0, 'p'}, {"timeout", required_argument, 0, 't'}, {"critical", required_argument, 0, 'c'}, + {"warning", required_argument, 0, 'w'}, {"variable", required_argument, 0, 'v'}, {"hostname", required_argument, 0, 'H'}, + {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0}}; /* no options were supplied */ if (argc < 2) return ERROR; /* backwards compatibility */ - if (!is_option (argv[1])) { + if (!is_option(argv[1])) { server_address = argv[1]; argv[1] = argv[0]; argv = &argv[1]; @@ -320,150 +283,136 @@ process_arguments (int argc, char **argv) } for (c = 1; c < argc; c++) { - if (strcmp ("-to", argv[c]) == 0) - strcpy (argv[c], "-t"); - else if (strcmp ("-wv", argv[c]) == 0) - strcpy (argv[c], "-w"); - else if (strcmp ("-cv", argv[c]) == 0) - strcpy (argv[c], "-c"); + if (strcmp("-to", argv[c]) == 0) + strcpy(argv[c], "-t"); + else if (strcmp("-wv", argv[c]) == 0) + strcpy(argv[c], "-w"); + else if (strcmp("-cv", argv[c]) == 0) + strcpy(argv[c], "-c"); } while (1) { - c = getopt_long (argc, argv, "+hVH:t:c:w:p:v:", longopts, - &option); + c = getopt_long(argc, argv, "+hVH:t:c:w:p:v:", longopts, &option); if (c == -1 || c == EOF || c == 1) break; switch (c) { - case '?': /* print short usage statement if args not parsable */ - usage5 (); - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'H': /* hostname */ + case '?': /* print short usage statement if args not parsable */ + usage5(); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'H': /* hostname */ server_address = optarg; break; - case 'p': /* port */ - if (is_intnonneg (optarg)) - server_port = atoi (optarg); + case 'p': /* port */ + if (is_intnonneg(optarg)) + server_port = atoi(optarg); else - die (STATE_UNKNOWN, - _("Server port an integer\n")); + die(STATE_UNKNOWN, _("Server port an integer\n")); break; - case 'v': /* variable */ - if (strcmp (optarg, "LOAD") == 0) { - strcpy (send_buffer, "LOAD\r\nQUIT\r\n"); - if (strcmp (optarg, "LOAD1") == 0) + case 'v': /* variable */ + if (strcmp(optarg, "LOAD") == 0) { + strcpy(send_buffer, "LOAD\r\nQUIT\r\n"); + if (strcmp(optarg, "LOAD1") == 0) vars_to_check = LOAD1; - else if (strcmp (optarg, "LOAD5") == 0) + else if (strcmp(optarg, "LOAD5") == 0) vars_to_check = LOAD5; - else if (strcmp (optarg, "LOAD15") == 0) + else if (strcmp(optarg, "LOAD15") == 0) vars_to_check = LOAD15; - } - else if (strcmp (optarg, "UPTIME") == 0) { + } else if (strcmp(optarg, "UPTIME") == 0) { vars_to_check = UPTIME; - strcpy (send_buffer, "UPTIME\r\n"); - } - else if (strstr (optarg, "PROC") == optarg) { + strcpy(send_buffer, "UPTIME\r\n"); + } else if (strstr(optarg, "PROC") == optarg) { vars_to_check = PROCS; - process_name = strscpy (process_name, optarg + 4); - sprintf (send_buffer, "PROCESS %s\r\n", process_name); - } - else if (strstr (optarg, "NET") == optarg) { + process_name = strscpy(process_name, optarg + 4); + sprintf(send_buffer, "PROCESS %s\r\n", process_name); + } else if (strstr(optarg, "NET") == optarg) { vars_to_check = NETSTAT; - netstat_port = atoi (optarg + 3); - sprintf (send_buffer, "NETSTAT %d\r\n", netstat_port); - } - else if (strstr (optarg, "DPU") == optarg) { + netstat_port = atoi(optarg + 3); + sprintf(send_buffer, "NETSTAT %d\r\n", netstat_port); + } else if (strstr(optarg, "DPU") == optarg) { vars_to_check = DPU; - strcpy (send_buffer, "DISKSPACE\r\n"); - disk_name = strscpy (disk_name, optarg + 3); - } - else + strcpy(send_buffer, "DISKSPACE\r\n"); + disk_name = strscpy(disk_name, optarg + 3); + } else return ERROR; break; - case 'w': /* warning threshold */ - warning_value = strtoul (optarg, NULL, 10); + case 'w': /* warning threshold */ + warning_value = strtoul(optarg, NULL, 10); check_warning_value = true; break; - case 'c': /* critical threshold */ - critical_value = strtoul (optarg, NULL, 10); + case 'c': /* critical threshold */ + critical_value = strtoul(optarg, NULL, 10); check_critical_value = true; break; - case 't': /* timeout */ - socket_timeout = atoi (optarg); + case 't': /* timeout */ + socket_timeout = atoi(optarg); if (socket_timeout <= 0) return ERROR; } - } return OK; } - -void -print_help (void) -{ +void print_help(void) { char *myport; - xasprintf (&myport, "%d", PORT); + xasprintf(&myport, "%d", PORT); - print_revision (progname, NP_VERSION); + 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 attempts to contact the Over-CR collector daemon running on the")); - printf ("%s\n", _("remote UNIX server in order to gather the requested system information.")); + printf("%s\n", _("This plugin attempts to contact the Over-CR collector daemon running on the")); + printf("%s\n", _("remote UNIX server in order to gather the requested system information.")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); - printf (UT_HOST_PORT, 'p', myport); + printf(UT_HOST_PORT, 'p', myport); - printf (" %s\n", "-w, --warning=INTEGER"); - printf (" %s\n", _("Threshold which will result in a warning status")); - printf (" %s\n", "-c, --critical=INTEGER"); - printf (" %s\n", _("Threshold which will result in a critical status")); - printf (" %s\n", "-v, --variable=STRING"); - printf (" %s\n", _("Variable to check. Valid variables include:")); - printf (" %s\n", _("LOAD1 = 1 minute average CPU load")); - printf (" %s\n", _("LOAD5 = 5 minute average CPU load")); - printf (" %s\n", _("LOAD15 = 15 minute average CPU load")); - printf (" %s\n", _("DPU = percent used disk space on filesystem ")); - printf (" %s\n", _("PROC = number of running processes with name ")); - printf (" %s\n", _("NET = number of active connections on TCP port ")); - printf (" %s\n", _("UPTIME = system uptime in seconds")); + printf(" %s\n", "-w, --warning=INTEGER"); + printf(" %s\n", _("Threshold which will result in a warning status")); + printf(" %s\n", "-c, --critical=INTEGER"); + printf(" %s\n", _("Threshold which will result in a critical status")); + printf(" %s\n", "-v, --variable=STRING"); + printf(" %s\n", _("Variable to check. Valid variables include:")); + printf(" %s\n", _("LOAD1 = 1 minute average CPU load")); + printf(" %s\n", _("LOAD5 = 5 minute average CPU load")); + printf(" %s\n", _("LOAD15 = 15 minute average CPU load")); + printf(" %s\n", _("DPU = percent used disk space on filesystem ")); + printf(" %s\n", _("PROC = number of running processes with name ")); + printf(" %s\n", _("NET = number of active connections on TCP port ")); + printf(" %s\n", _("UPTIME = system uptime in seconds")); - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - printf (UT_VERBOSE); + printf(UT_VERBOSE); - printf ("\n"); - printf ("%s\n", _("This plugin requires that Eric Molitors' Over-CR collector daemon be")); - printf ("%s\n", _("running on the remote server.")); - printf ("%s\n", _("Over-CR can be downloaded from http://www.molitor.org/overcr")); - printf ("%s\n", _("This plugin was tested with version 0.99.53 of the Over-CR collector")); + printf("\n"); + printf("%s\n", _("This plugin requires that Eric Molitors' Over-CR collector daemon be")); + printf("%s\n", _("running on the remote server.")); + printf("%s\n", _("Over-CR can be downloaded from http://www.molitor.org/overcr")); + printf("%s\n", _("This plugin was tested with version 0.99.53 of the Over-CR collector")); - printf ("\n"); - printf ("%s\n", _("Notes:")); - printf (" %s\n", _("For the available options, the critical threshold value should always be")); - printf (" %s\n", _("higher than the warning threshold value, EXCEPT with the uptime variable")); + printf("\n"); + printf("%s\n", _("Notes:")); + printf(" %s\n", _("For the available options, the critical threshold value should always be")); + printf(" %s\n", _("higher than the warning threshold value, EXCEPT with the uptime variable")); - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s -H host [-p port] [-v variable] [-w warning] [-c critical] [-t timeout]\n", progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s -H host [-p port] [-v variable] [-w warning] [-c critical] [-t timeout]\n", progname); } -- cgit v0.10-9-g596f From d08ac703906fb2508540b7a3ea00ab881599a494 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:40:13 +0100 Subject: check_overcr: update copyright diff --git a/plugins/check_overcr.c b/plugins/check_overcr.c index 21991db..e80d477 100644 --- a/plugins/check_overcr.c +++ b/plugins/check_overcr.c @@ -3,7 +3,7 @@ * Monitoring check_overcr plugin * * License: GPL - * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -30,7 +30,7 @@ *****************************************************************************/ const char *progname = "check_overcr"; -const char *copyright = "2000-2007"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 520617e398682322f0e79e932101d7235e41aeb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:41:42 +0100 Subject: check_nt: clang-format diff --git a/plugins/check_nt.c b/plugins/check_nt.c index 19c050d..e0d0c23 100644 --- a/plugins/check_nt.c +++ b/plugins/check_nt.c @@ -1,36 +1,36 @@ /***************************************************************************** -* -* Monitoring check_nt plugin -* -* License: GPL -* Copyright (c) 2000-2002 Yves Rubin (rubiyz@yahoo.com) -* Copyright (c) 2003-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_nt plugin -* -* This plugin collects data from the NSClient service running on a -* Windows NT/2000/XP/2003 server. -* This plugin requires NSClient software to run on NT -* (http://nsclient.ready2run.nl/) -* -* -* 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_nt plugin + * + * License: GPL + * Copyright (c) 2000-2002 Yves Rubin (rubiyz@yahoo.com) + * Copyright (c) 2003-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_nt plugin + * + * This plugin collects data from the NSClient service running on a + * Windows NT/2000/XP/2003 server. + * This plugin requires NSClient software to run on NT + * (http://nsclient.ready2run.nl/) + * + * + * 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_nt"; const char *copyright = "2000-2007"; @@ -59,75 +59,75 @@ enum { PORT = 1248 }; -char *server_address=NULL; -char *volume_name=NULL; -int server_port=PORT; -char *value_list=NULL; -char *req_password=NULL; +char *server_address = NULL; +char *volume_name = NULL; +int server_port = PORT; +char *value_list = NULL; +char *req_password = NULL; unsigned long lvalue_list[MAX_VALUE_LIST]; -unsigned long warning_value=0L; -unsigned long critical_value=0L; -bool check_warning_value=false; -bool check_critical_value=false; +unsigned long warning_value = 0L; +unsigned long critical_value = 0L; +bool check_warning_value = false; +bool check_critical_value = false; enum checkvars vars_to_check = CHECK_NONE; bool show_all = false; char recv_buffer[MAX_INPUT_BUFFER]; -void fetch_data (const char* address, int port, const char* sendb); +void fetch_data(const char *address, int port, const char *sendb); int process_arguments(int, char **); void preparelist(char *string); bool strtoularray(unsigned long *array, char *string, const char *delim); void print_help(void); void print_usage(void); -int main(int argc, char **argv){ +int main(int argc, char **argv) { -/* should be int result = STATE_UNKNOWN; */ + /* should be int result = STATE_UNKNOWN; */ int return_code = STATE_UNKNOWN; - char *send_buffer=NULL; - char *output_message=NULL; - char *perfdata=NULL; - char *temp_string=NULL; - char *temp_string_perf=NULL; - char *description=NULL,*counter_unit = NULL; + char *send_buffer = NULL; + char *output_message = NULL; + char *perfdata = NULL; + char *temp_string = NULL; + char *temp_string_perf = NULL; + char *description = NULL, *counter_unit = NULL; char *minval = NULL, *maxval = NULL, *errcvt = NULL; - char *fds=NULL, *tds=NULL; + char *fds = NULL, *tds = NULL; char *numstr; - double total_disk_space=0; - double free_disk_space=0; - double percent_used_space=0; - double warning_used_space=0; - double critical_used_space=0; - double mem_commitLimit=0; - double mem_commitByte=0; + double total_disk_space = 0; + double free_disk_space = 0; + double percent_used_space = 0; + double warning_used_space = 0; + double critical_used_space = 0; + double mem_commitLimit = 0; + double mem_commitByte = 0; double fminval = 0, fmaxval = 0; unsigned long utilization; unsigned long uptime; unsigned long age_in_minutes; double counter_value = 0.0; - int offset=0; - int updays=0; - int uphours=0; - int upminutes=0; + int offset = 0; + int updays = 0; + int uphours = 0; + int upminutes = 0; bool isPercent = false; bool allRight = false; - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if(process_arguments(argc,argv) == ERROR) - usage4 (_("Could not parse arguments")); + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments")); /* initialize alarm signal handling */ - signal(SIGALRM,socket_timeout_alarm_handler); + signal(SIGALRM, socket_timeout_alarm_handler); /* set socket timeout */ alarm(socket_timeout); @@ -137,61 +137,58 @@ int main(int argc, char **argv){ case CHECK_CLIENTVERSION: xasprintf(&send_buffer, "%s&1", req_password); - fetch_data (server_address, server_port, send_buffer); + fetch_data(server_address, server_port, send_buffer); if (value_list != NULL && strcmp(recv_buffer, value_list) != 0) { - xasprintf (&output_message, _("Wrong client version - running: %s, required: %s"), recv_buffer, value_list); + xasprintf(&output_message, _("Wrong client version - running: %s, required: %s"), recv_buffer, value_list); return_code = STATE_WARNING; } else { - xasprintf (&output_message, "%s", recv_buffer); + xasprintf(&output_message, "%s", recv_buffer); return_code = STATE_OK; } break; case CHECK_CPULOAD: - if (value_list==NULL) - output_message = strdup (_("missing -l parameters")); - else if (! strtoularray(lvalue_list,value_list,",")) - output_message = strdup (_("wrong -l parameter.")); + if (value_list == NULL) + output_message = strdup(_("missing -l parameters")); + else if (!strtoularray(lvalue_list, value_list, ",")) + output_message = strdup(_("wrong -l parameter.")); else { /* -l parameters is present with only integers */ - return_code=STATE_OK; - temp_string = strdup (_("CPU Load")); - temp_string_perf = strdup (" "); + return_code = STATE_OK; + temp_string = strdup(_("CPU Load")); + temp_string_perf = strdup(" "); /* loop until one of the parameters is wrong or not present */ - while (lvalue_list[0+offset]> (unsigned long)0 && - lvalue_list[0+offset]<=(unsigned long)17280 && - lvalue_list[1+offset]> (unsigned long)0 && - lvalue_list[1+offset]<=(unsigned long)100 && - lvalue_list[2+offset]> (unsigned long)0 && - lvalue_list[2+offset]<=(unsigned long)100) { + while (lvalue_list[0 + offset] > (unsigned long)0 && lvalue_list[0 + offset] <= (unsigned long)17280 && + lvalue_list[1 + offset] > (unsigned long)0 && lvalue_list[1 + offset] <= (unsigned long)100 && + lvalue_list[2 + offset] > (unsigned long)0 && lvalue_list[2 + offset] <= (unsigned long)100) { /* Send request and retrieve data */ - xasprintf(&send_buffer,"%s&2&%lu",req_password,lvalue_list[0+offset]); - fetch_data (server_address, server_port, send_buffer); + xasprintf(&send_buffer, "%s&2&%lu", req_password, lvalue_list[0 + offset]); + fetch_data(server_address, server_port, send_buffer); - utilization=strtoul(recv_buffer,NULL,10); + utilization = strtoul(recv_buffer, NULL, 10); /* Check if any of the request is in a warning or critical state */ - if(utilization >= lvalue_list[2+offset]) - return_code=STATE_CRITICAL; - else if(utilization >= lvalue_list[1+offset] && return_code= lvalue_list[2 + offset]) + return_code = STATE_CRITICAL; + else if (utilization >= lvalue_list[1 + offset] && return_code < STATE_WARNING) + return_code = STATE_WARNING; + + xasprintf(&output_message, _(" %lu%% (%lu min average)"), utilization, lvalue_list[0 + offset]); + xasprintf(&temp_string, "%s%s", temp_string, output_message); + xasprintf(&perfdata, _(" '%lu min avg Load'=%lu%%;%lu;%lu;0;100"), lvalue_list[0 + offset], utilization, + lvalue_list[1 + offset], lvalue_list[2 + offset]); + xasprintf(&temp_string_perf, "%s%s", temp_string_perf, perfdata); + offset += 3; /* move across the array */ } - if (strlen(temp_string)>10) { /* we had at least one loop */ - output_message = strdup (temp_string); + if (strlen(temp_string) > 10) { /* we had at least one loop */ + output_message = strdup(temp_string); perfdata = temp_string_perf; } else - output_message = strdup (_("not enough values for -l parameters")); + output_message = strdup(_("not enough values for -l parameters")); } break; @@ -200,16 +197,14 @@ int main(int argc, char **argv){ if (value_list == NULL) { value_list = "minutes"; } - if (strncmp(value_list, "seconds", strlen("seconds") + 1 ) && - strncmp(value_list, "minutes", strlen("minutes") + 1) && - strncmp(value_list, "hours", strlen("hours") + 1) && - strncmp(value_list, "days", strlen("days") + 1)) { + if (strncmp(value_list, "seconds", strlen("seconds") + 1) && strncmp(value_list, "minutes", strlen("minutes") + 1) && + strncmp(value_list, "hours", strlen("hours") + 1) && strncmp(value_list, "days", strlen("days") + 1)) { - output_message = strdup (_("wrong -l argument")); + output_message = strdup(_("wrong -l argument")); } else { xasprintf(&send_buffer, "%s&3", req_password); - fetch_data (server_address, server_port, send_buffer); - uptime=strtoul(recv_buffer,NULL,10); + fetch_data(server_address, server_port, send_buffer); + uptime = strtoul(recv_buffer, NULL, 10); updays = uptime / 86400; uphours = (uptime % 86400) / 3600; upminutes = ((uptime % 86400) % 3600) / 60; @@ -222,57 +217,58 @@ int main(int argc, char **argv){ uptime = uptime / 86400; /* else uptime in seconds, nothing to do */ - xasprintf(&output_message,_("System Uptime - %u day(s) %u hour(s) %u minute(s) |uptime=%lu"),updays, uphours, upminutes, uptime); + xasprintf(&output_message, _("System Uptime - %u day(s) %u hour(s) %u minute(s) |uptime=%lu"), updays, uphours, upminutes, + uptime); if (check_critical_value && uptime <= critical_value) - return_code=STATE_CRITICAL; + return_code = STATE_CRITICAL; else if (check_warning_value && uptime <= warning_value) - return_code=STATE_WARNING; + return_code = STATE_WARNING; else - return_code=STATE_OK; + return_code = STATE_OK; } break; case CHECK_USEDDISKSPACE: - if (value_list==NULL) - output_message = strdup (_("missing -l parameters")); - else if (strlen(value_list)!=1) - output_message = strdup (_("wrong -l argument")); + if (value_list == NULL) + output_message = strdup(_("missing -l parameters")); + else if (strlen(value_list) != 1) + output_message = strdup(_("wrong -l argument")); else { - xasprintf(&send_buffer,"%s&4&%s", req_password, value_list); - fetch_data (server_address, server_port, send_buffer); - fds=strtok(recv_buffer,"&"); - tds=strtok(NULL,"&"); - if(fds!=NULL) - free_disk_space=atof(fds); - if(tds!=NULL) - total_disk_space=atof(tds); - - if (total_disk_space>0 && free_disk_space>=0) { + xasprintf(&send_buffer, "%s&4&%s", req_password, value_list); + fetch_data(server_address, server_port, send_buffer); + fds = strtok(recv_buffer, "&"); + tds = strtok(NULL, "&"); + if (fds != NULL) + free_disk_space = atof(fds); + if (tds != NULL) + total_disk_space = atof(tds); + + if (total_disk_space > 0 && free_disk_space >= 0) { percent_used_space = ((total_disk_space - free_disk_space) / total_disk_space) * 100; warning_used_space = ((float)warning_value / 100) * total_disk_space; critical_used_space = ((float)critical_value / 100) * total_disk_space; - xasprintf(&temp_string,_("%s:\\ - total: %.2f Gb - used: %.2f Gb (%.0f%%) - free %.2f Gb (%.0f%%)"), - value_list, total_disk_space / 1073741824, (total_disk_space - free_disk_space) / 1073741824, - percent_used_space, free_disk_space / 1073741824, (free_disk_space / total_disk_space)*100); - xasprintf(&temp_string_perf,_("'%s:\\ Used Space'=%.2fGb;%.2f;%.2f;0.00;%.2f"), value_list, - (total_disk_space - free_disk_space) / 1073741824, warning_used_space / 1073741824, - critical_used_space / 1073741824, total_disk_space / 1073741824); + xasprintf(&temp_string, _("%s:\\ - total: %.2f Gb - used: %.2f Gb (%.0f%%) - free %.2f Gb (%.0f%%)"), value_list, + total_disk_space / 1073741824, (total_disk_space - free_disk_space) / 1073741824, percent_used_space, + free_disk_space / 1073741824, (free_disk_space / total_disk_space) * 100); + xasprintf(&temp_string_perf, _("'%s:\\ Used Space'=%.2fGb;%.2f;%.2f;0.00;%.2f"), value_list, + (total_disk_space - free_disk_space) / 1073741824, warning_used_space / 1073741824, + critical_used_space / 1073741824, total_disk_space / 1073741824); - if(check_critical_value && percent_used_space >= critical_value) - return_code=STATE_CRITICAL; + if (check_critical_value && percent_used_space >= critical_value) + return_code = STATE_CRITICAL; else if (check_warning_value && percent_used_space >= warning_value) - return_code=STATE_WARNING; + return_code = STATE_WARNING; else - return_code=STATE_OK; + return_code = STATE_OK; - output_message = strdup (temp_string); + output_message = strdup(temp_string); perfdata = temp_string_perf; } else { - output_message = strdup (_("Free disk space : Invalid drive")); - return_code=STATE_UNKNOWN; + output_message = strdup(_("Free disk space : Invalid drive")); + return_code = STATE_UNKNOWN; } } break; @@ -280,57 +276,56 @@ int main(int argc, char **argv){ case CHECK_SERVICESTATE: case CHECK_PROCSTATE: - if (value_list==NULL) - output_message = strdup (_("No service/process specified")); + if (value_list == NULL) + output_message = strdup(_("No service/process specified")); else { - preparelist(value_list); /* replace , between services with & to send the request */ - xasprintf(&send_buffer,"%s&%u&%s&%s", req_password,(vars_to_check==CHECK_SERVICESTATE)?5:6, - (show_all) ? "ShowAll" : "ShowFail",value_list); - fetch_data (server_address, server_port, send_buffer); - numstr = strtok(recv_buffer,"&"); + preparelist(value_list); /* replace , between services with & to send the request */ + xasprintf(&send_buffer, "%s&%u&%s&%s", req_password, (vars_to_check == CHECK_SERVICESTATE) ? 5 : 6, + (show_all) ? "ShowAll" : "ShowFail", value_list); + fetch_data(server_address, server_port, send_buffer); + numstr = strtok(recv_buffer, "&"); if (numstr == NULL) die(STATE_UNKNOWN, _("could not fetch information from server\n")); - return_code=atoi(numstr); - temp_string=strtok(NULL,"&"); - output_message = strdup (temp_string); + return_code = atoi(numstr); + temp_string = strtok(NULL, "&"); + output_message = strdup(temp_string); } break; case CHECK_MEMUSE: - xasprintf(&send_buffer,"%s&7", req_password); - fetch_data (server_address, server_port, send_buffer); - numstr = strtok(recv_buffer,"&"); + xasprintf(&send_buffer, "%s&7", req_password); + fetch_data(server_address, server_port, send_buffer); + numstr = strtok(recv_buffer, "&"); if (numstr == NULL) die(STATE_UNKNOWN, _("could not fetch information from server\n")); - mem_commitLimit=atof(numstr); - numstr = strtok(NULL,"&"); + mem_commitLimit = atof(numstr); + numstr = strtok(NULL, "&"); if (numstr == NULL) die(STATE_UNKNOWN, _("could not fetch information from server\n")); - mem_commitByte=atof(numstr); + mem_commitByte = atof(numstr); percent_used_space = (mem_commitByte / mem_commitLimit) * 100; warning_used_space = ((float)warning_value / 100) * mem_commitLimit; critical_used_space = ((float)critical_value / 100) * mem_commitLimit; /* Divisor should be 1048567, not 3044515, as we are measuring "Commit Charge" here, which equals RAM + Pagefiles. */ - xasprintf(&output_message,_("Memory usage: total:%.2f MB - used: %.2f MB (%.0f%%) - free: %.2f MB (%.0f%%)"), - mem_commitLimit / 1048567, mem_commitByte / 1048567, percent_used_space, - (mem_commitLimit - mem_commitByte) / 1048567, (mem_commitLimit - mem_commitByte) / mem_commitLimit * 100); - xasprintf(&perfdata,_("'Memory usage'=%.2fMB;%.2f;%.2f;0.00;%.2f"), mem_commitByte / 1048567, - warning_used_space / 1048567, critical_used_space / 1048567, mem_commitLimit / 1048567); - - return_code=STATE_OK; - if(check_critical_value && percent_used_space >= critical_value) - return_code=STATE_CRITICAL; + xasprintf(&output_message, _("Memory usage: total:%.2f MB - used: %.2f MB (%.0f%%) - free: %.2f MB (%.0f%%)"), + mem_commitLimit / 1048567, mem_commitByte / 1048567, percent_used_space, (mem_commitLimit - mem_commitByte) / 1048567, + (mem_commitLimit - mem_commitByte) / mem_commitLimit * 100); + xasprintf(&perfdata, _("'Memory usage'=%.2fMB;%.2f;%.2f;0.00;%.2f"), mem_commitByte / 1048567, warning_used_space / 1048567, + critical_used_space / 1048567, mem_commitLimit / 1048567); + + return_code = STATE_OK; + if (check_critical_value && percent_used_space >= critical_value) + return_code = STATE_CRITICAL; else if (check_warning_value && percent_used_space >= warning_value) - return_code=STATE_WARNING; + return_code = STATE_WARNING; break; case CHECK_COUNTER: - /* CHECK_COUNTER has been modified to provide extensive perfdata information. In order to do this, some modifications have been done to the code @@ -353,311 +348,290 @@ int main(int argc, char **argv){ */ if (value_list == NULL) - output_message = strdup (_("No counter specified")); - else - { - preparelist (value_list); /* replace , between services with & to send the request */ - isPercent = (strchr (value_list, '%') != NULL); - - strtok (value_list, "&"); /* burn the first parameters */ - description = strtok (NULL, "&"); - counter_unit = strtok (NULL, "&"); - xasprintf (&send_buffer, "%s&8&%s", req_password, value_list); - fetch_data (server_address, server_port, send_buffer); - counter_value = atof (recv_buffer); + output_message = strdup(_("No counter specified")); + else { + preparelist(value_list); /* replace , between services with & to send the request */ + isPercent = (strchr(value_list, '%') != NULL); + + strtok(value_list, "&"); /* burn the first parameters */ + description = strtok(NULL, "&"); + counter_unit = strtok(NULL, "&"); + xasprintf(&send_buffer, "%s&8&%s", req_password, value_list); + fetch_data(server_address, server_port, send_buffer); + counter_value = atof(recv_buffer); if (description == NULL) - xasprintf (&output_message, "%.f", counter_value); - else if (isPercent) - { - counter_unit = strdup ("%"); + xasprintf(&output_message, "%.f", counter_value); + else if (isPercent) { + counter_unit = strdup("%"); allRight = true; } - if ((counter_unit != NULL) && (!allRight)) - { - minval = strtok (NULL, "&"); - maxval = strtok (NULL, "&"); + if ((counter_unit != NULL) && (!allRight)) { + minval = strtok(NULL, "&"); + maxval = strtok(NULL, "&"); /* All parameters specified. Let's check the numbers */ - fminval = (minval != NULL) ? strtod (minval, &errcvt) : -1; - fmaxval = (minval != NULL) ? strtod (maxval, &errcvt) : -1; + fminval = (minval != NULL) ? strtod(minval, &errcvt) : -1; + fmaxval = (minval != NULL) ? strtod(maxval, &errcvt) : -1; if ((fminval == 0) && (minval == errcvt)) - output_message = strdup (_("Minimum value contains non-numbers")); - else - { + output_message = strdup(_("Minimum value contains non-numbers")); + else { if ((fmaxval == 0) && (maxval == errcvt)) - output_message = strdup (_("Maximum value contains non-numbers")); + output_message = strdup(_("Maximum value contains non-numbers")); else - allRight = true; /* Everything is OK. */ - + allRight = true; /* Everything is OK. */ } - } - else if ((counter_unit == NULL) && (description != NULL)) - output_message = strdup (_("No unit counter specified")); + } else if ((counter_unit == NULL) && (description != NULL)) + output_message = strdup(_("No unit counter specified")); - if (allRight) - { + if (allRight) { /* Let's format the output string, finally... */ - if (strstr(description, "%") == NULL) { - xasprintf (&output_message, "%s = %.2f %s", description, counter_value, counter_unit); - } else { - /* has formatting, will segv if wrong */ - xasprintf (&output_message, description, counter_value); - } - xasprintf (&output_message, "%s |", output_message); - xasprintf (&output_message,"%s %s", output_message, - fperfdata (description, counter_value, - counter_unit, 1, warning_value, 1, critical_value, - (!(isPercent) && (minval != NULL)), fminval, - (!(isPercent) && (minval != NULL)), fmaxval)); + if (strstr(description, "%") == NULL) { + xasprintf(&output_message, "%s = %.2f %s", description, counter_value, counter_unit); + } else { + /* has formatting, will segv if wrong */ + xasprintf(&output_message, description, counter_value); + } + xasprintf(&output_message, "%s |", output_message); + xasprintf(&output_message, "%s %s", output_message, + fperfdata(description, counter_value, counter_unit, 1, warning_value, 1, critical_value, + (!(isPercent) && (minval != NULL)), fminval, (!(isPercent) && (minval != NULL)), fmaxval)); } } - if (critical_value > warning_value) - { /* Normal thresholds */ + if (critical_value > warning_value) { /* Normal thresholds */ if (check_critical_value && counter_value >= critical_value) return_code = STATE_CRITICAL; - else if (check_warning_value && counter_value >= warning_value) + else if (check_warning_value && counter_value >= warning_value) return_code = STATE_WARNING; else return_code = STATE_OK; - } - else - { /* inverse thresholds */ + } else { /* inverse thresholds */ return_code = STATE_OK; if (check_critical_value && counter_value <= critical_value) return_code = STATE_CRITICAL; else if (check_warning_value && counter_value <= warning_value) return_code = STATE_WARNING; } - break; + break; case CHECK_FILEAGE: - if (value_list==NULL) - output_message = strdup (_("No counter specified")); + if (value_list == NULL) + output_message = strdup(_("No counter specified")); else { - preparelist(value_list); /* replace , between services with & to send the request */ - xasprintf(&send_buffer,"%s&9&%s", req_password,value_list); - fetch_data (server_address, server_port, send_buffer); - age_in_minutes = atoi(strtok(recv_buffer,"&")); - description = strtok(NULL,"&"); - output_message = strdup (description); - - if (critical_value > warning_value) { /* Normal thresholds */ - if(check_critical_value && age_in_minutes >= critical_value) - return_code=STATE_CRITICAL; + preparelist(value_list); /* replace , between services with & to send the request */ + xasprintf(&send_buffer, "%s&9&%s", req_password, value_list); + fetch_data(server_address, server_port, send_buffer); + age_in_minutes = atoi(strtok(recv_buffer, "&")); + description = strtok(NULL, "&"); + output_message = strdup(description); + + if (critical_value > warning_value) { /* Normal thresholds */ + if (check_critical_value && age_in_minutes >= critical_value) + return_code = STATE_CRITICAL; else if (check_warning_value && age_in_minutes >= warning_value) - return_code=STATE_WARNING; + return_code = STATE_WARNING; else - return_code=STATE_OK; - } - else { /* inverse thresholds */ - if(check_critical_value && age_in_minutes <= critical_value) - return_code=STATE_CRITICAL; + return_code = STATE_OK; + } else { /* inverse thresholds */ + if (check_critical_value && age_in_minutes <= critical_value) + return_code = STATE_CRITICAL; else if (check_warning_value && age_in_minutes <= warning_value) - return_code=STATE_WARNING; + return_code = STATE_WARNING; else - return_code=STATE_OK; + return_code = STATE_OK; } } break; case CHECK_INSTANCES: - if (value_list==NULL) - output_message = strdup (_("No counter specified")); + if (value_list == NULL) + output_message = strdup(_("No counter specified")); else { - xasprintf(&send_buffer,"%s&10&%s", req_password,value_list); - fetch_data (server_address, server_port, send_buffer); - if (!strncmp(recv_buffer,"ERROR",5)) { - printf("NSClient - %s\n",recv_buffer); + xasprintf(&send_buffer, "%s&10&%s", req_password, value_list); + fetch_data(server_address, server_port, send_buffer); + if (!strncmp(recv_buffer, "ERROR", 5)) { + printf("NSClient - %s\n", recv_buffer); exit(STATE_UNKNOWN); } - xasprintf(&output_message,"%s",recv_buffer); - return_code=STATE_OK; + xasprintf(&output_message, "%s", recv_buffer); + return_code = STATE_OK; } break; case CHECK_NONE: default: - usage4 (_("Please specify a variable to check")); + usage4(_("Please specify a variable to check")); break; - } /* reset timeout */ alarm(0); - if (perfdata==NULL) - printf("%s\n",output_message); + if (perfdata == NULL) + printf("%s\n", output_message); else - printf("%s | %s\n",output_message,perfdata); + printf("%s | %s\n", output_message, perfdata); return return_code; } - - /* process command-line arguments */ -int process_arguments(int argc, char **argv){ +int process_arguments(int argc, char **argv) { int c; int option = 0; - static struct option longopts[] = - { - {"port", required_argument,0,'p'}, - {"timeout", required_argument,0,'t'}, - {"critical", required_argument,0,'c'}, - {"warning", required_argument,0,'w'}, - {"variable", required_argument,0,'v'}, - {"hostname", required_argument,0,'H'}, - {"params", required_argument,0,'l'}, - {"secret", required_argument,0,'s'}, - {"display", required_argument,0,'d'}, - {"unknown-timeout", no_argument, 0, 'u'}, - {"version", no_argument, 0,'V'}, - {"help", no_argument, 0,'h'}, - {0,0,0,0} - }; + static struct option longopts[] = {{"port", required_argument, 0, 'p'}, + {"timeout", required_argument, 0, 't'}, + {"critical", required_argument, 0, 'c'}, + {"warning", required_argument, 0, 'w'}, + {"variable", required_argument, 0, 'v'}, + {"hostname", required_argument, 0, 'H'}, + {"params", required_argument, 0, 'l'}, + {"secret", required_argument, 0, 's'}, + {"display", required_argument, 0, 'd'}, + {"unknown-timeout", no_argument, 0, 'u'}, + {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {0, 0, 0, 0}}; /* no options were supplied */ - if(argc<2) return ERROR; + if (argc < 2) + return ERROR; /* backwards compatibility */ - if (! is_option(argv[1])) { + if (!is_option(argv[1])) { server_address = strdup(argv[1]); - argv[1]=argv[0]; - argv=&argv[1]; + argv[1] = argv[0]; + argv = &argv[1]; argc--; } - for (c=1;c delimited string into a long array */ - int idx=0; + int idx = 0; char *t1; - for (idx=0;idx"); - printf (" %s\n", _("Password needed for the request")); - printf (" %s\n", "-w, --warning=INTEGER"); - printf (" %s\n", _("Threshold which will result in a warning status")); - printf (" %s\n", "-c, --critical=INTEGER"); - printf (" %s\n", _("Threshold which will result in a critical status")); - printf (" %s\n", "-t, --timeout=INTEGER"); - printf (" %s", _("Seconds before connection attempt times out (default: ")); - printf (" %s\n", "-l, --params="); - printf (" %s", _("Parameters passed to specified check (see below)")); - printf (" %s\n", "-d, --display={SHOWALL}"); - printf (" %s", _("Display options (currently only SHOWALL works)")); - printf (" %s\n", "-u, --unknown-timeout"); - printf (" %s", _("Return UNKNOWN on timeouts")); - printf ("%d)\n", DEFAULT_SOCKET_TIMEOUT); - printf (" %s\n", "-h, --help"); - printf (" %s\n", _("Print this help screen")); - printf (" %s\n", "-V, --version"); - printf (" %s\n", _("Print version information")); - printf (" %s\n", "-v, --variable=STRING"); - printf (" %s\n\n", _("Variable to check")); - printf ("%s\n", _("Valid variables are:")); - printf (" %s", "CLIENTVERSION ="); - printf (" %s\n", _("Get the NSClient version")); - printf (" %s\n", _("If -l is specified, will return warning if versions differ.")); - printf (" %s\n", "CPULOAD ="); - printf (" %s\n", _("Average CPU load on last x minutes.")); - printf (" %s\n", _("Request a -l parameter with the following syntax:")); - printf (" %s\n", _("-l ,,.")); - printf (" %s\n", _(" should be less than 24*60.")); - printf (" %s\n", _("Thresholds are percentage and up to 10 requests can be done in one shot.")); - printf (" %s\n", "ie: -l 60,90,95,120,90,95"); - printf (" %s\n", "UPTIME ="); - printf (" %s\n", _("Get the uptime of the machine.")); - printf (" %s\n", _("-l ")); - printf (" %s\n", _(" = seconds, minutes, hours, or days. (default: minutes)")); - printf (" %s\n", _("Thresholds will use the unit specified above.")); - printf (" %s\n", "USEDDISKSPACE ="); - printf (" %s\n", _("Size and percentage of disk use.")); - printf (" %s\n", _("Request a -l parameter containing the drive letter only.")); - printf (" %s\n", _("Warning and critical thresholds can be specified with -w and -c.")); - printf (" %s\n", "MEMUSE ="); - printf (" %s\n", _("Memory use.")); - printf (" %s\n", _("Warning and critical thresholds can be specified with -w and -c.")); - printf (" %s\n", "SERVICESTATE ="); - printf (" %s\n", _("Check the state of one or several services.")); - printf (" %s\n", _("Request a -l parameters with the following syntax:")); - printf (" %s\n", _("-l ,,,...")); - printf (" %s\n", _("You can specify -d SHOWALL in case you want to see working services")); - printf (" %s\n", _("in the returned string.")); - printf (" %s\n", "PROCSTATE ="); - printf (" %s\n", _("Check if one or several process are running.")); - printf (" %s\n", _("Same syntax as SERVICESTATE.")); - printf (" %s\n", "COUNTER ="); - printf (" %s\n", _("Check any performance counter of Windows NT/2000.")); - printf (" %s\n", _("Request a -l parameters with the following syntax:")); - printf (" %s\n", _("-l \"\\\\\\\\counter\",\"")); - printf (" %s\n", _("The parameter is optional and is given to a printf ")); - printf (" %s\n", _("output command which requires a float parameter.")); - printf (" %s\n", _("If does not include \"%%\", it is used as a label.")); - printf (" %s\n", _("Some examples:")); - printf (" %s\n", "\"Paging file usage is %%.2f %%%%\""); - printf (" %s\n", "\"%%.f %%%% paging file used.\""); - printf (" %s\n", "INSTANCES ="); - printf (" %s\n", _("Check any performance counter object of Windows NT/2000.")); - printf (" %s\n", _("Syntax: check_nt -H -p -v INSTANCES -l ")); - printf (" %s\n", _(" is a Windows Perfmon Counter object (eg. Process),")); - printf (" %s\n", _("if it is two words, it should be enclosed in quotes")); - printf (" %s\n", _("The returned results will be a comma-separated list of instances on ")); - printf (" %s\n", _(" the selected computer for that object.")); - printf (" %s\n", _("The purpose of this is to be run from command line to determine what instances")); - printf (" %s\n", _(" are available for monitoring without having to log onto the Windows server")); - printf (" %s\n", _(" to run Perfmon directly.")); - printf (" %s\n", _("It can also be used in scripts that automatically create the monitoring service")); - printf (" %s\n", _(" configuration files.")); - printf (" %s\n", _("Some examples:")); - printf (" %s\n\n", _("check_nt -H 192.168.1.1 -p 1248 -v INSTANCES -l Process")); - - printf ("%s\n", _("Notes:")); - printf (" %s\n", _("- The NSClient service should be running on the server to get any information")); - printf (" %s\n", "(http://nsclient.ready2run.nl)."); - printf (" %s\n", _("- Critical thresholds should be lower than warning thresholds")); - printf (" %s\n", _("- Default port 1248 is sometimes in use by other services. The error")); - printf (" %s\n", _("output when this happens contains \"Cannot map xxxxx to protocol number\".")); - printf (" %s\n", _("One fix for this is to change the port to something else on check_nt ")); - printf (" %s\n", _("and on the client service it\'s connecting to.")); - - printf (UT_SUPPORT); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); + + printf("%s\n", _("Options:")); + printf(" %s\n", "-H, --hostname=HOST"); + printf(" %s\n", _("Name of the host to check")); + printf(" %s\n", "-p, --port=INTEGER"); + printf(" %s", _("Optional port number (default: ")); + printf("%d)\n", PORT); + printf(" %s\n", "-s, --secret="); + printf(" %s\n", _("Password needed for the request")); + printf(" %s\n", "-w, --warning=INTEGER"); + printf(" %s\n", _("Threshold which will result in a warning status")); + printf(" %s\n", "-c, --critical=INTEGER"); + printf(" %s\n", _("Threshold which will result in a critical status")); + printf(" %s\n", "-t, --timeout=INTEGER"); + printf(" %s", _("Seconds before connection attempt times out (default: ")); + printf(" %s\n", "-l, --params="); + printf(" %s", _("Parameters passed to specified check (see below)")); + printf(" %s\n", "-d, --display={SHOWALL}"); + printf(" %s", _("Display options (currently only SHOWALL works)")); + printf(" %s\n", "-u, --unknown-timeout"); + printf(" %s", _("Return UNKNOWN on timeouts")); + printf("%d)\n", DEFAULT_SOCKET_TIMEOUT); + printf(" %s\n", "-h, --help"); + printf(" %s\n", _("Print this help screen")); + printf(" %s\n", "-V, --version"); + printf(" %s\n", _("Print version information")); + printf(" %s\n", "-v, --variable=STRING"); + printf(" %s\n\n", _("Variable to check")); + printf("%s\n", _("Valid variables are:")); + printf(" %s", "CLIENTVERSION ="); + printf(" %s\n", _("Get the NSClient version")); + printf(" %s\n", _("If -l is specified, will return warning if versions differ.")); + printf(" %s\n", "CPULOAD ="); + printf(" %s\n", _("Average CPU load on last x minutes.")); + printf(" %s\n", _("Request a -l parameter with the following syntax:")); + printf(" %s\n", _("-l ,,.")); + printf(" %s\n", _(" should be less than 24*60.")); + printf(" %s\n", _("Thresholds are percentage and up to 10 requests can be done in one shot.")); + printf(" %s\n", "ie: -l 60,90,95,120,90,95"); + printf(" %s\n", "UPTIME ="); + printf(" %s\n", _("Get the uptime of the machine.")); + printf(" %s\n", _("-l ")); + printf(" %s\n", _(" = seconds, minutes, hours, or days. (default: minutes)")); + printf(" %s\n", _("Thresholds will use the unit specified above.")); + printf(" %s\n", "USEDDISKSPACE ="); + printf(" %s\n", _("Size and percentage of disk use.")); + printf(" %s\n", _("Request a -l parameter containing the drive letter only.")); + printf(" %s\n", _("Warning and critical thresholds can be specified with -w and -c.")); + printf(" %s\n", "MEMUSE ="); + printf(" %s\n", _("Memory use.")); + printf(" %s\n", _("Warning and critical thresholds can be specified with -w and -c.")); + printf(" %s\n", "SERVICESTATE ="); + printf(" %s\n", _("Check the state of one or several services.")); + printf(" %s\n", _("Request a -l parameters with the following syntax:")); + printf(" %s\n", _("-l ,,,...")); + printf(" %s\n", _("You can specify -d SHOWALL in case you want to see working services")); + printf(" %s\n", _("in the returned string.")); + printf(" %s\n", "PROCSTATE ="); + printf(" %s\n", _("Check if one or several process are running.")); + printf(" %s\n", _("Same syntax as SERVICESTATE.")); + printf(" %s\n", "COUNTER ="); + printf(" %s\n", _("Check any performance counter of Windows NT/2000.")); + printf(" %s\n", _("Request a -l parameters with the following syntax:")); + printf(" %s\n", _("-l \"\\\\\\\\counter\",\"")); + printf(" %s\n", _("The parameter is optional and is given to a printf ")); + printf(" %s\n", _("output command which requires a float parameter.")); + printf(" %s\n", _("If does not include \"%%\", it is used as a label.")); + printf(" %s\n", _("Some examples:")); + printf(" %s\n", "\"Paging file usage is %%.2f %%%%\""); + printf(" %s\n", "\"%%.f %%%% paging file used.\""); + printf(" %s\n", "INSTANCES ="); + printf(" %s\n", _("Check any performance counter object of Windows NT/2000.")); + printf(" %s\n", _("Syntax: check_nt -H -p -v INSTANCES -l ")); + printf(" %s\n", _(" is a Windows Perfmon Counter object (eg. Process),")); + printf(" %s\n", _("if it is two words, it should be enclosed in quotes")); + printf(" %s\n", _("The returned results will be a comma-separated list of instances on ")); + printf(" %s\n", _(" the selected computer for that object.")); + printf(" %s\n", _("The purpose of this is to be run from command line to determine what instances")); + printf(" %s\n", _(" are available for monitoring without having to log onto the Windows server")); + printf(" %s\n", _(" to run Perfmon directly.")); + printf(" %s\n", _("It can also be used in scripts that automatically create the monitoring service")); + printf(" %s\n", _(" configuration files.")); + printf(" %s\n", _("Some examples:")); + printf(" %s\n\n", _("check_nt -H 192.168.1.1 -p 1248 -v INSTANCES -l Process")); + + printf("%s\n", _("Notes:")); + printf(" %s\n", _("- The NSClient service should be running on the server to get any information")); + printf(" %s\n", "(http://nsclient.ready2run.nl)."); + printf(" %s\n", _("- Critical thresholds should be lower than warning thresholds")); + printf(" %s\n", _("- Default port 1248 is sometimes in use by other services. The error")); + printf(" %s\n", _("output when this happens contains \"Cannot map xxxxx to protocol number\".")); + printf(" %s\n", _("One fix for this is to change the port to something else on check_nt ")); + printf(" %s\n", _("and on the client service it\'s connecting to.")); + + printf(UT_SUPPORT); } - - -void print_usage(void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s -H host -v variable [-p port] [-w warning] [-c critical]\n",progname); - printf ("[-l params] [-d SHOWALL] [-u] [-t timeout]\n"); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s -H host -v variable [-p port] [-w warning] [-c critical]\n", progname); + printf("[-l params] [-d SHOWALL] [-u] [-t timeout]\n"); } - -- cgit v0.10-9-g596f From fcfa439ff85fab3d3d0046aff9f1e5ad4cb263c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:42:19 +0100 Subject: check_nt: update copyright diff --git a/plugins/check_nt.c b/plugins/check_nt.c index e0d0c23..413aad6 100644 --- a/plugins/check_nt.c +++ b/plugins/check_nt.c @@ -4,7 +4,7 @@ * * License: GPL * Copyright (c) 2000-2002 Yves Rubin (rubiyz@yahoo.com) - * Copyright (c) 2003-2007 Monitoring Plugins Development Team + * Copyright (c) 2003-2024 Monitoring Plugins Development Team * * Description: * @@ -33,7 +33,7 @@ *****************************************************************************/ const char *progname = "check_nt"; -const char *copyright = "2000-2007"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 66655d5d7a3467d997dab1bd122eeffa9b9b9cc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:43:27 +0100 Subject: check_radius: update copyright diff --git a/plugins/check_radius.c b/plugins/check_radius.c index 6b32710..8ed19e5 100644 --- a/plugins/check_radius.c +++ b/plugins/check_radius.c @@ -3,7 +3,7 @@ * Monitoring check_radius plugin * * License: GPL -* Copyright (c) 1999-2008 Monitoring Plugins Development Team +* Copyright (c) 1999-2024 Monitoring Plugins Development Team * * Description: * @@ -29,7 +29,7 @@ *****************************************************************************/ const char *progname = "check_radius"; -const char *copyright = "2000-2008"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 86f170336964f20bbfeb9f088e738336a708e736 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:44:11 +0100 Subject: check_ldap: update copyright diff --git a/plugins/check_ldap.c b/plugins/check_ldap.c index 868ffc1..1c72829 100644 --- a/plugins/check_ldap.c +++ b/plugins/check_ldap.c @@ -3,7 +3,7 @@ * Monitoring check_ldap plugin * * License: GPL -* Copyright (c) 2000-2008 Monitoring Plugins Development Team +* Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -28,7 +28,7 @@ /* progname may be check_ldaps */ char *progname = "check_ldap"; -const char *copyright = "2000-2008"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 2ceeada4347de40be211b5e2b386e524b287cc0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:44:59 +0100 Subject: check_apt: update copyright diff --git a/plugins/check_apt.c b/plugins/check_apt.c index 5c0f6e2..5e4021b 100644 --- a/plugins/check_apt.c +++ b/plugins/check_apt.c @@ -3,7 +3,7 @@ * Monitoring check_apt plugin * * License: GPL -* Copyright (c) 2006-2008 Monitoring Plugins Development Team +* Copyright (c) 2006-2024 Monitoring Plugins Development Team * * Original author: Sean Finney * @@ -30,7 +30,7 @@ *****************************************************************************/ const char *progname = "check_apt"; -const char *copyright = "2006-2008"; +const char *copyright = "2006-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From de5709bd7c0a15475daaf131491d3aa76ff464aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:45:24 +0100 Subject: check_mysql: update copyright diff --git a/plugins/check_mysql.c b/plugins/check_mysql.c index 15ec04c..1f0b709 100644 --- a/plugins/check_mysql.c +++ b/plugins/check_mysql.c @@ -5,7 +5,7 @@ * License: GPL * Copyright (c) 1999 Didi Rieder (adrieder@sbox.tu-graz.ac.at) * Copyright (c) 2000 Karl DeBisschop (kdebisschop@users.sourceforge.net) -* Copyright (c) 1999-2011 Monitoring Plugins Development Team +* Copyright (c) 1999-2024 Monitoring Plugins Development Team * * Description: * @@ -31,7 +31,7 @@ *****************************************************************************/ const char *progname = "check_mysql"; -const char *copyright = "1999-2011"; +const char *copyright = "1999-2024"; const char *email = "devel@monitoring-plugins.org"; #define SLAVERESULTSIZE 96 -- cgit v0.10-9-g596f From 3962ab996e0d891fb20815efc66674898b71bddc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:46:03 +0100 Subject: check_procs: update copyright diff --git a/plugins/check_procs.c b/plugins/check_procs.c index 1fcbd98..5777ba0 100644 --- a/plugins/check_procs.c +++ b/plugins/check_procs.c @@ -3,7 +3,7 @@ * Monitoring check_procs plugin * * License: GPL -* Copyright (c) 2000-2008 Monitoring Plugins Development Team +* Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -36,7 +36,7 @@ const char *progname = "check_procs"; const char *program_name = "check_procs"; /* Required for coreutils libs */ -const char *copyright = "2000-2008"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 41b0b959d8bac7ae359f63d101d404dfd5dd4591 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:46:36 +0100 Subject: check_smtp: update copyright diff --git a/plugins/check_smtp.c b/plugins/check_smtp.c index 986c3e1..bc17528 100644 --- a/plugins/check_smtp.c +++ b/plugins/check_smtp.c @@ -3,7 +3,7 @@ * Monitoring check_smtp plugin * * License: GPL -* Copyright (c) 2000-2023 Monitoring Plugins Development Team +* Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -29,7 +29,7 @@ *****************************************************************************/ const char *progname = "check_smtp"; -const char *copyright = "2000-2007"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From ffa1d68a3442dea9499fedd754ac1d02f5641c54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:47:16 +0100 Subject: check_ntp: update copyright diff --git a/plugins/check_ntp.c b/plugins/check_ntp.c index 61b2d69..55a4946 100644 --- a/plugins/check_ntp.c +++ b/plugins/check_ntp.c @@ -4,7 +4,7 @@ * * License: GPL * Copyright (c) 2006 Sean Finney -* Copyright (c) 2006-2008 Monitoring Plugins Development Team +* Copyright (c) 2006-2024 Monitoring Plugins Development Team * * Description: * @@ -31,7 +31,7 @@ *****************************************************************************/ const char *progname = "check_ntp"; -const char *copyright = "2006-2008"; +const char *copyright = "2006-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 611b33a30e0369168a0cddfa1a8b5f9479f52056 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:47:49 +0100 Subject: check_ssh: update copyright diff --git a/plugins/check_ssh.c b/plugins/check_ssh.c index 34ef37b..e9c55ad 100644 --- a/plugins/check_ssh.c +++ b/plugins/check_ssh.c @@ -3,7 +3,7 @@ * Monitoring check_ssh plugin * * License: GPL -* Copyright (c) 2000-2007 Monitoring Plugins Development Team +* Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -29,7 +29,7 @@ *****************************************************************************/ const char *progname = "check_ssh"; -const char *copyright = "2000-2007"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "./common.h" -- cgit v0.10-9-g596f From f0c6157cecdd8d2df832a649fe4ff35f8883b168 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:48:19 +0100 Subject: urlize: update copyright diff --git a/plugins/urlize.c b/plugins/urlize.c index 218233f..1aa4e42 100644 --- a/plugins/urlize.c +++ b/plugins/urlize.c @@ -30,7 +30,7 @@ *****************************************************************************/ const char *progname = "urlize"; -const char *copyright = "2000-2006"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v0.10-9-g596f From 8955f56de355403941bc8f02a4edb2bc72d1397a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lorenz=20K=C3=A4stle?= <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 14:48:54 +0100 Subject: check_http: update copyright diff --git a/plugins/check_http.c b/plugins/check_http.c index cdf768c..97c0e39 100644 --- a/plugins/check_http.c +++ b/plugins/check_http.c @@ -3,7 +3,7 @@ * Monitoring check_http plugin * * License: GPL -* Copyright (c) 1999-2013 Monitoring Plugins Development Team +* Copyright (c) 1999-2024 Monitoring Plugins Development Team * * Description: * @@ -32,7 +32,7 @@ *****************************************************************************/ const char *progname = "check_http"; -const char *copyright = "1999-2022"; +const char *copyright = "1999-2024"; const char *email = "devel@monitoring-plugins.org"; // Do NOT sort those headers, it will break the build -- cgit v0.10-9-g596f