Imported Upstream version 1.4.16+git20130902

This commit is contained in:
Jan Wagner 2013-11-26 23:59:47 +01:00
parent e76be63abf
commit e70fb8c051
517 changed files with 44015 additions and 43295 deletions

View file

@ -37,17 +37,21 @@ check_tcp_programs = check_ftp check_imap check_nntp check_pop \
EXTRA_PROGRAMS = check_mysql check_radius check_pgsql check_snmp check_hpjd \
check_swap check_fping check_ldap check_game check_dig \
check_nagios check_by_ssh check_dns check_nt check_ide_smart \
check_procs check_mysql_query check_apt
check_procs check_mysql_query check_apt check_dbi
EXTRA_DIST = t tests utils.c netutils.c sslutils.c popen.c utils.h netutils.h \
popen.h common.h runcmd.c runcmd.h
EXTRA_DIST = t tests
PLUGINHDRS = common.h
BASEOBJS = utils.o ../lib/libnagiosplug.a ../gl/libgnu.a
NETOBJS = netutils.o $(BASEOBJS) $(EXTRA_NETOBJS)
SSLOBJS = sslutils.o
noinst_LIBRARIES = libnpcommon.a
libnpcommon_a_SOURCES = utils.c netutils.c sslutils.c runcmd.c \
popen.c utils.h netutils.h popen.h common.h runcmd.c runcmd.h
BASEOBJS = libnpcommon.a ../lib/libnagiosplug.a ../gl/libgnu.a
NETOBJS = $(BASEOBJS) $(EXTRA_NETOBLS)
NETLIBS = $(NETOBJS) $(SOCKETLIBS)
SSLOBJS = $(BASEOBJS) $(NETLIBS) $(SSLLIBS)
TESTS_ENVIRONMENT = perl -I $(top_builddir) -I $(top_srcdir)
@ -62,18 +66,19 @@ test-debug:
##############################################################################
# the actual targets
check_apt_LDADD = $(BASEOBJS) runcmd.o
check_apt_LDADD = $(BASEOBJS)
check_cluster_LDADD = $(BASEOBJS)
check_dig_LDADD = $(NETLIBS) runcmd.o
check_disk_LDADD = $(BASEOBJS) popen.o
check_dns_LDADD = $(NETLIBS) runcmd.o
check_dbi_LDADD = $(NETLIBS) $(DBILIBS)
check_dig_LDADD = $(NETLIBS)
check_disk_LDADD = $(BASEOBJS)
check_dns_LDADD = $(NETLIBS)
check_dummy_LDADD = $(BASEOBJS)
check_fping_LDADD = $(NETLIBS) popen.o
check_game_LDADD = $(BASEOBJS) runcmd.o
check_http_LDADD = $(SSLOBJS) $(NETLIBS) $(SSLLIBS)
check_hpjd_LDADD = $(NETLIBS) popen.o
check_fping_LDADD = $(NETLIBS)
check_game_LDADD = $(BASEOBJS)
check_http_LDADD = $(SSLOBJS)
check_hpjd_LDADD = $(NETLIBS)
check_ldap_LDADD = $(NETLIBS) $(LDAPLIBS)
check_load_LDADD = $(BASEOBJS) popen.o
check_load_LDADD = $(BASEOBJS)
check_mrtg_LDADD = $(BASEOBJS)
check_mrtgtraf_LDADD = $(BASEOBJS)
check_mysql_CFLAGS = $(MYSQLCFLAGS) -DNP_VERSION='"$(NP_VERSION)"'
@ -82,22 +87,22 @@ check_mysql_LDADD = $(NETLIBS) $(MYSQLLIBS)
check_mysql_query_CFLAGS = $(MYSQLCFLAGS) -DNP_VERSION='"$(NP_VERSION)"'
check_mysql_query_CPPFLAGS = $(MYSQLINCLUDE)
check_mysql_query_LDADD = $(NETLIBS) $(MYSQLLIBS)
check_nagios_LDADD = $(BASEOBJS) runcmd.o
check_nagios_LDADD = $(BASEOBJS)
check_nt_LDADD = $(NETLIBS)
check_ntp_LDADD = $(NETLIBS) $(MATHLIBS)
check_ntp_peer_LDADD = $(NETLIBS) $(MATHLIBS)
check_nwstat_LDADD = $(NETLIBS)
check_overcr_LDADD = $(NETLIBS)
check_pgsql_LDADD = $(NETLIBS) $(PGLIBS)
check_ping_LDADD = $(NETLIBS) popen.o
check_ping_LDADD = $(NETLIBS)
check_procs_LDADD = $(BASEOBJS)
check_radius_LDADD = $(NETLIBS) $(RADIUSLIBS)
check_real_LDADD = $(NETLIBS)
check_snmp_LDADD = $(BASEOBJS)
check_smtp_LDADD = $(SSLOBJS) $(NETLIBS) $(SSLLIBS)
check_smtp_LDADD = $(SSLOBJS)
check_ssh_LDADD = $(NETLIBS)
check_swap_LDADD = $(MATHLIBS) $(BASEOBJS) popen.o
check_tcp_LDADD = $(SSLOBJS) $(NETLIBS) $(SSLLIBS)
check_swap_LDADD = $(MATHLIBS) $(BASEOBJS)
check_tcp_LDADD = $(SSLOBJS)
check_time_LDADD = $(NETLIBS)
check_ntp_time_LDADD = $(NETLIBS) $(MATHLIBS)
check_ups_LDADD = $(NETLIBS)
@ -105,61 +110,15 @@ check_users_LDADD = $(BASEOBJS)
check_by_ssh_LDADD = $(NETLIBS)
check_ide_smart_LDADD = $(BASEOBJS)
negate_LDADD = $(BASEOBJS)
urlize_LDADD = $(BASEOBJS) popen.o
urlize_LDADD = $(BASEOBJS)
check_apt_DEPENDENCIES = check_apt.c $(BASEOBJS) runcmd.o $(DEPLIBS)
check_cluster_DEPENDENCIES = check_cluster.c $(BASEOBJS) $(DEPLIBS)
check_dig_DEPENDENCIES = check_dig.c $(NETOBJS) runcmd.o $(DEPLIBS)
check_disk_DEPENDENCIES = check_disk.c $(BASEOBJS) popen.o $(DEPLIBS)
check_dns_DEPENDENCIES = check_dns.c $(NETOBJS) runcmd.o $(DEPLIBS)
check_dummy_DEPENDENCIES = check_dummy.c $(DEPLIBS)
check_fping_DEPENDENCIES = check_fping.c $(NETOBJS) popen.o $(DEPLIBS)
check_game_DEPENDENCIES = check_game.c $(DEPLIBS) runcmd.o
check_http_DEPENDENCIES = check_http.c $(SSLOBJS) $(NETOBJS) $(DEPLIBS)
check_hpjd_DEPENDENCIES = check_hpjd.c $(NETOBJS) popen.o $(DEPLIBS)
check_ide_smart_DEPENDENCIES = check_ide_smart.c $(BASEOBJS) $(DEPLIBS)
check_ldap_DEPENDENCIES = check_ldap.c $(NETOBJS) $(DEPLIBS)
check_load_DEPENDENCIES = check_load.c $(BASEOBJS) popen.o $(DEPLIBS)
check_mrtg_DEPENDENCIES = check_mrtg.c $(DEPLIBS)
check_mrtgtraf_DEPENDENCIES = check_mrtgtraf.c $(DEPLIBS)
check_mysql_DEPENDENCIES = check_mysql.c $(NETOBJS) $(DEPLIBS)
check_mysql_query_DEPENDENCIES = check_mysql_query.c $(NETOBJS) $(DEPLIBS)
check_nagios_DEPENDENCIES = check_nagios.c $(BASEOBJS) runcmd.o $(DEPLIBS)
check_nt_DEPENDENCIES = check_nt.c $(NETOBJS) $(DEPLIBS)
check_ntp_DEPENDENCIES = check_ntp.c $(NETOBJS) $(DEPLIBS)
check_ntp_peer_DEPENDENCIES = check_ntp_peer.c $(NETOBJS) $(DEPLIBS)
check_nwstat_DEPENDENCIES = check_nwstat.c $(NETOBJS) $(DEPLIBS)
check_overcr_DEPENDENCIES = check_overcr.c $(NETOBJS) $(DEPLIBS)
check_pgsql_DEPENDENCIES = check_pgsql.c $(NETOBJS) $(DEPLIBS)
check_ping_DEPENDENCIES = check_ping.c $(NETOBJS) popen.o $(DEPLIBS)
check_procs_DEPENDENCIES = check_procs.c $(BASEOBJS) popen.o $(DEPLIBS)
check_radius_DEPENDENCIES = check_radius.c $(NETOBJS) $(DEPLIBS)
check_real_DEPENDENCIES = check_real.c $(NETOBJS) $(DEPLIBS)
check_snmp_DEPENDENCIES = check_snmp.c $(BASEOBJS) $(DEPLIBS)
check_smtp_DEPENDENCIES = check_smtp.c $(SSLOBJS) $(NETOBJS) $(DEPLIBS)
check_ssh_DEPENDENCIES = check_ssh.c $(NETOBJS) $(DEPLIBS)
check_swap_DEPENDENCIES = check_swap.c $(BASEOBJS) popen.o $(DEPLIBS)
check_tcp_DEPENDENCIES = check_tcp.c $(SSLOBJS) $(NETOBJS) $(DEPLIBS)
check_time_DEPENDENCIES = check_time.c $(NETOBJS) $(DEPLIBS)
check_ntp_time_DEPENDENCIES = check_ntp_time.c $(NETOBJS) $(DEPLIBS)
check_ups_DEPENDENCIES = check_ups.c $(NETOBJS) $(DEPLIBS)
check_users_DEPENDENCIES = check_users.c $(BASEOBJS) popen.o $(DEPLIBS)
check_by_ssh_DEPENDENCIES = check_by_ssh.c $(NETOBJS) $(DEPLIBS)
negate_DEPENDENCIES = negate.c $(BASEOBJS) $(DEPLIBS)
urlize_DEPENDENCIES = urlize.c $(BASEOBJS) popen.o $(DEPLIBS)
if !HAVE_UTMPX
check_users_LDADD += popen.o
endif
##############################################################################
# secondary dependencies
popen.o: popen.c popen.h $(PLUGINHDRS)
runcmd.o: runcmd.c runcmd.h $(PLUGINHDRS)
utils.o: utils.c utils.h $(PLUGINHDRS)
netutils.o: netutils.c netutils.h $(PLUGINHDRS)
sslutils.o: sslutils.c netutils.h $(PLUGINHDRS)
all-local: $(check_tcp_programs)
$(check_tcp_programs): check_tcp

File diff suppressed because it is too large Load diff

View file

@ -41,6 +41,8 @@ const char *email = "nagiosplug-devel@lists.sourceforge.net";
/* some constants */
typedef enum { UPGRADE, DIST_UPGRADE, NO_UPGRADE } upgrade_type;
/* Character for hidden input file option (for testing). */
#define INPUT_FILE_OPT CHAR_MAX+1
/* the default opts can be overridden via the cmdline */
#define UPGRADE_DEFAULT_OPTS "-o 'Debug::NoLocking=true' -s -qq"
#define UPDATE_DEFAULT_OPTS "-q"
@ -49,8 +51,10 @@ typedef enum { UPGRADE, DIST_UPGRADE, NO_UPGRADE } upgrade_type;
#ifndef PATH_TO_APTGET
# define PATH_TO_APTGET "/usr/bin/apt-get"
#endif /* PATH_TO_APTGET */
/* String found at the beginning of the apt output lines we're interested in */
#define PKGINST_PREFIX "Inst "
/* the RE that catches security updates */
#define SECURITY_RE "^[^\\(]*\\([^ ]* (Debian-Security:|Ubuntu:[^/]*/[^-]*-security)"
#define SECURITY_RE "^[^\\(]*\\(.* (Debian-Security:|Ubuntu:[^/]*/[^-]*-security)"
/* some standard functions */
int process_arguments(int, char **);
@ -75,6 +79,7 @@ static char *update_opts = NULL; /* options to override defaults for update */
static char *do_include = NULL; /* regexp to only include certain packages */
static char *do_exclude = NULL; /* regexp to only exclude certain packages */
static char *do_critical = NULL; /* regexp specifying critical packages */
static char *input_filename = NULL; /* input filename for testing */
/* other global variables */
static int stderr_warning = 0; /* if a cmd issued output on stderr */
@ -107,11 +112,11 @@ int main (int argc, char **argv) {
result = max_state(result, STATE_CRITICAL);
} else if(packages_available > 0){
result = max_state(result, STATE_WARNING);
} else {
result = max_state(result, STATE_OK);
} else if(result > STATE_UNKNOWN){
result = STATE_UNKNOWN;
}
printf(_("APT %s: %d packages available for %s (%d critical updates). %s%s%s%s\n"),
printf(_("APT %s: %d packages available for %s (%d critical updates). %s%s%s%s|available_upgrades=%d;;;0 critical_updates=%d;;;0\n"),
state_text(result),
packages_available,
(upgrade==DIST_UPGRADE)?"dist-upgrade":"upgrade",
@ -119,7 +124,9 @@ int main (int argc, char **argv) {
(stderr_warning)?" warnings detected":"",
(stderr_warning && exec_warning)?",":"",
(exec_warning)?" errors detected":"",
(stderr_warning||exec_warning)?". run with -v for information.":""
(stderr_warning||exec_warning)?". run with -v for information.":"",
packages_available,
sec_count
);
return result;
@ -141,6 +148,7 @@ int process_arguments (int argc, char **argv) {
{"include", required_argument, 0, 'i'},
{"exclude", required_argument, 0, 'e'},
{"critical", required_argument, 0, 'c'},
{"input-file", required_argument, 0, INPUT_FILE_OPT},
{0, 0, 0, 0}
};
@ -195,6 +203,9 @@ int process_arguments (int argc, char **argv) {
case 'c':
do_critical=add_to_regexp(do_critical, optarg);
break;
case INPUT_FILE_OPT:
input_filename = optarg;
break;
default:
/* print short usage statement if args not parsable */
usage5();
@ -211,22 +222,18 @@ int run_upgrade(int *pkgcount, int *secpkgcount){
struct output chld_out, chld_err;
regex_t ireg, ereg, sreg;
char *cmdline=NULL, rerrbuf[64];
const char *include_ptr=NULL, *crit_ptr=NULL;
if(upgrade==NO_UPGRADE) return STATE_OK;
/* compile the regexps */
if(do_include!=NULL) include_ptr=do_include;
else include_ptr="^Inst";
if(do_critical!=NULL) crit_ptr=do_critical;
else crit_ptr=SECURITY_RE;
regres=regcomp(&ireg, include_ptr, REG_EXTENDED);
if(regres!=0) {
regerror(regres, &ireg, rerrbuf, 64);
die(STATE_UNKNOWN, _("%s: Error compiling regexp: %s"), progname, rerrbuf);
if (do_include != NULL) {
regres=regcomp(&ireg, do_include, REG_EXTENDED);
if (regres!=0) {
regerror(regres, &ireg, rerrbuf, 64);
die(STATE_UNKNOWN, _("%s: Error compiling regexp: %s"), progname, rerrbuf);
}
}
if(do_exclude!=NULL){
regres=regcomp(&ereg, do_exclude, REG_EXTENDED);
if(regres!=0) {
@ -235,6 +242,8 @@ int run_upgrade(int *pkgcount, int *secpkgcount){
progname, rerrbuf);
}
}
const char *crit_ptr = (do_critical != NULL) ? do_critical : SECURITY_RE;
regres=regcomp(&sreg, crit_ptr, REG_EXTENDED);
if(regres!=0) {
regerror(regres, &ereg, rerrbuf, 64);
@ -243,8 +252,14 @@ int run_upgrade(int *pkgcount, int *secpkgcount){
}
cmdline=construct_cmdline(upgrade, upgrade_opts);
/* run the upgrade */
result = np_runcmd(cmdline, &chld_out, &chld_err, 0);
if (input_filename != NULL) {
/* read input from a file for testing */
result = cmd_file_read(input_filename, &chld_out, 0);
} else {
/* run the upgrade */
result = np_runcmd(cmdline, &chld_out, &chld_err, 0);
}
/* apt-get upgrade only changes exit status if there is an
* internal error when run in dry-run mode. therefore we will
* treat such an error as UNKNOWN */
@ -269,7 +284,8 @@ int run_upgrade(int *pkgcount, int *secpkgcount){
printf("%s\n", chld_out.line[i]);
}
/* if it is a package we care about */
if(regexec(&ireg, chld_out.line[i], 0, NULL, 0)==0){
if (strncmp(PKGINST_PREFIX, chld_out.line[i], strlen(PKGINST_PREFIX)) == 0 &&
(do_include == NULL || regexec(&ireg, chld_out.line[i], 0, NULL, 0) == 0)) {
/* if we're not excluding, or it's not in the
* list of stuff to exclude */
if(do_exclude==NULL ||
@ -289,7 +305,7 @@ int run_upgrade(int *pkgcount, int *secpkgcount){
*secpkgcount=spc;
/* If we get anything on stderr, at least set warning */
if(chld_err.buflen){
if (input_filename == NULL && chld_err.buflen) {
stderr_warning=1;
result = max_state(result, STATE_WARNING);
if(verbose){
@ -298,7 +314,7 @@ int run_upgrade(int *pkgcount, int *secpkgcount){
}
}
}
regfree(&ireg);
if (do_include != NULL) regfree(&ireg);
regfree(&sreg);
if(do_exclude!=NULL) regfree(&ereg);
free(cmdline);
@ -348,15 +364,15 @@ char* add_to_regexp(char *expr, const char *next){
char *re=NULL;
if(expr==NULL){
re=malloc(sizeof(char)*(strlen("^Inst () ")+strlen(next)+1));
re=malloc(sizeof(char)*(strlen("()")+strlen(next)+1));
if(!re) die(STATE_UNKNOWN, "malloc failed!\n");
sprintf(re, "^Inst (%s) ", next);
sprintf(re, "(%s)", next);
} else {
/* resize it, adding an extra char for the new '|' separator */
re=realloc(expr, sizeof(char)*strlen(expr)+1+strlen(next)+1);
re=realloc(expr, sizeof(char)*(strlen(expr)+1+strlen(next)+1));
if(!re) die(STATE_UNKNOWN, "realloc failed!\n");
/* append it starting at ')' in the old re */
sprintf((char*)(re+strlen(re)-2), "|%s) ", next);
sprintf((char*)(re+strlen(re)-1), "|%s)", next);
}
return re;
@ -430,7 +446,7 @@ print_help (void)
printf (" %s\n", _("Do not run the upgrade. Probably not useful (without -u at least)."));
printf (" %s\n", "-i, --include=REGEXP");
printf (" %s\n", _("Include only packages matching REGEXP. Can be specified multiple times"));
printf (" %s\n", _("the values will be combined together. Any patches matching this list"));
printf (" %s\n", _("the values will be combined together. Any packages matching this list"));
printf (" %s\n", _("cause the plugin to return WARNING status. Others will be ignored."));
printf (" %s\n", _("Default is to include all packages."));
printf (" %s\n", "-e, --exclude=REGEXP");

View file

@ -281,8 +281,8 @@ process_arguments (int argc, char **argv)
case 'C': /* Command for remote machine */
commands++;
if (commands > 1)
asprintf (&remotecmd, "%s;echo STATUS CODE: $?;", remotecmd);
asprintf (&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 */
if (optarg == NULL)
@ -328,13 +328,13 @@ process_arguments (int argc, char **argv)
if (strlen(remotecmd) == 0) {
for (; c < argc; c++)
if (strlen(remotecmd) > 0)
asprintf (&remotecmd, "%s %s", remotecmd, argv[c]);
xasprintf (&remotecmd, "%s %s", remotecmd, argv[c]);
else
asprintf (&remotecmd, "%s", argv[c]);
xasprintf (&remotecmd, "%s", argv[c]);
}
if (commands > 1 || passive)
asprintf (&remotecmd, "%s;echo STATUS CODE: $?;", remotecmd);
xasprintf (&remotecmd, "%s;echo STATUS CODE: $?;", remotecmd);
if (remotecmd == NULL || strlen (remotecmd) <= 1)
usage_va(_("No remotecmd"));

817
plugins/check_dbi.c Normal file
View file

@ -0,0 +1,817 @@
/*****************************************************************************
*
* Nagios check_dbi plugin
*
* License: GPL
* Copyright (c) 2011 Nagios Plugins Development Team
* Author: Sebastian 'tokkee' Harl <sh@teamix.net>
*
* 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 <http://www.gnu.org/licenses/>.
*
*
*****************************************************************************/
const char *progname = "check_dbi";
const char *copyright = "2011";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "utils.h"
#include "netutils.h"
#include "regex.h"
/* required for NAN */
#ifndef _ISOC99_SOURCE
#define _ISOC99_SOURCE
#endif
#include <assert.h>
#include <math.h>
#include <dbi/dbi.h>
#include <stdarg.h>
typedef enum {
METRIC_CONN_TIME,
METRIC_SERVER_VERSION,
METRIC_QUERY_RESULT,
METRIC_QUERY_TIME,
} np_dbi_metric_t;
typedef enum {
TYPE_NUMERIC,
TYPE_STRING,
} np_dbi_type_t;
typedef struct {
char *key;
char *value;
} driver_option_t;
char *host = NULL;
int verbose = 0;
char *warning_range = NULL;
char *critical_range = NULL;
thresholds *dbi_thresholds = NULL;
char *expect = NULL;
regex_t expect_re;
char *expect_re_str = NULL;
int expect_re_cflags = 0;
np_dbi_metric_t metric = METRIC_QUERY_RESULT;
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;
int process_arguments (int, char **);
int validate_arguments (void);
void print_usage (void);
void print_help (void);
double timediff (struct timeval, struct timeval);
void np_dbi_print_error (dbi_conn, char *, ...);
int do_query (dbi_conn, const char **, double *, double *);
int
main (int argc, char **argv)
{
int status = STATE_UNKNOWN;
dbi_driver driver;
dbi_conn conn;
unsigned int server_version;
struct timeval start_timeval, end_timeval;
double conn_time = 0.0;
double query_time = 0.0;
const char *query_val_str = NULL;
double query_val = 0.0;
int i;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
/* Parse extra opts if any */
argv = np_extra_opts (&argc, argv, progname);
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* Set signal handling and alarm */
if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
usage4 (_("Cannot catch SIGALRM"));
}
alarm (timeout_interval);
if (verbose > 2)
printf ("Initializing DBI\n");
if (dbi_initialize (NULL) < 0) {
printf ("UNKNOWN - failed to initialize DBI; possibly you don't have any drivers installed.\n");
return STATE_UNKNOWN;
}
if (verbose)
printf ("Opening DBI driver '%s'\n", np_dbi_driver);
driver = dbi_driver_open (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");
for (driver = dbi_driver_list (NULL); driver; driver = dbi_driver_list (driver)) {
printf (" - %s\n", dbi_driver_get_name (driver));
}
return STATE_UNKNOWN;
}
/* make a connection to the database */
gettimeofday (&start_timeval, NULL);
conn = dbi_conn_open (driver);
if (! conn) {
printf ("UNKNOWN - failed top open connection object.\n");
dbi_conn_close (conn);
return STATE_UNKNOWN;
}
for (i = 0; i < np_dbi_options_num; ++i) {
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);
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");
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);
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);
}
if (verbose) {
const char *dbname, *host;
dbname = dbi_conn_get_option (conn, "dbname");
host = dbi_conn_get_option (conn, "host");
if (! dbname)
dbname = "<unspecified>";
if (! host)
host = "<unspecified>";
printf ("Connecting to database '%s' at host '%s'\n",
dbname, host);
}
if (dbi_conn_connect (conn) < 0) {
np_dbi_print_error (conn, "UNKOWN - failed to connect to database");
return STATE_UNKNOWN;
}
gettimeofday (&end_timeval, NULL);
conn_time = timediff (start_timeval, end_timeval);
server_version = dbi_conn_get_engine_version (conn);
if (verbose)
printf ("Connected to server version %u\n", server_version);
if (metric == METRIC_SERVER_VERSION)
status = get_status (server_version, dbi_thresholds);
if (verbose)
printf ("Time elapsed: %f\n", conn_time);
if (metric == METRIC_CONN_TIME)
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);
if (dbi_conn_select_db (conn, np_dbi_database)) {
np_dbi_print_error (conn, "UNKOWN - 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);
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))
status = STATE_CRITICAL;
else
status = STATE_OK;
}
else if (expect_re_str) {
int 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);
status = STATE_CRITICAL;
}
}
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);
/* 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 ((type != TYPE_STRING) || (expect || expect_re_str));
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 : "<nothing>", query_time);
if (status != STATE_OK) {
if (expect)
printf (" (expected '%s')", expect);
else if (expect_re_str)
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
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 : "");
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 : "");
}
printf ("\n");
return status;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
STD_LONG_OPTS,
{"expect", required_argument, 0, 'e'},
{"regex", required_argument, 0, 'r'},
{"regexi", required_argument, 0, 'R'},
{"metric", required_argument, 0, 'm'},
{"driver", required_argument, 0, 'd'},
{"option", required_argument, 0, 'o'},
{"query", required_argument, 0, 'q'},
{"database", required_argument, 0, 'D'},
{0, 0, 0, 0}
};
while (1) {
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_OK);
case 'V': /* version */
print_revision (progname, NP_VERSION);
exit (STATE_OK);
case 'c': /* critical range */
critical_range = optarg;
type = TYPE_NUMERIC;
break;
case 'w': /* warning range */
warning_range = optarg;
type = TYPE_NUMERIC;
break;
case 'e':
expect = optarg;
type = TYPE_STRING;
break;
case 'R':
expect_re_cflags = REG_ICASE;
/* fall through */
case 'r':
{
int err;
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;
}
case 'm':
if (! strcasecmp (optarg, "CONN_TIME"))
metric = METRIC_CONN_TIME;
else if (! strcasecmp (optarg, "SERVER_VERSION"))
metric = METRIC_SERVER_VERSION;
else if (! strcasecmp (optarg, "QUERY_RESULT"))
metric = METRIC_QUERY_RESULT;
else if (! strcasecmp (optarg, "QUERY_TIME"))
metric = METRIC_QUERY_TIME;
else
usage2 (_("Invalid metric"), optarg);
break;
case 't': /* timeout */
if (!is_intnonneg (optarg))
usage2 (_("Timeout interval must be a positive integer"), optarg);
else
timeout_interval = atoi (optarg);
case 'H': /* host */
if (!is_host (optarg))
usage2 (_("Invalid hostname/address"), optarg);
else
host = optarg;
break;
case 'v':
verbose++;
break;
case 'd':
np_dbi_driver = optarg;
break;
case 'o':
{
driver_option_t *new;
char *k, *v;
k = optarg;
v = strchr (k, (int)'=');
if (! v)
usage2 (_("Option must be '<key>=<value>'"), optarg);
*v = '\0';
++v;
new = realloc (np_dbi_options,
(np_dbi_options_num + 1) * sizeof (*new));
if (! new) {
printf ("UNKOWN - 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;
}
break;
case 'q':
np_dbi_query = optarg;
break;
case 'D':
np_dbi_database = optarg;
break;
}
}
set_thresholds (&dbi_thresholds, warning_range, critical_range);
return validate_arguments ();
}
int
validate_arguments ()
{
if (! np_dbi_driver)
usage ("Must specify a DBI driver");
if (((metric == METRIC_QUERY_RESULT) || (metric == METRIC_QUERY_TIME))
&& (! np_dbi_query))
usage ("Must specify a query to execute (metric == QUERY_RESULT)");
if ((metric != METRIC_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");
if (expect_re_str && (warning_range || critical_range || expect))
usage ("Do not mix -r/-R and -w/-c/-e");
if (expect && (metric != 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");
return OK;
}
void
print_help (void)
{
print_revision (progname, NP_VERSION);
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 ("\n\n");
print_usage ();
printf (UT_HELP_VRSN);
/* include this conditionally to avoid 'zero-length printf format string'
* compiler warnings */
#ifdef NP_EXTRA_OPTS
printf (UT_EXTRA_OPTS);
#endif
printf ("\n");
printf (" %s\n", "-d, --driver=STRING");
printf (" %s\n", _("DBI driver to use"));
printf (" %s\n", "-o, --option=STRING");
printf (" %s\n", _("DBI driver options"));
printf (" %s\n", "-q, --query=STRING");
printf (" %s\n", _("query to execute"));
printf ("\n");
printf (UT_WARN_CRIT_RANGE);
printf (" %s\n", "-e, --expect=STRING");
printf (" %s\n", _("String to expect as query result"));
printf (" %s\n", _("Do not mix with -w, -c, -r, or -R!"));
printf (" %s\n", "-r, --regex=REGEX");
printf (" %s\n", _("Extended POSIX regular expression to check query result against"));
printf (" %s\n", _("Do not mix with -w, -c, -e, or -R!"));
printf (" %s\n", "-R, --regexi=REGEX");
printf (" %s\n", _("Case-insensitive extended POSIX regex to check query result against"));
printf (" %s\n", _("Do not mix with -w, -c, -e, or -r!"));
printf (" %s\n", "-m, --metric=METRIC");
printf (" %s\n", _("Metric to check thresholds against. Available metrics:"));
printf (" CONN_TIME - %s\n", _("time used for setting up the database connection"));
printf (" QUERY_RESULT - %s\n", _("result (first column of first row) of the query"));
printf (" QUERY_TIME - %s\n", _("time used to execute the query"));
printf (" %s\n", _("(ignore the query result)"));
printf ("\n");
printf (UT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
printf (UT_VERBOSE);
printf ("\n");
printf (" %s\n", _("A DBI driver (-d option) is required. If the specified metric operates"));
printf (" %s\n\n", _("on a query, one has to be specified (-q option)."));
printf (" %s\n", _("This plugin connects to an (SQL) database using libdbi and, optionally,"));
printf (" %s\n", _("executes the specified query. The first column of the first row of the"));
printf (" %s\n", _("result will be parsed and, in QUERY_RESULT mode, compared with the"));
printf (" %s\n", _("warning and critical ranges. The result from the query has to be numeric"));
printf (" %s\n\n", _("(strings representing numbers are fine)."));
printf (" %s\n", _("The number and type of required DBI driver options depends on the actual"));
printf (" %s\n", _("driver. See its documentation at http://libdbi-drivers.sourceforge.net/"));
printf (" %s\n\n", _("for details."));
printf (" %s\n", _("Examples:"));
printf (" check_dbi -d pgsql -o username=postgres -m QUERY_RESULT \\\n");
printf (" -q 'SELECT COUNT(*) FROM pg_stat_activity' -w 5 -c 10\n");
printf (" Warning if more than five connections; critical if more than ten.\n\n");
printf (" check_dbi -d mysql -H localhost -o username=user -o password=secret \\\n");
printf (" -q 'SELECT COUNT(*) FROM logged_in_users -w 5:20 -c 0:50\n");
printf (" Warning if less than 5 or more than 20 users are logged in; critical\n");
printf (" if more than 50 users.\n\n");
printf (" check_dbi -d firebird -o username=user -o password=secret -o dbname=foo \\\n");
printf (" -m CONN_TIME -w 0.5 -c 2\n");
printf (" Warning if connecting to the database takes more than half of a second;\n");
printf (" critical if it takes more than 2 seconds.\n\n");
printf (" check_dbi -d mysql -H localhost -o username=user \\\n");
printf (" -q 'SELECT concat(@@version, \" \", @@version_comment)' \\\n");
printf (" -r '^5\\.[01].*MySQL Enterprise Server'\n");
printf (" Critical if the database server is not a MySQL enterprise server in either\n");
printf (" version 5.0.x or 5.1.x.\n\n");
printf (" check_dbi -d pgsql -u username=user -m SERVER_VERSION \\\n");
printf (" -w 090000:090099 -c 090000:090199\n");
printf (" Warn if the PostgreSQL server version is not 9.0.x; critical if the version\n");
printf (" is less than 9.x or higher than 9.1.x.\n");
printf (UT_SUPPORT);
}
void
print_usage (void)
{
printf ("%s\n", _("Usage:"));
printf ("%s -d <DBI driver> [-o <DBI driver option> [...]] [-q <query>]\n", progname);
printf (" [-H <host>] [-c <critical range>] [-w <warning range>] [-m <metric>]\n");
printf (" [-e <string>] [-r|-R <regex>]\n");
}
#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 *str;
if (field_type != DBI_TYPE_STRING) {
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");
return NULL;
}
if ((verbose && (type == TYPE_STRING)) || (verbose > 2))
printf ("Query returned string '%s'\n", str);
return str;
}
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) {
const char *val_str;
char *endptr = NULL;
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);
if (endptr == 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 (verbose)
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"
: "<unknown>",
*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)
{
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");
return STATE_CRITICAL;
}
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");
return STATE_CRITICAL;
}
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");
return STATE_CRITICAL;
}
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));
else
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");
return STATE_CRITICAL;
}
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)
{
dbi_result res;
struct timeval timeval_start, timeval_end;
int status = STATE_OK;
assert (np_dbi_query);
if (verbose)
printf ("Executing query '%s'\n", np_dbi_query);
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);
return STATE_CRITICAL;
}
status = get_query_result (conn, res, res_val_str, res_val);
gettimeofday (&timeval_end, NULL);
*res_time = timediff (timeval_start, timeval_end);
if (verbose)
printf ("Time elapsed: %f\n", *res_time);
return status;
}
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;
return diff;
}
void
np_dbi_print_error (dbi_conn conn, char *fmt, ...)
{
const char *errmsg = NULL;
va_list ap;
va_start (ap, fmt);
dbi_conn_error (conn, &errmsg);
vprintf (fmt, ap);
printf (": %s\n", errmsg);
va_end (ap);
}

View file

