diff --git a/.clang-format b/.clang-format
new file mode 100644
index 00000000..877a53b9
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,11 @@
+UseTab: ForContinuationAndIndentation
+IndentWidth: 4
+TabWidth: 4
+AllowShortIfStatementsOnASingleLine: false
+BreakBeforeBraces: Attach
+AlignConsecutiveMacros: true
+ColumnLimit: 140
+IndentPPDirectives: AfterHash
+SortIncludes: Never
+AllowShortEnumsOnASingleLine: false
+BinPackArguments: true
diff --git a/.github/mock.sh b/.github/mock.sh
index 7fbe6903..87543ce8 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"
@@ -18,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
@@ -32,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}
diff --git a/.github/prepare_debian.sh b/.github/prepare_debian.sh
index 3f4674a2..3640e500 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
@@ -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
diff --git a/.github/workflows/test-next.yml b/.github/workflows/test-next.yml
new file mode 100644
index 00000000..81240759
--- /dev/null
+++ b/.github/workflows/test-next.yml
@@ -0,0 +1,78 @@
+---
+name: Tests Debian:Testing and Fedora:Rawhide
+
+on:
+ workflow_dispatch: {}
+ 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 33220d6d..77ca6585 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"}
diff --git a/CODING b/CODING
index 74438e7c..d0673e7e 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
diff --git a/doc/developer-guidelines.sgml b/doc/developer-guidelines.sgml
index 37c963ed..0afa733b 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
@@ -383,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
@@ -727,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
@@ -756,32 +741,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
diff --git a/lib/extra_opts.c b/lib/extra_opts.c
index 771621d8..88787336 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 - 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 "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 8ff14a16..3f64360f 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 529b3568..ca5b6e54 100644
--- a/lib/maxfd.c
+++ b/lib/maxfd.c
@@ -1,7 +1,27 @@
+/*****************************************************************************
+ *
+ * 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
-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 +30,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 45218d0f..8fcd62d3 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 09c0dc4f..1289aae2 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 - 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 "common.h"
#include "idpriv.h"
@@ -40,31 +40,20 @@ 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_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",
+ "/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
-};
+ "/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 +70,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 +83,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 +92,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 +100,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 +131,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,13 +143,15 @@ 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;
- enum { NOSTANZA, WRONGSTANZA, RIGHTSTANZA } stanzastate = NOSTANZA;
+ enum {
+ NOSTANZA,
+ WRONGSTANZA,
+ RIGHTSTANZA
+ } stanzastate = NOSTANZA;
stanza_len = strlen(stanza);
@@ -217,8 +198,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 +207,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 +225,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 +272,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 +341,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 +356,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 e37601b5..d17409e3 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 05dd7943..94cb5aa9 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,124 @@ 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 02ae11f5..c8867dfb 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,154 @@ 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");
+ 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_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);
+ 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");
+ 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");
+ 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 == 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);
+ 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");
+ 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 e283fe2e..c18db7a4 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_generic_output b/lib/tests/test_generic_output
new file mode 100755
index 00000000..51e299a0
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 6843bac2..246c1250 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,93 @@ 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 8a2a0414..2186e4bb 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 077c5b63..984183d3 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,58 @@ 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 780220ee..23496617 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,77 @@ 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 b64270da..cecea437 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 1954b0fb..1b3003e9 100644
--- a/lib/tests/test_tcp.c
+++ b/lib/tests/test_tcp.c
@@ -1,34 +1,32 @@
/*****************************************************************************
-*
-* 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");
@@ -42,17 +40,13 @@ main(void)
"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 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 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 01afacdc..c3150f00 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,65 @@ 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 +422,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 +436,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
- };
+ char *states[] = {"Ok", "wArnINg", "cRiTIcaL", "UnKNoWN", NULL};
- for (i=0; states[i]!=NULL; i++) {
+ 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 +463,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 f8592f41..90a4aaa5 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 - 2024 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,43 @@ 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 +529,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 +552,7 @@ state_data *np_state_read() {
fclose(statefile);
}
- if(!rc) {
+ if (!rc) {
_cleanup_state_data();
}
@@ -577,60 +567,65 @@ 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));
+ 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';
+ 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 +642,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));
+ 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)) {
+ 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 9d4dffed..a209cb6d 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 7957ec14..416cf824 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-2024 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 061f5d4f..d00069c9 100644
--- a/lib/utils_cmd.h
+++ b/lib/utils_cmd.h
@@ -4,12 +4,10 @@
/*
* Header file for Monitoring Plugins utils_cmd.c
*
- *
*/
/** 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 +18,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 483be06d..2b761f5e 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-2024 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,187 @@ 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;
+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);
+ 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;
+ 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;
+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 (item->name_next)
+ next = item->name_next;
+ else
+ next = NULL;
- if (next)
- next->name_prev = prev;
+ if (next)
+ next->name_prev = prev;
- if (prev)
- prev->name_next = next;
+ if (prev)
+ prev->name_next = next;
- if (item->name) {
- free(item->name);
- }
- free(item);
+ if (item->name) {
+ free(item->name);
+ }
+ free(item);
- return next;
+ 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;
- }
+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;
+ 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;
+ 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 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;
- }
- }
- }
- }
+ /* 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 */
- }
- }
- }
+ 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;
+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;
+ 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;
-}
-
-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;
- }
+ 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;
+ }
return false;
}
diff --git a/lib/utils_disk.h b/lib/utils_disk.h
index 5b2caf23..c5e81dc1 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 23ee4a95..daae1d54 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-2024 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 0328a9cf..d5999e9b 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
@@ -16,7 +16,4 @@ enum np_match_result {
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);
diff --git a/plugins-root/check_dhcp.c b/plugins-root/check_dhcp.c
index 4b8f5e27..6802232e 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"
@@ -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 *);
+static 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
+#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_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 */
+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;
+} requested_server;
+#define BOOTREQUEST 1
+#define BOOTREPLY 2
-#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 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_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_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;
+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 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){
+static 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){
+static 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){
+static 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));
+ 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));
+ 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){
+static 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){
+static 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){
+static 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){
+static 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){
+static 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 */
+ 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));
+ 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){
+static 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){
+static 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;
+static 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)
+static 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){
+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'},
- {"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}
- };
+ 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);
+ 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)
+ if (c == -1 || c == EOF || c == 1)
break;
- switch(c){
+ switch (c) {
- case 's': /* DHCP server address */
- resolve_host(optarg,&dhcp_ip);
- add_requested_server(dhcp_ip);
- break;
+ case 's': /* DHCP server address */
+ resolve_host(optarg, &dhcp_ip);
+ add_requested_server(dhcp_ip);
+ break;
- case 'r': /* address we are requested from DHCP servers */
- resolve_host(optarg,&requested_address);
- request_specific_address=true;
- break;
+ case 'r': /* address we are requested from DHCP servers */
+ resolve_host(optarg, &requested_address);
+ request_specific_address = true;
+ break;
- case 't': /* timeout */
+ 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;
+ /*
+ 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;
}
+static 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){
+static 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){
+static 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){
+static 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){
+static 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){
+static 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_HELP_VRSN);
+ printf(UT_EXTRA_OPTS);
- printf (UT_VERBOSE);
+ 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(" %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_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;
}
diff --git a/plugins-root/check_icmp.c b/plugins-root/check_icmp.c
index f788d428..960ab8f1 100644
--- a/plugins-root/check_icmp.c
+++ b/plugins-root/check_icmp.c
@@ -1,45 +1,45 @@
/*****************************************************************************
-*
-* 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-2024 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"; */
char *progname;
-const char *copyright = "2005-2008";
+const char *copyright = "2005-2024";
const char *email = "devel@monitoring-plugins.org";
/** Monitoring Plugins basic includes */
@@ -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,10 +170,10 @@ 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,
@@ -189,30 +188,30 @@ 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 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 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 +234,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;
@@ -266,19 +253,17 @@ 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, ...)
-{
+static void crash(const char *fmt, ...) {
va_list ap;
printf("%s: ", progname);
@@ -287,55 +272,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 +374,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 +405,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 +448,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 +473,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 +488,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 +503,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 +533,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 +555,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 +568,20 @@ 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 +601,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 +615,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 +623,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 +685,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 +729,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 +746,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 +763,83 @@ 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,
+ 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 +850,24 @@ main(int argc, char **argv)
errno = 0;
finish(0);
- return(0);
+ return (0);
}
-static void
-run_checks()
-{
+static void run_checks(void) {
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 +878,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 +909,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 +922,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 +938,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 +965,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 +996,15 @@ 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));*/
+ /* 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");
+ 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 +1013,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 +1034,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 +1066,29 @@ 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 +1098,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 +1107,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 +1130,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 +1140,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 +1159,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 +1185,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 +1201,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 +1212,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 +1230,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 +1256,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 +1269,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 (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 (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) {
+ 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 +1332,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 +1356,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 +1375,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 +1443,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) {
+ while (host) {
- if(debug) puts("");
- if(i) {
- if(i < targets) printf(" :: ");
- else printf("\n");
+ 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 +1537,23 @@ 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 +1562,28 @@ finish(int sig)
}
if (jitter_mode) {
- if (host->pl<100) {
+ 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
- );
+ (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 +1592,35 @@ 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 +1629,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 +1639,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 +1687,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;
+ 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;
+ if (!list)
+ list = cursor = host;
+ else
+ cursor->next = host;
cursor = host;
targets++;
@@ -1738,9 +1712,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 +1726,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 +1745,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 +1762,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 +1771,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 +1788,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 +1811,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 +1829,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 (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 (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 +1903,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 +1925,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 +1934,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 +1957,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 +1988,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 (c) 2005 Andreas Ericsson \n");
- printf (COPYRIGHT, copyright, email);
+ printf(COPYRIGHT, copyright, email);
- 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", "-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", "-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(" %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);
}
diff --git a/plugins-scripts/check_ifstatus.pl b/plugins-scripts/check_ifstatus.pl
index 38b87fcc..f0b7c491 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);
diff --git a/plugins/check_apt.c b/plugins/check_apt.c
index 5c0f6e28..5e4021b5 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"
diff --git a/plugins/check_by_ssh.c b/plugins/check_by_ssh.c
index 2a23b397..905b2393 100644
--- a/plugins/check_by_ssh.c
+++ b/plugins/check_by_ssh.c
@@ -1,33 +1,33 @@
/*****************************************************************************
-*
-* 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-2024 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";
+const char *copyright = "2000-2024";
const char *email = "devel@monitoring-plugins.org";
#include "common.h"
@@ -36,82 +36,80 @@ 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);
+static int process_arguments(int /*argc*/, char ** /*argv*/);
+static int validate_arguments(void);
+static void comm_append(const char * /*str*/);
+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)
-{
+int main(int argc, char **argv) {
char *status_text;
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);
- 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,155 +119,144 @@ 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);
+ return max_state_alt(result, STATE_UNKNOWN);
}
/* 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 (!(file_pointer = 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 (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 (service[commands] && status_text && sscanf(chld_out.line[i], "STATUS CODE: %d", &cresult) == 1) {
+ fprintf(file_pointer, "[%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;
+ char *p1;
+ char *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 +264,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 +332,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 +340,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);
-void
-print_help (void)
-{
- print_revision (progname, NP_VERSION);
+ printf("Copyright (c) 1999 Karl DeBisschop \n");
+ printf(COPYRIGHT, copyright, email);
- printf ("Copyright (c) 1999 Karl DeBisschop \n");
- printf (COPYRIGHT, copyright, email);
+ printf(_("This plugin uses SSH to execute commands on a remote host"));
- printf (_("This plugin uses SSH to execute commands on a remote host"));
+ printf("\n\n");
- printf ("\n\n");
+ print_usage();
- print_usage ();
+ printf(UT_HELP_VRSN);
- printf (UT_HELP_VRSN);
+ printf(UT_EXTRA_OPTS);
- printf (UT_EXTRA_OPTS);
+ printf(UT_HOST_PORT, 'p', "none");
- printf (UT_HOST_PORT, 'p', "none");
+ printf(UT_IPv46);
- 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(" %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", _("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", _("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(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);
}
diff --git a/plugins/check_cluster.c b/plugins/check_cluster.c
index e1ede9f7..b40c38c7 100644
--- a/plugins/check_cluster.c
+++ b/plugins/check_cluster.c
@@ -1,92 +1,92 @@
/*****************************************************************************
-*
-* 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-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 .
+ *
+ *
+ *****************************************************************************/
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"
#include "utils.h"
#include "utils_base.h"
-#define CHECK_SERVICES 1
-#define CHECK_HOSTS 2
+enum {
+ CHECK_SERVICES = 1,
+ CHECK_HOSTS = 2
+};
-void print_help (void);
-void print_usage (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 /*argc*/, char ** /*argv*/);
-
-
-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 +101,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 +115,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 +174,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 +195,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 +207,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 +229,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 +251,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");
-
}
-
diff --git a/plugins/check_curl.c b/plugins/check_curl.c
index e9c15e64..1d27da28 100644
--- a/plugins/check_curl.c
+++ b/plugins/check_curl.c
@@ -1,40 +1,40 @@
/*****************************************************************************
-*
-* 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-2024 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";
+const char *copyright = "2006-2024";
const char *email = "devel@monitoring-plugins.org";
#include
@@ -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,1092 +66,1049 @@ 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;
-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;
+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;
-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 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;
+ 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;
+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;
+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;
-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);
+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 * /*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 * /*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);
-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 * /*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) */
-void remove_newlines (char *);
-void test_file (char *);
+static void test_file(char * /*path*/);
-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
+# 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;
+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;
+ X509_NAME *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
- SSL_CTX_set_verify(sslctx, SSL_VERIFY_PEER, verify_callback);
+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);
+ }
- return CURLE_OK;
+ // 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;
}
-#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];
+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;
- }
+ 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;
+ 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;
+static int expected_statuscode(const char *reply, const char *statuscodes) {
+ char *expected;
+ char *code;
+ int result = 0;
- if ((expected = strdup (statuscodes)) == NULL)
- die (STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n"));
+ if ((expected = strdup(statuscodes)) == NULL)
+ die(STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n"));
- for (code = strtok (expected, ","); code != NULL; code = strtok (NULL, ","))
- if (strstr (reply, code) != NULL) {
- result = 1;
- break;
- }
+ for (code = strtok(expected, ","); code != NULL; code = strtok(NULL, ","))
+ if (strstr(reply, code) != NULL) {
+ result = 1;
+ break;
+ }
- free (expected);
- return result;
+ 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;
+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;
+ 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;
+ errcode = getaddrinfo(host, NULL, &hints, &result);
+ if (errcode != 0)
+ return errcode;
- strcpy(buf, "");
- res = result;
+ 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;
- }
+ 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);
- }
+ 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;
- }
+ // 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;
- }
+ res = res->ai_next;
+ }
- freeaddrinfo(result);
+ freeaddrinfo(result);
- return 0;
+ 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];
+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;
+ /* 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;
+ 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);
+ /* 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");
+ 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");
+ /* 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 (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 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");
+ /* 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 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");
+ /* 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");
- }
+ /* 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);
- }
+ // 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 - %d"), 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;
- }
+ // 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
- );
+ /* 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");
+ 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");
- }
+ /* 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;
- }
+ /* 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 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");
- }
+ /* 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];
- }
- }
- }
+ /* 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);
- }
+ /* 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);
+ /* 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); */
- }
+ /* 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");
+ /* 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");
- }
+ /* 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");
- }
+ /* 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 ();
+ /* 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 */
- handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION");
- 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 */
- handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO");
- break;
+ /* 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_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_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)
- handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION");
- 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) */
- }
+ 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");
+ /* 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");
+ /* 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");
+ /* 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");
- */
+ /* 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");
+ /* 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");
+ /* 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) */
+ /* 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 */
- }
- }
+ /* 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");
+ /* 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)");
+ /* 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");
- }
- }
+ /* 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");
- }
+ /* 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);
+ /* do the request */
+ res = curl_easy_perform(curl);
- if (verbose>=2 && http_post_data)
- printf ("**** REQUEST CONTENT ****\n%s\n", http_post_data);
+ 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;
- }
+ /* 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);
- }
+ /* 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 */
+ /* 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;
+ 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);
- }
- }
- }
- }
+ 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)
- );
- }
+ /* 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"));
+ /* 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 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);
+ /* 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));
- }
+ /* 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 : "");
- }
+ /* 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;
- }
- }
+ 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);
- }
- }
+ /* 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);
- }
+ /* 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);
- }
+ if (maximum_age >= 0) {
+ result = max_state_alt(check_document_dates(&header_buf, &msg), result);
+ }
- /* Page and Header content checks go here */
+ /* Page and Header content checks go here */
- if (strlen (header_expect)) {
- if (!strstr (header_buf.buf, header_expect)) {
+ if (strlen(header_expect)) {
+ if (!strstr(header_buf.buf, header_expect)) {
- strncpy(&output_header_search[0],header_expect,sizeof(output_header_search));
+ 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,
- _("%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 (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);
- }
+ 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);
@@ -1160,1283 +1117,1230 @@ 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);
+ /* -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)));
-}
-
-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);
-
- if (res == -1) {
- die (STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n"));
+ /* Cut-off trailing characters */
+ if (strlen(msg) >= 2) {
+ if (msg[strlen(msg) - 2] == ',')
+ msg[strlen(msg) - 2] = '\0';
+ else
+ msg[strlen(msg) - 3] = '\0';
}
- location = get_header_value (headers, nof_headers, "location");
+ /* 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" : ""));
- if (verbose >= 2)
- printf(_("* Seen redirect location %s\n"), location);
+ return max_state_alt(result, result_ssl);
+}
- if (++redir_depth > max_depth)
- die (STATE_WARNING,
- _("HTTP WARNING - maximum redirection depth %d exceeded - %s%s\n"),
- max_depth, location, (display_html ? "" : ""));
+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)));
+}
- 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"));
- }
- }
+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;
+}
- 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));
- }
- }
+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;
- if (uri.scheme.first) {
- if (!uri_strcmp (uri.scheme, "https"))
- use_ssl = true;
- else
- use_ssl = false;
- }
+ 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);
- /* 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 ? "" : "");
+ if (res == -1) {
+ die(STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n"));
+ }
- /* 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));
- }
+ location = get_header_value(headers, nof_headers, "location");
- /* 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 (verbose >= 2)
+ printf(_("* Seen redirect location %s\n"), location);
- 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 ? "" : ""));
+ if (++redir_depth > max_depth)
+ die(STATE_WARNING, _("HTTP WARNING - maximum redirection depth %d exceeded - %s%s\n"), max_depth, location,
+ (display_html ? "" : ""));
- /* set new values for redirected request */
+ 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 (!(followsticky & STICKY_HOST)) {
- free (server_address);
- server_address = strndup (new_host, MAX_IPV4_HOSTLENGTH);
- }
- if (!(followsticky & STICKY_PORT)) {
- server_port = (unsigned short)new_port;
- }
+ 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));
+ }
+ }
- free (host_name);
- host_name = strndup (new_host, MAX_IPV4_HOSTLENGTH);
+ if (uri.scheme.first) {
+ if (!uri_strcmp(uri.scheme, "https"))
+ use_ssl = true;
+ else
+ use_ssl = false;
+ }
- /* reset virtual port */
- virtual_port = server_port;
+ /* 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 ? "" : "");
- free(new_host);
- free (server_url);
- server_url = new_url;
+ /* 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));
+ }
- uriFreeUriMembersA (&uri);
+ /* 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 (verbose)
- printf (_("Redirection to %s://%s:%d%s\n"), use_ssl ? "https" : "http",
- host_name ? host_name : server_address, server_port, server_url);
+ 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 ? "" : ""));
- /* TODO: the hash component MUST be taken from the original URL and
- * attached to the URL in Location
- */
+ /* set new values for redirected request */
- cleanup ();
- check_http ();
+ 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;
+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
- };
+ 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}
- };
+ 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;
+ 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);
+ /* 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");
}
- } 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 */
+
+ 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';
- }
+ 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;
+ 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 (!strcmp (optarg, "critical"))
- state_regex = STATE_CRITICAL;
- else if (!strcmp (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);
+ 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)) {
+ 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;
- }
- }
+ } 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;
+ c = optind;
- if (server_address == NULL && c < argc)
- server_address = strdup (argv[c++]);
+ if (server_address == NULL && c < argc)
+ server_address = strdup(argv[c++]);
- if (host_name == NULL && c < argc)
- host_name = 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);
- }
+ 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);
+ 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 (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 (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 (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;
- }
+ 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;
+ 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", "--regex-state=STATE");
- printf (" %s\n", _("Return STATE if regex is found, OK if not\n"));
- printf (" %s\n", "-a, --authorization=AUTH_PAIR");
- printf (" %s\n", _("Username:password on sites with basic authentication"));
- printf (" %s\n", "-b, --proxy-authorization=AUTH_PAIR");
- printf (" %s\n", _("Username:password on proxy-servers with basic authentication"));
- printf (" %s\n", "-A, --useragent=STRING");
- printf (" %s\n", _("String to be sent in http header as \"User Agent\""));
- printf (" %s\n", "-k, --header=STRING");
- printf (" %s\n", _("Any other tags to be sent in http header. Use multiple times for additional headers"));
- printf (" %s\n", "-E, --extended-perfdata");
- printf (" %s\n", _("Print additional performance data"));
- printf (" %s\n", "-B, --show-body");
- printf (" %s\n", _("Print body content below status line"));
- printf (" %s\n", "-L, --link");
- printf (" %s\n", _("Wrap output in HTML link (obsoleted by urlize)"));
- printf (" %s\n", "-f, --onredirect=");
- printf (" %s\n", _("How to handle redirected pages. sticky is like follow but stick to the"));
- printf (" %s\n", _("specified IP address. stickyport also ensures port stays the same."));
- printf (" %s\n", _("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(" %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_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", _("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("\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
- printf ("%s\n", _("WARNING: check_curl is experimental. Please use"));
- printf ("%s\n\n", _("check_http if you need a stable version."));
}
-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;
+
+ 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';
+
+ return (int)(size * nmemb);
}
-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_read_callback(void *buffer, size_t size, size_t nmemb, void *stream) {
+ curlhelp_read_curlbuf *buf = (curlhelp_read_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;
- }
- }
+ size_t n = min(nmemb * size, buf->buflen - buf->pos);
- memcpy (buf->buf + buf->buflen, buffer, size * nmemb);
- buf->buflen += size * nmemb;
- buf->buf[buf->buflen] = '\0';
+ memcpy(buffer, buf->buf + buf->pos, n);
+ buf->pos += n;
- return (int)(size * nmemb);
+ return (int)n;
}
-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);
-
- memcpy (buffer, buf->buf + buf->pos, n);
- buf->pos += 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;
+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 == NULL || needle == NULL)
+ return NULL;
- if (haystack[0] == '\0' || needle[0] == '\0')
- 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;
- }
+ counter = 0;
+ prev_pos = NULL;
+ pos = haystack;
+ len = strlen(needle);
+ for (;;) {
+ pos = strstr(pos, needle);
+ if (pos == NULL) {
+ if (counter == 0)
+ return NULL;
+ 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;
+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;
-}
-
-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 ) {
- 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);
-
- if (res == -1) {
- die (STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n"));
+ /* find last start of a new header */
+ start = strrstr2(buf, "\r\nHTTP/");
+ if (start != NULL) {
+ start += 2;
+ buf = start;
}
- server_date = get_header_value (headers, nof_headers, "date");
- document_date = get_header_value (headers, nof_headers, "last-modified");
+ 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;
+}
+
+void curlhelp_free_statusline(curlhelp_statusline *status_line) { free(status_line->first_line); }
+
+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);
+
+ if (res == -1) {
+ 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");
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);
@@ -2444,34 +2348,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);
@@ -2480,14 +2384,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);
@@ -2495,132 +2399,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;
+curlhelp_ssl_library curlhelp_get_ssl_library(void) {
+ 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;
+ 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;
+ 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;
+ 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 (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);
+ if (verbose >= 2)
+ printf("* SSL library string is : %s %s (%d)\n", version_data->ssl_version, library, ssl_library);
- free (ssl_version);
+ free(ssl_version);
- return ssl_library;
+ 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;
+# ifndef USE_OPENSSL
+time_t parse_cert_date(const char *s) {
+ struct tm tm;
+ time_t date;
+ char *res;
- if (!s) return -1;
+ 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);
+ /* 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;
+ 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;
@@ -2628,66 +2528,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");
+ 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);
- }
- }
+ 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;
- }
+ 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;
- }
+ 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));
+ time_left = difftime(end_date, time(NULL));
days_left = time_left / 86400;
tz = getenv("TZ");
setenv("TZ", "GMT", 1);
@@ -2700,30 +2598,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
@@ -2734,5 +2633,5 @@ HAVE_FIRST_CERT:
}
return status;
}
-#endif /* USE_OPENSSL */
-#endif /* LIBCURL_FEATURE_SSL */
+# endif /* USE_OPENSSL */
+#endif /* LIBCURL_FEATURE_SSL */
diff --git a/plugins/check_dbi.c b/plugins/check_dbi.c
index 29c85206..96575672 100644
--- a/plugins/check_dbi.c
+++ b/plugins/check_dbi.c
@@ -1,36 +1,36 @@
/*****************************************************************************
-*
-* 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-2024 Monitoring Plugins Development Team
+ * Original 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";
+const char *copyright = "2011-2024";
const char *email = "devel@monitoring-plugins.org";
#include "common.h"
@@ -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
@@ -70,42 +70,40 @@ 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);
-void print_usage (void);
-void print_help (void);
+static int process_arguments(int, char **);
+static int validate_arguments(void);
+void print_usage(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 main(int argc, char **argv) {
int status = STATE_UNKNOWN;
dbi_driver driver;
@@ -113,7 +111,8 @@ 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;
@@ -122,59 +121,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 +180,190 @@ 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;
+ const char *dbname;
+ const char *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,
+ 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}
- };
+ {"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 '?': /* 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 '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 +374,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 +423,34 @@ 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;
+ char *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);
- }
-
- np_dbi_options = new;
- new = np_dbi_options + np_dbi_options_num;
- ++np_dbi_options_num;
-
- new->key = k;
- new->value = 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);
}
- break;
+
+ np_dbi_options = new;
+ new = np_dbi_options + np_dbi_options_num;
+ ++np_dbi_options_num;
+
+ new->key = k;
+ new->value = v;
+ } break;
case 'q':
np_dbi_query = optarg;
break;
@@ -486,341 +460,314 @@ 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(void) {
+ 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("\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(" %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_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_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
- printf (UT_VERBOSE);
+ 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("\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", _("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", _("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(" %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 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 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 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(" 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(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')) {
+ 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;
+ struct timeval timeval_start;
+ struct timeval 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);
}
-
diff --git a/plugins/check_dig.c b/plugins/check_dig.c
index be7a6101..2bbd1e05 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-2024 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.
@@ -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"
@@ -41,340 +41,312 @@ 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);
+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 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;
- 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;
+int main(int argc, char **argv) {
+ char *command_line;
+ output chld_out;
+ output 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);
+ 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"));
+ /* 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);
+ /* Parse extra opts if any */
+ argv = np_extra_opts(&argc, argv, progname);
- if (process_arguments (argc, argv) == ERROR)
- usage_va(_("Could not parse arguments"));
+ 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;
+ /* 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);
+ /* 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);
+ 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);
- }
- }
+ 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");
- }
+ /* 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:")) {
+ 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]);
+ /* 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;
+ 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;
- }
- }
+ /* 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;
- }
+ 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;
- }
- }
+ /* 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 (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;
- }
- }
- }
+ /* 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;
+ microsec = deltime(tv);
+ elapsed_time = (double)microsec / 1.0e6;
- if (critical_interval > UNDEFINED && elapsed_time > critical_interval)
- result = STATE_CRITICAL;
+ if (critical_interval > UNDEFINED && elapsed_time > critical_interval)
+ result = STATE_CRITICAL;
- else if (warning_interval > UNDEFINED && elapsed_time > warning_interval)
- result = STATE_WARNING;
+ 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;
+ 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 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}
- };
+ 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;
+ if (argc < 2)
+ return ERROR;
- while (1) {
- c = getopt_long (argc, argv, "hVvt:l:H:w:c:T:p:a:A:46", longopts, &option);
+ 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;
+ 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();
- }
- }
+ 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");
- }
- }
+ 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 ();
+ 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;
+ 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");
}
diff --git a/plugins/check_disk.c b/plugins/check_disk.c
index 24de2d45..d1d1b92a 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-2024 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 *copyright = "1999-2008";
+const char *program_name = "check_disk"; /* Required for coreutils libs */
+const char *copyright = "1999-2024";
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,1054 +107,1007 @@ 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
-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);
-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);
+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);
+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);
-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 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 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;
-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;
+ struct mount_entry *me;
+ struct fs_usage fsp;
+ struct parameter_list *temp_list;
+ struct parameter_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);
+ 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);
+ setlocale(LC_ALL, "");
+ bindtextdomain(PACKAGE, LOCALEDIR);
+ textdomain(PACKAGE);
- mount_list = read_file_system_list (0);
+ mount_list = read_file_system_list(0);
- /* Parse extra opts if any */
- argv = np_extra_opts (&argc, argv, progname);
+ /* Parse extra opts if any */
+ 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 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 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);
- }
+ 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;
+ /* 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;
- }
- }
+ 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;
+ 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");
- }
- }
+ 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);
+ /* 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);
+ if (verbose >= 3 && path->group != NULL)
+ printf("Group of %s: %s\n", path->name, path->group);
- /* reset disk result */
- disk_result = STATE_UNKNOWN;
+ /* reset disk result */
+ disk_result = STATE_UNKNOWN;
- me = path->best_match;
+ me = path->best_match;
- if (!me) {
- continue;
- }
+ 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 */
+ /* Filters */
- /* Remove filesystems already seen */
- if (np_seen_name(seen, me->me_mountdir)) {
- continue;
- }
- np_add_name(&seen, me->me_mountdir);
+ /* 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 (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 */
+ }
+ if (me->me_dummy && !show_all_fs) {
+ continue;
+ /* Skip excluded fstypes */
+ }
+ if (fs_exclude_list && np_find_regmatch(fs_exclude_list, me->me_type)) {
+ continue;
+ /* Skip excluded fs's */
+ }
+ 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 */
+ }
+ 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 (!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 (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);
- }
+ 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 */
+ /* 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_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->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_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_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->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 );
+ 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);
+ 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...
- */
+ /* 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;
+ /* *_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)) );
- }
+ 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;
+ 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)) );
- }
+ 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));
+ /* 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 (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 ));
- }
+ 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));
- }
+ 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 == 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 (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 (verbose >= 2)
+ xasprintf(&output, "%s%s", output, details);
- if (strcmp(output, "") == 0 && ! erronly) {
- preamble = "";
- xasprintf (&output, " - No disks were found for provided parameters");
- }
+ 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;
+ 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 process_arguments(int argc, char **argv) {
+ int c;
+ int err;
+ struct parameter_list *se;
+ struct parameter_list *temp_list = NULL;
+ struct parameter_list *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}
- };
+ 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;
+ if (argc < 2)
+ return ERROR;
- np_add_regex(&fs_exclude_list, "iso9660", REG_EXTENDED);
+ 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");
+ 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);
+ 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;
+ 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);
+ 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);
}
- 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 */
+ /* See comments for 'c' */
+ case 'w': /* warning 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 --warning 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;
+ 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;
- 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"));
- }
+ /* 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);
+ }
- /* 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 (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;
- if (stat(optarg, &stat_buf[0]) && ignore_missing == true) {
- path_ignored = true;
- break;
- }
- }
- se->group = group;
- set_all_thresholds(se);
+ 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"));
+ }
- /* 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);
+ /* 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);
- 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);
- }
+ if (stat(optarg, &stat_buf[0]) && ignore_missing == true) {
+ path_ignored = true;
+ break;
+ }
+ }
+ se->group = group;
+ set_all_thresholds(se);
- temp_list = path_select_list;
+ /* 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);
- previous = NULL;
- while (temp_list) {
- if (temp_list->best_match) {
- if (np_regex_match_mount_entry(temp_list->best_match, &re)) {
+ 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);
+ }
- if (verbose >=3)
- printf("ignoring %s matching regex\n", temp_list->name);
+ temp_list = path_select_list;
- 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;
- }
- }
+ 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);
- cflags = default_cflags;
- break;
+ 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;
+ }
+ }
- 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"));
- }
+ cflags = default_cflags;
+ break;
- 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);
- }
+ 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"));
+ }
- 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);
+ 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);
+ }
- /* 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);
- }
- }
+ 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);
- 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);
+ /* 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);
+ }
+ }
- fnd = false;
- path_selected = true;
- np_set_best_match(path_select_list, mount_list, exact_match);
- cflags = default_cflags;
+ if (!fnd && ignore_missing == true) {
+ path_ignored = true;
+ path_selected = true;
+ break;
+ }
+ if (!fnd)
+ die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"), _("Regular expression did not match any path or disk"), optarg);
- 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;
+ fnd = false;
+ path_selected = true;
+ np_set_best_match(path_select_list, mount_list, exact_match);
+ cflags = default_cflags;
- 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"));
- }
- }
+ 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;
- /* 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++];
+ 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"));
+ }
+ }
- if (crit_usedspace_percent == NULL && argc > c && is_intnonneg (argv[c]))
- crit_usedspace_percent = argv[c++];
+ /* 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 (argc > c) {
- se = np_add_parameter(&path_select_list, strdup(argv[c++]));
- path_selected = true;
- set_all_thresholds(se);
- }
+ if (crit_usedspace_percent == NULL && argc > c && is_intnonneg(argv[c]))
+ crit_usedspace_percent = argv[c++];
- if (units == NULL) {
- units = strdup ("MiB");
- mult = (uintmax_t)1024 * 1024;
- }
+ if (argc > c) {
+ se = np_add_parameter(&path_select_list, strdup(argv[c++]));
+ path_selected = true;
+ set_all_thresholds(se);
+ }
- return true;
+ if (units == NULL) {
+ units = strdup("MiB");
+ mult = (uintmax_t)1024 * 1024;
+ }
+
+ 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) {
+ 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);
}
+void print_help(void) {
+ print_revision(progname, NP_VERSION);
-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);
+ 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_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
-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");
+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;
+ }
+ printf("DISK %s - ", _("CRITICAL"));
+ die(STATE_CRITICAL, _("%s %s: %s\n"), p->name, _("is not accessible"), strerror(errno));
+ }
+ return true;
}
-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;
-
-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);
+ 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;
+ /* 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;
- }
+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);
+ 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);
}
diff --git a/plugins/check_dns.c b/plugins/check_dns.c
index 468bc958..e1e7c00e 100644
--- a/plugins/check_dns.c
+++ b/plugins/check_dns.c
@@ -1,36 +1,36 @@
/*****************************************************************************
-*
-* 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-2024 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";
+const char *copyright = "2000-2024";
const char *email = "devel@monitoring-plugins.org";
#include "common.h"
@@ -39,579 +39,534 @@ 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);
-void print_usage (void);
+static int process_arguments(int /*argc*/, char ** /*argv*/);
+static int validate_arguments(void);
+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);
#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;
+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;
-bool expect_authority = false;
-bool all_match = false;
-thresholds *time_thresholds = NULL;
+static bool expect_authority = false;
+static bool all_match = false;
+static 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;
+ output chld_err;
+ bool is_nxdomain = false;
-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);
- 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"));
+ }
- /* 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);
- /* Parse extra opts if any */
- argv=np_extra_opts (&argc, argv, progname);
+ if (process_arguments(argc, argv) == ERROR) {
+ usage_va(_("Could not parse arguments"));
+ }
- 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);
- /* get the command to run */
- xasprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server);
+ alarm(timeout_interval);
+ gettimeofday(&tv, NULL);
- alarm (timeout_interval);
- gettimeofday (&tv, NULL);
+ if (verbose)
+ printf("%s\n", command_line);
- 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;
+ }
- /* 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));
- /* 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 (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;
+ }
+ }
- 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++;
- /* 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 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);
+ }
- 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);
+ }
+ }
- 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++;
- /* 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 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);
+ }
- 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;
+ }
- 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]);
- result = error_scan (chld_out.line[i], &is_nxdomain);
- if (result != STATE_OK) {
- msg = strchr (chld_out.line[i], ':');
- if(msg) msg++;
- break;
- }
- }
+ 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;
+ }
+ }
- /* scan stderr */
- for(size_t i = 0; i < chld_err.lines; i++) {
- if (verbose)
- puts(chld_err.line[i]);
+ if (is_nxdomain && !expect_nxdomain) {
+ die(STATE_CRITICAL, _("Domain '%s' was not found by the server\n"), query_address);
+ }
- 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 (addresses) {
+ int i;
+ int 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);
- if (is_nxdomain && !expect_nxdomain) {
- die (STATE_CRITICAL, _("Domain '%s' was not found by the server\n"), query_address);
- }
+ /* 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;
- 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);
+ 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);
+ }
+ }
- /* 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;
+ /* 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);
+ }
+ }
- 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);
- 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;
+ 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;
+ char *mask_c;
+ char *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)
-{
+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;
+ 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;
+ /* 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);
+ /* 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);
+ /* 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);
+ /* 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);
+ /* 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);
+ /* 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"));
+ /* 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);
+ /* 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;
+ /* 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 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}
- };
+ 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;
+ if (argc < 2)
+ return ERROR;
- for (c = 1; c < argc; c++)
- if (strcmp ("-to", argv[c]) == 0)
- strcpy (argv[c], "-t");
+ 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);
+ while (1) {
+ c = getopt_long(argc, argv, "hVvALnt:H:s:r:a:w:c:", long_opts, &opt_index);
- if (c == -1 || c == EOF)
- break;
+ 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, ',');
+ 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++]);
- }
+ 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++]);
+ }
- if (strlen(dns_server)==0 && c= ADDRESS_LENGTH)
- die (STATE_UNKNOWN, _("Input buffer overflow\n"));
- strcpy (dns_server, argv[c++]);
- }
+ 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++]);
+ }
- set_thresholds(&time_thresholds, warning, critical);
+ set_thresholds(&time_thresholds, warning, critical);
- return validate_arguments ();
+ return validate_arguments();
}
+int validate_arguments(void) {
+ if (query_address[0] == 0) {
+ printf("missing --host argument\n");
+ return ERROR;
+ }
-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;
+ }
- if (expected_address_cnt > 0 && expect_nxdomain) {
- printf ("--expected-address and --expect-nxdomain cannot be combined\n");
- return ERROR;
- }
-
- 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 Ethan Galstad \n");
+ printf(COPYRIGHT, copyright, email);
- 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 ("%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");
- printf ("\n\n");
+ print_usage();
- print_usage ();
+ printf(UT_HELP_VRSN);
+ printf(UT_EXTRA_OPTS);
- 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 (" -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_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
-
- printf (UT_SUPPORT);
+ 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);
}
diff --git a/plugins/check_dummy.c b/plugins/check_dummy.c
index 212a1344..19f6c046 100644
--- a/plugins/check_dummy.c
+++ b/plugins/check_dummy.c
@@ -1,124 +1,111 @@
/*****************************************************************************
-*
-* 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-2024 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";
+const char *copyright = "1999-2024";
const char *email = "devel@monitoring-plugins.org";
#include "common.h"
#include "utils.h"
-void print_help (void);
-void print_usage (void);
+static void print_help(void);
+void print_usage(void);
+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);
+ 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]);
- 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;
+ }
- 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]);
- if (argc >= 3)
- printf (": %s", argv[2]);
+ printf("\n");
- printf("\n");
-
- return result;
+ 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);
}
diff --git a/plugins/check_fping.c b/plugins/check_fping.c
index 70d6f9fc..49235e28 100644
--- a/plugins/check_fping.c
+++ b/plugins/check_fping.c
@@ -1,36 +1,36 @@
/*****************************************************************************
-*
-* 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-2024 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";
+const char *copyright = "2000-2024";
const char *email = "devel@monitoring-plugins.org";
#include "common.h"
@@ -40,488 +40,449 @@ 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);
+static int textscan(char *buf);
+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);
-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; */
+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);
+ 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);
+ 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);
- if (process_arguments (argc, argv) == ERROR)
- usage4 (_("Could not parse arguments"));
+ if (process_arguments(argc, argv) == ERROR)
+ usage4(_("Could not parse arguments"));
- server = strscpy (server, server_name);
+ 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);
+ /* 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);
+ 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);
+ 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;
- }
+ /* 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);
- }
+ 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));
- }
+ 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);
+ /* 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);
- }
+ /* 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"));
- }
+ 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);
- printf ("FPING %s - %s\n", state_text (status), server_name);
-
- return status;
+ 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;
-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));
+ }
- /* 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);
- 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, "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, "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, "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") && 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 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);
+ }
- }
- else {
- status = max_state (status, STATE_WARNING);
- }
-
- return status;
+ return status;
}
-
-
/* process command-line arguments */
-int
-process_arguments (int argc, char **argv)
-{
- int c;
- char *rv[2];
+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}
- };
+ 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;
+ rv[PL] = NULL;
+ rv[RTA] = NULL;
- if (argc < 2)
- return ERROR;
+ if (argc < 2)
+ return ERROR;
- if (!is_option (argv[1])) {
- server_name = argv[1];
- argv[1] = argv[0];
- argv = &argv[1];
- argc--;
- }
+ 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);
+ 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);
+ if (c == -1 || c == EOF || c == 1)
break;
- case '4': /* IPv4 only */
- address_family = AF_INET;
- break;
- case '6': /* IPv6 only */
+
+ 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);
+ 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;
- }
- }
+ 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"));
+ if (server_name == NULL)
+ usage4(_("Hostname was not supplied"));
- return OK;
+ return OK;
}
+int get_threshold(char *arg, char *rv[2]) {
+ char *arg1 = NULL;
+ char *arg2 = NULL;
-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, ",:");
- 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) {
- 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;
+ }
- 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;
}
+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);
}
diff --git a/plugins/check_game.c b/plugins/check_game.c
index ca126973..619277e7 100644
--- a/plugins/check_game.c
+++ b/plugins/check_game.c
@@ -1,335 +1,308 @@
/*****************************************************************************
-*
-* 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-2024 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";
+const char *copyright = "2002-2024";
const char *email = "devel@monitoring-plugins.org";
#include "common.h"
#include "utils.h"
#include "runcmd.h"
-int process_arguments (int, char **);
-int validate_arguments (void);
-void print_help (void);
-void print_usage (void);
+static int process_arguments(int /*argc*/, char ** /*argv*/);
+static int validate_arguments(void);
+static 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;
-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;
+ int result = STATE_UNKNOWN;
+ char *p;
+ char *ret[QSTAT_MAX_RETURN_ARGS];
+ size_t i = 0;
+ output chld_out;
-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);
- 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);
+ if (process_arguments(argc, argv) == ERROR)
+ usage_va(_("Could not parse arguments"));
- if (process_arguments (argc, argv) == ERROR)
- usage_va(_("Could not parse arguments"));
+ result = STATE_OK;
- 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);
- /* 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 (port)
- xasprintf (&command_line, "%s:%-d", command_line, port);
+ if (verbose)
+ printf("%s\n", command_line);
- 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);
- /* 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
- /* 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
+ */
- 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;
+ }
- 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;
+ }
- 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));
+ }
- 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;
+ return result;
}
+int process_arguments(int argc, char **argv) {
+ int c;
-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}};
- 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;
- 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");
+ }
- 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);
- while (1) {
- c = getopt_long (argc, argv, "hVvt:H:P:G:g:p:m:", long_opts, &opt_index);
+ if (c == -1 || c == EOF)
+ break;
- 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();
+ }
+ }
- 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 < argc)
+ game_type = strdup(argv[c++]);
- c = optind;
- /* first option is the game type */
- if (!game_type && c \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);
}
/******************************************************************************
diff --git a/plugins/check_hpjd.c b/plugins/check_hpjd.c
index c34bb082..b39bccff 100644
--- a/plugins/check_hpjd.c
+++ b/plugins/check_hpjd.c
@@ -1,36 +1,36 @@
/*****************************************************************************
-*
-* 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-2024 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";
+const char *copyright = "2000-2024";
const char *email = "devel@monitoring-plugins.org";
#include "common.h"
@@ -39,9 +39,7 @@ const char *email = "devel@monitoring-plugins.org";
#include "netutils.h"
#define DEFAULT_COMMUNITY "public"
-#define DEFAULT_PORT "161"
-
-const char *option_summary = "-H host [-C community]\n";
+#define DEFAULT_PORT "161"
#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"
@@ -56,22 +54,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);
+static int process_arguments(int /*argc*/, char ** /*argv*/);
+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)
-{
+int main(int argc, char **argv) {
char command_line[1024];
int result = STATE_UNKNOWN;
int line;
@@ -94,116 +90,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 +191,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 +219,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);
+
+ 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("\n\n");
+
+ print_usage();
+
+ 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(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 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");
-
- print_usage ();
-
- 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 (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);
}
diff --git a/plugins/check_http.c b/plugins/check_http.c
index cdf768c9..97c0e39a 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
diff --git a/plugins/check_ide_smart.c b/plugins/check_ide_smart.c
index 3872e341..381dbd80 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-2024 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 *copyright = "1998-2024";
const char *email = "devel@monitoring-plugins.org";
-
+
#include "common.h"
#include "utils.h"
-void print_help (void);
-void print_usage (void);
+static 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
+# 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 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
+# define OPEN_MODE O_RDWR
#endif /* __NetBSD__ */
#include
-
-#define NR_ATTRIBUTES 30
-
-#define PREFAILURE 2
-#define ADVISORY 1
-#define OPERATIONAL 0
-#define UNKNOWN -1
-typedef struct threshold_s
-{
+#define NR_ATTRIBUTES 30
+
+#define PREFAILURE 2
+#define ADVISORY 1
+#define OPERATIONAL 0
+#define UNKNOWN -1
+
+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,90 +111,71 @@ 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}
- };
+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_DISABLE, "SMART_DISABLE"},
+ {SMART_IMMEDIATE_OFFLINE, "SMART_IMMEDIATE_OFFLINE"},
+ {SMART_AUTO_OFFLINE, "SMART_AUTO_OFFLINE"}};
-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
+};
+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;
-/* 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 o;
+ int longindex;
int retval = 0;
thresholds_t thresholds;
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