remove source-dist branch

This commit is contained in:
Marc Haber 2006-01-20 18:48:40 +00:00
commit 27dcec3fa7
416 changed files with 128456 additions and 0 deletions

152
plugins/Makefile.am Normal file
View file

@ -0,0 +1,152 @@
## Process this file with automake to produce Makefile.in
VPATH = $(top_srcdir) $(top_srcdir)/lib $(top_srcdir)/plugins $(top_srcdir)/plugins/t
INCLUDES = -I.. -I$(top_srcdir)/lib -I$(top_srcdir)/intl @LDAPINCLUDE@ @PGINCLUDE@
datadir = @datadir@
localedir = $(datadir)/locale
DEFS = -DLOCALEDIR=\"$(localedir)\" @DEFS@
LIBS = @LIBINTL@ @LIBS@ @SSLINCLUDE@
MATHLIBS = @MATHLIBS@
libexec_PROGRAMS = check_dhcp check_disk check_dummy check_http check_load \
check_mrtg check_mrtgtraf check_nwstat check_overcr check_ping \
check_real check_smtp check_ssh check_tcp check_time \
check_udp check_ups check_users negate urlize \
check_icmp @EXTRAS@
check_tcp_programs = check_ftp check_imap check_nntp check_pop \
check_udp2 @check_tcp_ssl@
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
EXTRA_DIST = t utils.c netutils.c popen.c utils.h netutils.h popen.h common.h \
getaddrinfo.c getaddrinfo.h gethostbyname.c gethostbyname.h
PLUGINHDRS = common.h
BASEOBJS = utils.o ../lib/libnagiosplug.a ../lib/libcoreutils.a
NETOBJS = netutils.o $(BASEOBJS) $(EXTRA_NETOBJS)
NETLIBS = $(NETOBJS) $(SOCKETLIBS)
TESTS_ENVIRONMENT = perl -I $(top_builddir) -I $(top_srcdir)
TESTS = @PLUGIN_TEST@
test:
perl -I $(top_builddir) -I $(top_srcdir) ../test.pl
AM_INSTALL_PROGRAM_FLAGS = @INSTALL_OPTS@
##############################################################################
# the actual targets
check_dhcp_LDADD = $(NETLIBS)
check_dig_LDADD = $(NETLIBS) popen.o
check_disk_LDADD = $(BASEOBJS) popen.o
check_dns_LDADD = $(NETLIBS) popen.o
check_dummy_LDADD = $(BASEOBJS)
check_fping_LDADD = $(NETLIBS) popen.o
check_game_LDADD = $(BASEOBJS) popen.o
check_http_LDADD = $(NETLIBS) $(SSLLIBS)
check_hpjd_LDADD = $(NETLIBS) popen.o
check_icmp_LDADD = $(SOCKETLIBS)
check_ldap_LDADD = $(NETLIBS) $(LDAPLIBS)
check_load_LDADD = $(BASEOBJS) popen.o
check_mrtg_LDADD = $(BASEOBJS)
check_mrtgtraf_LDADD = $(BASEOBJS)
check_mysql_LDADD = $(NETLIBS) $(MYSQLLIBS)
check_nagios_LDADD = $(BASEOBJS) popen.o
check_nt_LDADD = $(NETLIBS)
check_nwstat_LDADD = $(NETLIBS)
check_overcr_LDADD = $(NETLIBS)
check_pgsql_LDADD = $(NETLIBS) $(PGLIBS)
check_ping_LDADD = $(NETLIBS) popen.o
check_procs_LDADD = $(BASEOBJS) popen.o
check_radius_LDADD = $(NETLIBS) $(RADIUSLIBS)
check_real_LDADD = $(NETLIBS)
check_snmp_LDADD = $(BASEOBJS) popen.o
check_smtp_LDADD = $(NETLIBS) $(SSLLIBS)
check_ssh_LDADD = $(NETLIBS)
check_swap_LDADD = $(MATHLIBS) $(BASEOBJS) popen.o
check_tcp_LDADD = $(NETLIBS) $(SSLLIBS)
check_time_LDADD = $(NETLIBS)
check_udp_LDADD = $(NETLIBS)
check_ups_LDADD = $(NETLIBS)
check_users_LDADD = $(BASEOBJS) popen.o
check_by_ssh_LDADD = $(NETLIBS) popen.o
check_ide_smart_LDADD = $(BASEOBJS)
negate_LDADD = $(BASEOBJS) popen.o
urlize_LDADD = $(BASEOBJS) popen.o
check_dhcp_DEPENDENCIES = check_dhcp.c $(NETOBJS) $(DEPLIBS)
check_dig_DEPENDENCIES = check_dig.c $(NETOBJS) popen.o $(DEPLIBS)
check_disk_DEPENDENCIES = check_disk.c $(BASEOBJS) popen.o $(DEPLIBS)
check_dns_DEPENDENCIES = check_dns.c $(NETOBJS) popen.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)
check_http_DEPENDENCIES = check_http.c $(NETOBJS) $(DEPLIBS)
check_hpjd_DEPENDENCIES = check_hpjd.c $(NETOBJS) popen.o $(DEPLIBS)
check_icmp_DEPENDENCIES = check_icmp.c
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_nagios_DEPENDENCIES = check_nagios.c $(BASEOBJS) popen.o $(DEPLIBS)
check_nt_DEPENDENCIES = check_nt.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) popen.o $(DEPLIBS)
check_smtp_DEPENDENCIES = check_smtp.c $(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 $(NETOBJS) $(DEPLIBS)
check_time_DEPENDENCIES = check_time.c $(NETOBJS) $(DEPLIBS)
check_udp_DEPENDENCIES = check_udp.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) popen.o $(DEPLIBS)
negate_DEPENDENCIES = negate.c $(BASEOBJS) popen.o $(DEPLIBS)
urlize_DEPENDENCIES = urlize.c $(BASEOBJS) popen.o $(DEPLIBS)
##############################################################################
# secondary dependencies
popen.o: popen.c popen.h $(PLUGINHDRS)
utils.o: utils.c utils.h $(PLUGINHDRS)
netutils.o: netutils.c netutils.h $(PLUGINHDRS)
getaddrinfo.o: getaddrinfo.h $(PLUGINHDRS)
gethostbyname.o: gethostbyname.h $(PLUGINHDRS)
all-local: $(check_tcp_programs)
$(check_tcp_programs): check_tcp
rm -f $@
ln -s check_tcp $@
install-exec-hook:
cd $(DESTDIR)$(libexecdir) && \
for i in $(check_tcp_programs) ; do rm -f $$i; ln -s check_tcp $$i ; done ;\
if [ -x check_ldaps ] ; then rm -f check_ldaps ; ln -s check_ldap check_ldaps ; fi
clean-local:
rm -f $(check_tcp_programs)
uninstall-local:
cd $(DESTDIR)$(libexecdir) && rm -f $(check_tcp_programs)

989
plugins/Makefile.in Normal file
View file

@ -0,0 +1,989 @@
# Makefile.in generated by automake 1.8 from Makefile.am.
# @configure_input@
# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003
# Free Software Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
@SET_MAKE@
SOURCES = check_by_ssh.c check_dhcp.c check_dig.c check_disk.c check_dns.c check_dummy.c check_fping.c check_game.c check_hpjd.c check_http.c check_icmp.c check_ide_smart.c check_ldap.c check_load.c check_mrtg.c check_mrtgtraf.c check_mysql.c check_nagios.c check_nt.c check_nwstat.c check_overcr.c check_pgsql.c check_ping.c check_procs.c check_radius.c check_real.c check_smtp.c check_snmp.c check_ssh.c check_swap.c check_tcp.c check_time.c check_udp.c check_ups.c check_users.c negate.c urlize.c
srcdir = @srcdir@
top_srcdir = @top_srcdir@
pkgdatadir = $(datadir)/@PACKAGE@
pkglibdir = $(libdir)/@PACKAGE@
pkgincludedir = $(includedir)/@PACKAGE@
top_builddir = ..
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
host_triplet = @host@
libexec_PROGRAMS = check_dhcp$(EXEEXT) check_disk$(EXEEXT) \
check_dummy$(EXEEXT) check_http$(EXEEXT) check_load$(EXEEXT) \
check_mrtg$(EXEEXT) check_mrtgtraf$(EXEEXT) \
check_nwstat$(EXEEXT) check_overcr$(EXEEXT) \
check_ping$(EXEEXT) check_real$(EXEEXT) check_smtp$(EXEEXT) \
check_ssh$(EXEEXT) check_tcp$(EXEEXT) check_time$(EXEEXT) \
check_udp$(EXEEXT) check_ups$(EXEEXT) check_users$(EXEEXT) \
negate$(EXEEXT) urlize$(EXEEXT) check_icmp$(EXEEXT) @EXTRAS@
EXTRA_PROGRAMS = check_mysql$(EXEEXT) check_radius$(EXEEXT) \
check_pgsql$(EXEEXT) check_snmp$(EXEEXT) check_hpjd$(EXEEXT) \
check_swap$(EXEEXT) check_fping$(EXEEXT) check_ldap$(EXEEXT) \
check_game$(EXEEXT) check_dig$(EXEEXT) check_nagios$(EXEEXT) \
check_by_ssh$(EXEEXT) check_dns$(EXEEXT) check_nt$(EXEEXT) \
check_ide_smart$(EXEEXT) check_procs$(EXEEXT)
subdir = plugins
DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/m4/afs.m4 \
$(top_srcdir)/m4/codeset.m4 $(top_srcdir)/m4/exitfail.m4 \
$(top_srcdir)/m4/extensions.m4 $(top_srcdir)/m4/fstypename.m4 \
$(top_srcdir)/m4/fsusage.m4 $(top_srcdir)/m4/getopt.m4 \
$(top_srcdir)/m4/gettext.m4 $(top_srcdir)/m4/glibc21.m4 \
$(top_srcdir)/m4/iconv.m4 $(top_srcdir)/m4/intdiv0.m4 \
$(top_srcdir)/m4/inttypes-pri.m4 $(top_srcdir)/m4/inttypes.m4 \
$(top_srcdir)/m4/inttypes_h.m4 $(top_srcdir)/m4/lcmessage.m4 \
$(top_srcdir)/m4/lib-ld.m4 $(top_srcdir)/m4/lib-link.m4 \
$(top_srcdir)/m4/lib-prefix.m4 $(top_srcdir)/m4/ls-mntd-fs.m4 \
$(top_srcdir)/m4/malloc.m4 $(top_srcdir)/m4/mountlist.m4 \
$(top_srcdir)/m4/np_coreutils.m4 $(top_srcdir)/m4/np_curl.m4 \
$(top_srcdir)/m4/onceonly.m4 $(top_srcdir)/m4/progtest.m4 \
$(top_srcdir)/m4/realloc.m4 $(top_srcdir)/m4/stdbool.m4 \
$(top_srcdir)/m4/stdint_h.m4 $(top_srcdir)/m4/uintmax_t.m4 \
$(top_srcdir)/m4/ulonglong.m4 $(top_srcdir)/m4/unlocked-io.m4 \
$(top_srcdir)/m4/xalloc.m4 $(top_srcdir)/acinclude.m4 \
$(top_srcdir)/configure.in
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs
CONFIG_HEADER = $(top_builddir)/config.h
CONFIG_CLEAN_FILES =
am__installdirs = $(DESTDIR)$(libexecdir)
libexecPROGRAMS_INSTALL = $(INSTALL_PROGRAM)
PROGRAMS = $(libexec_PROGRAMS)
check_by_ssh_SOURCES = check_by_ssh.c
check_by_ssh_OBJECTS = check_by_ssh.$(OBJEXT)
am__DEPENDENCIES_1 = utils.o ../lib/libnagiosplug.a \
../lib/libcoreutils.a
am__DEPENDENCIES_2 =
am__DEPENDENCIES_3 = netutils.o $(am__DEPENDENCIES_1) \
$(am__DEPENDENCIES_2)
am__DEPENDENCIES_4 = $(am__DEPENDENCIES_3) $(am__DEPENDENCIES_2)
check_dhcp_SOURCES = check_dhcp.c
check_dhcp_OBJECTS = check_dhcp.$(OBJEXT)
check_dig_SOURCES = check_dig.c
check_dig_OBJECTS = check_dig.$(OBJEXT)
check_disk_SOURCES = check_disk.c
check_disk_OBJECTS = check_disk.$(OBJEXT)
check_dns_SOURCES = check_dns.c
check_dns_OBJECTS = check_dns.$(OBJEXT)
check_dummy_SOURCES = check_dummy.c
check_dummy_OBJECTS = check_dummy.$(OBJEXT)
check_fping_SOURCES = check_fping.c
check_fping_OBJECTS = check_fping.$(OBJEXT)
check_game_SOURCES = check_game.c
check_game_OBJECTS = check_game.$(OBJEXT)
check_hpjd_SOURCES = check_hpjd.c
check_hpjd_OBJECTS = check_hpjd.$(OBJEXT)
check_http_SOURCES = check_http.c
check_http_OBJECTS = check_http.$(OBJEXT)
check_icmp_SOURCES = check_icmp.c
check_icmp_OBJECTS = check_icmp.$(OBJEXT)
check_ide_smart_SOURCES = check_ide_smart.c
check_ide_smart_OBJECTS = check_ide_smart.$(OBJEXT)
check_ldap_SOURCES = check_ldap.c
check_ldap_OBJECTS = check_ldap.$(OBJEXT)
check_load_SOURCES = check_load.c
check_load_OBJECTS = check_load.$(OBJEXT)
check_mrtg_SOURCES = check_mrtg.c
check_mrtg_OBJECTS = check_mrtg.$(OBJEXT)
check_mrtgtraf_SOURCES = check_mrtgtraf.c
check_mrtgtraf_OBJECTS = check_mrtgtraf.$(OBJEXT)
check_mysql_SOURCES = check_mysql.c
check_mysql_OBJECTS = check_mysql.$(OBJEXT)
check_nagios_SOURCES = check_nagios.c
check_nagios_OBJECTS = check_nagios.$(OBJEXT)
check_nt_SOURCES = check_nt.c
check_nt_OBJECTS = check_nt.$(OBJEXT)
check_nwstat_SOURCES = check_nwstat.c
check_nwstat_OBJECTS = check_nwstat.$(OBJEXT)
check_overcr_SOURCES = check_overcr.c
check_overcr_OBJECTS = check_overcr.$(OBJEXT)
check_pgsql_SOURCES = check_pgsql.c
check_pgsql_OBJECTS = check_pgsql.$(OBJEXT)
check_ping_SOURCES = check_ping.c
check_ping_OBJECTS = check_ping.$(OBJEXT)
check_procs_SOURCES = check_procs.c
check_procs_OBJECTS = check_procs.$(OBJEXT)
check_radius_SOURCES = check_radius.c
check_radius_OBJECTS = check_radius.$(OBJEXT)
check_real_SOURCES = check_real.c
check_real_OBJECTS = check_real.$(OBJEXT)
check_smtp_SOURCES = check_smtp.c
check_smtp_OBJECTS = check_smtp.$(OBJEXT)
check_snmp_SOURCES = check_snmp.c
check_snmp_OBJECTS = check_snmp.$(OBJEXT)
check_ssh_SOURCES = check_ssh.c
check_ssh_OBJECTS = check_ssh.$(OBJEXT)
check_swap_SOURCES = check_swap.c
check_swap_OBJECTS = check_swap.$(OBJEXT)
check_tcp_SOURCES = check_tcp.c
check_tcp_OBJECTS = check_tcp.$(OBJEXT)
check_time_SOURCES = check_time.c
check_time_OBJECTS = check_time.$(OBJEXT)
check_udp_SOURCES = check_udp.c
check_udp_OBJECTS = check_udp.$(OBJEXT)
check_ups_SOURCES = check_ups.c
check_ups_OBJECTS = check_ups.$(OBJEXT)
check_users_SOURCES = check_users.c
check_users_OBJECTS = check_users.$(OBJEXT)
negate_SOURCES = negate.c
negate_OBJECTS = negate.$(OBJEXT)
urlize_SOURCES = urlize.c
urlize_OBJECTS = urlize.$(OBJEXT)
DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)
depcomp = $(SHELL) $(top_srcdir)/depcomp
am__depfiles_maybe = depfiles
@AMDEP_TRUE@DEP_FILES = ./$(DEPDIR)/check_by_ssh.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_dhcp.Po ./$(DEPDIR)/check_dig.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_disk.Po ./$(DEPDIR)/check_dns.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_dummy.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_fping.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_game.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_hpjd.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_http.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_icmp.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_ide_smart.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_ldap.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_load.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_mrtg.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_mrtgtraf.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_mysql.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_nagios.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_nt.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_nwstat.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_overcr.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_pgsql.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_ping.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_procs.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_radius.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_real.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_smtp.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_snmp.Po ./$(DEPDIR)/check_ssh.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_swap.Po ./$(DEPDIR)/check_tcp.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_time.Po ./$(DEPDIR)/check_udp.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_ups.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/check_users.Po ./$(DEPDIR)/negate.Po \
@AMDEP_TRUE@ ./$(DEPDIR)/urlize.Po
COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
CCLD = $(CC)
LINK = $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
SOURCES = check_by_ssh.c check_dhcp.c check_dig.c check_disk.c \
check_dns.c check_dummy.c check_fping.c check_game.c \
check_hpjd.c check_http.c check_icmp.c check_ide_smart.c \
check_ldap.c check_load.c check_mrtg.c check_mrtgtraf.c \
check_mysql.c check_nagios.c check_nt.c check_nwstat.c \
check_overcr.c check_pgsql.c check_ping.c check_procs.c \
check_radius.c check_real.c check_smtp.c check_snmp.c \
check_ssh.c check_swap.c check_tcp.c check_time.c check_udp.c \
check_ups.c check_users.c negate.c urlize.c
DIST_SOURCES = check_by_ssh.c check_dhcp.c check_dig.c check_disk.c \
check_dns.c check_dummy.c check_fping.c check_game.c \
check_hpjd.c check_http.c check_icmp.c check_ide_smart.c \
check_ldap.c check_load.c check_mrtg.c check_mrtgtraf.c \
check_mysql.c check_nagios.c check_nt.c check_nwstat.c \
check_overcr.c check_pgsql.c check_ping.c check_procs.c \
check_radius.c check_real.c check_smtp.c check_snmp.c \
check_ssh.c check_swap.c check_tcp.c check_time.c check_udp.c \
check_ups.c check_users.c negate.c urlize.c
ETAGS = etags
CTAGS = ctags
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
VPATH = $(top_srcdir) $(top_srcdir)/lib $(top_srcdir)/plugins $(top_srcdir)/plugins/t
INSTALL = @INSTALL@
ACLOCAL = @ACLOCAL@
ALLOCA = @ALLOCA@
AMDEP_FALSE = @AMDEP_FALSE@
AMDEP_TRUE = @AMDEP_TRUE@
AMTAR = @AMTAR@
AUTOCONF = @AUTOCONF@
AUTOHEADER = @AUTOHEADER@
AUTOMAKE = @AUTOMAKE@
AWK = @AWK@
BASENAME = @BASENAME@
BUILD_INCLUDED_LIBINTL = @BUILD_INCLUDED_LIBINTL@
CATOBJEXT = @CATOBJEXT@
CC = @CC@
CCDEPMODE = @CCDEPMODE@
CFLAGS = @CFLAGS@
CPP = @CPP@
CPPFLAGS = @CPPFLAGS@
CYGPATH_W = @CYGPATH_W@
DATADIRNAME = @DATADIRNAME@
DEFS = -DLOCALEDIR=\"$(localedir)\" @DEFS@
DEPDIR = @DEPDIR@
DEPLIBS = @DEPLIBS@
ECHO_C = @ECHO_C@
ECHO_N = @ECHO_N@
ECHO_T = @ECHO_T@
EGREP = @EGREP@
EXEEXT = @EXEEXT@
EXTRAS = @EXTRAS@
EXTRA_NETOBJS = @EXTRA_NETOBJS@
GENCAT = @GENCAT@
GETLOADAVG_LIBS = @GETLOADAVG_LIBS@
GLIBC21 = @GLIBC21@
GMSGFMT = @GMSGFMT@
HAVE__BOOL = @HAVE__BOOL@
HOSTNAME = @HOSTNAME@
INSTALL_DATA = @INSTALL_DATA@
INSTALL_OPTS = @INSTALL_OPTS@
INSTALL_PROGRAM = @INSTALL_PROGRAM@
INSTALL_SCRIPT = @INSTALL_SCRIPT@
INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
INSTOBJEXT = @INSTOBJEXT@
INTLBISON = @INTLBISON@
INTLLIBS = @INTLLIBS@
INTLOBJS = @INTLOBJS@
INTL_LIBTOOL_SUFFIX_PREFIX = @INTL_LIBTOOL_SUFFIX_PREFIX@
KMEM_GROUP = @KMEM_GROUP@
KRBINCLUDE = @KRBINCLUDE@
LDAPINCLUDE = @LDAPINCLUDE@
LDAPLIBS = @LDAPLIBS@
LDFLAGS = @LDFLAGS@
LIBICONV = @LIBICONV@
LIBINTL = @LIBINTL@
LIBOBJS = @LIBOBJS@
LIBS = @LIBINTL@ @LIBS@ @SSLINCLUDE@
LTLIBICONV = @LTLIBICONV@
LTLIBINTL = @LTLIBINTL@
LTLIBOBJS = @LTLIBOBJS@
MAKEINFO = @MAKEINFO@
MATHLIBS = @MATHLIBS@
MKINSTALLDIRS = @MKINSTALLDIRS@
MSGFMT = @MSGFMT@
MSGMERGE = @MSGMERGE@
MYSQLINCLUDE = @MYSQLINCLUDE@
MYSQLLIBS = @MYSQLLIBS@
NEED_SETGID = @NEED_SETGID@
NEED_VA_LIST = @NEED_VA_LIST@
OBJEXT = @OBJEXT@
OPENSSL = @OPENSSL@
PACKAGE = @PACKAGE@
PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
PACKAGE_NAME = @PACKAGE_NAME@
PACKAGE_STRING = @PACKAGE_STRING@
PACKAGE_TARNAME = @PACKAGE_TARNAME@
PACKAGE_VERSION = @PACKAGE_VERSION@
PATH_SEPARATOR = @PATH_SEPARATOR@
PATH_TO_DIG = @PATH_TO_DIG@
PATH_TO_FPING = @PATH_TO_FPING@
PATH_TO_HOST = @PATH_TO_HOST@
PATH_TO_LMSTAT = @PATH_TO_LMSTAT@
PATH_TO_LSPS = @PATH_TO_LSPS@
PATH_TO_MAILQ = @PATH_TO_MAILQ@
PATH_TO_NSLOOKUP = @PATH_TO_NSLOOKUP@
PATH_TO_NTPDATE = @PATH_TO_NTPDATE@
PATH_TO_NTPDC = @PATH_TO_NTPDC@
PATH_TO_NTPQ = @PATH_TO_NTPQ@
PATH_TO_PING = @PATH_TO_PING@
PATH_TO_PING6 = @PATH_TO_PING6@
PATH_TO_PS = @PATH_TO_PS@
PATH_TO_QMAIL_QSTAT = @PATH_TO_QMAIL_QSTAT@
PATH_TO_QSTAT = @PATH_TO_QSTAT@
PATH_TO_QUAKESTAT = @PATH_TO_QUAKESTAT@
PATH_TO_RPCINFO = @PATH_TO_RPCINFO@
PATH_TO_SMBCLIENT = @PATH_TO_SMBCLIENT@
PATH_TO_SNMPGET = @PATH_TO_SNMPGET@
PATH_TO_SNMPGETNEXT = @PATH_TO_SNMPGETNEXT@
PATH_TO_SSH = @PATH_TO_SSH@
PATH_TO_SWAP = @PATH_TO_SWAP@
PATH_TO_SWAPINFO = @PATH_TO_SWAPINFO@
PATH_TO_UPTIME = @PATH_TO_UPTIME@
PATH_TO_WHO = @PATH_TO_WHO@
PERL = @PERL@
PGINCLUDE = @PGINCLUDE@
PGLIBS = @PGLIBS@
PKG_ARCH = @PKG_ARCH@
PLUGIN_TEST = @PLUGIN_TEST@
POSUB = @POSUB@
POW_LIB = @POW_LIB@
PYTHON = @PYTHON@
RADIUSLIBS = @RADIUSLIBS@
RANLIB = @RANLIB@
RELEASE = @RELEASE@
REV_DATESTAMP = @REV_DATESTAMP@
REV_TIMESTAMP = @REV_TIMESTAMP@
SCRIPT_TEST = @SCRIPT_TEST@
SET_MAKE = @SET_MAKE@
SH = @SH@
SHELL = @SHELL@
SOCKETLIBS = @SOCKETLIBS@
SSLINCLUDE = @SSLINCLUDE@
SSLLIBS = @SSLLIBS@
STDBOOL_H = @STDBOOL_H@
STRIP = @STRIP@
SUPPORT = @SUPPORT@
USE_INCLUDED_LIBINTL = @USE_INCLUDED_LIBINTL@
USE_NLS = @USE_NLS@
VERSION = @VERSION@
WARRANTY = @WARRANTY@
XGETTEXT = @XGETTEXT@
ac_ct_CC = @ac_ct_CC@
ac_ct_RANLIB = @ac_ct_RANLIB@
ac_ct_STRIP = @ac_ct_STRIP@
am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
am__include = @am__include@
am__leading_dot = @am__leading_dot@
am__quote = @am__quote@
bindir = @bindir@
build = @build@
build_alias = @build_alias@
build_cpu = @build_cpu@
build_os = @build_os@
build_vendor = @build_vendor@
check_mysql_LDFLAGS = @check_mysql_LDFLAGS@
check_tcp_ssl = @check_tcp_ssl@
datadir = @datadir@
exec_prefix = @exec_prefix@
host = @host@
host_alias = @host_alias@
host_cpu = @host_cpu@
host_os = @host_os@
host_vendor = @host_vendor@
includedir = @includedir@
infodir = @infodir@
install_sh = @install_sh@
libdir = @libdir@
libexecdir = @libexecdir@
localstatedir = @localstatedir@
mandir = @mandir@
mkdir_p = @mkdir_p@
oldincludedir = @oldincludedir@
prefix = @prefix@
program_transform_name = @program_transform_name@
sbindir = @sbindir@
sharedstatedir = @sharedstatedir@
sysconfdir = @sysconfdir@
target_alias = @target_alias@
with_nagios_group = @with_nagios_group@
with_nagios_user = @with_nagios_user@
with_trusted_path = @with_trusted_path@
INCLUDES = -I.. -I$(top_srcdir)/lib -I$(top_srcdir)/intl @LDAPINCLUDE@ @PGINCLUDE@
localedir = $(datadir)/locale
check_tcp_programs = check_ftp check_imap check_nntp check_pop \
check_udp2 @check_tcp_ssl@
EXTRA_DIST = t utils.c netutils.c popen.c utils.h netutils.h popen.h common.h \
getaddrinfo.c getaddrinfo.h gethostbyname.c gethostbyname.h
PLUGINHDRS = common.h
BASEOBJS = utils.o ../lib/libnagiosplug.a ../lib/libcoreutils.a
NETOBJS = netutils.o $(BASEOBJS) $(EXTRA_NETOBJS)
NETLIBS = $(NETOBJS) $(SOCKETLIBS)
TESTS_ENVIRONMENT = perl -I $(top_builddir) -I $(top_srcdir)
TESTS = @PLUGIN_TEST@
AM_INSTALL_PROGRAM_FLAGS = @INSTALL_OPTS@
##############################################################################
# the actual targets
check_dhcp_LDADD = $(NETLIBS)
check_dig_LDADD = $(NETLIBS) popen.o
check_disk_LDADD = $(BASEOBJS) popen.o
check_dns_LDADD = $(NETLIBS) popen.o
check_dummy_LDADD = $(BASEOBJS)
check_fping_LDADD = $(NETLIBS) popen.o
check_game_LDADD = $(BASEOBJS) popen.o
check_http_LDADD = $(NETLIBS) $(SSLLIBS)
check_hpjd_LDADD = $(NETLIBS) popen.o
check_icmp_LDADD = $(SOCKETLIBS)
check_ldap_LDADD = $(NETLIBS) $(LDAPLIBS)
check_load_LDADD = $(BASEOBJS) popen.o
check_mrtg_LDADD = $(BASEOBJS)
check_mrtgtraf_LDADD = $(BASEOBJS)
check_mysql_LDADD = $(NETLIBS) $(MYSQLLIBS)
check_nagios_LDADD = $(BASEOBJS) popen.o
check_nt_LDADD = $(NETLIBS)
check_nwstat_LDADD = $(NETLIBS)
check_overcr_LDADD = $(NETLIBS)
check_pgsql_LDADD = $(NETLIBS) $(PGLIBS)
check_ping_LDADD = $(NETLIBS) popen.o
check_procs_LDADD = $(BASEOBJS) popen.o
check_radius_LDADD = $(NETLIBS) $(RADIUSLIBS)
check_real_LDADD = $(NETLIBS)
check_snmp_LDADD = $(BASEOBJS) popen.o
check_smtp_LDADD = $(NETLIBS) $(SSLLIBS)
check_ssh_LDADD = $(NETLIBS)
check_swap_LDADD = $(MATHLIBS) $(BASEOBJS) popen.o
check_tcp_LDADD = $(NETLIBS) $(SSLLIBS)
check_time_LDADD = $(NETLIBS)
check_udp_LDADD = $(NETLIBS)
check_ups_LDADD = $(NETLIBS)
check_users_LDADD = $(BASEOBJS) popen.o
check_by_ssh_LDADD = $(NETLIBS) popen.o
check_ide_smart_LDADD = $(BASEOBJS)
negate_LDADD = $(BASEOBJS) popen.o
urlize_LDADD = $(BASEOBJS) popen.o
check_dhcp_DEPENDENCIES = check_dhcp.c $(NETOBJS) $(DEPLIBS)
check_dig_DEPENDENCIES = check_dig.c $(NETOBJS) popen.o $(DEPLIBS)
check_disk_DEPENDENCIES = check_disk.c $(BASEOBJS) popen.o $(DEPLIBS)
check_dns_DEPENDENCIES = check_dns.c $(NETOBJS) popen.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)
check_http_DEPENDENCIES = check_http.c $(NETOBJS) $(DEPLIBS)
check_hpjd_DEPENDENCIES = check_hpjd.c $(NETOBJS) popen.o $(DEPLIBS)
check_icmp_DEPENDENCIES = check_icmp.c
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_nagios_DEPENDENCIES = check_nagios.c $(BASEOBJS) popen.o $(DEPLIBS)
check_nt_DEPENDENCIES = check_nt.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) popen.o $(DEPLIBS)
check_smtp_DEPENDENCIES = check_smtp.c $(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 $(NETOBJS) $(DEPLIBS)
check_time_DEPENDENCIES = check_time.c $(NETOBJS) $(DEPLIBS)
check_udp_DEPENDENCIES = check_udp.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) popen.o $(DEPLIBS)
negate_DEPENDENCIES = negate.c $(BASEOBJS) popen.o $(DEPLIBS)
urlize_DEPENDENCIES = urlize.c $(BASEOBJS) popen.o $(DEPLIBS)
all: all-am
.SUFFIXES:
.SUFFIXES: .c .o .obj
$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
&& exit 0; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu plugins/Makefile'; \
cd $(top_srcdir) && \
$(AUTOMAKE) --gnu plugins/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(top_srcdir)/configure: $(am__configure_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): $(am__aclocal_m4_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
install-libexecPROGRAMS: $(libexec_PROGRAMS)
@$(NORMAL_INSTALL)
$(mkdir_p) $(DESTDIR)$(libexecdir)
@list='$(libexec_PROGRAMS)'; for p in $$list; do \
p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \
if test -f $$p \
; then \
f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
echo " $(INSTALL_PROGRAM_ENV) $(libexecPROGRAMS_INSTALL) $$p $(DESTDIR)$(libexecdir)/$$f"; \
$(INSTALL_PROGRAM_ENV) $(libexecPROGRAMS_INSTALL) $$p $(DESTDIR)$(libexecdir)/$$f || exit 1; \
else :; fi; \
done
uninstall-libexecPROGRAMS:
@$(NORMAL_UNINSTALL)
@list='$(libexec_PROGRAMS)'; for p in $$list; do \
f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \
echo " rm -f $(DESTDIR)$(libexecdir)/$$f"; \
rm -f $(DESTDIR)$(libexecdir)/$$f; \
done
clean-libexecPROGRAMS:
-test -z "$(libexec_PROGRAMS)" || rm -f $(libexec_PROGRAMS)
check_by_ssh$(EXEEXT): $(check_by_ssh_OBJECTS) $(check_by_ssh_DEPENDENCIES)
@rm -f check_by_ssh$(EXEEXT)
$(LINK) $(check_by_ssh_LDFLAGS) $(check_by_ssh_OBJECTS) $(check_by_ssh_LDADD) $(LIBS)
check_dhcp$(EXEEXT): $(check_dhcp_OBJECTS) $(check_dhcp_DEPENDENCIES)
@rm -f check_dhcp$(EXEEXT)
$(LINK) $(check_dhcp_LDFLAGS) $(check_dhcp_OBJECTS) $(check_dhcp_LDADD) $(LIBS)
check_dig$(EXEEXT): $(check_dig_OBJECTS) $(check_dig_DEPENDENCIES)
@rm -f check_dig$(EXEEXT)
$(LINK) $(check_dig_LDFLAGS) $(check_dig_OBJECTS) $(check_dig_LDADD) $(LIBS)
check_disk$(EXEEXT): $(check_disk_OBJECTS) $(check_disk_DEPENDENCIES)
@rm -f check_disk$(EXEEXT)
$(LINK) $(check_disk_LDFLAGS) $(check_disk_OBJECTS) $(check_disk_LDADD) $(LIBS)
check_dns$(EXEEXT): $(check_dns_OBJECTS) $(check_dns_DEPENDENCIES)
@rm -f check_dns$(EXEEXT)
$(LINK) $(check_dns_LDFLAGS) $(check_dns_OBJECTS) $(check_dns_LDADD) $(LIBS)
check_dummy$(EXEEXT): $(check_dummy_OBJECTS) $(check_dummy_DEPENDENCIES)
@rm -f check_dummy$(EXEEXT)
$(LINK) $(check_dummy_LDFLAGS) $(check_dummy_OBJECTS) $(check_dummy_LDADD) $(LIBS)
check_fping$(EXEEXT): $(check_fping_OBJECTS) $(check_fping_DEPENDENCIES)
@rm -f check_fping$(EXEEXT)
$(LINK) $(check_fping_LDFLAGS) $(check_fping_OBJECTS) $(check_fping_LDADD) $(LIBS)
check_game$(EXEEXT): $(check_game_OBJECTS) $(check_game_DEPENDENCIES)
@rm -f check_game$(EXEEXT)
$(LINK) $(check_game_LDFLAGS) $(check_game_OBJECTS) $(check_game_LDADD) $(LIBS)
check_hpjd$(EXEEXT): $(check_hpjd_OBJECTS) $(check_hpjd_DEPENDENCIES)
@rm -f check_hpjd$(EXEEXT)
$(LINK) $(check_hpjd_LDFLAGS) $(check_hpjd_OBJECTS) $(check_hpjd_LDADD) $(LIBS)
check_http$(EXEEXT): $(check_http_OBJECTS) $(check_http_DEPENDENCIES)
@rm -f check_http$(EXEEXT)
$(LINK) $(check_http_LDFLAGS) $(check_http_OBJECTS) $(check_http_LDADD) $(LIBS)
check_icmp$(EXEEXT): $(check_icmp_OBJECTS) $(check_icmp_DEPENDENCIES)
@rm -f check_icmp$(EXEEXT)
$(LINK) $(check_icmp_LDFLAGS) $(check_icmp_OBJECTS) $(check_icmp_LDADD) $(LIBS)
check_ide_smart$(EXEEXT): $(check_ide_smart_OBJECTS) $(check_ide_smart_DEPENDENCIES)
@rm -f check_ide_smart$(EXEEXT)
$(LINK) $(check_ide_smart_LDFLAGS) $(check_ide_smart_OBJECTS) $(check_ide_smart_LDADD) $(LIBS)
check_ldap$(EXEEXT): $(check_ldap_OBJECTS) $(check_ldap_DEPENDENCIES)
@rm -f check_ldap$(EXEEXT)
$(LINK) $(check_ldap_LDFLAGS) $(check_ldap_OBJECTS) $(check_ldap_LDADD) $(LIBS)
check_load$(EXEEXT): $(check_load_OBJECTS) $(check_load_DEPENDENCIES)
@rm -f check_load$(EXEEXT)
$(LINK) $(check_load_LDFLAGS) $(check_load_OBJECTS) $(check_load_LDADD) $(LIBS)
check_mrtg$(EXEEXT): $(check_mrtg_OBJECTS) $(check_mrtg_DEPENDENCIES)
@rm -f check_mrtg$(EXEEXT)
$(LINK) $(check_mrtg_LDFLAGS) $(check_mrtg_OBJECTS) $(check_mrtg_LDADD) $(LIBS)
check_mrtgtraf$(EXEEXT): $(check_mrtgtraf_OBJECTS) $(check_mrtgtraf_DEPENDENCIES)
@rm -f check_mrtgtraf$(EXEEXT)
$(LINK) $(check_mrtgtraf_LDFLAGS) $(check_mrtgtraf_OBJECTS) $(check_mrtgtraf_LDADD) $(LIBS)
check_mysql$(EXEEXT): $(check_mysql_OBJECTS) $(check_mysql_DEPENDENCIES)
@rm -f check_mysql$(EXEEXT)
$(LINK) $(check_mysql_LDFLAGS) $(check_mysql_OBJECTS) $(check_mysql_LDADD) $(LIBS)
check_nagios$(EXEEXT): $(check_nagios_OBJECTS) $(check_nagios_DEPENDENCIES)
@rm -f check_nagios$(EXEEXT)
$(LINK) $(check_nagios_LDFLAGS) $(check_nagios_OBJECTS) $(check_nagios_LDADD) $(LIBS)
check_nt$(EXEEXT): $(check_nt_OBJECTS) $(check_nt_DEPENDENCIES)
@rm -f check_nt$(EXEEXT)
$(LINK) $(check_nt_LDFLAGS) $(check_nt_OBJECTS) $(check_nt_LDADD) $(LIBS)
check_nwstat$(EXEEXT): $(check_nwstat_OBJECTS) $(check_nwstat_DEPENDENCIES)
@rm -f check_nwstat$(EXEEXT)
$(LINK) $(check_nwstat_LDFLAGS) $(check_nwstat_OBJECTS) $(check_nwstat_LDADD) $(LIBS)
check_overcr$(EXEEXT): $(check_overcr_OBJECTS) $(check_overcr_DEPENDENCIES)
@rm -f check_overcr$(EXEEXT)
$(LINK) $(check_overcr_LDFLAGS) $(check_overcr_OBJECTS) $(check_overcr_LDADD) $(LIBS)
check_pgsql$(EXEEXT): $(check_pgsql_OBJECTS) $(check_pgsql_DEPENDENCIES)
@rm -f check_pgsql$(EXEEXT)
$(LINK) $(check_pgsql_LDFLAGS) $(check_pgsql_OBJECTS) $(check_pgsql_LDADD) $(LIBS)
check_ping$(EXEEXT): $(check_ping_OBJECTS) $(check_ping_DEPENDENCIES)
@rm -f check_ping$(EXEEXT)
$(LINK) $(check_ping_LDFLAGS) $(check_ping_OBJECTS) $(check_ping_LDADD) $(LIBS)
check_procs$(EXEEXT): $(check_procs_OBJECTS) $(check_procs_DEPENDENCIES)
@rm -f check_procs$(EXEEXT)
$(LINK) $(check_procs_LDFLAGS) $(check_procs_OBJECTS) $(check_procs_LDADD) $(LIBS)
check_radius$(EXEEXT): $(check_radius_OBJECTS) $(check_radius_DEPENDENCIES)
@rm -f check_radius$(EXEEXT)
$(LINK) $(check_radius_LDFLAGS) $(check_radius_OBJECTS) $(check_radius_LDADD) $(LIBS)
check_real$(EXEEXT): $(check_real_OBJECTS) $(check_real_DEPENDENCIES)
@rm -f check_real$(EXEEXT)
$(LINK) $(check_real_LDFLAGS) $(check_real_OBJECTS) $(check_real_LDADD) $(LIBS)
check_smtp$(EXEEXT): $(check_smtp_OBJECTS) $(check_smtp_DEPENDENCIES)
@rm -f check_smtp$(EXEEXT)
$(LINK) $(check_smtp_LDFLAGS) $(check_smtp_OBJECTS) $(check_smtp_LDADD) $(LIBS)
check_snmp$(EXEEXT): $(check_snmp_OBJECTS) $(check_snmp_DEPENDENCIES)
@rm -f check_snmp$(EXEEXT)
$(LINK) $(check_snmp_LDFLAGS) $(check_snmp_OBJECTS) $(check_snmp_LDADD) $(LIBS)
check_ssh$(EXEEXT): $(check_ssh_OBJECTS) $(check_ssh_DEPENDENCIES)
@rm -f check_ssh$(EXEEXT)
$(LINK) $(check_ssh_LDFLAGS) $(check_ssh_OBJECTS) $(check_ssh_LDADD) $(LIBS)
check_swap$(EXEEXT): $(check_swap_OBJECTS) $(check_swap_DEPENDENCIES)
@rm -f check_swap$(EXEEXT)
$(LINK) $(check_swap_LDFLAGS) $(check_swap_OBJECTS) $(check_swap_LDADD) $(LIBS)
check_tcp$(EXEEXT): $(check_tcp_OBJECTS) $(check_tcp_DEPENDENCIES)
@rm -f check_tcp$(EXEEXT)
$(LINK) $(check_tcp_LDFLAGS) $(check_tcp_OBJECTS) $(check_tcp_LDADD) $(LIBS)
check_time$(EXEEXT): $(check_time_OBJECTS) $(check_time_DEPENDENCIES)
@rm -f check_time$(EXEEXT)
$(LINK) $(check_time_LDFLAGS) $(check_time_OBJECTS) $(check_time_LDADD) $(LIBS)
check_udp$(EXEEXT): $(check_udp_OBJECTS) $(check_udp_DEPENDENCIES)
@rm -f check_udp$(EXEEXT)
$(LINK) $(check_udp_LDFLAGS) $(check_udp_OBJECTS) $(check_udp_LDADD) $(LIBS)
check_ups$(EXEEXT): $(check_ups_OBJECTS) $(check_ups_DEPENDENCIES)
@rm -f check_ups$(EXEEXT)
$(LINK) $(check_ups_LDFLAGS) $(check_ups_OBJECTS) $(check_ups_LDADD) $(LIBS)
check_users$(EXEEXT): $(check_users_OBJECTS) $(check_users_DEPENDENCIES)
@rm -f check_users$(EXEEXT)
$(LINK) $(check_users_LDFLAGS) $(check_users_OBJECTS) $(check_users_LDADD) $(LIBS)
negate$(EXEEXT): $(negate_OBJECTS) $(negate_DEPENDENCIES)
@rm -f negate$(EXEEXT)
$(LINK) $(negate_LDFLAGS) $(negate_OBJECTS) $(negate_LDADD) $(LIBS)
urlize$(EXEEXT): $(urlize_OBJECTS) $(urlize_DEPENDENCIES)
@rm -f urlize$(EXEEXT)
$(LINK) $(urlize_LDFLAGS) $(urlize_OBJECTS) $(urlize_LDADD) $(LIBS)
mostlyclean-compile:
-rm -f *.$(OBJEXT)
distclean-compile:
-rm -f *.tab.c
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_by_ssh.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_dhcp.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_dig.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_disk.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_dns.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_dummy.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_fping.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_game.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_hpjd.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_http.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_icmp.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_ide_smart.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_ldap.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_load.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_mrtg.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_mrtgtraf.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_mysql.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_nagios.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_nt.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_nwstat.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_overcr.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_pgsql.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_ping.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_procs.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_radius.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_real.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_smtp.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_snmp.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_ssh.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_swap.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_tcp.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_time.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_udp.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_ups.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/check_users.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/negate.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/urlize.Po@am__quote@
.c.o:
@am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
@am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
@AMDEP_TRUE@@am__fastdepCC_FALSE@ depfile='$(DEPDIR)/$*.Po' tmpdepfile='$(DEPDIR)/$*.TPo' @AMDEPBACKSLASH@
@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
@am__fastdepCC_FALSE@ $(COMPILE) -c $<
.c.obj:
@am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \
@am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
@AMDEP_TRUE@@am__fastdepCC_FALSE@ depfile='$(DEPDIR)/$*.Po' tmpdepfile='$(DEPDIR)/$*.TPo' @AMDEPBACKSLASH@
@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
@am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'`
uninstall-info-am:
ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) ' { files[$$0] = 1; } \
END { for (i in files) print i; }'`; \
mkid -fID $$unique
tags: TAGS
TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
$(TAGS_FILES) $(LISP)
tags=; \
here=`pwd`; \
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) ' { files[$$0] = 1; } \
END { for (i in files) print i; }'`; \
test -z "$(ETAGS_ARGS)$$tags$$unique" \
|| $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
$$tags $$unique
ctags: CTAGS
CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
$(TAGS_FILES) $(LISP)
tags=; \
here=`pwd`; \
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) ' { files[$$0] = 1; } \
END { for (i in files) print i; }'`; \
test -z "$(CTAGS_ARGS)$$tags$$unique" \
|| $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
$$tags $$unique
GTAGS:
here=`$(am__cd) $(top_builddir) && pwd` \
&& cd $(top_srcdir) \
&& gtags -i $(GTAGS_ARGS) $$here
distclean-tags:
-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
check-TESTS: $(TESTS)
@failed=0; all=0; xfail=0; xpass=0; skip=0; \
srcdir=$(srcdir); export srcdir; \
list='$(TESTS)'; \
if test -n "$$list"; then \
for tst in $$list; do \
if test -f ./$$tst; then dir=./; \
elif test -f $$tst; then dir=; \
else dir="$(srcdir)/"; fi; \
if $(TESTS_ENVIRONMENT) $${dir}$$tst; then \
all=`expr $$all + 1`; \
case " $(XFAIL_TESTS) " in \
*" $$tst "*) \
xpass=`expr $$xpass + 1`; \
failed=`expr $$failed + 1`; \
echo "XPASS: $$tst"; \
;; \
*) \
echo "PASS: $$tst"; \
;; \
esac; \
elif test $$? -ne 77; then \
all=`expr $$all + 1`; \
case " $(XFAIL_TESTS) " in \
*" $$tst "*) \
xfail=`expr $$xfail + 1`; \
echo "XFAIL: $$tst"; \
;; \
*) \
failed=`expr $$failed + 1`; \
echo "FAIL: $$tst"; \
;; \
esac; \
else \
skip=`expr $$skip + 1`; \
echo "SKIP: $$tst"; \
fi; \
done; \
if test "$$failed" -eq 0; then \
if test "$$xfail" -eq 0; then \
banner="All $$all tests passed"; \
else \
banner="All $$all tests behaved as expected ($$xfail expected failures)"; \
fi; \
else \
if test "$$xpass" -eq 0; then \
banner="$$failed of $$all tests failed"; \
else \
banner="$$failed of $$all tests did not behave as expected ($$xpass unexpected passes)"; \
fi; \
fi; \
dashes="$$banner"; \
skipped=""; \
if test "$$skip" -ne 0; then \
skipped="($$skip tests were not run)"; \
test `echo "$$skipped" | wc -c` -gt `echo "$$banner" | wc -c` && \
dashes="$$skipped"; \
fi; \
report=""; \
if test "$$failed" -ne 0 && test -n "$(PACKAGE_BUGREPORT)"; then \
report="Please report to $(PACKAGE_BUGREPORT)"; \
test `echo "$$report" | wc -c` -gt `echo "$$banner" | wc -c` && \
dashes="$$report"; \
fi; \
dashes=`echo "$$dashes" | sed s/./=/g`; \
echo "$$dashes"; \
echo "$$banner"; \
test -n "$$skipped" && echo "$$skipped"; \
test -n "$$report" && echo "$$report"; \
echo "$$dashes"; \
test "$$failed" -eq 0; \
else :; fi
distdir: $(DISTFILES)
@srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
list='$(DISTFILES)'; for file in $$list; do \
case $$file in \
$(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
$(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
esac; \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
if test "$$dir" != "$$file" && test "$$dir" != "."; then \
dir="/$$dir"; \
$(mkdir_p) "$(distdir)$$dir"; \
else \
dir=''; \
fi; \
if test -d $$d/$$file; then \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
fi; \
cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
else \
test -f $(distdir)/$$file \
|| cp -p $$d/$$file $(distdir)/$$file \
|| exit 1; \
fi; \
done
check-am: all-am
$(MAKE) $(AM_MAKEFLAGS) check-TESTS
check: check-am
all-am: Makefile $(PROGRAMS) all-local
installdirs:
$(mkdir_p) $(DESTDIR)$(libexecdir)
install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-am
install-strip:
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
`test -z '$(STRIP)' || \
echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
mostlyclean-generic:
clean-generic:
distclean-generic:
-rm -f $(CONFIG_CLEAN_FILES)
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-am
clean-am: clean-generic clean-libexecPROGRAMS clean-local \
mostlyclean-am
distclean: distclean-am
-rm -rf ./$(DEPDIR)
-rm -f Makefile
distclean-am: clean-am distclean-compile distclean-generic \
distclean-tags
dvi: dvi-am
dvi-am:
html: html-am
info: info-am
info-am:
install-data-am:
install-exec-am: install-libexecPROGRAMS
@$(NORMAL_INSTALL)
$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
install-info: install-info-am
install-man:
installcheck-am:
maintainer-clean: maintainer-clean-am
-rm -rf ./$(DEPDIR)
-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-am
mostlyclean-am: mostlyclean-compile mostlyclean-generic
pdf: pdf-am
pdf-am:
ps: ps-am
ps-am:
uninstall-am: uninstall-info-am uninstall-libexecPROGRAMS \
uninstall-local
.PHONY: CTAGS GTAGS all all-am all-local check check-TESTS check-am \
clean clean-generic clean-libexecPROGRAMS clean-local ctags \
distclean distclean-compile distclean-generic distclean-tags \
distdir dvi dvi-am html html-am info info-am install \
install-am install-data install-data-am install-exec \
install-exec-am install-info install-info-am \
install-libexecPROGRAMS install-man install-strip installcheck \
installcheck-am installdirs maintainer-clean \
maintainer-clean-generic mostlyclean mostlyclean-compile \
mostlyclean-generic pdf pdf-am ps ps-am tags uninstall \
uninstall-am uninstall-info-am uninstall-libexecPROGRAMS \
uninstall-local
test:
perl -I $(top_builddir) -I $(top_srcdir) ../test.pl
##############################################################################
# secondary dependencies
popen.o: popen.c popen.h $(PLUGINHDRS)
utils.o: utils.c utils.h $(PLUGINHDRS)
netutils.o: netutils.c netutils.h $(PLUGINHDRS)
getaddrinfo.o: getaddrinfo.h $(PLUGINHDRS)
gethostbyname.o: gethostbyname.h $(PLUGINHDRS)
all-local: $(check_tcp_programs)
$(check_tcp_programs): check_tcp
rm -f $@
ln -s check_tcp $@
install-exec-hook:
cd $(DESTDIR)$(libexecdir) && \
for i in $(check_tcp_programs) ; do rm -f $$i; ln -s check_tcp $$i ; done ;\
if [ -x check_ldaps ] ; then rm -f check_ldaps ; ln -s check_ldap check_ldaps ; fi
clean-local:
rm -f $(check_tcp_programs)
uninstall-local:
cd $(DESTDIR)$(libexecdir) && rm -f $(check_tcp_programs)
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:

413
plugins/check_by_ssh.c Normal file
View file

@ -0,0 +1,413 @@
/******************************************************************************
The Nagios Plugins are free software; you can redistribute them
and/or modify them under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_by_ssh.c,v 1.35 2004/12/25 12:09:19 opensides Exp $
*****************************************************************************/
const char *progname = "check_by_ssh";
const char *revision = "$Revision: 1.35 $";
const char *copyright = "2000-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "netutils.h"
#include "utils.h"
#include "popen.h"
int process_arguments (int, char **);
int validate_arguments (void);
void print_help (void);
void print_usage (void);
int commands = 0;
int services = 0;
int skip_lines = 0;
char *remotecmd = NULL;
char *comm = NULL;
char *hostname = NULL;
char *outputfile = NULL;
char *host_shortname = NULL;
char **service;
int passive = FALSE;
int verbose = FALSE;
int
main (int argc, char **argv)
{
char input_buffer[MAX_INPUT_BUFFER];
char *result_text;
char *status_text;
char *output;
char *eol = NULL;
int cresult;
int result = STATE_UNKNOWN;
time_t local_time;
FILE *fp = NULL;
remotecmd = strdup ("");
comm = strdup (SSH_COMMAND);
result_text = strdup ("");
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
/* process arguments */
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* Set signal handling and alarm timeout */
if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
usage4 (_("Cannot catch SIGALRM"));
}
alarm (timeout_interval);
/* run the command */
if (verbose)
printf ("%s\n", comm);
child_process = spopen (comm);
if (child_process == NULL) {
printf (_("Could not open pipe: %s\n"), comm);
return STATE_UNKNOWN;
}
/* open STDERR for spopen */
child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
if (child_stderr == NULL) {
printf (_("Could not open stderr for %s\n"), SSH_COMMAND);
}
/* build up results from remote command in result_text */
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process))
asprintf (&result_text, "%s%s", result_text, input_buffer);
/* WARNING if output found on stderr */
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
if (skip_lines > 0) {
if (input_buffer[strlen(input_buffer)-1] == '\n') {
skip_lines--;
}
} else {
printf ("%s", input_buffer);
result = STATE_WARNING;
}
}
(void) fclose (child_stderr);
if (result == STATE_WARNING)
return result;
/* close the pipe */
result = spclose (child_process);
/* process output */
if (passive) {
if (!(fp = fopen (outputfile, "a"))) {
printf (_("SSH WARNING: could not open %s\n"), outputfile);
exit (STATE_UNKNOWN);
}
local_time = time (NULL);
commands = 0;
while (result_text && strlen(result_text) > 0) {
status_text = strstr (result_text, "STATUS CODE: ");
if (status_text == NULL) {
printf ("%s", result_text);
return result;
}
asprintf (&output, "%s", result_text);
result_text = strnl (status_text);
eol = strpbrk (output, "\r\n");
if (eol != NULL)
eol[0] = 0;
if (service[commands] && status_text
&& sscanf (status_text, "STATUS CODE: %d", &cresult) == 1) {
fprintf (fp, "[%d] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%d;%s\n",
(int) local_time, host_shortname, service[commands++], cresult,
output);
}
}
}
/* print the first line from the remote command */
else {
eol = strpbrk (result_text, "\r\n");
if (eol)
eol[0] = 0;
printf ("%s\n", result_text);
}
/* return error status from remote command */
return result;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
char *p1, *p2;
int option = 0;
static struct option longopts[] = {
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"fork", no_argument, 0, 'f'},
{"timeout", required_argument, 0, 't'},
{"host", required_argument, 0, 'H'},
{"port", required_argument,0,'p'},
{"output", required_argument, 0, 'O'},
{"name", required_argument, 0, 'n'},
{"services", required_argument, 0, 's'},
{"identity", required_argument, 0, 'i'},
{"user", required_argument, 0, 'u'},
{"logname", required_argument, 0, 'l'},
{"command", required_argument, 0, 'C'},
{"skip", required_argument, 0, 'S'},
{"proto1", no_argument, 0, '1'},
{"proto2", no_argument, 0, '2'},
{"use-ipv4", no_argument, 0, '4'},
{"use-ipv6", no_argument, 0, '6'},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
for (c = 1; c < argc; c++)
if (strcmp ("-to", argv[c]) == 0)
strcpy (argv[c], "-t");
while (1) {
c = getopt_long (argc, argv, "Vvh1246ft:H:O:p:i:u:l:C:S:n:s:", longopts,
&option);
if (c == -1 || c == EOF)
break;
switch (c) {
case '?': /* help */
usage2 (_("Unknown argument"), optarg);
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case 'v': /* help */
verbose = TRUE;
break;
case 't': /* timeout period */
if (!is_integer (optarg))
usage2 (_("Timeout interval must be a positive integer"), optarg);
else
timeout_interval = atoi (optarg);
break;
case 'H': /* host */
if (!is_host (optarg))
usage2 (_("Invalid hostname/address"), optarg);
hostname = optarg;
break;
case 'p': /* port number */
if (!is_integer (optarg))
usage2 (_("Port must be a positive integer"), optarg);
asprintf (&comm,"%s -p %s", comm, optarg);
break;
case 'O': /* output file */
outputfile = optarg;
passive = TRUE;
break;
case 's': /* description of service to check */
service = realloc (service, (++services) * sizeof(char *));
p1 = optarg;
while ((p2 = index (p1, ':'))) {
*p2 = '\0';
asprintf (&service[services-1], "%s", p1);
service = realloc (service, (++services) * sizeof(char *));
p1 = p2 + 1;
}
asprintf (&service[services-1], "%s", p1);
break;
case 'n': /* short name of host in nagios configuration */
host_shortname = optarg;
break;
case 'u':
c = 'l';
case 'l': /* login name */
case 'i': /* identity */
asprintf (&comm, "%s -%c %s", comm, c, optarg);
break;
case '1': /* Pass these switches directly to ssh */
case '2': /* 1 to force version 1, 2 to force version 2 */
case '4': /* -4 for IPv4 */
case '6': /* -6 for IPv6 */
case 'f': /* fork to background */
asprintf (&comm, "%s -%c", comm, c);
break;
case 'C': /* Command for remote machine */
commands++;
if (commands > 1)
asprintf (&remotecmd, "%s;echo STATUS CODE: $?;", remotecmd);
asprintf (&remotecmd, "%s%s", remotecmd, optarg);
break;
case 'S': /* Skip n lines in the output to ignore system banner */
if (!is_integer (optarg))
usage2 (_("skip lines must be an integer"), optarg);
else
skip_lines = atoi (optarg);
break;
}
}
c = optind;
if (hostname == NULL) {
if (c <= argc) {
die (STATE_UNKNOWN, _("%s: You must provide a host name\n"), progname);
} else if (!is_host (argv[c]))
die (STATE_UNKNOWN, "%s: %s %s\n", progname, _("Invalid hostname/address"), argv[c]);
hostname = argv[c++];
}
if (strlen(remotecmd) == 0) {
for (; c < argc; c++)
if (strlen(remotecmd) > 0)
asprintf (&remotecmd, "%s %s", remotecmd, argv[c]);
else
asprintf (&remotecmd, "%s", argv[c]);
}
if (commands > 1)
asprintf (&remotecmd, "%s;echo STATUS CODE: $?;", remotecmd);
if (remotecmd == NULL || strlen (remotecmd) <= 1)
usage4 (_("No remotecmd"));
asprintf (&comm, "%s %s '%s'", comm, hostname, remotecmd);
return validate_arguments ();
}
int
validate_arguments (void)
{
if (remotecmd == NULL || hostname == NULL)
return ERROR;
if (passive && commands != services)
die (STATE_UNKNOWN, _("%s: In passive mode, you must provide a service name for each command.\n"), progname);
if (passive && host_shortname == NULL)
die (STATE_UNKNOWN, _("%s: In passive mode, you must provide the host short name from the nagios configs.\n"), progname);
return OK;
}
void
print_help (void)
{
print_revision (progname, revision);
printf ("Copyright (c) 1999 Karl DeBisschop <kdebisschop@users.sourceforge.net>\n");
printf (COPYRIGHT, copyright, email);
printf (_("This plugin uses SSH to execute commands on a remote host\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_(UT_HOST_PORT), 'p', "none");
printf (_(UT_IPv46));
printf (_("\
-1, --proto1\n\
tell ssh to use Protocol 1\n\
-2, --proto2\n\
tell ssh to use Protocol 2\n\
-S, --skiplines=n\n\
Ignore first n lines on STDERR (to suppress a logon banner)\n\
-f\n\
tells ssh to fork rather than create a tty\n"));
printf (_("\
-C, --command='COMMAND STRING'\n\
command to execute on the remote machine\n\
-l, --logname=USERNAME\n\
SSH user name on remote host [optional]\n\
-i, --identity=KEYFILE\n\
identity of an authorized key [optional]\n\
-O, --output=FILE\n\
external command file for nagios [optional]\n\
-s, --services=LIST\n\
list of nagios service names, separated by ':' [optional]\n\
-n, --name=NAME\n\
short name of host in nagios configuration [optional]\n"));
printf (_(UT_WARN_CRIT));
printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
printf (_("\n\
The most common mode of use is to refer to a local identity file with\n\
the '-i' option. In this mode, the identity pair should have a null\n\
passphrase and the public key should be listed in the authorized_keys\n\
file of the remote host. Usually the key will be restricted to running\n\
only one command on the remote server. If the remote SSH server tracks\n\
invocation agruments, the one remote program may be an agent that can\n\
execute additional commands as proxy\n"));
printf (_("\n\
To use passive mode, provide multiple '-C' options, and provide\n\
all of -O, -s, and -n options (servicelist order must match '-C'\n\
options)\n"));
printf ("\n\
$ check_by_ssh -H localhost -n lh -s c1:c2:c3 \\\n\
-C uptime -C uptime -C uptime -O /tmp/foo\n\
$ cat /tmp/foo\n\
[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c1;0; up 2 days...\n\
[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c2;0; up 2 days...\n\
[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c3;0; up 2 days...\n");
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\n\
Usage: %s [-f46] [-t timeout] [-i identity] [-l user] -H <host> -C <command>\n\
[-n name] [-s servicelist] [-O outputfile] [-p port]\n", progname);
}

1261
plugins/check_dhcp.c Normal file

File diff suppressed because it is too large Load diff

364
plugins/check_dig.c Normal file
View file

@ -0,0 +1,364 @@
/*****************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_dig.c,v 1.40 2005/01/26 21:21:01 tonvoon Exp $
*****************************************************************************/
const char *progname = "check_dig";
const char *revision = "$Revision: 1.40 $";
const char *copyright = "2002-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "netutils.h"
#include "utils.h"
#include "popen.h"
int process_arguments (int, char **);
int validate_arguments (void);
void print_help (void);
void print_usage (void);
enum {
UNDEFINED = 0,
DEFAULT_PORT = 53
};
char *query_address = NULL;
char *record_type = "A";
char *expected_address = NULL;
char *dns_server = NULL;
int verbose = FALSE;
int server_port = DEFAULT_PORT;
double warning_interval = UNDEFINED;
double critical_interval = UNDEFINED;
struct timeval tv;
int
main (int argc, char **argv)
{
char input_buffer[MAX_INPUT_BUFFER];
char *command_line;
char *output;
char *t;
long microsec;
double elapsed_time;
int result = STATE_UNKNOWN;
output = strdup ("");
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
/* Set signal handling and alarm */
if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR)
usage4 (_("Cannot catch SIGALRM"));
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* get the command to run */
asprintf (&command_line, "%s @%s -p %d %s -t %s",
PATH_TO_DIG, dns_server, server_port, query_address, record_type);
alarm (timeout_interval);
gettimeofday (&tv, NULL);
if (verbose) {
printf ("%s\n", command_line);
if(expected_address != NULL) {
printf (_("Looking for: '%s'\n"), expected_address);
} else {
printf (_("Looking for: '%s'\n"), query_address);
}
}
/* run the command */
child_process = spopen (command_line);
if (child_process == NULL) {
printf (_("Could not open pipe: %s\n"), command_line);
return STATE_UNKNOWN;
}
child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
if (child_stderr == NULL)
printf (_("Could not open stderr for %s\n"), command_line);
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
/* the server is responding, we just got the host name... */
if (strstr (input_buffer, ";; ANSWER SECTION:")) {
/* loop through the whole 'ANSWER SECTION' */
do {
/* get the host address */
if (!fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process))
break;
if (strpbrk (input_buffer, "\r\n"))
input_buffer[strcspn (input_buffer, "\r\n")] = '\0';
if (verbose && !strstr (input_buffer, ";; "))
printf ("%s\n", input_buffer);
if (expected_address==NULL && strstr (input_buffer, query_address) != NULL) {
output = strdup(input_buffer);
result = STATE_OK;
}
else if (expected_address != NULL && strstr (input_buffer, expected_address) != NULL) {
output = strdup(input_buffer);
result = STATE_OK;
}
/* Translate output TAB -> SPACE */
t = output;
while ((t = index(t, '\t')) != NULL)
*t = ' ';
} while (!strstr (input_buffer, ";; "));
if (result == STATE_UNKNOWN) {
asprintf (&output, _("Server not found in ANSWER SECTION"));
result = STATE_WARNING;
}
}
}
if (result == STATE_UNKNOWN) {
asprintf (&output, _("No ANSWER SECTION found"));
}
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
/* If we get anything on STDERR, at least set warning */
result = max_state (result, STATE_WARNING);
printf ("%s", input_buffer);
if (strlen (output) == 0)
output = strdup (1 + index (input_buffer, ':'));
}
(void) fclose (child_stderr);
/* close the pipe */
if (spclose (child_process)) {
result = max_state (result, STATE_WARNING);
if (strlen (output) == 0)
asprintf (&output, _("dig returned an error status"));
}
microsec = deltime (tv);
elapsed_time = (double)microsec / 1.0e6;
if (output == NULL || strlen (output) == 0)
asprintf (&output, _(" Probably a non-existent host/domain"));
if (critical_interval > UNDEFINED && elapsed_time > critical_interval)
result = STATE_CRITICAL;
else if (warning_interval > UNDEFINED && elapsed_time > warning_interval)
result = STATE_WARNING;
asprintf (&output, _("%.3f seconds response time (%s)"), elapsed_time, output);
printf ("DNS %s - %s|%s\n",
state_text (result), output,
fperfdata("time", elapsed_time, "s",
(warning_interval>UNDEFINED?TRUE:FALSE),
warning_interval,
(critical_interval>UNDEFINED?TRUE:FALSE),
critical_interval,
TRUE, 0, FALSE, 0));
return result;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"hostname", required_argument, 0, 'H'},
{"query_address", required_argument, 0, 'l'},
{"warning", required_argument, 0, 'w'},
{"critical", required_argument, 0, 'c'},
{"timeout", required_argument, 0, 't'},
{"verbose", no_argument, 0, 'v'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{"record_type", required_argument, 0, 'T'},
{"expected_address", required_argument, 0, 'a'},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
while (1) {
c = getopt_long (argc, argv, "hVvt:l:H:w:c:T:a:", longopts, &option);
if (c == -1 || c == EOF)
break;
switch (c) {
case '?': /* help */
usage2 (_("Unknown argument"), optarg);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'H': /* hostname */
if (is_host (optarg)) {
dns_server = optarg;
}
else {
usage2 (_("Invalid hostname/address"), optarg);
}
break;
case 'p': /* server port */
if (is_intpos (optarg)) {
server_port = atoi (optarg);
}
else {
usage2 (_("Port must be a positive integer"), optarg);
}
break;
case 'l': /* address to lookup */
query_address = optarg;
break;
case 'w': /* warning */
if (is_nonnegative (optarg)) {
warning_interval = strtod (optarg, NULL);
}
else {
usage2 (_("Warning interval must be a positive integer"), optarg);
}
break;
case 'c': /* critical */
if (is_nonnegative (optarg)) {
critical_interval = strtod (optarg, NULL);
}
else {
usage2 (_("Critical interval must be a positive integer"), optarg);
}
break;
case 't': /* timeout */
if (is_intnonneg (optarg)) {
timeout_interval = atoi (optarg);
}
else {
usage2 (_("Timeout interval must be a positive integer"), optarg);
}
break;
case 'v': /* verbose */
verbose = TRUE;
break;
case 'T':
record_type = optarg;
break;
case 'a':
expected_address = optarg;
break;
}
}
c = optind;
if (dns_server == NULL) {
if (c < argc) {
if (is_host (argv[c])) {
dns_server = argv[c];
}
else {
usage2 (_("Invalid hostname/address"), argv[c]);
}
}
else {
dns_server = strdup ("127.0.0.1");
}
}
return validate_arguments ();
}
int
validate_arguments (void)
{
return OK;
}
void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", DEFAULT_PORT);
print_revision (progname, revision);
printf ("Copyright (c) 2000 Karl DeBisschop <kdebisschop@users.sourceforge.net>\n");
printf (COPYRIGHT, copyright, email);
printf (_("Test the DNS service on the specified host using dig\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_(UT_HOST_PORT), 'P', myport);
printf (_("\
-l, --lookup=STRING\n\
machine name to lookup\n"));
printf (_("\
-T, --record_type=STRING\n\
record type to lookup (default: A)\n"));
printf (_("\
-a, --expected_address=STRING\n\
an address expected to be in the answer section.\n\
if not set, uses whatever was in -l\n"));
printf (_(UT_WARN_CRIT));
printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
printf (_(UT_VERBOSE));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s -H host -l lookup [-p <server port>] [-T <query type>]\n\
[-w <warning interval>] [-c <critical interval>] [-t <timeout>]\n\
[-a <expected answer address>] [-v]\n", progname);
}

640
plugins/check_disk.c Normal file
View file

@ -0,0 +1,640 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_disk.c,v 1.57 2005/03/04 21:58:40 tonvoon Exp $
*****************************************************************************/
const char *progname = "check_disk";
const char *program_name = "check_disk"; /* Required for coreutils libs */
const char *revision = "$Revision: 1.57 $";
const char *copyright = "1999-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#if HAVE_INTTYPES_H
# include <inttypes.h>
#endif
#include <assert.h>
#include "popen.h"
#include "utils.h"
#include <stdarg.h>
#include "../lib/fsusage.h"
#include "../lib/mountlist.h"
#if HAVE_LIMITS_H
# include <limits.h>
#endif
/* If nonzero, show inode information. */
/* static int inode_format; */
/* If nonzero, show even filesystems with zero size or
uninteresting types. */
static int show_all_fs = 1;
/* If nonzero, show only local filesystems. */
static int show_local_fs = 0;
/* If positive, the units to use when printing sizes;
if negative, the human-readable base. */
/* static int output_block_size; */
/* If nonzero, invoke the `sync' system call before getting any usage data.
Using this option can make df very slow, especially with many or very
busy disks. Note that this may make a difference on some systems --
SunOs4.1.3, for one. It is *not* necessary on Linux. */
/* static int require_sync = 0; */
/* A filesystem type to display. */
struct name_list
{
char *name;
int found;
uintmax_t w_df;
uintmax_t c_df;
double w_dfp;
double c_dfp;
struct name_list *name_next;
};
/* Linked list of filesystem types to display.
If `fs_select_list' is NULL, list all types.
This table is generated dynamically from command-line options,
rather than hardcoding into the program what it thinks are the
valid filesystem types; let the user specify any filesystem type
they want to, and if there are any filesystems of that type, they
will be shown.
Some filesystem types:
4.2 4.3 ufs nfs swap ignore io vm efs dbg */
/* static struct name_list *fs_select_list; */
/* Linked list of filesystem types to omit.
If the list is empty, don't exclude any types. */
static struct name_list *fs_exclude_list;
static struct name_list *dp_exclude_list;
static struct name_list *path_select_list;
static struct name_list *dev_select_list;
/* Linked list of mounted filesystems. */
static struct mount_entry *mount_list;
/* For long options that have no equivalent short option, use a
non-character as a pseudo short option, starting with CHAR_MAX + 1. */
enum
{
SYNC_OPTION = CHAR_MAX + 1,
NO_SYNC_OPTION,
BLOCK_SIZE_OPTION
};
#ifdef _AIX
#pragma alloca
#endif
int process_arguments (int, char **);
void print_path (const char *mypath);
int validate_arguments (uintmax_t, uintmax_t, double, double, char *);
int check_disk (double usp, double free_disk);
int walk_name_list (struct name_list *list, const char *name);
void print_help (void);
void print_usage (void);
uintmax_t w_df = 0;
uintmax_t c_df = 0;
double w_dfp = -1.0;
double c_dfp = -1.0;
char *path;
char *exclude_device;
char *units;
uintmax_t mult = 1024 * 1024;
int verbose = 0;
int erronly = FALSE;
int display_mntp = FALSE;
/* Linked list of mounted filesystems. */
static struct mount_entry *mount_list;
int
main (int argc, char **argv)
{
double usp = -1.0;
int result = STATE_UNKNOWN;
int disk_result = STATE_UNKNOWN;
char file_system[MAX_INPUT_BUFFER];
char *output;
char *details;
char *perf;
uintmax_t psize;
float free_space, free_space_pct, total_space;
struct mount_entry *me;
struct fs_usage fsp;
struct name_list *temp_list;
output = strdup (" - free space:");
details = strdup ("");
perf = strdup ("");
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
mount_list = read_filesystem_list (0);
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
for (me = mount_list; me; me = me->me_next) {
if (path_select_list &&
(walk_name_list (path_select_list, me->me_mountdir) ||
walk_name_list (path_select_list, me->me_devname) ) )
get_fs_usage (me->me_mountdir, me->me_devname, &fsp);
else if (dev_select_list || path_select_list)
continue;
else if (me->me_remote && show_local_fs)
continue;
else if (me->me_dummy && !show_all_fs)
continue;
else if (fs_exclude_list && walk_name_list (fs_exclude_list, me->me_type))
continue;
else if (dp_exclude_list &&
(walk_name_list (dp_exclude_list, me->me_devname) ||
walk_name_list (dp_exclude_list, me->me_mountdir)))
continue;
else
get_fs_usage (me->me_mountdir, me->me_devname, &fsp);
if (fsp.fsu_blocks && strcmp ("none", me->me_mountdir)) {
usp = (double)(fsp.fsu_blocks - fsp.fsu_bavail) * 100 / fsp.fsu_blocks;
disk_result = check_disk (usp, (double)(fsp.fsu_bavail * fsp.fsu_blocksize / mult));
result = max_state (disk_result, result);
psize = fsp.fsu_blocks*fsp.fsu_blocksize/mult;
asprintf (&perf, "%s %s", perf,
perfdata ((!strcmp(file_system, "none") || display_mntp) ? me->me_devname : me->me_mountdir,
psize-(fsp.fsu_bavail*fsp.fsu_blocksize/mult), units,
TRUE, min ((uintmax_t)psize-(uintmax_t)w_df, (uintmax_t)((1.0-w_dfp/100.0)*psize)),
TRUE, min ((uintmax_t)psize-(uintmax_t)c_df, (uintmax_t)((1.0-c_dfp/100.0)*psize)),
TRUE, 0,
TRUE, psize));
if (disk_result==STATE_OK && erronly && !verbose)
continue;
free_space = (float)fsp.fsu_bavail*fsp.fsu_blocksize/mult;
free_space_pct = (float)fsp.fsu_bavail*100/fsp.fsu_blocks;
total_space = (float)fsp.fsu_blocks*fsp.fsu_blocksize/mult;
if (disk_result!=STATE_OK || verbose>=0)
asprintf (&output, ("%s %s %.0f %s (%.0f%%);"),
output,
(!strcmp(file_system, "none") || display_mntp) ? me->me_devname : me->me_mountdir,
free_space,
units,
free_space_pct);
asprintf (&details, _("%s\n\
%.0f of %.0f %s (%.0f%%) free on %s (type %s mounted on %s) warn:%lu crit:%lu warn%%:%.0f%% crit%%:%.0f%%"),
details, free_space, total_space, units, free_space_pct,
me->me_devname, me->me_type, me->me_mountdir,
(unsigned long)w_df, (unsigned long)c_df, w_dfp, c_dfp);
}
}
asprintf (&output, "%s|%s", output, perf);
if (verbose > 2)
asprintf (&output, "%s%s", output, details);
/* Override result if paths specified and not found */
temp_list = path_select_list;
while (temp_list) {
if (temp_list->found != TRUE) {
asprintf (&output, _("%s [%s not found]"), output, temp_list->name);
result = STATE_CRITICAL;
}
temp_list = temp_list->name_next;
}
printf ("DISK %s%s\n", state_text (result), output);
return result;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
struct name_list *se;
struct name_list **pathtail = &path_select_list;
struct name_list **fstail = &fs_exclude_list;
struct name_list **dptail = &dp_exclude_list;
struct name_list *temp_list;
int result = OK;
unsigned long l;
int option = 0;
static struct option longopts[] = {
{"timeout", required_argument, 0, 't'},
{"warning", required_argument, 0, 'w'},
{"critical", required_argument, 0, 'c'},
{"local", required_argument, 0, 'l'},
{"kilobytes", required_argument, 0, 'k'},
{"megabytes", required_argument, 0, 'm'},
{"units", required_argument, 0, 'u'},
{"path", required_argument, 0, 'p'},
{"partition", required_argument, 0, 'p'},
{"exclude_device", required_argument, 0, 'x'},
{"exclude-type", required_argument, 0, 'X'},
{"mountpoint", no_argument, 0, 'M'},
{"errors-only", no_argument, 0, 'e'},
{"verbose", no_argument, 0, 'v'},
{"quiet", no_argument, 0, 'q'},
{"clear", no_argument, 0, 'C'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
se = (struct name_list *) malloc (sizeof (struct name_list));
se->name = strdup ("iso9660");
se->name_next = NULL;
*fstail = se;
fstail = &se->name_next;
for (c = 1; c < argc; c++)
if (strcmp ("-to", argv[c]) == 0)
strcpy (argv[c], "-t");
while (1) {
c = getopt_long (argc, argv, "+?VqhveCt:c:w:u:p:x:X:mklM", longopts, &option);
if (c == -1 || c == EOF)
break;
switch (c) {
case 't': /* timeout period */
if (is_integer (optarg)) {
timeout_interval = atoi (optarg);
break;
}
else {
usage2 (_("Timeout interval must be a positive integer"), optarg);
}
case 'w': /* warning threshold */
if (is_intnonneg (optarg)) {
w_df = atoi (optarg);
break;
}
else if (strpbrk (optarg, ",:") &&
strstr (optarg, "%") &&
sscanf (optarg, "%lu%*[:,]%lf%%", &l, &w_dfp) == 2) {
w_df = (uintmax_t)l;
break;
}
else if (strstr (optarg, "%") && sscanf (optarg, "%lf%%", &w_dfp) == 1) {
break;
}
else {
usage4 (_("Warning threshold must be integer or percentage!"));
}
case 'c': /* critical threshold */
if (is_intnonneg (optarg)) {
c_df = atoi (optarg);
break;
}
else if (strpbrk (optarg, ",:") &&
strstr (optarg, "%") &&
sscanf (optarg, "%lu%*[,:]%lf%%", &l, &c_dfp) == 2) {
c_df = (uintmax_t)l;
break;
}
else if (strstr (optarg, "%") && sscanf (optarg, "%lf%%", &c_dfp) == 1) {
break;
}
else {
usage4 (_("Critical threshold must be integer or percentage!"));
}
case 'u':
if (units)
free(units);
if (! strcmp (optarg, "bytes")) {
mult = (uintmax_t)1;
units = strdup ("B");
} else if (! strcmp (optarg, "kB")) {
mult = (uintmax_t)1024;
units = strdup ("kB");
} else if (! strcmp (optarg, "MB")) {
mult = (uintmax_t)1024 * 1024;
units = strdup ("MB");
} else if (! strcmp (optarg, "GB")) {
mult = (uintmax_t)1024 * 1024 * 1024;
units = strdup ("GB");
} else if (! strcmp (optarg, "TB")) {
mult = (uintmax_t)1024 * 1024 * 1024 * 1024;
units = strdup ("TB");
} else {
die (STATE_UNKNOWN, _("unit type %s not known\n"), optarg);
}
if (units == NULL)
die (STATE_UNKNOWN, _("failed allocating storage for '%s'\n"), "units");
break;
case 'k': /* display mountpoint */
mult = 1024;
if (units)
free(units);
units = strdup ("kB");
break;
case 'm': /* display mountpoint */
mult = 1024 * 1024;
if (units)
free(units);
units = strdup ("MB");
break;
case 'l':
show_local_fs = 1;
break;
case 'p': /* select path */
se = (struct name_list *) malloc (sizeof (struct name_list));
se->name = optarg;
se->name_next = NULL;
se->w_df = w_df;
se->c_df = c_df;
se->w_dfp = w_dfp;
se->c_dfp = c_dfp;
*pathtail = se;
pathtail = &se->name_next;
break;
case 'x': /* exclude path or partition */
se = (struct name_list *) malloc (sizeof (struct name_list));
se->name = optarg;
se->name_next = NULL;
se->w_df = 0;
se->c_df = 0;
se->w_dfp = -1.0;
se->c_dfp = -1.0;
*dptail = se;
dptail = &se->name_next;
break;
case 'X': /* exclude file system type */
se = (struct name_list *) malloc (sizeof (struct name_list));
se->name = optarg;
se->name_next = NULL;
se->w_df = 0;
se->c_df = 0;
se->w_dfp = -1.0;
se->c_dfp = -1.0;
*fstail = se;
fstail = &se->name_next;
break;
case 'v': /* verbose */
verbose++;
break;
case 'q': /* verbose */
verbose--;
break;
case 'e':
erronly = TRUE;
break;
case 'M': /* display mountpoint */
display_mntp = TRUE;
break;
case 'C':
w_df = 0;
c_df = 0;
w_dfp = -1.0;
c_dfp = -1.0;
break;
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case '?': /* help */
usage2 (_("Unknown argument"), optarg);
}
}
/* Support for "check_disk warn crit [fs]" with thresholds at used level */
c = optind;
if (w_dfp < 0 && argc > c && is_intnonneg (argv[c]))
w_dfp = (100.0 - atof (argv[c++]));
if (c_dfp < 0 && argc > c && is_intnonneg (argv[c]))
c_dfp = (100.0 - atof (argv[c++]));
if (argc > c && path == NULL) {
se = (struct name_list *) malloc (sizeof (struct name_list));
se->name = strdup (argv[c++]);
se->name_next = NULL;
se->w_df = w_df;
se->c_df = c_df;
se->w_dfp = w_dfp;
se->c_dfp = c_dfp;
*pathtail = se;
}
if (path_select_list) {
temp_list = path_select_list;
while (temp_list) {
if (validate_arguments (temp_list->w_df,
temp_list->c_df,
temp_list->w_dfp,
temp_list->c_dfp,
temp_list->name) == ERROR)
result = ERROR;
temp_list = temp_list->name_next;
}
return result;
} else {
return validate_arguments (w_df, c_df, w_dfp, c_dfp, NULL);
}
}
void
print_path (const char *mypath)
{
if (mypath == NULL)
printf ("\n");
else
printf (_(" for %s\n"), mypath);
return;
}
int
validate_arguments (uintmax_t w, uintmax_t c, double wp, double cp, char *mypath)
{
if (w < 0 && c < 0 && wp < 0.0 && cp < 0.0) {
printf (_("INPUT ERROR: No thresholds specified"));
print_path (mypath);
return ERROR;
}
else if ((wp >= 0.0 || cp >= 0.0) &&
(wp < 0.0 || cp < 0.0 || wp > 100.0 || cp > 100.0 || cp > wp)) {
printf (_("\
INPUT ERROR: C_DFP (%f) should be less than W_DFP (%.1f) and both should be between zero and 100 percent, inclusive"),
cp, wp);
print_path (mypath);
return ERROR;
}
else if ((w > 0 || c > 0) && (w == 0 || c == 0 || c > w)) {
printf (_("\
INPUT ERROR: C_DF (%lu) should be less than W_DF (%lu) and both should be greater than zero"),
(unsigned long)c, (unsigned long)w);
print_path (mypath);
return ERROR;
}
if (units == NULL) {
units = strdup ("MB");
mult = (uintmax_t)1024 * 1024;
}
return OK;
}
int
check_disk (double usp, double free_disk)
{
int result = STATE_UNKNOWN;
/* check the percent used space against thresholds */
if (usp >= 0.0 && c_dfp >=0.0 && usp >= (100.0 - c_dfp))
result = STATE_CRITICAL;
else if (c_df > 0 && free_disk <= c_df)
result = STATE_CRITICAL;
else if (usp >= 0.0 && w_dfp >=0.0 && usp >= (100.0 - w_dfp))
result = STATE_WARNING;
else if (w_df > 0 && free_disk <= w_df)
result = STATE_WARNING;
else if (usp >= 0.0)
result = STATE_OK;
return result;
}
int
walk_name_list (struct name_list *list, const char *name)
{
while (list) {
if (! strcmp(list->name, name)) {
list->found = 1;
/* if required for name_lists that have not saved w_df, etc (eg exclude lists) */
if (list->w_df) w_df = list->w_df;
if (list->c_df) c_df = list->c_df;
if (list->w_dfp>=0.0) w_dfp = list->w_dfp;
if (list->c_dfp>=0.0) c_dfp = list->c_dfp;
return TRUE;
}
list = list->name_next;
}
return FALSE;
}
void
print_help (void)
{
print_revision (progname, revision);
printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
printf (COPYRIGHT, copyright, email);
printf (_("\
This plugin checks the amount of used disk space on a mounted file system\n\
and generates an alert if free space is less than one of the threshold values.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_("\
-w, --warning=INTEGER\n\
Exit with WARNING status if less than INTEGER --units of disk are free\n\
-w, --warning=PERCENT%%\n\
Exit with WARNING status if less than PERCENT of disk space is free\n\
-c, --critical=INTEGER\n\
Exit with CRITICAL status if less than INTEGER --units of disk are free\n\
-c, --critical=PERCENT%%\n\
Exit with CRITCAL status if less than PERCENT of disk space is free\n\
-C, --clear\n\
Clear thresholds\n"));
printf (_("\
-u, --units=STRING\n\
Choose bytes, kB, MB, GB, TB (default: MB)\n\
-k, --kilobytes\n\
Same as '--units kB'\n\
-m, --megabytes\n\
Same as '--units MB'\n"));
printf (_("\
-l, --local\n\
Only check local filesystems\n\
-p, --path=PATH, --partition=PARTITION\n\
Path or partition (may be repeated)\n\
-x, --exclude_device=PATH <STRING>\n\
Ignore device (only works if -p unspecified)\n\
-X, --exclude-type=TYPE <STRING>\n\
Ignore all filesystems of indicated type (may be repeated)\n\
-M, --mountpoint\n\
Display the mountpoint instead of the partition\n\
-e, --errors-only\n\
Display only devices/mountpoints with errors\n"));
printf (_(UT_WARN_CRIT));
printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
printf (_(UT_VERBOSE));
printf ("%s", _("Examples:\n\
check_disk -w 10% -c 5% -p /tmp -p /var -C -w 100000 -c 50000 -p /\n\
Checks /tmp and /var at 10%,5% and / at 100MB, 50MB\n"));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s -w limit -c limit [-p path | -x device] [-t timeout] [-m] [-e]\n\
[-v] [-q]\n", progname);
}

435
plugins/check_dns.c Normal file
View file

@ -0,0 +1,435 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
LIMITATION: nslookup on Solaris 7 can return output over 2 lines, which will not
be picked up by this plugin
$Id: check_dns.c,v 1.47 2004/12/30 00:41:39 opensides Exp $
******************************************************************************/
const char *progname = "check_dns";
const char *revision = "$Revision: 1.47 $";
const char *copyright = "2000-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "popen.h"
#include "utils.h"
#include "netutils.h"
int process_arguments (int, char **);
int validate_arguments (void);
int error_scan (char *);
void print_help (void);
void print_usage (void);
#define ADDRESS_LENGTH 256
char query_address[ADDRESS_LENGTH] = "";
char dns_server[ADDRESS_LENGTH] = "";
char ptr_server[ADDRESS_LENGTH] = "";
int verbose = FALSE;
char expected_address[ADDRESS_LENGTH] = "";
int match_expected_address = FALSE;
int expect_authority = FALSE;
int
main (int argc, char **argv)
{
char *command_line = NULL;
char input_buffer[MAX_INPUT_BUFFER];
char *output = NULL;
char *address = NULL;
char *temp_buffer = NULL;
int non_authoritative = FALSE;
int result = STATE_UNKNOWN;
double elapsed_time;
long microsec;
struct timeval tv;
int multi_address;
int parse_address = FALSE; /* This flag scans for Address: but only after Name: */
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
/* Set signal handling and alarm */
if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
usage4 (_("Cannot catch SIGALRM"));
}
if (process_arguments (argc, argv) == ERROR) {
usage4 (_("Could not parse arguments"));
}
/* get the command to run */
asprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server);
alarm (timeout_interval);
gettimeofday (&tv, NULL);
if (verbose)
printf ("%s\n", command_line);
/* run the command */
child_process = spopen (command_line);
if (child_process == NULL) {
printf (_("Could not open pipe: %s\n"), command_line);
return STATE_UNKNOWN;
}
child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
if (child_stderr == NULL)
printf (_("Could not open stderr for %s\n"), command_line);
/* scan stdout */
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
if (verbose)
printf ("%s", input_buffer);
if (strstr (input_buffer, ".in-addr.arpa")) {
if ((temp_buffer = strstr (input_buffer, "name = ")))
address = strdup (temp_buffer + 7);
else {
output = strdup (_("Warning plugin error"));
result = STATE_WARNING;
}
}
/* the server is responding, we just got the host name... */
if (strstr (input_buffer, "Name:"))
parse_address = TRUE;
else if (parse_address == TRUE && (strstr (input_buffer, "Address:") ||
strstr (input_buffer, "Addresses:"))) {
temp_buffer = index (input_buffer, ':');
temp_buffer++;
/* Strip leading spaces */
for (; *temp_buffer != '\0' && *temp_buffer == ' '; temp_buffer++)
/* NOOP */;
strip(temp_buffer);
if (temp_buffer==NULL || strlen(temp_buffer)==0) {
die (STATE_CRITICAL,
_("DNS CRITICAL - '%s' returned empty host name string\n"),
NSLOOKUP_COMMAND);
}
if (address == NULL)
address = strdup (temp_buffer);
else
asprintf(&address, "%s,%s", address, temp_buffer);
}
else if (strstr (input_buffer, _("Non-authoritative answer:"))) {
non_authoritative = TRUE;
}
result = error_scan (input_buffer);
if (result != STATE_OK) {
output = strdup (1 + index (input_buffer, ':'));
strip (output);
break;
}
}
/* scan stderr */
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
if (verbose)
printf ("%s", input_buffer);
if (error_scan (input_buffer) != STATE_OK) {
result = max_state (result, error_scan (input_buffer));
output = strdup (1 + index (input_buffer, ':'));
strip (output);
}
}
/* close stderr */
(void) fclose (child_stderr);
/* close stdout */
if (spclose (child_process)) {
result = max_state (result, STATE_WARNING);
if (output == NULL || !strcmp (output, ""))
output = strdup (_("nslookup returned error status"));
}
/* If we got here, we should have an address string,
and we can segfault if we do not */
if (address==NULL || strlen(address)==0)
die (STATE_CRITICAL,
_("DNS CRITICAL - '%s' output parsing exited with no address\n"),
NSLOOKUP_COMMAND);
/* compare to expected address */
if (result == STATE_OK && match_expected_address && strcmp(address, expected_address)) {
result = STATE_CRITICAL;
asprintf(&output, _("expected %s but got %s"), expected_address, address);
}
/* check if authoritative */
if (result == STATE_OK && expect_authority && non_authoritative) {
result = STATE_CRITICAL;
asprintf(&output, _("server %s is not authoritative for %s"), dns_server, query_address);
}
microsec = deltime (tv);
elapsed_time = (double)microsec / 1.0e6;
if (result == STATE_OK) {
if (strchr (address, ',') == NULL)
multi_address = FALSE;
else
multi_address = TRUE;
printf ("DNS %s: ", _("OK"));
printf (ngettext("%.3f second response time ", "%.3f seconds response time ", elapsed_time), elapsed_time);
printf (_("%s returns %s"), query_address, address);
printf ("|%s\n", fperfdata ("time", elapsed_time, "s", FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
}
else if (result == STATE_WARNING)
printf (_("DNS WARNING - %s\n"),
!strcmp (output, "") ? _(" Probably a non-existent host/domain") : output);
else if (result == STATE_CRITICAL)
printf (_("DNS CRITICAL - %s\n"),
!strcmp (output, "") ? _(" Probably a non-existent host/domain") : output);
else
printf (_("DNS UNKNOW - %s\n"),
!strcmp (output, "") ? _(" Probably a non-existent host/domain") : output);
return result;
}
int
error_scan (char *input_buffer)
{
/* the DNS lookup timed out */
if (strstr (input_buffer, _("Note: nslookup is deprecated and may be removed from future releases.")) ||
strstr (input_buffer, _("Consider using the `dig' or `host' programs instead. Run nslookup with")) ||
strstr (input_buffer, _("the `-sil[ent]' option to prevent this message from appearing.")))
return STATE_OK;
/* DNS server is not running... */
else if (strstr (input_buffer, "No response from server"))
die (STATE_CRITICAL, _("No response from DNS %s\n"), dns_server);
/* Host name is valid, but server doesn't have records... */
else if (strstr (input_buffer, "No records"))
die (STATE_CRITICAL, _("DNS %s has no records\n"), dns_server);
/* Connection was refused */
else if (strstr (input_buffer, "Connection refused") ||
strstr (input_buffer, "Couldn't find server") ||
strstr (input_buffer, "Refused") ||
(strstr (input_buffer, "** server can't find") &&
strstr (input_buffer, ": REFUSED")))
die (STATE_CRITICAL, _("Connection to DNS %s was refused\n"), dns_server);
/* Query refused (usually by an ACL in the namserver) */
else if (strstr (input_buffer, "Query refused"))
die (STATE_CRITICAL, _("Query was refused by DNS server at %s\n"), dns_server);
/* No information (e.g. nameserver IP has two PTR records) */
else if (strstr (input_buffer, "No information"))
die (STATE_CRITICAL, _("No information returned by DNS server at %s\n"), dns_server);
/* Host or domain name does not exist */
else if (strstr (input_buffer, "Non-existent") ||
strstr (input_buffer, "** server can't find") ||
strstr (input_buffer,"NXDOMAIN"))
die (STATE_CRITICAL, _("Domain %s was not found by the server\n"), query_address);
/* Network is unreachable */
else if (strstr (input_buffer, "Network is unreachable"))
die (STATE_CRITICAL, _("Network is unreachable\n"));
/* Internal server failure */
else if (strstr (input_buffer, "Server failure"))
die (STATE_CRITICAL, _("DNS failure for %s\n"), dns_server);
/* Request error or the DNS lookup timed out */
else if (strstr (input_buffer, "Format error") ||
strstr (input_buffer, "Timed out"))
return STATE_WARNING;
return STATE_OK;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int opt_index = 0;
static struct option long_opts[] = {
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{"verbose", no_argument, 0, 'v'},
{"timeout", required_argument, 0, 't'},
{"hostname", required_argument, 0, 'H'},
{"server", required_argument, 0, 's'},
{"reverse-server", required_argument, 0, 'r'},
{"expected-address", required_argument, 0, 'a'},
{"expect-authority", no_argument, 0, 'A'},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
for (c = 1; c < argc; c++)
if (strcmp ("-to", argv[c]) == 0)
strcpy (argv[c], "-t");
while (1) {
c = getopt_long (argc, argv, "hVvAt:H:s:r:a:", long_opts, &opt_index);
if (c == -1 || c == EOF)
break;
switch (c) {
case '?': /* args not parsable */
usage2 (_("Unknown argument"), optarg);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'v': /* version */
verbose = TRUE;
break;
case 't': /* timeout period */
timeout_interval = atoi (optarg);
break;
case 'H': /* hostname */
if (strlen (optarg) >= ADDRESS_LENGTH)
die (STATE_UNKNOWN, _("Input buffer overflow\n"));
strcpy (query_address, optarg);
break;
case 's': /* server name */
/* TODO: this is_host check is probably unnecessary. */
/* Better to confirm nslookup response matches */
if (is_host (optarg) == FALSE) {
usage2 (_("Invalid hostname/address"), optarg);
}
if (strlen (optarg) >= ADDRESS_LENGTH)
die (STATE_UNKNOWN, _("Input buffer overflow\n"));
strcpy (dns_server, optarg);
break;
case 'r': /* reverse server name */
/* TODO: Is this is_host necessary? */
if (is_host (optarg) == FALSE) {
usage2 (_("Invalid hostname/address"), optarg);
}
if (strlen (optarg) >= ADDRESS_LENGTH)
die (STATE_UNKNOWN, _("Input buffer overflow\n"));
strcpy (ptr_server, optarg);
break;
case 'a': /* expected address */
if (strlen (optarg) >= ADDRESS_LENGTH)
die (STATE_UNKNOWN, _("Input buffer overflow\n"));
strcpy (expected_address, optarg);
match_expected_address = TRUE;
break;
case 'A': /* expect authority */
expect_authority = TRUE;
break;
}
}
c = optind;
if (strlen(query_address)==0 && c<argc) {
if (strlen(argv[c])>=ADDRESS_LENGTH)
die (STATE_UNKNOWN, _("Input buffer overflow\n"));
strcpy (query_address, argv[c++]);
}
if (strlen(dns_server)==0 && c<argc) {
/* TODO: See -s option */
if (is_host(argv[c]) == FALSE) {
printf (_("Invalid hostname/address: %s\n\n"), argv[c]);
return ERROR;
}
if (strlen(argv[c]) >= ADDRESS_LENGTH)
die (STATE_UNKNOWN, _("Input buffer overflow\n"));
strcpy (dns_server, argv[c++]);
}
return validate_arguments ();
}
int
validate_arguments ()
{
if (query_address[0] == 0)
return ERROR;
else
return OK;
}
void
print_help (void)
{
print_revision (progname, revision);
printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
printf (COPYRIGHT, copyright, email);
printf (_("\
This plugin uses the nslookup program to obtain the IP address\n\
for the given host/domain query. A optional DNS server to use may\n\
be specified. If no DNS server is specified, the default server(s)\n\
specified in /etc/resolv.conf will be used.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_("\
-H, --hostname=HOST\n\
The name or address you want to query\n\
-s, --server=HOST\n\
Optional DNS server you want to use for the lookup\n\
-a, --expected-address=IP-ADDRESS\n\
Optional IP address you expect the DNS server to return\n\
-A, --expect-authority\n\
Optionally expect the DNS server to be authoritative for the lookup\n"));
printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s -H host [-s server] [-a expected-address] [-A] [-t timeout]\n", progname);
}

110
plugins/check_dummy.c Normal file
View file

@ -0,0 +1,110 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_dummy.c,v 1.14 2004/12/25 23:17:44 opensides Exp $
******************************************************************************/
const char *progname = "check_dummy";
const char *revision = "$Revision: 1.14 $";
const char *copyright = "1999-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "utils.h"
void print_help (void);
void print_usage (void);
int
main (int argc, char **argv)
{
int result = STATE_UNKNOWN;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (argc < 2)
usage4 (_("Could not parse arguments"));
else if (strcmp (argv[1], "-V") == 0 || strcmp (argv[1], "--version") == 0) {
print_revision (progname, revision);
exit (STATE_OK);
}
else if (strcmp (argv[1], "-h") == 0 || strcmp (argv[1], "--help") == 0) {
print_help ();
exit (STATE_OK);
}
else if (!is_integer (argv[1]))
usage4 (_("Arguments to check_dummy must be an integer"));
else
result = atoi (argv[1]);
switch (result) {
case STATE_OK:
printf (_("OK"));
break;
case STATE_WARNING:
printf (_("WARNING"));
break;
case STATE_CRITICAL:
printf (_("CRITICAL"));
break;
case STATE_UNKNOWN:
printf (_("UNKNOWN"));
break;
default:
printf (_("Status %d is not a supported error state\n"), result);
break;
}
if (argc >= 3)
printf (": %s", argv[2]);
printf("\n");
return result;
}
void
print_help (void)
{
print_revision (progname, revision);
printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
printf (COPYRIGHT, copyright, email);
printf (_("\
This plugin will simply return the state corresponding to the numeric value\n\
of the <state> argument with optional text.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("Usage: %s <integer state> [optional text]\n", progname);
}

397
plugins/check_fping.c Normal file
View file

@ -0,0 +1,397 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_fping.c,v 1.24 2004/12/25 23:17:44 opensides Exp $
******************************************************************************/
const char *progname = "check_fping";
const char *revision = "$Revision: 1.24 $";
const char *copyright = "2000-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "popen.h"
#include "netutils.h"
#include "utils.h"
enum {
PACKET_COUNT = 1,
PACKET_SIZE = 56,
PL = 0,
RTA = 1
};
int textscan (char *buf);
int process_arguments (int, char **);
int get_threshold (char *arg, char *rv[2]);
void print_help (void);
void print_usage (void);
char *server_name = NULL;
int packet_size = PACKET_SIZE;
int packet_count = PACKET_COUNT;
int verbose = FALSE;
int cpl;
int wpl;
double crta;
double wrta;
int cpl_p = FALSE;
int wpl_p = FALSE;
int crta_p = FALSE;
int wrta_p = FALSE;
int
main (int argc, char **argv)
{
/* normaly should be int result = STATE_UNKNOWN; */
int status = STATE_UNKNOWN;
char *server = NULL;
char *command_line = NULL;
char *input_buffer = NULL;
input_buffer = malloc (MAX_INPUT_BUFFER);
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
server = strscpy (server, server_name);
/* compose the command */
asprintf (&command_line, "%s -b %d -c %d %s", PATH_TO_FPING,
packet_size, packet_count, server);
if (verbose)
printf ("%s\n", command_line);
/* run the command */
child_process = spopen (command_line);
if (child_process == NULL) {
printf (_("Could not open pipe: %s\n"), command_line);
return STATE_UNKNOWN;
}
child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
if (child_stderr == NULL) {
printf (_("Could not open stderr for %s\n"), command_line);
}
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
if (verbose)
printf ("%s", input_buffer);
status = max_state (status, textscan (input_buffer));
}
/* If we get anything on STDERR, at least set warning */
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
status = max_state (status, STATE_WARNING);
if (verbose)
printf ("%s", input_buffer);
status = max_state (status, textscan (input_buffer));
}
(void) fclose (child_stderr);
/* close the pipe */
if (spclose (child_process))
/* need to use max_state not max */
status = max_state (status, STATE_WARNING);
printf ("FPING %s - %s\n", state_text (status), server_name);
return status;
}
int
textscan (char *buf)
{
char *rtastr = NULL;
char *losstr = NULL;
double loss;
double rta;
int status = STATE_UNKNOWN;
if (strstr (buf, "not found")) {
die (STATE_CRITICAL, _("FPING UNKNOW - %s not found\n"), server_name);
}
else if (strstr (buf, "is unreachable") || strstr (buf, "Unreachable")) {
die (STATE_CRITICAL, _("FPING CRITICAL - %s is unreachable\n"),
"host");
}
else if (strstr (buf, "is down")) {
die (STATE_CRITICAL, _("FPING CRITICAL - %s is down\n"), server_name);
}
else if (strstr (buf, "is alive")) {
status = STATE_OK;
}
else if (strstr (buf, "xmt/rcv/%loss") && strstr (buf, "min/avg/max")) {
losstr = strstr (buf, "=");
losstr = 1 + strstr (losstr, "/");
losstr = 1 + strstr (losstr, "/");
rtastr = strstr (buf, "min/avg/max");
rtastr = strstr (rtastr, "=");
rtastr = 1 + index (rtastr, '/');
loss = strtod (losstr, NULL);
rta = strtod (rtastr, NULL);
if (cpl_p == TRUE && loss > cpl)
status = STATE_CRITICAL;
else if (crta_p == TRUE && rta > crta)
status = STATE_CRITICAL;
else if (wpl_p == TRUE && loss > wpl)
status = STATE_WARNING;
else if (wrta_p == TRUE && rta > wrta)
status = STATE_WARNING;
else
status = STATE_OK;
die (status,
_("FPING %s - %s (loss=%.0f%%, rta=%f ms)|%s %s\n"),
state_text (status), server_name, loss, rta,
perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, TRUE, 0, TRUE, 100),
fperfdata ("rta", rta/1.0e3, "s", wrta_p, wrta/1.0e3, crta_p, crta/1.0e3, TRUE, 0, FALSE, 0));
}
else if(strstr (buf, "xmt/rcv/%loss") ) {
/* no min/max/avg if host was unreachable in fping v2.2.b1 */
losstr = strstr (buf, "=");
losstr = 1 + strstr (losstr, "/");
losstr = 1 + strstr (losstr, "/");
loss = strtod (losstr, NULL);
if (atoi(losstr) == 100)
status = STATE_CRITICAL;
else if (cpl_p == TRUE && loss > cpl)
status = STATE_CRITICAL;
else if (wpl_p == TRUE && loss > wpl)
status = STATE_WARNING;
else
status = STATE_OK;
/* loss=%.0f%%;%d;%d;0;100 */
die (status, _("FPING %s - %s (loss=%.0f%% )|%s\n"),
state_text (status), server_name, loss ,
perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, TRUE, 0, TRUE, 100));
}
else {
status = max_state (status, STATE_WARNING);
}
return status;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
char *rv[2];
int option = 0;
static struct option longopts[] = {
{"hostname", required_argument, 0, 'H'},
{"critical", required_argument, 0, 'c'},
{"warning", required_argument, 0, 'w'},
{"bytes", required_argument, 0, 'b'},
{"number", required_argument, 0, 'n'},
{"verbose", no_argument, 0, 'v'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
rv[PL] = NULL;
rv[RTA] = NULL;
if (argc < 2)
return ERROR;
if (!is_option (argv[1])) {
server_name = argv[1];
argv[1] = argv[0];
argv = &argv[1];
argc--;
}
while (1) {
c = getopt_long (argc, argv, "+hVvH:c:w:b:n:", longopts, &option);
if (c == -1 || c == EOF || c == 1)
break;
switch (c) {
case '?': /* print short usage statement if args not parsable */
usage2 (_("Unknown argument"), optarg);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'v': /* verbose mode */
verbose = TRUE;
break;
case 'H': /* hostname */
if (is_host (optarg) == FALSE) {
usage2 (_("Invalid hostname/address"), optarg);
}
server_name = strscpy (server_name, optarg);
break;
case 'c':
get_threshold (optarg, rv);
if (rv[RTA]) {
crta = strtod (rv[RTA], NULL);
crta_p = TRUE;
rv[RTA] = NULL;
}
if (rv[PL]) {
cpl = atoi (rv[PL]);
cpl_p = TRUE;
rv[PL] = NULL;
}
break;
case 'w':
get_threshold (optarg, rv);
if (rv[RTA]) {
wrta = strtod (rv[RTA], NULL);
wrta_p = TRUE;
rv[RTA] = NULL;
}
if (rv[PL]) {
wpl = atoi (rv[PL]);
wpl_p = TRUE;
rv[PL] = NULL;
}
break;
case 'b': /* bytes per packet */
if (is_intpos (optarg))
packet_size = atoi (optarg);
else
usage (_("Packet size must be a positive integer"));
break;
case 'n': /* number of packets */
if (is_intpos (optarg))
packet_count = atoi (optarg);
else
usage (_("Packet count must be a positive integer"));
break;
}
}
if (server_name == NULL)
usage4 (_("Hostname was not supplied"));
return OK;
}
int
get_threshold (char *arg, char *rv[2])
{
char *arg1 = NULL;
char *arg2 = NULL;
arg1 = strscpy (arg1, arg);
if (strpbrk (arg1, ",:"))
arg2 = 1 + strpbrk (arg1, ",:");
if (arg2) {
arg1[strcspn (arg1, ",:")] = 0;
if (strstr (arg1, "%") && strstr (arg2, "%"))
die (STATE_UNKNOWN,
_("%s: Only one threshold may be packet loss (%s)\n"), progname,
arg);
if (!strstr (arg1, "%") && !strstr (arg2, "%"))
die (STATE_UNKNOWN,
_("%s: Only one threshold must be packet loss (%s)\n"),
progname, arg);
}
if (arg2 && strstr (arg2, "%")) {
rv[PL] = arg2;
rv[RTA] = arg1;
}
else if (arg2) {
rv[PL] = arg1;
rv[RTA] = arg2;
}
else if (strstr (arg1, "%")) {
rv[PL] = arg1;
}
else {
rv[RTA] = arg1;
}
return OK;
}
void
print_help (void)
{
print_revision (progname, revision);
printf ("Copyright (c) 1999 Didi Rieder <adrieder@sbox.tu-graz.ac.at>\n");
printf (COPYRIGHT, copyright, email);
printf (_("\
This plugin will use the /bin/fping command to ping the specified host\n\
for a fast check if the host is alive.\n\
Note that it is necessary to set the suid flag on fping.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_("\
-H, --hostname=HOST\n\
Name or IP Address of host to ping (IP Address bypasses name lookup,\n\
reducing system load)\n\
-w, --warning=THRESHOLD\n\
warning threshold pair\n\
-c, --critical=THRESHOLD\n\
critical threshold pair\n\
-b, --bytes=INTEGER\n\
Size of ICMP packet (default: %d)\n\
-n, --number=INTEGER\n\
Number of ICMP packets to send (default: %d)\n"),
PACKET_SIZE, PACKET_COUNT);
printf (_(UT_VERBOSE));
printf (_("\n\
THRESHOLD is <rta>,<pl>%% where <rta> is the round trip average travel\n\
time (ms) which triggers a WARNING or CRITICAL state, and <pl> is the\n\
percentage of packet loss to trigger an alarm state.\n"));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("Usage: %s <host_address>\n", progname);
}

348
plugins/check_game.c Normal file
View file

@ -0,0 +1,348 @@
/******************************************************************************
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id: check_game.c,v 1.22 2004/12/25 23:17:44 opensides Exp $
*****************************************************************************/
const char *progname = "check_game";
const char *revision = "$Revision: 1.22 $";
const char *copyright = "2002-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "popen.h"
#include "utils.h"
int process_arguments (int, char **);
int validate_arguments (void);
void print_help (void);
void print_usage (void);
#define QSTAT_DATA_DELIMITER ","
#define QSTAT_HOST_ERROR "ERROR"
#define QSTAT_HOST_DOWN "DOWN"
#define QSTAT_HOST_TIMEOUT "TIMEOUT"
#define QSTAT_MAX_RETURN_ARGS 12
char *server_ip;
char *game_type;
int port = 0;
int verbose;
int qstat_game_players_max = -1;
int qstat_game_players = -1;
int qstat_game_field = -1;
int qstat_map_field = -1;
int qstat_ping_field = -1;
int
main (int argc, char **argv)
{
char *command_line;
int result = STATE_UNKNOWN;
FILE *fp;
char input_buffer[MAX_INPUT_BUFFER];
char *p, *ret[QSTAT_MAX_RETURN_ARGS];
int i;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
result = STATE_OK;
/* create the command line to execute */
asprintf (&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);
if (verbose > 0)
printf ("%s\n", command_line);
/* run the command */
fp = spopen (command_line);
if (fp == NULL) {
printf (_("Could not open pipe: %s\n"), command_line);
return STATE_UNKNOWN;
}
fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp); /* Only interested in the first line */
/* strip the newline character from the end of the input */
input_buffer[strlen (input_buffer) - 1] = 0;
/* sanity check */
/* was thinking about running qstat without any options, capturing the
-default line, parsing it & making an array of all know server types
but thought this would be too much hassle considering this is a tool
for intelligent sysadmins (ha). Could put a static array of known
server types in a header file but then we'd be limiting ourselves
In the end, I figured I'd simply let an error occur & then trap it
*/
if (!strncmp (input_buffer, "unknown option", 14)) {
printf (_("CRITICAL - Host type parameter incorrect!\n"));
result = STATE_CRITICAL;
return result;
}
/* initialize the returned data buffer */
for (i = 0; i < QSTAT_MAX_RETURN_ARGS; i++)
ret[i] = strdup("");
i = 0;
p = (char *) strtok (input_buffer, QSTAT_DATA_DELIMITER);
while (p != NULL) {
ret[i] = p;
p = (char *) strtok (NULL, QSTAT_DATA_DELIMITER);
i++;
if (i >= QSTAT_MAX_RETURN_ARGS)
break;
}
if (strstr (ret[2], QSTAT_HOST_ERROR)) {
printf (_("CRITICAL - Host not found\n"));
result = STATE_CRITICAL;
}
else if (strstr (ret[2], QSTAT_HOST_DOWN)) {
printf (_("CRITICAL - Game server down or unavailable\n"));
result = STATE_CRITICAL;
}
else if (strstr (ret[2], QSTAT_HOST_TIMEOUT)) {
printf (_("CRITICAL - Game server timeout\n"));
result = STATE_CRITICAL;
}
else {
printf ("OK: %s/%s %s (%s), Ping: %s ms|%s %s\n",
ret[qstat_game_players],
ret[qstat_game_players_max],
ret[qstat_game_field],
ret[qstat_map_field],
ret[qstat_ping_field],
perfdata ("players", atol(ret[qstat_game_players]), "",
FALSE, 0, FALSE, 0,
TRUE, 0, TRUE, atol(ret[qstat_game_players_max])),
fperfdata ("ping", strtod(ret[qstat_ping_field], NULL), "",
FALSE, 0, FALSE, 0,
TRUE, 0, FALSE, 0));
}
/* close the pipe */
spclose (fp);
return result;
}
int
process_arguments (int argc, char **argv)
{
int c;
int opt_index = 0;
static struct option long_opts[] = {
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{"verbose", no_argument, 0, 'v'},
{"timeout", required_argument, 0, 't'},
{"hostname", required_argument, 0, 'H'},
{"port", required_argument, 0, 'P'},
{"game-type", required_argument, 0, 'G'},
{"map-field", required_argument, 0, 'm'},
{"ping-field", required_argument, 0, 'p'},
{"game-field", required_argument, 0, 'g'},
{"players-field", required_argument, 0, 129},
{"max-players-field", required_argument, 0, 130},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
for (c = 1; c < argc; c++) {
if (strcmp ("-mf", argv[c]) == 0)
strcpy (argv[c], "-m");
else if (strcmp ("-pf", argv[c]) == 0)
strcpy (argv[c], "-p");
else if (strcmp ("-gf", argv[c]) == 0)
strcpy (argv[c], "-g");
}
while (1) {
c = getopt_long (argc, argv, "hVvt:H:P:G:g:p:m:", long_opts, &opt_index);
if (c == -1 || c == EOF)
break;
switch (c) {
case '?': /* args not parsable */
usage2 (_("Unknown argument"), optarg);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'v': /* version */
verbose = TRUE;
break;
case 't': /* timeout period */
timeout_interval = atoi (optarg);
break;
case 'H': /* hostname */
if (strlen (optarg) >= MAX_HOST_ADDRESS_LENGTH)
die (STATE_UNKNOWN, _("Input buffer overflow\n"));
server_ip = optarg;
break;
case 'P': /* port */
port = atoi (optarg);
break;
case 'G': /* hostname */
if (strlen (optarg) >= MAX_INPUT_BUFFER)
die (STATE_UNKNOWN, _("Input buffer overflow\n"));
game_type = optarg;
break;
case 'p': /* index of ping field */
qstat_ping_field = atoi (optarg);
if (qstat_ping_field < 0 || qstat_ping_field > QSTAT_MAX_RETURN_ARGS)
return ERROR;
break;
case 'm': /* index on map field */
qstat_map_field = atoi (optarg);
if (qstat_map_field < 0 || qstat_map_field > QSTAT_MAX_RETURN_ARGS)
return ERROR;
break;
case 'g': /* index of game field */
qstat_game_field = atoi (optarg);
if (qstat_game_field < 0 || qstat_game_field > QSTAT_MAX_RETURN_ARGS)
return ERROR;
break;
case 129: /* index of player count field */
qstat_game_players = atoi (optarg);
if (qstat_game_players_max == 0)
qstat_game_players_max = qstat_game_players - 1;
if (qstat_game_players < 0 || qstat_game_players > QSTAT_MAX_RETURN_ARGS)
return ERROR;
break;
case 130: /* index of max players field */
qstat_game_players_max = atoi (optarg);
if (qstat_game_players_max < 0 || qstat_game_players_max > QSTAT_MAX_RETURN_ARGS)
return ERROR;
break;
}
}
c = optind;
/* first option is the game type */
if (!game_type && c<argc)
game_type = strdup (argv[c++]);
/* Second option is the server name */
if (!server_ip && c<argc)
server_ip = strdup (argv[c++]);
return validate_arguments ();
}
int
validate_arguments (void)
{
if (qstat_game_players_max < 0)
qstat_game_players_max = 4;
if (qstat_game_players < 0)
qstat_game_players = 5;
if (qstat_game_field < 0)
qstat_game_field = 2;
if (qstat_map_field < 0)
qstat_map_field = 3;
if (qstat_ping_field < 0)
qstat_ping_field = 5;
return OK;
}
void
print_help (void)
{
print_revision (progname, revision);
printf ("Copyright (c) 1999 Ian Cass, Knowledge Matters Limited\n");
printf (COPYRIGHT, copyright, email);
printf (_("This plugin tests game server connections with the specified host."));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_("\
<game> = Game type that is recognised by qstat (without the leading dash)\n\
<ip_address> = The IP address of the device you wish to query\n\
[port] = Optional port of which to connect\n\
[game_field] = Field number in raw qstat output that contains game name\n\
[map_field] = Field number in raw qstat output that contains map name\n\
[ping_field] = Field number in raw qstat output that contains ping time\n"));
printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
printf (_("\n\
Notes:\n\
- This plugin uses the 'qstat' command, the popular game server status query tool .\n\
If you don't have the package installed, you will need to download it from\n\
http://www.activesw.com/people/steve/qstat.html before you can use this plugin.\n"));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s <game> <ip_address> [-p port] [-gf game_field] [-mf map_field]\n\
[-pf ping_field]\n", progname);
}
/******************************************************************************
*
* Test Cases:
*
* ./check_game --players 7 -p 8 --map 5 qs 67.20.190.61 26000
*
* qstat -raw , -qs 67.20.190.61
* ==> QS,67.20.190.61,Nightmare.fintek.ca,67.20.190.61:26000,3,e2m1,6,0,83,0
*
* qstat -qs 67.20.190.61
* ==> ADDRESS PLAYERS MAP RESPONSE TIME NAME
* ==> 67.20.190.61 0/ 6 e2m1 79 / 0 Nightmare.fintek.ca
*
******************************************************************************/

398
plugins/check_hpjd.c Normal file
View file

@ -0,0 +1,398 @@
/******************************************************************************
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id: check_hpjd.c,v 1.32 2005/06/27 13:07:39 seanius Exp $
*****************************************************************************/
const char *progname = "check_hpjd";
const char *revision = "$Revision: 1.32 $";
const char *copyright = "2000-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "popen.h"
#include "utils.h"
#include "netutils.h"
#define DEFAULT_COMMUNITY "public"
const char *option_summary = "-H host [-C community]\n";
#define HPJD_LINE_STATUS ".1.3.6.1.4.1.11.2.3.9.1.1.2.1"
#define HPJD_PAPER_STATUS ".1.3.6.1.4.1.11.2.3.9.1.1.2.2"
#define HPJD_INTERVENTION_REQUIRED ".1.3.6.1.4.1.11.2.3.9.1.1.2.3"
#define HPJD_GD_PERIPHERAL_ERROR ".1.3.6.1.4.1.11.2.3.9.1.1.2.6"
#define HPJD_GD_PAPER_OUT ".1.3.6.1.4.1.11.2.3.9.1.1.2.8"
#define HPJD_GD_PAPER_JAM ".1.3.6.1.4.1.11.2.3.9.1.1.2.9"
#define HPJD_GD_TONER_LOW ".1.3.6.1.4.1.11.2.3.9.1.1.2.10"
#define HPJD_GD_PAGE_PUNT ".1.3.6.1.4.1.11.2.3.9.1.1.2.11"
#define HPJD_GD_MEMORY_OUT ".1.3.6.1.4.1.11.2.3.9.1.1.2.12"
#define HPJD_GD_DOOR_OPEN ".1.3.6.1.4.1.11.2.3.9.1.1.2.17"
#define HPJD_GD_PAPER_OUTPUT ".1.3.6.1.4.1.11.2.3.9.1.1.2.19"
#define HPJD_GD_STATUS_DISPLAY ".1.3.6.1.4.1.11.2.3.9.1.1.3"
#define ONLINE 0
#define OFFLINE 1
int process_arguments (int, char **);
int validate_arguments (void);
void print_help (void);
void print_usage (void);
char *community = NULL;
char *address = NULL;
int
main (int argc, char **argv)
{
char command_line[1024];
int result = STATE_UNKNOWN;
int line;
char input_buffer[MAX_INPUT_BUFFER];
char query_string[512];
char *errmsg;
char *temp_buffer;
int line_status = ONLINE;
int paper_status = 0;
int intervention_required = 0;
int peripheral_error = 0;
int paper_jam = 0;
int paper_out = 0;
int toner_low = 0;
int page_punt = 0;
int memory_out = 0;
int door_open = 0;
int paper_output = 0;
char display_message[MAX_INPUT_BUFFER];
errmsg = malloc(MAX_INPUT_BUFFER);
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* removed ' 2>1' at end of command 10/27/1999 - EG */
/* create the query string */
sprintf
(query_string,
"%s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0",
HPJD_LINE_STATUS,
HPJD_PAPER_STATUS,
HPJD_INTERVENTION_REQUIRED,
HPJD_GD_PERIPHERAL_ERROR,
HPJD_GD_PAPER_JAM,
HPJD_GD_PAPER_OUT,
HPJD_GD_TONER_LOW,
HPJD_GD_PAGE_PUNT,
HPJD_GD_MEMORY_OUT,
HPJD_GD_DOOR_OPEN, HPJD_GD_PAPER_OUTPUT, HPJD_GD_STATUS_DISPLAY);
/* get the command to run */
sprintf (command_line, "%s -OQa -m : -v 1 -c %s %s %s", PATH_TO_SNMPGET, community,
address, query_string);
/* run the command */
child_process = spopen (command_line);
if (child_process == NULL) {
printf (_("Could not open pipe: %s\n"), command_line);
return STATE_UNKNOWN;
}
child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
if (child_stderr == NULL) {
printf (_("Could not open stderr for %s\n"), command_line);
}
result = STATE_OK;
line = 0;
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
/* strip the newline character from the end of the input */
if (input_buffer[strlen (input_buffer) - 1] == '\n')
input_buffer[strlen (input_buffer) - 1] = 0;
line++;
temp_buffer = strtok (input_buffer, "=");
temp_buffer = strtok (NULL, "=");
if (temp_buffer == NULL && line < 13) {
result = STATE_UNKNOWN;
strcpy (errmsg, input_buffer);
} else {
switch (line) {
case 1: /* 1st line should contain the line status */
line_status = atoi (temp_buffer);
break;
case 2: /* 2nd line should contain the paper status */
paper_status = atoi (temp_buffer);
break;
case 3: /* 3rd line should be intervention required */
intervention_required = atoi (temp_buffer);
break;
case 4: /* 4th line should be peripheral error */
peripheral_error = atoi (temp_buffer);
break;
case 5: /* 5th line should contain the paper jam status */
paper_jam = atoi (temp_buffer);
break;
case 6: /* 6th line should contain the paper out status */
paper_out = atoi (temp_buffer);
break;
case 7: /* 7th line should contain the toner low status */
toner_low = atoi (temp_buffer);
break;
case 8: /* did data come too slow for engine */
page_punt = atoi (temp_buffer);
break;
case 9: /* did we run out of memory */
memory_out = atoi (temp_buffer);
break;
case 10: /* is there a door open */
door_open = atoi (temp_buffer);
break;
case 11: /* is output tray full */
paper_output = atoi (temp_buffer);
break;
case 12: /* display panel message */
strcpy (display_message, temp_buffer + 1);
break;
default: /* fold multiline message */
strncat (display_message, input_buffer,
sizeof (display_message) - strlen (display_message) - 1);
}
}
/* break out of the read loop if we encounter an error */
if (result != STATE_OK)
break;
}
/* WARNING if output found on stderr */
if (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
result = max_state (result, STATE_WARNING);
/* remove CRLF */
if (input_buffer[strlen (input_buffer) - 1] == '\n')
input_buffer[strlen (input_buffer) - 1] = 0;
sprintf (errmsg, "%s", input_buffer );
}
/* close stderr */
(void) fclose (child_stderr);
/* close the pipe */
if (spclose (child_process))
result = max_state (result, STATE_WARNING);
/* if there wasn't any output, display an error */
if (line == 0) {
/* might not be the problem, but most likely is. */
result = STATE_UNKNOWN ;
asprintf (&errmsg, "%s : Timeout from host %s\n", errmsg, address );
}
/* if we had no read errors, check the printer status results... */
if (result == STATE_OK) {
if (paper_jam) {
result = STATE_WARNING;
strcpy (errmsg, _("Paper Jam"));
}
else if (paper_out) {
result = STATE_WARNING;
strcpy (errmsg, _("Out of Paper"));
}
else if (line_status == OFFLINE) {
if (strcmp (errmsg, "POWERSAVE ON") != 0) {
result = STATE_WARNING;
strcpy (errmsg, _("Printer Offline"));
}
}
else if (peripheral_error) {
result = STATE_WARNING;
strcpy (errmsg, _("Peripheral Error"));
}
else if (intervention_required) {
result = STATE_WARNING;
strcpy (errmsg, _("Intervention Required"));
}
else if (toner_low) {
result = STATE_WARNING;
strcpy (errmsg, _("Toner Low"));
}
else if (memory_out) {
result = STATE_WARNING;
strcpy (errmsg, _("Insufficient Memory"));
}
else if (door_open) {
result = STATE_WARNING;
strcpy (errmsg, _("A Door is Open"));
}
else if (paper_output) {
result = STATE_WARNING;
strcpy (errmsg, _("Output Tray is Full"));
}
else if (page_punt) {
result = STATE_WARNING;
strcpy (errmsg, _("Data too Slow for Engine"));
}
else if (paper_status) {
result = STATE_WARNING;
strcpy (errmsg, _("Unknown Paper Error"));
}
}
if (result == STATE_OK)
printf (_("Printer ok - (%s)\n"), display_message);
else if (result == STATE_UNKNOWN) {
printf ("%s\n", errmsg);
/* if printer could not be reached, escalate to critical */
if (strstr (errmsg, "Timeout"))
result = STATE_CRITICAL;
}
else if (result == STATE_WARNING)
printf ("%s (%s)\n", errmsg, display_message);
return result;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"hostname", required_argument, 0, 'H'},
{"community", required_argument, 0, 'C'},
/* {"critical", required_argument,0,'c'}, */
/* {"warning", required_argument,0,'w'}, */
/* {"port", required_argument,0,'P'}, */
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
while (1) {
c = getopt_long (argc, argv, "+hVH:C:", longopts, &option);
if (c == -1 || c == EOF || c == 1)
break;
switch (c) {
case 'H': /* hostname */
if (is_host (optarg)) {
address = strscpy(address, optarg) ;
}
else {
usage2 (_("Invalid hostname/address"), optarg);
}
break;
case 'C': /* community */
community = strscpy (community, optarg);
break;
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case '?': /* help */
usage2 (_("Unknown argument"), optarg);
}
}
c = optind;
if (address == NULL) {
if (is_host (argv[c])) {
address = argv[c++];
}
else {
usage2 (_("Invalid hostname/address"), argv[c]);
}
}
if (community == NULL) {
if (argv[c] != NULL )
community = argv[c];
else
community = strdup (DEFAULT_COMMUNITY);
}
return validate_arguments ();
}
int
validate_arguments (void)
{
return OK;
}
void
print_help (void)
{
print_revision (progname, revision);
printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
printf (COPYRIGHT, copyright, email);
printf (_("\
This plugin tests the STATUS of an HP printer with a JetDirect card.\n\
Net-snmp must be installed on the computer running the plugin.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_("\
-C, --community=STRING\n\
The SNMP community name (default=%s)\n"), DEFAULT_COMMUNITY);
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("Usage: %s -H host [-C community]\n", progname);
}

1572
plugins/check_http.c Normal file

File diff suppressed because it is too large Load diff

1199
plugins/check_icmp.c Normal file

File diff suppressed because it is too large Load diff

530
plugins/check_ide_smart.c Normal file
View file

@ -0,0 +1,530 @@
/*
* check_ide-smart v.1 - hacked version of ide-smart for Nagios
* Copyright (C) 2000 Robert Dale <rdale@digital-mission.com>
*
* Nagios - http://www.nagios.org
*
* Notes:
* ide-smart has the same functionality as before. Some return
* values were changed, otherwise the --nagios option was added.
*
* Run with: check_ide-smart --nagios [-d] <DRIVE>
* Where DRIVE is an IDE drive, ie. /dev/hda, /dev/hdb, /dev/hdc
*
* - Returns 0 on no errors
* - Returns 1 on advisories
* - Returns 2 on prefailure
* - Returns -1 not too often
*
* ide-smart 1.3 - IDE S.M.A.R.T. checking tool
* Copyright (C) 1998-1999 Ragnar Hojland Espinosa <ragnar@lightside.dhis.org>
* 1998 Gadi Oxman <gadio@netvision.net.il>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id: check_ide_smart.c,v 1.10 2005/02/02 06:42:18 stanleyhopcroft Exp $
*/
const char *progname = "check_ide_smart";
const char *revision = "$Revision: 1.10 $";
const char *copyright = "2000-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "utils.h"
void print_help (void);
void print_usage (void);
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <linux/hdreg.h>
#include <linux/types.h>
#include <errno.h>
#define NR_ATTRIBUTES 30
#ifndef TRUE
#define TRUE 1
#endif /* */
#define PREFAILURE 2
#define ADVISORY 1
#define OPERATIONAL 0
#define UNKNOWN -1
typedef struct threshold_s
{
__u8 id;
__u8 threshold;
__u8 reserved[10];
}
__attribute__ ((packed)) threshold_t;
typedef struct thresholds_s
{
__u16 revision;
threshold_t thresholds[NR_ATTRIBUTES];
__u8 reserved[18];
__u8 vendor[131];
__u8 checksum;
}
__attribute__ ((packed)) thresholds_t;
typedef struct value_s
{
__u8 id;
__u16 status;
__u8 value;
__u8 vendor[8];
}
__attribute__ ((packed)) value_t;
typedef struct values_s
{
__u16 revision;
value_t values[NR_ATTRIBUTES];
__u8 offline_status;
__u8 vendor1;
__u16 offline_timeout;
__u8 vendor2;
__u8 offline_capability;
__u16 smart_capability;
__u8 reserved[16];
__u8 vendor[125];
__u8 checksum;
}
__attribute__ ((packed)) values_t;
struct
{
__u8 value;
char *text;
}
offline_status_text[] =
{
{0x00, "NeverStarted"},
{0x02, "Completed"},
{0x04, "Suspended"},
{0x05, "Aborted"},
{0x06, "Failed"},
{0, 0}
};
struct
{
__u8 value;
char *text;
}
smart_command[] =
{
{SMART_ENABLE, "SMART_ENABLE"},
{SMART_DISABLE, "SMART_DISABLE"},
{SMART_IMMEDIATE_OFFLINE, "SMART_IMMEDIATE_OFFLINE"},
{SMART_AUTO_OFFLINE, "SMART_AUTO_OFFLINE"}
};
/* Index to smart_command table, keep in order */
enum SmartCommand
{ SMART_CMD_ENABLE,
SMART_CMD_DISABLE,
SMART_CMD_IMMEDIATE_OFFLINE,
SMART_CMD_AUTO_OFFLINE
};
void print_values (values_t * p, thresholds_t * t);
int smart_cmd_simple (int fd, enum SmartCommand command, __u8 val0, char show_error);
int
main (int argc, char *argv[])
{
char *device = NULL;
int command = -1;
int o, longindex;
int retval = 0;
thresholds_t thresholds;
values_t values;
int fd;
static struct option longopts[] = {
{"device", required_argument, 0, 'd'},
{"immediate", no_argument, 0, 'i'},
{"quiet-check", no_argument, 0, 'q'},
{"auto-on", no_argument, 0, '1'},
{"auto-off", no_argument, 0, '0'},
{"nagios", no_argument, 0, 'n'},
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'}, {0, 0, 0, 0}
};
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
while (1) {
o = getopt_long (argc, argv, "+d:iq10nhV", longopts, &longindex);
if (o == -1 || o == EOF || o == 1)
break;
switch (o) {
case 'd':
device = optarg;
break;
case 'q':
command = 3;
break;
case 'i':
command = 2;
break;
case '1':
command = 1;
break;
case '0':
command = 0;
break;
case 'n':
command = 4;
break;
case 'h':
print_help ();
return STATE_OK;
case 'V':
print_revision (progname, revision);
return STATE_OK;
default:
usage2 (_("Unknown argument"), optarg);
}
}
if (optind < argc) {
device = argv[optind];
}
if (!device) {
print_help ();
return STATE_OK;
}
fd = open (device, O_RDONLY);
if (fd < 0) {
printf (_("CRITICAL - Couldn't open device %s: %s\n"), device, strerror (errno));
return STATE_CRITICAL;
}
if (smart_cmd_simple (fd, SMART_CMD_ENABLE, 0, TRUE)) {
printf (_("CRITICAL - SMART_CMD_ENABLE\n"));
return STATE_CRITICAL;
}
switch (command) {
case 0:
retval = smart_cmd_simple (fd, SMART_CMD_AUTO_OFFLINE, 0, TRUE);
break;
case 1:
retval = smart_cmd_simple (fd, SMART_CMD_AUTO_OFFLINE, 0xF8, TRUE);
break;
case 2:
retval = smart_cmd_simple (fd, SMART_CMD_IMMEDIATE_OFFLINE, 0, TRUE);
break;
case 3:
smart_read_values (fd, &values);
smart_read_thresholds (fd, &thresholds);
retval = values_not_passed (&values, &thresholds);
break;
case 4:
smart_read_values (fd, &values);
smart_read_thresholds (fd, &thresholds);
retval = nagios (&values, &thresholds);
break;
default:
smart_read_values (fd, &values);
smart_read_thresholds (fd, &thresholds);
print_values (&values, &thresholds);
break;
}
close (fd);
return retval;
}
char *
get_offline_text (int status)
{
int i;
for (i = 0; offline_status_text[i].text; i++) {
if (offline_status_text[i].value == status) {
return offline_status_text[i].text;
}
}
return "UNKNOW";
}
int
smart_read_values (int fd, values_t * values)
{
int e;
__u8 args[4 + 512];
args[0] = WIN_SMART;
args[1] = 0;
args[2] = SMART_READ_VALUES;
args[3] = 1;
if (ioctl (fd, HDIO_DRIVE_CMD, &args)) {
e = errno;
printf (_("CRITICAL - SMART_READ_VALUES: %s\n"), strerror (errno));
return e;
}
memcpy (values, args + 4, 512);
return 0;
}
int
values_not_passed (values_t * p, thresholds_t * t)
{
value_t * value = p->values;
threshold_t * threshold = t->thresholds;
int failed = 0;
int passed = 0;
int i;
for (i = 0; i < NR_ATTRIBUTES; i++) {
if (value->id && threshold->id && value->id == threshold->id) {
if (value->value <= threshold->threshold) {
++failed;
}
else {
++passed;
}
}
++value;
++threshold;
}
return (passed ? -failed : 2);
}
int
nagios (values_t * p, thresholds_t * t)
{
value_t * value = p->values;
threshold_t * threshold = t->thresholds;
int status = OPERATIONAL;
int prefailure = 0;
int advisory = 0;
int failed = 0;
int passed = 0;
int total = 0;
int i;
for (i = 0; i < NR_ATTRIBUTES; i++) {
if (value->id && threshold->id && value->id == threshold->id) {
if (value->value <= threshold->threshold) {
++failed;
if (value->status & 1) {
status = PREFAILURE;
++prefailure;
}
else {
status = ADVISORY;
++advisory;
}
}
else {
++passed;
}
++total;
}
++value;
++threshold;
}
switch (status) {
case PREFAILURE:
printf (_("CRITICAL - %d Harddrive PreFailure%cDetected! %d/%d tests failed.\n"),
prefailure,
prefailure > 1 ? 's' : ' ',
failed,
total);
status=STATE_CRITICAL;
break;
case ADVISORY:
printf (_("WARNING - %d Harddrive Advisor%s Detected. %d/%d tests failed.\n"),
advisory,
advisory > 1 ? "ies" : "y",
failed,
total);
status=STATE_WARNING;
break;
case OPERATIONAL:
printf (_("OK - Operational (%d/%d tests passed)\n"), passed, total);
status=STATE_OK;
break;
default:
printf (_("ERROR - Status '%d' unkown. %d/%d tests passed\n"), status,
passed, total);
status = STATE_UNKNOWN;
break;
}
return status;
}
void
print_value (value_t * p, threshold_t * t)
{
printf ("Id=%3d, Status=%2d {%s , %s}, Value=%3d, Threshold=%3d, %s\n",
p->id, p->status, p->status & 1 ? "PreFailure" : "Advisory ",
p->status & 2 ? "OnLine " : "OffLine", p->value, t->threshold,
p->value > t->threshold ? "Passed" : "Failed");
}
void
print_values (values_t * p, thresholds_t * t)
{
value_t * value = p->values;
threshold_t * threshold = t->thresholds;
int i;
for (i = 0; i < NR_ATTRIBUTES; i++) {
if (value->id && threshold->id && value->id == threshold->id) {
print_value (value++, threshold++);
}
}
printf
(_("OffLineStatus=%d {%s}, AutoOffLine=%s, OffLineTimeout=%d minutes\n"),
p->offline_status,
get_offline_text (p->offline_status & 0x7f),
(p->offline_status & 0x80 ? "Yes" : "No"),
p->offline_timeout / 60);
printf
(_("OffLineCapability=%d {%s %s %s}\n"),
p->offline_capability,
p->offline_capability & 1 ? "Immediate" : "",
p->offline_capability & 2 ? "Auto" : "",
p->offline_capability & 4 ? "AbortOnCmd" : "SuspendOnCmd");
printf
(_("SmartRevision=%d, CheckSum=%d, SmartCapability=%d {%s %s}\n"),
p->revision,
p->checksum,
p->smart_capability,
p->smart_capability & 1 ? "SaveOnStandBy" : "",
p->smart_capability & 2 ? "AutoSave" : "");
}
void
print_thresholds (thresholds_t * p)
{
threshold_t * threshold = p->thresholds;
int i;
printf ("\n");
printf ("SmartRevision=%d\n", p->revision);
for (i = 0; i < NR_ATTRIBUTES; i++) {
if (threshold->id) {
printf ("Id=%3d, Threshold=%3d\n", threshold->id,
threshold->threshold); }
++threshold;
}
printf ("CheckSum=%d\n", p->checksum);
}
int
smart_cmd_simple (int fd, enum SmartCommand command, __u8 val0, char show_error)
{
int e = 0;
__u8 args[4];
args[0] = WIN_SMART;
args[1] = val0;
args[2] = smart_command[command].value;
args[3] = 0;
if (ioctl (fd, HDIO_DRIVE_CMD, &args)) {
e = errno;
if (show_error) {
printf (_("CRITICAL - %s: %s\n"), smart_command[command].text, strerror (errno));
}
}
return e;
}
int
smart_read_thresholds (int fd, thresholds_t * thresholds)
{
int e;
__u8 args[4 + 512];
args[0] = WIN_SMART;
args[1] = 0;
args[2] = SMART_READ_THRESHOLDS;
args[3] = 1;
if (ioctl (fd, HDIO_DRIVE_CMD, &args)) {
e = errno;
printf (_("CRITICAL - SMART_READ_THRESHOLDS: %s\n"), strerror (errno));
return e;
}
memcpy (thresholds, args + 4, 512);
return 0;
}
void
print_help (void)
{
print_revision (progname, revision);
printf ("Nagios feature - 1999 Robert Dale <rdale@digital-mission.com>\n");
printf ("(C) 1999 Ragnar Hojland Espinosa <ragnar@lightside.dhis.org>\n");
printf (COPYRIGHT, copyright, email);
printf(_("This plugin checks a local hard drive with the (Linux specific) SMART interface [http://smartlinux.sourceforge.net/smart/index.php].\n\n"));
printf ("\
Usage: %s [OPTION] [DEVICE]\n\
-d, --device=DEVICE\n\
Select device DEVICE\n\
Note: if the device is selected with this option, _no_ other options are accepted\n\
-i, --immediate\n\
Perform immediately offline tests\n\
-q, --quiet-check\n\
Returns the number of failed tests\n\
-1, --auto-on\n\
Turn on automatic offline tests\n\
-0, --auto-off\n\
Turn off automatic offline tests\n\
-n, --nagios\n\
Output suitable for Nagios\n", progname);
}
void
print_usage (void)
{
printf ("\
Usage: %s [-d <device>] [-i <immediate>] [-q quiet] [-1 <auto-on>]\n\
[-O <auto-off>] [-n <nagios>]\n", progname);
}

407
plugins/check_ldap.c Normal file
View file

@ -0,0 +1,407 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_ldap.c,v 1.30 2004/12/25 23:17:44 opensides Exp $
******************************************************************************/
/* progname may be check_ldaps */
char *progname = "check_ldap";
const char *revision = "$Revision: 1.30 $";
const char *copyright = "2000-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "netutils.h"
#include "utils.h"
#include <lber.h>
#include <ldap.h>
enum {
UNDEFINED = 0,
#ifdef HAVE_LDAP_SET_OPTION
DEFAULT_PROTOCOL = 2,
#endif
DEFAULT_PORT = 389
};
int process_arguments (int, char **);
int validate_arguments (void);
void print_help (void);
void print_usage (void);
char ld_defattr[] = "(objectclass=*)";
char *ld_attr = ld_defattr;
char *ld_host = NULL;
char *ld_base = NULL;
char *ld_passwd = NULL;
char *ld_binddn = NULL;
int ld_port = DEFAULT_PORT;
#ifdef HAVE_LDAP_SET_OPTION
int ld_protocol = DEFAULT_PROTOCOL;
#endif
double warn_time = UNDEFINED;
double crit_time = UNDEFINED;
struct timeval tv;
/* for ldap tls */
char *SERVICE = "LDAP";
int
main (int argc, char *argv[])
{
LDAP *ld;
LDAPMessage *result;
/* should be int result = STATE_UNKNOWN; */
int status = STATE_UNKNOWN;
long microsec;
double elapsed_time;
/* for ldap tls */
int tls;
int version=3;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (strstr(argv[0],"check_ldaps")) {
asprintf (&progname, "check_ldaps");
}
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* initialize alarm signal handling */
signal (SIGALRM, socket_timeout_alarm_handler);
/* set socket timeout */
alarm (socket_timeout);
/* get the start time */
gettimeofday (&tv, NULL);
/* initialize ldap */
#ifdef HAVE_LDAP_INIT
if (!(ld = ldap_init (ld_host, ld_port))) {
printf ("Could not connect to the server at port %i\n", ld_port);
return STATE_CRITICAL;
}
#else
if (!(ld = ldap_open (ld_host, ld_port))) {
/*ldap_perror(ld, "ldap_open"); */
printf (_("Could not connect to the server at port %i\n"), ld_port);
return STATE_CRITICAL;
}
#endif /* HAVE_LDAP_INIT */
#ifdef HAVE_LDAP_SET_OPTION
/* set ldap options */
if (ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &ld_protocol) !=
LDAP_OPT_SUCCESS ) {
printf(_("Could not set protocol version %d\n"), ld_protocol);
return STATE_CRITICAL;
}
#endif
if (strstr(argv[0],"check_ldaps")) {
/* with TLS */
if ( ld_port == LDAPS_PORT ) {
asprintf (&SERVICE, "LDAPS");
#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_X_TLS)
/* ldaps: set option tls */
tls = LDAP_OPT_X_TLS_HARD;
if (ldap_set_option (ld, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
{
/*ldap_perror(ld, "ldaps_option"); */
printf (_("Could not init TLS at port %i!\n"), ld_port);
return STATE_CRITICAL;
}
#else
printf (_("TLS not supported by the libraries!\n"), ld_port);
return STATE_CRITICAL;
#endif /* LDAP_OPT_X_TLS */
} else {
asprintf (&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 )
{
if (version < LDAP_VERSION3)
{
version = LDAP_VERSION3;
ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version);
}
}
/* call start_tls */
if (ldap_start_tls_s(ld, NULL, NULL) != LDAP_SUCCESS)
{
/*ldap_perror(ld, "ldap_start_tls"); */
printf (_("Could not init startTLS at port %i!\n"), ld_port);
return STATE_CRITICAL;
}
#else
printf (_("startTLS not supported by the library, needs LDAPv3!\n"));
return STATE_CRITICAL;
#endif /* HAVE_LDAP_START_TLS_S */
}
}
/* bind to the ldap server */
if (ldap_bind_s (ld, ld_binddn, ld_passwd, LDAP_AUTH_SIMPLE) !=
LDAP_SUCCESS) {
/*ldap_perror(ld, "ldap_bind"); */
printf (_("Could not bind to the ldap-server\n"));
return STATE_CRITICAL;
}
/* do a search of all objectclasses in the base dn */
if (ldap_search_s (ld, ld_base, LDAP_SCOPE_BASE, ld_attr, NULL, 0, &result)
!= LDAP_SUCCESS) {
/*ldap_perror(ld, "ldap_search"); */
printf (_("Could not search/find objectclasses in %s\n"), ld_base);
return STATE_CRITICAL;
}
/* unbind from the ldap server */
ldap_unbind (ld);
/* reset the alarm handler */
alarm (0);
/* calcutate the elapsed time and compare to thresholds */
microsec = deltime (tv);
elapsed_time = (double)microsec / 1.0e6;
if (crit_time!=UNDEFINED && elapsed_time>crit_time)
status = STATE_CRITICAL;
else if (warn_time!=UNDEFINED && elapsed_time>warn_time)
status = STATE_WARNING;
else
status = STATE_OK;
/* print out the result */
printf (_("LDAP %s - %.3f seconds response time|%s\n"),
state_text (status),
elapsed_time,
fperfdata ("time", elapsed_time, "s",
(int)warn_time, warn_time,
(int)crit_time, crit_time,
TRUE, 0, FALSE, 0));
return status;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
/* initialize the long option struct */
static struct option longopts[] = {
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{"timeout", required_argument, 0, 't'},
{"host", required_argument, 0, 'H'},
{"base", required_argument, 0, 'b'},
{"attr", required_argument, 0, 'a'},
{"bind", required_argument, 0, 'D'},
{"pass", required_argument, 0, 'P'},
#ifdef HAVE_LDAP_SET_OPTION
{"ver2", no_argument, 0, '2'},
{"ver3", no_argument, 0, '3'},
#endif
{"use-ipv4", no_argument, 0, '4'},
{"use-ipv6", no_argument, 0, '6'},
{"port", required_argument, 0, 'p'},
{"warn", required_argument, 0, 'w'},
{"crit", required_argument, 0, 'c'},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
for (c = 1; c < argc; c++) {
if (strcmp ("-to", argv[c]) == 0)
strcpy (argv[c], "-t");
}
while (1) {
c = getopt_long (argc, argv, "hV2346t:c:w:H:b:p:a:D:P:", longopts, &option);
if (c == -1 || c == EOF)
break;
switch (c) {
case 'h': /* help */
print_help ();
exit (STATE_OK);
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 't': /* timeout period */
if (!is_intnonneg (optarg))
usage2 (_("Timeout interval must be a positive integer"), optarg);
else
socket_timeout = atoi (optarg);
break;
case 'H':
ld_host = optarg;
break;
case 'b':
ld_base = optarg;
break;
case 'p':
ld_port = atoi (optarg);
break;
case 'a':
ld_attr = optarg;
break;
case 'D':
ld_binddn = optarg;
break;
case 'P':
ld_passwd = optarg;
break;
case 'w':
warn_time = strtod (optarg, NULL);
break;
case 'c':
crit_time = strtod (optarg, NULL);
break;
#ifdef HAVE_LDAP_SET_OPTION
case '2':
ld_protocol = 2;
break;
case '3':
ld_protocol = 3;
break;
#endif
case '4':
address_family = AF_INET;
break;
case '6':
#ifdef USE_IPV6
address_family = AF_INET6;
#else
usage (_("IPv6 support not available\n"));
#endif
break;
default:
usage2 (_("Unknown argument"), optarg);
}
}
c = optind;
if (ld_host == NULL && is_host(argv[c]))
ld_host = strdup (argv[c++]);
if (ld_base == NULL && argv[c])
ld_base = strdup (argv[c++]);
return validate_arguments ();
}
int
validate_arguments ()
{
if (ld_host==NULL || strlen(ld_host)==0)
usage4 (_("Please specify the host name\n"));
if (ld_base==NULL || strlen(ld_base)==0)
usage4 (_("Please specify the LDAP base\n"));
return OK;
}
void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", DEFAULT_PORT);
print_revision (progname, revision);
printf ("Copyright (c) 1999 Didi Rieder (adrieder@sbox.tu-graz.ac.at)\n");
printf (COPYRIGHT, copyright, email);
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_(UT_HOST_PORT), 'p', myport);
printf (_(UT_IPv46));
printf (_("\
-a [--attr]\n\
ldap attribute to search (default: \"(objectclass=*)\"\n\
-b [--base]\n\
ldap base (eg. ou=my unit, o=my org, c=at)\n\
-D [--bind]\n\
ldap bind DN (if required)\n\
-P [--pass]\n\
ldap password (if required)\n"));
#ifdef HAVE_LDAP_SET_OPTION
printf (_("\
-2 [--ver2]\n\
use ldap protocol version 2\n\
-3 [--ver3]\n\
use ldap protocol version 3\n\
(default protocol version: %d)\n"),
DEFAULT_PROTOCOL);
#endif
printf (_(UT_WARN_CRIT));
printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
printf (_(UT_VERBOSE));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s -H <host> -b <base_dn> [-p <port>] [-a <attr>] [-D <binddn>]\n\
[-P <password>] [-w <warn_time>] [-c <crit_time>]\n\
[-t timeout]%s\n",
//(Note: all times are in seconds.)\n",
progname,
#ifdef HAVE_LDAP_SET_OPTION
" [-2|-3] [-4|-6]"
#else
""
#endif
);
}

295
plugins/check_load.c Normal file
View file

@ -0,0 +1,295 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_load.c,v 1.30 2005/09/14 09:53:49 tonvoon Exp $
******************************************************************************/
const char *progname = "check_load";
const char *revision = "$Revision: 1.30 $";
const char *copyright = "1999-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "utils.h"
#include "popen.h"
#ifdef HAVE_SYS_LOADAVG_H
#include <sys/loadavg.h>
#endif
/* needed for compilation under NetBSD, as suggested by Andy Doran */
#ifndef LOADAVG_1MIN
#define LOADAVG_1MIN 0
#define LOADAVG_5MIN 1
#define LOADAVG_15MIN 2
#endif /* !defined LOADAVG_1MIN */
static int process_arguments (int argc, char **argv);
static int validate_arguments (void);
void print_help (void);
void print_usage (void);
/* strictly for pretty-print usage in loops */
static const int nums[3] = { 1, 5, 15 };
/* provide some fairly sane defaults */
double wload[3] = { 0.0, 0.0, 0.0 };
double cload[3] = { 0.0, 0.0, 0.0 };
#define la1 la[0]
#define la5 la[1]
#define la15 la[2]
char *status_line;
static void
get_threshold(char *arg, double *th)
{
size_t i, n;
char *str = arg, *p;
n = strlen(arg);
for(i = 0; i < 3; i++) {
th[i] = strtod(str, &p);
if(p == str) break;
str = p + 1;
if(n <= (size_t)(str - arg)) break;
}
/* empty argument or non-floatish, so warn about it and die */
if(!i) usage (_("Warning threshold must be float or float triplet!\n"));
if(i != 2) {
/* one or more numbers were given, so fill array with last
* we got (most likely to NOT produce the least expected result) */
for(n = i; n < 3; n++) th[n] = th[i];
}
}
int
main (int argc, char **argv)
{
int result;
int i;
double la[3] = { 0.0, 0.0, 0.0 }; /* NetBSD complains about unitialized arrays */
#ifndef HAVE_GETLOADAVG
char input_buffer[MAX_INPUT_BUFFER];
# ifdef HAVE_PROC_LOADAVG
FILE *fp;
char *str, *next;
# endif
#endif
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
setlocale(LC_NUMERIC, "POSIX");
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
#ifdef HAVE_GETLOADAVG
result = getloadavg (la, 3);
if (result != 3)
return STATE_UNKNOWN;
#else
# ifdef HAVE_PROC_LOADAVG
fp = fopen (PROC_LOADAVG, "r");
if (fp == NULL) {
printf (_("Error opening %s\n"), PROC_LOADAVG);
return STATE_UNKNOWN;
}
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
str = (char *)input_buffer;
for(i = 0; i < 3; i++) {
la[i] = strtod(str, &next);
str = next;
}
}
fclose (fp);
# else
child_process = spopen (PATH_TO_UPTIME);
if (child_process == NULL) {
printf (_("Error opening %s\n"), PATH_TO_UPTIME);
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"), PATH_TO_UPTIME);
}
fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process);
sscanf (input_buffer, "%*[^l]load average: %lf, %lf, %lf", &la1, &la5, &la15);
result = spclose (child_process);
if (result) {
printf (_("Error code %d returned in %s\n"), result, PATH_TO_UPTIME);
return STATE_UNKNOWN;
}
# endif
#endif
if ((la[0] < 0.0) || (la[1] < 0.0) || (la[2] < 0.0)) {
#ifdef HAVE_GETLOADAVG
printf (_("Error in getloadavg()\n"));
#else
# ifdef HAVE_PROC_LOADAVG
printf (_("Error processing %s\n"), PROC_LOADAVG);
# else
printf (_("Error processing %s\n"), PATH_TO_UPTIME);
# endif
#endif
return STATE_UNKNOWN;
}
/* 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);
for(i = 0; i < 3; i++) {
if(la[i] > cload[i]) {
result = STATE_CRITICAL;
break;
}
else if(la[i] > wload[i]) result = STATE_WARNING;
}
printf("%s - %s|", state_text(result), status_line);
for(i = 0; i < 3; i++)
printf("load%d=%.3f;%.3f;%.3f;0; ", nums[i], la[i], wload[i], cload[i]);
putchar('\n');
return result;
}
/* process command-line arguments */
static int
process_arguments (int argc, char **argv)
{
int c = 0;
int option = 0;
static struct option longopts[] = {
{"warning", required_argument, 0, 'w'},
{"critical", required_argument, 0, 'c'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
while (1) {
c = getopt_long (argc, argv, "Vhc:w:", longopts, &option);
if (c == -1 || c == EOF)
break;
switch (c) {
case 'w': /* warning time threshold */
get_threshold(optarg, wload);
break;
case 'c': /* critical time threshold */
get_threshold(optarg, cload);
break;
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case '?': /* help */
usage2 (_("Unknown argument"), optarg);
}
}
c = optind;
if (c == argc)
return validate_arguments ();
/* handle the case if both arguments are missing,
* but not if only one is given without -c or -w flag */
if(c - argc == 2) {
get_threshold(argv[c++], wload);
get_threshold(argv[c++], cload);
}
else if(c - argc == 1) {
get_threshold(argv[c++], cload);
}
return validate_arguments ();
}
static int
validate_arguments (void)
{
int i = 0;
/* match cload first, as it will give the most friendly error message
* if user hasn't given the -c switch properly */
for(i = 0; i < 3; i++) {
if(cload[i] < 0)
die (STATE_UNKNOWN, _("Critical threshold for %d-minute load average is not specified\n"), nums[i]);
if(wload[i] < 0)
die (STATE_UNKNOWN, _("Warning threshold for %d-minute load average is not specified\n"), nums[i]);
if(wload[i] > cload[i])
die (STATE_UNKNOWN, _("Parameter inconsistency: %d-minute \"warning load\" is greater than \"critical load\"\n"), nums[i]);
}
return OK;
}
void
print_help (void)
{
print_revision (progname, revision);
printf ("Copyright (c) 1999 Felipe Gustavo de Almeida <galmeida@linux.ime.usp.br>\n");
printf (COPYRIGHT, copyright, email);
printf (_("This plugin tests the current system load average.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_("\
-w, --warning=WLOAD1,WLOAD5,WLOAD15\n\
Exit with WARNING status if load average exceeds WLOADn\n\
-c, --critical=CLOAD1,CLOAD5,CLOAD15\n\
Exit with CRITICAL status if load average exceed CLOADn\n\n\
the load average format is the same used by \"uptime\" and \"w\"\n\n"));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("Usage: %s -w WLOAD1,WLOAD5,WLOAD15 -c CLOAD1,CLOAD5,CLOAD15\n", progname);
}

380
plugins/check_mrtg.c Normal file
View file

@ -0,0 +1,380 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_mrtg.c,v 1.24 2004/12/25 23:17:44 opensides Exp $
******************************************************************************/
const char *progname = "check_mrtg";
const char *revision = "$Revision: 1.24 $";
const char *copyright = "1999-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "utils.h"
int process_arguments (int, char **);
int validate_arguments (void);
void print_help (void);
void print_usage (void);
char *log_file = NULL;
int expire_minutes = 0;
int use_average = TRUE;
int variable_number = -1;
unsigned long value_warning_threshold = 0L;
unsigned long value_critical_threshold = 0L;
char *label;
char *units;
int
main (int argc, char **argv)
{
int result = STATE_UNKNOWN;
FILE *fp;
int line;
char input_buffer[MAX_INPUT_BUFFER];
char *temp_buffer;
time_t current_time;
char* message;
time_t timestamp = 0L;
unsigned long average_value_rate = 0L;
unsigned long maximum_value_rate = 0L;
unsigned long rate = 0L;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments\n"));
/* open the MRTG log file for reading */
fp = fopen (log_file, "r");
if (fp == NULL) {
printf (_("Unable to open MRTG log file\n"));
return STATE_UNKNOWN;
}
line = 0;
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
line++;
/* skip the first line of the log file */
if (line == 1)
continue;
/* break out of read loop if we've passed the number of entries we want to read */
if (line > 2)
break;
/* grab the timestamp */
temp_buffer = strtok (input_buffer, " ");
timestamp = strtoul (temp_buffer, NULL, 10);
/* grab the average value 1 rate */
temp_buffer = strtok (NULL, " ");
if (variable_number == 1)
average_value_rate = strtoul (temp_buffer, NULL, 10);
/* grab the average value 2 rate */
temp_buffer = strtok (NULL, " ");
if (variable_number == 2)
average_value_rate = strtoul (temp_buffer, NULL, 10);
/* grab the maximum value 1 rate */
temp_buffer = strtok (NULL, " ");
if (variable_number == 1)
maximum_value_rate = strtoul (temp_buffer, NULL, 10);
/* grab the maximum value 2 rate */
temp_buffer = strtok (NULL, " ");
if (variable_number == 2)
maximum_value_rate = strtoul (temp_buffer, NULL, 10);
}
/* close the log file */
fclose (fp);
/* if we couldn't read enough data, return an unknown error */
if (line <= 2) {
result = STATE_UNKNOWN;
asprintf (&message, _("Unable to process MRTG log file\n"));
}
/* make sure the MRTG data isn't too old */
if (result == STATE_OK) {
time (&current_time);
if (expire_minutes > 0
&& (current_time - timestamp) > (expire_minutes * 60)) {
result = STATE_WARNING;
asprintf (&message, _("MRTG data has expired (%d minutes old)\n"),
(int) ((current_time - timestamp) / 60));
}
}
/* else check the incoming/outgoing rates */
if (result == STATE_OK) {
if (use_average == TRUE)
rate = average_value_rate;
else
rate = maximum_value_rate;
if (rate > value_critical_threshold)
result = STATE_CRITICAL;
else if (rate > value_warning_threshold)
result = STATE_WARNING;
asprintf (&message, "%s. %s = %lu %s|%s",
(use_average == TRUE) ? _("Avg") : _("Max"),
label, rate, units,
perfdata(label, (long) rate, units,
(int) value_warning_threshold, (long) value_warning_threshold,
(int) value_critical_threshold, (long) value_critical_threshold,
0, 0, 0, 0));
}
printf ("%s\n", message);
return result;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"logfile", required_argument, 0, 'F'},
{"expires", required_argument, 0, 'e'},
{"aggregation", required_argument, 0, 'a'},
{"variable", required_argument, 0, 'v'},
{"critical", required_argument, 0, 'c'},
{"warning", required_argument, 0, 'w'},
{"label", required_argument, 0, 'l'},
{"units", required_argument, 0, 'u'},
{"verbose", no_argument, 0, 'v'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
for (c = 1; c < argc; c++) {
if (strcmp ("-to", argv[c]) == 0)
strcpy (argv[c], "-t");
else if (strcmp ("-wt", argv[c]) == 0)
strcpy (argv[c], "-w");
else if (strcmp ("-ct", argv[c]) == 0)
strcpy (argv[c], "-c");
}
while (1) {
c = getopt_long (argc, argv, "hVF:e:a:v:c:w:l:u:", longopts,
&option);
if (c == -1 || c == EOF)
break;
switch (c) {
case 'F': /* input file */
log_file = optarg;
break;
case 'e': /* ups name */
expire_minutes = atoi (optarg);
break;
case 'a': /* port */
if (!strcmp (optarg, "MAX"))
use_average = FALSE;
else
use_average = TRUE;
break;
case 'v':
variable_number = atoi (optarg);
if (variable_number < 1 || variable_number > 2)
usage4 (_("Invalid variable number"));
break;
case 'w': /* critical time threshold */
value_warning_threshold = strtoul (optarg, NULL, 10);
break;
case 'c': /* warning time threshold */
value_critical_threshold = strtoul (optarg, NULL, 10);
break;
case 'l': /* label */
label = optarg;
break;
case 'u': /* timeout */
units = optarg;
break;
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case '?': /* help */
usage2 (_("Unknown argument"), optarg);
}
}
c = optind;
if (log_file == NULL && argc > c) {
log_file = argv[c++];
}
if (expire_minutes <= 0 && argc > c) {
if (is_intpos (argv[c]))
expire_minutes = atoi (argv[c++]);
else
die (STATE_UNKNOWN,
_("%s is not a valid expiration time\nUse '%s -h' for additional help\n"),
argv[c], progname);
}
if (argc > c && strcmp (argv[c], "MAX") == 0) {
use_average = FALSE;
c++;
}
else if (argc > c && strcmp (argv[c], "AVG") == 0) {
use_average = TRUE;
c++;
}
if (argc > c && variable_number == -1) {
variable_number = atoi (argv[c++]);
if (variable_number < 1 || variable_number > 2) {
printf ("%s :", argv[c]);
usage (_("Invalid variable number\n"));
}
}
if (argc > c && value_warning_threshold == 0) {
value_warning_threshold = strtoul (argv[c++], NULL, 10);
}
if (argc > c && value_critical_threshold == 0) {
value_critical_threshold = strtoul (argv[c++], NULL, 10);
}
if (argc > c && strlen (label) == 0) {
label = argv[c++];
}
if (argc > c && strlen (units) == 0) {
units = argv[c++];
}
return validate_arguments ();
}
int
validate_arguments (void)
{
if (variable_number == -1)
usage4 (_("You must supply the variable number"));
if (label == NULL)
label = strdup ("value");
if (units == NULL)
units = strdup ("");
return OK;
}
void
print_help (void)
{
print_revision (progname, revision);
printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
printf (COPYRIGHT, copyright, email);
printf(_("\
This plugin will check either the average or maximum value of one of the\n\
two variables recorded in an MRTG log file.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_("\
-F, --logfile=FILE\n\
The MRTG log file containing the data you want to monitor\n\
-e, --expires=MINUTES\n\
Minutes before MRTG data is considered to be too old\n\
-a, --aggregation=AVG|MAX\n\
Should we check average or maximum values?\n\
-v, --variable=INTEGER\n\
Which variable set should we inspect? (1 or 2)\n\
-w, --warning=INTEGER\n\
Threshold value for data to result in WARNING status\n\
-c, --critical=INTEGER\n\
Threshold value for data to result in CRITICAL status\n"));
printf (_("\
-l, --label=STRING\n\
Type label for data (Examples: Conns, \"Processor Load\", In, Out)\n\
-u, --units=STRING\n\
Option units label for data (Example: Packets/Sec, Errors/Sec, \n\
\"Bytes Per Second\", \"%% Utilization\")\n"));
printf (_("\
If the value exceeds the <vwl> threshold, a WARNING status is returned. If\n\
the value exceeds the <vcl> threshold, a CRITICAL status is returned. If\n\
the data in the log file is older than <expire_minutes> old, a WARNING\n\
status is returned and a warning message is printed.\n\n"));
printf(_("This plugin is useful for monitoring MRTG data that does not correspond to\n\
bandwidth usage. (Use the check_mrtgtraf plugin for monitoring bandwidth).\n\
It can be used to monitor any kind of data that MRTG is monitoring - errors,\n\
packets/sec, etc. I use MRTG in conjuction with the Novell NLM that allows\n\
me to track processor utilization, user connections, drive space, etc and\n\
this plugin works well for monitoring that kind of data as well.\n\n"));
printf (_("Notes:\n\
- This plugin only monitors one of the two variables stored in the MRTG log\n\
file. If you want to monitor both values you will have to define two\n\
commands with different values for the <variable> argument. Of course,\n\
you can always hack the code to make this plugin work for you...\n\
- MRTG stands for the Multi Router Traffic Grapher. It can be downloaded from\n\
http://ee-staff.ethz.ch/~oetiker/webtools/mrtg/mrtg.html\n"));
printf (_(UT_SUPPORT));
}
/* original command line:
<log_file> <expire_minutes> <AVG|MAX> <variable> <vwl> <vcl> <label> [units] */
void
print_usage (void)
{
printf ("\
Usage: %s -F log_file -a <AVG | MAX> -v variable -w warning -c critical\n\
[-l label] [-u units] [-e expire_minutes] [-t timeout]\n\
[-v]\n", progname);
}

364
plugins/check_mrtgtraf.c Normal file
View file

@ -0,0 +1,364 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_mrtgtraf.c,v 1.24 2004/12/25 23:17:44 opensides Exp $
******************************************************************************/
#include "common.h"
#include "utils.h"
const char *progname = "check_mrtgtraf";
const char *revision = "$Revision: 1.24 $";
const char *copyright = "1999-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
int process_arguments (int, char **);
int validate_arguments (void);
void print_help(void);
void print_usage(void);
char *log_file = NULL;
int expire_minutes = -1;
int use_average = TRUE;
unsigned long incoming_warning_threshold = 0L;
unsigned long incoming_critical_threshold = 0L;
unsigned long outgoing_warning_threshold = 0L;
unsigned long outgoing_critical_threshold = 0L;
int
main (int argc, char **argv)
{
int result = STATE_UNKNOWN;
FILE *fp;
int line;
char input_buffer[MAX_INPUT_BUFFER];
char *temp_buffer;
time_t current_time;
char *error_message;
time_t timestamp = 0L;
unsigned long average_incoming_rate = 0L;
unsigned long average_outgoing_rate = 0L;
unsigned long maximum_incoming_rate = 0L;
unsigned long maximum_outgoing_rate = 0L;
unsigned long incoming_rate = 0L;
unsigned long outgoing_rate = 0L;
double adjusted_incoming_rate = 0.0;
double adjusted_outgoing_rate = 0.0;
char incoming_speed_rating[8];
char outgoing_speed_rating[8];
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* open the MRTG log file for reading */
fp = fopen (log_file, "r");
if (fp == NULL)
usage4 (_("Unable to open MRTG log file"));
line = 0;
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
line++;
/* skip the first line of the log file */
if (line == 1)
continue;
/* break out of read loop */
/* if we've passed the number of entries we want to read */
if (line > 2)
break;
/* grab the timestamp */
temp_buffer = strtok (input_buffer, " ");
timestamp = strtoul (temp_buffer, NULL, 10);
/* grab the average incoming transfer rate */
temp_buffer = strtok (NULL, " ");
average_incoming_rate = strtoul (temp_buffer, NULL, 10);
/* grab the average outgoing transfer rate */
temp_buffer = strtok (NULL, " ");
average_outgoing_rate = strtoul (temp_buffer, NULL, 10);
/* grab the maximum incoming transfer rate */
temp_buffer = strtok (NULL, " ");
maximum_incoming_rate = strtoul (temp_buffer, NULL, 10);
/* grab the maximum outgoing transfer rate */
temp_buffer = strtok (NULL, " ");
maximum_outgoing_rate = strtoul (temp_buffer, NULL, 10);
}
/* close the log file */
fclose (fp);
/* if we couldn't read enough data, return an unknown error */
if (line <= 2)
usage4 (_("Unable to process MRTG log file"));
/* make sure the MRTG data isn't too old */
time (&current_time);
if ((expire_minutes > 0) &&
(current_time - timestamp) > (expire_minutes * 60))
die (STATE_WARNING, _("MRTG data has expired (%d minutes old)\n"),
(int) ((current_time - timestamp) / 60));
/* else check the incoming/outgoing rates */
if (use_average == TRUE) {
incoming_rate = average_incoming_rate;
outgoing_rate = average_outgoing_rate;
}
else {
incoming_rate = maximum_incoming_rate;
outgoing_rate = maximum_outgoing_rate;
}
/* report incoming traffic in Bytes/sec */
if (incoming_rate < 1024) {
strcpy (incoming_speed_rating, "B/s");
adjusted_incoming_rate = (double) incoming_rate;
}
/* report incoming traffic in KBytes/sec */
else if (incoming_rate < (1024 * 1024)) {
strcpy (incoming_speed_rating, "KB/s");
adjusted_incoming_rate = (double) (incoming_rate / 1024.0);
}
/* report incoming traffic in MBytes/sec */
else {
strcpy (incoming_speed_rating, "MB/s");
adjusted_incoming_rate = (double) (incoming_rate / 1024.0 / 1024.0);
}
/* report outgoing traffic in Bytes/sec */
if (outgoing_rate < 1024) {
strcpy (outgoing_speed_rating, "B/s");
adjusted_outgoing_rate = (double) outgoing_rate;
}
/* report outgoing traffic in KBytes/sec */
else if (outgoing_rate < (1024 * 1024)) {
strcpy (outgoing_speed_rating, "KB/s");
adjusted_outgoing_rate = (double) (outgoing_rate / 1024.0);
}
/* report outgoing traffic in MBytes/sec */
else {
strcpy (outgoing_speed_rating, "MB/s");
adjusted_outgoing_rate = (double) (outgoing_rate / 1024.0 / 1024.0);
}
if (incoming_rate > incoming_critical_threshold
|| outgoing_rate > outgoing_critical_threshold) {
result = STATE_CRITICAL;
}
else if (incoming_rate > incoming_warning_threshold
|| outgoing_rate > outgoing_warning_threshold) {
result = STATE_WARNING;
}
asprintf (&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,
fperfdata("in", adjusted_incoming_rate, incoming_speed_rating,
(int)incoming_warning_threshold, incoming_warning_threshold,
(int)incoming_critical_threshold, incoming_critical_threshold,
TRUE, 0, FALSE, 0),
fperfdata("in", adjusted_outgoing_rate, outgoing_speed_rating,
(int)outgoing_warning_threshold, outgoing_warning_threshold,
(int)outgoing_critical_threshold, outgoing_critical_threshold,
TRUE, 0, FALSE, 0));
printf (_("Traffic %s - %s\n"), state_text(result), error_message);
return result;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"logfile", required_argument, 0, 'F'},
{"expires", required_argument, 0, 'e'},
{"aggregation", required_argument, 0, 'a'},
{"variable", required_argument, 0, 'v'},
{"critical", required_argument, 0, 'c'},
{"warning", required_argument, 0, 'w'},
{"verbose", no_argument, 0, 'v'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
for (c = 1; c < argc; c++) {
if (strcmp ("-to", argv[c]) == 0)
strcpy (argv[c], "-t");
else if (strcmp ("-wt", argv[c]) == 0)
strcpy (argv[c], "-w");
else if (strcmp ("-ct", argv[c]) == 0)
strcpy (argv[c], "-c");
}
while (1) {
c = getopt_long (argc, argv, "hVF:e:a:c:w:", longopts, &option);
if (c == -1 || c == EOF)
break;
switch (c) {
case 'F': /* input file */
log_file = optarg;
break;
case 'e': /* expiration time */
expire_minutes = atoi (optarg);
break;
case 'a': /* aggregation (AVE or MAX) */
if (!strcmp (optarg, "MAX"))
use_average = FALSE;
else
use_average = TRUE;
break;
case 'c': /* warning threshold */
sscanf (optarg, "%lu,%lu", &incoming_critical_threshold,
&outgoing_critical_threshold);
break;
case 'w': /* critical threshold */
sscanf (optarg, "%lu,%lu", &incoming_warning_threshold,
&outgoing_warning_threshold);
break;
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case '?': /* help */
usage2 (_("Unknown argument"), optarg);
}
}
c = optind;
if (argc > c && log_file == NULL) {
log_file = argv[c++];
}
if (argc > c && expire_minutes == -1) {
expire_minutes = atoi (argv[c++]);
}
if (argc > c && strcmp (argv[c], "MAX") == 0) {
use_average = FALSE;
c++;
}
else if (argc > c && strcmp (argv[c], "AVG") == 0) {
use_average = TRUE;
c++;
}
if (argc > c && incoming_warning_threshold == 0) {
incoming_warning_threshold = strtoul (argv[c++], NULL, 10);
}
if (argc > c && incoming_critical_threshold == 0) {
incoming_critical_threshold = strtoul (argv[c++], NULL, 10);
}
if (argc > c && outgoing_warning_threshold == 0) {
outgoing_warning_threshold = strtoul (argv[c++], NULL, 10);
}
if (argc > c && outgoing_critical_threshold == 0) {
outgoing_critical_threshold = strtoul (argv[c++], NULL, 10);
}
return validate_arguments ();
}
int
validate_arguments (void)
{
return OK;
}
void
print_help (void)
{
print_revision (progname, revision);
printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
printf (COPYRIGHT, copyright, email);
printf (_("\n\
This plugin will check the incoming/outgoing transfer rates of a router,\n\
switch, etc recorded in an MRTG log. If the newest log entry is older\n\
than <expire_minutes>, a WARNING status is returned. If either the\n\
incoming or outgoing rates exceed the <icl> or <ocl> thresholds (in\n\
Bytes/sec), a CRITICAL status results. If either of the rates exceed\n\
the <iwl> or <owl> thresholds (in Bytes/sec), a WARNING status results.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_("\
-F, --filename=STRING\n\
File to read log from\n\
-e, --expires=INTEGER\n\
Minutes after which log expires\n\
-a, --aggregation=(AVG|MAX)\n\
Test average or maximum\n\
-w, --warning\n\
Warning threshold pair \"<incoming>,<outgoing>\"\n\
-c, --critical\n\
Critical threshold pair \"<incoming>,<outgoing>\"\n"));
printf (_("Notes:\n\
- MRTG stands for Multi Router Traffic Grapher. It can be downloaded from\n\
http://ee-staff.ethz.ch/~oetiker/webtools/mrtg/mrtg.html\n\
- While MRTG can monitor things other than traffic rates, this\n\
plugin probably won't work with much else without modification.\n\
- The calculated i/o rates are a little off from what MRTG actually\n\
reports. I'm not sure why this is right now, but will look into it\n\
for future enhancements of this plugin.\n"));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s -F <log_file> -a <AVG | MAX> -v <variable> -w <warning_pair>\n\
-c <critical_pair> [-e expire_minutes] [-t timeout] [-v]\n", progname);
}

333
plugins/check_mysql.c Normal file
View file

@ -0,0 +1,333 @@
/******************************************************************************
*
* CHECK_MYSQL.C
*
* Program: Mysql plugin for Nagios
* License: GPL
* Copyright (c) 1999 Didi Rieder (adrieder@sbox.tu-graz.ac.at)
* portions (c) 2000 Karl DeBisschop (kdebisschop@users.sourceforge.net)
*
* $Id: check_mysql.c,v 1.26 2005/05/26 02:13:19 seanius Exp $
*
* Description:
*
* This plugin is for testing a mysql server.
******************************************************************************/
const char *progname = "check_mysql";
const char *revision = "$Revision: 1.26 $";
const char *copyright = "1999-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#define SLAVERESULTSIZE 40
#include "common.h"
#include "utils.h"
#include "netutils.h"
#include <mysql/mysql.h>
#include <mysql/errmsg.h>
char *db_user = NULL;
char *db_host = NULL;
char *db_pass = NULL;
char *db = NULL;
unsigned int db_port = MYSQL_PORT;
int check_slave = 0;
int process_arguments (int, char **);
int validate_arguments (void);
void print_help (void);
void print_usage (void);
int
main (int argc, char **argv)
{
MYSQL mysql;
MYSQL_RES *res;
MYSQL_ROW row;
/* should be status */
char *result = NULL;
char slaveresult[SLAVERESULTSIZE];
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* initialize mysql */
mysql_init (&mysql);
/* establish a connection to the server and error checking */
if (!mysql_real_connect(&mysql,db_host,db_user,db_pass,db,db_port,NULL,0)) {
if (mysql_errno (&mysql) == CR_UNKNOWN_HOST)
die (STATE_WARNING, "%s\n", mysql_error (&mysql));
else if (mysql_errno (&mysql) == CR_VERSION_ERROR)
die (STATE_WARNING, "%s\n", mysql_error (&mysql));
else if (mysql_errno (&mysql) == CR_OUT_OF_MEMORY)
die (STATE_WARNING, "%s\n", mysql_error (&mysql));
else if (mysql_errno (&mysql) == CR_IPSOCK_ERROR)
die (STATE_WARNING, "%s\n", mysql_error (&mysql));
else if (mysql_errno (&mysql) == CR_SOCKET_CREATE_ERROR)
die (STATE_WARNING, "%s\n", mysql_error (&mysql));
else
die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
}
/* get the server stats */
result = strdup (mysql_stat (&mysql));
/* error checking once more */
if (mysql_error (&mysql)) {
if (mysql_errno (&mysql) == CR_SERVER_GONE_ERROR)
die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
else if (mysql_errno (&mysql) == CR_SERVER_LOST)
die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
else if (mysql_errno (&mysql) == CR_UNKNOWN_ERROR)
die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
}
if(check_slave) {
/* check the slave status */
if (mysql_query (&mysql, "show slave status") != 0) {
mysql_close (&mysql);
die (STATE_CRITICAL, _("slave query error: %s\n"), mysql_error (&mysql));
}
/* store the result */
if ( (res = mysql_store_result (&mysql)) == NULL) {
mysql_close (&mysql);
die (STATE_CRITICAL, _("slave store_result error: %s\n"), mysql_error (&mysql));
}
/* fetch the first row */
if ( (row = mysql_fetch_row (res)) == NULL) {
mysql_free_result (res);
mysql_close (&mysql);
die (STATE_CRITICAL, _("slave fetch row error: %s\n"), mysql_error (&mysql));
}
if (mysql_field_count (&mysql) == 12) {
/* mysql 3.23.x */
snprintf (slaveresult, SLAVERESULTSIZE, _("Slave running: %s"), row[6]);
if (strcmp (row[6], "Yes") != 0) {
mysql_free_result (res);
mysql_close (&mysql);
die (STATE_CRITICAL, "%s\n", slaveresult);
}
} else {
/* mysql 4.x.x */
int slave_io_field = -1 , slave_sql_field = -1, i, num_fields;
MYSQL_FIELD* fields;
num_fields = mysql_num_fields(res);
fields = mysql_fetch_fields(res);
for(i = 0; i < num_fields; i++)
{
if (0 == strcmp(fields[i].name, "Slave_IO_Running"))
{
slave_io_field = i;
continue;
}
if (0 == strcmp(fields[i].name, "Slave_SQL_Running"))
{
slave_sql_field = i;
continue;
}
}
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");
}
snprintf (slaveresult, SLAVERESULTSIZE, "Slave IO: %s Slave SQL: %s", row[slave_io_field], row[slave_sql_field]);
if (strcmp (row[slave_io_field], "Yes") != 0 || strcmp (row[slave_sql_field], "Yes") != 0) {
mysql_free_result (res);
mysql_close (&mysql);
die (STATE_CRITICAL, "%s\n", slaveresult);
}
}
/* free the result */
mysql_free_result (res);
}
/* close the connection */
mysql_close (&mysql);
/* print out the result of stats */
if (check_slave) {
printf ("%s %s\n", result, slaveresult);
} else {
printf ("%s\n", result);
}
return STATE_OK;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"hostname", required_argument, 0, 'H'},
{"database", required_argument, 0, 'd'},
{"username", required_argument, 0, 'u'},
{"password", required_argument, 0, 'p'},
{"port", required_argument, 0, 'P'},
{"check-slave", no_argument, 0, 'S'},
{"verbose", no_argument, 0, 'v'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
if (argc < 1)
return ERROR;
while (1) {
c = getopt_long (argc, argv, "hVSP:p:u:d:H:", longopts, &option);
if (c == -1 || c == EOF)
break;
switch (c) {
case 'H': /* hostname */
if (is_host (optarg)) {
db_host = optarg;
}
else {
usage2 (_("Invalid hostname/address"), optarg);
}
break;
case 'd': /* hostname */
db = optarg;
break;
case 'u': /* username */
db_user = optarg;
break;
case 'p': /* authentication information: password */
db_pass = optarg;
break;
case 'P': /* critical time threshold */
db_port = atoi (optarg);
break;
case 'S':
check_slave = 1; /* check-slave */
break;
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case '?': /* help */
usage2 (_("Unknown argument"), optarg);
}
}
c = optind;
while ( argc > c ) {
if (strlen(db_host) == 0)
if (is_host (argv[c])) {
db_host = argv[c++];
}
else {
usage2 (_("Invalid hostname/address"), optarg);
}
else if (strlen(db_user) == 0)
db_user = argv[c++];
else if (strlen(db_pass) == 0)
db_pass = argv[c++];
else if (strlen(db) == 0)
db = argv[c++];
else if (is_intnonneg (argv[c]))
db_port = atoi (argv[c++]);
else
break;
}
return validate_arguments ();
}
int
validate_arguments (void)
{
if (db_user == NULL)
db_user = strdup("");
if (db_host == NULL)
db_host = strdup("");
if (db_pass == NULL)
db_pass == strdup("");
if (db == NULL)
db = strdup("");
return OK;
}
void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", MYSQL_PORT);
print_revision (progname, revision);
printf (_(COPYRIGHT), copyright, email);
printf (_("This program tests connections to a mysql server\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_(UT_HOST_PORT), 'P', myport);
printf (_("\
-d, --database=STRING\n\
Check database with indicated name\n\
-u, --username=STRING\n\
Connect using the indicated username\n\
-p, --password=STRING\n\
Use the indicated password to authenticate the connection\n\
==> IMPORTANT: THIS FORM OF AUTHENTICATION IS NOT SECURE!!! <==\n\
Your clear-text password will be visible as a process table entry\n\
-S, --check-slave\n\
Check if the slave thread is running properly.\n"));
printf (_("\n\
There are no required arguments. By default, the local database with\n\
a server listening on MySQL standard port %d will be checked\n"), MYSQL_PORT);
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s [-d database] [-H host] [-P port] [-u user] [-p password] [-S]\n",
progname);
}

299
plugins/check_nagios.c Normal file
View file

@ -0,0 +1,299 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_nagios.c,v 1.26 2005/05/25 00:43:20 seanius Exp $
******************************************************************************/
const char *progname = "check_nagios";
const char *revision = "$Revision: 1.26 $";
const char *copyright = "1999-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "popen.h"
#include "utils.h"
int process_arguments (int, char **);
void print_help (void);
void print_usage (void);
char *status_log = NULL;
char *process_string = NULL;
int expire_minutes = 0;
int verbose = 0;
int
main (int argc, char **argv)
{
int result = STATE_UNKNOWN;
char input_buffer[MAX_INPUT_BUFFER];
unsigned long latest_entry_time = 0L;
unsigned long temp_entry_time = 0L;
int proc_entries = 0;
time_t current_time;
char *temp_ptr;
FILE *fp;
int procuid = 0;
int procpid = 0;
int procppid = 0;
int procvsz = 0;
int procrss = 0;
float procpcpu = 0;
char procstat[8];
char procetime[MAX_INPUT_BUFFER];
char procprog[MAX_INPUT_BUFFER];
char *procargs;
int pos, cols;
int expected_cols = PS_COLS - 1;
const char *zombie = "Z";
char *temp_string;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* Set signal handling and alarm timeout */
if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
usage4 (_("Cannot catch SIGALRM"));
}
/* handle timeouts gracefully... */
alarm (timeout_interval);
/* open the status log */
fp = fopen (status_log, "r");
if (fp == NULL) {
printf (_("CRITICAL - Cannot open status log for reading!\n"));
return STATE_CRITICAL;
}
/* get the date/time of the last item updated in the log */
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
temp_ptr = strtok (input_buffer, "]");
temp_entry_time =
(temp_ptr == NULL) ? 0L : strtoul (temp_ptr + 1, NULL, 10);
if (temp_entry_time > latest_entry_time)
latest_entry_time = temp_entry_time;
}
fclose (fp);
if (verbose >= 2)
printf(_("command: %s\n"), PS_COMMAND);
/* run the command to check for the Nagios process.. */
child_process = spopen (PS_COMMAND);
if (child_process == NULL) {
printf (_("Could not open pipe: %s\n"), PS_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"), PS_COMMAND);
}
fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process);
/* count the number of matching Nagios processes... */
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
cols = sscanf (input_buffer, PS_FORMAT, PS_VARLIST);
/* Zombie processes do not give a procprog command */
if ( cols == (expected_cols - 1) && strstr(procstat, zombie) ) {
cols = expected_cols;
/* Set some value for procargs for the strip command further below
Seen to be a problem on some Solaris 7 and 8 systems */
input_buffer[pos] = '\n';
input_buffer[pos+1] = 0x0;
}
if ( cols >= expected_cols ) {
asprintf (&procargs, "%s", input_buffer + pos);
strip (procargs);
/* Some ps return full pathname for command. This removes path */
temp_string = strtok ((char *)procprog, "/");
while (temp_string) {
strcpy(procprog, temp_string);
temp_string = strtok (NULL, "/");
}
/* May get empty procargs */
if (!strstr(procargs, argv[0]) && strstr(procargs, process_string) && strcmp(procargs,"")) {
proc_entries++;
if (verbose >= 2) {
printf (_("Found process: %s %s\n"), procprog, procargs);
}
}
}
}
/* If we get anything on stderr, at least set warning */
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr))
result = max_state (result, STATE_WARNING);
/* close stderr */
(void) fclose (child_stderr);
/* close the pipe */
if (spclose (child_process))
result = max_state (result, STATE_WARNING);
/* reset the alarm handler */
alarm (0);
if (proc_entries == 0) {
printf (_("Could not locate a running Nagios process!\n"));
return STATE_CRITICAL;
}
result = STATE_OK;
time (&current_time);
if ((int)(current_time - latest_entry_time) > (expire_minutes * 60))
result = STATE_WARNING;
printf
(_("Nagios %s: located %d process%s, status log updated %d second%s ago\n"),
(result == STATE_OK) ? "ok" : "problem", proc_entries,
(proc_entries == 1) ? "" : "es",
(int) (current_time - latest_entry_time),
((int) (current_time - latest_entry_time) == 1) ? "" : "s");
return result;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"filename", required_argument, 0, 'F'},
{"expires", required_argument, 0, 'e'},
{"command", required_argument, 0, 'C'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
if (!is_option (argv[1])) {
status_log = argv[1];
if (is_intnonneg (argv[2]))
expire_minutes = atoi (argv[2]);
else
die (STATE_UNKNOWN,
_("Expiration time must be an integer (seconds)\n"));
process_string = argv[3];
return OK;
}
while (1) {
c = getopt_long (argc, argv, "+hVvF:C:e:", longopts, &option);
if (c == -1 || c == EOF || c == 1)
break;
switch (c) {
case '?': /* print short usage statement if args not parsable */
usage2 (_("Unknown argument"), optarg);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'F': /* status log */
status_log = optarg;
break;
case 'C': /* command */
process_string = optarg;
break;
case 'e': /* expiry time */
if (is_intnonneg (optarg))
expire_minutes = atoi (optarg);
else
die (STATE_UNKNOWN,
_("Expiration time must be an integer (seconds)\n"));
break;
case 'v':
verbose++;
break;
}
}
if (status_log == NULL)
die (STATE_UNKNOWN,
_("You must provide the status_log\n"));
else if (process_string == NULL)
die (STATE_UNKNOWN,
_("You must provide a process string\n"));
return OK;
}
void
print_help (void)
{
print_revision (progname, revision);
printf (_(COPYRIGHT), copyright, email);
printf (_("\
This plugin checks the status of the Nagios process on the local\n\
machine. The plugin will check to make sure the Nagios status log is no older\n\
than the number of minutes specified by the expires option. It also\n\
checks the process table for a process matching the command argument.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_("\
-F, --filename=FILE\n\
Name of the log file to check\n\
-e, --expires=INTEGER\n\
Minutes aging after which logfile is considered stale\n\
-C, --command=STRING\n\
Substring to search for in process arguments\n"));
printf (_("\
Example:\n\
./check_nagios -e 5 -F /usr/local/nagios/var/status.log -C /usr/local/nagios/bin/nagios\n"));
}
void
print_usage (void)
{
printf ("\
Usage: %s -F <status log file> -e <expire_minutes> -C <process_string>\n", progname);
}

695
plugins/check_nt.c Normal file
View file

@ -0,0 +1,695 @@
/******************************************************************************
*
* CHECK_NT.C
*
* Program: Windows NT plugin for Nagios
* License: GPL
* Copyright (c) 2000-2002 Yves Rubin (rubiyz@yahoo.com)
*
* Description:
*
* This requires NSClient software to run on NT (http://nsclient.ready2run.nl/)
*
* License Information:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id: check_nt.c,v 1.39 2005/01/19 23:39:45 harpermann Exp $
*
*****************************************************************************/
const char *progname = "check_nt";
const char *revision = "$Revision: 1.39 $";
const char *copyright = "2003-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "netutils.h"
#include "utils.h"
enum checkvars {
CHECK_NONE,
CHECK_CLIENTVERSION,
CHECK_CPULOAD,
CHECK_UPTIME,
CHECK_USEDDISKSPACE,
CHECK_SERVICESTATE,
CHECK_PROCSTATE,
CHECK_MEMUSE,
CHECK_COUNTER,
CHECK_FILEAGE
};
enum {
MAX_VALUE_LIST = 30,
PORT = 1248
};
char *server_address=NULL;
char *volume_name=NULL;
int server_port=PORT;
char *value_list=NULL;
char *req_password=NULL;
unsigned long lvalue_list[MAX_VALUE_LIST];
unsigned long warning_value=0L;
unsigned long critical_value=0L;
int check_warning_value=FALSE;
int check_critical_value=FALSE;
enum checkvars vars_to_check = CHECK_NONE;
int show_all=FALSE;
char recv_buffer[MAX_INPUT_BUFFER];
void fetch_data (const char* address, int port, const char* sendb);
int process_arguments(int, char **);
void preparelist(char *string);
int strtoularray(unsigned long *array, char *string, const char *delim);
void print_help(void);
void print_usage(void);
int main(int argc, char **argv){
/* should be int result = STATE_UNKNOWN; */
int return_code = STATE_UNKNOWN;
char *send_buffer=NULL;
char *output_message=NULL;
char *perfdata=NULL;
char *temp_string=NULL;
char *temp_string_perf=NULL;
char *description=NULL,*counter_unit = NULL;
char *minval = NULL, *maxval = NULL, *errcvt = NULL;
double total_disk_space=0;
double free_disk_space=0;
double percent_used_space=0;
double warning_used_space=0;
double critical_used_space=0;
double mem_commitLimit=0;
double mem_commitByte=0;
double fminval = 0, fmaxval = 0;
unsigned long utilization;
unsigned long uptime;
unsigned long age_in_minutes;
double counter_value = 0.0;
int offset=0;
int updays=0;
int uphours=0;
int upminutes=0;
int isPercent = FALSE;
int allRight = FALSE;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if(process_arguments(argc,argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* initialize alarm signal handling */
signal(SIGALRM,socket_timeout_alarm_handler);
/* set socket timeout */
alarm(socket_timeout);
switch (vars_to_check) {
case CHECK_CLIENTVERSION:
asprintf(&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);
return_code = STATE_WARNING;
} else {
asprintf (&output_message, "%s", recv_buffer);
return_code = STATE_OK;
}
break;
case CHECK_CPULOAD:
if (value_list==NULL)
output_message = strdup (_("missing -l parameters"));
else if (strtoularray(lvalue_list,value_list,",")==FALSE)
output_message = strdup (_("wrong -l parameter."));
else {
/* -l parameters is present with only integers */
return_code=STATE_OK;
temp_string = strdup (_("CPU Load"));
temp_string_perf = strdup (" ");
/* loop until one of the parameters is wrong or not present */
while (lvalue_list[0+offset]> (unsigned long)0 &&
lvalue_list[0+offset]<=(unsigned long)17280 &&
lvalue_list[1+offset]> (unsigned long)0 &&
lvalue_list[1+offset]<=(unsigned long)100 &&
lvalue_list[2+offset]> (unsigned long)0 &&
lvalue_list[2+offset]<=(unsigned long)100) {
/* Send request and retrieve data */
asprintf(&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);
/* Check if any of the request is in a warning or critical state */
if(utilization >= lvalue_list[2+offset])
return_code=STATE_CRITICAL;
else if(utilization >= lvalue_list[1+offset] && return_code<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,
lvalue_list[1+offset], lvalue_list[2+offset]);
asprintf(&temp_string_perf,"%s%s",temp_string_perf,perfdata);
offset+=3; /* move across the array */
}
if (strlen(temp_string)>10) { /* we had at least one loop */
output_message = strdup (temp_string);
perfdata = temp_string_perf;
} else
output_message = strdup (_("not enough values for -l parameters"));
}
break;
case CHECK_UPTIME:
asprintf(&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);
return_code=STATE_OK;
break;
case CHECK_USEDDISKSPACE:
if (value_list==NULL)
output_message = strdup (_("missing -l parameters"));
else if (strlen(value_list)!=1)
output_message = strdup (_("wrong -l argument"));
else {
asprintf(&send_buffer,"%s&4&%s", req_password, value_list);
fetch_data (server_address, server_port, send_buffer);
free_disk_space=atof(strtok(recv_buffer,"&"));
total_disk_space=atof(strtok(NULL,"&"));
percent_used_space = ((total_disk_space - free_disk_space) / total_disk_space) * 100;
warning_used_space = ((float)warning_value / 100) * total_disk_space;
critical_used_space = ((float)critical_value / 100) * total_disk_space;
if (free_disk_space>=0) {
asprintf(&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,
(total_disk_space - free_disk_space) / 1073741824, warning_used_space / 1073741824,
critical_used_space / 1073741824, total_disk_space / 1073741824);
if(check_critical_value==TRUE && percent_used_space >= critical_value)
return_code=STATE_CRITICAL;
else if (check_warning_value==TRUE && percent_used_space >= warning_value)
return_code=STATE_WARNING;
else
return_code=STATE_OK;
output_message = strdup (temp_string);
perfdata = temp_string_perf;
} else {
output_message = strdup (_("Free disk space : Invalid drive "));
return_code=STATE_UNKNOWN;
}
}
break;
case CHECK_SERVICESTATE:
case CHECK_PROCSTATE:
if (value_list==NULL)
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,
(show_all==TRUE) ? "ShowAll" : "ShowFail",value_list);
fetch_data (server_address, server_port, send_buffer);
return_code=atoi(strtok(recv_buffer,"&"));
temp_string=strtok(NULL,"&");
output_message = strdup (temp_string);
}
break;
case CHECK_MEMUSE:
asprintf(&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,"&"));
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%%)"),
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,
warning_used_space / 1048567, critical_used_space / 1048567, mem_commitLimit / 1048567);
return_code=STATE_OK;
if(check_critical_value==TRUE && percent_used_space >= critical_value)
return_code=STATE_CRITICAL;
else if (check_warning_value==TRUE && percent_used_space >= warning_value)
return_code=STATE_WARNING;
break;
case CHECK_COUNTER:
/*
CHECK_COUNTER has been modified to provide extensive perfdata information.
In order to do this, some modifications have been done to the code
and some constraints have been introduced.
1) For the sake of simplicity of the code, perfdata information will only be
provided when the "description" field is added.
2) If the counter you're going to measure is percent-based, the code will detect
the percent sign in its name and will attribute minimum (0%) and maximum (100%)
values automagically, as well the ¨%" sign to graph units.
3) OTOH, if the counter is "absolute", you'll have to provide the following
the counter unit - that is, the dimensions of the counter you're getting. Examples:
pages/s, packets transferred, etc.
4) If you want, you may provide the minimum and maximum values to expect. They aren't mandatory,
but once specified they MUST have the same order of magnitude and units of -w and -c; otherwise.
strange things will happen when you make graphs of your data.
*/
if (value_list == NULL)
output_message = strdup (_("No counter specified"));
else
{
preparelist (value_list); /* replace , between services with & to send the request */
isPercent = (strchr (value_list, '%') != NULL);
strtok (value_list, "&"); /* burn the first parameters */
description = strtok (NULL, "&");
counter_unit = strtok (NULL, "&");
asprintf (&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);
else if (isPercent)
{
counter_unit = strdup ("%");
allRight = TRUE;
}
if ((counter_unit != NULL) && (!allRight))
{
minval = strtok (NULL, "&");
maxval = strtok (NULL, "&");
/* All parameters specified. Let's check the numbers */
fminval = (minval != NULL) ? strtod (minval, &errcvt) : -1;
fmaxval = (minval != NULL) ? strtod (maxval, &errcvt) : -1;
if ((fminval == 0) && (minval == errcvt))
output_message = strdup (_("Minimum value contains non-numbers"));
else
{
if ((fmaxval == 0) && (maxval == errcvt))
output_message = strdup (_("Maximum value contains non-numbers"));
else
allRight = TRUE; /* Everything is OK. */
}
}
else if ((counter_unit == NULL) && (description != NULL))
output_message = strdup (_("No unit counter specified"));
if (allRight)
{
/* Let's format the output string, finally... */
if (strstr(description, "%") == NULL) {
asprintf (&output_message, "%s = %.2f %s", description, counter_value, counter_unit);
} else {
/* has formatting, will segv if wrong */
asprintf (&output_message, description, counter_value);
}
asprintf (&output_message, "%s |", output_message);
asprintf (&output_message,"%s %s", output_message,
fperfdata (description, counter_value,
counter_unit, 1, warning_value, 1, critical_value,
(!(isPercent) && (minval != NULL)), fminval,
(!(isPercent) && (minval != NULL)), fmaxval));
}
}
if (critical_value > warning_value)
{ /* Normal thresholds */
if (check_critical_value == TRUE && counter_value >= critical_value)
return_code = STATE_CRITICAL;
else if (check_warning_value == TRUE && counter_value >= warning_value)
return_code = STATE_WARNING;
else
return_code = STATE_OK;
}
else
{ /* inverse thresholds */
return_code = STATE_OK;
if (check_critical_value == TRUE && counter_value <= critical_value)
return_code = STATE_CRITICAL;
else if (check_warning_value == TRUE && counter_value <= warning_value)
return_code = STATE_WARNING;
}
break;
case CHECK_FILEAGE:
if (value_list==NULL)
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);
fetch_data (server_address, server_port, send_buffer);
age_in_minutes = atoi(strtok(recv_buffer,"&"));
description = strtok(NULL,"&");
output_message = strdup (description);
if (critical_value > warning_value) { /* Normal thresholds */
if(check_critical_value==TRUE && age_in_minutes >= critical_value)
return_code=STATE_CRITICAL;
else if (check_warning_value==TRUE && age_in_minutes >= warning_value)
return_code=STATE_WARNING;
else
return_code=STATE_OK;
}
else { /* inverse thresholds */
if(check_critical_value==TRUE && age_in_minutes <= critical_value)
return_code=STATE_CRITICAL;
else if (check_warning_value==TRUE && age_in_minutes <= warning_value)
return_code=STATE_WARNING;
else
return_code=STATE_OK;
}
}
break;
case CHECK_NONE:
default:
usage4 (_("Please specify a variable to check"));
break;
}
/* reset timeout */
alarm(0);
if (perfdata==NULL)
printf("%s\n",output_message);
else
printf("%s | %s\n",output_message,perfdata);
return return_code;
}
/* process command-line arguments */
int process_arguments(int argc, char **argv){
int c;
int option = 0;
static struct option longopts[] =
{
{"port", required_argument,0,'p'},
{"timeout", required_argument,0,'t'},
{"critical", required_argument,0,'c'},
{"warning", required_argument,0,'w'},
{"variable", required_argument,0,'v'},
{"hostname", required_argument,0,'H'},
{"version", no_argument, 0,'V'},
{"help", no_argument, 0,'h'},
{0,0,0,0}
};
/* no options were supplied */
if(argc<2) return ERROR;
/* backwards compatibility */
if (! is_option(argv[1])) {
server_address = strdup(argv[1]);
argv[1]=argv[0];
argv=&argv[1];
argc--;
}
for (c=1;c<argc;c++) {
if(strcmp("-to",argv[c])==0)
strcpy(argv[c],"-t");
else if (strcmp("-wv",argv[c])==0)
strcpy(argv[c],"-w");
else if (strcmp("-cv",argv[c])==0)
strcpy(argv[c],"-c");
}
while (1){
c = getopt_long(argc,argv,"+hVH:t:c:w:p:v:l:s:d:",longopts,&option);
if (c==-1||c==EOF||c==1)
break;
switch (c)
{
case '?': /* print short usage statement if args not parsable */
usage2 (_("Unknown argument"), optarg);
case 'h': /* help */
print_help();
exit(STATE_OK);
case 'V': /* version */
print_revision(progname,revision);
exit(STATE_OK);
case 'H': /* hostname */
if (server_address) free(server_address);
server_address = optarg;
break;
case 's': /* password */
req_password = optarg;
break;
case 'p': /* port */
if (is_intnonneg(optarg))
server_port=atoi(optarg);
else
die(STATE_UNKNOWN,_("Server port must be an integer\n"));
break;
case 'v':
if(strlen(optarg)<4)
return ERROR;
if(!strcmp(optarg,"CLIENTVERSION"))
vars_to_check=CHECK_CLIENTVERSION;
else if(!strcmp(optarg,"CPULOAD"))
vars_to_check=CHECK_CPULOAD;
else if(!strcmp(optarg,"UPTIME"))
vars_to_check=CHECK_UPTIME;
else if(!strcmp(optarg,"USEDDISKSPACE"))
vars_to_check=CHECK_USEDDISKSPACE;
else if(!strcmp(optarg,"SERVICESTATE"))
vars_to_check=CHECK_SERVICESTATE;
else if(!strcmp(optarg,"PROCSTATE"))
vars_to_check=CHECK_PROCSTATE;
else if(!strcmp(optarg,"MEMUSE"))
vars_to_check=CHECK_MEMUSE;
else if(!strcmp(optarg,"COUNTER"))
vars_to_check=CHECK_COUNTER;
else if(!strcmp(optarg,"FILEAGE"))
vars_to_check=CHECK_FILEAGE;
else
return ERROR;
break;
case 'l': /* value list */
value_list = optarg;
break;
case 'w': /* warning threshold */
warning_value=strtoul(optarg,NULL,10);
check_warning_value=TRUE;
break;
case 'c': /* critical threshold */
critical_value=strtoul(optarg,NULL,10);
check_critical_value=TRUE;
break;
case 'd': /* Display select for services */
if (!strcmp(optarg,"SHOWALL"))
show_all = TRUE;
break;
case 't': /* timeout */
socket_timeout=atoi(optarg);
if(socket_timeout<=0)
return ERROR;
}
}
if (vars_to_check==CHECK_NONE)
return ERROR;
if (req_password == NULL)
req_password = strdup (_("None"));
return OK;
}
void fetch_data (const char *address, int port, const char *sendb) {
int result;
result=process_tcp_request(address, port, sendb, recv_buffer,sizeof(recv_buffer));
if(result!=STATE_OK)
die (result, _("could not fetch information from server\n"));
if (!strncmp(recv_buffer,"ERROR",5))
die (STATE_UNKNOWN, "NSClient - %s\n",recv_buffer);
}
int strtoularray(unsigned long *array, char *string, const char *delim) {
/* split a <delim> delimited string into a long array */
int idx=0;
char *t1;
for (idx=0;idx<MAX_VALUE_LIST;idx++)
array[idx]=0;
idx=0;
for(t1 = strtok(string,delim);t1 != NULL; t1 = strtok(NULL, delim)) {
if (is_numeric(t1) && idx<MAX_VALUE_LIST) {
array[idx]=strtoul(t1,NULL,10);
idx++;
} else
return FALSE;
}
return TRUE;
}
void preparelist(char *string) {
/* Replace all , with & which is the delimiter for the request */
int i;
for (i = 0; (size_t)i < strlen(string); i++)
if (string[i] == ',') {
string[i]='&';
}
}
void print_help(void)
{
print_revision(progname,revision);
printf ("Copyright (c) 2000 Yves Rubin (rubiyz@yahoo.com)\n");
printf (COPYRIGHT, copyright, email);
printf (_("This plugin collects data from the NSClient service running on a\n\
Windows NT/2000/XP/2003 server.\n\n"));
print_usage();
printf (_("\nOptions:\n\
-H, --hostname=HOST\n\
Name of the host to check\n\
-p, --port=INTEGER\n\
Optional port number (default: %d)\n\
-s <password>\n\
Password needed for the request\n\
-w, --warning=INTEGER\n\
Threshold which will result in a warning status\n\
-c, --critical=INTEGER\n\
Threshold which will result in a critical status\n\
-t, --timeout=INTEGER\n\
Seconds before connection attempt times out (default: %d)\n\
-h, --help\n\
Print this help screen\n\
-V, --version\n\
Print version information\n"), PORT, DEFAULT_SOCKET_TIMEOUT);
printf (_("\
-v, --variable=STRING\n\
Variable to check. Valid variables are:\n"));
printf (_("\
CLIENTVERSION = Get the NSClient version\n\
If -l <version> is specified, will return warning if versions differ.\n"));
printf (_("\
CPULOAD = Average CPU load on last x minutes.\n\
Request a -l parameter with the following syntax:\n\
-l <minutes range>,<warning threshold>,<critical threshold>.\n\
<minute range> should be less than 24*60.\n\
Thresholds are percentage and up to 10 requests can be done in one shot.\n\
ie: -l 60,90,95,120,90,95\n"));
printf (_("\
UPTIME = Get the uptime of the machine.\n\
No specific parameters. No warning or critical threshold\n"));
printf (_("\
USEDDISKSPACE = Size and percentage of disk use.\n\
Request a -l parameter containing the drive letter only.\n\
Warning and critical thresholds can be specified with -w and -c.\n"));
printf (_("\
MEMUSE = Memory use.\n\
Warning and critical thresholds can be specified with -w and -c.\n"));
printf (_("\
SERVICESTATE = Check the state of one or several services.\n\
Request a -l parameters with the following syntax:\n\
-l <service1>,<service2>,<service3>,...\n\
You can specify -d SHOWALL in case you want to see working services\n\
in the returned string.\n"));
printf (_("\
PROCSTATE = Check if one or several process are running.\n\
Same syntax as SERVICESTATE.\n"));
printf (_("\
COUNTER = Check any performance counter of Windows NT/2000.\n\
Request a -l parameters with the following syntax:\n\
-l \"\\\\<performance object>\\\\counter\",\"<description>\n\
The <description> parameter is optional and \n\
is given to a printf output command which requires a float parameter.\n\
If <description> does not include \"%%\", it is used as a label.\n\
Some examples:\n\
\"Paging file usage is %%.2f %%%%\"\n\
\"%%.f %%%% paging file used.\"\n"));
printf (_("Notes:\n\
- The NSClient service should be running on the server to get any information\n\
(http://nsclient.ready2run.nl).\n\
- Critical thresholds should be lower than warning thresholds\n"));
}
void print_usage(void)
{
printf("\
Usage: %s -H host -v variable [-p port] [-w warning] [-c critical]\n\
[-l params] [-d SHOWALL] [-t timeout]\n", progname);
}

1008
plugins/check_nwstat.c Normal file

File diff suppressed because it is too large Load diff

456
plugins/check_overcr.c Normal file
View file

@ -0,0 +1,456 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_overcr.c,v 1.19 2004/12/25 23:17:44 opensides Exp $
******************************************************************************/
const char *progname = "check_overcr";
const char *revision = "$Revision: 1.19 $";
const char *copyright = "2000-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "netutils.h"
#include "utils.h"
enum checkvar {
NONE,
LOAD1,
LOAD5,
LOAD15,
DPU,
PROCS,
NETSTAT,
UPTIME
};
enum {
PORT = 2000
};
char *server_address = NULL;
int server_port = PORT;
double warning_value = 0L;
double critical_value = 0L;
int check_warning_value = FALSE;
int check_critical_value = FALSE;
enum checkvar vars_to_check = NONE;
int cmd_timeout = 1;
int netstat_port = 0;
char *disk_name = NULL;
char *process_name = NULL;
char send_buffer[MAX_INPUT_BUFFER];
int process_arguments (int, char **);
void print_usage (void);
void print_help (void);
int
main (int argc, char **argv)
{
int result = STATE_UNKNOWN;
char recv_buffer[MAX_INPUT_BUFFER];
char temp_buffer[MAX_INPUT_BUFFER];
char *temp_ptr = NULL;
int found_disk = FALSE;
unsigned long percent_used_disk_space = 100;
double load;
double load_1min;
double load_5min;
double load_15min;
int port_connections = 0;
int processes = 0;
double uptime_raw_hours;
int uptime_raw_minutes = 0;
int uptime_days = 0;
int uptime_hours = 0;
int uptime_minutes = 0;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* initialize alarm signal handling */
signal (SIGALRM, socket_timeout_alarm_handler);
/* set socket timeout */
alarm (socket_timeout);
result = process_tcp_request2 (server_address,
server_port,
send_buffer,
recv_buffer,
sizeof (recv_buffer));
switch (vars_to_check) {
case LOAD1:
case LOAD5:
case LOAD15:
if (result != STATE_OK)
die (result, _("Unknown error fetching load data\n"));
temp_ptr = (char *) strtok (recv_buffer, "\r\n");
if (temp_ptr == NULL)
die (STATE_CRITICAL, _("Invalid response from server - no load information\n"));
else
load_1min = strtod (temp_ptr, NULL);
temp_ptr = (char *) strtok (NULL, "\r\n");
if (temp_ptr == NULL)
die (STATE_CRITICAL, _("Invalid response from server after load 1\n"));
else
load_5min = strtod (temp_ptr, NULL);
temp_ptr = (char *) strtok (NULL, "\r\n");
if (temp_ptr == NULL)
die (STATE_CRITICAL, _("Invalid response from server after load 5\n"));
else
load_15min = strtod (temp_ptr, NULL);
switch (vars_to_check) {
case LOAD1:
strcpy (temp_buffer, "1");
load = load_1min;
break;
case LOAD5:
strcpy (temp_buffer, "5");
load = load_5min;
break;
default:
strcpy (temp_buffer, "15");
load = load_15min;
break;
}
if (check_critical_value == TRUE && (load >= critical_value))
result = STATE_CRITICAL;
else if (check_warning_value == TRUE && (load >= warning_value))
result = STATE_WARNING;
die (result,
_("Load %s - %s-min load average = %0.2f"),
state_text(result),
temp_buffer,
load);
break;
case DPU:
if (result != STATE_OK)
die (result, _("Unknown error fetching disk data\n"));
for (temp_ptr = (char *) strtok (recv_buffer, " ");
temp_ptr != NULL;
temp_ptr = (char *) strtok (NULL, " ")) {
if (!strcmp (temp_ptr, disk_name)) {
found_disk = TRUE;
temp_ptr = (char *) strtok (NULL, "%");
if (temp_ptr == NULL)
die (STATE_CRITICAL, _("Invalid response from server\n"));
else
percent_used_disk_space = strtoul (temp_ptr, NULL, 10);
break;
}
temp_ptr = (char *) strtok (NULL, "\r\n");
}
/* error if we couldn't find the info for the disk */
if (found_disk == FALSE)
die (STATE_CRITICAL,
"CRITICAL - Disk '%s' non-existent or not mounted",
disk_name);
if (check_critical_value == TRUE && (percent_used_disk_space >= critical_value))
result = STATE_CRITICAL;
else if (check_warning_value == TRUE && (percent_used_disk_space >= warning_value))
result = STATE_WARNING;
die (result, "Disk %s - %lu%% used on %s", state_text(result), percent_used_disk_space, disk_name);
break;
case NETSTAT:
if (result != STATE_OK)
die (result, _("Unknown error fetching network status\n"));
else
port_connections = strtod (recv_buffer, NULL);
if (check_critical_value == TRUE && (port_connections >= critical_value))
result = STATE_CRITICAL;
else if (check_warning_value == TRUE && (port_connections >= warning_value))
result = STATE_WARNING;
die (result,
_("Net %s - %d connection%s on port %d"),
state_text(result),
port_connections,
(port_connections == 1) ? "" : "s",
netstat_port);
break;
case PROCS:
if (result != STATE_OK)
die (result, _("Unknown error fetching process status\n"));
temp_ptr = (char *) strtok (recv_buffer, "(");
if (temp_ptr == NULL)
die (STATE_CRITICAL, _("Invalid response from server\n"));
temp_ptr = (char *) strtok (NULL, ")");
if (temp_ptr == NULL)
die (STATE_CRITICAL, _("Invalid response from server\n"));
else
processes = strtod (temp_ptr, NULL);
if (check_critical_value == TRUE && (processes >= critical_value))
result = STATE_CRITICAL;
else if (check_warning_value == TRUE && (processes >= warning_value))
result = STATE_WARNING;
die (result,
_("Process %s - %d instance%s of %s running"),
state_text(result),
processes,
(processes == 1) ? "" : "s",
process_name);
break;
case UPTIME:
if (result != STATE_OK)
return result;
uptime_raw_hours = strtod (recv_buffer, NULL);
uptime_raw_minutes = (unsigned long) (uptime_raw_hours * 60.0);
if (check_critical_value == TRUE && (uptime_raw_minutes <= critical_value))
result = STATE_CRITICAL;
else if (check_warning_value == TRUE && (uptime_raw_minutes <= warning_value))
result = STATE_WARNING;
uptime_days = uptime_raw_minutes / 1440;
uptime_raw_minutes %= 1440;
uptime_hours = uptime_raw_minutes / 60;
uptime_raw_minutes %= 60;
uptime_minutes = uptime_raw_minutes;
die (result,
_("Uptime %s - Up %d days %d hours %d minutes"),
state_text(result),
uptime_days,
uptime_hours,
uptime_minutes);
break;
default:
die (STATE_UNKNOWN, _("Nothing to check!\n"));
break;
}
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"port", required_argument, 0, 'p'},
{"timeout", required_argument, 0, 't'},
{"critical", required_argument, 0, 'c'},
{"warning", required_argument, 0, 'w'},
{"variable", required_argument, 0, 'v'},
{"hostname", required_argument, 0, 'H'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
/* no options were supplied */
if (argc < 2)
return ERROR;
/* backwards compatibility */
if (!is_option (argv[1])) {
server_address = argv[1];
argv[1] = argv[0];
argv = &argv[1];
argc--;
}
for (c = 1; c < argc; c++) {
if (strcmp ("-to", argv[c]) == 0)
strcpy (argv[c], "-t");
else if (strcmp ("-wv", argv[c]) == 0)
strcpy (argv[c], "-w");
else if (strcmp ("-cv", argv[c]) == 0)
strcpy (argv[c], "-c");
}
while (1) {
c = getopt_long (argc, argv, "+hVH:t:c:w:p:v:", longopts,
&option);
if (c == -1 || c == EOF || c == 1)
break;
switch (c) {
case '?': /* print short usage statement if args not parsable */
usage2 (_("Unknown argument"), optarg);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'H': /* hostname */
server_address = optarg;
break;
case 'p': /* port */
if (is_intnonneg (optarg))
server_port = atoi (optarg);
else
die (STATE_UNKNOWN,
_("Server port an integer\n"));
break;
case 'v': /* variable */
if (strcmp (optarg, "LOAD") == 0) {
strcpy (send_buffer, "LOAD\r\nQUIT\r\n");
if (strcmp (optarg, "LOAD1") == 0)
vars_to_check = LOAD1;
else if (strcmp (optarg, "LOAD5") == 0)
vars_to_check = LOAD5;
else if (strcmp (optarg, "LOAD15") == 0)
vars_to_check = LOAD15;
}
else if (strcmp (optarg, "UPTIME") == 0) {
vars_to_check = UPTIME;
strcpy (send_buffer, "UPTIME\r\n");
}
else if (strstr (optarg, "PROC") == optarg) {
vars_to_check = PROCS;
process_name = strscpy (process_name, optarg + 4);
sprintf (send_buffer, "PROCESS %s\r\n", process_name);
}
else if (strstr (optarg, "NET") == optarg) {
vars_to_check = NETSTAT;
netstat_port = atoi (optarg + 3);
sprintf (send_buffer, "NETSTAT %d\r\n", netstat_port);
}
else if (strstr (optarg, "DPU") == optarg) {
vars_to_check = DPU;
strcpy (send_buffer, "DISKSPACE\r\n");
disk_name = strscpy (disk_name, optarg + 3);
}
else
return ERROR;
break;
case 'w': /* warning threshold */
warning_value = strtoul (optarg, NULL, 10);
check_warning_value = TRUE;
break;
case 'c': /* critical threshold */
critical_value = strtoul (optarg, NULL, 10);
check_critical_value = TRUE;
break;
case 't': /* timeout */
socket_timeout = atoi (optarg);
if (socket_timeout <= 0)
return ERROR;
}
}
return OK;
}
void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", PORT);
print_revision (progname, revision);
printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
printf (COPYRIGHT, copyright, email);
printf (_("\
This plugin attempts to contact the Over-CR collector daemon running on the\n\
remote UNIX server in order to gather the requested system information.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_(UT_HOST_PORT), 'p', myport);
printf (_("\
-v, --variable=STRING\n\
Variable to check. Valid variables include:\n\
LOAD1 = 1 minute average CPU load\n\
LOAD5 = 5 minute average CPU load\n\
LOAD15 = 15 minute average CPU load\n\
DPU<filesys> = percent used disk space on filesystem <filesys>\n\
PROC<process> = number of running processes with name <process>\n\
NET<port> = number of active connections on TCP port <port>\n\
UPTIME = system uptime in seconds\n"));
printf (_("\
-w, --warning=INTEGER\n\
Threshold which will result in a warning status\n\
-c, --critical=INTEGER\n\
Threshold which will result in a critical status\n"));
printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
printf (_("\
Notes:\n\
- For the available options, the critical threshold value should always be\n\
higher than the warning threshold value, EXCEPT with the uptime variable\n\n"));
printf (_("\
- This plugin requres that Eric Molitors' Over-CR collector daemon be\n\
running on the remote server. Over-CR can be downloaded from\n\
http://www.molitor.org/overcr (This plugin was tested with version\n\
0.99.53 of the Over-CR collector)\n\n"));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s -H host [-p port] [-v variable] [-w warning] [-c critical]\n\
[-t timeout]\n", progname);
}

445
plugins/check_pgsql.c Normal file
View file

@ -0,0 +1,445 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_pgsql.c,v 1.31 2004/12/25 23:17:44 opensides Exp $
*****************************************************************************/
const char *progname = "check_pgsql";
const char *revision = "$Revision: 1.31 $";
const char *copyright = "1999-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "utils.h"
#include "netutils.h"
#include <libpq-fe.h>
#define DEFAULT_DB "template1"
#define DEFAULT_HOST "127.0.0.1"
enum {
DEFAULT_PORT = 5432,
DEFAULT_WARN = 2,
DEFAULT_CRIT = 8
};
int process_arguments (int, char **);
int validate_arguments (void);
void print_usage (void);
void print_help (void);
int is_pg_dbname (char *);
int is_pg_logname (char *);
char *pghost = NULL; /* host name of the backend server */
char *pgport = NULL; /* port of the backend server */
int default_port = DEFAULT_PORT;
char *pgoptions = NULL;
char *pgtty = NULL;
char dbName[NAMEDATALEN] = DEFAULT_DB;
char *pguser = NULL;
char *pgpasswd = NULL;
double twarn = (double)DEFAULT_WARN;
double tcrit = (double)DEFAULT_CRIT;
PGconn *conn;
/*PGresult *res;*/
/******************************************************************************
The (psuedo?)literate programming XML is contained within \@\@\- <XML> \-\@\@
tags in the comments. With in the tags, the XML is assembled sequentially.
You can define entities in tags. You also have all the #defines available as
entities.
Please note that all tags must be lowercase to use the DocBook XML DTD.
@@-<article>
<sect1>
<title>Quick Reference</title>
<!-- The refentry forms a manpage -->
<refentry>
<refmeta>
<manvolnum>5<manvolnum>
</refmeta>
<refnamdiv>
<refname>&progname;</refname>
<refpurpose>&SUMMARY;</refpurpose>
</refnamdiv>
</refentry>
</sect1>
<sect1>
<title>FAQ</title>
</sect1>
<sect1>
<title>Theory, Installation, and Operation</title>
<sect2>
<title>General Description</title>
<para>
&DESCRIPTION;
</para>
</sect2>
<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>
<sect2>
<title>Functions</title>
-@@
******************************************************************************/
int
main (int argc, char **argv)
{
int elapsed_time;
int 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
* defaults by looking up environment variables or, failing that,
* using hardwired constants */
pgoptions = NULL; /* special options to start up the backend server */
pgtty = NULL; /* debugging tty for the backend server */
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
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);
/* 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);
/* check to see that the backend connection was successfully made */
if (PQstatus (conn) == CONNECTION_BAD) {
printf (_("CRITICAL - no connection to '%s' (%s).\n"),
dbName, PQerrorMessage (conn));
PQfinish (conn);
return STATE_CRITICAL;
}
else if (elapsed_time > tcrit) {
status = STATE_CRITICAL;
}
else if (elapsed_time > twarn) {
status = STATE_WARNING;
}
else {
status = STATE_OK;
}
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;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{"timeout", required_argument, 0, 't'},
{"critical", required_argument, 0, 'c'},
{"warning", required_argument, 0, 'w'},
{"hostname", required_argument, 0, 'H'},
{"logname", required_argument, 0, 'l'},
{"password", required_argument, 0, 'p'},
{"authorization", required_argument, 0, 'a'},
{"port", required_argument, 0, 'P'},
{"database", required_argument, 0, 'd'},
{0, 0, 0, 0}
};
while (1) {
c = getopt_long (argc, argv, "hVt:c:w:H:P:d:l:p:a:",
longopts, &option);
if (c == EOF)
break;
switch (c) {
case '?': /* usage */
usage2 (_("Unknown argument"), optarg);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 't': /* timeout period */
if (!is_integer (optarg))
usage2 (_("Timeout interval must be a positive integer"), optarg);
else
timeout_interval = atoi (optarg);
break;
case 'c': /* critical time threshold */
if (!is_nonnegative (optarg))
usage2 (_("Critical threshold must be a positive integer"), optarg);
else
tcrit = strtod (optarg, NULL);
break;
case 'w': /* warning time threshold */
if (!is_nonnegative (optarg))
usage2 (_("Warning threshold must be a positive integer"), optarg);
else
twarn = strtod (optarg, NULL);
break;
case 'H': /* host */
if (!is_host (optarg))
usage2 (_("Invalid hostname/address"), optarg);
else
pghost = optarg;
break;
case 'P': /* port */
if (!is_integer (optarg))
usage2 (_("Port must be a positive integer"), optarg);
else
pgport = optarg;
break;
case 'd': /* database name */
if (!is_pg_dbname (optarg)) /* checks length and valid chars */
usage2 (_("Database name is not valid"), optarg);
else /* we know length, and know optarg is terminated, so us strcpy */
strcpy (dbName, optarg);
break;
case 'l': /* login name */
if (!is_pg_logname (optarg))
usage2 (_("User name is not valid"), optarg);
else
pguser = optarg;
break;
case 'p': /* authentication password */
case 'a':
pgpasswd = optarg;
break;
}
}
return validate_arguments ();
}
/******************************************************************************
@@-
<sect3>
<title>validate_arguments</title>
<para>&PROTO_validate_arguments;</para>
<para>Given a database name, this function returns TRUE if the string
is a valid PostgreSQL database name, and returns false if it is
not.</para>
<para>Valid PostgreSQL database names are less than &NAMEDATALEN;
characters long and consist of letters, numbers, and underscores. The
first character cannot be a number, however.</para>
</sect3>
-@@
******************************************************************************/
int
validate_arguments ()
{
return OK;
}
/******************************************************************************
@@-
<sect3>
<title>is_pg_dbname</title>
<para>&PROTO_is_pg_dbname;</para>
<para>Given a database name, this function returns TRUE if the string
is a valid PostgreSQL database name, and returns false if it is
not.</para>
<para>Valid PostgreSQL database names are less than &NAMEDATALEN;
characters long and consist of letters, numbers, and underscores. The
first character cannot be a number, however.</para>
</sect3>
-@@
******************************************************************************/
int
is_pg_dbname (char *dbname)
{
char txt[NAMEDATALEN];
char tmp[NAMEDATALEN];
if (strlen (dbname) > NAMEDATALEN - 1)
return (FALSE);
strncpy (txt, dbname, NAMEDATALEN - 1);
txt[NAMEDATALEN - 1] = 0;
if (sscanf (txt, "%[_a-zA-Z]%[^_a-zA-Z0-9]", tmp, tmp) == 1)
return (TRUE);
if (sscanf (txt, "%[_a-zA-Z]%[_a-zA-Z0-9]%[^_a-zA-Z0-9]", tmp, tmp, tmp) ==
2) return (TRUE);
return (FALSE);
}
/**
the tango program should eventually create an entity here based on the
function prototype
@@-
<sect3>
<title>is_pg_logname</title>
<para>&PROTO_is_pg_logname;</para>
<para>Given a username, this function returns TRUE if the string is a
valid PostgreSQL username, and returns false if it is not. Valid PostgreSQL
usernames are less than &NAMEDATALEN; characters long and consist of
letters, numbers, dashes, and underscores, plus possibly some other
characters.</para>
<para>Currently this function only checks string length. Additional checks
should be added.</para>
</sect3>
-@@
******************************************************************************/
int
is_pg_logname (char *username)
{
if (strlen (username) > NAMEDATALEN - 1)
return (FALSE);
return (TRUE);
}
/******************************************************************************
@@-
</sect2>
</sect1>
</article>
-@@
******************************************************************************/
void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", DEFAULT_PORT);
print_revision (progname, revision);
printf (COPYRIGHT, copyright, email);
printf (_("Test whether a PostgreSQL Database is accepting connections.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_(UT_HOST_PORT), 'P', myport);
printf (_(UT_IPv46));
printf (_("\
-d, --database=STRING\n\
Database to check (default: %s)\n\
-l, --logname = STRING\n\
Login name of user\n\
-p, --password = STRING\n\
Password (BIG SECURITY ISSUE)\n"), DEFAULT_DB);
printf (_(UT_WARN_CRIT));
printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
printf (_(UT_VERBOSE));
printf (_("\nAll parameters are optional.\n\
\n\
This plugin tests a PostgreSQL DBMS to determine whether it is active and\n\
accepting queries. In its current operation, it simply connects to the\n\
specified database, and then disconnects. If no database is specified, it\n\
connects to the template1 database, which is present in every functioning \n\
PostgreSQL DBMS.\n"));
printf (_("\n\
The plugin will connect to a local postmaster if no host is specified. To\n\
connect to a remote host, be sure that the remote postmaster accepts TCP/IP\n\
connections (start the postmaster with the -i option).\n"));
printf (_("\n\
Typically, the nagios user (unless the --logname option is used) should be\n\
able to connect to the database without a password. The plugin can also send\n\
a password, but no effort is made to obsure or encrypt the password.\n"));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s [-H <host>] [-P <port>] [-c <critical time>] [-w <warning time>]\n\
[-t <timeout>] [-d <database>] [-l <logname>] [-p <password>]\n", progname);
}

550
plugins/check_ping.c Normal file
View file

@ -0,0 +1,550 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_ping.c,v 1.49 2005/09/14 14:40:20 tonvoon Exp $
******************************************************************************/
const char *progname = "check_ping";
const char *revision = "$Revision: 1.49 $";
const char *copyright = "2000-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "netutils.h"
#include "popen.h"
#include "utils.h"
#define WARN_DUPLICATES "DUPLICATES FOUND! "
#define UNKNOWN_TRIP_TIME -1.0 /* -1 seconds */
enum {
UNKNOWN_PACKET_LOSS = 200, /* 200% */
DEFAULT_MAX_PACKETS = 5 /* default no. of ICMP ECHO packets */
};
int process_arguments (int, char **);
int get_threshold (char *, float *, int *);
int validate_arguments (void);
int run_ping (const char *cmd, const char *addr);
int error_scan (char buf[MAX_INPUT_BUFFER], const char *addr);
void print_usage (void);
void print_help (void);
int display_html = FALSE;
int wpl = UNKNOWN_PACKET_LOSS;
int cpl = UNKNOWN_PACKET_LOSS;
float wrta = UNKNOWN_TRIP_TIME;
float crta = UNKNOWN_TRIP_TIME;
char **addresses = NULL;
int n_addresses = 0;
int max_addr = 1;
int max_packets = -1;
int verbose = 0;
float rta = UNKNOWN_TRIP_TIME;
int pl = UNKNOWN_PACKET_LOSS;
char *warn_text;
int
main (int argc, char **argv)
{
char *cmd = NULL;
char *rawcmd = NULL;
int result = STATE_UNKNOWN;
int this_result = STATE_UNKNOWN;
int i;
setlocale (LC_ALL, "");
setlocale (LC_NUMERIC, "C");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
addresses = malloc (sizeof(char*) * max_addr);
addresses[0] = NULL;
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* Set signal handling and alarm */
if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
usage4 (_("Cannot catch SIGALRM"));
}
/* handle timeouts gracefully */
alarm (timeout_interval);
for (i = 0 ; i < n_addresses ; i++) {
#ifdef PING6_COMMAND
if (is_inet6_addr(addresses[i]) && address_family != AF_INET)
rawcmd = strdup(PING6_COMMAND);
else
rawcmd = strdup(PING_COMMAND);
#else
rawcmd = strdup(PING_COMMAND);
#endif
/* 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]);
# else
asprintf (&cmd, rawcmd, max_packets, addresses[i]);
# endif
#else
asprintf (&cmd, rawcmd, addresses[i], max_packets);
#endif
if (verbose >= 2)
printf ("CMD: %s\n", cmd);
/* run the command */
this_result = run_ping (cmd, addresses[i]);
if (pl == UNKNOWN_PACKET_LOSS || rta < 0.0) {
printf ("%s\n", cmd);
die (STATE_UNKNOWN,
_("CRITICAL - Could not interpret output from ping command\n"));
}
if (pl >= cpl || rta >= crta || rta < 0)
this_result = STATE_CRITICAL;
else if (pl >= wpl || rta >= wrta)
this_result = STATE_WARNING;
else if (pl >= 0 && rta >= 0)
this_result = max_state (STATE_OK, this_result);
if (n_addresses > 1 && this_result != STATE_UNKNOWN)
die (STATE_OK, "%s is alive\n", addresses[i]);
if (display_html == TRUE)
printf ("<A HREF='%s/traceroute.cgi?%s'>", CGIURL, addresses[i]);
if (pl == 100)
printf (_("PING %s - %sPacket loss = %d%%"), state_text (this_result), warn_text,
pl);
else
printf (_("PING %s - %sPacket loss = %d%%, RTA = %2.2f ms"),
state_text (this_result), warn_text, pl, rta);
if (display_html == TRUE)
printf ("</A>");
printf ("\n");
if (verbose >= 2)
printf ("%f:%d%% %f:%d%%\n", wrta, wpl, crta, cpl);
result = max_state (result, this_result);
free (rawcmd);
free (cmd);
}
return result;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c = 1;
char *ptr;
int option = 0;
static struct option longopts[] = {
STD_LONG_OPTS,
{"packets", required_argument, 0, 'p'},
{"nohtml", no_argument, 0, 'n'},
{"link", no_argument, 0, 'L'},
{"use-ipv4", no_argument, 0, '4'},
{"use-ipv6", no_argument, 0, '6'},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
for (c = 1; c < argc; c++) {
if (strcmp ("-to", argv[c]) == 0)
strcpy (argv[c], "-t");
if (strcmp ("-nohtml", argv[c]) == 0)
strcpy (argv[c], "-n");
}
while (1) {
c = getopt_long (argc, argv, "VvhnL46t:c:w:H:p:", longopts, &option);
if (c == -1 || c == EOF)
break;
switch (c) {
case '?': /* usage */
usage2 (_("Unknown argument"), optarg);
case 'h': /* help */
print_help ();
exit (STATE_OK);
break;
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
break;
case 't': /* timeout period */
timeout_interval = atoi (optarg);
break;
case 'v': /* verbose mode */
verbose++;
break;
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 'H': /* hostname */
ptr=optarg;
while (1) {
n_addresses++;
if (n_addresses > max_addr) {
max_addr *= 2;
addresses = realloc (addresses, sizeof(char*) * max_addr);
if (addresses == NULL)
die (STATE_UNKNOWN, _("Could not realloc() addresses\n"));
}
addresses[n_addresses-1] = ptr;
if ((ptr = index (ptr, ','))) {
strcpy (ptr, "");
ptr += sizeof(char);
} else {
break;
}
}
break;
case 'p': /* number of packets to send */
if (is_intnonneg (optarg))
max_packets = atoi (optarg);
else
usage2 (_("<max_packets> (%s) must be a non-negative number\n"), optarg);
break;
case 'n': /* no HTML */
display_html = FALSE;
break;
case 'L': /* show HTML */
display_html = TRUE;
break;
case 'c':
get_threshold (optarg, &crta, &cpl);
break;
case 'w':
get_threshold (optarg, &wrta, &wpl);
break;
}
}
c = optind;
if (c == argc)
return validate_arguments ();
if (addresses[0] == NULL) {
if (is_host (argv[c]) == FALSE) {
usage2 (_("Invalid hostname/address"), argv[c]);
} else {
addresses[0] = argv[c++];
n_addresses++;
if (c == argc)
return validate_arguments ();
}
}
if (wpl == UNKNOWN_PACKET_LOSS) {
if (is_intpercent (argv[c]) == FALSE) {
printf (_("<wpl> (%s) must be an integer percentage\n"), argv[c]);
return ERROR;
} else {
wpl = atoi (argv[c++]);
if (c == argc)
return validate_arguments ();
}
}
if (cpl == UNKNOWN_PACKET_LOSS) {
if (is_intpercent (argv[c]) == FALSE) {
printf (_("<cpl> (%s) must be an integer percentage\n"), argv[c]);
return ERROR;
} else {
cpl = atoi (argv[c++]);
if (c == argc)
return validate_arguments ();
}
}
if (wrta < 0.0) {
if (is_negative (argv[c])) {
printf (_("<wrta> (%s) must be a non-negative number\n"), argv[c]);
return ERROR;
} else {
wrta = atof (argv[c++]);
if (c == argc)
return validate_arguments ();
}
}
if (crta < 0.0) {
if (is_negative (argv[c])) {
printf (_("<crta> (%s) must be a non-negative number\n"), argv[c]);
return ERROR;
} else {
crta = atof (argv[c++]);
if (c == argc)
return validate_arguments ();
}
}
if (max_packets == -1) {
if (is_intnonneg (argv[c])) {
max_packets = atoi (argv[c++]);
} else {
printf (_("<max_packets> (%s) must be a non-negative number\n"), argv[c]);
return ERROR;
}
}
return validate_arguments ();
}
int
get_threshold (char *arg, float *trta, int *tpl)
{
if (is_intnonneg (arg) && sscanf (arg, "%f", trta) == 1)
return OK;
else if (strpbrk (arg, ",:") && strstr (arg, "%") && sscanf (arg, "%f%*[:,]%d%%", trta, tpl) == 2)
return OK;
else if (strstr (arg, "%") && sscanf (arg, "%d%%", tpl) == 1)
return OK;
usage2 (_("%s: Warning threshold must be integer or percentage!\n\n"), arg);
return STATE_UNKNOWN;
}
int
validate_arguments ()
{
float max_seconds;
int i;
if (wrta < 0.0) {
printf (_("<wrta> was not set\n"));
return ERROR;
}
else if (crta < 0.0) {
printf (_("<crta> was not set\n"));
return ERROR;
}
else if (wpl == UNKNOWN_PACKET_LOSS) {
printf (_("<wpl> was not set\n"));
return ERROR;
}
else if (cpl == UNKNOWN_PACKET_LOSS) {
printf (_("<cpl> was not set\n"));
return ERROR;
}
else if (wrta > crta) {
printf (_("<wrta> (%f) cannot be larger than <crta> (%f)\n"), wrta, crta);
return ERROR;
}
else if (wpl > cpl) {
printf (_("<wpl> (%d) cannot be larger than <cpl> (%d)\n"), wpl, cpl);
return ERROR;
}
if (max_packets == -1)
max_packets = DEFAULT_MAX_PACKETS;
max_seconds = crta / 1000.0 * max_packets + max_packets;
if (max_seconds > timeout_interval)
timeout_interval = (int)max_seconds;
for (i=0; i<n_addresses; i++) {
if (is_host(addresses[i]) == FALSE)
usage2 (_("Invalid hostname/address"), addresses[i]);
}
if (n_addresses == 0) {
usage (_("You must specify a server address or host name"));
}
return OK;
}
int
run_ping (const char *cmd, const char *addr)
{
char buf[MAX_INPUT_BUFFER];
int result = STATE_UNKNOWN;
if ((child_process = spopen (cmd)) == NULL)
die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd);
child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
if (child_stderr == NULL)
printf (_("Cannot open stderr for %s\n"), cmd);
while (fgets (buf, MAX_INPUT_BUFFER - 1, child_process)) {
if (verbose >= 3)
printf("Output: %s", buf);
result = max_state (result, error_scan (buf, addr));
/* get the percent loss statistics */
if(sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d errors, %d%% packet loss",&pl)==1 ||
sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d duplicates, %d%% packet loss", &pl) == 1 ||
sscanf(buf,"%*d packets transmitted, %*d received, +%*d duplicates, %d%% packet loss", &pl) == 1 ||
sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% packet loss",&pl)==1 ||
sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% loss, time",&pl)==1 ||
sscanf(buf,"%*d packets transmitted, %*d received, %d%% loss, time", &pl)==1 ||
sscanf(buf,"%*d packets transmitted, %*d received, %d%% packet loss, time", &pl)==1 ||
sscanf(buf,"%*d packets transmitted, %*d received, +%*d errors, %d%% packet loss", &pl) == 1 ||
sscanf(buf,"%*d packets transmitted %*d received, +%*d errors, %d%% packet loss", &pl) == 1
)
continue;
/* get the round trip average */
else
if(sscanf(buf,"round-trip min/avg/max = %*f/%f/%*f",&rta)==1 ||
sscanf(buf,"round-trip min/avg/max/mdev = %*f/%f/%*f/%*f",&rta)==1 ||
sscanf(buf,"round-trip min/avg/max/sdev = %*f/%f/%*f/%*f",&rta)==1 ||
sscanf(buf,"round-trip min/avg/max/stddev = %*f/%f/%*f/%*f",&rta)==1 ||
sscanf(buf,"round-trip min/avg/max/std-dev = %*f/%f/%*f/%*f",&rta)==1 ||
sscanf(buf,"round-trip (ms) min/avg/max = %*f/%f/%*f",&rta)==1 ||
sscanf(buf,"round-trip (ms) min/avg/max/stddev = %*f/%f/%*f/%*f",&rta)==1 ||
sscanf(buf,"rtt min/avg/max/mdev = %*f/%f/%*f/%*f ms",&rta)==1)
continue;
}
/* this is needed because there is no rta if all packets are lost */
if (pl == 100)
rta = crta;
/* check stderr, setting at least WARNING if there is output here */
while (fgets (buf, MAX_INPUT_BUFFER - 1, child_stderr))
if (! strstr(buf,"WARNING - no SO_TIMESTAMP support, falling back to SIOCGSTAMP"))
result = max_state (STATE_WARNING, error_scan (buf, addr));
(void) fclose (child_stderr);
/* close the pipe - WARNING if status is set */
if (spclose (child_process))
result = max_state (result, STATE_WARNING);
if (warn_text == NULL)
warn_text = strdup("");
return result;
}
int
error_scan (char buf[MAX_INPUT_BUFFER], const char *addr)
{
if (strstr (buf, "Network is unreachable"))
die (STATE_CRITICAL, _("CRITICAL - Network unreachable (%s)"), addr);
else if (strstr (buf, "Destination Host Unreachable"))
die (STATE_CRITICAL, _("CRITICAL - Host Unreachable (%s)"), addr);
else if (strstr (buf, "unknown host" ))
die (STATE_CRITICAL, _("CRITICAL - Host not found (%s)"), addr);
else if (strstr (buf, "Time to live exceeded"))
die (STATE_CRITICAL, _("CRITICAL - Time to live exceeded (%s)"), addr);
if (strstr (buf, "(DUP!)") || strstr (buf, "DUPLICATES FOUND")) {
if (warn_text == NULL)
warn_text = strdup (_(WARN_DUPLICATES));
else if (! strstr (warn_text, _(WARN_DUPLICATES)) &&
asprintf (&warn_text, "%s %s", warn_text, _(WARN_DUPLICATES)) == -1)
die (STATE_UNKNOWN, _("Unable to realloc warn_text"));
return (STATE_WARNING);
}
return (STATE_OK);
}
void
print_help (void)
{
print_revision (progname, revision);
printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>");
printf (COPYRIGHT, copyright, email);
printf (_("Use ping to check connection statistics for a remote host.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_(UT_IPv46));
printf (_("\
-H, --hostname=HOST\n\
host to ping\n\
-w, --warning=THRESHOLD\n\
warning threshold pair\n\
-c, --critical=THRESHOLD\n\
critical threshold pair\n\
-p, --packets=INTEGER\n\
number of ICMP ECHO packets to send (Default: %d)\n\
-L, --link\n\
show HTML in the plugin output (obsoleted by urlize)\n"),
DEFAULT_MAX_PACKETS);
printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
printf (_("\
THRESHOLD is <rta>,<pl>%% where <rta> is the round trip average travel\n\
time (ms) which triggers a WARNING or CRITICAL state, and <pl> is the\n\
percentage of packet loss to trigger an alarm state.\n\n"));
printf (_("\
This plugin uses the ping command to probe the specified host for packet loss\n\
(percentage) and round trip average (milliseconds). It can produce HTML output\n\
linking to a traceroute CGI contributed by Ian Cass. The CGI can be found in\n\
the contrib area of the downloads section at http://www.nagios.org\n\n"));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("Usage: %s -H <host_address> -w <wrta>,<wpl>%% -c <crta>,<cpl>%%\n\
[-p packets] [-t timeout] [-L] [-4|-6]\n", progname);
}

751
plugins/check_procs.c Normal file
View file

@ -0,0 +1,751 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_procs.c,v 1.46 2005/09/15 08:27:58 tonvoon Exp $
******************************************************************************/
const char *progname = "check_procs";
const char *revision = "$Revision: 1.46 $";
const char *copyright = "2000-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "popen.h"
#include "utils.h"
#include <pwd.h>
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;
int options = 0; /* bitmask of filter criteria to test against */
#define ALL 1
#define STAT 2
#define PPID 4
#define USER 8
#define PROG 16
#define ARGS 32
#define VSZ 64
#define RSS 128
#define PCPU 256
#define ELAPSED 512
/* Different metrics */
char *metric_name;
enum metric {
METRIC_PROCS,
METRIC_VSZ,
METRIC_RSS,
METRIC_CPU,
METRIC_ELAPSED
};
enum metric metric = METRIC_PROCS;
int verbose = 0;
int uid;
int ppid;
int vsz;
int rss;
float pcpu;
char *statopts;
char *prog;
char *args;
char *fmt;
char *fails;
char tmp[MAX_INPUT_BUFFER];
int
main (int argc, char **argv)
{
char *input_buffer;
char *input_line;
char *procprog;
pid_t mypid = 0;
int procuid = 0;
int procpid = 0;
int procppid = 0;
int procvsz = 0;
int procrss = 0;
int procseconds = 0;
float procpcpu = 0;
char procstat[8];
char procetime[MAX_INPUT_BUFFER] = { '\0' };
char *procargs;
#ifdef HAVE_BASENAME
char *temp_string;
#endif
const char *zombie = "Z";
int resultsum = 0; /* bitmask of the filter criteria met by a process */
int found = 0; /* counter for number of lines returned in `ps` output */
int procs = 0; /* counter for number of processes meeting filter criteria */
int pos; /* number of spaces before 'args' in `ps` output */
int cols; /* number of columns in ps output */
int expected_cols = PS_COLS - 1;
int warn = 0; /* number of processes in warn state */
int crit = 0; /* number of processes in crit state */
int i = 0;
int result = STATE_UNKNOWN;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
input_buffer = malloc (MAX_INPUT_BUFFER);
procprog = malloc (MAX_INPUT_BUFFER);
asprintf (&metric_name, "PROCS");
metric = METRIC_PROCS;
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* get our pid */
mypid = getpid();
/* Set signal handling and alarm timeout */
if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
usage4 (_("Cannot catch SIGALRM"));
}
alarm (timeout_interval);
if (verbose >= 2)
printf (_("CMD: %s\n"), PS_COMMAND);
child_process = spopen (PS_COMMAND);
if (child_process == NULL) {
printf (_("Could not open pipe: %s\n"), PS_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"), PS_COMMAND);
/* flush first line */
fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process);
while ( input_buffer[strlen(input_buffer)-1] != '\n' )
fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process);
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
asprintf (&input_line, "%s", input_buffer);
while ( input_buffer[strlen(input_buffer)-1] != '\n' ) {
fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process);
asprintf (&input_line, "%s%s", input_line, input_buffer);
}
if (verbose >= 3)
printf ("%s", input_line);
strcpy (procprog, "");
asprintf (&procargs, "%s", "");
cols = sscanf (input_line, PS_FORMAT, PS_VARLIST);
/* Zombie processes do not give a procprog command */
if ( cols == (expected_cols - 1) && strstr(procstat, zombie) ) {
cols = expected_cols;
}
if ( cols >= expected_cols ) {
resultsum = 0;
asprintf (&procargs, "%s", input_line + pos);
strip (procargs);
/* Some ps return full pathname for command. This removes path */
#ifdef HAVE_BASENAME
temp_string = strdup(procprog);
procprog = basename(temp_string);
#endif /* HAVE_BASENAME */
/* we need to convert the elapsed time to seconds */
procseconds = convert_to_seconds(procetime);
if (verbose >= 3)
printf ("%d %d %d %d %d %d %.2f %s %s %s %s\n",
procs, procuid, procvsz, procrss,
procpid, procppid, procpcpu, procstat,
procetime, procprog, procargs);
/* Ignore self */
if (mypid == procpid) continue;
if ((options & STAT) && (strstr (statopts, procstat)))
resultsum |= STAT;
if ((options & ARGS) && procargs && (strstr (procargs, args) != NULL))
resultsum |= ARGS;
if ((options & PROG) && procprog && (strcmp (prog, procprog) == 0))
resultsum |= PROG;
if ((options & PPID) && (procppid == ppid))
resultsum |= PPID;
if ((options & USER) && (procuid == uid))
resultsum |= USER;
if ((options & VSZ) && (procvsz >= vsz))
resultsum |= VSZ;
if ((options & RSS) && (procrss >= rss))
resultsum |= RSS;
if ((options & PCPU) && (procpcpu >= pcpu))
resultsum |= PCPU;
found++;
/* Next line if filters not matched */
if (!(options == resultsum || options == ALL))
continue;
procs++;
if (metric == METRIC_VSZ)
i = check_thresholds (procvsz);
else if (metric == METRIC_RSS)
i = check_thresholds (procrss);
/* TODO? float thresholds for --metric=CPU */
else if (metric == METRIC_CPU)
i = check_thresholds ((int)procpcpu);
else if (metric == METRIC_ELAPSED)
i = check_thresholds (procseconds);
if (metric != METRIC_PROCS) {
if (i == STATE_WARNING) {
warn++;
asprintf (&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);
result = max_state (result, i);
}
}
}
/* This should not happen */
else if (verbose) {
printf(_("Not parseable: %s"), input_buffer);
}
}
/* If we get anything on STDERR, at least set warning */
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
if (verbose)
printf ("STDERR: %s", input_buffer);
result = max_state (result, STATE_WARNING);
printf (_("System call sent warnings to stderr\n"));
}
(void) fclose (child_stderr);
/* close the pipe */
if (spclose (child_process)) {
printf (_("System call returned nonzero status\n"));
result = max_state (result, STATE_WARNING);
}
if (found == 0) { /* no process lines parsed so return STATE_UNKNOWN */
printf (_("Unable to read output\n"));
return result;
}
if ( result == STATE_UNKNOWN )
result = STATE_OK;
/* Needed if procs found, but none match filter */
if ( metric == METRIC_PROCS ) {
result = max_state (result, check_thresholds (procs) );
}
if ( result == STATE_OK ) {
printf ("%s %s: ", metric_name, _("OK"));
} else if (result == STATE_WARNING) {
printf ("%s %s: ", metric_name, _("WARNING"));
if ( metric != METRIC_PROCS ) {
printf (_("%d warn out of "), warn);
}
} else if (result == STATE_CRITICAL) {
printf ("%s %s: ", metric_name, _("CRITICAL"));
if (metric != METRIC_PROCS) {
printf (_("%d crit, %d warn out of "), crit, warn);
}
}
printf (ngettext ("%d process", "%d processes", (unsigned long) procs), procs);
if (strcmp(fmt,"") != 0) {
printf (_(" with %s"), fmt);
}
if ( verbose >= 1 && strcmp(fails,"") )
printf (" [%s]", fails);
printf ("\n");
return result;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c = 1;
char *user;
struct passwd *pw;
int option = 0;
static struct option longopts[] = {
{"warning", required_argument, 0, 'w'},
{"critical", required_argument, 0, 'c'},
{"metric", required_argument, 0, 'm'},
{"timeout", required_argument, 0, 't'},
{"status", required_argument, 0, 's'},
{"ppid", required_argument, 0, 'p'},
{"command", required_argument, 0, 'C'},
{"vsz", required_argument, 0, 'z'},
{"rss", required_argument, 0, 'r'},
{"pcpu", required_argument, 0, 'P'},
{"elapsed", required_argument, 0, 'e'},
{"argument-array", required_argument, 0, 'a'},
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{"verbose", no_argument, 0, 'v'},
{0, 0, 0, 0}
};
for (c = 1; c < argc; c++)
if (strcmp ("-to", argv[c]) == 0)
strcpy (argv[c], "-t");
while (1) {
c = getopt_long (argc, argv, "Vvht:c:w:p:s:u:C:a:z:r:m:P:",
longopts, &option);
if (c == -1 || c == EOF)
break;
switch (c) {
case '?': /* help */
usage2 (_("Unknown argument"), optarg);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 't': /* timeout period */
if (!is_integer (optarg))
usage2 (_("Timeout interval must be a positive integer"), optarg);
else
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!"));
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!"));
break;
case 'p': /* process id */
if (sscanf (optarg, "%d%[^0-9]", &ppid, tmp) == 1) {
asprintf (&fmt, "%s%sPPID = %d", (fmt ? fmt : "") , (options ? ", " : ""), ppid);
options |= PPID;
break;
}
usage4 (_("Parent Process ID must be an integer!"));
case 's': /* status */
if (statopts)
break;
else
statopts = optarg;
asprintf (&fmt, _("%s%sSTATE = %s"), (fmt ? fmt : ""), (options ? ", " : ""), statopts);
options |= STAT;
break;
case 'u': /* user or user id */
if (is_integer (optarg)) {
uid = atoi (optarg);
pw = getpwuid ((uid_t) uid);
/* check to be sure user exists */
if (pw == NULL)
usage2 (_("UID %s was not found"), optarg);
}
else {
pw = getpwnam (optarg);
/* check to be sure user exists */
if (pw == NULL)
usage2 (_("User name %s was not found"), optarg);
/* then get uid */
uid = pw->pw_uid;
}
user = pw->pw_name;
asprintf (&fmt, "%s%sUID = %d (%s)", (fmt ? fmt : ""), (options ? ", " : ""),
uid, user);
options |= USER;
break;
case 'C': /* command */
/* TODO: allow this to be passed in with --metric */
if (prog)
break;
else
prog = optarg;
asprintf (&fmt, _("%s%scommand name '%s'"), (fmt ? fmt : ""), (options ? ", " : ""),
prog);
options |= PROG;
break;
case 'a': /* args (full path name with args) */
/* TODO: allow this to be passed in with --metric */
if (args)
break;
else
args = optarg;
asprintf (&fmt, "%s%sargs '%s'", (fmt ? fmt : ""), (options ? ", " : ""), args);
options |= ARGS;
break;
case 'r': /* RSS */
if (sscanf (optarg, "%d%[^0-9]", &rss, tmp) == 1) {
asprintf (&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);
options |= VSZ;
break;
}
usage4 (_("VSZ must be an integer!"));
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);
options |= PCPU;
break;
}
usage4 (_("PCPU must be a float!"));
case 'm':
asprintf (&metric_name, "%s", optarg);
if ( strcmp(optarg, "PROCS") == 0) {
metric = METRIC_PROCS;
break;
}
else if ( strcmp(optarg, "VSZ") == 0) {
metric = METRIC_VSZ;
break;
}
else if ( strcmp(optarg, "RSS") == 0 ) {
metric = METRIC_RSS;
break;
}
else if ( strcmp(optarg, "CPU") == 0 ) {
metric = METRIC_CPU;
break;
}
else if ( strcmp(optarg, "ELAPSED") == 0) {
metric = METRIC_ELAPSED;
break;
}
usage4 (_("Metric must be one of PROCS, VSZ, RSS, CPU, ELAPSED!"));
case 'v': /* command */
verbose++;
break;
}
}
c = optind;
if (wmax == -1 && argv[c])
wmax = atoi (argv[c++]);
if (cmax == -1 && argv[c])
cmax = atoi (argv[c++]);
if (statopts == NULL && argv[c]) {
asprintf (&statopts, "%s", argv[c++]);
asprintf (&fmt, _("%s%sSTATE = %s"), (fmt ? fmt : ""), (options ? ", " : ""), statopts);
options |= STAT;
}
return validate_arguments ();
}
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;
if (statopts==NULL)
statopts = strdup("");
if (prog==NULL)
prog = strdup("");
if (args==NULL)
args = strdup("");
if (fmt==NULL)
fmt = strdup("");
if (fails==NULL)
fails = strdup("");
return options;
}
/* 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) {
char *ptr;
int total;
int hyphcnt;
int coloncnt;
int days;
int hours;
int minutes;
int seconds;
hyphcnt = 0;
coloncnt = 0;
days = 0;
hours = 0;
minutes = 0;
seconds = 0;
for (ptr = etime; *ptr != '\0'; ptr++) {
if (*ptr == '-') {
hyphcnt++;
continue;
}
if (*ptr == ':') {
coloncnt++;
continue;
}
}
if (hyphcnt > 0) {
sscanf(etime, "%d-%d:%d:%d",
&days, &hours, &minutes, &seconds);
/* linux 2.6.5/2.6.6 reporting some processes with infinite
* elapsed times for some reason */
if (days == 49710) {
return 0;
}
} else {
if (coloncnt == 2) {
sscanf(etime, "%d:%d:%d",
&hours, &minutes, &seconds);
} else if (coloncnt == 1) {
sscanf(etime, "%d:%d",
&minutes, &seconds);
}
}
total = (days * 86400) +
(hours * 3600) +
(minutes * 60) +
seconds;
if (verbose >= 3 && metric == METRIC_ELAPSED) {
printf("seconds: %d\n", total);
}
return total;
}
void
print_help (void)
{
print_revision (progname, revision);
printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>");
printf (COPYRIGHT, copyright, email);
printf(_("\
Checks all processes and generates WARNING or CRITICAL states if the specified\n\
metric is outside the required threshold ranges. The metric defaults to number\n\
of processes. Search filters can be applied to limit the processes to check.\n\n"));
print_usage ();
printf(_("\n\
Required Arguments:\n\
-w, --warning=RANGE\n\
Generate warning state if metric is outside this range\n\
-c, --critical=RANGE\n\
Generate critical state if metric is outside this range\n"));
printf(_("\n\
Optional Arguments:\n\
-m, --metric=TYPE\n\
Check thresholds against metric. Valid types:\n\
PROCS - number of processes (default)\n\
VSZ - virtual memory size\n\
RSS - resident set memory size\n\
CPU - percentage cpu\n"));
/* only linux etime is support currently */
#if defined( __linux__ )
printf(_("\
ELAPSED - time elapsed in seconds\n"));
#endif /* defined(__linux__) */
printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
printf(_("\
-v, --verbose\n\
Extra information. Up to 3 verbosity levels\n"));
printf(_("\n\
Optional Filters:\n\
-s, --state=STATUSFLAGS\n\
Only scan for processes that have, in the output of `ps`, one or\n\
more of the status flags you specify (for example R, Z, S, RS,\n\
RSZDT, plus others based on the output of your 'ps' command).\n\
-p, --ppid=PPID\n\
Only scan for children of the parent process ID indicated.\n\
-z, --vsz=VSZ\n\
Only scan for processes with vsz higher than indicated.\n\
-r, --rss=RSS\n\
Only scan for processes with rss higher than indicated.\n"));
printf(_("\
-P, --pcpu=PCPU\n\
Only scan for processes with pcpu higher than indicated.\n\
-u, --user=USER\n\
Only scan for processes with user name or ID indicated.\n\
-a, --argument-array=STRING\n\
Only scan for processes with args that contain STRING.\n\
-C, --command=COMMAND\n\
Only scan for exact matches of COMMAND (without path).\n"));
printf(_("\n\
RANGEs are specified 'min:max' or 'min:' or ':max' (or 'max'). If\n\
specified 'max:min', a warning status will be generated if the\n\
count is inside the specified range\n\n"));
printf(_("\
This plugin checks the number of currently running processes and\n\
generates WARNING or CRITICAL states if the process count is outside\n\
the specified threshold ranges. The process count can be filtered by\n\
process owner, parent process PID, current state (e.g., 'Z'), or may\n\
be the total number of running processes\n\n"));
printf(_("\
Examples:\n\
check_procs -w 2:2 -c 2:1024 -C portsentry\n\
Warning if not two processes with command name portsentry. Critical\n\
if < 2 or > 1024 processes\n\n\
check_procs -w 10 -a '/usr/local/bin/perl' -u root\n\
Warning alert if > 10 processes with command arguments containing \n\
'/usr/local/bin/perl' and owned by root\n\n\
check_procs -w 50000 -c 100000 --metric=VSZ\n\
Alert if vsz of any processes over 50K or 100K\n\
check_procs -w 10 -c 20 --metric=CPU\n\
Alert if cpu of any processes over 10%% or 20%%\n\n"));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s -w <range> -c <range> [-m metric] [-s state] [-p ppid]\n\
[-u user] [-r rss] [-z vsz] [-P %%cpu] [-a argument-array]\n\
[-C command] [-t timeout] [-v]\n", progname);
}

338
plugins/check_radius.c Normal file
View file

@ -0,0 +1,338 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_radius.c,v 1.21 2004/12/25 23:17:44 opensides Exp $
******************************************************************************/
const char *progname = "check_radius";
const char *revision = "$Revision: 1.21 $";
const char *copyright = "2000-2003";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "utils.h"
#include "netutils.h"
#include <radiusclient.h>
int process_arguments (int, char **);
void print_help (void);
void print_usage (void);
char *server = NULL;
char *username = NULL;
char *password = NULL;
char *nasid = NULL;
char *expect = NULL;
char *config_file = NULL;
unsigned short port = PW_AUTH_UDP_PORT;
int retries = 1;
int verbose = FALSE;
ENV *env = NULL;
/******************************************************************************
The (psuedo?)literate programming XML is contained within \@\@\- <XML> \-\@\@
tags in the comments. With in the tags, the XML is assembled sequentially.
You can define entities in tags. You also have all the #defines available as
entities.
Please note that all tags must be lowercase to use the DocBook XML DTD.
@@-<article>
<sect1>
<title>Quick Reference</title>
<!-- The refentry forms a manpage -->
<refentry>
<refmeta>
<manvolnum>5<manvolnum>
</refmeta>
<refnamdiv>
<refname>&progname;</refname>
<refpurpose>&SUMMARY;</refpurpose>
</refnamdiv>
</refentry>
</sect1>
<sect1>
<title>FAQ</title>
</sect1>
<sect1>
<title>Theory, Installation, and Operation</title>
<sect2>
<title>General Description</title>
<para>
&DESCRIPTION;
</para>
</sect2>
<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>
</itemizedlist>
</sect2>
<sect2>
<title>Functions</title>
-@@
******************************************************************************/
int
main (int argc, char **argv)
{
UINT4 service;
char msg[BUFFER_LEN];
SEND_DATA data;
int result = STATE_UNKNOWN;
UINT4 client_id;
char *str;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
str = strdup ("dictionary");
if ((config_file && rc_read_config (config_file)) ||
rc_read_dictionary (rc_conf_str (str)))
die (STATE_UNKNOWN, _("Config file error"));
service = PW_AUTHENTICATE_ONLY;
if (!(rc_avpair_add (&data.send_pairs, PW_SERVICE_TYPE, &service, 0) &&
rc_avpair_add (&data.send_pairs, PW_USER_NAME, username, 0) &&
rc_avpair_add (&data.send_pairs, PW_USER_PASSWORD, password, 0) &&
(nasid==NULL || rc_avpair_add (&data.send_pairs, PW_NAS_IDENTIFIER, nasid, 0))))
die (STATE_UNKNOWN, _("Out of Memory?"));
/*
* Fill in NAS-IP-Address
*/
if ((client_id = rc_own_ipaddress ()) == 0)
return (ERROR_RC);
if (rc_avpair_add (&(data.send_pairs), PW_NAS_IP_ADDRESS, &client_id, 0) ==
NULL) return (ERROR_RC);
rc_buildreq (&data, PW_ACCESS_REQUEST, server, port, (int)timeout_interval,
retries);
result = rc_send_server (&data, msg);
rc_avpair_free (data.send_pairs);
if (data.receive_pairs)
rc_avpair_free (data.receive_pairs);
if (result == TIMEOUT_RC)
die (STATE_CRITICAL, _("Timeout"));
if (result == ERROR_RC)
die (STATE_CRITICAL, _("Auth Error"));
if (result == BADRESP_RC)
die (STATE_WARNING, _("Auth Failed"));
if (expect && !strstr (msg, expect))
die (STATE_WARNING, "%s", msg);
if (result == OK_RC)
die (STATE_OK, _("Auth OK"));
return (0);
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"hostname", required_argument, 0, 'H'},
{"port", required_argument, 0, 'P'},
{"username", required_argument, 0, 'u'},
{"password", required_argument, 0, 'p'},
{"nas-id", required_argument, 0, 'n'},
{"filename", required_argument, 0, 'F'},
{"expect", required_argument, 0, 'e'},
{"retries", required_argument, 0, 'r'},
{"timeout", required_argument, 0, 't'},
{"verbose", no_argument, 0, 'v'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
if (argc == 9) {
config_file = argv[1];
username = argv[2];
password = argv[3];
if (is_intpos (argv[4]))
timeout_interval = atoi (argv[4]);
else
usage2 (_("Timeout interval must be a positive integer"), optarg);
if (is_intpos (argv[5]))
retries = atoi (argv[5]);
else
usage4 (_("Number of retries must be a positive integer"));
server = argv[6];
if (is_intpos (argv[7]))
port = atoi (argv[7]);
else
usage4 (_("Port must be a positive integer"));
expect = argv[8];
return OK;
}
while (1) {
c = getopt_long (argc, argv, "+hVvH:P:F:u:p:n:t:r:e:", longopts,
&option);
if (c == -1 || c == EOF || c == 1)
break;
switch (c) {
case '?': /* print short usage statement if args not parsable */
usage2 (_("Unknown argument"), optarg);
case 'h': /* help */
print_help ();
exit (OK);
case 'V': /* version */
print_revision (progname, revision);
exit (OK);
case 'v': /* verbose mode */
verbose = TRUE;
break;
case 'H': /* hostname */
if (is_host (optarg) == FALSE) {
usage2 (_("Invalid hostname/address"), optarg);
}
server = optarg;
break;
case 'P': /* port */
if (is_intnonneg (optarg))
port = atoi (optarg);
else
usage4 (_("Port must be a positive integer"));
break;
case 'u': /* username */
username = optarg;
break;
case 'p': /* password */
password = optarg;
break;
case 'n': /* nas id */
nasid = optarg;
break;
case 'F': /* configuration file */
config_file = optarg;
break;
case 'e': /* expect */
expect = optarg;
break;
case 'r': /* retries */
if (is_intpos (optarg))
retries = atoi (optarg);
else
usage4 (_("Number of retries must be a positive integer"));
break;
case 't': /* timeout */
if (is_intpos (optarg))
timeout_interval = atoi (optarg);
else
usage2 (_("Timeout interval must be a positive integer"), optarg);
break;
}
}
return OK;
}
void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", PW_AUTH_UDP_PORT);
print_revision (progname, revision);
printf ("Copyright (c) 1999 Robert August Vincent II\n");
printf (COPYRIGHT, copyright, email);
printf(_("Tests to see if a radius server is accepting connections.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_(UT_HOST_PORT), 'P', myport);
printf (_("\
-u, --username=STRING\n\
The user to authenticate\n\
-p, --password=STRING\n\
Password for autentication (SECURITY RISK)\n\
-n, --nas-id=STRING\n\
NAS identifier\n\
-F, --filename=STRING\n\
Configuration file\n\
-e, --expect=STRING\n\
Response string to expect from the server\n\
-r, --retries=INTEGER\n\
Number of times to retry a failed connection\n"));
printf (_(UT_TIMEOUT), timeout_interval);
printf (_("\n\
This plugin tests a radius server to see if it is accepting connections.\n\
\n\
The server to test must be specified in the invocation, as well as a user\n\
name and password. A configuration file may also be present. The format of\n\
the configuration file is described in the radiusclient library sources.\n\n"));
printf (_("\
The password option presents a substantial security issue because the\n\
password can be determined by careful watching of the command line in\n\
a process listing. This risk is exacerbated because nagios will\n\
run the plugin at regular prdictable intervals. Please be sure that\n\
the password used does not allow access to sensitive system resources,\n\
otherwise compormise could occur.\n"));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s -H host -F config_file -u username -p password [-n nas-id] [-P port]\n\
[-t timeout] [-r retries] [-e expect]\n", progname);
}

440
plugins/check_real.c Normal file
View file

@ -0,0 +1,440 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_real.c,v 1.25 2004/12/25 23:17:44 opensides Exp $
******************************************************************************/
const char *progname = "check_real";
const char *revision = "$Revision: 1.25 $";
const char *copyright = "2000-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "netutils.h"
#include "utils.h"
enum {
PORT = 554
};
#define EXPECT "RTSP/1."
#define URL ""
int process_arguments (int, char **);
int validate_arguments (void);
void print_help (void);
void print_usage (void);
int server_port = PORT;
char *server_address;
char *host_name;
char *server_url = NULL;
char *server_expect;
int warning_time = 0;
int check_warning_time = FALSE;
int critical_time = 0;
int check_critical_time = FALSE;
int verbose = FALSE;
int
main (int argc, char **argv)
{
int sd;
int result = STATE_UNKNOWN;
char buffer[MAX_INPUT_BUFFER];
char *status_line = NULL;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* initialize alarm signal handling */
signal (SIGALRM, socket_timeout_alarm_handler);
/* set socket timeout */
alarm (socket_timeout);
time (&start_time);
/* try to connect to the host at the given port number */
if (my_tcp_connect (server_address, server_port, &sd) != STATE_OK)
die (STATE_CRITICAL, _("Unable to connect to %s on port %d\n"),
server_address, server_port);
/* Part I - Server Check */
/* send the OPTIONS request */
sprintf (buffer, "OPTIONS rtsp://%s:%d RTSP/1.0\r\n", host_name, server_port);
result = send (sd, buffer, strlen (buffer), 0);
/* send the header sync */
sprintf (buffer, "CSeq: 1\r\n");
result = send (sd, buffer, strlen (buffer), 0);
/* send a newline so the server knows we're done with the request */
sprintf (buffer, "\r\n");
result = send (sd, buffer, strlen (buffer), 0);
/* watch for the REAL connection string */
result = recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0);
/* return a CRITICAL status if we couldn't read any data */
if (result == -1)
die (STATE_CRITICAL, _("No data received from %s\n"), host_name);
/* make sure we find the response we are looking for */
if (!strstr (buffer, server_expect)) {
if (server_port == PORT)
printf (_("Invalid REAL response received from host\n"));
else
printf (_("Invalid REAL response received from host on port %d\n"),
server_port);
}
else {
/* else we got the REAL string, so check the return code */
time (&end_time);
result = STATE_OK;
status_line = (char *) strtok (buffer, "\n");
if (strstr (status_line, "200"))
result = STATE_OK;
/* client errors result in a warning state */
else if (strstr (status_line, "400"))
result = STATE_WARNING;
else if (strstr (status_line, "401"))
result = STATE_WARNING;
else if (strstr (status_line, "402"))
result = STATE_WARNING;
else if (strstr (status_line, "403"))
result = STATE_WARNING;
else if (strstr (status_line, "404"))
result = STATE_WARNING;
/* server errors result in a critical state */
else if (strstr (status_line, "500"))
result = STATE_CRITICAL;
else if (strstr (status_line, "501"))
result = STATE_CRITICAL;
else if (strstr (status_line, "502"))
result = STATE_CRITICAL;
else if (strstr (status_line, "503"))
result = STATE_CRITICAL;
else
result = STATE_UNKNOWN;
}
/* Part II - Check stream exists and is ok */
if ((result == STATE_OK )&& (server_url != NULL) ) {
/* Part I - Server Check */
/* send the OPTIONS request */
sprintf (buffer, "DESCRIBE rtsp://%s:%d%s RTSP/1.0\n", host_name,
server_port, server_url);
result = send (sd, buffer, strlen (buffer), 0);
/* send the header sync */
sprintf (buffer, "CSeq: 2\n");
result = send (sd, buffer, strlen (buffer), 0);
/* send a newline so the server knows we're done with the request */
sprintf (buffer, "\n");
result = send (sd, buffer, strlen (buffer), 0);
/* watch for the REAL connection string */
result = recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0);
/* return a CRITICAL status if we couldn't read any data */
if (result == -1) {
printf (_("No data received from host\n"));
result = STATE_CRITICAL;
}
else {
/* make sure we find the response we are looking for */
if (!strstr (buffer, server_expect)) {
if (server_port == PORT)
printf (_("Invalid REAL response received from host\n"));
else
printf (_("Invalid REAL response received from host on port %d\n"),
server_port);
}
else {
/* else we got the REAL string, so check the return code */
time (&end_time);
result = STATE_OK;
status_line = (char *) strtok (buffer, "\n");
if (strstr (status_line, "200"))
result = STATE_OK;
/* client errors result in a warning state */
else if (strstr (status_line, "400"))
result = STATE_WARNING;
else if (strstr (status_line, "401"))
result = STATE_WARNING;
else if (strstr (status_line, "402"))
result = STATE_WARNING;
else if (strstr (status_line, "403"))
result = STATE_WARNING;
else if (strstr (status_line, "404"))
result = STATE_WARNING;
/* server errors result in a critical state */
else if (strstr (status_line, "500"))
result = STATE_CRITICAL;
else if (strstr (status_line, "501"))
result = STATE_CRITICAL;
else if (strstr (status_line, "502"))
result = STATE_CRITICAL;
else if (strstr (status_line, "503"))
result = STATE_CRITICAL;
else
result = STATE_UNKNOWN;
}
}
}
/* Return results */
if (result == STATE_OK) {
if (check_critical_time == TRUE
&& (end_time - start_time) > critical_time) result = STATE_CRITICAL;
else if (check_warning_time == TRUE
&& (end_time - start_time) > warning_time) result =
STATE_WARNING;
/* Put some HTML in here to create a dynamic link */
printf (_("REAL %s - %d second response time\n"),
state_text (result),
(int) (end_time - start_time));
}
else
printf ("%s\n", status_line);
/* close the connection */
close (sd);
/* reset the alarm */
alarm (0);
return result;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"hostname", required_argument, 0, 'H'},
{"IPaddress", required_argument, 0, 'I'},
{"expect", required_argument, 0, 'e'},
{"url", required_argument, 0, 'u'},
{"port", required_argument, 0, 'p'},
{"critical", required_argument, 0, 'c'},
{"warning", required_argument, 0, 'w'},
{"timeout", required_argument, 0, 't'},
{"verbose", no_argument, 0, 'v'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
for (c = 1; c < argc; c++) {
if (strcmp ("-to", argv[c]) == 0)
strcpy (argv[c], "-t");
else if (strcmp ("-wt", argv[c]) == 0)
strcpy (argv[c], "-w");
else if (strcmp ("-ct", argv[c]) == 0)
strcpy (argv[c], "-c");
}
while (1) {
c = getopt_long (argc, argv, "+hVI:H:e:u:p:w:c:t:", longopts,
&option);
if (c == -1 || c == EOF)
break;
switch (c) {
case 'I': /* hostname */
case 'H': /* hostname */
if (server_address)
break;
else if (is_host (optarg))
server_address = optarg;
else
usage2 (_("Invalid hostname/address"), optarg);
break;
case 'e': /* string to expect in response header */
server_expect = optarg;
break;
case 'u': /* server URL */
server_url = optarg;
break;
case 'p': /* port */
if (is_intpos (optarg)) {
server_port = atoi (optarg);
}
else {
usage4 (_("Port must be a positive integer"));
}
break;
case 'w': /* warning time threshold */
if (is_intnonneg (optarg)) {
warning_time = atoi (optarg);
check_warning_time = TRUE;
}
else {
usage4 (_("Warning time must be a positive integer"));
}
break;
case 'c': /* critical time threshold */
if (is_intnonneg (optarg)) {
critical_time = atoi (optarg);
check_critical_time = TRUE;
}
else {
usage4 (_("Critical time must be a positive integer"));
}
break;
case 'v': /* verbose */
verbose = TRUE;
break;
case 't': /* timeout */
if (is_intnonneg (optarg)) {
socket_timeout = atoi (optarg);
}
else {
usage4 (_("Timeout interval must be a positive integer"));
}
break;
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case '?': /* usage */
usage2 (_("Unknown argument"), optarg);
}
}
c = optind;
if (server_address==NULL && argc>c) {
if (is_host (argv[c])) {
server_address = argv[c++];
}
else {
usage2 (_("Invalid hostname/address"), argv[c]);
}
}
if (server_address==NULL)
usage4 (_("You must provide a server to check"));
if (host_name==NULL)
host_name = strdup (server_address);
if (server_expect == NULL)
server_expect = strdup(EXPECT);
return validate_arguments ();
}
int
validate_arguments (void)
{
return OK;
}
void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", PORT);
print_revision (progname, revision);
printf ("Copyright (c) 1999 Pedro Leite <leite@cic.ua.pt>\n");
printf (COPYRIGHT, copyright, email);
printf (_("This plugin tests the REAL service on the specified host.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_(UT_HOST_PORT), 'p', myport);
printf (_("\
-u, --url=STRING\n\
Connect to this url\n\
-e, --expect=STRING\n\
String to expect in first line of server response (default: %s)\n"),
EXPECT);
printf (_(UT_WARN_CRIT));
printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
printf (_(UT_VERBOSE));
printf(_("\
This plugin will attempt to open an RTSP connection with the host.\n\
Successul connects return STATE_OK, refusals and timeouts return\n\
STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful connects,\n\
but incorrect reponse messages from the host result in STATE_WARNING return\n\
values."));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s -H host [-e expect] [-p port] [-w warn] [-c crit]\n\
[-t timeout] [-v]\n", progname);
}

723
plugins/check_smtp.c Normal file
View file

@ -0,0 +1,723 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_smtp.c,v 1.46 2005/04/07 04:33:33 seanius Exp $
******************************************************************************/
const char *progname = "check_smtp";
const char *revision = "$Revision: 1.46 $";
const char *copyright = "2000-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "netutils.h"
#include "utils.h"
#ifdef HAVE_SSL_H
# include <rsa.h>
# include <crypto.h>
# include <x509.h>
# include <pem.h>
# include <ssl.h>
# include <err.h>
#else
# ifdef HAVE_OPENSSL_SSL_H
# include <openssl/rsa.h>
# include <openssl/crypto.h>
# include <openssl/x509.h>
# include <openssl/pem.h>
# include <openssl/ssl.h>
# include <openssl/err.h>
# endif
#endif
#ifdef HAVE_SSL
int check_cert = FALSE;
int days_till_exp;
SSL_CTX *ctx;
SSL *ssl;
X509 *server_cert;
int connect_STARTTLS (void);
int check_certificate (X509 **);
#endif
enum {
SMTP_PORT = 25
};
const char *SMTP_EXPECT = "220";
const char *SMTP_HELO = "HELO ";
const char *SMTP_QUIT = "QUIT\r\n";
const char *SMTP_STARTTLS = "STARTTLS\r\n";
int process_arguments (int, char **);
int validate_arguments (void);
void print_help (void);
void print_usage (void);
int myrecv(void);
int my_close(void);
#ifdef HAVE_REGEX_H
#include <regex.h>
char regex_expect[MAX_INPUT_BUFFER] = "";
regex_t preg;
regmatch_t pmatch[10];
char timestamp[20] = "";
char errbuf[MAX_INPUT_BUFFER];
int cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
int eflags = 0;
int errcode, excode;
#endif
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 ncommands=0;
int command_size=0;
int nresponses=0;
int response_size=0;
char **commands = NULL;
char **responses = NULL;
int warning_time = 0;
int check_warning_time = FALSE;
int critical_time = 0;
int check_critical_time = FALSE;
int verbose = 0;
int use_ssl = FALSE;
int sd;
char buffer[MAX_INPUT_BUFFER];
enum {
TCP_PROTOCOL = 1,
UDP_PROTOCOL = 2,
MAXBUF = 1024
};
int
main (int argc, char **argv)
{
int n = 0;
double elapsed_time;
long microsec;
int result = STATE_UNKNOWN;
char *cmd_str = NULL;
char *helocmd = NULL;
struct timeval tv;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* initialize the HELO command with the localhostname */
#ifndef HOST_MAX_BYTES
#define HOST_MAX_BYTES 255
#endif
helocmd = malloc (HOST_MAX_BYTES);
gethostname(helocmd, HOST_MAX_BYTES);
asprintf (&helocmd, "%s%s%s", SMTP_HELO, helocmd, "\r\n");
/* initialize the MAIL command with optional FROM command */
asprintf (&cmd_str, "%sFROM: %s%s", mail_command, from_arg, "\r\n");
if (verbose && smtp_use_dummycmd)
printf ("FROM CMD: %s", cmd_str);
/* initialize alarm signal handling */
(void) signal (SIGALRM, socket_timeout_alarm_handler);
/* set socket timeout */
(void) alarm (socket_timeout);
/* start timer */
gettimeofday (&tv, NULL);
/* try to connect to the host at the given port number */
result = my_tcp_connect (server_address, server_port, &sd);
if (result == STATE_OK) { /* we connected */
/* watch for the SMTP connection string and */
/* return a WARNING status if we couldn't read any data */
if (recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0) == -1) {
printf (_("recv() failed\n"));
result = STATE_WARNING;
}
else {
if (verbose)
printf ("%s", buffer);
/* strip the buffer of carriage returns */
strip (buffer);
/* make sure we find the response we are looking for */
if (!strstr (buffer, server_expect)) {
if (server_port == SMTP_PORT)
printf (_("Invalid SMTP response received from host\n"));
else
printf (_("Invalid SMTP response received from host on port %d\n"),
server_port);
result = STATE_WARNING;
}
}
/* send the HELO command */
send(sd, helocmd, strlen(helocmd), 0);
/* allow for response to helo command to reach us */
read (sd, buffer, MAXBUF - 1);
#ifdef HAVE_SSL
if(use_ssl) {
/* send the STARTTLS command */
send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0);
recv(sd,buffer, MAX_INPUT_BUFFER-1, 0); /* wait for it */
if (!strstr (buffer, server_expect)) {
printf (_("Server does not support STARTTLS\n"));
return STATE_UNKNOWN;
}
if(connect_STARTTLS() != OK) {
printf (_("CRITICAL - Cannot create SSL context.\n"));
return STATE_CRITICAL;
}
if ( check_cert ) {
if ((server_cert = SSL_get_peer_certificate (ssl)) != NULL) {
result = check_certificate (&server_cert);
X509_free(server_cert);
}
else {
printf (_("CRITICAL - Cannot retrieve server certificate.\n"));
result = STATE_CRITICAL;
}
my_close();
return result;
}
}
#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.
*
* You can disable sending mail_command with '--nocommand'
* Use the -f option to provide a FROM address
*/
if (smtp_use_dummycmd) {
#ifdef HAVE_SSL
if (use_ssl)
SSL_write(ssl, cmd_str, strlen(cmd_str));
else
#endif
send(sd, cmd_str, strlen(cmd_str), 0);
myrecv();
if (verbose)
printf("%s", buffer);
}
while (n < ncommands) {
asprintf (&cmd_str, "%s%s", commands[n], "\r\n");
#ifdef HAVE_SSL
if (use_ssl)
SSL_write(ssl,cmd_str, strlen(cmd_str));
else
#endif
send(sd, cmd_str, strlen(cmd_str), 0);
myrecv();
if (verbose)
printf("%s", buffer);
strip (buffer);
if (n < nresponses) {
#ifdef HAVE_REGEX_H
cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
errcode = regcomp (&preg, responses[n], cflags);
if (errcode != 0) {
regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
printf (_("Could Not Compile Regular Expression"));
return ERROR;
}
excode = regexec (&preg, buffer, 10, pmatch, eflags);
if (excode == 0) {
result = STATE_OK;
}
else if (excode == REG_NOMATCH) {
result = STATE_WARNING;
printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
}
else {
regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER);
printf (_("Execute Error: %s\n"), errbuf);
result = STATE_UNKNOWN;
}
#else
if (strstr(buffer, responses[n])!=buffer) {
result = STATE_WARNING;
printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
}
#endif
}
n++;
}
/* tell the server we're done */
#ifdef HAVE_SSL
if (use_ssl)
SSL_write(ssl,SMTP_QUIT, strlen (SMTP_QUIT));
else
#endif
send (sd, SMTP_QUIT, strlen (SMTP_QUIT), 0);
/* finally close the connection */
close (sd);
}
/* reset the alarm */
alarm (0);
microsec = deltime (tv);
elapsed_time = (double)microsec / 1.0e6;
if (result == STATE_OK) {
if (check_critical_time && elapsed_time > (double) critical_time)
result = STATE_CRITICAL;
else if (check_warning_time && elapsed_time > (double) warning_time)
result = STATE_WARNING;
}
printf (_("SMTP %s - %.3f sec. response time%s%s|%s\n"),
state_text (result), elapsed_time,
verbose?", ":"", verbose?buffer:"",
fperfdata ("time", elapsed_time, "s",
(int)check_warning_time, warning_time,
(int)check_critical_time, critical_time,
TRUE, 0, FALSE, 0));
return result;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"hostname", required_argument, 0, 'H'},
{"expect", required_argument, 0, 'e'},
{"critical", required_argument, 0, 'c'},
{"warning", required_argument, 0, 'w'},
{"timeout", required_argument, 0, 't'},
{"port", required_argument, 0, 'p'},
{"from", required_argument, 0, 'f'},
{"command", required_argument, 0, 'C'},
{"response", required_argument, 0, 'R'},
{"nocommand", required_argument, 0, 'n'},
{"verbose", no_argument, 0, 'v'},
{"version", no_argument, 0, 'V'},
{"use-ipv4", no_argument, 0, '4'},
{"use-ipv6", no_argument, 0, '6'},
{"help", no_argument, 0, 'h'},
{"starttls",no_argument,0,'S'},
{"certificate",required_argument,0,'D'},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
for (c = 1; c < argc; c++) {
if (strcmp ("-to", argv[c]) == 0)
strcpy (argv[c], "-t");
else if (strcmp ("-wt", argv[c]) == 0)
strcpy (argv[c], "-w");
else if (strcmp ("-ct", argv[c]) == 0)
strcpy (argv[c], "-c");
}
while (1) {
c = getopt_long (argc, argv, "+hVv46t:p:f:e:c:w:H:C:R:SD:",
longopts, &option);
if (c == -1 || c == EOF)
break;
switch (c) {
case 'H': /* hostname */
if (is_host (optarg)) {
server_address = optarg;
}
else {
usage2 (_("Invalid hostname/address"), optarg);
}
break;
case 'p': /* port */
if (is_intpos (optarg))
server_port = atoi (optarg);
else
usage4 (_("Port must be a positive integer"));
break;
case 'f': /* from argument */
from_arg = optarg;
smtp_use_dummycmd = 1;
break;
case 'e': /* server expect string on 220 */
server_expect = optarg;
break;
case 'C': /* commands */
if (ncommands >= command_size) {
commands = realloc (commands, command_size+8);
if (commands == NULL)
die (STATE_UNKNOWN,
_("Could not realloc() units [%d]\n"), ncommands);
}
commands[ncommands] = optarg;
ncommands++;
break;
case 'R': /* server responses */
if (nresponses >= response_size) {
responses = realloc (responses, response_size+8);
if (responses == NULL)
die (STATE_UNKNOWN,
_("Could not realloc() units [%d]\n"), nresponses);
}
responses[nresponses] = optarg;
nresponses++;
break;
case 'c': /* critical time threshold */
if (is_intnonneg (optarg)) {
critical_time = atoi (optarg);
check_critical_time = TRUE;
}
else {
usage4 (_("Critical time must be a positive integer"));
}
break;
case 'w': /* warning time threshold */
if (is_intnonneg (optarg)) {
warning_time = atoi (optarg);
check_warning_time = TRUE;
}
else {
usage4 (_("Warning time must be a positive integer"));
}
break;
case 'v': /* verbose */
verbose++;
break;
case 't': /* timeout */
if (is_intnonneg (optarg)) {
socket_timeout = atoi (optarg);
}
else {
usage4 (_("Timeout interval must be a positive integer"));
}
break;
case 'S':
/* starttls */
use_ssl = TRUE;
break;
case 'D':
/* Check SSL cert validity */
#ifdef HAVE_SSL
if (!is_intnonneg (optarg))
usage2 ("Invalid certificate expiration period",optarg);
days_till_exp = atoi (optarg);
check_cert = TRUE;
#else
usage (_("SSL support not available - install OpenSSL and recompile"));
#endif
break;
case '4':
address_family = AF_INET;
break;
case '6':
#ifdef USE_IPV6
address_family = AF_INET6;
#else
usage4 (_("IPv6 support not available"));
#endif
break;
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case '?': /* help */
usage2 (_("Unknown argument"), optarg);
}
}
c = optind;
if (server_address == NULL) {
if (argv[c]) {
if (is_host (argv[c]))
server_address = argv[c];
else
usage2 (_("Invalid hostname/address"), argv[c]);
}
else {
asprintf (&server_address, "127.0.0.1");
}
}
if (server_expect == NULL)
server_expect = strdup (SMTP_EXPECT);
if (mail_command == NULL)
mail_command = strdup("MAIL ");
if (from_arg==NULL)
from_arg = strdup(" ");
return validate_arguments ();
}
int
validate_arguments (void)
{
return OK;
}
void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", SMTP_PORT);
print_revision (progname, revision);
printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
printf (COPYRIGHT, copyright, email);
printf(_("This plugin will attempt to open an SMTP connection with the host.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_(UT_HOST_PORT), 'p', myport);
printf (_(UT_IPv46));
printf (_("\
-e, --expect=STRING\n\
String to expect in first line of server response (default: '%s')\n\
-n, nocommand\n\
Suppress SMTP command\n\
-C, --command=STRING\n\
SMTP command (may be used repeatedly)\n\
-R, --command=STRING\n\
Expected response to command (may be used repeatedly)\n\
-f, --from=STRING\n\
FROM-address to include in MAIL command, required by Exchange 2000\n"),
SMTP_EXPECT);
#ifdef HAVE_SSL
printf (_("\
-D, --certificate=INTEGER\n\
Minimum number of days a certificate has to be valid.\n\
-S, --starttls\n\
Use STARTTLS for the connection.\n"));
#endif
printf (_(UT_WARN_CRIT));
printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
printf (_(UT_VERBOSE));
printf(_("\n\
Successul connects return STATE_OK, refusals and timeouts return\n\
STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful\n\
connects, but incorrect reponse messages from the host result in\n\
STATE_WARNING return values.\n"));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s -H host [-p port] [-e expect] [-C command] [-f from addr]\n\
[-w warn] [-c crit] [-t timeout] [-S] [-D days] [-n] [-v] [-4|-6]\n", progname);
}
#ifdef HAVE_SSL
int
connect_STARTTLS (void)
{
SSL_METHOD *meth;
/* Initialize SSL context */
SSLeay_add_ssl_algorithms ();
meth = SSLv2_client_method ();
SSL_load_error_strings ();
if ((ctx = SSL_CTX_new (meth)) == NULL)
{
printf(_("CRITICAL - Cannot create SSL context.\n"));
return STATE_CRITICAL;
}
/* do the SSL handshake */
if ((ssl = SSL_new (ctx)) != NULL)
{
SSL_set_fd (ssl, sd);
/* original version checked for -1
I look for success instead (1) */
if (SSL_connect (ssl) == 1)
return OK;
ERR_print_errors_fp (stderr);
}
else
{
printf (_("CRITICAL - Cannot initiate SSL handshake.\n"));
}
/* this causes a seg faul
not sure why, being sloppy
and commenting it out */
/* SSL_free (ssl); */
SSL_CTX_free(ctx);
my_close();
return STATE_CRITICAL;
}
int
check_certificate (X509 ** certificate)
{
ASN1_STRING *tm;
int offset;
struct tm stamp;
int days_left;
/* Retrieve timestamp of certificate */
tm = X509_get_notAfter (*certificate);
/* Generate tm structure to process timestamp */
if (tm->type == V_ASN1_UTCTIME) {
if (tm->length < 10) {
printf (_("CRITICAL - Wrong time format in certificate.\n"));
return STATE_CRITICAL;
}
else {
stamp.tm_year = (tm->data[0] - '0') * 10 + (tm->data[1] - '0');
if (stamp.tm_year < 50)
stamp.tm_year += 100;
offset = 0;
}
}
else {
if (tm->length < 12) {
printf (_("CRITICAL - Wrong time format in certificate.\n"));
return STATE_CRITICAL;
}
else {
stamp.tm_year =
(tm->data[0] - '0') * 1000 + (tm->data[1] - '0') * 100 +
(tm->data[2] - '0') * 10 + (tm->data[3] - '0');
stamp.tm_year -= 1900;
offset = 2;
}
}
stamp.tm_mon =
(tm->data[2 + offset] - '0') * 10 + (tm->data[3 + offset] - '0') - 1;
stamp.tm_mday =
(tm->data[4 + offset] - '0') * 10 + (tm->data[5 + offset] - '0');
stamp.tm_hour =
(tm->data[6 + offset] - '0') * 10 + (tm->data[7 + offset] - '0');
stamp.tm_min =
(tm->data[8 + offset] - '0') * 10 + (tm->data[9 + offset] - '0');
stamp.tm_sec = 0;
stamp.tm_isdst = -1;
days_left = (mktime (&stamp) - time (NULL)) / 86400;
snprintf
(timestamp, sizeof(timestamp), "%02d/%02d/%04d %02d:%02d",
stamp.tm_mon + 1,
stamp.tm_mday, stamp.tm_year + 1900, stamp.tm_hour, stamp.tm_min);
if (days_left > 0 && days_left <= days_till_exp) {
printf ("Certificate expires in %d day(s) (%s).\n", days_left, timestamp);
return STATE_WARNING;
}
if (days_left < 0) {
printf ("Certificate expired on %s.\n", timestamp);
return STATE_CRITICAL;
}
if (days_left == 0) {
printf ("Certificate expires today (%s).\n", timestamp);
return STATE_WARNING;
}
printf ("Certificate will expire on %s.\n", timestamp);
return STATE_OK;
}
#endif
int
myrecv (void)
{
int i;
#ifdef HAVE_SSL
if (use_ssl) {
i = SSL_read (ssl, buffer, MAXBUF - 1);
}
else {
#endif
i = read (sd, buffer, MAXBUF - 1);
#ifdef HAVE_SSL
}
#endif
return i;
}
int
my_close (void)
{
#ifdef HAVE_SSL
if (use_ssl == TRUE) {
SSL_shutdown (ssl);
SSL_free (ssl);
SSL_CTX_free (ctx);
return 0;
}
else {
#endif
return close(sd);
#ifdef HAVE_SSL
}
#endif
}

1017
plugins/check_snmp.c Normal file

File diff suppressed because it is too large Load diff

290
plugins/check_ssh.c Normal file
View file

@ -0,0 +1,290 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_ssh.c,v 1.27 2005/04/11 18:02:40 seanius Exp $
******************************************************************************/
const char *progname = "check_ssh";
const char *revision = "$Revision: 1.27 $";
const char *copyright = "2000-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "netutils.h"
#include "utils.h"
#ifndef MSG_DONTWAIT
#define MSG_DONTWAIT 0
#endif
#define SSH_DFL_PORT 22
#define BUFF_SZ 256
int port = -1;
char *server_name = NULL;
char *remote_version = NULL;
int verbose = FALSE;
int process_arguments (int, char **);
int validate_arguments (void);
void print_help (void);
void print_usage (void);
int ssh_connect (char *haddr, int hport, char *remote_version);
int
main (int argc, char **argv)
{
int result = STATE_UNKNOWN;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* initialize alarm signal handling */
signal (SIGALRM, socket_timeout_alarm_handler);
alarm (socket_timeout);
/* ssh_connect exits if error is found */
result = ssh_connect (server_name, port, remote_version);
alarm (0);
return (result);
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{"host", required_argument, 0, 'H'},
{"port", required_argument, 0, 'p'},
{"use-ipv4", no_argument, 0, '4'},
{"use-ipv6", no_argument, 0, '6'},
{"timeout", required_argument, 0, 't'},
{"verbose", no_argument, 0, 'v'},
{"remote-version", required_argument, 0, 'r'},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
for (c = 1; c < argc; c++)
if (strcmp ("-to", argv[c]) == 0)
strcpy (argv[c], "-t");
while (1) {
c = getopt_long (argc, argv, "+Vhv46t:r:H:p:", longopts, &option);
if (c == -1 || c == EOF)
break;
switch (c) {
case '?': /* help */
usage2 (_("Unknown argument"), optarg);
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case 'v': /* verbose */
verbose = TRUE;
break;
case 't': /* timeout period */
if (!is_integer (optarg))
usage2 (_("Timeout interval must be a positive integer"), optarg);
else
socket_timeout = atoi (optarg);
break;
case '4':
address_family = AF_INET;
break;
case '6':
#ifdef USE_IPV6
address_family = AF_INET6;
#else
usage4 (_("IPv6 support not available"));
#endif
break;
case 'r': /* remote version */
remote_version = optarg;
break;
case 'H': /* host */
if (is_host (optarg) == FALSE)
usage2 (_("Invalid hostname/address"), optarg);
server_name = optarg;
break;
case 'p': /* port */
if (is_intpos (optarg)) {
port = atoi (optarg);
}
else {
usage2 (_("Port number must be a positive integer"), optarg);
}
}
}
c = optind;
if (server_name == NULL && c < argc) {
if (is_host (argv[c])) {
server_name = argv[c++];
}
}
if (port == -1 && c < argc) {
if (is_intpos (argv[c])) {
port = atoi (argv[c++]);
}
else {
print_usage ();
exit (STATE_UNKNOWN);
}
}
return validate_arguments ();
}
int
validate_arguments (void)
{
if (server_name == NULL)
return ERROR;
if (port == -1) /* funky, but allows -p to override stray integer in args */
port = SSH_DFL_PORT;
return OK;
}
/************************************************************************
*
* Try to connect to SSH server at specified server and port
*
*-----------------------------------------------------------------------*/
int
ssh_connect (char *haddr, int hport, char *remote_version)
{
int sd;
int result;
char *output = NULL;
char *buffer = NULL;
char *ssh_proto = NULL;
char *ssh_server = NULL;
char rev_no[20];
sscanf ("$Revision: 1.27 $", "$Revision: %[0123456789.]", rev_no);
result = my_tcp_connect (haddr, hport, &sd);
if (result != STATE_OK)
return result;
output = (char *) malloc (BUFF_SZ + 1);
memset (output, 0, BUFF_SZ + 1);
recv (sd, output, BUFF_SZ, 0);
if (strncmp (output, "SSH", 3)) {
printf (_("Server answer: %s"), output);
exit (STATE_CRITICAL);
}
else {
strip (output);
if (verbose)
printf ("%s\n", output);
ssh_proto = output + 4;
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);
send (sd, buffer, strlen (buffer), MSG_DONTWAIT);
if (verbose)
printf ("%s\n", buffer);
if (remote_version && strcmp(remote_version, ssh_server)) {
printf
(_("SSH WARNING - %s (protocol %s) version mismatch, expected '%s'\n"),
ssh_server, ssh_proto, remote_version);
exit (STATE_WARNING);
}
printf
(_("SSH OK - %s (protocol %s)\n"),
ssh_server, ssh_proto);
close(sd);
exit (STATE_OK);
}
}
void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", SSH_DFL_PORT);
print_revision (progname, revision);
printf ("Copyright (c) 1999 Remi Paulmier <remi@sinfomic.fr>\n");
printf (COPYRIGHT, copyright, email);
printf (_("Try to connect to an SSH server at specified server and port\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_(UT_HOST_PORT), 'p', myport);
printf (_(UT_IPv46));
printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
printf (_("\
-r, --remote-version=STRING\n\
Warn if string doesn't match expected server version (ex: OpenSSH_3.9p1)\n"));
printf (_(UT_VERBOSE));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s [-46] [-t <timeout>] [-r <remote version>] [-p <port>] <host>\n", progname);
}

521
plugins/check_swap.c Normal file
View file

@ -0,0 +1,521 @@
/******************************************************************************
*
* Program: Swap space plugin for Nagios
* License: GPL
*
* License Information:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Copyright (c) 2000 Karl DeBisschop (kdebisschop@users.sourceforge.net)
*
* $Id: check_swap.c,v 1.52 2005/09/15 08:27:58 tonvoon Exp $
*
*****************************************************************************/
const char *progname = "check_swap";
const char *revision = "$Revision: 1.52 $";
const char *copyright = "2000-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "popen.h"
#include "utils.h"
int check_swap (int usp, float free_swap);
int process_arguments (int argc, char **argv);
int validate_arguments (void);
void print_usage (void);
void print_help (void);
int warn_percent = 0;
int crit_percent = 0;
double warn_size = 0;
double crit_size = 0;
int verbose;
int allswaps;
int
main (int argc, char **argv)
{
int percent_used, percent;
float total_swap = 0, used_swap = 0, free_swap = 0;
float dsktotal = 0, dskused = 0, dskfree = 0, tmp = 0;
int result = STATE_UNKNOWN;
char input_buffer[MAX_INPUT_BUFFER];
#ifdef HAVE_PROC_MEMINFO
FILE *fp;
#else
int conv_factor = SWAP_CONVERSION;
# ifdef HAVE_SWAP
char *temp_buffer;
char *swap_command;
char *swap_format;
# else
# ifdef HAVE_DECL_SWAPCTL
int i=0, nswaps=0, swapctl_res=0;
# ifdef CHECK_SWAP_SWAPCTL_SVR4
swaptbl_t *tbl=NULL;
swapent_t *ent=NULL;
# else
# ifdef CHECK_SWAP_SWAPCTL_BSD
struct swapent *ent;
# endif /* CHECK_SWAP_SWAPCTL_BSD */
# endif /* CHECK_SWAP_SWAPCTL_SVR4 */
# endif /* HAVE_DECL_SWAPCTL */
# endif
#endif
char str[32];
char *status;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
status = strdup ("");
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
#ifdef HAVE_PROC_MEMINFO
fp = fopen (PROC_MEMINFO, "r");
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%*[:] %f %f %f", &dsktotal, &dskused, &dskfree) == 3) {
dsktotal = dsktotal / 1048576;
dskused = dskused / 1048576;
dskfree = dskfree / 1048576;
total_swap += dsktotal;
used_swap += dskused;
free_swap += dskfree;
if (allswaps) {
if (dsktotal == 0)
percent=100.0;
else
percent = 100 * (((double) dskused) / ((double) dsktotal));
result = max_state (result, check_swap (percent, dskfree));
if (verbose)
asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree, 100 - percent);
}
}
else if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%[TotalFre]%*[:] %f %*[k]%*[B]", str, &tmp)) {
if (strcmp ("Total", str) == 0) {
dsktotal = tmp / 1024;
}
else if (strcmp ("Free", str) == 0) {
dskfree = tmp / 1024;
}
}
}
fclose(fp);
dskused = dsktotal - dskfree;
total_swap = dsktotal;
used_swap = dskused;
free_swap = dskfree;
#else
# ifdef HAVE_SWAP
asprintf(&swap_command, "%s", SWAP_COMMAND);
asprintf(&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");
conv_factor = 1;
}
# endif
if (verbose >= 2)
printf (_("Command: %s\n"), swap_command);
if (verbose >= 3)
printf (_("Format: %s\n"), swap_format);
child_process = spopen (swap_command);
if (child_process == NULL) {
printf (_("Could not open pipe: %s\n"), swap_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"), swap_command);
sprintf (str, "%s", "");
/* read 1st line */
fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process);
if (strcmp (swap_format, "") == 0) {
temp_buffer = strtok (input_buffer, " \n");
while (temp_buffer) {
if (strstr (temp_buffer, "blocks"))
sprintf (str, "%s %s", str, "%f");
else if (strstr (temp_buffer, "dskfree"))
sprintf (str, "%s %s", str, "%f");
else
sprintf (str, "%s %s", str, "%*s");
temp_buffer = strtok (NULL, " \n");
}
}
/* If different swap command is used for summary switch, need to read format differently */
# ifdef _AIX
if (!allswaps) {
fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process); /* Ignore first line */
sscanf (input_buffer, swap_format, &total_swap, &used_swap);
free_swap = total_swap * (100 - used_swap) /100;
used_swap = total_swap - free_swap;
if (verbose >= 3)
printf (_("total=%.0f, used=%.0f, free=%.0f\n"), total_swap, used_swap, free_swap);
} else {
# endif
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
sscanf (input_buffer, swap_format, &dsktotal, &dskfree);
dsktotal = dsktotal / conv_factor;
/* AIX lists percent used, so this converts to dskfree in MBs */
# ifdef _AIX
dskfree = dsktotal * (100 - dskfree) / 100;
# else
dskfree = dskfree / conv_factor;
# endif
if (verbose >= 3)
printf (_("total=%.0f, free=%.0f\n"), dsktotal, dskfree);
dskused = dsktotal - dskfree;
total_swap += dsktotal;
used_swap += dskused;
free_swap += dskfree;
if (allswaps) {
percent = 100 * (((double) dskused) / ((double) dsktotal));
result = max_state (result, check_swap (percent, dskfree));
if (verbose)
asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree, 100 - percent);
}
}
# ifdef _AIX
}
# endif
/* If we get anything on STDERR, at least set warning */
while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr))
result = max_state (result, STATE_WARNING);
/* close stderr */
(void) fclose (child_stderr);
/* close the pipe */
if (spclose (child_process))
result = max_state (result, STATE_WARNING);
# else
# ifdef CHECK_SWAP_SWAPCTL_SVR4
/* get the number of active swap devices */
nswaps=swapctl(SC_GETNSWP, NULL);
/* initialize swap table + entries */
tbl=(swaptbl_t*)malloc(sizeof(swaptbl_t)+(sizeof(swapent_t)*nswaps));
memset(tbl, 0, sizeof(swaptbl_t)+(sizeof(swapent_t)*nswaps));
tbl->swt_n=nswaps;
for(i=0;i<nswaps;i++){
ent=&tbl->swt_ent[i];
ent->ste_path=(char*)malloc(sizeof(char)*MAXPATHLEN);
}
/* and now, tally 'em up */
swapctl_res=swapctl(SC_LIST, tbl);
if(swapctl_res < 0){
perror(_("swapctl failed: "));
result = STATE_WARNING;
}
for(i=0;i<nswaps;i++){
dsktotal = (float) tbl->swt_ent[i].ste_pages / SWAP_CONVERSION;
dskfree = (float) tbl->swt_ent[i].ste_free / SWAP_CONVERSION;
dskused = ( dsktotal - dskfree );
if (verbose >= 3)
printf ("dsktotal=%.0f dskfree=%.0f dskused=%.0f\n", dsktotal, dskfree, dskused);
if(allswaps && dsktotal > 0){
percent = 100 * (((double) dskused) / ((double) dsktotal));
result = max_state (result, check_swap (percent, dskfree));
if (verbose) {
asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree, 100 - percent);
}
}
total_swap += dsktotal;
free_swap += dskfree;
used_swap += dskused;
}
/* and clean up after ourselves */
for(i=0;i<nswaps;i++){
free(tbl->swt_ent[i].ste_path);
}
free(tbl);
# else
# ifdef CHECK_SWAP_SWAPCTL_BSD
/* get the number of active swap devices */
nswaps=swapctl(SWAP_NSWAP, NULL, 0);
/* initialize swap table + entries */
ent=(struct swapent*)malloc(sizeof(struct swapent)*nswaps);
/* and now, tally 'em up */
swapctl_res=swapctl(SWAP_STATS, ent, nswaps);
if(swapctl_res < 0){
perror(_("swapctl failed: "));
result = STATE_WARNING;
}
for(i=0;i<nswaps;i++){
dsktotal = (float) ent->se_nblks / conv_factor;
dskused = (float) ent->se_inuse / conv_factor;
dskfree = ( dsktotal - dskused );
if(allswaps && dsktotal > 0){
percent = 100 * (((double) dskused) / ((double) dsktotal));
result = max_state (result, check_swap (percent, dskfree));
if (verbose) {
asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree, 100 - percent);
}
}
total_swap += dsktotal;
free_swap += dskfree;
used_swap += dskused;
}
/* and clean up after ourselves */
free(ent);
# endif /* CHECK_SWAP_SWAPCTL_BSD */
# endif /* CHECK_SWAP_SWAPCTL_SVR4 */
# endif /* HAVE_SWAP */
#endif /* HAVE_PROC_MEMINFO */
/* if total_swap == 0, let's not divide by 0 */
if(total_swap) {
percent_used = 100 * ((double) used_swap) / ((double) total_swap);
} else {
percent_used = 0;
}
result = max_state (result, check_swap (percent_used, free_swap));
printf (_("SWAP %s - %d%% free (%.0f MB out of %.0f MB) %s|"),
state_text (result),
(100 - percent_used), free_swap, total_swap, status);
puts (perfdata ("swap", (long) free_swap, "MB",
TRUE, (long) max (warn_size/1024, warn_percent/100.0*total_swap),
TRUE, (long) max (crit_size/1024, crit_percent/100.0*total_swap),
TRUE, 0,
TRUE, (long) total_swap));
return result;
}
int
check_swap (int usp, float free_swap)
{
int result = STATE_UNKNOWN;
free_swap = free_swap * 1024; /* Convert back to bytes as warn and crit specified in bytes */
if (usp >= 0 && crit_percent != 0 && usp >= (100.0 - crit_percent))
result = STATE_CRITICAL;
else if (crit_size > 0 && free_swap <= crit_size)
result = STATE_CRITICAL;
else if (usp >= 0 && warn_percent != 0 && usp >= (100.0 - warn_percent))
result = STATE_WARNING;
else if (warn_size > 0 && free_swap <= warn_size)
result = STATE_WARNING;
else if (usp >= 0.0)
result = STATE_OK;
return result;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c = 0; /* option character */
int option = 0;
static struct option longopts[] = {
{"warning", required_argument, 0, 'w'},
{"critical", required_argument, 0, 'c'},
{"allswaps", no_argument, 0, 'a'},
{"verbose", no_argument, 0, 'v'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
while (1) {
c = getopt_long (argc, argv, "+?Vvhac:w:", longopts, &option);
if (c == -1 || c == EOF)
break;
switch (c) {
case 'w': /* warning size threshold */
if (is_intnonneg (optarg)) {
warn_size = (double) atoi (optarg);
break;
}
else if (strstr (optarg, ",") &&
strstr (optarg, "%") &&
sscanf (optarg, "%g,%d%%", &warn_size, &warn_percent) == 2) {
warn_size = floor(warn_size);
break;
}
else if (strstr (optarg, "%") &&
sscanf (optarg, "%d%%", &warn_percent) == 1) {
break;
}
else {
usage4 (_("Warning threshold must be integer or percentage!"));
}
case 'c': /* critical size threshold */
if (is_intnonneg (optarg)) {
crit_size = (double) atoi (optarg);
break;
}
else if (strstr (optarg, ",") &&
strstr (optarg, "%") &&
sscanf (optarg, "%g,%d%%", &crit_size, &crit_percent) == 2) {
crit_size = floor(crit_size);
break;
}
else if (strstr (optarg, "%") &&
sscanf (optarg, "%d%%", &crit_percent) == 1) {
break;
}
else {
usage4 (_("Critical threshold must be integer or percentage!"));
}
case 'a': /* all swap */
allswaps = TRUE;
break;
case 'v': /* verbose */
verbose++;
break;
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case '?': /* error */
usage2 (_("Unknown argument"), optarg);
}
}
c = optind;
if (c == argc)
return validate_arguments ();
if (warn_percent == 0 && is_intnonneg (argv[c]))
warn_percent = atoi (argv[c++]);
if (c == argc)
return validate_arguments ();
if (crit_percent == 0 && is_intnonneg (argv[c]))
crit_percent = atoi (argv[c++]);
if (c == argc)
return validate_arguments ();
if (warn_size == 0 && is_intnonneg (argv[c]))
warn_size = (double) atoi (argv[c++]);
if (c == argc)
return validate_arguments ();
if (crit_size == 0 && is_intnonneg (argv[c]))
crit_size = (double) atoi (argv[c++]);
return validate_arguments ();
}
int
validate_arguments (void)
{
if (warn_percent == 0 && crit_percent == 0 && warn_size == 0
&& crit_size == 0) {
return ERROR;
}
else if (warn_percent < crit_percent) {
usage4
(_("Warning percentage should be more than critical percentage"));
}
else if (warn_size < crit_size) {
usage4
(_("Warning free space should be more than critical free space"));
}
return OK;
}
void
print_help (void)
{
print_revision (progname, revision);
printf (_(COPYRIGHT), copyright, email);
printf (_("Check swap space on local machine.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_("\n\
-w, --warning=INTEGER\n\
Exit with WARNING status if less than INTEGER bytes of swap space are free\n\
-w, --warning=PERCENT%%\n\
Exit with WARNING status if less than PERCENT of swap space is free\n\
-c, --critical=INTEGER\n\
Exit with CRITICAL status if less than INTEGER bytes of swap space are free\n\
-c, --critical=PERCENT%%\n\
Exit with CRITCAL status if less than PERCENT of swap space is free\n\
-a, --allswaps\n\
Conduct comparisons for all swap partitions, one by one\n\
-v, --verbose\n\
Verbose output. Up to 3 levels\n"));
printf (_("\n\
On AIX, if -a is specified, uses lsps -a, otherwise uses lsps -s.\n"));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s [-av] -w <percent_free>%% -c <percent_free>%%\n\
%s [-av] -w <bytes_free> -c <bytes_free>\n", progname, progname);
}

788
plugins/check_tcp.c Normal file
View file

@ -0,0 +1,788 @@
/*****************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_tcp.c,v 1.66 2005/06/05 17:43:58 seanius Exp $
*****************************************************************************/
/* progname "check_tcp" changes depending on symlink called */
char *progname;
const char *revision = "$Revision: 1.66 $";
const char *copyright = "1999-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "netutils.h"
#include "utils.h"
#ifdef HAVE_SSL_H
# include <rsa.h>
# include <crypto.h>
# include <x509.h>
# include <pem.h>
# include <ssl.h>
# include <err.h>
#else
# ifdef HAVE_OPENSSL_SSL_H
# include <openssl/rsa.h>
# include <openssl/crypto.h>
# include <openssl/x509.h>
# include <openssl/pem.h>
# include <openssl/ssl.h>
# include <openssl/err.h>
# endif
#endif
#ifdef HAVE_SSL
static int check_cert = FALSE;
static int days_till_exp;
static char *randbuff = "";
static SSL_CTX *ctx;
static SSL *ssl;
static X509 *server_cert;
static int connect_SSL (void);
static int check_certificate (X509 **);
# define my_recv(buf, len) ((flags & FLAG_SSL) ? SSL_read(ssl, buf, len) : read(sd, buf, len))
#else
# define my_recv(buf, len) read(sd, buf, len)
#endif
/* int my_recv(char *, size_t); */
static int process_arguments (int, char **);
void print_help (void);
void print_usage (void);
#define EXPECT server_expect[0]
static char *SERVICE = "TCP";
static char *SEND = NULL;
static char *QUIT = NULL;
static int PROTOCOL = IPPROTO_TCP; /* most common is default */
static int PORT = 0;
static char timestamp[17] = "";
static int server_port = 0;
static char *server_address = NULL;
static char *server_send = NULL;
static char *server_quit = NULL;
static char **server_expect;
static size_t server_expect_count = 0;
static size_t maxbytes = 0;
static char **warn_codes = NULL;
static size_t warn_codes_count = 0;
static char **crit_codes = NULL;
static size_t crit_codes_count = 0;
static unsigned int delay = 0;
static double warning_time = 0;
static double critical_time = 0;
static double elapsed_time = 0;
static long microsec;
static int sd = 0;
#define MAXBUF 1024
static char buffer[MAXBUF];
static int expect_mismatch_state = STATE_WARNING;
#define FLAG_SSL 0x01
#define FLAG_VERBOSE 0x02
#define FLAG_EXACT_MATCH 0x04
#define FLAG_TIME_WARN 0x08
#define FLAG_TIME_CRIT 0x10
#define FLAG_HIDE_OUTPUT 0x20
static size_t flags = FLAG_EXACT_MATCH;
int
main (int argc, char **argv)
{
int result = STATE_UNKNOWN;
int i;
char *status = NULL;
struct timeval tv;
size_t len, match = -1;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
/* determine program- and service-name quickly */
progname = strrchr(argv[0], '/');
if(progname != NULL) progname++;
else progname = argv[0];
len = strlen(progname);
if(len > 6 && !memcmp(progname, "check_", 6)) {
SERVICE = progname + 6;
for(i = 0; i < len - 6; i++)
SERVICE[i] = toupper(SERVICE[i]);
}
/* set up a resonable buffer at first (will be realloc()'ed if
* user specifies other options) */
server_expect = calloc(sizeof(char *), 2);
/* determine defaults for this service's protocol */
if (!strncmp(SERVICE, "UDP", 3)) {
PROTOCOL = IPPROTO_UDP;
}
else if (!strncmp(SERVICE, "FTP", 3)) {
EXPECT = "220";
QUIT = "QUIT\r\n";
PORT = 21;
}
else if (!strncmp(SERVICE, "POP", 3) || !strncmp(SERVICE, "POP3", 4)) {
EXPECT = "+OK";
QUIT = "QUIT\r\n";
PORT = 110;
}
else if (!strncmp(SERVICE, "SMTP", 4)) {
EXPECT = "220";
QUIT = "QUIT\r\n";
PORT = 25;
}
else if (!strncmp(SERVICE, "IMAP", 4)) {
EXPECT = "* OK";
QUIT = "a1 LOGOUT\r\n";
PORT = 143;
}
#ifdef HAVE_SSL
else if (!strncmp(SERVICE, "SIMAP", 5)) {
EXPECT = "* OK";
QUIT = "a1 LOGOUT\r\n";
flags |= FLAG_SSL;
PORT = 993;
}
else if (!strncmp(SERVICE, "SPOP", 4)) {
EXPECT = "+OK";
QUIT = "QUIT\r\n";
flags |= FLAG_SSL;
PORT = 995;
}
else if (!strncmp(SERVICE, "SSMTP", 5)) {
EXPECT = "220";
QUIT = "QUIT\r\n";
flags |= FLAG_SSL;
PORT = 465;
}
else if (!strncmp(SERVICE, "JABBER", 6)) {
SEND = "<stream:stream to=\'host\' xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'>\n";
EXPECT = "<?xml version=\'1.0\'?><stream:stream xmlns:stream=\'http://etherx.jabber.org/streams\'";
QUIT = "</stream:stream>\n";
flags |= FLAG_SSL | FLAG_HIDE_OUTPUT;
PORT = 5222;
}
else if (!strncmp (SERVICE, "NNTPS", 5)) {
server_expect_count = 2;
server_expect[0] = "200";
server_expect[1] = "201";
QUIT = "QUIT\r\n";
flags |= FLAG_SSL;
PORT = 563;
}
#endif
else if (!strncmp (SERVICE, "NNTP", 4)) {
server_expect_count = 2;
server_expect = malloc(sizeof(char *) * server_expect_count);
server_expect[0] = strdup("200");
server_expect[1] = strdup("201");
QUIT = "QUIT\r\n";
PORT = 119;
}
/* fallthrough check, so it's supposed to use reverse matching */
else if (strcmp (SERVICE, "TCP"))
usage (_("CRITICAL - Generic check_tcp called with unknown service\n"));
server_address = "127.0.0.1";
server_port = PORT;
server_send = SEND;
server_quit = QUIT;
status = NULL;
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
if(flags & FLAG_VERBOSE) {
printf("Using service %s\n", SERVICE);
printf("Port: %d\n", PORT);
printf("flags: 0x%x\n", flags);
}
if(EXPECT && !server_expect_count)
server_expect_count++;
/* set up the timer */
signal (SIGALRM, socket_timeout_alarm_handler);
alarm (socket_timeout);
/* try to connect to the host at the given port number */
gettimeofday (&tv, NULL);
#ifdef HAVE_SSL
if (flags & FLAG_SSL && check_cert == TRUE) {
if (connect_SSL () != OK)
die (STATE_CRITICAL,_("CRITICAL - Could not make SSL connection\n"));
if ((server_cert = SSL_get_peer_certificate (ssl)) != NULL) {
result = check_certificate (&server_cert);
X509_free(server_cert);
}
else {
printf(_("CRITICAL - Cannot retrieve server certificate.\n"));
result = STATE_CRITICAL;
}
SSL_shutdown (ssl);
SSL_free (ssl);
SSL_CTX_free (ctx);
close (sd);
return result;
}
else if (flags & FLAG_SSL)
result = connect_SSL ();
else
#endif
result = np_net_connect (server_address, server_port, &sd, PROTOCOL);
if (result == STATE_CRITICAL)
return STATE_CRITICAL;
if (server_send != NULL) { /* Something to send? */
#ifdef HAVE_SSL
if (flags & FLAG_SSL)
SSL_write(ssl, server_send, (int)strlen(server_send));
else
#endif
send (sd, server_send, strlen(server_send), 0);
}
if (delay > 0) {
tv.tv_sec += delay;
sleep (delay);
}
if(flags & FLAG_VERBOSE) {
printf("server_expect_count: %d\n", server_expect_count);
for(i = 0; i < server_expect_count; i++)
printf("\t%d: %s\n", i, server_expect[i]);
}
/* if(len) later on, we know we have a non-NULL response */
len = 0;
if (server_expect_count) {
/* watch for the expect string */
while ((i = my_recv(buffer, sizeof(buffer))) > 0) {
status = realloc(status, len + i + 1);
memcpy(&status[len], buffer, i);
len += i;
/* stop reading if user-forced or data-starved */
if(i < sizeof(buffer) || (maxbytes && len >= maxbytes))
break;
if (maxbytes && len >= maxbytes)
break;
}
/* no data when expected, so return critical */
if (len == 0)
die (STATE_CRITICAL, _("No data received from host\n"));
/* force null-termination and strip whitespace from end of output */
status[len--] = '\0';
/* print raw output if we're debugging */
if(flags & FLAG_VERBOSE)
printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n",
len + 1, status);
while(isspace(status[len])) status[len--] = '\0';
for (i = 0; i < server_expect_count; i++) {
match = -2; /* tag it so we know if we tried and failed */
if (flags & FLAG_VERBOSE)
printf ("looking for [%s] %s [%s]\n", server_expect[i],
(flags & FLAG_EXACT_MATCH) ? "in beginning of" : "anywhere in",
status);
/* match it. math first in short-circuit */
if ((flags & FLAG_EXACT_MATCH && !strncmp(status, server_expect[i], strlen(server_expect[i]))) ||
(!(flags & FLAG_EXACT_MATCH) && strstr(status, server_expect[i])))
{
if(flags & FLAG_VERBOSE) puts("found it");
match = i;
break;
}
}
}
if (server_quit != NULL) {
#ifdef HAVE_SSL
if (flags & FLAG_SSL) {
SSL_write (ssl, server_quit, (int)strlen(server_quit));
SSL_shutdown (ssl);
SSL_free (ssl);
SSL_CTX_free (ctx);
}
else
#endif
send (sd, server_quit, strlen (server_quit), 0);
}
/* close the connection */
if (sd)
close (sd);
microsec = deltime (tv);
elapsed_time = (double)microsec / 1.0e6;
if (flags & FLAG_TIME_CRIT && elapsed_time > critical_time)
result = STATE_CRITICAL;
else if (flags & FLAG_TIME_WARN && elapsed_time > warning_time)
result = STATE_WARNING;
/* did we get the response we hoped? */
if(match == -2 && result != STATE_CRITICAL)
result = STATE_WARNING;
/* reset the alarm */
alarm (0);
/* this is a bit stupid, because we don't want to print the
* response time (which can look ok to the user) if we didn't get
* the response we were looking for. if-else */
printf(_("%s %s - "), SERVICE, state_text(result));
if(match == -2 && len && !(flags & FLAG_HIDE_OUTPUT))
printf("Unexpected response from host: %s", status);
else
printf("%.3f second response time on port %d",
elapsed_time, server_port);
if (match != -2 && !(flags & FLAG_HIDE_OUTPUT) && len)
printf (" [%s]", status);
/* perf-data doesn't apply when server doesn't talk properly,
* so print all zeroes on warn and crit */
if(match == -2)
printf ("|time=%fs;0.0;0.0;0.0;0.0", elapsed_time);
else
printf("|%s",
fperfdata ("time", elapsed_time, "s",
TRUE, warning_time,
TRUE, critical_time,
TRUE, 0,
TRUE, socket_timeout)
);
putchar('\n');
return result;
}
/* process command-line arguments */
static int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"hostname", required_argument, 0, 'H'},
{"critical-time", required_argument, 0, 'c'},
{"warning-time", required_argument, 0, 'w'},
{"critical-codes", required_argument, 0, 'C'},
{"warning-codes", required_argument, 0, 'W'},
{"timeout", required_argument, 0, 't'},
{"protocol", required_argument, 0, 'P'},
{"port", required_argument, 0, 'p'},
{"send", required_argument, 0, 's'},
{"expect", required_argument, 0, 'e'},
{"maxbytes", required_argument, 0, 'm'},
{"quit", required_argument, 0, 'q'},
{"jail", required_argument, 0, 'j'},
{"delay", required_argument, 0, 'd'},
{"refuse", required_argument, 0, 'r'},
{"mismatch", required_argument, 0, 'M'},
{"use-ipv4", no_argument, 0, '4'},
{"use-ipv6", no_argument, 0, '6'},
{"verbose", no_argument, 0, 'v'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
#ifdef HAVE_SSL
{"ssl", no_argument, 0, 'S'},
{"certificate", required_argument, 0, 'D'},
#endif
{0, 0, 0, 0}
};
if (argc < 2)
usage4 (_("No arguments found"));
/* backwards compatibility */
for (c = 1; c < argc; c++) {
if (strcmp ("-to", argv[c]) == 0)
strcpy (argv[c], "-t");
else if (strcmp ("-wt", argv[c]) == 0)
strcpy (argv[c], "-w");
else if (strcmp ("-ct", argv[c]) == 0)
strcpy (argv[c], "-c");
}
if (!is_option (argv[1])) {
server_address = argv[1];
argv[1] = argv[0];
argv = &argv[1];
argc--;
}
while (1) {
c = getopt_long (argc, argv, "+hVv46H:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:",
longopts, &option);
if (c == -1 || c == EOF || c == 1)
break;
switch (c) {
case '?': /* print short usage statement if args not parsable */
usage2 (_("Unknown argument"), optarg);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'v': /* verbose mode */
flags |= FLAG_VERBOSE;
break;
case '4':
address_family = AF_INET;
break;
case '6':
#ifdef USE_IPV6
address_family = AF_INET6;
#else
usage4 (_("IPv6 support not available"));
#endif
break;
case 'H': /* hostname */
if (is_host (optarg) == FALSE)
usage2 (_("Invalid hostname/address"), optarg);
server_address = optarg;
break;
case 'c': /* critical */
if (!is_intnonneg (optarg))
usage4 (_("Critical threshold must be a positive integer"));
else
critical_time = strtod (optarg, NULL);
flags |= FLAG_TIME_CRIT;
break;
case 'j': /* hide output */
flags |= FLAG_HIDE_OUTPUT;
break;
case 'w': /* warning */
if (!is_intnonneg (optarg))
usage4 (_("Warning threshold must be a positive integer"));
else
warning_time = strtod (optarg, NULL);
flags |= FLAG_TIME_WARN;
break;
case 'C':
crit_codes = realloc (crit_codes, ++crit_codes_count);
crit_codes[crit_codes_count - 1] = optarg;
break;
case 'W':
warn_codes = realloc (warn_codes, ++warn_codes_count);
warn_codes[warn_codes_count - 1] = optarg;
break;
case 't': /* timeout */
if (!is_intpos (optarg))
usage4 (_("Timeout interval must be a positive integer"));
else
socket_timeout = atoi (optarg);
break;
case 'p': /* port */
if (!is_intpos (optarg))
usage4 (_("Port must be a positive integer"));
else
server_port = atoi (optarg);
break;
case 's':
server_send = optarg;
break;
case 'e': /* expect string (may be repeated) */
EXPECT = NULL;
flags &= ~FLAG_EXACT_MATCH;
if (server_expect_count == 0)
server_expect = malloc (sizeof (char *) * (++server_expect_count));
else
server_expect = realloc (server_expect, sizeof (char *) * (++server_expect_count));
server_expect[server_expect_count - 1] = optarg;
break;
case 'm':
if (!is_intpos (optarg))
usage4 (_("Maxbytes must be a positive integer"));
else
maxbytes = strtol (optarg, NULL, 0);
case 'q':
asprintf(&server_quit, "%s\r\n", optarg);
break;
case 'r':
if (!strncmp(optarg,"ok",2))
econn_refuse_state = STATE_OK;
else if (!strncmp(optarg,"warn",4))
econn_refuse_state = STATE_WARNING;
else if (!strncmp(optarg,"crit",4))
econn_refuse_state = STATE_CRITICAL;
else
usage4 (_("Refuse must be one of ok, warn, crit"));
break;
case 'M':
if (!strncmp(optarg,"ok",2))
expect_mismatch_state = STATE_OK;
else if (!strncmp(optarg,"warn",4))
expect_mismatch_state = STATE_WARNING;
else if (!strncmp(optarg,"crit",4))
expect_mismatch_state = STATE_CRITICAL;
else
usage4 (_("Mismatch must be one of ok, warn, crit"));
break;
case 'd':
if (is_intpos (optarg))
delay = atoi (optarg);
else
usage4 (_("Delay must be a positive integer"));
break;
case 'D': /* Check SSL cert validity - days 'til certificate expiration */
#ifdef HAVE_SSL
if (!is_intnonneg (optarg))
usage2 (_("Invalid certificate expiration period"), optarg);
days_till_exp = atoi (optarg);
check_cert = TRUE;
flags |= FLAG_SSL;
break;
#endif
/* fallthrough if we don't have ssl */
case 'S':
#ifdef HAVE_SSL
flags |= FLAG_SSL;
#else
die (STATE_UNKNOWN, _("Invalid option - SSL is not available"));
#endif
break;
}
}
if (server_address == NULL)
usage4 (_("You must provide a server address"));
return TRUE;
}
/* SSL-specific functions */
#ifdef HAVE_SSL
static int
connect_SSL (void)
{
SSL_METHOD *meth;
/* Initialize SSL context */
SSLeay_add_ssl_algorithms ();
meth = SSLv23_client_method ();
SSL_load_error_strings ();
OpenSSL_add_all_algorithms();
if ((ctx = SSL_CTX_new (meth)) == NULL)
{
printf (_("CRITICAL - Cannot create SSL context.\n"));
return STATE_CRITICAL;
}
/* Initialize alarm signal handling */
signal (SIGALRM, socket_timeout_alarm_handler);
/* Set socket timeout */
alarm (socket_timeout);
/* Save start time */
time (&start_time);
/* Make TCP connection */
if (my_tcp_connect (server_address, server_port, &sd) == STATE_OK && was_refused == FALSE)
{
/* Do the SSL handshake */
if ((ssl = SSL_new (ctx)) != NULL)
{
SSL_set_fd (ssl, sd);
if (SSL_connect(ssl) == 1)
return OK;
/* ERR_print_errors_fp (stderr); */
printf (_("CRITICAL - Cannot make SSL connection "));
ERR_print_errors_fp (stdout);
/* printf("\n"); */
}
else
{
printf (_("CRITICAL - Cannot initiate SSL handshake.\n"));
}
SSL_free (ssl);
}
SSL_CTX_free (ctx);
close (sd);
return STATE_CRITICAL;
}
static int
check_certificate (X509 ** certificate)
{
ASN1_STRING *tm;
int offset;
struct tm stamp;
int days_left;
/* Retrieve timestamp of certificate */
tm = X509_get_notAfter (*certificate);
/* Generate tm structure to process timestamp */
if (tm->type == V_ASN1_UTCTIME) {
if (tm->length < 10) {
printf (_("CRITICAL - Wrong time format in certificate.\n"));
return STATE_CRITICAL;
}
else {
stamp.tm_year = (tm->data[0] - '0') * 10 + (tm->data[1] - '0');
if (stamp.tm_year < 50)
stamp.tm_year += 100;
offset = 0;
}
}
else {
if (tm->length < 12) {
printf (_("CRITICAL - Wrong time format in certificate.\n"));
return STATE_CRITICAL;
}
else {
stamp.tm_year =
(tm->data[0] - '0') * 1000 + (tm->data[1] - '0') * 100 +
(tm->data[2] - '0') * 10 + (tm->data[3] - '0');
stamp.tm_year -= 1900;
offset = 2;
}
}
stamp.tm_mon =
(tm->data[2 + offset] - '0') * 10 + (tm->data[3 + offset] - '0') - 1;
stamp.tm_mday =
(tm->data[4 + offset] - '0') * 10 + (tm->data[5 + offset] - '0');
stamp.tm_hour =
(tm->data[6 + offset] - '0') * 10 + (tm->data[7 + offset] - '0');
stamp.tm_min =
(tm->data[8 + offset] - '0') * 10 + (tm->data[9 + offset] - '0');
stamp.tm_sec = 0;
stamp.tm_isdst = -1;
days_left = (mktime (&stamp) - time (NULL)) / 86400;
snprintf
(timestamp, 16, "%02d/%02d/%04d %02d:%02d",
stamp.tm_mon + 1,
stamp.tm_mday, stamp.tm_year + 1900, stamp.tm_hour, stamp.tm_min);
if (days_left > 0 && days_left <= days_till_exp) {
printf (_("Certificate expires in %d day(s) (%s).\n"), days_left, timestamp);
return STATE_WARNING;
}
if (days_left < 0) {
printf (_("Certificate expired on %s.\n"), timestamp);
return STATE_CRITICAL;
}
if (days_left == 0) {
printf (_("Certificate expires today (%s).\n"), timestamp);
return STATE_WARNING;
}
printf (_("Certificate will expire on %s.\n"), timestamp);
return STATE_OK;
}
#endif /* HAVE_SSL */
void
print_help (void)
{
print_revision (progname, revision);
printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
printf (COPYRIGHT, copyright, email);
printf (_("This plugin tests %s connections with the specified host.\n\n"),
SERVICE);
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_(UT_HOST_PORT), 'p', "none");
printf (_(UT_IPv46));
printf (_("\
-s, --send=STRING\n\
String to send to the server\n\
-e, --expect=STRING\n\
String to expect in server response\n\
-q, --quit=STRING\n\
String to send server to initiate a clean close of the connection\n"));
printf (_("\
-r, --refuse=ok|warn|crit\n\
Accept tcp refusals with states ok, warn, crit (default: crit)\n\
-M, --mismatch=ok|warn|crit\n\
Accept expected string mismatches with states ok, warn, crit (default: warn)\n\
-j, --jail\n\
Hide output from TCP socket\n\
-m, --maxbytes=INTEGER\n\
Close connection once more than this number of bytes are received\n\
-d, --delay=INTEGER\n\
Seconds to wait between sending string and polling for response\n"));
#ifdef HAVE_SSL
printf (_("\
-D, --certificate=INTEGER\n\
Minimum number of days a certificate has to be valid.\n\
-S, --ssl\n\
Use SSL for the connection.\n"));
#endif
printf (_(UT_WARN_CRIT));
printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
printf (_(UT_VERBOSE));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s -H host -p port [-w <warning time>] [-c <critical time>]\n\
[-s <send string>] [-e <expect string>] [-q <quit string>]\n\
[-m <maximum bytes>] [-d <delay>] [-t <timeout seconds>]\n\
[-r <refuse state>] [-M <mismatch state>] [-v] [-4|-6] [-j]\n\
[-D <days to cert expiry>] [-S <use SSL>]\n", progname);
}

360
plugins/check_time.c Normal file
View file

@ -0,0 +1,360 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_time.c,v 1.26 2005/05/25 17:42:35 sghosh Exp $
******************************************************************************/
const char *progname = "check_time";
const char *revision = "$Revision: 1.26 $";
const char *copyright = "1999-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "netutils.h"
#include "utils.h"
enum {
TIME_PORT = 37
};
#define UNIX_EPOCH 2208988800UL
uint32_t server_time, raw_server_time;
time_t diff_time;
int warning_time = 0;
int check_warning_time = FALSE;
int critical_time = 0;
int check_critical_time = FALSE;
unsigned long warning_diff = 0;
int check_warning_diff = FALSE;
unsigned long critical_diff = 0;
int check_critical_diff = FALSE;
int server_port = TIME_PORT;
char *server_address = NULL;
int use_udp = FALSE;
int process_arguments (int, char **);
void print_help (void);
void print_usage (void);
int
main (int argc, char **argv)
{
int sd;
int result = STATE_UNKNOWN;
time_t conntime;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* initialize alarm signal handling */
signal (SIGALRM, socket_timeout_alarm_handler);
/* set socket timeout */
alarm (socket_timeout);
time (&start_time);
/* try to connect to the host at the given port number */
if (use_udp) {
result = my_udp_connect (server_address, server_port, &sd);
} else {
result = my_tcp_connect (server_address, server_port, &sd);
}
if (result != STATE_OK) {
if (check_critical_time == TRUE)
result = STATE_CRITICAL;
else if (check_warning_time == TRUE)
result = STATE_WARNING;
else
result = STATE_UNKNOWN;
die (result,
_("TIME UNKNOWN - could not connect to server %s, port %d\n"),
server_address, server_port);
}
if (use_udp) {
if (send (sd, "", 0, 0) < 0) {
if (check_critical_time == TRUE)
result = STATE_CRITICAL;
else if (check_warning_time == TRUE)
result = STATE_WARNING;
else
result = STATE_UNKNOWN;
die (result,
_("TIME UNKNOWN - could not send UDP request to server %s, port %d\n"),
server_address, server_port);
}
}
/* watch for the connection string */
result = recv (sd, (void *)&raw_server_time, sizeof (raw_server_time), 0);
/* close the connection */
close (sd);
/* reset the alarm */
time (&end_time);
alarm (0);
/* return a WARNING status if we couldn't read any data */
if (result <= 0) {
if (check_critical_time == TRUE)
result = STATE_CRITICAL;
else if (check_warning_time == TRUE)
result = STATE_WARNING;
else
result = STATE_UNKNOWN;
die (result,
_("TIME UNKNOWN - no data received from server %s, port %d\n"),
server_address, server_port);
}
result = STATE_OK;
conntime = (end_time - start_time);
if (check_critical_time == TRUE && conntime > critical_time)
result = STATE_CRITICAL;
else if (check_warning_time == TRUE && conntime > warning_time)
result = STATE_WARNING;
if (result != STATE_OK)
die (result, _("TIME %s - %d second response time|%s\n"),
state_text (result), (int)conntime,
perfdata ("time", (long)conntime, "s",
check_warning_time, (long)warning_time,
check_critical_time, (long)critical_time,
TRUE, 0, FALSE, 0));
server_time = ntohl (raw_server_time) - UNIX_EPOCH;
if (server_time > (unsigned long)end_time)
diff_time = server_time - (unsigned long)end_time;
else
diff_time = (unsigned long)end_time - server_time;
if (check_critical_diff == TRUE && diff_time > (time_t)critical_diff)
result = STATE_CRITICAL;
else if (check_warning_diff == TRUE && diff_time > (time_t)warning_diff)
result = STATE_WARNING;
printf (_("TIME %s - %lu second time difference|%s %s\n"),
state_text (result), diff_time,
perfdata ("time", (long)conntime, "s",
check_warning_time, (long)warning_time,
check_critical_time, (long)critical_time,
TRUE, 0, FALSE, 0),
perfdata ("offset", (long)diff_time, "s",
check_warning_diff, (long)warning_diff,
check_critical_diff, (long)critical_diff,
TRUE, 0, FALSE, 0));
return result;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"hostname", required_argument, 0, 'H'},
{"warning-variance", required_argument, 0, 'w'},
{"critical-variance", required_argument, 0, 'c'},
{"warning-connect", required_argument, 0, 'W'},
{"critical-connect", required_argument, 0, 'C'},
{"port", required_argument, 0, 'p'},
{"udp", no_argument, 0, 'u'},
{"timeout", required_argument, 0, 't'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
if (argc < 2)
usage ("\n");
for (c = 1; c < argc; c++) {
if (strcmp ("-to", argv[c]) == 0)
strcpy (argv[c], "-t");
else if (strcmp ("-wd", argv[c]) == 0)
strcpy (argv[c], "-w");
else if (strcmp ("-cd", argv[c]) == 0)
strcpy (argv[c], "-c");
else if (strcmp ("-wt", argv[c]) == 0)
strcpy (argv[c], "-W");
else if (strcmp ("-ct", argv[c]) == 0)
strcpy (argv[c], "-C");
}
while (1) {
c = getopt_long (argc, argv, "hVH:w:c:W:C:p:t:u", longopts,
&option);
if (c == -1 || c == EOF)
break;
switch (c) {
case '?': /* print short usage statement if args not parsable */
usage2 (_("Unknown argument"), optarg);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'H': /* hostname */
if (is_host (optarg) == FALSE)
usage2 (_("Invalid hostname/address"), optarg);
server_address = optarg;
break;
case 'w': /* warning-variance */
if (is_intnonneg (optarg)) {
warning_diff = strtoul (optarg, NULL, 10);
check_warning_diff = TRUE;
}
else if (strspn (optarg, "0123456789:,") > 0) {
if (sscanf (optarg, "%lu%*[:,]%d", &warning_diff, &warning_time) == 2) {
check_warning_diff = TRUE;
check_warning_time = TRUE;
}
else {
usage4 (_("Warning thresholds must be a positive integer"));
}
}
else {
usage4 (_("Warning threshold must be a positive integer"));
}
break;
case 'c': /* critical-variance */
if (is_intnonneg (optarg)) {
critical_diff = strtoul (optarg, NULL, 10);
check_critical_diff = TRUE;
}
else if (strspn (optarg, "0123456789:,") > 0) {
if (sscanf (optarg, "%lu%*[:,]%d", &critical_diff, &critical_time) ==
2) {
check_critical_diff = TRUE;
check_critical_time = TRUE;
}
else {
usage4 (_("Critical thresholds must be a positive integer"));
}
}
else {
usage4 (_("Critical threshold must be a positive integer"));
}
break;
case 'W': /* warning-connect */
if (!is_intnonneg (optarg))
usage4 (_("Warning threshold must be a positive integer"));
else
warning_time = atoi (optarg);
check_warning_time = TRUE;
break;
case 'C': /* critical-connect */
if (!is_intnonneg (optarg))
usage4 (_("Critical threshold must be a positive integer"));
else
critical_time = atoi (optarg);
check_critical_time = TRUE;
break;
case 'p': /* port */
if (!is_intnonneg (optarg))
usage4 (_("Port must be a positive integer"));
else
server_port = atoi (optarg);
break;
case 't': /* timeout */
if (!is_intnonneg (optarg))
usage2 (_("Timeout interval must be a positive integer"), optarg);
else
socket_timeout = atoi (optarg);
break;
case 'u': /* udp */
use_udp = TRUE;
}
}
c = optind;
if (server_address == NULL) {
if (argc > c) {
if (is_host (argv[c]) == FALSE)
usage2 (_("Invalid hostname/address"), optarg);
server_address = argv[c];
}
else {
usage4 (_("Hostname was not supplied"));
}
}
return OK;
}
void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", TIME_PORT);
print_revision (progname, revision);
printf ("Copyright (c) 1999 Ethan Galstad\n");
printf (COPYRIGHT, copyright, email);
printf (_("This plugin will check the time on the specified host.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_(UT_HOST_PORT), 'p', myport);
printf (_("\
-u, --udp\n\
Use UDP to connect, not TCP\n\
-w, --warning-variance=INTEGER\n\
Time difference (sec.) necessary to result in a warning status\n\
-c, --critical-variance=INTEGER\n\
Time difference (sec.) necessary to result in a critical status\n\
-W, --warning-connect=INTEGER\n\
Response time (sec.) necessary to result in warning status\n\
-C, --critical-connect=INTEGER\n\
Response time (sec.) necessary to result in critical status\n"));
printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s -H <host_address> [-p port] [-u] [-w variance] [-c variance]\n\
[-W connect_time] [-C connect_time] [-t timeout]\n", progname);
}

264
plugins/check_udp.c Normal file
View file

@ -0,0 +1,264 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_udp.c,v 1.25 2004/12/25 23:17:44 opensides Exp $
*****************************************************************************/
const char *progname = "check_udp";
const char *revision = "$Revision: 1.25 $";
const char *copyright = "1999-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "netutils.h"
#include "utils.h"
int process_arguments (int, char **);
void print_help (void);
void print_usage (void);
int warning_time = 0;
int check_warning_time = FALSE;
int critical_time = 0;
int check_critical_time = FALSE;
int verbose = FALSE;
int server_port = 0;
char *server_address = NULL;
char *server_expect = NULL;
char *server_send;
int
main (int argc, char **argv)
{
int result = STATE_UNKNOWN;
char recv_buffer[MAX_INPUT_BUFFER];
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* initialize alarm signal handling */
signal (SIGALRM, socket_timeout_alarm_handler);
/* set socket timeout */
alarm (socket_timeout);
time (&start_time);
result = process_udp_request (server_address, server_port, server_send,
recv_buffer, MAX_INPUT_BUFFER - 1);
time (&end_time);
if (result != STATE_OK) {
printf (_("No response from host on port %d\n"), server_port);
result = STATE_CRITICAL;
}
else {
/* check to see if we got the response we wanted */
if (server_expect) {
if (!strstr (recv_buffer, server_expect)) {
printf (_("Invalid response received from host on port %d\n"),
server_port);
result = STATE_CRITICAL;
}
}
}
/* we connected, so close connection before exiting */
if (result == STATE_OK) {
if (check_critical_time == TRUE
&& (end_time - start_time) > critical_time) result = STATE_CRITICAL;
else if (check_warning_time == TRUE
&& (end_time - start_time) > warning_time) result =
STATE_WARNING;
printf (_("Connection %s on port %d - %d second response time\n"),
(result == STATE_OK) ? _("accepted") : _("problem"), server_port,
(int) (end_time - start_time));
}
/* reset the alarm */
alarm (0);
return result;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"hostname", required_argument, 0, 'H'},
{"critical", required_argument, 0, 'c'},
{"warning", required_argument, 0, 'w'},
{"timeout", required_argument, 0, 't'},
{"port", required_argument, 0, 'p'},
{"expect", required_argument, 0, 'e'},
{"send", required_argument, 0, 's'},
{"verbose", no_argument, 0, 'v'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
if (argc < 2)
usage ("\n");
for (c = 1; c < argc; c++) {
if (strcmp ("-to", argv[c]) == 0)
strcpy (argv[c], "-t");
else if (strcmp ("-wt", argv[c]) == 0)
strcpy (argv[c], "-w");
else if (strcmp ("-ct", argv[c]) == 0)
strcpy (argv[c], "-c");
}
while (1) {
c = getopt_long (argc, argv, "+hVvH:e:s:c:w:t:p:", longopts, &option);
if (c == -1 || c == EOF || c == 1)
break;
switch (c) {
case '?': /* print short usage statement if args not parsable */
usage2 (_("Unknown argument"), optarg);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'v': /* verbose mode */
verbose = TRUE;
break;
case 'H': /* hostname */
if (is_host (optarg) == FALSE)
usage2 (_("Invalid hostname/address"), optarg);
server_address = optarg;
break;
case 'c': /* critical */
if (!is_intnonneg (optarg))
usage4 (_("Critical threshold must be a positive integer"));
else
critical_time = atoi (optarg);
check_critical_time = TRUE;
break;
case 'w': /* warning */
if (!is_intnonneg (optarg))
usage4 (_("Warning threshold must be a positive integer"));
else
warning_time = atoi (optarg);
check_warning_time = TRUE;
break;
case 't': /* timeout */
if (!is_intnonneg (optarg))
usage2 (_("Timeout interval must be a positive integer"), optarg);
else
socket_timeout = atoi (optarg);
break;
case 'p': /* port */
if (!is_intnonneg (optarg))
usage4 (_("Port must be a positive integer"));
else
server_port = atoi (optarg);
break;
case 'e': /* expect */
server_expect = optarg;
break;
case 's': /* send */
server_send = optarg;
break;
}
}
c = optind;
if (server_address == NULL && c < argc && argv[c]) {
if (is_host (argv[c]) == FALSE)
usage2 (_("Invalid hostname/address"), optarg);
server_address = argv[c++];
}
if (server_address == NULL)
usage4 (_("Hostname was not supplied"));
if (server_send == NULL)
server_send = strdup("");
return c;
}
void
print_help (void)
{
print_revision (progname, revision);
printf ("Copyright (c) 1999 Ethan Galstad\n");
printf (COPYRIGHT, copyright, email);
printf (_("\
This plugin tests an UDP connection with the specified host.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_(UT_HOST_PORT), 'p', "none");
printf (_("\
-e, --expect=STRING <optional>\n\
String to expect in first line of server response\n\
-s, --send=STRING <optional>\n\
String to send to the server when initiating the connection\n"));
printf (_(UT_WARN_CRIT));
printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
printf (_(UT_VERBOSE));
printf (_("\
This plugin will attempt to connect to the specified port on the host.\n\
Successful connects return STATE_OK, refusals and timeouts return\n\
STATE_CRITICAL, other errors return STATE_UNKNOWN.\n\n"));
printf(_(UT_SUPPORT));
}
/* Original Command line:
check_udp <host_address> [-p port] [-s send] [-e expect] \
[-wt warn_time] [-ct crit_time] [-to to_sec] */
void
print_usage (void)
{
printf ("\
Usage: %s -H <host_address> [-p port] [-w warn_time] [-c crit_time]\n\
[-e expect] [-s send] [-t to_sec] [-v]\n", progname);
}

646
plugins/check_ups.c Normal file
View file

@ -0,0 +1,646 @@
/******************************************************************************
check_ups
Program: Network UPS Tools plugin for Nagios
License: GPL
Copyright (c) 2000 Tom Shields
2004 Alain Richard <alain.richard@equation.fr>
2004 Arnaud Quette <arnaud.quette@mgeups.com>
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_ups.c,v 1.27 2005/03/04 21:58:40 tonvoon Exp $
******************************************************************************/
const char *progname = "check_ups";
const char *revision = "$Revision: 1.27 $";
const char *copyright = "2000-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "netutils.h"
#include "utils.h"
enum {
PORT = 3493
};
#define CHECK_NONE 0
#define UPS_NONE 0 /* no supported options */
#define UPS_UTILITY 1 /* supports utility line voltage */
#define UPS_BATTPCT 2 /* supports percent battery remaining */
#define UPS_STATUS 4 /* supports UPS status */
#define UPS_TEMP 8 /* supports UPS temperature */
#define UPS_LOADPCT 16 /* supports load percent */
#define UPSSTATUS_NONE 0
#define UPSSTATUS_OFF 1
#define UPSSTATUS_OL 2
#define UPSSTATUS_OB 4
#define UPSSTATUS_LB 8
#define UPSSTATUS_CAL 16
#define UPSSTATUS_RB 32 /*Replace Battery */
#define UPSSTATUS_BYPASS 64
#define UPSSTATUS_OVER 128
#define UPSSTATUS_TRIM 256
#define UPSSTATUS_BOOST 512
#define UPSSTATUS_CHRG 1024
#define UPSSTATUS_DISCHRG 2048
#define UPSSTATUS_UNKOWN 4096
enum { NOSUCHVAR = ERROR-1 };
int server_port = PORT;
char *server_address;
char *ups_name = NULL;
double warning_value = 0.0;
double critical_value = 0.0;
int check_warn = FALSE;
int check_crit = FALSE;
int check_variable = UPS_NONE;
int supported_options = UPS_NONE;
int status = UPSSTATUS_NONE;
double ups_utility_voltage = 0.0;
double ups_battery_percent = 0.0;
double ups_load_percent = 0.0;
double ups_temperature = 0.0;
char *ups_status;
int temp_output_c = 0;
int determine_status (void);
int get_ups_variable (const char *, char *, size_t);
int process_arguments (int, char **);
int validate_arguments (void);
void print_help (void);
void print_usage (void);
int
main (int argc, char **argv)
{
int result = STATE_UNKNOWN;
char *message;
char *data;
char temp_buffer[MAX_INPUT_BUFFER];
double ups_utility_deviation = 0.0;
int res;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
ups_status = strdup ("N/A");
data = strdup ("");
message = strdup ("");
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* initialize alarm signal handling */
signal (SIGALRM, socket_timeout_alarm_handler);
/* set socket timeout */
alarm (socket_timeout);
/* get the ups status if possible */
if (determine_status () != OK)
return STATE_CRITICAL;
if (supported_options & UPS_STATUS) {
ups_status = strdup ("");
result = STATE_OK;
if (status & UPSSTATUS_OFF) {
asprintf (&ups_status, "Off");
result = STATE_CRITICAL;
}
else if ((status & (UPSSTATUS_OB | UPSSTATUS_LB)) ==
(UPSSTATUS_OB | UPSSTATUS_LB)) {
asprintf (&ups_status, _("On Battery, Low Battery"));
result = STATE_CRITICAL;
}
else {
if (status & UPSSTATUS_OL) {
asprintf (&ups_status, "%s%s", ups_status, _("Online"));
}
if (status & UPSSTATUS_OB) {
asprintf (&ups_status, "%s%s", ups_status, _("On Battery"));
result = STATE_WARNING;
}
if (status & UPSSTATUS_LB) {
asprintf (&ups_status, "%s%s", ups_status, _(", Low Battery"));
result = STATE_WARNING;
}
if (status & UPSSTATUS_CAL) {
asprintf (&ups_status, "%s%s", ups_status, _(", Calibrating"));
}
if (status & UPSSTATUS_RB) {
asprintf (&ups_status, "%s%s", ups_status, _(", Replace Battery"));
result = STATE_WARNING;
}
if (status & UPSSTATUS_BYPASS) {
asprintf (&ups_status, "%s%s", ups_status, _(", On Bypass"));
}
if (status & UPSSTATUS_OVER) {
asprintf (&ups_status, "%s%s", ups_status, _(", Overload"));
}
if (status & UPSSTATUS_TRIM) {
asprintf (&ups_status, "%s%s", ups_status, _(", Trimming"));
}
if (status & UPSSTATUS_BOOST) {
asprintf (&ups_status, "%s%s", ups_status, _(", Boosting"));
}
if (status & UPSSTATUS_CHRG) {
asprintf (&ups_status, "%s%s", ups_status, _(", Charging"));
}
if (status & UPSSTATUS_DISCHRG) {
asprintf (&ups_status, "%s%s", ups_status, _(", Discharging"));
}
if (status & UPSSTATUS_UNKOWN) {
asprintf (&ups_status, "%s%s", ups_status, _(", Unknown"));
}
}
asprintf (&message, "%sStatus=%s ", message, ups_status);
}
/* get the ups utility voltage if possible */
res=get_ups_variable ("input.voltage", temp_buffer, sizeof (temp_buffer));
if (res == NOSUCHVAR) supported_options &= ~UPS_UTILITY;
else if (res != OK)
return STATE_CRITICAL;
else {
supported_options |= UPS_UTILITY;
ups_utility_voltage = atof (temp_buffer);
asprintf (&message, "%sUtility=%3.1fV ", message, ups_utility_voltage);
if (ups_utility_voltage > 120.0)
ups_utility_deviation = 120.0 - ups_utility_voltage;
else
ups_utility_deviation = ups_utility_voltage - 120.0;
if (check_variable == UPS_UTILITY) {
if (check_crit==TRUE && ups_utility_deviation>=critical_value) {
result = STATE_CRITICAL;
}
else if (check_warn==TRUE && ups_utility_deviation>=warning_value) {
result = max_state (result, STATE_WARNING);
}
asprintf (&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",
perfdata ("voltage", (long)(1000*ups_utility_voltage), "mV",
FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
}
}
/* get the ups battery percent if possible */
res=get_ups_variable ("battery.charge", temp_buffer, sizeof (temp_buffer));
if (res == NOSUCHVAR) supported_options &= ~UPS_BATTPCT;
else if ( res != OK)
return STATE_CRITICAL;
else {
supported_options |= UPS_BATTPCT;
ups_battery_percent = atof (temp_buffer);
asprintf (&message, "%sBatt=%3.1f%% ", message, ups_battery_percent);
if (check_variable == UPS_BATTPCT) {
if (check_crit==TRUE && ups_battery_percent <= critical_value) {
result = STATE_CRITICAL;
}
else if (check_warn==TRUE && ups_battery_percent<=warning_value) {
result = max_state (result, STATE_WARNING);
}
asprintf (&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,
perfdata ("battery", (long)ups_battery_percent, "%",
FALSE, 0, FALSE, 0, TRUE, 0, TRUE, 100));
}
}
/* get the ups load percent if possible */
res=get_ups_variable ("ups.load", temp_buffer, sizeof (temp_buffer));
if ( res == NOSUCHVAR ) supported_options &= ~UPS_LOADPCT;
else if ( res != OK)
return STATE_CRITICAL;
else {
supported_options |= UPS_LOADPCT;
ups_load_percent = atof (temp_buffer);
asprintf (&message, "%sLoad=%3.1f%% ", message, ups_load_percent);
if (check_variable == UPS_LOADPCT) {
if (check_crit==TRUE && ups_load_percent>=critical_value) {
result = STATE_CRITICAL;
}
else if (check_warn==TRUE && ups_load_percent>=warning_value) {
result = max_state (result, STATE_WARNING);
}
asprintf (&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,
perfdata ("load", (long)ups_load_percent, "%",
FALSE, 0, FALSE, 0, TRUE, 0, TRUE, 100));
}
}
/* get the ups temperature if possible */
res=get_ups_variable ("ups.temperature", temp_buffer, sizeof (temp_buffer));
if ( res == NOSUCHVAR ) supported_options &= ~UPS_TEMP;
else if ( res != OK)
return STATE_CRITICAL;
else {
supported_options |= UPS_TEMP;
if (temp_output_c) {
ups_temperature = atof (temp_buffer);
asprintf (&message, "%sTemp=%3.1fC", message, ups_temperature);
}
else {
ups_temperature = (atof (temp_buffer) * 1.8) + 32;
asprintf (&message, "%sTemp=%3.1fF", message, ups_temperature);
}
if (check_variable == UPS_TEMP) {
if (check_crit==TRUE && ups_temperature>=critical_value) {
result = STATE_CRITICAL;
}
else if (check_warn == TRUE && ups_temperature>=warning_value) {
result = max_state (result, STATE_WARNING);
}
asprintf (&data, "%s %s", data,
perfdata ("temp", (long)ups_temperature, "degF",
check_warn, (long)(1000*warning_value),
check_crit, (long)(1000*critical_value),
TRUE, 0, FALSE, 0));
} else {
asprintf (&data, "%s %s", data,
perfdata ("temp", (long)ups_temperature, "degF",
FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
}
}
/* 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"));
}
/* reset timeout */
alarm (0);
printf ("UPS %s - %s|%s\n", state_text(result), message, data);
return result;
}
/* determines what options are supported by the UPS */
int
determine_status (void)
{
char recv_buffer[MAX_INPUT_BUFFER];
char temp_buffer[MAX_INPUT_BUFFER];
char *ptr;
int res;
res=get_ups_variable ("ups.status", recv_buffer, sizeof (recv_buffer));
if (res == NOSUCHVAR) return OK;
if (res != STATE_OK) {
printf (_("Invalid response received from host\n"));
return ERROR;
}
supported_options |= UPS_STATUS;
strcpy (temp_buffer, recv_buffer);
for (ptr = (char *) strtok (temp_buffer, " "); ptr != NULL;
ptr = (char *) strtok (NULL, " ")) {
if (!strcmp (ptr, "OFF"))
status |= UPSSTATUS_OFF;
else if (!strcmp (ptr, "OL"))
status |= UPSSTATUS_OL;
else if (!strcmp (ptr, "OB"))
status |= UPSSTATUS_OB;
else if (!strcmp (ptr, "LB"))
status |= UPSSTATUS_LB;
else if (!strcmp (ptr, "CAL"))
status |= UPSSTATUS_CAL;
else if (!strcmp (ptr, "RB"))
status |= UPSSTATUS_RB;
else if (!strcmp (ptr, "BYPASS"))
status |= UPSSTATUS_BYPASS;
else if (!strcmp (ptr, "OVER"))
status |= UPSSTATUS_OVER;
else if (!strcmp (ptr, "TRIM"))
status |= UPSSTATUS_TRIM;
else if (!strcmp (ptr, "BOOST"))
status |= UPSSTATUS_BOOST;
else if (!strcmp (ptr, "CHRG"))
status |= UPSSTATUS_CHRG;
else if (!strcmp (ptr, "DISCHRG"))
status |= UPSSTATUS_DISCHRG;
else
status |= UPSSTATUS_UNKOWN;
}
return OK;
}
/* gets a variable value for a specific UPS */
int
get_ups_variable (const char *varname, char *buf, size_t buflen)
{
/* char command[MAX_INPUT_BUFFER]; */
char temp_buffer[MAX_INPUT_BUFFER];
char send_buffer[MAX_INPUT_BUFFER];
char *ptr;
int len;
*buf=0;
/* create the command string to send to the UPS daemon */
sprintf (send_buffer, "GET VAR %s %s\n", ups_name, varname);
/* send the command to the daemon and get a response back */
if (process_tcp_request
(server_address, server_port, send_buffer, temp_buffer,
sizeof (temp_buffer)) != STATE_OK) {
printf (_("Invalid response received from host\n"));
return ERROR;
}
ptr = temp_buffer;
len = strlen(ptr);
if (len > 0 && ptr[len-1] == '\n') ptr[len-1]=0;
if (strcmp (ptr, "ERR UNKNOWN-UPS") == 0) {
printf (_("CRITICAL - no such ups '%s' on that host\n"), ups_name);
return ERROR;
}
if (strcmp (ptr, "ERR VAR-NOT-SUPPORTED") == 0) {
/*printf ("Error: Variable '%s' is not supported\n", varname);*/
return NOSUCHVAR;
}
if (strcmp (ptr, "ERR DATA-STALE") == 0) {
printf (_("CRITICAL - UPS data is stale\n"));
return ERROR;
}
if (strncmp (ptr, "ERR", 3) == 0) {
printf (_("Unknown error: %s\n"), ptr);
return ERROR;
}
ptr = temp_buffer + strlen (varname) + strlen (ups_name) + 6;
len = strlen(ptr);
if (len < 2 || ptr[0] != '"' || ptr[len-1] != '"') {
printf (_("Error: unable to parse variable\n"));
return ERROR;
}
strncpy (buf, ptr+1, len - 2);
buf[len - 2] = 0;
return OK;
}
/* Command line: CHECK_UPS -H <host_address> -u ups [-p port] [-v variable]
[-wv warn_value] [-cv crit_value] [-to to_sec] */
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"hostname", required_argument, 0, 'H'},
{"ups", required_argument, 0, 'u'},
{"port", required_argument, 0, 'p'},
{"critical", required_argument, 0, 'c'},
{"warning", required_argument, 0, 'w'},
{"timeout", required_argument, 0, 't'},
{"temperature", no_argument, 0, 'T'},
{"variable", required_argument, 0, 'v'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
if (argc < 2)
return ERROR;
for (c = 1; c < argc; c++) {
if (strcmp ("-to", argv[c]) == 0)
strcpy (argv[c], "-t");
else if (strcmp ("-wt", argv[c]) == 0)
strcpy (argv[c], "-w");
else if (strcmp ("-ct", argv[c]) == 0)
strcpy (argv[c], "-c");
}
while (1) {
c = getopt_long (argc, argv, "hVTH:u:p:v:c:w:t:", longopts,
&option);
if (c == -1 || c == EOF)
break;
switch (c) {
case '?': /* help */
usage2 (_("Unknown argument"), optarg);
case 'H': /* hostname */
if (is_host (optarg)) {
server_address = optarg;
}
else {
usage2 (_("Invalid hostname/address"), optarg);
}
break;
case 'T': /* FIXME: to be improved (ie "-T C" for Celsius or "-T F" for Farenheit) */
temp_output_c = 1;
break;
case 'u': /* ups name */
ups_name = optarg;
break;
case 'p': /* port */
if (is_intpos (optarg)) {
server_port = atoi (optarg);
}
else {
usage2 (_("Port must be a positive integer"), optarg);
}
break;
case 'c': /* critical time threshold */
if (is_intnonneg (optarg)) {
critical_value = atoi (optarg);
check_crit = TRUE;
}
else {
usage2 (_("Critical time must be a positive integer"), optarg);
}
break;
case 'w': /* warning time threshold */
if (is_intnonneg (optarg)) {
warning_value = atoi (optarg);
check_warn = TRUE;
}
else {
usage2 (_("Warning time must be a positive integer"), optarg);
}
break;
case 'v': /* variable */
if (!strcmp (optarg, "LINE"))
check_variable = UPS_UTILITY;
else if (!strcmp (optarg, "TEMP"))
check_variable = UPS_TEMP;
else if (!strcmp (optarg, "BATTPCT"))
check_variable = UPS_BATTPCT;
else if (!strcmp (optarg, "LOADPCT"))
check_variable = UPS_LOADPCT;
else
usage2 (_("Unrecognized UPS variable"), optarg);
break;
case 't': /* timeout */
if (is_intnonneg (optarg)) {
socket_timeout = atoi (optarg);
}
else {
usage4 (_("Timeout interval must be a positive integer"));
}
break;
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'h': /* help */
print_help ();
exit (STATE_OK);
}
}
if (server_address == NULL && argc > optind) {
if (is_host (argv[optind]))
server_address = argv[optind++];
else
usage2 (_("Invalid hostname/address"), optarg);
}
if (server_address == NULL)
server_address = strdup("127.0.0.1");
return validate_arguments();
}
int
validate_arguments (void)
{
if (! ups_name) {
printf (_("Error : no ups indicated\n"));
return ERROR;
}
return OK;
}
void
print_help (void)
{
char *myport;
asprintf (&myport, "%d", PORT);
print_revision (progname, revision);
printf ("Copyright (c) 2000 Tom Shields");
printf ("Copyright (c) 2004 Alain Richard <alain.richard@equation.fr>\n");
printf ("Copyright (c) 2004 Arnaud Quette <arnaud.quette@mgeups.com>\n");
printf (COPYRIGHT, copyright, email);
printf (_("This plugin tests the UPS service on the specified host.\n\
Network UPS Tools from www.networkupstools.org must be running for this\n\
plugin to work.\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_(UT_HOST_PORT), 'p', myport);
printf (_("\
-u, --ups=STRING\n\
Name of UPS\n"));
printf (_("\
-T, --temperature\n\
Output of temperatures in Celsius\n"));
printf (_(UT_WARN_CRIT));
printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
printf (_(UT_VERBOSE));
printf (_("\
This plugin attempts to determine the status of a UPS (Uninterruptible Power\n\
Supply) on a local or remote host. If the UPS is online or calibrating, the\n\
plugin will return an OK state. If the battery is on it will return a WARNING\n\
state. If the UPS is off or has a low battery the plugin will return a CRITICAL\n\
state.\n\n"));
printf (_("\
You may also specify a variable to check [such as temperature, utility voltage,\n\
battery load, etc.] as well as warning and critical thresholds for the value of\n\
that variable. If the remote host has multiple UPS that are being monitored you\n\
will have to use the [ups] option to specify which UPS to check.\n\n"));
printf (_("Notes:\n\n\
This plugin requires that the UPSD daemon distributed with Russel Kroll's\n\
Smart UPS Tools be installed on the remote host. If you do not have the\n\
package installed on your system, you can download it from\n\
http://www.networkupstools.org\n\n"));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("\
Usage: %s -H host -u ups [-p port] [-v variable]\n\
[-wv warn_value] [-cv crit_value] [-to to_sec] [-T]\n", progname);
}

215
plugins/check_users.c Normal file
View file

@ -0,0 +1,215 @@
/*****************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: check_users.c,v 1.19 2004/12/25 23:17:44 opensides Exp $
*****************************************************************************/
const char *progname = "check_users";
const char *revision = "$Revision: 1.19 $";
const char *copyright = "2000-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "popen.h"
#include "utils.h"
#define possibly_set(a,b) ((a) == 0 ? (b) : 0)
int process_arguments (int, char **);
void print_help (void);
void print_usage (void);
int wusers = -1;
int cusers = -1;
int
main (int argc, char **argv)
{
int users = -1;
int result = STATE_UNKNOWN;
char input_buffer[MAX_INPUT_BUFFER];
char *perf;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
perf = strdup("");
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* 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);
users = 0;
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);
/* else check the user count against warning and critical thresholds */
if (users >= cusers)
result = STATE_CRITICAL;
else if (users >= wusers)
result = STATE_WARNING;
else if (users >= 0)
result = STATE_OK;
if (result == STATE_UNKNOWN)
printf (_("Unable to read output\n"));
else {
asprintf(&perf, "%s", perfdata ("users", users, "",
TRUE, wusers,
TRUE, cusers,
TRUE, 0,
FALSE, 0));
printf (_("USERS %s - %d users currently logged in |%s\n"), state_text (result),
users, perf);
}
return result;
}
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"critical", required_argument, 0, 'c'},
{"warning", required_argument, 0, 'w'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
if (argc < 2)
usage ("\n");
while (1) {
c = getopt_long (argc, argv, "+hVvc:w:", longopts, &option);
if (c == -1 || c == EOF || c == 1)
break;
switch (c) {
case '?': /* print short usage statement if args not parsable */
usage2 (_("Unknown argument"), optarg);
case 'h': /* help */
print_help ();
exit (STATE_OK);
case 'V': /* version */
print_revision (progname, revision);
exit (STATE_OK);
case 'c': /* critical */
if (!is_intnonneg (optarg))
usage4 (_("Critical threshold must be a positive integer"));
else
cusers = atoi (optarg);
break;
case 'w': /* warning */
if (!is_intnonneg (optarg))
usage4 (_("Warning threshold must be a positive integer"));
else
wusers = atoi (optarg);
break;
}
}
c = optind;
if (wusers == -1 && argc > c) {
if (is_intnonneg (argv[c]) == FALSE)
usage4 (_("Warning threshold must be a positive integer"));
else
wusers = atoi (argv[c++]);
}
if (cusers == -1 && argc > c) {
if (is_intnonneg (argv[c]) == FALSE)
usage4 (_("Warning threshold must be a positive integer"));
else
cusers = atoi (argv[c]);
}
return OK;
}
void
print_help (void)
{
print_revision (progname, revision);
printf ("Copyright (c) 1999 Ethan Galstad\n");
printf (COPYRIGHT, copyright, email);
printf (_("\
This plugin checks the number of users currently logged in on the local\n\
system and generates an error if the number exceeds the thresholds specified.\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_("\
-w, --warning=INTEGER\n\
Set WARNING status if more than INTEGER users are logged in\n\
-c, --critical=INTEGER\n\
Set CRITICAL status if more than INTEGER users are logged in\n"));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("Usage: %s -w <users> -c <users>\n", progname);
}

193
plugins/common.h Normal file
View file

@ -0,0 +1,193 @@
/******************************************************************************
*
* Nagios plugins common include file
*
* License: GPL
* Copyright (c) 1999 Ethan Galstad (nagios@nagios.org)
*
* Last Modified: 11-05-1999
*
* Description:
*
* This file contains common include files and defines used in many of
* the plugins.
*
* License Information:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id: common.h,v 1.15 2004/12/10 00:13:43 tonvoon Exp $
*
*****************************************************************************/
#include "config.h"
#ifdef HAVE_FEATURES_H
#include <features.h>
#endif
#include <stdio.h> /* obligatory includes */
#include <stdlib.h>
#include <errno.h>
#ifdef HUGE_VAL_NEEDS_MATH_H
#include <math.h>
#endif
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
/* TODO: define can be removed when all ifdef in each plugin has been removed */
#define HAVE_GETOPT_H
#include <getopt.h>
#include <ctype.h>
#ifdef HAVE_LWRES_NETDB_H
#include <lwres/netdb.h>
#else
# if !HAVE_GETADDRINFO
# include "getaddrinfo.h"
# else
# include <netdb.h>
# endif
#endif
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
#ifdef HAVE_DECL_SWAPCTL
# ifdef HAVE_SYS_SWAP_H
# include <sys/swap.h>
# endif
# ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
# endif
# ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
# endif
#endif
#ifndef SWAP_CONVERSION
# define SWAP_CONVERSION 1
#endif
/*
*
* Missing Functions
*
*/
#ifndef HAVE_STRTOL
# define strtol(a,b,c) atol((a))
#endif
#ifndef HAVE_STRTOUL
# define strtoul(a,b,c) (unsigned long)atol((a))
#endif
#ifndef HAVE_ASPRINTF
int asprintf(char **strp, const char *fmt, ...);
#endif
#ifndef HAVE_VASPRINTF
/* int vasprintf(char **strp, const char *fmt, va_list ap); */
#endif
#ifndef HAVE_SNPRINTF
int snprintf(char *str, size_t size, const char *format, ...);
#endif
#ifndef HAVE_VSNPRINTF
int vsnprintf(char *str, size_t size, const char *format, va_list ap);
#endif
/*
*
* Standard Values
*
*/
enum {
OK = 0,
ERROR = -1
};
/* AIX seems to have this defined somewhere else */
#ifndef FALSE
enum {
FALSE,
TRUE
};
#endif
enum {
STATE_OK,
STATE_WARNING,
STATE_CRITICAL,
STATE_UNKNOWN,
STATE_DEPENDENT
};
enum {
DEFAULT_SOCKET_TIMEOUT = 10, /* timeout after 10 seconds */
MAX_INPUT_BUFFER = 1024, /* max size of most buffers we use */
MAX_HOST_ADDRESS_LENGTH = 256 /* max size of a host address */
};
/*
*
* Internationalization
*
*/
#include "gettext.h"
#define _(String) gettext (String)
/* For non-GNU compilers to ignore __attribute__ */
#ifndef __GNUC__
# define __attribute__(x) /* do nothing */
#endif

305
plugins/getaddrinfo.c Normal file
View file

@ -0,0 +1,305 @@
/*
* This file is part of libESMTP, a library for submission of RFC 2822
* formatted electronic mail messages using the SMTP protocol described
* in RFC 2821.
* Modified by Jeremy T. Bouse for use in Nagios plugins
*
* Copyright (C) 2001,2002 Brian Stafford <brian@stafford.uklinux.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* An emulation of the RFC 2553 / Posix getaddrinfo resolver interface.
*
* $Id: getaddrinfo.c,v 1.2 2004/12/01 23:54:51 opensides Exp $
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/* Need to turn off Posix features in glibc to build this */
#undef _POSIX_C_SOURCE
#undef _XOPEN_SOURCE
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include "gethostbyname.h"
#include "getaddrinfo.h"
static struct addrinfo *
dup_addrinfo (struct addrinfo *info, void *addr, size_t addrlen)
{
struct addrinfo *ret;
ret = malloc (sizeof (struct addrinfo));
if (ret == NULL)
return NULL;
memcpy (ret, info, sizeof (struct addrinfo));
ret->ai_addr = malloc (addrlen);
if (ret->ai_addr == NULL)
{
free (ret);
return NULL;
}
memcpy (ret->ai_addr, addr, addrlen);
ret->ai_addrlen = addrlen;
return ret;
}
int
getaddrinfo (const char *nodename, const char *servname,
const struct addrinfo *hints, struct addrinfo **res)
{
struct hostent *hp;
struct servent *servent;
const char *socktype;
int port;
struct addrinfo hint, result;
struct addrinfo *ai, *sai, *eai;
struct ghbnctx ghbnctx;
char **addrs;
int code;
memset (&result, 0, sizeof result);
/* default for hints */
if (hints == NULL)
{
memset (&hint, 0, sizeof hint);
hint.ai_family = PF_UNSPEC;
hints = &hint;
}
result.ai_socktype = hints->ai_socktype;
/* Note: maintain port in host byte order to make debugging easier */
if (servname != NULL) {
if (isdigit (*servname))
port = strtol (servname, NULL, 10);
else if ((servent = getservbyname (servname, socktype)) != NULL)
port = ntohs (servent->s_port);
else
return EAI_NONAME;
}
/* if nodename == NULL refer to the local host for a client or any
for a server */
if (nodename == NULL)
{
struct sockaddr_in sin;
/* check protocol family is PF_UNSPEC or PF_INET - could try harder
for IPv6 but that's more code than I'm prepared to write */
if (hints->ai_family == PF_UNSPEC || hints->ai_family == PF_INET)
result.ai_family = AF_INET;
else
return EAI_FAMILY;
sin.sin_family = result.ai_family;
sin.sin_port = htons (port);
if (hints->ai_flags & AI_PASSIVE)
sin.sin_addr.s_addr = htonl (INADDR_ANY);
else
sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
/* Duplicate result and addr and return */
*res = dup_addrinfo (&result, &sin, sizeof sin);
return (*res == NULL) ? EAI_MEMORY : 0;
}
/* If AI_NUMERIC is specified, use inet_addr to translate numbers and
dots notation. */
if (hints->ai_flags & AI_NUMERICHOST)
{
struct sockaddr_in sin;
/* check protocol family is PF_UNSPEC or PF_INET */
if (hints->ai_family == PF_UNSPEC || hints->ai_family == PF_INET)
result.ai_family = AF_INET;
else
return EAI_FAMILY;
sin.sin_family = result.ai_family;
sin.sin_port = htons (port);
sin.sin_addr.s_addr = inet_addr (nodename);
/* Duplicate result and addr and return */
*res = dup_addrinfo (&result, &sin, sizeof sin);
return (*res == NULL) ? EAI_MEMORY : 0;
}
errno = 0;
hp = gethostbyname_ctx (nodename, &ghbnctx);
if (hp == NULL)
{
if (errno != 0)
{
free_ghbnctx (&ghbnctx);
return EAI_SYSTEM;
}
code = h_error_ctx (&ghbnctx);
switch (code)
{
case HOST_NOT_FOUND: code = EAI_NODATA; break;
case NO_DATA: code = EAI_NODATA; break;
#if defined(NO_ADDRESS) && NO_ADDRESS != NO_DATA
case NO_ADDRESS: code = EAI_NODATA; break;
#endif
case NO_RECOVERY: code = EAI_FAIL; break;
case TRY_AGAIN: code = EAI_AGAIN; break;
default: code = EAI_FAIL; break;
}
free_ghbnctx (&ghbnctx);
return code;
}
/* Check that the address family is acceptable.
*/
switch (hp->h_addrtype)
{
case AF_INET:
if (!(hints->ai_family == PF_UNSPEC || hints->ai_family == PF_INET))
goto eai_family;
break;
#ifdef USE_IPV6
case AF_INET6:
if (!(hints->ai_family == PF_UNSPEC || hints->ai_family == PF_INET6))
goto eai_family;
break;
#endif
default:
eai_family:
free_ghbnctx (&ghbnctx);
return EAI_FAMILY;
}
/* For each element pointed to by hp, create an element in the
result linked list. */
sai = eai = NULL;
for (addrs = hp->h_addr_list; *addrs != NULL; addrs++)
{
struct sockaddr sa;
size_t addrlen;
sa.sa_family = hp->h_addrtype;
switch (hp->h_addrtype)
{
case AF_INET:
((struct sockaddr_in *) &sa)->sin_port = htons (port);
memcpy (&((struct sockaddr_in *) &sa)->sin_addr,
*addrs, hp->h_length);
addrlen = sizeof (struct sockaddr_in);
break;
#ifdef USE_IPV6
case AF_INET6:
# if SIN6_LEN
((struct sockaddr_in6 *) &sa)->sin6_len = hp->h_length;
# endif
((struct sockaddr_in6 *) &sa)->sin6_port = htons (port);
memcpy (&((struct sockaddr_in6 *) &sa)->sin6_addr,
*addrs, hp->h_length);
addrlen = sizeof (struct sockaddr_in6);
break;
#endif
default:
continue;
}
result.ai_family = hp->h_addrtype;
ai = dup_addrinfo (&result, &sa, addrlen);
if (ai == NULL)
{
free_ghbnctx (&ghbnctx);
freeaddrinfo (sai);
return EAI_MEMORY;
}
if (sai == NULL)
sai = ai;
else
eai->ai_next = ai;
eai = ai;
}
if (sai == NULL)
{
free_ghbnctx (&ghbnctx);
return EAI_NODATA;
}
if (hints->ai_flags & AI_CANONNAME)
{
sai->ai_canonname = malloc (strlen (hp->h_name) + 1);
if (sai->ai_canonname == NULL)
{
free_ghbnctx (&ghbnctx);
freeaddrinfo (sai);
return EAI_MEMORY;
}
strcpy (sai->ai_canonname, hp->h_name);
}
free_ghbnctx (&ghbnctx);
*res = sai;
return 0;
}
void
freeaddrinfo (struct addrinfo *ai)
{
struct addrinfo *next;
while (ai != NULL)
{
next = ai->ai_next;
if (ai->ai_canonname != NULL)
free (ai->ai_canonname);
if (ai->ai_addr != NULL)
free (ai->ai_addr);
free (ai);
ai = next;
}
}
const char *
gai_strerror (int ecode)
{
static const char *eai_descr[] =
{
"no error",
"address family for nodename not supported", /* EAI_ADDRFAMILY */
"temporary failure in name resolution", /* EAI_AGAIN */
"invalid value for ai_flags", /* EAI_BADFLAGS */
"non-recoverable failure in name resolution", /* EAI_FAIL */
"ai_family not supported", /* EAI_FAMILY */
"memory allocation failure", /* EAI_MEMORY */
"no address associated with nodename", /* EAI_NODATA */
"nodename nor servname provided, or not known", /* EAI_NONAME */
"servname not supported for ai_socktype", /* EAI_SERVICE */
"ai_socktype not supported", /* EAI_SOCKTYPE */
"system error returned in errno", /* EAI_SYSTEM */
};
if (ecode < 0 || ecode > (int) (sizeof eai_descr/ sizeof eai_descr[0]))
return "unknown error";
return eai_descr[ecode];
}

71
plugins/getaddrinfo.h Normal file
View file

@ -0,0 +1,71 @@
#ifndef _getaddrinfo_h
#define _getaddrinfo_h
/*
* This file is part of libESMTP, a library for submission of RFC 2822
* formatted electronic mail messages using the SMTP protocol described
* in RFC 2821.
* Modified by Jeremy T. Bouse for use in Nagios plugins
*
* Copyright (C) 2001,2002 Brian Stafford <brian@stafford.uklinux.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Structure and prototypes aken from RFC 2553
*
* $Id: getaddrinfo.h,v 1.2 2004/12/01 23:54:51 opensides Exp $
*/
struct addrinfo
{
int ai_flags; /* AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST */
int ai_family; /* PF_xxx */
int ai_socktype; /* SOCK_xxx */
int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
size_t ai_addrlen; /* length of ai_addr */
char *ai_canonname; /* canonical name for nodename */
struct sockaddr *ai_addr; /* binary address */
struct addrinfo *ai_next; /* next structure in linked list */
};
/* Supposed to be defined in <netdb.h> */
#define AI_PASSIVE 1 /* Socket address is intended for `bind'. */
#define AI_CANONNAME 2 /* Request for canonical name. */
#define AI_NUMERICHOST 4 /* Don't use name resolution. */
/* Supposed to be defined in <netdb.h> */
#define EAI_ADDRFAMILY 1 /* address family for nodename not supported */
#define EAI_AGAIN 2 /* temporary failure in name resolution */
#define EAI_BADFLAGS 3 /* invalid value for ai_flags */
#define EAI_FAIL 4 /* non-recoverable failure in name resolution */
#define EAI_FAMILY 5 /* ai_family not supported */
#define EAI_MEMORY 6 /* memory allocation failure */
#define EAI_NODATA 7 /* no address associated with nodename */
#define EAI_NONAME 8 /* nodename nor servname provided, or not known */
#define EAI_SERVICE 9 /* servname not supported for ai_socktype */
#define EAI_SOCKTYPE 10 /* ai_socktype not supported */
#define EAI_SYSTEM 11 /* system error returned in errno */
/* RFC 2553 / Posix resolver */
int getaddrinfo (const char *nodename, const char *servname,
const struct addrinfo *hints, struct addrinfo **res);
/* Free addrinfo structure and associated storage */
void freeaddrinfo (struct addrinfo *ai);
/* Convert error return from getaddrinfo() to string */
const char *gai_strerror (int code);
#endif

230
plugins/gethostbyname.c Normal file
View file

@ -0,0 +1,230 @@
/*
* This file is a ghastly hack because nobody can agree on
* gethostbyname_r()'s prototype.
*
* Copyright (C) 2001,2002 Brian Stafford <brian@stafford.uklinux.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: gethostbyname.c,v 1.2 2004/12/01 23:54:51 opensides Exp $
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#define _SVID_SOURCE 1 /* Need this to get gethostbyname_r() */
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <errno.h>
#include "gethostbyname.h"
#if HAVE_GETIPNODEBYNAME
void
free_ghbnctx (struct ghbnctx *ctx)
{
assert (ctx != NULL);
if (ctx->hostent != NULL)
freehostent (ctx->hostent);
}
struct hostent *
gethostbyname_ctx (const char *host, struct ghbnctx *ctx)
{
assert (ctx != NULL);
memset (ctx, 0, sizeof (struct ghbnctx));
ctx->hostent = getipnodebyname (host, AF_UNSPEC, AI_ADDRCONFIG, &ctx->h_err);
return ctx->hostent;
}
int
h_error_ctx (struct ghbnctx *ctx)
{
assert (ctx != NULL);
return ctx->h_err;
}
#elif HAVE_GETHOSTBYNAME_R == 6
void
free_ghbnctx (struct ghbnctx *ctx)
{
assert (ctx != NULL);
if (ctx->hostbuf != NULL)
free (ctx->hostbuf);
}
struct hostent *
gethostbyname_ctx (const char *host, struct ghbnctx *ctx)
{
struct hostent *hp;
char *tmp;
int err;
assert (ctx != NULL);
memset (ctx, 0, sizeof (struct ghbnctx));
ctx->hostbuf_len = 2048;
if ((ctx->hostbuf = malloc (ctx->hostbuf_len)) == NULL)
{
errno = ENOMEM;
return NULL;
}
while ((err = gethostbyname_r (host,
&ctx->hostent, ctx->hostbuf, ctx->hostbuf_len,
&hp, &ctx->h_err)) == ERANGE)
{
ctx->hostbuf_len += 1024;
if ((tmp = realloc (ctx->hostbuf, ctx->hostbuf_len)) == NULL)
{
errno = ENOMEM;
return NULL;
}
ctx->hostbuf = tmp;
}
if (err != 0)
{
errno = err;
return NULL;
}
return hp;
}
int
h_error_ctx (struct ghbnctx *ctx)
{
assert (ctx != NULL);
return ctx->h_err;
}
#elif HAVE_GETHOSTBYNAME_R == 5
void
free_ghbnctx (struct ghbnctx *ctx)
{
assert (ctx != NULL);
if (ctx->hostbuf != NULL)
free (ctx->hostbuf);
}
struct hostent *
gethostbyname_ctx (const char *host, struct ghbnctx *ctx)
{
struct hostent *hp;
char *tmp;
assert (ctx != NULL);
memset (ctx, 0, sizeof (struct ghbnctx));
ctx->hostbuf_len = 2048;
if ((ctx->hostbuf = malloc (ctx->hostbuf_len)) == NULL)
{
errno = ENOMEM;
return NULL;
}
while ((hp = gethostbyname_r (host, &ctx->hostent,
ctx->hostbuf, ctx->hostbuf_len,
&ctx->h_err)) == NULL && errno == ERANGE)
{
ctx->hostbuf_len += 1024;
if ((tmp = realloc (ctx->hostbuf, ctx->hostbuf_len)) == NULL)
{
errno = ENOMEM;
return NULL;
}
ctx->hostbuf = tmp;
}
return hp;
}
int
h_error_ctx (struct ghbnctx *ctx)
{
assert (ctx != NULL);
return ctx->h_err;
}
#elif HAVE_GETHOSTBYNAME_R == 3
void
free_ghbnctx (struct ghbnctx *ctx)
{
assert (ctx != NULL);
/* FIXME: does this need to do anything? */
}
struct hostent *
gethostbyname_ctx (const char *host, struct ghbnctx *ctx)
{
assert (ctx != NULL);
if (!gethostbyname_r (host, &ctx->hostent, &ctx->hostent_data))
{
ctx->h_err = h_errno; /* FIXME: is this correct? */
return NULL;
}
return &ctx->hostent;
}
int
h_error_ctx (struct ghbnctx *ctx)
{
assert (ctx != NULL);
return ctx->h_err;
}
#else
void
free_ghbnctx (struct ghbnctx *ctx __attribute__ ((unused)))
{
assert (ctx != NULL);
}
struct hostent *
gethostbyname_ctx (const char *host, struct ghbnctx *ctx)
{
struct hostent *hp;
hp = gethostbyname (host);
if (hp == NULL)
ctx->h_err = h_errno;
return hp;
}
int
h_error_ctx (struct ghbnctx *ctx)
{
assert (ctx != NULL);
return ctx->h_err;
}
#endif

105
plugins/gethostbyname.h Normal file
View file

@ -0,0 +1,105 @@
/*
* This file is a ghastly hack because nobody can agree on
* gethostbyname_r()'s prototype.
*
* Copyright (C) 2001,2002 Brian Stafford <brian@stafford.uklinux.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: gethostbyname.h,v 1.2 2004/12/01 23:54:51 opensides Exp $
*/
/*************************************************************************
Usage:
#include <errno.h>
#include "gethostbyname.h"
f ()
{
struct ghbnctx ctx;
errno = 0;
hp = gethostbyname_ctx (host, &ctx);
if (hp == NULL)
{
if (errno != 0)
handle_value_of_errno (errno);
else
handle_value_of_h_errno (h_error_ctx (&ctx));
}
else
{
...
}
free_ghbnctx (&ctx);
}
*************************************************************************/
#ifndef _gethostbyname_h
#define _gethostbyname_h
#if HAVE_GETIPNODEBYNAME
struct ghbnctx
{
int h_err;
struct hostent *hostent;
};
#elif HAVE_GETHOSTBYNAME_R == 6
struct ghbnctx
{
int h_err;
struct hostent hostent;
char *hostbuf;
size_t hostbuf_len;
};
#elif HAVE_GETHOSTBYNAME_R == 5
struct ghbnctx
{
int h_err;
struct hostent hostent;
char *hostbuf;
int hostbuf_len;
};
#elif HAVE_GETHOSTBYNAME_R == 3
struct ghbnctx
{
int h_err;
struct hostent_data hostent_data;
struct hostent hostent;
};
#else
struct ghbnctx
{
int h_err;
};
#endif
struct hostent *gethostbyname_ctx (const char *host, struct ghbnctx *ctx);
int h_error_ctx (struct ghbnctx *ctx);
void free_ghbnctx (struct ghbnctx *ctx);
#endif

275
plugins/negate.c Normal file
View file

@ -0,0 +1,275 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: negate.c,v 1.24 2004/12/25 23:17:44 opensides Exp $
@@-<article>
<sect1>
<title>Quick Reference</title>
<refentry>
<refmeta><manvolnum>5<manvolnum></refmeta>
<refnamdiv>
<refname>&progname;</refname>
<refpurpose>&SUMMARY;</refpurpose>
</refnamdiv>
</refentry>
</sect1>
<sect1>
<title>FAQ</title>
</sect1>
<sect1>
<title>Theory, Installation, and Operation</title>
<sect2>
<title>General Description</title>
<para>
&DESCRIPTION;
</para>
</sect2>
<sect2>
<title>Future Enhancements</title>
<para>ToDo List</para>
<itemizedlist>
<listitem>Add option to do regex substitution in output text</listitem>
</itemizedlist>
</sect2>-@@
******************************************************************************/
const char *progname = "negate";
const char *revision = "$Revision: 1.24 $";
const char *copyright = "2002-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#define DEFAULT_TIMEOUT 9
#include "common.h"
#include "utils.h"
#include "popen.h"
char *command_line;
int process_arguments (int, char **);
int validate_arguments (void);
void print_help (void);
void print_usage (void);
int
main (int argc, char **argv)
{
int found = 0, result = STATE_UNKNOWN;
char *buf;
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (process_arguments (argc, argv) == ERROR)
usage4 (_("Could not parse arguments"));
/* Set signal handling and alarm */
if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR)
die (STATE_UNKNOWN, _("Cannot catch SIGALRM"));
(void) alarm ((unsigned) timeout_interval);
child_process = spopen (command_line);
if (child_process == NULL)
die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), command_line);
child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
if (child_stderr == NULL) {
printf (_("Could not open stderr for %s\n"), command_line);
}
buf = malloc(MAX_INPUT_BUFFER);
while (fgets (buf, MAX_INPUT_BUFFER - 1, child_process)) {
found++;
printf ("%s", buf);
}
if (!found)
die (STATE_UNKNOWN,
_("%s problem - No data received from host\nCMD: %s\n"),\
argv[0], command_line);
/* close the pipe */
result = spclose (child_process);
/* WARNING if output found on stderr */
if (fgets (buf, MAX_INPUT_BUFFER - 1, child_stderr))
result = max_state (result, STATE_WARNING);
/* close stderr */
(void) fclose (child_stderr);
if (result == STATE_OK)
exit (STATE_CRITICAL);
else if (result == STATE_CRITICAL)
exit (EXIT_SUCCESS);
else
exit (result);
}
/******************************************************************************
@@-
<sect2>
<title>Functions</title>
<sect3>
<title>process_arguments</title>
<para>This function parses the command line into the needed
variables.</para>
<para>Aside from the standard 'help' and 'version' options, there
is a only a 'timeout' option.</para>
</sect3>
-@@
******************************************************************************/
/* process command-line arguments */
int
process_arguments (int argc, char **argv)
{
int c;
int option = 0;
static struct option longopts[] = {
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{"timeout", required_argument, 0, 't'},
{0, 0, 0, 0}
};
while (1) {
c = getopt_long (argc, argv, "+hVt:",
longopts, &option);
if (c == -1 || c == EOF)
break;
switch (c) {
case '?': /* help */
usage2 (_("Unknown argument"), optarg);
break;
case 'h': /* help */
print_help ();
exit (EXIT_SUCCESS);
break;
case 'V': /* version */
print_revision (progname, revision);
exit (EXIT_SUCCESS);
case 't': /* timeout period */
if (!is_integer (optarg))
usage2 (_("Timeout interval must be a positive integer"), optarg);
else
timeout_interval = atoi (optarg);
break;
}
}
asprintf (&command_line, "%s", argv[optind]);
for (c = optind+1; c < argc; c++) {
asprintf (&command_line, "%s %s", command_line, argv[c]);
}
return validate_arguments ();
}
/******************************************************************************
@@-
<sect3>
<title>validate_arguments</title>
<para>No validation is currently done.</para>
</sect3>
-@@
******************************************************************************/
int
validate_arguments ()
{
if (command_line == NULL)
return ERROR;
return STATE_OK;
}
/******************************************************************************
@@-
</sect2>
</sect1>
</article>
-@@
******************************************************************************/
void
print_help (void)
{
print_revision (progname, revision);
printf (COPYRIGHT, copyright, email);
printf (_("\
Negates the status of a plugin (returns OK for CRITICAL, and vice-versa).\n\n"));
print_usage ();
printf (_(UT_HELP_VRSN));
printf (_(UT_TIMEOUT), DEFAULT_TIMEOUT);
printf (_("\
[keep timeout than the plugin timeout to retain CRITICAL status]\n"));
printf (_("\
negate \"/usr/local/nagios/libexec/check_ping -H host\"\n\
Run check_ping and invert result. Must use full path to plugin\n\
negate \"/usr/local/nagios/libexec/check_procs -a 'vi negate.c'\"\n\
Use single quotes if you need to retain spaces\n"));
printf (_("\
This plugin is a wrapper to take the output of another plugin and invert it.\n\
If the wrapped plugin returns STATE_OK, the wrapper will return STATE_CRITICAL.\n\
If the wrapped plugin returns STATE_CRITICAL, the wrapper will return STATE_OK.\n\
Otherwise, the output state of the wrapped plugin is unchanged.\n"));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("Usage: %s [-t timeout] <definition of wrapped plugin>\n",progname);
}

330
plugins/netutils.c Normal file
View file

@ -0,0 +1,330 @@
/****************************************************************************
*
* Nagios plugins network utilities
*
* License: GPL
* Copyright (c) 1999 Ethan Galstad (nagios@nagios.org)
*
* Last Modified: $Date: 2005/05/25 00:30:19 $
*
* Description:
*
* This file contains commons functions used in many of the plugins.
*
* License Information:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id: netutils.c,v 1.24 2005/05/25 00:30:19 seanius Exp $
*
****************************************************************************/
#include "common.h"
#include "netutils.h"
unsigned int socket_timeout = DEFAULT_SOCKET_TIMEOUT;
int econn_refuse_state = STATE_CRITICAL;
int was_refused = FALSE;
int address_family = AF_UNSPEC;
/* handles socket timeouts */
void
socket_timeout_alarm_handler (int sig)
{
if (sig == SIGALRM)
printf (_("CRITICAL - Socket timeout after %d seconds\n"), socket_timeout);
else
printf (_("CRITICAL - Abnormal timeout after %d seconds\n"), socket_timeout);
exit (STATE_CRITICAL);
}
/* connects to a host on a specified tcp port, sends a string, and gets a
response. loops on select-recv until timeout or eof to get all of a
multi-packet answer */
int
process_tcp_request2 (const char *server_address, int server_port,
const char *send_buffer, char *recv_buffer, int recv_size)
{
int result;
int send_result;
int recv_result;
int sd;
struct timeval tv;
fd_set readfds;
int recv_length = 0;
result = np_net_connect (server_address, server_port, &sd, IPPROTO_TCP);
if (result != STATE_OK)
return STATE_CRITICAL;
send_result = send (sd, send_buffer, strlen (send_buffer), 0);
if (send_result<0 || (size_t)send_result!=strlen(send_buffer)) {
printf (_("Send failed\n"));
result = STATE_WARNING;
}
while (1) {
/* wait up to the number of seconds for socket timeout
minus one for data from the host */
tv.tv_sec = socket_timeout - 1;
tv.tv_usec = 0;
FD_ZERO (&readfds);
FD_SET (sd, &readfds);
select (sd + 1, &readfds, NULL, NULL, &tv);
/* make sure some data has arrived */
if (!FD_ISSET (sd, &readfds)) { /* it hasn't */
if (!recv_length) {
strcpy (recv_buffer, "");
printf (_("No data was received from host!\n"));
result = STATE_WARNING;
}
else { /* this one failed, but previous ones worked */
recv_buffer[recv_length] = 0;
}
break;
}
else { /* it has */
recv_result =
recv (sd, recv_buffer + recv_length,
(size_t)recv_size - recv_length - 1, 0);
if (recv_result == -1) {
/* recv failed, bail out */
strcpy (recv_buffer + recv_length, "");
result = STATE_WARNING;
break;
}
else if (recv_result == 0) {
/* end of file ? */
recv_buffer[recv_length] = 0;
break;
}
else { /* we got data! */
recv_length += recv_result;
if (recv_length >= recv_size - 1) {
/* buffer full, we're done */
recv_buffer[recv_size - 1] = 0;
break;
}
}
}
/* end if(!FD_ISSET(sd,&readfds)) */
}
/* end while(1) */
close (sd);
return result;
}
/* connects to a host on a specified port, sends a string, and gets a
response */
int
process_request (const char *server_address, int server_port, int proto,
const char *send_buffer, char *recv_buffer, int recv_size)
{
int result;
int sd;
result = STATE_OK;
result = np_net_connect (server_address, server_port, &sd, proto);
if (result != STATE_OK)
return STATE_CRITICAL;
result = send_request (sd, proto, send_buffer, recv_buffer, recv_size);
close (sd);
return result;
}
/* opens a tcp or udp connection to a remote host */
int
np_net_connect (const char *host_name, int port, int *sd, int proto)
{
struct addrinfo hints;
struct addrinfo *res, *res0;
char port_str[6];
int result;
memset (&hints, 0, sizeof (hints));
hints.ai_family = address_family;
hints.ai_protocol = proto;
hints.ai_socktype = (proto == IPPROTO_UDP) ? SOCK_DGRAM : SOCK_STREAM;
snprintf (port_str, sizeof (port_str), "%d", port);
result = getaddrinfo (host_name, port_str, &hints, &res0);
if (result != 0) {
printf ("%s\n", gai_strerror (result));
return STATE_UNKNOWN;
}
else {
res = res0;
while (res) {
/* attempt to create a socket */
*sd = socket (res->ai_family, (proto == IPPROTO_UDP) ?
SOCK_DGRAM : SOCK_STREAM, res->ai_protocol);
if (*sd < 0) {
printf (_("Socket creation failed\n"));
freeaddrinfo (res);
return STATE_UNKNOWN;
}
/* attempt to open a connection */
result = connect (*sd, res->ai_addr, res->ai_addrlen);
if (result == 0) {
was_refused = FALSE;
break;
}
if (result < 0) {
switch (errno) {
case ECONNREFUSED:
was_refused = TRUE;
break;
}
}
close (*sd);
res = res->ai_next;
}
freeaddrinfo (res0);
}
if (result == 0)
return STATE_OK;
else if (was_refused) {
switch (econn_refuse_state) { /* a user-defined expected outcome */
case STATE_OK:
case STATE_WARNING: /* user wants WARN or OK on refusal */
return econn_refuse_state;
break;
case STATE_CRITICAL: /* user did not set econn_refuse_state */
printf ("%s\n", strerror(errno));
return econn_refuse_state;
break;
default: /* it's a logic error if we do not end up in STATE_(OK|WARNING|CRITICAL) */
return STATE_UNKNOWN;
break;
}
}
else {
printf ("%s\n", strerror(errno));
return STATE_CRITICAL;
}
}
int
send_request (int sd, int proto, const char *send_buffer, char *recv_buffer, int recv_size)
{
int result = STATE_OK;
int send_result;
int recv_result;
struct timeval tv;
fd_set readfds;
send_result = send (sd, send_buffer, strlen (send_buffer), 0);
if (send_result<0 || (size_t)send_result!=strlen(send_buffer)) {
printf (_("Send failed\n"));
result = STATE_WARNING;
}
/* wait up to the number of seconds for socket timeout minus one
for data from the host */
tv.tv_sec = socket_timeout - 1;
tv.tv_usec = 0;
FD_ZERO (&readfds);
FD_SET (sd, &readfds);
select (sd + 1, &readfds, NULL, NULL, &tv);
/* make sure some data has arrived */
if (!FD_ISSET (sd, &readfds)) {
strcpy (recv_buffer, "");
printf (_("No data was received from host!\n"));
result = STATE_WARNING;
}
else {
recv_result = recv (sd, recv_buffer, (size_t)recv_size - 1, 0);
if (recv_result == -1) {
strcpy (recv_buffer, "");
if (proto != IPPROTO_TCP)
printf (_("Receive failed\n"));
result = STATE_WARNING;
}
else
recv_buffer[recv_result] = 0;
/* die returned string */
recv_buffer[recv_size - 1] = 0;
}
return result;
}
int
is_host (const char *address)
{
if (is_addr (address) || is_hostname (address))
return (TRUE);
return (FALSE);
}
int
is_addr (const char *address)
{
#ifdef USE_IPV6
if (is_inet_addr (address) && address_family != AF_INET6)
#else
if (is_inet_addr (address))
#endif
return (TRUE);
#ifdef USE_IPV6
if (is_inet6_addr (address) && address_family != AF_INET)
return (TRUE);
#endif
return (FALSE);
}
int
resolve_host_or_addr (const char *address, int family)
{
struct addrinfo hints;
struct addrinfo *res;
int retval;
memset (&hints, 0, sizeof (hints));
hints.ai_family = family;
retval = getaddrinfo (address, NULL, &hints, &res);
if (retval != 0)
return FALSE;
else {
freeaddrinfo (res);
return TRUE;
}
}

79
plugins/netutils.h Normal file
View file

@ -0,0 +1,79 @@
/******************************************************************************
*
* Nagios plugins net utilities include file
*
* License: GPL
* Copyright (c) 1999 Ethan Galstad (nagios@nagios.org)
*
* Last Modified: $Date: 2005/05/25 00:30:19 $
*
* Description:
*
* This file contains common include files and function definitions
* used in many of the plugins.
*
* License Information:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id: netutils.h,v 1.12 2005/05/25 00:30:19 seanius Exp $
*
******************************************************************************/
#include "config.h"
#include <netinet/in.h>
#include <arpa/inet.h>
RETSIGTYPE socket_timeout_alarm_handler (int) __attribute__((noreturn));
/* process_request and wrapper macros */
#define process_tcp_request(addr, port, sbuf, rbuf, rsize) \
process_request(addr, port, IPPROTO_TCP, sbuf, rbuf, rsize)
#define process_udp_request(addr, port, sbuf, rbuf, rsize) \
process_request(addr, port, IPPROTO_UDP, sbuf, rbuf, rsize)
int process_tcp_request2 (const char *address, int port,
const char *sbuffer, char *rbuffer, int rsize);
int process_request (const char *address, int port, int proto,
const char *sbuffer, char *rbuffer, int rsize);
/* my_connect and wrapper macros */
#define my_tcp_connect(addr, port, s) np_net_connect(addr, port, s, IPPROTO_TCP)
#define my_udp_connect(addr, port, s) np_net_connect(addr, port, s, IPPROTO_UDP)
int np_net_connect(const char *address, int port, int *sd, int proto);
/* send_request and wrapper macros */
#define send_tcp_request(s, sbuf, rbuf, rsize) \
send_request(s, IPPROTO_TCP, sbuf, rbuf, rsize)
#define send_udp_request(s, sbuf, rbuf, rsize) \
send_request(s, IPPROTO_UDP, sbuf, rbuf, rsize)
int send_request (int sd, int proto, const char *send_buffer, char *recv_buffer, int recv_size);
/* "is_*" wrapper macros and functions */
int is_host (const char *);
int is_addr (const char *);
int resolve_host_or_addr (const char *, int);
#define is_inet_addr(addr) resolve_host_or_addr(addr, AF_INET)
#ifdef USE_IPV6
# define is_inet6_addr(addr) resolve_host_or_addr(addr, AF_INET6)
# define is_hostname(addr) resolve_host_or_addr(addr, address_family)
#else
# define is_hostname(addr) resolve_host_or_addr(addr, AF_INET)
#endif
extern unsigned int socket_timeout;
extern int econn_refuse_state;
extern int was_refused;
extern int address_family;

341
plugins/popen.c Normal file
View file

@ -0,0 +1,341 @@
/******************************************************************************
* popen.c
*
* A safe alternative to popen
*
* Provides spopen and spclose
FILE * spopen(const char *);
int spclose(FILE *);
*
* Code taken with liitle modification from "Advanced Programming for the Unix
* Environment" by W. Richard Stevens
*
* This is considered safe in that no shell is spawned, and the environment and
* path passed to the exec'd program are esstially empty. (popen create a shell
* and passes the environment to it).
*
* $Id: popen.c,v 1.13 2005/09/12 10:31:28 tonvoon Exp $
*
******************************************************************************/
#include "common.h"
/* extern so plugin has pid to kill exec'd process on timeouts */
extern int timeout_interval;
extern pid_t *childpid;
extern int *child_stderr_array;
extern FILE *child_process;
FILE *spopen (const char *);
int spclose (FILE *);
#ifdef REDHAT_SPOPEN_ERROR
RETSIGTYPE popen_sigchld_handler (int);
#endif
RETSIGTYPE popen_timeout_alarm_handler (int);
#include <stdarg.h> /* ANSI C header file */
#include <fcntl.h>
#include <limits.h>
#include <sys/resource.h>
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#ifndef WEXITSTATUS
# define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
#endif
#ifndef WIFEXITED
# define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
#endif
/* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
#if defined(SIG_IGN) && !defined(SIG_ERR)
#define SIG_ERR ((Sigfunc *)-1)
#endif
#define min(a,b) ((a) < (b) ? (a) : (b))
#define max(a,b) ((a) > (b) ? (a) : (b))
int open_max (void); /* {Prog openmax} */
static void err_sys (const char *, ...) __attribute__((noreturn,format(printf, 1, 2)));
char *rtrim (char *, const char *);
char *pname = NULL; /* caller can set this from argv[0] */
/*int *childerr = NULL;*//* ptr to array allocated at run-time */
/*extern pid_t *childpid = NULL; *//* ptr to array allocated at run-time */
static int maxfd; /* from our open_max(), {Prog openmax} */
#ifdef REDHAT_SPOPEN_ERROR
static volatile int childtermd = 0;
#endif
FILE *
spopen (const char *cmdstring)
{
char *env[2];
char *cmd = NULL;
char **argv = NULL;
char *str;
int argc;
int i = 0, pfd[2], pfderr[2];
pid_t pid;
#ifdef RLIMIT_CORE
/* do not leave core files */
struct rlimit limit;
getrlimit (RLIMIT_CORE, &limit);
limit.rlim_cur = 0;
setrlimit (RLIMIT_CORE, &limit);
#endif
env[0] = strdup("LC_ALL=C");
env[1] = '\0';
/* if no command was passed, return with no error */
if (cmdstring == NULL)
return (NULL);
/* make copy of command string so strtok() doesn't silently modify it */
/* (the calling program may want to access it later) */
cmd = malloc (strlen (cmdstring) + 1);
if (cmd == NULL)
return NULL;
strcpy (cmd, cmdstring);
/* This is not a shell, so we don't handle "???" */
if (strstr (cmdstring, "\""))
return NULL;
/* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
return NULL;
/* there cannot be more args than characters */
argc = strlen (cmdstring) + 1; /* add 1 for NULL termination */
argv = malloc (sizeof(char*)*argc);
if (argv == NULL) {
printf (_("Could not malloc argv array in popen()\n"));
return NULL;
}
/* loop to get arguments to command */
while (cmd) {
str = cmd;
str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
if (i >= argc - 2) {
printf (_("CRITICAL - You need more args!!!\n"));
return (NULL);
}
if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
str++;
if (!strstr (str, "'"))
return NULL; /* balanced? */
cmd = 1 + strstr (str, "'");
str[strcspn (str, "'")] = 0;
}
else {
if (strpbrk (str, " \t\r\n")) {
cmd = 1 + strpbrk (str, " \t\r\n");
str[strcspn (str, " \t\r\n")] = 0;
}
else {
cmd = NULL;
}
}
if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
cmd = NULL;
argv[i++] = str;
}
argv[i] = NULL;
if (childpid == NULL) { /* first time through */
maxfd = open_max (); /* allocate zeroed out array for child pids */
if ((childpid = calloc ((size_t)maxfd, sizeof (pid_t))) == NULL)
return (NULL);
}
if (child_stderr_array == NULL) { /* first time through */
maxfd = open_max (); /* allocate zeroed out array for child pids */
if ((child_stderr_array = calloc ((size_t)maxfd, sizeof (int))) == NULL)
return (NULL);
}
if (pipe (pfd) < 0)
return (NULL); /* errno set by pipe() */
if (pipe (pfderr) < 0)
return (NULL); /* errno set by pipe() */
#ifdef REDHAT_SPOPEN_ERROR
if (signal (SIGCHLD, popen_sigchld_handler) == SIG_ERR) {
usage4 (_("Cannot catch SIGCHLD"));
}
#endif
if ((pid = fork ()) < 0)
return (NULL); /* errno set by fork() */
else if (pid == 0) { /* child */
close (pfd[0]);
if (pfd[1] != STDOUT_FILENO) {
dup2 (pfd[1], STDOUT_FILENO);
close (pfd[1]);
}
close (pfderr[0]);
if (pfderr[1] != STDERR_FILENO) {
dup2 (pfderr[1], STDERR_FILENO);
close (pfderr[1]);
}
/* close all descriptors in childpid[] */
for (i = 0; i < maxfd; i++)
if (childpid[i] > 0)
close (i);
execve (argv[0], argv, env);
_exit (0);
}
close (pfd[1]); /* parent */
if ((child_process = fdopen (pfd[0], "r")) == NULL)
return (NULL);
close (pfderr[1]);
childpid[fileno (child_process)] = pid; /* remember child pid for this fd */
child_stderr_array[fileno (child_process)] = pfderr[0]; /* remember STDERR */
return (child_process);
}
int
spclose (FILE * fp)
{
int fd, status;
pid_t pid;
if (childpid == NULL)
return (1); /* popen() has never been called */
fd = fileno (fp);
if ((pid = childpid[fd]) == 0)
return (1); /* fp wasn't opened by popen() */
childpid[fd] = 0;
if (fclose (fp) == EOF)
return (1);
#ifdef REDHAT_SPOPEN_ERROR
while (!childtermd); /* wait until SIGCHLD */
#endif
while (waitpid (pid, &status, 0) < 0)
if (errno != EINTR)
return (1); /* error other than EINTR from waitpid() */
if (WIFEXITED (status))
return (WEXITSTATUS (status)); /* return child's termination status */
return (1);
}
#ifdef OPEN_MAX
static int openmax = OPEN_MAX;
#else
static int openmax = 0;
#endif
#define OPEN_MAX_GUESS 256 /* if OPEN_MAX is indeterminate */
/* no guarantee this is adequate */
#ifdef REDHAT_SPOPEN_ERROR
RETSIGTYPE
popen_sigchld_handler (int signo)
{
if (signo == SIGCHLD)
childtermd = 1;
}
#endif
RETSIGTYPE
popen_timeout_alarm_handler (int signo)
{
int fh;
if (signo == SIGALRM) {
fh=fileno (child_process);
if(fh >= 0){
kill (childpid[fh], SIGKILL);
}
printf (_("CRITICAL - Plugin timed out after %d seconds\n"),
timeout_interval);
exit (STATE_CRITICAL);
}
}
int
open_max (void)
{
if (openmax == 0) { /* first time through */
errno = 0;
if ((openmax = sysconf (_SC_OPEN_MAX)) < 0) {
if (errno == 0)
openmax = OPEN_MAX_GUESS; /* it's indeterminate */
else
err_sys (_("sysconf error for _SC_OPEN_MAX"));
}
}
return (openmax);
}
/* Fatal error related to a system call.
* Print a message and die. */
#define MAXLINE 2048
static void
err_sys (const char *fmt, ...)
{
int errnoflag = 1;
int errno_save;
char buf[MAXLINE];
va_list ap;
va_start (ap, fmt);
/* err_doit (1, fmt, ap); */
errno_save = errno; /* value caller might want printed */
vsprintf (buf, fmt, ap);
if (errnoflag)
sprintf (buf + strlen (buf), ": %s", strerror (errno_save));
strcat (buf, "\n");
fflush (stdout); /* in case stdout and stderr are the same */
fputs (buf, stderr);
fflush (NULL); /* flushes all stdio output streams */
va_end (ap);
exit (1);
}
char *
rtrim (char *str, const char *tok)
{
int i = 0;
int j = sizeof (str);
while (str != NULL && i < j) {
if (*(str + i) == *tok) {
sprintf (str + i, "%s", "\0");
return str;
}
i++;
}
return str;
}

15
plugins/popen.h Normal file
View file

@ -0,0 +1,15 @@
/******************************************************************************
*
* $Id: popen.h,v 1.4 2005/05/01 20:12:03 seanius Exp $
*
******************************************************************************/
FILE *spopen (const char *);
int spclose (FILE *);
RETSIGTYPE popen_timeout_alarm_handler (int);
extern unsigned int timeout_interval;
pid_t *childpid=NULL;
int *child_stderr_array=NULL;
FILE *child_process=NULL;
FILE *child_stderr=NULL;

33
plugins/t/check_disk.t Normal file
View file

@ -0,0 +1,33 @@
#! /usr/bin/perl -w -I ..
#
# Disk Space Tests via check_disk
#
# $Id: check_disk.t,v 1.2 2005/07/25 01:47:14 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 10; plan tests => $tests}
my $successOutput = '/^DISK OK - /';
my $failureOutput = '/^DISK CRITICAL - /';
my $mountpoint_valid = getTestParameter( "mountpoint_valid", "NP_MOUNTPOINT_VALID", "/",
"The path to a valid mountpoint" );
my $mountpoint_invalid = getTestParameter( "mountpoint_invalid", "NP_MOUNTPOINT_INVALID", "/missing",
"The path to a invalid (non-existent) mountpoint" );
my $t;
$t += checkCmd( "./check_disk 100 100 ${mountpoint_valid}", 0, $successOutput );
$t += checkCmd( "./check_disk -w 0 -c 0 ${mountpoint_valid}", 0, $successOutput );
$t += checkCmd( "./check_disk -w 1\% -c 1\% ${mountpoint_valid}", 0, $successOutput );
$t += checkCmd( "./check_disk 0 0 ${mountpoint_valid}", 2, $failureOutput );
$t += checkCmd( "./check_disk 100 100 ${mountpoint_invalid}", 2, '/not found/' );
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

42
plugins/t/check_dns.t Normal file
View file

@ -0,0 +1,42 @@
#! /usr/bin/perl -w -I ..
#
# Domain Name Server (DNS) Tests via check_dns
#
# $Id: check_dns.t,v 1.3 2005/07/25 01:47:14 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 6; plan tests => $tests}
my $successOutput = '/DNS OK: [\.0-9]+ seconds response time/';
my $hostname_valid = getTestParameter( "hostname_valid", "NP_HOSTNAME_VALID", "localhost",
"A valid (known to DNS) hostname" );
my $hostname_invalid = getTestParameter( "hostname_invalid", "NP_HOSTNAME_INVALID", "nosuchhost",
"An invalid (not known to DNS) hostname" );
my $dns_server = getTestParameter( "dns_server", "NP_DNS_SERVER", undef,
"A non default (remote) DNS server" );
my $t;
#
# Default DNS Server
#
$t += checkCmd( "./check_dns -H $hostname_valid -t 5", 0, $successOutput );
$t += checkCmd( "./check_dns -H $hostname_invalid -t 1", 2 );
#
# Specified DNS Server
#
$t += checkCmd( "./check_dns -H $hostname_valid -s $dns_server -t 5", 0, $successOutput );
$t += checkCmd( "./check_dns -H $hostname_invalid -s $dns_server -t 1", 2 );
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

43
plugins/t/check_fping.t Normal file
View file

@ -0,0 +1,43 @@
#! /usr/bin/perl -w -I ..
#
# FPing Tests via check_fping
#
# $Id: check_fping.t,v 1.2 2005/07/25 01:47:14 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 4; plan tests => $tests}
my $successOutput = '/^FPING OK - /';
my $failureOutput = '/^FPING CRITICAL - /';
my $host_responsive = getTestParameter( "host_responsive", "NP_HOST_RESPONSIVE", "localhost",
"The hostname of system responsive to network requests" );
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" );
my $t;
if ( -x "./check_fping" )
{
$t += checkCmd( "./check_fping $host_responsive", 0, $successOutput );
$t += checkCmd( "./check_fping $host_nonresponsive", [ 1, 2 ] );
$t += checkCmd( "./check_fping $hostname_invalid", [ 1, 2 ] );
}
else
{
$t += skipMissingCmd( "./check_fping", $tests );
}
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

34
plugins/t/check_ftp.t Normal file
View file

@ -0,0 +1,34 @@
#! /usr/bin/perl -w -I ..
#
# File Transfer Protocol (FTP) Test via check_ftp
#
# $Id: check_ftp.t,v 1.3 2005/07/25 01:47:14 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 4; plan tests => $tests}
my $host_tcp_ftp = getTestParameter( "host_tcp_ftp", "NP_HOST_TCP_FTP", "localhost",
"A host providing the FTP Service (an FTP server)");
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" );
my $successOutput = '/FTP OK -\s+[0-9]?\.?[0-9]+ second response time/';
my $t;
$t += checkCmd( "./check_ftp $host_tcp_ftp -wt 300 -ct 600", 0, $successOutput );
$t += checkCmd( "./check_ftp $host_nonresponsive -wt 0 -ct 0 -to 1", 2 );
$t += checkCmd( "./check_ftp $hostname_invalid -wt 0 -ct 0", 2 );
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

42
plugins/t/check_hpjd.t Normal file
View file

@ -0,0 +1,42 @@
#! /usr/bin/perl -w -I ..
#
# HP JetDirect Test via check_hpjd
#
# $Id: check_hpjd.t,v 1.2 2005/07/25 01:47:14 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 5; plan tests => $tests}
my $successOutput = '/^Printer ok - /';
my $failureOutput = '/Timeout: No [Rr]esponse from /';
my $host_tcp_hpjd = getTestParameter( "host_tcp_hpjd", "NP_HOST_TCP_HPJD", undef,
"A host (usually a printer) providing the HP-JetDirect Services" );
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" );
my $t;
if ( -x "./check_hpjd" )
{
$t += checkCmd( "./check_hpjd $host_tcp_hpjd", 0, $successOutput );
$t += checkCmd( "./check_hpjd $host_nonresponsive", 2, $failureOutput );
$t += checkCmd( "./check_hpjd $hostname_invalid", 3 );
}
else
{
$t += skipMissingCmd( "./check_hpjd", $tests );
}
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

36
plugins/t/check_http.t Normal file
View file

@ -0,0 +1,36 @@
#! /usr/bin/perl -w -I ..
#
# HyperText Transfer Protocol (HTTP) Test via check_http
#
# $Id: check_http.t,v 1.4 2005/07/25 01:47:14 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 4; 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)" );
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" );
my $successOutput = '/(HTTP\s[o|O][k|K]\s)?\s?HTTP\/1.[01]\s[0-9]{3}\s(OK|Found)\s-\s+[0-9]+\sbytes\sin\s+([0-9]+|[0-9]+\.[0-9]+)\sseconds/';
my %exceptions = ( 2 => "No Web Server present?" );
my $t;
$t += checkCmd( "./check_http $host_tcp_http -wt 300 -ct 600", { 0 => 'continue', 2 => 'skip' }, $successOutput, %exceptions );
$t += checkCmd( "./check_http $host_nonresponsive -wt 1 -ct 2", 2 );
$t += checkCmd( "./check_http $hostname_invalid -wt 1 -ct 2", 2 );
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

39
plugins/t/check_imap.t Normal file
View file

@ -0,0 +1,39 @@
#! /usr/bin/perl -w -I ..
#
# Internet Mail Access Protocol (IMAP) Server Tests via check_imap
#
# $Id: check_imap.t,v 1.2 2005/07/25 01:47:14 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 5; plan tests => $tests}
my $host_tcp_smtp = getTestParameter( "host_tcp_smtp", "NP_HOST_TCP_SMTP", "mailhost",
"A host providing an STMP Service (a mail server)");
my $host_tcp_imap = getTestParameter( "host_tcp_imap", "NP_HOST_TCP_IMAP", $host_tcp_smtp,
"A host providing an IMAP Service (a mail server)");
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" );
my %exceptions = ( 2 => "No IMAP Server present?" );
my $t;
$t += checkCmd( "./check_imap $host_tcp_imap", 0, undef, %exceptions );
$t += checkCmd( "./check_imap -H $host_tcp_imap -p 143 -w 9 -c 9 -t 10 -e '* OK'", 0, undef, %exceptions );
$t += checkCmd( "./check_imap $host_tcp_imap -p 143 -wt 9 -ct 9 -to 10 -e '* OK'", 0, undef, %exceptions );
$t += checkCmd( "./check_imap $host_nonresponsive", 2 );
$t += checkCmd( "./check_imap $hostname_invalid", 2 );
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

25
plugins/t/check_load.t Normal file
View file

@ -0,0 +1,25 @@
#! /usr/bin/perl -w -I ..
#
# Load Average Tests via check_load
#
# $Id: check_load.t,v 1.4 2005/07/25 01:47:14 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 4; plan tests => $tests}
my $successOutput = '/^OK - load average: [0-9]\.?[0-9]+, [0-9]\.?[0-9]+, [0-9]\.?[0-9]+/';
my $failureOutput = '/^CRITICAL - load average: [0-9]\.?[0-9]+, [0-9]\.?[0-9]+, [0-9]\.?[0-9]+/';
my $t;
$t += checkCmd( "./check_load -w 100,100,100 -c 100,100,100", 0, $successOutput );
$t += checkCmd( "./check_load -w 0,0,0 -c 0,0,0", 2, $failureOutput );
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

33
plugins/t/check_mysql.t Normal file
View file

@ -0,0 +1,33 @@
#! /usr/bin/perl -w -I ..
#
# MySQL Database Server Tests via check_mysql
#
# $Id: check_mysql.t,v 1.3 2005/07/25 01:47:14 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 2; plan tests => $tests}
my $t;
my $failureOutput = '/Access denied for user: /';
if ( -x "./check_mysql" )
{
my $mysqlserver = getTestParameter( "mysql_server", "NP_MYSQL_SERVER", undef,
"A MySQL Server");
$t += checkCmd( "./check_mysql -H $mysqlserver -P 3306", 2, $failureOutput );
}
else
{
$t += skipMissingCmd( "./check_mysql", $tests );
}
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

37
plugins/t/check_ping.t Normal file
View file

@ -0,0 +1,37 @@
#! /usr/bin/perl -w -I ..
#
# Ping Response Tests via check_ping
#
# $Id: check_ping.t,v 1.3 2005/09/15 08:39:23 tonvoon Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 8; plan tests => $tests}
my $successOutput = '/PING (ok|OK) - Packet loss = +[0-9]{1,2}\%, +RTA = [\.0-9]+ ms/';
my $failureOutput = '/Packet loss = +[0-9]{1,2}\%, +RTA = [\.0-9]+ ms/';
my $host_responsive = getTestParameter( "host_responsive", "NP_HOST_RESPONSIVE", "localhost",
"The hostname of system responsive to network requests" );
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" );
my $t;
$t += checkCmd( "./check_ping $host_responsive 100 100 1000 1000 -p 1", 0, $successOutput );
$t += checkCmd( "./check_ping $host_responsive 0 0 0 0 -p 1", 2, $failureOutput );
$t += checkCmd( "./check_ping $host_nonresponsive 0 0 0 0 -p 1 -to 1", 2 );
$t += checkCmd( "./check_ping $hostname_invalid 0 0 0 0 -p 1 -to 1", 3 );
$t += checkCmd( "./check_ping -w 100,10% -c 200,20%" , 3 , "/You must specify a server address or host name.*/");
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

38
plugins/t/check_pop.t Normal file
View file

@ -0,0 +1,38 @@
#! /usr/bin/perl -w -I ..
#
# Post Office Protocol (POP) Server Tests via check_pop
#
# $Id: check_pop.t,v 1.2 2005/07/25 01:47:14 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 5; plan tests => $tests}
my $host_tcp_smtp = getTestParameter( "host_tcp_smtp", "NP_HOST_TCP_SMTP", "mailhost",
"A host providing an STMP Service (a mail server)");
my $host_tcp_pop = getTestParameter( "host_tcp_pop", "NP_HOST_TCP_POP", $host_tcp_smtp,
"A host providing an POP Service (a mail server)");
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" );
my %exceptions = ( 2 => "No POP Server present?" );
my $t;
$t += checkCmd( "./check_pop $host_tcp_pop", 0, undef, %exceptions );
$t += checkCmd( "./check_pop -H $host_tcp_pop -p 110 -w 9 -c 9 -t 10 -e '+OK'", 0, undef, %exceptions );
$t += checkCmd( "./check_pop $host_tcp_pop -p 110 -wt 9 -ct 9 -to 10 -e '+OK'", 0, undef, %exceptions );
$t += checkCmd( "./check_pop $host_nonresponsive", 2 );
$t += checkCmd( "./check_pop $hostname_invalid", 2 );
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

24
plugins/t/check_procs.t Normal file
View file

@ -0,0 +1,24 @@
#! /usr/bin/perl -w -I ..
#
# Process Tests via check_procs
#
# $Id: check_procs.t,v 1.3 2005/07/25 01:47:15 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 10; plan tests => $tests}
my $t;
$t += checkCmd( "./check_procs -w 100000 -c 100000", 0, '/^PROCS OK: [0-9]+ process(es)?$/' );
$t += checkCmd( "./check_procs -w 100000 -c 100000 -s Z", 0, '/^PROCS OK: [0-9]+ process(es)? with /' );
$t += checkCmd( "./check_procs -w 0 -c 10000000", 1, '/^PROCS WARNING: [0-9]+ process(es)?$/' );
$t += checkCmd( "./check_procs -w 0 -c 0", 2, '/^PROCS CRITICAL: [0-9]+ process(es)?$/' );
$t += checkCmd( "./check_procs -w 0 -c 0 -s S", 2, '/^PROCS CRITICAL: [0-9]+ process(es)? with /' );
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

34
plugins/t/check_smtp.t Normal file
View file

@ -0,0 +1,34 @@
#! /usr/bin/perl -w -I ..
#
# Simple Mail Transfer Protocol (SMTP) Test via check_smtp
#
# $Id: check_smtp.t,v 1.2 2005/07/25 01:47:15 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 5; plan tests => $tests}
my $host_tcp_smtp = getTestParameter( "host_tcp_smtp", "NP_HOST_TCP_SMTP", "mailhost",
"A host providing an STMP Service (a mail server)");
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" );
my %exceptions = ( 2 => "No SMTP Server present?" );
my $t;
$t += checkCmd( "./check_smtp $host_tcp_smtp", 0, undef, %exceptions );
$t += checkCmd( "./check_smtp -H $host_tcp_smtp -p 25 -t 1 -w 9 -c 9 -t 10 -e 220", 0, undef, %exceptions );
$t += checkCmd( "./check_smtp -H $host_tcp_smtp -p 25 -wt 9 -ct 9 -to 10 -e 220", 0, undef, %exceptions );
$t += checkCmd( "./check_smtp $host_nonresponsive", 2 );
$t += checkCmd( "./check_smtp $hostname_invalid", 3 );
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

57
plugins/t/check_snmp.t Normal file
View file

@ -0,0 +1,57 @@
#! /usr/bin/perl -w -I ..
#
# Simple Network Management Protocol (SNMP) Test via check_snmp
#
# $Id: check_snmp.t,v 1.2 2005/07/25 01:47:15 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 12; plan tests => $tests}
my $t;
if ( -x "./check_snmp" )
{
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" );
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" );
my %exceptions = ( 3 => "No SNMP Server present?" );
$t += checkCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0 -w 1: -c 1:",
{ 0 => 'continue', 3 => 'skip' }, '/^SNMP OK - \d+/', %exceptions );
$t += checkCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrSWRun.hrSWRunTable.hrSWRunEntry.hrSWRunIndex.1 -w 1:1 -c 1:1",
{ 0 => 'continue', 3 => 'skip' }, '/^SNMP OK - 1\s*$/', %exceptions );
$t += checkCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrSWRun.hrSWRunTable.hrSWRunEntry.hrSWRunIndex.1 -w 0 -c 1:",
{ 1 => 'continue', 3 => 'skip' }, '/^SNMP WARNING - \*1\*\s*$/', %exceptions );
$t += checkCmd( "./check_snmp -H $host_snmp -C $snmp_community -o host.hrSWRun.hrSWRunTable.hrSWRunEntry.hrSWRunIndex.1 -w :0 -c 0",
{ 2 => 'continue', 3 => 'skip' }, '/^SNMP CRITICAL - \*1\*\s*$/', %exceptions );
$t += checkCmd( "./check_snmp -H $host_nonresponsive -C $snmp_community -o system.sysUpTime.0 -w 1: -c 1:", 3, '/SNMP problem - /' );
$t += checkCmd( "./check_snmp -H $hostname_invalid -C $snmp_community -o system.sysUpTime.0 -w 1: -c 1:", 3, '/SNMP problem - /' );
}
else
{
$t += skipMissingCmd( "./check_snmp", $tests );
}
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

25
plugins/t/check_swap.t Normal file
View file

@ -0,0 +1,25 @@
#! /usr/bin/perl -w -I ..
#
# Swap Space Tests via check_swap
#
# $Id: check_swap.t,v 1.2 2005/07/25 01:47:15 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 6; plan tests => $tests}
my $t;
my $successOutput = '/^SWAP OK - [0-9]+\% free \([0-9]+ MB out of [0-9]+ MB\)/';
my $failureOutput = '/^SWAP CRITICAL - [0-9]+\% free \([0-9]+ MB out of [0-9]+ MB\)/';
$t += checkCmd( "./check_swap -w 1048576 -c 1048576", 0, $successOutput ); # 1MB free
$t += checkCmd( "./check_swap -w 1\% -c 1\%", 0, $successOutput ); # 1% free
$t += checkCmd( "./check_swap -w 100\% -c 100\%", 2, $failureOutput ); # 100% free (always fails)
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

34
plugins/t/check_tcp.t Normal file
View file

@ -0,0 +1,34 @@
#! /usr/bin/perl -w -I ..
#
# TCP Connection Based Tests via check_tcp
#
# $Id: check_tcp.t,v 1.3 2005/07/25 01:47:15 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 5; 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)" );
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" );
my $successOutput = '/^TCP OK\s-\s+[0-9]?\.?[0-9]+ second response time on port [0-9]+/';
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 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 );
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

40
plugins/t/check_time.t Normal file
View file

@ -0,0 +1,40 @@
#! /usr/bin/perl -w -I ..
#
# System Time Tests via check_time
#
# $Id: check_time.t,v 1.2 2005/07/25 01:47:15 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 8; plan tests => $tests}
my $host_udp_time = getTestParameter( "host_udp_time", "NP_HOST_UDP_TIME", "localhost",
"A host providing the UDP Time Service" );
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" );
my $successOutput = '/^TIME OK - [0-9]+ second time difference/';
my $t;
# standard mode
$t += checkCmd( "./check_time -H $host_udp_time -w 999999,59 -c 999999,59 -t 60", 0, $successOutput );
$t += checkCmd( "./check_time -H $host_udp_time -w 999999 -W 59 -c 999999 -C 59 -t 60", 0, $successOutput );
# reverse compatibility mode
$t += checkCmd( "./check_time $host_udp_time -wt 59 -ct 59 -cd 999999 -wd 999999 -to 60", 0, $successOutput );
# failure mode
$t += checkCmd( "./check_time -H $host_nonresponsive -t 1", 2 );
$t += checkCmd( "./check_time -H $hostname_invalid -t 1", 3 );
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

33
plugins/t/check_udp.t Normal file
View file

@ -0,0 +1,33 @@
#! /usr/bin/perl -w -I ..
#
# UDP Connection Based Tests via check_udp
#
# $Id: check_udp.t,v 1.2 2005/07/25 01:47:15 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 3; plan tests => $tests} #TODO# Update to 4 when the commented out test is fixed
my $host_udp_time = getTestParameter( "host_udp_time", "NP_HOST_UDP_TIME", "localhost",
"A host providing the UDP Time Service" );
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" );
my $successOutput = '/^Connection accepted on port [0-9]+ - [0-9]+ second response time$/';
my $t;
$t += checkCmd( "./check_udp -H $host_udp_time -p 37 -wt 300 -ct 600", 0, $successOutput );
$t += checkCmd( "./check_udp $host_nonresponsive -p 37 -wt 0 -ct 0 -to 1", 2 );
#TODO# $t += checkCmd( "./check_udp $hostname_invalid -p 37 -wt 0 -ct 0 -to 1", 2 ); # Currently returns 0 (ie success)
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

25
plugins/t/check_users.t Normal file
View file

@ -0,0 +1,25 @@
#! /usr/bin/perl -w -I ..
#
# Logged in Users Tests via check_users
#
# $Id: check_users.t,v 1.2 2005/07/25 01:47:15 illumino Exp $
#
use strict;
use Test;
use NPTest;
use vars qw($tests);
BEGIN {$tests = 4; plan tests => $tests}
my $successOutput = '/^USERS OK - [0-9]+ users currently logged in/';
my $failureOutput = '/^USERS CRITICAL - [0-9]+ users currently logged in/';
my $t;
$t += checkCmd( "./check_users 1000 1000", 0, $successOutput );
$t += checkCmd( "./check_users 0 0", 2, $failureOutput );
exit(0) if defined($Test::Harness::VERSION);
exit($tests - $t);

164
plugins/urlize.c Normal file
View file

@ -0,0 +1,164 @@
/******************************************************************************
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: urlize.c,v 1.17 2004/12/25 23:17:44 opensides Exp $
******************************************************************************/
const char *progname = "urlize";
const char *revision = "$Revision: 1.17 $";
const char *copyright = "2000-2004";
const char *email = "nagiosplug-devel@lists.sourceforge.net";
#include "common.h"
#include "utils.h"
#include "popen.h"
void print_help (void);
void print_usage (void);
int
main (int argc, char **argv)
{
int found = 0, result = STATE_UNKNOWN;
char *url = NULL;
char *cmd;
char *buf;
int c;
int option = 0;
static struct option longopts[] = {
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{"url", required_argument, 0, 'u'},
{0, 0, 0, 0}
};
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
while (1) {
c = getopt_long (argc, argv, "+hVu:", longopts, &option);
if (c == -1 || c == EOF)
break;
switch (c) {
case 'h': /* help */
print_help ();
exit (EXIT_SUCCESS);
break;
case 'V': /* version */
print_revision (progname, revision);
exit (EXIT_SUCCESS);
break;
case 'u':
url = strdup (argv[optind]);
break;
case '?':
default:
usage2 (_("Unknown argument"), optarg);
}
}
if (url == NULL)
url = strdup (argv[optind++]);
cmd = strdup (argv[optind++]);
for (c = optind; c < argc; c++) {
asprintf (&cmd, "%s %s", cmd, argv[c]);
}
child_process = spopen (cmd);
if (child_process == NULL) {
printf (_("Could not open pipe: %s\n"), cmd);
exit (STATE_UNKNOWN);
}
child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
if (child_stderr == NULL) {
printf (_("Could not open stderr for %s\n"), cmd);
}
buf = malloc(MAX_INPUT_BUFFER);
printf ("<A href=\"%s\">", argv[1]);
while (fgets (buf, MAX_INPUT_BUFFER - 1, child_process)) {
found++;
printf ("%s", buf);
}
if (!found)
die (STATE_UNKNOWN,
_("%s UNKNOWN - No data received from host\nCMD: %s</A>\n"),
argv[0], cmd);
/* close the pipe */
result = spclose (child_process);
/* WARNING if output found on stderr */
if (fgets (buf, MAX_INPUT_BUFFER - 1, child_stderr))
result = max_state (result, STATE_WARNING);
/* close stderr */
(void) fclose (child_stderr);
printf ("</A>\n");
return result;
}
void
print_help (void)
{
print_revision (progname, revision);
printf ("Copyright (c) 2000 Karl DeBisschop <kdebisschop@users.sourceforge.net>\n");
printf (COPYRIGHT, copyright, email);
printf (_("\n\
This plugin wraps the text output of another command (plugin) in HTML\n\
<A> tags, thus displaying the plugin output in as a clickable link in\n\
the Nagios status screen. The return status is the same as the invoked\n\
plugin.\n\n"));
print_usage ();
printf (_("\n\
Pay close attention to quoting to ensure that the shell passes the expected\n\
data to the plugin. For example, in:\n\
\n\
urlize http://example.com/ check_http -H example.com -r 'two words'\n\
\n\
the shell will remove the single quotes and urlize will see:\n\
\n\
urlize http://example.com/ check_http -H example.com -r two words\n\
\n\
You probably want:\n\
\n\
urlize http://example.com/ \"check_http -H example.com -r 'two words'\"\n"));
printf (_(UT_SUPPORT));
}
void
print_usage (void)
{
printf ("Usage:\n %s <url> <plugin> <arg1> ... <argN>\n", progname);
}

570
plugins/utils.c Normal file
View file

@ -0,0 +1,570 @@
/*****************************************************************************
*
* utils.c
*
* Library of useful functions for plugins
*
* Copyright (c) 2000 Karl DeBisschop (karl@debisschop.net)
* License: GPL
*
* $Revision: 1.41 $
* $Date: 2004/12/25 23:17:44 $
****************************************************************************/
#define LOCAL_TIMEOUT_ALARM_HANDLER
#include "common.h"
#include "utils.h"
#include <stdarg.h>
#include <limits.h>
#include <arpa/inet.h>
extern void print_usage (void);
extern const char *progname;
#define STRLEN 64
#define TXTBLK 128
/* **************************************************************************
* max_state(STATE_x, STATE_y)
* compares STATE_x to STATE_y and returns result based on the following
* STATE_UNKNOWN < STATE_OK < STATE_WARNING < STATE_CRITICAL
*
* Note that numerically the above does not hold
****************************************************************************/
int
max_state (int a, int b)
{
if (a == STATE_CRITICAL || b == STATE_CRITICAL)
return STATE_CRITICAL;
else if (a == STATE_WARNING || b == STATE_WARNING)
return STATE_WARNING;
else if (a == STATE_OK || b == STATE_OK)
return STATE_OK;
else if (a == STATE_UNKNOWN || b == STATE_UNKNOWN)
return STATE_UNKNOWN;
else if (a == STATE_DEPENDENT || b == STATE_DEPENDENT)
return STATE_DEPENDENT;
else
return max (a, b);
}
void usage (const char *msg)
{
printf ("%s\n", msg);
print_usage ();
exit (STATE_UNKNOWN);
}
void usage2(const char *msg, const char *arg)
{
printf ("%s: %s - %s\n",progname,msg,arg);
print_usage ();
exit (STATE_UNKNOWN);
}
void
usage3 (const char *msg, int arg)
{
printf ("%s: %s - %c\n", progname, msg, arg);
print_usage();
exit (STATE_UNKNOWN);
}
void
usage4 (const char *msg)
{
printf ("%s: %s\n", progname, msg);
print_usage();
exit (STATE_UNKNOWN);
}
char *
clean_revstring (const char *revstring)
{
char plugin_revision[STRLEN];
if (sscanf (revstring,"$Revision: %[0-9.]",plugin_revision) == 1)
return strscpy (NULL, plugin_revision);
else
return strscpy (NULL, "N/A");
}
void
print_revision (const char *command_name, const char *revision_string)
{
char plugin_revision[STRLEN];
if (sscanf (revision_string, "$Revision: %[0-9.]", plugin_revision) != 1)
strncpy (plugin_revision, "N/A", STRLEN);
printf ("%s (%s %s) %s\n",
command_name, PACKAGE, VERSION, plugin_revision);
}
const char *
state_text (int result)
{
switch (result) {
case STATE_OK:
return "OK";
case STATE_WARNING:
return "WARNING";
case STATE_CRITICAL:
return "CRITICAL";
case STATE_DEPENDENT:
return "DEPENDENT";
default:
return "UNKNOWN";
}
}
void
die (int result, const char *fmt, ...)
{
va_list ap;
va_start (ap, fmt);
vprintf (fmt, ap);
va_end (ap);
exit (result);
}
void
timeout_alarm_handler (int signo)
{
if (signo == SIGALRM) {
printf (_("CRITICAL - Plugin timed out after %d seconds\n"),
timeout_interval);
exit (STATE_CRITICAL);
}
}
int
is_numeric (char *number)
{
char tmp[1];
float x;
if (!number)
return FALSE;
else if (sscanf (number, "%f%c", &x, tmp) == 1)
return TRUE;
else
return FALSE;
}
int
is_positive (char *number)
{
if (is_numeric (number) && atof (number) > 0.0)
return TRUE;
else
return FALSE;
}
int
is_negative (char *number)
{
if (is_numeric (number) && atof (number) < 0.0)
return TRUE;
else
return FALSE;
}
int
is_nonnegative (char *number)
{
if (is_numeric (number) && atof (number) >= 0.0)
return TRUE;
else
return FALSE;
}
int
is_percentage (char *number)
{
int x;
if (is_numeric (number) && (x = atof (number)) >= 0 && x <= 100)
return TRUE;
else
return FALSE;
}
int
is_integer (char *number)
{
long int n;
if (!number || (strspn (number, "-0123456789 ") != strlen (number)))
return FALSE;
n = strtol (number, NULL, 10);
if (errno != ERANGE && n >= INT_MIN && n <= INT_MAX)
return TRUE;
else
return FALSE;
}
int
is_intpos (char *number)
{
if (is_integer (number) && atoi (number) > 0)
return TRUE;
else
return FALSE;
}
int
is_intneg (char *number)
{
if (is_integer (number) && atoi (number) < 0)
return TRUE;
else
return FALSE;
}
int
is_intnonneg (char *number)
{
if (is_integer (number) && atoi (number) >= 0)
return TRUE;
else
return FALSE;
}
int
is_intpercent (char *number)
{
int i;
if (is_integer (number) && (i = atoi (number)) >= 0 && i <= 100)
return TRUE;
else
return FALSE;
}
int
is_option (char *str)
{
if (!str)
return FALSE;
else if (strspn (str, "-") == 1 || strspn (str, "-") == 2)
return TRUE;
else
return FALSE;
}
#ifdef NEED_GETTIMEOFDAY
int
gettimeofday (struct timeval *tv, struct timezone *tz)
{
tv->tv_usec = 0;
tv->tv_sec = (long) time ((time_t) 0);
}
#endif
double
delta_time (struct timeval tv)
{
struct timeval now;
gettimeofday (&now, NULL);
return ((double)(now.tv_sec - tv.tv_sec) + (double)(now.tv_usec - tv.tv_usec) / (double)1000000);
}
long
deltime (struct timeval tv)
{
struct timeval now;
gettimeofday (&now, NULL);
return (now.tv_sec - tv.tv_sec)*1000000 + now.tv_usec - tv.tv_usec;
}
void
strip (char *buffer)
{
size_t x;
int i;
for (x = strlen (buffer); x >= 1; x--) {
i = x - 1;
if (buffer[i] == ' ' ||
buffer[i] == '\r' || buffer[i] == '\n' || buffer[i] == '\t')
buffer[i] = '\0';
else
break;
}
return;
}
/******************************************************************************
*
* Copies one string to another. Any previously existing data in
* the destination string is lost.
*
* Example:
*
* char *str=NULL;
* str = strscpy("This is a line of text with no trailing newline");
*
*****************************************************************************/
char *
strscpy (char *dest, const char *src)
{
if (src == NULL)
return NULL;
asprintf (&dest, "%s", src);
return dest;
}
/******************************************************************************
*
* Returns a pointer to the next line of a multiline string buffer
*
* Given a pointer string, find the text following the next sequence
* of \r and \n characters. This has the effect of skipping blank
* lines as well
*
* Example:
*
* Given text as follows:
*
* ==============================
* This
* is
* a
*
* multiline string buffer
* ==============================
*
* int i=0;
* char *str=NULL;
* char *ptr=NULL;
* str = strscpy(str,"This\nis\r\na\n\nmultiline string buffer\n");
* ptr = str;
* while (ptr) {
* printf("%d %s",i++,firstword(ptr));
* ptr = strnl(ptr);
* }
*
* Produces the following:
*
* 1 This
* 2 is
* 3 a
* 4 multiline
*
* NOTE: The 'firstword()' function is conceptual only and does not
* exist in this package.
*
* NOTE: Although the second 'ptr' variable is not strictly needed in
* this example, it is good practice with these utilities. Once
* the * pointer is advance in this manner, it may no longer be
* handled with * realloc(). So at the end of the code fragment
* above, * strscpy(str,"foo") work perfectly fine, but
* strscpy(ptr,"foo") will * cause the the program to crash with
* a segmentation fault.
*
*****************************************************************************/
char *
strnl (char *str)
{
size_t len;
if (str == NULL)
return NULL;
str = strpbrk (str, "\r\n");
if (str == NULL)
return NULL;
len = strspn (str, "\r\n");
if (str[len] == '\0')
return NULL;
str += len;
if (strlen (str) == 0)
return NULL;
return str;
}
/******************************************************************************
*
* Like strscpy, except only the portion of the source string up to
* the provided delimiter is copied.
*
* Example:
*
* str = strpcpy(str,"This is a line of text with no trailing newline","x");
* printf("%s\n",str);
*
* Produces:
*
*This is a line of te
*
*****************************************************************************/
char *
strpcpy (char *dest, const char *src, const char *str)
{
size_t len;
if (src)
len = strcspn (src, str);
else
return NULL;
if (dest == NULL || strlen (dest) < len)
dest = realloc (dest, len + 1);
if (dest == NULL)
die (STATE_UNKNOWN, _("failed realloc in strpcpy\n"));
strncpy (dest, src, len);
dest[len] = '\0';
return dest;
}
/******************************************************************************
*
* Like strscat, except only the portion of the source string up to
* the provided delimiter is copied.
*
* str = strpcpy(str,"This is a line of text with no trailing newline","x");
* str = strpcat(str,"This is a line of text with no trailing newline","x");
* printf("%s\n",str);
*
*This is a line of texThis is a line of tex
*
*****************************************************************************/
char *
strpcat (char *dest, const char *src, const char *str)
{
size_t len, l2;
if (dest)
len = strlen (dest);
else
len = 0;
if (src) {
l2 = strcspn (src, str);
}
else {
return dest;
}
dest = realloc (dest, len + l2 + 1);
if (dest == NULL)
die (STATE_UNKNOWN, _("failed malloc in strscat\n"));
strncpy (dest + len, src, l2);
dest[len + l2] = '\0';
return dest;
}
/******************************************************************************
*
* Print perfdata in a standard format
*
******************************************************************************/
char *perfdata (const char *label,
long int val,
const char *uom,
int warnp,
long int warn,
int critp,
long int crit,
int minp,
long int minv,
int maxp,
long int maxv)
{
char *data = NULL;
if (strpbrk (label, "'= "))
asprintf (&data, "'%s'=%ld%s;", label, val, uom);
else
asprintf (&data, "%s=%ld%s;", label, val, uom);
if (warnp)
asprintf (&data, "%s%ld;", data, warn);
else
asprintf (&data, "%s;", data);
if (critp)
asprintf (&data, "%s%ld;", data, crit);
else
asprintf (&data, "%s;", data);
if (minp)
asprintf (&data, "%s%ld", data, minv);
if (maxp)
asprintf (&data, "%s;%ld", data, maxv);
return data;
}
char *fperfdata (const char *label,
double val,
const char *uom,
int warnp,
double warn,
int critp,
double crit,
int minp,
double minv,
int maxp,
double maxv)
{
char *data = NULL;
if (strpbrk (label, "'= "))
asprintf (&data, "'%s'=", label);
else
asprintf (&data, "%s=", label);
asprintf (&data, "%s%f", data, val);
asprintf (&data, "%s%s;", data, uom);
if (warnp)
asprintf (&data, "%s%f", data, warn);
asprintf (&data, "%s;", data);
if (critp)
asprintf (&data, "%s%f", data, crit);
asprintf (&data, "%s;", data);
if (minp)
asprintf (&data, "%s%f", data, minv);
if (maxp) {
asprintf (&data, "%s;", data);
asprintf (&data, "%s%f", data, maxv);
}
return data;
}

171
plugins/utils.h Normal file
View file

@ -0,0 +1,171 @@
/* Header file for nagios plugins utils.c */
/* This file should be included in all plugins */
/* The purpose of this package is to provide safer alternatives to C
functions that might otherwise be vulnerable to hacking. This
currently includes a standard suite of validation routines to be sure
that an string argument acually converts to its intended type and a
suite of string handling routine that do their own memory management
in order to resist overflow attacks. In addition, a few functions are
provided to standardize version and error reporting across the entire
suite of plugins. */
/* Standardize version information, termination */
/* $Id: utils.h,v 1.22 2004/12/05 00:54:09 opensides Exp $ */
void support (void);
char *clean_revstring (const char *);
void print_revision (const char *, const char *);
void die (int, const char *, ...) __attribute__((noreturn,format(printf, 2, 3)));
/* Handle timeouts */
#ifdef LOCAL_TIMEOUT_ALARM_HANDLER
extern unsigned int timeout_interval;
RETSIGTYPE timeout_alarm_handler (int);
#else
unsigned int timeout_interval = DEFAULT_SOCKET_TIMEOUT;
extern RETSIGTYPE timeout_alarm_handler (int);
#endif
time_t start_time, end_time;
/* Test input types */
int is_integer (char *);
int is_intpos (char *);
int is_intneg (char *);
int is_intnonneg (char *);
int is_intpercent (char *);
int is_numeric (char *);
int is_positive (char *);
int is_negative (char *);
int is_nonnegative (char *);
int is_percentage (char *);
int is_option (char *);
/* Generalized timer that will do milliseconds if available */
#ifndef HAVE_STRUCT_TIMEVAL
struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* microseconds */
};
#endif
#ifndef HAVE_GETTIMEOFDAY
int gettimeofday(struct timeval *, struct timezone *);
#endif
double delta_time (struct timeval tv);
long deltime (struct timeval tv);
/* Handle strings safely */
void strip (char *);
char *strscpy (char *, const char *);
char *strnl (char *);
char *strpcpy (char *, const char *, const char *);
char *strpcat (char *, const char *, const char *);
int max_state (int a, int b);
void usage (const char *) __attribute__((noreturn));
void usage2(const char *, const char *) __attribute__((noreturn));
void usage3(const char *, int) __attribute__((noreturn));
void usage4(const char *);
const char *state_text (int);
#define max(a,b) (((a)>(b))?(a):(b))
#define min(a,b) (((a)<(b))?(a):(b))
char *perfdata (const char *,
long int,
const char *,
int,
long int,
int,
long int,
int,
long int,
int,
long int);
char *fperfdata (const char *,
double,
const char *,
int,
double,
int,
double,
int,
double,
int,
double);
/* The idea here is that, although not every plugin will use all of these,
most will or should. Therefore, for consistency, these very common
options should have only these meanings throughout the overall suite */
#define STD_LONG_OPTS \
{"version",no_argument,0,'V'},\
{"verbose",no_argument,0,'v'},\
{"help",no_argument,0,'h'},\
{"timeout",required_argument,0,'t'},\
{"critical",required_argument,0,'c'},\
{"warning",required_argument,0,'w'},\
{"hostname",required_argument,0,'H'}
#define COPYRIGHT "Copyright (c) %s Nagios Plugin Development Team\n\
\t<%s>\n\n"
#define UT_HLP_VRS "\
%s (-h | --help) for detailed help\n\
%s (-V | --version) for version information\n"
#define UT_HELP_VRSN "\
\nOptions:\n\
-h, --help\n\
Print detailed help screen\n\
-V, --version\n\
Print version information\n"
#define UT_HOST_PORT "\
-H, --hostname=ADDRESS\n\
Host name or IP Address\n\
-%c, --port=INTEGER\n\
Port number (default: %s)\n"
#define UT_IPv46 "\
-4, --use-ipv4\n\
Use IPv4 connection\n\
-6, --use-ipv6\n\
Use IPv6 connection\n"
#define UT_VERBOSE "\
-v, --verbose\n\
Show details for command-line debugging (Nagios may truncate output)\n"
#define UT_WARN_CRIT "\
-w, --warning=DOUBLE\n\
Response time to result in warning status (seconds)\n\
-c, --critical=DOUBLE\n\
Response time to result in critical status (seconds)\n"
#define UT_TIMEOUT "\
-t, --timeout=INTEGER\n\
Seconds before connection times out (default: %d)\n"
#define UT_SUPPORT "\n\
Send email to nagios-users@lists.sourceforge.net if you have questions\n\
regarding use of this software. To submit patches or suggest improvements,\n\
send email to nagiosplug-devel@lists.sourceforge.net\n"
#define UT_NOWARRANTY "\n\
The nagios plugins come with ABSOLUTELY NO WARRANTY. You may redistribute\n\
copies of the plugins under the terms of the GNU General Public License.\n\
For more information about these matters, see the file named COPYING.\n"