@ -54,6 +54,7 @@ char *record_type = "A";
char *expected_address = NULL;
char *dns_server = NULL;
char *dig_args = "";
char *query_transport = "";
int verbose = FALSE;
int server_port = DEFAULT_PORT;
double warning_interval = UNDEFINED;
@ -77,7 +78,7 @@ main (int argc, char **argv)
textdomain (PACKAGE);
/* Set signal handling and alarm */
if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR)
if (signal (SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR)
usage_va(_("Cannot catch SIGALRM"));
/* Parse extra opts if any */
@ -87,8 +88,8 @@ main (int argc, char **argv)
usage_va(_("Could not parse arguments"));
/* get the command to run */
asprintf (&command_line, "%s @%s -p %d %s -t %s %s",
PATH_TO_DIG, dns_server, server_port, query_address, record_type, dig_args);
xasprintf (&command_line, "%s @%s -p %d %s -t %s %s %s",
PATH_TO_DIG, dns_server, server_port, query_address, record_type, dig_args, query_transport);
alarm (timeout_interval);
gettimeofday (&tv, NULL);
@ -199,6 +200,8 @@ process_arguments (int argc, char **argv)
{"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}
};
@ -206,7 +209,7 @@ process_arguments (int argc, char **argv)
return ERROR;
while (1) {
c = getopt_long (argc, argv, "hVvt:l:H:w:c:T:p:a:A:", longopts, &option);
c = getopt_long (argc, argv, "hVvt:l:H:w:c:T:p:a:A:46", longopts, &option);
if (c == -1 || c == EOF)
break;
@ -269,6 +272,12 @@ process_arguments (int argc, char **argv)
case 'a':
expected_address = optarg;
break;
case '4':
query_transport = "-4";
break;
case '6':
query_transport = "-6";
break;
default: /* usage5 */
usage5();
}
@ -306,7 +315,7 @@ print_help (void)
{
char *myport;
asprintf (&myport, "%d", DEFAULT_PORT);
xasprintf (&myport, "%d", DEFAULT_PORT);
print_revision (progname, NP_VERSION);
@ -325,6 +334,10 @@ print_help (void)
printf (UT_HOST_PORT, 'p', myport);
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");

View file

@ -91,9 +91,12 @@ static int stat_remote_fs = 0;
/* Linked list of filesystem types to omit.
If the list is empty, don't exclude any types. */
static struct name_list *fs_exclude_list;
/* Linked list of filesystem types to check.
If the list is empty, include all types. */
static struct name_list *fs_include_list;
static struct name_list *dp_exclude_list;
static struct parameter_list *path_select_list = NULL;
@ -135,6 +138,7 @@ int verbose = 0;
int erronly = FALSE;
int display_mntp = FALSE;
int exact_match = FALSE;
int freespace_ignore_reserved = FALSE;
char *warn_freespace_units = NULL;
char *crit_freespace_units = NULL;
char *warn_freespace_percent = NULL;
@ -255,6 +259,9 @@ main (int argc, char **argv)
(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_name (fs_include_list, me->me_type)) {
continue;
}
stat_path(path);
@ -320,7 +327,7 @@ main (int argc, char **argv)
}
/* Nb: *_high_tide are unset when == UINT_MAX */
asprintf (&perf, "%s %s", perf,
xasprintf (&perf, "%s %s", perf,
perfdata ((!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir,
path->dused_units, units,
(warning_high_tide != UINT_MAX ? TRUE : FALSE), warning_high_tide,
@ -331,20 +338,20 @@ main (int argc, char **argv)
if (disk_result==STATE_OK && erronly && !verbose)
continue;
asprintf (&output, "%s %s %.0f %s (%.0f%%",
xasprintf (&output, "%s %s %.0f %s (%.0f%%",
output,
(!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) {
asprintf(&output, "%s inode=-);", output);
xasprintf(&output, "%s inode=-);", output);
} else {
asprintf(&output, "%s inode=%.0f%%);", output, path->dfree_inodes_percent );
xasprintf(&output, "%s inode=%.0f%%);", output, path->dfree_inodes_percent );
}
/* TODO: Need to do a similar debug line
asprintf (&details, _("%s\n\
xasprintf (&details, _("%s\n\
%.0f of %.0f %s (%.0f%% inode=%.0f%%) free on %s (type %s mounted on %s) warn:%lu crit:%lu warn%%:%.0f%% crit%%:%.0f%%"),
details, dfree_units, dtotal_units, units, dfree_pct, inode_space_pct,
me->me_devname, me->me_type, me->me_mountdir,
@ -356,7 +363,7 @@ main (int argc, char **argv)
}
if (verbose >= 2)
asprintf (&output, "%s%s", output, details);
xasprintf (&output, "%s%s", output, details);
printf ("DISK %s%s%s|%s\n", state_text (result), (erronly && result==STATE_OK) ? "" : preamble, output, perf);
@ -419,11 +426,13 @@ process_arguments (int argc, char **argv)
{"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'},
@ -452,7 +461,7 @@ process_arguments (int argc, char **argv)
strcpy (argv[c], "-t");
while (1) {
c = getopt_long (argc, argv, "+?VqhveCt:c:w:K:W:u:p:x:X:mklLg:R:r:i:I:MEA", longopts, &option);
c = getopt_long (argc, argv, "+?VqhvefCt:c:w:K:W:u:p:x:X:N:mklLg:R:r:i:I:MEA", longopts, &option);
if (c == -1 || c == EOF)
break;
@ -473,13 +482,13 @@ process_arguments (int argc, char **argv)
if (*optarg == '@') {
warn_freespace_percent = optarg;
} else {
asprintf(&warn_freespace_percent, "@%s", optarg);
xasprintf(&warn_freespace_percent, "@%s", optarg);
}
} else {
if (*optarg == '@') {
warn_freespace_units = optarg;
} else {
asprintf(&warn_freespace_units, "@%s", optarg);
xasprintf(&warn_freespace_units, "@%s", optarg);
}
}
break;
@ -494,13 +503,13 @@ process_arguments (int argc, char **argv)
if (*optarg == '@') {
crit_freespace_percent = optarg;
} else {
asprintf(&crit_freespace_percent, "@%s", optarg);
xasprintf(&crit_freespace_percent, "@%s", optarg);
}
} else {
if (*optarg == '@') {
crit_freespace_units = optarg;
} else {
asprintf(&crit_freespace_units, "@%s", optarg);
xasprintf(&crit_freespace_units, "@%s", optarg);
}
}
break;
@ -509,14 +518,14 @@ process_arguments (int argc, char **argv)
if (*optarg == '@') {
warn_freeinodes_percent = optarg;
} else {
asprintf(&warn_freeinodes_percent, "@%s", optarg);
xasprintf(&warn_freeinodes_percent, "@%s", optarg);
}
break;
case 'K': /* critical inode threshold */
if (*optarg == '@') {
crit_freeinodes_percent = optarg;
} else {
asprintf(&crit_freeinodes_percent, "@%s", optarg);
xasprintf(&crit_freeinodes_percent, "@%s", optarg);
}
break;
case 'u':
@ -591,6 +600,9 @@ process_arguments (int argc, char **argv)
case 'X': /* exclude file system type */
np_add_name(&fs_exclude_list, optarg);
break;
case 'N': /* include file system type */
np_add_name(&fs_include_list, optarg);
break;
case 'v': /* verbose */
verbose++;
break;
@ -606,6 +618,9 @@ process_arguments (int argc, char **argv)
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"));
@ -856,7 +871,7 @@ print_help (void)
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 CRITCAL status if less than PERCENT of disk space is free"));
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%");
@ -871,6 +886,8 @@ print_help (void)
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", "-g, --group=NAME");
printf (" %s\n", _("Group paths. Thresholds apply to (free-)space of all partitions together"));
printf (" %s\n", "-k, --kilobytes");
@ -900,6 +917,8 @@ print_help (void)
printf (UT_VERBOSE);
printf (" %s\n", "-X, --exclude-type=TYPE");
printf (" %s\n", _("Ignore all filesystems of indicated type (may be repeated)"));
printf (" %s\n", "-N, --include-type=TYPE");
printf (" %s\n", _("Check only filesystems of indicated type (may be repeated)"));
printf ("\n");
printf ("%s\n", _("Examples:"));
@ -921,8 +940,8 @@ print_usage (void)
{
printf ("%s\n", _("Usage:"));
printf (" %s -w limit -c limit [-W limit] [-K limit] {-p path | -x device}\n", progname);
printf ("[-C] [-E] [-e] [-g group ] [-k] [-l] [-M] [-m] [-R path ] [-r path ]\n");
printf ("[-t timeout] [-u unit] [-v] [-X type]\n");
printf ("[-C] [-E] [-e] [-f] [-g group ] [-k] [-l] [-M] [-m] [-R path ] [-r path ]\n");
printf ("[-t timeout] [-u unit] [-v] [-X type] [-N type]\n");
}
void
@ -994,13 +1013,19 @@ get_stats (struct parameter_list *p, struct fs_usage *fsp) {
void
get_path_stats (struct parameter_list *p, struct fs_usage *fsp) {
p->total = fsp->fsu_blocks;
/* 2007-12-08 - Workaround for Gnulib reporting insanely high available
* space on BSD (the actual value should be negative but fsp->fsu_bavail
* is unsigned) */
p->available = fsp->fsu_bavail > fsp->fsu_bfree ? 0 : fsp->fsu_bavail;
p->available_to_root = fsp->fsu_bfree;
p->used = p->total - p->available_to_root;
p->used = fsp->fsu_blocks - fsp->fsu_bfree;
if (freespace_ignore_reserved) {
/* option activated : we substract 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;

View file

@ -91,7 +91,7 @@ main (int argc, char **argv)
textdomain (PACKAGE);
/* Set signal handling and alarm */
if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
if (signal (SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) {
usage_va(_("Cannot catch SIGALRM"));
}
@ -103,7 +103,7 @@ main (int argc, char **argv)
}
/* get the command to run */
asprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server);
xasprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server);
alarm (timeout_interval);
gettimeofday (&tv, NULL);
@ -208,19 +208,19 @@ main (int argc, char **argv)
for (i=0; i<expected_address_cnt; i++) {
/* check if we get a match and prepare an error string */
if (strcmp(address, expected_address[i]) == 0) result = STATE_OK;
asprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]);
xasprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]);
}
if (result == STATE_CRITICAL) {
/* Strip off last semicolon... */
temp_buffer[strlen(temp_buffer)-2] = '\0';
asprintf(&msg, _("expected '%s' but got '%s'"), temp_buffer, address);
xasprintf(&msg, _("expected '%s' but got '%s'"), temp_buffer, address);
}
}
/* check if authoritative */
if (result == STATE_OK && expect_authority && non_authoritative) {
result = STATE_CRITICAL;
asprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address);
xasprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address);
}
microsec = deltime (tv);

View file

@ -52,6 +52,8 @@ 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;
@ -72,6 +74,8 @@ main (int argc, char **argv)
/* normaly 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;
@ -92,11 +96,24 @@ main (int argc, char **argv)
/* compose the command */
if (target_timeout)
asprintf(&option_string, "%s-t %d ", option_string, target_timeout);
xasprintf(&option_string, "%s-t %d ", option_string, target_timeout);
if (packet_interval)
asprintf(&option_string, "%s-p %d ", option_string, 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);
asprintf (&command_line, "%s %s-b %d -c %d %s", PATH_TO_FPING,
#ifdef PATH_TO_FPING6
if (address_family == AF_INET6)
fping_prog = strdup(PATH_TO_FPING6);
else
fping_prog = strdup(PATH_TO_FPING);
#else
fping_prog = strdup(PATH_TO_FPING);
#endif
xasprintf (&command_line, "%s %s-b %d -c %d %s", fping_prog,
option_string, packet_size, packet_count, server);
if (verbose)
@ -130,10 +147,24 @@ main (int argc, char **argv)
(void) fclose (child_stderr);
/* close the pipe */
if (spclose (child_process))
if (result = spclose (child_process))
/* need to use max_state not max */
status = max_state (status, STATE_WARNING);
if (result > 1 ) {
status = max_state (status, STATE_UNKNOWN);
if (result == 2) {
die (STATE_UNKNOWN, _("FPING UNKNOWN - IP address not found\n"));
}
if (result == 3) {
die (STATE_UNKNOWN, _("FPING UNKNOWN - invalid commandline argument\n"));
}
if (result == 4) {
die (STATE_UNKNOWN, _("FPING UNKNOWN - failed system call\n"));
}
}
printf ("FPING %s - %s\n", state_text (status), server_name);
return status;
@ -159,6 +190,10 @@ textscan (char *buf)
"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);
@ -232,6 +267,8 @@ process_arguments (int argc, char **argv)
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'},
{"bytes", required_argument, 0, 'b'},
@ -241,6 +278,8 @@ process_arguments (int argc, char **argv)
{"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}
};
@ -258,7 +297,7 @@ process_arguments (int argc, char **argv)
}
while (1) {
c = getopt_long (argc, argv, "+hVvH:c:w:b:n:T:i:", longopts, &option);
c = getopt_long (argc, argv, "+hVvH:S:c:w:b:n:T:i:I:46", longopts, &option);
if (c == -1 || c == EOF || c == 1)
break;
@ -281,6 +320,24 @@ process_arguments (int argc, char **argv)
}
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);
case '4': /* IPv4 only */
address_family = AF_INET;
break;
case '6': /* IPv6 only */
#ifdef USE_IPV6
address_family = AF_INET6;
#else
usage (_("IPv6 support not available\n"));
#endif
break;
case 'c':
get_threshold (optarg, rv);
if (rv[RTA]) {
@ -402,6 +459,8 @@ print_help (void)
printf (UT_HELP_VRSN);
printf (UT_EXTRA_OPTS);
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");
@ -413,15 +472,22 @@ print_help (void)
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)"),PACKET_COUNT);
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"),PACKET_COUNT);
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 <rta>,<pl>%% where <rta> is the round trip average travel time (ms)"));
printf (" %s\n", _("which triggers a WARNING or CRITICAL state, and <pl> 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 (UT_SUPPORT);
}

View file

@ -84,11 +84,11 @@ main (int argc, char **argv)
result = STATE_OK;
/* create the command line to execute */
asprintf (&command_line, "%s -raw %s -%s %s",
xasprintf (&command_line, "%s -raw %s -%s %s",
PATH_TO_QSTAT, QSTAT_DATA_DELIMITER, game_type, server_ip);
if (port)
asprintf (&command_line, "%s:%-d", command_line, port);
xasprintf (&command_line, "%s:%-d", command_line, port);
if (verbose > 0)
printf ("%s\n", command_line);

View file

@ -227,7 +227,7 @@ main (int argc, char **argv)
/* might not be the problem, but most likely is. */
result = STATE_UNKNOWN ;
asprintf (&errmsg, "%s : Timeout from host %s\n", errmsg, address );
xasprintf (&errmsg, "%s : Timeout from host %s\n", errmsg, address );
}

View file

@ -1,40 +1,40 @@
/*****************************************************************************
*
*
* Nagios check_http plugin
*
*
* License: GPL
* Copyright (c) 1999-2008 Nagios Plugins Development Team
*
* Copyright (c) 1999-2013 Nagios Plugins Development Team
*
* Description:
*
*
* This file contains the check_http plugin
*
*
* This plugin tests the HTTP service on the specified host. It can test
* normal (http) and secure (https) servers, follow redirects, search for
* strings and regular expressions, check connection times, and report on
* certificate expiration times.
*
*
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
*****************************************************************************/
/* splint -I. -I../../plugins -I../../lib/ -I/usr/kerberos/include/ ../../plugins/check_http.c */
const char *progname = "check_http";
const char *copyright = "1999-2011";
const char *copyright = "1999-2013";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
@ -43,7 +43,6 @@ const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "base64.h"
#include <ctype.h>
#define INPUT_DELIMITER ";"
#define STICKY_NONE 0
#define STICKY_HOST 1
#define STICKY_PORT 2
@ -85,6 +84,7 @@ int errcode;
int invert_regex = 0;
struct timeval tv;
struct timeval tv_temp;
#define HTTP_URL "/"
#define CRLF "\r\n"
@ -100,7 +100,9 @@ char *user_agent;
int server_url_length;
int server_expect_yn = 0;
char server_expect[MAX_INPUT_BUFFER] = HTTP_EXPECT;
char header_expect[MAX_INPUT_BUFFER] = "";
char string_expect[MAX_INPUT_BUFFER] = "";
char output_header_search[30] = "";
char output_string_search[30] = "";
char *warning_thresholds = NULL;
char *critical_thresholds = NULL;
@ -115,6 +117,7 @@ int followsticky = STICKY_NONE;
int use_ssl = FALSE;
int use_sni = FALSE;
int verbose = FALSE;
int show_extended_perfdata = FALSE;
int sd;
int min_page_len = 0;
int max_page_len = 0;
@ -124,6 +127,8 @@ char *http_method;
char *http_post_data;
char *http_content_type;
char buffer[MAX_INPUT_BUFFER];
char *client_cert = NULL;
char *client_privkey = NULL;
int process_arguments (int, char **);
int check_http (void);
@ -131,6 +136,11 @@ void redir (char *pos, char *status_line);
int server_type_check(const char *type);
int server_port_check(int ssl_flag);
char *perfd_time (double microsec);
char *perfd_time_connect (double microsec);
char *perfd_time_ssl (double microsec);
char *perfd_time_firstbyte (double microsec);
char *perfd_time_headers (double microsec);
char *perfd_time_transfer (double microsec);
char *perfd_size (int page_len);
void print_help (void);
void print_usage (void);
@ -147,7 +157,7 @@ main (int argc, char **argv)
/* Set default URL. Must be malloced for subsequent realloc if --onredirect=follow */
server_url = strdup(HTTP_URL);
server_url_length = strlen(server_url);
asprintf (&user_agent, "User-Agent: check_http/v%s (nagios-plugins %s)",
xasprintf (&user_agent, "User-Agent: check_http/v%s (nagios-plugins %s)",
NP_VERSION, VERSION);
/* Parse extra opts if any */
@ -170,7 +180,14 @@ main (int argc, char **argv)
return result;
}
/* 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);
}
/* process command-line arguments */
int
@ -199,6 +216,7 @@ process_arguments (int argc, char **argv)
{"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'},
@ -207,6 +225,8 @@ process_arguments (int argc, char **argv)
{"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'},
{"useragent", required_argument, 0, 'A'},
{"header", required_argument, 0, 'k'},
{"no-body", no_argument, 0, 'N'},
@ -216,6 +236,7 @@ process_arguments (int argc, char **argv)
{"invert-regex", no_argument, NULL, INVERT_REGEX},
{"use-ipv4", no_argument, 0, '4'},
{"use-ipv6", no_argument, 0, '6'},
{"extended-perfdata", no_argument, 0, 'E'},
{0, 0, 0, 0}
};
@ -236,7 +257,7 @@ process_arguments (int argc, char **argv)
}
while (1) {
c = getopt_long (argc, argv, "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:e:p:s:R:r:u:f:C:nlLS::m:M:N", longopts, &option);
c = getopt_long (argc, argv, "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:d:e:p:s:R:r:u:f:C:J:K:nlLS::m:M:N:E", longopts, &option);
if (c == -1 || c == EOF)
break;
@ -265,7 +286,7 @@ process_arguments (int argc, char **argv)
warning_thresholds = optarg;
break;
case 'A': /* User Agent String */
asprintf (&user_agent, "User-Agent: %s", optarg);
xasprintf (&user_agent, "User-Agent: %s", optarg);
break;
case 'k': /* Additional headers */
if (http_opt_headers_count == 0)
@ -273,7 +294,7 @@ process_arguments (int argc, char **argv)
else
http_opt_headers = realloc (http_opt_headers, sizeof (char *) * (++http_opt_headers_count));
http_opt_headers[http_opt_headers_count - 1] = optarg;
/* asprintf (&http_opt_headers, "%s", optarg); */
/* xasprintf (&http_opt_headers, "%s", optarg); */
break;
case 'L': /* show html link */
display_html = TRUE;
@ -284,29 +305,40 @@ process_arguments (int argc, char **argv)
case 'C': /* Check SSL cert validity */
#ifdef HAVE_SSL
if ((temp=strchr(optarg,','))!=NULL) {
*temp='\0';
if (!is_intnonneg (temp))
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);
*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;
days_till_exp_crit=0;
if (!is_intnonneg (optarg))
usage2 (_("Invalid certificate expiration period"), optarg);
days_till_exp_warn = atoi (optarg);
}
check_cert = TRUE;
/* Fall through to -S option */
goto enable_ssl;
#endif
case 'J': /* use client certificate */
#ifdef HAVE_SSL
test_file(optarg);
client_cert = optarg;
goto enable_ssl;
#endif
case 'K': /* use client private key */
#ifdef HAVE_SSL
test_file(optarg);
client_privkey = optarg;
goto enable_ssl;
#endif
case 'S': /* use SSL */
#ifndef HAVE_SSL
usage4 (_("Invalid option - SSL is not available"));
#endif
#ifdef HAVE_SSL
enable_ssl:
use_ssl = TRUE;
if (optarg == NULL || c != 'S')
ssl_version = 0;
@ -317,6 +349,10 @@ process_arguments (int argc, char **argv)
}
if (specify_port == FALSE)
server_port = HTTPS_PORT;
#else
/* -C -J and -K fall through to here without SSL */
usage4 (_("Invalid option - SSL is not available"));
#endif
break;
case SNI_OPTION:
use_sni = TRUE;
@ -384,6 +420,10 @@ process_arguments (int argc, char **argv)
free(http_method);
http_method = strdup (optarg);
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;
@ -394,7 +434,7 @@ process_arguments (int argc, char **argv)
server_expect_yn = 1;
break;
case 'T': /* Content-type */
asprintf (&http_content_type, "%s", optarg);
xasprintf (&http_content_type, "%s", optarg);
break;
case 'l': /* linespan */
cflags &= ~REG_NEWLINE;
@ -470,6 +510,9 @@ process_arguments (int argc, char **argv)
}
}
break;
case 'E': /* show extended perfdata */
show_extended_perfdata = TRUE;
break;
}
}
@ -496,6 +539,9 @@ process_arguments (int argc, char **argv)
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"));
return TRUE;
}
@ -690,31 +736,31 @@ check_document_dates (const char *headers, char **msg)
/* Done parsing the body. Now check the dates we (hopefully) parsed. */
if (!server_date || !*server_date) {
asprintf (msg, _("%sServer date unknown, "), *msg);
xasprintf (msg, _("%sServer date unknown, "), *msg);
date_result = max_state_alt(STATE_UNKNOWN, date_result);
} else if (!document_date || !*document_date) {
asprintf (msg, _("%sDocument modification date unknown, "), *msg);
xasprintf (msg, _("%sDocument modification date unknown, "), *msg);
date_result = max_state_alt(STATE_CRITICAL, date_result);
} else {
time_t srv_data = parse_time_string (server_date);
time_t doc_data = parse_time_string (document_date);
if (srv_data <= 0) {
asprintf (msg, _("%sServer date \"%100s\" unparsable, "), *msg, server_date);
xasprintf (msg, _("%sServer date \"%100s\" unparsable, "), *msg, server_date);
date_result = max_state_alt(STATE_CRITICAL, date_result);
} else if (doc_data <= 0) {
asprintf (msg, _("%sDocument date \"%100s\" unparsable, "), *msg, document_date);
xasprintf (msg, _("%sDocument date \"%100s\" unparsable, "), *msg, document_date);
date_result = max_state_alt(STATE_CRITICAL, date_result);
} else if (doc_data > srv_data + 30) {
asprintf (msg, _("%sDocument is %d seconds in the future, "), *msg, (int)doc_data - (int)srv_data);
xasprintf (msg, _("%sDocument is %d seconds in the future, "), *msg, (int)doc_data - (int)srv_data);
date_result = max_state_alt(STATE_CRITICAL, date_result);
} else if (doc_data < srv_data - maximum_age) {
int n = (srv_data - doc_data);
if (n > (60 * 60 * 24 * 2)) {
asprintf (msg, _("%sLast modified %.1f days ago, "), *msg, ((float) n) / (60 * 60 * 24));
xasprintf (msg, _("%sLast modified %.1f days ago, "), *msg, ((float) n) / (60 * 60 * 24));
date_result = max_state_alt(STATE_CRITICAL, date_result);
} else {
asprintf (msg, _("%sLast modified %d:%02d:%02d ago, "), *msg, n / (60 * 60), (n / 60) % 60, n % 60);
xasprintf (msg, _("%sLast modified %d:%02d:%02d ago, "), *msg, n / (60 * 60), (n / 60) % 60, n % 60);
date_result = max_state_alt(STATE_CRITICAL, date_result);
}
}
@ -811,17 +857,33 @@ check_http (void)
char *pos;
long microsec;
double elapsed_time;
long microsec_connect;
double elapsed_time_connect;
long microsec_ssl;
double elapsed_time_ssl;
long microsec_firstbyte;
double elapsed_time_firstbyte;
long microsec_headers;
double elapsed_time_headers;
long microsec_transfer;
double elapsed_time_transfer;
int page_len = 0;
int result = STATE_OK;
/* try to connect to the host at the given port number */
gettimeofday (&tv_temp, NULL);
if (my_tcp_connect (server_address, server_port, &sd) != STATE_OK)
die (STATE_CRITICAL, _("HTTP CRITICAL - Unable to open TCP socket\n"));
microsec_connect = deltime (tv_temp);
#ifdef HAVE_SSL
elapsed_time_connect = (double)microsec_connect / 1.0e6;
if (use_ssl == TRUE) {
result = np_net_ssl_init_with_hostname_and_version(sd, (use_sni ? host_name : NULL), ssl_version);
gettimeofday (&tv_temp, NULL);
result = np_net_ssl_init_with_hostname_version_and_cert(sd, (use_sni ? host_name : NULL), ssl_version, client_cert, client_privkey);
if (result != STATE_OK)
return result;
microsec_ssl = deltime (tv_temp);
elapsed_time_ssl = (double)microsec_ssl / 1.0e6;
if (check_cert == TRUE) {
result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit);
np_net_ssl_cleanup();
@ -831,10 +893,10 @@ check_http (void)
}
#endif /* HAVE_SSL */
asprintf (&buf, "%s %s %s\r\n%s\r\n", http_method, server_url, host_name ? "HTTP/1.1" : "HTTP/1.0", user_agent);
xasprintf (&buf, "%s %s %s\r\n%s\r\n", http_method, server_url, host_name ? "HTTP/1.1" : "HTTP/1.0", user_agent);
/* tell HTTP/1.1 servers not to keep the connection alive */
asprintf (&buf, "%sConnection: close\r\n", buf);
xasprintf (&buf, "%sConnection: close\r\n", buf);
/* optionally send the host header info */
if (host_name) {
@ -845,16 +907,15 @@ check_http (void)
*/
if ((use_ssl == FALSE && server_port == HTTP_PORT) ||
(use_ssl == TRUE && server_port == HTTPS_PORT))
asprintf (&buf, "%sHost: %s\r\n", buf, host_name);
xasprintf (&buf, "%sHost: %s\r\n", buf, host_name);
else
asprintf (&buf, "%sHost: %s:%d\r\n", buf, host_name, server_port);
xasprintf (&buf, "%sHost: %s:%d\r\n", buf, host_name, server_port);
}
/* optionally send any other header tag */
if (http_opt_headers_count) {
for (i = 0; i < http_opt_headers_count ; i++) {
for ((pos = strtok(http_opt_headers[i], INPUT_DELIMITER)); pos; (pos = strtok(NULL, INPUT_DELIMITER)))
asprintf (&buf, "%s%s\r\n", buf, pos);
xasprintf (&buf, "%s%s\r\n", buf, http_opt_headers[i]);
}
/* This cannot be free'd here because a redirection will then try to access this and segfault */
/* Covered in a testcase in tests/check_http.t */
@ -864,39 +925,47 @@ check_http (void)
/* optionally send the authentication info */
if (strlen(user_auth)) {
base64_encode_alloc (user_auth, strlen (user_auth), &auth);
asprintf (&buf, "%sAuthorization: Basic %s\r\n", buf, auth);
xasprintf (&buf, "%sAuthorization: Basic %s\r\n", buf, auth);
}
/* optionally send the proxy authentication info */
if (strlen(proxy_auth)) {
base64_encode_alloc (proxy_auth, strlen (proxy_auth), &auth);
asprintf (&buf, "%sProxy-Authorization: Basic %s\r\n", buf, auth);
xasprintf (&buf, "%sProxy-Authorization: Basic %s\r\n", buf, auth);
}
/* either send http POST data (any data, not only POST)*/
if (http_post_data) {
if (http_content_type) {
asprintf (&buf, "%sContent-Type: %s\r\n", buf, http_content_type);
xasprintf (&buf, "%sContent-Type: %s\r\n", buf, http_content_type);
} else {
asprintf (&buf, "%sContent-Type: application/x-www-form-urlencoded\r\n", buf);
xasprintf (&buf, "%sContent-Type: application/x-www-form-urlencoded\r\n", buf);
}
asprintf (&buf, "%sContent-Length: %i\r\n\r\n", buf, (int)strlen (http_post_data));
asprintf (&buf, "%s%s%s", buf, http_post_data, CRLF);
xasprintf (&buf, "%sContent-Length: %i\r\n\r\n", buf, (int)strlen (http_post_data));
xasprintf (&buf, "%s%s%s", buf, http_post_data, CRLF);
}
else {
/* or just a newline so the server knows we're done with the request */
asprintf (&buf, "%s%s", buf, CRLF);
xasprintf (&buf, "%s%s", buf, CRLF);
}
if (verbose) printf ("%s\n", buf);
gettimeofday (&tv_temp, NULL);
my_send (buf, strlen (buf));
microsec_headers = deltime (tv_temp);
elapsed_time_headers = (double)microsec_headers / 1.0e6;
/* fetch the page */
full_page = strdup("");
gettimeofday (&tv_temp, NULL);
while ((i = my_recv (buffer, MAX_INPUT_BUFFER-1)) > 0) {
if ((i >= 1) && (elapsed_time_firstbyte <= 0.000001)) {
microsec_firstbyte = deltime (tv_temp);
elapsed_time_firstbyte = (double)microsec_firstbyte / 1.0e6;
}
buffer[i] = '\0';
asprintf (&full_page_new, "%s%s", full_page, buffer);
xasprintf (&full_page_new, "%s%s", full_page, buffer);
free (full_page);
full_page = full_page_new;
pagesize += i;
@ -906,6 +975,8 @@ check_http (void)
break;
}
}
microsec_transfer = deltime (tv_temp);
elapsed_time_transfer = (double)microsec_transfer / 1.0e6;
if (i < 0 && errno != ECONNRESET) {
#ifdef HAVE_SSL
@ -981,11 +1052,11 @@ check_http (void)
/* make sure the status line matches the response we are looking for */
if (!expected_statuscode (status_line, server_expect)) {
if (server_port == HTTP_PORT)
asprintf (&msg,
xasprintf (&msg,
_("Invalid HTTP response received from host: %s\n"),
status_line);
else
asprintf (&msg,
xasprintf (&msg,
_("Invalid HTTP response received from host on port %d: %s\n"),
server_port, status_line);
die (STATE_CRITICAL, "HTTP CRITICAL - %s", msg);
@ -994,7 +1065,7 @@ check_http (void)
/* Bypass normal status line check if server_expect was set by user and not default */
/* NOTE: After this if/else block msg *MUST* be an asprintf-allocated string */
if ( server_expect_yn ) {
asprintf (&msg,
xasprintf (&msg,
_("Status line output matched \"%s\" - "), server_expect);
if (verbose)
printf ("%s\n",msg);
@ -1017,12 +1088,12 @@ check_http (void)
}
/* server errors result in a critical state */
else if (http_status >= 500) {
asprintf (&msg, _("%s - "), status_line);
xasprintf (&msg, _("%s - "), status_line);
result = STATE_CRITICAL;
}
/* client errors result in a warning state */
else if (http_status >= 400) {
asprintf (&msg, _("%s - "), status_line);
xasprintf (&msg, _("%s - "), status_line);
result = max_state_alt(STATE_WARNING, result);
}
/* check redirected page if specified */
@ -1032,11 +1103,11 @@ check_http (void)
redir (header, status_line);
else
result = max_state_alt(onredirect, result);
asprintf (&msg, _("%s - "), status_line);
xasprintf (&msg, _("%s - "), status_line);
} /* end if (http_status >= 300) */
else {
/* Print OK status anyway */
asprintf (&msg, _("%s - "), status_line);
xasprintf (&msg, _("%s - "), status_line);
}
} /* end else (server_expect_yn) */
@ -1049,6 +1120,17 @@ check_http (void)
}
/* Page and Header content checks go here */
if (strlen (header_expect)) {
if (!strstr (header, header_expect)) {
strncpy(&output_header_search[0],header_expect,sizeof(output_header_search));
if(output_header_search[sizeof(output_header_search)-1]!='\0') {
bcopy("...",&output_header_search[sizeof(output_header_search)-4],4);
}
xasprintf (&msg, _("%sheader '%s' not found on '%s://%s:%d%s', "), msg, output_header_search, use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port, server_url);
result = STATE_CRITICAL;
}
}
if (strlen (string_expect)) {
if (!strstr (page, string_expect)) {
@ -1056,7 +1138,7 @@ check_http (void)
if(output_string_search[sizeof(output_string_search)-1]!='\0') {
bcopy("...",&output_string_search[sizeof(output_string_search)-4],4);
}
asprintf (&msg, _("%sstring '%s' not found on '%s://%s:%d%s', "), msg, output_string_search, use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port, server_url);
xasprintf (&msg, _("%sstring '%s' not found on '%s://%s:%d%s', "), msg, output_string_search, use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port, server_url);
result = STATE_CRITICAL;
}
}
@ -1069,15 +1151,15 @@ check_http (void)
}
else if ((errcode == REG_NOMATCH && invert_regex == 0) || (errcode == 0 && invert_regex == 1)) {
if (invert_regex == 0)
asprintf (&msg, _("%spattern not found, "), msg);
xasprintf (&msg, _("%spattern not found, "), msg);
else
asprintf (&msg, _("%spattern found, "), msg);
xasprintf (&msg, _("%spattern found, "), msg);
result = STATE_CRITICAL;
}
else {
/* FIXME: Shouldn't that be UNKNOWN? */
regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
asprintf (&msg, _("%sExecute Error: %s, "), msg, errbuf);
xasprintf (&msg, _("%sExecute Error: %s, "), msg, errbuf);
result = STATE_CRITICAL;
}
}
@ -1093,10 +1175,10 @@ check_http (void)
*/
page_len = pagesize;
if ((max_page_len > 0) && (page_len > max_page_len)) {
asprintf (&msg, _("%spage size %d too large, "), msg, page_len);
xasprintf (&msg, _("%spage size %d too large, "), msg, page_len);
result = max_state_alt(STATE_WARNING, result);
} else if ((min_page_len > 0) && (page_len < min_page_len)) {
asprintf (&msg, _("%spage size %d too small, "), msg, page_len);
xasprintf (&msg, _("%spage size %d too small, "), msg, page_len);
result = max_state_alt(STATE_WARNING, result);
}
@ -1107,11 +1189,25 @@ check_http (void)
msg[strlen(msg)-3] = '\0';
/* check elapsed time */
asprintf (&msg,
_("%s - %d bytes in %.3f second response time %s|%s %s"),
msg, page_len, elapsed_time,
(display_html ? "</A>" : ""),
perfd_time (elapsed_time), perfd_size (page_len));
if (show_extended_perfdata)
xasprintf (&msg,
_("%s - %d bytes in %.3f second response time %s|%s %s %s %s %s %s %s"),
msg, page_len, elapsed_time,
(display_html ? "</A>" : ""),
perfd_time (elapsed_time),
perfd_size (page_len),
perfd_time_connect (elapsed_time_connect),
use_ssl == TRUE ? perfd_time_ssl (elapsed_time_ssl) : "",
perfd_time_headers (elapsed_time_headers),
perfd_time_firstbyte (elapsed_time_firstbyte),
perfd_time_transfer (elapsed_time_transfer));
else
xasprintf (&msg,
_("%s - %d bytes in %.3f second response time %s|%s %s"),
msg, page_len, elapsed_time,
(display_html ? "</A>" : ""),
perfd_time (elapsed_time),
perfd_size (page_len));
result = max_state_alt(get_status(elapsed_time, thlds), result);
@ -1214,7 +1310,7 @@ redir (char *pos, char *status_line)
if ((url[0] != '/')) {
if ((x = strrchr(server_url, '/')))
*x = '\0';
asprintf (&url, "%s/%s", server_url, url);
xasprintf (&url, "%s/%s", server_url, url);
}
i = server_port;
strcpy (type, server_type);
@ -1300,7 +1396,30 @@ char *perfd_time (double elapsed_time)
TRUE, 0, FALSE, 0);
}
char *perfd_time_connect (double elapsed_time_connect)
{
return fperfdata ("time_connect", elapsed_time_connect, "s", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0);
}
char *perfd_time_ssl (double elapsed_time_ssl)
{
return fperfdata ("time_ssl", elapsed_time_ssl, "s", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0);
}
char *perfd_time_headers (double elapsed_time_headers)
{
return fperfdata ("time_headers", elapsed_time_headers, "s", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0);
}
char *perfd_time_firstbyte (double elapsed_time_firstbyte)
{
return fperfdata ("time_firstbyte", elapsed_time_firstbyte, "s", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0);
}
char *perfd_time_transfer (double elapsed_time_transfer)
{
return fperfdata ("time_transfer", elapsed_time_transfer, "s", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0);
}
char *perfd_size (int page_len)
{
@ -1351,9 +1470,15 @@ print_help (void)
printf (" %s\n", _("auto-negotiation (1 = TLSv1, 2 = SSLv2, 3 = SSLv3)."));
printf (" %s\n", "--sni");
printf (" %s\n", _("Enable SSL/TLS hostname extension support (SNI)"));
printf (" %s\n", "-C, --certificate=INTEGER");
printf (" %s\n", "-C, --certificate=INTEGER[,INTEGER]");
printf (" %s\n", _("Minimum number of days a certificate has to be valid. Port defaults to 443"));
printf (" %s\n", _("(when this option is used the URL is not checked.)\n"));
printf (" %s\n", _("(when this option is used the URL is not checked.)"));
printf (" %s\n", "-J, --client-cert=FILE");
printf (" %s\n", _("Name of file that contains the client certificate (PEM format)"));
printf (" %s\n", _("to be used in establishing the SSL session"));
printf (" %s\n", "-K, --private-key=FILE");
printf (" %s\n", _("Name of file containing the private key (PEM format)"));
printf (" %s\n", _("matching the client certificate"));
#endif
printf (" %s\n", "-e, --expect=STRING");
@ -1361,6 +1486,8 @@ print_help (void)
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");
@ -1395,6 +1522,8 @@ print_help (void)
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", "-L, --link");
printf (" %s\n", _("Wrap output in HTML link (obsoleted by urlize)"));
printf (" %s\n", "-f, --onredirect=<ok|warning|critical|follow|sticky|stickyport>");
@ -1433,14 +1562,14 @@ print_help (void)
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\n", _("a STATE_CRITICAL will be returned."));
printf (" %s\n", _("a STATE_CRITICAL will be returned."));
printf ("\n");
printf (" %s\n\n", "CHECK CERTIFICATE: check_http -H www.verisign.com -C 14");
printf (" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 14 days,"));
printf (" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than"));
printf (" %s\n", _("14 days, a STATE_WARNING is returned. A STATE_CRITICAL will be returned when"));
printf (" %s\n", _("the certificate is expired."));
printf ("\n");
printf (" %s\n\n", "CHECK CERTIFICATE: check_http -H www.verisign.com -C 30,14");
printf (" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 30 days,"));
printf (" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than"));
@ -1460,9 +1589,10 @@ print_usage (void)
{
printf ("%s\n", _("Usage:"));
printf (" %s -H <vhost> | -I <IP-address> [-u <uri>] [-p <port>]\n",progname);
printf (" [-w <warn time>] [-c <critical time>] [-t <timeout>] [-L] [-a auth]\n");
printf (" [-J <client certificate file>] [-K <private key>]\n");
printf (" [-w <warn time>] [-c <critical time>] [-t <timeout>] [-L] [-E] [-a auth]\n");
printf (" [-b proxy_auth] [-f <ok|warning|critcal|follow|sticky|stickyport>]\n");
printf (" [-e <expect>] [-s string] [-l] [-r <regex> | -R <case-insensitive regex>]\n");
printf (" [-e <expect>] [-d string] [-s string] [-l] [-r <regex> | -R <case-insensitive regex>]\n");
printf (" [-P string] [-m <min_pg_size>:<max_pg_size>] [-4|-6] [-N] [-M <age>]\n");
printf (" [-A string] [-k string] [-S <version>] [--sni] [-C <warn_age>[,<crit_age>]]\n");
printf (" [-T <content-type>] [-j method]\n");

View file

@ -46,8 +46,29 @@ void print_usage (void);
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#ifdef __linux__
#include <linux/hdreg.h>
#include <linux/types.h>
#define OPEN_MODE O_RDONLY
#endif /* __linux__ */
#ifdef __NetBSD__
#include <sys/device.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#include <sys/videoio.h> /* for __u8 and friends */
#include <sys/scsiio.h>
#include <sys/ataio.h>
#include <dev/ata/atareg.h>
#include <dev/ic/wdcreg.h>
#define SMART_ENABLE WDSM_ENABLE_OPS
#define SMART_DISABLE WDSM_DISABLE_OPS
#define SMART_IMMEDIATE_OFFLINE WDSM_EXEC_OFFL_IMM
#define SMART_AUTO_OFFLINE 0xdb /* undefined in NetBSD headers */
#define OPEN_MODE O_RDWR
#endif /* __NetBSD__ */
#include <errno.h>
#define NR_ATTRIBUTES 30
@ -223,7 +244,7 @@ main (int argc, char *argv[])
return STATE_OK;
}
fd = open (device, O_RDONLY);
fd = open (device, OPEN_MODE);
if (fd < 0) {
printf (_("CRITICAL - Couldn't open device %s: %s\n"), device, strerror (errno));
@ -284,6 +305,7 @@ get_offline_text (int status)
int
smart_read_values (int fd, values_t * values)
{
#ifdef __linux__
int e;
__u8 args[4 + 512];
args[0] = WIN_SMART;
@ -296,6 +318,35 @@ smart_read_values (int fd, values_t * values)
return e;
}
memcpy (values, args + 4, 512);
#endif /* __linux__ */
#ifdef __NetBSD__
struct atareq req;
unsigned char inbuf[DEV_BSIZE];
memset(&req, 0, sizeof(req));
req.timeout = 1000;
memset(&inbuf, 0, sizeof(inbuf));
req.flags = ATACMD_READ;
req.features = WDSM_RD_DATA;
req.command = WDCC_SMART;
req.databuf = (char *)inbuf;
req.datalen = sizeof(inbuf);
req.cylinder = WDSMART_CYL;
if (ioctl(fd, ATAIOCCOMMAND, &req) == 0) {
if (req.retsts != ATACMD_OK)
errno = ENODEV;
}
if (errno != 0) {
int e = errno;
printf (_("CRITICAL - SMART_READ_VALUES: %s\n"), strerror (errno));
return e;
}
(void)memcpy(values, inbuf, 512);
#endif /* __NetBSD__ */
return 0;
}
@ -439,6 +490,7 @@ int
smart_cmd_simple (int fd, enum SmartCommand command, __u8 val0, char show_error)
{
int e = 0;
#ifdef __linux__
__u8 args[4];
args[0] = WIN_SMART;
args[1] = val0;
@ -450,6 +502,31 @@ smart_cmd_simple (int fd, enum SmartCommand command, __u8 val0, char show_error)
printf (_("CRITICAL - %s: %s\n"), smart_command[command].text, strerror (errno));
}
}
#endif /* __linux__ */
#ifdef __NetBSD__
struct atareq req;
memset(&req, 0, sizeof(req));
req.timeout = 1000;
req.flags = ATACMD_READREG;
req.features = smart_command[command].value;
req.command = WDCC_SMART;
req.cylinder = WDSMART_CYL;
req.sec_count = val0;
if (ioctl(fd, ATAIOCCOMMAND, &req) == 0) {
if (req.retsts != ATACMD_OK)
errno = ENODEV;
if (req.cylinder != WDSMART_CYL)
errno = ENODEV;
}
if (errno != 0) {
e = errno;
printf (_("CRITICAL - %s: %s\n"), smart_command[command].text, strerror (errno));
return e;
}
#endif /* __NetBSD__ */
return e;
}
@ -458,6 +535,7 @@ smart_cmd_simple (int fd, enum SmartCommand command, __u8 val0, char show_error)
int
smart_read_thresholds (int fd, thresholds_t * thresholds)
{
#ifdef __linux__
int e;
__u8 args[4 + 512];
args[0] = WIN_SMART;
@ -470,6 +548,35 @@ smart_read_thresholds (int fd, thresholds_t * thresholds)
return e;
}
memcpy (thresholds, args + 4, 512);
#endif /* __linux__ */
#ifdef __NetBSD__
struct atareq req;
unsigned char inbuf[DEV_BSIZE];
memset(&req, 0, sizeof(req));
req.timeout = 1000;
memset(&inbuf, 0, sizeof(inbuf));
req.flags = ATACMD_READ;
req.features = WDSM_RD_THRESHOLDS;
req.command = WDCC_SMART;
req.databuf = (char *)inbuf;
req.datalen = sizeof(inbuf);
req.cylinder = WDSMART_CYL;
if (ioctl(fd, ATAIOCCOMMAND, &req) == 0) {
if (req.retsts != ATACMD_OK)
errno = ENODEV;
}
if (errno != 0) {
int e = errno;
printf (_("CRITICAL - SMART_READ_THRESHOLDS: %s\n"), strerror (errno));
return e;
}
(void)memcpy(thresholds, inbuf, 512);
#endif /* __NetBSD__ */
return 0;
}

View file

@ -99,7 +99,7 @@ main (int argc, char *argv[])
textdomain (PACKAGE);
if (strstr(argv[0],"check_ldaps")) {
asprintf (&progname, "check_ldaps");
xasprintf (&progname, "check_ldaps");
}
/* Parse extra opts if any */
@ -145,7 +145,7 @@ main (int argc, char *argv[])
#endif
if (ld_port == LDAPS_PORT || ssl_on_connect) {
asprintf (&SERVICE, "LDAPS");
xasprintf (&SERVICE, "LDAPS");
#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_X_TLS)
/* ldaps: set option tls */
tls = LDAP_OPT_X_TLS_HARD;
@ -162,7 +162,7 @@ main (int argc, char *argv[])
return STATE_CRITICAL;
#endif /* LDAP_OPT_X_TLS */
} else if (starttls) {
asprintf (&SERVICE, "LDAP-TLS");
xasprintf (&SERVICE, "LDAP-TLS");
#if defined(HAVE_LDAP_SET_OPTION) && defined(HAVE_LDAP_START_TLS_S)
/* ldap with startTLS: set option version */
if (ldap_get_option(ld,LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS )
@ -389,7 +389,7 @@ void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", DEFAULT_PORT);
xasprintf (&myport, "%d", DEFAULT_PORT);
print_revision (progname, NP_VERSION);
@ -445,11 +445,6 @@ print_help (void)
printf (UT_SUPPORT);
}
/* todo
* add option -4 and -6 to the long manual
*
*/
void
print_usage (void)
{

View file

@ -186,7 +186,7 @@ main (int argc, char **argv)
/* we got this far, so assume OK until we've measured */
result = STATE_OK;
asprintf(&status_line, _("load average: %.2f, %.2f, %.2f"), la1, la5, la15);
xasprintf(&status_line, _("load average: %.2f, %.2f, %.2f"), la1, la5, la15);
for(i = 0; i < 3; i++) {
if(la[i] > cload[i]) {

View file

@ -191,7 +191,7 @@ main (int argc, char **argv)
result = STATE_WARNING;
}
asprintf (&error_message, _("%s. In = %0.1f %s, %s. Out = %0.1f %s|%s %s\n"),
xasprintf (&error_message, _("%s. In = %0.1f %s, %s. Out = %0.1f %s|%s %s\n"),
(use_average == TRUE) ? _("Avg") : _("Max"), adjusted_incoming_rate,
incoming_speed_rating, (use_average == TRUE) ? _("Avg") : _("Max"),
adjusted_outgoing_rate, outgoing_speed_rating,

View file

@ -5,7 +5,7 @@
* License: GPL
* Copyright (c) 1999 Didi Rieder (adrieder@sbox.tu-graz.ac.at)
* Copyright (c) 2000 Karl DeBisschop (kdebisschop@users.sourceforge.net)
* Copyright (c) 1999-2009 Nagios Plugins Development Team
* Copyright (c) 1999-2011 Nagios Plugins Development Team
*
* Description:
*
@ -31,7 +31,7 @@
*****************************************************************************/
const char *progname = "check_mysql";
const char *copyright = "1999-2007";
const char *copyright = "1999-2011";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#define SLAVERESULTSIZE 70
@ -49,10 +49,44 @@ char *db_host = NULL;
char *db_socket = NULL;
char *db_pass = NULL;
char *db = NULL;
char *ca_cert = NULL;
char *ca_dir = NULL;
char *cert = NULL;
char *key = NULL;
char *ciphers = NULL;
bool ssl = false;
char *opt_file = NULL;
char *opt_group = NULL;
unsigned int db_port = MYSQL_PORT;
int check_slave = 0, warn_sec = 0, crit_sec = 0;
int verbose = 0;
static double warning_time = 0;
static double critical_time = 0;
#define LENGTH_METRIC_UNIT 6
static const char *metric_unit[LENGTH_METRIC_UNIT] = {
"Open_files",
"Open_tables",
"Qcache_free_memory",
"Qcache_queries_in_cache",
"Threads_connected",
"Threads_running"
};
#define LENGTH_METRIC_COUNTER 9
static const char *metric_counter[LENGTH_METRIC_COUNTER] = {
"Connections",
"Qcache_hits",
"Qcache_inserts",
"Qcache_lowmem_prunes",
"Qcache_not_cached",
"Queries",
"Questions",
"Table_locks_waited",
"Uptime"
};
thresholds *my_threshold = NULL;
int process_arguments (int, char **);
@ -73,6 +107,9 @@ main (int argc, char **argv)
char *result = NULL;
char *error = NULL;
char slaveresult[SLAVERESULTSIZE];
char* perf;
perf = strdup ("");
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
@ -86,9 +123,17 @@ main (int argc, char **argv)
/* initialize mysql */
mysql_init (&mysql);
if (opt_file != NULL)
mysql_options(&mysql,MYSQL_READ_DEFAULT_FILE,opt_file);
mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"client");
if (opt_group != NULL)
mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,opt_group);
else
mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"client");
if (ssl)
mysql_ssl_set(&mysql,key,cert,ca_cert,ca_dir,ciphers);
/* establish a connection to the server and error checking */
if (!mysql_real_connect(&mysql,db_host,db_user,db_pass,db,db_port,db_socket,0)) {
if (mysql_errno (&mysql) == CR_UNKNOWN_HOST)
@ -118,6 +163,37 @@ main (int argc, char **argv)
die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
}
/* try to fetch some perf data */
if (mysql_query (&mysql, "show global status") == 0) {
if ( (res = mysql_store_result (&mysql)) == NULL) {
error = strdup(mysql_error(&mysql));
mysql_close (&mysql);
die (STATE_CRITICAL, _("status store_result error: %s\n"), error);
}
while ( (row = mysql_fetch_row (res)) != NULL) {
int i;
for(i = 0; i < LENGTH_METRIC_UNIT; i++) {
if (strcmp(row[0], metric_unit[i]) == 0) {
xasprintf(&perf, "%s%s ", perf, perfdata(metric_unit[i],
atol(row[1]), "", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0));
continue;
}
}
for(i = 0; i < LENGTH_METRIC_COUNTER; i++) {
if (strcmp(row[0], metric_counter[i]) == 0) {
xasprintf(&perf, "%s%s ", perf, perfdata(metric_counter[i],
atol(row[1]), "c", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0));
continue;
}
}
}
/* remove trailing space */
if (strlen(perf) > 0)
perf[strlen(perf) - 1] = '\0';
}
if(check_slave) {
/* check the slave status */
if (mysql_query (&mysql, "show slave status") != 0) {
@ -157,7 +233,7 @@ main (int argc, char **argv)
}
} else {
/* mysql 4.x.x */
/* mysql 4.x.x and mysql 5.x.x */
int slave_io_field = -1 , slave_sql_field = -1, seconds_behind_field = -1, i, num_fields;
MYSQL_FIELD* fields;
@ -178,13 +254,17 @@ main (int argc, char **argv)
}
}
/* Check if slave status is available */
if ((slave_io_field < 0) || (slave_sql_field < 0) || (num_fields == 0)) {
mysql_free_result (res);
mysql_close (&mysql);
die (STATE_CRITICAL, "Slave status unavailable\n");
}
/* Save slave status in slaveresult */
snprintf (slaveresult, SLAVERESULTSIZE, "Slave IO: %s Slave SQL: %s Seconds Behind Master: %s", row[slave_io_field], row[slave_sql_field], seconds_behind_field!=-1?row[seconds_behind_field]:"Unknown");
/* Raise critical error if SQL THREAD or IO THREAD are stopped */
if (strcmp (row[slave_io_field], "Yes") != 0 || strcmp (row[slave_sql_field], "Yes") != 0) {
mysql_free_result (res);
mysql_close (&mysql);
@ -199,17 +279,24 @@ main (int argc, char **argv)
}
}
/* Check Seconds Behind against threshold */
if ((seconds_behind_field != -1) && (strcmp (row[seconds_behind_field], "NULL") != 0)) {
double value = atof(row[seconds_behind_field]);
int status;
status = get_status(value, my_threshold);
xasprintf (&perf, "%s %s", perf, fperfdata ("seconds behind master", value, "s",
TRUE, (double) warning_time,
TRUE, (double) critical_time,
FALSE, 0,
FALSE, 0));
if (status == STATE_WARNING) {
printf("SLOW_SLAVE %s: %s\n", _("WARNING"), slaveresult);
printf("SLOW_SLAVE %s: %s|%s\n", _("WARNING"), slaveresult, perf);
exit(STATE_WARNING);
} else if (status == STATE_CRITICAL) {
printf("SLOW_SLAVE %s: %s\n", _("CRITICAL"), slaveresult);
printf("SLOW_SLAVE %s: %s|%s\n", _("CRITICAL"), slaveresult, perf);
exit(STATE_CRITICAL);
}
}
@ -224,9 +311,9 @@ main (int argc, char **argv)
/* print out the result of stats */
if (check_slave) {
printf ("%s %s\n", result, slaveresult);
printf ("%s %s|%s\n", result, slaveresult, perf);
} else {
printf ("%s\n", result);
printf ("%s|%s\n", result, perf);
}
return STATE_OK;
@ -248,6 +335,8 @@ process_arguments (int argc, char **argv)
{"database", required_argument, 0, 'd'},
{"username", required_argument, 0, 'u'},
{"password", required_argument, 0, 'p'},
{"file", required_argument, 0, 'f'},
{"group", required_argument, 0, 'g'},
{"port", required_argument, 0, 'P'},
{"critical", required_argument, 0, 'c'},
{"warning", required_argument, 0, 'w'},
@ -255,6 +344,12 @@ process_arguments (int argc, char **argv)
{"verbose", no_argument, 0, 'v'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{"ssl", no_argument, 0, 'l'},
{"ca-cert", optional_argument, 0, 'C'},
{"key", required_argument,0,'k'},
{"cert", required_argument,0,'a'},
{"ca-dir", required_argument, 0, 'D'},
{"ciphers", required_argument, 0, 'L'},
{0, 0, 0, 0}
};
@ -262,7 +357,7 @@ process_arguments (int argc, char **argv)
return ERROR;
while (1) {
c = getopt_long (argc, argv, "hvVSP:p:u:d:H:s:c:w:", longopts, &option);
c = getopt_long (argc, argv, "hlvVSP:p:u:d:H:s:c:w:a:k:C:D:L:f:g:", longopts, &option);
if (c == -1 || c == EOF)
break;
@ -282,6 +377,24 @@ process_arguments (int argc, char **argv)
case 'd': /* database */
db = optarg;
break;
case 'l':
ssl = true;
break;
case 'C':
ca_cert = optarg;
break;
case 'a':
cert = optarg;
break;
case 'k':
key = optarg;
break;
case 'D':
ca_dir = optarg;
break;
case 'L':
ciphers = optarg;
break;
case 'u': /* username */
db_user = optarg;
break;
@ -294,6 +407,12 @@ process_arguments (int argc, char **argv)
optarg++;
}
break;
case 'f': /* client options file */
opt_file = optarg;
break;
case 'g': /* client options group */
opt_group = optarg;
break;
case 'P': /* critical time threshold */
db_port = atoi (optarg);
break;
@ -302,9 +421,11 @@ process_arguments (int argc, char **argv)
break;
case 'w':
warning = optarg;
warning_time = strtod (warning, NULL);
break;
case 'c':
critical = optarg;
critical_time = strtod (critical, NULL);
break;
case 'V': /* version */
print_revision (progname, NP_VERSION);
@ -355,6 +476,12 @@ validate_arguments (void)
if (db_user == NULL)
db_user = strdup("");
if (opt_file == NULL)
opt_file = strdup("");
if (opt_group == NULL)
opt_group = strdup("");
if (db_host == NULL)
db_host = strdup("");
@ -369,7 +496,7 @@ void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", MYSQL_PORT);
xasprintf (&myport, "%d", MYSQL_PORT);
print_revision (progname, NP_VERSION);
@ -390,6 +517,10 @@ print_help (void)
printf (" %s\n", "-d, --database=STRING");
printf (" %s\n", _("Check database with indicated name"));
printf (" %s\n", "-f, --file=STRING");
printf (" %s\n", _("Read from the specified client options file"));
printf (" %s\n", "-g, --group=STRING");
printf (" %s\n", _("Use a client options group"));
printf (" %s\n", "-u, --username=STRING");
printf (" %s\n", _("Connect using the indicated username"));
printf (" %s\n", "-p, --password=STRING");
@ -404,6 +535,19 @@ print_help (void)
printf (" %s\n", "-c, --critical");
printf (" %s\n", _("Exit with CRITICAL status if slave server is more then INTEGER seconds"));
printf (" %s\n", _("behind master"));
printf (" %s\n", "-l, --ssl");
printf (" %s\n", _("Use ssl encryptation"));
printf (" %s\n", "-C, --ca-cert=STRING");
printf (" %s\n", _("Path to CA signing the cert"));
printf (" %s\n", "-a, --cert=STRING");
printf (" %s\n", _("Path to SSL certificate"));
printf (" %s\n", "-k, --key=STRING");
printf (" %s\n", _("Path to private SSL key"));
printf (" %s\n", "-D, --ca-dir=STRING");
printf (" %s\n", _("Path to CA directory"));
printf (" %s\n", "-L, --ciphers=STRING");
printf (" %s\n", _("List of valid SSL ciphers"));
printf ("\n");
printf (" %s\n", _("There are no required arguments. By default, the local database is checked"));
@ -424,5 +568,6 @@ print_usage (void)
{
printf ("%s\n", _("Usage:"));
printf (" %s [-d database] [-H host] [-P port] [-s socket]\n",progname);
printf (" [-u user] [-p password] [-S]\n");
printf (" [-u user] [-p password] [-S] [-l] [-a cert] [-k key]\n");
printf (" [-C ca-cert] [-D ca-dir] [-L ciphers] [-f optfile] [-g group]\n");
}

View file

@ -233,7 +233,7 @@ process_arguments (int argc, char **argv)
print_help ();
exit (STATE_OK);
case 'q':
asprintf(&sql_query, "%s", optarg);
xasprintf(&sql_query, "%s", optarg);
break;
case 'w':
warning = optarg;
@ -277,7 +277,7 @@ void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", MYSQL_PORT);
xasprintf (&myport, "%d", MYSQL_PORT);
print_revision (progname, NP_VERSION);

View file

@ -137,7 +137,7 @@ main (int argc, char **argv)
chld_out.line[i][pos+1] = 0x0;
}
if ( cols >= expected_cols ) {
asprintf (&procargs, "%s", chld_out.line[i] + pos);
xasprintf (&procargs, "%s", chld_out.line[i] + pos);
strip (procargs);
/* Some ps return full pathname for command. This removes path */
@ -205,6 +205,7 @@ process_arguments (int argc, char **argv)
{"filename", required_argument, 0, 'F'},
{"expires", required_argument, 0, 'e'},
{"command", required_argument, 0, 'C'},
{"timeout", optional_argument, 0, 't'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
@ -226,7 +227,7 @@ process_arguments (int argc, char **argv)
}
while (1) {
c = getopt_long (argc, argv, "+hVvF:C:e:", longopts, &option);
c = getopt_long (argc, argv, "+hVvF:C:e:t:", longopts, &option);
if (c == -1 || c == EOF || c == 1)
break;
@ -251,6 +252,13 @@ process_arguments (int argc, char **argv)
die (STATE_UNKNOWN,
_("Expiration time must be an integer (seconds)\n"));
break;
case 't': /* timeout */
if (is_intnonneg (optarg))
timeout_interval = atoi (optarg);
else
die (STATE_UNKNOWN,
_("Timeout must be an integer (seconds)\n"));
break;
case 'v':
verbose++;
break;
@ -296,11 +304,13 @@ print_help (void)
printf (" %s\n", _("Minutes aging after which logfile is considered stale"));
printf (" %s\n", "-C, --command=STRING");
printf (" %s\n", _("Substring to search for in process arguments"));
printf (" %s\n", "-t, --timeout=INTEGER");
printf (" %s\n", _("Timeout for the plugin in seconds"));
printf (UT_VERBOSE);
printf ("\n");
printf ("%s\n", _("Examples:"));
printf (" %s\n", "check_nagios -e 5 -F /usr/local/nagios/var/status.log -C /usr/local/nagios/bin/nagios");
printf (" %s\n", "check_nagios -t 20 -e 5 -F /usr/local/nagios/var/status.log -C /usr/local/nagios/bin/nagios");
printf (UT_SUPPORT);
}
@ -311,5 +321,5 @@ void
print_usage (void)
{
printf ("%s\n", _("Usage:"));
printf ("%s -F <status log file> -e <expire_minutes> -C <process_string>\n", progname);
printf ("%s -F <status log file> -t <timeout_seconds> -e <expire_minutes> -C <process_string>\n", progname);
}

View file

@ -94,6 +94,7 @@ int main(int argc, char **argv){
char *description=NULL,*counter_unit = NULL;
char *minval = NULL, *maxval = NULL, *errcvt = NULL;
char *fds=NULL, *tds=NULL;
char *numstr;
double total_disk_space=0;
double free_disk_space=0;
@ -135,13 +136,13 @@ int main(int argc, char **argv){
case CHECK_CLIENTVERSION:
asprintf(&send_buffer, "%s&1", req_password);
xasprintf(&send_buffer, "%s&1", req_password);
fetch_data (server_address, server_port, send_buffer);
if (value_list != NULL && strcmp(recv_buffer, value_list) != 0) {
asprintf (&output_message, _("Wrong client version - running: %s, required: %s"), recv_buffer, value_list);
xasprintf (&output_message, _("Wrong client version - running: %s, required: %s"), recv_buffer, value_list);
return_code = STATE_WARNING;
} else {
asprintf (&output_message, "%s", recv_buffer);
xasprintf (&output_message, "%s", recv_buffer);
return_code = STATE_OK;
}
break;
@ -167,7 +168,7 @@ int main(int argc, char **argv){
lvalue_list[2+offset]<=(unsigned long)100) {
/* Send request and retrieve data */
asprintf(&send_buffer,"%s&2&%lu",req_password,lvalue_list[0+offset]);
xasprintf(&send_buffer,"%s&2&%lu",req_password,lvalue_list[0+offset]);
fetch_data (server_address, server_port, send_buffer);
utilization=strtoul(recv_buffer,NULL,10);
@ -178,11 +179,11 @@ int main(int argc, char **argv){
else if(utilization >= lvalue_list[1+offset] && return_code<STATE_WARNING)
return_code=STATE_WARNING;
asprintf(&output_message,_(" %lu%% (%lu min average)"), utilization, lvalue_list[0+offset]);
asprintf(&temp_string,"%s%s",temp_string,output_message);
asprintf(&perfdata,_(" '%lu min avg Load'=%lu%%;%lu;%lu;0;100"), lvalue_list[0+offset], utilization,
xasprintf(&output_message,_(" %lu%% (%lu min average)"), utilization, lvalue_list[0+offset]);
xasprintf(&temp_string,"%s%s",temp_string,output_message);
xasprintf(&perfdata,_(" '%lu min avg Load'=%lu%%;%lu;%lu;0;100"), lvalue_list[0+offset], utilization,
lvalue_list[1+offset], lvalue_list[2+offset]);
asprintf(&temp_string_perf,"%s%s",temp_string_perf,perfdata);
xasprintf(&temp_string_perf,"%s%s",temp_string_perf,perfdata);
offset+=3; /* move across the array */
}
@ -196,13 +197,13 @@ int main(int argc, char **argv){
case CHECK_UPTIME:
asprintf(&send_buffer, "%s&3", req_password);
xasprintf(&send_buffer, "%s&3", req_password);
fetch_data (server_address, server_port, send_buffer);
uptime=strtoul(recv_buffer,NULL,10);
updays = uptime / 86400;
uphours = (uptime % 86400) / 3600;
upminutes = ((uptime % 86400) % 3600) / 60;
asprintf(&output_message,_("System Uptime - %u day(s) %u hour(s) %u minute(s)"),updays,uphours, upminutes);
xasprintf(&output_message,_("System Uptime - %u day(s) %u hour(s) %u minute(s)"),updays,uphours, upminutes);
if (check_critical_value==TRUE && uptime <= critical_value)
return_code=STATE_CRITICAL;
else if (check_warning_value==TRUE && uptime <= warning_value)
@ -218,7 +219,7 @@ int main(int argc, char **argv){
else if (strlen(value_list)!=1)
output_message = strdup (_("wrong -l argument"));
else {
asprintf(&send_buffer,"%s&4&%s", req_password, value_list);
xasprintf(&send_buffer,"%s&4&%s", req_password, value_list);
fetch_data (server_address, server_port, send_buffer);
fds=strtok(recv_buffer,"&");
tds=strtok(NULL,"&");
@ -232,10 +233,10 @@ int main(int argc, char **argv){
warning_used_space = ((float)warning_value / 100) * total_disk_space;
critical_used_space = ((float)critical_value / 100) * total_disk_space;
asprintf(&temp_string,_("%s:\\ - total: %.2f Gb - used: %.2f Gb (%.0f%%) - free %.2f Gb (%.0f%%)"),
xasprintf(&temp_string,_("%s:\\ - total: %.2f Gb - used: %.2f Gb (%.0f%%) - free %.2f Gb (%.0f%%)"),
value_list, total_disk_space / 1073741824, (total_disk_space - free_disk_space) / 1073741824,
percent_used_space, free_disk_space / 1073741824, (free_disk_space / total_disk_space)*100);
asprintf(&temp_string_perf,_("'%s:\\ Used Space'=%.2fGb;%.2f;%.2f;0.00;%.2f"), value_list,
xasprintf(&temp_string_perf,_("'%s:\\ Used Space'=%.2fGb;%.2f;%.2f;0.00;%.2f"), value_list,
(total_disk_space - free_disk_space) / 1073741824, warning_used_space / 1073741824,
critical_used_space / 1073741824, total_disk_space / 1073741824);
@ -262,10 +263,13 @@ int main(int argc, char **argv){
output_message = strdup (_("No service/process specified"));
else {
preparelist(value_list); /* replace , between services with & to send the request */
asprintf(&send_buffer,"%s&%u&%s&%s", req_password,(vars_to_check==CHECK_SERVICESTATE)?5:6,
xasprintf(&send_buffer,"%s&%u&%s&%s", req_password,(vars_to_check==CHECK_SERVICESTATE)?5:6,
(show_all==TRUE) ? "ShowAll" : "ShowFail",value_list);
fetch_data (server_address, server_port, send_buffer);
return_code=atoi(strtok(recv_buffer,"&"));
numstr = strtok(recv_buffer,"&");
if (numstr == NULL)
die(STATE_UNKNOWN, _("could not fetch information from server\n"));
return_code=atoi(numstr);
temp_string=strtok(NULL,"&");
output_message = strdup (temp_string);
}
@ -273,20 +277,26 @@ int main(int argc, char **argv){
case CHECK_MEMUSE:
asprintf(&send_buffer,"%s&7", req_password);
xasprintf(&send_buffer,"%s&7", req_password);
fetch_data (server_address, server_port, send_buffer);
mem_commitLimit=atof(strtok(recv_buffer,"&"));
mem_commitByte=atof(strtok(NULL,"&"));
numstr = strtok(recv_buffer,"&");
if (numstr == NULL)
die(STATE_UNKNOWN, _("could not fetch information from server\n"));
mem_commitLimit=atof(numstr);
numstr = strtok(NULL,"&");
if (numstr == NULL)
die(STATE_UNKNOWN, _("could not fetch information from server\n"));
mem_commitByte=atof(numstr);
percent_used_space = (mem_commitByte / mem_commitLimit) * 100;
warning_used_space = ((float)warning_value / 100) * mem_commitLimit;
critical_used_space = ((float)critical_value / 100) * mem_commitLimit;
/* Divisor should be 1048567, not 3044515, as we are measuring "Commit Charge" here,
which equals RAM + Pagefiles. */
asprintf(&output_message,_("Memory usage: total:%.2f Mb - used: %.2f Mb (%.0f%%) - free: %.2f Mb (%.0f%%)"),
xasprintf(&output_message,_("Memory usage: total:%.2f Mb - used: %.2f Mb (%.0f%%) - free: %.2f Mb (%.0f%%)"),
mem_commitLimit / 1048567, mem_commitByte / 1048567, percent_used_space,
(mem_commitLimit - mem_commitByte) / 1048567, (mem_commitLimit - mem_commitByte) / mem_commitLimit * 100);
asprintf(&perfdata,_("'Memory usage'=%.2fMb;%.2f;%.2f;0.00;%.2f"), mem_commitByte / 1048567,
xasprintf(&perfdata,_("'Memory usage'=%.2fMb;%.2f;%.2f;0.00;%.2f"), mem_commitByte / 1048567,
warning_used_space / 1048567, critical_used_space / 1048567, mem_commitLimit / 1048567);
return_code=STATE_OK;
@ -331,12 +341,12 @@ int main(int argc, char **argv){
strtok (value_list, "&"); /* burn the first parameters */
description = strtok (NULL, "&");
counter_unit = strtok (NULL, "&");
asprintf (&send_buffer, "%s&8&%s", req_password, value_list);
xasprintf (&send_buffer, "%s&8&%s", req_password, value_list);
fetch_data (server_address, server_port, send_buffer);
counter_value = atof (recv_buffer);
if (description == NULL)
asprintf (&output_message, "%.f", counter_value);
xasprintf (&output_message, "%.f", counter_value);
else if (isPercent)
{
counter_unit = strdup ("%");
@ -371,13 +381,13 @@ int main(int argc, char **argv){
{
/* Let's format the output string, finally... */
if (strstr(description, "%") == NULL) {
asprintf (&output_message, "%s = %.2f %s", description, counter_value, counter_unit);
xasprintf (&output_message, "%s = %.2f %s", description, counter_value, counter_unit);
} else {
/* has formatting, will segv if wrong */
asprintf (&output_message, description, counter_value);
xasprintf (&output_message, description, counter_value);
}
asprintf (&output_message, "%s |", output_message);
asprintf (&output_message,"%s %s", output_message,
xasprintf (&output_message, "%s |", output_message);
xasprintf (&output_message,"%s %s", output_message,
fperfdata (description, counter_value,
counter_unit, 1, warning_value, 1, critical_value,
(!(isPercent) && (minval != NULL)), fminval,
@ -410,7 +420,7 @@ int main(int argc, char **argv){
output_message = strdup (_("No counter specified"));
else {
preparelist(value_list); /* replace , between services with & to send the request */
asprintf(&send_buffer,"%s&9&%s", req_password,value_list);
xasprintf(&send_buffer,"%s&9&%s", req_password,value_list);
fetch_data (server_address, server_port, send_buffer);
age_in_minutes = atoi(strtok(recv_buffer,"&"));
description = strtok(NULL,"&");
@ -439,13 +449,13 @@ int main(int argc, char **argv){
if (value_list==NULL)
output_message = strdup (_("No counter specified"));
else {
asprintf(&send_buffer,"%s&10&%s", req_password,value_list);
xasprintf(&send_buffer,"%s&10&%s", req_password,value_list);
fetch_data (server_address, server_port, send_buffer);
if (!strncmp(recv_buffer,"ERROR",5)) {
printf("NSClient - %s\n",recv_buffer);
exit(STATE_UNKNOWN);
}
asprintf(&output_message,"%s",recv_buffer);
xasprintf(&output_message,"%s",recv_buffer);
return_code=STATE_OK;
}
break;

View file

@ -398,7 +398,11 @@ double offset_request(const char *host, int *status){
die(STATE_UNKNOWN, "can not create new socket");
}
if(connect(socklist[i], ai_tmp->ai_addr, ai_tmp->ai_addrlen)){
die(STATE_UNKNOWN, "can't create socket connection");
/* don't die here, because it is enough if there is one server
answering in time. This also would break for dual ipv4/6 stacked
ntp servers when the client only supports on of them.
*/
DBG(printf("can't create socket connection on peer %i: %s\n", i, strerror(errno)));
} else {
ufds[i].fd=socklist[i];
ufds[i].events=POLLIN;
@ -800,28 +804,28 @@ int main(int argc, char *argv[]){
switch (result) {
case STATE_CRITICAL :
asprintf(&result_line, _("NTP CRITICAL:"));
xasprintf(&result_line, _("NTP CRITICAL:"));
break;
case STATE_WARNING :
asprintf(&result_line, _("NTP WARNING:"));
xasprintf(&result_line, _("NTP WARNING:"));
break;
case STATE_OK :
asprintf(&result_line, _("NTP OK:"));
xasprintf(&result_line, _("NTP OK:"));
break;
default :
asprintf(&result_line, _("NTP UNKNOWN:"));
xasprintf(&result_line, _("NTP UNKNOWN:"));
break;
}
if(offset_result == STATE_UNKNOWN){
asprintf(&result_line, "%s %s", result_line, _("Offset unknown"));
asprintf(&perfdata_line, "");
xasprintf(&result_line, "%s %s", result_line, _("Offset unknown"));
xasprintf(&perfdata_line, "");
} else {
asprintf(&result_line, "%s %s %.10g secs", result_line, _("Offset"), offset);
asprintf(&perfdata_line, "%s", perfd_offset(offset));
xasprintf(&result_line, "%s %s %.10g secs", result_line, _("Offset"), offset);
xasprintf(&perfdata_line, "%s", perfd_offset(offset));
}
if (do_jitter) {
asprintf(&result_line, "%s, jitter=%f", result_line, jitter);
asprintf(&perfdata_line, "%s %s", perfdata_line, perfd_jitter(jitter));
xasprintf(&result_line, "%s, jitter=%f", result_line, jitter);
xasprintf(&perfdata_line, "%s %s", perfdata_line, perfd_jitter(jitter));
}
printf("%s|%s\n", result_line, perfdata_line);
@ -845,6 +849,7 @@ void print_help(void){
printf (UT_HELP_VRSN);
printf (UT_EXTRA_OPTS);
printf (UT_HOST_PORT, 'p', "123");
printf (UT_IPv46);
printf (" %s\n", "-w, --warning=THRESHOLD");
printf (" %s\n", _("Offset to result in warning status (seconds)"));
printf (" %s\n", "-c, --critical=THRESHOLD");
@ -881,5 +886,5 @@ print_usage(void)
printf ("%s\n", _("WARNING: check_ntp is deprecated. Please use check_ntp_peer or"));
printf ("%s\n\n", _("check_ntp_time instead."));
printf ("%s\n", _("Usage:"));
printf(" %s -H <host> [-w <warn>] [-c <crit>] [-j <warn>] [-k <crit>] [-v verbose]\n", progname);
printf(" %s -H <host> [-w <warn>] [-c <crit>] [-j <warn>] [-k <crit>] [-4|-6] [-v verbose]\n", progname);
}

View file

@ -241,15 +241,19 @@ int ntp_request(const char *host, double *offset, int *offset_result, double *ji
DBG(printf("sending READSTAT request"));
write(conn, &req, SIZEOF_NTPCM(req));
DBG(print_ntp_control_message(&req));
/* Attempt to read the largest size packet possible */
req.count=htons(MAX_CM_SIZE);
DBG(printf("recieving READSTAT response"))
if(read(conn, &req, SIZEOF_NTPCM(req)) == -1)
die(STATE_CRITICAL, "NTP CRITICAL: No response from NTP server\n");
DBG(print_ntp_control_message(&req));
/* discard obviously invalid packets */
if (ntohs(req.count) > MAX_CM_SIZE)
die(STATE_CRITICAL, "NTP CRITICAL: Invalid packet received from NTP server\n");
do {
/* Attempt to read the largest size packet possible */
req.count=htons(MAX_CM_SIZE);
DBG(printf("recieving READSTAT response"))
if(read(conn, &req, SIZEOF_NTPCM(req)) == -1)
die(STATE_CRITICAL, "NTP CRITICAL: No response from NTP server\n");
DBG(print_ntp_control_message(&req));
/* discard obviously invalid packets */
if (ntohs(req.count) > MAX_CM_SIZE)
die(STATE_CRITICAL, "NTP CRITICAL: Invalid packet received from NTP server\n");
} while (!(req.op&OP_READSTAT && ntohs(req.seq) == 1));
if (LI(req.flags) == LI_ALARM) li_alarm = 1;
/* Each peer identifier is 4 bytes in the data section, which
* we represent as a ntp_assoc_status_pair datatype.
@ -295,7 +299,7 @@ int ntp_request(const char *host, double *offset, int *offset_result, double *ji
/* If there's no sync.peer, query all candidates and use the best one */
if (PEER_SEL(peers[i].status) >= min_peer_sel){
if(verbose) printf("Getting offset, jitter and stratum for peer %.2x\n", ntohs(peers[i].assoc));
asprintf(&data, "");
xasprintf(&data, "");
do{
setup_control_request(&req, OP_READVAR, 2);
req.assoc = peers[i].assoc;
@ -312,13 +316,15 @@ int ntp_request(const char *host, double *offset, int *offset_result, double *ji
write(conn, &req, SIZEOF_NTPCM(req));
DBG(print_ntp_control_message(&req));
req.count = htons(MAX_CM_SIZE);
DBG(printf("receiving READVAR response...\n"));
read(conn, &req, SIZEOF_NTPCM(req));
DBG(print_ntp_control_message(&req));
do {
req.count = htons(MAX_CM_SIZE);
DBG(printf("receiving READVAR response...\n"));
read(conn, &req, SIZEOF_NTPCM(req));
DBG(print_ntp_control_message(&req));
} while (!(req.op&OP_READVAR && ntohs(req.seq) == 2));
if(!(req.op&REM_ERROR))
asprintf(&data, "%s%s", data, req.data);
xasprintf(&data, "%s%s", data, req.data);
} while(req.op&REM_MORE);
if(req.op&REM_ERROR) {
@ -603,41 +609,41 @@ int main(int argc, char *argv[]){
switch (result) {
case STATE_CRITICAL :
asprintf(&result_line, _("NTP CRITICAL:"));
xasprintf(&result_line, _("NTP CRITICAL:"));
break;
case STATE_WARNING :
asprintf(&result_line, _("NTP WARNING:"));
xasprintf(&result_line, _("NTP WARNING:"));
break;
case STATE_OK :
asprintf(&result_line, _("NTP OK:"));
xasprintf(&result_line, _("NTP OK:"));
break;
default :
asprintf(&result_line, _("NTP UNKNOWN:"));
xasprintf(&result_line, _("NTP UNKNOWN:"));
break;
}
if(!syncsource_found)
asprintf(&result_line, "%s %s,", result_line, _("Server not synchronized"));
xasprintf(&result_line, "%s %s,", result_line, _("Server not synchronized"));
else if(li_alarm)
asprintf(&result_line, "%s %s,", result_line, _("Server has the LI_ALARM bit set"));
xasprintf(&result_line, "%s %s,", result_line, _("Server has the LI_ALARM bit set"));
if(offset_result == STATE_UNKNOWN){
asprintf(&result_line, "%s %s", result_line, _("Offset unknown"));
asprintf(&perfdata_line, "");
xasprintf(&result_line, "%s %s", result_line, _("Offset unknown"));
xasprintf(&perfdata_line, "");
} else {
asprintf(&result_line, "%s %s %.10g secs", result_line, _("Offset"), offset);
asprintf(&perfdata_line, "%s", perfd_offset(offset));
xasprintf(&result_line, "%s %s %.10g secs", result_line, _("Offset"), offset);
xasprintf(&perfdata_line, "%s", perfd_offset(offset));
}
if (do_jitter) {
asprintf(&result_line, "%s, jitter=%f", result_line, jitter);
asprintf(&perfdata_line, "%s %s", perfdata_line, perfd_jitter(jitter));
xasprintf(&result_line, "%s, jitter=%f", result_line, jitter);
xasprintf(&perfdata_line, "%s %s", perfdata_line, perfd_jitter(jitter));
}
if (do_stratum) {
asprintf(&result_line, "%s, stratum=%i", result_line, stratum);
asprintf(&perfdata_line, "%s %s", perfdata_line, perfd_stratum(stratum));
xasprintf(&result_line, "%s, stratum=%i", result_line, stratum);
xasprintf(&perfdata_line, "%s %s", perfdata_line, perfd_stratum(stratum));
}
if (do_truechimers) {
asprintf(&result_line, "%s, truechimers=%i", result_line, num_truechimers);
asprintf(&perfdata_line, "%s %s", perfdata_line, perfd_truechimers(num_truechimers));
xasprintf(&result_line, "%s, truechimers=%i", result_line, num_truechimers);
xasprintf(&perfdata_line, "%s %s", perfdata_line, perfd_truechimers(num_truechimers));
}
printf("%s|%s\n", result_line, perfdata_line);
@ -660,6 +666,7 @@ void print_help(void){
print_usage();
printf (UT_HELP_VRSN);
printf (UT_EXTRA_OPTS);
printf (UT_IPv46);
printf (UT_HOST_PORT, 'p', "123");
printf (" %s\n", "-q, --quiet");
printf (" %s\n", _("Returns UNKNOWN instead of CRITICAL or WARNING if server isn't synchronized"));
@ -668,9 +675,9 @@ void print_help(void){
printf (" %s\n", "-c, --critical=THRESHOLD");
printf (" %s\n", _("Offset to result in critical status (seconds)"));
printf (" %s\n", "-W, --swarn=THRESHOLD");
printf (" %s\n", _("Warning threshold for stratum"));
printf (" %s\n", _("Warning threshold for stratum of server's synchronization peer"));
printf (" %s\n", "-C, --scrit=THRESHOLD");
printf (" %s\n", _("Critical threshold for stratum"));
printf (" %s\n", _("Critical threshold for stratum of server's synchronization peer"));
printf (" %s\n", "-j, --jwarn=THRESHOLD");
printf (" %s\n", _("Warning threshold for jitter"));
printf (" %s\n", "-k, --jcrit=THRESHOLD");
@ -704,7 +711,7 @@ void print_help(void){
printf(" %s\n", ("./check_ntp_peer -H ntpserv -w 0.5 -c 1 -j -1:100 -k -1:200"));
printf("\n");
printf(" %s\n", _("Only check the number of usable time sources (\"truechimers\"):"));
printf(" %s\n", ("./check_ntp_peer -H ntpserv -m :5 -n :3"));
printf(" %s\n", ("./check_ntp_peer -H ntpserv -m @5 -n @3"));
printf("\n");
printf(" %s\n", _("Check only stratum:"));
printf(" %s\n", ("./check_ntp_peer -H ntpserv -W 4 -C 6"));
@ -716,6 +723,6 @@ void
print_usage(void)
{
printf ("%s\n", _("Usage:"));
printf(" %s -H <host> [-w <warn>] [-c <crit>] [-W <warn>] [-C <crit>]\n", progname);
printf(" %s -H <host> [-4|-6] [-w <warn>] [-c <crit>] [-W <warn>] [-C <crit>]\n", progname);
printf(" [-j <warn>] [-k <crit>] [-v verbose]\n");
}

View file

@ -344,7 +344,11 @@ double offset_request(const char *host, int *status){
die(STATE_UNKNOWN, "can not create new socket");
}
if(connect(socklist[i], ai_tmp->ai_addr, ai_tmp->ai_addrlen)){
die(STATE_UNKNOWN, "can't create socket connection");
/* don't die here, because it is enough if there is one server
answering in time. This also would break for dual ipv4/6 stacked
ntp servers when the client only supports on of them.
*/
DBG(printf("can't create socket connection on peer %i: %s\n", i, strerror(errno)));
} else {
ufds[i].fd=socklist[i];
ufds[i].events=POLLIN;
@ -564,24 +568,24 @@ int main(int argc, char *argv[]){
switch (result) {
case STATE_CRITICAL :
asprintf(&result_line, _("NTP CRITICAL:"));
xasprintf(&result_line, _("NTP CRITICAL:"));
break;
case STATE_WARNING :
asprintf(&result_line, _("NTP WARNING:"));
xasprintf(&result_line, _("NTP WARNING:"));
break;
case STATE_OK :
asprintf(&result_line, _("NTP OK:"));
xasprintf(&result_line, _("NTP OK:"));
break;
default :
asprintf(&result_line, _("NTP UNKNOWN:"));
xasprintf(&result_line, _("NTP UNKNOWN:"));
break;
}
if(offset_result == STATE_UNKNOWN){
asprintf(&result_line, "%s %s", result_line, _("Offset unknown"));
asprintf(&perfdata_line, "");
xasprintf(&result_line, "%s %s", result_line, _("Offset unknown"));
xasprintf(&perfdata_line, "");
} else {
asprintf(&result_line, "%s %s %.10g secs", result_line, _("Offset"), offset);
asprintf(&perfdata_line, "%s", perfd_offset(offset));
xasprintf(&result_line, "%s %s %.10g secs", result_line, _("Offset"), offset);
xasprintf(&perfdata_line, "%s", perfd_offset(offset));
}
printf("%s|%s\n", result_line, perfdata_line);
@ -602,6 +606,7 @@ void print_help(void){
print_usage();
printf (UT_HELP_VRSN);
printf (UT_EXTRA_OPTS);
printf (UT_IPv46);
printf (UT_HOST_PORT, 'p', "123");
printf (" %s\n", "-q, --quiet");
printf (" %s\n", _("Returns UNKNOWN instead of CRITICAL if offset cannot be found"));
@ -635,6 +640,6 @@ void
print_usage(void)
{
printf ("%s\n", _("Usage:"));
printf(" %s -H <host> [-w <warn>] [-c <crit>] [-v verbose]\n", progname);
printf(" %s -H <host> [-4|-6] [-w <warn>] [-c <crit>] [-v verbose]\n", progname);
}

View file

@ -191,7 +191,7 @@ main(int argc, char **argv) {
netware_version = strdup("");
else {
recv_buffer[strlen(recv_buffer)-1]=0;
asprintf (&netware_version,_("NetWare %s: "),recv_buffer);
xasprintf (&netware_version,_("NetWare %s: "),recv_buffer);
}
} else
netware_version = strdup("");
@ -215,7 +215,7 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"UTIL%s\r\n",temp_buffer);
xasprintf (&send_buffer,"UTIL%s\r\n",temp_buffer);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
@ -236,7 +236,7 @@ main(int argc, char **argv) {
else if (check_warning_value==TRUE && utilization >= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("Load %s - %s %s-min load average = %lu%%|load%s=%lu;%lu;%lu;0;100"),
state_text(result),
uptime,
@ -264,7 +264,7 @@ main(int argc, char **argv) {
else if (check_warning_value==TRUE && current_connections >= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("Conns %s - %lu current connections|Conns=%lu;%lu;%lu;;"),
state_text(result),
current_connections,
@ -289,7 +289,7 @@ main(int argc, char **argv) {
else if (check_warning_value==TRUE && cache_hits <= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%s: Long term cache hits = %lu%%"),
state_text(result),
cache_hits);
@ -311,7 +311,7 @@ main(int argc, char **argv) {
else if (check_warning_value==TRUE && cache_buffers <= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%s: Total cache buffers = %lu|Cachebuffers=%lu;%lu;%lu;;"),
state_text(result),
cache_buffers,
@ -336,7 +336,7 @@ main(int argc, char **argv) {
else if (check_warning_value==TRUE && cache_buffers >= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%s: Dirty cache buffers = %lu|Dirty-Cache-Buffers=%lu;%lu;%lu;;"),
state_text(result),
cache_buffers,
@ -361,7 +361,7 @@ main(int argc, char **argv) {
else if (check_warning_value==TRUE && lru_time <= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%s: LRU sitting time = %lu minutes"),
state_text(result),
lru_time);
@ -373,13 +373,13 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"VKF%s\r\n",volume_name);
xasprintf (&send_buffer,"VKF%s\r\n",volume_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
result=STATE_CRITICAL;
} else {
free_disk_space=strtoul(recv_buffer,NULL,10);
@ -387,7 +387,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && free_disk_space <= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%s%lu KB free on volume %s|KBFree%s=%lu;%lu;%lu;;"),
(result==STATE_OK)?"":_("Only "),
free_disk_space,
@ -401,13 +401,13 @@ main(int argc, char **argv) {
/* check MB free space on volume */
} else if (vars_to_check==VMF) {
asprintf (&send_buffer,"VMF%s\r\n",volume_name);
xasprintf (&send_buffer,"VMF%s\r\n",volume_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
result=STATE_CRITICAL;
} else {
free_disk_space=strtoul(recv_buffer,NULL,10);
@ -415,7 +415,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && free_disk_space <= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%s%lu MB free on volume %s|MBFree%s=%lu;%lu;%lu;;"),
(result==STATE_OK)?"":_("Only "),
free_disk_space,
@ -428,13 +428,13 @@ main(int argc, char **argv) {
/* check MB used space on volume */
} else if (vars_to_check==VMU) {
asprintf (&send_buffer,"VMU%s\r\n",volume_name);
xasprintf (&send_buffer,"VMU%s\r\n",volume_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
result=STATE_CRITICAL;
} else {
free_disk_space=strtoul(recv_buffer,NULL,10);
@ -442,7 +442,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && free_disk_space <= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%s%lu MB used on volume %s|MBUsed%s=%lu;%lu;%lu;;"),
(result==STATE_OK)?"":_("Only "),
free_disk_space,
@ -460,14 +460,14 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"VKF%s\r\n",volume_name);
xasprintf (&send_buffer,"VKF%s\r\n",volume_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
result=STATE_CRITICAL;
} else {
@ -477,7 +477,7 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"VKS%s\r\n",volume_name);
xasprintf (&send_buffer,"VKS%s\r\n",volume_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
@ -491,7 +491,7 @@ main(int argc, char **argv) {
result=STATE_WARNING;
free_disk_space/=1024;
total_disk_space/=1024;
asprintf (&output_message,_("%lu MB (%lu%%) free on volume %s - total %lu MB|FreeMB%s=%lu;%lu;%lu;0;100"),
xasprintf (&output_message,_("%lu MB (%lu%%) free on volume %s - total %lu MB|FreeMB%s=%lu;%lu;%lu;0;100"),
free_disk_space,
percent_free_space,
volume_name,
@ -525,7 +525,7 @@ main(int argc, char **argv) {
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
temp_buffer=strtok(recv_buffer,"\r\n");
asprintf (&output_message,_("Directory Services Database is %s (DS version %s)"),(result==STATE_OK)?"open":"closed",temp_buffer);
xasprintf (&output_message,_("Directory Services Database is %s (DS version %s)"),(result==STATE_OK)?"open":"closed",temp_buffer);
/* check to see if logins are enabled */
} else if (vars_to_check==LOGINS) {
@ -542,13 +542,13 @@ main(int argc, char **argv) {
else
result=STATE_WARNING;
asprintf (&output_message,_("Logins are %s"),(result==STATE_OK)?_("enabled"):_("disabled"));
xasprintf (&output_message,_("Logins are %s"),(result==STATE_OK)?_("enabled"):_("disabled"));
/* check NRM Health Status Summary*/
} else if (vars_to_check==NRMH) {
asprintf (&send_buffer,"NRMH\r\n");
xasprintf (&send_buffer,"NRMH\r\n");
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
@ -557,15 +557,15 @@ main(int argc, char **argv) {
if (nrm_health_status==2) {
result=STATE_OK;
asprintf (&output_message,_("CRITICAL - NRM Status is bad!"));
xasprintf (&output_message,_("CRITICAL - NRM Status is bad!"));
}
else {
if (nrm_health_status==1) {
result=STATE_WARNING;
asprintf (&output_message,_("Warning - NRM Status is suspect!"));
xasprintf (&output_message,_("Warning - NRM Status is suspect!"));
}
asprintf (&output_message,_("OK - NRM Status is good!"));
xasprintf (&output_message,_("OK - NRM Status is good!"));
}
@ -576,7 +576,7 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"S15\r\n");
xasprintf (&send_buffer,"S15\r\n");
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
@ -586,7 +586,7 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"S16\r\n");
xasprintf (&send_buffer,"S16\r\n");
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
@ -607,7 +607,7 @@ main(int argc, char **argv) {
result=STATE_WARNING;
}
asprintf (&output_message,_("%lu of %lu (%lu%%) packet receive buffers used"),used_packet_receive_buffers,max_packet_receive_buffers,percent_used_packet_receive_buffers);
xasprintf (&output_message,_("%lu of %lu (%lu%%) packet receive buffers used"),used_packet_receive_buffers,max_packet_receive_buffers,percent_used_packet_receive_buffers);
/* check SAP table entries */
} else if (vars_to_check==SAPENTRIES) {
@ -616,9 +616,9 @@ main(int argc, char **argv) {
my_tcp_connect (server_address, server_port, &sd);
if (sap_number==-1)
asprintf (&send_buffer,"S9\r\n");
xasprintf (&send_buffer,"S9\r\n");
else
asprintf (&send_buffer,"S9.%d\r\n",sap_number);
xasprintf (&send_buffer,"S9.%d\r\n",sap_number);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
@ -631,9 +631,9 @@ main(int argc, char **argv) {
result=STATE_WARNING;
if (sap_number==-1)
asprintf (&output_message,_("%lu entries in SAP table"),sap_entries);
xasprintf (&output_message,_("%lu entries in SAP table"),sap_entries);
else
asprintf (&output_message,_("%lu entries in SAP table for SAP type %d"),sap_entries,sap_number);
xasprintf (&output_message,_("%lu entries in SAP table for SAP type %d"),sap_entries,sap_number);
/* check KB purgeable space on volume */
} else if (vars_to_check==VKP) {
@ -641,13 +641,13 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"VKP%s\r\n",volume_name);
xasprintf (&send_buffer,"VKP%s\r\n",volume_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
result=STATE_CRITICAL;
} else {
purgeable_disk_space=strtoul(recv_buffer,NULL,10);
@ -655,7 +655,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && purgeable_disk_space >= warning_value)
result=STATE_WARNING;
asprintf (&output_message,_("%s%lu KB purgeable on volume %s|Purge%s=%lu;%lu;%lu;;"),
xasprintf (&output_message,_("%s%lu KB purgeable on volume %s|Purge%s=%lu;%lu;%lu;;"),
(result==STATE_OK)?"":_("Only "),
purgeable_disk_space,
volume_name,
@ -667,13 +667,13 @@ main(int argc, char **argv) {
/* check MB purgeable space on volume */
} else if (vars_to_check==VMP) {
asprintf (&send_buffer,"VMP%s\r\n",volume_name);
xasprintf (&send_buffer,"VMP%s\r\n",volume_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
result=STATE_CRITICAL;
} else {
purgeable_disk_space=strtoul(recv_buffer,NULL,10);
@ -681,7 +681,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && purgeable_disk_space >= warning_value)
result=STATE_WARNING;
asprintf (&output_message,_("%s%lu MB purgeable on volume %s|Purge%s=%lu;%lu;%lu;;"),
xasprintf (&output_message,_("%s%lu MB purgeable on volume %s|Purge%s=%lu;%lu;%lu;;"),
(result==STATE_OK)?"":_("Only "),
purgeable_disk_space,
volume_name,
@ -697,14 +697,14 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"VKP%s\r\n",volume_name);
xasprintf (&send_buffer,"VKP%s\r\n",volume_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
result=STATE_CRITICAL;
} else {
@ -714,7 +714,7 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"VKS%s\r\n",volume_name);
xasprintf (&send_buffer,"VKS%s\r\n",volume_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
@ -727,7 +727,7 @@ main(int argc, char **argv) {
else if (check_warning_value==TRUE && percent_purgeable_space >= warning_value)
result=STATE_WARNING;
purgeable_disk_space/=1024;
asprintf (&output_message,_("%lu MB (%lu%%) purgeable on volume %s|Purgeable%s=%lu;%lu;%lu;0;100"),
xasprintf (&output_message,_("%lu MB (%lu%%) purgeable on volume %s|Purgeable%s=%lu;%lu;%lu;0;100"),
purgeable_disk_space,
percent_purgeable_space,
volume_name,
@ -744,13 +744,13 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"VKNP%s\r\n",volume_name);
xasprintf (&send_buffer,"VKNP%s\r\n",volume_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
result=STATE_CRITICAL;
} else {
non_purgeable_disk_space=strtoul(recv_buffer,NULL,10);
@ -758,7 +758,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && non_purgeable_disk_space >= warning_value)
result=STATE_WARNING;
asprintf (&output_message,_("%s%lu KB not yet purgeable on volume %s"),(result==STATE_OK)?"":_("Only "),non_purgeable_disk_space,volume_name);
xasprintf (&output_message,_("%s%lu KB not yet purgeable on volume %s"),(result==STATE_OK)?"":_("Only "),non_purgeable_disk_space,volume_name);
}
/* check % not yet purgeable space on volume */
@ -767,14 +767,14 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"VKNP%s\r\n",volume_name);
xasprintf (&send_buffer,"VKNP%s\r\n",volume_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
xasprintf (&output_message,_("CRITICAL - Volume '%s' does not exist!"),volume_name);
result=STATE_CRITICAL;
} else {
@ -784,7 +784,7 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"VKS%s\r\n",volume_name);
xasprintf (&send_buffer,"VKS%s\r\n",volume_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
@ -797,7 +797,7 @@ main(int argc, char **argv) {
else if (check_warning_value==TRUE && percent_non_purgeable_space >= warning_value)
result=STATE_WARNING;
purgeable_disk_space/=1024;
asprintf (&output_message,_("%lu MB (%lu%%) not yet purgeable on volume %s"),non_purgeable_disk_space,percent_non_purgeable_space,volume_name);
xasprintf (&output_message,_("%lu MB (%lu%%) not yet purgeable on volume %s"),non_purgeable_disk_space,percent_non_purgeable_space,volume_name);
}
/* check # of open files */
@ -806,7 +806,7 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"S18\r\n");
xasprintf (&send_buffer,"S18\r\n");
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
@ -818,7 +818,7 @@ main(int argc, char **argv) {
else if (check_warning_value==TRUE && open_files >= warning_value)
result=STATE_WARNING;
asprintf (&output_message,_("%lu open files|Openfiles=%lu;%lu;%lu;0,0"),
xasprintf (&output_message,_("%lu open files|Openfiles=%lu;%lu;%lu;0,0"),
open_files,
open_files,
warning_value,
@ -831,7 +831,7 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"S17\r\n");
xasprintf (&send_buffer,"S17\r\n");
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
@ -843,7 +843,7 @@ main(int argc, char **argv) {
else if (check_warning_value==TRUE && abended_threads >= warning_value)
result=STATE_WARNING;
asprintf (&output_message,_("%lu abended threads|Abends=%lu;%lu;%lu;;"),
xasprintf (&output_message,_("%lu abended threads|Abends=%lu;%lu;%lu;;"),
abended_threads,
abended_threads,
warning_value,
@ -855,7 +855,7 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"S20\r\n");
xasprintf (&send_buffer,"S20\r\n");
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
@ -865,7 +865,7 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"S21\r\n");
xasprintf (&send_buffer,"S21\r\n");
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
@ -877,7 +877,7 @@ main(int argc, char **argv) {
else if (check_warning_value==TRUE && current_service_processes >= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%lu current service processes (%lu max)|Processes=%lu;%lu;%lu;0;%lu"),
current_service_processes,
max_service_processes,
@ -892,7 +892,7 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"S22\r\n");
xasprintf (&send_buffer,"S22\r\n");
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
@ -901,10 +901,10 @@ main(int argc, char **argv) {
if (time_sync_status==0) {
result=STATE_CRITICAL;
asprintf (&output_message,_("CRITICAL - Time not in sync with network!"));
xasprintf (&output_message,_("CRITICAL - Time not in sync with network!"));
}
else {
asprintf (&output_message,_("OK - Time in sync with network!"));
xasprintf (&output_message,_("OK - Time in sync with network!"));
}
@ -927,7 +927,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && lru_time <= warning_value)
result=STATE_WARNING;
asprintf (&output_message,_("LRU sitting time = %lu seconds"),lru_time);
xasprintf (&output_message,_("LRU sitting time = %lu seconds"),lru_time);
/* check % dirty cacheobuffers as a percentage of the total*/
@ -946,7 +946,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && dirty_cache_buffers <= warning_value)
result=STATE_WARNING;
asprintf (&output_message,_("Dirty cache buffers = %lu%% of the total|DCB=%lu;%lu;%lu;0;100"),
xasprintf (&output_message,_("Dirty cache buffers = %lu%% of the total|DCB=%lu;%lu;%lu;0;100"),
dirty_cache_buffers,
dirty_cache_buffers,
warning_value,
@ -968,7 +968,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && total_cache_buffers <= warning_value)
result=STATE_WARNING;
asprintf (&output_message,_("Total cache buffers = %lu%% of the original|TCB=%lu;%lu;%lu;0;100"),
xasprintf (&output_message,_("Total cache buffers = %lu%% of the original|TCB=%lu;%lu;%lu;0;100"),
total_cache_buffers,
total_cache_buffers,
warning_value,
@ -979,21 +979,21 @@ main(int argc, char **argv) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"S13\r\n");
xasprintf (&send_buffer,"S13\r\n");
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
recv_buffer[strlen(recv_buffer)-1]=0;
asprintf (&output_message,_("NDS Version %s"),recv_buffer);
xasprintf (&output_message,_("NDS Version %s"),recv_buffer);
} else if (vars_to_check==UPTIME) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"UPTIME\r\n");
xasprintf (&send_buffer,"UPTIME\r\n");
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
@ -1002,35 +1002,35 @@ main(int argc, char **argv) {
recv_buffer[sizeof(recv_buffer)-1]=0;
recv_buffer[strlen(recv_buffer)-1]=0;
asprintf (&output_message,_("Up %s"),recv_buffer);
xasprintf (&output_message,_("Up %s"),recv_buffer);
} else if (vars_to_check==NLM) {
close(sd);
my_tcp_connect (server_address, server_port, &sd);
asprintf (&send_buffer,"S24:%s\r\n",nlm_name);
xasprintf (&send_buffer,"S24:%s\r\n",nlm_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
recv_buffer[strlen(recv_buffer)-1]=0;
if (strcmp(recv_buffer,"-1")) {
asprintf (&output_message,_("Module %s version %s is loaded"),nlm_name,recv_buffer);
xasprintf (&output_message,_("Module %s version %s is loaded"),nlm_name,recv_buffer);
} else {
result=STATE_CRITICAL;
asprintf (&output_message,_("Module %s is not loaded"),nlm_name);
xasprintf (&output_message,_("Module %s is not loaded"),nlm_name);
}
} else if (vars_to_check==NRMP) {
asprintf (&send_buffer,"NRMP:%s\r\n",nrmp_name);
xasprintf (&send_buffer,"NRMP:%s\r\n",nrmp_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nrmp_name);
xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nrmp_name);
result=STATE_CRITICAL;
} else {
nrmp_value=strtoul(recv_buffer,NULL,10);
@ -1038,7 +1038,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && nrmp_value <= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%s is %lu|%s=%lu;%lu;%lu;;"),
nrmp_name,
nrmp_value,
@ -1050,13 +1050,13 @@ main(int argc, char **argv) {
} else if (vars_to_check==NRMM) {
asprintf (&send_buffer,"NRMM:%s\r\n",nrmm_name);
xasprintf (&send_buffer,"NRMM:%s\r\n",nrmm_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nrmm_name);
xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nrmm_name);
result=STATE_CRITICAL;
} else {
nrmm_value=strtoul(recv_buffer,NULL,10);
@ -1064,7 +1064,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && nrmm_value <= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%s is %lu|%s=%lu;%lu;%lu;;"),
nrmm_name,
nrmm_value,
@ -1076,13 +1076,13 @@ main(int argc, char **argv) {
} else if (vars_to_check==NRMS) {
asprintf (&send_buffer,"NRMS:%s\r\n",nrms_name);
xasprintf (&send_buffer,"NRMS:%s\r\n",nrms_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nrms_name);
xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nrms_name);
result=STATE_CRITICAL;
} else {
nrms_value=strtoul(recv_buffer,NULL,10);
@ -1090,7 +1090,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && nrms_value >= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%s is %lu|%s=%lu;%lu;%lu;;"),
nrms_name,
nrms_value,
@ -1102,13 +1102,13 @@ main(int argc, char **argv) {
} else if (vars_to_check==NSS1) {
asprintf (&send_buffer,"NSS1:%s\r\n",nss1_name);
xasprintf (&send_buffer,"NSS1:%s\r\n",nss1_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss1_name);
xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss1_name);
result=STATE_CRITICAL;
} else {
nss1_value=strtoul(recv_buffer,NULL,10);
@ -1116,7 +1116,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && nss1_value >= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%s is %lu|%s=%lu;%lu;%lu;;"),
nss1_name,
nss1_value,
@ -1128,13 +1128,13 @@ main(int argc, char **argv) {
} else if (vars_to_check==NSS2) {
asprintf (&send_buffer,"NSS2:%s\r\n",nss2_name);
xasprintf (&send_buffer,"NSS2:%s\r\n",nss2_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss2_name);
xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss2_name);
result=STATE_CRITICAL;
} else {
nss2_value=strtoul(recv_buffer,NULL,10);
@ -1142,7 +1142,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && nss2_value >= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%s is %lu|%s=%lu;%lu;%lu;;"),
nss2_name,
nss2_value,
@ -1154,13 +1154,13 @@ main(int argc, char **argv) {
} else if (vars_to_check==NSS3) {
asprintf (&send_buffer,"NSS3:%s\r\n",nss3_name);
xasprintf (&send_buffer,"NSS3:%s\r\n",nss3_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss3_name);
xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss3_name);
result=STATE_CRITICAL;
} else {
nss3_value=strtoul(recv_buffer,NULL,10);
@ -1168,7 +1168,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && nss3_value >= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%s is %lu|%s=%lu;%lu;%lu;;"),
nss3_name,
nss3_value,
@ -1180,13 +1180,13 @@ main(int argc, char **argv) {
} else if (vars_to_check==NSS4) {
asprintf (&send_buffer,"NSS4:%s\r\n",nss4_name);
xasprintf (&send_buffer,"NSS4:%s\r\n",nss4_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss4_name);
xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss4_name);
result=STATE_CRITICAL;
} else {
nss4_value=strtoul(recv_buffer,NULL,10);
@ -1194,7 +1194,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && nss4_value >= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%s is %lu|%s=%lu;%lu;%lu;;"),
nss4_name,
nss4_value,
@ -1206,13 +1206,13 @@ main(int argc, char **argv) {
} else if (vars_to_check==NSS5) {
asprintf (&send_buffer,"NSS5:%s\r\n",nss5_name);
xasprintf (&send_buffer,"NSS5:%s\r\n",nss5_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss5_name);
xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss5_name);
result=STATE_CRITICAL;
} else {
nss5_value=strtoul(recv_buffer,NULL,10);
@ -1220,7 +1220,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && nss5_value >= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%s is %lu|%s=%lu;%lu;%lu;;"),
nss5_name,
nss5_value,
@ -1232,13 +1232,13 @@ main(int argc, char **argv) {
} else if (vars_to_check==NSS6) {
asprintf (&send_buffer,"NSS6:%s\r\n",nss6_name);
xasprintf (&send_buffer,"NSS6:%s\r\n",nss6_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss6_name);
xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss6_name);
result=STATE_CRITICAL;
} else {
nss6_value=strtoul(recv_buffer,NULL,10);
@ -1246,7 +1246,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && nss6_value >= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%s is %lu|%s=%lu;%lu;%lu;;"),
nss6_name,
nss6_value,
@ -1258,13 +1258,13 @@ main(int argc, char **argv) {
} else if (vars_to_check==NSS7) {
asprintf (&send_buffer,"NSS7:%s\r\n",nss7_name);
xasprintf (&send_buffer,"NSS7:%s\r\n",nss7_name);
result=send_tcp_request(sd,send_buffer,recv_buffer,sizeof(recv_buffer));
if (result!=STATE_OK)
return result;
if (!strcmp(recv_buffer,"-1\n")) {
asprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss7_name);
xasprintf (&output_message,_("CRITICAL - Value '%s' does not exist!"),nss7_name);
result=STATE_CRITICAL;
} else {
nss7_value=strtoul(recv_buffer,NULL,10);
@ -1272,7 +1272,7 @@ main(int argc, char **argv) {
result=STATE_CRITICAL;
else if (check_warning_value==TRUE && nss7_value >= warning_value)
result=STATE_WARNING;
asprintf (&output_message,
xasprintf (&output_message,
_("%s is %lu|%s=%lu;%lu;%lu;;"),
nss7_name,
nss7_value,
@ -1591,7 +1591,7 @@ int process_arguments(int argc, char **argv) {
void print_help(void)
{
char *myport;
asprintf (&myport, "%d", PORT);
xasprintf (&myport, "%d", PORT);
print_revision (progname, NP_VERSION);

View file

@ -409,7 +409,7 @@ void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", PORT);
xasprintf (&myport, "%d", PORT);
print_revision (progname, NP_VERSION);

View file

@ -3,7 +3,7 @@
* Nagios check_pgsql plugin
*
* License: GPL
* Copyright (c) 1999-2007 Nagios Plugins Development Team
* Copyright (c) 1999-2011 Nagios Plugins Development Team
*
* Description:
*
@ -29,7 +29,7 @@
*****************************************************************************/
const char *progname = "check_pgsql";
const char *copyright = "1999-2007";
const char *copyright = "1999-2011";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
@ -42,6 +42,20 @@ const char *email = "nagiosplug-devel@lists.sourceforge.net";
#define DEFAULT_DB "template1"
#define DEFAULT_HOST "127.0.0.1"
/* return the PSQL server version as a 3-tuple */
#define PSQL_SERVER_VERSION3(server_version) \
(server_version) / 10000, \
(server_version) / 100 - (int)((server_version) / 10000) * 100, \
(server_version) - (int)((server_version) / 100) * 100
/* return true if the given host is a UNIX domain socket */
#define PSQL_IS_UNIX_DOMAIN_SOCKET(host) \
((NULL == (host)) || ('\0' == *(host)) || ('/' == *(host)))
/* return a 3-tuple identifying a host/port independent of the socket type */
#define PSQL_SOCKET3(host, port) \
((NULL == (host)) || ('\0' == *(host))) ? DEFAULT_PGSOCKET_DIR : host, \
PSQL_IS_UNIX_DOMAIN_SOCKET (host) ? "/.s.PGSQL." : ":", \
port
enum {
DEFAULT_PORT = 5432,
DEFAULT_WARN = 2,
@ -56,6 +70,7 @@ void print_usage (void);
void print_help (void);
int is_pg_dbname (char *);
int is_pg_logname (char *);
int do_query (PGconn *, char *);
char *pghost = NULL; /* host name of the backend server */
char *pgport = NULL; /* port of the backend server */
@ -65,14 +80,15 @@ char *pgtty = NULL;
char dbName[NAMEDATALEN] = DEFAULT_DB;
char *pguser = NULL;
char *pgpasswd = NULL;
char *pgparams = NULL;
double twarn = (double)DEFAULT_WARN;
double tcrit = (double)DEFAULT_CRIT;
char *pgquery = NULL;
char *query_warning = NULL;
char *query_critical = NULL;
thresholds *qthresholds = NULL;
int verbose = 0;
PGconn *conn;
/*PGresult *res;*/
/******************************************************************************
The (psuedo?)literate programming XML is contained within \@\@\- <XML> \-\@\@
@ -115,10 +131,6 @@ Please note that all tags must be lowercase to use the DocBook XML DTD.
<sect2>
<title>Future Enhancements</title>
<para>ToDo List</para>
<itemizedlist>
<listitem>Add option to get password from a secured file rather than the command line</listitem>
<listitem>Add option to specify the query to execute</listitem>
</itemizedlist>
</sect2>
@ -132,8 +144,14 @@ Please note that all tags must be lowercase to use the DocBook XML DTD.
int
main (int argc, char **argv)
{
int elapsed_time;
PGconn *conn;
char *conninfo = NULL;
struct timeval start_timeval;
struct timeval end_timeval;
double elapsed_time;
int status = STATE_UNKNOWN;
int query_status = STATE_UNKNOWN;
/* begin, by setting the parameters for a backend connection if the
* parameters are null, then the system will try to use reasonable
@ -161,20 +179,41 @@ main (int argc, char **argv)
}
alarm (timeout_interval);
if (verbose)
printf("Connecting to database:\n DB: %s\n User: %s\n Host: %s\n Port: %d\n", dbName,
(pguser != NULL) ? pguser : "unspecified",
(pghost != NULL) ? pghost : "unspecified",
(pgport != NULL) ? atoi(pgport) : DEFAULT_PORT);
if (pgparams)
asprintf (&conninfo, "%s ", pgparams);
asprintf (&conninfo, "%sdbname = '%s'", conninfo ? conninfo : "", dbName);
if (pghost)
asprintf (&conninfo, "%s host = '%s'", conninfo, pghost);
if (pgport)
asprintf (&conninfo, "%s port = '%s'", conninfo, pgport);
if (pgoptions)
asprintf (&conninfo, "%s options = '%s'", conninfo, pgoptions);
/* if (pgtty) -- ignored by PQconnectdb */
if (pguser)
asprintf (&conninfo, "%s user = '%s'", conninfo, pguser);
if (verbose) /* do not include password (see right below) in output */
printf ("Connecting to PostgreSQL using conninfo: %s%s\n", conninfo,
pgpasswd ? " password = <hidden>" : "");
if (pgpasswd)
asprintf (&conninfo, "%s password = '%s'", conninfo, pgpasswd);
/* make a connection to the database */
time (&start_time);
conn =
PQsetdbLogin (pghost, pgport, pgoptions, pgtty, dbName, pguser, pgpasswd);
time (&end_time);
elapsed_time = (int) (end_time - start_time);
gettimeofday (&start_timeval, NULL);
conn = PQconnectdb (conninfo);
gettimeofday (&end_timeval, NULL);
while (start_timeval.tv_usec > end_timeval.tv_usec) {
--end_timeval.tv_sec;
end_timeval.tv_usec += 1000000;
}
elapsed_time = (double)(end_timeval.tv_sec - start_timeval.tv_sec)
+ (double)(end_timeval.tv_usec - start_timeval.tv_usec) / 1000000.0;
if (verbose)
printf("Time elapsed: %d\n", elapsed_time);
printf("Time elapsed: %f\n", elapsed_time);
/* check to see that the backend connection was successfully made */
if (verbose)
@ -194,14 +233,32 @@ main (int argc, char **argv)
else {
status = STATE_OK;
}
if (verbose) {
char *server_host = PQhost (conn);
int server_version = PQserverVersion (conn);
printf ("Successfully connected to database %s (user %s) "
"at server %s%s%s (server version: %d.%d.%d, "
"protocol version: %d, pid: %d)\n",
PQdb (conn), PQuser (conn),
PSQL_SOCKET3 (server_host, PQport (conn)),
PSQL_SERVER_VERSION3 (server_version),
PQprotocolVersion (conn), PQbackendPID (conn));
}
printf (_(" %s - database %s (%f sec.)|%s\n"),
state_text(status), dbName, elapsed_time,
fperfdata("time", elapsed_time, "s",
!!(twarn > 0.0), twarn, !!(tcrit > 0.0), tcrit, TRUE, 0, FALSE,0));
if (pgquery)
query_status = do_query (conn, pgquery);
if (verbose)
printf("Closing connection\n");
PQfinish (conn);
printf (_(" %s - database %s (%d sec.)|%s\n"),
state_text(status), dbName, elapsed_time,
fperfdata("time", elapsed_time, "s",
(int)twarn, twarn, (int)tcrit, tcrit, TRUE, 0, FALSE,0));
return status;
return (query_status > status) ? query_status : status;
}
@ -225,12 +282,16 @@ process_arguments (int argc, char **argv)
{"authorization", required_argument, 0, 'a'},
{"port", required_argument, 0, 'P'},
{"database", required_argument, 0, 'd'},
{"option", required_argument, 0, 'o'},
{"query", required_argument, 0, 'q'},
{"query_critical", required_argument, 0, 'C'},
{"query_warning", required_argument, 0, 'W'},
{"verbose", no_argument, 0, 'v'},
{0, 0, 0, 0}
};
while (1) {
c = getopt_long (argc, argv, "hVt:c:w:H:P:d:l:p:a:v",
c = getopt_long (argc, argv, "hVt:c:w:H:P:d:l:p:a:o:q:C:W:v",
longopts, &option);
if (c == EOF)
@ -263,8 +324,14 @@ process_arguments (int argc, char **argv)
else
twarn = strtod (optarg, NULL);
break;
case 'C': /* critical query threshold */
query_critical = optarg;
break;
case 'W': /* warning query threshold */
query_warning = optarg;
break;
case 'H': /* host */
if (!is_host (optarg))
if ((*optarg != '/') && (!is_host (optarg)))
usage2 (_("Invalid hostname/address"), optarg);
else
pghost = optarg;
@ -291,12 +358,23 @@ process_arguments (int argc, char **argv)
case 'a':
pgpasswd = optarg;
break;
case 'o':
if (pgparams)
asprintf (&pgparams, "%s %s", pgparams, optarg);
else
asprintf (&pgparams, "%s", optarg);
break;
case 'q':
pgquery = optarg;
break;
case 'v':
verbose++;
break;
}
}
set_thresholds (&qthresholds, query_warning, query_critical);
return validate_arguments ();
}
@ -417,7 +495,7 @@ print_help (void)
{
char *myport;
asprintf (&myport, "%d", DEFAULT_PORT);
xasprintf (&myport, "%d", DEFAULT_PORT);
print_revision (progname, NP_VERSION);
@ -434,8 +512,6 @@ print_help (void)
printf (UT_HOST_PORT, 'P', myport);
printf (UT_IPv46);
printf (" %s\n", "-d, --database=STRING");
printf (" %s", _("Database to check "));
printf (_("(default: %s)"), DEFAULT_DB);
@ -443,11 +519,20 @@ print_help (void)
printf (" %s\n", _("Login name of user"));
printf (" %s\n", "-p, --password = STRING");
printf (" %s\n", _("Password (BIG SECURITY ISSUE)"));
printf (" %s\n", "-o, --option = STRING");
printf (" %s\n", _("Connection parameters (keyword = value), see below"));
printf (UT_WARN_CRIT);
printf (UT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
printf (" %s\n", "-q, --query=STRING");
printf (" %s\n", _("SQL query to run. Only first column in first row will be read"));
printf (" %s\n", "-W, --query-warning=RANGE");
printf (" %s\n", _("SQL query value to result in warning status (double)"));
printf (" %s\n", "-C, --query-critical=RANGE");
printf (" %s\n", _("SQL query value to result in critical status (double)"));
printf (UT_VERBOSE);
printf ("\n");
@ -458,6 +543,22 @@ print_help (void)
printf (" %s\n", _("connects to the template1 database, which is present in every functioning"));
printf (" %s\n\n", _("PostgreSQL DBMS."));
printf (" %s\n", _("If a query is specified using the -q option, it will be executed after"));
printf (" %s\n", _("connecting to the server. The result from the query has to be numeric."));
printf (" %s\n", _("Multiple SQL commands, separated by semicolon, are allowed but the result "));
printf (" %s\n", _("of the last command is taken into account only. The value of the first"));
printf (" %s\n\n", _("column in the first row is used as the check result."));
printf (" %s\n", _("See the chapter \"Monitoring Database Activity\" of the PostgreSQL manual"));
printf (" %s\n\n", _("for details about how to access internal statistics of the database server."));
printf (" %s\n", _("For a list of available connection parameters which may be used with the -o"));
printf (" %s\n", _("command line option, see the documentation for PQconnectdb() in the chapter"));
printf (" %s\n", _("\"libpq - C Library\" of the PostgreSQL manual. For example, this may be"));
printf (" %s\n", _("used to specify a service name in pg_service.conf to be used for additional"));
printf (" %s\n", _("connection parameters: -o 'service=<name>' or to specify the SSL mode:"));
printf (" %s\n\n", _("-o 'sslmode=require'."));
printf (" %s\n", _("The plugin will connect to a local postmaster if no host is specified. To"));
printf (" %s\n", _("connect to a remote host, be sure that the remote postmaster accepts TCP/IP"));
printf (" %s\n\n", _("connections (start the postmaster with the -i option)."));
@ -476,5 +577,74 @@ print_usage (void)
{
printf ("%s\n", _("Usage:"));
printf ("%s [-H <host>] [-P <port>] [-c <critical time>] [-w <warning time>]\n", progname);
printf (" [-t <timeout>] [-d <database>] [-l <logname>] [-p <password>]\n");
printf (" [-t <timeout>] [-d <database>] [-l <logname>] [-p <password>]\n"
"[-q <query>] [-C <critical query range>] [-W <warning query range>]\n");
}
int
do_query (PGconn *conn, char *query)
{
PGresult *res;
char *val_str;
double value;
char *endptr = NULL;
int my_status = STATE_UNKNOWN;
if (verbose)
printf ("Executing SQL query \"%s\".\n", query);
res = PQexec (conn, query);
if (PGRES_TUPLES_OK != PQresultStatus (res)) {
printf (_("QUERY %s - %s: %s.\n"), _("CRITICAL"), _("Error with query"),
PQerrorMessage (conn));
return STATE_CRITICAL;
}
if (PQntuples (res) < 1) {
printf ("QUERY %s - %s.\n", _("WARNING"), _("No rows returned"));
return STATE_WARNING;
}
if (PQnfields (res) < 1) {
printf ("QUERY %s - %s.\n", _("WARNING"), _("No columns returned"));
return STATE_WARNING;
}
val_str = PQgetvalue (res, 0, 0);
if (! val_str) {
printf ("QUERY %s - %s.\n", _("CRITICAL"), _("No data returned"));
return STATE_CRITICAL;
}
value = strtod (val_str, &endptr);
if (verbose)
printf ("Query result: %f\n", value);
if (endptr == val_str) {
printf ("QUERY %s - %s: %s\n", _("CRITICAL"), _("Is not a numeric"), val_str);
return STATE_CRITICAL;
}
else if ((endptr != NULL) && (*endptr != '\0')) {
if (verbose)
printf ("Garbage after value: %s.\n", endptr);
}
my_status = get_status (value, qthresholds);
printf ("QUERY %s - ",
(my_status == STATE_OK)
? _("OK")
: (my_status == STATE_WARNING)
? _("WARNING")
: (my_status == STATE_CRITICAL)
? _("CRITICAL")
: _("UNKNOWN"));
printf (_("'%s' returned %f"), query, value);
printf ("|query=%f;%s;%s;;\n", value,
query_warning ? query_warning : "",
query_critical ? query_critical : "");
return my_status;
}

View file

@ -121,12 +121,12 @@ main (int argc, char **argv)
/* does the host address of number of packets argument come first? */
#ifdef PING_PACKETS_FIRST
# ifdef PING_HAS_TIMEOUT
asprintf (&cmd, rawcmd, timeout_interval, max_packets, addresses[i]);
xasprintf (&cmd, rawcmd, timeout_interval, max_packets, addresses[i]);
# else
asprintf (&cmd, rawcmd, max_packets, addresses[i]);
xasprintf (&cmd, rawcmd, max_packets, addresses[i]);
# endif
#else
asprintf (&cmd, rawcmd, addresses[i], max_packets);
xasprintf (&cmd, rawcmd, addresses[i], max_packets);
#endif
if (verbose >= 2)
@ -491,7 +491,7 @@ run_ping (const char *cmd, const char *addr)
if (warn_text == NULL) {
warn_text = strdup(_("System call sent warnings to stderr "));
} else {
asprintf(&warn_text, "%s %s", warn_text, _("System call sent warnings to stderr "));
xasprintf(&warn_text, "%s %s", warn_text, _("System call sent warnings to stderr "));
}
}
}
@ -540,7 +540,7 @@ error_scan (char buf[MAX_INPUT_BUFFER], const char *addr)
if (warn_text == NULL)
warn_text = strdup (_(WARN_DUPLICATES));
else if (! strstr (warn_text, _(WARN_DUPLICATES)) &&
asprintf (&warn_text, "%s %s", warn_text, _(WARN_DUPLICATES)) == -1)
xasprintf (&warn_text, "%s %s", warn_text, _(WARN_DUPLICATES)) == -1)
die (STATE_UNKNOWN, _("Unable to realloc warn_text\n"));
return (STATE_WARNING);
}

View file

@ -42,18 +42,21 @@ const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "regex.h"
#include <pwd.h>
#include <errno.h>
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
int process_arguments (int, char **);
int validate_arguments (void);
int check_thresholds (int);
int convert_to_seconds (char *);
void print_help (void);
void print_usage (void);
int wmax = -1;
int cmax = -1;
int wmin = -1;
int cmin = -1;
char *warning_range = NULL;
char *critical_range = NULL;
thresholds *procs_thresholds = NULL;
int options = 0; /* bitmask of filter criteria to test against */
#define ALL 1
@ -67,6 +70,10 @@ int options = 0; /* bitmask of filter criteria to test against */
#define PCPU 256
#define ELAPSED 512
#define EREG_ARGS 1024
#define KTHREAD_PARENT "kthreadd" /* the parent process of kernel threads:
ppid of procs are compared to pid of this proc*/
/* Different metrics */
char *metric_name;
enum metric {
@ -92,9 +99,21 @@ regex_t re_args;
char *fmt;
char *fails;
char tmp[MAX_INPUT_BUFFER];
int kthread_filter = 0;
int usepid = 0; /* whether to test for pid or /proc/pid/exe */
FILE *ps_input = NULL;
static int
stat_exe (const pid_t pid, struct stat *buf) {
char *path;
int ret;
xasprintf(&path, "/proc/%d/exe", pid);
ret = stat(path, buf);
free(path);
return ret;
}
int
main (int argc, char **argv)
@ -104,9 +123,13 @@ main (int argc, char **argv)
char *procprog;
pid_t mypid = 0;
struct stat statbuf;
dev_t mydev = 0;
ino_t myino = 0;
int procuid = 0;
pid_t procpid = 0;
pid_t procppid = 0;
pid_t kthread_ppid = 0;
int procvsz = 0;
int procrss = 0;
int procseconds = 0;
@ -127,6 +150,7 @@ main (int argc, char **argv)
int crit = 0; /* number of processes in crit state */
int i = 0, j = 0;
int result = STATE_UNKNOWN;
int ret;
output chld_out, chld_err;
setlocale (LC_ALL, "");
@ -137,7 +161,7 @@ main (int argc, char **argv)
input_buffer = malloc (MAX_INPUT_BUFFER);
procprog = malloc (MAX_INPUT_BUFFER);
asprintf (&metric_name, "PROCS");
xasprintf (&metric_name, "PROCS");
metric = METRIC_PROCS;
/* Parse extra opts if any */
@ -146,8 +170,16 @@ main (int argc, char **argv)
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* get our pid */
/* find ourself */
mypid = getpid();
if (usepid || stat_exe(mypid, &statbuf) == -1) {
/* usepid might have been set by -T */
usepid = 1;
} else {
usepid = 0;
mydev = statbuf.st_dev;
myino = statbuf.st_ino;
}
/* Set signal handling and alarm timeout */
if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
@ -176,7 +208,7 @@ main (int argc, char **argv)
printf ("%s", input_line);
strcpy (procprog, "");
asprintf (&procargs, "%s", "");
xasprintf (&procargs, "%s", "");
cols = sscanf (input_line, PS_FORMAT, PS_VARLIST);
@ -186,7 +218,7 @@ main (int argc, char **argv)
}
if ( cols >= expected_cols ) {
resultsum = 0;
asprintf (&procargs, "%s", input_line + pos);
xasprintf (&procargs, "%s", input_line + pos);
strip (procargs);
/* Some ps return full pathname for command. This removes path */
@ -202,7 +234,28 @@ main (int argc, char **argv)
procetime, procprog, procargs);
/* Ignore self */
if (mypid == procpid) continue;
if ((usepid && mypid == procpid) ||
(!usepid && ((ret = stat_exe(procpid, &statbuf) != -1) && statbuf.st_dev == mydev && statbuf.st_ino == myino) ||
(ret == -1 && errno == ENOENT))) {
if (verbose >= 3)
printf("not considering - is myself or gone\n");
continue;
}
/* filter kernel threads (childs of KTHREAD_PARENT)*/
/* TODO adapt for other OSes than GNU/Linux
sorry for not doing that, but I've no other OSes to test :-( */
if (kthread_filter == 1) {
/* get pid KTHREAD_PARENT */
if (kthread_ppid == 0 && !strcmp(procprog, KTHREAD_PARENT) )
kthread_ppid = procpid;
if (kthread_ppid == procppid) {
if (verbose >= 2)
printf ("Ignore kernel thread: pid=%d ppid=%d prog=%s args=%s\n", procpid, procppid, procprog, procargs);
continue;
}
}
if ((options & STAT) && (strstr (statopts, procstat)))
resultsum |= STAT;
@ -238,24 +291,24 @@ main (int argc, char **argv)
}
if (metric == METRIC_VSZ)
i = check_thresholds (procvsz);
i = get_status ((double)procvsz, procs_thresholds);
else if (metric == METRIC_RSS)
i = check_thresholds (procrss);
i = get_status ((double)procrss, procs_thresholds);
/* TODO? float thresholds for --metric=CPU */
else if (metric == METRIC_CPU)
i = check_thresholds ((int)procpcpu);
i = get_status (procpcpu, procs_thresholds);
else if (metric == METRIC_ELAPSED)
i = check_thresholds (procseconds);
i = get_status ((double)procseconds, procs_thresholds);
if (metric != METRIC_PROCS) {
if (i == STATE_WARNING) {
warn++;
asprintf (&fails, "%s%s%s", fails, (strcmp(fails,"") ? ", " : ""), procprog);
xasprintf (&fails, "%s%s%s", fails, (strcmp(fails,"") ? ", " : ""), procprog);
result = max_state (result, i);
}
if (i == STATE_CRITICAL) {
crit++;
asprintf (&fails, "%s%s%s", fails, (strcmp(fails,"") ? ", " : ""), procprog);
xasprintf (&fails, "%s%s%s", fails, (strcmp(fails,"") ? ", " : ""), procprog);
result = max_state (result, i);
}
}
@ -276,7 +329,7 @@ main (int argc, char **argv)
/* Needed if procs found, but none match filter */
if ( metric == METRIC_PROCS ) {
result = max_state (result, check_thresholds (procs) );
result = max_state (result, get_status ((double)procs, procs_thresholds) );
}
if ( result == STATE_OK ) {
@ -301,6 +354,13 @@ main (int argc, char **argv)
if ( verbose >= 1 && strcmp(fails,"") )
printf (" [%s]", fails);
if (metric == METRIC_PROCS)
printf (" | procs=%d;%s;%s;0;", procs,
warning_range ? warning_range : "",
critical_range ? critical_range : "");
else
printf (" | procs=%d;;;0; procs_warn=%d;;;0; procs_crit=%d;;;0;", procs, warn, crit);
printf ("\n");
return result;
}
@ -327,6 +387,7 @@ process_arguments (int argc, char **argv)
{"timeout", required_argument, 0, 't'},
{"status", required_argument, 0, 's'},
{"ppid", required_argument, 0, 'p'},
{"user", required_argument, 0, 'u'},
{"command", required_argument, 0, 'C'},
{"vsz", required_argument, 0, 'z'},
{"rss", required_argument, 0, 'r'},
@ -338,6 +399,8 @@ process_arguments (int argc, char **argv)
{"verbose", no_argument, 0, 'v'},
{"ereg-argument-array", required_argument, 0, CHAR_MAX+1},
{"input-file", required_argument, 0, CHAR_MAX+2},
{"no-kthreads", required_argument, 0, 'k'},
{"traditional-filter", no_argument, 0, 'T'},
{0, 0, 0, 0}
};
@ -346,7 +409,7 @@ process_arguments (int argc, char **argv)
strcpy (argv[c], "-t");
while (1) {
c = getopt_long (argc, argv, "Vvht:c:w:p:s:u:C:a:z:r:m:P:",
c = getopt_long (argc, argv, "Vvhkt:c:w:p:s:u:C:a:z:r:m:P:T",
longopts, &option);
if (c == -1 || c == EOF)
@ -368,32 +431,14 @@ process_arguments (int argc, char **argv)
timeout_interval = atoi (optarg);
break;
case 'c': /* critical threshold */
if (is_integer (optarg))
cmax = atoi (optarg);
else if (sscanf (optarg, ":%d", &cmax) == 1)
break;
else if (sscanf (optarg, "%d:%d", &cmin, &cmax) == 2)
break;
else if (sscanf (optarg, "%d:", &cmin) == 1)
break;
else
usage4 (_("Critical Process Count must be an integer!"));
critical_range = optarg;
break;
case 'w': /* warning threshold */
if (is_integer (optarg))
wmax = atoi (optarg);
else if (sscanf (optarg, ":%d", &wmax) == 1)
break;
else if (sscanf (optarg, "%d:%d", &wmin, &wmax) == 2)
break;
else if (sscanf (optarg, "%d:", &wmin) == 1)
break;
else
usage4 (_("Warning Process Count must be an integer!"));
warning_range = optarg;
break;
case 'p': /* process id */
if (sscanf (optarg, "%d%[^0-9]", &ppid, tmp) == 1) {
asprintf (&fmt, "%s%sPPID = %d", (fmt ? fmt : "") , (options ? ", " : ""), ppid);
xasprintf (&fmt, "%s%sPPID = %d", (fmt ? fmt : "") , (options ? ", " : ""), ppid);
options |= PPID;
break;
}
@ -403,7 +448,7 @@ process_arguments (int argc, char **argv)
break;
else
statopts = optarg;
asprintf (&fmt, _("%s%sSTATE = %s"), (fmt ? fmt : ""), (options ? ", " : ""), statopts);
xasprintf (&fmt, _("%s%sSTATE = %s"), (fmt ? fmt : ""), (options ? ", " : ""), statopts);
options |= STAT;
break;
case 'u': /* user or user id */
@ -423,7 +468,7 @@ process_arguments (int argc, char **argv)
uid = pw->pw_uid;
}
user = pw->pw_name;
asprintf (&fmt, "%s%sUID = %d (%s)", (fmt ? fmt : ""), (options ? ", " : ""),
xasprintf (&fmt, "%s%sUID = %d (%s)", (fmt ? fmt : ""), (options ? ", " : ""),
uid, user);
options |= USER;
break;
@ -433,7 +478,7 @@ process_arguments (int argc, char **argv)
break;
else
prog = optarg;
asprintf (&fmt, _("%s%scommand name '%s'"), (fmt ? fmt : ""), (options ? ", " : ""),
xasprintf (&fmt, _("%s%scommand name '%s'"), (fmt ? fmt : ""), (options ? ", " : ""),
prog);
options |= PROG;
break;
@ -443,7 +488,7 @@ process_arguments (int argc, char **argv)
break;
else
args = optarg;
asprintf (&fmt, "%s%sargs '%s'", (fmt ? fmt : ""), (options ? ", " : ""), args);
xasprintf (&fmt, "%s%sargs '%s'", (fmt ? fmt : ""), (options ? ", " : ""), args);
options |= ARGS;
break;
case CHAR_MAX+1:
@ -459,19 +504,19 @@ process_arguments (int argc, char **argv)
temp_string[i]=',';
i++;
}
asprintf (&fmt, "%s%sregex args '%s'", (fmt ? fmt : ""), (options ? ", " : ""), temp_string);
xasprintf (&fmt, "%s%sregex args '%s'", (fmt ? fmt : ""), (options ? ", " : ""), temp_string);
options |= EREG_ARGS;
break;
case 'r': /* RSS */
if (sscanf (optarg, "%d%[^0-9]", &rss, tmp) == 1) {
asprintf (&fmt, "%s%sRSS >= %d", (fmt ? fmt : ""), (options ? ", " : ""), rss);
xasprintf (&fmt, "%s%sRSS >= %d", (fmt ? fmt : ""), (options ? ", " : ""), rss);
options |= RSS;
break;
}
usage4 (_("RSS must be an integer!"));
case 'z': /* VSZ */
if (sscanf (optarg, "%d%[^0-9]", &vsz, tmp) == 1) {
asprintf (&fmt, "%s%sVSZ >= %d", (fmt ? fmt : ""), (options ? ", " : ""), vsz);
xasprintf (&fmt, "%s%sVSZ >= %d", (fmt ? fmt : ""), (options ? ", " : ""), vsz);
options |= VSZ;
break;
}
@ -479,13 +524,13 @@ process_arguments (int argc, char **argv)
case 'P': /* PCPU */
/* TODO: -P 1.5.5 is accepted */
if (sscanf (optarg, "%f%[^0-9.]", &pcpu, tmp) == 1) {
asprintf (&fmt, "%s%sPCPU >= %.2f", (fmt ? fmt : ""), (options ? ", " : ""), pcpu);
xasprintf (&fmt, "%s%sPCPU >= %.2f", (fmt ? fmt : ""), (options ? ", " : ""), pcpu);
options |= PCPU;
break;
}
usage4 (_("PCPU must be a float!"));
case 'm':
asprintf (&metric_name, "%s", optarg);
xasprintf (&metric_name, "%s", optarg);
if ( strcmp(optarg, "PROCS") == 0) {
metric = METRIC_PROCS;
break;
@ -508,9 +553,15 @@ process_arguments (int argc, char **argv)
}
usage4 (_("Metric must be one of PROCS, VSZ, RSS, CPU, ELAPSED!"));
case 'k': /* linux kernel thread filter */
kthread_filter = 1;
break;
case 'v': /* command */
verbose++;
break;
case 'T':
usepid = 1;
break;
case CHAR_MAX+2:
input_filename = optarg;
break;
@ -518,16 +569,19 @@ process_arguments (int argc, char **argv)
}
c = optind;
if (wmax == -1 && argv[c])
wmax = atoi (argv[c++]);
if (cmax == -1 && argv[c])
cmax = atoi (argv[c++]);
if ((! warning_range) && argv[c])
warning_range = argv[c++];
if ((! critical_range) && argv[c])
critical_range = argv[c++];
if (statopts == NULL && argv[c]) {
asprintf (&statopts, "%s", argv[c++]);
asprintf (&fmt, _("%s%sSTATE = %s"), (fmt ? fmt : ""), (options ? ", " : ""), statopts);
xasprintf (&statopts, "%s", argv[c++]);
xasprintf (&fmt, _("%s%sSTATE = %s"), (fmt ? fmt : ""), (options ? ", " : ""), statopts);
options |= STAT;
}
/* this will abort in case of invalid ranges */
set_thresholds (&procs_thresholds, warning_range, critical_range);
return validate_arguments ();
}
@ -536,27 +590,6 @@ process_arguments (int argc, char **argv)
int
validate_arguments ()
{
if (wmax >= 0 && wmin == -1)
wmin = 0;
if (cmax >= 0 && cmin == -1)
cmin = 0;
if (wmax >= wmin && cmax >= cmin) { /* standard ranges */
if (wmax > cmax && cmax != -1) {
printf (_("wmax (%d) cannot be greater than cmax (%d)\n"), wmax, cmax);
return ERROR;
}
if (cmin > wmin && wmin != -1) {
printf (_("wmin (%d) cannot be less than cmin (%d)\n"), wmin, cmin);
return ERROR;
}
}
/* if (wmax == -1 && cmax == -1 && wmin == -1 && cmin == -1) { */
/* printf ("At least one threshold must be set\n"); */
/* return ERROR; */
/* } */
if (options == 0)
options = ALL;
@ -579,40 +612,6 @@ validate_arguments ()
}
/* Check thresholds against value */
int
check_thresholds (int value)
{
if (wmax == -1 && cmax == -1 && wmin == -1 && cmin == -1) {
return OK;
}
else if (cmax >= 0 && cmin >= 0 && cmax < cmin) {
if (value > cmax && value < cmin)
return STATE_CRITICAL;
}
else if (cmax >= 0 && value > cmax) {
return STATE_CRITICAL;
}
else if (cmin >= 0 && value < cmin) {
return STATE_CRITICAL;
}
if (wmax >= 0 && wmin >= 0 && wmax < wmin) {
if (value > wmax && value < wmin) {
return STATE_WARNING;
}
}
else if (wmax >= 0 && value > wmax) {
return STATE_WARNING;
}
else if (wmin >= 0 && value < wmin) {
return STATE_WARNING;
}
return STATE_OK;
}
/* convert the elapsed time to seconds */
int
convert_to_seconds(char *etime) {
@ -713,6 +712,9 @@ print_help (void)
printf (" %s\n", "-v, --verbose");
printf (" %s\n", _("Extra information. Up to 3 verbosity levels"));
printf (" %s\n", "-T, --traditional");
printf (" %s\n", _("Filter own process the traditional way by PID instead of /proc/pid/exe"));
printf ("\n");
printf ("%s\n", "Filters:");
printf (" %s\n", "-s, --state=STATUSFLAGS");
@ -735,6 +737,8 @@ print_help (void)
printf (" %s\n", _("Only scan for processes with args that contain the regex STRING."));
printf (" %s\n", "-C, --command=COMMAND");
printf (" %s\n", _("Only scan for exact matches of COMMAND (without path)."));
printf (" %s\n", "-k, --no-kthreads");
printf (" %s\n", _("Only scan for non kernel threads (works on Linux only)."));
printf(_("\n\
RANGEs are specified 'min:max' or 'min:' or ':max' (or 'max'). If\n\
@ -769,5 +773,5 @@ print_usage (void)
printf ("%s\n", _("Usage:"));
printf ("%s -w <range> -c <range> [-m metric] [-s state] [-p ppid]\n", progname);
printf (" [-u user] [-r rss] [-z vsz] [-P %%cpu] [-a argument-array]\n");
printf (" [-C command] [-t timeout] [-v]\n");
printf (" [-C command] [-k] [-t timeout] [-v]\n");
}

View file

@ -328,7 +328,7 @@ void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", PW_AUTH_UDP_PORT);
xasprintf (&myport, "%d", PW_AUTH_UDP_PORT);
print_revision (progname, NP_VERSION);

View file

@ -403,7 +403,7 @@ void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", PORT);
xasprintf (&myport, "%d", PORT);
print_revision (progname, NP_VERSION);

View file

@ -87,9 +87,9 @@ int errcode, excode;
int server_port = SMTP_PORT;
char *server_address = NULL;
char *server_expect = NULL;
int smtp_use_dummycmd = 0;
char *mail_command = NULL;
char *from_arg = NULL;
int send_mail_from=0;
int ncommands=0;
int command_size=0;
int nresponses=0;
@ -99,9 +99,9 @@ char **responses = NULL;
char *authtype = NULL;
char *authuser = NULL;
char *authpass = NULL;
int warning_time = 0;
double warning_time = 0;
int check_warning_time = FALSE;
int critical_time = 0;
double critical_time = 0;
int check_critical_time = FALSE;
int verbose = 0;
int use_ssl = FALSE;
@ -156,17 +156,17 @@ main (int argc, char **argv)
}
}
if(use_ehlo)
asprintf (&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n");
xasprintf (&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n");
else
asprintf (&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n");
xasprintf (&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n");
if (verbose)
printf("HELOCMD: %s", helocmd);
/* initialize the MAIL command with optional FROM command */
asprintf (&cmd_str, "%sFROM: %s%s", mail_command, from_arg, "\r\n");
xasprintf (&cmd_str, "%sFROM:<%s>%s", mail_command, from_arg, "\r\n");
if (verbose && smtp_use_dummycmd)
if (verbose && send_mail_from)
printf ("FROM CMD: %s", cmd_str);
/* initialize alarm signal handling */
@ -283,23 +283,14 @@ main (int argc, char **argv)
}
#endif
/* sendmail will syslog a "NOQUEUE" error if session does not attempt
* to do something useful. This can be prevented by giving a command
* even if syntax is illegal (MAIL requires a FROM:<...> argument)
*
* According to rfc821 you can include a null reversepath in the from command
* - but a log message is generated on the smtp server.
*
* Use the -f option to provide a FROM address
*/
if (smtp_use_dummycmd) {
if (send_mail_from) {
my_send(cmd_str, strlen(cmd_str));
if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose)
printf("%s", buffer);
}
while (n < ncommands) {
asprintf (&cmd_str, "%s%s", commands[n], "\r\n");
xasprintf (&cmd_str, "%s%s", commands[n], "\r\n");
my_send(cmd_str, strlen(cmd_str));
if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose)
printf("%s", buffer);
@ -336,12 +327,12 @@ main (int argc, char **argv)
do {
if (authuser == NULL) {
result = STATE_CRITICAL;
asprintf(&error_msg, _("no authuser specified, "));
xasprintf(&error_msg, _("no authuser specified, "));
break;
}
if (authpass == NULL) {
result = STATE_CRITICAL;
asprintf(&error_msg, _("no authpass specified, "));
xasprintf(&error_msg, _("no authpass specified, "));
break;
}
@ -351,7 +342,7 @@ main (int argc, char **argv)
printf (_("sent %s\n"), "AUTH LOGIN");
if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
asprintf(&error_msg, _("recv() failed after AUTH LOGIN, "));
xasprintf(&error_msg, _("recv() failed after AUTH LOGIN, "));
result = STATE_WARNING;
break;
}
@ -360,21 +351,20 @@ main (int argc, char **argv)
if (strncmp (buffer, "334", 3) != 0) {
result = STATE_CRITICAL;
asprintf(&error_msg, _("invalid response received after AUTH LOGIN, "));
xasprintf(&error_msg, _("invalid response received after AUTH LOGIN, "));
break;
}
/* encode authuser with base64 */
base64_encode_alloc (authuser, strlen(authuser), &abuf);
/* FIXME: abuf shouldn't have enough space to strcat a '\r\n' into it. */
strcat (abuf, "\r\n");
xasprintf(&abuf, "%s\r\n", abuf);
my_send(abuf, strlen(abuf));
if (verbose)
printf (_("sent %s\n"), abuf);
if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
result = STATE_CRITICAL;
asprintf(&error_msg, _("recv() failed after sending authuser, "));
xasprintf(&error_msg, _("recv() failed after sending authuser, "));
break;
}
if (verbose) {
@ -382,20 +372,19 @@ main (int argc, char **argv)
}
if (strncmp (buffer, "334", 3) != 0) {
result = STATE_CRITICAL;
asprintf(&error_msg, _("invalid response received after authuser, "));
xasprintf(&error_msg, _("invalid response received after authuser, "));
break;
}
/* encode authpass with base64 */
base64_encode_alloc (authpass, strlen(authpass), &abuf);
/* FIXME: abuf shouldn't have enough space to strcat a '\r\n' into it. */
strcat (abuf, "\r\n");
xasprintf(&abuf, "%s\r\n", abuf);
my_send(abuf, strlen(abuf));
if (verbose) {
printf (_("sent %s\n"), abuf);
}
if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
result = STATE_CRITICAL;
asprintf(&error_msg, _("recv() failed after sending authpass, "));
xasprintf(&error_msg, _("recv() failed after sending authpass, "));
break;
}
if (verbose) {
@ -403,14 +392,14 @@ main (int argc, char **argv)
}
if (strncmp (buffer, "235", 3) != 0) {
result = STATE_CRITICAL;
asprintf(&error_msg, _("invalid response received after authpass, "));
xasprintf(&error_msg, _("invalid response received after authpass, "));
break;
}
break;
} while (0);
} else {
result = STATE_CRITICAL;
asprintf(&error_msg, _("only authtype LOGIN is supported, "));
xasprintf(&error_msg, _("only authtype LOGIN is supported, "));
}
}
@ -428,9 +417,9 @@ main (int argc, char **argv)
elapsed_time = (double)microsec / 1.0e6;
if (result == STATE_OK) {
if (check_critical_time && elapsed_time > (double) critical_time)
if (check_critical_time && elapsed_time > critical_time)
result = STATE_CRITICAL;
else if (check_warning_time && elapsed_time > (double) warning_time)
else if (check_warning_time && elapsed_time > warning_time)
result = STATE_WARNING;
}
@ -521,8 +510,9 @@ process_arguments (int argc, char **argv)
localhostname = strdup(optarg);
break;
case 'f': /* from argument */
from_arg = optarg;
smtp_use_dummycmd = 1;
from_arg = optarg + strspn(optarg, "<");
from_arg = strndup(from_arg, strcspn(from_arg, ">"));
send_mail_from = 1;
break;
case 'A':
authtype = optarg;
@ -562,21 +552,19 @@ process_arguments (int argc, char **argv)
nresponses++;
break;
case 'c': /* critical time threshold */
if (is_intnonneg (optarg)) {
critical_time = atoi (optarg);
check_critical_time = TRUE;
}
if (!is_nonnegative (optarg))
usage4 (_("Critical time must be a positive"));
else {
usage4 (_("Critical time must be a positive integer"));
critical_time = strtod (optarg, NULL);
check_critical_time = TRUE;
}
break;
case 'w': /* warning time threshold */
if (is_intnonneg (optarg)) {
warning_time = atoi (optarg);
check_warning_time = TRUE;
}
if (!is_nonnegative (optarg))
usage4 (_("Warning time must be a positive"));
else {
usage4 (_("Warning time must be a positive integer"));
warning_time = strtod (optarg, NULL);
check_warning_time = TRUE;
}
break;
case 'v': /* verbose */
@ -603,7 +591,7 @@ process_arguments (int argc, char **argv)
#ifdef USE_OPENSSL
if ((temp=strchr(optarg,','))!=NULL) {
*temp='\0';
if (!is_intnonneg (temp))
if (!is_intnonneg (optarg))
usage2 ("Invalid certificate expiration period", optarg);
days_till_exp_warn = atoi(optarg);
*temp=',';
@ -653,7 +641,7 @@ process_arguments (int argc, char **argv)
usage2 (_("Invalid hostname/address"), argv[c]);
}
else {
asprintf (&server_address, "127.0.0.1");
xasprintf (&server_address, "127.0.0.1");
}
}
@ -786,7 +774,7 @@ void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", SMTP_PORT);
xasprintf (&myport, "%d", SMTP_PORT);
print_revision (progname, NP_VERSION);
@ -810,7 +798,7 @@ print_help (void)
printf (_(" String to expect in first line of server response (default: '%s')\n"), SMTP_EXPECT);
printf (" %s\n", "-C, --command=STRING");
printf (" %s\n", _("SMTP command (may be used repeatedly)"));
printf (" %s\n", "-R, --command=STRING");
printf (" %s\n", "-R, --response=STRING");
printf (" %s\n", _("Expected response to command (may be used repeatedly)"));
printf (" %s\n", "-f, --from=STRING");
printf (" %s\n", _("FROM-address to include in MAIL command, required by Exchange 2000")),
@ -853,7 +841,7 @@ void
print_usage (void)
{
printf ("%s\n", _("Usage:"));
printf ("%s -H host [-p port] [-4|-6] [-e expect] [-C command] [-f from addr]", progname);
printf ("%s -H host [-p port] [-4|-6] [-e expect] [-C command] [-R response] [-f from addr]\n", progname);
printf ("[-A authtype -U authuser -P authpass] [-w warn] [-c crit] [-t timeout] [-q]\n");
printf ("[-F fqdn] [-S] [-D warn days cert expire[,crit days cert expire]] [-v] \n");
}

View file

@ -57,12 +57,13 @@ const char *email = "nagiosplug-devel@lists.sourceforge.net";
#define WARN_STRING 16
#define WARN_REGEX 32
#define MAX_OIDS 8
#define OID_COUNT_STEP 8
/* Longopts only arguments */
#define L_CALCULATE_RATE CHAR_MAX+1
#define L_RATE_MULTIPLIER CHAR_MAX+2
#define L_INVERT_SEARCH CHAR_MAX+3
#define L_OFFSET CHAR_MAX+4
/* Gobble to string - stop incrementing c when c[0] match one of the
* characters in s */
@ -111,6 +112,7 @@ char *privproto = NULL;
char *authpasswd = NULL;
char *privpasswd = NULL;
char **oids = NULL;
size_t oids_size = NULL;
char *label;
char *units;
char *port;
@ -120,30 +122,56 @@ int invert_search=0;
char **labels = NULL;
char **unitv = NULL;
size_t nlabels = 0;
size_t labels_size = 8;
size_t labels_size = OID_COUNT_STEP;
size_t nunits = 0;
size_t unitv_size = 8;
size_t unitv_size = OID_COUNT_STEP;
int numoids = 0;
int numauthpriv = 0;
int verbose = 0;
int usesnmpgetnext = FALSE;
char *warning_thresholds = NULL;
char *critical_thresholds = NULL;
thresholds *thlds[MAX_OIDS];
double response_value[MAX_OIDS];
thresholds **thlds;
size_t thlds_size = OID_COUNT_STEP;
double *response_value;
size_t response_size = OID_COUNT_STEP;
int retries = 0;
int eval_method[MAX_OIDS];
int *eval_method;
size_t eval_size = OID_COUNT_STEP;
char *delimiter;
char *output_delim;
char *miblist = NULL;
int needmibs = FALSE;
int calculate_rate = 0;
double offset = 0.0;
int rate_multiplier = 1;
state_data *previous_state;
double previous_value[MAX_OIDS];
double *previous_value;
size_t previous_size = OID_COUNT_STEP;
int perf_labels = 1;
static char *fix_snmp_range(char *th)
{
double left, right;
char *colon, *ret;
if ((colon = strchr(th, ':')) == NULL || *(colon + 1) == '\0')
return th;
left = strtod(th, NULL);
right = strtod(colon + 1, NULL);
if (right >= left)
return th;
if ((ret = malloc(strlen(th) + 2)) == NULL)
die(STATE_UNKNOWN, _("Cannot malloc"));
*colon = '\0';
sprintf(ret, "@%s:%s", colon + 1, th);
free(th);
return ret;
}
int
main (int argc, char **argv)
{
@ -181,10 +209,13 @@ main (int argc, char **argv)
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
labels = malloc (labels_size);
unitv = malloc (unitv_size);
for (i = 0; i < MAX_OIDS; i++)
eval_method[i] = CHECK_UNDEF;
labels = malloc (labels_size * sizeof(*labels));
unitv = malloc (unitv_size * sizeof(*unitv));
thlds = malloc (thlds_size * sizeof(*thlds));
response_value = malloc (response_size * sizeof(*response_value));
previous_value = malloc (previous_size * sizeof(*previous_value));
eval_method = calloc (eval_size, sizeof(*eval_method));
oids = calloc(oids_size, sizeof (char *));
label = strdup ("SNMP");
units = strdup ("");
@ -202,13 +233,14 @@ main (int argc, char **argv)
np_set_args(argc, argv);
time(&current_time);
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
if(calculate_rate) {
if (!strcmp(label, "SNMP"))
label = strdup("SNMP RATE");
time(&current_time);
i=0;
previous_state = np_state_read();
if(previous_state!=NULL) {
@ -217,6 +249,10 @@ main (int argc, char **argv)
while((ap = strsep(&previous_string, ":")) != NULL) {
if(verbose>2)
printf("State for %d=%s\n", i, ap);
while (i >= previous_size) {
previous_size += OID_COUNT_STEP;
previous_value = realloc(previous_value, previous_size * sizeof(*previous_value));
}
previous_value[i++]=strtod(ap,NULL);
}
}
@ -228,6 +264,15 @@ main (int argc, char **argv)
for (i=0; i<numoids; i++) {
char *w = th_warn ? strndup(th_warn, strcspn(th_warn, ",")) : NULL;
char *c = th_crit ? strndup(th_crit, strcspn(th_crit, ",")) : NULL;
/* translate "2:1" to "@1:2" for backwards compatibility */
w = w ? fix_snmp_range(w) : NULL;
c = c ? fix_snmp_range(c) : NULL;
while (i >= thlds_size) {
thlds_size += OID_COUNT_STEP;
thlds = realloc(thlds, thlds_size * sizeof(*thlds));
}
/* Skip empty thresholds, while avoiding segfault */
set_thresholds(&thlds[i],
w ? strpbrk(w, NP_THRESHOLDS_CHARS) : NULL,
@ -251,35 +296,36 @@ main (int argc, char **argv)
snmpcmd = strdup (PATH_TO_SNMPGET);
}
/* 9 arguments to pass before authpriv options + 1 for host and numoids. Add one for terminating NULL */
command_line = calloc (9 + numauthpriv + 1 + numoids + 1, sizeof (char *));
/* 10 arguments to pass before authpriv options + 1 for host and numoids. Add one for terminating NULL */
command_line = calloc (10 + numauthpriv + 1 + numoids + 1, sizeof (char *));
command_line[0] = snmpcmd;
command_line[1] = strdup ("-t");
asprintf (&command_line[2], "%d", timeout_interval);
command_line[3] = strdup ("-r");
asprintf (&command_line[4], "%d", retries);
command_line[5] = strdup ("-m");
command_line[6] = strdup (miblist);
command_line[7] = "-v";
command_line[8] = strdup (proto);
command_line[1] = strdup ("-Le");
command_line[2] = strdup ("-t");
xasprintf (&command_line[3], "%d", timeout_interval);
command_line[4] = strdup ("-r");
xasprintf (&command_line[5], "%d", retries);
command_line[6] = strdup ("-m");
command_line[7] = strdup (miblist);
command_line[8] = "-v";
command_line[9] = strdup (proto);
for (i = 0; i < numauthpriv; i++) {
command_line[9 + i] = authpriv[i];
command_line[10 + i] = authpriv[i];
}
asprintf (&command_line[9 + numauthpriv], "%s:%s", server_address, port);
xasprintf (&command_line[10 + numauthpriv], "%s:%s", server_address, port);
/* This is just for display purposes, so it can remain a string */
asprintf(&cl_hidden_auth, "%s -t %d -r %d -m %s -v %s %s %s:%s",
xasprintf(&cl_hidden_auth, "%s -Le -t %d -r %d -m %s -v %s %s %s:%s",
snmpcmd, timeout_interval, retries, strlen(miblist) ? miblist : "''", proto, "[authpriv]",
server_address, port);
for (i = 0; i < numoids; i++) {
command_line[9 + numauthpriv + 1 + i] = oids[i];
asprintf(&cl_hidden_auth, "%s %s", cl_hidden_auth, oids[i]);
command_line[10 + numauthpriv + 1 + i] = oids[i];
xasprintf(&cl_hidden_auth, "%s %s", cl_hidden_auth, oids[i]);
}
command_line[9 + numauthpriv + 1 + numoids] = NULL;
command_line[10 + numauthpriv + 1 + numoids] = NULL;
if (verbose)
printf ("%s\n", cl_hidden_auth);
@ -371,14 +417,14 @@ main (int argc, char **argv)
if (dq_count) { /* unfinished line */
/* copy show verbatim first */
if (!mult_resp) mult_resp = strdup("");
asprintf (&mult_resp, "%s%s:\n%s\n", mult_resp, oids[i], show);
xasprintf (&mult_resp, "%s%s:\n%s\n", mult_resp, oids[i], show);
/* then strip out unmatched double-quote from single-line output */
if (show[0] == '"') show++;
/* Keep reading until we match end of double-quoted string */
for (line++; line < chld_out.lines; line++) {
ptr = chld_out.line[line];
asprintf (&mult_resp, "%s%s\n", mult_resp, ptr);
xasprintf (&mult_resp, "%s%s\n", mult_resp, ptr);
COUNT_SEQ(ptr, bk_count, dq_count)
while (dq_count && ptr[0] != '\n' && ptr[0] != '\0') {
@ -396,7 +442,7 @@ main (int argc, char **argv)
show = strstr (response, "Timeticks: ");
}
else
show = response;
show = response + 3;
iresult = STATE_DEPENDENT;
@ -405,8 +451,12 @@ main (int argc, char **argv)
if (thlds[i]->warning || thlds[i]->critical || calculate_rate) {
ptr = strpbrk (show, "0123456789");
if (ptr == NULL)
die (STATE_UNKNOWN,_("No valid data returned"));
response_value[i] = strtod (ptr, NULL);
die (STATE_UNKNOWN,_("No valid data returned (%s)\n"), show);
while (i >= response_size) {
response_size += OID_COUNT_STEP;
response_value = realloc(response_value, response_size * sizeof(*response_value));
}
response_value[i] = strtod (ptr, NULL) + offset;
if(calculate_rate) {
if (previous_state!=NULL) {
@ -424,16 +474,16 @@ main (int argc, char **argv)
/* Convert to per second, then use multiplier */
temp_double = temp_double/duration*rate_multiplier;
iresult = get_status(temp_double, thlds[i]);
asprintf (&show, conv, temp_double);
xasprintf (&show, conv, temp_double);
}
} else {
iresult = get_status(response_value[i], thlds[i]);
asprintf (&show, conv, response_value[i]);
xasprintf (&show, conv, response_value[i]);
}
}
/* Process this block for string matching */
else if (eval_method[i] & CRIT_STRING) {
else if (eval_size > i && eval_method[i] & CRIT_STRING) {
if (strcmp (show, string_value))
iresult = (invert_search==0) ? STATE_CRITICAL : STATE_OK;
else
@ -441,7 +491,7 @@ main (int argc, char **argv)
}
/* Process this block for regex matching */
else if (eval_method[i] & CRIT_REGEX) {
else if (eval_size > i && eval_method[i] & CRIT_REGEX) {
excode = regexec (&preg, response, 10, pmatch, eflags);
if (excode == 0) {
iresult = (invert_search==0) ? STATE_OK : STATE_CRITICAL;
@ -459,9 +509,9 @@ main (int argc, char **argv)
/* Process this block for existence-nonexistence checks */
/* TV: Should this be outside of this else block? */
else {
if (eval_method[i] & CRIT_PRESENT)
if (eval_size > i && eval_method[i] & CRIT_PRESENT)
iresult = STATE_CRITICAL;
else if (eval_method[i] & WARN_PRESENT)
else if (eval_size > i && eval_method[i] & WARN_PRESENT)
iresult = STATE_WARNING;
else if (response && iresult == STATE_DEPENDENT)
iresult = STATE_OK;
@ -472,16 +522,16 @@ main (int argc, char **argv)
/* Prepend a label for this OID if there is one */
if (nlabels >= (size_t)1 && (size_t)i < nlabels && labels[i] != NULL)
asprintf (&outbuff, "%s%s%s %s%s%s", outbuff,
xasprintf (&outbuff, "%s%s%s %s%s%s", outbuff,
(i == 0) ? " " : output_delim,
labels[i], mark (iresult), show, mark (iresult));
else
asprintf (&outbuff, "%s%s%s%s%s", outbuff, (i == 0) ? " " : output_delim,
xasprintf (&outbuff, "%s%s%s%s%s", outbuff, (i == 0) ? " " : output_delim,
mark (iresult), show, mark (iresult));
/* Append a unit string for this OID if there is one */
if (nunits > (size_t)0 && (size_t)i < nunits && unitv[i] != NULL)
asprintf (&outbuff, "%s %s", outbuff, unitv[i]);
xasprintf (&outbuff, "%s %s", outbuff, unitv[i]);
/* Write perfdata with whatever can be parsed by strtod, if possible */
ptr = NULL;
@ -523,7 +573,7 @@ main (int argc, char **argv)
current_length=0;
for(i=0; i<total_oids; i++) {
asprintf(&temp_string,"%.0f",response_value[i]);
xasprintf(&temp_string,"%.0f",response_value[i]);
if(temp_string==NULL)
die(STATE_UNKNOWN,_("Cannot asprintf()"));
response_length = strlen(temp_string);
@ -595,6 +645,7 @@ process_arguments (int argc, char **argv)
{"next", no_argument, 0, 'n'},
{"rate", no_argument, 0, L_CALCULATE_RATE},
{"rate-multiplier", required_argument, 0, L_RATE_MULTIPLIER},
{"offset", required_argument, 0, L_OFFSET},
{"invert-search", no_argument, 0, L_INVERT_SEARCH},
{"perf-oids", no_argument, 0, 'O'},
{0, 0, 0, 0}
@ -700,23 +751,36 @@ process_arguments (int argc, char **argv)
*/
needmibs = TRUE;
}
if (!oids) oids = calloc(MAX_OIDS, sizeof (char *));
for (ptr = strtok(optarg, ", "); ptr != NULL && j < MAX_OIDS; ptr = strtok(NULL, ", "), j++) {
for (ptr = strtok(optarg, ", "); ptr != NULL; ptr = strtok(NULL, ", "), j++) {
while (j >= oids_size) {
oids_size += OID_COUNT_STEP;
oids = realloc(oids, oids_size * sizeof (*oids));
}
oids[j] = strdup(ptr);
}
numoids = j;
if (c == 'E' || c == 'e') {
jj++;
ii++;
while (j+1 >= eval_size) {
eval_size += OID_COUNT_STEP;
eval_method = realloc(eval_method, eval_size * sizeof(*eval_method));
memset(eval_method + eval_size - OID_COUNT_STEP, 0, 8);
}
if (c == 'E')
eval_method[j+1] |= WARN_PRESENT;
else if (c == 'e')
eval_method[j+1] |= CRIT_PRESENT;
}
if (c == 'E')
eval_method[j+1] |= WARN_PRESENT;
else if (c == 'e')
eval_method[j+1] |= CRIT_PRESENT;
break;
case 's': /* string or substring */
strncpy (string_value, optarg, sizeof (string_value) - 1);
string_value[sizeof (string_value) - 1] = 0;
while (jj >= eval_size) {
eval_size += OID_COUNT_STEP;
eval_method = realloc(eval_method, eval_size * sizeof(*eval_method));
memset(eval_method + eval_size - OID_COUNT_STEP, 0, 8);
}
eval_method[jj++] = CRIT_STRING;
ii++;
break;
@ -732,6 +796,11 @@ process_arguments (int argc, char **argv)
printf (_("Could Not Compile Regular Expression"));
return ERROR;
}
while (jj >= eval_size) {
eval_size += OID_COUNT_STEP;
eval_method = realloc(eval_method, eval_size * sizeof(*eval_method));
memset(eval_method + eval_size - OID_COUNT_STEP, 0, 8);
}
eval_method[jj++] = CRIT_REGEX;
ii++;
break;
@ -745,9 +814,9 @@ process_arguments (int argc, char **argv)
break;
case 'l': /* label */
nlabels++;
if (nlabels >= labels_size) {
if (nlabels > labels_size) {
labels_size += 8;
labels = realloc (labels, labels_size);
labels = realloc (labels, labels_size * sizeof(*labels));
if (labels == NULL)
die (STATE_UNKNOWN, _("Could not reallocate labels[%d]"), (int)nlabels);
}
@ -757,13 +826,13 @@ process_arguments (int argc, char **argv)
if (ptr[0] == '\'')
labels[nlabels - 1] = ptr + 1;
while (ptr && (ptr = nextarg (ptr))) {
if (nlabels >= labels_size) {
nlabels++;
if (nlabels > labels_size) {
labels_size += 8;
labels = realloc (labels, labels_size);
labels = realloc (labels, labels_size * sizeof(*labels));
if (labels == NULL)
die (STATE_UNKNOWN, _("Could not reallocate labels\n"));
}
nlabels++;
ptr = thisarg (ptr);
if (ptr[0] == '\'')
labels[nlabels - 1] = ptr + 1;
@ -774,9 +843,9 @@ process_arguments (int argc, char **argv)
case 'u': /* units */
units = optarg;
nunits++;
if (nunits >= unitv_size) {
if (nunits > unitv_size) {
unitv_size += 8;
unitv = realloc (unitv, unitv_size);
unitv = realloc (unitv, unitv_size * sizeof(*unitv));
if (unitv == NULL)
die (STATE_UNKNOWN, _("Could not reallocate units [%d]\n"), (int)nunits);
}
@ -786,9 +855,9 @@ process_arguments (int argc, char **argv)
if (ptr[0] == '\'')
unitv[nunits - 1] = ptr + 1;
while (ptr && (ptr = nextarg (ptr))) {
if (nunits >= unitv_size) {
if (nunits > unitv_size) {
unitv_size += 8;
unitv = realloc (unitv, unitv_size);
unitv = realloc (unitv, unitv_size * sizeof(*unitv));
if (units == NULL)
die (STATE_UNKNOWN, _("Could not realloc() units\n"));
}
@ -809,6 +878,9 @@ process_arguments (int argc, char **argv)
if(!is_integer(optarg)||((rate_multiplier=atoi(optarg))<=0))
usage2(_("Rate multiplier must be a positive integer"),optarg);
break;
case L_OFFSET:
offset=strtod(optarg,NULL);
break;
case L_INVERT_SEARCH:
invert_search=1;
break;
@ -869,7 +941,7 @@ validate_arguments ()
die(STATE_UNKNOWN, _("No OIDs specified\n"));
if (proto == NULL)
asprintf(&proto, DEFAULT_PROTOCOL);
xasprintf(&proto, DEFAULT_PROTOCOL);
if ((strcmp(proto,"1") == 0) || (strcmp(proto, "2c")==0)) { /* snmpv1 or snmpv2c */
numauthpriv = 2;
@ -879,7 +951,7 @@ validate_arguments ()
}
else if ( strcmp (proto, "3") == 0 ) { /* snmpv3 args */
if (seclevel == NULL)
asprintf(&seclevel, "noAuthNoPriv");
xasprintf(&seclevel, "noAuthNoPriv");
if (strcmp(seclevel, "noAuthNoPriv") == 0) {
numauthpriv = 2;
@ -892,7 +964,7 @@ validate_arguments ()
}
if (authproto == NULL )
asprintf(&authproto, DEFAULT_AUTH_PROTOCOL);
xasprintf(&authproto, DEFAULT_AUTH_PROTOCOL);
if (secname == NULL)
die(STATE_UNKNOWN, _("Required parameter: %s\n"), "secname");
@ -913,7 +985,7 @@ validate_arguments ()
authpriv[7] = strdup (authpasswd);
} else if ( strcmp(seclevel, "authPriv") == 0 ) {
if (privproto == NULL )
asprintf(&privproto, DEFAULT_PRIV_PROTOCOL);
xasprintf(&privproto, DEFAULT_PRIV_PROTOCOL);
if (privpasswd == NULL)
die(STATE_UNKNOWN, _("Required parameter: %s\n"), "privpasswd");
@ -1057,6 +1129,8 @@ print_help (void)
printf (" %s\n", _("Enable rate calculation. See 'Rate Calculation' below"));
printf (" %s\n", "--rate-multiplier");
printf (" %s\n", _("Converts rate per second. For example, set to 60 to convert to per minute"));
printf (" %s\n", "--offset=OFFSET");
printf (" %s\n", _("Add/substract the specified OFFSET to numeric sensor data"));
/* Tests Against Strings */
printf (" %s\n", "-s, --string=STRING");
@ -1093,7 +1167,7 @@ print_help (void)
printf ("\n");
printf ("%s\n", _("Notes:"));
printf (" %s\n", _("- Multiple OIDs (and labels) may be indicated by a comma or space-delimited "));
printf (" %s %i %s\n", _("list (lists with internal spaces must be quoted). Maximum:"), MAX_OIDS, _("OIDs."));
printf (" %s\n", _("list (lists with internal spaces must be quoted)."));
printf(" -%s", UT_THRESHOLDS_NOTES);

View file

@ -241,7 +241,7 @@ ssh_connect (char *haddr, int hport, char *remote_version)
ssh_server = ssh_proto + strspn (ssh_proto, "-0123456789. ");
ssh_proto[strspn (ssh_proto, "0123456789. ")] = 0;
asprintf (&buffer, "SSH-%s-check_ssh_%s\r\n", ssh_proto, rev_no);
xasprintf (&buffer, "SSH-%s-check_ssh_%s\r\n", ssh_proto, rev_no);
send (sd, buffer, strlen (buffer), MSG_DONTWAIT);
if (verbose)
printf ("%s\n", buffer);
@ -271,7 +271,7 @@ void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", SSH_DFL_PORT);
xasprintf (&myport, "%d", SSH_DFL_PORT);
print_revision (progname, NP_VERSION);
@ -307,6 +307,6 @@ void
print_usage (void)
{
printf ("%s\n", _("Usage:"));
printf ("%s [-46] [-t <timeout>] [-r <remote version>] [-p <port>] <host>\n", progname);
printf ("%s [-4|-6] [-t <timeout>] [-r <remote version>] [-p <port>] <host>\n", progname);
}

View file

@ -129,7 +129,7 @@ main (int argc, char **argv)
percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
result = max_state (result, check_swap (percent, dskfree_mb));
if (verbose)
asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
}
}
else if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%[TotalFre]%*[:] %f %*[k]%*[B]", str, &tmp_mb)) {
@ -152,15 +152,15 @@ main (int argc, char **argv)
free_swap_mb = dskfree_mb;
#else
# ifdef HAVE_SWAP
asprintf(&swap_command, "%s", SWAP_COMMAND);
asprintf(&swap_format, "%s", SWAP_FORMAT);
xasprintf(&swap_command, "%s", SWAP_COMMAND);
xasprintf(&swap_format, "%s", SWAP_FORMAT);
/* These override the command used if a summary (and thus ! allswaps) is required */
/* The summary flag returns more accurate information about swap usage on these OSes */
# ifdef _AIX
if (!allswaps) {
asprintf(&swap_command, "%s", "/usr/sbin/lsps -s");
asprintf(&swap_format, "%s", "%f%*s %f");
xasprintf(&swap_command, "%s", "/usr/sbin/lsps -s");
xasprintf(&swap_format, "%s", "%f%*s %f");
conv_factor = 1;
}
# endif
@ -228,7 +228,7 @@ main (int argc, char **argv)
percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
result = max_state (result, check_swap (percent, dskfree_mb));
if (verbose)
asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
}
}
# ifdef _AIX
@ -290,7 +290,7 @@ main (int argc, char **argv)
percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
result = max_state (result, check_swap (percent, dskfree_mb));
if (verbose) {
asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
}
}
@ -329,7 +329,7 @@ main (int argc, char **argv)
percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
result = max_state (result, check_swap (percent, dskfree_mb));
if (verbose) {
asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
}
}

View file

@ -1,30 +1,30 @@
/*****************************************************************************
*
*
* Nagios check_tcp plugin
*
*
* License: GPL
* Copyright (c) 1999-2008 Nagios Plugins Development Team
*
*
* Description:
*
*
* This file contains the check_tcp plugin
*
*
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* $Id$
*
*
*****************************************************************************/
/* progname "check_tcp" changes depending on symlink called */
@ -61,6 +61,7 @@ static int PORT = 0;
static int server_port = 0;
static char *server_address = NULL;
static int host_specified = FALSE;
static char *server_send = NULL;
static char *server_quit = NULL;
static char **server_expect;
@ -462,6 +463,7 @@ process_arguments (int argc, char **argv)
#endif
break;
case 'H': /* hostname */
host_specified = TRUE;
server_address = optarg;
break;
case 'c': /* critical */
@ -502,7 +504,7 @@ process_arguments (int argc, char **argv)
if (escape)
server_send = np_escaped_string(optarg);
else
asprintf(&server_send, "%s", optarg);
xasprintf(&server_send, "%s", optarg);
break;
case 'e': /* expect string (may be repeated) */
flags &= ~FLAG_EXACT_MATCH;
@ -522,7 +524,7 @@ process_arguments (int argc, char **argv)
if (escape)
server_quit = np_escaped_string(optarg);
else
asprintf(&server_quit, "%s\r\n", optarg);
xasprintf(&server_quit, "%s\r\n", optarg);
break;
case 'r':
if (!strncmp(optarg,"ok",2))
@ -555,7 +557,7 @@ process_arguments (int argc, char **argv)
# ifdef USE_OPENSSL /* XXX */
if ((temp=strchr(optarg,','))!=NULL) {
*temp='\0';
if (!is_intnonneg (temp))
if (!is_intnonneg (optarg))
usage2 (_("Invalid certificate expiration period"), optarg); days_till_exp_warn = atoi(optarg);
*temp=',';
temp++;
@ -588,6 +590,10 @@ process_arguments (int argc, char **argv)
}
}
c = optind;
if(host_specified == FALSE && c < argc)
server_address = strdup (argv[c++]);
if (server_address == NULL)
usage4 (_("You must provide a server address"));
else if (server_address[0] != '/' && is_host (server_address) == FALSE)
@ -666,4 +672,3 @@ print_usage (void)
printf ("[-t <timeout seconds>] [-r <refuse state>] [-M <mismatch state>] [-v] [-4|-6] [-j]\n");
printf ("[-D <warn days cert expire>[,<crit days cert expire>]] [-S <use SSL>] [-E]\n");
}

View file

@ -329,7 +329,7 @@ void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", TIME_PORT);
xasprintf (&myport, "%d", TIME_PORT);
print_revision (progname, NP_VERSION);

View file

@ -136,56 +136,56 @@ main (int argc, char **argv)
result = STATE_OK;
if (status & UPSSTATUS_OFF) {
asprintf (&ups_status, "Off");
xasprintf (&ups_status, "Off");
result = STATE_CRITICAL;
}
else if ((status & (UPSSTATUS_OB | UPSSTATUS_LB)) ==
(UPSSTATUS_OB | UPSSTATUS_LB)) {
asprintf (&ups_status, _("On Battery, Low Battery"));
xasprintf (&ups_status, _("On Battery, Low Battery"));
result = STATE_CRITICAL;
}
else {
if (status & UPSSTATUS_OL) {
asprintf (&ups_status, "%s%s", ups_status, _("Online"));
xasprintf (&ups_status, "%s%s", ups_status, _("Online"));
}
if (status & UPSSTATUS_OB) {
asprintf (&ups_status, "%s%s", ups_status, _("On Battery"));
xasprintf (&ups_status, "%s%s", ups_status, _("On Battery"));
result = STATE_WARNING;
}
if (status & UPSSTATUS_LB) {
asprintf (&ups_status, "%s%s", ups_status, _(", Low Battery"));
xasprintf (&ups_status, "%s%s", ups_status, _(", Low Battery"));
result = STATE_WARNING;
}
if (status & UPSSTATUS_CAL) {
asprintf (&ups_status, "%s%s", ups_status, _(", Calibrating"));
xasprintf (&ups_status, "%s%s", ups_status, _(", Calibrating"));
}
if (status & UPSSTATUS_RB) {
asprintf (&ups_status, "%s%s", ups_status, _(", Replace Battery"));
xasprintf (&ups_status, "%s%s", ups_status, _(", Replace Battery"));
result = STATE_WARNING;
}
if (status & UPSSTATUS_BYPASS) {
asprintf (&ups_status, "%s%s", ups_status, _(", On Bypass"));
xasprintf (&ups_status, "%s%s", ups_status, _(", On Bypass"));
}
if (status & UPSSTATUS_OVER) {
asprintf (&ups_status, "%s%s", ups_status, _(", Overload"));
xasprintf (&ups_status, "%s%s", ups_status, _(", Overload"));
}
if (status & UPSSTATUS_TRIM) {
asprintf (&ups_status, "%s%s", ups_status, _(", Trimming"));
xasprintf (&ups_status, "%s%s", ups_status, _(", Trimming"));
}
if (status & UPSSTATUS_BOOST) {
asprintf (&ups_status, "%s%s", ups_status, _(", Boosting"));
xasprintf (&ups_status, "%s%s", ups_status, _(", Boosting"));
}
if (status & UPSSTATUS_CHRG) {
asprintf (&ups_status, "%s%s", ups_status, _(", Charging"));
xasprintf (&ups_status, "%s%s", ups_status, _(", Charging"));
}
if (status & UPSSTATUS_DISCHRG) {
asprintf (&ups_status, "%s%s", ups_status, _(", Discharging"));
xasprintf (&ups_status, "%s%s", ups_status, _(", Discharging"));
}
if (status & UPSSTATUS_UNKOWN) {
asprintf (&ups_status, "%s%s", ups_status, _(", Unknown"));
xasprintf (&ups_status, "%s%s", ups_status, _(", Unknown"));
}
}
asprintf (&message, "%sStatus=%s ", message, ups_status);
xasprintf (&message, "%sStatus=%s ", message, ups_status);
}
/* get the ups utility voltage if possible */
@ -197,7 +197,7 @@ main (int argc, char **argv)
supported_options |= UPS_UTILITY;
ups_utility_voltage = atof (temp_buffer);
asprintf (&message, "%sUtility=%3.1fV ", message, ups_utility_voltage);
xasprintf (&message, "%sUtility=%3.1fV ", message, ups_utility_voltage);
if (ups_utility_voltage > 120.0)
ups_utility_deviation = 120.0 - ups_utility_voltage;
@ -211,13 +211,13 @@ main (int argc, char **argv)
else if (check_warn==TRUE && ups_utility_deviation>=warning_value) {
result = max_state (result, STATE_WARNING);
}
asprintf (&data, "%s",
xasprintf (&data, "%s",
perfdata ("voltage", (long)(1000*ups_utility_voltage), "mV",
check_warn, (long)(1000*warning_value),
check_crit, (long)(1000*critical_value),
TRUE, 0, FALSE, 0));
} else {
asprintf (&data, "%s",
xasprintf (&data, "%s",
perfdata ("voltage", (long)(1000*ups_utility_voltage), "mV",
FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
}
@ -231,7 +231,7 @@ main (int argc, char **argv)
else {
supported_options |= UPS_BATTPCT;
ups_battery_percent = atof (temp_buffer);
asprintf (&message, "%sBatt=%3.1f%% ", message, ups_battery_percent);
xasprintf (&message, "%sBatt=%3.1f%% ", message, ups_battery_percent);
if (check_variable == UPS_BATTPCT) {
if (check_crit==TRUE && ups_battery_percent <= critical_value) {
@ -240,13 +240,13 @@ main (int argc, char **argv)
else if (check_warn==TRUE && ups_battery_percent<=warning_value) {
result = max_state (result, STATE_WARNING);
}
asprintf (&data, "%s %s", data,
xasprintf (&data, "%s %s", data,
perfdata ("battery", (long)ups_battery_percent, "%",
check_warn, (long)(1000*warning_value),
check_crit, (long)(1000*critical_value),
TRUE, 0, TRUE, 100));
} else {
asprintf (&data, "%s %s", data,
xasprintf (&data, "%s %s", data,
perfdata ("battery", (long)ups_battery_percent, "%",
FALSE, 0, FALSE, 0, TRUE, 0, TRUE, 100));
}
@ -260,7 +260,7 @@ main (int argc, char **argv)
else {
supported_options |= UPS_LOADPCT;
ups_load_percent = atof (temp_buffer);
asprintf (&message, "%sLoad=%3.1f%% ", message, ups_load_percent);
xasprintf (&message, "%sLoad=%3.1f%% ", message, ups_load_percent);
if (check_variable == UPS_LOADPCT) {
if (check_crit==TRUE && ups_load_percent>=critical_value) {
@ -269,13 +269,13 @@ main (int argc, char **argv)
else if (check_warn==TRUE && ups_load_percent>=warning_value) {
result = max_state (result, STATE_WARNING);
}
asprintf (&data, "%s %s", data,
xasprintf (&data, "%s %s", data,
perfdata ("load", (long)ups_load_percent, "%",
check_warn, (long)(1000*warning_value),
check_crit, (long)(1000*critical_value),
TRUE, 0, TRUE, 100));
} else {
asprintf (&data, "%s %s", data,
xasprintf (&data, "%s %s", data,
perfdata ("load", (long)ups_load_percent, "%",
FALSE, 0, FALSE, 0, TRUE, 0, TRUE, 100));
}
@ -291,12 +291,12 @@ main (int argc, char **argv)
if (temp_output_c) {
tunits="degC";
ups_temperature = atof (temp_buffer);
asprintf (&message, "%sTemp=%3.1fC", message, ups_temperature);
xasprintf (&message, "%sTemp=%3.1fC", message, ups_temperature);
}
else {
tunits="degF";
ups_temperature = (atof (temp_buffer) * 1.8) + 32;
asprintf (&message, "%sTemp=%3.1fF", message, ups_temperature);
xasprintf (&message, "%sTemp=%3.1fF", message, ups_temperature);
}
if (check_variable == UPS_TEMP) {
@ -306,13 +306,13 @@ main (int argc, char **argv)
else if (check_warn == TRUE && ups_temperature>=warning_value) {
result = max_state (result, STATE_WARNING);
}
asprintf (&data, "%s %s", data,
xasprintf (&data, "%s %s", data,
perfdata ("temp", (long)ups_temperature, tunits,
check_warn, (long)(1000*warning_value),
check_crit, (long)(1000*critical_value),
TRUE, 0, FALSE, 0));
} else {
asprintf (&data, "%s %s", data,
xasprintf (&data, "%s %s", data,
perfdata ("temp", (long)ups_temperature, tunits,
FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
}
@ -321,7 +321,7 @@ main (int argc, char **argv)
/* if the UPS does not support any options we are looking for, report an error */
if (supported_options == UPS_NONE) {
result = STATE_CRITICAL;
asprintf (&message, _("UPS does not support any available options\n"));
xasprintf (&message, _("UPS does not support any available options\n"));
}
/* reset timeout */
@ -595,7 +595,7 @@ void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", PORT);
xasprintf (&myport, "%d", PORT);
print_revision (progname, NP_VERSION);

View file

@ -36,7 +36,12 @@ const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "utils.h"
#include <utmpx.h>
#if HAVE_UTMPX_H
# include <utmpx.h>
#else
# include "popen.h"
#endif
#define possibly_set(a,b) ((a) == 0 ? (b) : 0)
@ -53,7 +58,11 @@ main (int argc, char **argv)
int users = -1;
int result = STATE_UNKNOWN;
char *perf;
#if HAVE_UTMPX_H
struct utmpx *putmpx;
#else
char input_buffer[MAX_INPUT_BUFFER];
#endif
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
@ -69,6 +78,7 @@ main (int argc, char **argv)
users = 0;
#if HAVE_UTMPX_H
/* get currently logged users from utmpx */
setutxent ();
@ -77,6 +87,39 @@ main (int argc, char **argv)
users++;
endutxent ();
#else
/* run the command */
child_process = spopen (WHO_COMMAND);
if (child_process == NULL) {
printf (_("Could not open pipe: %s\n"), WHO_COMMAND);
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"), WHO_COMMAND);
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
/* increment 'users' on all lines except total user count */
if (input_buffer[0] != '#') {
users++;
continue;
}
/* get total logged in users */
if (sscanf (input_buffer, _("# users=%d"), &users) == 1)
break;
}
/* check STDERR */
if (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr))
result = possibly_set (result, STATE_UNKNOWN);
(void) fclose (child_stderr);
/* close the pipe */
if (spclose (child_process))
result = possibly_set (result, STATE_UNKNOWN);
#endif
/* check the user count against warning and critical thresholds */
if (users > cusers)
@ -89,7 +132,7 @@ main (int argc, char **argv)
if (result == STATE_UNKNOWN)
printf ("%s\n", _("Unable to read output"));
else {
asprintf (&perf, "%s", perfdata ("users", users, "",
xasprintf (&perf, "%s", perfdata ("users", users, "",
TRUE, wusers,
TRUE, cusers,
TRUE, 0,

View file

@ -82,10 +82,12 @@
getting that data
Will return -1 if cannot get data
*/
#ifdef HAVE_SYSCONF__SC_NPROCESSORS_CONF
#define GET_NUMBER_OF_CPUS() sysconf(_SC_NPROCESSORS_CONF)
#if defined(HAVE_SYSCONF__SC_NPROCESSORS_ONLN)
# define GET_NUMBER_OF_CPUS() sysconf(_SC_NPROCESSORS_ONLN)
#elif defined (HAVE_SYSCONF__SC_NPROCESSORS_CONF)
# define GET_NUMBER_OF_CPUS() sysconf(_SC_NPROCESSORS_CONF)
#else
#define GET_NUMBER_OF_CPUS() -1
# define GET_NUMBER_OF_CPUS() -1
#endif
#ifdef TIME_WITH_SYS_TIME
@ -115,9 +117,7 @@
#include <getopt.h>
#include "dirname.h"
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
#ifdef HAVE_SYS_POLL_H
# include "sys/poll.h"
@ -141,6 +141,7 @@
#ifdef HAVE_GNUTLS_OPENSSL_H
# include <gnutls/openssl.h>
#else
# define OPENSSL_LOAD_CONF /* See the OPENSSL_config(3) man page. */
# ifdef HAVE_SSL_H
# include <rsa.h>
# include <crypto.h>

View file

@ -104,7 +104,7 @@ main (int argc, char **argv)
*sub = '\0';
sub += strlen (state_text (result));
/* then put everything back together */
asprintf (&chld_out.line[i], "%s%s%s", chld_out.line[i], state_text (state[result]), sub);
xasprintf (&chld_out.line[i], "%s%s%s", chld_out.line[i], state_text (state[result]), sub);
}
}
printf ("%s\n", chld_out.line[i]);

View file

@ -100,6 +100,8 @@ extern int address_family;
/* maybe this could be merged with the above np_net_connect, via some flags */
int np_net_ssl_init(int sd);
int np_net_ssl_init_with_hostname(int sd, char *host_name);
int np_net_ssl_init_with_hostname_and_version(int sd, char *host_name, int version);
int np_net_ssl_init_with_hostname_version_and_cert(int sd, char *host_name, int version, char *cert, char *privkey);
void np_net_ssl_cleanup();
int np_net_ssl_write(const void *buf, int num);
int np_net_ssl_read(void *buf, int num);

View file

@ -256,7 +256,7 @@ np_runcmd_close(int fd)
void
popen_timeout_alarm_handler (int signo)
runcmd_timeout_alarm_handler (int signo)
{
size_t i;

View file

@ -39,7 +39,7 @@ typedef struct output output;
/** prototypes **/
int np_runcmd(const char *, output *, output *, int);
void popen_timeout_alarm_handler(int)
void runcmd_timeout_alarm_handler(int)
__attribute__((__noreturn__));
/* only multi-threaded plugins need to bother with this */

View file

@ -45,6 +45,10 @@ int np_net_ssl_init_with_hostname(int sd, char *host_name) {
}
int np_net_ssl_init_with_hostname_and_version(int sd, char *host_name, int version) {
return np_net_ssl_init_with_hostname_version_and_cert(sd, host_name, version, NULL, NULL);
}
int np_net_ssl_init_with_hostname_version_and_cert(int sd, char *host_name, int version, char *cert, char *privkey) {
const SSL_METHOD *method = NULL;
switch (version) {
@ -80,9 +84,18 @@ int np_net_ssl_init_with_hostname_and_version(int sd, char *host_name, int versi
printf("%s\n", _("CRITICAL - Cannot create SSL context."));
return STATE_CRITICAL;
}
if (cert && privkey) {
SSL_CTX_use_certificate_file(c, cert, SSL_FILETYPE_PEM);
SSL_CTX_use_PrivateKey_file(c, privkey, SSL_FILETYPE_PEM);
if (!SSL_CTX_check_private_key(c)) {
printf ("%s\n", _("CRITICAL - Private key does not seem to match certificate!\n"));
return STATE_CRITICAL;
}
}
#ifdef SSL_OP_NO_TICKET
SSL_CTX_set_options(c, SSL_OP_NO_TICKET);
#endif
SSL_CTX_set_mode(c, SSL_MODE_AUTO_RETRY);
if ((s = SSL_new(c)) != NULL) {
#ifdef SSL_set_tlsext_host_name
if (host_name != NULL)

90
plugins/t/check_apt.t Normal file
View file

@ -0,0 +1,90 @@
#!/usr/bin/perl -w -I ..
#
# Test check_apt using input files.
# Contributed by Alex Bradley, October 2012
#
use strict;
use Test::More;
use NPTest;
sub make_result_regexp {
my ($warning, $critical) = @_;
my $status;
if ($warning == 0 && $critical == 0) {
$status = "OK";
} elsif ($critical == 0) {
$status = "WARNING";
} else {
$status = "CRITICAL";
}
return sprintf('/^APT %s: %d packages available for upgrade \(%d critical updates\)\. |available_upgrades=%d;;;0 critical_updates=%d;;;0$/',
$status, $warning, $critical, $warning, $critical);
}
if (-x "./check_apt") {
plan tests => 28;
} else {
plan skip_all => "No check_apt compiled";
}
my $result;
my $testfile_command = "./check_apt %s --input-file=t/check_apt_input/%s";
$result = NPTest->testCmd( sprintf($testfile_command, "", "debian1") );
is( $result->return_code, 0, "No upgrades" );
like( $result->output, make_result_regexp(0, 0), "Output correct" );
$result = NPTest->testCmd( sprintf($testfile_command, "", "debian2") );
is( $result->return_code, 1, "Debian apt output, warning" );
like( $result->output, make_result_regexp(13, 0), "Output correct" );
$result = NPTest->testCmd( sprintf($testfile_command, "", "debian3") );
is( $result->return_code, 2, "Debian apt output, some critical" );
like( $result->output, make_result_regexp(19, 4), "Output correct" );
$result = NPTest->testCmd( sprintf($testfile_command, "-c '^[^\\(]*\\(.* (Debian-Security:|Ubuntu:[^/]*/[^-]*-security)'", "debian3") );
is( $result->return_code, 2, "Debian apt output - should have same result when default security regexp specified via -c" );
like( $result->output, make_result_regexp(19, 4), "Output correct" );
$result = NPTest->testCmd( sprintf($testfile_command, "-i libc6", "debian3") );
is( $result->return_code, 1, "Debian apt output, filter for libc6" );
like( $result->output, make_result_regexp(3, 0), "Output correct" );
$result = NPTest->testCmd( sprintf($testfile_command, "-i libc6 -i xen", "debian3") );
is( $result->return_code, 2, "Debian apt output, filter for libc6 and xen" );
like( $result->output, make_result_regexp(9, 4), "Output correct" );
$result = NPTest->testCmd( sprintf($testfile_command, "-i libc6 -i xen -i linux", "debian3") );
is( $result->return_code, 2, "Debian apt output, filter for libc6, xen, linux" );
like( $result->output, make_result_regexp(12, 4), "Output correct" );
$result = NPTest->testCmd( sprintf($testfile_command, "-e libc6", "debian3") );
is( $result->return_code, 2, "Debian apt output, filter out libc6" );
like( $result->output, make_result_regexp(16, 4), "Output correct" );
$result = NPTest->testCmd( sprintf($testfile_command, "-e libc6 -e xen", "debian3") );
is( $result->return_code, 1, "Debian apt output, filter out libc6 and xen" );
like( $result->output, make_result_regexp(10, 0), "Output correct" );
$result = NPTest->testCmd( sprintf($testfile_command, "-e libc6 -e xen -e linux", "debian3") );
is( $result->return_code, 1, "Debian apt output, filter out libc6, xen, linux" );
like( $result->output, make_result_regexp(7, 0), "Output correct" );
$result = NPTest->testCmd( sprintf($testfile_command, "-c Debian-Security -c linux", "debian3") );
is( $result->return_code, 2, "Debian apt output, critical on Debian-Security or linux" );
like( $result->output, make_result_regexp(19, 9), "Output correct" );
$result = NPTest->testCmd( sprintf($testfile_command, "-i lib -i linux -e gc1c -c linux-image", "debian3") );
is( $result->return_code, 2, "Debian apt output, include lib and linux, exclude gc1c, critical on linux-image" );
like( $result->output, make_result_regexp(10, 2), "Output correct" );
$result = NPTest->testCmd( sprintf($testfile_command, "", "ubuntu1") );
is( $result->return_code, 1, "Ubuntu apt output, warning" );
like( $result->output, make_result_regexp(5, 0), "Output correct" );
$result = NPTest->testCmd( sprintf($testfile_command, "", "ubuntu2") );
is( $result->return_code, 2, "Ubuntu apt output, some critical" );
like( $result->output, make_result_regexp(25, 14), "Output correct" );

View file

@ -0,0 +1,4 @@
NOTE: This is only a simulation!
apt-get needs root privileges for real execution.
Keep also in mind that locking is deactivated,
so don't depend on the relevance to the real current situation!

View file

@ -0,0 +1,37 @@
NOTE: This is only a simulation!
apt-get needs root privileges for real execution.
Keep also in mind that locking is deactivated,
so don't depend on the relevance to the real current situation!
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be upgraded:
base-files debian-archive-keyring dpkg firmware-linux-free libc-bin libc-dev-bin libc6 libc6-dev linux-base
linux-image-2.6.32-5-xen-amd64 linux-libc-dev locales lockfile-progs
13 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Inst base-files [6.0squeeze5] (6.0squeeze6 Debian:6.0.6/stable [amd64])
Conf base-files (6.0squeeze6 Debian:6.0.6/stable [amd64])
Inst dpkg [1.15.8.12] (1.15.8.13 Debian:6.0.6/stable [amd64])
Conf dpkg (1.15.8.13 Debian:6.0.6/stable [amd64])
Inst linux-base [2.6.32-45] (2.6.32-46 Debian:6.0.6/stable [all])
Inst linux-image-2.6.32-5-xen-amd64 [2.6.32-45] (2.6.32-46 Debian:6.0.6/stable [amd64])
Inst debian-archive-keyring [2010.08.28] (2010.08.28+squeeze1 Debian:6.0.6/stable [all])
Conf debian-archive-keyring (2010.08.28+squeeze1 Debian:6.0.6/stable [all])
Inst libc6-dev [2.11.3-3] (2.11.3-4 Debian:6.0.6/stable [amd64]) []
Inst libc-dev-bin [2.11.3-3] (2.11.3-4 Debian:6.0.6/stable [amd64]) []
Inst linux-libc-dev [2.6.32-45] (2.6.32-46 Debian:6.0.6/stable [amd64]) []
Inst libc-bin [2.11.3-3] (2.11.3-4 Debian:6.0.6/stable [amd64]) [libc6:amd64 ]
Conf libc-bin (2.11.3-4 Debian:6.0.6/stable [amd64]) [libc6:amd64 ]
Inst libc6 [2.11.3-3] (2.11.3-4 Debian:6.0.6/stable [amd64])
Conf libc6 (2.11.3-4 Debian:6.0.6/stable [amd64])
Inst locales [2.11.3-3] (2.11.3-4 Debian:6.0.6/stable [all])
Inst firmware-linux-free [2.6.32-45] (2.6.32-46 Debian:6.0.6/stable [all])
Inst lockfile-progs [0.1.15] (0.1.15+squeeze1 Debian:6.0.6/stable [amd64])
Conf linux-base (2.6.32-46 Debian:6.0.6/stable [all])
Conf linux-image-2.6.32-5-xen-amd64 (2.6.32-46 Debian:6.0.6/stable [amd64])
Conf libc-dev-bin (2.11.3-4 Debian:6.0.6/stable [amd64])
Conf linux-libc-dev (2.6.32-46 Debian:6.0.6/stable [amd64])
Conf libc6-dev (2.11.3-4 Debian:6.0.6/stable [amd64])
Conf locales (2.11.3-4 Debian:6.0.6/stable [all])
Conf firmware-linux-free (2.6.32-46 Debian:6.0.6/stable [all])
Conf lockfile-progs (0.1.15+squeeze1 Debian:6.0.6/stable [amd64])

View file

@ -0,0 +1,42 @@
NOTE: This is only a simulation!
apt-get needs root privileges for real execution.
Keep also in mind that locking is deactivated,
so don't depend on the relevance to the real current situation!
Inst base-files [6.0squeeze5] (6.0squeeze6 Debian:6.0.6/stable [amd64])
Conf base-files (6.0squeeze6 Debian:6.0.6/stable [amd64])
Inst dpkg [1.15.8.12] (1.15.8.13 Debian:6.0.6/stable [amd64])
Conf dpkg (1.15.8.13 Debian:6.0.6/stable [amd64])
Inst linux-base [2.6.32-45] (2.6.32-46 Debian:6.0.6/stable [all])
Inst linux-image-2.6.32-5-amd64 [2.6.32-45] (2.6.32-46 Debian:6.0.6/stable [amd64])
Inst xen-hypervisor-4.0-amd64 [4.0.1-5.3] (4.0.1-5.4 Debian:6.0.6/stable, Debian-Security:6.0/stable [amd64])
Inst xen-linux-system-2.6.32-5-xen-amd64 [2.6.32-45] (2.6.32-46 Debian:6.0.6/stable [amd64]) []
Inst linux-image-2.6.32-5-xen-amd64 [2.6.32-45] (2.6.32-46 Debian:6.0.6/stable [amd64])
Inst debian-archive-keyring [2010.08.28] (2010.08.28+squeeze1 Debian:6.0.6/stable [all])
Conf debian-archive-keyring (2010.08.28+squeeze1 Debian:6.0.6/stable [all])
Inst libc6-i386 [2.11.3-3] (2.11.3-4 Debian:6.0.6/stable [amd64]) []
Inst libc-bin [2.11.3-3] (2.11.3-4 Debian:6.0.6/stable [amd64]) [libc6:amd64 ]
Conf libc-bin (2.11.3-4 Debian:6.0.6/stable [amd64]) [libc6:amd64 ]
Inst libc6 [2.11.3-3] (2.11.3-4 Debian:6.0.6/stable [amd64])
Conf libc6 (2.11.3-4 Debian:6.0.6/stable [amd64])
Inst libgc1c2 [1:6.8-1.2] (1:6.8-2 Debian:6.0.6/stable [amd64])
Inst locales [2.11.3-3] (2.11.3-4 Debian:6.0.6/stable [all])
Inst firmware-linux-free [2.6.32-45] (2.6.32-46 Debian:6.0.6/stable [all])
Inst libxenstore3.0 [4.0.1-5.3] (4.0.1-5.4 Debian:6.0.6/stable, Debian-Security:6.0/stable [amd64])
Inst lockfile-progs [0.1.15] (0.1.15+squeeze1 Debian:6.0.6/stable [amd64])
Inst xen-utils-4.0 [4.0.1-5.3] (4.0.1-5.4 Debian:6.0.6/stable, Debian-Security:6.0/stable [amd64])
Inst xenstore-utils [4.0.1-5.3] (4.0.1-5.4 Debian:6.0.6/stable, Debian-Security:6.0/stable [amd64])
Inst libconfig-inifiles-perl [2.52-1] (2.52-1+squeeze1 Debian:6.0.6/stable [all])
Conf linux-base (2.6.32-46 Debian:6.0.6/stable [all])
Conf linux-image-2.6.32-5-amd64 (2.6.32-46 Debian:6.0.6/stable [amd64])
Conf xen-hypervisor-4.0-amd64 (4.0.1-5.4 Debian:6.0.6/stable, Debian-Security:6.0/stable [amd64])
Conf linux-image-2.6.32-5-xen-amd64 (2.6.32-46 Debian:6.0.6/stable [amd64])
Conf xen-linux-system-2.6.32-5-xen-amd64 (2.6.32-46 Debian:6.0.6/stable [amd64])
Conf libc6-i386 (2.11.3-4 Debian:6.0.6/stable [amd64])
Conf libgc1c2 (1:6.8-2 Debian:6.0.6/stable [amd64])
Conf locales (2.11.3-4 Debian:6.0.6/stable [all])
Conf firmware-linux-free (2.6.32-46 Debian:6.0.6/stable [all])
Conf libxenstore3.0 (4.0.1-5.4 Debian:6.0.6/stable, Debian-Security:6.0/stable [amd64])
Conf lockfile-progs (0.1.15+squeeze1 Debian:6.0.6/stable [amd64])
Conf xen-utils-4.0 (4.0.1-5.4 Debian:6.0.6/stable, Debian-Security:6.0/stable [amd64])
Conf xenstore-utils (4.0.1-5.4 Debian:6.0.6/stable, Debian-Security:6.0/stable [amd64])
Conf libconfig-inifiles-perl (2.52-1+squeeze1 Debian:6.0.6/stable [all])

View file

@ -0,0 +1,14 @@
NOTE: This is only a simulation!
apt-get needs root privileges for real execution.
Also keep in mind that locking is deactivated,
so don't depend on the relevance to the real current situation!
Inst grub-pc [1.99-21ubuntu3.1] (1.99-21ubuntu3.4 Ubuntu:12.04/precise-updates [amd64]) []
Inst grub-pc-bin [1.99-21ubuntu3.1] (1.99-21ubuntu3.4 Ubuntu:12.04/precise-updates [amd64]) []
Inst grub2-common [1.99-21ubuntu3.1] (1.99-21ubuntu3.4 Ubuntu:12.04/precise-updates [amd64]) []
Inst grub-efi-amd64-bin [1.99-21ubuntu3.1] (1.99-21ubuntu3.4 Ubuntu:12.04/precise-updates [amd64]) []
Inst grub-common [1.99-21ubuntu3.1] (1.99-21ubuntu3.4 Ubuntu:12.04/precise-updates [amd64])
Conf grub-common (1.99-21ubuntu3.4 Ubuntu:12.04/precise-updates [amd64])
Conf grub2-common (1.99-21ubuntu3.4 Ubuntu:12.04/precise-updates [amd64])
Conf grub-pc-bin (1.99-21ubuntu3.4 Ubuntu:12.04/precise-updates [amd64])
Conf grub-pc (1.99-21ubuntu3.4 Ubuntu:12.04/precise-updates [amd64])
Conf grub-efi-amd64-bin (1.99-21ubuntu3.4 Ubuntu:12.04/precise-updates [amd64])

View file

@ -0,0 +1,54 @@
NOTE: This is only a simulation!
apt-get needs root privileges for real execution.
Also keep in mind that locking is deactivated,
so don't depend on the relevance to the real current situation!
Inst libc6-dev [2.15-0ubuntu10] (2.15-0ubuntu10.2 Ubuntu:12.04/precise-security [amd64]) []
Inst libc-dev-bin [2.15-0ubuntu10] (2.15-0ubuntu10.2 Ubuntu:12.04/precise-security [amd64]) []
Inst linux-libc-dev [3.2.0-29.46] (3.2.0-31.50 Ubuntu:12.04/precise-security [amd64]) []
Inst tzdata [2012e-0ubuntu0.12.04] (2012e-0ubuntu0.12.04.1 Ubuntu:12.04/precise-security [all]) []
Conf tzdata (2012e-0ubuntu0.12.04.1 Ubuntu:12.04/precise-security [all]) []
Inst libc-bin [2.15-0ubuntu10] (2.15-0ubuntu10.2 Ubuntu:12.04/precise-security [amd64]) [libc6:amd64 ]
Conf libc-bin (2.15-0ubuntu10.2 Ubuntu:12.04/precise-security [amd64]) [libc6:amd64 ]
Inst libc6 [2.15-0ubuntu10] (2.15-0ubuntu10.2 Ubuntu:12.04/precise-security [amd64])
Conf libc6 (2.15-0ubuntu10.2 Ubuntu:12.04/precise-security [amd64])
Inst libapt-pkg4.12 [0.8.16~exp12ubuntu10.2] (0.8.16~exp12ubuntu10.3 Ubuntu:12.04/precise-updates [amd64])
Conf libapt-pkg4.12 (0.8.16~exp12ubuntu10.3 Ubuntu:12.04/precise-updates [amd64])
Inst ubuntu-keyring [2011.11.21] (2011.11.21.1 Ubuntu:12.04/precise-updates [all])
Conf ubuntu-keyring (2011.11.21.1 Ubuntu:12.04/precise-updates [all])
Inst gpgv [1.4.11-3ubuntu2] (1.4.11-3ubuntu2.1 Ubuntu:12.04/precise-security [amd64])
Conf gpgv (1.4.11-3ubuntu2.1 Ubuntu:12.04/precise-security [amd64])
Inst gnupg [1.4.11-3ubuntu2] (1.4.11-3ubuntu2.1 Ubuntu:12.04/precise-security [amd64])
Conf gnupg (1.4.11-3ubuntu2.1 Ubuntu:12.04/precise-security [amd64])
Inst apt [0.8.16~exp12ubuntu10.2] (0.8.16~exp12ubuntu10.3 Ubuntu:12.04/precise-updates [amd64])
Conf apt (0.8.16~exp12ubuntu10.3 Ubuntu:12.04/precise-updates [amd64])
Inst libssl1.0.0 [1.0.1-4ubuntu5.3] (1.0.1-4ubuntu5.5 Ubuntu:12.04/precise-updates [amd64])
Conf libssl1.0.0 (1.0.1-4ubuntu5.5 Ubuntu:12.04/precise-updates [amd64])
Inst libapt-inst1.4 [0.8.16~exp12ubuntu10.2] (0.8.16~exp12ubuntu10.3 Ubuntu:12.04/precise-updates [amd64])
Inst resolvconf [1.63ubuntu15] (1.63ubuntu16 Ubuntu:12.04/precise-updates [all])
Inst libdbus-1-3 [1.4.18-1ubuntu1] (1.4.18-1ubuntu1.1 Ubuntu:12.04/precise-security [amd64])
Inst libxml2 [2.7.8.dfsg-5.1ubuntu4.1] (2.7.8.dfsg-5.1ubuntu4.2 Ubuntu:12.04/precise-security [amd64])
Inst multiarch-support [2.15-0ubuntu10] (2.15-0ubuntu10.2 Ubuntu:12.04/precise-security [amd64])
Conf multiarch-support (2.15-0ubuntu10.2 Ubuntu:12.04/precise-security [amd64])
Inst apt-utils [0.8.16~exp12ubuntu10.2] (0.8.16~exp12ubuntu10.3 Ubuntu:12.04/precise-updates [amd64])
Inst isc-dhcp-client [4.1.ESV-R4-0ubuntu5.2] (4.1.ESV-R4-0ubuntu5.5 Ubuntu:12.04/precise-security [amd64]) []
Inst isc-dhcp-common [4.1.ESV-R4-0ubuntu5.2] (4.1.ESV-R4-0ubuntu5.5 Ubuntu:12.04/precise-security [amd64])
Inst dbus [1.4.18-1ubuntu1] (1.4.18-1ubuntu1.1 Ubuntu:12.04/precise-security [amd64])
Inst linux-firmware [1.79] (1.79.1 Ubuntu:12.04/precise-updates [all])
Inst xserver-common [2:1.11.4-0ubuntu10.7] (2:1.11.4-0ubuntu10.8 Ubuntu:12.04/precise-updates [all])
Inst xserver-xorg-core [2:1.11.4-0ubuntu10.7] (2:1.11.4-0ubuntu10.8 Ubuntu:12.04/precise-updates [amd64])
Inst xserver-xorg-input-synaptics [1.6.2-1ubuntu1~precise1] (1.6.2-1ubuntu1~precise2 Ubuntu:12.04/precise-updates [amd64])
Conf libc-dev-bin (2.15-0ubuntu10.2 Ubuntu:12.04/precise-security [amd64])
Conf linux-libc-dev (3.2.0-31.50 Ubuntu:12.04/precise-security [amd64])
Conf libc6-dev (2.15-0ubuntu10.2 Ubuntu:12.04/precise-security [amd64])
Conf libapt-inst1.4 (0.8.16~exp12ubuntu10.3 Ubuntu:12.04/precise-updates [amd64])
Conf resolvconf (1.63ubuntu16 Ubuntu:12.04/precise-updates [all])
Conf libdbus-1-3 (1.4.18-1ubuntu1.1 Ubuntu:12.04/precise-security [amd64])
Conf libxml2 (2.7.8.dfsg-5.1ubuntu4.2 Ubuntu:12.04/precise-security [amd64])
Conf apt-utils (0.8.16~exp12ubuntu10.3 Ubuntu:12.04/precise-updates [amd64])
Conf isc-dhcp-common (4.1.ESV-R4-0ubuntu5.5 Ubuntu:12.04/precise-security [amd64])
Conf isc-dhcp-client (4.1.ESV-R4-0ubuntu5.5 Ubuntu:12.04/precise-security [amd64])
Conf dbus (1.4.18-1ubuntu1.1 Ubuntu:12.04/precise-security [amd64])
Conf linux-firmware (1.79.1 Ubuntu:12.04/precise-updates [all])
Conf xserver-common (2:1.11.4-0ubuntu10.8 Ubuntu:12.04/precise-updates [all])
Conf xserver-xorg-core (2:1.11.4-0ubuntu10.8 Ubuntu:12.04/precise-updates [amd64])
Conf xserver-xorg-input-synaptics (1.6.2-1ubuntu1~precise2 Ubuntu:12.04/precise-updates [amd64])

103
plugins/t/check_dbi.t Normal file
View file

@ -0,0 +1,103 @@
#! /usr/bin/perl -w -I ..
#
# Database Server Tests via check_dbi
#
#
# Uses the 'sqlite3' DBD driver and command line utility.
use strict;
use Test::More;
use NPTest;
use File::Temp;
use vars qw($tests);
plan skip_all => "check_dbi not compiled" unless (-x "check_dbi");
$tests = 20;
plan tests => $tests;
my $missing_driver_output = "failed to open DBI driver 'sqlite3'";
my $bad_driver_output = "/failed to open DBI driver 'nodriver'/";
my $conn_time_output = "/OK - connection time: [0-9\.]+s \|/";
my $missing_query_output = "/Must specify a query to execute/";
my $no_rows_output = "/WARNING - no rows returned/";
my $not_numeric_output = "/CRITICAL - result value is not a numeric:/";
my $query_time_output = "/OK - connection time: [0-9\.]+s, 'SELECT 1' returned 1.000000 in [0-9\.]+s \|/";
my $syntax_error_output = "/CRITICAL - failed to execute query 'GET ALL FROM test': 1: near \"GET\": syntax error/";
my $result;
SKIP: {
my $sqlite3 = qx(which sqlite3 2> /dev/null);
chomp($sqlite3);
skip "No Sqlite3 found", $tests unless $sqlite3;
my $sqlite3_check = qx(./check_dbi -d sqlite3 -q '');
if ($sqlite3_check =~ m/$missing_driver_output/) {
skip "No 'sqlite3' DBD driver found", $tests;
}
my $fh = File::Temp->new(
TEMPLATE => "/tmp/check_dbi_sqlite3.XXXXXXX",
UNLINK => 1,
);
my $filename = $fh->filename;
$filename =~ s/^\/tmp\///;
system("$sqlite3 /tmp/$filename 'CREATE TABLE test(a INT, b TEXT)'");
system("$sqlite3 /tmp/$filename 'INSERT INTO test VALUES (1, \"text1\")'");
system("$sqlite3 /tmp/$filename 'INSERT INTO test VALUES (2, \"text2\")'");
my $check_cmd = "./check_dbi -d sqlite3 -o sqlite3_dbdir=/tmp -o dbname=$filename";
$result = NPTest->testCmd("$check_cmd -q 'SELECT 1'");
cmp_ok($result->return_code, '==', 0, "Sqlite3 login okay and can run query");
$result = NPTest->testCmd("$check_cmd");
cmp_ok($result->return_code, '==', 3, "Missing query parameter");
like($result->output, $missing_query_output, "Missing query parameter error message");
$result = NPTest->testCmd("$check_cmd -q 'GET ALL FROM test'");
cmp_ok($result->return_code, '==', 2, "Invalid query");
like($result->output, $syntax_error_output, "Syntax error message");
$result = NPTest->testCmd("$check_cmd -q 'SELECT 2.71828' -w 2 -c 3");
cmp_ok($result->return_code, '==', 1, "Got warning");
$result = NPTest->testCmd("$check_cmd -q 'SELECT 3.1415' -w 2 -c 3");
cmp_ok($result->return_code, '==', 2, "Got critical");
$result = NPTest->testCmd("$check_cmd -q ''");
cmp_ok($result->return_code, '==', 1, "No rows returned");
like($result->output, $no_rows_output, "Now rows returned warning message");
$result = NPTest->testCmd("$check_cmd -q 'SELECT b FROM test'");
cmp_ok($result->return_code, '==', 2, "Value is not a numeric");
like($result->output, $not_numeric_output, "Value is not a numeric error message");
$result = NPTest->testCmd("$check_cmd -m QUERY_RESULT -q 'SELECT b FROM test' -e text1");
cmp_ok($result->return_code, '==', 0, "Query result string comparison okay");
$result = NPTest->testCmd("$check_cmd -q 'SELECT b FROM test' -r 'eXt[0-9]'");
cmp_ok($result->return_code, '==', 2, "Query result case-insensitive regex failure");
$result = NPTest->testCmd("$check_cmd -q 'SELECT b FROM test' -R 'eXt[0-9]'");
cmp_ok($result->return_code, '==', 0, "Query result case-sensitive regex okay");
$result = NPTest->testCmd("$check_cmd -m CONN_TIME -w 0.5 -c 0.7");
cmp_ok($result->return_code, '==', 0, "CONN_TIME metric okay");
like($result->output, $conn_time_output, "CONN_TIME metric output okay");
$result = NPTest->testCmd("$check_cmd -m QUERY_TIME -q 'SELECT 1'");
cmp_ok($result->return_code, '==', 0, "QUERY_TIME metric okay");
like($result->output, $query_time_output, "QUERY_TIME metric output okay");
$result = NPTest->testCmd("./check_dbi -d nodriver -q ''");
cmp_ok($result->return_code, '==', 3, "Unknown DBI driver");
like($result->output, $bad_driver_output, "Correct error message");
}

View file

@ -10,30 +10,30 @@ use NPTest;
plan skip_all => "check_dig not compiled" unless (-x "check_dig");
plan tests => 12;
plan tests => 16;
my $successOutput = '/DNS OK - [\.0-9]+ seconds? response time/';
my $hostname_valid = getTestParameter(
my $hostname_valid = getTestParameter(
"NP_HOSTNAME_VALID",
"A valid (known to DNS) hostname",
"nagios.com"
"nagiosplugins.org"
);
my $hostname_valid_ip = getTestParameter(
"NP_HOSTNAME_VALID_IP",
"The IP address of the valid hostname $hostname_valid",
"66.118.156.50",
"67.207.143.200",
);
my $hostname_valid_reverse = getTestParameter(
"NP_HOSTNAME_VALID_REVERSE",
"The hostname of $hostname_valid_ip",
"66-118-156-50.static.sagonet.net.",
"nagiosplugins.org.",
);
my $hostname_invalid = getTestParameter(
"NP_HOSTNAME_INVALID",
my $hostname_invalid = getTestParameter(
"NP_HOSTNAME_INVALID",
"An invalid (not known to DNS) hostname",
"nosuchhost.altinity.com",
);
@ -69,6 +69,14 @@ SKIP: {
cmp_ok( $res->return_code, '==', 0, "Found $hostname_valid on $dns_server");
like ( $res->output, $successOutput, "Output OK" );
$res = NPTest->testCmd("./check_dig -H $dns_server -l $hostname_valid -t 5 -4");
cmp_ok( $res->return_code, '==', 0, "Found $hostname_valid on $dns_server");
like ( $res->output, $successOutput, "Output OK for IPv4" );
$res = NPTest->testCmd("./check_dig -H $dns_server -l $hostname_valid -t 5 -6");
cmp_ok( $res->return_code, '==', 0, "Found $hostname_valid on $dns_server");
like ( $res->output, $successOutput, "Output OK for IPv6" );
$res = NPTest->testCmd("./check_dig -H $dns_server -l $hostname_valid -a $hostname_valid_ip -t 5");
cmp_ok( $res->return_code, '==', 0, "Got expected address");

View file

@ -8,22 +8,22 @@ use strict;
use Test::More;
use NPTest;
plan tests => 28;
plan tests => 30;
my $successOutput = '/OK.*HTTP.*second/';
my $res;
my $host_tcp_http = getTestParameter( "NP_HOST_TCP_HTTP",
"A host providing the HTTP Service (a web server)",
my $host_tcp_http = getTestParameter( "NP_HOST_TCP_HTTP",
"A host providing the HTTP Service (a web server)",
"localhost" );
my $host_nonresponsive = getTestParameter( "NP_HOST_NONRESPONSIVE",
my $host_nonresponsive = getTestParameter( "NP_HOST_NONRESPONSIVE",
"The hostname of system not responsive to network requests",
"10.0.0.1" );
my $hostname_invalid = getTestParameter( "NP_HOSTNAME_INVALID",
"An invalid (not known to DNS) hostname",
my $hostname_invalid = getTestParameter( "NP_HOSTNAME_INVALID",
"An invalid (not known to DNS) hostname",
"nosuchhost");
my $internet_access = getTestParameter( "NP_INTERNET_ACCESS",
@ -32,8 +32,8 @@ my $internet_access = getTestParameter( "NP_INTERNET_ACCESS",
my $host_tcp_http2;
if ($internet_access eq "no") {
$host_tcp_http2 = getTestParameter( "NP_HOST_TCP_HTTP2",
"A host providing an index page containing the string 'nagios'",
$host_tcp_http2 = getTestParameter( "NP_HOST_TCP_HTTP2",
"A host providing an index page containing the string 'nagios'",
"www.nagios.com" );
}
@ -45,14 +45,9 @@ cmp_ok( $res->return_code, '==', 0, "Webserver $host_tcp_http responded" );
like( $res->output, $successOutput, "Output OK" );
$res = NPTest->testCmd(
"./check_http $host_tcp_http -wt 300 -ct 600 -v -v -v -k 'bob:there;fred:here'"
"./check_http $host_tcp_http -wt 300 -ct 600 -v -v -v -k 'bob:there' -k 'carl:frown'"
);
like( $res->output, '/bob:there\r\nfred:here\r\n/', "Got headers, delimited with ';'" );
$res = NPTest->testCmd(
"./check_http $host_tcp_http -wt 300 -ct 600 -v -v -v -k 'bob:there;fred:here' -k 'carl:frown'"
);
like( $res->output, '/bob:there\r\nfred:here\r\ncarl:frown\r\n/', "Got headers with multiple -k options" );
like( $res->output, '/bob:there\r\ncarl:frown\r\n/', "Got headers with multiple -k options" );
$res = NPTest->testCmd(
"./check_http $host_nonresponsive -wt 1 -ct 2"
@ -123,6 +118,10 @@ SKIP: {
$res = NPTest->testCmd( "./check_http www.verisign.com -C 1" );
cmp_ok( $res->output, 'eq', $saved_cert_output, "Old syntax for cert checking still works");
$res = NPTest->testCmd( "./check_http --ssl www.verisign.com -E" );
like ( $res->output, '/time_connect=[\d\.]+/', 'Extended Performance Data Output OK' );
like ( $res->output, '/time_ssl=[\d\.]+/', 'Extended Performance Data SSL Output OK' );
$res = NPTest->testCmd(
"./check_http --ssl www.e-paycobalt.com"
);
@ -131,4 +130,7 @@ SKIP: {
$res = NPTest->testCmd( "./check_http -H www.mozilla.com -u /firefox -f follow" );
is( $res->return_code, 0, "Redirection based on location is okay");
$res = NPTest->testCmd( "./check_http -H www.mozilla.com --extended-perfdata" );
like ( $res->output, '/time_connect=[\d\.]+/', 'Extended Performance Data Output OK' );
}

View file

@ -20,7 +20,7 @@ my $result;
$result = NPTest->testCmd( "./check_procs -w 100000 -c 100000" );
is( $result->return_code, 0, "Checking less than 10000 processes" );
like( $result->output, '/^PROCS OK: [0-9]+ process(es)?$/', "Output correct" );
like( $result->output, '/^PROCS OK: [0-9]+ process(es)? | procs=[0-9]+;100000;100000;0;$/', "Output correct" );
$result = NPTest->testCmd( "./check_procs -w 100000 -c 100000 -s Z" );
is( $result->return_code, 0, "Checking less than 100000 zombie processes" );
@ -28,11 +28,11 @@ like( $result->output, '/^PROCS OK: [0-9]+ process(es)? with /', "Output correct
$result = NPTest->testCmd( "./check_procs -w 0 -c 100000" );
is( $result->return_code, 1, "Checking warning if processes > 0" );
like( $result->output, '/^PROCS WARNING: [0-9]+ process(es)?$/', "Output correct" );
like( $result->output, '/^PROCS WARNING: [0-9]+ process(es)? | procs=[0-9]+;0;100000;0;$/', "Output correct" );
$result = NPTest->testCmd( "./check_procs -w 0 -c 0" );
is( $result->return_code, 2, "Checking critical if processes > 0" );
like( $result->output, '/^PROCS CRITICAL: [0-9]+ process(es)?$/', "Output correct" );
like( $result->output, '/^PROCS CRITICAL: [0-9]+ process(es)? | procs=[0-9]+;0;0;0;$/', "Output correct" );
$result = NPTest->testCmd( "./check_procs -w 0 -c 0 -s S" );
is( $result->return_code, 2, "Checking critical if sleeping processes" );

View file

@ -8,145 +8,164 @@ use strict;
use Test::More;
use NPTest;
my $tests = 8+42+2+2;
plan tests => $tests;
BEGIN {
plan skip_all => 'check_snmp is not compiled' unless -x "./check_snmp";
plan tests => 60;
}
my $res;
my $host_snmp = getTestParameter( "host_snmp", "NP_HOST_SNMP", "localhost",
"A host providing an SNMP Service");
my $snmp_community = getTestParameter( "snmp_community", "NP_SNMP_COMMUNITY", "public",
"The SNMP Community string for SNMP Testing (assumes snmp v1)" );
my $host_nonresponsive = getTestParameter( "host_nonresponsive", "NP_HOST_NONRESPONSIVE", "10.0.0.1",
"The hostname of system not responsive to network requests" );
my $hostname_invalid = getTestParameter( "hostname_invalid", "NP_HOSTNAME_INVALID", "nosuchhost",
"An invalid (not known to DNS) hostname" );
$res = NPTest->testCmd( "./check_snmp -t 1" );
is( $res->return_code, 3, "No host name" );
is( $res->output, "No host specified" );
$res = NPTest->testCmd( "./check_snmp -H fakehostname" );
is( $res->return_code, 3, "No OIDs specified" );
is( $res->output, "No OIDs specified" );
$res = NPTest->testCmd( "./check_snmp -H fakehost -o oids -P 3 --seclevel=rubbish" );
is( $res->return_code, 3, "Invalid seclevel" );
like( $res->output, "/check_snmp: Invalid seclevel - rubbish/" );
$res = NPTest->testCmd( "./check_snmp -H fakehost -o oids -P 3c" );
is( $res->return_code, 3, "Invalid protocol" );
like( $res->output, "/check_snmp: Invalid SNMP version - 3c/" );
SKIP: {
skip "check_snmp is not compiled", $tests if ( ! -x "./check_snmp" );
skip "no snmp host defined", 38 if ( ! $host_snmp );
my $host_snmp = getTestParameter( "host_snmp", "NP_HOST_SNMP", "localhost",
"A host providing an SNMP Service");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0 -w 1: -c 1:");
cmp_ok( $res->return_code, '==', 0, "Exit OK when querying uptime" );
like($res->output, '/^SNMP OK - (\d+)/', "String contains SNMP OK");
$res->output =~ /^SNMP OK - (\d+)/;
my $value = $1;
cmp_ok( $value, ">", 0, "Got a time value" );
like($res->perf_output, "/sysUpTime.*$1/", "Got perfdata with value '$1' in it");
my $snmp_community = getTestParameter( "snmp_community", "NP_SNMP_COMMUNITY", "public",
"The SNMP Community string for SNMP Testing (assumes snmp v1)" );
my $host_nonresponsive = getTestParameter( "host_nonresponsive", "NP_HOST_NONRESPONSIVE", "10.0.0.1",
"The hostname of system not responsive to network requests" );
# some more threshold tests
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0 -c 1");
cmp_ok( $res->return_code, '==', 2, "Threshold test -c 1" );
my $hostname_invalid = getTestParameter( "hostname_invalid", "NP_HOSTNAME_INVALID", "nosuchhost",
"An invalid (not known to DNS) hostname" );
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0 -c 1:");
cmp_ok( $res->return_code, '==', 0, "Threshold test -c 1:" );
$res = NPTest->testCmd( "./check_snmp -t 1" );
is( $res->return_code, 3, "No host name" );
is( $res->output, "No host specified" );
$res = NPTest->testCmd( "./check_snmp -H fakehostname" );
is( $res->return_code, 3, "No OIDs specified" );
is( $res->output, "No OIDs specified" );
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0 -c ~:1");
cmp_ok( $res->return_code, '==', 2, "Threshold test -c ~:1" );
$res = NPTest->testCmd( "./check_snmp -H fakehost -o oids -P 3 --seclevel=rubbish" );
is( $res->return_code, 3, "Invalid seclevel" );
like( $res->output, "/check_snmp: Invalid seclevel - rubbish/" );
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0 -c 1:10");
cmp_ok( $res->return_code, '==', 2, "Threshold test -c 1:10" );
$res = NPTest->testCmd( "./check_snmp -H fakehost -o oids -P 3c" );
is( $res->return_code, 3, "Invalid protocol" );
like( $res->output, "/check_snmp: Invalid SNMP version - 3c/" );
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0 -c \@1:10");
cmp_ok( $res->return_code, '==', 0, "Threshold test -c \@1:10" );
SKIP: {
skip "no snmp host defined", 38 if ( ! $host_snmp );
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0 -c 10:1");
cmp_ok( $res->return_code, '==', 0, "Threshold test -c 10:1" );
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0 -w 1: -c 1:");
cmp_ok( $res->return_code, '==', 0, "Exit OK when querying uptime" );
like($res->output, '/^SNMP OK - (\d+)/', "String contains SNMP OK");
$res->output =~ /^SNMP OK - (\d+)/;
my $value = $1;
cmp_ok( $value, ">", 0, "Got a time value" );
like($res->perf_output, "/sysUpTime.*$1/", "Got perfdata with value '$1' in it");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o .1.3.6.1.2.1.1.3.0 -w 1: -c 1:");
cmp_ok( $res->return_code, '==', 0, "Test with numeric OID (no mibs loaded)" );
like($res->output, '/^SNMP OK - \d+/', "String contains SNMP OK");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o .1.3.6.1.2.1.1.3.0 -w 1: -c 1:");
cmp_ok( $res->return_code, '==', 0, "Test with numeric OID (no mibs loaded)" );
like($res->output, '/^SNMP OK - \d+/', "String contains SNMP OK");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysDescr.0");
cmp_ok( $res->return_code, '==', 0, "Exit OK when querying sysDescr" );
unlike($res->perf_output, '/sysDescr/', "Perfdata doesn't contain string values");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysDescr.0");
cmp_ok( $res->return_code, '==', 0, "Exit OK when querying sysDescr" );
unlike($res->perf_output, '/sysDescr/', "Perfdata doesn't contain string values");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysDescr.0,system.sysDescr.0");
cmp_ok( $res->return_code, '==', 0, "Exit OK when querying two string OIDs, comma-separated" );
like($res->output, '/^SNMP OK - /', "String contains SNMP OK");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysDescr.0,system.sysDescr.0");
cmp_ok( $res->return_code, '==', 0, "Exit OK when querying two string OIDs, comma-separated" );
like($res->output, '/^SNMP OK - /', "String contains SNMP OK");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysDescr.0 -o system.sysDescr.0");
cmp_ok( $res->return_code, '==', 0, "Exit OK when querying two string OIDs, repeated option" );
like($res->output, '/^SNMP OK - /', "String contains SNMP OK");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysDescr.0 -o system.sysDescr.0");
cmp_ok( $res->return_code, '==', 0, "Exit OK when querying two string OIDs, repeated option" );
like($res->output, '/^SNMP OK - /', "String contains SNMP OK");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrSWRun.hrSWRunTable.hrSWRunEntry.hrSWRunIndex.1 -w 1:1 -c 1:1");
cmp_ok( $res->return_code, '==', 0, "Exit OK when querying hrSWRunIndex.1" );
like($res->output, '/^SNMP OK - 1\s.*$/', "String fits SNMP OK and output format");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrSWRun.hrSWRunTable.hrSWRunEntry.hrSWRunIndex.1 -w 1:1 -c 1:1");
cmp_ok( $res->return_code, '==', 0, "Exit OK when querying hrSWRunIndex.1" );
like($res->output, '/^SNMP OK - 1\s.*$/', "String fits SNMP OK and output format");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrSWRun.hrSWRunTable.hrSWRunEntry.hrSWRunIndex.1 -w 0 -c 1:");
cmp_ok( $res->return_code, '==', 1, "Exit WARNING when querying hrSWRunIndex.1 and warn-th doesn't apply " );
like($res->output, '/^SNMP WARNING - \*1\*\s.*$/', "String matches SNMP WARNING and output format");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrSWRun.hrSWRunTable.hrSWRunEntry.hrSWRunIndex.1 -w 0 -c 1:");
cmp_ok( $res->return_code, '==', 1, "Exit WARNING when querying hrSWRunIndex.1 and warn-th doesn't apply " );
like($res->output, '/^SNMP WARNING - \*1\*\s.*$/', "String matches SNMP WARNING and output format");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrSWRun.hrSWRunTable.hrSWRunEntry.hrSWRunIndex.1 -w :0 -c 0");
cmp_ok( $res->return_code, '==', 2, "Exit CRITICAL when querying hrSWRunIndex.1 and crit-th doesn't apply" );
like($res->output, '/^SNMP CRITICAL - \*1\*\s.*$/', "String matches SNMP CRITICAL and output format");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrSWRun.hrSWRunTable.hrSWRunEntry.hrSWRunIndex.1 -w :0 -c 0");
cmp_ok( $res->return_code, '==', 2, "Exit CRITICAL when querying hrSWRunIndex.1 and crit-th doesn't apply" );
like($res->output, '/^SNMP CRITICAL - \*1\*\s.*$/', "String matches SNMP CRITICAL and output format");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o ifIndex.2,ifIndex.1 -w 1:2 -c 1:2");
cmp_ok( $res->return_code, '==', 0, "Checking two OIDs at once" );
like($res->output, "/^SNMP OK - 2 1/", "Got two values back" );
like( $res->perf_output, "/ifIndex.2=2/", "Got 1st perf data" );
like( $res->perf_output, "/ifIndex.1=1/", "Got 2nd perf data" );
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o ifIndex.2,ifIndex.1 -w 1:2 -c 1:2");
cmp_ok( $res->return_code, '==', 0, "Checking two OIDs at once" );
like($res->output, "/^SNMP OK - 2 1/", "Got two values back" );
like( $res->perf_output, "/ifIndex.2=2/", "Got 1st perf data" );
like( $res->perf_output, "/ifIndex.1=1/", "Got 2nd perf data" );
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o ifIndex.2,ifIndex.1 -w 1:2,1:2 -c 2:2,2:2");
cmp_ok( $res->return_code, '==', 2, "Checking critical threshold is passed if any one value crosses" );
like($res->output, "/^SNMP CRITICAL - 2 *1*/", "Got two values back" );
like( $res->perf_output, "/ifIndex.2=2/", "Got 1st perf data" );
like( $res->perf_output, "/ifIndex.1=1/", "Got 2nd perf data" );
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o ifIndex.2,ifIndex.1 -w 1:2,1:2 -c 2:2,2:2");
cmp_ok( $res->return_code, '==', 2, "Checking critical threshold is passed if any one value crosses" );
like($res->output, "/^SNMP CRITICAL - 2 *1*/", "Got two values back" );
like( $res->perf_output, "/ifIndex.2=2/", "Got 1st perf data" );
like( $res->perf_output, "/ifIndex.1=1/", "Got 2nd perf data" );
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrStorage.hrMemorySize.0,host.hrSystem.hrSystemProcesses.0 -w 1:,1: -c 1:,1:");
cmp_ok( $res->return_code, '==', 0, "Exit OK when querying hrMemorySize and hrSystemProcesses");
like($res->output, '/^SNMP OK - \d+ \d+/', "String contains hrMemorySize and hrSystemProcesses");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrStorage.hrMemorySize.0,host.hrSystem.hrSystemProcesses.0 -w 1:,1: -c 1:,1:");
cmp_ok( $res->return_code, '==', 0, "Exit OK when querying hrMemorySize and hrSystemProcesses");
like($res->output, '/^SNMP OK - \d+ \d+/', "String contains hrMemorySize and hrSystemProcesses");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrSWRun.hrSWRunTable.hrSWRunEntry.hrSWRunIndex.1 -w \@:0 -c \@0");
cmp_ok( $res->return_code, '==', 0, "Exit OK with inside-range thresholds");
like($res->output, '/^SNMP OK - 1\s.*$/', "String matches SNMP OK and output format");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrSWRun.hrSWRunTable.hrSWRunEntry.hrSWRunIndex.1 -w \@:0 -c \@0");
cmp_ok( $res->return_code, '==', 0, "Exit OK with inside-range thresholds");
like($res->output, '/^SNMP OK - 1\s.*$/', "String matches SNMP OK and output format");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o enterprises.ucdavis.laTable.laEntry.laLoad.3");
$res->output =~ m/^SNMP OK - (\d+\.\d{2})\s.*$/;
my $lower = $1 - 0.05;
my $higher = $1 + 0.05;
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o enterprises.ucdavis.laTable.laEntry.laLoad.3 -w $lower -c $higher");
cmp_ok( $res->return_code, '==', 1, "Exit WARNING with fractionnal arguments");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o enterprises.ucdavis.laTable.laEntry.laLoad.3");
$res->output =~ m/^SNMP OK - (\d+\.\d{2})\s.*$/;
my $lower = $1 - 0.05;
my $higher = $1 + 0.05;
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o enterprises.ucdavis.laTable.laEntry.laLoad.3 -w $lower -c $higher");
cmp_ok( $res->return_code, '==', 1, "Exit WARNING with fractionnal arguments");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0,host.hrSWRun.hrSWRunTable.hrSWRunEntry.hrSWRunIndex.1 -w ,:0 -c ,:2");
cmp_ok( $res->return_code, '==', 1, "Exit WARNING on 2nd threshold");
like($res->output, '/^SNMP WARNING - Timeticks:\s\(\d+\)\s+(?:\d+ days?,\s+)?\d+:\d+:\d+\.\d+\s+\*1\*\s.*$/', "First OID returned as string, 2nd checked for thresholds");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0,host.hrSWRun.hrSWRunTable.hrSWRunEntry.hrSWRunIndex.1 -w ,:0 -c ,:2");
cmp_ok( $res->return_code, '==', 1, "Exit WARNING on 2nd threshold");
like($res->output, '/^SNMP WARNING - Timeticks:\s\(\d+\)\s+(?:\d+ days?,\s+)?\d+:\d+:\d+\.\d+\s+\*1\*\s.*$/', "First OID returned as string, 2nd checked for thresholds");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrSWRun.hrSWRunTable.hrSWRunEntry.hrSWRunIndex.1 -w '' -c ''");
cmp_ok( $res->return_code, '==', 0, "Empty thresholds doesn't crash");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrSWRun.hrSWRunTable.hrSWRunEntry.hrSWRunIndex.1 -w '' -c ''");
cmp_ok( $res->return_code, '==', 0, "Empty thresholds doesn't crash");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrStorage.hrMemorySize.0,host.hrSystem.hrSystemProcesses.0 -w ,,1 -c ,,2");
cmp_ok( $res->return_code, '==', 0, "Skipping first two thresholds on 2 OID check");
like($res->output, '/^SNMP OK - \d+ \w+ \d+\s.*$/', "Skipping first two thresholds, result printed rather than parsed");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrStorage.hrMemorySize.0,host.hrSystem.hrSystemProcesses.0 -w ,,1 -c ,,2");
cmp_ok( $res->return_code, '==', 0, "Skipping first two thresholds on 2 OID check");
like($res->output, '/^SNMP OK - \d+ \w+ \d+\s.*$/', "Skipping first two thresholds, result printed rather than parsed");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrStorage.hrMemorySize.0,host.hrSystem.hrSystemProcesses.0 -w ,, -c ,,");
cmp_ok( $res->return_code, '==', 0, "Skipping all thresholds");
like($res->output, '/^SNMP OK - \d+ \w+ \d+\s.*$/', "Skipping all thresholds, result printed rather than parsed");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrStorage.hrMemorySize.0,host.hrSystem.hrSystemProcesses.0 -w ,, -c ,,");
cmp_ok( $res->return_code, '==', 0, "Skipping all thresholds");
like($res->output, '/^SNMP OK - \d+ \w+ \d+\s.*$/', "Skipping all thresholds, result printed rather than parsed");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0 -c 1000000000000: -u '1/100 sec'");
cmp_ok( $res->return_code, '==', 2, "Timetick used as a threshold");
like($res->output, '/^SNMP CRITICAL - \*\d+\* 1\/100 sec.*$/', "Timetick used as a threshold, parsed as numeric");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0");
cmp_ok( $res->return_code, '==', 0, "Timetick used as a string");
like($res->output, '/^SNMP OK - Timeticks:\s\(\d+\)\s+(?:\d+ days?,\s+)?\d+:\d+:\d+\.\d+\s.*$/', "Timetick used as a string, result printed rather than parsed");
}
# These checks need a complete command line. An invalid community is used so
# the tests can run on hosts w/o snmp host/community in NPTest.cache. Execution will fail anyway
SKIP: {
skip "no non responsive host defined", 2 if ( ! $host_nonresponsive );
$res = NPTest->testCmd( "./check_snmp -H $host_nonresponsive -C np_foobar -o system.sysUpTime.0 -w 1: -c 1:");
cmp_ok( $res->return_code, '==', 3, "Exit UNKNOWN with non responsive host" );
like($res->output, '/External command error: Timeout: No Response from /', "String matches timeout problem");
}
SKIP: {
skip "no non invalid host defined", 2 if ( ! $hostname_invalid );
$res = NPTest->testCmd( "./check_snmp -H $hostname_invalid -C np_foobar -o system.sysUpTime.0 -w 1: -c 1:");
cmp_ok( $res->return_code, '==', 3, "Exit UNKNOWN with non responsive host" );
like($res->output, '/External command error: .*(nosuchhost|Name or service not known|Unknown host)/', "String matches invalid host");
}
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0 -c 1000000000000: -u '1/100 sec'");
cmp_ok( $res->return_code, '==', 2, "Timetick used as a threshold");
like($res->output, '/^SNMP CRITICAL - \*\d+\* 1\/100 sec.*$/', "Timetick used as a threshold, parsed as numeric");
$res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0");
cmp_ok( $res->return_code, '==', 0, "Timetick used as a string");
like($res->output, '/^SNMP OK - Timeticks:\s\(\d+\)\s+(?:\d+ days?,\s+)?\d+:\d+:\d+\.\d+\s.*$/', "Timetick used as a string, result printed rather than parsed");
}
# These checks need a complete command line. An invalid community is used so
# the tests can run on hosts w/o snmp host/community in NPTest.cache. Execution will fail anyway
SKIP: {
skip "no non responsive host defined", 2 if ( ! $host_nonresponsive );
$res = NPTest->testCmd( "./check_snmp -H $host_nonresponsive -C np_foobar -o system.sysUpTime.0 -w 1: -c 1:");
cmp_ok( $res->return_code, '==', 3, "Exit UNKNOWN with non responsive host" );
like($res->output, '/External command error: Timeout: No Response from /', "String matches timeout problem");
}
SKIP: {
skip "no non invalid host defined", 2 if ( ! $hostname_invalid );
$res = NPTest->testCmd( "./check_snmp -H $hostname_invalid -C np_foobar -o system.sysUpTime.0 -w 1: -c 1:");
cmp_ok( $res->return_code, '==', 3, "Exit UNKNOWN with non responsive host" );
like($res->output, '/External command error: .*(nosuchhost|Name or service not known|Unknown host)/', "String matches invalid host");
}

View file

@ -9,7 +9,7 @@ use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 7; plan tests => $tests}
BEGIN {$tests = 14; plan tests => $tests}
my $host_tcp_http = getTestParameter( "host_tcp_http", "NP_HOST_TCP_HTTP", "localhost",
"A host providing the HTTP Service (a web server)" );
@ -27,13 +27,15 @@ my $failedExpect = '/^TCP WARNING\s-\sUnexpected response from host/socket on po
my $t;
$t += checkCmd( "./check_tcp $host_tcp_http -p 80 -wt 300 -ct 600", 0, $successOutput );
$t += checkCmd( "./check_tcp $host_tcp_http -p 80 -wt 300 -ct 600 -6 ", 0, $successOutput );
$t += checkCmd( "./check_tcp $host_tcp_http -p 81 -wt 0 -ct 0 -to 1", 2 ); # use invalid port for this test
$t += checkCmd( "./check_tcp $host_nonresponsive -p 80 -wt 0 -ct 0 -to 1", 2 );
$t += checkCmd( "./check_tcp $hostname_invalid -p 80 -wt 0 -ct 0 -to 1", 2 );
$t += checkCmd( "./check_tcp -S -D 1 -H www.verisign.com -p 443", 0 );
$t += checkCmd( "./check_tcp -S -D 9000,1 -H www.verisign.com -p 443", 0 );
$t += checkCmd( "./check_tcp -S -D 9000,1 -H www.verisign.com -p 443", 1 );
$t += checkCmd( "./check_tcp -S -D 9000 -H www.verisign.com -p 443", 1 );
$t += checkCmd( "./check_tcp -S -D 9000,8999 -H www.verisign.com -p 443", 2 );
$t += checkCmd( "./check_tcp -6 -p 80 www.heise.de", 0 );
# Need the \r\n to make it more standards compliant with web servers. Need the various quotes
# so that perl doesn't interpret the \r\n and is passed onto command line correctly

View file

@ -12,14 +12,13 @@
# Common Name (eg, YOUR name) []:Ton Voon
# Email Address []:tonvoon@mac.com
use strict;
use Test::More;
use NPTest;
use FindBin qw($Bin);
my $common_tests = 66;
my $ssl_only_tests = 6;
my $common_tests = 70;
my $ssl_only_tests = 8;
# Check that all dependent modules are available
eval {
require HTTP::Daemon;
@ -152,6 +151,10 @@ sub run_server {
unshift @persist, $c;
delete($persist[1000]);
next MAINLOOP;
} elsif ($r->url->path eq "/header_check") {
$c->send_basic_header;
$c->send_header('foo');
$c->send_crlf;
} else {
$c->send_error(HTTP::Status->RC_FORBIDDEN);
}
@ -160,9 +163,9 @@ sub run_server {
}
}
END {
END {
foreach my $pid (@pids) {
if ($pid) { print "Killing $pid\n"; kill "INT", $pid }
if ($pid) { print "Killing $pid\n"; kill "INT", $pid }
}
};
@ -179,7 +182,7 @@ run_common_tests( { command => "$command -p $port_http" } );
SKIP: {
skip "HTTP::Daemon::SSL not installed", $common_tests + $ssl_only_tests if ! exists $servers->{https};
run_common_tests( { command => "$command -p $port_https", ssl => 1 } );
$result = NPTest->testCmd( "$command -p $port_https -S -C 14" );
is( $result->return_code, 0, "$command -p $port_https -S -C 14" );
is( $result->output, 'OK - Certificate \'Ton Voon\' will expire on 03/03/2019 21:41.', "output ok" );
@ -188,14 +191,14 @@ SKIP: {
is( $result->return_code, 1, "$command -p $port_https -S -C 14000" );
like( $result->output, '/WARNING - Certificate \'Ton Voon\' expires in \d+ day\(s\) \(03/03/2019 21:41\)./', "output ok" );
$result = NPTest->testCmd( "$command -p $port_https -S -C 13960,14000" );
is( $result->return_code, 1, "$command -p $port_https -S -C 139600,14000" );
like( $result->output, '/CRITICAL - Certificate \'Ton Voon\' expires in \d+ day\(s\) \(03/03/2019 21:41\)./', "output ok" );
# Expired cert tests
$result = NPTest->testCmd( "$command -p $port_https -S -C 13960,14000" );
is( $result->return_code, 2, "$command -p $port_https -S -C 13960,14000" );
like( $result->output, '/CRITICAL - Certificate \'Ton Voon\' expires in \d+ day\(s\) \(03/03/2019 21:41\)./', "output ok" );
$result = NPTest->testCmd( "$command -p $port_https_expired -S -C 7" );
is( $result->return_code, 2, "$command -p $port_https_expired -S -C 7" );
is( $result->output,
is( $result->output,
'CRITICAL - Certificate \'Ton Voon\' expired on 03/05/2009 00:13.',
"output ok" );
@ -224,6 +227,13 @@ sub run_common_tests {
is( $result->return_code, 2, "Missing string check");
like( $result->output, qr%HTTP CRITICAL: HTTP/1\.1 200 OK - string 'NonRootWithOver30charsAndM...' not found on 'https?://127\.0\.0\.1:\d+/file/root'%, "Shows search string and location");
$result = NPTest->testCmd( "$command -u /header_check -d foo" );
is( $result->return_code, 0, "header_check search for string");
like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - 96 bytes in [\d\.]+ second/', "Output correct" );
$result = NPTest->testCmd( "$command -u /header_check -d bar" );
is( $result->return_code, 2, "Missing header string check");
like( $result->output, qr%^HTTP CRITICAL: HTTP/1\.1 200 OK - header 'bar' not found on 'https?://127\.0\.0\.1:\d+/header_check'%, "Shows search string and location");
my $cmd;
$cmd = "$command -u /slow";
@ -406,4 +416,3 @@ sub run_common_tests {
isnt( $@, "alarm\n", $cmd );
}

View file

@ -102,7 +102,7 @@ main (int argc, char **argv)
cmd = strdup (argv[optind++]);
for (c = optind; c < argc; c++) {
asprintf (&cmd, "%s %s", cmd, argv[c]);
xasprintf (&cmd, "%s %s", cmd, argv[c]);
}
child_process = spopen (cmd);

View file

@ -358,7 +358,7 @@ strscpy (char *dest, const char *src)
if (src == NULL)
return NULL;
asprintf (&dest, "%s", src);
xasprintf (&dest, "%s", src);
return dest;
}
@ -513,6 +513,33 @@ strpcat (char *dest, const char *src, const char *str)
return dest;
}
/******************************************************************************
*
* asprintf, but die on failure
*
******************************************************************************/
int
xvasprintf (char **strp, const char *fmt, va_list ap)
{
int result = vasprintf (strp, fmt, ap);
if (result == -1 || *strp == NULL)
die (STATE_UNKNOWN, _("failed malloc in xvasprintf\n"));
return result;
}
int
xasprintf (char **strp, const char *fmt, ...)
{
va_list ap;
int result;
va_start (ap, fmt);
result = xvasprintf (strp, fmt, ap);
va_end (ap);
return result;
}
/******************************************************************************
*
* Print perfdata in a standard format
@ -534,25 +561,25 @@ char *perfdata (const char *label,
char *data = NULL;
if (strpbrk (label, "'= "))
asprintf (&data, "'%s'=%ld%s;", label, val, uom);
xasprintf (&data, "'%s'=%ld%s;", label, val, uom);
else
asprintf (&data, "%s=%ld%s;", label, val, uom);
xasprintf (&data, "%s=%ld%s;", label, val, uom);
if (warnp)
asprintf (&data, "%s%ld;", data, warn);
xasprintf (&data, "%s%ld;", data, warn);
else
asprintf (&data, "%s;", data);
xasprintf (&data, "%s;", data);
if (critp)
asprintf (&data, "%s%ld;", data, crit);
xasprintf (&data, "%s%ld;", data, crit);
else
asprintf (&data, "%s;", data);
xasprintf (&data, "%s;", data);
if (minp)
asprintf (&data, "%s%ld", data, minv);
xasprintf (&data, "%s%ld", data, minv);
if (maxp)
asprintf (&data, "%s;%ld", data, maxv);
xasprintf (&data, "%s;%ld", data, maxv);
return data;
}
@ -573,29 +600,29 @@ char *fperfdata (const char *label,
char *data = NULL;
if (strpbrk (label, "'= "))
asprintf (&data, "'%s'=", label);
xasprintf (&data, "'%s'=", label);
else
asprintf (&data, "%s=", label);
xasprintf (&data, "%s=", label);
asprintf (&data, "%s%f", data, val);
asprintf (&data, "%s%s;", data, uom);
xasprintf (&data, "%s%f", data, val);
xasprintf (&data, "%s%s;", data, uom);
if (warnp)
asprintf (&data, "%s%f", data, warn);
xasprintf (&data, "%s%f", data, warn);
asprintf (&data, "%s;", data);
xasprintf (&data, "%s;", data);
if (critp)
asprintf (&data, "%s%f", data, crit);
xasprintf (&data, "%s%f", data, crit);
asprintf (&data, "%s;", data);
xasprintf (&data, "%s;", data);
if (minp)
asprintf (&data, "%s%f", data, minv);
xasprintf (&data, "%s%f", data, minv);
if (maxp) {
asprintf (&data, "%s;", data);
asprintf (&data, "%s%f", data, maxv);
xasprintf (&data, "%s;", data);
xasprintf (&data, "%s%f", data, maxv);
}
return data;

View file

@ -81,6 +81,8 @@ char *strscpy (char *, const char *);
char *strnl (char *);
char *strpcpy (char *, const char *, const char *);
char *strpcat (char *, const char *, const char *);
int xvasprintf (char **strp, const char *fmt, va_list ap);
int xasprintf (char **strp, const char *fmt, ...);
int max_state (int a, int b);
int max_state_alt (int a, int b);